AgentHandlers.cs 34 KB

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