MapAddServerConnector.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.IO;
  30. using System.Reflection;
  31. using System.Xml;
  32. using Nini.Config;
  33. using log4net;
  34. using OpenMetaverse;
  35. using OpenSim.Framework;
  36. using OpenSim.Server.Base;
  37. using OpenSim.Services.Interfaces;
  38. using OpenSim.Framework.ServiceAuth;
  39. using OpenSim.Framework.Servers.HttpServer;
  40. using OpenSim.Server.Handlers.Base;
  41. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  42. namespace OpenSim.Server.Handlers.MapImage
  43. {
  44. public class MapAddServiceConnector : ServiceConnector
  45. {
  46. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  47. private IMapImageService m_MapService;
  48. private IGridService m_GridService;
  49. private string m_ConfigName = "MapImageService";
  50. public MapAddServiceConnector(IConfigSource config, IHttpServer server, string configName) :
  51. base(config, server, configName)
  52. {
  53. IConfig serverConfig = config.Configs[m_ConfigName];
  54. if (serverConfig == null)
  55. throw new Exception(String.Format("No section {0} in config file", m_ConfigName));
  56. string mapService = serverConfig.GetString("LocalServiceModule",
  57. String.Empty);
  58. if (mapService == String.Empty)
  59. throw new Exception("No LocalServiceModule in config file");
  60. Object[] args = new Object[] { config };
  61. m_MapService = ServerUtils.LoadPlugin<IMapImageService>(mapService, args);
  62. string gridService = serverConfig.GetString("GridService", String.Empty);
  63. if (gridService != string.Empty)
  64. m_GridService = ServerUtils.LoadPlugin<IGridService>(gridService, args);
  65. if (m_GridService != null)
  66. m_log.InfoFormat("[MAP IMAGE HANDLER]: GridService check is ON");
  67. else
  68. m_log.InfoFormat("[MAP IMAGE HANDLER]: GridService check is OFF");
  69. bool proxy = serverConfig.GetBoolean("HasProxy", false);
  70. IServiceAuth auth = ServiceAuth.Create(config, m_ConfigName);
  71. server.AddStreamHandler(new MapServerPostHandler(m_MapService, m_GridService, proxy, auth));
  72. }
  73. }
  74. class MapServerPostHandler : BaseStreamHandler
  75. {
  76. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  77. private IMapImageService m_MapService;
  78. private IGridService m_GridService;
  79. bool m_Proxy;
  80. public MapServerPostHandler(IMapImageService service, IGridService grid, bool proxy, IServiceAuth auth) :
  81. base("POST", "/map", auth)
  82. {
  83. m_MapService = service;
  84. m_GridService = grid;
  85. m_Proxy = proxy;
  86. }
  87. protected override byte[] ProcessRequest(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  88. {
  89. // m_log.DebugFormat("[MAP SERVICE IMAGE HANDLER]: Received {0}", path);
  90. StreamReader sr = new StreamReader(requestData);
  91. string body = sr.ReadToEnd();
  92. sr.Close();
  93. body = body.Trim();
  94. try
  95. {
  96. Dictionary<string, object> request = ServerUtils.ParseQueryString(body);
  97. if (!request.ContainsKey("X") || !request.ContainsKey("Y") || !request.ContainsKey("DATA"))
  98. {
  99. httpResponse.StatusCode = (int)OSHttpStatusCode.ClientErrorBadRequest;
  100. return FailureResult("Bad request.");
  101. }
  102. uint x = 0, y = 0;
  103. UInt32.TryParse(request["X"].ToString(), out x);
  104. UInt32.TryParse(request["Y"].ToString(), out y);
  105. m_log.DebugFormat("[MAP ADD SERVER CONNECTOR]: Received map data for region at {0}-{1}", x, y);
  106. // string type = "image/jpeg";
  107. //
  108. // if (request.ContainsKey("TYPE"))
  109. // type = request["TYPE"].ToString();
  110. if (m_GridService != null)
  111. {
  112. System.Net.IPAddress ipAddr = GetCallerIP(httpRequest);
  113. GridRegion r = m_GridService.GetRegionByPosition(UUID.Zero, (int)Util.RegionToWorldLoc(x), (int)Util.RegionToWorldLoc(y));
  114. if (r != null)
  115. {
  116. if (r.ExternalEndPoint.Address.ToString() != ipAddr.ToString())
  117. {
  118. m_log.WarnFormat("[MAP IMAGE HANDLER]: IP address {0} may be trying to impersonate region in IP {1}", ipAddr, r.ExternalEndPoint.Address);
  119. return FailureResult("IP address of caller does not match IP address of registered region");
  120. }
  121. }
  122. else
  123. {
  124. m_log.WarnFormat("[MAP IMAGE HANDLER]: IP address {0} may be rogue. Region not found at coordinates {1}-{2}",
  125. ipAddr, x, y);
  126. return FailureResult("Region not found at given coordinates");
  127. }
  128. }
  129. byte[] data = Convert.FromBase64String(request["DATA"].ToString());
  130. string reason = string.Empty;
  131. bool result = m_MapService.AddMapTile((int)x, (int)y, data, out reason);
  132. if (result)
  133. return SuccessResult();
  134. else
  135. return FailureResult(reason);
  136. }
  137. catch (Exception e)
  138. {
  139. m_log.ErrorFormat("[MAP SERVICE IMAGE HANDLER]: Exception {0} {1}", e.Message, e.StackTrace);
  140. }
  141. return FailureResult("Unexpected server error");
  142. }
  143. private byte[] SuccessResult()
  144. {
  145. XmlDocument doc = new XmlDocument();
  146. XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
  147. "", "");
  148. doc.AppendChild(xmlnode);
  149. XmlElement rootElement = doc.CreateElement("", "ServerResponse",
  150. "");
  151. doc.AppendChild(rootElement);
  152. XmlElement result = doc.CreateElement("", "Result", "");
  153. result.AppendChild(doc.CreateTextNode("Success"));
  154. rootElement.AppendChild(result);
  155. return Util.DocToBytes(doc);
  156. }
  157. private byte[] FailureResult(string msg)
  158. {
  159. XmlDocument doc = new XmlDocument();
  160. XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
  161. "", "");
  162. doc.AppendChild(xmlnode);
  163. XmlElement rootElement = doc.CreateElement("", "ServerResponse",
  164. "");
  165. doc.AppendChild(rootElement);
  166. XmlElement result = doc.CreateElement("", "Result", "");
  167. result.AppendChild(doc.CreateTextNode("Failure"));
  168. rootElement.AppendChild(result);
  169. XmlElement message = doc.CreateElement("", "Message", "");
  170. message.AppendChild(doc.CreateTextNode(msg));
  171. rootElement.AppendChild(message);
  172. return Util.DocToBytes(doc);
  173. }
  174. private System.Net.IPAddress GetCallerIP(IOSHttpRequest request)
  175. {
  176. if (!m_Proxy)
  177. return request.RemoteIPEndPoint.Address;
  178. // We're behind a proxy
  179. string xff = "X-Forwarded-For";
  180. string xffValue = request.Headers[xff.ToLower()];
  181. if (xffValue == null || (xffValue != null && xffValue == string.Empty))
  182. xffValue = request.Headers[xff];
  183. if (xffValue == null || (xffValue != null && xffValue == string.Empty))
  184. {
  185. m_log.WarnFormat("[MAP IMAGE HANDLER]: No XFF header");
  186. return request.RemoteIPEndPoint.Address;
  187. }
  188. System.Net.IPEndPoint ep = Util.GetClientIPFromXFF(xffValue);
  189. if (ep != null)
  190. return ep.Address;
  191. // Oops
  192. return request.RemoteIPEndPoint.Address;
  193. }
  194. }
  195. }