AgentHandlers.cs 32 KB

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