From 134f86e8d5c414409631b25b8c6f0ee45fbd8631 Mon Sep 17 00:00:00 2001 From: David Walter Seikel Date: Thu, 3 Nov 2016 21:44:39 +1000 Subject: Initial update to OpenSim 0.8.2.1 source code. --- .../AgentPreferencesServerPostHandler.cs | 206 +++++++++ .../AgentPreferencesServiceConnector.cs | 64 +++ .../Server/Handlers/Asset/AssetServerConnector.cs | 26 +- .../Handlers/Asset/AssetServerDeleteHandler.cs | 9 +- .../Server/Handlers/Asset/AssetServerGetHandler.cs | 100 ++-- .../Handlers/Asset/AssetServerPostHandler.cs | 28 +- .../Server/Handlers/Asset/AssetsExistHandler.cs | 87 ++++ .../Asset/Tests/AssetServerPostHandlerTests.cs | 1 - .../AuthenticationServerConnector.cs | 5 +- .../AuthenticationServerPostHandler.cs | 27 +- .../Handlers/Authentication/OpenIdServerHandler.cs | 30 +- .../AuthorizationServerPostHandler.cs | 2 +- .../Handlers/Avatar/AvatarServerConnector.cs | 5 +- .../Handlers/Avatar/AvatarServerPostHandler.cs | 22 +- OpenSim/Server/Handlers/BakedTextures/XBakes.cs | 148 ++++++ .../Handlers/BakedTextures/XBakesGetHandler.cs | 71 +++ .../Server/Handlers/BakedTextures/XBakesHandler.cs | 69 +++ .../Handlers/BakedTextures/XBakesPostHandler.cs | 76 +++ .../Handlers/Estate/EstateDataRobustConnector.cs | 343 ++++++++++++++ .../Handlers/Friends/FriendServerConnector.cs | 4 +- .../Handlers/Friends/FriendsServerPostHandler.cs | 22 +- OpenSim/Server/Handlers/Grid/GridInfoHandlers.cs | 21 +- .../Server/Handlers/Grid/GridServerConnector.cs | 5 +- .../Server/Handlers/Grid/GridServerPostHandler.cs | 99 +++- .../Handlers/GridUser/GridUserServerConnector.cs | 5 +- .../Handlers/GridUser/GridUserServerPostHandler.cs | 29 +- OpenSim/Server/Handlers/Hypergrid/AgentHandlers.cs | 5 +- .../Hypergrid/GatekeeperServerConnector.cs | 8 +- .../Hypergrid/HGFriendsServerPostHandler.cs | 22 +- .../Handlers/Hypergrid/HeloServerConnector.cs | 4 +- .../Server/Handlers/Hypergrid/HomeAgentHandlers.cs | 202 ++------ .../Server/Handlers/Hypergrid/HypergridHandlers.cs | 20 +- .../Hypergrid/InstantMessageServerConnector.cs | 7 +- .../Handlers/Hypergrid/UserAgentServerConnector.cs | 19 +- .../Inventory/InventoryServerInConnector.cs | 10 - .../Inventory/InventoryServerMoveItemsHandler.cs | 2 +- .../Handlers/Inventory/XInventoryInConnector.cs | 179 ++++--- OpenSim/Server/Handlers/Login/LLLoginHandlers.cs | 67 +++ .../Handlers/Login/LLLoginServiceInConnector.cs | 25 +- .../Server/Handlers/Map/MapAddServerConnector.cs | 35 +- .../Server/Handlers/Map/MapGetServerConnector.cs | 2 +- .../Server/Handlers/Neighbour/NeighbourHandlers.cs | 8 +- .../Handlers/Presence/PresenceServerConnector.cs | 5 +- .../Handlers/Presence/PresenceServerPostHandler.cs | 22 +- .../Handlers/Profiles/UserProfilesConnector.cs | 109 +++++ .../Handlers/Profiles/UserProfilesHandlers.cs | 513 +++++++++++++++++++++ OpenSim/Server/Handlers/Properties/AssemblyInfo.cs | 4 +- .../Server/Handlers/Simulation/AgentHandlers.cs | 369 ++++++++++----- .../UserAccounts/UserAccountServerConnector.cs | 5 +- .../UserAccounts/UserAccountServerPostHandler.cs | 27 +- 50 files changed, 2564 insertions(+), 609 deletions(-) create mode 100644 OpenSim/Server/Handlers/AgentPreferences/AgentPreferencesServerPostHandler.cs create mode 100644 OpenSim/Server/Handlers/AgentPreferences/AgentPreferencesServiceConnector.cs create mode 100644 OpenSim/Server/Handlers/Asset/AssetsExistHandler.cs create mode 100644 OpenSim/Server/Handlers/BakedTextures/XBakes.cs create mode 100644 OpenSim/Server/Handlers/BakedTextures/XBakesGetHandler.cs create mode 100644 OpenSim/Server/Handlers/BakedTextures/XBakesHandler.cs create mode 100644 OpenSim/Server/Handlers/BakedTextures/XBakesPostHandler.cs create mode 100644 OpenSim/Server/Handlers/Estate/EstateDataRobustConnector.cs create mode 100644 OpenSim/Server/Handlers/Profiles/UserProfilesConnector.cs create mode 100644 OpenSim/Server/Handlers/Profiles/UserProfilesHandlers.cs (limited to 'OpenSim/Server/Handlers') diff --git a/OpenSim/Server/Handlers/AgentPreferences/AgentPreferencesServerPostHandler.cs b/OpenSim/Server/Handlers/AgentPreferences/AgentPreferencesServerPostHandler.cs new file mode 100644 index 0000000..713b755 --- /dev/null +++ b/OpenSim/Server/Handlers/AgentPreferences/AgentPreferencesServerPostHandler.cs @@ -0,0 +1,206 @@ +/* + * 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 Nini.Config; +using log4net; +using System; +using System.Reflection; +using System.IO; +using System.Net; +using System.Text; +using System.Text.RegularExpressions; +using System.Xml; +using System.Xml.Serialization; +using System.Collections.Generic; +using OpenSim.Server.Base; +using OpenSim.Services.Interfaces; +using OpenSim.Framework; +using OpenSim.Framework.ServiceAuth; +using OpenSim.Framework.Servers.HttpServer; +using OpenMetaverse; + +namespace OpenSim.Server.Handlers.AgentPreferences +{ + public class AgentPreferencesServerPostHandler : BaseStreamHandler + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private IAgentPreferencesService m_AgentPreferencesService; + + public AgentPreferencesServerPostHandler(IAgentPreferencesService service, IServiceAuth auth) : + base("POST", "/agentprefs", auth) + { + m_AgentPreferencesService = service; + } + + protected override byte[] ProcessRequest(string path, Stream requestData, + IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) + { + StreamReader sr = new StreamReader(requestData); + string body = sr.ReadToEnd(); + sr.Close(); + body = body.Trim(); + + //m_log.DebugFormat("[XXX]: query String: {0}", body); + + try + { + Dictionary request = + ServerUtils.ParseQueryString(body); + + if (!request.ContainsKey("METHOD")) + return FailureResult(); + + string method = request["METHOD"].ToString(); + + switch (method) + { + case "getagentprefs": + return GetAgentPrefs(request); + case "setagentprefs": + return SetAgentPrefs(request); + case "getagentlang": + return GetAgentLang(request); + } + m_log.DebugFormat("[AGENT PREFERENCES HANDLER]: unknown method request: {0}", method); + } + catch (Exception e) + { + m_log.DebugFormat("[AGENT PREFERENCES HANDLER]: Exception {0}", e); + } + + return FailureResult(); + } + + byte[] GetAgentPrefs(Dictionary request) + { + if (!request.ContainsKey("UserID")) + return FailureResult(); + + UUID userID; + if (!UUID.TryParse(request["UserID"].ToString(), out userID)) + return FailureResult(); + AgentPrefs prefs = m_AgentPreferencesService.GetAgentPreferences(userID); + Dictionary result = new Dictionary(); + result = prefs.ToKeyValuePairs(); + + string xmlString = ServerUtils.BuildXmlResponse(result); + + return Util.UTF8NoBomEncoding.GetBytes(xmlString); + } + + byte[] SetAgentPrefs(Dictionary request) + { + if (!request.ContainsKey("PrincipalID") || !request.ContainsKey("AccessPrefs") || !request.ContainsKey("HoverHeight") + || !request.ContainsKey("Language") || !request.ContainsKey("LanguageIsPublic") || !request.ContainsKey("PermEveryone") + || !request.ContainsKey("PermGroup") || !request.ContainsKey("PermNextOwner")) + { + return FailureResult(); + } + + UUID userID; + if (!UUID.TryParse(request["PrincipalID"].ToString(), out userID)) + return FailureResult(); + + AgentPrefs data = new AgentPrefs(userID); + data.AccessPrefs = request["AccessPrefs"].ToString(); + data.HoverHeight = double.Parse(request["HoverHeight"].ToString()); + data.Language = request["Language"].ToString(); + data.LanguageIsPublic = bool.Parse(request["LanguageIsPublic"].ToString()); + data.PermEveryone = int.Parse(request["PermEveryone"].ToString()); + data.PermGroup = int.Parse(request["PermGroup"].ToString()); + data.PermNextOwner = int.Parse(request["PermNextOwner"].ToString()); + + return m_AgentPreferencesService.StoreAgentPreferences(data) ? SuccessResult() : FailureResult(); + } + + byte[] GetAgentLang(Dictionary request) + { + if (!request.ContainsKey("UserID")) + return FailureResult(); + UUID userID; + if (!UUID.TryParse(request["UserID"].ToString(), out userID)) + return FailureResult(); + + string lang = "en-us"; + AgentPrefs prefs = m_AgentPreferencesService.GetAgentPreferences(userID); + if (prefs != null) + { + if (prefs.LanguageIsPublic) + lang = prefs.Language; + } + Dictionary result = new Dictionary(); + result["Language"] = lang; + string xmlString = ServerUtils.BuildXmlResponse(result); + return Util.UTF8NoBomEncoding.GetBytes(xmlString); + } + + private byte[] SuccessResult() + { + XmlDocument doc = new XmlDocument(); + + XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, + "", ""); + + doc.AppendChild(xmlnode); + + XmlElement rootElement = doc.CreateElement("", "ServerResponse", + ""); + + doc.AppendChild(rootElement); + + XmlElement result = doc.CreateElement("", "result", ""); + result.AppendChild(doc.CreateTextNode("Success")); + + rootElement.AppendChild(result); + + return Util.DocToBytes(doc); + } + + private byte[] FailureResult() + { + XmlDocument doc = new XmlDocument(); + + XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, + "", ""); + + doc.AppendChild(xmlnode); + + XmlElement rootElement = doc.CreateElement("", "ServerResponse", + ""); + + doc.AppendChild(rootElement); + + XmlElement result = doc.CreateElement("", "result", ""); + result.AppendChild(doc.CreateTextNode("Failure")); + + rootElement.AppendChild(result); + + return Util.DocToBytes(doc); + } + } +} diff --git a/OpenSim/Server/Handlers/AgentPreferences/AgentPreferencesServiceConnector.cs b/OpenSim/Server/Handlers/AgentPreferences/AgentPreferencesServiceConnector.cs new file mode 100644 index 0000000..a581ea2 --- /dev/null +++ b/OpenSim/Server/Handlers/AgentPreferences/AgentPreferencesServiceConnector.cs @@ -0,0 +1,64 @@ +/* + * 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 Nini.Config; +using OpenSim.Server.Base; +using OpenSim.Services.Interfaces; +using OpenSim.Framework.ServiceAuth; +using OpenSim.Framework.Servers.HttpServer; +using OpenSim.Server.Handlers.Base; + +namespace OpenSim.Server.Handlers.AgentPreferences +{ + public class AgentPreferencesServiceConnector : ServiceConnector + { + private IAgentPreferencesService m_AgentPreferencesService; + private string m_ConfigName = "AgentPreferencesService"; + + public AgentPreferencesServiceConnector(IConfigSource config, IHttpServer server, string configName) : + base(config, server, configName) + { + IConfig serverConfig = config.Configs[m_ConfigName]; + if (serverConfig == null) + throw new Exception(String.Format("No section {0} in config file", m_ConfigName)); + + string service = serverConfig.GetString("LocalServiceModule", String.Empty); + + if (String.IsNullOrWhiteSpace(service)) + throw new Exception("No LocalServiceModule in config file"); + + Object[] args = new Object[] { config }; + m_AgentPreferencesService = ServerUtils.LoadPlugin(service, args); + + IServiceAuth auth = ServiceAuth.Create(config, m_ConfigName); ; + + server.AddStreamHandler(new AgentPreferencesServerPostHandler(m_AgentPreferencesService, auth)); + } + } +} diff --git a/OpenSim/Server/Handlers/Asset/AssetServerConnector.cs b/OpenSim/Server/Handlers/Asset/AssetServerConnector.cs index ff45d94..ab81dd6 100644 --- a/OpenSim/Server/Handlers/Asset/AssetServerConnector.cs +++ b/OpenSim/Server/Handlers/Asset/AssetServerConnector.cs @@ -30,6 +30,7 @@ using System.IO; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; +using OpenSim.Framework.ServiceAuth; using OpenSim.Framework.Console; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; @@ -69,6 +70,8 @@ namespace OpenSim.Server.Handlers.Asset bool allowDelete = serverConfig.GetBoolean("AllowRemoteDelete", false); bool allowDeleteAllTypes = serverConfig.GetBoolean("AllowRemoteDeleteAllTypes", false); + string redirectURL = serverConfig.GetString("RedirectURL", string.Empty); + AllowedRemoteDeleteTypes allowedRemoteDeleteTypes; if (!allowDelete) @@ -83,9 +86,12 @@ namespace OpenSim.Server.Handlers.Asset allowedRemoteDeleteTypes = AllowedRemoteDeleteTypes.MapTile; } - server.AddStreamHandler(new AssetServerGetHandler(m_AssetService)); - server.AddStreamHandler(new AssetServerPostHandler(m_AssetService)); - server.AddStreamHandler(new AssetServerDeleteHandler(m_AssetService, allowedRemoteDeleteTypes)); + IServiceAuth auth = ServiceAuth.Create(config, m_ConfigName); + + server.AddStreamHandler(new AssetServerGetHandler(m_AssetService, auth, redirectURL)); + server.AddStreamHandler(new AssetServerPostHandler(m_AssetService, auth)); + server.AddStreamHandler(new AssetServerDeleteHandler(m_AssetService, allowedRemoteDeleteTypes, auth)); + server.AddStreamHandler(new AssetsExistHandler(m_AssetService)); MainConsole.Instance.Commands.AddCommand("Assets", false, "show asset", @@ -119,16 +125,14 @@ namespace OpenSim.Server.Handlers.Asset if (asset == null || asset.Data.Length == 0) { - MainConsole.Instance.Output("Asset not found"); + MainConsole.Instance.OutputFormat("Could not find asset with ID {0}", args[2]); return; } - m_AssetService.Delete(args[2]); - - //MainConsole.Instance.Output("Asset deleted"); - // TODO: Implement this - - MainConsole.Instance.Output("Asset deletion not supported by database"); + if (!m_AssetService.Delete(asset.ID)) + MainConsole.Instance.OutputFormat("ERROR: Could not delete asset {0} {1}", asset.ID, asset.Name); + else + MainConsole.Instance.OutputFormat("Deleted asset {0} {1}", asset.ID, asset.Name); } void HandleDumpAsset(string module, string[] args) @@ -214,4 +218,4 @@ namespace OpenSim.Server.Handlers.Asset } } } -} \ No newline at end of file +} diff --git a/OpenSim/Server/Handlers/Asset/AssetServerDeleteHandler.cs b/OpenSim/Server/Handlers/Asset/AssetServerDeleteHandler.cs index 986394b..d85d471 100644 --- a/OpenSim/Server/Handlers/Asset/AssetServerDeleteHandler.cs +++ b/OpenSim/Server/Handlers/Asset/AssetServerDeleteHandler.cs @@ -38,6 +38,7 @@ using System.Xml.Serialization; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenSim.Framework; +using OpenSim.Framework.ServiceAuth; using OpenSim.Framework.Servers.HttpServer; namespace OpenSim.Server.Handlers.Asset @@ -70,7 +71,13 @@ namespace OpenSim.Server.Handlers.Asset m_allowedTypes = allowedTypes; } - public override byte[] Handle(string path, Stream request, + public AssetServerDeleteHandler(IAssetService service, AllowedRemoteDeleteTypes allowedTypes, IServiceAuth auth) : + base("DELETE", "/assets", auth) + { + m_AssetService = service; + m_allowedTypes = allowedTypes; + } + protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { bool result = false; diff --git a/OpenSim/Server/Handlers/Asset/AssetServerGetHandler.cs b/OpenSim/Server/Handlers/Asset/AssetServerGetHandler.cs index 8f7412b..91c5c54 100644 --- a/OpenSim/Server/Handlers/Asset/AssetServerGetHandler.cs +++ b/OpenSim/Server/Handlers/Asset/AssetServerGetHandler.cs @@ -38,23 +38,34 @@ using System.Xml.Serialization; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenSim.Framework; +using OpenSim.Framework.ServiceAuth; using OpenSim.Framework.Servers.HttpServer; namespace OpenSim.Server.Handlers.Asset { public class AssetServerGetHandler : BaseStreamHandler { - // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IAssetService m_AssetService; + private string m_RedirectURL; public AssetServerGetHandler(IAssetService service) : base("GET", "/assets") { + m_AssetService = service; + } + + public AssetServerGetHandler(IAssetService service, IServiceAuth auth, string redirectURL) : + base("GET", "/assets", auth) + { m_AssetService = service; + m_RedirectURL = redirectURL; + if (!m_RedirectURL.EndsWith("/")) + m_RedirectURL = m_RedirectURL.TrimEnd('/'); } - public override byte[] Handle(string path, Stream request, + protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { byte[] result = new byte[0]; @@ -64,45 +75,62 @@ namespace OpenSim.Server.Handlers.Asset if (p.Length == 0) return result; - if (p.Length > 1 && p[1] == "data") + string id = string.Empty; + if (p.Length > 1) { - result = m_AssetService.GetData(p[0]); - if (result == null) + id = p[0]; + string cmd = p[1]; + + if (cmd == "data") { - httpResponse.StatusCode = (int)HttpStatusCode.NotFound; - httpResponse.ContentType = "text/plain"; - result = new byte[0]; + result = m_AssetService.GetData(id); + if (result == null) + { + httpResponse.StatusCode = (int)HttpStatusCode.NotFound; + httpResponse.ContentType = "text/plain"; + result = new byte[0]; + } + else + { + httpResponse.StatusCode = (int)HttpStatusCode.OK; + httpResponse.ContentType = "application/octet-stream"; + } } - else + else if (cmd == "metadata") { - httpResponse.StatusCode = (int)HttpStatusCode.OK; - httpResponse.ContentType = "application/octet-stream"; - } - } - else if (p.Length > 1 && p[1] == "metadata") - { - AssetMetadata metadata = m_AssetService.GetMetadata(p[0]); + AssetMetadata metadata = m_AssetService.GetMetadata(id); - if (metadata != null) - { - XmlSerializer xs = - new XmlSerializer(typeof(AssetMetadata)); - result = ServerUtils.SerializeResult(xs, metadata); + if (metadata != null) + { + XmlSerializer xs = + new XmlSerializer(typeof(AssetMetadata)); + result = ServerUtils.SerializeResult(xs, metadata); - httpResponse.StatusCode = (int)HttpStatusCode.OK; - httpResponse.ContentType = - SLUtil.SLAssetTypeToContentType(metadata.Type); + httpResponse.StatusCode = (int)HttpStatusCode.OK; + httpResponse.ContentType = + SLUtil.SLAssetTypeToContentType(metadata.Type); + } + else + { + httpResponse.StatusCode = (int)HttpStatusCode.NotFound; + httpResponse.ContentType = "text/plain"; + result = new byte[0]; + } } else { - httpResponse.StatusCode = (int)HttpStatusCode.NotFound; + // Unknown request + httpResponse.StatusCode = (int)HttpStatusCode.BadRequest; httpResponse.ContentType = "text/plain"; result = new byte[0]; } } - else + else if (p.Length == 1) { - AssetBase asset = m_AssetService.Get(p[0]); + // Get the entire asset (metadata + data) + + id = p[0]; + AssetBase asset = m_AssetService.Get(id); if (asset != null) { @@ -120,6 +148,24 @@ namespace OpenSim.Server.Handlers.Asset result = new byte[0]; } } + else + { + // Unknown request + httpResponse.StatusCode = (int)HttpStatusCode.BadRequest; + httpResponse.ContentType = "text/plain"; + result = new byte[0]; + } + + if (httpResponse.StatusCode == (int)HttpStatusCode.NotFound && !string.IsNullOrEmpty(m_RedirectURL) && !string.IsNullOrEmpty(id)) + { + httpResponse.StatusCode = (int)HttpStatusCode.Redirect; + string rurl = m_RedirectURL; + if (!path.StartsWith("/")) + rurl += "/"; + rurl += path; + httpResponse.AddHeader("Location", rurl); + m_log.DebugFormat("[ASSET GET HANDLER]: Asset not found, redirecting to {0} ({1})", rurl, httpResponse.StatusCode); + } return result; } } diff --git a/OpenSim/Server/Handlers/Asset/AssetServerPostHandler.cs b/OpenSim/Server/Handlers/Asset/AssetServerPostHandler.cs index a006fa8..1c706a7 100644 --- a/OpenSim/Server/Handlers/Asset/AssetServerPostHandler.cs +++ b/OpenSim/Server/Handlers/Asset/AssetServerPostHandler.cs @@ -38,6 +38,7 @@ using System.Xml.Serialization; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenSim.Framework; +using OpenSim.Framework.ServiceAuth; using OpenSim.Framework.Servers.HttpServer; namespace OpenSim.Server.Handlers.Asset @@ -54,35 +55,44 @@ namespace OpenSim.Server.Handlers.Asset m_AssetService = service; } - public override byte[] Handle(string path, Stream request, + public AssetServerPostHandler(IAssetService service, IServiceAuth auth) : + base("POST", "/assets", auth) + { + m_AssetService = service; + } + + protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { AssetBase asset; - XmlSerializer xs = new XmlSerializer(typeof (AssetBase)); + XmlSerializer xs = new XmlSerializer(typeof(AssetBase)); try { asset = (AssetBase)xs.Deserialize(request); } - catch (XmlException) + catch (Exception) { httpResponse.StatusCode = (int)HttpStatusCode.BadRequest; return null; } string[] p = SplitParams(path); - if (p.Length > 1) + if (p.Length > 0) { - bool result = m_AssetService.UpdateContent(p[1], asset.Data); + string id = p[0]; + bool result = m_AssetService.UpdateContent(id, asset.Data); xs = new XmlSerializer(typeof(bool)); return ServerUtils.SerializeResult(xs, result); } + else + { + string id = m_AssetService.Store(asset); - string id = m_AssetService.Store(asset); - - xs = new XmlSerializer(typeof(string)); - return ServerUtils.SerializeResult(xs, id); + xs = new XmlSerializer(typeof(string)); + return ServerUtils.SerializeResult(xs, id); + } } } } diff --git a/OpenSim/Server/Handlers/Asset/AssetsExistHandler.cs b/OpenSim/Server/Handlers/Asset/AssetsExistHandler.cs new file mode 100644 index 0000000..32901b3 --- /dev/null +++ b/OpenSim/Server/Handlers/Asset/AssetsExistHandler.cs @@ -0,0 +1,87 @@ +/* + * 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 Nini.Config; +using log4net; +using System; +using System.Reflection; +using System.IO; +using System.Net; +using System.Text; +using System.Text.RegularExpressions; +using System.Xml; +using System.Xml.Serialization; +using OpenSim.Server.Base; +using OpenSim.Services.Interfaces; +using OpenSim.Framework; +using OpenSim.Framework.ServiceAuth; +using OpenSim.Framework.Servers.HttpServer; +using OpenMetaverse; + +namespace OpenSim.Server.Handlers.Asset +{ + public class AssetsExistHandler : BaseStreamHandler + { + //private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private IAssetService m_AssetService; + + public AssetsExistHandler(IAssetService service) : + base("POST", "/get_assets_exist") + { + m_AssetService = service; + } + + public AssetsExistHandler(IAssetService service, IServiceAuth auth) : + base("POST", "/get_assets_exist", auth) + { + m_AssetService = service; + } + + protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) + { + XmlSerializer xs; + + string[] ids; + try + { + xs = new XmlSerializer(typeof(string[])); + ids = (string[])xs.Deserialize(request); + } + catch (Exception) + { + httpResponse.StatusCode = (int)HttpStatusCode.BadRequest; + return null; + } + + bool[] exist = m_AssetService.AssetsExist(ids); + + xs = new XmlSerializer(typeof(bool[])); + return ServerUtils.SerializeResult(xs, exist); + } + } +} diff --git a/OpenSim/Server/Handlers/Asset/Tests/AssetServerPostHandlerTests.cs b/OpenSim/Server/Handlers/Asset/Tests/AssetServerPostHandlerTests.cs index 427fa16..faa6fb7 100644 --- a/OpenSim/Server/Handlers/Asset/Tests/AssetServerPostHandlerTests.cs +++ b/OpenSim/Server/Handlers/Asset/Tests/AssetServerPostHandlerTests.cs @@ -39,7 +39,6 @@ using OpenSim.Server.Handlers.Asset; using OpenSim.Services.AssetService; using OpenSim.Services.Interfaces; using OpenSim.Tests.Common; -using OpenSim.Tests.Common.Mock; namespace OpenSim.Server.Handlers.Asset.Test { diff --git a/OpenSim/Server/Handlers/Authentication/AuthenticationServerConnector.cs b/OpenSim/Server/Handlers/Authentication/AuthenticationServerConnector.cs index 848a037..c9a8dce 100644 --- a/OpenSim/Server/Handlers/Authentication/AuthenticationServerConnector.cs +++ b/OpenSim/Server/Handlers/Authentication/AuthenticationServerConnector.cs @@ -29,6 +29,7 @@ using System; using Nini.Config; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; +using OpenSim.Framework.ServiceAuth; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Server.Handlers.Base; @@ -58,7 +59,9 @@ namespace OpenSim.Server.Handlers.Authentication Object[] args = new Object[] { config }; m_AuthenticationService = ServerUtils.LoadPlugin(authenticationService, args); - server.AddStreamHandler(new AuthenticationServerPostHandler(m_AuthenticationService, serverConfig)); + IServiceAuth auth = ServiceAuth.Create(config, m_ConfigName); + + server.AddStreamHandler(new AuthenticationServerPostHandler(m_AuthenticationService, serverConfig, auth)); } } } diff --git a/OpenSim/Server/Handlers/Authentication/AuthenticationServerPostHandler.cs b/OpenSim/Server/Handlers/Authentication/AuthenticationServerPostHandler.cs index 6b93cd9..6ee98b3 100644 --- a/OpenSim/Server/Handlers/Authentication/AuthenticationServerPostHandler.cs +++ b/OpenSim/Server/Handlers/Authentication/AuthenticationServerPostHandler.cs @@ -39,6 +39,7 @@ using System.Collections.Generic; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenSim.Framework; +using OpenSim.Framework.ServiceAuth; using OpenSim.Framework.Servers.HttpServer; using OpenMetaverse; @@ -55,10 +56,10 @@ namespace OpenSim.Server.Handlers.Authentication private bool m_AllowSetPassword = false; public AuthenticationServerPostHandler(IAuthenticationService service) : - this(service, null) {} + this(service, null, null) {} - public AuthenticationServerPostHandler(IAuthenticationService service, IConfig config) : - base("POST", "/auth") + public AuthenticationServerPostHandler(IAuthenticationService service, IConfig config, IServiceAuth auth) : + base("POST", "/auth", auth) { m_AuthenticationService = service; @@ -70,9 +71,10 @@ namespace OpenSim.Server.Handlers.Authentication } } - public override byte[] Handle(string path, Stream request, + protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { +// m_log.Error("[XXX]: Authenticating..."); string[] p = SplitParams(path); if (p.Length > 0) @@ -207,7 +209,7 @@ namespace OpenSim.Server.Handlers.Authentication rootElement.AppendChild(result); - return DocToBytes(doc); + return Util.DocToBytes(doc); } byte[] GetAuthInfo(UUID principalID) @@ -277,7 +279,7 @@ namespace OpenSim.Server.Handlers.Authentication rootElement.AppendChild(result); - return DocToBytes(doc); + return Util.DocToBytes(doc); } private byte[] SuccessResult(string token) @@ -304,18 +306,7 @@ namespace OpenSim.Server.Handlers.Authentication rootElement.AppendChild(t); - return DocToBytes(doc); - } - - private byte[] DocToBytes(XmlDocument doc) - { - MemoryStream ms = new MemoryStream(); - XmlTextWriter xw = new XmlTextWriter(ms, null); - xw.Formatting = Formatting.Indented; - doc.WriteTo(xw); - xw.Flush(); - - return ms.GetBuffer(); + return Util.DocToBytes(doc); } private byte[] ResultToBytes(Dictionary result) diff --git a/OpenSim/Server/Handlers/Authentication/OpenIdServerHandler.cs b/OpenSim/Server/Handlers/Authentication/OpenIdServerHandler.cs index 18cef15..b201dc7 100644 --- a/OpenSim/Server/Handlers/Authentication/OpenIdServerHandler.cs +++ b/OpenSim/Server/Handlers/Authentication/OpenIdServerHandler.cs @@ -147,7 +147,7 @@ namespace OpenSim.Server.Handlers.Authentication #endregion } - public class OpenIdStreamHandler : IStreamHandler + public class OpenIdStreamHandler : BaseOutputStreamHandler, IStreamHandler { #region HTML @@ -191,42 +191,34 @@ For more information, see http://openid.net/. #endregion HTML - public string Name { get { return "OpenId"; } } - public string Description { get { return null; } } - 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; IAuthenticationService m_authenticationService; IUserAccountService m_userAccountService; ProviderMemoryStore m_openidStore = new ProviderMemoryStore(); + public override string ContentType { get { return "text/html"; } } + /// /// Constructor /// - public OpenIdStreamHandler(string httpMethod, string path, IUserAccountService userService, IAuthenticationService authService) + public OpenIdStreamHandler( + string httpMethod, string path, IUserAccountService userService, IAuthenticationService authService) + : base(httpMethod, path, "OpenId", "OpenID stream handler") { m_authenticationService = authService; m_userAccountService = userService; - 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, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) + protected override void ProcessRequest( + string path, Stream request, Stream response, IOSHttpRequest httpRequest, IOSHttpResponse 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"; + httpResponse.ContentType = ContentType; try { @@ -276,7 +268,7 @@ For more information, see http://openid.net/. string[] contentTypeValues = provider.Request.Response.Headers.GetValues("Content-Type"); if (contentTypeValues != null && contentTypeValues.Length == 1) - m_contentType = contentTypeValues[0]; + httpResponse.ContentType = contentTypeValues[0]; // Set the response code and document body based on the OpenID result httpResponse.StatusCode = (int)provider.Request.Response.Code; @@ -344,4 +336,4 @@ For more information, see http://openid.net/. return false; } } -} +} \ No newline at end of file diff --git a/OpenSim/Server/Handlers/Authorization/AuthorizationServerPostHandler.cs b/OpenSim/Server/Handlers/Authorization/AuthorizationServerPostHandler.cs index bcf9d47..c9b4e9b 100644 --- a/OpenSim/Server/Handlers/Authorization/AuthorizationServerPostHandler.cs +++ b/OpenSim/Server/Handlers/Authorization/AuthorizationServerPostHandler.cs @@ -54,7 +54,7 @@ namespace OpenSim.Server.Handlers.Authorization m_AuthorizationService = service; } - public override byte[] Handle(string path, Stream request, + protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { XmlSerializer xs = new XmlSerializer(typeof (AuthorizationRequest)); diff --git a/OpenSim/Server/Handlers/Avatar/AvatarServerConnector.cs b/OpenSim/Server/Handlers/Avatar/AvatarServerConnector.cs index 9a57cd9..1831e84 100644 --- a/OpenSim/Server/Handlers/Avatar/AvatarServerConnector.cs +++ b/OpenSim/Server/Handlers/Avatar/AvatarServerConnector.cs @@ -29,6 +29,7 @@ using System; using Nini.Config; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; +using OpenSim.Framework.ServiceAuth; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Server.Handlers.Base; @@ -55,7 +56,9 @@ namespace OpenSim.Server.Handlers.Avatar Object[] args = new Object[] { config }; m_AvatarService = ServerUtils.LoadPlugin(avatarService, args); - server.AddStreamHandler(new AvatarServerPostHandler(m_AvatarService)); + IServiceAuth auth = ServiceAuth.Create(config, m_ConfigName); + + server.AddStreamHandler(new AvatarServerPostHandler(m_AvatarService, auth)); } } } diff --git a/OpenSim/Server/Handlers/Avatar/AvatarServerPostHandler.cs b/OpenSim/Server/Handlers/Avatar/AvatarServerPostHandler.cs index 8cd747e..ff8699f 100644 --- a/OpenSim/Server/Handlers/Avatar/AvatarServerPostHandler.cs +++ b/OpenSim/Server/Handlers/Avatar/AvatarServerPostHandler.cs @@ -39,6 +39,7 @@ using System.Collections.Generic; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenSim.Framework; +using OpenSim.Framework.ServiceAuth; using OpenSim.Framework.Servers.HttpServer; using OpenMetaverse; @@ -50,13 +51,13 @@ namespace OpenSim.Server.Handlers.Avatar private IAvatarService m_AvatarService; - public AvatarServerPostHandler(IAvatarService service) : - base("POST", "/avatar") + public AvatarServerPostHandler(IAvatarService service, IServiceAuth auth) : + base("POST", "/avatar", auth) { m_AvatarService = service; } - public override byte[] Handle(string path, Stream requestData, + protected override byte[] ProcessRequest(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { StreamReader sr = new StreamReader(requestData); @@ -246,7 +247,7 @@ namespace OpenSim.Server.Handlers.Avatar rootElement.AppendChild(result); - return DocToBytes(doc); + return Util.DocToBytes(doc); } private byte[] FailureResult() @@ -268,18 +269,7 @@ namespace OpenSim.Server.Handlers.Avatar rootElement.AppendChild(result); - return DocToBytes(doc); - } - - private byte[] DocToBytes(XmlDocument doc) - { - MemoryStream ms = new MemoryStream(); - XmlTextWriter xw = new XmlTextWriter(ms, null); - xw.Formatting = Formatting.Indented; - doc.WriteTo(xw); - xw.Flush(); - - return ms.ToArray(); + return Util.DocToBytes(doc); } } diff --git a/OpenSim/Server/Handlers/BakedTextures/XBakes.cs b/OpenSim/Server/Handlers/BakedTextures/XBakes.cs new file mode 100644 index 0000000..4e55433 --- /dev/null +++ b/OpenSim/Server/Handlers/BakedTextures/XBakes.cs @@ -0,0 +1,148 @@ +/* + * 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.Diagnostics; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Threading; +using System.Reflection; +using OpenSim.Framework; +using OpenSim.Framework.Console; +using OpenSim.Server.Base; +using OpenSim.Services.Base; +using OpenSim.Services.Interfaces; +using Nini.Config; +using log4net; +using OpenMetaverse; + +namespace OpenSim.Server.Handlers.BakedTextures +{ + public class XBakes : ServiceBase, IBakedTextureService + { + private static readonly ILog m_log = + LogManager.GetLogger( + MethodBase.GetCurrentMethod().DeclaringType); + + protected string m_FSBase; + + private System.Text.UTF8Encoding utf8encoding = + new System.Text.UTF8Encoding(); + + public XBakes(IConfigSource config) : base(config) + { + MainConsole.Instance.Commands.AddCommand("fs", false, + "delete bakes", "delete bakes ", + "Delete agent's baked textures from server", + HandleDeleteBakes); + + IConfig assetConfig = config.Configs["BakedTextureService"]; + if (assetConfig == null) + { + throw new Exception("No BakedTextureService configuration"); + } + + m_FSBase = assetConfig.GetString("BaseDirectory", String.Empty); + if (m_FSBase == String.Empty) + { + m_log.ErrorFormat("[BAKES]: BaseDirectory not specified"); + throw new Exception("Configuration error"); + } + + m_log.Info("[BAKES]: XBakes service enabled"); + } + + public string Get(string id) + { + string file = HashToFile(id); + string diskFile = Path.Combine(m_FSBase, file); + + if (File.Exists(diskFile)) + { + try + { + byte[] content = File.ReadAllBytes(diskFile); + + return utf8encoding.GetString(content); + } + catch + { + } + } + return String.Empty; + } + + public void Store(string id, string sdata) + { + string file = HashToFile(id); + string diskFile = Path.Combine(m_FSBase, file); + + Directory.CreateDirectory(Path.GetDirectoryName(diskFile)); + + File.Delete(diskFile); + + byte[] data = utf8encoding.GetBytes(sdata); + + using (FileStream fs = File.Create(diskFile)) + fs.Write(data, 0, data.Length); + } + + private void HandleDeleteBakes(string module, string[] args) + { + if (args.Length < 3) + { + MainConsole.Instance.Output("Syntax: delete bakes "); + return; + } + + string file = HashToFile(args[2]); + string diskFile = Path.Combine(m_FSBase, file); + + if (File.Exists(diskFile)) + { + File.Delete(diskFile); + MainConsole.Instance.Output("Bakes deleted"); + return; + } + MainConsole.Instance.Output("Bakes not found"); + } + + public string HashToPath(string hash) + { + return Path.Combine(hash.Substring(0, 2), + Path.Combine(hash.Substring(2, 2), + Path.Combine(hash.Substring(4, 2), + hash.Substring(6, 4)))); + } + + public string HashToFile(string hash) + { + return Path.Combine(HashToPath(hash), hash); + } + } +} diff --git a/OpenSim/Server/Handlers/BakedTextures/XBakesGetHandler.cs b/OpenSim/Server/Handlers/BakedTextures/XBakesGetHandler.cs new file mode 100644 index 0000000..3c61673 --- /dev/null +++ b/OpenSim/Server/Handlers/BakedTextures/XBakesGetHandler.cs @@ -0,0 +1,71 @@ +/* + * 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 Nini.Config; +using log4net; +using System; +using System.IO; +using System.Reflection; +using System.Net; +using System.Text; +using System.Text.RegularExpressions; +using System.Xml; +using System.Xml.Serialization; +using OpenSim.Server.Base; +using OpenSim.Services.Interfaces; +using OpenSim.Framework; +using OpenSim.Framework.ServiceAuth; +using OpenSim.Framework.Servers.HttpServer; + +namespace OpenSim.Server.Handlers.BakedTextures +{ + public class BakesServerGetHandler : BaseStreamHandler + { +// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private IBakedTextureService m_BakesService; + private System.Text.UTF8Encoding utf8 = + new System.Text.UTF8Encoding(); + + public BakesServerGetHandler(IBakedTextureService service, IServiceAuth auth) : + base("GET", "/bakes", auth) + { + m_BakesService = service; + } + + protected override byte[] ProcessRequest( + string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) + { + string[] p = SplitParams(path); + + if (p.Length == 0) + return new byte[0]; + + return utf8.GetBytes(m_BakesService.Get(p[0])); + } + } +} diff --git a/OpenSim/Server/Handlers/BakedTextures/XBakesHandler.cs b/OpenSim/Server/Handlers/BakedTextures/XBakesHandler.cs new file mode 100644 index 0000000..4c12967 --- /dev/null +++ b/OpenSim/Server/Handlers/BakedTextures/XBakesHandler.cs @@ -0,0 +1,69 @@ +/* + * 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 Nini.Config; +using OpenSim.Server.Base; +using OpenSim.Services.Interfaces; +using OpenSim.Framework.ServiceAuth; +using OpenSim.Framework.Servers.HttpServer; +using OpenSim.Server.Handlers.Base; + +namespace OpenSim.Server.Handlers.BakedTextures +{ + public class XBakesConnector : ServiceConnector + { + private IBakedTextureService m_BakesService; + private string m_ConfigName = "BakedTextureService"; + + public XBakesConnector(IConfigSource config, IHttpServer server, string configName) : + base(config, server, configName) + { + if (configName != String.Empty) + m_ConfigName = configName; + + IConfig serverConfig = config.Configs[m_ConfigName]; + if (serverConfig == null) + throw new Exception(String.Format("No section '{0}' in config file", m_ConfigName)); + + string assetService = serverConfig.GetString("LocalServiceModule", + String.Empty); + + if (assetService == String.Empty) + throw new Exception("No BakedTextureService in config file"); + + Object[] args = new Object[] { config }; + m_BakesService = + ServerUtils.LoadPlugin(assetService, args); + + IServiceAuth auth = ServiceAuth.Create(config, m_ConfigName); + + server.AddStreamHandler(new BakesServerGetHandler(m_BakesService, auth)); + server.AddStreamHandler(new BakesServerPostHandler(m_BakesService, auth)); + } + } +} diff --git a/OpenSim/Server/Handlers/BakedTextures/XBakesPostHandler.cs b/OpenSim/Server/Handlers/BakedTextures/XBakesPostHandler.cs new file mode 100644 index 0000000..e38543b --- /dev/null +++ b/OpenSim/Server/Handlers/BakedTextures/XBakesPostHandler.cs @@ -0,0 +1,76 @@ +/* + * 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 Nini.Config; +using log4net; +using System; +using System.Reflection; +using System.IO; +using System.Net; +using System.Text; +using System.Text.RegularExpressions; +using System.Xml; +using System.Xml.Serialization; +using OpenSim.Server.Base; +using OpenSim.Services.Interfaces; +using OpenSim.Framework; +using OpenSim.Framework.ServiceAuth; +using OpenSim.Framework.Servers.HttpServer; + +namespace OpenSim.Server.Handlers.BakedTextures +{ + public class BakesServerPostHandler : BaseStreamHandler + { +// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private IBakedTextureService m_BakesService; + + public BakesServerPostHandler(IBakedTextureService service, IServiceAuth auth) : + base("POST", "/bakes", auth) + { + m_BakesService = service; + } + + protected override byte[] ProcessRequest( + string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) + { + string[] p = SplitParams(path); + + if (p.Length == 0) + { + return new byte[0]; + } + + StreamReader sr = new StreamReader(request); + + m_BakesService.Store(p[0], sr.ReadToEnd()); + sr.Close(); + + return new byte[0]; + } + } +} \ No newline at end of file diff --git a/OpenSim/Server/Handlers/Estate/EstateDataRobustConnector.cs b/OpenSim/Server/Handlers/Estate/EstateDataRobustConnector.cs new file mode 100644 index 0000000..e0c2810 --- /dev/null +++ b/OpenSim/Server/Handlers/Estate/EstateDataRobustConnector.cs @@ -0,0 +1,343 @@ +/* + * 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 System.IO; +using System.Reflection; +using System.Net; + +using Nini.Config; +using log4net; +using OpenMetaverse; + +using OpenSim.Server.Base; +using OpenSim.Services.Interfaces; +using OpenSim.Framework; +using OpenSim.Framework.ServiceAuth; +using OpenSim.Framework.Servers.HttpServer; +using OpenSim.Server.Handlers.Base; + +namespace OpenSim.Server.Handlers +{ + public class EstateDataRobustConnector : ServiceConnector + { + private string m_ConfigName = "EstateService"; + + public EstateDataRobustConnector(IConfigSource config, IHttpServer server, string configName) : + base(config, server, configName) + { + IConfig serverConfig = config.Configs[m_ConfigName]; + if (serverConfig == null) + throw new Exception(String.Format("No section {0} in config file", m_ConfigName)); + + string service = serverConfig.GetString("LocalServiceModule", + String.Empty); + + if (service == String.Empty) + throw new Exception("No LocalServiceModule in config file"); + + Object[] args = new Object[] { config }; + IEstateDataService e_service = ServerUtils.LoadPlugin(service, args); + + IServiceAuth auth = ServiceAuth.Create(config, m_ConfigName); ; + + server.AddStreamHandler(new EstateServerGetHandler(e_service, auth)); + server.AddStreamHandler(new EstateServerPostHandler(e_service, auth)); + } + } + + + public class EstateServerGetHandler : BaseStreamHandler + { +// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + IEstateDataService m_EstateService; + + // Possibilities + // /estates/estate/?region=uuid&create=[t|f] + // /estates/estate/?eid=int + // /estates/?name=string + // /estates/?owner=uuid + // /estates/ (all) + // /estates/regions/?eid=int + + public EstateServerGetHandler(IEstateDataService service, IServiceAuth auth) : + base("GET", "/estates", auth) + { + m_EstateService = service; + } + + protected override byte[] ProcessRequest(string path, Stream request, + IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) + { + Dictionary data = null; + + string[] p = SplitParams(path); + + // /estates/ (all) + // /estates/?name=string + // /estates/?owner=uuid + if (p.Length == 0) + data = GetEstates(httpRequest, httpResponse); + else + { + string resource = p[0]; + + // /estates/estate/?region=uuid&create=[t|f] + // /estates/estate/?eid=int + if ("estate".Equals(resource)) + data = GetEstate(httpRequest, httpResponse); + // /estates/regions/?eid=int + else if ("regions".Equals(resource)) + data = GetRegions(httpRequest, httpResponse); + } + + if (data == null) + data = new Dictionary(); + + string xmlString = ServerUtils.BuildXmlResponse(data); + return Util.UTF8NoBomEncoding.GetBytes(xmlString); + + } + + private Dictionary GetEstates(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) + { + // /estates/ (all) + // /estates/?name=string + // /estates/?owner=uuid + + Dictionary data = null; + string name = (string)httpRequest.Query["name"]; + string owner = (string)httpRequest.Query["owner"]; + + if (!string.IsNullOrEmpty(name) || !string.IsNullOrEmpty(owner)) + { + List estateIDs = null; + if (!string.IsNullOrEmpty(name)) + { + estateIDs = m_EstateService.GetEstates(name); + } + else if (!string.IsNullOrEmpty(owner)) + { + UUID ownerID = UUID.Zero; + if (UUID.TryParse(owner, out ownerID)) + estateIDs = m_EstateService.GetEstatesByOwner(ownerID); + } + + if (estateIDs == null || (estateIDs != null && estateIDs.Count == 0)) + httpResponse.StatusCode = (int)HttpStatusCode.NotFound; + else + { + httpResponse.StatusCode = (int)HttpStatusCode.OK; + httpResponse.ContentType = "text/xml"; + data = new Dictionary(); + int i = 0; + foreach (int id in estateIDs) + data["estate" + i++] = id; + } + } + else + { + List estates = m_EstateService.LoadEstateSettingsAll(); + if (estates == null || estates.Count == 0) + { + httpResponse.StatusCode = (int)HttpStatusCode.NotFound; + } + else + { + httpResponse.StatusCode = (int)HttpStatusCode.OK; + httpResponse.ContentType = "text/xml"; + data = new Dictionary(); + int i = 0; + foreach (EstateSettings es in estates) + data["estate" + i++] = es.ToMap(); + + } + } + + return data; + } + + private Dictionary GetEstate(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) + { + // /estates/estate/?region=uuid&create=[t|f] + // /estates/estate/?eid=int + Dictionary data = null; + string region = (string)httpRequest.Query["region"]; + string eid = (string)httpRequest.Query["eid"]; + + EstateSettings estate = null; + + if (!string.IsNullOrEmpty(region)) + { + UUID regionID = UUID.Zero; + if (UUID.TryParse(region, out regionID)) + { + string create = (string)httpRequest.Query["create"]; + bool createYN = false; + Boolean.TryParse(create, out createYN); + estate = m_EstateService.LoadEstateSettings(regionID, createYN); + } + } + else if (!string.IsNullOrEmpty(eid)) + { + int id = 0; + if (Int32.TryParse(eid, out id)) + estate = m_EstateService.LoadEstateSettings(id); + } + + if (estate != null) + { + httpResponse.StatusCode = (int)HttpStatusCode.OK; + httpResponse.ContentType = "text/xml"; + data = estate.ToMap(); + } + else + httpResponse.StatusCode = (int)HttpStatusCode.NotFound; + + return data; + } + + private Dictionary GetRegions(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) + { + // /estates/regions/?eid=int + Dictionary data = null; + string eid = (string)httpRequest.Query["eid"]; + + httpResponse.StatusCode = (int)HttpStatusCode.NotFound; + if (!string.IsNullOrEmpty(eid)) + { + int id = 0; + if (Int32.TryParse(eid, out id)) + { + List regions = m_EstateService.GetRegions(id); + if (regions != null && regions.Count > 0) + { + data = new Dictionary(); + int i = 0; + foreach (UUID uuid in regions) + data["region" + i++] = uuid.ToString(); + httpResponse.StatusCode = (int)HttpStatusCode.OK; + httpResponse.ContentType = "text/xml"; + } + } + } + + return data; + } + } + + public class EstateServerPostHandler : BaseStreamHandler + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + IEstateDataService m_EstateService; + + // Possibilities + // /estates/estate/ (post an estate) + // /estates/estate/?eid=int®ion=uuid (link a region to an estate) + + public EstateServerPostHandler(IEstateDataService service, IServiceAuth auth) : + base("POST", "/estates", auth) + { + m_EstateService = service; + } + + protected override byte[] ProcessRequest(string path, Stream request, + IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) + { + Dictionary data = null; + + string[] p = SplitParams(path); + + if (p.Length > 0) + { + string resource = p[0]; + + // /estates/estate/ + // /estates/estate/?eid=int®ion=uuid + if ("estate".Equals(resource)) + { + StreamReader sr = new StreamReader(request); + string body = sr.ReadToEnd(); + sr.Close(); + body = body.Trim(); + + Dictionary requestData = ServerUtils.ParseQueryString(body); + + data = UpdateEstate(requestData, httpRequest, httpResponse); + } + } + + if (data == null) + data = new Dictionary(); + + string xmlString = ServerUtils.BuildXmlResponse(data); + return Util.UTF8NoBomEncoding.GetBytes(xmlString); + + } + + private Dictionary UpdateEstate(Dictionary requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) + { + // /estates/estate/ + // /estates/estate/?eid=int®ion=uuid + Dictionary result = new Dictionary(); + string eid = (string)httpRequest.Query["eid"]; + string region = (string)httpRequest.Query["region"]; + + httpResponse.StatusCode = (int)HttpStatusCode.NotFound; + + if (string.IsNullOrEmpty(eid) && string.IsNullOrEmpty(region) && + requestData.ContainsKey("OP") && requestData["OP"] != null && "STORE".Equals(requestData["OP"])) + { + // /estates/estate/ + EstateSettings es = new EstateSettings(requestData); + m_EstateService.StoreEstateSettings(es); + //m_log.DebugFormat("[EstateServerPostHandler]: Store estate {0}", es.ToString()); + httpResponse.StatusCode = (int)HttpStatusCode.OK; + result["Result"] = true; + } + else if (!string.IsNullOrEmpty(region) && !string.IsNullOrEmpty(eid) && + requestData.ContainsKey("OP") && requestData["OP"] != null && "LINK".Equals(requestData["OP"])) + { + int id = 0; + UUID regionID = UUID.Zero; + if (UUID.TryParse(region, out regionID) && Int32.TryParse(eid, out id)) + { + m_log.DebugFormat("[EstateServerPostHandler]: Link region {0} to estate {1}", regionID, id); + httpResponse.StatusCode = (int)HttpStatusCode.OK; + result["Result"] = m_EstateService.LinkRegion(regionID, id); + } + } + else + m_log.WarnFormat("[EstateServerPostHandler]: something wrong with POST request {0}", httpRequest.RawUrl); + + return result; + } + + } +} diff --git a/OpenSim/Server/Handlers/Friends/FriendServerConnector.cs b/OpenSim/Server/Handlers/Friends/FriendServerConnector.cs index 5784bdf..b0e6c7d 100644 --- a/OpenSim/Server/Handlers/Friends/FriendServerConnector.cs +++ b/OpenSim/Server/Handlers/Friends/FriendServerConnector.cs @@ -29,6 +29,7 @@ using System; using Nini.Config; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; +using OpenSim.Framework.ServiceAuth; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Server.Handlers.Base; @@ -55,7 +56,8 @@ namespace OpenSim.Server.Handlers.Friends Object[] args = new Object[] { config }; m_FriendsService = ServerUtils.LoadPlugin(theService, args); - server.AddStreamHandler(new FriendsServerPostHandler(m_FriendsService)); + IServiceAuth auth = ServiceAuth.Create(config, m_ConfigName); + server.AddStreamHandler(new FriendsServerPostHandler(m_FriendsService, auth)); } } } diff --git a/OpenSim/Server/Handlers/Friends/FriendsServerPostHandler.cs b/OpenSim/Server/Handlers/Friends/FriendsServerPostHandler.cs index 47a8558..3aab30b 100644 --- a/OpenSim/Server/Handlers/Friends/FriendsServerPostHandler.cs +++ b/OpenSim/Server/Handlers/Friends/FriendsServerPostHandler.cs @@ -40,6 +40,7 @@ using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using FriendInfo = OpenSim.Services.Interfaces.FriendInfo; using OpenSim.Framework; +using OpenSim.Framework.ServiceAuth; using OpenSim.Framework.Servers.HttpServer; using OpenMetaverse; @@ -51,13 +52,13 @@ namespace OpenSim.Server.Handlers.Friends private IFriendsService m_FriendsService; - public FriendsServerPostHandler(IFriendsService service) : - base("POST", "/friends") + public FriendsServerPostHandler(IFriendsService service, IServiceAuth auth) : + base("POST", "/friends", auth) { m_FriendsService = service; } - public override byte[] Handle(string path, Stream requestData, + protected override byte[] ProcessRequest(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { StreamReader sr = new StreamReader(requestData); @@ -228,7 +229,7 @@ namespace OpenSim.Server.Handlers.Friends rootElement.AppendChild(result); - return DocToBytes(doc); + return Util.DocToBytes(doc); } private byte[] FailureResult() @@ -260,18 +261,7 @@ namespace OpenSim.Server.Handlers.Friends rootElement.AppendChild(message); - return DocToBytes(doc); - } - - private byte[] DocToBytes(XmlDocument doc) - { - MemoryStream ms = new MemoryStream(); - XmlTextWriter xw = new XmlTextWriter(ms, null); - xw.Formatting = Formatting.Indented; - doc.WriteTo(xw); - xw.Flush(); - - return ms.ToArray(); + return Util.DocToBytes(doc); } void FromKeyValuePairs(Dictionary kvp, out string principalID, out string friend, out int flags) diff --git a/OpenSim/Server/Handlers/Grid/GridInfoHandlers.cs b/OpenSim/Server/Handlers/Grid/GridInfoHandlers.cs index 965a54e..346af32 100644 --- a/OpenSim/Server/Handlers/Grid/GridInfoHandlers.cs +++ b/OpenSim/Server/Handlers/Grid/GridInfoHandlers.cs @@ -170,14 +170,6 @@ namespace OpenSim.Server.Handlers.Grid public string JsonGetGridInfoMethod(string request, string path, string param, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { - string HomeURI = String.Empty; - IConfig cfg = m_Config.Configs["LoginService"]; - - if (null != cfg) - { - HomeURI = cfg.GetString("SRV_HomeURI", HomeURI); - } - OSDMap map = new OSDMap(); foreach (string k in _info.Keys) @@ -185,9 +177,20 @@ namespace OpenSim.Server.Handlers.Grid map[k] = OSD.FromString(_info[k].ToString()); } + string HomeURI = Util.GetConfigVarFromSections(m_Config, "HomeURI", + new string[] { "Startup", "Hypergrid" }, String.Empty); + if (!String.IsNullOrEmpty(HomeURI)) + map["home"] = OSD.FromString(HomeURI); + else // Legacy. Remove soon! { - map["home"] = OSD.FromString(HomeURI); + IConfig cfg = m_Config.Configs["LoginService"]; + + if (null != cfg) + HomeURI = cfg.GetString("SRV_HomeURI", HomeURI); + + if (!String.IsNullOrEmpty(HomeURI)) + map["home"] = OSD.FromString(HomeURI); } return OSDParser.SerializeJsonString(map).ToString(); diff --git a/OpenSim/Server/Handlers/Grid/GridServerConnector.cs b/OpenSim/Server/Handlers/Grid/GridServerConnector.cs index 14daf12..6eb6a79 100644 --- a/OpenSim/Server/Handlers/Grid/GridServerConnector.cs +++ b/OpenSim/Server/Handlers/Grid/GridServerConnector.cs @@ -29,6 +29,7 @@ using System; using Nini.Config; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; +using OpenSim.Framework.ServiceAuth; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Server.Handlers.Base; @@ -55,7 +56,9 @@ namespace OpenSim.Server.Handlers.Grid Object[] args = new Object[] { config }; m_GridService = ServerUtils.LoadPlugin(gridService, args); - server.AddStreamHandler(new GridServerPostHandler(m_GridService)); + IServiceAuth auth = ServiceAuth.Create(config, m_ConfigName); + + server.AddStreamHandler(new GridServerPostHandler(m_GridService, auth)); } } } diff --git a/OpenSim/Server/Handlers/Grid/GridServerPostHandler.cs b/OpenSim/Server/Handlers/Grid/GridServerPostHandler.cs index ef5f33e..86fda36 100644 --- a/OpenSim/Server/Handlers/Grid/GridServerPostHandler.cs +++ b/OpenSim/Server/Handlers/Grid/GridServerPostHandler.cs @@ -40,6 +40,7 @@ using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenSim.Framework; +using OpenSim.Framework.ServiceAuth; using OpenSim.Framework.Servers.HttpServer; using OpenMetaverse; @@ -49,15 +50,19 @@ namespace OpenSim.Server.Handlers.Grid { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); +#pragma warning disable 414 + private static string LogHeader = "[GRID HANDLER]"; +#pragma warning restore 414 + private IGridService m_GridService; - public GridServerPostHandler(IGridService service) : - base("POST", "/grid") + public GridServerPostHandler(IGridService service, IServiceAuth auth) : + base("POST", "/grid", auth) { m_GridService = service; } - public override byte[] Handle(string path, Stream requestData, + protected override byte[] ProcessRequest(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { StreamReader sr = new StreamReader(requestData); @@ -106,6 +111,9 @@ namespace OpenSim.Server.Handlers.Grid case "get_default_regions": return GetDefaultRegions(request); + case "get_default_hypergrid_regions": + return GetDefaultHypergridRegions(request); + case "get_fallback_regions": return GetFallbackRegions(request); @@ -114,6 +122,9 @@ namespace OpenSim.Server.Handlers.Grid case "get_region_flags": return GetRegionFlags(request); + + case "get_grid_extra_features": + return GetGridExtraFeatures(request); } m_log.DebugFormat("[GRID HANDLER]: unknown method request {0}", method); @@ -148,7 +159,24 @@ namespace OpenSim.Server.Handlers.Grid m_log.WarnFormat("[GRID HANDLER]: no maximum protocol version in request to register region"); // Check the protocol version - if ((versionNumberMin > ProtocolVersions.ServerProtocolVersionMax && versionNumberMax < ProtocolVersions.ServerProtocolVersionMax)) + // This is how it works: + // Example 1: + // Client: [0 0] + // Server: [1 1] + // ==> fail + // Example 2: + // Client: [1 1] + // Server: [0 0] + // ==> fail + // Example 3: + // Client: [0 1] + // Server: [1 1] + // ==> success + // Example 4: + // Client: [1 1] + // Server: [0 1] + // ==> success + if ((versionNumberMin > ProtocolVersions.ServerProtocolVersionMax || versionNumberMax < ProtocolVersions.ServerProtocolVersionMin)) { // Can't do, there is no overlap in the acceptable ranges return FailureResult(); @@ -278,8 +306,8 @@ namespace OpenSim.Server.Handlers.Grid else m_log.WarnFormat("[GRID HANDLER]: no Y in request to get region by position"); + // m_log.DebugFormat("{0} GetRegionByPosition: loc=<{1},{2}>", LogHeader, x, y); GridRegion rinfo = m_GridService.GetRegionByPosition(scopeID, x, y); - //m_log.DebugFormat("[GRID HANDLER]: neighbours for region {0}: {1}", regionID, rinfos.Count); Dictionary result = new Dictionary(); if (rinfo == null) @@ -444,6 +472,36 @@ namespace OpenSim.Server.Handlers.Grid return Util.UTF8NoBomEncoding.GetBytes(xmlString); } + byte[] GetDefaultHypergridRegions(Dictionary request) + { + //m_log.DebugFormat("[GRID HANDLER]: GetDefaultRegions"); + UUID scopeID = UUID.Zero; + if (request.ContainsKey("SCOPEID")) + UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); + else + m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get region range"); + + List rinfos = m_GridService.GetDefaultHypergridRegions(scopeID); + + Dictionary result = new Dictionary(); + if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0))) + result["result"] = "null"; + else + { + int i = 0; + foreach (GridRegion rinfo in rinfos) + { + Dictionary rinfoDict = rinfo.ToKeyValuePairs(); + result["region" + i] = rinfoDict; + i++; + } + } + string xmlString = ServerUtils.BuildXmlResponse(result); + + //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); + return Util.UTF8NoBomEncoding.GetBytes(xmlString); + } + byte[] GetFallbackRegions(Dictionary request) { //m_log.DebugFormat("[GRID HANDLER]: GetRegionRange"); @@ -540,6 +598,22 @@ namespace OpenSim.Server.Handlers.Grid //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } + + byte[] GetGridExtraFeatures(Dictionary request) + { + + Dictionary result = new Dictionary (); + Dictionary extraFeatures = m_GridService.GetExtraFeatures (); + + foreach (string key in extraFeatures.Keys) + { + result [key] = extraFeatures [key]; + } + + string xmlString = ServerUtils.BuildXmlResponse(result); + + return Util.UTF8NoBomEncoding.GetBytes(xmlString); + } #endregion @@ -564,7 +638,7 @@ namespace OpenSim.Server.Handlers.Grid rootElement.AppendChild(result); - return DocToBytes(doc); + return Util.DocToBytes(doc); } private byte[] FailureResult() @@ -596,18 +670,7 @@ namespace OpenSim.Server.Handlers.Grid rootElement.AppendChild(message); - return DocToBytes(doc); - } - - private byte[] DocToBytes(XmlDocument doc) - { - MemoryStream ms = new MemoryStream(); - XmlTextWriter xw = new XmlTextWriter(ms, null); - xw.Formatting = Formatting.Indented; - doc.WriteTo(xw); - xw.Flush(); - - return ms.ToArray(); + return Util.DocToBytes(doc); } #endregion diff --git a/OpenSim/Server/Handlers/GridUser/GridUserServerConnector.cs b/OpenSim/Server/Handlers/GridUser/GridUserServerConnector.cs index 66f35e3..1e29378 100644 --- a/OpenSim/Server/Handlers/GridUser/GridUserServerConnector.cs +++ b/OpenSim/Server/Handlers/GridUser/GridUserServerConnector.cs @@ -29,6 +29,7 @@ using System; using Nini.Config; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; +using OpenSim.Framework.ServiceAuth; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Server.Handlers.Base; @@ -55,7 +56,9 @@ namespace OpenSim.Server.Handlers.GridUser Object[] args = new Object[] { config }; m_GridUserService = ServerUtils.LoadPlugin(service, args); - server.AddStreamHandler(new GridUserServerPostHandler(m_GridUserService)); + IServiceAuth auth = ServiceAuth.Create(config, m_ConfigName); ; + + server.AddStreamHandler(new GridUserServerPostHandler(m_GridUserService, auth)); } } } diff --git a/OpenSim/Server/Handlers/GridUser/GridUserServerPostHandler.cs b/OpenSim/Server/Handlers/GridUser/GridUserServerPostHandler.cs index 687cf8d..9237c63 100644 --- a/OpenSim/Server/Handlers/GridUser/GridUserServerPostHandler.cs +++ b/OpenSim/Server/Handlers/GridUser/GridUserServerPostHandler.cs @@ -39,6 +39,7 @@ using System.Collections.Generic; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenSim.Framework; +using OpenSim.Framework.ServiceAuth; using OpenSim.Framework.Servers.HttpServer; using OpenMetaverse; @@ -50,13 +51,13 @@ namespace OpenSim.Server.Handlers.GridUser private IGridUserService m_GridUserService; - public GridUserServerPostHandler(IGridUserService service) : - base("POST", "/griduser") + public GridUserServerPostHandler(IGridUserService service, IServiceAuth auth) : + base("POST", "/griduser", auth) { m_GridUserService = service; } - public override byte[] Handle(string path, Stream requestData, + protected override byte[] ProcessRequest(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { StreamReader sr = new StreamReader(requestData); @@ -185,10 +186,12 @@ namespace OpenSim.Server.Handlers.GridUser GridUserInfo guinfo = m_GridUserService.GetGridUserInfo(user); Dictionary result = new Dictionary(); - result["result"] = guinfo.ToKeyValuePairs(); + if (guinfo != null) + result["result"] = guinfo.ToKeyValuePairs(); + else + result["result"] = "null"; string xmlString = ServerUtils.BuildXmlResponse(result); - //m_log.DebugFormat("[GRID USER HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } @@ -276,7 +279,7 @@ namespace OpenSim.Server.Handlers.GridUser rootElement.AppendChild(result); - return DocToBytes(doc); + return Util.DocToBytes(doc); } private byte[] FailureResult() @@ -298,20 +301,8 @@ namespace OpenSim.Server.Handlers.GridUser rootElement.AppendChild(result); - return DocToBytes(doc); + return Util.DocToBytes(doc); } - private byte[] DocToBytes(XmlDocument doc) - { - MemoryStream ms = new MemoryStream(); - XmlTextWriter xw = new XmlTextWriter(ms, null); - xw.Formatting = Formatting.Indented; - doc.WriteTo(xw); - xw.Flush(); - - return ms.ToArray(); - } - - } } diff --git a/OpenSim/Server/Handlers/Hypergrid/AgentHandlers.cs b/OpenSim/Server/Handlers/Hypergrid/AgentHandlers.cs index cf1af15..95a0510 100644 --- a/OpenSim/Server/Handlers/Hypergrid/AgentHandlers.cs +++ b/OpenSim/Server/Handlers/Hypergrid/AgentHandlers.cs @@ -61,9 +61,10 @@ namespace OpenSim.Server.Handlers.Hypergrid m_Proxy = proxy; } - protected override bool CreateAgent(GridRegion destination, AgentCircuitData aCircuit, uint teleportFlags, out string reason) + protected override bool CreateAgent(GridRegion source, GridRegion gatekeeper, GridRegion destination, + AgentCircuitData aCircuit, uint teleportFlags, bool fromLogin, out string reason) { - return m_GatekeeperService.LoginAgent(aCircuit, destination, out reason); + return m_GatekeeperService.LoginAgent(source, aCircuit, destination, out reason); } } } diff --git a/OpenSim/Server/Handlers/Hypergrid/GatekeeperServerConnector.cs b/OpenSim/Server/Handlers/Hypergrid/GatekeeperServerConnector.cs index 0d4990a..ffe2f36 100644 --- a/OpenSim/Server/Handlers/Hypergrid/GatekeeperServerConnector.cs +++ b/OpenSim/Server/Handlers/Hypergrid/GatekeeperServerConnector.cs @@ -76,10 +76,14 @@ namespace OpenSim.Server.Handlers.Hypergrid server.AddStreamHandler(new GatekeeperAgentHandler(m_GatekeeperService, m_Proxy)); } - public GatekeeperServiceInConnector(IConfigSource config, IHttpServer server) - : this(config, server, null) + public GatekeeperServiceInConnector(IConfigSource config, IHttpServer server, string configName) + : this(config, server, (ISimulationService)null) { } + public GatekeeperServiceInConnector(IConfigSource config, IHttpServer server) + : this(config, server, String.Empty) + { + } } } diff --git a/OpenSim/Server/Handlers/Hypergrid/HGFriendsServerPostHandler.cs b/OpenSim/Server/Handlers/Hypergrid/HGFriendsServerPostHandler.cs index 0aa2729..37b47ed 100644 --- a/OpenSim/Server/Handlers/Hypergrid/HGFriendsServerPostHandler.cs +++ b/OpenSim/Server/Handlers/Hypergrid/HGFriendsServerPostHandler.cs @@ -68,7 +68,7 @@ namespace OpenSim.Server.Handlers.Hypergrid m_log.ErrorFormat("[HGFRIENDS HANDLER]: TheService is null!"); } - public override byte[] Handle(string path, Stream requestData, + protected override byte[] ProcessRequest(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { StreamReader sr = new StreamReader(requestData); @@ -335,7 +335,7 @@ namespace OpenSim.Server.Handlers.Hypergrid rootElement.AppendChild(result); - return DocToBytes(doc); + return Util.DocToBytes(doc); } private byte[] SuccessResult(string value) @@ -362,7 +362,7 @@ namespace OpenSim.Server.Handlers.Hypergrid rootElement.AppendChild(message); - return DocToBytes(doc); + return Util.DocToBytes(doc); } @@ -395,7 +395,7 @@ namespace OpenSim.Server.Handlers.Hypergrid rootElement.AppendChild(message); - return DocToBytes(doc); + return Util.DocToBytes(doc); } private byte[] BoolResult(bool value) @@ -417,21 +417,9 @@ namespace OpenSim.Server.Handlers.Hypergrid rootElement.AppendChild(result); - return DocToBytes(doc); + return Util.DocToBytes(doc); } - private byte[] DocToBytes(XmlDocument doc) - { - MemoryStream ms = new MemoryStream(); - XmlTextWriter xw = new XmlTextWriter(ms, null); - xw.Formatting = Formatting.Indented; - doc.WriteTo(xw); - xw.Flush(); - - return ms.ToArray(); - } - - #endregion } } diff --git a/OpenSim/Server/Handlers/Hypergrid/HeloServerConnector.cs b/OpenSim/Server/Handlers/Hypergrid/HeloServerConnector.cs index f306b1c..dac4ca8 100644 --- a/OpenSim/Server/Handlers/Hypergrid/HeloServerConnector.cs +++ b/OpenSim/Server/Handlers/Hypergrid/HeloServerConnector.cs @@ -44,7 +44,9 @@ namespace OpenSim.Server.Handlers.Hypergrid public HeloServiceInConnector(IConfigSource config, IHttpServer server, string configName) : base(config, server, configName) { +#pragma warning disable 0612 server.AddStreamHandler(new HeloServerGetHandler("opensim-robust")); +#pragma warning restore 0612 server.AddStreamHandler(new HeloServerHeadHandler("opensim-robust")); } } @@ -91,7 +93,7 @@ namespace OpenSim.Server.Handlers.Hypergrid m_HandlersType = handlersType; } - public override byte[] Handle(string path, Stream requestData, + protected override byte[] ProcessRequest(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { return OKResponse(httpResponse); diff --git a/OpenSim/Server/Handlers/Hypergrid/HomeAgentHandlers.cs b/OpenSim/Server/Handlers/Hypergrid/HomeAgentHandlers.cs index 968c1e6..e787f7c 100644 --- a/OpenSim/Server/Handlers/Hypergrid/HomeAgentHandlers.cs +++ b/OpenSim/Server/Handlers/Hypergrid/HomeAgentHandlers.cs @@ -49,191 +49,89 @@ using log4net; namespace OpenSim.Server.Handlers.Hypergrid { - public class HomeAgentHandler + public class HomeAgentHandler : AgentPostHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IUserAgentService m_UserAgentService; private string m_LoginServerIP; - private bool m_Proxy = false; - public HomeAgentHandler(IUserAgentService userAgentService, string loginServerIP, bool proxy) + public HomeAgentHandler(IUserAgentService userAgentService, string loginServerIP, bool proxy) : + base("/homeagent") { m_UserAgentService = userAgentService; m_LoginServerIP = loginServerIP; m_Proxy = proxy; } - public Hashtable Handler(Hashtable request) + protected override AgentDestinationData CreateAgentDestinationData() { -// m_log.Debug("[CONNECTION DEBUGGING]: HomeAgentHandler Called"); -// -// m_log.Debug("---------------------------"); -// m_log.Debug(" >> uri=" + request["uri"]); -// m_log.Debug(" >> content-type=" + request["content-type"]); -// m_log.Debug(" >> http-method=" + request["http-method"]); -// m_log.Debug("---------------------------\n"); - - Hashtable responsedata = new Hashtable(); - responsedata["content_type"] = "text/html"; - responsedata["keepalive"] = false; - - - UUID agentID; - UUID regionID; - string action; - if (!Utils.GetParams((string)request["uri"], out agentID, out regionID, out action)) + return new ExtendedAgentDestinationData(); + } + + protected override void UnpackData(OSDMap args, AgentDestinationData d, Hashtable request) + { + base.UnpackData(args, d, request); + ExtendedAgentDestinationData data = (ExtendedAgentDestinationData)d; + try { - m_log.InfoFormat("[HOME AGENT HANDLER]: Invalid parameters for agent message {0}", request["uri"]); - responsedata["int_response_code"] = 404; - responsedata["str_response_string"] = "false"; + if (args.ContainsKey("gatekeeper_host") && args["gatekeeper_host"] != null) + data.host = args["gatekeeper_host"].AsString(); + if (args.ContainsKey("gatekeeper_port") && args["gatekeeper_port"] != null) + Int32.TryParse(args["gatekeeper_port"].AsString(), out data.port); + if (args.ContainsKey("gatekeeper_serveruri") && args["gatekeeper_serveruri"] != null) + data.gatekeeperServerURI = args["gatekeeper_serveruri"]; + if (args.ContainsKey("destination_serveruri") && args["destination_serveruri"] != null) + data.destinationServerURI = args["destination_serveruri"]; - return responsedata; } - - // Next, let's parse the verb - string method = (string)request["http-method"]; - if (method.Equals("POST")) + catch (InvalidCastException) { - DoAgentPost(request, responsedata, agentID); - return responsedata; + m_log.ErrorFormat("[HOME AGENT HANDLER]: Bad cast in UnpackData"); } - else - { - m_log.InfoFormat("[HOME AGENT HANDLER]: method {0} not supported in agent message", method); - responsedata["int_response_code"] = HttpStatusCode.MethodNotAllowed; - responsedata["str_response_string"] = "Method not allowed"; - return responsedata; - } + string callerIP = GetCallerIP(request); + // Verify if this call came from the login server + if (callerIP == m_LoginServerIP) + data.fromLogin = true; } - protected void DoAgentPost(Hashtable request, Hashtable responsedata, UUID id) + protected override GridRegion ExtractGatekeeper(AgentDestinationData d) { - OSDMap args = Utils.GetOSDMap((string)request["body"]); - if (args == null) + if (d is ExtendedAgentDestinationData) { - responsedata["int_response_code"] = HttpStatusCode.BadRequest; - responsedata["str_response_string"] = "Bad request"; - return; + ExtendedAgentDestinationData data = (ExtendedAgentDestinationData)d; + GridRegion gatekeeper = new GridRegion(); + gatekeeper.ServerURI = data.gatekeeperServerURI; + gatekeeper.ExternalHostName = data.host; + gatekeeper.HttpPort = (uint)data.port; + gatekeeper.InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), 0); + + return gatekeeper; } - - // retrieve the input arguments - int x = 0, y = 0; - UUID uuid = UUID.Zero; - string regionname = string.Empty; - string gatekeeper_host = string.Empty; - string gatekeeper_serveruri = string.Empty; - string destination_serveruri = string.Empty; - int gatekeeper_port = 0; - IPEndPoint client_ipaddress = null; - - if (args.ContainsKey("gatekeeper_host") && args["gatekeeper_host"] != null) - gatekeeper_host = args["gatekeeper_host"].AsString(); - if (args.ContainsKey("gatekeeper_port") && args["gatekeeper_port"] != null) - Int32.TryParse(args["gatekeeper_port"].AsString(), out gatekeeper_port); - if (args.ContainsKey("gatekeeper_serveruri") && args["gatekeeper_serveruri"] !=null) - gatekeeper_serveruri = args["gatekeeper_serveruri"]; - if (args.ContainsKey("destination_serveruri") && args["destination_serveruri"] !=null) - destination_serveruri = args["destination_serveruri"]; - - GridRegion gatekeeper = new GridRegion(); - gatekeeper.ServerURI = gatekeeper_serveruri; - gatekeeper.ExternalHostName = gatekeeper_host; - gatekeeper.HttpPort = (uint)gatekeeper_port; - gatekeeper.InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), 0); - - if (args.ContainsKey("destination_x") && args["destination_x"] != null) - Int32.TryParse(args["destination_x"].AsString(), out x); - else - m_log.WarnFormat(" -- request didn't have destination_x"); - if (args.ContainsKey("destination_y") && args["destination_y"] != null) - Int32.TryParse(args["destination_y"].AsString(), out y); else - m_log.WarnFormat(" -- request didn't have destination_y"); - if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null) - UUID.TryParse(args["destination_uuid"].AsString(), out uuid); - if (args.ContainsKey("destination_name") && args["destination_name"] != null) - regionname = args["destination_name"].ToString(); - - if (args.ContainsKey("client_ip") && args["client_ip"] != null) - { - string ip_str = args["client_ip"].ToString(); - try - { - string callerIP = GetCallerIP(request); - // Verify if this caller has authority to send the client IP - if (callerIP == m_LoginServerIP) - client_ipaddress = new IPEndPoint(IPAddress.Parse(ip_str), 0); - else // leaving this for now, but this warning should be removed - m_log.WarnFormat("[HOME AGENT HANDLER]: Unauthorized machine {0} tried to set client ip to {1}", callerIP, ip_str); - } - catch - { - m_log.DebugFormat("[HOME AGENT HANDLER]: Exception parsing client ip address from {0}", ip_str); - } - } + m_log.WarnFormat("[HOME AGENT HANDLER]: Wrong data type"); - GridRegion destination = new GridRegion(); - destination.RegionID = uuid; - destination.RegionLocX = x; - destination.RegionLocY = y; - destination.RegionName = regionname; - destination.ServerURI = destination_serveruri; - - AgentCircuitData aCircuit = new AgentCircuitData(); - try - { - aCircuit.UnpackAgentCircuitData(args); - } - catch (Exception ex) - { - m_log.InfoFormat("[HOME AGENT HANDLER]: exception on unpacking ChildCreate message {0}", ex.Message); - responsedata["int_response_code"] = HttpStatusCode.BadRequest; - responsedata["str_response_string"] = "Bad request"; - return; - } - - OSDMap resp = new OSDMap(2); - string reason = String.Empty; - - bool result = m_UserAgentService.LoginAgentToGrid(aCircuit, gatekeeper, destination, client_ipaddress, out reason); - - resp["reason"] = OSD.FromString(reason); - resp["success"] = OSD.FromBoolean(result); - - // TODO: add reason if not String.Empty? - responsedata["int_response_code"] = HttpStatusCode.OK; - responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp); + return null; } - private string GetCallerIP(Hashtable request) - { - if (!m_Proxy) - return Util.GetCallerIP(request); - - // We're behind a proxy - Hashtable headers = (Hashtable)request["headers"]; - string xff = "X-Forwarded-For"; - if (headers.ContainsKey(xff.ToLower())) - xff = xff.ToLower(); - if (!headers.ContainsKey(xff) || headers[xff] == null) - { - m_log.WarnFormat("[AGENT HANDLER]: No XFF header"); - return Util.GetCallerIP(request); - } + protected override bool CreateAgent(GridRegion source, GridRegion gatekeeper, GridRegion destination, + AgentCircuitData aCircuit, uint teleportFlags, bool fromLogin, out string reason) + { + return m_UserAgentService.LoginAgentToGrid(source, aCircuit, gatekeeper, destination, fromLogin, out reason); + } - m_log.DebugFormat("[AGENT HANDLER]: XFF is {0}", headers[xff]); + } - IPEndPoint ep = Util.GetClientIPFromXFF((string)headers[xff]); - if (ep != null) - return ep.Address.ToString(); + public class ExtendedAgentDestinationData : AgentDestinationData + { + public string host; + public int port; + public string gatekeeperServerURI; + public string destinationServerURI; - // Oops - return Util.GetCallerIP(request); - } } } diff --git a/OpenSim/Server/Handlers/Hypergrid/HypergridHandlers.cs b/OpenSim/Server/Handlers/Hypergrid/HypergridHandlers.cs index 5d03097..c7ac9be 100644 --- a/OpenSim/Server/Handlers/Hypergrid/HypergridHandlers.cs +++ b/OpenSim/Server/Handlers/Hypergrid/HypergridHandlers.cs @@ -1,4 +1,4 @@ -/* +/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * @@ -94,22 +94,38 @@ namespace OpenSim.Server.Handlers.Hypergrid UUID regionID = UUID.Zero; UUID.TryParse(regionID_str, out regionID); - GridRegion regInfo = m_GatekeeperService.GetHyperlinkRegion(regionID); + UUID agentID = UUID.Zero; + string agentHomeURI = null; + if (requestData.ContainsKey("agent_id")) + agentID = UUID.Parse((string)requestData["agent_id"]); + if (requestData.ContainsKey("agent_home_uri")) + agentHomeURI = (string)requestData["agent_home_uri"]; + + string message; + GridRegion regInfo = m_GatekeeperService.GetHyperlinkRegion(regionID, agentID, agentHomeURI, out message); Hashtable hash = new Hashtable(); if (regInfo == null) + { hash["result"] = "false"; + } else { hash["result"] = "true"; hash["uuid"] = regInfo.RegionID.ToString(); hash["x"] = regInfo.RegionLocX.ToString(); hash["y"] = regInfo.RegionLocY.ToString(); + hash["size_x"] = regInfo.RegionSizeX.ToString(); + hash["size_y"] = regInfo.RegionSizeY.ToString(); hash["region_name"] = regInfo.RegionName; hash["hostname"] = regInfo.ExternalHostName; hash["http_port"] = regInfo.HttpPort.ToString(); hash["internal_port"] = regInfo.InternalEndPoint.Port.ToString(); } + + if (message != null) + hash["message"] = message; + XmlRpcResponse response = new XmlRpcResponse(); response.Value = hash; return response; diff --git a/OpenSim/Server/Handlers/Hypergrid/InstantMessageServerConnector.cs b/OpenSim/Server/Handlers/Hypergrid/InstantMessageServerConnector.cs index 80eb5d2..8145a21 100644 --- a/OpenSim/Server/Handlers/Hypergrid/InstantMessageServerConnector.cs +++ b/OpenSim/Server/Handlers/Hypergrid/InstantMessageServerConnector.cs @@ -54,10 +54,15 @@ namespace OpenSim.Server.Handlers.Hypergrid private IInstantMessage m_IMService; public InstantMessageServerConnector(IConfigSource config, IHttpServer server) : - this(config, server, null) + this(config, server, (IInstantMessageSimConnector)null) { } + public InstantMessageServerConnector(IConfigSource config, IHttpServer server, string configName) : + this(config, server) + { + } + public InstantMessageServerConnector(IConfigSource config, IHttpServer server, IInstantMessageSimConnector simConnector) : base(config, server, String.Empty) { diff --git a/OpenSim/Server/Handlers/Hypergrid/UserAgentServerConnector.cs b/OpenSim/Server/Handlers/Hypergrid/UserAgentServerConnector.cs index db62aaa..e112e0e 100644 --- a/OpenSim/Server/Handlers/Hypergrid/UserAgentServerConnector.cs +++ b/OpenSim/Server/Handlers/Hypergrid/UserAgentServerConnector.cs @@ -62,10 +62,15 @@ namespace OpenSim.Server.Handlers.Hypergrid private bool m_VerifyCallers = false; public UserAgentServerConnector(IConfigSource config, IHttpServer server) : - this(config, server, null) + this(config, server, (IFriendsSimConnector)null) { } + public UserAgentServerConnector(IConfigSource config, IHttpServer server, string configName) : + this(config, server) + { + } + public UserAgentServerConnector(IConfigSource config, IHttpServer server, IFriendsSimConnector friendsConnector) : base(config, server, String.Empty) { @@ -94,8 +99,10 @@ namespace OpenSim.Server.Handlers.Hypergrid server.AddXmlRPCHandler("verify_client", VerifyClient, false); server.AddXmlRPCHandler("logout_agent", LogoutAgent, false); +#pragma warning disable 0612 server.AddXmlRPCHandler("status_notification", StatusNotification, false); server.AddXmlRPCHandler("get_online_friends", GetOnlineFriends, false); +#pragma warning restore 0612 server.AddXmlRPCHandler("get_user_info", GetUserInfo, false); server.AddXmlRPCHandler("get_server_urls", GetServerURLs, false); @@ -103,7 +110,7 @@ namespace OpenSim.Server.Handlers.Hypergrid server.AddXmlRPCHandler("get_uui", GetUUI, false); server.AddXmlRPCHandler("get_uuid", GetUUID, false); - server.AddHTTPHandler("/homeagent/", new HomeAgentHandler(m_HomeUsersService, loginServerIP, proxy).Handler); + server.AddStreamHandler(new HomeAgentHandler(m_HomeUsersService, loginServerIP, proxy)); } public XmlRpcResponse GetHomeRegion(XmlRpcRequest request, IPEndPoint remoteClient) @@ -127,6 +134,8 @@ namespace OpenSim.Server.Handlers.Hypergrid hash["uuid"] = regInfo.RegionID.ToString(); hash["x"] = regInfo.RegionLocX.ToString(); hash["y"] = regInfo.RegionLocY.ToString(); + hash["size_x"] = regInfo.RegionSizeX.ToString(); + hash["size_y"] = regInfo.RegionSizeY.ToString(); hash["region_name"] = regInfo.RegionName; hash["hostname"] = regInfo.ExternalHostName; hash["http_port"] = regInfo.HttpPort.ToString(); @@ -448,7 +457,6 @@ namespace OpenSim.Server.Handlers.Hypergrid XmlRpcResponse response = new XmlRpcResponse(); response.Value = hash; return response; - } /// @@ -466,9 +474,7 @@ namespace OpenSim.Server.Handlers.Hypergrid //string portstr = (string)requestData["port"]; if (requestData.ContainsKey("first") && requestData.ContainsKey("last")) { - UUID userID = UUID.Zero; string first = (string)requestData["first"]; - string last = (string)requestData["last"]; UUID uuid = m_HomeUsersService.GetUUID(first, last); hash["UUID"] = uuid.ToString(); @@ -477,7 +483,6 @@ namespace OpenSim.Server.Handlers.Hypergrid XmlRpcResponse response = new XmlRpcResponse(); response.Value = hash; return response; - } } -} +} \ No newline at end of file diff --git a/OpenSim/Server/Handlers/Inventory/InventoryServerInConnector.cs b/OpenSim/Server/Handlers/Inventory/InventoryServerInConnector.cs index 1d422a7..b295446 100644 --- a/OpenSim/Server/Handlers/Inventory/InventoryServerInConnector.cs +++ b/OpenSim/Server/Handlers/Inventory/InventoryServerInConnector.cs @@ -86,10 +86,6 @@ namespace OpenSim.Server.Handlers.Inventory protected virtual void AddHttpHandlers(IHttpServer m_httpServer) { m_httpServer.AddStreamHandler( - new RestDeserialiseSecureHandler( - "POST", "/GetInventory/", GetUserInventory, CheckAuthSession)); - - m_httpServer.AddStreamHandler( new RestDeserialiseSecureHandler>( "POST", "/SystemFolders/", GetSystemFolders, CheckAuthSession)); @@ -178,12 +174,6 @@ namespace OpenSim.Server.Handlers.Inventory #region Wrappers for converting the Guid parameter - public InventoryCollection GetUserInventory(Guid guid) - { - UUID userID = new UUID(guid); - return m_InventoryService.GetUserInventory(userID); - } - public List GetSystemFolders(Guid guid) { UUID userID = new UUID(guid); diff --git a/OpenSim/Server/Handlers/Inventory/InventoryServerMoveItemsHandler.cs b/OpenSim/Server/Handlers/Inventory/InventoryServerMoveItemsHandler.cs index 231e32f..e2c50fe 100644 --- a/OpenSim/Server/Handlers/Inventory/InventoryServerMoveItemsHandler.cs +++ b/OpenSim/Server/Handlers/Inventory/InventoryServerMoveItemsHandler.cs @@ -56,7 +56,7 @@ namespace OpenSim.Server.Handlers.Inventory m_InventoryService = service; } - public override byte[] Handle(string path, Stream request, + protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { XmlSerializer xs = new XmlSerializer(typeof (List)); diff --git a/OpenSim/Server/Handlers/Inventory/XInventoryInConnector.cs b/OpenSim/Server/Handlers/Inventory/XInventoryInConnector.cs index 64127c2..5c4e7a9 100644 --- a/OpenSim/Server/Handlers/Inventory/XInventoryInConnector.cs +++ b/OpenSim/Server/Handlers/Inventory/XInventoryInConnector.cs @@ -33,6 +33,7 @@ using System.Collections.Generic; using System.IO; using Nini.Config; using OpenSim.Framework; +using OpenSim.Framework.ServiceAuth; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenSim.Framework.Servers.HttpServer; @@ -40,7 +41,9 @@ using OpenSim.Server.Handlers.Base; using log4net; using OpenMetaverse; -namespace OpenSim.Server.Handlers.Asset +using System.Threading; + +namespace OpenSim.Server.Handlers.Inventory { public class XInventoryInConnector : ServiceConnector { @@ -71,7 +74,9 @@ namespace OpenSim.Server.Handlers.Asset m_InventoryService = ServerUtils.LoadPlugin(inventoryService, args); - server.AddStreamHandler(new XInventoryConnectorPostHandler(m_InventoryService)); + IServiceAuth auth = ServiceAuth.Create(config, m_ConfigName); + + server.AddStreamHandler(new XInventoryConnectorPostHandler(m_InventoryService, auth)); } } @@ -81,13 +86,13 @@ namespace OpenSim.Server.Handlers.Asset private IInventoryService m_InventoryService; - public XInventoryConnectorPostHandler(IInventoryService service) : - base("POST", "/xinventory") + public XInventoryConnectorPostHandler(IInventoryService service, IServiceAuth auth) : + base("POST", "/xinventory", auth) { m_InventoryService = service; } - public override byte[] Handle(string path, Stream requestData, + protected override byte[] ProcessRequest(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { StreamReader sr = new StreamReader(requestData); @@ -114,14 +119,14 @@ namespace OpenSim.Server.Handlers.Asset return HandleCreateUserInventory(request); case "GETINVENTORYSKELETON": return HandleGetInventorySkeleton(request); - case "GETUSERINVENTORY": - return HandleGetUserInventory(request); case "GETROOTFOLDER": return HandleGetRootFolder(request); case "GETFOLDERFORTYPE": return HandleGetFolderForType(request); case "GETFOLDERCONTENT": return HandleGetFolderContent(request); + case "GETMULTIPLEFOLDERSCONTENT": + return HandleGetMultipleFoldersContent(request); case "GETFOLDERITEMS": return HandleGetFolderItems(request); case "ADDFOLDER": @@ -144,6 +149,8 @@ namespace OpenSim.Server.Handlers.Asset return HandleDeleteItems(request); case "GETITEM": return HandleGetItem(request); + case "GETMULTIPLEITEMS": + return HandleGetMultipleItems(request); case "GETFOLDER": return HandleGetFolder(request); case "GETACTIVEGESTURES": @@ -155,7 +162,7 @@ namespace OpenSim.Server.Handlers.Asset } catch (Exception e) { - m_log.DebugFormat("[XINVENTORY HANDLER]: Exception {0}", e.StackTrace); + m_log.Error(string.Format("[XINVENTORY HANDLER]: Exception {0} ", e.Message), e); } return FailureResult(); @@ -190,18 +197,7 @@ namespace OpenSim.Server.Handlers.Asset rootElement.AppendChild(result); - return DocToBytes(doc); - } - - private byte[] DocToBytes(XmlDocument doc) - { - MemoryStream ms = new MemoryStream(); - XmlTextWriter xw = new XmlTextWriter(ms, null); - xw.Formatting = Formatting.Indented; - doc.WriteTo(xw); - xw.Flush(); - - return ms.ToArray(); + return Util.DocToBytes(doc); } byte[] HandleCreateUserInventory(Dictionary request) @@ -250,45 +246,6 @@ namespace OpenSim.Server.Handlers.Asset return Util.UTF8NoBomEncoding.GetBytes(xmlString); } - byte[] HandleGetUserInventory(Dictionary request) - { - Dictionary result = new Dictionary(); - UUID principal = UUID.Zero; - UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); - - InventoryCollection icoll = m_InventoryService.GetUserInventory(principal); - if (icoll != null) - { - Dictionary folders = new Dictionary(); - int i = 0; - if (icoll.Folders != null) - { - foreach (InventoryFolderBase f in icoll.Folders) - { - folders["folder_" + i.ToString()] = EncodeFolder(f); - i++; - } - result["FOLDERS"] = folders; - } - if (icoll.Items != null) - { - i = 0; - Dictionary items = new Dictionary(); - foreach (InventoryItemBase it in icoll.Items) - { - items["item_" + i.ToString()] = EncodeItem(it); - i++; - } - result["ITEMS"] = items; - } - } - - string xmlString = ServerUtils.BuildXmlResponse(result); - - //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); - return Util.UTF8NoBomEncoding.GetBytes(xmlString); - } - byte[] HandleGetRootFolder(Dictionary request) { Dictionary result = new Dictionary(); @@ -312,7 +269,7 @@ namespace OpenSim.Server.Handlers.Asset UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); int type = 0; Int32.TryParse(request["TYPE"].ToString(), out type); - InventoryFolderBase folder = m_InventoryService.GetFolderForType(principal, (AssetType)type); + InventoryFolderBase folder = m_InventoryService.GetFolderForType(principal, (FolderType)type); if (folder != null) result["folder"] = EncodeFolder(folder); @@ -333,6 +290,8 @@ namespace OpenSim.Server.Handlers.Asset InventoryCollection icoll = m_InventoryService.GetFolderContent(principal, folderID); if (icoll != null) { + result["FID"] = icoll.FolderID.ToString(); + result["VERSION"] = icoll.Version.ToString(); Dictionary folders = new Dictionary(); int i = 0; if (icoll.Folders != null) @@ -363,7 +322,71 @@ namespace OpenSim.Server.Handlers.Asset return Util.UTF8NoBomEncoding.GetBytes(xmlString); } - byte[] HandleGetFolderItems(Dictionary request) + byte[] HandleGetMultipleFoldersContent(Dictionary request) + { + Dictionary resultSet = new Dictionary(); + UUID principal = UUID.Zero; + UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); + string folderIDstr = request["FOLDERS"].ToString(); + int count = 0; + Int32.TryParse(request["COUNT"].ToString(), out count); + + UUID[] fids = new UUID[count]; + string[] uuids = folderIDstr.Split(','); + int i = 0; + foreach (string id in uuids) + { + UUID fid = UUID.Zero; + if (UUID.TryParse(id, out fid)) + fids[i] = fid; + i += 1; + } + + count = 0; + InventoryCollection[] icollList = m_InventoryService.GetMultipleFoldersContent(principal, fids); + if (icollList != null && icollList.Length > 0) + { + foreach (InventoryCollection icoll in icollList) + { + Dictionary result = new Dictionary(); + result["FID"] = icoll.FolderID.ToString(); + result["VERSION"] = icoll.Version.ToString(); + result["OWNER"] = icoll.OwnerID.ToString(); + Dictionary folders = new Dictionary(); + i = 0; + if (icoll.Folders != null) + { + foreach (InventoryFolderBase f in icoll.Folders) + { + folders["folder_" + i.ToString()] = EncodeFolder(f); + i++; + } + result["FOLDERS"] = folders; + } + i = 0; + if (icoll.Items != null) + { + Dictionary items = new Dictionary(); + foreach (InventoryItemBase it in icoll.Items) + { + items["item_" + i.ToString()] = EncodeItem(it); + i++; + } + result["ITEMS"] = items; + } + + resultSet["F_" + fids[count++]] = result; + //m_log.DebugFormat("[XXX]: Sending {0} {1}", fids[count-1], icoll.FolderID); + } + } + + string xmlString = ServerUtils.BuildXmlResponse(resultSet); + + //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); + return Util.UTF8NoBomEncoding.GetBytes(xmlString); + } + + byte[] HandleGetFolderItems(Dictionary request) { Dictionary result = new Dictionary(); UUID principal = UUID.Zero; @@ -555,6 +578,40 @@ namespace OpenSim.Server.Handlers.Asset return Util.UTF8NoBomEncoding.GetBytes(xmlString); } + byte[] HandleGetMultipleItems(Dictionary request) + { + Dictionary resultSet = new Dictionary(); + UUID principal = UUID.Zero; + UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); + string itemIDstr = request["ITEMS"].ToString(); + int count = 0; + Int32.TryParse(request["COUNT"].ToString(), out count); + + UUID[] fids = new UUID[count]; + string[] uuids = itemIDstr.Split(','); + int i = 0; + foreach (string id in uuids) + { + UUID fid = UUID.Zero; + if (UUID.TryParse(id, out fid)) + fids[i] = fid; + i += 1; + } + + InventoryItemBase[] itemsList = m_InventoryService.GetMultipleItems(principal, fids); + if (itemsList != null && itemsList.Length > 0) + { + count = 0; + foreach (InventoryItemBase item in itemsList) + resultSet["item_" + count++] = (item == null) ? (object)"NULL" : EncodeItem(item); + } + + string xmlString = ServerUtils.BuildXmlResponse(resultSet); + + //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); + return Util.UTF8NoBomEncoding.GetBytes(xmlString); + } + byte[] HandleGetFolder(Dictionary request) { Dictionary result = new Dictionary(); diff --git a/OpenSim/Server/Handlers/Login/LLLoginHandlers.cs b/OpenSim/Server/Handlers/Login/LLLoginHandlers.cs index f83a239..f2a5678 100644 --- a/OpenSim/Server/Handlers/Login/LLLoginHandlers.cs +++ b/OpenSim/Server/Handlers/Login/LLLoginHandlers.cs @@ -53,6 +53,7 @@ namespace OpenSim.Server.Handlers.Login private ILoginService m_LocalService; private bool m_Proxy; + public LLLoginHandlers(ILoginService service, bool hasProxy) { @@ -144,6 +145,17 @@ namespace OpenSim.Server.Handlers.Login return FailedXMLRPCResponse(); } + public XmlRpcResponse HandleXMLRPCLoginBlocked(XmlRpcRequest request, IPEndPoint client) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable resp = new Hashtable(); + + resp["reason"] = "presence"; + resp["message"] = "Logins are currently restricted. Please try again later."; + resp["login"] = "false"; + response.Value = resp; + return response; + } public XmlRpcResponse HandleXMLRPCSetLoginLevel(XmlRpcRequest request, IPEndPoint remoteClient) { @@ -213,6 +225,61 @@ namespace OpenSim.Server.Handlers.Login return FailedOSDResponse(); } + public void HandleWebSocketLoginEvents(string path, WebSocketHttpServerHandler sock) + { + sock.MaxPayloadSize = 16384; //16 kb payload + sock.InitialMsgTimeout = 5000; //5 second first message to trigger at least one of these events + sock.NoDelay_TCP_Nagle = true; + sock.OnData += delegate(object sender, WebsocketDataEventArgs data) { sock.Close("fail"); }; + sock.OnPing += delegate(object sender, PingEventArgs pingdata) { sock.Close("fail"); }; + sock.OnPong += delegate(object sender, PongEventArgs pongdata) { sock.Close("fail"); }; + sock.OnText += delegate(object sender, WebsocketTextEventArgs text) + { + OSD request = null; + try + { + request = OSDParser.DeserializeJson(text.Data); + if (!(request is OSDMap)) + { + sock.SendMessage(OSDParser.SerializeJsonString(FailedOSDResponse())); + } + else + { + OSDMap req = request as OSDMap; + string first = req["firstname"].AsString(); + string last = req["lastname"].AsString(); + string passwd = req["passwd"].AsString(); + string start = req["startlocation"].AsString(); + string version = req["version"].AsString(); + string channel = req["channel"].AsString(); + string mac = req["mac"].AsString(); + string id0 = req["id0"].AsString(); + UUID scope = UUID.Zero; + IPEndPoint endPoint = + (sender as WebSocketHttpServerHandler).GetRemoteIPEndpoint(); + LoginResponse reply = null; + reply = m_LocalService.Login(first, last, passwd, start, scope, version, + channel, mac, id0, endPoint); + sock.SendMessage(OSDParser.SerializeJsonString(reply.ToOSDMap())); + + } + + } + catch (Exception) + { + sock.SendMessage(OSDParser.SerializeJsonString(FailedOSDResponse())); + } + finally + { + sock.Close("success"); + } + }; + + sock.HandshakeAndUpgrade(); + + } + + private XmlRpcResponse FailedXMLRPCResponse() { Hashtable hash = new Hashtable(); diff --git a/OpenSim/Server/Handlers/Login/LLLoginServiceInConnector.cs b/OpenSim/Server/Handlers/Login/LLLoginServiceInConnector.cs index 9a7ad34..f60e892 100644 --- a/OpenSim/Server/Handlers/Login/LLLoginServiceInConnector.cs +++ b/OpenSim/Server/Handlers/Login/LLLoginServiceInConnector.cs @@ -44,6 +44,7 @@ namespace OpenSim.Server.Handlers.Login private ILoginService m_LoginService; private bool m_Proxy; + private BasicDosProtectorOptions m_DosProtectionOptions; public LLLoginServiceInConnector(IConfigSource config, IHttpServer server, IScene scene) : base(config, server, String.Empty) @@ -60,8 +61,8 @@ namespace OpenSim.Server.Handlers.Login InitializeHandlers(server); } - public LLLoginServiceInConnector(IConfigSource config, IHttpServer server) : - base(config, server, String.Empty) + public LLLoginServiceInConnector(IConfigSource config, IHttpServer server, string configName) : + base(config, server, configName) { string loginService = ReadLocalServiceFromConfig(config); @@ -72,6 +73,11 @@ namespace OpenSim.Server.Handlers.Login InitializeHandlers(server); } + public LLLoginServiceInConnector(IConfigSource config, IHttpServer server) : + this(config, server, String.Empty) + { + } + private string ReadLocalServiceFromConfig(IConfigSource config) { IConfig serverConfig = config.Configs["LoginService"]; @@ -83,6 +89,16 @@ namespace OpenSim.Server.Handlers.Login throw new Exception(String.Format("No LocalServiceModule for LoginService in config file")); m_Proxy = serverConfig.GetBoolean("HasProxy", false); + m_DosProtectionOptions = new BasicDosProtectorOptions(); + // Dos Protection Options + m_DosProtectionOptions.AllowXForwardedFor = serverConfig.GetBoolean("DOSAllowXForwardedForHeader", false); + m_DosProtectionOptions.RequestTimeSpan = + TimeSpan.FromMilliseconds(serverConfig.GetInt("DOSRequestTimeFrameMS", 10000)); + m_DosProtectionOptions.MaxRequestsInTimeframe = serverConfig.GetInt("DOSMaxRequestsInTimeFrame", 5); + m_DosProtectionOptions.ForgetTimeSpan = + TimeSpan.FromMilliseconds(serverConfig.GetInt("DOSForgiveClientAfterMS", 120000)); + m_DosProtectionOptions.ReportingName = "LOGINDOSPROTECTION"; + return loginService; } @@ -90,9 +106,12 @@ namespace OpenSim.Server.Handlers.Login private void InitializeHandlers(IHttpServer server) { LLLoginHandlers loginHandlers = new LLLoginHandlers(m_LoginService, m_Proxy); - server.AddXmlRPCHandler("login_to_simulator", loginHandlers.HandleXMLRPCLogin, false); + server.AddXmlRPCHandler("login_to_simulator", + new XmlRpcBasicDOSProtector(loginHandlers.HandleXMLRPCLogin,loginHandlers.HandleXMLRPCLoginBlocked, + m_DosProtectionOptions).Process, false); server.AddXmlRPCHandler("set_login_level", loginHandlers.HandleXMLRPCSetLoginLevel, false); server.SetDefaultLLSDHandler(loginHandlers.HandleLLSDLogin); + server.AddWebSocketHandler("/WebSocket/GridLogin", loginHandlers.HandleWebSocketLoginEvents); } } } diff --git a/OpenSim/Server/Handlers/Map/MapAddServerConnector.cs b/OpenSim/Server/Handlers/Map/MapAddServerConnector.cs index 4a61969..649a27e 100644 --- a/OpenSim/Server/Handlers/Map/MapAddServerConnector.cs +++ b/OpenSim/Server/Handlers/Map/MapAddServerConnector.cs @@ -38,6 +38,7 @@ using OpenMetaverse; using OpenSim.Framework; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; +using OpenSim.Framework.ServiceAuth; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Server.Handlers.Base; @@ -79,7 +80,8 @@ namespace OpenSim.Server.Handlers.MapImage m_log.InfoFormat("[MAP IMAGE HANDLER]: GridService check is OFF"); bool proxy = serverConfig.GetBoolean("HasProxy", false); - server.AddStreamHandler(new MapServerPostHandler(m_MapService, m_GridService, proxy)); + IServiceAuth auth = ServiceAuth.Create(config, m_ConfigName); + server.AddStreamHandler(new MapServerPostHandler(m_MapService, m_GridService, proxy, auth)); } } @@ -91,15 +93,15 @@ namespace OpenSim.Server.Handlers.MapImage private IGridService m_GridService; bool m_Proxy; - public MapServerPostHandler(IMapImageService service, IGridService grid, bool proxy) : - base("POST", "/map") + public MapServerPostHandler(IMapImageService service, IGridService grid, bool proxy, IServiceAuth auth) : + base("POST", "/map", auth) { m_MapService = service; m_GridService = grid; m_Proxy = proxy; } - public override byte[] Handle(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) + protected override byte[] ProcessRequest(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // m_log.DebugFormat("[MAP SERVICE IMAGE HANDLER]: Received {0}", path); StreamReader sr = new StreamReader(requestData); @@ -116,9 +118,9 @@ namespace OpenSim.Server.Handlers.MapImage httpResponse.StatusCode = (int)OSHttpStatusCode.ClientErrorBadRequest; return FailureResult("Bad request."); } - int x = 0, y = 0; - Int32.TryParse(request["X"].ToString(), out x); - Int32.TryParse(request["Y"].ToString(), out y); + uint x = 0, y = 0; + UInt32.TryParse(request["X"].ToString(), out x); + UInt32.TryParse(request["Y"].ToString(), out y); m_log.DebugFormat("[MAP ADD SERVER CONNECTOR]: Received map data for region at {0}-{1}", x, y); @@ -130,7 +132,7 @@ namespace OpenSim.Server.Handlers.MapImage if (m_GridService != null) { System.Net.IPAddress ipAddr = GetCallerIP(httpRequest); - GridRegion r = m_GridService.GetRegionByPosition(UUID.Zero, x * (int)Constants.RegionSize, y * (int)Constants.RegionSize); + GridRegion r = m_GridService.GetRegionByPosition(UUID.Zero, (int)Util.RegionToWorldLoc(x), (int)Util.RegionToWorldLoc(y)); if (r != null) { if (r.ExternalEndPoint.Address.ToString() != ipAddr.ToString()) @@ -151,7 +153,7 @@ namespace OpenSim.Server.Handlers.MapImage byte[] data = Convert.FromBase64String(request["DATA"].ToString()); string reason = string.Empty; - bool result = m_MapService.AddMapTile(x, y, data, out reason); + bool result = m_MapService.AddMapTile((int)x, (int)y, data, out reason); if (result) return SuccessResult(); @@ -186,7 +188,7 @@ namespace OpenSim.Server.Handlers.MapImage rootElement.AppendChild(result); - return DocToBytes(doc); + return Util.DocToBytes(doc); } private byte[] FailureResult(string msg) @@ -213,18 +215,7 @@ namespace OpenSim.Server.Handlers.MapImage rootElement.AppendChild(message); - return DocToBytes(doc); - } - - private byte[] DocToBytes(XmlDocument doc) - { - MemoryStream ms = new MemoryStream(); - XmlTextWriter xw = new XmlTextWriter(ms, null); - xw.Formatting = Formatting.Indented; - doc.WriteTo(xw); - xw.Flush(); - - return ms.ToArray(); + return Util.DocToBytes(doc); } private System.Net.IPAddress GetCallerIP(IOSHttpRequest request) diff --git a/OpenSim/Server/Handlers/Map/MapGetServerConnector.cs b/OpenSim/Server/Handlers/Map/MapGetServerConnector.cs index fb85d1c..7bb2f39 100644 --- a/OpenSim/Server/Handlers/Map/MapGetServerConnector.cs +++ b/OpenSim/Server/Handlers/Map/MapGetServerConnector.cs @@ -80,7 +80,7 @@ namespace OpenSim.Server.Handlers.MapImage m_MapService = service; } - public override byte[] Handle(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) + protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { byte[] result = new byte[0]; diff --git a/OpenSim/Server/Handlers/Neighbour/NeighbourHandlers.cs b/OpenSim/Server/Handlers/Neighbour/NeighbourHandlers.cs index 8a1f824..3525a01 100644 --- a/OpenSim/Server/Handlers/Neighbour/NeighbourHandlers.cs +++ b/OpenSim/Server/Handlers/Neighbour/NeighbourHandlers.cs @@ -58,7 +58,7 @@ namespace OpenSim.Server.Handlers.Neighbour // TODO: unused: m_AuthenticationService = authentication; } - public override byte[] Handle(string path, Stream request, + protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // Not implemented yet @@ -83,7 +83,7 @@ namespace OpenSim.Server.Handlers.Neighbour // TODO: unused: m_AllowForeignGuests = foreignGuests; } - public override byte[] Handle(string path, Stream request, + protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { byte[] result = new byte[0]; @@ -176,7 +176,7 @@ namespace OpenSim.Server.Handlers.Neighbour // TODO: unused: m_AuthenticationService = authentication; } - public override byte[] Handle(string path, Stream request, + protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // Not implemented yet @@ -197,7 +197,7 @@ namespace OpenSim.Server.Handlers.Neighbour // TODO: unused: m_AuthenticationService = authentication; } - public override byte[] Handle(string path, Stream request, + protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // Not implemented yet diff --git a/OpenSim/Server/Handlers/Presence/PresenceServerConnector.cs b/OpenSim/Server/Handlers/Presence/PresenceServerConnector.cs index 899cd8f..7a63c36 100644 --- a/OpenSim/Server/Handlers/Presence/PresenceServerConnector.cs +++ b/OpenSim/Server/Handlers/Presence/PresenceServerConnector.cs @@ -30,6 +30,7 @@ using Nini.Config; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenSim.Framework.Servers.HttpServer; +using OpenSim.Framework.ServiceAuth; using OpenSim.Server.Handlers.Base; namespace OpenSim.Server.Handlers.Presence @@ -55,7 +56,9 @@ namespace OpenSim.Server.Handlers.Presence Object[] args = new Object[] { config }; m_PresenceService = ServerUtils.LoadPlugin(gridService, args); - server.AddStreamHandler(new PresenceServerPostHandler(m_PresenceService)); + IServiceAuth auth = ServiceAuth.Create(config, m_ConfigName); + + server.AddStreamHandler(new PresenceServerPostHandler(m_PresenceService, auth)); } } } diff --git a/OpenSim/Server/Handlers/Presence/PresenceServerPostHandler.cs b/OpenSim/Server/Handlers/Presence/PresenceServerPostHandler.cs index 2d67c6d..49dbcb5 100644 --- a/OpenSim/Server/Handlers/Presence/PresenceServerPostHandler.cs +++ b/OpenSim/Server/Handlers/Presence/PresenceServerPostHandler.cs @@ -40,6 +40,7 @@ using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; +using OpenSim.Framework.ServiceAuth; using OpenMetaverse; namespace OpenSim.Server.Handlers.Presence @@ -50,13 +51,13 @@ namespace OpenSim.Server.Handlers.Presence private IPresenceService m_PresenceService; - public PresenceServerPostHandler(IPresenceService service) : - base("POST", "/presence") + public PresenceServerPostHandler(IPresenceService service, IServiceAuth auth) : + base("POST", "/presence", auth) { m_PresenceService = service; } - public override byte[] Handle(string path, Stream requestData, + protected override byte[] ProcessRequest(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { StreamReader sr = new StreamReader(requestData); @@ -264,7 +265,7 @@ namespace OpenSim.Server.Handlers.Presence rootElement.AppendChild(result); - return DocToBytes(doc); + return Util.DocToBytes(doc); } private byte[] FailureResult() @@ -286,18 +287,7 @@ namespace OpenSim.Server.Handlers.Presence rootElement.AppendChild(result); - return DocToBytes(doc); - } - - private byte[] DocToBytes(XmlDocument doc) - { - MemoryStream ms = new MemoryStream(); - XmlTextWriter xw = new XmlTextWriter(ms, null); - xw.Formatting = Formatting.Indented; - doc.WriteTo(xw); - xw.Flush(); - - return ms.ToArray(); + return Util.DocToBytes(doc); } } diff --git a/OpenSim/Server/Handlers/Profiles/UserProfilesConnector.cs b/OpenSim/Server/Handlers/Profiles/UserProfilesConnector.cs new file mode 100644 index 0000000..2dfb862 --- /dev/null +++ b/OpenSim/Server/Handlers/Profiles/UserProfilesConnector.cs @@ -0,0 +1,109 @@ +/* + * 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.Reflection; +using Nini.Config; +using OpenSim.Server.Base; +using OpenSim.Services.Interfaces; +using OpenSim.Framework.Servers.HttpServer; +using OpenSim.Framework; +using OpenSim.Server.Handlers.Base; +using log4net; + +namespace OpenSim.Server.Handlers.Profiles +{ + public class UserProfilesConnector: ServiceConnector + { +// static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + // Our Local Module + public IUserProfilesService ServiceModule + { + get; private set; + } + + // The HTTP server. + public IHttpServer Server + { + get; private set; + } + + public bool Enabled + { + get; private set; + } + + public UserProfilesConnector(IConfigSource config, IHttpServer server, string configName) : + base(config, server, configName) + { + ConfigName = "UserProfilesService"; + if(!string.IsNullOrEmpty(configName)) + ConfigName = configName; + + IConfig serverConfig = config.Configs[ConfigName]; + if (serverConfig == null) + throw new Exception(String.Format("No section {0} in config file", ConfigName)); + + if(!serverConfig.GetBoolean("Enabled",false)) + { + Enabled = false; + return; + } + + Enabled = true; + + Server = server; + + string service = serverConfig.GetString("LocalServiceModule", String.Empty); + + Object[] args = new Object[] { config, ConfigName }; + ServiceModule = ServerUtils.LoadPlugin(service, args); + + JsonRpcProfileHandlers handler = new JsonRpcProfileHandlers(ServiceModule); + + Server.AddJsonRPCHandler("avatarclassifiedsrequest", handler.AvatarClassifiedsRequest); + Server.AddJsonRPCHandler("classified_update", handler.ClassifiedUpdate); + Server.AddJsonRPCHandler("classifieds_info_query", handler.ClassifiedInfoRequest); + Server.AddJsonRPCHandler("classified_delete", handler.ClassifiedDelete); + Server.AddJsonRPCHandler("avatarpicksrequest", handler.AvatarPicksRequest); + Server.AddJsonRPCHandler("pickinforequest", handler.PickInfoRequest); + Server.AddJsonRPCHandler("picks_update", handler.PicksUpdate); + Server.AddJsonRPCHandler("picks_delete", handler.PicksDelete); + Server.AddJsonRPCHandler("avatarnotesrequest", handler.AvatarNotesRequest); + Server.AddJsonRPCHandler("avatar_notes_update", handler.NotesUpdate); + Server.AddJsonRPCHandler("avatar_properties_request", handler.AvatarPropertiesRequest); + Server.AddJsonRPCHandler("avatar_properties_update", handler.AvatarPropertiesUpdate); + Server.AddJsonRPCHandler("avatar_interests_update", handler.AvatarInterestsUpdate); + Server.AddJsonRPCHandler("user_preferences_update", handler.UserPreferenecesUpdate); + Server.AddJsonRPCHandler("user_preferences_request", handler.UserPreferencesRequest); + Server.AddJsonRPCHandler("image_assets_request", handler.AvatarImageAssetsRequest); + Server.AddJsonRPCHandler("user_data_request", handler.RequestUserAppData); + Server.AddJsonRPCHandler("user_data_update", handler.UpdateUserAppData); + } + } +} \ No newline at end of file diff --git a/OpenSim/Server/Handlers/Profiles/UserProfilesHandlers.cs b/OpenSim/Server/Handlers/Profiles/UserProfilesHandlers.cs new file mode 100644 index 0000000..49aa8ba --- /dev/null +++ b/OpenSim/Server/Handlers/Profiles/UserProfilesHandlers.cs @@ -0,0 +1,513 @@ +/* + * 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.Reflection; +using OpenMetaverse; +using OpenMetaverse.StructuredData; +using log4net; +using OpenSim.Services.Interfaces; +using OpenSim.Framework.Servers.HttpServer; +using OpenSim.Framework; + +namespace OpenSim.Server.Handlers +{ + public class UserProfilesHandlers + { + public UserProfilesHandlers () + { + } + } + + public class JsonRpcProfileHandlers + { + static readonly ILog m_log = + LogManager.GetLogger( + MethodBase.GetCurrentMethod().DeclaringType); + + public IUserProfilesService Service + { + get; private set; + } + + public JsonRpcProfileHandlers(IUserProfilesService service) + { + Service = service; + } + + #region Classifieds + /// + /// Request avatar's classified ads. + /// + /// + /// An array containing all the calassified uuid and it's name created by the creator id + /// + /// + /// Our parameters are in the OSDMap json["params"] + /// + /// + /// If set to true response. + /// + public bool AvatarClassifiedsRequest(OSDMap json, ref JsonRpcResponse response) + { + if(!json.ContainsKey("params")) + { + response.Error.Code = ErrorCode.ParseError; + m_log.DebugFormat ("Classified Request"); + return false; + } + + OSDMap request = (OSDMap)json["params"]; + UUID creatorId = new UUID(request["creatorId"].AsString()); + + + OSDArray data = (OSDArray) Service.AvatarClassifiedsRequest(creatorId); + response.Result = data; + + return true; + } + + public bool ClassifiedUpdate(OSDMap json, ref JsonRpcResponse response) + { + if(!json.ContainsKey("params")) + { + response.Error.Code = ErrorCode.ParseError; + response.Error.Message = "Error parsing classified update request"; + m_log.DebugFormat ("Classified Update Request"); + return false; + } + + string result = string.Empty; + UserClassifiedAdd ad = new UserClassifiedAdd(); + object Ad = (object)ad; + OSD.DeserializeMembers(ref Ad, (OSDMap)json["params"]); + if(Service.ClassifiedUpdate(ad, ref result)) + { + response.Result = OSD.SerializeMembers(ad); + return true; + } + + response.Error.Code = ErrorCode.InternalError; + response.Error.Message = string.Format("{0}", result); + return false; + } + + public bool ClassifiedDelete(OSDMap json, ref JsonRpcResponse response) + { + if(!json.ContainsKey("params")) + { + response.Error.Code = ErrorCode.ParseError; + m_log.DebugFormat ("Classified Delete Request"); + return false; + } + + OSDMap request = (OSDMap)json["params"]; + UUID classifiedId = new UUID(request["classifiedId"].AsString()); + + if (Service.ClassifiedDelete(classifiedId)) + return true; + + response.Error.Code = ErrorCode.InternalError; + response.Error.Message = "data error removing record"; + return false; + } + + public bool ClassifiedInfoRequest(OSDMap json, ref JsonRpcResponse response) + { + if(!json.ContainsKey("params")) + { + response.Error.Code = ErrorCode.ParseError; + response.Error.Message = "no parameters supplied"; + m_log.DebugFormat ("Classified Info Request"); + return false; + } + + string result = string.Empty; + UserClassifiedAdd ad = new UserClassifiedAdd(); + object Ad = (object)ad; + OSD.DeserializeMembers(ref Ad, (OSDMap)json["params"]); + if(Service.ClassifiedInfoRequest(ref ad, ref result)) + { + response.Result = OSD.SerializeMembers(ad); + return true; + } + + response.Error.Code = ErrorCode.InternalError; + response.Error.Message = string.Format("{0}", result); + return false; + } + #endregion Classifieds + + #region Picks + public bool AvatarPicksRequest(OSDMap json, ref JsonRpcResponse response) + { + if(!json.ContainsKey("params")) + { + response.Error.Code = ErrorCode.ParseError; + m_log.DebugFormat ("Avatar Picks Request"); + return false; + } + + OSDMap request = (OSDMap)json["params"]; + UUID creatorId = new UUID(request["creatorId"].AsString()); + + + OSDArray data = (OSDArray) Service.AvatarPicksRequest(creatorId); + response.Result = data; + + return true; + } + + public bool PickInfoRequest(OSDMap json, ref JsonRpcResponse response) + { + if(!json.ContainsKey("params")) + { + response.Error.Code = ErrorCode.ParseError; + response.Error.Message = "no parameters supplied"; + m_log.DebugFormat ("Avatar Picks Info Request"); + return false; + } + + string result = string.Empty; + UserProfilePick pick = new UserProfilePick(); + object Pick = (object)pick; + OSD.DeserializeMembers(ref Pick, (OSDMap)json["params"]); + if(Service.PickInfoRequest(ref pick, ref result)) + { + response.Result = OSD.SerializeMembers(pick); + return true; + } + + response.Error.Code = ErrorCode.InternalError; + response.Error.Message = string.Format("{0}", result); + return false; + } + + public bool PicksUpdate(OSDMap json, ref JsonRpcResponse response) + { + if(!json.ContainsKey("params")) + { + response.Error.Code = ErrorCode.ParseError; + response.Error.Message = "no parameters supplied"; + m_log.DebugFormat ("Avatar Picks Update Request"); + return false; + } + + string result = string.Empty; + UserProfilePick pick = new UserProfilePick(); + object Pick = (object)pick; + OSD.DeserializeMembers(ref Pick, (OSDMap)json["params"]); + if(Service.PicksUpdate(ref pick, ref result)) + { + response.Result = OSD.SerializeMembers(pick); + return true; + } + + response.Error.Code = ErrorCode.InternalError; + response.Error.Message = "unable to update pick"; + + return false; + } + + public bool PicksDelete(OSDMap json, ref JsonRpcResponse response) + { + if(!json.ContainsKey("params")) + { + response.Error.Code = ErrorCode.ParseError; + m_log.DebugFormat ("Avatar Picks Delete Request"); + return false; + } + + OSDMap request = (OSDMap)json["params"]; + UUID pickId = new UUID(request["pickId"].AsString()); + if(Service.PicksDelete(pickId)) + return true; + + response.Error.Code = ErrorCode.InternalError; + response.Error.Message = "data error removing record"; + return false; + } + #endregion Picks + + #region Notes + public bool AvatarNotesRequest(OSDMap json, ref JsonRpcResponse response) + { + if(!json.ContainsKey("params")) + { + response.Error.Code = ErrorCode.ParseError; + response.Error.Message = "Params missing"; + m_log.DebugFormat ("Avatar Notes Request"); + return false; + } + + UserProfileNotes note = new UserProfileNotes(); + object Note = (object)note; + OSD.DeserializeMembers(ref Note, (OSDMap)json["params"]); + if(Service.AvatarNotesRequest(ref note)) + { + response.Result = OSD.SerializeMembers(note); + return true; + } + + response.Error.Code = ErrorCode.InternalError; + response.Error.Message = "Error reading notes"; + return false; + } + + public bool NotesUpdate(OSDMap json, ref JsonRpcResponse response) + { + if(!json.ContainsKey("params")) + { + response.Error.Code = ErrorCode.ParseError; + response.Error.Message = "No parameters"; + m_log.DebugFormat ("Avatar Notes Update Request"); + return false; + } + + string result = string.Empty; + UserProfileNotes note = new UserProfileNotes(); + object Notes = (object) note; + OSD.DeserializeMembers(ref Notes, (OSDMap)json["params"]); + if(Service.NotesUpdate(ref note, ref result)) + { + response.Result = OSD.SerializeMembers(note); + return true; + } + return true; + } + #endregion Notes + + #region Profile Properties + public bool AvatarPropertiesRequest(OSDMap json, ref JsonRpcResponse response) + { + if(!json.ContainsKey("params")) + { + response.Error.Code = ErrorCode.ParseError; + response.Error.Message = "no parameters supplied"; + m_log.DebugFormat ("Avatar Properties Request"); + return false; + } + + string result = string.Empty; + UserProfileProperties props = new UserProfileProperties(); + object Props = (object)props; + OSD.DeserializeMembers(ref Props, (OSDMap)json["params"]); + if(Service.AvatarPropertiesRequest(ref props, ref result)) + { + response.Result = OSD.SerializeMembers(props); + return true; + } + + response.Error.Code = ErrorCode.InternalError; + response.Error.Message = string.Format("{0}", result); + return false; + } + + public bool AvatarPropertiesUpdate(OSDMap json, ref JsonRpcResponse response) + { + if(!json.ContainsKey("params")) + { + response.Error.Code = ErrorCode.ParseError; + response.Error.Message = "no parameters supplied"; + m_log.DebugFormat ("Avatar Properties Update Request"); + return false; + } + + string result = string.Empty; + UserProfileProperties props = new UserProfileProperties(); + object Props = (object)props; + OSD.DeserializeMembers(ref Props, (OSDMap)json["params"]); + if(Service.AvatarPropertiesUpdate(ref props, ref result)) + { + response.Result = OSD.SerializeMembers(props); + return true; + } + + response.Error.Code = ErrorCode.InternalError; + response.Error.Message = string.Format("{0}", result); + return false; + } + #endregion Profile Properties + + #region Interests + public bool AvatarInterestsUpdate(OSDMap json, ref JsonRpcResponse response) + { + if(!json.ContainsKey("params")) + { + response.Error.Code = ErrorCode.ParseError; + response.Error.Message = "no parameters supplied"; + m_log.DebugFormat ("Avatar Interests Update Request"); + return false; + } + + string result = string.Empty; + UserProfileProperties props = new UserProfileProperties(); + object Props = (object)props; + OSD.DeserializeMembers(ref Props, (OSDMap)json["params"]); + if(Service.AvatarInterestsUpdate(props, ref result)) + { + response.Result = OSD.SerializeMembers(props); + return true; + } + + response.Error.Code = ErrorCode.InternalError; + response.Error.Message = string.Format("{0}", result); + return false; + } + #endregion Interests + + #region User Preferences + public bool UserPreferencesRequest(OSDMap json, ref JsonRpcResponse response) + { + if(!json.ContainsKey("params")) + { + response.Error.Code = ErrorCode.ParseError; + m_log.DebugFormat ("User Preferences Request"); + return false; + } + + string result = string.Empty; + UserPreferences prefs = new UserPreferences(); + object Prefs = (object)prefs; + OSD.DeserializeMembers(ref Prefs, (OSDMap)json["params"]); + if(Service.UserPreferencesRequest(ref prefs, ref result)) + { + response.Result = OSD.SerializeMembers(prefs); + return true; + } + + response.Error.Code = ErrorCode.InternalError; + response.Error.Message = string.Format("{0}", result); +// m_log.InfoFormat("[PROFILES]: User preferences request error - {0}", response.Error.Message); + return false; + } + + public bool UserPreferenecesUpdate(OSDMap json, ref JsonRpcResponse response) + { + if(!json.ContainsKey("params")) + { + response.Error.Code = ErrorCode.ParseError; + response.Error.Message = "no parameters supplied"; + m_log.DebugFormat ("User Preferences Update Request"); + return false; + } + + string result = string.Empty; + UserPreferences prefs = new UserPreferences(); + object Prefs = (object)prefs; + OSD.DeserializeMembers(ref Prefs, (OSDMap)json["params"]); + if(Service.UserPreferencesUpdate(ref prefs, ref result)) + { + response.Result = OSD.SerializeMembers(prefs); + return true; + } + + response.Error.Code = ErrorCode.InternalError; + response.Error.Message = string.Format("{0}", result); + m_log.InfoFormat("[PROFILES]: User preferences update error - {0}", response.Error.Message); + return false; + } + #endregion User Preferences + + #region Utility + public bool AvatarImageAssetsRequest(OSDMap json, ref JsonRpcResponse response) + { + if(!json.ContainsKey("params")) + { + response.Error.Code = ErrorCode.ParseError; + m_log.DebugFormat ("Avatar Image Assets Request"); + return false; + } + + OSDMap request = (OSDMap)json["params"]; + UUID avatarId = new UUID(request["avatarId"].AsString()); + + OSDArray data = (OSDArray) Service.AvatarImageAssetsRequest(avatarId); + response.Result = data; + + return true; + } + #endregion Utiltiy + + #region UserData + public bool RequestUserAppData(OSDMap json, ref JsonRpcResponse response) + { + if(!json.ContainsKey("params")) + { + response.Error.Code = ErrorCode.ParseError; + response.Error.Message = "no parameters supplied"; + m_log.DebugFormat ("User Application Service URL Request: No Parameters!"); + return false; + } + + string result = string.Empty; + UserAppData props = new UserAppData(); + object Props = (object)props; + OSD.DeserializeMembers(ref Props, (OSDMap)json["params"]); + if(Service.RequestUserAppData(ref props, ref result)) + { + OSDMap res = new OSDMap(); + res["result"] = OSD.FromString("success"); + res["token"] = OSD.FromString (result); + response.Result = res; + + return true; + } + + response.Error.Code = ErrorCode.InternalError; + response.Error.Message = string.Format("{0}", result); + return false; + } + + public bool UpdateUserAppData(OSDMap json, ref JsonRpcResponse response) + { + if(!json.ContainsKey("params")) + { + response.Error.Code = ErrorCode.ParseError; + response.Error.Message = "no parameters supplied"; + m_log.DebugFormat ("User App Data Update Request"); + return false; + } + + string result = string.Empty; + UserAppData props = new UserAppData(); + object Props = (object)props; + OSD.DeserializeMembers(ref Props, (OSDMap)json["params"]); + if(Service.SetUserAppData(props, ref result)) + { + response.Result = OSD.SerializeMembers(props); + return true; + } + + response.Error.Code = ErrorCode.InternalError; + response.Error.Message = string.Format("{0}", result); + return false; + } + #endregion UserData + } +} + diff --git a/OpenSim/Server/Handlers/Properties/AssemblyInfo.cs b/OpenSim/Server/Handlers/Properties/AssemblyInfo.cs index 53e9737..f0b36c1 100644 --- a/OpenSim/Server/Handlers/Properties/AssemblyInfo.cs +++ b/OpenSim/Server/Handlers/Properties/AssemblyInfo.cs @@ -29,5 +29,5 @@ using System.Runtime.InteropServices; // Build Number // Revision // -[assembly: AssemblyVersion("0.7.5.*")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyVersion("0.8.3.*")] + diff --git a/OpenSim/Server/Handlers/Simulation/AgentHandlers.cs b/OpenSim/Server/Handlers/Simulation/AgentHandlers.cs index 012b14e..98c5312 100644 --- a/OpenSim/Server/Handlers/Simulation/AgentHandlers.cs +++ b/OpenSim/Server/Handlers/Simulation/AgentHandlers.cs @@ -27,11 +27,14 @@ using System; using System.Collections; +using System.Collections.Generic; +using System.Collections.Specialized; using System.IO; using System.IO.Compression; using System.Reflection; using System.Net; using System.Text; +using System.Web; using OpenSim.Server.Base; using OpenSim.Server.Handlers.Base; @@ -90,14 +93,13 @@ namespace OpenSim.Server.Handlers.Simulation // Next, let's parse the verb string method = (string)request["http-method"]; - if (method.Equals("GET")) + if (method.Equals("DELETE")) { - DoAgentGet(request, responsedata, agentID, regionID); - return responsedata; - } - else if (method.Equals("DELETE")) - { - DoAgentDelete(request, responsedata, agentID, action, regionID); + string auth_token = string.Empty; + if (request.ContainsKey("auth")) + auth_token = request["auth"].ToString(); + + DoAgentDelete(request, responsedata, agentID, action, regionID, auth_token); return responsedata; } else if (method.Equals("QUERYACCESS")) @@ -107,7 +109,7 @@ namespace OpenSim.Server.Handlers.Simulation } else { - m_log.InfoFormat("[AGENT HANDLER]: method {0} not supported in agent message", method); + m_log.ErrorFormat("[AGENT HANDLER]: method {0} not supported in agent message {1} (caller is {2})", method, (string)request["uri"], Util.GetCallerIP(request)); responsedata["int_response_code"] = HttpStatusCode.MethodNotAllowed; responsedata["str_response_string"] = "Method not allowed"; @@ -116,7 +118,7 @@ namespace OpenSim.Server.Handlers.Simulation } - protected virtual void DoQueryAccess(Hashtable request, Hashtable responsedata, UUID id, UUID regionID) + protected virtual void DoQueryAccess(Hashtable request, Hashtable responsedata, UUID agentID, UUID regionID) { if (m_SimulationService == null) { @@ -131,86 +133,155 @@ namespace OpenSim.Server.Handlers.Simulation // m_log.DebugFormat("[AGENT HANDLER]: Received QUERYACCESS with {0}", (string)request["body"]); OSDMap args = Utils.GetOSDMap((string)request["body"]); + bool viaTeleport = true; + if (args.ContainsKey("viaTeleport")) + viaTeleport = args["viaTeleport"].AsBoolean(); + Vector3 position = Vector3.Zero; if (args.ContainsKey("position")) position = Vector3.Parse(args["position"].AsString()); - GridRegion destination = new GridRegion(); - destination.RegionID = regionID; + string agentHomeURI = null; + if (args.ContainsKey("agent_home_uri")) + agentHomeURI = args["agent_home_uri"].AsString(); - string reason; - string version; - bool result = m_SimulationService.QueryAccess(destination, id, position, out version, out reason); + // Decode the legacy (string) version and extract the number + float theirVersion = 0f; + if (args.ContainsKey("my_version")) + { + string theirVersionStr = args["my_version"].AsString(); + string[] parts = theirVersionStr.Split(new char[] {'/'}); + if (parts.Length > 1) + theirVersion = float.Parse(parts[1]); + } - responsedata["int_response_code"] = HttpStatusCode.OK; + // Decode the new versioning data + float minVersionRequired = 0f; + float maxVersionRequired = 0f; + float minVersionProvided = 0f; + float maxVersionProvided = 0f; - OSDMap resp = new OSDMap(3); + if (args.ContainsKey("simulation_service_supported_min")) + minVersionProvided = (float)args["simulation_service_supported_min"].AsReal(); + if (args.ContainsKey("simulation_service_supported_max")) + maxVersionProvided = (float)args["simulation_service_supported_max"].AsReal(); - resp["success"] = OSD.FromBoolean(result); - resp["reason"] = OSD.FromString(reason); - resp["version"] = OSD.FromString(version); + if (args.ContainsKey("simulation_service_accepted_min")) + minVersionRequired = (float)args["simulation_service_accepted_min"].AsReal(); + if (args.ContainsKey("simulation_service_accepted_max")) + maxVersionRequired = (float)args["simulation_service_accepted_max"].AsReal(); - // We must preserve defaults here, otherwise a false "success" will not be put into the JSON map! - responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true); + responsedata["int_response_code"] = HttpStatusCode.OK; + OSDMap resp = new OSDMap(3); -// Console.WriteLine("str_response_string [{0}]", responsedata["str_response_string"]); - } + float version = 0f; - protected virtual void DoAgentGet(Hashtable request, Hashtable responsedata, UUID id, UUID regionID) - { - if (m_SimulationService == null) + float outboundVersion = 0f; + float inboundVersion = 0f; + + if (minVersionProvided == 0f) // string version or older { - m_log.Debug("[AGENT HANDLER]: Agent GET called. Harmless but useless."); - responsedata["content_type"] = "application/json"; - responsedata["int_response_code"] = HttpStatusCode.NotImplemented; - responsedata["str_response_string"] = string.Empty; + // If there is no version in the packet at all we're looking at 0.6 or + // even more ancient. Refuse it. + if(theirVersion == 0f) + { + resp["success"] = OSD.FromBoolean(false); + resp["reason"] = OSD.FromString("Your region is running a old version of opensim no longer supported. Consider updating it"); + responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true); + return; + } - return; + version = theirVersion; + + if (version < VersionInfo.SimulationServiceVersionAcceptedMin || + version > VersionInfo.SimulationServiceVersionAcceptedMax ) + { + resp["success"] = OSD.FromBoolean(false); + resp["reason"] = OSD.FromString(String.Format("Your region protocol version is {0} and we accept only {1} - {2}. No version overlap.", theirVersion, VersionInfo.SimulationServiceVersionAcceptedMin, VersionInfo.SimulationServiceVersionAcceptedMax)); + responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true); + return; + } } - - GridRegion destination = new GridRegion(); - destination.RegionID = regionID; - - IAgentData agent = null; - bool result = m_SimulationService.RetrieveAgent(destination, id, out agent); - OSDMap map = null; - if (result) + else { - if (agent != null) // just to make sure + // Test for no overlap + if (minVersionProvided > VersionInfo.SimulationServiceVersionAcceptedMax || + maxVersionProvided < VersionInfo.SimulationServiceVersionAcceptedMin) { - map = agent.Pack(); - string strBuffer = ""; - try - { - strBuffer = OSDParser.SerializeJsonString(map); - } - catch (Exception e) - { - m_log.WarnFormat("[AGENT HANDLER]: Exception thrown on serialization of DoAgentGet: {0}", e.Message); - responsedata["int_response_code"] = HttpStatusCode.InternalServerError; - // ignore. buffer will be empty, caller should check. - } - - responsedata["content_type"] = "application/json"; - responsedata["int_response_code"] = HttpStatusCode.OK; - responsedata["str_response_string"] = strBuffer; + resp["success"] = OSD.FromBoolean(false); + resp["reason"] = OSD.FromString(String.Format("Your region provide protocol versions {0} - {1} and we accept only {2} - {3}. No version overlap.", minVersionProvided, maxVersionProvided, VersionInfo.SimulationServiceVersionAcceptedMin, VersionInfo.SimulationServiceVersionAcceptedMax)); + responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true); + return; } - else + if (minVersionRequired > VersionInfo.SimulationServiceVersionSupportedMax || + maxVersionRequired < VersionInfo.SimulationServiceVersionSupportedMin) { - responsedata["int_response_code"] = HttpStatusCode.InternalServerError; - responsedata["str_response_string"] = "Internal error"; + resp["success"] = OSD.FromBoolean(false); + resp["reason"] = OSD.FromString(String.Format("You require region protocol versions {0} - {1} and we provide only {2} - {3}. No version overlap.", minVersionRequired, maxVersionRequired, VersionInfo.SimulationServiceVersionSupportedMin, VersionInfo.SimulationServiceVersionSupportedMax)); + responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true); + return; } + + // Determine versions to use + // This is intentionally inverted. Inbound and Outbound refer to the direction of the transfer. + // Therefore outbound means from the sender to the receier and inbound means from the receiver to the sender. + // So outbound is what we will accept and inbound is what we will send. Confused yet? + outboundVersion = Math.Min(maxVersionProvided, VersionInfo.SimulationServiceVersionAcceptedMax); + inboundVersion = Math.Min(maxVersionRequired, VersionInfo.SimulationServiceVersionSupportedMax); } - else + + List features = new List(); + + if (args.ContainsKey("features")) + { + OSDArray array = (OSDArray)args["features"]; + + foreach (OSD o in array) + features.Add(new UUID(o.AsString())); + } + + GridRegion destination = new GridRegion(); + destination.RegionID = regionID; + + string reason; + // We're sending the version numbers down to the local connector to do the varregion check. + EntityTransferContext ctx = new EntityTransferContext(); + ctx.InboundVersion = inboundVersion; + ctx.OutboundVersion = outboundVersion; + if (minVersionProvided == 0f) { - responsedata["int_response_code"] = HttpStatusCode.NotFound; - responsedata["str_response_string"] = "Not Found"; + ctx.InboundVersion = version; + ctx.OutboundVersion = version; } + + bool result = m_SimulationService.QueryAccess(destination, agentID, agentHomeURI, viaTeleport, position, features, ctx, out reason); + + resp["success"] = OSD.FromBoolean(result); + resp["reason"] = OSD.FromString(reason); + string legacyVersion = String.Format("SIMULATION/{0}", version); + resp["version"] = OSD.FromString(legacyVersion); + resp["negotiated_inbound_version"] = OSD.FromReal(inboundVersion); + resp["negotiated_outbound_version"] = OSD.FromReal(outboundVersion); + resp["variable_wearables_count_supported"] = OSD.FromBoolean(true); + + OSDArray featuresWanted = new OSDArray(); + foreach (UUID feature in features) + featuresWanted.Add(OSD.FromString(feature.ToString())); + + resp["features"] = featuresWanted; + + // We must preserve defaults here, otherwise a false "success" will not be put into the JSON map! + responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true); + +// Console.WriteLine("str_response_string [{0}]", responsedata["str_response_string"]); } - protected void DoAgentDelete(Hashtable request, Hashtable responsedata, UUID id, string action, UUID regionID) + protected void DoAgentDelete(Hashtable request, Hashtable responsedata, UUID id, string action, UUID regionID, string auth_token) { - m_log.Debug(" >>> DoDelete action:" + action + "; RegionID:" + regionID); + if (string.IsNullOrEmpty(action)) + m_log.DebugFormat("[AGENT HANDLER]: >>> DELETE <<< RegionID: {0}; from: {1}; auth_code: {2}", regionID, Util.GetCallerIP(request), auth_token); + else + m_log.DebugFormat("[AGENT HANDLER]: Release {0} to RegionID: {1}", id, regionID); GridRegion destination = new GridRegion(); destination.RegionID = regionID; @@ -218,12 +289,13 @@ namespace OpenSim.Server.Handlers.Simulation if (action.Equals("release")) ReleaseAgent(regionID, id); else - m_SimulationService.CloseAgent(destination, id); + Util.FireAndForget( + o => m_SimulationService.CloseAgent(destination, id, auth_token), null, "AgentHandler.DoAgentDelete"); responsedata["int_response_code"] = HttpStatusCode.OK; responsedata["str_response_string"] = "OpenSim agent " + id.ToString(); - m_log.DebugFormat("[AGENT HANDLER]: Agent {0} Released/Deleted from region {1}", id, regionID); + //m_log.DebugFormat("[AGENT HANDLER]: Agent {0} Released/Deleted from region {1}", id, regionID); } protected virtual void ReleaseAgent(UUID regionID, UUID id) @@ -251,7 +323,7 @@ namespace OpenSim.Server.Handlers.Simulation m_SimulationService = null; } - public override byte[] Handle(string path, Stream request, + protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // m_log.DebugFormat("[SIMULATION]: Stream handler called"); @@ -280,21 +352,36 @@ namespace OpenSim.Server.Handlers.Simulation httpResponse.KeepAlive = false; Encoding encoding = Encoding.UTF8; - Stream inputStream = null; - if (httpRequest.ContentType == "application/x-gzip") - inputStream = new GZipStream(request, CompressionMode.Decompress); - else if (httpRequest.ContentType == "application/json") - inputStream = request; - else // no go + if (httpRequest.ContentType != "application/json") { httpResponse.StatusCode = 406; return encoding.GetBytes("false"); } - StreamReader reader = new StreamReader(inputStream, encoding); + string requestBody; + + Stream inputStream = request; + Stream innerStream = null; + try + { + if ((httpRequest.ContentType == "application/x-gzip" || httpRequest.Headers["Content-Encoding"] == "gzip") || (httpRequest.Headers["X-Content-Encoding"] == "gzip")) + { + innerStream = inputStream; + inputStream = new GZipStream(innerStream, CompressionMode.Decompress); + } + + using (StreamReader reader = new StreamReader(inputStream, encoding)) + { + requestBody = reader.ReadToEnd(); + } + } + finally + { + if (innerStream != null) + innerStream.Dispose(); + inputStream.Dispose(); + } - string requestBody = reader.ReadToEnd(); - reader.Close(); keysvals.Add("body", requestBody); Hashtable responsedata = new Hashtable(); @@ -328,31 +415,16 @@ namespace OpenSim.Server.Handlers.Simulation return; } - // retrieve the input arguments - int x = 0, y = 0; - UUID uuid = UUID.Zero; - string regionname = string.Empty; - uint teleportFlags = 0; - if (args.ContainsKey("destination_x") && args["destination_x"] != null) - Int32.TryParse(args["destination_x"].AsString(), out x); - else - m_log.WarnFormat(" -- request didn't have destination_x"); - if (args.ContainsKey("destination_y") && args["destination_y"] != null) - Int32.TryParse(args["destination_y"].AsString(), out y); - else - m_log.WarnFormat(" -- request didn't have destination_y"); - if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null) - UUID.TryParse(args["destination_uuid"].AsString(), out uuid); - if (args.ContainsKey("destination_name") && args["destination_name"] != null) - regionname = args["destination_name"].ToString(); - if (args.ContainsKey("teleport_flags") && args["teleport_flags"] != null) - teleportFlags = args["teleport_flags"].AsUInteger(); + AgentDestinationData data = CreateAgentDestinationData(); + UnpackData(args, data, request); GridRegion destination = new GridRegion(); - destination.RegionID = uuid; - destination.RegionLocX = x; - destination.RegionLocY = y; - destination.RegionName = regionname; + destination.RegionID = data.uuid; + destination.RegionLocX = data.x; + destination.RegionLocY = data.y; + destination.RegionName = data.name; + + GridRegion gatekeeper = ExtractGatekeeper(data); AgentCircuitData aCircuit = new AgentCircuitData(); try @@ -367,13 +439,29 @@ namespace OpenSim.Server.Handlers.Simulation return; } + GridRegion source = null; + + if (args.ContainsKey("source_uuid")) + { + source = new GridRegion(); + source.RegionLocX = Int32.Parse(args["source_x"].AsString()); + source.RegionLocY = Int32.Parse(args["source_y"].AsString()); + source.RegionName = args["source_name"].AsString(); + source.RegionID = UUID.Parse(args["source_uuid"].AsString()); + + if (args.ContainsKey("source_server_uri")) + source.RawServerURI = args["source_server_uri"].AsString(); + else + source.RawServerURI = null; + } + OSDMap resp = new OSDMap(2); string reason = String.Empty; // This is the meaning of POST agent //m_regionClient.AdjustUserInformation(aCircuit); //bool result = m_SimulationService.CreateAgent(destination, aCircuit, teleportFlags, out reason); - bool result = CreateAgent(destination, aCircuit, teleportFlags, out reason); + bool result = CreateAgent(source, gatekeeper, destination, aCircuit, data.flags, data.fromLogin, out reason); resp["reason"] = OSD.FromString(reason); resp["success"] = OSD.FromBoolean(result); @@ -385,7 +473,36 @@ namespace OpenSim.Server.Handlers.Simulation responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp); } - private string GetCallerIP(Hashtable request) + protected virtual AgentDestinationData CreateAgentDestinationData() + { + return new AgentDestinationData(); + } + + protected virtual void UnpackData(OSDMap args, AgentDestinationData data, Hashtable request) + { + // retrieve the input arguments + if (args.ContainsKey("destination_x") && args["destination_x"] != null) + Int32.TryParse(args["destination_x"].AsString(), out data.x); + else + m_log.WarnFormat(" -- request didn't have destination_x"); + if (args.ContainsKey("destination_y") && args["destination_y"] != null) + Int32.TryParse(args["destination_y"].AsString(), out data.y); + else + m_log.WarnFormat(" -- request didn't have destination_y"); + if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null) + UUID.TryParse(args["destination_uuid"].AsString(), out data.uuid); + if (args.ContainsKey("destination_name") && args["destination_name"] != null) + data.name = args["destination_name"].ToString(); + if (args.ContainsKey("teleport_flags") && args["teleport_flags"] != null) + data.flags = args["teleport_flags"].AsUInteger(); + } + + protected virtual GridRegion ExtractGatekeeper(AgentDestinationData data) + { + return null; + } + + protected string GetCallerIP(Hashtable request) { if (!m_Proxy) return Util.GetCallerIP(request); @@ -418,9 +535,10 @@ namespace OpenSim.Server.Handlers.Simulation } // subclasses can override this - protected virtual bool CreateAgent(GridRegion destination, AgentCircuitData aCircuit, uint teleportFlags, out string reason) + protected virtual bool CreateAgent(GridRegion source, GridRegion gatekeeper, GridRegion destination, + AgentCircuitData aCircuit, uint teleportFlags, bool fromLogin, out string reason) { - return m_SimulationService.CreateAgent(destination, aCircuit, teleportFlags, out reason); + return m_SimulationService.CreateAgent(source, destination, aCircuit, teleportFlags, out reason); } } @@ -443,7 +561,7 @@ namespace OpenSim.Server.Handlers.Simulation m_SimulationService = null; } - public override byte[] Handle(string path, Stream request, + protected override byte[] ProcessRequest(string path, Stream request, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // m_log.DebugFormat("[SIMULATION]: Stream handler called"); @@ -467,17 +585,31 @@ namespace OpenSim.Server.Handlers.Simulation keysvals.Add("headers", headervals); keysvals.Add("querystringkeys", querystringkeys); - Stream inputStream; - if (httpRequest.ContentType == "application/x-gzip") - inputStream = new GZipStream(request, CompressionMode.Decompress); - else - inputStream = request; - + String requestBody; Encoding encoding = Encoding.UTF8; - StreamReader reader = new StreamReader(inputStream, encoding); - string requestBody = reader.ReadToEnd(); - reader.Close(); + Stream inputStream = request; + Stream innerStream = null; + try + { + if ((httpRequest.ContentType == "application/x-gzip" || httpRequest.Headers["Content-Encoding"] == "gzip") || (httpRequest.Headers["X-Content-Encoding"] == "gzip")) + { + innerStream = inputStream; + inputStream = new GZipStream(innerStream, CompressionMode.Decompress); + } + + using (StreamReader reader = new StreamReader(inputStream, encoding)) + { + requestBody = reader.ReadToEnd(); + } + } + finally + { + if (innerStream != null) + innerStream.Dispose(); + inputStream.Dispose(); + } + keysvals.Add("body", requestBody); httpResponse.StatusCode = 200; @@ -562,7 +694,6 @@ namespace OpenSim.Server.Handlers.Simulation //agent.Dump(); // This is one of the meanings of PUT agent result = UpdateAgent(destination, agent); - } else if ("AgentPosition".Equals(messageType)) { @@ -593,4 +724,14 @@ namespace OpenSim.Server.Handlers.Simulation return m_SimulationService.UpdateAgent(destination, agent); } } + + public class AgentDestinationData + { + public int x; + public int y; + public string name; + public UUID uuid; + public uint flags; + public bool fromLogin; + } } diff --git a/OpenSim/Server/Handlers/UserAccounts/UserAccountServerConnector.cs b/OpenSim/Server/Handlers/UserAccounts/UserAccountServerConnector.cs index 344b513..e95e3dc 100644 --- a/OpenSim/Server/Handlers/UserAccounts/UserAccountServerConnector.cs +++ b/OpenSim/Server/Handlers/UserAccounts/UserAccountServerConnector.cs @@ -30,6 +30,7 @@ using Nini.Config; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenSim.Framework.Servers.HttpServer; +using OpenSim.Framework.ServiceAuth; using OpenSim.Server.Handlers.Base; namespace OpenSim.Server.Handlers.UserAccounts @@ -55,7 +56,9 @@ namespace OpenSim.Server.Handlers.UserAccounts Object[] args = new Object[] { config }; m_UserAccountService = ServerUtils.LoadPlugin(service, args); - server.AddStreamHandler(new UserAccountServerPostHandler(m_UserAccountService, serverConfig)); + IServiceAuth auth = ServiceAuth.Create(config, m_ConfigName); + + server.AddStreamHandler(new UserAccountServerPostHandler(m_UserAccountService, serverConfig, auth)); } } } diff --git a/OpenSim/Server/Handlers/UserAccounts/UserAccountServerPostHandler.cs b/OpenSim/Server/Handlers/UserAccounts/UserAccountServerPostHandler.cs index 72551ef..21eb790 100644 --- a/OpenSim/Server/Handlers/UserAccounts/UserAccountServerPostHandler.cs +++ b/OpenSim/Server/Handlers/UserAccounts/UserAccountServerPostHandler.cs @@ -41,6 +41,7 @@ using OpenSim.Services.Interfaces; using OpenSim.Services.UserAccountService; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; +using OpenSim.Framework.ServiceAuth; using OpenMetaverse; namespace OpenSim.Server.Handlers.UserAccounts @@ -54,10 +55,10 @@ namespace OpenSim.Server.Handlers.UserAccounts private bool m_AllowSetAccount = false; public UserAccountServerPostHandler(IUserAccountService service) - : this(service, null) {} + : this(service, null, null) {} - public UserAccountServerPostHandler(IUserAccountService service, IConfig config) : - base("POST", "/accounts") + public UserAccountServerPostHandler(IUserAccountService service, IConfig config, IServiceAuth auth) : + base("POST", "/accounts", auth) { m_UserAccountService = service; @@ -68,7 +69,7 @@ namespace OpenSim.Server.Handlers.UserAccounts } } - public override byte[] Handle(string path, Stream requestData, + protected override byte[] ProcessRequest(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { StreamReader sr = new StreamReader(requestData); @@ -256,8 +257,7 @@ namespace OpenSim.Server.Handlers.UserAccounts byte[] CreateUser(Dictionary request) { - if (! - request.ContainsKey("FirstName") + if (! request.ContainsKey("FirstName") && request.ContainsKey("LastName") && request.ContainsKey("Password")) return FailureResult(); @@ -314,7 +314,7 @@ namespace OpenSim.Server.Handlers.UserAccounts rootElement.AppendChild(result); - return DocToBytes(doc); + return Util.DocToBytes(doc); } private byte[] FailureResult() @@ -336,18 +336,7 @@ namespace OpenSim.Server.Handlers.UserAccounts rootElement.AppendChild(result); - return DocToBytes(doc); - } - - private byte[] DocToBytes(XmlDocument doc) - { - MemoryStream ms = new MemoryStream(); - XmlTextWriter xw = new XmlTextWriter(ms, null); - xw.Formatting = Formatting.Indented; - doc.WriteTo(xw); - xw.Flush(); - - return ms.ToArray(); + return Util.DocToBytes(doc); } private byte[] ResultToBytes(Dictionary result) -- cgit v1.1