From d81fb565c1f48b013d107651c3bf383bd59e4daa Mon Sep 17 00:00:00 2001 From: Mike Mazur Date: Tue, 24 Feb 2009 23:40:08 +0000 Subject: Setting svn:eol-style=native on new files. --- OpenSim/Grid/Framework/IGridMessagingMapper.cs | 80 +- OpenSim/Grid/Framework/IMessageRegionService.cs | 76 +- .../Grid/Framework/IMessageUserServerService.cs | 70 +- OpenSim/Grid/Framework/IUGAIMCore.cs | 80 +- OpenSim/Grid/Framework/XMPPHTTPService.cs | 220 +-- OpenSim/Grid/GridServer.Modules/GridDBService.cs | 568 +++---- .../Grid/GridServer.Modules/GridMessagingModule.cs | 322 ++-- OpenSim/Grid/GridServer.Modules/GridRestModule.cs | 564 +++---- .../Grid/GridServer.Modules/GridXmlRpcModule.cs | 1770 ++++++++++---------- .../MessagingServer.Modules/MessageRegionModule.cs | 426 ++--- .../Grid/MessagingServer.Modules/MessageService.cs | 974 +++++------ .../MessageUserServerModule.cs | 372 ++-- .../PresenceBackreferenceEntry.cs | 192 +-- .../MessagingServer.Modules/PresenceInformer.cs | 270 +-- .../MessagingServer.Modules/PresenceService.cs | 66 +- .../MessagingServer.Modules/UserDataBaseService.cs | 150 +- .../MessagingServer.Modules/UserPresenceData.cs | 100 +- .../Grid/MessagingServer.Modules/WorkUnitBase.cs | 66 +- .../WorkUnitPresenceUpdate.cs | 66 +- .../UserServer.Modules/MessageServersConnector.cs | 1018 +++++------ OpenSim/Grid/UserServer.Modules/OpenIdService.cs | 674 ++++---- .../Grid/UserServer.Modules/UserDataBaseService.cs | 222 +-- .../Grid/UserServer.Modules/UserLoginService.cs | 1200 ++++++------- OpenSim/Grid/UserServer.Modules/UserManager.cs | 1372 +++++++-------- .../UserServerAvatarAppearanceModule.cs | 248 +-- .../UserServer.Modules/UserServerFriendsModule.cs | 346 ++-- OpenSim/Grid/UserServer/UserServerCommandModule.cs | 732 ++++---- 27 files changed, 6122 insertions(+), 6122 deletions(-) (limited to 'OpenSim/Grid') diff --git a/OpenSim/Grid/Framework/IGridMessagingMapper.cs b/OpenSim/Grid/Framework/IGridMessagingMapper.cs index b89f102..3a21431 100644 --- a/OpenSim/Grid/Framework/IGridMessagingMapper.cs +++ b/OpenSim/Grid/Framework/IGridMessagingMapper.cs @@ -1,40 +1,40 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using OpenSim.Framework.Servers; - -namespace OpenSim.Grid.Framework -{ - public interface IGridMessagingMapper - { - List GetMessageServersList(); - void RegisterMessageServer(MessageServerInfo m); - void DeRegisterMessageServer(MessageServerInfo m); - } -} +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using OpenSim.Framework.Servers; + +namespace OpenSim.Grid.Framework +{ + public interface IGridMessagingMapper + { + List GetMessageServersList(); + void RegisterMessageServer(MessageServerInfo m); + void DeRegisterMessageServer(MessageServerInfo m); + } +} diff --git a/OpenSim/Grid/Framework/IMessageRegionService.cs b/OpenSim/Grid/Framework/IMessageRegionService.cs index 2fdb40e..8c1d15a 100644 --- a/OpenSim/Grid/Framework/IMessageRegionService.cs +++ b/OpenSim/Grid/Framework/IMessageRegionService.cs @@ -1,38 +1,38 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using OpenSim.Data; - -namespace OpenSim.Grid.Framework -{ - public interface IMessageRegionService - { - int ClearRegionCache(); - RegionProfileData GetRegionInfo(ulong regionhandle); - } -} +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using OpenSim.Data; + +namespace OpenSim.Grid.Framework +{ + public interface IMessageRegionService + { + int ClearRegionCache(); + RegionProfileData GetRegionInfo(ulong regionhandle); + } +} diff --git a/OpenSim/Grid/Framework/IMessageUserServerService.cs b/OpenSim/Grid/Framework/IMessageUserServerService.cs index 614606b..9ebaf61 100644 --- a/OpenSim/Grid/Framework/IMessageUserServerService.cs +++ b/OpenSim/Grid/Framework/IMessageUserServerService.cs @@ -1,35 +1,35 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -namespace OpenSim.Grid.Framework -{ - public interface IMessageUserServerService - { - bool SendToUserServer(System.Collections.Hashtable request, string method); - } -} +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +namespace OpenSim.Grid.Framework +{ + public interface IMessageUserServerService + { + bool SendToUserServer(System.Collections.Hashtable request, string method); + } +} diff --git a/OpenSim/Grid/Framework/IUGAIMCore.cs b/OpenSim/Grid/Framework/IUGAIMCore.cs index a7df0d4..46fde8c 100644 --- a/OpenSim/Grid/Framework/IUGAIMCore.cs +++ b/OpenSim/Grid/Framework/IUGAIMCore.cs @@ -1,40 +1,40 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using OpenSim.Framework.Servers; - -namespace OpenSim.Grid.Framework -{ - public interface IUGAIMCore - { - T Get(); - void RegisterInterface(T iface); - bool TryGet(out T iface); - BaseHttpServer GetHttpServer(); - } -} +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using OpenSim.Framework.Servers; + +namespace OpenSim.Grid.Framework +{ + public interface IUGAIMCore + { + T Get(); + void RegisterInterface(T iface); + bool TryGet(out T iface); + BaseHttpServer GetHttpServer(); + } +} diff --git a/OpenSim/Grid/Framework/XMPPHTTPService.cs b/OpenSim/Grid/Framework/XMPPHTTPService.cs index bb09c8a..e87c2be 100644 --- a/OpenSim/Grid/Framework/XMPPHTTPService.cs +++ b/OpenSim/Grid/Framework/XMPPHTTPService.cs @@ -1,110 +1,110 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.IO; -using System.Reflection; -using log4net; -using OpenMetaverse; -using OpenSim.Framework.Servers; - -namespace OpenSim.Grid.Framework -{ - public class XMPPHTTPStreamHandler : BaseStreamHandler - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - - /// - /// Constructor. - /// - /// - /// - public XMPPHTTPStreamHandler() - : base("GET", "/presence") - { - m_log.Info("[REST]: In Get Request"); - - } - - public override byte[] Handle(string path, Stream request, - OSHttpRequest httpRequest, OSHttpResponse httpResponse) - { - string param = GetParam(path); - byte[] result = new byte[] {}; - try - { - string[] p = param.Split(new char[] {'/', '?', '&'}, StringSplitOptions.RemoveEmptyEntries); - - if (p.Length > 0) - { - UUID assetID = UUID.Zero; - - if (!UUID.TryParse(p[0], out assetID)) - { - m_log.InfoFormat( - "[REST]: GET:/presence ignoring request with malformed UUID {0}", p[0]); - return result; - } - - } - } - catch (Exception e) - { - m_log.Error(e.ToString()); - } - return result; - } - } - - public class PostXMPPStreamHandler : BaseStreamHandler - { - // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - public override byte[] Handle(string path, Stream request, - OSHttpRequest httpRequest, OSHttpResponse httpResponse) - { - string param = GetParam(path); - - UUID assetId; - if (param.Length > 0) - UUID.TryParse(param, out assetId); - // byte[] txBuffer = new byte[4096]; - - // TODO: Read POST serialize XMPP stanzas - - return new byte[] {}; - } - - public PostXMPPStreamHandler() - : base("POST", "/presence") - { - - } - - } -} +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.IO; +using System.Reflection; +using log4net; +using OpenMetaverse; +using OpenSim.Framework.Servers; + +namespace OpenSim.Grid.Framework +{ + public class XMPPHTTPStreamHandler : BaseStreamHandler + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + + /// + /// Constructor. + /// + /// + /// + public XMPPHTTPStreamHandler() + : base("GET", "/presence") + { + m_log.Info("[REST]: In Get Request"); + + } + + public override byte[] Handle(string path, Stream request, + OSHttpRequest httpRequest, OSHttpResponse httpResponse) + { + string param = GetParam(path); + byte[] result = new byte[] {}; + try + { + string[] p = param.Split(new char[] {'/', '?', '&'}, StringSplitOptions.RemoveEmptyEntries); + + if (p.Length > 0) + { + UUID assetID = UUID.Zero; + + if (!UUID.TryParse(p[0], out assetID)) + { + m_log.InfoFormat( + "[REST]: GET:/presence ignoring request with malformed UUID {0}", p[0]); + return result; + } + + } + } + catch (Exception e) + { + m_log.Error(e.ToString()); + } + return result; + } + } + + public class PostXMPPStreamHandler : BaseStreamHandler + { + // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + public override byte[] Handle(string path, Stream request, + OSHttpRequest httpRequest, OSHttpResponse httpResponse) + { + string param = GetParam(path); + + UUID assetId; + if (param.Length > 0) + UUID.TryParse(param, out assetId); + // byte[] txBuffer = new byte[4096]; + + // TODO: Read POST serialize XMPP stanzas + + return new byte[] {}; + } + + public PostXMPPStreamHandler() + : base("POST", "/presence") + { + + } + + } +} diff --git a/OpenSim/Grid/GridServer.Modules/GridDBService.cs b/OpenSim/Grid/GridServer.Modules/GridDBService.cs index b728f1f..2274214 100644 --- a/OpenSim/Grid/GridServer.Modules/GridDBService.cs +++ b/OpenSim/Grid/GridServer.Modules/GridDBService.cs @@ -1,284 +1,284 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Reflection; -using System.Xml; -using log4net; -using Nwc.XmlRpc; -using OpenMetaverse; -using OpenSim.Data; -using OpenSim.Framework; -using OpenSim.Framework.Communications; -using OpenSim.Framework.Servers; - - -namespace OpenSim.Grid.GridServer.Modules -{ - public class GridDBService - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private List _plugins = new List(); - private List _logplugins = new List(); - - /// - /// Adds a list of grid and log data plugins, as described by - /// `provider' and `connect', to `_plugins' and `_logplugins', - /// respectively. - /// - /// - /// The filename of the inventory server plugin DLL. - /// - /// - /// The connection string for the storage backend. - /// - public void AddPlugin(string provider, string connect) - { - _plugins = DataPluginFactory.LoadDataPlugins(provider, connect); - _logplugins = DataPluginFactory.LoadDataPlugins(provider, connect); - } - - public int GetNumberOfPlugins() - { - return _plugins.Count; - } - - /// - /// Logs a piece of information to the database - /// - /// What you were operating on (in grid server, this will likely be the region UUIDs) - /// Which method is being called? - /// What arguments are being passed? - /// How high priority is this? 1 = Max, 6 = Verbose - /// The message to log - private void logToDB(string target, string method, string args, int priority, string message) - { - foreach (ILogDataPlugin plugin in _logplugins) - { - try - { - plugin.saveLog("Gridserver", target, method, args, priority, message); - } - catch (Exception) - { - m_log.Warn("[storage]: Unable to write log via " + plugin.Name); - } - } - } - - /// - /// Returns a region by argument - /// - /// A UUID key of the region to return - /// A SimProfileData for the region - public RegionProfileData GetRegion(UUID uuid) - { - foreach (IGridDataPlugin plugin in _plugins) - { - try - { - return plugin.GetProfileByUUID(uuid); - } - catch (Exception e) - { - m_log.Warn("[storage]: GetRegion - " + e.Message); - } - } - return null; - } - - /// - /// Returns a region by argument - /// - /// A regionHandle of the region to return - /// A SimProfileData for the region - public RegionProfileData GetRegion(ulong handle) - { - foreach (IGridDataPlugin plugin in _plugins) - { - try - { - return plugin.GetProfileByHandle(handle); - } - catch (Exception ex) - { - m_log.Debug("[storage]: " + ex.Message); - m_log.Warn("[storage]: Unable to find region " + handle.ToString() + " via " + plugin.Name); - } - } - return null; - } - - /// - /// Returns a region by argument - /// - /// A partial regionName of the region to return - /// A SimProfileData for the region - public RegionProfileData GetRegion(string regionName) - { - foreach (IGridDataPlugin plugin in _plugins) - { - try - { - return plugin.GetProfileByString(regionName); - } - catch - { - m_log.Warn("[storage]: Unable to find region " + regionName + " via " + plugin.Name); - } - } - return null; - } - - public List GetRegions(uint xmin, uint ymin, uint xmax, uint ymax) - { - List regions = new List(); - - foreach (IGridDataPlugin plugin in _plugins) - { - try - { - regions.AddRange(plugin.GetProfilesInRange(xmin, ymin, xmax, ymax)); - } - catch - { - m_log.Warn("[storage]: Unable to query regionblock via " + plugin.Name); - } - } - - return regions; - } - - public List GetRegions(string name, int maxNum) - { - List regions = new List(); - foreach (IGridDataPlugin plugin in _plugins) - { - try - { - int num = maxNum - regions.Count; - List profiles = plugin.GetRegionsByName(name, (uint)num); - if (profiles != null) regions.AddRange(profiles); - } - catch - { - m_log.Warn("[storage]: Unable to query regionblock via " + plugin.Name); - } - } - - return regions; - } - - public DataResponse AddUpdateRegion(RegionProfileData sim, RegionProfileData existingSim) - { - DataResponse insertResponse = DataResponse.RESPONSE_ERROR; - foreach (IGridDataPlugin plugin in _plugins) - { - try - { - if (existingSim == null) - { - insertResponse = plugin.AddProfile(sim); - } - else - { - insertResponse = plugin.UpdateProfile(sim); - } - } - catch (Exception e) - { - m_log.Warn("[LOGIN END]: " + - "Unable to login region " + sim.ToString() + " via " + plugin.Name); - m_log.Warn("[LOGIN END]: " + e.ToString()); - } - } - return insertResponse; - } - - public DataResponse DeleteRegion(string uuid) - { - DataResponse insertResponse = DataResponse.RESPONSE_ERROR; - foreach (IGridDataPlugin plugin in _plugins) - { - //OpenSim.Data.MySQL.MySQLGridData dbengine = new OpenSim.Data.MySQL.MySQLGridData(); - try - { - //Nice are we not using multiple databases? - //MySQLGridData mysqldata = (MySQLGridData)(plugin); - - //DataResponse insertResponse = mysqldata.DeleteProfile(TheSim); - insertResponse = plugin.DeleteProfile(uuid); - } - catch (Exception) - { - m_log.Error("storage Unable to delete region " + uuid + " via " + plugin.Name); - //MainLog.Instance.Warn("storage", e.ToString()); - insertResponse = DataResponse.RESPONSE_ERROR; - } - } - return insertResponse; - } - - public string CheckReservations(RegionProfileData theSim, XmlNode authkeynode) - { - foreach (IGridDataPlugin plugin in _plugins) - { - try - { - //Check reservations - ReservationData reserveData = - plugin.GetReservationAtPoint(theSim.regionLocX, theSim.regionLocY); - if ((reserveData != null && reserveData.gridRecvKey == theSim.regionRecvKey) || - (reserveData == null && authkeynode.InnerText != theSim.regionRecvKey)) - { - plugin.AddProfile(theSim); - m_log.Info("[grid]: New sim added to grid (" + theSim.regionName + ")"); - logToDB(theSim.ToString(), "RestSetSimMethod", String.Empty, 5, - "Region successfully updated and connected to grid."); - } - else - { - m_log.Warn("[grid]: " + - "Unable to update region (RestSetSimMethod): Incorrect reservation auth key."); - // Wanted: " + reserveData.gridRecvKey + ", Got: " + theSim.regionRecvKey + "."); - return "Unable to update region (RestSetSimMethod): Incorrect auth key."; - } - } - catch (Exception e) - { - m_log.Warn("[GRID]: GetRegionPlugin Handle " + plugin.Name + " unable to add new sim: " + - e.ToString()); - } - } - return "OK"; - } - } -} +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Xml; +using log4net; +using Nwc.XmlRpc; +using OpenMetaverse; +using OpenSim.Data; +using OpenSim.Framework; +using OpenSim.Framework.Communications; +using OpenSim.Framework.Servers; + + +namespace OpenSim.Grid.GridServer.Modules +{ + public class GridDBService + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private List _plugins = new List(); + private List _logplugins = new List(); + + /// + /// Adds a list of grid and log data plugins, as described by + /// `provider' and `connect', to `_plugins' and `_logplugins', + /// respectively. + /// + /// + /// The filename of the inventory server plugin DLL. + /// + /// + /// The connection string for the storage backend. + /// + public void AddPlugin(string provider, string connect) + { + _plugins = DataPluginFactory.LoadDataPlugins(provider, connect); + _logplugins = DataPluginFactory.LoadDataPlugins(provider, connect); + } + + public int GetNumberOfPlugins() + { + return _plugins.Count; + } + + /// + /// Logs a piece of information to the database + /// + /// What you were operating on (in grid server, this will likely be the region UUIDs) + /// Which method is being called? + /// What arguments are being passed? + /// How high priority is this? 1 = Max, 6 = Verbose + /// The message to log + private void logToDB(string target, string method, string args, int priority, string message) + { + foreach (ILogDataPlugin plugin in _logplugins) + { + try + { + plugin.saveLog("Gridserver", target, method, args, priority, message); + } + catch (Exception) + { + m_log.Warn("[storage]: Unable to write log via " + plugin.Name); + } + } + } + + /// + /// Returns a region by argument + /// + /// A UUID key of the region to return + /// A SimProfileData for the region + public RegionProfileData GetRegion(UUID uuid) + { + foreach (IGridDataPlugin plugin in _plugins) + { + try + { + return plugin.GetProfileByUUID(uuid); + } + catch (Exception e) + { + m_log.Warn("[storage]: GetRegion - " + e.Message); + } + } + return null; + } + + /// + /// Returns a region by argument + /// + /// A regionHandle of the region to return + /// A SimProfileData for the region + public RegionProfileData GetRegion(ulong handle) + { + foreach (IGridDataPlugin plugin in _plugins) + { + try + { + return plugin.GetProfileByHandle(handle); + } + catch (Exception ex) + { + m_log.Debug("[storage]: " + ex.Message); + m_log.Warn("[storage]: Unable to find region " + handle.ToString() + " via " + plugin.Name); + } + } + return null; + } + + /// + /// Returns a region by argument + /// + /// A partial regionName of the region to return + /// A SimProfileData for the region + public RegionProfileData GetRegion(string regionName) + { + foreach (IGridDataPlugin plugin in _plugins) + { + try + { + return plugin.GetProfileByString(regionName); + } + catch + { + m_log.Warn("[storage]: Unable to find region " + regionName + " via " + plugin.Name); + } + } + return null; + } + + public List GetRegions(uint xmin, uint ymin, uint xmax, uint ymax) + { + List regions = new List(); + + foreach (IGridDataPlugin plugin in _plugins) + { + try + { + regions.AddRange(plugin.GetProfilesInRange(xmin, ymin, xmax, ymax)); + } + catch + { + m_log.Warn("[storage]: Unable to query regionblock via " + plugin.Name); + } + } + + return regions; + } + + public List GetRegions(string name, int maxNum) + { + List regions = new List(); + foreach (IGridDataPlugin plugin in _plugins) + { + try + { + int num = maxNum - regions.Count; + List profiles = plugin.GetRegionsByName(name, (uint)num); + if (profiles != null) regions.AddRange(profiles); + } + catch + { + m_log.Warn("[storage]: Unable to query regionblock via " + plugin.Name); + } + } + + return regions; + } + + public DataResponse AddUpdateRegion(RegionProfileData sim, RegionProfileData existingSim) + { + DataResponse insertResponse = DataResponse.RESPONSE_ERROR; + foreach (IGridDataPlugin plugin in _plugins) + { + try + { + if (existingSim == null) + { + insertResponse = plugin.AddProfile(sim); + } + else + { + insertResponse = plugin.UpdateProfile(sim); + } + } + catch (Exception e) + { + m_log.Warn("[LOGIN END]: " + + "Unable to login region " + sim.ToString() + " via " + plugin.Name); + m_log.Warn("[LOGIN END]: " + e.ToString()); + } + } + return insertResponse; + } + + public DataResponse DeleteRegion(string uuid) + { + DataResponse insertResponse = DataResponse.RESPONSE_ERROR; + foreach (IGridDataPlugin plugin in _plugins) + { + //OpenSim.Data.MySQL.MySQLGridData dbengine = new OpenSim.Data.MySQL.MySQLGridData(); + try + { + //Nice are we not using multiple databases? + //MySQLGridData mysqldata = (MySQLGridData)(plugin); + + //DataResponse insertResponse = mysqldata.DeleteProfile(TheSim); + insertResponse = plugin.DeleteProfile(uuid); + } + catch (Exception) + { + m_log.Error("storage Unable to delete region " + uuid + " via " + plugin.Name); + //MainLog.Instance.Warn("storage", e.ToString()); + insertResponse = DataResponse.RESPONSE_ERROR; + } + } + return insertResponse; + } + + public string CheckReservations(RegionProfileData theSim, XmlNode authkeynode) + { + foreach (IGridDataPlugin plugin in _plugins) + { + try + { + //Check reservations + ReservationData reserveData = + plugin.GetReservationAtPoint(theSim.regionLocX, theSim.regionLocY); + if ((reserveData != null && reserveData.gridRecvKey == theSim.regionRecvKey) || + (reserveData == null && authkeynode.InnerText != theSim.regionRecvKey)) + { + plugin.AddProfile(theSim); + m_log.Info("[grid]: New sim added to grid (" + theSim.regionName + ")"); + logToDB(theSim.ToString(), "RestSetSimMethod", String.Empty, 5, + "Region successfully updated and connected to grid."); + } + else + { + m_log.Warn("[grid]: " + + "Unable to update region (RestSetSimMethod): Incorrect reservation auth key."); + // Wanted: " + reserveData.gridRecvKey + ", Got: " + theSim.regionRecvKey + "."); + return "Unable to update region (RestSetSimMethod): Incorrect auth key."; + } + } + catch (Exception e) + { + m_log.Warn("[GRID]: GetRegionPlugin Handle " + plugin.Name + " unable to add new sim: " + + e.ToString()); + } + } + return "OK"; + } + } +} diff --git a/OpenSim/Grid/GridServer.Modules/GridMessagingModule.cs b/OpenSim/Grid/GridServer.Modules/GridMessagingModule.cs index 9c2b5ca..ee38310 100644 --- a/OpenSim/Grid/GridServer.Modules/GridMessagingModule.cs +++ b/OpenSim/Grid/GridServer.Modules/GridMessagingModule.cs @@ -1,161 +1,161 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using System.Text; -using Nwc.XmlRpc; -using log4net; -using OpenSim.Framework.Servers; -using OpenSim.Framework; -using OpenSim.Grid.Framework; - -namespace OpenSim.Grid.GridServer.Modules -{ - public class GridMessagingModule : IGridMessagingMapper - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - protected GridDBService m_gridDBService; - protected IUGAIMCore m_gridCore; - - protected GridConfig m_config; - - /// - /// Used to notify old regions as to which OpenSim version to upgrade to - /// - private string m_opensimVersion; - - protected BaseHttpServer m_httpServer; - - // This is here so that the grid server can hand out MessageServer settings to regions on registration - private List m_messageServers = new List(); - - public GridMessagingModule() - { - } - - public void Initialise(string opensimVersion, GridDBService gridDBService, IUGAIMCore gridCore, GridConfig config) - { - m_opensimVersion = opensimVersion; - m_gridDBService = gridDBService; - m_gridCore = gridCore; - m_config = config; - - m_gridCore.RegisterInterface(this); - - RegisterHandlers(); - } - - public void PostInitialise() - { - - } - - public void RegisterHandlers() - { - //have these in separate method as some servers restart the http server and reregister all the handlers. - m_httpServer = m_gridCore.GetHttpServer(); - - // Message Server ---> Grid Server - m_httpServer.AddXmlRPCHandler("register_messageserver", XmlRPCRegisterMessageServer); - m_httpServer.AddXmlRPCHandler("deregister_messageserver", XmlRPCDeRegisterMessageServer); - } - - public List GetMessageServersList() - { - lock (m_messageServers) - { - return new List(m_messageServers); - } - } - - public XmlRpcResponse XmlRPCRegisterMessageServer(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable)request.Params[0]; - Hashtable responseData = new Hashtable(); - - if (requestData.Contains("uri")) - { - string URI = (string)requestData["URI"]; - string sendkey = (string)requestData["sendkey"]; - string recvkey = (string)requestData["recvkey"]; - MessageServerInfo m = new MessageServerInfo(); - m.URI = URI; - m.sendkey = sendkey; - m.recvkey = recvkey; - RegisterMessageServer(m); - responseData["responsestring"] = "TRUE"; - response.Value = responseData; - } - return response; - } - - public XmlRpcResponse XmlRPCDeRegisterMessageServer(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable)request.Params[0]; - Hashtable responseData = new Hashtable(); - - if (requestData.Contains("uri")) - { - string URI = (string)requestData["uri"]; - string sendkey = (string)requestData["sendkey"]; - string recvkey = (string)requestData["recvkey"]; - MessageServerInfo m = new MessageServerInfo(); - m.URI = URI; - m.sendkey = sendkey; - m.recvkey = recvkey; - DeRegisterMessageServer(m); - responseData["responsestring"] = "TRUE"; - response.Value = responseData; - } - return response; - } - - public void RegisterMessageServer(MessageServerInfo m) - { - lock (m_messageServers) - { - if (!m_messageServers.Contains(m)) - m_messageServers.Add(m); - } - } - - public void DeRegisterMessageServer(MessageServerInfo m) - { - lock (m_messageServers) - { - if (m_messageServers.Contains(m)) - m_messageServers.Remove(m); - } - } - } -} +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using System.Text; +using Nwc.XmlRpc; +using log4net; +using OpenSim.Framework.Servers; +using OpenSim.Framework; +using OpenSim.Grid.Framework; + +namespace OpenSim.Grid.GridServer.Modules +{ + public class GridMessagingModule : IGridMessagingMapper + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + protected GridDBService m_gridDBService; + protected IUGAIMCore m_gridCore; + + protected GridConfig m_config; + + /// + /// Used to notify old regions as to which OpenSim version to upgrade to + /// + private string m_opensimVersion; + + protected BaseHttpServer m_httpServer; + + // This is here so that the grid server can hand out MessageServer settings to regions on registration + private List m_messageServers = new List(); + + public GridMessagingModule() + { + } + + public void Initialise(string opensimVersion, GridDBService gridDBService, IUGAIMCore gridCore, GridConfig config) + { + m_opensimVersion = opensimVersion; + m_gridDBService = gridDBService; + m_gridCore = gridCore; + m_config = config; + + m_gridCore.RegisterInterface(this); + + RegisterHandlers(); + } + + public void PostInitialise() + { + + } + + public void RegisterHandlers() + { + //have these in separate method as some servers restart the http server and reregister all the handlers. + m_httpServer = m_gridCore.GetHttpServer(); + + // Message Server ---> Grid Server + m_httpServer.AddXmlRPCHandler("register_messageserver", XmlRPCRegisterMessageServer); + m_httpServer.AddXmlRPCHandler("deregister_messageserver", XmlRPCDeRegisterMessageServer); + } + + public List GetMessageServersList() + { + lock (m_messageServers) + { + return new List(m_messageServers); + } + } + + public XmlRpcResponse XmlRPCRegisterMessageServer(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable responseData = new Hashtable(); + + if (requestData.Contains("uri")) + { + string URI = (string)requestData["URI"]; + string sendkey = (string)requestData["sendkey"]; + string recvkey = (string)requestData["recvkey"]; + MessageServerInfo m = new MessageServerInfo(); + m.URI = URI; + m.sendkey = sendkey; + m.recvkey = recvkey; + RegisterMessageServer(m); + responseData["responsestring"] = "TRUE"; + response.Value = responseData; + } + return response; + } + + public XmlRpcResponse XmlRPCDeRegisterMessageServer(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable responseData = new Hashtable(); + + if (requestData.Contains("uri")) + { + string URI = (string)requestData["uri"]; + string sendkey = (string)requestData["sendkey"]; + string recvkey = (string)requestData["recvkey"]; + MessageServerInfo m = new MessageServerInfo(); + m.URI = URI; + m.sendkey = sendkey; + m.recvkey = recvkey; + DeRegisterMessageServer(m); + responseData["responsestring"] = "TRUE"; + response.Value = responseData; + } + return response; + } + + public void RegisterMessageServer(MessageServerInfo m) + { + lock (m_messageServers) + { + if (!m_messageServers.Contains(m)) + m_messageServers.Add(m); + } + } + + public void DeRegisterMessageServer(MessageServerInfo m) + { + lock (m_messageServers) + { + if (m_messageServers.Contains(m)) + m_messageServers.Remove(m); + } + } + } +} diff --git a/OpenSim/Grid/GridServer.Modules/GridRestModule.cs b/OpenSim/Grid/GridServer.Modules/GridRestModule.cs index cd6d4d5..716f923 100644 --- a/OpenSim/Grid/GridServer.Modules/GridRestModule.cs +++ b/OpenSim/Grid/GridServer.Modules/GridRestModule.cs @@ -1,282 +1,282 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Reflection; -using System.Xml; -using log4net; -using OpenMetaverse; -using OpenSim.Data; -using OpenSim.Framework; -using OpenSim.Framework.Communications; -using OpenSim.Framework.Servers; -using OpenSim.Grid.Framework; - -namespace OpenSim.Grid.GridServer.Modules -{ - public class GridRestModule - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private GridDBService m_gridDBService; - private IUGAIMCore m_gridCore; - - protected GridConfig m_config; - - /// - /// Used to notify old regions as to which OpenSim version to upgrade to - /// - private string m_opensimVersion; - - protected BaseHttpServer m_httpServer; - - /// - /// Constructor - /// - /// - /// Used to notify old regions as to which OpenSim version to upgrade to - /// - public GridRestModule() - { - } - - public void Initialise(string opensimVersion, GridDBService gridDBService, IUGAIMCore gridCore, GridConfig config) - { - m_opensimVersion = opensimVersion; - m_gridDBService = gridDBService; - m_gridCore = gridCore; - m_config = config; - RegisterHandlers(); - } - - public void PostInitialise() - { - - } - - public void RegisterHandlers() - { - //have these in separate method as some servers restart the http server and reregister all the handlers. - m_httpServer = m_gridCore.GetHttpServer(); - - m_httpServer.AddStreamHandler(new RestStreamHandler("GET", "/sims/", RestGetSimMethod)); - m_httpServer.AddStreamHandler(new RestStreamHandler("POST", "/sims/", RestSetSimMethod)); - - m_httpServer.AddStreamHandler(new RestStreamHandler("GET", "/regions/", RestGetRegionMethod)); - m_httpServer.AddStreamHandler(new RestStreamHandler("POST", "/regions/", RestSetRegionMethod)); - } - - /// - /// Performs a REST Get Operation - /// - /// - /// - /// - /// HTTP request header object - /// HTTP response header object - /// - public string RestGetRegionMethod(string request, string path, string param, - OSHttpRequest httpRequest, OSHttpResponse httpResponse) - { - return RestGetSimMethod(String.Empty, "/sims/", param, httpRequest, httpResponse); - } - - /// - /// Performs a REST Set Operation - /// - /// - /// - /// - /// HTTP request header object - /// HTTP response header object - /// - public string RestSetRegionMethod(string request, string path, string param, - OSHttpRequest httpRequest, OSHttpResponse httpResponse) - { - return RestSetSimMethod(String.Empty, "/sims/", param, httpRequest, httpResponse); - } - - /// - /// Returns information about a sim via a REST Request - /// - /// - /// - /// A string representing the sim's UUID - /// HTTP request header object - /// HTTP response header object - /// Information about the sim in XML - public string RestGetSimMethod(string request, string path, string param, - OSHttpRequest httpRequest, OSHttpResponse httpResponse) - { - string respstring = String.Empty; - - RegionProfileData TheSim; - - UUID UUID; - if (UUID.TryParse(param, out UUID)) - { - TheSim = m_gridDBService.GetRegion(UUID); - - if (!(TheSim == null)) - { - respstring = ""; - respstring += "" + TheSim.regionSendKey + ""; - respstring += ""; - respstring += "" + TheSim.UUID.ToString() + ""; - respstring += "" + TheSim.regionName + ""; - respstring += "" + TheSim.serverIP + ""; - respstring += "" + TheSim.serverPort.ToString() + ""; - respstring += "" + TheSim.regionLocX.ToString() + ""; - respstring += "" + TheSim.regionLocY.ToString() + ""; - respstring += "1"; - respstring += ""; - respstring += ""; - } - } - else - { - respstring = ""; - respstring += "Param must be a UUID"; - respstring += ""; - } - - return respstring; - } - - /// - /// Creates or updates a sim via a REST Method Request - /// BROKEN with SQL Update - /// - /// - /// - /// - /// HTTP request header object - /// HTTP response header object - /// "OK" or an error - public string RestSetSimMethod(string request, string path, string param, - OSHttpRequest httpRequest, OSHttpResponse httpResponse) - { - m_log.Info("Processing region update via REST method"); - RegionProfileData theSim; - theSim = m_gridDBService.GetRegion(new UUID(param)); - if (theSim == null) - { - theSim = new RegionProfileData(); - UUID UUID = new UUID(param); - theSim.UUID = UUID; - theSim.regionRecvKey = m_config.SimRecvKey; - } - - XmlDocument doc = new XmlDocument(); - doc.LoadXml(request); - XmlNode rootnode = doc.FirstChild; - XmlNode authkeynode = rootnode.ChildNodes[0]; - if (authkeynode.Name != "authkey") - { - return "ERROR! bad XML - expected authkey tag"; - } - - XmlNode simnode = rootnode.ChildNodes[1]; - if (simnode.Name != "sim") - { - return "ERROR! bad XML - expected sim tag"; - } - - //theSim.regionSendKey = Cfg; - theSim.regionRecvKey = m_config.SimRecvKey; - theSim.regionSendKey = m_config.SimSendKey; - theSim.regionSecret = m_config.SimRecvKey; - theSim.regionDataURI = String.Empty; - theSim.regionAssetURI = m_config.DefaultAssetServer; - theSim.regionAssetRecvKey = m_config.AssetRecvKey; - theSim.regionAssetSendKey = m_config.AssetSendKey; - theSim.regionUserURI = m_config.DefaultUserServer; - theSim.regionUserSendKey = m_config.UserSendKey; - theSim.regionUserRecvKey = m_config.UserRecvKey; - - for (int i = 0; i < simnode.ChildNodes.Count; i++) - { - switch (simnode.ChildNodes[i].Name) - { - case "regionname": - theSim.regionName = simnode.ChildNodes[i].InnerText; - break; - - case "sim_ip": - theSim.serverIP = simnode.ChildNodes[i].InnerText; - break; - - case "sim_port": - theSim.serverPort = Convert.ToUInt32(simnode.ChildNodes[i].InnerText); - break; - - case "region_locx": - theSim.regionLocX = Convert.ToUInt32((string)simnode.ChildNodes[i].InnerText); - theSim.regionHandle = Utils.UIntsToLong((theSim.regionLocX * Constants.RegionSize), (theSim.regionLocY * Constants.RegionSize)); - break; - - case "region_locy": - theSim.regionLocY = Convert.ToUInt32((string)simnode.ChildNodes[i].InnerText); - theSim.regionHandle = Utils.UIntsToLong((theSim.regionLocX * Constants.RegionSize), (theSim.regionLocY * Constants.RegionSize)); - break; - } - } - - theSim.serverURI = "http://" + theSim.serverIP + ":" + theSim.serverPort + "/"; - bool requirePublic = false; - bool requireValid = true; - - if (requirePublic && - (theSim.serverIP.StartsWith("172.16") || theSim.serverIP.StartsWith("192.168") || - theSim.serverIP.StartsWith("10.") || theSim.serverIP.StartsWith("0.") || - theSim.serverIP.StartsWith("255."))) - { - return "ERROR! Servers must register with public addresses."; - } - - if (requireValid && (theSim.serverIP.StartsWith("0.") || theSim.serverIP.StartsWith("255."))) - { - return "ERROR! 0.*.*.* / 255.*.*.* Addresses are invalid, please check your server config and try again"; - } - - try - { - m_log.Info("[DATA]: " + - "Updating / adding via " + m_gridDBService.GetNumberOfPlugins() + " storage provider(s) registered."); - - return m_gridDBService.CheckReservations(theSim, authkeynode); - } - catch (Exception e) - { - return "ERROR! Could not save to database! (" + e.ToString() + ")"; - } - } - } -} +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Xml; +using log4net; +using OpenMetaverse; +using OpenSim.Data; +using OpenSim.Framework; +using OpenSim.Framework.Communications; +using OpenSim.Framework.Servers; +using OpenSim.Grid.Framework; + +namespace OpenSim.Grid.GridServer.Modules +{ + public class GridRestModule + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private GridDBService m_gridDBService; + private IUGAIMCore m_gridCore; + + protected GridConfig m_config; + + /// + /// Used to notify old regions as to which OpenSim version to upgrade to + /// + private string m_opensimVersion; + + protected BaseHttpServer m_httpServer; + + /// + /// Constructor + /// + /// + /// Used to notify old regions as to which OpenSim version to upgrade to + /// + public GridRestModule() + { + } + + public void Initialise(string opensimVersion, GridDBService gridDBService, IUGAIMCore gridCore, GridConfig config) + { + m_opensimVersion = opensimVersion; + m_gridDBService = gridDBService; + m_gridCore = gridCore; + m_config = config; + RegisterHandlers(); + } + + public void PostInitialise() + { + + } + + public void RegisterHandlers() + { + //have these in separate method as some servers restart the http server and reregister all the handlers. + m_httpServer = m_gridCore.GetHttpServer(); + + m_httpServer.AddStreamHandler(new RestStreamHandler("GET", "/sims/", RestGetSimMethod)); + m_httpServer.AddStreamHandler(new RestStreamHandler("POST", "/sims/", RestSetSimMethod)); + + m_httpServer.AddStreamHandler(new RestStreamHandler("GET", "/regions/", RestGetRegionMethod)); + m_httpServer.AddStreamHandler(new RestStreamHandler("POST", "/regions/", RestSetRegionMethod)); + } + + /// + /// Performs a REST Get Operation + /// + /// + /// + /// + /// HTTP request header object + /// HTTP response header object + /// + public string RestGetRegionMethod(string request, string path, string param, + OSHttpRequest httpRequest, OSHttpResponse httpResponse) + { + return RestGetSimMethod(String.Empty, "/sims/", param, httpRequest, httpResponse); + } + + /// + /// Performs a REST Set Operation + /// + /// + /// + /// + /// HTTP request header object + /// HTTP response header object + /// + public string RestSetRegionMethod(string request, string path, string param, + OSHttpRequest httpRequest, OSHttpResponse httpResponse) + { + return RestSetSimMethod(String.Empty, "/sims/", param, httpRequest, httpResponse); + } + + /// + /// Returns information about a sim via a REST Request + /// + /// + /// + /// A string representing the sim's UUID + /// HTTP request header object + /// HTTP response header object + /// Information about the sim in XML + public string RestGetSimMethod(string request, string path, string param, + OSHttpRequest httpRequest, OSHttpResponse httpResponse) + { + string respstring = String.Empty; + + RegionProfileData TheSim; + + UUID UUID; + if (UUID.TryParse(param, out UUID)) + { + TheSim = m_gridDBService.GetRegion(UUID); + + if (!(TheSim == null)) + { + respstring = ""; + respstring += "" + TheSim.regionSendKey + ""; + respstring += ""; + respstring += "" + TheSim.UUID.ToString() + ""; + respstring += "" + TheSim.regionName + ""; + respstring += "" + TheSim.serverIP + ""; + respstring += "" + TheSim.serverPort.ToString() + ""; + respstring += "" + TheSim.regionLocX.ToString() + ""; + respstring += "" + TheSim.regionLocY.ToString() + ""; + respstring += "1"; + respstring += ""; + respstring += ""; + } + } + else + { + respstring = ""; + respstring += "Param must be a UUID"; + respstring += ""; + } + + return respstring; + } + + /// + /// Creates or updates a sim via a REST Method Request + /// BROKEN with SQL Update + /// + /// + /// + /// + /// HTTP request header object + /// HTTP response header object + /// "OK" or an error + public string RestSetSimMethod(string request, string path, string param, + OSHttpRequest httpRequest, OSHttpResponse httpResponse) + { + m_log.Info("Processing region update via REST method"); + RegionProfileData theSim; + theSim = m_gridDBService.GetRegion(new UUID(param)); + if (theSim == null) + { + theSim = new RegionProfileData(); + UUID UUID = new UUID(param); + theSim.UUID = UUID; + theSim.regionRecvKey = m_config.SimRecvKey; + } + + XmlDocument doc = new XmlDocument(); + doc.LoadXml(request); + XmlNode rootnode = doc.FirstChild; + XmlNode authkeynode = rootnode.ChildNodes[0]; + if (authkeynode.Name != "authkey") + { + return "ERROR! bad XML - expected authkey tag"; + } + + XmlNode simnode = rootnode.ChildNodes[1]; + if (simnode.Name != "sim") + { + return "ERROR! bad XML - expected sim tag"; + } + + //theSim.regionSendKey = Cfg; + theSim.regionRecvKey = m_config.SimRecvKey; + theSim.regionSendKey = m_config.SimSendKey; + theSim.regionSecret = m_config.SimRecvKey; + theSim.regionDataURI = String.Empty; + theSim.regionAssetURI = m_config.DefaultAssetServer; + theSim.regionAssetRecvKey = m_config.AssetRecvKey; + theSim.regionAssetSendKey = m_config.AssetSendKey; + theSim.regionUserURI = m_config.DefaultUserServer; + theSim.regionUserSendKey = m_config.UserSendKey; + theSim.regionUserRecvKey = m_config.UserRecvKey; + + for (int i = 0; i < simnode.ChildNodes.Count; i++) + { + switch (simnode.ChildNodes[i].Name) + { + case "regionname": + theSim.regionName = simnode.ChildNodes[i].InnerText; + break; + + case "sim_ip": + theSim.serverIP = simnode.ChildNodes[i].InnerText; + break; + + case "sim_port": + theSim.serverPort = Convert.ToUInt32(simnode.ChildNodes[i].InnerText); + break; + + case "region_locx": + theSim.regionLocX = Convert.ToUInt32((string)simnode.ChildNodes[i].InnerText); + theSim.regionHandle = Utils.UIntsToLong((theSim.regionLocX * Constants.RegionSize), (theSim.regionLocY * Constants.RegionSize)); + break; + + case "region_locy": + theSim.regionLocY = Convert.ToUInt32((string)simnode.ChildNodes[i].InnerText); + theSim.regionHandle = Utils.UIntsToLong((theSim.regionLocX * Constants.RegionSize), (theSim.regionLocY * Constants.RegionSize)); + break; + } + } + + theSim.serverURI = "http://" + theSim.serverIP + ":" + theSim.serverPort + "/"; + bool requirePublic = false; + bool requireValid = true; + + if (requirePublic && + (theSim.serverIP.StartsWith("172.16") || theSim.serverIP.StartsWith("192.168") || + theSim.serverIP.StartsWith("10.") || theSim.serverIP.StartsWith("0.") || + theSim.serverIP.StartsWith("255."))) + { + return "ERROR! Servers must register with public addresses."; + } + + if (requireValid && (theSim.serverIP.StartsWith("0.") || theSim.serverIP.StartsWith("255."))) + { + return "ERROR! 0.*.*.* / 255.*.*.* Addresses are invalid, please check your server config and try again"; + } + + try + { + m_log.Info("[DATA]: " + + "Updating / adding via " + m_gridDBService.GetNumberOfPlugins() + " storage provider(s) registered."); + + return m_gridDBService.CheckReservations(theSim, authkeynode); + } + catch (Exception e) + { + return "ERROR! Could not save to database! (" + e.ToString() + ")"; + } + } + } +} diff --git a/OpenSim/Grid/GridServer.Modules/GridXmlRpcModule.cs b/OpenSim/Grid/GridServer.Modules/GridXmlRpcModule.cs index d5af900..292ce0d 100644 --- a/OpenSim/Grid/GridServer.Modules/GridXmlRpcModule.cs +++ b/OpenSim/Grid/GridServer.Modules/GridXmlRpcModule.cs @@ -1,885 +1,885 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Reflection; -using System.Xml; -using log4net; -using Nwc.XmlRpc; -using OpenMetaverse; -using OpenSim.Data; -using OpenSim.Framework; -using OpenSim.Framework.Communications; -using OpenSim.Framework.Servers; -using OpenSim.Grid.Framework; - -namespace OpenSim.Grid.GridServer.Modules -{ - public class GridXmlRpcModule - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private GridDBService m_gridDBService; - private IUGAIMCore m_gridCore; - - protected GridConfig m_config; - - protected IGridMessagingMapper m_messagingServerMapper; - /// - /// Used to notify old regions as to which OpenSim version to upgrade to - /// - private string m_opensimVersion; - - protected BaseHttpServer m_httpServer; - - /// - /// Constructor - /// - /// - /// Used to notify old regions as to which OpenSim version to upgrade to - /// - public GridXmlRpcModule() - { - } - - public void Initialise(string opensimVersion, GridDBService gridDBService, IUGAIMCore gridCore, GridConfig config) - { - m_opensimVersion = opensimVersion; - m_gridDBService = gridDBService; - m_gridCore = gridCore; - m_config = config; - RegisterHandlers(); - } - - public void PostInitialise() - { - IGridMessagingMapper messagingModule; - if (m_gridCore.TryGet(out messagingModule)) - { - m_messagingServerMapper = messagingModule; - } - } - - public void RegisterHandlers() - { - //have these in separate method as some servers restart the http server and reregister all the handlers. - m_httpServer = m_gridCore.GetHttpServer(); - - m_httpServer.AddXmlRPCHandler("simulator_login", XmlRpcSimulatorLoginMethod); - m_httpServer.AddXmlRPCHandler("simulator_data_request", XmlRpcSimulatorDataRequestMethod); - m_httpServer.AddXmlRPCHandler("simulator_after_region_moved", XmlRpcDeleteRegionMethod); - m_httpServer.AddXmlRPCHandler("map_block", XmlRpcMapBlockMethod); - m_httpServer.AddXmlRPCHandler("search_for_region_by_name", XmlRpcSearchForRegionMethod); - } - - /// - /// Returns a XML String containing a list of the neighbouring regions - /// - /// The regionhandle for the center sim - /// An XML string containing neighbour entities - public string GetXMLNeighbours(ulong reqhandle) - { - string response = String.Empty; - RegionProfileData central_region = m_gridDBService.GetRegion(reqhandle); - RegionProfileData neighbour; - for (int x = -1; x < 2; x++) - { - for (int y = -1; y < 2; y++) - { - if ( - m_gridDBService.GetRegion( - Util.UIntsToLong((uint)((central_region.regionLocX + x) * Constants.RegionSize), - (uint)(central_region.regionLocY + y) * Constants.RegionSize)) != null) - { - neighbour = - m_gridDBService.GetRegion( - Util.UIntsToLong((uint)((central_region.regionLocX + x) * Constants.RegionSize), - (uint)(central_region.regionLocY + y) * Constants.RegionSize)); - - response += ""; - response += "" + neighbour.serverIP + ""; - response += "" + neighbour.serverPort.ToString() + ""; - response += "" + neighbour.regionLocX.ToString() + ""; - response += "" + neighbour.regionLocY.ToString() + ""; - response += "" + neighbour.regionHandle.ToString() + ""; - response += ""; - } - } - } - return response; - } - - /// - /// Checks that it's valid to replace the existing region data with new data - /// - /// Currently, this means ensure that the keys passed in by the new region - /// match those in the original region. (XXX Is this correct? Shouldn't we simply check - /// against the keys in the current configuration?) - /// - /// - /// - protected virtual void ValidateOverwriteKeys(RegionProfileData sim, RegionProfileData existingSim) - { - if (!(existingSim.regionRecvKey == sim.regionRecvKey && existingSim.regionSendKey == sim.regionSendKey)) - { - throw new LoginException( - String.Format( - "Authentication failed when trying to login existing region {0} at location {1} {2} currently occupied by {3}" - + " with the region's send key {4} (expected {5}) and the region's receive key {6} (expected {7})", - sim.regionName, sim.regionLocX, sim.regionLocY, existingSim.regionName, - sim.regionSendKey, existingSim.regionSendKey, sim.regionRecvKey, existingSim.regionRecvKey), - "The keys required to login your region did not match the grid server keys. Please check your grid send and receive keys."); - } - } - - /// - /// Checks that the new region data is valid. - /// - /// Currently, this means checking that the keys passed in by the new region - /// match those in the grid server's configuration. - /// - /// - /// - /// Thrown if region login failed - protected virtual void ValidateNewRegionKeys(RegionProfileData sim) - { - if (!(sim.regionRecvKey == m_config.SimSendKey && sim.regionSendKey == m_config.SimRecvKey)) - { - throw new LoginException( - String.Format( - "Authentication failed when trying to login new region {0} at location {1} {2}" - + " with the region's send key {3} (expected {4}) and the region's receive key {5} (expected {6})", - sim.regionName, sim.regionLocX, sim.regionLocY, - sim.regionSendKey, m_config.SimRecvKey, sim.regionRecvKey, m_config.SimSendKey), - "The keys required to login your region did not match your existing region keys. Please check your grid send and receive keys."); - } - } - - /// - /// Check that a region's http uri is externally contactable. - /// - /// - /// Thrown if the region is not contactable - protected virtual void ValidateRegionContactable(RegionProfileData sim) - { - string regionStatusUrl = String.Format("{0}{1}", sim.httpServerURI, "simstatus/"); - string regionStatusResponse; - - RestClient rc = new RestClient(regionStatusUrl); - rc.RequestMethod = "GET"; - - m_log.DebugFormat("[LOGIN]: Contacting {0} for status of region {1}", regionStatusUrl, sim.regionName); - - try - { - Stream rs = rc.Request(); - StreamReader sr = new StreamReader(rs); - regionStatusResponse = sr.ReadToEnd(); - sr.Close(); - } - catch (Exception e) - { - throw new LoginException( - String.Format("Region status request to {0} failed", regionStatusUrl), - String.Format( - "The grid service could not contact the http url {0} at your region. Please make sure this url is reachable by the grid service", - regionStatusUrl), - e); - } - - if (!regionStatusResponse.Equals("OK")) - { - throw new LoginException( - String.Format( - "Region {0} at {1} returned status response {2} rather than {3}", - sim.regionName, regionStatusUrl, regionStatusResponse, "OK"), - String.Format( - "When the grid service asked for the status of your region, it received the response {0} rather than {1}. Please check your status", - regionStatusResponse, "OK")); - } - } - - /// - /// Construct an XMLRPC error response - /// - /// - /// - public static XmlRpcResponse ErrorResponse(string error) - { - XmlRpcResponse errorResponse = new XmlRpcResponse(); - Hashtable errorResponseData = new Hashtable(); - errorResponse.Value = errorResponseData; - errorResponseData["error"] = error; - return errorResponse; - } - - /// - /// Performed when a region connects to the grid server initially. - /// - /// The XML RPC Request - /// Startup parameters - public XmlRpcResponse XmlRpcSimulatorLoginMethod(XmlRpcRequest request) - { - RegionProfileData sim; - RegionProfileData existingSim; - - Hashtable requestData = (Hashtable)request.Params[0]; - UUID uuid; - - if (!requestData.ContainsKey("UUID") || !UUID.TryParse((string)requestData["UUID"], out uuid)) - { - m_log.Debug("[LOGIN PRELUDE]: Region connected without a UUID, sending back error response."); - return ErrorResponse("No UUID passed to grid server - unable to connect you"); - } - - try - { - sim = RegionFromRequest(requestData); - } - catch (FormatException e) - { - m_log.Debug("[LOGIN PRELUDE]: Invalid login parameters, sending back error response."); - return ErrorResponse("Wrong format in login parameters. Please verify parameters." + e.ToString()); - } - - m_log.InfoFormat("[LOGIN BEGIN]: Received login request from simulator: {0}", sim.regionName); - - if (!m_config.AllowRegionRegistration) - { - m_log.DebugFormat( - "[LOGIN END]: Disabled region registration blocked login request from simulator: {0}", - sim.regionName); - - return ErrorResponse("This grid is currently not accepting region registrations."); - } - - int majorInterfaceVersion = 0; - if (requestData.ContainsKey("major_interface_version")) - int.TryParse((string)requestData["major_interface_version"], out majorInterfaceVersion); - - if (majorInterfaceVersion != VersionInfo.MajorInterfaceVersion) - { - return ErrorResponse( - String.Format( - "Your region service implements OGS1 interface version {0}" - + " but this grid requires that the region implement OGS1 interface version {1} to connect." - + " Try changing to OpenSimulator {2}", - majorInterfaceVersion, VersionInfo.MajorInterfaceVersion, m_opensimVersion)); - } - - existingSim = m_gridDBService.GetRegion(sim.regionHandle); - - if (existingSim == null || existingSim.UUID == sim.UUID || sim.UUID != sim.originUUID) - { - try - { - if (existingSim == null) - { - ValidateNewRegionKeys(sim); - } - else - { - ValidateOverwriteKeys(sim, existingSim); - } - - ValidateRegionContactable(sim); - } - catch (LoginException e) - { - string logMsg = e.Message; - if (e.InnerException != null) - logMsg += ", " + e.InnerException.Message; - - m_log.WarnFormat("[LOGIN END]: {0}", logMsg); - - return e.XmlRpcErrorResponse; - } - - DataResponse insertResponse = m_gridDBService.AddUpdateRegion(sim, existingSim); - - switch (insertResponse) - { - case DataResponse.RESPONSE_OK: - m_log.Info("[LOGIN END]: " + (existingSim == null ? "New" : "Existing") + " sim login successful: " + sim.regionName); - break; - case DataResponse.RESPONSE_ERROR: - m_log.Warn("[LOGIN END]: Sim login failed (Error): " + sim.regionName); - break; - case DataResponse.RESPONSE_INVALIDCREDENTIALS: - m_log.Warn("[LOGIN END]: " + - "Sim login failed (Invalid Credentials): " + sim.regionName); - break; - case DataResponse.RESPONSE_AUTHREQUIRED: - m_log.Warn("[LOGIN END]: " + - "Sim login failed (Authentication Required): " + - sim.regionName); - break; - } - - XmlRpcResponse response = CreateLoginResponse(sim); - - return response; - } - else - { - m_log.Warn("[LOGIN END]: Failed to login region " + sim.regionName + " at location " + sim.regionLocX + " " + sim.regionLocY + " currently occupied by " + existingSim.regionName); - return ErrorResponse("Another region already exists at that location. Please try another."); - } - } - - /// - /// Construct a successful response to a simulator's login attempt. - /// - /// - /// - private XmlRpcResponse CreateLoginResponse(RegionProfileData sim) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable responseData = new Hashtable(); - response.Value = responseData; - - ArrayList SimNeighboursData = GetSimNeighboursData(sim); - - responseData["UUID"] = sim.UUID.ToString(); - responseData["region_locx"] = sim.regionLocX.ToString(); - responseData["region_locy"] = sim.regionLocY.ToString(); - responseData["regionname"] = sim.regionName; - responseData["estate_id"] = "1"; - responseData["neighbours"] = SimNeighboursData; - - responseData["sim_ip"] = sim.serverIP; - responseData["sim_port"] = sim.serverPort.ToString(); - responseData["asset_url"] = sim.regionAssetURI; - responseData["asset_sendkey"] = sim.regionAssetSendKey; - responseData["asset_recvkey"] = sim.regionAssetRecvKey; - responseData["user_url"] = sim.regionUserURI; - responseData["user_sendkey"] = sim.regionUserSendKey; - responseData["user_recvkey"] = sim.regionUserRecvKey; - responseData["authkey"] = sim.regionSecret; - - // New! If set, use as URL to local sim storage (ie http://remotehost/region.Yap) - responseData["data_uri"] = sim.regionDataURI; - - responseData["allow_forceful_banlines"] = m_config.AllowForcefulBanlines; - - // Instead of sending a multitude of message servers to the registering sim - // we should probably be sending a single one and parhaps it's backup - // that has responsibility over routing it's messages. - - // The Sim won't be contacting us again about any of the message server stuff during it's time up. - - responseData["messageserver_count"] = 0; - - // IGridMessagingModule messagingModule; - // if (m_gridCore.TryGet(out messagingModule)) - //{ - if(m_messagingServerMapper != null) - { - List messageServers = m_messagingServerMapper.GetMessageServersList(); - responseData["messageserver_count"] = messageServers.Count; - - for (int i = 0; i < messageServers.Count; i++) - { - responseData["messageserver_uri" + i] = messageServers[i].URI; - responseData["messageserver_sendkey" + i] = messageServers[i].sendkey; - responseData["messageserver_recvkey" + i] = messageServers[i].recvkey; - } - } - return response; - } - - private ArrayList GetSimNeighboursData(RegionProfileData sim) - { - ArrayList SimNeighboursData = new ArrayList(); - - RegionProfileData neighbour; - Hashtable NeighbourBlock; - - //First use the fast method. (not implemented in SQLLite) - List neighbours = m_gridDBService.GetRegions(sim.regionLocX - 1, sim.regionLocY - 1, sim.regionLocX + 1, sim.regionLocY + 1); - - if (neighbours.Count > 0) - { - foreach (RegionProfileData aSim in neighbours) - { - NeighbourBlock = new Hashtable(); - NeighbourBlock["sim_ip"] = aSim.serverIP; - NeighbourBlock["sim_port"] = aSim.serverPort.ToString(); - NeighbourBlock["region_locx"] = aSim.regionLocX.ToString(); - NeighbourBlock["region_locy"] = aSim.regionLocY.ToString(); - NeighbourBlock["UUID"] = aSim.ToString(); - NeighbourBlock["regionHandle"] = aSim.regionHandle.ToString(); - - if (aSim.UUID != sim.UUID) - { - SimNeighboursData.Add(NeighbourBlock); - } - } - } - else - { - for (int x = -1; x < 2; x++) - { - for (int y = -1; y < 2; y++) - { - if ( - m_gridDBService.GetRegion( - Utils.UIntsToLong((uint)((sim.regionLocX + x) * Constants.RegionSize), - (uint)(sim.regionLocY + y) * Constants.RegionSize)) != null) - { - neighbour = - m_gridDBService.GetRegion( - Utils.UIntsToLong((uint)((sim.regionLocX + x) * Constants.RegionSize), - (uint)(sim.regionLocY + y) * Constants.RegionSize)); - - NeighbourBlock = new Hashtable(); - NeighbourBlock["sim_ip"] = neighbour.serverIP; - NeighbourBlock["sim_port"] = neighbour.serverPort.ToString(); - NeighbourBlock["region_locx"] = neighbour.regionLocX.ToString(); - NeighbourBlock["region_locy"] = neighbour.regionLocY.ToString(); - NeighbourBlock["UUID"] = neighbour.UUID.ToString(); - NeighbourBlock["regionHandle"] = neighbour.regionHandle.ToString(); - - if (neighbour.UUID != sim.UUID) SimNeighboursData.Add(NeighbourBlock); - } - } - } - } - return SimNeighboursData; - } - - /// - /// Loads the grid's own RegionProfileData object with data from the XMLRPC simulator_login request from a region - /// - /// - /// - private RegionProfileData RegionFromRequest(Hashtable requestData) - { - RegionProfileData sim; - sim = new RegionProfileData(); - - sim.UUID = new UUID((string)requestData["UUID"]); - sim.originUUID = new UUID((string)requestData["originUUID"]); - - sim.regionRecvKey = String.Empty; - sim.regionSendKey = String.Empty; - - if (requestData.ContainsKey("region_secret")) - { - string regionsecret = (string)requestData["region_secret"]; - if (regionsecret.Length > 0) - sim.regionSecret = regionsecret; - else - sim.regionSecret = m_config.SimRecvKey; - - } - else - { - sim.regionSecret = m_config.SimRecvKey; - } - - sim.regionDataURI = String.Empty; - sim.regionAssetURI = m_config.DefaultAssetServer; - sim.regionAssetRecvKey = m_config.AssetRecvKey; - sim.regionAssetSendKey = m_config.AssetSendKey; - sim.regionUserURI = m_config.DefaultUserServer; - sim.regionUserSendKey = m_config.UserSendKey; - sim.regionUserRecvKey = m_config.UserRecvKey; - - sim.serverIP = (string)requestData["sim_ip"]; - sim.serverPort = Convert.ToUInt32((string)requestData["sim_port"]); - sim.httpPort = Convert.ToUInt32((string)requestData["http_port"]); - sim.remotingPort = Convert.ToUInt32((string)requestData["remoting_port"]); - sim.regionLocX = Convert.ToUInt32((string)requestData["region_locx"]); - sim.regionLocY = Convert.ToUInt32((string)requestData["region_locy"]); - sim.regionLocZ = 0; - - UUID textureID; - if (UUID.TryParse((string)requestData["map-image-id"], out textureID)) - { - sim.regionMapTextureID = textureID; - } - - // part of an initial brutish effort to provide accurate information (as per the xml region spec) - // wrt the ownership of a given region - // the (very bad) assumption is that this value is being read and handled inconsistently or - // not at all. Current strategy is to put the code in place to support the validity of this information - // and to roll forward debugging any issues from that point - // - // this particular section of the mod attempts to receive a value from the region's xml file by way of - // OSG1GridServices for the region's owner - sim.owner_uuid = (UUID)(string)requestData["master_avatar_uuid"]; - - try - { - sim.regionRecvKey = (string)requestData["recvkey"]; - sim.regionSendKey = (string)requestData["authkey"]; - } - catch (KeyNotFoundException) { } - - sim.regionHandle = Utils.UIntsToLong((sim.regionLocX * Constants.RegionSize), (sim.regionLocY * Constants.RegionSize)); - sim.serverURI = (string)requestData["server_uri"]; - - sim.httpServerURI = "http://" + sim.serverIP + ":" + sim.httpPort + "/"; - - sim.regionName = (string)requestData["sim_name"]; - return sim; - } - - /// - /// Returns an XML RPC response to a simulator profile request - /// Performed after moving a region. - /// - /// - /// - /// The XMLRPC Request - /// Processing parameters - public XmlRpcResponse XmlRpcDeleteRegionMethod(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable responseData = new Hashtable(); - response.Value = responseData; - - //RegionProfileData TheSim = null; - string uuid; - Hashtable requestData = (Hashtable)request.Params[0]; - - if (requestData.ContainsKey("UUID")) - { - //TheSim = GetRegion(new UUID((string) requestData["UUID"])); - uuid = requestData["UUID"].ToString(); - m_log.InfoFormat("[LOGOUT]: Logging out region: {0}", uuid); - // logToDB((new LLUUID((string)requestData["UUID"])).ToString(),"XmlRpcDeleteRegionMethod","", 5,"Attempting delete with UUID."); - } - else - { - responseData["error"] = "No UUID or region_handle passed to grid server - unable to delete"; - return response; - } - - DataResponse insertResponse = m_gridDBService.DeleteRegion(uuid); - - string insertResp = ""; - switch (insertResponse) - { - case DataResponse.RESPONSE_OK: - //MainLog.Instance.Verbose("grid", "Deleting region successful: " + uuid); - insertResp = "Deleting region successful: " + uuid; - break; - case DataResponse.RESPONSE_ERROR: - //MainLog.Instance.Warn("storage", "Deleting region failed (Error): " + uuid); - insertResp = "Deleting region failed (Error): " + uuid; - break; - case DataResponse.RESPONSE_INVALIDCREDENTIALS: - //MainLog.Instance.Warn("storage", "Deleting region failed (Invalid Credentials): " + uuid); - insertResp = "Deleting region (Invalid Credentials): " + uuid; - break; - case DataResponse.RESPONSE_AUTHREQUIRED: - //MainLog.Instance.Warn("storage", "Deleting region failed (Authentication Required): " + uuid); - insertResp = "Deleting region (Authentication Required): " + uuid; - break; - } - - responseData["status"] = insertResp; - - return response; - } - - /// - /// Returns an XML RPC response to a simulator profile request - /// - /// - /// - public XmlRpcResponse XmlRpcSimulatorDataRequestMethod(XmlRpcRequest request) - { - Hashtable requestData = (Hashtable)request.Params[0]; - Hashtable responseData = new Hashtable(); - RegionProfileData simData = null; - if (requestData.ContainsKey("region_UUID")) - { - UUID regionID = new UUID((string)requestData["region_UUID"]); - simData = m_gridDBService.GetRegion(regionID); - if (simData == null) - { - m_log.WarnFormat("[DATA] didn't find region for regionID {0} from {1}", - regionID, request.Params.Count > 1 ? request.Params[1] : "unknwon source"); - } - } - else if (requestData.ContainsKey("region_handle")) - { - //CFK: The if/else below this makes this message redundant. - //CFK: m_log.Info("requesting data for region " + (string) requestData["region_handle"]); - ulong regionHandle = Convert.ToUInt64((string)requestData["region_handle"]); - simData = m_gridDBService.GetRegion(regionHandle); - if (simData == null) - { - m_log.WarnFormat("[DATA] didn't find region for regionHandle {0} from {1}", - regionHandle, request.Params.Count > 1 ? request.Params[1] : "unknwon source"); - } - } - else if (requestData.ContainsKey("region_name_search")) - { - string regionName = (string)requestData["region_name_search"]; - simData = m_gridDBService.GetRegion(regionName); - if (simData == null) - { - m_log.WarnFormat("[DATA] didn't find region for regionName {0} from {1}", - regionName, request.Params.Count > 1 ? request.Params[1] : "unknwon source"); - } - } - else m_log.Warn("[DATA] regionlookup without regionID, regionHandle or regionHame"); - - if (simData == null) - { - //Sim does not exist - responseData["error"] = "Sim does not exist"; - } - else - { - m_log.Info("[DATA]: found " + (string)simData.regionName + " regionHandle = " + - (string)requestData["region_handle"]); - responseData["sim_ip"] = simData.serverIP; - responseData["sim_port"] = simData.serverPort.ToString(); - responseData["server_uri"] = simData.serverURI; - responseData["http_port"] = simData.httpPort.ToString(); - responseData["remoting_port"] = simData.remotingPort.ToString(); - responseData["region_locx"] = simData.regionLocX.ToString(); - responseData["region_locy"] = simData.regionLocY.ToString(); - responseData["region_UUID"] = simData.UUID.Guid.ToString(); - responseData["region_name"] = simData.regionName; - responseData["regionHandle"] = simData.regionHandle.ToString(); - } - - XmlRpcResponse response = new XmlRpcResponse(); - response.Value = responseData; - return response; - } - - public XmlRpcResponse XmlRpcMapBlockMethod(XmlRpcRequest request) - { - int xmin = 980, ymin = 980, xmax = 1020, ymax = 1020; - - Hashtable requestData = (Hashtable)request.Params[0]; - if (requestData.ContainsKey("xmin")) - { - xmin = (Int32)requestData["xmin"]; - } - if (requestData.ContainsKey("ymin")) - { - ymin = (Int32)requestData["ymin"]; - } - if (requestData.ContainsKey("xmax")) - { - xmax = (Int32)requestData["xmax"]; - } - if (requestData.ContainsKey("ymax")) - { - ymax = (Int32)requestData["ymax"]; - } - //CFK: The second log is more meaningful and either standard or fast generally occurs. - //CFK: m_log.Info("[MAP]: World map request for range (" + xmin + "," + ymin + ")..(" + xmax + "," + ymax + ")"); - - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable responseData = new Hashtable(); - response.Value = responseData; - IList simProfileList = new ArrayList(); - - bool fastMode = (m_config.DatabaseProvider == "OpenSim.Data.MySQL.dll" || m_config.DatabaseProvider == "OpenSim.Data.MSSQL.dll"); - - if (fastMode) - { - List neighbours = m_gridDBService.GetRegions((uint)xmin, (uint)ymin, (uint)xmax, (uint)ymax); - - foreach (RegionProfileData aSim in neighbours) - { - Hashtable simProfileBlock = new Hashtable(); - simProfileBlock["x"] = aSim.regionLocX.ToString(); - simProfileBlock["y"] = aSim.regionLocY.ToString(); - //m_log.DebugFormat("[MAP]: Sending neighbour info for {0},{1}", aSim.regionLocX, aSim.regionLocY); - simProfileBlock["name"] = aSim.regionName; - simProfileBlock["access"] = 21; - simProfileBlock["region-flags"] = 512; - simProfileBlock["water-height"] = 0; - simProfileBlock["agents"] = 1; - simProfileBlock["map-image-id"] = aSim.regionMapTextureID.ToString(); - - // For Sugilite compatibility - simProfileBlock["regionhandle"] = aSim.regionHandle.ToString(); - simProfileBlock["sim_ip"] = aSim.serverIP; - simProfileBlock["sim_port"] = aSim.serverPort.ToString(); - simProfileBlock["sim_uri"] = aSim.serverURI.ToString(); - simProfileBlock["uuid"] = aSim.UUID.ToString(); - simProfileBlock["remoting_port"] = aSim.remotingPort.ToString(); - simProfileBlock["http_port"] = aSim.httpPort.ToString(); - - simProfileList.Add(simProfileBlock); - } - m_log.Info("[MAP]: Fast map " + simProfileList.Count.ToString() + - " regions @ (" + xmin + "," + ymin + ")..(" + xmax + "," + ymax + ")"); - } - else - { - RegionProfileData simProfile; - for (int x = xmin; x < xmax + 1; x++) - { - for (int y = ymin; y < ymax + 1; y++) - { - ulong regHandle = Utils.UIntsToLong((uint)(x * Constants.RegionSize), (uint)(y * Constants.RegionSize)); - simProfile = m_gridDBService.GetRegion(regHandle); - if (simProfile != null) - { - Hashtable simProfileBlock = new Hashtable(); - simProfileBlock["x"] = x; - simProfileBlock["y"] = y; - simProfileBlock["name"] = simProfile.regionName; - simProfileBlock["access"] = 0; - simProfileBlock["region-flags"] = 0; - simProfileBlock["water-height"] = 20; - simProfileBlock["agents"] = 1; - simProfileBlock["map-image-id"] = simProfile.regionMapTextureID.ToString(); - - // For Sugilite compatibility - simProfileBlock["regionhandle"] = simProfile.regionHandle.ToString(); - simProfileBlock["sim_ip"] = simProfile.serverIP.ToString(); - simProfileBlock["sim_port"] = simProfile.serverPort.ToString(); - simProfileBlock["sim_uri"] = simProfile.serverURI.ToString(); - simProfileBlock["uuid"] = simProfile.UUID.ToString(); - simProfileBlock["remoting_port"] = simProfile.remotingPort.ToString(); - simProfileBlock["http_port"] = simProfile.httpPort; - - simProfileList.Add(simProfileBlock); - } - } - } - m_log.Info("[MAP]: Std map " + simProfileList.Count.ToString() + - " regions @ (" + xmin + "," + ymin + ")..(" + xmax + "," + ymax + ")"); - } - - responseData["sim-profiles"] = simProfileList; - - return response; - } - - /// - /// Returns up to maxNumber profiles of regions that have a name starting with name - /// - /// - /// - public XmlRpcResponse XmlRpcSearchForRegionMethod(XmlRpcRequest request) - { - Hashtable requestData = (Hashtable)request.Params[0]; - - if (!requestData.ContainsKey("name") || !requestData.Contains("maxNumber")) - { - m_log.Warn("[DATA] Invalid region-search request; missing name or maxNumber"); - return new XmlRpcResponse(500, "Missing name or maxNumber in region search request"); - } - - Hashtable responseData = new Hashtable(); - - string name = (string)requestData["name"]; - int maxNumber = Convert.ToInt32((string)requestData["maxNumber"]); - if (maxNumber == 0 || name.Length < 3) - { - // either we didn't want any, or we were too unspecific - responseData["numFound"] = 0; - } - else - { - List sims = m_gridDBService.GetRegions(name, maxNumber); - - responseData["numFound"] = sims.Count; - for (int i = 0; i < sims.Count; ++i) - { - RegionProfileData sim = sims[i]; - string prefix = "region" + i + "."; - responseData[prefix + "region_name"] = sim.regionName; - responseData[prefix + "region_UUID"] = sim.UUID.ToString(); - responseData[prefix + "region_locx"] = sim.regionLocX.ToString(); - responseData[prefix + "region_locy"] = sim.regionLocY.ToString(); - responseData[prefix + "sim_ip"] = sim.serverIP.ToString(); - responseData[prefix + "sim_port"] = sim.serverPort.ToString(); - responseData[prefix + "remoting_port"] = sim.remotingPort.ToString(); - responseData[prefix + "http_port"] = sim.httpPort.ToString(); - responseData[prefix + "map_UUID"] = sim.regionMapTextureID.ToString(); - } - } - - XmlRpcResponse response = new XmlRpcResponse(); - response.Value = responseData; - return response; - } - - /// - /// Construct an XMLRPC registration disabled response - /// - /// - /// - public static XmlRpcResponse XmlRPCRegionRegistrationDisabledResponse(string error) - { - XmlRpcResponse errorResponse = new XmlRpcResponse(); - Hashtable errorResponseData = new Hashtable(); - errorResponse.Value = errorResponseData; - errorResponseData["restricted"] = error; - return errorResponse; - } - } - - /// - /// Exception generated when a simulator fails to login to the grid - /// - public class LoginException : Exception - { - /// - /// Return an XmlRpcResponse version of the exception message suitable for sending to a client - /// - /// - /// - public XmlRpcResponse XmlRpcErrorResponse - { - get { return m_xmlRpcErrorResponse; } - } - private XmlRpcResponse m_xmlRpcErrorResponse; - - public LoginException(string message, string xmlRpcMessage) - : base(message) - { - // FIXME: Might be neater to refactor and put the method inside here - m_xmlRpcErrorResponse = GridXmlRpcModule.ErrorResponse(xmlRpcMessage); - } - - public LoginException(string message, string xmlRpcMessage, Exception e) - : base(message, e) - { - // FIXME: Might be neater to refactor and put the method inside here - m_xmlRpcErrorResponse = GridXmlRpcModule.ErrorResponse(xmlRpcMessage); - } - } -} +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Xml; +using log4net; +using Nwc.XmlRpc; +using OpenMetaverse; +using OpenSim.Data; +using OpenSim.Framework; +using OpenSim.Framework.Communications; +using OpenSim.Framework.Servers; +using OpenSim.Grid.Framework; + +namespace OpenSim.Grid.GridServer.Modules +{ + public class GridXmlRpcModule + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private GridDBService m_gridDBService; + private IUGAIMCore m_gridCore; + + protected GridConfig m_config; + + protected IGridMessagingMapper m_messagingServerMapper; + /// + /// Used to notify old regions as to which OpenSim version to upgrade to + /// + private string m_opensimVersion; + + protected BaseHttpServer m_httpServer; + + /// + /// Constructor + /// + /// + /// Used to notify old regions as to which OpenSim version to upgrade to + /// + public GridXmlRpcModule() + { + } + + public void Initialise(string opensimVersion, GridDBService gridDBService, IUGAIMCore gridCore, GridConfig config) + { + m_opensimVersion = opensimVersion; + m_gridDBService = gridDBService; + m_gridCore = gridCore; + m_config = config; + RegisterHandlers(); + } + + public void PostInitialise() + { + IGridMessagingMapper messagingModule; + if (m_gridCore.TryGet(out messagingModule)) + { + m_messagingServerMapper = messagingModule; + } + } + + public void RegisterHandlers() + { + //have these in separate method as some servers restart the http server and reregister all the handlers. + m_httpServer = m_gridCore.GetHttpServer(); + + m_httpServer.AddXmlRPCHandler("simulator_login", XmlRpcSimulatorLoginMethod); + m_httpServer.AddXmlRPCHandler("simulator_data_request", XmlRpcSimulatorDataRequestMethod); + m_httpServer.AddXmlRPCHandler("simulator_after_region_moved", XmlRpcDeleteRegionMethod); + m_httpServer.AddXmlRPCHandler("map_block", XmlRpcMapBlockMethod); + m_httpServer.AddXmlRPCHandler("search_for_region_by_name", XmlRpcSearchForRegionMethod); + } + + /// + /// Returns a XML String containing a list of the neighbouring regions + /// + /// The regionhandle for the center sim + /// An XML string containing neighbour entities + public string GetXMLNeighbours(ulong reqhandle) + { + string response = String.Empty; + RegionProfileData central_region = m_gridDBService.GetRegion(reqhandle); + RegionProfileData neighbour; + for (int x = -1; x < 2; x++) + { + for (int y = -1; y < 2; y++) + { + if ( + m_gridDBService.GetRegion( + Util.UIntsToLong((uint)((central_region.regionLocX + x) * Constants.RegionSize), + (uint)(central_region.regionLocY + y) * Constants.RegionSize)) != null) + { + neighbour = + m_gridDBService.GetRegion( + Util.UIntsToLong((uint)((central_region.regionLocX + x) * Constants.RegionSize), + (uint)(central_region.regionLocY + y) * Constants.RegionSize)); + + response += ""; + response += "" + neighbour.serverIP + ""; + response += "" + neighbour.serverPort.ToString() + ""; + response += "" + neighbour.regionLocX.ToString() + ""; + response += "" + neighbour.regionLocY.ToString() + ""; + response += "" + neighbour.regionHandle.ToString() + ""; + response += ""; + } + } + } + return response; + } + + /// + /// Checks that it's valid to replace the existing region data with new data + /// + /// Currently, this means ensure that the keys passed in by the new region + /// match those in the original region. (XXX Is this correct? Shouldn't we simply check + /// against the keys in the current configuration?) + /// + /// + /// + protected virtual void ValidateOverwriteKeys(RegionProfileData sim, RegionProfileData existingSim) + { + if (!(existingSim.regionRecvKey == sim.regionRecvKey && existingSim.regionSendKey == sim.regionSendKey)) + { + throw new LoginException( + String.Format( + "Authentication failed when trying to login existing region {0} at location {1} {2} currently occupied by {3}" + + " with the region's send key {4} (expected {5}) and the region's receive key {6} (expected {7})", + sim.regionName, sim.regionLocX, sim.regionLocY, existingSim.regionName, + sim.regionSendKey, existingSim.regionSendKey, sim.regionRecvKey, existingSim.regionRecvKey), + "The keys required to login your region did not match the grid server keys. Please check your grid send and receive keys."); + } + } + + /// + /// Checks that the new region data is valid. + /// + /// Currently, this means checking that the keys passed in by the new region + /// match those in the grid server's configuration. + /// + /// + /// + /// Thrown if region login failed + protected virtual void ValidateNewRegionKeys(RegionProfileData sim) + { + if (!(sim.regionRecvKey == m_config.SimSendKey && sim.regionSendKey == m_config.SimRecvKey)) + { + throw new LoginException( + String.Format( + "Authentication failed when trying to login new region {0} at location {1} {2}" + + " with the region's send key {3} (expected {4}) and the region's receive key {5} (expected {6})", + sim.regionName, sim.regionLocX, sim.regionLocY, + sim.regionSendKey, m_config.SimRecvKey, sim.regionRecvKey, m_config.SimSendKey), + "The keys required to login your region did not match your existing region keys. Please check your grid send and receive keys."); + } + } + + /// + /// Check that a region's http uri is externally contactable. + /// + /// + /// Thrown if the region is not contactable + protected virtual void ValidateRegionContactable(RegionProfileData sim) + { + string regionStatusUrl = String.Format("{0}{1}", sim.httpServerURI, "simstatus/"); + string regionStatusResponse; + + RestClient rc = new RestClient(regionStatusUrl); + rc.RequestMethod = "GET"; + + m_log.DebugFormat("[LOGIN]: Contacting {0} for status of region {1}", regionStatusUrl, sim.regionName); + + try + { + Stream rs = rc.Request(); + StreamReader sr = new StreamReader(rs); + regionStatusResponse = sr.ReadToEnd(); + sr.Close(); + } + catch (Exception e) + { + throw new LoginException( + String.Format("Region status request to {0} failed", regionStatusUrl), + String.Format( + "The grid service could not contact the http url {0} at your region. Please make sure this url is reachable by the grid service", + regionStatusUrl), + e); + } + + if (!regionStatusResponse.Equals("OK")) + { + throw new LoginException( + String.Format( + "Region {0} at {1} returned status response {2} rather than {3}", + sim.regionName, regionStatusUrl, regionStatusResponse, "OK"), + String.Format( + "When the grid service asked for the status of your region, it received the response {0} rather than {1}. Please check your status", + regionStatusResponse, "OK")); + } + } + + /// + /// Construct an XMLRPC error response + /// + /// + /// + public static XmlRpcResponse ErrorResponse(string error) + { + XmlRpcResponse errorResponse = new XmlRpcResponse(); + Hashtable errorResponseData = new Hashtable(); + errorResponse.Value = errorResponseData; + errorResponseData["error"] = error; + return errorResponse; + } + + /// + /// Performed when a region connects to the grid server initially. + /// + /// The XML RPC Request + /// Startup parameters + public XmlRpcResponse XmlRpcSimulatorLoginMethod(XmlRpcRequest request) + { + RegionProfileData sim; + RegionProfileData existingSim; + + Hashtable requestData = (Hashtable)request.Params[0]; + UUID uuid; + + if (!requestData.ContainsKey("UUID") || !UUID.TryParse((string)requestData["UUID"], out uuid)) + { + m_log.Debug("[LOGIN PRELUDE]: Region connected without a UUID, sending back error response."); + return ErrorResponse("No UUID passed to grid server - unable to connect you"); + } + + try + { + sim = RegionFromRequest(requestData); + } + catch (FormatException e) + { + m_log.Debug("[LOGIN PRELUDE]: Invalid login parameters, sending back error response."); + return ErrorResponse("Wrong format in login parameters. Please verify parameters." + e.ToString()); + } + + m_log.InfoFormat("[LOGIN BEGIN]: Received login request from simulator: {0}", sim.regionName); + + if (!m_config.AllowRegionRegistration) + { + m_log.DebugFormat( + "[LOGIN END]: Disabled region registration blocked login request from simulator: {0}", + sim.regionName); + + return ErrorResponse("This grid is currently not accepting region registrations."); + } + + int majorInterfaceVersion = 0; + if (requestData.ContainsKey("major_interface_version")) + int.TryParse((string)requestData["major_interface_version"], out majorInterfaceVersion); + + if (majorInterfaceVersion != VersionInfo.MajorInterfaceVersion) + { + return ErrorResponse( + String.Format( + "Your region service implements OGS1 interface version {0}" + + " but this grid requires that the region implement OGS1 interface version {1} to connect." + + " Try changing to OpenSimulator {2}", + majorInterfaceVersion, VersionInfo.MajorInterfaceVersion, m_opensimVersion)); + } + + existingSim = m_gridDBService.GetRegion(sim.regionHandle); + + if (existingSim == null || existingSim.UUID == sim.UUID || sim.UUID != sim.originUUID) + { + try + { + if (existingSim == null) + { + ValidateNewRegionKeys(sim); + } + else + { + ValidateOverwriteKeys(sim, existingSim); + } + + ValidateRegionContactable(sim); + } + catch (LoginException e) + { + string logMsg = e.Message; + if (e.InnerException != null) + logMsg += ", " + e.InnerException.Message; + + m_log.WarnFormat("[LOGIN END]: {0}", logMsg); + + return e.XmlRpcErrorResponse; + } + + DataResponse insertResponse = m_gridDBService.AddUpdateRegion(sim, existingSim); + + switch (insertResponse) + { + case DataResponse.RESPONSE_OK: + m_log.Info("[LOGIN END]: " + (existingSim == null ? "New" : "Existing") + " sim login successful: " + sim.regionName); + break; + case DataResponse.RESPONSE_ERROR: + m_log.Warn("[LOGIN END]: Sim login failed (Error): " + sim.regionName); + break; + case DataResponse.RESPONSE_INVALIDCREDENTIALS: + m_log.Warn("[LOGIN END]: " + + "Sim login failed (Invalid Credentials): " + sim.regionName); + break; + case DataResponse.RESPONSE_AUTHREQUIRED: + m_log.Warn("[LOGIN END]: " + + "Sim login failed (Authentication Required): " + + sim.regionName); + break; + } + + XmlRpcResponse response = CreateLoginResponse(sim); + + return response; + } + else + { + m_log.Warn("[LOGIN END]: Failed to login region " + sim.regionName + " at location " + sim.regionLocX + " " + sim.regionLocY + " currently occupied by " + existingSim.regionName); + return ErrorResponse("Another region already exists at that location. Please try another."); + } + } + + /// + /// Construct a successful response to a simulator's login attempt. + /// + /// + /// + private XmlRpcResponse CreateLoginResponse(RegionProfileData sim) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable responseData = new Hashtable(); + response.Value = responseData; + + ArrayList SimNeighboursData = GetSimNeighboursData(sim); + + responseData["UUID"] = sim.UUID.ToString(); + responseData["region_locx"] = sim.regionLocX.ToString(); + responseData["region_locy"] = sim.regionLocY.ToString(); + responseData["regionname"] = sim.regionName; + responseData["estate_id"] = "1"; + responseData["neighbours"] = SimNeighboursData; + + responseData["sim_ip"] = sim.serverIP; + responseData["sim_port"] = sim.serverPort.ToString(); + responseData["asset_url"] = sim.regionAssetURI; + responseData["asset_sendkey"] = sim.regionAssetSendKey; + responseData["asset_recvkey"] = sim.regionAssetRecvKey; + responseData["user_url"] = sim.regionUserURI; + responseData["user_sendkey"] = sim.regionUserSendKey; + responseData["user_recvkey"] = sim.regionUserRecvKey; + responseData["authkey"] = sim.regionSecret; + + // New! If set, use as URL to local sim storage (ie http://remotehost/region.Yap) + responseData["data_uri"] = sim.regionDataURI; + + responseData["allow_forceful_banlines"] = m_config.AllowForcefulBanlines; + + // Instead of sending a multitude of message servers to the registering sim + // we should probably be sending a single one and parhaps it's backup + // that has responsibility over routing it's messages. + + // The Sim won't be contacting us again about any of the message server stuff during it's time up. + + responseData["messageserver_count"] = 0; + + // IGridMessagingModule messagingModule; + // if (m_gridCore.TryGet(out messagingModule)) + //{ + if(m_messagingServerMapper != null) + { + List messageServers = m_messagingServerMapper.GetMessageServersList(); + responseData["messageserver_count"] = messageServers.Count; + + for (int i = 0; i < messageServers.Count; i++) + { + responseData["messageserver_uri" + i] = messageServers[i].URI; + responseData["messageserver_sendkey" + i] = messageServers[i].sendkey; + responseData["messageserver_recvkey" + i] = messageServers[i].recvkey; + } + } + return response; + } + + private ArrayList GetSimNeighboursData(RegionProfileData sim) + { + ArrayList SimNeighboursData = new ArrayList(); + + RegionProfileData neighbour; + Hashtable NeighbourBlock; + + //First use the fast method. (not implemented in SQLLite) + List neighbours = m_gridDBService.GetRegions(sim.regionLocX - 1, sim.regionLocY - 1, sim.regionLocX + 1, sim.regionLocY + 1); + + if (neighbours.Count > 0) + { + foreach (RegionProfileData aSim in neighbours) + { + NeighbourBlock = new Hashtable(); + NeighbourBlock["sim_ip"] = aSim.serverIP; + NeighbourBlock["sim_port"] = aSim.serverPort.ToString(); + NeighbourBlock["region_locx"] = aSim.regionLocX.ToString(); + NeighbourBlock["region_locy"] = aSim.regionLocY.ToString(); + NeighbourBlock["UUID"] = aSim.ToString(); + NeighbourBlock["regionHandle"] = aSim.regionHandle.ToString(); + + if (aSim.UUID != sim.UUID) + { + SimNeighboursData.Add(NeighbourBlock); + } + } + } + else + { + for (int x = -1; x < 2; x++) + { + for (int y = -1; y < 2; y++) + { + if ( + m_gridDBService.GetRegion( + Utils.UIntsToLong((uint)((sim.regionLocX + x) * Constants.RegionSize), + (uint)(sim.regionLocY + y) * Constants.RegionSize)) != null) + { + neighbour = + m_gridDBService.GetRegion( + Utils.UIntsToLong((uint)((sim.regionLocX + x) * Constants.RegionSize), + (uint)(sim.regionLocY + y) * Constants.RegionSize)); + + NeighbourBlock = new Hashtable(); + NeighbourBlock["sim_ip"] = neighbour.serverIP; + NeighbourBlock["sim_port"] = neighbour.serverPort.ToString(); + NeighbourBlock["region_locx"] = neighbour.regionLocX.ToString(); + NeighbourBlock["region_locy"] = neighbour.regionLocY.ToString(); + NeighbourBlock["UUID"] = neighbour.UUID.ToString(); + NeighbourBlock["regionHandle"] = neighbour.regionHandle.ToString(); + + if (neighbour.UUID != sim.UUID) SimNeighboursData.Add(NeighbourBlock); + } + } + } + } + return SimNeighboursData; + } + + /// + /// Loads the grid's own RegionProfileData object with data from the XMLRPC simulator_login request from a region + /// + /// + /// + private RegionProfileData RegionFromRequest(Hashtable requestData) + { + RegionProfileData sim; + sim = new RegionProfileData(); + + sim.UUID = new UUID((string)requestData["UUID"]); + sim.originUUID = new UUID((string)requestData["originUUID"]); + + sim.regionRecvKey = String.Empty; + sim.regionSendKey = String.Empty; + + if (requestData.ContainsKey("region_secret")) + { + string regionsecret = (string)requestData["region_secret"]; + if (regionsecret.Length > 0) + sim.regionSecret = regionsecret; + else + sim.regionSecret = m_config.SimRecvKey; + + } + else + { + sim.regionSecret = m_config.SimRecvKey; + } + + sim.regionDataURI = String.Empty; + sim.regionAssetURI = m_config.DefaultAssetServer; + sim.regionAssetRecvKey = m_config.AssetRecvKey; + sim.regionAssetSendKey = m_config.AssetSendKey; + sim.regionUserURI = m_config.DefaultUserServer; + sim.regionUserSendKey = m_config.UserSendKey; + sim.regionUserRecvKey = m_config.UserRecvKey; + + sim.serverIP = (string)requestData["sim_ip"]; + sim.serverPort = Convert.ToUInt32((string)requestData["sim_port"]); + sim.httpPort = Convert.ToUInt32((string)requestData["http_port"]); + sim.remotingPort = Convert.ToUInt32((string)requestData["remoting_port"]); + sim.regionLocX = Convert.ToUInt32((string)requestData["region_locx"]); + sim.regionLocY = Convert.ToUInt32((string)requestData["region_locy"]); + sim.regionLocZ = 0; + + UUID textureID; + if (UUID.TryParse((string)requestData["map-image-id"], out textureID)) + { + sim.regionMapTextureID = textureID; + } + + // part of an initial brutish effort to provide accurate information (as per the xml region spec) + // wrt the ownership of a given region + // the (very bad) assumption is that this value is being read and handled inconsistently or + // not at all. Current strategy is to put the code in place to support the validity of this information + // and to roll forward debugging any issues from that point + // + // this particular section of the mod attempts to receive a value from the region's xml file by way of + // OSG1GridServices for the region's owner + sim.owner_uuid = (UUID)(string)requestData["master_avatar_uuid"]; + + try + { + sim.regionRecvKey = (string)requestData["recvkey"]; + sim.regionSendKey = (string)requestData["authkey"]; + } + catch (KeyNotFoundException) { } + + sim.regionHandle = Utils.UIntsToLong((sim.regionLocX * Constants.RegionSize), (sim.regionLocY * Constants.RegionSize)); + sim.serverURI = (string)requestData["server_uri"]; + + sim.httpServerURI = "http://" + sim.serverIP + ":" + sim.httpPort + "/"; + + sim.regionName = (string)requestData["sim_name"]; + return sim; + } + + /// + /// Returns an XML RPC response to a simulator profile request + /// Performed after moving a region. + /// + /// + /// + /// The XMLRPC Request + /// Processing parameters + public XmlRpcResponse XmlRpcDeleteRegionMethod(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable responseData = new Hashtable(); + response.Value = responseData; + + //RegionProfileData TheSim = null; + string uuid; + Hashtable requestData = (Hashtable)request.Params[0]; + + if (requestData.ContainsKey("UUID")) + { + //TheSim = GetRegion(new UUID((string) requestData["UUID"])); + uuid = requestData["UUID"].ToString(); + m_log.InfoFormat("[LOGOUT]: Logging out region: {0}", uuid); + // logToDB((new LLUUID((string)requestData["UUID"])).ToString(),"XmlRpcDeleteRegionMethod","", 5,"Attempting delete with UUID."); + } + else + { + responseData["error"] = "No UUID or region_handle passed to grid server - unable to delete"; + return response; + } + + DataResponse insertResponse = m_gridDBService.DeleteRegion(uuid); + + string insertResp = ""; + switch (insertResponse) + { + case DataResponse.RESPONSE_OK: + //MainLog.Instance.Verbose("grid", "Deleting region successful: " + uuid); + insertResp = "Deleting region successful: " + uuid; + break; + case DataResponse.RESPONSE_ERROR: + //MainLog.Instance.Warn("storage", "Deleting region failed (Error): " + uuid); + insertResp = "Deleting region failed (Error): " + uuid; + break; + case DataResponse.RESPONSE_INVALIDCREDENTIALS: + //MainLog.Instance.Warn("storage", "Deleting region failed (Invalid Credentials): " + uuid); + insertResp = "Deleting region (Invalid Credentials): " + uuid; + break; + case DataResponse.RESPONSE_AUTHREQUIRED: + //MainLog.Instance.Warn("storage", "Deleting region failed (Authentication Required): " + uuid); + insertResp = "Deleting region (Authentication Required): " + uuid; + break; + } + + responseData["status"] = insertResp; + + return response; + } + + /// + /// Returns an XML RPC response to a simulator profile request + /// + /// + /// + public XmlRpcResponse XmlRpcSimulatorDataRequestMethod(XmlRpcRequest request) + { + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable responseData = new Hashtable(); + RegionProfileData simData = null; + if (requestData.ContainsKey("region_UUID")) + { + UUID regionID = new UUID((string)requestData["region_UUID"]); + simData = m_gridDBService.GetRegion(regionID); + if (simData == null) + { + m_log.WarnFormat("[DATA] didn't find region for regionID {0} from {1}", + regionID, request.Params.Count > 1 ? request.Params[1] : "unknwon source"); + } + } + else if (requestData.ContainsKey("region_handle")) + { + //CFK: The if/else below this makes this message redundant. + //CFK: m_log.Info("requesting data for region " + (string) requestData["region_handle"]); + ulong regionHandle = Convert.ToUInt64((string)requestData["region_handle"]); + simData = m_gridDBService.GetRegion(regionHandle); + if (simData == null) + { + m_log.WarnFormat("[DATA] didn't find region for regionHandle {0} from {1}", + regionHandle, request.Params.Count > 1 ? request.Params[1] : "unknwon source"); + } + } + else if (requestData.ContainsKey("region_name_search")) + { + string regionName = (string)requestData["region_name_search"]; + simData = m_gridDBService.GetRegion(regionName); + if (simData == null) + { + m_log.WarnFormat("[DATA] didn't find region for regionName {0} from {1}", + regionName, request.Params.Count > 1 ? request.Params[1] : "unknwon source"); + } + } + else m_log.Warn("[DATA] regionlookup without regionID, regionHandle or regionHame"); + + if (simData == null) + { + //Sim does not exist + responseData["error"] = "Sim does not exist"; + } + else + { + m_log.Info("[DATA]: found " + (string)simData.regionName + " regionHandle = " + + (string)requestData["region_handle"]); + responseData["sim_ip"] = simData.serverIP; + responseData["sim_port"] = simData.serverPort.ToString(); + responseData["server_uri"] = simData.serverURI; + responseData["http_port"] = simData.httpPort.ToString(); + responseData["remoting_port"] = simData.remotingPort.ToString(); + responseData["region_locx"] = simData.regionLocX.ToString(); + responseData["region_locy"] = simData.regionLocY.ToString(); + responseData["region_UUID"] = simData.UUID.Guid.ToString(); + responseData["region_name"] = simData.regionName; + responseData["regionHandle"] = simData.regionHandle.ToString(); + } + + XmlRpcResponse response = new XmlRpcResponse(); + response.Value = responseData; + return response; + } + + public XmlRpcResponse XmlRpcMapBlockMethod(XmlRpcRequest request) + { + int xmin = 980, ymin = 980, xmax = 1020, ymax = 1020; + + Hashtable requestData = (Hashtable)request.Params[0]; + if (requestData.ContainsKey("xmin")) + { + xmin = (Int32)requestData["xmin"]; + } + if (requestData.ContainsKey("ymin")) + { + ymin = (Int32)requestData["ymin"]; + } + if (requestData.ContainsKey("xmax")) + { + xmax = (Int32)requestData["xmax"]; + } + if (requestData.ContainsKey("ymax")) + { + ymax = (Int32)requestData["ymax"]; + } + //CFK: The second log is more meaningful and either standard or fast generally occurs. + //CFK: m_log.Info("[MAP]: World map request for range (" + xmin + "," + ymin + ")..(" + xmax + "," + ymax + ")"); + + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable responseData = new Hashtable(); + response.Value = responseData; + IList simProfileList = new ArrayList(); + + bool fastMode = (m_config.DatabaseProvider == "OpenSim.Data.MySQL.dll" || m_config.DatabaseProvider == "OpenSim.Data.MSSQL.dll"); + + if (fastMode) + { + List neighbours = m_gridDBService.GetRegions((uint)xmin, (uint)ymin, (uint)xmax, (uint)ymax); + + foreach (RegionProfileData aSim in neighbours) + { + Hashtable simProfileBlock = new Hashtable(); + simProfileBlock["x"] = aSim.regionLocX.ToString(); + simProfileBlock["y"] = aSim.regionLocY.ToString(); + //m_log.DebugFormat("[MAP]: Sending neighbour info for {0},{1}", aSim.regionLocX, aSim.regionLocY); + simProfileBlock["name"] = aSim.regionName; + simProfileBlock["access"] = 21; + simProfileBlock["region-flags"] = 512; + simProfileBlock["water-height"] = 0; + simProfileBlock["agents"] = 1; + simProfileBlock["map-image-id"] = aSim.regionMapTextureID.ToString(); + + // For Sugilite compatibility + simProfileBlock["regionhandle"] = aSim.regionHandle.ToString(); + simProfileBlock["sim_ip"] = aSim.serverIP; + simProfileBlock["sim_port"] = aSim.serverPort.ToString(); + simProfileBlock["sim_uri"] = aSim.serverURI.ToString(); + simProfileBlock["uuid"] = aSim.UUID.ToString(); + simProfileBlock["remoting_port"] = aSim.remotingPort.ToString(); + simProfileBlock["http_port"] = aSim.httpPort.ToString(); + + simProfileList.Add(simProfileBlock); + } + m_log.Info("[MAP]: Fast map " + simProfileList.Count.ToString() + + " regions @ (" + xmin + "," + ymin + ")..(" + xmax + "," + ymax + ")"); + } + else + { + RegionProfileData simProfile; + for (int x = xmin; x < xmax + 1; x++) + { + for (int y = ymin; y < ymax + 1; y++) + { + ulong regHandle = Utils.UIntsToLong((uint)(x * Constants.RegionSize), (uint)(y * Constants.RegionSize)); + simProfile = m_gridDBService.GetRegion(regHandle); + if (simProfile != null) + { + Hashtable simProfileBlock = new Hashtable(); + simProfileBlock["x"] = x; + simProfileBlock["y"] = y; + simProfileBlock["name"] = simProfile.regionName; + simProfileBlock["access"] = 0; + simProfileBlock["region-flags"] = 0; + simProfileBlock["water-height"] = 20; + simProfileBlock["agents"] = 1; + simProfileBlock["map-image-id"] = simProfile.regionMapTextureID.ToString(); + + // For Sugilite compatibility + simProfileBlock["regionhandle"] = simProfile.regionHandle.ToString(); + simProfileBlock["sim_ip"] = simProfile.serverIP.ToString(); + simProfileBlock["sim_port"] = simProfile.serverPort.ToString(); + simProfileBlock["sim_uri"] = simProfile.serverURI.ToString(); + simProfileBlock["uuid"] = simProfile.UUID.ToString(); + simProfileBlock["remoting_port"] = simProfile.remotingPort.ToString(); + simProfileBlock["http_port"] = simProfile.httpPort; + + simProfileList.Add(simProfileBlock); + } + } + } + m_log.Info("[MAP]: Std map " + simProfileList.Count.ToString() + + " regions @ (" + xmin + "," + ymin + ")..(" + xmax + "," + ymax + ")"); + } + + responseData["sim-profiles"] = simProfileList; + + return response; + } + + /// + /// Returns up to maxNumber profiles of regions that have a name starting with name + /// + /// + /// + public XmlRpcResponse XmlRpcSearchForRegionMethod(XmlRpcRequest request) + { + Hashtable requestData = (Hashtable)request.Params[0]; + + if (!requestData.ContainsKey("name") || !requestData.Contains("maxNumber")) + { + m_log.Warn("[DATA] Invalid region-search request; missing name or maxNumber"); + return new XmlRpcResponse(500, "Missing name or maxNumber in region search request"); + } + + Hashtable responseData = new Hashtable(); + + string name = (string)requestData["name"]; + int maxNumber = Convert.ToInt32((string)requestData["maxNumber"]); + if (maxNumber == 0 || name.Length < 3) + { + // either we didn't want any, or we were too unspecific + responseData["numFound"] = 0; + } + else + { + List sims = m_gridDBService.GetRegions(name, maxNumber); + + responseData["numFound"] = sims.Count; + for (int i = 0; i < sims.Count; ++i) + { + RegionProfileData sim = sims[i]; + string prefix = "region" + i + "."; + responseData[prefix + "region_name"] = sim.regionName; + responseData[prefix + "region_UUID"] = sim.UUID.ToString(); + responseData[prefix + "region_locx"] = sim.regionLocX.ToString(); + responseData[prefix + "region_locy"] = sim.regionLocY.ToString(); + responseData[prefix + "sim_ip"] = sim.serverIP.ToString(); + responseData[prefix + "sim_port"] = sim.serverPort.ToString(); + responseData[prefix + "remoting_port"] = sim.remotingPort.ToString(); + responseData[prefix + "http_port"] = sim.httpPort.ToString(); + responseData[prefix + "map_UUID"] = sim.regionMapTextureID.ToString(); + } + } + + XmlRpcResponse response = new XmlRpcResponse(); + response.Value = responseData; + return response; + } + + /// + /// Construct an XMLRPC registration disabled response + /// + /// + /// + public static XmlRpcResponse XmlRPCRegionRegistrationDisabledResponse(string error) + { + XmlRpcResponse errorResponse = new XmlRpcResponse(); + Hashtable errorResponseData = new Hashtable(); + errorResponse.Value = errorResponseData; + errorResponseData["restricted"] = error; + return errorResponse; + } + } + + /// + /// Exception generated when a simulator fails to login to the grid + /// + public class LoginException : Exception + { + /// + /// Return an XmlRpcResponse version of the exception message suitable for sending to a client + /// + /// + /// + public XmlRpcResponse XmlRpcErrorResponse + { + get { return m_xmlRpcErrorResponse; } + } + private XmlRpcResponse m_xmlRpcErrorResponse; + + public LoginException(string message, string xmlRpcMessage) + : base(message) + { + // FIXME: Might be neater to refactor and put the method inside here + m_xmlRpcErrorResponse = GridXmlRpcModule.ErrorResponse(xmlRpcMessage); + } + + public LoginException(string message, string xmlRpcMessage, Exception e) + : base(message, e) + { + // FIXME: Might be neater to refactor and put the method inside here + m_xmlRpcErrorResponse = GridXmlRpcModule.ErrorResponse(xmlRpcMessage); + } + } +} diff --git a/OpenSim/Grid/MessagingServer.Modules/MessageRegionModule.cs b/OpenSim/Grid/MessagingServer.Modules/MessageRegionModule.cs index f77ef4b..7b3edfb 100644 --- a/OpenSim/Grid/MessagingServer.Modules/MessageRegionModule.cs +++ b/OpenSim/Grid/MessagingServer.Modules/MessageRegionModule.cs @@ -1,213 +1,213 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Net; -using System.Reflection; -using System.Threading; -using System.Timers; -using log4net; -using Nwc.XmlRpc; -using OpenMetaverse; -using OpenSim.Data; -using OpenSim.Framework; -using OpenSim.Grid.Framework; -using Timer = System.Timers.Timer; - -namespace OpenSim.Grid.MessagingServer.Modules -{ - public class MessageRegionModule : IMessageRegionService - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private MessageServerConfig m_cfg; - - private IMessageUserServerService m_userServerModule; - - private IUGAIMCore m_messageCore; - - // a dictionary of all current regions this server knows about - private Dictionary m_regionInfoCache = new Dictionary(); - - public MessageRegionModule(MessageServerConfig config, IUGAIMCore messageCore) - { - m_cfg = config; - m_messageCore = messageCore; - } - - public void Initialise() - { - m_messageCore.RegisterInterface(this); - } - - public void PostInitialise() - { - IMessageUserServerService messageUserServer; - if (m_messageCore.TryGet(out messageUserServer)) - { - m_userServerModule = messageUserServer; - } - } - - public void RegisterHandlers() - { - //have these in separate method as some servers restart the http server and reregister all the handlers. - - } - - /// - /// Gets and caches a RegionInfo object from the gridserver based on regionhandle - /// if the regionhandle is already cached, use the cached values - /// Gets called by lots of threads!!!!! - /// - /// handle to the XY of the region we're looking for - /// A RegionInfo object to stick in the presence info - public RegionProfileData GetRegionInfo(ulong regionhandle) - { - RegionProfileData regionInfo = null; - - lock (m_regionInfoCache) - { - m_regionInfoCache.TryGetValue(regionhandle, out regionInfo); - } - - if (regionInfo == null) // not found in cache - { - regionInfo = RequestRegionInfo(regionhandle); - - if (regionInfo != null) // lookup was successful - { - lock (m_regionInfoCache) - { - m_regionInfoCache[regionhandle] = regionInfo; - } - } - } - - return regionInfo; - } - - public int ClearRegionCache() - { - int cachecount = 0; - - lock (m_regionInfoCache) - { - cachecount = m_regionInfoCache.Count; - m_regionInfoCache.Clear(); - } - - return cachecount; - } - - /// - /// Get RegionProfileData from the GridServer. - /// We'll cache this information in GetRegionInfo and use it for presence updates - /// - /// - /// - public RegionProfileData RequestRegionInfo(ulong regionHandle) - { - RegionProfileData regionProfile = null; - try - { - Hashtable requestData = new Hashtable(); - requestData["region_handle"] = regionHandle.ToString(); - requestData["authkey"] = m_cfg.GridSendKey; - - ArrayList SendParams = new ArrayList(); - SendParams.Add(requestData); - - XmlRpcRequest GridReq = new XmlRpcRequest("simulator_data_request", SendParams); - - XmlRpcResponse GridResp = GridReq.Send(m_cfg.GridServerURL, 3000); - - Hashtable responseData = (Hashtable)GridResp.Value; - - if (responseData.ContainsKey("error")) - { - m_log.Error("[GRID]: error received from grid server" + responseData["error"]); - return null; - } - - uint regX = Convert.ToUInt32((string)responseData["region_locx"]); - uint regY = Convert.ToUInt32((string)responseData["region_locy"]); - string internalIpStr = (string)responseData["sim_ip"]; - - regionProfile = new RegionProfileData(); - regionProfile.httpPort = (uint)Convert.ToInt32((string)responseData["http_port"]); - regionProfile.httpServerURI = "http://" + internalIpStr + ":" + regionProfile.httpPort + "/"; - regionProfile.regionHandle = Utils.UIntsToLong((regX * Constants.RegionSize), (regY * Constants.RegionSize)); - regionProfile.regionLocX = regX; - regionProfile.regionLocY = regY; - - regionProfile.remotingPort = Convert.ToUInt32((string)responseData["remoting_port"]); - regionProfile.UUID = new UUID((string)responseData["region_UUID"]); - regionProfile.regionName = (string)responseData["region_name"]; - } - catch (WebException) - { - m_log.Error("[GRID]: " + - "Region lookup failed for: " + regionHandle.ToString() + - " - Is the GridServer down?"); - } - - return regionProfile; - } - - public XmlRpcResponse RegionStartup(XmlRpcRequest request) - { - Hashtable requestData = (Hashtable)request.Params[0]; - Hashtable result = new Hashtable(); - result["success"] = "FALSE"; - - if (m_userServerModule.SendToUserServer(requestData, "region_startup")) - result["success"] = "TRUE"; - - XmlRpcResponse response = new XmlRpcResponse(); - response.Value = result; - return response; - } - - public XmlRpcResponse RegionShutdown(XmlRpcRequest request) - { - Hashtable requestData = (Hashtable)request.Params[0]; - Hashtable result = new Hashtable(); - result["success"] = "FALSE"; - - if (m_userServerModule.SendToUserServer(requestData, "region_shutdown")) - result["success"] = "TRUE"; - - XmlRpcResponse response = new XmlRpcResponse(); - response.Value = result; - return response; - } - - } -} +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Net; +using System.Reflection; +using System.Threading; +using System.Timers; +using log4net; +using Nwc.XmlRpc; +using OpenMetaverse; +using OpenSim.Data; +using OpenSim.Framework; +using OpenSim.Grid.Framework; +using Timer = System.Timers.Timer; + +namespace OpenSim.Grid.MessagingServer.Modules +{ + public class MessageRegionModule : IMessageRegionService + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private MessageServerConfig m_cfg; + + private IMessageUserServerService m_userServerModule; + + private IUGAIMCore m_messageCore; + + // a dictionary of all current regions this server knows about + private Dictionary m_regionInfoCache = new Dictionary(); + + public MessageRegionModule(MessageServerConfig config, IUGAIMCore messageCore) + { + m_cfg = config; + m_messageCore = messageCore; + } + + public void Initialise() + { + m_messageCore.RegisterInterface(this); + } + + public void PostInitialise() + { + IMessageUserServerService messageUserServer; + if (m_messageCore.TryGet(out messageUserServer)) + { + m_userServerModule = messageUserServer; + } + } + + public void RegisterHandlers() + { + //have these in separate method as some servers restart the http server and reregister all the handlers. + + } + + /// + /// Gets and caches a RegionInfo object from the gridserver based on regionhandle + /// if the regionhandle is already cached, use the cached values + /// Gets called by lots of threads!!!!! + /// + /// handle to the XY of the region we're looking for + /// A RegionInfo object to stick in the presence info + public RegionProfileData GetRegionInfo(ulong regionhandle) + { + RegionProfileData regionInfo = null; + + lock (m_regionInfoCache) + { + m_regionInfoCache.TryGetValue(regionhandle, out regionInfo); + } + + if (regionInfo == null) // not found in cache + { + regionInfo = RequestRegionInfo(regionhandle); + + if (regionInfo != null) // lookup was successful + { + lock (m_regionInfoCache) + { + m_regionInfoCache[regionhandle] = regionInfo; + } + } + } + + return regionInfo; + } + + public int ClearRegionCache() + { + int cachecount = 0; + + lock (m_regionInfoCache) + { + cachecount = m_regionInfoCache.Count; + m_regionInfoCache.Clear(); + } + + return cachecount; + } + + /// + /// Get RegionProfileData from the GridServer. + /// We'll cache this information in GetRegionInfo and use it for presence updates + /// + /// + /// + public RegionProfileData RequestRegionInfo(ulong regionHandle) + { + RegionProfileData regionProfile = null; + try + { + Hashtable requestData = new Hashtable(); + requestData["region_handle"] = regionHandle.ToString(); + requestData["authkey"] = m_cfg.GridSendKey; + + ArrayList SendParams = new ArrayList(); + SendParams.Add(requestData); + + XmlRpcRequest GridReq = new XmlRpcRequest("simulator_data_request", SendParams); + + XmlRpcResponse GridResp = GridReq.Send(m_cfg.GridServerURL, 3000); + + Hashtable responseData = (Hashtable)GridResp.Value; + + if (responseData.ContainsKey("error")) + { + m_log.Error("[GRID]: error received from grid server" + responseData["error"]); + return null; + } + + uint regX = Convert.ToUInt32((string)responseData["region_locx"]); + uint regY = Convert.ToUInt32((string)responseData["region_locy"]); + string internalIpStr = (string)responseData["sim_ip"]; + + regionProfile = new RegionProfileData(); + regionProfile.httpPort = (uint)Convert.ToInt32((string)responseData["http_port"]); + regionProfile.httpServerURI = "http://" + internalIpStr + ":" + regionProfile.httpPort + "/"; + regionProfile.regionHandle = Utils.UIntsToLong((regX * Constants.RegionSize), (regY * Constants.RegionSize)); + regionProfile.regionLocX = regX; + regionProfile.regionLocY = regY; + + regionProfile.remotingPort = Convert.ToUInt32((string)responseData["remoting_port"]); + regionProfile.UUID = new UUID((string)responseData["region_UUID"]); + regionProfile.regionName = (string)responseData["region_name"]; + } + catch (WebException) + { + m_log.Error("[GRID]: " + + "Region lookup failed for: " + regionHandle.ToString() + + " - Is the GridServer down?"); + } + + return regionProfile; + } + + public XmlRpcResponse RegionStartup(XmlRpcRequest request) + { + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable result = new Hashtable(); + result["success"] = "FALSE"; + + if (m_userServerModule.SendToUserServer(requestData, "region_startup")) + result["success"] = "TRUE"; + + XmlRpcResponse response = new XmlRpcResponse(); + response.Value = result; + return response; + } + + public XmlRpcResponse RegionShutdown(XmlRpcRequest request) + { + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable result = new Hashtable(); + result["success"] = "FALSE"; + + if (m_userServerModule.SendToUserServer(requestData, "region_shutdown")) + result["success"] = "TRUE"; + + XmlRpcResponse response = new XmlRpcResponse(); + response.Value = result; + return response; + } + + } +} diff --git a/OpenSim/Grid/MessagingServer.Modules/MessageService.cs b/OpenSim/Grid/MessagingServer.Modules/MessageService.cs index 15cfa3b..c76f332 100644 --- a/OpenSim/Grid/MessagingServer.Modules/MessageService.cs +++ b/OpenSim/Grid/MessagingServer.Modules/MessageService.cs @@ -1,488 +1,488 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Net; -using System.Reflection; -using System.Threading; -using System.Timers; -using log4net; -using Nwc.XmlRpc; -using OpenMetaverse; -using OpenSim.Data; -using OpenSim.Framework; -using OpenSim.Grid.Framework; -using Timer=System.Timers.Timer; - -namespace OpenSim.Grid.MessagingServer.Modules -{ - public class MessageService - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private MessageServerConfig m_cfg; - private UserDataBaseService m_userDataBaseService; - - private IUGAIMCore m_messageCore; - - private IMessageUserServerService m_userServerModule; - private IMessageRegionService m_regionModule; - - // a dictionary of all current presences this server knows about - private Dictionary m_presences = new Dictionary(); - - public MessageService(MessageServerConfig cfg, IUGAIMCore messageCore, UserDataBaseService userDataBaseService) - { - m_cfg = cfg; - m_messageCore = messageCore; - - m_userDataBaseService = userDataBaseService; - - //??? - UserConfig uc = new UserConfig(); - uc.DatabaseConnect = cfg.DatabaseConnect; - uc.DatabaseProvider = cfg.DatabaseProvider; - } - - public void Initialise() - { - } - - public void PostInitialise() - { - IMessageUserServerService messageUserServer; - if (m_messageCore.TryGet(out messageUserServer)) - { - m_userServerModule = messageUserServer; - } - - IMessageRegionService messageRegion; - if (m_messageCore.TryGet(out messageRegion)) - { - m_regionModule = messageRegion; - } - } - - public void RegisterHandlers() - { - //have these in separate method as some servers restart the http server and reregister all the handlers. - - } - - #region FriendList Methods - - /// - /// Process Friendlist subscriptions for a user - /// The login method calls this for a User - /// - /// The Agent we're processing the friendlist subscriptions for - private void ProcessFriendListSubscriptions(UserPresenceData userpresence) - { - lock (m_presences) - { - m_presences[userpresence.agentData.AgentID] = userpresence; - } - - Dictionary uFriendList = userpresence.friendData; - foreach (KeyValuePair pair in uFriendList) - { - UserPresenceData friendup = null; - lock (m_presences) - { - m_presences.TryGetValue(pair.Key, out friendup); - } - if (friendup != null) - { - SubscribeToPresenceUpdates(userpresence, friendup, pair.Value); - } - } - } - - /// - /// Enqueues a presence update, sending info about user 'talkingAbout' to user 'receiver'. - /// - /// We are sending presence information about this user. - /// We are sending the presence update to this user - private void enqueuePresenceUpdate(UserPresenceData talkingAbout, UserPresenceData receiver) - { - UserAgentData p2Handle = m_userDataBaseService.GetUserAgentData(receiver.agentData.AgentID); - if (p2Handle != null) - { - if (receiver.lookupUserRegionYN) - { - receiver.regionData.regionHandle = p2Handle.Handle; - } - else - { - receiver.lookupUserRegionYN = true; // TODO Huh? - } - - PresenceInformer friendlistupdater = new PresenceInformer(); - friendlistupdater.presence1 = talkingAbout; - friendlistupdater.presence2 = receiver; - friendlistupdater.OnGetRegionData += m_regionModule.GetRegionInfo; - friendlistupdater.OnDone += PresenceUpdateDone; - WaitCallback cb = new WaitCallback(friendlistupdater.go); - ThreadPool.QueueUserWorkItem(cb); - } - else - { - m_log.WarnFormat("no data found for user {0}", receiver.agentData.AgentID); - // Skip because we can't find any data on the user - } - } - - /// - /// Does the necessary work to subscribe one agent to another's presence notifications - /// Gets called by ProcessFriendListSubscriptions. You shouldn't call this directly - /// unless you know what you're doing - /// - /// P1 - /// P2 - /// - private void SubscribeToPresenceUpdates(UserPresenceData userpresence, - UserPresenceData friendpresence, - FriendListItem uFriendListItem) - { - // Can the friend see me online? - if ((uFriendListItem.FriendListOwnerPerms & (uint)FriendRights.CanSeeOnline) != 0) - { - // tell user to update friend about user's presence changes - if (!userpresence.subscriptionData.Contains(friendpresence.agentData.AgentID)) - { - userpresence.subscriptionData.Add(friendpresence.agentData.AgentID); - } - - // send an update about user's presence to the friend - enqueuePresenceUpdate(userpresence, friendpresence); - } - - // Can I see the friend online? - if ((uFriendListItem.FriendPerms & (uint)FriendRights.CanSeeOnline) != 0) - { - // tell friend to update user about friend's presence changes - if (!friendpresence.subscriptionData.Contains(userpresence.agentData.AgentID)) - { - friendpresence.subscriptionData.Add(userpresence.agentData.AgentID); - } - - // send an update about friend's presence to user. - enqueuePresenceUpdate(friendpresence, userpresence); - } - } - - /// - /// Logoff Processor. Call this to clean up agent presence data and send logoff presence notifications - /// - /// - private void ProcessLogOff(UUID AgentID) - { - m_log.Info("[LOGOFF]: Processing Logoff"); - - UserPresenceData userPresence = null; - lock (m_presences) - { - m_presences.TryGetValue(AgentID, out userPresence); - } - - if (userPresence != null) // found the user - { - List AgentsNeedingNotification = userPresence.subscriptionData; - userPresence.OnlineYN = false; - - for (int i = 0; i < AgentsNeedingNotification.Count; i++) - { - UserPresenceData friendPresence = null; - lock (m_presences) - { - m_presences.TryGetValue(AgentsNeedingNotification[i], out friendPresence); - } - - // This might need to be enumerated and checked before we try to remove it. - if (friendPresence != null) - { - lock (friendPresence) - { - // no updates for this user anymore - friendPresence.subscriptionData.Remove(AgentID); - - // set user's entry in the friend's list to offline (if it exists) - if (friendPresence.friendData.ContainsKey(AgentID)) - { - friendPresence.friendData[AgentID].onlinestatus = false; - } - } - - enqueuePresenceUpdate(userPresence, friendPresence); - } - } - } - } - - #endregion - - private void PresenceUpdateDone(PresenceInformer obj) - { - obj.OnGetRegionData -= m_regionModule.GetRegionInfo; - obj.OnDone -= PresenceUpdateDone; - } - - #region UserServer Comms - - /// - /// Returns a list of FriendsListItems that describe the friends and permissions in the friend - /// relationship for UUID friendslistowner. For faster lookup, we index by friend's UUID. - /// - /// The agent that we're retreiving the friends Data for. - private Dictionary GetUserFriendList(UUID friendlistowner) - { - Dictionary buddies = new Dictionary(); - - try - { - Hashtable param = new Hashtable(); - param["ownerID"] = friendlistowner.ToString(); - - IList parameters = new ArrayList(); - parameters.Add(param); - XmlRpcRequest req = new XmlRpcRequest("get_user_friend_list", parameters); - XmlRpcResponse resp = req.Send(m_cfg.UserServerURL, 3000); - Hashtable respData = (Hashtable)resp.Value; - - if (respData.Contains("avcount")) - { - buddies = ConvertXMLRPCDataToFriendListItemList(respData); - } - - } - catch (WebException e) - { - m_log.Warn("Error when trying to fetch Avatar's friends list: " + - e.Message); - // Return Empty list (no friends) - } - return buddies; - } - - /// - /// Converts XMLRPC Friend List to FriendListItem Object - /// - /// XMLRPC response data Hashtable - /// - public Dictionary ConvertXMLRPCDataToFriendListItemList(Hashtable data) - { - Dictionary buddies = new Dictionary(); - int buddycount = Convert.ToInt32((string)data["avcount"]); - - for (int i = 0; i < buddycount; i++) - { - FriendListItem buddylistitem = new FriendListItem(); - - buddylistitem.FriendListOwner = new UUID((string)data["ownerID" + i.ToString()]); - buddylistitem.Friend = new UUID((string)data["friendID" + i.ToString()]); - buddylistitem.FriendListOwnerPerms = (uint)Convert.ToInt32((string)data["ownerPerms" + i.ToString()]); - buddylistitem.FriendPerms = (uint)Convert.ToInt32((string)data["friendPerms" + i.ToString()]); - - buddies.Add(buddylistitem.Friend, buddylistitem); - } - - return buddies; - } - - /// - /// UserServer sends an expect_user method - /// this handles the method and provisions the - /// necessary info for presence to work - /// - /// UserServer Data - /// - public XmlRpcResponse UserLoggedOn(XmlRpcRequest request) - { - Hashtable requestData = (Hashtable)request.Params[0]; - - AgentCircuitData agentData = new AgentCircuitData(); - agentData.SessionID = new UUID((string)requestData["sessionid"]); - agentData.SecureSessionID = new UUID((string)requestData["secure_session_id"]); - agentData.firstname = (string)requestData["firstname"]; - agentData.lastname = (string)requestData["lastname"]; - agentData.AgentID = new UUID((string)requestData["agentid"]); - agentData.circuitcode = Convert.ToUInt32(requestData["circuit_code"]); - agentData.CapsPath = (string)requestData["caps_path"]; - - if (requestData.ContainsKey("child_agent") && requestData["child_agent"].Equals("1")) - { - agentData.child = true; - } - else - { - agentData.startpos = - new Vector3(Convert.ToSingle(requestData["positionx"]), - Convert.ToSingle(requestData["positiony"]), - Convert.ToSingle(requestData["positionz"])); - agentData.child = false; - } - - ulong regionHandle = Convert.ToUInt64((string)requestData["regionhandle"]); - - m_log.InfoFormat("[LOGON]: User {0} {1} logged into region {2} as {3} agent, building indexes for user", - agentData.firstname, agentData.lastname, regionHandle, agentData.child ? "child" : "root"); - - UserPresenceData up = new UserPresenceData(); - up.agentData = agentData; - up.friendData = GetUserFriendList(agentData.AgentID); - up.regionData = m_regionModule.GetRegionInfo(regionHandle); - up.OnlineYN = true; - up.lookupUserRegionYN = false; - ProcessFriendListSubscriptions(up); - - return new XmlRpcResponse(); - } - - /// - /// The UserServer got a Logoff message - /// Cleanup time for that user. Send out presence notifications - /// - /// - /// - public XmlRpcResponse UserLoggedOff(XmlRpcRequest request) - { - m_log.Info("[USERLOGOFF]: User logged off called"); - Hashtable requestData = (Hashtable)request.Params[0]; - - UUID AgentID = new UUID((string)requestData["agentid"]); - ProcessLogOff(AgentID); - - return new XmlRpcResponse(); - } - - #endregion - - public XmlRpcResponse GetPresenceInfoBulk(XmlRpcRequest request) - { - Hashtable paramHash = (Hashtable)request.Params[0]; - Hashtable result = new Hashtable(); - - // TODO check access (recv_key/send_key) - - IList list = (IList)paramHash["uuids"]; - - // convert into List - List uuids = new List(); - for (int i = 0; i < list.Count; ++i) - { - UUID uuid; - if (UUID.TryParse((string)list[i], out uuid)) - { - uuids.Add(uuid); - } - } - - try { - Dictionary infos = m_userDataBaseService.GetFriendRegionInfos(uuids); - m_log.DebugFormat("[FRIEND]: Got {0} region entries back.", infos.Count); - int count = 0; - foreach (KeyValuePair pair in infos) - { - result["uuid_" + count] = pair.Key.ToString(); - result["isOnline_" + count] = pair.Value.isOnline; - result["regionHandle_" + count] = pair.Value.regionHandle.ToString(); // XML-RPC doesn't know ulongs - ++count; - } - result["count"] = count; - - XmlRpcResponse response = new XmlRpcResponse(); - response.Value = result; - return response; - } - catch(Exception e) { - m_log.Error("Got exception:", e); - throw e; - } - } - - public XmlRpcResponse AgentLocation(XmlRpcRequest request) - { - Hashtable requestData = (Hashtable)request.Params[0]; - Hashtable result = new Hashtable(); - result["success"] = "FALSE"; - - if (m_userServerModule.SendToUserServer(requestData, "agent_location")) - result["success"] = "TRUE"; - - - XmlRpcResponse response = new XmlRpcResponse(); - response.Value = result; - return response; - } - - public XmlRpcResponse AgentLeaving(XmlRpcRequest request) - { - Hashtable requestData = (Hashtable)request.Params[0]; - Hashtable result = new Hashtable(); - result["success"] = "FALSE"; - - if (m_userServerModule.SendToUserServer(requestData, "agent_leaving")) - result["success"] = "TRUE"; - - XmlRpcResponse response = new XmlRpcResponse(); - response.Value = result; - return response; - } - - public XmlRpcResponse ProcessRegionShutdown(XmlRpcRequest request) - { - Hashtable requestData = (Hashtable)request.Params[0]; - Hashtable result = new Hashtable(); - result["success"] = "FALSE"; - - UUID regionID; - if (UUID.TryParse((string)requestData["regionid"], out regionID)) - { - m_log.DebugFormat("[PRESENCE] Processing region restart for {0}", regionID); - result["success"] = "TRUE"; - - foreach (UserPresenceData up in m_presences.Values) - { - if (up.regionData.UUID == regionID) - { - if (up.OnlineYN) - { - m_log.DebugFormat("[PRESENCE] Logging off {0} because the region they were in has gone", up.agentData.AgentID); - ProcessLogOff(up.agentData.AgentID); - } - } - } - } - - XmlRpcResponse response = new XmlRpcResponse(); - response.Value = result; - return response; - } - } +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Net; +using System.Reflection; +using System.Threading; +using System.Timers; +using log4net; +using Nwc.XmlRpc; +using OpenMetaverse; +using OpenSim.Data; +using OpenSim.Framework; +using OpenSim.Grid.Framework; +using Timer=System.Timers.Timer; + +namespace OpenSim.Grid.MessagingServer.Modules +{ + public class MessageService + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private MessageServerConfig m_cfg; + private UserDataBaseService m_userDataBaseService; + + private IUGAIMCore m_messageCore; + + private IMessageUserServerService m_userServerModule; + private IMessageRegionService m_regionModule; + + // a dictionary of all current presences this server knows about + private Dictionary m_presences = new Dictionary(); + + public MessageService(MessageServerConfig cfg, IUGAIMCore messageCore, UserDataBaseService userDataBaseService) + { + m_cfg = cfg; + m_messageCore = messageCore; + + m_userDataBaseService = userDataBaseService; + + //??? + UserConfig uc = new UserConfig(); + uc.DatabaseConnect = cfg.DatabaseConnect; + uc.DatabaseProvider = cfg.DatabaseProvider; + } + + public void Initialise() + { + } + + public void PostInitialise() + { + IMessageUserServerService messageUserServer; + if (m_messageCore.TryGet(out messageUserServer)) + { + m_userServerModule = messageUserServer; + } + + IMessageRegionService messageRegion; + if (m_messageCore.TryGet(out messageRegion)) + { + m_regionModule = messageRegion; + } + } + + public void RegisterHandlers() + { + //have these in separate method as some servers restart the http server and reregister all the handlers. + + } + + #region FriendList Methods + + /// + /// Process Friendlist subscriptions for a user + /// The login method calls this for a User + /// + /// The Agent we're processing the friendlist subscriptions for + private void ProcessFriendListSubscriptions(UserPresenceData userpresence) + { + lock (m_presences) + { + m_presences[userpresence.agentData.AgentID] = userpresence; + } + + Dictionary uFriendList = userpresence.friendData; + foreach (KeyValuePair pair in uFriendList) + { + UserPresenceData friendup = null; + lock (m_presences) + { + m_presences.TryGetValue(pair.Key, out friendup); + } + if (friendup != null) + { + SubscribeToPresenceUpdates(userpresence, friendup, pair.Value); + } + } + } + + /// + /// Enqueues a presence update, sending info about user 'talkingAbout' to user 'receiver'. + /// + /// We are sending presence information about this user. + /// We are sending the presence update to this user + private void enqueuePresenceUpdate(UserPresenceData talkingAbout, UserPresenceData receiver) + { + UserAgentData p2Handle = m_userDataBaseService.GetUserAgentData(receiver.agentData.AgentID); + if (p2Handle != null) + { + if (receiver.lookupUserRegionYN) + { + receiver.regionData.regionHandle = p2Handle.Handle; + } + else + { + receiver.lookupUserRegionYN = true; // TODO Huh? + } + + PresenceInformer friendlistupdater = new PresenceInformer(); + friendlistupdater.presence1 = talkingAbout; + friendlistupdater.presence2 = receiver; + friendlistupdater.OnGetRegionData += m_regionModule.GetRegionInfo; + friendlistupdater.OnDone += PresenceUpdateDone; + WaitCallback cb = new WaitCallback(friendlistupdater.go); + ThreadPool.QueueUserWorkItem(cb); + } + else + { + m_log.WarnFormat("no data found for user {0}", receiver.agentData.AgentID); + // Skip because we can't find any data on the user + } + } + + /// + /// Does the necessary work to subscribe one agent to another's presence notifications + /// Gets called by ProcessFriendListSubscriptions. You shouldn't call this directly + /// unless you know what you're doing + /// + /// P1 + /// P2 + /// + private void SubscribeToPresenceUpdates(UserPresenceData userpresence, + UserPresenceData friendpresence, + FriendListItem uFriendListItem) + { + // Can the friend see me online? + if ((uFriendListItem.FriendListOwnerPerms & (uint)FriendRights.CanSeeOnline) != 0) + { + // tell user to update friend about user's presence changes + if (!userpresence.subscriptionData.Contains(friendpresence.agentData.AgentID)) + { + userpresence.subscriptionData.Add(friendpresence.agentData.AgentID); + } + + // send an update about user's presence to the friend + enqueuePresenceUpdate(userpresence, friendpresence); + } + + // Can I see the friend online? + if ((uFriendListItem.FriendPerms & (uint)FriendRights.CanSeeOnline) != 0) + { + // tell friend to update user about friend's presence changes + if (!friendpresence.subscriptionData.Contains(userpresence.agentData.AgentID)) + { + friendpresence.subscriptionData.Add(userpresence.agentData.AgentID); + } + + // send an update about friend's presence to user. + enqueuePresenceUpdate(friendpresence, userpresence); + } + } + + /// + /// Logoff Processor. Call this to clean up agent presence data and send logoff presence notifications + /// + /// + private void ProcessLogOff(UUID AgentID) + { + m_log.Info("[LOGOFF]: Processing Logoff"); + + UserPresenceData userPresence = null; + lock (m_presences) + { + m_presences.TryGetValue(AgentID, out userPresence); + } + + if (userPresence != null) // found the user + { + List AgentsNeedingNotification = userPresence.subscriptionData; + userPresence.OnlineYN = false; + + for (int i = 0; i < AgentsNeedingNotification.Count; i++) + { + UserPresenceData friendPresence = null; + lock (m_presences) + { + m_presences.TryGetValue(AgentsNeedingNotification[i], out friendPresence); + } + + // This might need to be enumerated and checked before we try to remove it. + if (friendPresence != null) + { + lock (friendPresence) + { + // no updates for this user anymore + friendPresence.subscriptionData.Remove(AgentID); + + // set user's entry in the friend's list to offline (if it exists) + if (friendPresence.friendData.ContainsKey(AgentID)) + { + friendPresence.friendData[AgentID].onlinestatus = false; + } + } + + enqueuePresenceUpdate(userPresence, friendPresence); + } + } + } + } + + #endregion + + private void PresenceUpdateDone(PresenceInformer obj) + { + obj.OnGetRegionData -= m_regionModule.GetRegionInfo; + obj.OnDone -= PresenceUpdateDone; + } + + #region UserServer Comms + + /// + /// Returns a list of FriendsListItems that describe the friends and permissions in the friend + /// relationship for UUID friendslistowner. For faster lookup, we index by friend's UUID. + /// + /// The agent that we're retreiving the friends Data for. + private Dictionary GetUserFriendList(UUID friendlistowner) + { + Dictionary buddies = new Dictionary(); + + try + { + Hashtable param = new Hashtable(); + param["ownerID"] = friendlistowner.ToString(); + + IList parameters = new ArrayList(); + parameters.Add(param); + XmlRpcRequest req = new XmlRpcRequest("get_user_friend_list", parameters); + XmlRpcResponse resp = req.Send(m_cfg.UserServerURL, 3000); + Hashtable respData = (Hashtable)resp.Value; + + if (respData.Contains("avcount")) + { + buddies = ConvertXMLRPCDataToFriendListItemList(respData); + } + + } + catch (WebException e) + { + m_log.Warn("Error when trying to fetch Avatar's friends list: " + + e.Message); + // Return Empty list (no friends) + } + return buddies; + } + + /// + /// Converts XMLRPC Friend List to FriendListItem Object + /// + /// XMLRPC response data Hashtable + /// + public Dictionary ConvertXMLRPCDataToFriendListItemList(Hashtable data) + { + Dictionary buddies = new Dictionary(); + int buddycount = Convert.ToInt32((string)data["avcount"]); + + for (int i = 0; i < buddycount; i++) + { + FriendListItem buddylistitem = new FriendListItem(); + + buddylistitem.FriendListOwner = new UUID((string)data["ownerID" + i.ToString()]); + buddylistitem.Friend = new UUID((string)data["friendID" + i.ToString()]); + buddylistitem.FriendListOwnerPerms = (uint)Convert.ToInt32((string)data["ownerPerms" + i.ToString()]); + buddylistitem.FriendPerms = (uint)Convert.ToInt32((string)data["friendPerms" + i.ToString()]); + + buddies.Add(buddylistitem.Friend, buddylistitem); + } + + return buddies; + } + + /// + /// UserServer sends an expect_user method + /// this handles the method and provisions the + /// necessary info for presence to work + /// + /// UserServer Data + /// + public XmlRpcResponse UserLoggedOn(XmlRpcRequest request) + { + Hashtable requestData = (Hashtable)request.Params[0]; + + AgentCircuitData agentData = new AgentCircuitData(); + agentData.SessionID = new UUID((string)requestData["sessionid"]); + agentData.SecureSessionID = new UUID((string)requestData["secure_session_id"]); + agentData.firstname = (string)requestData["firstname"]; + agentData.lastname = (string)requestData["lastname"]; + agentData.AgentID = new UUID((string)requestData["agentid"]); + agentData.circuitcode = Convert.ToUInt32(requestData["circuit_code"]); + agentData.CapsPath = (string)requestData["caps_path"]; + + if (requestData.ContainsKey("child_agent") && requestData["child_agent"].Equals("1")) + { + agentData.child = true; + } + else + { + agentData.startpos = + new Vector3(Convert.ToSingle(requestData["positionx"]), + Convert.ToSingle(requestData["positiony"]), + Convert.ToSingle(requestData["positionz"])); + agentData.child = false; + } + + ulong regionHandle = Convert.ToUInt64((string)requestData["regionhandle"]); + + m_log.InfoFormat("[LOGON]: User {0} {1} logged into region {2} as {3} agent, building indexes for user", + agentData.firstname, agentData.lastname, regionHandle, agentData.child ? "child" : "root"); + + UserPresenceData up = new UserPresenceData(); + up.agentData = agentData; + up.friendData = GetUserFriendList(agentData.AgentID); + up.regionData = m_regionModule.GetRegionInfo(regionHandle); + up.OnlineYN = true; + up.lookupUserRegionYN = false; + ProcessFriendListSubscriptions(up); + + return new XmlRpcResponse(); + } + + /// + /// The UserServer got a Logoff message + /// Cleanup time for that user. Send out presence notifications + /// + /// + /// + public XmlRpcResponse UserLoggedOff(XmlRpcRequest request) + { + m_log.Info("[USERLOGOFF]: User logged off called"); + Hashtable requestData = (Hashtable)request.Params[0]; + + UUID AgentID = new UUID((string)requestData["agentid"]); + ProcessLogOff(AgentID); + + return new XmlRpcResponse(); + } + + #endregion + + public XmlRpcResponse GetPresenceInfoBulk(XmlRpcRequest request) + { + Hashtable paramHash = (Hashtable)request.Params[0]; + Hashtable result = new Hashtable(); + + // TODO check access (recv_key/send_key) + + IList list = (IList)paramHash["uuids"]; + + // convert into List + List uuids = new List(); + for (int i = 0; i < list.Count; ++i) + { + UUID uuid; + if (UUID.TryParse((string)list[i], out uuid)) + { + uuids.Add(uuid); + } + } + + try { + Dictionary infos = m_userDataBaseService.GetFriendRegionInfos(uuids); + m_log.DebugFormat("[FRIEND]: Got {0} region entries back.", infos.Count); + int count = 0; + foreach (KeyValuePair pair in infos) + { + result["uuid_" + count] = pair.Key.ToString(); + result["isOnline_" + count] = pair.Value.isOnline; + result["regionHandle_" + count] = pair.Value.regionHandle.ToString(); // XML-RPC doesn't know ulongs + ++count; + } + result["count"] = count; + + XmlRpcResponse response = new XmlRpcResponse(); + response.Value = result; + return response; + } + catch(Exception e) { + m_log.Error("Got exception:", e); + throw e; + } + } + + public XmlRpcResponse AgentLocation(XmlRpcRequest request) + { + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable result = new Hashtable(); + result["success"] = "FALSE"; + + if (m_userServerModule.SendToUserServer(requestData, "agent_location")) + result["success"] = "TRUE"; + + + XmlRpcResponse response = new XmlRpcResponse(); + response.Value = result; + return response; + } + + public XmlRpcResponse AgentLeaving(XmlRpcRequest request) + { + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable result = new Hashtable(); + result["success"] = "FALSE"; + + if (m_userServerModule.SendToUserServer(requestData, "agent_leaving")) + result["success"] = "TRUE"; + + XmlRpcResponse response = new XmlRpcResponse(); + response.Value = result; + return response; + } + + public XmlRpcResponse ProcessRegionShutdown(XmlRpcRequest request) + { + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable result = new Hashtable(); + result["success"] = "FALSE"; + + UUID regionID; + if (UUID.TryParse((string)requestData["regionid"], out regionID)) + { + m_log.DebugFormat("[PRESENCE] Processing region restart for {0}", regionID); + result["success"] = "TRUE"; + + foreach (UserPresenceData up in m_presences.Values) + { + if (up.regionData.UUID == regionID) + { + if (up.OnlineYN) + { + m_log.DebugFormat("[PRESENCE] Logging off {0} because the region they were in has gone", up.agentData.AgentID); + ProcessLogOff(up.agentData.AgentID); + } + } + } + } + + XmlRpcResponse response = new XmlRpcResponse(); + response.Value = result; + return response; + } + } } \ No newline at end of file diff --git a/OpenSim/Grid/MessagingServer.Modules/MessageUserServerModule.cs b/OpenSim/Grid/MessagingServer.Modules/MessageUserServerModule.cs index 9293b3e..e153c39 100644 --- a/OpenSim/Grid/MessagingServer.Modules/MessageUserServerModule.cs +++ b/OpenSim/Grid/MessagingServer.Modules/MessageUserServerModule.cs @@ -1,186 +1,186 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Net; -using System.Reflection; -using System.Threading; -using System.Timers; -using log4net; -using Nwc.XmlRpc; -using OpenMetaverse; -using OpenSim.Data; -using OpenSim.Framework; -using OpenSim.Grid.Framework; -using Timer = System.Timers.Timer; - -namespace OpenSim.Grid.MessagingServer.Modules -{ - public class MessageUserServerModule : IMessageUserServerService - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private MessageServerConfig m_cfg; - - private IUGAIMCore m_messageCore; - - private Timer reconnectTimer = new Timer(300000); // 5 mins - - public MessageUserServerModule(MessageServerConfig config, IUGAIMCore messageCore) - { - m_cfg = config; - m_messageCore = messageCore; - - reconnectTimer.Elapsed += registerWithUserServer; - reconnectTimer.Start(); - } - - public void Initialise() - { - m_messageCore.RegisterInterface(this); - } - - public void PostInitialise() - { - - } - - public void RegisterHandlers() - { - //have these in separate method as some servers restart the http server and reregister all the handlers. - - } - - public void registerWithUserServer(object sender, ElapsedEventArgs e) - { - registerWithUserServer(); - } - - public bool registerWithUserServer() - { - Hashtable UserParams = new Hashtable(); - // Login / Authentication - - if (m_cfg.HttpSSL) - { - UserParams["uri"] = "https://" + m_cfg.MessageServerIP + ":" + m_cfg.HttpPort; - } - else - { - UserParams["uri"] = "http://" + m_cfg.MessageServerIP + ":" + m_cfg.HttpPort; - } - - UserParams["recvkey"] = m_cfg.UserRecvKey; - UserParams["sendkey"] = m_cfg.UserRecvKey; - - // Package into an XMLRPC Request - ArrayList SendParams = new ArrayList(); - SendParams.Add(UserParams); - - bool success = true; - string[] servers = m_cfg.UserServerURL.Split(' '); - - foreach (string srv in servers) - { - // Send Request - try - { - XmlRpcRequest UserReq = new XmlRpcRequest("register_messageserver", SendParams); - XmlRpcResponse UserResp = UserReq.Send(srv, 16000); - - // Process Response - Hashtable GridRespData = (Hashtable)UserResp.Value; - // if we got a response, we were successful - if (!GridRespData.ContainsKey("responsestring")) - success = false; - else - m_log.InfoFormat("[SERVER] Registered with {0}", srv); - } - catch - { - m_log.ErrorFormat("Unable to connect to server {0}. Server not running?", srv); - success = false; - } - } - return success; - } - - public bool deregisterWithUserServer() - { - Hashtable request = new Hashtable(); - - return SendToUserServer(request, "deregister_messageserver"); - } - - public bool SendToUserServer(Hashtable request, string method) - { - // Login / Authentication - - if (m_cfg.HttpSSL) - { - request["uri"] = "https://" + m_cfg.MessageServerIP + ":" + m_cfg.HttpPort; - } - else - { - request["uri"] = "http://" + m_cfg.MessageServerIP + ":" + m_cfg.HttpPort; - } - - request["recvkey"] = m_cfg.UserRecvKey; - request["sendkey"] = m_cfg.UserRecvKey; - - // Package into an XMLRPC Request - ArrayList SendParams = new ArrayList(); - SendParams.Add(request); - - bool success = true; - string[] servers = m_cfg.UserServerURL.Split(' '); - - // Send Request - foreach (string srv in servers) - { - try - { - XmlRpcRequest UserReq = new XmlRpcRequest(method, SendParams); - XmlRpcResponse UserResp = UserReq.Send(m_cfg.UserServerURL, 16000); - // Process Response - Hashtable UserRespData = (Hashtable)UserResp.Value; - // if we got a response, we were successful - if (!UserRespData.ContainsKey("responsestring")) - success = false; - } - catch - { - m_log.ErrorFormat("Unable to connect to server {0}. Server not running?", srv); - success = false; - } - } - return success; - } - } -} +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Net; +using System.Reflection; +using System.Threading; +using System.Timers; +using log4net; +using Nwc.XmlRpc; +using OpenMetaverse; +using OpenSim.Data; +using OpenSim.Framework; +using OpenSim.Grid.Framework; +using Timer = System.Timers.Timer; + +namespace OpenSim.Grid.MessagingServer.Modules +{ + public class MessageUserServerModule : IMessageUserServerService + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private MessageServerConfig m_cfg; + + private IUGAIMCore m_messageCore; + + private Timer reconnectTimer = new Timer(300000); // 5 mins + + public MessageUserServerModule(MessageServerConfig config, IUGAIMCore messageCore) + { + m_cfg = config; + m_messageCore = messageCore; + + reconnectTimer.Elapsed += registerWithUserServer; + reconnectTimer.Start(); + } + + public void Initialise() + { + m_messageCore.RegisterInterface(this); + } + + public void PostInitialise() + { + + } + + public void RegisterHandlers() + { + //have these in separate method as some servers restart the http server and reregister all the handlers. + + } + + public void registerWithUserServer(object sender, ElapsedEventArgs e) + { + registerWithUserServer(); + } + + public bool registerWithUserServer() + { + Hashtable UserParams = new Hashtable(); + // Login / Authentication + + if (m_cfg.HttpSSL) + { + UserParams["uri"] = "https://" + m_cfg.MessageServerIP + ":" + m_cfg.HttpPort; + } + else + { + UserParams["uri"] = "http://" + m_cfg.MessageServerIP + ":" + m_cfg.HttpPort; + } + + UserParams["recvkey"] = m_cfg.UserRecvKey; + UserParams["sendkey"] = m_cfg.UserRecvKey; + + // Package into an XMLRPC Request + ArrayList SendParams = new ArrayList(); + SendParams.Add(UserParams); + + bool success = true; + string[] servers = m_cfg.UserServerURL.Split(' '); + + foreach (string srv in servers) + { + // Send Request + try + { + XmlRpcRequest UserReq = new XmlRpcRequest("register_messageserver", SendParams); + XmlRpcResponse UserResp = UserReq.Send(srv, 16000); + + // Process Response + Hashtable GridRespData = (Hashtable)UserResp.Value; + // if we got a response, we were successful + if (!GridRespData.ContainsKey("responsestring")) + success = false; + else + m_log.InfoFormat("[SERVER] Registered with {0}", srv); + } + catch + { + m_log.ErrorFormat("Unable to connect to server {0}. Server not running?", srv); + success = false; + } + } + return success; + } + + public bool deregisterWithUserServer() + { + Hashtable request = new Hashtable(); + + return SendToUserServer(request, "deregister_messageserver"); + } + + public bool SendToUserServer(Hashtable request, string method) + { + // Login / Authentication + + if (m_cfg.HttpSSL) + { + request["uri"] = "https://" + m_cfg.MessageServerIP + ":" + m_cfg.HttpPort; + } + else + { + request["uri"] = "http://" + m_cfg.MessageServerIP + ":" + m_cfg.HttpPort; + } + + request["recvkey"] = m_cfg.UserRecvKey; + request["sendkey"] = m_cfg.UserRecvKey; + + // Package into an XMLRPC Request + ArrayList SendParams = new ArrayList(); + SendParams.Add(request); + + bool success = true; + string[] servers = m_cfg.UserServerURL.Split(' '); + + // Send Request + foreach (string srv in servers) + { + try + { + XmlRpcRequest UserReq = new XmlRpcRequest(method, SendParams); + XmlRpcResponse UserResp = UserReq.Send(m_cfg.UserServerURL, 16000); + // Process Response + Hashtable UserRespData = (Hashtable)UserResp.Value; + // if we got a response, we were successful + if (!UserRespData.ContainsKey("responsestring")) + success = false; + } + catch + { + m_log.ErrorFormat("Unable to connect to server {0}. Server not running?", srv); + success = false; + } + } + return success; + } + } +} diff --git a/OpenSim/Grid/MessagingServer.Modules/PresenceBackreferenceEntry.cs b/OpenSim/Grid/MessagingServer.Modules/PresenceBackreferenceEntry.cs index b6023e3..ddb143f 100644 --- a/OpenSim/Grid/MessagingServer.Modules/PresenceBackreferenceEntry.cs +++ b/OpenSim/Grid/MessagingServer.Modules/PresenceBackreferenceEntry.cs @@ -1,96 +1,96 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System.Collections.Generic; -using OpenMetaverse; - -namespace OpenSim.Grid.MessagingServer.Modules -{ - // This is a wrapper for a List so it can be happily stored in a hashtable. - public class PresenceBackreferenceEntry - { - List AgentList = new List(); - - public PresenceBackreferenceEntry() - { - - } - - public void Add(UUID item) - { - lock (AgentList) - { - AgentList.Add(item); - } - } - - public UUID getitem(int index) - { - UUID result = UUID.Zero; - lock (AgentList) - { - if (index > 0 && index < AgentList.Count) - { - result = AgentList[index]; - } - } - return result; - } - - public int Count - { - get - { - int count = 0; - lock (AgentList) - { - count = AgentList.Count; - } - return count; - } - } - - public void Remove(UUID item) - { - lock (AgentList) - { - if (AgentList.Contains(item)) - AgentList.Remove(item); - } - } - - public bool contains(UUID item) - { - bool result = false; - lock (AgentList) - { - result = AgentList.Contains(item); - } - return result; - } - } -} +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System.Collections.Generic; +using OpenMetaverse; + +namespace OpenSim.Grid.MessagingServer.Modules +{ + // This is a wrapper for a List so it can be happily stored in a hashtable. + public class PresenceBackreferenceEntry + { + List AgentList = new List(); + + public PresenceBackreferenceEntry() + { + + } + + public void Add(UUID item) + { + lock (AgentList) + { + AgentList.Add(item); + } + } + + public UUID getitem(int index) + { + UUID result = UUID.Zero; + lock (AgentList) + { + if (index > 0 && index < AgentList.Count) + { + result = AgentList[index]; + } + } + return result; + } + + public int Count + { + get + { + int count = 0; + lock (AgentList) + { + count = AgentList.Count; + } + return count; + } + } + + public void Remove(UUID item) + { + lock (AgentList) + { + if (AgentList.Contains(item)) + AgentList.Remove(item); + } + } + + public bool contains(UUID item) + { + bool result = false; + lock (AgentList) + { + result = AgentList.Contains(item); + } + return result; + } + } +} diff --git a/OpenSim/Grid/MessagingServer.Modules/PresenceInformer.cs b/OpenSim/Grid/MessagingServer.Modules/PresenceInformer.cs index 5d13c1b..67d630e 100644 --- a/OpenSim/Grid/MessagingServer.Modules/PresenceInformer.cs +++ b/OpenSim/Grid/MessagingServer.Modules/PresenceInformer.cs @@ -1,135 +1,135 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System.Collections; -using System.Net; -using System.Reflection; -using log4net; -using Nwc.XmlRpc; -using OpenSim.Data; - -namespace OpenSim.Grid.MessagingServer.Modules -{ - public delegate RegionProfileData GetRegionData(ulong region_handle); - public delegate void Done(PresenceInformer obj); - - - public class PresenceInformer - { - public event GetRegionData OnGetRegionData; - public event Done OnDone; - - private GetRegionData handlerGetRegionData = null; - private Done handlerDone = null; - - public UserPresenceData presence1 = null; - public UserPresenceData presence2 = null; - public string gridserverurl, gridserversendkey, gridserverrecvkey; - public bool lookupRegion = true; - //public methodGroup - - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - public PresenceInformer() - { - - } - public void go(object o) - { - if (presence1 != null && presence2 != null) - { - SendRegionPresenceUpdate(presence1, presence2); - } - - } - - /// - /// Informs a region about an Agent - /// - /// User to talk about - /// User we're sending this too (contains the region) - public void SendRegionPresenceUpdate(UserPresenceData TalkingAbout, UserPresenceData UserToUpdate) - { - // TODO: Fill in pertenant Presence Data from 'TalkingAbout' - RegionProfileData whichRegion = new RegionProfileData(); - if (lookupRegion) - { - handlerGetRegionData = OnGetRegionData; - if (handlerGetRegionData != null) - { - whichRegion = handlerGetRegionData(UserToUpdate.regionData.regionHandle); - } - //RegionProfileData rp = RegionProfileData.RequestSimProfileData(UserToUpdate.regionData.regionHandle, gridserverurl, gridserversendkey, gridserverrecvkey); - - //whichRegion = rp; - } - else - { - whichRegion = UserToUpdate.regionData; - } - //whichRegion.httpServerURI - - if (whichRegion != null) - { - Hashtable PresenceParams = new Hashtable(); - PresenceParams.Add("agent_id",TalkingAbout.agentData.AgentID.ToString()); - PresenceParams.Add("notify_id",UserToUpdate.agentData.AgentID.ToString()); - if (TalkingAbout.OnlineYN) - PresenceParams.Add("status","TRUE"); - else - PresenceParams.Add("status","FALSE"); - - ArrayList SendParams = new ArrayList(); - SendParams.Add(PresenceParams); - - m_log.InfoFormat("[PRESENCE]: Informing {0}@{1} at {2} about {3}", TalkingAbout.agentData.firstname + " " + TalkingAbout.agentData.lastname, whichRegion.regionName, whichRegion.httpServerURI, UserToUpdate.agentData.firstname + " " + UserToUpdate.agentData.lastname); - // Send - XmlRpcRequest RegionReq = new XmlRpcRequest("presence_update", SendParams); - try - { - // XmlRpcResponse RegionResp = RegionReq.Send(whichRegion.httpServerURI, 6000); - RegionReq.Send(whichRegion.httpServerURI, 6000); - } - catch (WebException) - { - m_log.WarnFormat("[INFORM]: failed notifying region {0} containing user {1} about {2}", whichRegion.regionName, UserToUpdate.agentData.firstname + " " + UserToUpdate.agentData.lastname, TalkingAbout.agentData.firstname + " " + TalkingAbout.agentData.lastname); - } - } - else - { - m_log.Info("[PRESENCEUPDATER]: Region data was null skipping"); - - } - - handlerDone = OnDone; - if (handlerDone != null) - { - handlerDone(this); - } - } - } -} +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System.Collections; +using System.Net; +using System.Reflection; +using log4net; +using Nwc.XmlRpc; +using OpenSim.Data; + +namespace OpenSim.Grid.MessagingServer.Modules +{ + public delegate RegionProfileData GetRegionData(ulong region_handle); + public delegate void Done(PresenceInformer obj); + + + public class PresenceInformer + { + public event GetRegionData OnGetRegionData; + public event Done OnDone; + + private GetRegionData handlerGetRegionData = null; + private Done handlerDone = null; + + public UserPresenceData presence1 = null; + public UserPresenceData presence2 = null; + public string gridserverurl, gridserversendkey, gridserverrecvkey; + public bool lookupRegion = true; + //public methodGroup + + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + public PresenceInformer() + { + + } + public void go(object o) + { + if (presence1 != null && presence2 != null) + { + SendRegionPresenceUpdate(presence1, presence2); + } + + } + + /// + /// Informs a region about an Agent + /// + /// User to talk about + /// User we're sending this too (contains the region) + public void SendRegionPresenceUpdate(UserPresenceData TalkingAbout, UserPresenceData UserToUpdate) + { + // TODO: Fill in pertenant Presence Data from 'TalkingAbout' + RegionProfileData whichRegion = new RegionProfileData(); + if (lookupRegion) + { + handlerGetRegionData = OnGetRegionData; + if (handlerGetRegionData != null) + { + whichRegion = handlerGetRegionData(UserToUpdate.regionData.regionHandle); + } + //RegionProfileData rp = RegionProfileData.RequestSimProfileData(UserToUpdate.regionData.regionHandle, gridserverurl, gridserversendkey, gridserverrecvkey); + + //whichRegion = rp; + } + else + { + whichRegion = UserToUpdate.regionData; + } + //whichRegion.httpServerURI + + if (whichRegion != null) + { + Hashtable PresenceParams = new Hashtable(); + PresenceParams.Add("agent_id",TalkingAbout.agentData.AgentID.ToString()); + PresenceParams.Add("notify_id",UserToUpdate.agentData.AgentID.ToString()); + if (TalkingAbout.OnlineYN) + PresenceParams.Add("status","TRUE"); + else + PresenceParams.Add("status","FALSE"); + + ArrayList SendParams = new ArrayList(); + SendParams.Add(PresenceParams); + + m_log.InfoFormat("[PRESENCE]: Informing {0}@{1} at {2} about {3}", TalkingAbout.agentData.firstname + " " + TalkingAbout.agentData.lastname, whichRegion.regionName, whichRegion.httpServerURI, UserToUpdate.agentData.firstname + " " + UserToUpdate.agentData.lastname); + // Send + XmlRpcRequest RegionReq = new XmlRpcRequest("presence_update", SendParams); + try + { + // XmlRpcResponse RegionResp = RegionReq.Send(whichRegion.httpServerURI, 6000); + RegionReq.Send(whichRegion.httpServerURI, 6000); + } + catch (WebException) + { + m_log.WarnFormat("[INFORM]: failed notifying region {0} containing user {1} about {2}", whichRegion.regionName, UserToUpdate.agentData.firstname + " " + UserToUpdate.agentData.lastname, TalkingAbout.agentData.firstname + " " + TalkingAbout.agentData.lastname); + } + } + else + { + m_log.Info("[PRESENCEUPDATER]: Region data was null skipping"); + + } + + handlerDone = OnDone; + if (handlerDone != null) + { + handlerDone(this); + } + } + } +} diff --git a/OpenSim/Grid/MessagingServer.Modules/PresenceService.cs b/OpenSim/Grid/MessagingServer.Modules/PresenceService.cs index cacc34e..d235e58 100644 --- a/OpenSim/Grid/MessagingServer.Modules/PresenceService.cs +++ b/OpenSim/Grid/MessagingServer.Modules/PresenceService.cs @@ -1,33 +1,33 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -namespace OpenSim.Grid.MessagingServer.Modules -{ - class PresenceService - { - } -} +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +namespace OpenSim.Grid.MessagingServer.Modules +{ + class PresenceService + { + } +} diff --git a/OpenSim/Grid/MessagingServer.Modules/UserDataBaseService.cs b/OpenSim/Grid/MessagingServer.Modules/UserDataBaseService.cs index ee1da86..6dec026 100644 --- a/OpenSim/Grid/MessagingServer.Modules/UserDataBaseService.cs +++ b/OpenSim/Grid/MessagingServer.Modules/UserDataBaseService.cs @@ -1,75 +1,75 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using OpenMetaverse; -using OpenSim.Framework; -using OpenSim.Framework.Communications; - -namespace OpenSim.Grid.MessagingServer.Modules -{ - public class UserDataBaseService : UserManagerBase - { - /// - /// Constructor. - /// - /// Passing null to parent because we never use any function that requires an interservice inventory call. - public UserDataBaseService() - : base(null) - { - } - - public UserAgentData GetUserAgentData(UUID AgentID) - { - UserProfileData userProfile = GetUserProfile(AgentID); - - if (userProfile != null) - { - return userProfile.CurrentAgent; - } - - return null; - } - - public override UserProfileData SetupMasterUser(string firstName, string lastName) - { - //throw new Exception("The method or operation is not implemented."); - return null; - } - - public override UserProfileData SetupMasterUser(string firstName, string lastName, string password) - { - //throw new Exception("The method or operation is not implemented."); - return null; - } - - public override UserProfileData SetupMasterUser(UUID uuid) - { - //throw new Exception("The method or operation is not implemented."); - return null; - } - } -} +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Framework.Communications; + +namespace OpenSim.Grid.MessagingServer.Modules +{ + public class UserDataBaseService : UserManagerBase + { + /// + /// Constructor. + /// + /// Passing null to parent because we never use any function that requires an interservice inventory call. + public UserDataBaseService() + : base(null) + { + } + + public UserAgentData GetUserAgentData(UUID AgentID) + { + UserProfileData userProfile = GetUserProfile(AgentID); + + if (userProfile != null) + { + return userProfile.CurrentAgent; + } + + return null; + } + + public override UserProfileData SetupMasterUser(string firstName, string lastName) + { + //throw new Exception("The method or operation is not implemented."); + return null; + } + + public override UserProfileData SetupMasterUser(string firstName, string lastName, string password) + { + //throw new Exception("The method or operation is not implemented."); + return null; + } + + public override UserProfileData SetupMasterUser(UUID uuid) + { + //throw new Exception("The method or operation is not implemented."); + return null; + } + } +} diff --git a/OpenSim/Grid/MessagingServer.Modules/UserPresenceData.cs b/OpenSim/Grid/MessagingServer.Modules/UserPresenceData.cs index 2b56fe8..d548fc6 100644 --- a/OpenSim/Grid/MessagingServer.Modules/UserPresenceData.cs +++ b/OpenSim/Grid/MessagingServer.Modules/UserPresenceData.cs @@ -1,50 +1,50 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using OpenMetaverse; -using OpenSim.Data; -using OpenSim.Framework; - -namespace OpenSim.Grid.MessagingServer -{ - public class UserPresenceData - { - public AgentCircuitData agentData = new AgentCircuitData(); - public RegionProfileData regionData = new RegionProfileData(); - public string httpURI = String.Empty; - public Dictionary friendData = new Dictionary(); - public List subscriptionData = new List(); - public bool OnlineYN = true; - public bool lookupUserRegionYN = true; - - public UserPresenceData() - { - } - } -} +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using OpenMetaverse; +using OpenSim.Data; +using OpenSim.Framework; + +namespace OpenSim.Grid.MessagingServer +{ + public class UserPresenceData + { + public AgentCircuitData agentData = new AgentCircuitData(); + public RegionProfileData regionData = new RegionProfileData(); + public string httpURI = String.Empty; + public Dictionary friendData = new Dictionary(); + public List subscriptionData = new List(); + public bool OnlineYN = true; + public bool lookupUserRegionYN = true; + + public UserPresenceData() + { + } + } +} diff --git a/OpenSim/Grid/MessagingServer.Modules/WorkUnitBase.cs b/OpenSim/Grid/MessagingServer.Modules/WorkUnitBase.cs index cbd9443..0e0d562 100644 --- a/OpenSim/Grid/MessagingServer.Modules/WorkUnitBase.cs +++ b/OpenSim/Grid/MessagingServer.Modules/WorkUnitBase.cs @@ -1,33 +1,33 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -namespace OpenSim.Grid.MessagingServer.Modules -{ - public class WorkUnitBase - { - } -} +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +namespace OpenSim.Grid.MessagingServer.Modules +{ + public class WorkUnitBase + { + } +} diff --git a/OpenSim/Grid/MessagingServer.Modules/WorkUnitPresenceUpdate.cs b/OpenSim/Grid/MessagingServer.Modules/WorkUnitPresenceUpdate.cs index 7150cea..8eda305 100644 --- a/OpenSim/Grid/MessagingServer.Modules/WorkUnitPresenceUpdate.cs +++ b/OpenSim/Grid/MessagingServer.Modules/WorkUnitPresenceUpdate.cs @@ -1,33 +1,33 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -namespace OpenSim.Grid.MessagingServer.Modules -{ - public class WorkUnitPresenceUpdate : WorkUnitBase - { - } -} +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +namespace OpenSim.Grid.MessagingServer.Modules +{ + public class WorkUnitPresenceUpdate : WorkUnitBase + { + } +} diff --git a/OpenSim/Grid/UserServer.Modules/MessageServersConnector.cs b/OpenSim/Grid/UserServer.Modules/MessageServersConnector.cs index b98c614..59e9805 100644 --- a/OpenSim/Grid/UserServer.Modules/MessageServersConnector.cs +++ b/OpenSim/Grid/UserServer.Modules/MessageServersConnector.cs @@ -1,509 +1,509 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System.Collections; -using System.Collections.Generic; -using System.Net; -using System.Reflection; -using System.Threading; -using log4net; -using Nwc.XmlRpc; -using OpenMetaverse; -using OpenSim.Framework; -using OpenSim.Framework.Servers; - -namespace OpenSim.Grid.UserServer.Modules -{ - public enum NotificationRequest : int - { - Login = 0, - Logout = 1, - Shutdown = 2 - } - - public struct PresenceNotification - { - public NotificationRequest request; - public UUID agentID; - public UUID sessionID; - public UUID RegionID; - public ulong regionhandle; - public float positionX; - public float positionY; - public float positionZ; - public string firstname; - public string lastname; - } - - public delegate void AgentLocationDelegate(UUID agentID, UUID regionID, ulong regionHandle); - public delegate void AgentLeavingDelegate(UUID agentID, UUID regionID, ulong regionHandle); - public delegate void RegionStartupDelegate(UUID regionID); - public delegate void RegionShutdownDelegate(UUID regionID); - - - public class MessageServersConnector - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - public Dictionary MessageServers; - - private BaseHttpServer m_httpServer; - - private BlockingQueue m_NotifyQueue = - new BlockingQueue(); - - Thread m_NotifyThread; - - public event AgentLocationDelegate OnAgentLocation; - public event AgentLeavingDelegate OnAgentLeaving; - public event RegionStartupDelegate OnRegionStartup; - public event RegionShutdownDelegate OnRegionShutdown; - - public MessageServersConnector() - { - MessageServers = new Dictionary(); - m_NotifyThread = new Thread(new ThreadStart(NotifyQueueRunner)); - m_NotifyThread.Start(); - } - - public void Initialise() - { - - } - - public void PostInitialise() - { - - } - - public void RegisterHandlers(BaseHttpServer httpServer) - { - m_httpServer = httpServer; - - m_httpServer.AddXmlRPCHandler("region_startup", RegionStartup); - m_httpServer.AddXmlRPCHandler("region_shutdown", RegionShutdown); - m_httpServer.AddXmlRPCHandler("agent_location", AgentLocation); - m_httpServer.AddXmlRPCHandler("agent_leaving", AgentLeaving); - // Message Server ---> User Server - m_httpServer.AddXmlRPCHandler("register_messageserver", XmlRPCRegisterMessageServer); - m_httpServer.AddXmlRPCHandler("agent_change_region", XmlRPCUserMovedtoRegion); - m_httpServer.AddXmlRPCHandler("deregister_messageserver", XmlRPCDeRegisterMessageServer); - } - - public void RegisterMessageServer(string URI, MessageServerInfo serverData) - { - lock (MessageServers) - { - if (!MessageServers.ContainsKey(URI)) - MessageServers.Add(URI, serverData); - } - } - - public void DeRegisterMessageServer(string URI) - { - lock (MessageServers) - { - if (MessageServers.ContainsKey(URI)) - MessageServers.Remove(URI); - } - } - - public void AddResponsibleRegion(string URI, ulong regionhandle) - { - if (!MessageServers.ContainsKey(URI)) - { - m_log.Warn("[MSGSERVER]: Got addResponsibleRegion Request for a MessageServer that isn't registered"); - } - else - { - MessageServerInfo msginfo = MessageServers["URI"]; - msginfo.responsibleForRegions.Add(regionhandle); - MessageServers["URI"] = msginfo; - } - } - public void RemoveResponsibleRegion(string URI, ulong regionhandle) - { - if (!MessageServers.ContainsKey(URI)) - { - m_log.Warn("[MSGSERVER]: Got RemoveResponsibleRegion Request for a MessageServer that isn't registered"); - } - else - { - MessageServerInfo msginfo = MessageServers["URI"]; - if (msginfo.responsibleForRegions.Contains(regionhandle)) - { - msginfo.responsibleForRegions.Remove(regionhandle); - MessageServers["URI"] = msginfo; - } - } - - } - public XmlRpcResponse XmlRPCRegisterMessageServer(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable)request.Params[0]; - Hashtable responseData = new Hashtable(); - - if (requestData.Contains("uri")) - { - string URI = (string)requestData["uri"]; - string sendkey=(string)requestData["sendkey"]; - string recvkey=(string)requestData["recvkey"]; - MessageServerInfo m = new MessageServerInfo(); - m.URI = URI; - m.sendkey = sendkey; - m.recvkey = recvkey; - RegisterMessageServer(URI, m); - responseData["responsestring"] = "TRUE"; - response.Value = responseData; - } - return response; - } - public XmlRpcResponse XmlRPCDeRegisterMessageServer(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable)request.Params[0]; - Hashtable responseData = new Hashtable(); - - if (requestData.Contains("uri")) - { - string URI = (string)requestData["uri"]; - - DeRegisterMessageServer(URI); - responseData["responsestring"] = "TRUE"; - response.Value = responseData; - } - return response; - } - public XmlRpcResponse XmlRPCUserMovedtoRegion(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable)request.Params[0]; - Hashtable responseData = new Hashtable(); - - if (requestData.Contains("fromuri")) - { - // string sURI = (string)requestData["fromuri"]; - // string sagentID = (string)requestData["agentid"]; - // string ssessionID = (string)requestData["sessionid"]; - // string scurrentRegionID = (string)requestData["regionid"]; - // string sregionhandle = (string)requestData["regionhandle"]; - // string scurrentpos = (string)requestData["currentpos"]; - //Vector3.TryParse((string)reader["currentPos"], out retval.currentPos); - // TODO: Okay now raise event so the user server can pass this data to the Usermanager - - responseData["responsestring"] = "TRUE"; - response.Value = responseData; - } - return response; - } - - public void TellMessageServersAboutUser(UUID agentID, UUID sessionID, UUID RegionID, - ulong regionhandle, float positionX, float positionY, - float positionZ, string firstname, string lastname) - { - PresenceNotification notification = new PresenceNotification(); - - notification.request = NotificationRequest.Login; - notification.agentID = agentID; - notification.sessionID = sessionID; - notification.RegionID = RegionID; - notification.regionhandle = regionhandle; - notification.positionX = positionX; - notification.positionY = positionY; - notification.positionZ = positionZ; - notification.firstname = firstname; - notification.lastname = lastname; - - m_NotifyQueue.Enqueue(notification); - } - - private void TellMessageServersAboutUserInternal(UUID agentID, UUID sessionID, UUID RegionID, - ulong regionhandle, float positionX, float positionY, - float positionZ, string firstname, string lastname) - { - // Loop over registered Message Servers (AND THERE WILL BE MORE THEN ONE :D) - lock (MessageServers) - { - if (MessageServers.Count > 0) - { - m_log.Info("[MSGCONNECTOR]: Sending login notice to registered message servers"); - } -// else -// { -// m_log.Debug("[MSGCONNECTOR]: No Message Servers registered, ignoring"); -// } - foreach (MessageServerInfo serv in MessageServers.Values) - { - NotifyMessageServerAboutUser(serv, agentID, sessionID, RegionID, - regionhandle, positionX, positionY, positionZ, - firstname, lastname); - } - } - } - - private void TellMessageServersAboutUserLogoffInternal(UUID agentID) - { - lock (MessageServers) - { - if (MessageServers.Count > 0) - { - m_log.Info("[MSGCONNECTOR]: Sending logoff notice to registered message servers"); - } - else - { -// m_log.Debug("[MSGCONNECTOR]: No Message Servers registered, ignoring"); - } - foreach (MessageServerInfo serv in MessageServers.Values) - { - NotifyMessageServerAboutUserLogoff(serv,agentID); - } - } - } - - private void TellMessageServersAboutRegionShutdownInternal(UUID regionID) - { - lock (MessageServers) - { - if (MessageServers.Count > 0) - { - m_log.Info("[MSGCONNECTOR]: Sending region down notice to registered message servers"); - } - else - { -// m_log.Debug("[MSGCONNECTOR]: No Message Servers registered, ignoring"); - } - foreach (MessageServerInfo serv in MessageServers.Values) - { - NotifyMessageServerAboutRegionShutdown(serv,regionID); - } - } - } - - public void TellMessageServersAboutUserLogoff(UUID agentID) - { - PresenceNotification notification = new PresenceNotification(); - - notification.request = NotificationRequest.Logout; - notification.agentID = agentID; - - m_NotifyQueue.Enqueue(notification); - } - - public void TellMessageServersAboutRegionShutdown(UUID regionID) - { - PresenceNotification notification = new PresenceNotification(); - - notification.request = NotificationRequest.Shutdown; - notification.RegionID = regionID; - - m_NotifyQueue.Enqueue(notification); - } - - private void NotifyMessageServerAboutUserLogoff(MessageServerInfo serv, UUID agentID) - { - Hashtable reqparams = new Hashtable(); - reqparams["sendkey"] = serv.sendkey; - reqparams["agentid"] = agentID.ToString(); - ArrayList SendParams = new ArrayList(); - SendParams.Add(reqparams); - - XmlRpcRequest GridReq = new XmlRpcRequest("logout_of_simulator", SendParams); - try - { - GridReq.Send(serv.URI, 6000); - } - catch (WebException) - { - m_log.Warn("[MSGCONNECTOR]: Unable to notify Message Server about log out. Other users might still think this user is online"); - } - m_log.Info("[LOGOUT]: Notified : " + serv.URI + " about user logout"); - } - - private void NotifyMessageServerAboutRegionShutdown(MessageServerInfo serv, UUID regionID) - { - Hashtable reqparams = new Hashtable(); - reqparams["sendkey"] = serv.sendkey; - reqparams["regionid"] = regionID.ToString(); - ArrayList SendParams = new ArrayList(); - SendParams.Add(reqparams); - - XmlRpcRequest GridReq = new XmlRpcRequest("process_region_shutdown", SendParams); - try - { - GridReq.Send(serv.URI, 6000); - } - catch (WebException) - { - m_log.Warn("[MSGCONNECTOR]: Unable to notify Message Server about region shutdown."); - } - m_log.Info("[REGION UPDOWN]: Notified : " + serv.URI + " about region state change"); - } - - private void NotifyMessageServerAboutUser(MessageServerInfo serv, - UUID agentID, UUID sessionID, UUID RegionID, - ulong regionhandle, float positionX, float positionY, float positionZ, - string firstname, string lastname) - { - Hashtable reqparams = new Hashtable(); - reqparams["sendkey"] = serv.sendkey; - reqparams["agentid"] = agentID.ToString(); - reqparams["sessionid"] = sessionID.ToString(); - reqparams["regionid"] = RegionID.ToString(); - reqparams["regionhandle"] = regionhandle.ToString(); - reqparams["positionx"] = positionX.ToString(); - reqparams["positiony"] = positionY.ToString(); - reqparams["positionz"] = positionZ.ToString(); - reqparams["firstname"] = firstname; - reqparams["lastname"] = lastname; - - //reqparams["position"] = Position.ToString(); - - ArrayList SendParams = new ArrayList(); - SendParams.Add(reqparams); - - XmlRpcRequest GridReq = new XmlRpcRequest("login_to_simulator", SendParams); - try - { - GridReq.Send(serv.URI, 6000); - m_log.Info("[LOGIN]: Notified : " + serv.URI + " about user login"); - } - catch (WebException) - { - m_log.Warn("[MSGCONNECTOR]: Unable to notify Message Server about login. Presence might be borked for this user"); - } - - } - - private void NotifyQueueRunner() - { - while (true) - { - PresenceNotification presence = m_NotifyQueue.Dequeue(); - - if (presence.request == NotificationRequest.Shutdown) - { - TellMessageServersAboutRegionShutdownInternal(presence.RegionID); - } - - if (presence.request == NotificationRequest.Login) - { - TellMessageServersAboutUserInternal(presence.agentID, - presence.sessionID, presence.RegionID, - presence.regionhandle, presence.positionX, - presence.positionY, presence.positionZ, - presence.firstname, presence.lastname); - } - - if (presence.request == NotificationRequest.Logout) - { - TellMessageServersAboutUserLogoffInternal(presence.agentID); - } - } - } - - public XmlRpcResponse RegionStartup(XmlRpcRequest request) - { - Hashtable requestData = (Hashtable)request.Params[0]; - Hashtable result = new Hashtable(); - - UUID regionID; - if (UUID.TryParse((string)requestData["RegionUUID"], out regionID)) - { - if (OnRegionStartup != null) - OnRegionStartup(regionID); - - result["responsestring"] = "TRUE"; - } - - XmlRpcResponse response = new XmlRpcResponse(); - response.Value = result; - return response; - } - - public XmlRpcResponse RegionShutdown(XmlRpcRequest request) - { - Hashtable requestData = (Hashtable)request.Params[0]; - Hashtable result = new Hashtable(); - - UUID regionID; - if (UUID.TryParse((string)requestData["RegionUUID"], out regionID)) - { - if (OnRegionShutdown != null) - OnRegionShutdown(regionID); - - result["responsestring"] = "TRUE"; - } - - XmlRpcResponse response = new XmlRpcResponse(); - response.Value = result; - return response; - } - - public XmlRpcResponse AgentLocation(XmlRpcRequest request) - { - Hashtable requestData = (Hashtable)request.Params[0]; - Hashtable result = new Hashtable(); - - UUID agentID; - UUID regionID; - ulong regionHandle; - if (UUID.TryParse((string)requestData["AgentID"], out agentID) && UUID.TryParse((string)requestData["RegionUUID"], out regionID) && ulong.TryParse((string)requestData["RegionHandle"], out regionHandle)) - { - if (OnAgentLocation != null) - OnAgentLocation(agentID, regionID, regionHandle); - - result["responsestring"] = "TRUE"; - } - - XmlRpcResponse response = new XmlRpcResponse(); - response.Value = result; - return response; - } - - public XmlRpcResponse AgentLeaving(XmlRpcRequest request) - { - Hashtable requestData = (Hashtable)request.Params[0]; - Hashtable result = new Hashtable(); - - UUID agentID; - UUID regionID; - ulong regionHandle; - if (UUID.TryParse((string)requestData["AgentID"], out agentID) && UUID.TryParse((string)requestData["RegionUUID"], out regionID) && ulong.TryParse((string)requestData["RegionHandle"], out regionHandle)) - { - if (OnAgentLeaving != null) - OnAgentLeaving(agentID, regionID, regionHandle); - - result["responsestring"] = "TRUE"; - } - - XmlRpcResponse response = new XmlRpcResponse(); - response.Value = result; - return response; - } - } -} +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System.Collections; +using System.Collections.Generic; +using System.Net; +using System.Reflection; +using System.Threading; +using log4net; +using Nwc.XmlRpc; +using OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Framework.Servers; + +namespace OpenSim.Grid.UserServer.Modules +{ + public enum NotificationRequest : int + { + Login = 0, + Logout = 1, + Shutdown = 2 + } + + public struct PresenceNotification + { + public NotificationRequest request; + public UUID agentID; + public UUID sessionID; + public UUID RegionID; + public ulong regionhandle; + public float positionX; + public float positionY; + public float positionZ; + public string firstname; + public string lastname; + } + + public delegate void AgentLocationDelegate(UUID agentID, UUID regionID, ulong regionHandle); + public delegate void AgentLeavingDelegate(UUID agentID, UUID regionID, ulong regionHandle); + public delegate void RegionStartupDelegate(UUID regionID); + public delegate void RegionShutdownDelegate(UUID regionID); + + + public class MessageServersConnector + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + public Dictionary MessageServers; + + private BaseHttpServer m_httpServer; + + private BlockingQueue m_NotifyQueue = + new BlockingQueue(); + + Thread m_NotifyThread; + + public event AgentLocationDelegate OnAgentLocation; + public event AgentLeavingDelegate OnAgentLeaving; + public event RegionStartupDelegate OnRegionStartup; + public event RegionShutdownDelegate OnRegionShutdown; + + public MessageServersConnector() + { + MessageServers = new Dictionary(); + m_NotifyThread = new Thread(new ThreadStart(NotifyQueueRunner)); + m_NotifyThread.Start(); + } + + public void Initialise() + { + + } + + public void PostInitialise() + { + + } + + public void RegisterHandlers(BaseHttpServer httpServer) + { + m_httpServer = httpServer; + + m_httpServer.AddXmlRPCHandler("region_startup", RegionStartup); + m_httpServer.AddXmlRPCHandler("region_shutdown", RegionShutdown); + m_httpServer.AddXmlRPCHandler("agent_location", AgentLocation); + m_httpServer.AddXmlRPCHandler("agent_leaving", AgentLeaving); + // Message Server ---> User Server + m_httpServer.AddXmlRPCHandler("register_messageserver", XmlRPCRegisterMessageServer); + m_httpServer.AddXmlRPCHandler("agent_change_region", XmlRPCUserMovedtoRegion); + m_httpServer.AddXmlRPCHandler("deregister_messageserver", XmlRPCDeRegisterMessageServer); + } + + public void RegisterMessageServer(string URI, MessageServerInfo serverData) + { + lock (MessageServers) + { + if (!MessageServers.ContainsKey(URI)) + MessageServers.Add(URI, serverData); + } + } + + public void DeRegisterMessageServer(string URI) + { + lock (MessageServers) + { + if (MessageServers.ContainsKey(URI)) + MessageServers.Remove(URI); + } + } + + public void AddResponsibleRegion(string URI, ulong regionhandle) + { + if (!MessageServers.ContainsKey(URI)) + { + m_log.Warn("[MSGSERVER]: Got addResponsibleRegion Request for a MessageServer that isn't registered"); + } + else + { + MessageServerInfo msginfo = MessageServers["URI"]; + msginfo.responsibleForRegions.Add(regionhandle); + MessageServers["URI"] = msginfo; + } + } + public void RemoveResponsibleRegion(string URI, ulong regionhandle) + { + if (!MessageServers.ContainsKey(URI)) + { + m_log.Warn("[MSGSERVER]: Got RemoveResponsibleRegion Request for a MessageServer that isn't registered"); + } + else + { + MessageServerInfo msginfo = MessageServers["URI"]; + if (msginfo.responsibleForRegions.Contains(regionhandle)) + { + msginfo.responsibleForRegions.Remove(regionhandle); + MessageServers["URI"] = msginfo; + } + } + + } + public XmlRpcResponse XmlRPCRegisterMessageServer(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable responseData = new Hashtable(); + + if (requestData.Contains("uri")) + { + string URI = (string)requestData["uri"]; + string sendkey=(string)requestData["sendkey"]; + string recvkey=(string)requestData["recvkey"]; + MessageServerInfo m = new MessageServerInfo(); + m.URI = URI; + m.sendkey = sendkey; + m.recvkey = recvkey; + RegisterMessageServer(URI, m); + responseData["responsestring"] = "TRUE"; + response.Value = responseData; + } + return response; + } + public XmlRpcResponse XmlRPCDeRegisterMessageServer(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable responseData = new Hashtable(); + + if (requestData.Contains("uri")) + { + string URI = (string)requestData["uri"]; + + DeRegisterMessageServer(URI); + responseData["responsestring"] = "TRUE"; + response.Value = responseData; + } + return response; + } + public XmlRpcResponse XmlRPCUserMovedtoRegion(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable responseData = new Hashtable(); + + if (requestData.Contains("fromuri")) + { + // string sURI = (string)requestData["fromuri"]; + // string sagentID = (string)requestData["agentid"]; + // string ssessionID = (string)requestData["sessionid"]; + // string scurrentRegionID = (string)requestData["regionid"]; + // string sregionhandle = (string)requestData["regionhandle"]; + // string scurrentpos = (string)requestData["currentpos"]; + //Vector3.TryParse((string)reader["currentPos"], out retval.currentPos); + // TODO: Okay now raise event so the user server can pass this data to the Usermanager + + responseData["responsestring"] = "TRUE"; + response.Value = responseData; + } + return response; + } + + public void TellMessageServersAboutUser(UUID agentID, UUID sessionID, UUID RegionID, + ulong regionhandle, float positionX, float positionY, + float positionZ, string firstname, string lastname) + { + PresenceNotification notification = new PresenceNotification(); + + notification.request = NotificationRequest.Login; + notification.agentID = agentID; + notification.sessionID = sessionID; + notification.RegionID = RegionID; + notification.regionhandle = regionhandle; + notification.positionX = positionX; + notification.positionY = positionY; + notification.positionZ = positionZ; + notification.firstname = firstname; + notification.lastname = lastname; + + m_NotifyQueue.Enqueue(notification); + } + + private void TellMessageServersAboutUserInternal(UUID agentID, UUID sessionID, UUID RegionID, + ulong regionhandle, float positionX, float positionY, + float positionZ, string firstname, string lastname) + { + // Loop over registered Message Servers (AND THERE WILL BE MORE THEN ONE :D) + lock (MessageServers) + { + if (MessageServers.Count > 0) + { + m_log.Info("[MSGCONNECTOR]: Sending login notice to registered message servers"); + } +// else +// { +// m_log.Debug("[MSGCONNECTOR]: No Message Servers registered, ignoring"); +// } + foreach (MessageServerInfo serv in MessageServers.Values) + { + NotifyMessageServerAboutUser(serv, agentID, sessionID, RegionID, + regionhandle, positionX, positionY, positionZ, + firstname, lastname); + } + } + } + + private void TellMessageServersAboutUserLogoffInternal(UUID agentID) + { + lock (MessageServers) + { + if (MessageServers.Count > 0) + { + m_log.Info("[MSGCONNECTOR]: Sending logoff notice to registered message servers"); + } + else + { +// m_log.Debug("[MSGCONNECTOR]: No Message Servers registered, ignoring"); + } + foreach (MessageServerInfo serv in MessageServers.Values) + { + NotifyMessageServerAboutUserLogoff(serv,agentID); + } + } + } + + private void TellMessageServersAboutRegionShutdownInternal(UUID regionID) + { + lock (MessageServers) + { + if (MessageServers.Count > 0) + { + m_log.Info("[MSGCONNECTOR]: Sending region down notice to registered message servers"); + } + else + { +// m_log.Debug("[MSGCONNECTOR]: No Message Servers registered, ignoring"); + } + foreach (MessageServerInfo serv in MessageServers.Values) + { + NotifyMessageServerAboutRegionShutdown(serv,regionID); + } + } + } + + public void TellMessageServersAboutUserLogoff(UUID agentID) + { + PresenceNotification notification = new PresenceNotification(); + + notification.request = NotificationRequest.Logout; + notification.agentID = agentID; + + m_NotifyQueue.Enqueue(notification); + } + + public void TellMessageServersAboutRegionShutdown(UUID regionID) + { + PresenceNotification notification = new PresenceNotification(); + + notification.request = NotificationRequest.Shutdown; + notification.RegionID = regionID; + + m_NotifyQueue.Enqueue(notification); + } + + private void NotifyMessageServerAboutUserLogoff(MessageServerInfo serv, UUID agentID) + { + Hashtable reqparams = new Hashtable(); + reqparams["sendkey"] = serv.sendkey; + reqparams["agentid"] = agentID.ToString(); + ArrayList SendParams = new ArrayList(); + SendParams.Add(reqparams); + + XmlRpcRequest GridReq = new XmlRpcRequest("logout_of_simulator", SendParams); + try + { + GridReq.Send(serv.URI, 6000); + } + catch (WebException) + { + m_log.Warn("[MSGCONNECTOR]: Unable to notify Message Server about log out. Other users might still think this user is online"); + } + m_log.Info("[LOGOUT]: Notified : " + serv.URI + " about user logout"); + } + + private void NotifyMessageServerAboutRegionShutdown(MessageServerInfo serv, UUID regionID) + { + Hashtable reqparams = new Hashtable(); + reqparams["sendkey"] = serv.sendkey; + reqparams["regionid"] = regionID.ToString(); + ArrayList SendParams = new ArrayList(); + SendParams.Add(reqparams); + + XmlRpcRequest GridReq = new XmlRpcRequest("process_region_shutdown", SendParams); + try + { + GridReq.Send(serv.URI, 6000); + } + catch (WebException) + { + m_log.Warn("[MSGCONNECTOR]: Unable to notify Message Server about region shutdown."); + } + m_log.Info("[REGION UPDOWN]: Notified : " + serv.URI + " about region state change"); + } + + private void NotifyMessageServerAboutUser(MessageServerInfo serv, + UUID agentID, UUID sessionID, UUID RegionID, + ulong regionhandle, float positionX, float positionY, float positionZ, + string firstname, string lastname) + { + Hashtable reqparams = new Hashtable(); + reqparams["sendkey"] = serv.sendkey; + reqparams["agentid"] = agentID.ToString(); + reqparams["sessionid"] = sessionID.ToString(); + reqparams["regionid"] = RegionID.ToString(); + reqparams["regionhandle"] = regionhandle.ToString(); + reqparams["positionx"] = positionX.ToString(); + reqparams["positiony"] = positionY.ToString(); + reqparams["positionz"] = positionZ.ToString(); + reqparams["firstname"] = firstname; + reqparams["lastname"] = lastname; + + //reqparams["position"] = Position.ToString(); + + ArrayList SendParams = new ArrayList(); + SendParams.Add(reqparams); + + XmlRpcRequest GridReq = new XmlRpcRequest("login_to_simulator", SendParams); + try + { + GridReq.Send(serv.URI, 6000); + m_log.Info("[LOGIN]: Notified : " + serv.URI + " about user login"); + } + catch (WebException) + { + m_log.Warn("[MSGCONNECTOR]: Unable to notify Message Server about login. Presence might be borked for this user"); + } + + } + + private void NotifyQueueRunner() + { + while (true) + { + PresenceNotification presence = m_NotifyQueue.Dequeue(); + + if (presence.request == NotificationRequest.Shutdown) + { + TellMessageServersAboutRegionShutdownInternal(presence.RegionID); + } + + if (presence.request == NotificationRequest.Login) + { + TellMessageServersAboutUserInternal(presence.agentID, + presence.sessionID, presence.RegionID, + presence.regionhandle, presence.positionX, + presence.positionY, presence.positionZ, + presence.firstname, presence.lastname); + } + + if (presence.request == NotificationRequest.Logout) + { + TellMessageServersAboutUserLogoffInternal(presence.agentID); + } + } + } + + public XmlRpcResponse RegionStartup(XmlRpcRequest request) + { + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable result = new Hashtable(); + + UUID regionID; + if (UUID.TryParse((string)requestData["RegionUUID"], out regionID)) + { + if (OnRegionStartup != null) + OnRegionStartup(regionID); + + result["responsestring"] = "TRUE"; + } + + XmlRpcResponse response = new XmlRpcResponse(); + response.Value = result; + return response; + } + + public XmlRpcResponse RegionShutdown(XmlRpcRequest request) + { + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable result = new Hashtable(); + + UUID regionID; + if (UUID.TryParse((string)requestData["RegionUUID"], out regionID)) + { + if (OnRegionShutdown != null) + OnRegionShutdown(regionID); + + result["responsestring"] = "TRUE"; + } + + XmlRpcResponse response = new XmlRpcResponse(); + response.Value = result; + return response; + } + + public XmlRpcResponse AgentLocation(XmlRpcRequest request) + { + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable result = new Hashtable(); + + UUID agentID; + UUID regionID; + ulong regionHandle; + if (UUID.TryParse((string)requestData["AgentID"], out agentID) && UUID.TryParse((string)requestData["RegionUUID"], out regionID) && ulong.TryParse((string)requestData["RegionHandle"], out regionHandle)) + { + if (OnAgentLocation != null) + OnAgentLocation(agentID, regionID, regionHandle); + + result["responsestring"] = "TRUE"; + } + + XmlRpcResponse response = new XmlRpcResponse(); + response.Value = result; + return response; + } + + public XmlRpcResponse AgentLeaving(XmlRpcRequest request) + { + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable result = new Hashtable(); + + UUID agentID; + UUID regionID; + ulong regionHandle; + if (UUID.TryParse((string)requestData["AgentID"], out agentID) && UUID.TryParse((string)requestData["RegionUUID"], out regionID) && ulong.TryParse((string)requestData["RegionHandle"], out regionHandle)) + { + if (OnAgentLeaving != null) + OnAgentLeaving(agentID, regionID, regionHandle); + + result["responsestring"] = "TRUE"; + } + + XmlRpcResponse response = new XmlRpcResponse(); + response.Value = result; + return response; + } + } +} diff --git a/OpenSim/Grid/UserServer.Modules/OpenIdService.cs b/OpenSim/Grid/UserServer.Modules/OpenIdService.cs index 5c8501f..28a8fdb 100644 --- a/OpenSim/Grid/UserServer.Modules/OpenIdService.cs +++ b/OpenSim/Grid/UserServer.Modules/OpenIdService.cs @@ -1,337 +1,337 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.IO; -using System.Net; -using System.Web; -using DotNetOpenId; -using DotNetOpenId.Provider; -using OpenSim.Framework; -using OpenSim.Framework.Servers; - -namespace OpenSim.Grid.UserServer.Modules -{ - /// - /// Temporary, in-memory store for OpenID associations - /// - public class ProviderMemoryStore : IAssociationStore - { - private class AssociationItem - { - public AssociationRelyingPartyType DistinguishingFactor; - public string Handle; - public DateTime Expires; - public byte[] PrivateData; - } - - Dictionary m_store = new Dictionary(); - SortedList m_sortedStore = new SortedList(); - object m_syncRoot = new object(); - - #region IAssociationStore Members - - public void StoreAssociation(AssociationRelyingPartyType distinguishingFactor, Association assoc) - { - AssociationItem item = new AssociationItem(); - item.DistinguishingFactor = distinguishingFactor; - item.Handle = assoc.Handle; - item.Expires = assoc.Expires.ToLocalTime(); - item.PrivateData = assoc.SerializePrivateData(); - - lock (m_syncRoot) - { - m_store[item.Handle] = item; - m_sortedStore[item.Expires] = item; - } - } - - public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor) - { - lock (m_syncRoot) - { - if (m_sortedStore.Count > 0) - { - AssociationItem item = m_sortedStore.Values[m_sortedStore.Count - 1]; - return Association.Deserialize(item.Handle, item.Expires.ToUniversalTime(), item.PrivateData); - } - else - { - return null; - } - } - } - - public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor, string handle) - { - AssociationItem item; - bool success = false; - lock (m_syncRoot) - success = m_store.TryGetValue(handle, out item); - - if (success) - return Association.Deserialize(item.Handle, item.Expires.ToUniversalTime(), item.PrivateData); - else - return null; - } - - public bool RemoveAssociation(AssociationRelyingPartyType distinguishingFactor, string handle) - { - lock (m_syncRoot) - { - for (int i = 0; i < m_sortedStore.Values.Count; i++) - { - AssociationItem item = m_sortedStore.Values[i]; - if (item.Handle == handle) - { - m_sortedStore.RemoveAt(i); - break; - } - } - - return m_store.Remove(handle); - } - } - - public void ClearExpiredAssociations() - { - lock (m_syncRoot) - { - List itemsCopy = new List(m_sortedStore.Values); - DateTime now = DateTime.Now; - - for (int i = 0; i < itemsCopy.Count; i++) - { - AssociationItem item = itemsCopy[i]; - - if (item.Expires <= now) - { - m_sortedStore.RemoveAt(i); - m_store.Remove(item.Handle); - } - } - } - } - - #endregion - } - - public class OpenIdStreamHandler : IStreamHandler - { - #region HTML - - /// Login form used to authenticate OpenID requests - const string LOGIN_PAGE = -@" -OpenSim OpenID Login - -

OpenSim Login

-
- - - - -
- -"; - - /// Page shown for a valid OpenID identity - const string OPENID_PAGE = -@" - -{2} {3} - - -OpenID identifier for {2} {3} - -"; - - /// Page shown for an invalid OpenID identity - const string INVALID_OPENID_PAGE = -@"Identity not found -Invalid OpenID identity"; - - /// Page shown if the OpenID endpoint is requested directly - const string ENDPOINT_PAGE = -@"OpenID Endpoint -This is an OpenID server endpoint, not a human-readable resource. -For more information, see http://openid.net/. -"; - - #endregion HTML - - public string ContentType { get { return m_contentType; } } - public string HttpMethod { get { return m_httpMethod; } } - public string Path { get { return m_path; } } - - string m_contentType; - string m_httpMethod; - string m_path; - UserLoginService m_loginService; - ProviderMemoryStore m_openidStore = new ProviderMemoryStore(); - - /// - /// Constructor - /// - public OpenIdStreamHandler(string httpMethod, string path, UserLoginService loginService) - { - m_loginService = loginService; - m_httpMethod = httpMethod; - m_path = path; - - m_contentType = "text/html"; - } - - /// - /// Handles all GET and POST requests for OpenID identifier pages and endpoint - /// server communication - /// - public void Handle(string path, Stream request, Stream response, OSHttpRequest httpRequest, OSHttpResponse httpResponse) - { - Uri providerEndpoint = new Uri(String.Format("{0}://{1}{2}", httpRequest.Url.Scheme, httpRequest.Url.Authority, httpRequest.Url.AbsolutePath)); - - // Defult to returning HTML content - m_contentType = "text/html"; - - try - { - NameValueCollection postQuery = HttpUtility.ParseQueryString(new StreamReader(httpRequest.InputStream).ReadToEnd()); - NameValueCollection getQuery = HttpUtility.ParseQueryString(httpRequest.Url.Query); - NameValueCollection openIdQuery = (postQuery.GetValues("openid.mode") != null ? postQuery : getQuery); - - OpenIdProvider provider = new OpenIdProvider(m_openidStore, providerEndpoint, httpRequest.Url, openIdQuery); - - if (provider.Request != null) - { - if (!provider.Request.IsResponseReady && provider.Request is IAuthenticationRequest) - { - IAuthenticationRequest authRequest = (IAuthenticationRequest)provider.Request; - string[] passwordValues = postQuery.GetValues("pass"); - - UserProfileData profile; - if (TryGetProfile(new Uri(authRequest.ClaimedIdentifier.ToString()), out profile)) - { - // Check for form POST data - if (passwordValues != null && passwordValues.Length == 1) - { - if (profile != null && m_loginService.AuthenticateUser(profile, passwordValues[0])) - authRequest.IsAuthenticated = true; - else - authRequest.IsAuthenticated = false; - } - else - { - // Authentication was requested, send the client a login form - using (StreamWriter writer = new StreamWriter(response)) - writer.Write(String.Format(LOGIN_PAGE, profile.FirstName, profile.SurName)); - return; - } - } - else - { - // Cannot find an avatar matching the claimed identifier - authRequest.IsAuthenticated = false; - } - } - - // Add OpenID headers to the response - foreach (string key in provider.Request.Response.Headers.Keys) - httpResponse.AddHeader(key, provider.Request.Response.Headers[key]); - - string[] contentTypeValues = provider.Request.Response.Headers.GetValues("Content-Type"); - if (contentTypeValues != null && contentTypeValues.Length == 1) - m_contentType = contentTypeValues[0]; - - // Set the response code and document body based on the OpenID result - httpResponse.StatusCode = (int)provider.Request.Response.Code; - response.Write(provider.Request.Response.Body, 0, provider.Request.Response.Body.Length); - response.Close(); - } - else if (httpRequest.Url.AbsolutePath.Contains("/openid/server")) - { - // Standard HTTP GET was made on the OpenID endpoint, send the client the default error page - using (StreamWriter writer = new StreamWriter(response)) - writer.Write(ENDPOINT_PAGE); - } - else - { - // Try and lookup this avatar - UserProfileData profile; - if (TryGetProfile(httpRequest.Url, out profile)) - { - using (StreamWriter writer = new StreamWriter(response)) - { - // TODO: Print out a full profile page for this avatar - writer.Write(String.Format(OPENID_PAGE, httpRequest.Url.Scheme, - httpRequest.Url.Authority, profile.FirstName, profile.SurName)); - } - } - else - { - // Couldn't parse an avatar name, or couldn't find the avatar in the user server - using (StreamWriter writer = new StreamWriter(response)) - writer.Write(INVALID_OPENID_PAGE); - } - } - } - catch (Exception ex) - { - httpResponse.StatusCode = (int)HttpStatusCode.InternalServerError; - using (StreamWriter writer = new StreamWriter(response)) - writer.Write(ex.Message); - } - } - - /// - /// Parse a URL with a relative path of the form /users/First_Last and try to - /// retrieve the profile matching that avatar name - /// - /// URL to parse for an avatar name - /// Profile data for the avatar - /// True if the parse and lookup were successful, otherwise false - bool TryGetProfile(Uri requestUrl, out UserProfileData profile) - { - if (requestUrl.Segments.Length == 3 && requestUrl.Segments[1] == "users/") - { - // Parse the avatar name from the path - string username = requestUrl.Segments[requestUrl.Segments.Length - 1]; - string[] name = username.Split('_'); - - if (name.Length == 2) - { - profile = m_loginService.GetTheUser(name[0], name[1]); - return (profile != null); - } - } - - profile = null; - return false; - } - } -} +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.IO; +using System.Net; +using System.Web; +using DotNetOpenId; +using DotNetOpenId.Provider; +using OpenSim.Framework; +using OpenSim.Framework.Servers; + +namespace OpenSim.Grid.UserServer.Modules +{ + /// + /// Temporary, in-memory store for OpenID associations + /// + public class ProviderMemoryStore : IAssociationStore + { + private class AssociationItem + { + public AssociationRelyingPartyType DistinguishingFactor; + public string Handle; + public DateTime Expires; + public byte[] PrivateData; + } + + Dictionary m_store = new Dictionary(); + SortedList m_sortedStore = new SortedList(); + object m_syncRoot = new object(); + + #region IAssociationStore Members + + public void StoreAssociation(AssociationRelyingPartyType distinguishingFactor, Association assoc) + { + AssociationItem item = new AssociationItem(); + item.DistinguishingFactor = distinguishingFactor; + item.Handle = assoc.Handle; + item.Expires = assoc.Expires.ToLocalTime(); + item.PrivateData = assoc.SerializePrivateData(); + + lock (m_syncRoot) + { + m_store[item.Handle] = item; + m_sortedStore[item.Expires] = item; + } + } + + public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor) + { + lock (m_syncRoot) + { + if (m_sortedStore.Count > 0) + { + AssociationItem item = m_sortedStore.Values[m_sortedStore.Count - 1]; + return Association.Deserialize(item.Handle, item.Expires.ToUniversalTime(), item.PrivateData); + } + else + { + return null; + } + } + } + + public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor, string handle) + { + AssociationItem item; + bool success = false; + lock (m_syncRoot) + success = m_store.TryGetValue(handle, out item); + + if (success) + return Association.Deserialize(item.Handle, item.Expires.ToUniversalTime(), item.PrivateData); + else + return null; + } + + public bool RemoveAssociation(AssociationRelyingPartyType distinguishingFactor, string handle) + { + lock (m_syncRoot) + { + for (int i = 0; i < m_sortedStore.Values.Count; i++) + { + AssociationItem item = m_sortedStore.Values[i]; + if (item.Handle == handle) + { + m_sortedStore.RemoveAt(i); + break; + } + } + + return m_store.Remove(handle); + } + } + + public void ClearExpiredAssociations() + { + lock (m_syncRoot) + { + List itemsCopy = new List(m_sortedStore.Values); + DateTime now = DateTime.Now; + + for (int i = 0; i < itemsCopy.Count; i++) + { + AssociationItem item = itemsCopy[i]; + + if (item.Expires <= now) + { + m_sortedStore.RemoveAt(i); + m_store.Remove(item.Handle); + } + } + } + } + + #endregion + } + + public class OpenIdStreamHandler : IStreamHandler + { + #region HTML + + /// Login form used to authenticate OpenID requests + const string LOGIN_PAGE = +@" +OpenSim OpenID Login + +

OpenSim Login

+
+ + + + +
+ +"; + + /// Page shown for a valid OpenID identity + const string OPENID_PAGE = +@" + +{2} {3} + + +OpenID identifier for {2} {3} + +"; + + /// Page shown for an invalid OpenID identity + const string INVALID_OPENID_PAGE = +@"Identity not found +Invalid OpenID identity"; + + /// Page shown if the OpenID endpoint is requested directly + const string ENDPOINT_PAGE = +@"OpenID Endpoint +This is an OpenID server endpoint, not a human-readable resource. +For more information, see http://openid.net/. +"; + + #endregion HTML + + public string ContentType { get { return m_contentType; } } + public string HttpMethod { get { return m_httpMethod; } } + public string Path { get { return m_path; } } + + string m_contentType; + string m_httpMethod; + string m_path; + UserLoginService m_loginService; + ProviderMemoryStore m_openidStore = new ProviderMemoryStore(); + + /// + /// Constructor + /// + public OpenIdStreamHandler(string httpMethod, string path, UserLoginService loginService) + { + m_loginService = loginService; + m_httpMethod = httpMethod; + m_path = path; + + m_contentType = "text/html"; + } + + /// + /// Handles all GET and POST requests for OpenID identifier pages and endpoint + /// server communication + /// + public void Handle(string path, Stream request, Stream response, OSHttpRequest httpRequest, OSHttpResponse httpResponse) + { + Uri providerEndpoint = new Uri(String.Format("{0}://{1}{2}", httpRequest.Url.Scheme, httpRequest.Url.Authority, httpRequest.Url.AbsolutePath)); + + // Defult to returning HTML content + m_contentType = "text/html"; + + try + { + NameValueCollection postQuery = HttpUtility.ParseQueryString(new StreamReader(httpRequest.InputStream).ReadToEnd()); + NameValueCollection getQuery = HttpUtility.ParseQueryString(httpRequest.Url.Query); + NameValueCollection openIdQuery = (postQuery.GetValues("openid.mode") != null ? postQuery : getQuery); + + OpenIdProvider provider = new OpenIdProvider(m_openidStore, providerEndpoint, httpRequest.Url, openIdQuery); + + if (provider.Request != null) + { + if (!provider.Request.IsResponseReady && provider.Request is IAuthenticationRequest) + { + IAuthenticationRequest authRequest = (IAuthenticationRequest)provider.Request; + string[] passwordValues = postQuery.GetValues("pass"); + + UserProfileData profile; + if (TryGetProfile(new Uri(authRequest.ClaimedIdentifier.ToString()), out profile)) + { + // Check for form POST data + if (passwordValues != null && passwordValues.Length == 1) + { + if (profile != null && m_loginService.AuthenticateUser(profile, passwordValues[0])) + authRequest.IsAuthenticated = true; + else + authRequest.IsAuthenticated = false; + } + else + { + // Authentication was requested, send the client a login form + using (StreamWriter writer = new StreamWriter(response)) + writer.Write(String.Format(LOGIN_PAGE, profile.FirstName, profile.SurName)); + return; + } + } + else + { + // Cannot find an avatar matching the claimed identifier + authRequest.IsAuthenticated = false; + } + } + + // Add OpenID headers to the response + foreach (string key in provider.Request.Response.Headers.Keys) + httpResponse.AddHeader(key, provider.Request.Response.Headers[key]); + + string[] contentTypeValues = provider.Request.Response.Headers.GetValues("Content-Type"); + if (contentTypeValues != null && contentTypeValues.Length == 1) + m_contentType = contentTypeValues[0]; + + // Set the response code and document body based on the OpenID result + httpResponse.StatusCode = (int)provider.Request.Response.Code; + response.Write(provider.Request.Response.Body, 0, provider.Request.Response.Body.Length); + response.Close(); + } + else if (httpRequest.Url.AbsolutePath.Contains("/openid/server")) + { + // Standard HTTP GET was made on the OpenID endpoint, send the client the default error page + using (StreamWriter writer = new StreamWriter(response)) + writer.Write(ENDPOINT_PAGE); + } + else + { + // Try and lookup this avatar + UserProfileData profile; + if (TryGetProfile(httpRequest.Url, out profile)) + { + using (StreamWriter writer = new StreamWriter(response)) + { + // TODO: Print out a full profile page for this avatar + writer.Write(String.Format(OPENID_PAGE, httpRequest.Url.Scheme, + httpRequest.Url.Authority, profile.FirstName, profile.SurName)); + } + } + else + { + // Couldn't parse an avatar name, or couldn't find the avatar in the user server + using (StreamWriter writer = new StreamWriter(response)) + writer.Write(INVALID_OPENID_PAGE); + } + } + } + catch (Exception ex) + { + httpResponse.StatusCode = (int)HttpStatusCode.InternalServerError; + using (StreamWriter writer = new StreamWriter(response)) + writer.Write(ex.Message); + } + } + + /// + /// Parse a URL with a relative path of the form /users/First_Last and try to + /// retrieve the profile matching that avatar name + /// + /// URL to parse for an avatar name + /// Profile data for the avatar + /// True if the parse and lookup were successful, otherwise false + bool TryGetProfile(Uri requestUrl, out UserProfileData profile) + { + if (requestUrl.Segments.Length == 3 && requestUrl.Segments[1] == "users/") + { + // Parse the avatar name from the path + string username = requestUrl.Segments[requestUrl.Segments.Length - 1]; + string[] name = username.Split('_'); + + if (name.Length == 2) + { + profile = m_loginService.GetTheUser(name[0], name[1]); + return (profile != null); + } + } + + profile = null; + return false; + } + } +} diff --git a/OpenSim/Grid/UserServer.Modules/UserDataBaseService.cs b/OpenSim/Grid/UserServer.Modules/UserDataBaseService.cs index ef59cac..80f2f7b 100644 --- a/OpenSim/Grid/UserServer.Modules/UserDataBaseService.cs +++ b/OpenSim/Grid/UserServer.Modules/UserDataBaseService.cs @@ -1,111 +1,111 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using log4net; -using Nwc.XmlRpc; -using OpenMetaverse; -using OpenSim.Framework; -using OpenSim.Framework.Communications; -using OpenSim.Framework.Servers; -using OpenSim.Grid.Framework; - -namespace OpenSim.Grid.UserServer.Modules -{ - public class UserDataBaseService : UserManagerBase - { - protected IUGAIMCore m_core; - - public UserDataBaseService() - : base(null) - { - } - - public UserDataBaseService(IInterServiceInventoryServices interServiceInventoryService) - : base(interServiceInventoryService) - { - } - - public void Initialise(IUGAIMCore core) - { - m_core = core; - - //we only need core components so we can request them from here - IInterServiceInventoryServices inventoryService; - if (m_core.TryGet(out inventoryService)) - { - m_interServiceInventoryService = inventoryService; - } - - UserConfig cfg; - if (m_core.TryGet(out cfg)) - { - AddPlugin(cfg.DatabaseProvider, cfg.DatabaseConnect); - } - - m_core.RegisterInterface(this); - } - - public void PostInitialise() - { - } - - public void RegisterHandlers(BaseHttpServer httpServer) - { - } - - public UserAgentData GetUserAgentData(UUID AgentID) - { - UserProfileData userProfile = GetUserProfile(AgentID); - - if (userProfile != null) - { - return userProfile.CurrentAgent; - } - - return null; - } - - public override UserProfileData SetupMasterUser(string firstName, string lastName) - { - throw new Exception("The method or operation is not implemented."); - } - - public override UserProfileData SetupMasterUser(string firstName, string lastName, string password) - { - throw new Exception("The method or operation is not implemented."); - } - - public override UserProfileData SetupMasterUser(UUID uuid) - { - throw new Exception("The method or operation is not implemented."); - } - } -} +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using log4net; +using Nwc.XmlRpc; +using OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Framework.Communications; +using OpenSim.Framework.Servers; +using OpenSim.Grid.Framework; + +namespace OpenSim.Grid.UserServer.Modules +{ + public class UserDataBaseService : UserManagerBase + { + protected IUGAIMCore m_core; + + public UserDataBaseService() + : base(null) + { + } + + public UserDataBaseService(IInterServiceInventoryServices interServiceInventoryService) + : base(interServiceInventoryService) + { + } + + public void Initialise(IUGAIMCore core) + { + m_core = core; + + //we only need core components so we can request them from here + IInterServiceInventoryServices inventoryService; + if (m_core.TryGet(out inventoryService)) + { + m_interServiceInventoryService = inventoryService; + } + + UserConfig cfg; + if (m_core.TryGet(out cfg)) + { + AddPlugin(cfg.DatabaseProvider, cfg.DatabaseConnect); + } + + m_core.RegisterInterface(this); + } + + public void PostInitialise() + { + } + + public void RegisterHandlers(BaseHttpServer httpServer) + { + } + + public UserAgentData GetUserAgentData(UUID AgentID) + { + UserProfileData userProfile = GetUserProfile(AgentID); + + if (userProfile != null) + { + return userProfile.CurrentAgent; + } + + return null; + } + + public override UserProfileData SetupMasterUser(string firstName, string lastName) + { + throw new Exception("The method or operation is not implemented."); + } + + public override UserProfileData SetupMasterUser(string firstName, string lastName, string password) + { + throw new Exception("The method or operation is not implemented."); + } + + public override UserProfileData SetupMasterUser(UUID uuid) + { + throw new Exception("The method or operation is not implemented."); + } + } +} diff --git a/OpenSim/Grid/UserServer.Modules/UserLoginService.cs b/OpenSim/Grid/UserServer.Modules/UserLoginService.cs index 928753f..64ac463 100644 --- a/OpenSim/Grid/UserServer.Modules/UserLoginService.cs +++ b/OpenSim/Grid/UserServer.Modules/UserLoginService.cs @@ -1,600 +1,600 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using System.Text.RegularExpressions; -using log4net; -using Nwc.XmlRpc; -using OpenMetaverse; -using OpenSim.Data; -using OpenSim.Framework; -using OpenSim.Framework.Communications; -using OpenSim.Framework.Communications.Cache; -using OpenSim.Framework.Communications.Capabilities; -using OpenSim.Framework.Servers; - -namespace OpenSim.Grid.UserServer.Modules -{ - public delegate void UserLoggedInAtLocation(UUID agentID, UUID sessionID, UUID RegionID, - ulong regionhandle, float positionX, float positionY, float positionZ, - string firstname, string lastname); - - /// - /// Login service used in grid mode. - /// - public class UserLoginService : LoginService - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - protected IInterServiceInventoryServices m_inventoryService; - - public event UserLoggedInAtLocation OnUserLoggedInAtLocation; - - private UserLoggedInAtLocation handlerUserLoggedInAtLocation; - - public UserConfig m_config; - private readonly IRegionProfileService m_regionProfileService; - - protected BaseHttpServer m_httpServer; - - public UserLoginService( - UserManagerBase userManager, IInterServiceInventoryServices inventoryService, - LibraryRootFolder libraryRootFolder, - UserConfig config, string welcomeMess, IRegionProfileService regionProfileService) - : base(userManager, libraryRootFolder, welcomeMess) - { - m_config = config; - m_inventoryService = inventoryService; - m_regionProfileService = regionProfileService; - } - - public void RegisterHandlers(BaseHttpServer httpServer, bool registerLLSDHandler, bool registerOpenIDHandlers) - { - m_httpServer = httpServer; - - m_httpServer.AddXmlRPCHandler("login_to_simulator", XmlRpcLoginMethod); - m_httpServer.AddHTTPHandler("login", ProcessHTMLLogin); - m_httpServer.AddXmlRPCHandler("set_login_params", XmlRPCSetLoginParams); - - if (registerLLSDHandler) - { - m_httpServer.SetDefaultLLSDHandler(LLSDLoginMethod); - } - - if (registerOpenIDHandlers) - { - // Handler for OpenID avatar identity pages - m_httpServer.AddStreamHandler(new OpenIdStreamHandler("GET", "/users/", this)); - // Handlers for the OpenID endpoint server - m_httpServer.AddStreamHandler(new OpenIdStreamHandler("POST", "/openid/server/", this)); - m_httpServer.AddStreamHandler(new OpenIdStreamHandler("GET", "/openid/server/", this)); - } - } - - public void setloginlevel(int level) - { - m_minLoginLevel = level; - m_log.InfoFormat("[GRID]: Login Level set to {0} ", level); - } - public void setwelcometext(string text) - { - m_welcomeMessage = text; - m_log.InfoFormat("[GRID]: Login text set to {0} ", text); - } - - public override void LogOffUser(UserProfileData theUser, string message) - { - RegionProfileData SimInfo; - try - { - SimInfo = m_regionProfileService.RequestSimProfileData( - theUser.CurrentAgent.Handle, m_config.GridServerURL, - m_config.GridSendKey, m_config.GridRecvKey); - - if (SimInfo == null) - { - m_log.Error("[GRID]: Region user was in isn't currently logged in"); - return; - } - } - catch (Exception) - { - m_log.Error("[GRID]: Unable to look up region to log user off"); - return; - } - - // Prepare notification - Hashtable SimParams = new Hashtable(); - SimParams["agent_id"] = theUser.ID.ToString(); - SimParams["region_secret"] = theUser.CurrentAgent.SecureSessionID.ToString(); - SimParams["region_secret2"] = SimInfo.regionSecret; - //m_log.Info(SimInfo.regionSecret); - SimParams["regionhandle"] = theUser.CurrentAgent.Handle.ToString(); - SimParams["message"] = message; - ArrayList SendParams = new ArrayList(); - SendParams.Add(SimParams); - - m_log.InfoFormat( - "[ASSUMED CRASH]: Telling region {0} @ {1},{2} ({3}) that their agent is dead: {4}", - SimInfo.regionName, SimInfo.regionLocX, SimInfo.regionLocY, SimInfo.httpServerURI, - theUser.FirstName + " " + theUser.SurName); - - try - { - XmlRpcRequest GridReq = new XmlRpcRequest("logoff_user", SendParams); - XmlRpcResponse GridResp = GridReq.Send(SimInfo.httpServerURI, 6000); - - if (GridResp.IsFault) - { - m_log.ErrorFormat( - "[LOGIN]: XMLRPC request for {0} failed, fault code: {1}, reason: {2}, This is likely an old region revision.", - SimInfo.httpServerURI, GridResp.FaultCode, GridResp.FaultString); - } - } - catch (Exception) - { - m_log.Error("[LOGIN]: Error telling region to logout user!"); - } - - // Prepare notification - SimParams = new Hashtable(); - SimParams["agent_id"] = theUser.ID.ToString(); - SimParams["region_secret"] = SimInfo.regionSecret; - //m_log.Info(SimInfo.regionSecret); - SimParams["regionhandle"] = theUser.CurrentAgent.Handle.ToString(); - SimParams["message"] = message; - SendParams = new ArrayList(); - SendParams.Add(SimParams); - - m_log.InfoFormat( - "[ASSUMED CRASH]: Telling region {0} @ {1},{2} ({3}) that their agent is dead: {4}", - SimInfo.regionName, SimInfo.regionLocX, SimInfo.regionLocY, SimInfo.httpServerURI, - theUser.FirstName + " " + theUser.SurName); - - try - { - XmlRpcRequest GridReq = new XmlRpcRequest("logoff_user", SendParams); - XmlRpcResponse GridResp = GridReq.Send(SimInfo.httpServerURI, 6000); - - if (GridResp.IsFault) - { - m_log.ErrorFormat( - "[LOGIN]: XMLRPC request for {0} failed, fault code: {1}, reason: {2}, This is likely an old region revision.", - SimInfo.httpServerURI, GridResp.FaultCode, GridResp.FaultString); - } - } - catch (Exception) - { - m_log.Error("[LOGIN]: Error telling region to logout user!"); - } - //base.LogOffUser(theUser); - } - - /// - /// Customises the login response and fills in missing values. - /// - /// The existing response - /// The user profile - /// The requested start location - public override bool CustomiseResponse(LoginResponse response, UserProfileData theUser, string startLocationRequest) - { - // add active gestures to login-response - AddActiveGestures(response, theUser); - - // HomeLocation - RegionProfileData homeInfo = null; - // use the homeRegionID if it is stored already. If not, use the regionHandle as before - UUID homeRegionId = theUser.HomeRegionID; - ulong homeRegionHandle = theUser.HomeRegion; - if (homeRegionId != UUID.Zero) - { - homeInfo = GetRegionInfo(homeRegionId); - } - else - { - homeInfo = GetRegionInfo(homeRegionHandle); - } - - if (homeInfo != null) - { - response.Home = - string.Format( - "{{'region_handle':[r{0},r{1}], 'position':[r{2},r{3},r{4}], 'look_at':[r{5},r{6},r{7}]}}", - (homeInfo.regionLocX*Constants.RegionSize), - (homeInfo.regionLocY*Constants.RegionSize), - theUser.HomeLocation.X, theUser.HomeLocation.Y, theUser.HomeLocation.Z, - theUser.HomeLookAt.X, theUser.HomeLookAt.Y, theUser.HomeLookAt.Z); - } - else - { - // Emergency mode: Home-region isn't available, so we can't request the region info. - // Use the stored home regionHandle instead. - // NOTE: If the home-region moves, this will be wrong until the users update their user-profile again - ulong regionX = homeRegionHandle >> 32; - ulong regionY = homeRegionHandle & 0xffffffff; - response.Home = - string.Format( - "{{'region_handle':[r{0},r{1}], 'position':[r{2},r{3},r{4}], 'look_at':[r{5},r{6},r{7}]}}", - regionX, regionY, - theUser.HomeLocation.X, theUser.HomeLocation.Y, theUser.HomeLocation.Z, - theUser.HomeLookAt.X, theUser.HomeLookAt.Y, theUser.HomeLookAt.Z); - m_log.InfoFormat("[LOGIN] Home region of user {0} {1} is not available; using computed region position {2} {3}", - theUser.FirstName, theUser.SurName, - regionX, regionY); - } - - // StartLocation - RegionProfileData regionInfo = null; - if (startLocationRequest == "home") - { - regionInfo = homeInfo; - theUser.CurrentAgent.Position = theUser.HomeLocation; - response.LookAt = "[r" + theUser.HomeLookAt.X.ToString() + ",r" + theUser.HomeLookAt.Y.ToString() + ",r" + theUser.HomeLookAt.Z.ToString() + "]"; - } - else if (startLocationRequest == "last") - { - UUID lastRegion = theUser.CurrentAgent.Region; - regionInfo = GetRegionInfo(lastRegion); - response.LookAt = "[r" + theUser.CurrentAgent.LookAt.X.ToString() + ",r" + theUser.CurrentAgent.LookAt.Y.ToString() + ",r" + theUser.CurrentAgent.LookAt.Z.ToString() + "]"; - } - else - { - Regex reURI = new Regex(@"^uri:(?[^&]+)&(?\d+)&(?\d+)&(?\d+)$"); - Match uriMatch = reURI.Match(startLocationRequest); - if (uriMatch == null) - { - m_log.InfoFormat("[LOGIN]: Got Custom Login URL {0}, but can't process it", startLocationRequest); - } - else - { - string region = uriMatch.Groups["region"].ToString(); - regionInfo = RequestClosestRegion(region); - if (regionInfo == null) - { - m_log.InfoFormat("[LOGIN]: Got Custom Login URL {0}, can't locate region {1}", startLocationRequest, region); - } - else - { - theUser.CurrentAgent.Position = new Vector3(float.Parse(uriMatch.Groups["x"].Value), - float.Parse(uriMatch.Groups["y"].Value), float.Parse(uriMatch.Groups["z"].Value)); - } - } - response.LookAt = "[r0,r1,r0]"; - // can be: last, home, safe, url - response.StartLocation = "url"; - } - - if ((regionInfo != null) && (PrepareLoginToRegion(regionInfo, theUser, response))) - { - return true; - } - - // StartLocation not available, send him to a nearby region instead - //regionInfo = RegionProfileData.RequestSimProfileData("", m_config.GridServerURL, m_config.GridSendKey, m_config.GridRecvKey); - //m_log.InfoFormat("[LOGIN]: StartLocation not available sending to region {0}", regionInfo.regionName); - - // Send him to default region instead - // Load information from the gridserver - ulong defaultHandle = (((ulong) m_config.DefaultX * Constants.RegionSize) << 32) | - ((ulong) m_config.DefaultY * Constants.RegionSize); - - if ((regionInfo != null) && (defaultHandle == regionInfo.regionHandle)) - { - m_log.ErrorFormat("[LOGIN]: Not trying the default region since this is the same as the selected region"); - return false; - } - - m_log.Error("[LOGIN]: Sending user to default region " + defaultHandle + " instead"); - regionInfo = GetRegionInfo(defaultHandle); - - // Customise the response - //response.Home = - // string.Format( - // "{{'region_handle':[r{0},r{1}], 'position':[r{2},r{3},r{4}], 'look_at':[r{5},r{6},r{7}]}}", - // (SimInfo.regionLocX * Constants.RegionSize), - // (SimInfo.regionLocY*Constants.RegionSize), - // theUser.HomeLocation.X, theUser.HomeLocation.Y, theUser.HomeLocation.Z, - // theUser.HomeLookAt.X, theUser.HomeLookAt.Y, theUser.HomeLookAt.Z); - theUser.CurrentAgent.Position = new Vector3(128,128,0); - response.StartLocation = "safe"; - - return PrepareLoginToRegion(regionInfo, theUser, response); - } - - protected RegionProfileData RequestClosestRegion(string region) - { - return m_regionProfileService.RequestSimProfileData(region, - m_config.GridServerURL, m_config.GridSendKey, m_config.GridRecvKey); - } - - protected RegionProfileData GetRegionInfo(ulong homeRegionHandle) - { - return m_regionProfileService.RequestSimProfileData(homeRegionHandle, - m_config.GridServerURL, m_config.GridSendKey, - m_config.GridRecvKey); - } - - protected RegionProfileData GetRegionInfo(UUID homeRegionId) - { - return m_regionProfileService.RequestSimProfileData(homeRegionId, - m_config.GridServerURL, m_config.GridSendKey, - m_config.GridRecvKey); - } - - /// - /// Add active gestures of the user to the login response. - /// - /// - /// A - /// - /// - /// A - /// - private void AddActiveGestures(LoginResponse response, UserProfileData theUser) - { - List gestures = m_inventoryService.GetActiveGestures(theUser.ID); - //m_log.DebugFormat("[LOGIN]: AddActiveGestures, found {0}", gestures == null ? 0 : gestures.Count); - ArrayList list = new ArrayList(); - if (gestures != null) - { - foreach (InventoryItemBase gesture in gestures) - { - Hashtable item = new Hashtable(); - item["item_id"] = gesture.ID.ToString(); - item["asset_id"] = gesture.AssetID.ToString(); - list.Add(item); - } - } - response.ActiveGestures = list; - } - - /// - /// Prepare a login to the given region. This involves both telling the region to expect a connection - /// and appropriately customising the response to the user. - /// - /// - /// - /// - /// true if the region was successfully contacted, false otherwise - private bool PrepareLoginToRegion(RegionProfileData regionInfo, UserProfileData user, LoginResponse response) - { - try - { - response.SimAddress = Util.GetHostFromURL(regionInfo.serverURI).ToString(); - response.SimPort = uint.Parse(regionInfo.serverURI.Split(new char[] { '/', ':' })[4]); - response.RegionX = regionInfo.regionLocX; - response.RegionY = regionInfo.regionLocY; - - string capsPath = CapsUtil.GetRandomCapsObjectPath(); - - // Take off trailing / so that the caps path isn't //CAPS/someUUID - if (regionInfo.httpServerURI.EndsWith("/")) - regionInfo.httpServerURI = regionInfo.httpServerURI.Substring(0, regionInfo.httpServerURI.Length - 1); - response.SeedCapability = regionInfo.httpServerURI + CapsUtil.GetCapsSeedPath(capsPath); - - // Notify the target of an incoming user - m_log.InfoFormat( - "[LOGIN]: Telling {0} @ {1},{2} ({3}) to prepare for client connection", - regionInfo.regionName, response.RegionX, response.RegionY, regionInfo.httpServerURI); - - // Update agent with target sim - user.CurrentAgent.Region = regionInfo.UUID; - user.CurrentAgent.Handle = regionInfo.regionHandle; - - // Prepare notification - Hashtable loginParams = new Hashtable(); - loginParams["session_id"] = user.CurrentAgent.SessionID.ToString(); - loginParams["secure_session_id"] = user.CurrentAgent.SecureSessionID.ToString(); - loginParams["firstname"] = user.FirstName; - loginParams["lastname"] = user.SurName; - loginParams["agent_id"] = user.ID.ToString(); - loginParams["circuit_code"] = (Int32) Convert.ToUInt32(response.CircuitCode); - loginParams["startpos_x"] = user.CurrentAgent.Position.X.ToString(); - loginParams["startpos_y"] = user.CurrentAgent.Position.Y.ToString(); - loginParams["startpos_z"] = user.CurrentAgent.Position.Z.ToString(); - loginParams["regionhandle"] = user.CurrentAgent.Handle.ToString(); - loginParams["caps_path"] = capsPath; - - // Get appearance - AvatarAppearance appearance = m_userManager.GetUserAppearance(user.ID); - if (appearance != null) - { - loginParams["appearance"] = appearance.ToHashTable(); - m_log.DebugFormat("[LOGIN]: Found appearance for {0} {1}", user.FirstName, user.SurName); - } - else - { - m_log.DebugFormat("[LOGIN]: Appearance not for {0} {1}. Creating default.", user.FirstName, user.SurName); - appearance = new AvatarAppearance(user.ID); - } - - ArrayList SendParams = new ArrayList(); - SendParams.Add(loginParams); - - // Send - XmlRpcRequest GridReq = new XmlRpcRequest("expect_user", SendParams); - XmlRpcResponse GridResp = GridReq.Send(regionInfo.httpServerURI, 6000); - - if (!GridResp.IsFault) - { - bool responseSuccess = true; - - if (GridResp.Value != null) - { - Hashtable resp = (Hashtable) GridResp.Value; - if (resp.ContainsKey("success")) - { - if ((string) resp["success"] == "FALSE") - { - responseSuccess = false; - } - } - } - if (responseSuccess) - { - handlerUserLoggedInAtLocation = OnUserLoggedInAtLocation; - if (handlerUserLoggedInAtLocation != null) - { - handlerUserLoggedInAtLocation(user.ID, user.CurrentAgent.SessionID, - user.CurrentAgent.Region, - user.CurrentAgent.Handle, - user.CurrentAgent.Position.X, - user.CurrentAgent.Position.Y, - user.CurrentAgent.Position.Z, - user.FirstName, user.SurName); - } - } - else - { - m_log.ErrorFormat("[LOGIN]: Region responded that it is not available to receive clients"); - return false; - } - } - else - { - m_log.ErrorFormat("[LOGIN]: XmlRpc request to region failed with message {0}, code {1} ", GridResp.FaultString, GridResp.FaultCode); - return false; - } - } - catch (Exception e) - { - m_log.ErrorFormat("[LOGIN]: Region not available for login, {0}", e); - return false; - } - - return true; - } - - // See LoginService - protected override InventoryData GetInventorySkeleton(UUID userID) - { - m_log.DebugFormat( - "[LOGIN]: Contacting inventory service at {0} for inventory skeleton of user {1}", - m_config.InventoryUrl, userID); - - List folders = m_inventoryService.GetInventorySkeleton(userID); - - if (null == folders || folders.Count == 0) - { - m_log.InfoFormat( - "[LOGIN]: A root inventory folder for user {0} was not found. Requesting creation.", userID); - - // Although the create user function creates a new agent inventory along with a new user profile, some - // tools are creating the user profile directly in the database without creating the inventory. At - // this time we'll accomodate them by lazily creating the user inventory now if it doesn't already - // exist. - if (!m_inventoryService.CreateNewUserInventory(userID)) - { - throw new Exception( - String.Format( - "The inventory creation request for user {0} did not succeed." - + " Please contact your inventory service provider for more information.", - userID)); - } - m_log.InfoFormat("[LOGIN]: A new inventory skeleton was successfully created for user {0}", userID); - - folders = m_inventoryService.GetInventorySkeleton(userID); - } - - if (folders != null && folders.Count > 0) - { - UUID rootID = UUID.Zero; - ArrayList AgentInventoryArray = new ArrayList(); - Hashtable TempHash; - - foreach (InventoryFolderBase InvFolder in folders) - { -// m_log.DebugFormat("[LOGIN]: Received agent inventory folder {0}", InvFolder.name); - - if (InvFolder.ParentID == UUID.Zero) - { - rootID = InvFolder.ID; - } - TempHash = new Hashtable(); - TempHash["name"] = InvFolder.Name; - TempHash["parent_id"] = InvFolder.ParentID.ToString(); - TempHash["version"] = (Int32) InvFolder.Version; - TempHash["type_default"] = (Int32) InvFolder.Type; - TempHash["folder_id"] = InvFolder.ID.ToString(); - AgentInventoryArray.Add(TempHash); - } - - return new InventoryData(AgentInventoryArray, rootID); - } - throw new Exception( - String.Format( - "A root inventory folder for user {0} could not be retrieved from the inventory service", - userID)); - } - - public XmlRpcResponse XmlRPCSetLoginParams(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable) request.Params[0]; - UserProfileData userProfile; - Hashtable responseData = new Hashtable(); - - UUID uid; - string pass = requestData["password"].ToString(); - - if (!UUID.TryParse((string) requestData["avatar_uuid"], out uid)) - { - responseData["error"] = "No authorization"; - response.Value = responseData; - return response; - } - - userProfile = m_userManager.GetUserProfile(uid); - - if (userProfile == null || - (!AuthenticateUser(userProfile, pass)) || - userProfile.GodLevel < 200) - { - responseData["error"] = "No authorization"; - response.Value = responseData; - return response; - } - - if (requestData.ContainsKey("login_level")) - { - m_minLoginLevel = Convert.ToInt32(requestData["login_level"]); - } - - if (requestData.ContainsKey("login_motd")) - { - m_welcomeMessage = requestData["login_motd"].ToString(); - } - - response.Value = responseData; - return response; - } - - } -} +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using System.Text.RegularExpressions; +using log4net; +using Nwc.XmlRpc; +using OpenMetaverse; +using OpenSim.Data; +using OpenSim.Framework; +using OpenSim.Framework.Communications; +using OpenSim.Framework.Communications.Cache; +using OpenSim.Framework.Communications.Capabilities; +using OpenSim.Framework.Servers; + +namespace OpenSim.Grid.UserServer.Modules +{ + public delegate void UserLoggedInAtLocation(UUID agentID, UUID sessionID, UUID RegionID, + ulong regionhandle, float positionX, float positionY, float positionZ, + string firstname, string lastname); + + /// + /// Login service used in grid mode. + /// + public class UserLoginService : LoginService + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + protected IInterServiceInventoryServices m_inventoryService; + + public event UserLoggedInAtLocation OnUserLoggedInAtLocation; + + private UserLoggedInAtLocation handlerUserLoggedInAtLocation; + + public UserConfig m_config; + private readonly IRegionProfileService m_regionProfileService; + + protected BaseHttpServer m_httpServer; + + public UserLoginService( + UserManagerBase userManager, IInterServiceInventoryServices inventoryService, + LibraryRootFolder libraryRootFolder, + UserConfig config, string welcomeMess, IRegionProfileService regionProfileService) + : base(userManager, libraryRootFolder, welcomeMess) + { + m_config = config; + m_inventoryService = inventoryService; + m_regionProfileService = regionProfileService; + } + + public void RegisterHandlers(BaseHttpServer httpServer, bool registerLLSDHandler, bool registerOpenIDHandlers) + { + m_httpServer = httpServer; + + m_httpServer.AddXmlRPCHandler("login_to_simulator", XmlRpcLoginMethod); + m_httpServer.AddHTTPHandler("login", ProcessHTMLLogin); + m_httpServer.AddXmlRPCHandler("set_login_params", XmlRPCSetLoginParams); + + if (registerLLSDHandler) + { + m_httpServer.SetDefaultLLSDHandler(LLSDLoginMethod); + } + + if (registerOpenIDHandlers) + { + // Handler for OpenID avatar identity pages + m_httpServer.AddStreamHandler(new OpenIdStreamHandler("GET", "/users/", this)); + // Handlers for the OpenID endpoint server + m_httpServer.AddStreamHandler(new OpenIdStreamHandler("POST", "/openid/server/", this)); + m_httpServer.AddStreamHandler(new OpenIdStreamHandler("GET", "/openid/server/", this)); + } + } + + public void setloginlevel(int level) + { + m_minLoginLevel = level; + m_log.InfoFormat("[GRID]: Login Level set to {0} ", level); + } + public void setwelcometext(string text) + { + m_welcomeMessage = text; + m_log.InfoFormat("[GRID]: Login text set to {0} ", text); + } + + public override void LogOffUser(UserProfileData theUser, string message) + { + RegionProfileData SimInfo; + try + { + SimInfo = m_regionProfileService.RequestSimProfileData( + theUser.CurrentAgent.Handle, m_config.GridServerURL, + m_config.GridSendKey, m_config.GridRecvKey); + + if (SimInfo == null) + { + m_log.Error("[GRID]: Region user was in isn't currently logged in"); + return; + } + } + catch (Exception) + { + m_log.Error("[GRID]: Unable to look up region to log user off"); + return; + } + + // Prepare notification + Hashtable SimParams = new Hashtable(); + SimParams["agent_id"] = theUser.ID.ToString(); + SimParams["region_secret"] = theUser.CurrentAgent.SecureSessionID.ToString(); + SimParams["region_secret2"] = SimInfo.regionSecret; + //m_log.Info(SimInfo.regionSecret); + SimParams["regionhandle"] = theUser.CurrentAgent.Handle.ToString(); + SimParams["message"] = message; + ArrayList SendParams = new ArrayList(); + SendParams.Add(SimParams); + + m_log.InfoFormat( + "[ASSUMED CRASH]: Telling region {0} @ {1},{2} ({3}) that their agent is dead: {4}", + SimInfo.regionName, SimInfo.regionLocX, SimInfo.regionLocY, SimInfo.httpServerURI, + theUser.FirstName + " " + theUser.SurName); + + try + { + XmlRpcRequest GridReq = new XmlRpcRequest("logoff_user", SendParams); + XmlRpcResponse GridResp = GridReq.Send(SimInfo.httpServerURI, 6000); + + if (GridResp.IsFault) + { + m_log.ErrorFormat( + "[LOGIN]: XMLRPC request for {0} failed, fault code: {1}, reason: {2}, This is likely an old region revision.", + SimInfo.httpServerURI, GridResp.FaultCode, GridResp.FaultString); + } + } + catch (Exception) + { + m_log.Error("[LOGIN]: Error telling region to logout user!"); + } + + // Prepare notification + SimParams = new Hashtable(); + SimParams["agent_id"] = theUser.ID.ToString(); + SimParams["region_secret"] = SimInfo.regionSecret; + //m_log.Info(SimInfo.regionSecret); + SimParams["regionhandle"] = theUser.CurrentAgent.Handle.ToString(); + SimParams["message"] = message; + SendParams = new ArrayList(); + SendParams.Add(SimParams); + + m_log.InfoFormat( + "[ASSUMED CRASH]: Telling region {0} @ {1},{2} ({3}) that their agent is dead: {4}", + SimInfo.regionName, SimInfo.regionLocX, SimInfo.regionLocY, SimInfo.httpServerURI, + theUser.FirstName + " " + theUser.SurName); + + try + { + XmlRpcRequest GridReq = new XmlRpcRequest("logoff_user", SendParams); + XmlRpcResponse GridResp = GridReq.Send(SimInfo.httpServerURI, 6000); + + if (GridResp.IsFault) + { + m_log.ErrorFormat( + "[LOGIN]: XMLRPC request for {0} failed, fault code: {1}, reason: {2}, This is likely an old region revision.", + SimInfo.httpServerURI, GridResp.FaultCode, GridResp.FaultString); + } + } + catch (Exception) + { + m_log.Error("[LOGIN]: Error telling region to logout user!"); + } + //base.LogOffUser(theUser); + } + + /// + /// Customises the login response and fills in missing values. + /// + /// The existing response + /// The user profile + /// The requested start location + public override bool CustomiseResponse(LoginResponse response, UserProfileData theUser, string startLocationRequest) + { + // add active gestures to login-response + AddActiveGestures(response, theUser); + + // HomeLocation + RegionProfileData homeInfo = null; + // use the homeRegionID if it is stored already. If not, use the regionHandle as before + UUID homeRegionId = theUser.HomeRegionID; + ulong homeRegionHandle = theUser.HomeRegion; + if (homeRegionId != UUID.Zero) + { + homeInfo = GetRegionInfo(homeRegionId); + } + else + { + homeInfo = GetRegionInfo(homeRegionHandle); + } + + if (homeInfo != null) + { + response.Home = + string.Format( + "{{'region_handle':[r{0},r{1}], 'position':[r{2},r{3},r{4}], 'look_at':[r{5},r{6},r{7}]}}", + (homeInfo.regionLocX*Constants.RegionSize), + (homeInfo.regionLocY*Constants.RegionSize), + theUser.HomeLocation.X, theUser.HomeLocation.Y, theUser.HomeLocation.Z, + theUser.HomeLookAt.X, theUser.HomeLookAt.Y, theUser.HomeLookAt.Z); + } + else + { + // Emergency mode: Home-region isn't available, so we can't request the region info. + // Use the stored home regionHandle instead. + // NOTE: If the home-region moves, this will be wrong until the users update their user-profile again + ulong regionX = homeRegionHandle >> 32; + ulong regionY = homeRegionHandle & 0xffffffff; + response.Home = + string.Format( + "{{'region_handle':[r{0},r{1}], 'position':[r{2},r{3},r{4}], 'look_at':[r{5},r{6},r{7}]}}", + regionX, regionY, + theUser.HomeLocation.X, theUser.HomeLocation.Y, theUser.HomeLocation.Z, + theUser.HomeLookAt.X, theUser.HomeLookAt.Y, theUser.HomeLookAt.Z); + m_log.InfoFormat("[LOGIN] Home region of user {0} {1} is not available; using computed region position {2} {3}", + theUser.FirstName, theUser.SurName, + regionX, regionY); + } + + // StartLocation + RegionProfileData regionInfo = null; + if (startLocationRequest == "home") + { + regionInfo = homeInfo; + theUser.CurrentAgent.Position = theUser.HomeLocation; + response.LookAt = "[r" + theUser.HomeLookAt.X.ToString() + ",r" + theUser.HomeLookAt.Y.ToString() + ",r" + theUser.HomeLookAt.Z.ToString() + "]"; + } + else if (startLocationRequest == "last") + { + UUID lastRegion = theUser.CurrentAgent.Region; + regionInfo = GetRegionInfo(lastRegion); + response.LookAt = "[r" + theUser.CurrentAgent.LookAt.X.ToString() + ",r" + theUser.CurrentAgent.LookAt.Y.ToString() + ",r" + theUser.CurrentAgent.LookAt.Z.ToString() + "]"; + } + else + { + Regex reURI = new Regex(@"^uri:(?[^&]+)&(?\d+)&(?\d+)&(?\d+)$"); + Match uriMatch = reURI.Match(startLocationRequest); + if (uriMatch == null) + { + m_log.InfoFormat("[LOGIN]: Got Custom Login URL {0}, but can't process it", startLocationRequest); + } + else + { + string region = uriMatch.Groups["region"].ToString(); + regionInfo = RequestClosestRegion(region); + if (regionInfo == null) + { + m_log.InfoFormat("[LOGIN]: Got Custom Login URL {0}, can't locate region {1}", startLocationRequest, region); + } + else + { + theUser.CurrentAgent.Position = new Vector3(float.Parse(uriMatch.Groups["x"].Value), + float.Parse(uriMatch.Groups["y"].Value), float.Parse(uriMatch.Groups["z"].Value)); + } + } + response.LookAt = "[r0,r1,r0]"; + // can be: last, home, safe, url + response.StartLocation = "url"; + } + + if ((regionInfo != null) && (PrepareLoginToRegion(regionInfo, theUser, response))) + { + return true; + } + + // StartLocation not available, send him to a nearby region instead + //regionInfo = RegionProfileData.RequestSimProfileData("", m_config.GridServerURL, m_config.GridSendKey, m_config.GridRecvKey); + //m_log.InfoFormat("[LOGIN]: StartLocation not available sending to region {0}", regionInfo.regionName); + + // Send him to default region instead + // Load information from the gridserver + ulong defaultHandle = (((ulong) m_config.DefaultX * Constants.RegionSize) << 32) | + ((ulong) m_config.DefaultY * Constants.RegionSize); + + if ((regionInfo != null) && (defaultHandle == regionInfo.regionHandle)) + { + m_log.ErrorFormat("[LOGIN]: Not trying the default region since this is the same as the selected region"); + return false; + } + + m_log.Error("[LOGIN]: Sending user to default region " + defaultHandle + " instead"); + regionInfo = GetRegionInfo(defaultHandle); + + // Customise the response + //response.Home = + // string.Format( + // "{{'region_handle':[r{0},r{1}], 'position':[r{2},r{3},r{4}], 'look_at':[r{5},r{6},r{7}]}}", + // (SimInfo.regionLocX * Constants.RegionSize), + // (SimInfo.regionLocY*Constants.RegionSize), + // theUser.HomeLocation.X, theUser.HomeLocation.Y, theUser.HomeLocation.Z, + // theUser.HomeLookAt.X, theUser.HomeLookAt.Y, theUser.HomeLookAt.Z); + theUser.CurrentAgent.Position = new Vector3(128,128,0); + response.StartLocation = "safe"; + + return PrepareLoginToRegion(regionInfo, theUser, response); + } + + protected RegionProfileData RequestClosestRegion(string region) + { + return m_regionProfileService.RequestSimProfileData(region, + m_config.GridServerURL, m_config.GridSendKey, m_config.GridRecvKey); + } + + protected RegionProfileData GetRegionInfo(ulong homeRegionHandle) + { + return m_regionProfileService.RequestSimProfileData(homeRegionHandle, + m_config.GridServerURL, m_config.GridSendKey, + m_config.GridRecvKey); + } + + protected RegionProfileData GetRegionInfo(UUID homeRegionId) + { + return m_regionProfileService.RequestSimProfileData(homeRegionId, + m_config.GridServerURL, m_config.GridSendKey, + m_config.GridRecvKey); + } + + /// + /// Add active gestures of the user to the login response. + /// + /// + /// A + /// + /// + /// A + /// + private void AddActiveGestures(LoginResponse response, UserProfileData theUser) + { + List gestures = m_inventoryService.GetActiveGestures(theUser.ID); + //m_log.DebugFormat("[LOGIN]: AddActiveGestures, found {0}", gestures == null ? 0 : gestures.Count); + ArrayList list = new ArrayList(); + if (gestures != null) + { + foreach (InventoryItemBase gesture in gestures) + { + Hashtable item = new Hashtable(); + item["item_id"] = gesture.ID.ToString(); + item["asset_id"] = gesture.AssetID.ToString(); + list.Add(item); + } + } + response.ActiveGestures = list; + } + + /// + /// Prepare a login to the given region. This involves both telling the region to expect a connection + /// and appropriately customising the response to the user. + /// + /// + /// + /// + /// true if the region was successfully contacted, false otherwise + private bool PrepareLoginToRegion(RegionProfileData regionInfo, UserProfileData user, LoginResponse response) + { + try + { + response.SimAddress = Util.GetHostFromURL(regionInfo.serverURI).ToString(); + response.SimPort = uint.Parse(regionInfo.serverURI.Split(new char[] { '/', ':' })[4]); + response.RegionX = regionInfo.regionLocX; + response.RegionY = regionInfo.regionLocY; + + string capsPath = CapsUtil.GetRandomCapsObjectPath(); + + // Take off trailing / so that the caps path isn't //CAPS/someUUID + if (regionInfo.httpServerURI.EndsWith("/")) + regionInfo.httpServerURI = regionInfo.httpServerURI.Substring(0, regionInfo.httpServerURI.Length - 1); + response.SeedCapability = regionInfo.httpServerURI + CapsUtil.GetCapsSeedPath(capsPath); + + // Notify the target of an incoming user + m_log.InfoFormat( + "[LOGIN]: Telling {0} @ {1},{2} ({3}) to prepare for client connection", + regionInfo.regionName, response.RegionX, response.RegionY, regionInfo.httpServerURI); + + // Update agent with target sim + user.CurrentAgent.Region = regionInfo.UUID; + user.CurrentAgent.Handle = regionInfo.regionHandle; + + // Prepare notification + Hashtable loginParams = new Hashtable(); + loginParams["session_id"] = user.CurrentAgent.SessionID.ToString(); + loginParams["secure_session_id"] = user.CurrentAgent.SecureSessionID.ToString(); + loginParams["firstname"] = user.FirstName; + loginParams["lastname"] = user.SurName; + loginParams["agent_id"] = user.ID.ToString(); + loginParams["circuit_code"] = (Int32) Convert.ToUInt32(response.CircuitCode); + loginParams["startpos_x"] = user.CurrentAgent.Position.X.ToString(); + loginParams["startpos_y"] = user.CurrentAgent.Position.Y.ToString(); + loginParams["startpos_z"] = user.CurrentAgent.Position.Z.ToString(); + loginParams["regionhandle"] = user.CurrentAgent.Handle.ToString(); + loginParams["caps_path"] = capsPath; + + // Get appearance + AvatarAppearance appearance = m_userManager.GetUserAppearance(user.ID); + if (appearance != null) + { + loginParams["appearance"] = appearance.ToHashTable(); + m_log.DebugFormat("[LOGIN]: Found appearance for {0} {1}", user.FirstName, user.SurName); + } + else + { + m_log.DebugFormat("[LOGIN]: Appearance not for {0} {1}. Creating default.", user.FirstName, user.SurName); + appearance = new AvatarAppearance(user.ID); + } + + ArrayList SendParams = new ArrayList(); + SendParams.Add(loginParams); + + // Send + XmlRpcRequest GridReq = new XmlRpcRequest("expect_user", SendParams); + XmlRpcResponse GridResp = GridReq.Send(regionInfo.httpServerURI, 6000); + + if (!GridResp.IsFault) + { + bool responseSuccess = true; + + if (GridResp.Value != null) + { + Hashtable resp = (Hashtable) GridResp.Value; + if (resp.ContainsKey("success")) + { + if ((string) resp["success"] == "FALSE") + { + responseSuccess = false; + } + } + } + if (responseSuccess) + { + handlerUserLoggedInAtLocation = OnUserLoggedInAtLocation; + if (handlerUserLoggedInAtLocation != null) + { + handlerUserLoggedInAtLocation(user.ID, user.CurrentAgent.SessionID, + user.CurrentAgent.Region, + user.CurrentAgent.Handle, + user.CurrentAgent.Position.X, + user.CurrentAgent.Position.Y, + user.CurrentAgent.Position.Z, + user.FirstName, user.SurName); + } + } + else + { + m_log.ErrorFormat("[LOGIN]: Region responded that it is not available to receive clients"); + return false; + } + } + else + { + m_log.ErrorFormat("[LOGIN]: XmlRpc request to region failed with message {0}, code {1} ", GridResp.FaultString, GridResp.FaultCode); + return false; + } + } + catch (Exception e) + { + m_log.ErrorFormat("[LOGIN]: Region not available for login, {0}", e); + return false; + } + + return true; + } + + // See LoginService + protected override InventoryData GetInventorySkeleton(UUID userID) + { + m_log.DebugFormat( + "[LOGIN]: Contacting inventory service at {0} for inventory skeleton of user {1}", + m_config.InventoryUrl, userID); + + List folders = m_inventoryService.GetInventorySkeleton(userID); + + if (null == folders || folders.Count == 0) + { + m_log.InfoFormat( + "[LOGIN]: A root inventory folder for user {0} was not found. Requesting creation.", userID); + + // Although the create user function creates a new agent inventory along with a new user profile, some + // tools are creating the user profile directly in the database without creating the inventory. At + // this time we'll accomodate them by lazily creating the user inventory now if it doesn't already + // exist. + if (!m_inventoryService.CreateNewUserInventory(userID)) + { + throw new Exception( + String.Format( + "The inventory creation request for user {0} did not succeed." + + " Please contact your inventory service provider for more information.", + userID)); + } + m_log.InfoFormat("[LOGIN]: A new inventory skeleton was successfully created for user {0}", userID); + + folders = m_inventoryService.GetInventorySkeleton(userID); + } + + if (folders != null && folders.Count > 0) + { + UUID rootID = UUID.Zero; + ArrayList AgentInventoryArray = new ArrayList(); + Hashtable TempHash; + + foreach (InventoryFolderBase InvFolder in folders) + { +// m_log.DebugFormat("[LOGIN]: Received agent inventory folder {0}", InvFolder.name); + + if (InvFolder.ParentID == UUID.Zero) + { + rootID = InvFolder.ID; + } + TempHash = new Hashtable(); + TempHash["name"] = InvFolder.Name; + TempHash["parent_id"] = InvFolder.ParentID.ToString(); + TempHash["version"] = (Int32) InvFolder.Version; + TempHash["type_default"] = (Int32) InvFolder.Type; + TempHash["folder_id"] = InvFolder.ID.ToString(); + AgentInventoryArray.Add(TempHash); + } + + return new InventoryData(AgentInventoryArray, rootID); + } + throw new Exception( + String.Format( + "A root inventory folder for user {0} could not be retrieved from the inventory service", + userID)); + } + + public XmlRpcResponse XmlRPCSetLoginParams(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable) request.Params[0]; + UserProfileData userProfile; + Hashtable responseData = new Hashtable(); + + UUID uid; + string pass = requestData["password"].ToString(); + + if (!UUID.TryParse((string) requestData["avatar_uuid"], out uid)) + { + responseData["error"] = "No authorization"; + response.Value = responseData; + return response; + } + + userProfile = m_userManager.GetUserProfile(uid); + + if (userProfile == null || + (!AuthenticateUser(userProfile, pass)) || + userProfile.GodLevel < 200) + { + responseData["error"] = "No authorization"; + response.Value = responseData; + return response; + } + + if (requestData.ContainsKey("login_level")) + { + m_minLoginLevel = Convert.ToInt32(requestData["login_level"]); + } + + if (requestData.ContainsKey("login_motd")) + { + m_welcomeMessage = requestData["login_motd"].ToString(); + } + + response.Value = responseData; + return response; + } + + } +} diff --git a/OpenSim/Grid/UserServer.Modules/UserManager.cs b/OpenSim/Grid/UserServer.Modules/UserManager.cs index dd9f495..c6c3a1a 100644 --- a/OpenSim/Grid/UserServer.Modules/UserManager.cs +++ b/OpenSim/Grid/UserServer.Modules/UserManager.cs @@ -1,686 +1,686 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using log4net; -using Nwc.XmlRpc; -using OpenMetaverse; -using OpenSim.Framework; -using OpenSim.Framework.Communications; -using OpenSim.Framework.Servers; - -namespace OpenSim.Grid.UserServer.Modules -{ - public delegate void logOffUser(UUID AgentID); - - public class UserManager - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - public event logOffUser OnLogOffUser; - private logOffUser handlerLogOffUser; - - private UserDataBaseService m_userDataBaseService; - private BaseHttpServer m_httpServer; - - /// - /// - /// - /// - public UserManager( UserDataBaseService userDataBaseService) - { - m_userDataBaseService = userDataBaseService; - } - - public void Initialise() - { - - } - - public void PostInitialise() - { - - } - - public void RegisterHandlers(BaseHttpServer httpServer) - { - m_httpServer = httpServer; - - m_httpServer.AddXmlRPCHandler("get_user_by_name", XmlRPCGetUserMethodName); - m_httpServer.AddXmlRPCHandler("get_user_by_uuid", XmlRPCGetUserMethodUUID); - m_httpServer.AddXmlRPCHandler("get_avatar_picker_avatar", XmlRPCGetAvatarPickerAvatar); - - m_httpServer.AddXmlRPCHandler("update_user_current_region", XmlRPCAtRegion); - m_httpServer.AddXmlRPCHandler("logout_of_simulator", XmlRPCLogOffUserMethodUUID); - m_httpServer.AddXmlRPCHandler("get_agent_by_uuid", XmlRPCGetAgentMethodUUID); - m_httpServer.AddXmlRPCHandler("check_auth_session", XmlRPCCheckAuthSession); - - m_httpServer.AddXmlRPCHandler("update_user_profile", XmlRpcResponseXmlRPCUpdateUserProfile); - - m_httpServer.AddStreamHandler(new RestStreamHandler("DELETE", "/usersessions/", RestDeleteUserSessionMethod)); - } - - /// - /// Deletes an active agent session - /// - /// The request - /// The path (eg /bork/narf/test) - /// Parameters sent - /// HTTP request header object - /// HTTP response header object - /// Success "OK" else error - public string RestDeleteUserSessionMethod(string request, string path, string param, - OSHttpRequest httpRequest, OSHttpResponse httpResponse) - { - // TODO! Important! - - return "OK"; - } - - /// - /// Returns an error message that the user could not be found in the database - /// - /// XML string consisting of a error element containing individual error(s) - public XmlRpcResponse CreateUnknownUserErrorResponse() - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable responseData = new Hashtable(); - responseData["error_type"] = "unknown_user"; - responseData["error_desc"] = "The user requested is not in the database"; - - response.Value = responseData; - return response; - } - - public XmlRpcResponse AvatarPickerListtoXmlRPCResponse(UUID queryID, List returnUsers) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable responseData = new Hashtable(); - // Query Result Information - responseData["queryid"] = queryID.ToString(); - responseData["avcount"] = returnUsers.Count.ToString(); - - for (int i = 0; i < returnUsers.Count; i++) - { - responseData["avatarid" + i] = returnUsers[i].AvatarID.ToString(); - responseData["firstname" + i] = returnUsers[i].firstName; - responseData["lastname" + i] = returnUsers[i].lastName; - } - response.Value = responseData; - - return response; - } - - /// - /// Converts a user profile to an XML element which can be returned - /// - /// The user profile - /// A string containing an XML Document of the user profile - public XmlRpcResponse ProfileToXmlRPCResponse(UserProfileData profile) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable responseData = new Hashtable(); - - // Account information - responseData["firstname"] = profile.FirstName; - responseData["lastname"] = profile.SurName; - responseData["uuid"] = profile.ID.ToString(); - // Server Information - responseData["server_inventory"] = profile.UserInventoryURI; - responseData["server_asset"] = profile.UserAssetURI; - // Profile Information - responseData["profile_about"] = profile.AboutText; - responseData["profile_firstlife_about"] = profile.FirstLifeAboutText; - responseData["profile_firstlife_image"] = profile.FirstLifeImage.ToString(); - responseData["profile_can_do"] = profile.CanDoMask.ToString(); - responseData["profile_want_do"] = profile.WantDoMask.ToString(); - responseData["profile_image"] = profile.Image.ToString(); - responseData["profile_created"] = profile.Created.ToString(); - responseData["profile_lastlogin"] = profile.LastLogin.ToString(); - // Home region information - responseData["home_coordinates_x"] = profile.HomeLocation.X.ToString(); - responseData["home_coordinates_y"] = profile.HomeLocation.Y.ToString(); - responseData["home_coordinates_z"] = profile.HomeLocation.Z.ToString(); - - responseData["home_region"] = profile.HomeRegion.ToString(); - responseData["home_region_id"] = profile.HomeRegionID.ToString(); - - responseData["home_look_x"] = profile.HomeLookAt.X.ToString(); - responseData["home_look_y"] = profile.HomeLookAt.Y.ToString(); - responseData["home_look_z"] = profile.HomeLookAt.Z.ToString(); - - responseData["user_flags"] = profile.UserFlags.ToString(); - responseData["god_level"] = profile.GodLevel.ToString(); - responseData["custom_type"] = profile.CustomType; - responseData["partner"] = profile.Partner.ToString(); - response.Value = responseData; - - return response; - } - - #region XMLRPC User Methods - - public XmlRpcResponse XmlRPCGetAvatarPickerAvatar(XmlRpcRequest request) - { - // XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable) request.Params[0]; - List returnAvatar = new List(); - UUID queryID = new UUID(UUID.Zero.ToString()); - - if (requestData.Contains("avquery") && requestData.Contains("queryid")) - { - queryID = new UUID((string) requestData["queryid"]); - returnAvatar = m_userDataBaseService.GenerateAgentPickerRequestResponse(queryID, (string) requestData["avquery"]); - } - - m_log.InfoFormat("[AVATARINFO]: Servicing Avatar Query: " + (string) requestData["avquery"]); - return AvatarPickerListtoXmlRPCResponse(queryID, returnAvatar); - } - - public XmlRpcResponse XmlRPCAtRegion(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable) request.Params[0]; - Hashtable responseData = new Hashtable(); - string returnstring = "FALSE"; - - if (requestData.Contains("avatar_id") && requestData.Contains("region_handle") && - requestData.Contains("region_uuid")) - { - // ulong cregionhandle = 0; - UUID regionUUID; - UUID avatarUUID; - - UUID.TryParse((string) requestData["avatar_id"], out avatarUUID); - UUID.TryParse((string) requestData["region_uuid"], out regionUUID); - - if (avatarUUID != UUID.Zero) - { - UserProfileData userProfile = m_userDataBaseService.GetUserProfile(avatarUUID); - userProfile.CurrentAgent.Region = regionUUID; - userProfile.CurrentAgent.Handle = (ulong) Convert.ToInt64((string) requestData["region_handle"]); - //userProfile.CurrentAgent. - m_userDataBaseService.CommitAgent(ref userProfile); - //setUserProfile(userProfile); - - - returnstring = "TRUE"; - } - } - responseData.Add("returnString", returnstring); - response.Value = responseData; - return response; - } - - public XmlRpcResponse XmlRPCGetUserMethodName(XmlRpcRequest request) - { - // XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable) request.Params[0]; - UserProfileData userProfile; - if (requestData.Contains("avatar_name")) - { - string query = (string) requestData["avatar_name"]; - - // Regex objAlphaNumericPattern = new Regex("[^a-zA-Z0-9]"); - - string[] querysplit = query.Split(' '); - - if (querysplit.Length == 2) - { - userProfile = m_userDataBaseService.GetUserProfile(querysplit[0], querysplit[1]); - if (userProfile == null) - { - return CreateUnknownUserErrorResponse(); - } - } - else - { - return CreateUnknownUserErrorResponse(); - } - } - else - { - return CreateUnknownUserErrorResponse(); - } - - return ProfileToXmlRPCResponse(userProfile); - } - - public XmlRpcResponse XmlRPCGetUserMethodUUID(XmlRpcRequest request) - { - // XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable) request.Params[0]; - UserProfileData userProfile; - //CFK: this clogs the UserServer log and is not necessary at this time. - //CFK: m_log.Debug("METHOD BY UUID CALLED"); - if (requestData.Contains("avatar_uuid")) - { - try - { - UUID guess = new UUID((string) requestData["avatar_uuid"]); - - userProfile = m_userDataBaseService.GetUserProfile(guess); - } - catch (FormatException) - { - return CreateUnknownUserErrorResponse(); - } - - if (userProfile == null) - { - return CreateUnknownUserErrorResponse(); - } - } - else - { - return CreateUnknownUserErrorResponse(); - } - - return ProfileToXmlRPCResponse(userProfile); - } - - public XmlRpcResponse XmlRPCGetAgentMethodUUID(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable) request.Params[0]; - UserProfileData userProfile; - //CFK: this clogs the UserServer log and is not necessary at this time. - //CFK: m_log.Debug("METHOD BY UUID CALLED"); - if (requestData.Contains("avatar_uuid")) - { - UUID guess; - - UUID.TryParse((string) requestData["avatar_uuid"], out guess); - - if (guess == UUID.Zero) - { - return CreateUnknownUserErrorResponse(); - } - - userProfile = m_userDataBaseService.GetUserProfile(guess); - - if (userProfile == null) - { - return CreateUnknownUserErrorResponse(); - } - - // no agent??? - if (userProfile.CurrentAgent == null) - { - return CreateUnknownUserErrorResponse(); - } - Hashtable responseData = new Hashtable(); - - responseData["handle"] = userProfile.CurrentAgent.Handle.ToString(); - responseData["session"] = userProfile.CurrentAgent.SessionID.ToString(); - if (userProfile.CurrentAgent.AgentOnline) - responseData["agent_online"] = "TRUE"; - else - responseData["agent_online"] = "FALSE"; - - response.Value = responseData; - } - else - { - return CreateUnknownUserErrorResponse(); - } - - return response; - } - - public XmlRpcResponse XmlRPCCheckAuthSession(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable) request.Params[0]; - UserProfileData userProfile; - - string authed = "FALSE"; - if (requestData.Contains("avatar_uuid") && requestData.Contains("session_id")) - { - UUID guess_aid; - UUID guess_sid; - - UUID.TryParse((string) requestData["avatar_uuid"], out guess_aid); - if (guess_aid == UUID.Zero) - { - return CreateUnknownUserErrorResponse(); - } - UUID.TryParse((string) requestData["session_id"], out guess_sid); - if (guess_sid == UUID.Zero) - { - return CreateUnknownUserErrorResponse(); - } - userProfile = m_userDataBaseService.GetUserProfile(guess_aid); - if (userProfile != null && userProfile.CurrentAgent != null && - userProfile.CurrentAgent.SessionID == guess_sid) - { - authed = "TRUE"; - } - m_log.InfoFormat("[UserManager]: CheckAuthSession TRUE for user {0}", guess_aid); - } - else - { - m_log.InfoFormat("[UserManager]: CheckAuthSession FALSE"); - return CreateUnknownUserErrorResponse(); - } - Hashtable responseData = new Hashtable(); - responseData["auth_session"] = authed; - response.Value = responseData; - return response; - } - - public XmlRpcResponse XmlRpcResponseXmlRPCUpdateUserProfile(XmlRpcRequest request) - { - m_log.Debug("[UserManager]: Got request to update user profile"); - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable) request.Params[0]; - Hashtable responseData = new Hashtable(); - - if (!requestData.Contains("avatar_uuid")) - { - return CreateUnknownUserErrorResponse(); - } - - UUID UserUUID = new UUID((string) requestData["avatar_uuid"]); - UserProfileData userProfile = m_userDataBaseService.GetUserProfile(UserUUID); - if (null == userProfile) - { - return CreateUnknownUserErrorResponse(); - } - // don't know how yet. - if (requestData.Contains("AllowPublish")) - { - } - if (requestData.Contains("FLImageID")) - { - userProfile.FirstLifeImage = new UUID((string) requestData["FLImageID"]); - } - if (requestData.Contains("ImageID")) - { - userProfile.Image = new UUID((string) requestData["ImageID"]); - } - // dont' know how yet - if (requestData.Contains("MaturePublish")) - { - } - if (requestData.Contains("AboutText")) - { - userProfile.AboutText = (string) requestData["AboutText"]; - } - if (requestData.Contains("FLAboutText")) - { - userProfile.FirstLifeAboutText = (string) requestData["FLAboutText"]; - } - // not in DB yet. - if (requestData.Contains("ProfileURL")) - { - } - if (requestData.Contains("home_region")) - { - try - { - userProfile.HomeRegion = Convert.ToUInt64((string) requestData["home_region"]); - } - catch (ArgumentException) - { - m_log.Error("[PROFILE]:Failed to set home region, Invalid Argument"); - } - catch (FormatException) - { - m_log.Error("[PROFILE]:Failed to set home region, Invalid Format"); - } - catch (OverflowException) - { - m_log.Error("[PROFILE]:Failed to set home region, Value was too large"); - } - } - if (requestData.Contains("home_region_id")) - { - UUID regionID; - UUID.TryParse((string) requestData["home_region_id"], out regionID); - userProfile.HomeRegionID = regionID; - } - if (requestData.Contains("home_pos_x")) - { - try - { - userProfile.HomeLocationX = (float) Convert.ToDecimal((string) requestData["home_pos_x"]); - } - catch (InvalidCastException) - { - m_log.Error("[PROFILE]:Failed to set home postion x"); - } - } - if (requestData.Contains("home_pos_y")) - { - try - { - userProfile.HomeLocationY = (float) Convert.ToDecimal((string) requestData["home_pos_y"]); - } - catch (InvalidCastException) - { - m_log.Error("[PROFILE]:Failed to set home postion y"); - } - } - if (requestData.Contains("home_pos_z")) - { - try - { - userProfile.HomeLocationZ = (float) Convert.ToDecimal((string) requestData["home_pos_z"]); - } - catch (InvalidCastException) - { - m_log.Error("[PROFILE]:Failed to set home postion z"); - } - } - if (requestData.Contains("home_look_x")) - { - try - { - userProfile.HomeLookAtX = (float) Convert.ToDecimal((string) requestData["home_look_x"]); - } - catch (InvalidCastException) - { - m_log.Error("[PROFILE]:Failed to set home lookat x"); - } - } - if (requestData.Contains("home_look_y")) - { - try - { - userProfile.HomeLookAtY = (float) Convert.ToDecimal((string) requestData["home_look_y"]); - } - catch (InvalidCastException) - { - m_log.Error("[PROFILE]:Failed to set home lookat y"); - } - } - if (requestData.Contains("home_look_z")) - { - try - { - userProfile.HomeLookAtZ = (float) Convert.ToDecimal((string) requestData["home_look_z"]); - } - catch (InvalidCastException) - { - m_log.Error("[PROFILE]:Failed to set home lookat z"); - } - } - if (requestData.Contains("user_flags")) - { - try - { - userProfile.UserFlags = Convert.ToInt32((string) requestData["user_flags"]); - } - catch (InvalidCastException) - { - m_log.Error("[PROFILE]:Failed to set user flags"); - } - } - if (requestData.Contains("god_level")) - { - try - { - userProfile.GodLevel = Convert.ToInt32((string) requestData["god_level"]); - } - catch (InvalidCastException) - { - m_log.Error("[PROFILE]:Failed to set god level"); - } - } - if (requestData.Contains("custom_type")) - { - try - { - userProfile.CustomType = (string) requestData["custom_type"]; - } - catch (InvalidCastException) - { - m_log.Error("[PROFILE]:Failed to set custom type"); - } - } - if (requestData.Contains("partner")) - { - try - { - userProfile.Partner = new UUID((string) requestData["partner"]); - } - catch (InvalidCastException) - { - m_log.Error("[PROFILE]:Failed to set partner"); - } - } - else - { - userProfile.Partner = UUID.Zero; - } - - // call plugin! - bool ret = m_userDataBaseService.UpdateUserProfile(userProfile); - responseData["returnString"] = ret.ToString(); - response.Value = responseData; - return response; - } - - public XmlRpcResponse XmlRPCLogOffUserMethodUUID(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable) request.Params[0]; - - if (requestData.Contains("avatar_uuid")) - { - try - { - UUID userUUID = new UUID((string)requestData["avatar_uuid"]); - UUID RegionID = new UUID((string)requestData["region_uuid"]); - ulong regionhandle = (ulong)Convert.ToInt64((string)requestData["region_handle"]); - Vector3 position = new Vector3( - (float)Convert.ToDecimal((string)requestData["region_pos_x"]), - (float)Convert.ToDecimal((string)requestData["region_pos_y"]), - (float)Convert.ToDecimal((string)requestData["region_pos_z"])); - Vector3 lookat = new Vector3( - (float)Convert.ToDecimal((string)requestData["lookat_x"]), - (float)Convert.ToDecimal((string)requestData["lookat_y"]), - (float)Convert.ToDecimal((string)requestData["lookat_z"])); - - handlerLogOffUser = OnLogOffUser; - if (handlerLogOffUser != null) - handlerLogOffUser(userUUID); - - m_userDataBaseService.LogOffUser(userUUID, RegionID, regionhandle, position, lookat); - } - catch (FormatException) - { - m_log.Warn("[LOGOUT]: Error in Logout XMLRPC Params"); - return response; - } - } - else - { - return CreateUnknownUserErrorResponse(); - } - - return response; - } - - #endregion - - - public void HandleAgentLocation(UUID agentID, UUID regionID, ulong regionHandle) - { - UserProfileData userProfile = m_userDataBaseService.GetUserProfile(agentID); - if (userProfile != null) - { - userProfile.CurrentAgent.Region = regionID; - userProfile.CurrentAgent.Handle = regionHandle; - m_userDataBaseService.CommitAgent(ref userProfile); - } - } - - public void HandleAgentLeaving(UUID agentID, UUID regionID, ulong regionHandle) - { - UserProfileData userProfile = m_userDataBaseService.GetUserProfile(agentID); - if (userProfile != null) - { - if (userProfile.CurrentAgent.Region == regionID) - { - UserAgentData userAgent = userProfile.CurrentAgent; - if (userAgent != null && userAgent.AgentOnline) - { - userAgent.AgentOnline = false; - userAgent.LogoutTime = Util.UnixTimeSinceEpoch(); - if (regionID != UUID.Zero) - { - userAgent.Region = regionID; - } - userAgent.Handle = regionHandle; - userProfile.LastLogin = userAgent.LogoutTime; - - m_userDataBaseService.CommitAgent(ref userProfile); - - handlerLogOffUser = OnLogOffUser; - if (handlerLogOffUser != null) - handlerLogOffUser(agentID); - } - } - } - } - - public void HandleRegionStartup(UUID regionID) - { - m_userDataBaseService.LogoutUsers(regionID); - } - - public void HandleRegionShutdown(UUID regionID) - { - m_userDataBaseService.LogoutUsers(regionID); - } - } -} +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using log4net; +using Nwc.XmlRpc; +using OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Framework.Communications; +using OpenSim.Framework.Servers; + +namespace OpenSim.Grid.UserServer.Modules +{ + public delegate void logOffUser(UUID AgentID); + + public class UserManager + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + public event logOffUser OnLogOffUser; + private logOffUser handlerLogOffUser; + + private UserDataBaseService m_userDataBaseService; + private BaseHttpServer m_httpServer; + + /// + /// + /// + /// + public UserManager( UserDataBaseService userDataBaseService) + { + m_userDataBaseService = userDataBaseService; + } + + public void Initialise() + { + + } + + public void PostInitialise() + { + + } + + public void RegisterHandlers(BaseHttpServer httpServer) + { + m_httpServer = httpServer; + + m_httpServer.AddXmlRPCHandler("get_user_by_name", XmlRPCGetUserMethodName); + m_httpServer.AddXmlRPCHandler("get_user_by_uuid", XmlRPCGetUserMethodUUID); + m_httpServer.AddXmlRPCHandler("get_avatar_picker_avatar", XmlRPCGetAvatarPickerAvatar); + + m_httpServer.AddXmlRPCHandler("update_user_current_region", XmlRPCAtRegion); + m_httpServer.AddXmlRPCHandler("logout_of_simulator", XmlRPCLogOffUserMethodUUID); + m_httpServer.AddXmlRPCHandler("get_agent_by_uuid", XmlRPCGetAgentMethodUUID); + m_httpServer.AddXmlRPCHandler("check_auth_session", XmlRPCCheckAuthSession); + + m_httpServer.AddXmlRPCHandler("update_user_profile", XmlRpcResponseXmlRPCUpdateUserProfile); + + m_httpServer.AddStreamHandler(new RestStreamHandler("DELETE", "/usersessions/", RestDeleteUserSessionMethod)); + } + + /// + /// Deletes an active agent session + /// + /// The request + /// The path (eg /bork/narf/test) + /// Parameters sent + /// HTTP request header object + /// HTTP response header object + /// Success "OK" else error + public string RestDeleteUserSessionMethod(string request, string path, string param, + OSHttpRequest httpRequest, OSHttpResponse httpResponse) + { + // TODO! Important! + + return "OK"; + } + + /// + /// Returns an error message that the user could not be found in the database + /// + /// XML string consisting of a error element containing individual error(s) + public XmlRpcResponse CreateUnknownUserErrorResponse() + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable responseData = new Hashtable(); + responseData["error_type"] = "unknown_user"; + responseData["error_desc"] = "The user requested is not in the database"; + + response.Value = responseData; + return response; + } + + public XmlRpcResponse AvatarPickerListtoXmlRPCResponse(UUID queryID, List returnUsers) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable responseData = new Hashtable(); + // Query Result Information + responseData["queryid"] = queryID.ToString(); + responseData["avcount"] = returnUsers.Count.ToString(); + + for (int i = 0; i < returnUsers.Count; i++) + { + responseData["avatarid" + i] = returnUsers[i].AvatarID.ToString(); + responseData["firstname" + i] = returnUsers[i].firstName; + responseData["lastname" + i] = returnUsers[i].lastName; + } + response.Value = responseData; + + return response; + } + + /// + /// Converts a user profile to an XML element which can be returned + /// + /// The user profile + /// A string containing an XML Document of the user profile + public XmlRpcResponse ProfileToXmlRPCResponse(UserProfileData profile) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable responseData = new Hashtable(); + + // Account information + responseData["firstname"] = profile.FirstName; + responseData["lastname"] = profile.SurName; + responseData["uuid"] = profile.ID.ToString(); + // Server Information + responseData["server_inventory"] = profile.UserInventoryURI; + responseData["server_asset"] = profile.UserAssetURI; + // Profile Information + responseData["profile_about"] = profile.AboutText; + responseData["profile_firstlife_about"] = profile.FirstLifeAboutText; + responseData["profile_firstlife_image"] = profile.FirstLifeImage.ToString(); + responseData["profile_can_do"] = profile.CanDoMask.ToString(); + responseData["profile_want_do"] = profile.WantDoMask.ToString(); + responseData["profile_image"] = profile.Image.ToString(); + responseData["profile_created"] = profile.Created.ToString(); + responseData["profile_lastlogin"] = profile.LastLogin.ToString(); + // Home region information + responseData["home_coordinates_x"] = profile.HomeLocation.X.ToString(); + responseData["home_coordinates_y"] = profile.HomeLocation.Y.ToString(); + responseData["home_coordinates_z"] = profile.HomeLocation.Z.ToString(); + + responseData["home_region"] = profile.HomeRegion.ToString(); + responseData["home_region_id"] = profile.HomeRegionID.ToString(); + + responseData["home_look_x"] = profile.HomeLookAt.X.ToString(); + responseData["home_look_y"] = profile.HomeLookAt.Y.ToString(); + responseData["home_look_z"] = profile.HomeLookAt.Z.ToString(); + + responseData["user_flags"] = profile.UserFlags.ToString(); + responseData["god_level"] = profile.GodLevel.ToString(); + responseData["custom_type"] = profile.CustomType; + responseData["partner"] = profile.Partner.ToString(); + response.Value = responseData; + + return response; + } + + #region XMLRPC User Methods + + public XmlRpcResponse XmlRPCGetAvatarPickerAvatar(XmlRpcRequest request) + { + // XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable) request.Params[0]; + List returnAvatar = new List(); + UUID queryID = new UUID(UUID.Zero.ToString()); + + if (requestData.Contains("avquery") && requestData.Contains("queryid")) + { + queryID = new UUID((string) requestData["queryid"]); + returnAvatar = m_userDataBaseService.GenerateAgentPickerRequestResponse(queryID, (string) requestData["avquery"]); + } + + m_log.InfoFormat("[AVATARINFO]: Servicing Avatar Query: " + (string) requestData["avquery"]); + return AvatarPickerListtoXmlRPCResponse(queryID, returnAvatar); + } + + public XmlRpcResponse XmlRPCAtRegion(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable) request.Params[0]; + Hashtable responseData = new Hashtable(); + string returnstring = "FALSE"; + + if (requestData.Contains("avatar_id") && requestData.Contains("region_handle") && + requestData.Contains("region_uuid")) + { + // ulong cregionhandle = 0; + UUID regionUUID; + UUID avatarUUID; + + UUID.TryParse((string) requestData["avatar_id"], out avatarUUID); + UUID.TryParse((string) requestData["region_uuid"], out regionUUID); + + if (avatarUUID != UUID.Zero) + { + UserProfileData userProfile = m_userDataBaseService.GetUserProfile(avatarUUID); + userProfile.CurrentAgent.Region = regionUUID; + userProfile.CurrentAgent.Handle = (ulong) Convert.ToInt64((string) requestData["region_handle"]); + //userProfile.CurrentAgent. + m_userDataBaseService.CommitAgent(ref userProfile); + //setUserProfile(userProfile); + + + returnstring = "TRUE"; + } + } + responseData.Add("returnString", returnstring); + response.Value = responseData; + return response; + } + + public XmlRpcResponse XmlRPCGetUserMethodName(XmlRpcRequest request) + { + // XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable) request.Params[0]; + UserProfileData userProfile; + if (requestData.Contains("avatar_name")) + { + string query = (string) requestData["avatar_name"]; + + // Regex objAlphaNumericPattern = new Regex("[^a-zA-Z0-9]"); + + string[] querysplit = query.Split(' '); + + if (querysplit.Length == 2) + { + userProfile = m_userDataBaseService.GetUserProfile(querysplit[0], querysplit[1]); + if (userProfile == null) + { + return CreateUnknownUserErrorResponse(); + } + } + else + { + return CreateUnknownUserErrorResponse(); + } + } + else + { + return CreateUnknownUserErrorResponse(); + } + + return ProfileToXmlRPCResponse(userProfile); + } + + public XmlRpcResponse XmlRPCGetUserMethodUUID(XmlRpcRequest request) + { + // XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable) request.Params[0]; + UserProfileData userProfile; + //CFK: this clogs the UserServer log and is not necessary at this time. + //CFK: m_log.Debug("METHOD BY UUID CALLED"); + if (requestData.Contains("avatar_uuid")) + { + try + { + UUID guess = new UUID((string) requestData["avatar_uuid"]); + + userProfile = m_userDataBaseService.GetUserProfile(guess); + } + catch (FormatException) + { + return CreateUnknownUserErrorResponse(); + } + + if (userProfile == null) + { + return CreateUnknownUserErrorResponse(); + } + } + else + { + return CreateUnknownUserErrorResponse(); + } + + return ProfileToXmlRPCResponse(userProfile); + } + + public XmlRpcResponse XmlRPCGetAgentMethodUUID(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable) request.Params[0]; + UserProfileData userProfile; + //CFK: this clogs the UserServer log and is not necessary at this time. + //CFK: m_log.Debug("METHOD BY UUID CALLED"); + if (requestData.Contains("avatar_uuid")) + { + UUID guess; + + UUID.TryParse((string) requestData["avatar_uuid"], out guess); + + if (guess == UUID.Zero) + { + return CreateUnknownUserErrorResponse(); + } + + userProfile = m_userDataBaseService.GetUserProfile(guess); + + if (userProfile == null) + { + return CreateUnknownUserErrorResponse(); + } + + // no agent??? + if (userProfile.CurrentAgent == null) + { + return CreateUnknownUserErrorResponse(); + } + Hashtable responseData = new Hashtable(); + + responseData["handle"] = userProfile.CurrentAgent.Handle.ToString(); + responseData["session"] = userProfile.CurrentAgent.SessionID.ToString(); + if (userProfile.CurrentAgent.AgentOnline) + responseData["agent_online"] = "TRUE"; + else + responseData["agent_online"] = "FALSE"; + + response.Value = responseData; + } + else + { + return CreateUnknownUserErrorResponse(); + } + + return response; + } + + public XmlRpcResponse XmlRPCCheckAuthSession(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable) request.Params[0]; + UserProfileData userProfile; + + string authed = "FALSE"; + if (requestData.Contains("avatar_uuid") && requestData.Contains("session_id")) + { + UUID guess_aid; + UUID guess_sid; + + UUID.TryParse((string) requestData["avatar_uuid"], out guess_aid); + if (guess_aid == UUID.Zero) + { + return CreateUnknownUserErrorResponse(); + } + UUID.TryParse((string) requestData["session_id"], out guess_sid); + if (guess_sid == UUID.Zero) + { + return CreateUnknownUserErrorResponse(); + } + userProfile = m_userDataBaseService.GetUserProfile(guess_aid); + if (userProfile != null && userProfile.CurrentAgent != null && + userProfile.CurrentAgent.SessionID == guess_sid) + { + authed = "TRUE"; + } + m_log.InfoFormat("[UserManager]: CheckAuthSession TRUE for user {0}", guess_aid); + } + else + { + m_log.InfoFormat("[UserManager]: CheckAuthSession FALSE"); + return CreateUnknownUserErrorResponse(); + } + Hashtable responseData = new Hashtable(); + responseData["auth_session"] = authed; + response.Value = responseData; + return response; + } + + public XmlRpcResponse XmlRpcResponseXmlRPCUpdateUserProfile(XmlRpcRequest request) + { + m_log.Debug("[UserManager]: Got request to update user profile"); + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable) request.Params[0]; + Hashtable responseData = new Hashtable(); + + if (!requestData.Contains("avatar_uuid")) + { + return CreateUnknownUserErrorResponse(); + } + + UUID UserUUID = new UUID((string) requestData["avatar_uuid"]); + UserProfileData userProfile = m_userDataBaseService.GetUserProfile(UserUUID); + if (null == userProfile) + { + return CreateUnknownUserErrorResponse(); + } + // don't know how yet. + if (requestData.Contains("AllowPublish")) + { + } + if (requestData.Contains("FLImageID")) + { + userProfile.FirstLifeImage = new UUID((string) requestData["FLImageID"]); + } + if (requestData.Contains("ImageID")) + { + userProfile.Image = new UUID((string) requestData["ImageID"]); + } + // dont' know how yet + if (requestData.Contains("MaturePublish")) + { + } + if (requestData.Contains("AboutText")) + { + userProfile.AboutText = (string) requestData["AboutText"]; + } + if (requestData.Contains("FLAboutText")) + { + userProfile.FirstLifeAboutText = (string) requestData["FLAboutText"]; + } + // not in DB yet. + if (requestData.Contains("ProfileURL")) + { + } + if (requestData.Contains("home_region")) + { + try + { + userProfile.HomeRegion = Convert.ToUInt64((string) requestData["home_region"]); + } + catch (ArgumentException) + { + m_log.Error("[PROFILE]:Failed to set home region, Invalid Argument"); + } + catch (FormatException) + { + m_log.Error("[PROFILE]:Failed to set home region, Invalid Format"); + } + catch (OverflowException) + { + m_log.Error("[PROFILE]:Failed to set home region, Value was too large"); + } + } + if (requestData.Contains("home_region_id")) + { + UUID regionID; + UUID.TryParse((string) requestData["home_region_id"], out regionID); + userProfile.HomeRegionID = regionID; + } + if (requestData.Contains("home_pos_x")) + { + try + { + userProfile.HomeLocationX = (float) Convert.ToDecimal((string) requestData["home_pos_x"]); + } + catch (InvalidCastException) + { + m_log.Error("[PROFILE]:Failed to set home postion x"); + } + } + if (requestData.Contains("home_pos_y")) + { + try + { + userProfile.HomeLocationY = (float) Convert.ToDecimal((string) requestData["home_pos_y"]); + } + catch (InvalidCastException) + { + m_log.Error("[PROFILE]:Failed to set home postion y"); + } + } + if (requestData.Contains("home_pos_z")) + { + try + { + userProfile.HomeLocationZ = (float) Convert.ToDecimal((string) requestData["home_pos_z"]); + } + catch (InvalidCastException) + { + m_log.Error("[PROFILE]:Failed to set home postion z"); + } + } + if (requestData.Contains("home_look_x")) + { + try + { + userProfile.HomeLookAtX = (float) Convert.ToDecimal((string) requestData["home_look_x"]); + } + catch (InvalidCastException) + { + m_log.Error("[PROFILE]:Failed to set home lookat x"); + } + } + if (requestData.Contains("home_look_y")) + { + try + { + userProfile.HomeLookAtY = (float) Convert.ToDecimal((string) requestData["home_look_y"]); + } + catch (InvalidCastException) + { + m_log.Error("[PROFILE]:Failed to set home lookat y"); + } + } + if (requestData.Contains("home_look_z")) + { + try + { + userProfile.HomeLookAtZ = (float) Convert.ToDecimal((string) requestData["home_look_z"]); + } + catch (InvalidCastException) + { + m_log.Error("[PROFILE]:Failed to set home lookat z"); + } + } + if (requestData.Contains("user_flags")) + { + try + { + userProfile.UserFlags = Convert.ToInt32((string) requestData["user_flags"]); + } + catch (InvalidCastException) + { + m_log.Error("[PROFILE]:Failed to set user flags"); + } + } + if (requestData.Contains("god_level")) + { + try + { + userProfile.GodLevel = Convert.ToInt32((string) requestData["god_level"]); + } + catch (InvalidCastException) + { + m_log.Error("[PROFILE]:Failed to set god level"); + } + } + if (requestData.Contains("custom_type")) + { + try + { + userProfile.CustomType = (string) requestData["custom_type"]; + } + catch (InvalidCastException) + { + m_log.Error("[PROFILE]:Failed to set custom type"); + } + } + if (requestData.Contains("partner")) + { + try + { + userProfile.Partner = new UUID((string) requestData["partner"]); + } + catch (InvalidCastException) + { + m_log.Error("[PROFILE]:Failed to set partner"); + } + } + else + { + userProfile.Partner = UUID.Zero; + } + + // call plugin! + bool ret = m_userDataBaseService.UpdateUserProfile(userProfile); + responseData["returnString"] = ret.ToString(); + response.Value = responseData; + return response; + } + + public XmlRpcResponse XmlRPCLogOffUserMethodUUID(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable) request.Params[0]; + + if (requestData.Contains("avatar_uuid")) + { + try + { + UUID userUUID = new UUID((string)requestData["avatar_uuid"]); + UUID RegionID = new UUID((string)requestData["region_uuid"]); + ulong regionhandle = (ulong)Convert.ToInt64((string)requestData["region_handle"]); + Vector3 position = new Vector3( + (float)Convert.ToDecimal((string)requestData["region_pos_x"]), + (float)Convert.ToDecimal((string)requestData["region_pos_y"]), + (float)Convert.ToDecimal((string)requestData["region_pos_z"])); + Vector3 lookat = new Vector3( + (float)Convert.ToDecimal((string)requestData["lookat_x"]), + (float)Convert.ToDecimal((string)requestData["lookat_y"]), + (float)Convert.ToDecimal((string)requestData["lookat_z"])); + + handlerLogOffUser = OnLogOffUser; + if (handlerLogOffUser != null) + handlerLogOffUser(userUUID); + + m_userDataBaseService.LogOffUser(userUUID, RegionID, regionhandle, position, lookat); + } + catch (FormatException) + { + m_log.Warn("[LOGOUT]: Error in Logout XMLRPC Params"); + return response; + } + } + else + { + return CreateUnknownUserErrorResponse(); + } + + return response; + } + + #endregion + + + public void HandleAgentLocation(UUID agentID, UUID regionID, ulong regionHandle) + { + UserProfileData userProfile = m_userDataBaseService.GetUserProfile(agentID); + if (userProfile != null) + { + userProfile.CurrentAgent.Region = regionID; + userProfile.CurrentAgent.Handle = regionHandle; + m_userDataBaseService.CommitAgent(ref userProfile); + } + } + + public void HandleAgentLeaving(UUID agentID, UUID regionID, ulong regionHandle) + { + UserProfileData userProfile = m_userDataBaseService.GetUserProfile(agentID); + if (userProfile != null) + { + if (userProfile.CurrentAgent.Region == regionID) + { + UserAgentData userAgent = userProfile.CurrentAgent; + if (userAgent != null && userAgent.AgentOnline) + { + userAgent.AgentOnline = false; + userAgent.LogoutTime = Util.UnixTimeSinceEpoch(); + if (regionID != UUID.Zero) + { + userAgent.Region = regionID; + } + userAgent.Handle = regionHandle; + userProfile.LastLogin = userAgent.LogoutTime; + + m_userDataBaseService.CommitAgent(ref userProfile); + + handlerLogOffUser = OnLogOffUser; + if (handlerLogOffUser != null) + handlerLogOffUser(agentID); + } + } + } + } + + public void HandleRegionStartup(UUID regionID) + { + m_userDataBaseService.LogoutUsers(regionID); + } + + public void HandleRegionShutdown(UUID regionID) + { + m_userDataBaseService.LogoutUsers(regionID); + } + } +} diff --git a/OpenSim/Grid/UserServer.Modules/UserServerAvatarAppearanceModule.cs b/OpenSim/Grid/UserServer.Modules/UserServerAvatarAppearanceModule.cs index 1c8c0c8..a1497b4 100644 --- a/OpenSim/Grid/UserServer.Modules/UserServerAvatarAppearanceModule.cs +++ b/OpenSim/Grid/UserServer.Modules/UserServerAvatarAppearanceModule.cs @@ -1,124 +1,124 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using log4net; -using Nwc.XmlRpc; -using OpenMetaverse; -using OpenSim.Framework; -using OpenSim.Framework.Communications; -using OpenSim.Framework.Servers; - -namespace OpenSim.Grid.UserServer.Modules -{ - public class UserServerAvatarAppearanceModule - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private UserDataBaseService m_userDataBaseService; - private BaseHttpServer m_httpServer; - - public UserServerAvatarAppearanceModule(UserDataBaseService userDataBaseService) - { - m_userDataBaseService = userDataBaseService; - } - - public void Initialise() - { - - } - - public void PostInitialise() - { - - } - - public void RegisterHandlers(BaseHttpServer httpServer) - { - m_httpServer = httpServer; - - m_httpServer.AddXmlRPCHandler("get_avatar_appearance", XmlRPCGetAvatarAppearance); - m_httpServer.AddXmlRPCHandler("update_avatar_appearance", XmlRPCUpdateAvatarAppearance); - } - - public XmlRpcResponse XmlRPCGetAvatarAppearance(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable)request.Params[0]; - AvatarAppearance appearance; - Hashtable responseData; - if (requestData.Contains("owner")) - { - appearance = m_userDataBaseService.GetUserAppearance(new UUID((string)requestData["owner"])); - if (appearance == null) - { - responseData = new Hashtable(); - responseData["error_type"] = "no appearance"; - responseData["error_desc"] = "There was no appearance found for this avatar"; - } - else - { - responseData = appearance.ToHashTable(); - } - } - else - { - responseData = new Hashtable(); - responseData["error_type"] = "unknown_avatar"; - responseData["error_desc"] = "The avatar appearance requested is not in the database"; - } - - response.Value = responseData; - return response; - } - - public XmlRpcResponse XmlRPCUpdateAvatarAppearance(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable)request.Params[0]; - Hashtable responseData; - if (requestData.Contains("owner")) - { - AvatarAppearance appearance = new AvatarAppearance(requestData); - m_userDataBaseService.UpdateUserAppearance(new UUID((string)requestData["owner"]), appearance); - responseData = new Hashtable(); - responseData["returnString"] = "TRUE"; - } - else - { - responseData = new Hashtable(); - responseData["error_type"] = "unknown_avatar"; - responseData["error_desc"] = "The avatar appearance requested is not in the database"; - } - response.Value = responseData; - return response; - } - } -} +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using log4net; +using Nwc.XmlRpc; +using OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Framework.Communications; +using OpenSim.Framework.Servers; + +namespace OpenSim.Grid.UserServer.Modules +{ + public class UserServerAvatarAppearanceModule + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private UserDataBaseService m_userDataBaseService; + private BaseHttpServer m_httpServer; + + public UserServerAvatarAppearanceModule(UserDataBaseService userDataBaseService) + { + m_userDataBaseService = userDataBaseService; + } + + public void Initialise() + { + + } + + public void PostInitialise() + { + + } + + public void RegisterHandlers(BaseHttpServer httpServer) + { + m_httpServer = httpServer; + + m_httpServer.AddXmlRPCHandler("get_avatar_appearance", XmlRPCGetAvatarAppearance); + m_httpServer.AddXmlRPCHandler("update_avatar_appearance", XmlRPCUpdateAvatarAppearance); + } + + public XmlRpcResponse XmlRPCGetAvatarAppearance(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable)request.Params[0]; + AvatarAppearance appearance; + Hashtable responseData; + if (requestData.Contains("owner")) + { + appearance = m_userDataBaseService.GetUserAppearance(new UUID((string)requestData["owner"])); + if (appearance == null) + { + responseData = new Hashtable(); + responseData["error_type"] = "no appearance"; + responseData["error_desc"] = "There was no appearance found for this avatar"; + } + else + { + responseData = appearance.ToHashTable(); + } + } + else + { + responseData = new Hashtable(); + responseData["error_type"] = "unknown_avatar"; + responseData["error_desc"] = "The avatar appearance requested is not in the database"; + } + + response.Value = responseData; + return response; + } + + public XmlRpcResponse XmlRPCUpdateAvatarAppearance(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable responseData; + if (requestData.Contains("owner")) + { + AvatarAppearance appearance = new AvatarAppearance(requestData); + m_userDataBaseService.UpdateUserAppearance(new UUID((string)requestData["owner"]), appearance); + responseData = new Hashtable(); + responseData["returnString"] = "TRUE"; + } + else + { + responseData = new Hashtable(); + responseData["error_type"] = "unknown_avatar"; + responseData["error_desc"] = "The avatar appearance requested is not in the database"; + } + response.Value = responseData; + return response; + } + } +} diff --git a/OpenSim/Grid/UserServer.Modules/UserServerFriendsModule.cs b/OpenSim/Grid/UserServer.Modules/UserServerFriendsModule.cs index fec2dc0..9711a4b 100644 --- a/OpenSim/Grid/UserServer.Modules/UserServerFriendsModule.cs +++ b/OpenSim/Grid/UserServer.Modules/UserServerFriendsModule.cs @@ -1,173 +1,173 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using log4net; -using Nwc.XmlRpc; -using OpenMetaverse; -using OpenSim.Framework; -using OpenSim.Framework.Communications; -using OpenSim.Framework.Servers; - -namespace OpenSim.Grid.UserServer.Modules -{ - public class UserServerFriendsModule - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private UserDataBaseService m_userDataBaseService; - - private BaseHttpServer m_httpServer; - - public UserServerFriendsModule(UserDataBaseService userDataBaseService) - { - m_userDataBaseService = userDataBaseService; - } - - public void Initialise() - { - - } - - public void PostInitialise() - { - - } - - public void RegisterHandlers(BaseHttpServer httpServer) - { - m_httpServer = httpServer; - - m_httpServer.AddXmlRPCHandler("add_new_user_friend", XmlRpcResponseXmlRPCAddUserFriend); - m_httpServer.AddXmlRPCHandler("remove_user_friend", XmlRpcResponseXmlRPCRemoveUserFriend); - m_httpServer.AddXmlRPCHandler("update_user_friend_perms", XmlRpcResponseXmlRPCUpdateUserFriendPerms); - m_httpServer.AddXmlRPCHandler("get_user_friend_list", XmlRpcResponseXmlRPCGetUserFriendList); - } - - public XmlRpcResponse FriendListItemListtoXmlRPCResponse(List returnUsers) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable responseData = new Hashtable(); - // Query Result Information - - responseData["avcount"] = returnUsers.Count.ToString(); - - for (int i = 0; i < returnUsers.Count; i++) - { - responseData["ownerID" + i] = returnUsers[i].FriendListOwner.ToString(); - responseData["friendID" + i] = returnUsers[i].Friend.ToString(); - responseData["ownerPerms" + i] = returnUsers[i].FriendListOwnerPerms.ToString(); - responseData["friendPerms" + i] = returnUsers[i].FriendPerms.ToString(); - } - response.Value = responseData; - - return response; - } - - public XmlRpcResponse XmlRpcResponseXmlRPCAddUserFriend(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable)request.Params[0]; - Hashtable responseData = new Hashtable(); - string returnString = "FALSE"; - // Query Result Information - - if (requestData.Contains("ownerID") && requestData.Contains("friendID") && - requestData.Contains("friendPerms")) - { - // UserManagerBase.AddNewuserFriend - m_userDataBaseService.AddNewUserFriend(new UUID((string)requestData["ownerID"]), - new UUID((string)requestData["friendID"]), - (uint)Convert.ToInt32((string)requestData["friendPerms"])); - returnString = "TRUE"; - } - responseData["returnString"] = returnString; - response.Value = responseData; - return response; - } - - public XmlRpcResponse XmlRpcResponseXmlRPCRemoveUserFriend(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable)request.Params[0]; - Hashtable responseData = new Hashtable(); - string returnString = "FALSE"; - // Query Result Information - - if (requestData.Contains("ownerID") && requestData.Contains("friendID")) - { - // UserManagerBase.AddNewuserFriend - m_userDataBaseService.RemoveUserFriend(new UUID((string)requestData["ownerID"]), - new UUID((string)requestData["friendID"])); - returnString = "TRUE"; - } - responseData["returnString"] = returnString; - response.Value = responseData; - return response; - } - - public XmlRpcResponse XmlRpcResponseXmlRPCUpdateUserFriendPerms(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable)request.Params[0]; - Hashtable responseData = new Hashtable(); - string returnString = "FALSE"; - - if (requestData.Contains("ownerID") && requestData.Contains("friendID") && - requestData.Contains("friendPerms")) - { - m_userDataBaseService.UpdateUserFriendPerms(new UUID((string)requestData["ownerID"]), - new UUID((string)requestData["friendID"]), - (uint)Convert.ToInt32((string)requestData["friendPerms"])); - // UserManagerBase. - returnString = "TRUE"; - } - responseData["returnString"] = returnString; - response.Value = responseData; - return response; - } - - public XmlRpcResponse XmlRpcResponseXmlRPCGetUserFriendList(XmlRpcRequest request) - { - // XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable)request.Params[0]; - // Hashtable responseData = new Hashtable(); - - List returndata = new List(); - - if (requestData.Contains("ownerID")) - { - returndata = m_userDataBaseService.GetUserFriendList(new UUID((string)requestData["ownerID"])); - } - - return FriendListItemListtoXmlRPCResponse(returndata); - } - } -} +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Reflection; +using log4net; +using Nwc.XmlRpc; +using OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Framework.Communications; +using OpenSim.Framework.Servers; + +namespace OpenSim.Grid.UserServer.Modules +{ + public class UserServerFriendsModule + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private UserDataBaseService m_userDataBaseService; + + private BaseHttpServer m_httpServer; + + public UserServerFriendsModule(UserDataBaseService userDataBaseService) + { + m_userDataBaseService = userDataBaseService; + } + + public void Initialise() + { + + } + + public void PostInitialise() + { + + } + + public void RegisterHandlers(BaseHttpServer httpServer) + { + m_httpServer = httpServer; + + m_httpServer.AddXmlRPCHandler("add_new_user_friend", XmlRpcResponseXmlRPCAddUserFriend); + m_httpServer.AddXmlRPCHandler("remove_user_friend", XmlRpcResponseXmlRPCRemoveUserFriend); + m_httpServer.AddXmlRPCHandler("update_user_friend_perms", XmlRpcResponseXmlRPCUpdateUserFriendPerms); + m_httpServer.AddXmlRPCHandler("get_user_friend_list", XmlRpcResponseXmlRPCGetUserFriendList); + } + + public XmlRpcResponse FriendListItemListtoXmlRPCResponse(List returnUsers) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable responseData = new Hashtable(); + // Query Result Information + + responseData["avcount"] = returnUsers.Count.ToString(); + + for (int i = 0; i < returnUsers.Count; i++) + { + responseData["ownerID" + i] = returnUsers[i].FriendListOwner.ToString(); + responseData["friendID" + i] = returnUsers[i].Friend.ToString(); + responseData["ownerPerms" + i] = returnUsers[i].FriendListOwnerPerms.ToString(); + responseData["friendPerms" + i] = returnUsers[i].FriendPerms.ToString(); + } + response.Value = responseData; + + return response; + } + + public XmlRpcResponse XmlRpcResponseXmlRPCAddUserFriend(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable responseData = new Hashtable(); + string returnString = "FALSE"; + // Query Result Information + + if (requestData.Contains("ownerID") && requestData.Contains("friendID") && + requestData.Contains("friendPerms")) + { + // UserManagerBase.AddNewuserFriend + m_userDataBaseService.AddNewUserFriend(new UUID((string)requestData["ownerID"]), + new UUID((string)requestData["friendID"]), + (uint)Convert.ToInt32((string)requestData["friendPerms"])); + returnString = "TRUE"; + } + responseData["returnString"] = returnString; + response.Value = responseData; + return response; + } + + public XmlRpcResponse XmlRpcResponseXmlRPCRemoveUserFriend(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable responseData = new Hashtable(); + string returnString = "FALSE"; + // Query Result Information + + if (requestData.Contains("ownerID") && requestData.Contains("friendID")) + { + // UserManagerBase.AddNewuserFriend + m_userDataBaseService.RemoveUserFriend(new UUID((string)requestData["ownerID"]), + new UUID((string)requestData["friendID"])); + returnString = "TRUE"; + } + responseData["returnString"] = returnString; + response.Value = responseData; + return response; + } + + public XmlRpcResponse XmlRpcResponseXmlRPCUpdateUserFriendPerms(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable responseData = new Hashtable(); + string returnString = "FALSE"; + + if (requestData.Contains("ownerID") && requestData.Contains("friendID") && + requestData.Contains("friendPerms")) + { + m_userDataBaseService.UpdateUserFriendPerms(new UUID((string)requestData["ownerID"]), + new UUID((string)requestData["friendID"]), + (uint)Convert.ToInt32((string)requestData["friendPerms"])); + // UserManagerBase. + returnString = "TRUE"; + } + responseData["returnString"] = returnString; + response.Value = responseData; + return response; + } + + public XmlRpcResponse XmlRpcResponseXmlRPCGetUserFriendList(XmlRpcRequest request) + { + // XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable)request.Params[0]; + // Hashtable responseData = new Hashtable(); + + List returndata = new List(); + + if (requestData.Contains("ownerID")) + { + returndata = m_userDataBaseService.GetUserFriendList(new UUID((string)requestData["ownerID"])); + } + + return FriendListItemListtoXmlRPCResponse(returndata); + } + } +} diff --git a/OpenSim/Grid/UserServer/UserServerCommandModule.cs b/OpenSim/Grid/UserServer/UserServerCommandModule.cs index 41a7eed..f35cfec 100644 --- a/OpenSim/Grid/UserServer/UserServerCommandModule.cs +++ b/OpenSim/Grid/UserServer/UserServerCommandModule.cs @@ -1,366 +1,366 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSim Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.IO; -using System.Reflection; -using log4net; -using log4net.Config; -using OpenMetaverse; -using OpenSim.Data; -using OpenSim.Framework; -using OpenSim.Framework.Communications; -using OpenSim.Framework.Communications.Cache; -using OpenSim.Framework.Console; -using OpenSim.Framework.Servers; -using OpenSim.Framework.Statistics; -using OpenSim.Grid.Communications.OGS1; -using OpenSim.Grid.Framework; -using OpenSim.Grid.UserServer.Modules; - -namespace OpenSim.Grid.UserServer -{ - public class UserServerCommandModule - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - protected ConsoleBase m_console; - protected UserConfig m_cfg; - - protected UserDataBaseService m_userDataBaseService; - protected UserLoginService m_loginService; - - protected UUID m_lastCreatedUser = UUID.Random(); - - protected IUGAIMCore m_core; - - public UserServerCommandModule( UserLoginService loginService) - { - m_loginService = loginService; - } - - public void Initialise(IUGAIMCore core) - { - m_core = core; - } - - public void PostInitialise() - { - UserConfig cfg; - if (m_core.TryGet(out cfg)) - { - m_cfg = cfg; - } - - UserDataBaseService userDBservice; - if (m_core.TryGet(out userDBservice)) - { - m_userDataBaseService = userDBservice; - } - - ConsoleBase console; - if ((m_core.TryGet(out console)) && (m_cfg != null) && (m_userDataBaseService != null)) - { - RegisterConsoleCommands(console); - } - } - - public void RegisterHandlers(BaseHttpServer httpServer) - { - - } - - private void RegisterConsoleCommands(ConsoleBase console) - { - m_console = console; - m_console.Commands.AddCommand("userserver", false, "create user", - "create user [ [ [ [email]]]]", - "Create a new user account", RunCommand); - - m_console.Commands.AddCommand("userserver", false, "reset user password", - "reset user password [ [ []]]", - "Reset a user's password", RunCommand); - - m_console.Commands.AddCommand("userserver", false, "login level", - "login level ", - "Set the minimum user level to log in", HandleLoginCommand); - - m_console.Commands.AddCommand("userserver", false, "login reset", - "login reset", - "Reset the login level to allow all users", - HandleLoginCommand); - - m_console.Commands.AddCommand("userserver", false, "login text", - "login text ", - "Set the text users will see on login", HandleLoginCommand); - - m_console.Commands.AddCommand("userserver", false, "test-inventory", - "test-inventory", - "Perform a test inventory transaction", RunCommand); - - m_console.Commands.AddCommand("userserver", false, "logoff-user", - "logoff-user ", - "Log off a named user", RunCommand); - } - - #region Console Command Handlers - public void do_create(string[] args) - { - switch (args[0]) - { - case "user": - CreateUser(args); - break; - } - } - - /// - /// Execute switch for some of the reset commands - /// - /// - protected void Reset(string[] args) - { - if (args.Length == 0) - return; - - switch (args[0]) - { - case "user": - - switch (args[1]) - { - case "password": - ResetUserPassword(args); - break; - } - - break; - } - } - - /// - /// Create a new user - /// - /// string array with parameters: firstname, lastname, password, locationX, locationY, email - protected void CreateUser(string[] cmdparams) - { - string firstName; - string lastName; - string password; - string email; - uint regX = 1000; - uint regY = 1000; - - if (cmdparams.Length < 2) - firstName = MainConsole.Instance.CmdPrompt("First name", "Default"); - else firstName = cmdparams[1]; - - if (cmdparams.Length < 3) - lastName = MainConsole.Instance.CmdPrompt("Last name", "User"); - else lastName = cmdparams[2]; - - if (cmdparams.Length < 4) - password = MainConsole.Instance.PasswdPrompt("Password"); - else password = cmdparams[3]; - - if (cmdparams.Length < 5) - regX = Convert.ToUInt32(MainConsole.Instance.CmdPrompt("Start Region X", regX.ToString())); - else regX = Convert.ToUInt32(cmdparams[4]); - - if (cmdparams.Length < 6) - regY = Convert.ToUInt32(MainConsole.Instance.CmdPrompt("Start Region Y", regY.ToString())); - else regY = Convert.ToUInt32(cmdparams[5]); - - if (cmdparams.Length < 7) - email = MainConsole.Instance.CmdPrompt("Email", ""); - else email = cmdparams[6]; - - if (null == m_userDataBaseService.GetUserProfile(firstName, lastName)) - { - m_lastCreatedUser = m_userDataBaseService.AddUser(firstName, lastName, password, email, regX, regY); - } - else - { - m_log.ErrorFormat("[USERS]: A user with the name {0} {1} already exists!", firstName, lastName); - } - } - - /// - /// Reset a user password. - /// - /// - private void ResetUserPassword(string[] cmdparams) - { - string firstName; - string lastName; - string newPassword; - - if (cmdparams.Length < 3) - firstName = MainConsole.Instance.CmdPrompt("First name"); - else firstName = cmdparams[2]; - - if (cmdparams.Length < 4) - lastName = MainConsole.Instance.CmdPrompt("Last name"); - else lastName = cmdparams[3]; - - if (cmdparams.Length < 5) - newPassword = MainConsole.Instance.PasswdPrompt("New password"); - else newPassword = cmdparams[4]; - - m_userDataBaseService.ResetUserPassword(firstName, lastName, newPassword); - } - - private void HandleTestCommand(string module, string[] cmd) - { - m_log.Info("test command received"); - } - - private void HandleLoginCommand(string module, string[] cmd) - { - string subcommand = cmd[1]; - - switch (subcommand) - { - case "level": - // Set the minimal level to allow login - // Useful to allow grid update without worrying about users. - // or fixing critical issues - // - if (cmd.Length > 2) - { - int level = Convert.ToInt32(cmd[2]); - m_loginService.setloginlevel(level); - } - break; - case "reset": - m_loginService.setloginlevel(0); - break; - case "text": - if (cmd.Length > 2) - { - m_loginService.setwelcometext(cmd[2]); - } - break; - } - } - - public void RunCommand(string module, string[] cmd) - { - List args = new List(cmd); - string command = cmd[0]; - - args.RemoveAt(0); - - string[] cmdparams = args.ToArray(); - - switch (command) - { - case "create": - do_create(cmdparams); - break; - - case "reset": - Reset(cmdparams); - break; - - - case "test-inventory": - // RestObjectPosterResponse> requester = new RestObjectPosterResponse>(); - // requester.ReturnResponseVal = TestResponse; - // requester.BeginPostObject(m_userManager._config.InventoryUrl + "RootFolders/", m_lastCreatedUser); - SynchronousRestObjectPoster.BeginPostObject>( - "POST", m_cfg.InventoryUrl + "RootFolders/", m_lastCreatedUser); - break; - - case "logoff-user": - if (cmdparams.Length >= 3) - { - string firstname = cmdparams[0]; - string lastname = cmdparams[1]; - string message = ""; - - for (int i = 2; i < cmdparams.Length; i++) - message += " " + cmdparams[i]; - - UserProfileData theUser = null; - try - { - theUser = m_loginService.GetTheUser(firstname, lastname); - } - catch (Exception) - { - m_log.Error("[LOGOFF]: Error getting user data from the database."); - } - - if (theUser != null) - { - if (theUser.CurrentAgent != null) - { - if (theUser.CurrentAgent.AgentOnline) - { - m_log.Info("[LOGOFF]: Logging off requested user!"); - m_loginService.LogOffUser(theUser, message); - - theUser.CurrentAgent.AgentOnline = false; - - m_loginService.CommitAgent(ref theUser); - } - else - { - m_log.Info( - "[LOGOFF]: User Doesn't appear to be online, sending the logoff message anyway."); - m_loginService.LogOffUser(theUser, message); - - theUser.CurrentAgent.AgentOnline = false; - - m_loginService.CommitAgent(ref theUser); - } - } - else - { - m_log.Error( - "[LOGOFF]: Unable to logoff-user. User doesn't have an agent record so I can't find the simulator to notify"); - } - } - else - { - m_log.Info("[LOGOFF]: User doesn't exist in the database"); - } - } - else - { - m_log.Error( - "[LOGOFF]: Invalid amount of parameters. logoff-user takes at least three. Firstname, Lastname, and message"); - } - - break; - } - } - } - #endregion -} +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSim Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using log4net; +using log4net.Config; +using OpenMetaverse; +using OpenSim.Data; +using OpenSim.Framework; +using OpenSim.Framework.Communications; +using OpenSim.Framework.Communications.Cache; +using OpenSim.Framework.Console; +using OpenSim.Framework.Servers; +using OpenSim.Framework.Statistics; +using OpenSim.Grid.Communications.OGS1; +using OpenSim.Grid.Framework; +using OpenSim.Grid.UserServer.Modules; + +namespace OpenSim.Grid.UserServer +{ + public class UserServerCommandModule + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + protected ConsoleBase m_console; + protected UserConfig m_cfg; + + protected UserDataBaseService m_userDataBaseService; + protected UserLoginService m_loginService; + + protected UUID m_lastCreatedUser = UUID.Random(); + + protected IUGAIMCore m_core; + + public UserServerCommandModule( UserLoginService loginService) + { + m_loginService = loginService; + } + + public void Initialise(IUGAIMCore core) + { + m_core = core; + } + + public void PostInitialise() + { + UserConfig cfg; + if (m_core.TryGet(out cfg)) + { + m_cfg = cfg; + } + + UserDataBaseService userDBservice; + if (m_core.TryGet(out userDBservice)) + { + m_userDataBaseService = userDBservice; + } + + ConsoleBase console; + if ((m_core.TryGet(out console)) && (m_cfg != null) && (m_userDataBaseService != null)) + { + RegisterConsoleCommands(console); + } + } + + public void RegisterHandlers(BaseHttpServer httpServer) + { + + } + + private void RegisterConsoleCommands(ConsoleBase console) + { + m_console = console; + m_console.Commands.AddCommand("userserver", false, "create user", + "create user [ [ [ [email]]]]", + "Create a new user account", RunCommand); + + m_console.Commands.AddCommand("userserver", false, "reset user password", + "reset user password [ [ []]]", + "Reset a user's password", RunCommand); + + m_console.Commands.AddCommand("userserver", false, "login level", + "login level ", + "Set the minimum user level to log in", HandleLoginCommand); + + m_console.Commands.AddCommand("userserver", false, "login reset", + "login reset", + "Reset the login level to allow all users", + HandleLoginCommand); + + m_console.Commands.AddCommand("userserver", false, "login text", + "login text ", + "Set the text users will see on login", HandleLoginCommand); + + m_console.Commands.AddCommand("userserver", false, "test-inventory", + "test-inventory", + "Perform a test inventory transaction", RunCommand); + + m_console.Commands.AddCommand("userserver", false, "logoff-user", + "logoff-user ", + "Log off a named user", RunCommand); + } + + #region Console Command Handlers + public void do_create(string[] args) + { + switch (args[0]) + { + case "user": + CreateUser(args); + break; + } + } + + /// + /// Execute switch for some of the reset commands + /// + /// + protected void Reset(string[] args) + { + if (args.Length == 0) + return; + + switch (args[0]) + { + case "user": + + switch (args[1]) + { + case "password": + ResetUserPassword(args); + break; + } + + break; + } + } + + /// + /// Create a new user + /// + /// string array with parameters: firstname, lastname, password, locationX, locationY, email + protected void CreateUser(string[] cmdparams) + { + string firstName; + string lastName; + string password; + string email; + uint regX = 1000; + uint regY = 1000; + + if (cmdparams.Length < 2) + firstName = MainConsole.Instance.CmdPrompt("First name", "Default"); + else firstName = cmdparams[1]; + + if (cmdparams.Length < 3) + lastName = MainConsole.Instance.CmdPrompt("Last name", "User"); + else lastName = cmdparams[2]; + + if (cmdparams.Length < 4) + password = MainConsole.Instance.PasswdPrompt("Password"); + else password = cmdparams[3]; + + if (cmdparams.Length < 5) + regX = Convert.ToUInt32(MainConsole.Instance.CmdPrompt("Start Region X", regX.ToString())); + else regX = Convert.ToUInt32(cmdparams[4]); + + if (cmdparams.Length < 6) + regY = Convert.ToUInt32(MainConsole.Instance.CmdPrompt("Start Region Y", regY.ToString())); + else regY = Convert.ToUInt32(cmdparams[5]); + + if (cmdparams.Length < 7) + email = MainConsole.Instance.CmdPrompt("Email", ""); + else email = cmdparams[6]; + + if (null == m_userDataBaseService.GetUserProfile(firstName, lastName)) + { + m_lastCreatedUser = m_userDataBaseService.AddUser(firstName, lastName, password, email, regX, regY); + } + else + { + m_log.ErrorFormat("[USERS]: A user with the name {0} {1} already exists!", firstName, lastName); + } + } + + /// + /// Reset a user password. + /// + /// + private void ResetUserPassword(string[] cmdparams) + { + string firstName; + string lastName; + string newPassword; + + if (cmdparams.Length < 3) + firstName = MainConsole.Instance.CmdPrompt("First name"); + else firstName = cmdparams[2]; + + if (cmdparams.Length < 4) + lastName = MainConsole.Instance.CmdPrompt("Last name"); + else lastName = cmdparams[3]; + + if (cmdparams.Length < 5) + newPassword = MainConsole.Instance.PasswdPrompt("New password"); + else newPassword = cmdparams[4]; + + m_userDataBaseService.ResetUserPassword(firstName, lastName, newPassword); + } + + private void HandleTestCommand(string module, string[] cmd) + { + m_log.Info("test command received"); + } + + private void HandleLoginCommand(string module, string[] cmd) + { + string subcommand = cmd[1]; + + switch (subcommand) + { + case "level": + // Set the minimal level to allow login + // Useful to allow grid update without worrying about users. + // or fixing critical issues + // + if (cmd.Length > 2) + { + int level = Convert.ToInt32(cmd[2]); + m_loginService.setloginlevel(level); + } + break; + case "reset": + m_loginService.setloginlevel(0); + break; + case "text": + if (cmd.Length > 2) + { + m_loginService.setwelcometext(cmd[2]); + } + break; + } + } + + public void RunCommand(string module, string[] cmd) + { + List args = new List(cmd); + string command = cmd[0]; + + args.RemoveAt(0); + + string[] cmdparams = args.ToArray(); + + switch (command) + { + case "create": + do_create(cmdparams); + break; + + case "reset": + Reset(cmdparams); + break; + + + case "test-inventory": + // RestObjectPosterResponse> requester = new RestObjectPosterResponse>(); + // requester.ReturnResponseVal = TestResponse; + // requester.BeginPostObject(m_userManager._config.InventoryUrl + "RootFolders/", m_lastCreatedUser); + SynchronousRestObjectPoster.BeginPostObject>( + "POST", m_cfg.InventoryUrl + "RootFolders/", m_lastCreatedUser); + break; + + case "logoff-user": + if (cmdparams.Length >= 3) + { + string firstname = cmdparams[0]; + string lastname = cmdparams[1]; + string message = ""; + + for (int i = 2; i < cmdparams.Length; i++) + message += " " + cmdparams[i]; + + UserProfileData theUser = null; + try + { + theUser = m_loginService.GetTheUser(firstname, lastname); + } + catch (Exception) + { + m_log.Error("[LOGOFF]: Error getting user data from the database."); + } + + if (theUser != null) + { + if (theUser.CurrentAgent != null) + { + if (theUser.CurrentAgent.AgentOnline) + { + m_log.Info("[LOGOFF]: Logging off requested user!"); + m_loginService.LogOffUser(theUser, message); + + theUser.CurrentAgent.AgentOnline = false; + + m_loginService.CommitAgent(ref theUser); + } + else + { + m_log.Info( + "[LOGOFF]: User Doesn't appear to be online, sending the logoff message anyway."); + m_loginService.LogOffUser(theUser, message); + + theUser.CurrentAgent.AgentOnline = false; + + m_loginService.CommitAgent(ref theUser); + } + } + else + { + m_log.Error( + "[LOGOFF]: Unable to logoff-user. User doesn't have an agent record so I can't find the simulator to notify"); + } + } + else + { + m_log.Info("[LOGOFF]: User doesn't exist in the database"); + } + } + else + { + m_log.Error( + "[LOGOFF]: Invalid amount of parameters. logoff-user takes at least three. Firstname, Lastname, and message"); + } + + break; + } + } + } + #endregion +} -- cgit v1.1