From 28f99ce3b5f4c663123fc0bf1dd892f0ba210a84 Mon Sep 17 00:00:00 2001 From: UbitUmarov Date: Sun, 3 Apr 2022 16:01:27 +0100 Subject: [PATCH] a few mostly cosmetics to map connectors and handlers. the .../map url will also remove map if data field is not present, ../removemap is just pollution in urls space, if fact both remove map are useless, since they are api for regions and regions can not do it, keeping just because.. --- .../Handlers/Map/MapAddServerConnector.cs | 58 +++-- .../Handlers/Map/MapRemoveServerConnector.cs | 154 +++--------- .../MapImage/MapImageServicesConnector.cs | 230 +++++++----------- 3 files changed, 158 insertions(+), 284 deletions(-) diff --git a/OpenSim/Server/Handlers/Map/MapAddServerConnector.cs b/OpenSim/Server/Handlers/Map/MapAddServerConnector.cs index 26d86bbe07..fa40c66371 100644 --- a/OpenSim/Server/Handlers/Map/MapAddServerConnector.cs +++ b/OpenSim/Server/Handlers/Map/MapAddServerConnector.cs @@ -102,32 +102,44 @@ namespace OpenSim.Server.Handlers.MapImage protected override void ProcessRequest(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { //m_log.DebugFormat("[MAP SERVICE IMAGE HANDLER]: Received {0}", path); - string body; - using(StreamReader sr = new StreamReader(httpRequest.InputStream)) - body = sr.ReadToEnd(); - body = body.Trim(); - httpRequest.InputStream.Dispose(); + int x = 0, y = 0; + UUID scopeID = UUID.Zero; + byte[] data = null; + + httpResponse.StatusCode = (int)HttpStatusCode.OK; try { + string body; + using (StreamReader sr = new StreamReader(httpRequest.InputStream)) + body = sr.ReadToEnd(); + body = body.Trim(); + Dictionary request = ServerUtils.ParseQueryString(body); - httpResponse.StatusCode = (int)HttpStatusCode.OK; - if (!request.ContainsKey("X") || !request.ContainsKey("Y") || !request.ContainsKey("DATA")) + x = Int32.Parse(request["X"].ToString()); + y = Int32.Parse(request["Y"].ToString()); + if (request.TryGetValue("SCOPE", out object o)) + UUID.TryParse(o.ToString(), out scopeID); + if(request.TryGetValue("DATA", out object od)) { - httpResponse.RawBuffer = Util.ResultFailureMessage("Bad request."); - return; + data = Convert.FromBase64String(od.ToString()); + if (data.Length < 10) + { + httpResponse.RawBuffer = Util.ResultFailureMessage("Bad request."); + return; + } } + } + catch + { + httpResponse.RawBuffer = Util.ResultFailureMessage("Bad request."); + return; + } - int x = 0, y = 0; - //UUID scopeID = new UUID("07f8d88e-cd5e-4239-a0ed-843f75d09992"); - UUID scopeID = UUID.Zero; - Int32.TryParse(request["X"].ToString(), out x); - Int32.TryParse(request["Y"].ToString(), out y); - if (request.ContainsKey("SCOPE")) - UUID.TryParse(request["SCOPE"].ToString(), out scopeID); - + try + { m_log.DebugFormat("[MAP ADD SERVER CONNECTOR]: Received map data for region at {0}-{1}", x, y); //string type = "image/jpeg"; @@ -156,13 +168,13 @@ namespace OpenSim.Server.Handlers.MapImage } } - byte[] data = Convert.FromBase64String(request["DATA"].ToString()); - - bool result = m_MapService.AddMapTile(x, y, data, scopeID, out string reason); - if (result) - httpResponse.RawBuffer = Util.sucessResultSuccess; + bool result; + string reason; + if (data == null) + result = m_MapService.RemoveMapTile(x, y, scopeID, out reason); else - httpResponse.RawBuffer = Util.ResultFailureMessage(reason); + result = m_MapService.AddMapTile(x, y, data, scopeID, out reason); + httpResponse.RawBuffer = result ? Util.sucessResultSuccess : Util.ResultFailureMessage(reason); return; } catch (Exception e) diff --git a/OpenSim/Server/Handlers/Map/MapRemoveServerConnector.cs b/OpenSim/Server/Handlers/Map/MapRemoveServerConnector.cs index d894171928..75360078f5 100644 --- a/OpenSim/Server/Handlers/Map/MapRemoveServerConnector.cs +++ b/OpenSim/Server/Handlers/Map/MapRemoveServerConnector.cs @@ -30,7 +30,6 @@ using System.Collections.Generic; using System.IO; using System.Reflection; using System.Net; -using System.Xml; using Nini.Config; using log4net; @@ -39,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; @@ -61,17 +61,16 @@ namespace OpenSim.Server.Handlers.MapImage if (serverConfig == null) throw new Exception(String.Format("No section {0} in config file", m_ConfigName)); - string mapService = serverConfig.GetString("LocalServiceModule", - String.Empty); + string mapService = serverConfig.GetString("LocalServiceModule", string.Empty); - if (mapService == String.Empty) + if (string.IsNullOrWhiteSpace(mapService)) throw new Exception("No LocalServiceModule in config file"); - Object[] args = new Object[] { config }; + object[] args = new object[] { config }; m_MapService = ServerUtils.LoadPlugin(mapService, args); string gridService = serverConfig.GetString("GridService", String.Empty); - if (gridService != string.Empty) + if (!string.IsNullOrWhiteSpace(gridService)) m_GridService = ServerUtils.LoadPlugin(gridService, args); if (m_GridService != null) @@ -79,44 +78,45 @@ namespace OpenSim.Server.Handlers.MapImage else m_log.InfoFormat("[MAP IMAGE HANDLER]: GridService check is OFF"); - bool proxy = serverConfig.GetBoolean("HasProxy", false); - server.AddStreamHandler(new MapServerRemoveHandler(m_MapService, m_GridService, proxy)); - + IServiceAuth auth = ServiceAuth.Create(config, m_ConfigName); + server.AddSimpleStreamHandler(new MapServerRemoveHandler(m_MapService, m_GridService, auth)); } } - class MapServerRemoveHandler : BaseStreamHandler + class MapServerRemoveHandler : SimpleStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - private IMapImageService m_MapService; - private IGridService m_GridService; - bool m_Proxy; + private readonly IMapImageService m_MapService; + private readonly IGridService m_GridService; - public MapServerRemoveHandler(IMapImageService service, IGridService grid, bool proxy) : - base("POST", "/removemap") + public MapServerRemoveHandler(IMapImageService service, IGridService grid, IServiceAuth auth) : + base("/removemap", auth) { m_MapService = service; m_GridService = grid; - m_Proxy = proxy; } - public override byte[] Handle(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) + protected override void ProcessRequest(IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { -// m_log.DebugFormat("[MAP SERVICE IMAGE HANDLER]: Received {0}", path); - string body; - using(StreamReader sr = new StreamReader(requestData)) - body = sr.ReadToEnd(); - body = body.Trim(); - + //m_log.DebugFormat("[MAP SERVICE IMAGE HANDLER]: Received {0}", path); try { + string body; + using (StreamReader sr = new StreamReader(httpRequest.InputStream)) + body = sr.ReadToEnd(); + body = body.Trim(); + + httpRequest.InputStream.Dispose(); Dictionary request = ServerUtils.ParseQueryString(body); if (!request.ContainsKey("X") || !request.ContainsKey("Y")) { httpResponse.StatusCode = (int)HttpStatusCode.BadRequest; - return FailureResult("Bad request."); + httpResponse.RawBuffer = Util.ResultFailureMessage("Bad request."); + return; } + + httpResponse.StatusCode = (int)HttpStatusCode.OK; int x = 0, y = 0; Int32.TryParse(request["X"].ToString(), out x); Int32.TryParse(request["Y"].ToString(), out y); @@ -129,22 +129,23 @@ namespace OpenSim.Server.Handlers.MapImage if (m_GridService != null) { - System.Net.IPAddress ipAddr = GetCallerIP(httpRequest); + System.Net.IPAddress ipAddr = httpRequest.RemoteIPEndPoint.Address; GridRegion r = m_GridService.GetRegionByPosition(UUID.Zero, (int)Util.RegionToWorldLoc((uint)x), (int)Util.RegionToWorldLoc((uint)y)); if (r != null) { if (r.ExternalEndPoint.Address.ToString() != ipAddr.ToString()) { m_log.WarnFormat("[MAP IMAGE HANDLER]: IP address {0} may be trying to impersonate region in IP {1}", ipAddr, r.ExternalEndPoint.Address); - return FailureResult("IP address of caller does not match IP address of registered region"); + httpResponse.RawBuffer = Util.ResultFailureMessage("IP address of caller does not match IP address of registered region"); + return; } - } else { m_log.WarnFormat("[MAP IMAGE HANDLER]: IP address {0} may be rogue. Region not found at coordinates {1}-{2}", ipAddr, x, y); - return FailureResult("Region not found at given coordinates"); + httpResponse.RawBuffer = Util.ResultFailureMessage("Region not found at given coordinates"); + return; } } @@ -152,106 +153,17 @@ namespace OpenSim.Server.Handlers.MapImage bool result = m_MapService.RemoveMapTile(x, y, scopeID, out reason); if (result) - return SuccessResult(); + httpResponse.RawBuffer = Util.sucessResultSuccess; else - return FailureResult(reason); - + httpResponse.RawBuffer = Util.ResultFailureMessage(reason); + return; } catch (Exception e) { m_log.ErrorFormat("[MAP SERVICE IMAGE HANDLER]: Exception {0} {1}", e.Message, e.StackTrace); } - return FailureResult("Unexpected server error"); + httpResponse.RawBuffer = Util.ResultFailureMessage("Unexpected server error"); } - - 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 DocToBytes(doc); - } - - private byte[] FailureResult(string msg) - { - 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); - - XmlElement message = doc.CreateElement("", "Message", ""); - message.AppendChild(doc.CreateTextNode(msg)); - - rootElement.AppendChild(message); - - return DocToBytes(doc); - } - - private byte[] DocToBytes(XmlDocument doc) - { - using(MemoryStream ms = new MemoryStream()) - { - using(XmlTextWriter xw = new XmlTextWriter(ms,null)) - { - xw.Formatting = Formatting.Indented; - doc.WriteTo(xw); - xw.Flush(); - } - return ms.ToArray(); - } - } - - private System.Net.IPAddress GetCallerIP(IOSHttpRequest request) - { -// if (!m_Proxy) -// return request.RemoteIPEndPoint.Address; - - // We're behind a proxy - string xff = "X-Forwarded-For"; - string xffValue = request.Headers[xff.ToLower()]; - if (xffValue == null || (xffValue != null && xffValue == string.Empty)) - xffValue = request.Headers[xff]; - - if (xffValue == null || (xffValue != null && xffValue == string.Empty)) - { -// m_log.WarnFormat("[MAP IMAGE HANDLER]: No XFF header"); - return request.RemoteIPEndPoint.Address; - } - - System.Net.IPEndPoint ep = Util.GetClientIPFromXFF(xffValue); - if (ep != null) - return ep.Address; - - // Oops - return request.RemoteIPEndPoint.Address; - } - } } diff --git a/OpenSim/Services/Connectors/MapImage/MapImageServicesConnector.cs b/OpenSim/Services/Connectors/MapImage/MapImageServicesConnector.cs index 9652fee40d..f61679e988 100644 --- a/OpenSim/Services/Connectors/MapImage/MapImageServicesConnector.cs +++ b/OpenSim/Services/Connectors/MapImage/MapImageServicesConnector.cs @@ -88,125 +88,68 @@ namespace OpenSim.Services.Connectors base.Initialise(source, "MapImageService"); } - public bool RemoveMapTile(int x, int y, out string reason) - { - reason = string.Empty; - int tickstart = Util.EnvironmentTickCount(); - Dictionary sendData = new Dictionary(); - sendData["X"] = x.ToString(); - sendData["Y"] = y.ToString(); - - string reqString = ServerUtils.BuildQueryString(sendData); - string uri = m_ServerURI + "/removemap"; - - try - { - string reply = SynchronousRestFormsRequester.MakeRequest("POST", - uri, - reqString, - m_Auth); - if (reply != string.Empty) - { - Dictionary replyData = ServerUtils.ParseXmlResponse(reply); - - if (replyData.ContainsKey("Result") && (replyData["Result"].ToString().ToLower() == "success")) - { - return true; - } - else if (replyData.ContainsKey("Result") && (replyData["Result"].ToString().ToLower() == "failure")) - { - m_log.DebugFormat("[MAP IMAGE CONNECTOR]: Delete failed: {0}", replyData["Message"].ToString()); - reason = replyData["Message"].ToString(); - return false; - } - else if (!replyData.ContainsKey("Result")) - { - m_log.DebugFormat("[MAP IMAGE CONNECTOR]: reply data does not contain result field"); - } - else - { - m_log.DebugFormat("[MAP IMAGE CONNECTOR]: unexpected result {0}", replyData["Result"].ToString()); - reason = "Unexpected result " + replyData["Result"].ToString(); - } - - } - else - { - m_log.DebugFormat("[MAP IMAGE CONNECTOR]: Map post received null reply"); - } - } - catch (Exception e) - { - m_log.DebugFormat("[MAP IMAGE CONNECTOR]: Exception when contacting map server at {0}: {1}", uri, e.Message); - } - finally - { - // This just dumps a warning for any operation that takes more than 100 ms - int tickdiff = Util.EnvironmentTickCountSubtract(tickstart); - m_log.DebugFormat("[MAP IMAGE CONNECTOR]: map tile deleted in {0}ms", tickdiff); - } - - return false; - } - public bool RemoveMapTile(int x, int y, UUID scopeID, out string reason) { reason = string.Empty; - int tickstart = Util.EnvironmentTickCount(); - Dictionary sendData = new Dictionary(); - sendData["X"] = x.ToString(); - sendData["Y"] = y.ToString(); - sendData["SCOPE"] = scopeID.ToString(); - - string reqString = ServerUtils.BuildQueryString(sendData); - string uri = m_ServerURI + "/removemap"; + string reqString; + if (scopeID.IsNotZero()) + { + reqString = ServerUtils.BuildQueryString( + new Dictionary() + { + {"X" , x.ToString() }, + {"Y" , y.ToString() }, + { "SCOPE" , scopeID.ToString() }, + } + ); + } + else + { + reqString = ServerUtils.BuildQueryString( + new Dictionary() + { + {"X" , x.ToString() }, + {"Y" , y.ToString() }, + { "SCOPE" , scopeID.ToString() }, + } + ); + } try { - string reply = SynchronousRestFormsRequester.MakeRequest("POST", - uri, - reqString); - if (reply != string.Empty) + string reply = SynchronousRestFormsRequester.MakeRequest("POST", m_ServerURI + "/map", reqString, 10, null, false); + if (reply.Length > 0) { Dictionary replyData = ServerUtils.ParseXmlResponse(reply); - - if (replyData.ContainsKey("Result") && (replyData["Result"].ToString().ToLower() == "success")) + if(replyData.TryGetValue("Result", out object resultobj)) { - return true; - } - else if (replyData.ContainsKey("Result") && (replyData["Result"].ToString().ToLower() == "failure")) - { - m_log.DebugFormat("[MAP IMAGE CONNECTOR]: Delete failed: {0}", replyData["Message"].ToString()); - reason = replyData["Message"].ToString(); + string res = resultobj as string; + if(string.IsNullOrEmpty(res)) + { + m_log.DebugFormat("[MAP IMAGE CONNECTOR]: unknown result field"); + return false; + } + else if (res.Equals("success", StringComparison.InvariantCultureIgnoreCase)) + return true; + else if (res.Equals("failure", StringComparison.InvariantCultureIgnoreCase)) + { + reason = replyData["Message"].ToString(); + m_log.DebugFormat("[MAP IMAGE CONNECTOR]: RemoveMapTile failed: {0}", reason); + return false; + } + m_log.DebugFormat("[MAP IMAGE CONNECTOR]: RemoveMapTile unknown result field contents"); return false; } - else if (!replyData.ContainsKey("Result")) - { - m_log.DebugFormat("[MAP IMAGE CONNECTOR]: reply data does not contain result field"); - } - else - { - m_log.DebugFormat("[MAP IMAGE CONNECTOR]: unexpected result {0}", replyData["Result"].ToString()); - reason = "Unexpected result " + replyData["Result"].ToString(); - } - } else { - m_log.DebugFormat("[MAP IMAGE CONNECTOR]: Map post received null reply"); + m_log.DebugFormat("[MAP IMAGE CONNECTOR]: RemoveMapTile reply data does not contain result field"); } } catch (Exception e) { - m_log.DebugFormat("[MAP IMAGE CONNECTOR]: Exception when contacting map server at {0}: {1}", uri, e.Message); + m_log.DebugFormat("[MAP IMAGE CONNECTOR]: RemoveMapTile Exception at {0}/map: {1}", m_ServerURI, e.Message); } - finally - { - // This just dumps a warning for any operation that takes more than 100 ms - int tickdiff = Util.EnvironmentTickCountSubtract(tickstart); - m_log.DebugFormat("[MAP IMAGE CONNECTOR]: map tile deleted in {0}ms", tickdiff); - } - return false; } @@ -214,69 +157,76 @@ namespace OpenSim.Services.Connectors { reason = string.Empty; int tickstart = Util.EnvironmentTickCount(); - Dictionary sendData = new Dictionary(); - sendData["X"] = x.ToString(); - sendData["Y"] = y.ToString(); - sendData["SCOPE"] = scopeID.ToString(); - sendData["TYPE"] = "image/jpeg"; - sendData["DATA"] = Convert.ToBase64String(jpgData); - string reqString = ServerUtils.BuildQueryString(sendData); - string uri = m_ServerURI + "/map"; + string reqString; + if (scopeID.IsNotZero()) + { + reqString = ServerUtils.BuildQueryString( + new Dictionary() + { + {"X" , x.ToString() }, + {"Y" , y.ToString() }, + { "SCOPE" , scopeID.ToString() }, + { "TYPE" , "image/jpeg" }, + { "DATA" , Convert.ToBase64String(jpgData) } + } + ); + } + else + { + reqString = ServerUtils.BuildQueryString( + new Dictionary() + { + {"X" , x.ToString() }, + {"Y" , y.ToString() }, + { "TYPE" , "image/jpeg" }, + { "DATA" , Convert.ToBase64String(jpgData) } + } + ); + } try { - string reply = SynchronousRestFormsRequester.MakeRequest("POST", - uri, - reqString, - 30, - m_Auth); - if (reply != string.Empty) + string reply = SynchronousRestFormsRequester.MakeRequest("POST", m_ServerURI + "/map", reqString, 10, m_Auth, false); + if (reply.Length > 0) { Dictionary replyData = ServerUtils.ParseXmlResponse(reply); - - if (replyData.ContainsKey("Result") && (replyData["Result"].ToString().ToLower() == "success")) + if (replyData.TryGetValue("Result", out object resultobj)) { - return true; - } - else if (replyData.ContainsKey("Result") && (replyData["Result"].ToString().ToLower() == "failure")) - { - reason = string.Format("Map post to {0} failed: {1}", uri, replyData["Message"].ToString()); - m_log.WarnFormat("[MAP IMAGE CONNECTOR]: {0}", reason); - + string res = resultobj as string; + if (string.IsNullOrEmpty(res)) + { + m_log.DebugFormat("[MAP IMAGE CONNECTOR]: AddMapTile unknown result field"); + return false; + } + else if (res.Equals("success", StringComparison.InvariantCultureIgnoreCase)) + return true; + else if (res.Equals("failure", StringComparison.InvariantCultureIgnoreCase)) + { + reason = replyData["Message"].ToString(); + m_log.DebugFormat("[MAP IMAGE CONNECTOR]: AddMapTile failed: {0}", reason); + return false; + } + m_log.DebugFormat("[MAP IMAGE CONNECTOR]: AddMapTile unknown result field contents"); return false; } - else if (!replyData.ContainsKey("Result")) - { - reason = string.Format("Reply data from {0} does not contain result field", uri); - m_log.WarnFormat("[MAP IMAGE CONNECTOR]: {0}", reason); - } - else - { - reason = string.Format("Unexpected result {0} from {1}" + replyData["Result"].ToString(), uri); - m_log.WarnFormat("[MAP IMAGE CONNECTOR]: {0}", reason); - } } else { - reason = string.Format("Map post received null reply from {0}", uri); - m_log.WarnFormat("[MAP IMAGE CONNECTOR]: {0}", reason); + m_log.DebugFormat("[MAP IMAGE CONNECTOR]: AddMapTile reply data does not contain result field"); } } catch (Exception e) { - reason = string.Format("Exception when posting to map server at {0}: {1}", uri, e.Message); - m_log.WarnFormat("[MAP IMAGE CONNECTOR]: {0}", reason); + m_log.DebugFormat("[MAP IMAGE CONNECTOR]: AddMapTile Exception at {0}/map: {1}", m_ServerURI, e.Message); } finally { // This just dumps a warning for any operation that takes more than 100 ms int tickdiff = Util.EnvironmentTickCountSubtract(tickstart); - m_log.DebugFormat("[MAP IMAGE CONNECTOR]: map tile upload time {0}ms", tickdiff); + m_log.DebugFormat("[MAP IMAGE CONNECTOR]: AddMapTile time {0}ms", tickdiff); } - return false; - } public byte[] GetMapTile(string fileName, UUID scopeID, out string format)