AgentHandlers.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  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;
  29. using System.Collections.Generic;
  30. using System.Collections.Specialized;
  31. using System.IO;
  32. using System.IO.Compression;
  33. using System.Reflection;
  34. using System.Net;
  35. using System.Text;
  36. using System.Web;
  37. using OpenSim.Server.Base;
  38. using OpenSim.Server.Handlers.Base;
  39. using OpenSim.Services.Interfaces;
  40. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  41. using OpenSim.Framework;
  42. using OpenSim.Framework.Servers.HttpServer;
  43. using OpenMetaverse;
  44. using OpenMetaverse.StructuredData;
  45. using Nini.Config;
  46. using log4net;
  47. namespace OpenSim.Server.Handlers.Simulation
  48. {
  49. public class AgentHandler
  50. {
  51. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  52. private ISimulationService m_SimulationService;
  53. public AgentHandler() { }
  54. public AgentHandler(ISimulationService sim)
  55. {
  56. m_SimulationService = sim;
  57. }
  58. public Hashtable Handler(Hashtable request)
  59. {
  60. // m_log.Debug("[CONNECTION DEBUGGING]: AgentHandler Called");
  61. //
  62. // m_log.Debug("---------------------------");
  63. // m_log.Debug(" >> uri=" + request["uri"]);
  64. // m_log.Debug(" >> content-type=" + request["content-type"]);
  65. // m_log.Debug(" >> http-method=" + request["http-method"]);
  66. // m_log.Debug("---------------------------\n");
  67. Hashtable responsedata = new Hashtable();
  68. responsedata["content_type"] = "text/html";
  69. responsedata["keepalive"] = false;
  70. UUID agentID;
  71. UUID regionID;
  72. string action;
  73. if (!Utils.GetParams((string)request["uri"], out agentID, out regionID, out action))
  74. {
  75. m_log.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", request["uri"]);
  76. responsedata["int_response_code"] = 404;
  77. responsedata["str_response_string"] = "false";
  78. return responsedata;
  79. }
  80. // Next, let's parse the verb
  81. string method = (string)request["http-method"];
  82. if (method.Equals("DELETE"))
  83. {
  84. string auth_token = string.Empty;
  85. if (request.ContainsKey("auth"))
  86. auth_token = request["auth"].ToString();
  87. DoAgentDelete(request, responsedata, agentID, action, regionID, auth_token);
  88. return responsedata;
  89. }
  90. else if (method.Equals("QUERYACCESS"))
  91. {
  92. DoQueryAccess(request, responsedata, agentID, regionID);
  93. return responsedata;
  94. }
  95. else
  96. {
  97. m_log.ErrorFormat("[AGENT HANDLER]: method {0} not supported in agent message {1} (caller is {2})", method, (string)request["uri"], Util.GetCallerIP(request));
  98. responsedata["int_response_code"] = HttpStatusCode.MethodNotAllowed;
  99. responsedata["str_response_string"] = "Method not allowed";
  100. return responsedata;
  101. }
  102. }
  103. protected virtual void DoQueryAccess(Hashtable request, Hashtable responsedata, UUID agentID, UUID regionID)
  104. {
  105. Culture.SetCurrentCulture();
  106. EntityTransferContext ctx = new EntityTransferContext();
  107. if (m_SimulationService == null)
  108. {
  109. m_log.Debug("[AGENT HANDLER]: Agent QUERY called. Harmless but useless.");
  110. responsedata["content_type"] = "application/json";
  111. responsedata["int_response_code"] = HttpStatusCode.NotImplemented;
  112. responsedata["str_response_string"] = string.Empty;
  113. return;
  114. }
  115. // m_log.DebugFormat("[AGENT HANDLER]: Received QUERYACCESS with {0}", (string)request["body"]);
  116. OSDMap args = Utils.GetOSDMap((string)request["body"]);
  117. bool viaTeleport = true;
  118. if (args.ContainsKey("viaTeleport"))
  119. viaTeleport = args["viaTeleport"].AsBoolean();
  120. Vector3 position = Vector3.Zero;
  121. if (args.ContainsKey("position"))
  122. position = Vector3.Parse(args["position"].AsString());
  123. string agentHomeURI = null;
  124. if (args.ContainsKey("agent_home_uri"))
  125. agentHomeURI = args["agent_home_uri"].AsString();
  126. // Decode the legacy (string) version and extract the number
  127. float theirVersion = 0f;
  128. if (args.ContainsKey("my_version"))
  129. {
  130. string theirVersionStr = args["my_version"].AsString();
  131. string[] parts = theirVersionStr.Split(new char[] {'/'});
  132. if (parts.Length > 1)
  133. theirVersion = float.Parse(parts[1]);
  134. }
  135. if (args.ContainsKey("context"))
  136. ctx.Unpack((OSDMap)args["context"]);
  137. // Decode the new versioning data
  138. float minVersionRequired = 0f;
  139. float maxVersionRequired = 0f;
  140. float minVersionProvided = 0f;
  141. float maxVersionProvided = 0f;
  142. if (args.ContainsKey("simulation_service_supported_min"))
  143. minVersionProvided = (float)args["simulation_service_supported_min"].AsReal();
  144. if (args.ContainsKey("simulation_service_supported_max"))
  145. maxVersionProvided = (float)args["simulation_service_supported_max"].AsReal();
  146. if (args.ContainsKey("simulation_service_accepted_min"))
  147. minVersionRequired = (float)args["simulation_service_accepted_min"].AsReal();
  148. if (args.ContainsKey("simulation_service_accepted_max"))
  149. maxVersionRequired = (float)args["simulation_service_accepted_max"].AsReal();
  150. responsedata["int_response_code"] = HttpStatusCode.OK;
  151. OSDMap resp = new OSDMap(3);
  152. float version = 0f;
  153. float outboundVersion = 0f;
  154. float inboundVersion = 0f;
  155. if (minVersionProvided == 0f) // string version or older
  156. {
  157. // If there is no version in the packet at all we're looking at 0.6 or
  158. // even more ancient. Refuse it.
  159. if(theirVersion == 0f)
  160. {
  161. resp["success"] = OSD.FromBoolean(false);
  162. resp["reason"] = OSD.FromString("Your region is running a old version of opensim no longer supported. Consider updating it");
  163. responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true);
  164. return;
  165. }
  166. version = theirVersion;
  167. if (version < VersionInfo.SimulationServiceVersionAcceptedMin ||
  168. version > VersionInfo.SimulationServiceVersionAcceptedMax )
  169. {
  170. resp["success"] = OSD.FromBoolean(false);
  171. 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));
  172. responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true);
  173. return;
  174. }
  175. }
  176. else
  177. {
  178. // Test for no overlap
  179. if (minVersionProvided > VersionInfo.SimulationServiceVersionAcceptedMax ||
  180. maxVersionProvided < VersionInfo.SimulationServiceVersionAcceptedMin)
  181. {
  182. resp["success"] = OSD.FromBoolean(false);
  183. 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));
  184. responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true);
  185. return;
  186. }
  187. if (minVersionRequired > VersionInfo.SimulationServiceVersionSupportedMax ||
  188. maxVersionRequired < VersionInfo.SimulationServiceVersionSupportedMin)
  189. {
  190. resp["success"] = OSD.FromBoolean(false);
  191. 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));
  192. responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true);
  193. return;
  194. }
  195. // Determine versions to use
  196. // This is intentionally inverted. Inbound and Outbound refer to the direction of the transfer.
  197. // Therefore outbound means from the sender to the receier and inbound means from the receiver to the sender.
  198. // So outbound is what we will accept and inbound is what we will send. Confused yet?
  199. outboundVersion = Math.Min(maxVersionProvided, VersionInfo.SimulationServiceVersionAcceptedMax);
  200. inboundVersion = Math.Min(maxVersionRequired, VersionInfo.SimulationServiceVersionSupportedMax);
  201. }
  202. List<UUID> features = new List<UUID>();
  203. if (args.ContainsKey("features"))
  204. {
  205. OSDArray array = (OSDArray)args["features"];
  206. foreach (OSD o in array)
  207. features.Add(new UUID(o.AsString()));
  208. }
  209. GridRegion destination = new GridRegion();
  210. destination.RegionID = regionID;
  211. string reason;
  212. // We're sending the version numbers down to the local connector to do the varregion check.
  213. ctx.InboundVersion = inboundVersion;
  214. ctx.OutboundVersion = outboundVersion;
  215. if (minVersionProvided == 0f)
  216. {
  217. ctx.InboundVersion = version;
  218. ctx.OutboundVersion = version;
  219. }
  220. bool result = m_SimulationService.QueryAccess(destination, agentID, agentHomeURI, viaTeleport, position, features, ctx, out reason);
  221. m_log.DebugFormat("[AGENT HANDLER]: QueryAccess returned {0} ({1}). Version={2}, {3}/{4}",
  222. result, reason, version, inboundVersion, outboundVersion);
  223. resp["success"] = OSD.FromBoolean(result);
  224. resp["reason"] = OSD.FromString(reason);
  225. string legacyVersion = String.Format("SIMULATION/{0}", version);
  226. resp["version"] = OSD.FromString(legacyVersion);
  227. resp["negotiated_inbound_version"] = OSD.FromReal(inboundVersion);
  228. resp["negotiated_outbound_version"] = OSD.FromReal(outboundVersion);
  229. OSDArray featuresWanted = new OSDArray();
  230. foreach (UUID feature in features)
  231. featuresWanted.Add(OSD.FromString(feature.ToString()));
  232. resp["features"] = featuresWanted;
  233. // We must preserve defaults here, otherwise a false "success" will not be put into the JSON map!
  234. responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true);
  235. // Console.WriteLine("str_response_string [{0}]", responsedata["str_response_string"]);
  236. }
  237. protected void DoAgentDelete(Hashtable request, Hashtable responsedata, UUID id, string action, UUID regionID, string auth_token)
  238. {
  239. if (string.IsNullOrEmpty(action))
  240. m_log.DebugFormat("[AGENT HANDLER]: >>> DELETE <<< RegionID: {0}; from: {1}; auth_code: {2}", regionID, Util.GetCallerIP(request), auth_token);
  241. else
  242. m_log.DebugFormat("[AGENT HANDLER]: Release {0} to RegionID: {1}", id, regionID);
  243. GridRegion destination = new GridRegion();
  244. destination.RegionID = regionID;
  245. if (action.Equals("release"))
  246. ReleaseAgent(regionID, id);
  247. else
  248. Util.FireAndForget(
  249. o => m_SimulationService.CloseAgent(destination, id, auth_token), null, "AgentHandler.DoAgentDelete");
  250. responsedata["int_response_code"] = HttpStatusCode.OK;
  251. responsedata["str_response_string"] = "OpenSim agent " + id.ToString();
  252. //m_log.DebugFormat("[AGENT HANDLER]: Agent {0} Released/Deleted from region {1}", id, regionID);
  253. }
  254. protected virtual void ReleaseAgent(UUID regionID, UUID id)
  255. {
  256. m_SimulationService.ReleaseAgent(regionID, id, "");
  257. }
  258. }
  259. public class AgentPostHandler : BaseStreamHandler
  260. {
  261. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  262. private ISimulationService m_SimulationService;
  263. protected bool m_Proxy = false;
  264. public AgentPostHandler(ISimulationService service) :
  265. base("POST", "/agent")
  266. {
  267. m_SimulationService = service;
  268. }
  269. public AgentPostHandler(string path) :
  270. base("POST", path)
  271. {
  272. m_SimulationService = null;
  273. }
  274. protected override byte[] ProcessRequest(string path, Stream request,
  275. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  276. {
  277. // m_log.DebugFormat("[SIMULATION]: Stream handler called");
  278. Hashtable keysvals = new Hashtable();
  279. Hashtable headervals = new Hashtable();
  280. string[] querystringkeys = httpRequest.QueryString.AllKeys;
  281. string[] rHeaders = httpRequest.Headers.AllKeys;
  282. keysvals.Add("uri", httpRequest.RawUrl);
  283. keysvals.Add("content-type", httpRequest.ContentType);
  284. keysvals.Add("http-method", httpRequest.HttpMethod);
  285. foreach (string queryname in querystringkeys)
  286. keysvals.Add(queryname, httpRequest.QueryString[queryname]);
  287. foreach (string headername in rHeaders)
  288. headervals[headername] = httpRequest.Headers[headername];
  289. keysvals.Add("headers", headervals);
  290. keysvals.Add("querystringkeys", querystringkeys);
  291. httpResponse.StatusCode = 200;
  292. httpResponse.ContentType = "text/html";
  293. httpResponse.KeepAlive = false;
  294. Encoding encoding = Encoding.UTF8;
  295. if (httpRequest.ContentType != "application/json")
  296. {
  297. httpResponse.StatusCode = 406;
  298. return encoding.GetBytes("false");
  299. }
  300. string requestBody;
  301. Stream inputStream = request;
  302. Stream innerStream = null;
  303. try
  304. {
  305. if ((httpRequest.ContentType == "application/x-gzip" || httpRequest.Headers["Content-Encoding"] == "gzip") || (httpRequest.Headers["X-Content-Encoding"] == "gzip"))
  306. {
  307. innerStream = inputStream;
  308. inputStream = new GZipStream(innerStream, CompressionMode.Decompress);
  309. }
  310. using (StreamReader reader = new StreamReader(inputStream, encoding))
  311. {
  312. requestBody = reader.ReadToEnd();
  313. }
  314. }
  315. finally
  316. {
  317. if (innerStream != null)
  318. innerStream.Dispose();
  319. inputStream.Dispose();
  320. }
  321. keysvals.Add("body", requestBody);
  322. Hashtable responsedata = new Hashtable();
  323. UUID agentID;
  324. UUID regionID;
  325. string action;
  326. if (!Utils.GetParams((string)keysvals["uri"], out agentID, out regionID, out action))
  327. {
  328. m_log.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", keysvals["uri"]);
  329. httpResponse.StatusCode = 404;
  330. return encoding.GetBytes("false");
  331. }
  332. DoAgentPost(keysvals, responsedata, agentID);
  333. httpResponse.StatusCode = (int)responsedata["int_response_code"];
  334. return encoding.GetBytes((string)responsedata["str_response_string"]);
  335. }
  336. protected void DoAgentPost(Hashtable request, Hashtable responsedata, UUID id)
  337. {
  338. EntityTransferContext ctx = new EntityTransferContext();
  339. OSDMap args = Utils.GetOSDMap((string)request["body"]);
  340. if (args == null)
  341. {
  342. responsedata["int_response_code"] = HttpStatusCode.BadRequest;
  343. responsedata["str_response_string"] = "Bad request";
  344. return;
  345. }
  346. if (args.ContainsKey("context"))
  347. ctx.Unpack((OSDMap)args["context"]);
  348. AgentDestinationData data = CreateAgentDestinationData();
  349. UnpackData(args, data, request);
  350. GridRegion destination = new GridRegion();
  351. destination.RegionID = data.uuid;
  352. destination.RegionLocX = data.x;
  353. destination.RegionLocY = data.y;
  354. destination.RegionName = data.name;
  355. GridRegion gatekeeper = ExtractGatekeeper(data);
  356. AgentCircuitData aCircuit = new AgentCircuitData();
  357. try
  358. {
  359. aCircuit.UnpackAgentCircuitData(args);
  360. }
  361. catch (Exception ex)
  362. {
  363. m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildCreate message {0}", ex.Message);
  364. responsedata["int_response_code"] = HttpStatusCode.BadRequest;
  365. responsedata["str_response_string"] = "Bad request";
  366. return;
  367. }
  368. GridRegion source = null;
  369. if (args.ContainsKey("source_uuid"))
  370. {
  371. source = new GridRegion();
  372. source.RegionLocX = Int32.Parse(args["source_x"].AsString());
  373. source.RegionLocY = Int32.Parse(args["source_y"].AsString());
  374. source.RegionName = args["source_name"].AsString();
  375. source.RegionID = UUID.Parse(args["source_uuid"].AsString());
  376. if (args.ContainsKey("source_server_uri"))
  377. source.RawServerURI = args["source_server_uri"].AsString();
  378. else
  379. source.RawServerURI = null;
  380. }
  381. OSDMap resp = new OSDMap(2);
  382. string reason = String.Empty;
  383. // This is the meaning of POST agent
  384. //m_regionClient.AdjustUserInformation(aCircuit);
  385. //bool result = m_SimulationService.CreateAgent(destination, aCircuit, teleportFlags, out reason);
  386. bool result = CreateAgent(source, gatekeeper, destination, aCircuit, data.flags, data.fromLogin, ctx, out reason);
  387. resp["reason"] = OSD.FromString(reason);
  388. resp["success"] = OSD.FromBoolean(result);
  389. // Let's also send out the IP address of the caller back to the caller (HG 1.5)
  390. resp["your_ip"] = OSD.FromString(GetCallerIP(request));
  391. // TODO: add reason if not String.Empty?
  392. responsedata["int_response_code"] = HttpStatusCode.OK;
  393. responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp);
  394. }
  395. protected virtual AgentDestinationData CreateAgentDestinationData()
  396. {
  397. return new AgentDestinationData();
  398. }
  399. protected virtual void UnpackData(OSDMap args, AgentDestinationData data, Hashtable request)
  400. {
  401. // retrieve the input arguments
  402. if (args.ContainsKey("destination_x") && args["destination_x"] != null)
  403. Int32.TryParse(args["destination_x"].AsString(), out data.x);
  404. else
  405. m_log.WarnFormat(" -- request didn't have destination_x");
  406. if (args.ContainsKey("destination_y") && args["destination_y"] != null)
  407. Int32.TryParse(args["destination_y"].AsString(), out data.y);
  408. else
  409. m_log.WarnFormat(" -- request didn't have destination_y");
  410. if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null)
  411. UUID.TryParse(args["destination_uuid"].AsString(), out data.uuid);
  412. if (args.ContainsKey("destination_name") && args["destination_name"] != null)
  413. data.name = args["destination_name"].ToString();
  414. if (args.ContainsKey("teleport_flags") && args["teleport_flags"] != null)
  415. data.flags = args["teleport_flags"].AsUInteger();
  416. }
  417. protected virtual GridRegion ExtractGatekeeper(AgentDestinationData data)
  418. {
  419. return null;
  420. }
  421. protected string GetCallerIP(Hashtable request)
  422. {
  423. if (request.ContainsKey("headers"))
  424. {
  425. Hashtable headers = (Hashtable)request["headers"];
  426. //// DEBUG
  427. //foreach (object o in headers.Keys)
  428. // m_log.DebugFormat("XXX {0} = {1}", o.ToString(), (headers[o] == null? "null" : headers[o].ToString()));
  429. string xff = "X-Forwarded-For";
  430. if (!headers.ContainsKey(xff))
  431. xff = xff.ToLower();
  432. if (!headers.ContainsKey(xff) || headers[xff] == null)
  433. {
  434. // m_log.WarnFormat("[AGENT HANDLER]: No XFF header");
  435. return Util.GetCallerIP(request);
  436. }
  437. // m_log.DebugFormat("[AGENT HANDLER]: XFF is {0}", headers[xff]);
  438. IPEndPoint ep = Util.GetClientIPFromXFF((string)headers[xff]);
  439. if (ep != null)
  440. return ep.Address.ToString();
  441. }
  442. // Oops
  443. return Util.GetCallerIP(request);
  444. }
  445. // subclasses can override this
  446. protected virtual bool CreateAgent(GridRegion source, GridRegion gatekeeper, GridRegion destination,
  447. AgentCircuitData aCircuit, uint teleportFlags, bool fromLogin, EntityTransferContext ctx, out string reason)
  448. {
  449. reason = String.Empty;
  450. // The data and protocols are already defined so this is just a dummy to satisfy the interface
  451. // TODO: make this end-to-end
  452. /* this needs to be sync
  453. if ((teleportFlags & (uint)TeleportFlags.ViaLogin) == 0)
  454. {
  455. Util.FireAndForget(x =>
  456. {
  457. string r;
  458. m_SimulationService.CreateAgent(source, destination, aCircuit, teleportFlags, ctx, out r);
  459. m_log.DebugFormat("[AGENT HANDLER]: ASYNC CreateAgent {0}", r);
  460. });
  461. return true;
  462. }
  463. else
  464. {
  465. */
  466. bool ret = m_SimulationService.CreateAgent(source, destination, aCircuit, teleportFlags, ctx, out reason);
  467. // m_log.DebugFormat("[AGENT HANDLER]: SYNC CreateAgent {0} {1}", ret.ToString(), reason);
  468. return ret;
  469. // }
  470. }
  471. }
  472. public class AgentPutHandler : BaseStreamHandler
  473. {
  474. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  475. private ISimulationService m_SimulationService;
  476. protected bool m_Proxy = false;
  477. public AgentPutHandler(ISimulationService service) :
  478. base("PUT", "/agent")
  479. {
  480. m_SimulationService = service;
  481. }
  482. public AgentPutHandler(string path) :
  483. base("PUT", path)
  484. {
  485. m_SimulationService = null;
  486. }
  487. protected override byte[] ProcessRequest(string path, Stream request,
  488. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  489. {
  490. // m_log.DebugFormat("[SIMULATION]: Stream handler called");
  491. Hashtable keysvals = new Hashtable();
  492. Hashtable headervals = new Hashtable();
  493. string[] querystringkeys = httpRequest.QueryString.AllKeys;
  494. string[] rHeaders = httpRequest.Headers.AllKeys;
  495. keysvals.Add("uri", httpRequest.RawUrl);
  496. keysvals.Add("content-type", httpRequest.ContentType);
  497. keysvals.Add("http-method", httpRequest.HttpMethod);
  498. foreach (string queryname in querystringkeys)
  499. keysvals.Add(queryname, httpRequest.QueryString[queryname]);
  500. foreach (string headername in rHeaders)
  501. headervals[headername] = httpRequest.Headers[headername];
  502. keysvals.Add("headers", headervals);
  503. keysvals.Add("querystringkeys", querystringkeys);
  504. String requestBody;
  505. Encoding encoding = Encoding.UTF8;
  506. Stream inputStream = request;
  507. Stream innerStream = null;
  508. try
  509. {
  510. if ((httpRequest.ContentType == "application/x-gzip" || httpRequest.Headers["Content-Encoding"] == "gzip") || (httpRequest.Headers["X-Content-Encoding"] == "gzip"))
  511. {
  512. innerStream = inputStream;
  513. inputStream = new GZipStream(innerStream, CompressionMode.Decompress);
  514. }
  515. using (StreamReader reader = new StreamReader(inputStream, encoding))
  516. {
  517. requestBody = reader.ReadToEnd();
  518. }
  519. }
  520. finally
  521. {
  522. if (innerStream != null)
  523. innerStream.Dispose();
  524. inputStream.Dispose();
  525. }
  526. keysvals.Add("body", requestBody);
  527. httpResponse.StatusCode = 200;
  528. httpResponse.ContentType = "text/html";
  529. httpResponse.KeepAlive = false;
  530. Hashtable responsedata = new Hashtable();
  531. UUID agentID;
  532. UUID regionID;
  533. string action;
  534. if (!Utils.GetParams((string)keysvals["uri"], out agentID, out regionID, out action))
  535. {
  536. m_log.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", keysvals["uri"]);
  537. httpResponse.StatusCode = 404;
  538. return encoding.GetBytes("false");
  539. }
  540. DoAgentPut(keysvals, responsedata);
  541. httpResponse.StatusCode = (int)responsedata["int_response_code"];
  542. return encoding.GetBytes((string)responsedata["str_response_string"]);
  543. }
  544. protected void DoAgentPut(Hashtable request, Hashtable responsedata)
  545. {
  546. // TODO: Encode the ENtityTransferContext
  547. EntityTransferContext ctx = new EntityTransferContext();
  548. OSDMap args = Utils.GetOSDMap((string)request["body"]);
  549. if (args == null)
  550. {
  551. responsedata["int_response_code"] = HttpStatusCode.BadRequest;
  552. responsedata["str_response_string"] = "Bad request";
  553. return;
  554. }
  555. // retrieve the input arguments
  556. int x = 0, y = 0;
  557. UUID uuid = UUID.Zero;
  558. string regionname = string.Empty;
  559. if (args.ContainsKey("destination_x") && args["destination_x"] != null)
  560. Int32.TryParse(args["destination_x"].AsString(), out x);
  561. if (args.ContainsKey("destination_y") && args["destination_y"] != null)
  562. Int32.TryParse(args["destination_y"].AsString(), out y);
  563. if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null)
  564. UUID.TryParse(args["destination_uuid"].AsString(), out uuid);
  565. if (args.ContainsKey("destination_name") && args["destination_name"] != null)
  566. regionname = args["destination_name"].ToString();
  567. if (args.ContainsKey("context"))
  568. ctx.Unpack((OSDMap)args["context"]);
  569. GridRegion destination = new GridRegion();
  570. destination.RegionID = uuid;
  571. destination.RegionLocX = x;
  572. destination.RegionLocY = y;
  573. destination.RegionName = regionname;
  574. string messageType;
  575. if (args["message_type"] != null)
  576. messageType = args["message_type"].AsString();
  577. else
  578. {
  579. m_log.Warn("[AGENT HANDLER]: Agent Put Message Type not found. ");
  580. messageType = "AgentData";
  581. }
  582. bool result = true;
  583. if ("AgentData".Equals(messageType))
  584. {
  585. AgentData agent = new AgentData();
  586. try
  587. {
  588. agent.Unpack(args, m_SimulationService.GetScene(destination.RegionID), ctx);
  589. }
  590. catch (Exception ex)
  591. {
  592. m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildAgentUpdate message {0}", ex.Message);
  593. responsedata["int_response_code"] = HttpStatusCode.BadRequest;
  594. responsedata["str_response_string"] = "Bad request";
  595. return;
  596. }
  597. //agent.Dump();
  598. // This is one of the meanings of PUT agent
  599. result = UpdateAgent(destination, agent);
  600. }
  601. else if ("AgentPosition".Equals(messageType))
  602. {
  603. AgentPosition agent = new AgentPosition();
  604. try
  605. {
  606. agent.Unpack(args, m_SimulationService.GetScene(destination.RegionID), ctx);
  607. }
  608. catch (Exception ex)
  609. {
  610. m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildAgentUpdate message {0}", ex.Message);
  611. return;
  612. }
  613. //agent.Dump();
  614. // This is one of the meanings of PUT agent
  615. result = m_SimulationService.UpdateAgent(destination, agent);
  616. }
  617. responsedata["int_response_code"] = HttpStatusCode.OK;
  618. responsedata["str_response_string"] = result.ToString();
  619. //responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp); ??? instead
  620. }
  621. // subclasses can override this
  622. protected virtual bool UpdateAgent(GridRegion destination, AgentData agent)
  623. {
  624. // The data and protocols are already defined so this is just a dummy to satisfy the interface
  625. // TODO: make this end-to-end
  626. EntityTransferContext ctx = new EntityTransferContext();
  627. return m_SimulationService.UpdateAgent(destination, agent, ctx);
  628. }
  629. }
  630. public class AgentDestinationData
  631. {
  632. public int x;
  633. public int y;
  634. public string name;
  635. public UUID uuid;
  636. public uint flags;
  637. public bool fromLogin;
  638. }
  639. }