AgentHandlers.cs 32 KB

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