1
0

AgentHandlers.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  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.IO;
  30. using System.IO.Compression;
  31. using System.Reflection;
  32. using System.Net;
  33. using System.Text;
  34. using OpenSim.Server.Base;
  35. using OpenSim.Server.Handlers.Base;
  36. using OpenSim.Services.Interfaces;
  37. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  38. using OpenSim.Framework;
  39. using OpenSim.Framework.Servers.HttpServer;
  40. using OpenMetaverse;
  41. using OpenMetaverse.StructuredData;
  42. using Nini.Config;
  43. using log4net;
  44. namespace OpenSim.Server.Handlers.Simulation
  45. {
  46. public class AgentHandler
  47. {
  48. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  49. private ISimulationService m_SimulationService;
  50. public AgentHandler() { }
  51. public AgentHandler(ISimulationService sim)
  52. {
  53. m_SimulationService = sim;
  54. }
  55. public Hashtable Handler(Hashtable request)
  56. {
  57. // m_log.Debug("[CONNECTION DEBUGGING]: AgentHandler Called");
  58. //
  59. // m_log.Debug("---------------------------");
  60. // m_log.Debug(" >> uri=" + request["uri"]);
  61. // m_log.Debug(" >> content-type=" + request["content-type"]);
  62. // m_log.Debug(" >> http-method=" + request["http-method"]);
  63. // m_log.Debug("---------------------------\n");
  64. Hashtable responsedata = new Hashtable();
  65. responsedata["content_type"] = "text/html";
  66. responsedata["keepalive"] = false;
  67. UUID agentID;
  68. UUID regionID;
  69. string action;
  70. if (!Utils.GetParams((string)request["uri"], out agentID, out regionID, out action))
  71. {
  72. m_log.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", request["uri"]);
  73. responsedata["int_response_code"] = 404;
  74. responsedata["str_response_string"] = "false";
  75. return responsedata;
  76. }
  77. // Next, let's parse the verb
  78. string method = (string)request["http-method"];
  79. if (method.Equals("GET"))
  80. {
  81. DoAgentGet(request, responsedata, agentID, regionID);
  82. return responsedata;
  83. }
  84. else if (method.Equals("DELETE"))
  85. {
  86. DoAgentDelete(request, responsedata, agentID, action, regionID);
  87. return responsedata;
  88. }
  89. else if (method.Equals("QUERYACCESS"))
  90. {
  91. DoQueryAccess(request, responsedata, agentID, regionID);
  92. return responsedata;
  93. }
  94. else
  95. {
  96. m_log.InfoFormat("[AGENT HANDLER]: method {0} not supported in agent message", method);
  97. responsedata["int_response_code"] = HttpStatusCode.MethodNotAllowed;
  98. responsedata["str_response_string"] = "Method not allowed";
  99. return responsedata;
  100. }
  101. }
  102. protected virtual void DoQueryAccess(Hashtable request, Hashtable responsedata, UUID id, UUID regionID)
  103. {
  104. if (m_SimulationService == null)
  105. {
  106. m_log.Debug("[AGENT HANDLER]: Agent QUERY called. Harmless but useless.");
  107. responsedata["content_type"] = "application/json";
  108. responsedata["int_response_code"] = HttpStatusCode.NotImplemented;
  109. responsedata["str_response_string"] = string.Empty;
  110. return;
  111. }
  112. // m_log.DebugFormat("[AGENT HANDLER]: Received QUERYACCESS with {0}", (string)request["body"]);
  113. OSDMap args = Utils.GetOSDMap((string)request["body"]);
  114. Vector3 position = Vector3.Zero;
  115. if (args.ContainsKey("position"))
  116. position = Vector3.Parse(args["position"].AsString());
  117. GridRegion destination = new GridRegion();
  118. destination.RegionID = regionID;
  119. string reason;
  120. string version;
  121. bool result = m_SimulationService.QueryAccess(destination, id, position, out version, out reason);
  122. responsedata["int_response_code"] = HttpStatusCode.OK;
  123. OSDMap resp = new OSDMap(3);
  124. resp["success"] = OSD.FromBoolean(result);
  125. resp["reason"] = OSD.FromString(reason);
  126. resp["version"] = OSD.FromString(version);
  127. // We must preserve defaults here, otherwise a false "success" will not be put into the JSON map!
  128. responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true);
  129. // Console.WriteLine("str_response_string [{0}]", responsedata["str_response_string"]);
  130. }
  131. protected virtual void DoAgentGet(Hashtable request, Hashtable responsedata, UUID id, UUID regionID)
  132. {
  133. if (m_SimulationService == null)
  134. {
  135. m_log.Debug("[AGENT HANDLER]: Agent GET called. Harmless but useless.");
  136. responsedata["content_type"] = "application/json";
  137. responsedata["int_response_code"] = HttpStatusCode.NotImplemented;
  138. responsedata["str_response_string"] = string.Empty;
  139. return;
  140. }
  141. GridRegion destination = new GridRegion();
  142. destination.RegionID = regionID;
  143. IAgentData agent = null;
  144. bool result = m_SimulationService.RetrieveAgent(destination, id, out agent);
  145. OSDMap map = null;
  146. if (result)
  147. {
  148. if (agent != null) // just to make sure
  149. {
  150. map = agent.Pack();
  151. string strBuffer = "";
  152. try
  153. {
  154. strBuffer = OSDParser.SerializeJsonString(map);
  155. }
  156. catch (Exception e)
  157. {
  158. m_log.WarnFormat("[AGENT HANDLER]: Exception thrown on serialization of DoAgentGet: {0}", e.Message);
  159. responsedata["int_response_code"] = HttpStatusCode.InternalServerError;
  160. // ignore. buffer will be empty, caller should check.
  161. }
  162. responsedata["content_type"] = "application/json";
  163. responsedata["int_response_code"] = HttpStatusCode.OK;
  164. responsedata["str_response_string"] = strBuffer;
  165. }
  166. else
  167. {
  168. responsedata["int_response_code"] = HttpStatusCode.InternalServerError;
  169. responsedata["str_response_string"] = "Internal error";
  170. }
  171. }
  172. else
  173. {
  174. responsedata["int_response_code"] = HttpStatusCode.NotFound;
  175. responsedata["str_response_string"] = "Not Found";
  176. }
  177. }
  178. protected void DoAgentDelete(Hashtable request, Hashtable responsedata, UUID id, string action, UUID regionID)
  179. {
  180. m_log.Debug(" >>> DoDelete action:" + action + "; RegionID:" + regionID);
  181. GridRegion destination = new GridRegion();
  182. destination.RegionID = regionID;
  183. if (action.Equals("release"))
  184. ReleaseAgent(regionID, id);
  185. else
  186. m_SimulationService.CloseAgent(destination, id);
  187. responsedata["int_response_code"] = HttpStatusCode.OK;
  188. responsedata["str_response_string"] = "OpenSim agent " + id.ToString();
  189. m_log.DebugFormat("[AGENT HANDLER]: Agent {0} Released/Deleted from region {1}", id, regionID);
  190. }
  191. protected virtual void ReleaseAgent(UUID regionID, UUID id)
  192. {
  193. m_SimulationService.ReleaseAgent(regionID, id, "");
  194. }
  195. }
  196. public class AgentPostHandler : BaseStreamHandler
  197. {
  198. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  199. private ISimulationService m_SimulationService;
  200. protected bool m_Proxy = false;
  201. public AgentPostHandler(ISimulationService service) :
  202. base("POST", "/agent")
  203. {
  204. m_SimulationService = service;
  205. }
  206. public AgentPostHandler(string path) :
  207. base("POST", path)
  208. {
  209. m_SimulationService = null;
  210. }
  211. public override byte[] Handle(string path, Stream request,
  212. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  213. {
  214. // m_log.DebugFormat("[SIMULATION]: Stream handler called");
  215. Hashtable keysvals = new Hashtable();
  216. Hashtable headervals = new Hashtable();
  217. string[] querystringkeys = httpRequest.QueryString.AllKeys;
  218. string[] rHeaders = httpRequest.Headers.AllKeys;
  219. keysvals.Add("uri", httpRequest.RawUrl);
  220. keysvals.Add("content-type", httpRequest.ContentType);
  221. keysvals.Add("http-method", httpRequest.HttpMethod);
  222. foreach (string queryname in querystringkeys)
  223. keysvals.Add(queryname, httpRequest.QueryString[queryname]);
  224. foreach (string headername in rHeaders)
  225. headervals[headername] = httpRequest.Headers[headername];
  226. keysvals.Add("headers", headervals);
  227. keysvals.Add("querystringkeys", querystringkeys);
  228. httpResponse.StatusCode = 200;
  229. httpResponse.ContentType = "text/html";
  230. httpResponse.KeepAlive = false;
  231. Encoding encoding = Encoding.UTF8;
  232. Stream inputStream = null;
  233. if (httpRequest.ContentType == "application/x-gzip")
  234. inputStream = new GZipStream(request, CompressionMode.Decompress);
  235. else if (httpRequest.ContentType == "application/json")
  236. inputStream = request;
  237. else // no go
  238. {
  239. httpResponse.StatusCode = 406;
  240. return encoding.GetBytes("false");
  241. }
  242. StreamReader reader = new StreamReader(inputStream, encoding);
  243. string requestBody = reader.ReadToEnd();
  244. reader.Close();
  245. keysvals.Add("body", requestBody);
  246. Hashtable responsedata = new Hashtable();
  247. UUID agentID;
  248. UUID regionID;
  249. string action;
  250. if (!Utils.GetParams((string)keysvals["uri"], out agentID, out regionID, out action))
  251. {
  252. m_log.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", keysvals["uri"]);
  253. httpResponse.StatusCode = 404;
  254. return encoding.GetBytes("false");
  255. }
  256. DoAgentPost(keysvals, responsedata, agentID);
  257. httpResponse.StatusCode = (int)responsedata["int_response_code"];
  258. return encoding.GetBytes((string)responsedata["str_response_string"]);
  259. }
  260. protected void DoAgentPost(Hashtable request, Hashtable responsedata, UUID id)
  261. {
  262. OSDMap args = Utils.GetOSDMap((string)request["body"]);
  263. if (args == null)
  264. {
  265. responsedata["int_response_code"] = HttpStatusCode.BadRequest;
  266. responsedata["str_response_string"] = "Bad request";
  267. return;
  268. }
  269. // retrieve the input arguments
  270. int x = 0, y = 0;
  271. UUID uuid = UUID.Zero;
  272. string regionname = string.Empty;
  273. uint teleportFlags = 0;
  274. if (args.ContainsKey("destination_x") && args["destination_x"] != null)
  275. Int32.TryParse(args["destination_x"].AsString(), out x);
  276. else
  277. m_log.WarnFormat(" -- request didn't have destination_x");
  278. if (args.ContainsKey("destination_y") && args["destination_y"] != null)
  279. Int32.TryParse(args["destination_y"].AsString(), out y);
  280. else
  281. m_log.WarnFormat(" -- request didn't have destination_y");
  282. if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null)
  283. UUID.TryParse(args["destination_uuid"].AsString(), out uuid);
  284. if (args.ContainsKey("destination_name") && args["destination_name"] != null)
  285. regionname = args["destination_name"].ToString();
  286. if (args.ContainsKey("teleport_flags") && args["teleport_flags"] != null)
  287. teleportFlags = args["teleport_flags"].AsUInteger();
  288. GridRegion destination = new GridRegion();
  289. destination.RegionID = uuid;
  290. destination.RegionLocX = x;
  291. destination.RegionLocY = y;
  292. destination.RegionName = regionname;
  293. AgentCircuitData aCircuit = new AgentCircuitData();
  294. try
  295. {
  296. aCircuit.UnpackAgentCircuitData(args);
  297. }
  298. catch (Exception ex)
  299. {
  300. m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildCreate message {0}", ex.Message);
  301. responsedata["int_response_code"] = HttpStatusCode.BadRequest;
  302. responsedata["str_response_string"] = "Bad request";
  303. return;
  304. }
  305. OSDMap resp = new OSDMap(2);
  306. string reason = String.Empty;
  307. // This is the meaning of POST agent
  308. //m_regionClient.AdjustUserInformation(aCircuit);
  309. //bool result = m_SimulationService.CreateAgent(destination, aCircuit, teleportFlags, out reason);
  310. bool result = CreateAgent(destination, aCircuit, teleportFlags, out reason);
  311. resp["reason"] = OSD.FromString(reason);
  312. resp["success"] = OSD.FromBoolean(result);
  313. // Let's also send out the IP address of the caller back to the caller (HG 1.5)
  314. resp["your_ip"] = OSD.FromString(GetCallerIP(request));
  315. // TODO: add reason if not String.Empty?
  316. responsedata["int_response_code"] = HttpStatusCode.OK;
  317. responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp);
  318. }
  319. private string GetCallerIP(Hashtable request)
  320. {
  321. if (!m_Proxy)
  322. return Util.GetCallerIP(request);
  323. // We're behind a proxy
  324. Hashtable headers = (Hashtable)request["headers"];
  325. //// DEBUG
  326. //foreach (object o in headers.Keys)
  327. // m_log.DebugFormat("XXX {0} = {1}", o.ToString(), (headers[o] == null? "null" : headers[o].ToString()));
  328. string xff = "X-Forwarded-For";
  329. if (headers.ContainsKey(xff.ToLower()))
  330. xff = xff.ToLower();
  331. if (!headers.ContainsKey(xff) || headers[xff] == null)
  332. {
  333. m_log.WarnFormat("[AGENT HANDLER]: No XFF header");
  334. return Util.GetCallerIP(request);
  335. }
  336. m_log.DebugFormat("[AGENT HANDLER]: XFF is {0}", headers[xff]);
  337. IPEndPoint ep = Util.GetClientIPFromXFF((string)headers[xff]);
  338. if (ep != null)
  339. return ep.Address.ToString();
  340. // Oops
  341. return Util.GetCallerIP(request);
  342. }
  343. // subclasses can override this
  344. protected virtual bool CreateAgent(GridRegion destination, AgentCircuitData aCircuit, uint teleportFlags, out string reason)
  345. {
  346. return m_SimulationService.CreateAgent(destination, aCircuit, teleportFlags, out reason);
  347. }
  348. }
  349. public class AgentPutHandler : BaseStreamHandler
  350. {
  351. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  352. private ISimulationService m_SimulationService;
  353. protected bool m_Proxy = false;
  354. public AgentPutHandler(ISimulationService service) :
  355. base("PUT", "/agent")
  356. {
  357. m_SimulationService = service;
  358. }
  359. public AgentPutHandler(string path) :
  360. base("PUT", path)
  361. {
  362. m_SimulationService = null;
  363. }
  364. public override byte[] Handle(string path, Stream request,
  365. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  366. {
  367. // m_log.DebugFormat("[SIMULATION]: Stream handler called");
  368. Hashtable keysvals = new Hashtable();
  369. Hashtable headervals = new Hashtable();
  370. string[] querystringkeys = httpRequest.QueryString.AllKeys;
  371. string[] rHeaders = httpRequest.Headers.AllKeys;
  372. keysvals.Add("uri", httpRequest.RawUrl);
  373. keysvals.Add("content-type", httpRequest.ContentType);
  374. keysvals.Add("http-method", httpRequest.HttpMethod);
  375. foreach (string queryname in querystringkeys)
  376. keysvals.Add(queryname, httpRequest.QueryString[queryname]);
  377. foreach (string headername in rHeaders)
  378. headervals[headername] = httpRequest.Headers[headername];
  379. keysvals.Add("headers", headervals);
  380. keysvals.Add("querystringkeys", querystringkeys);
  381. Stream inputStream;
  382. if (httpRequest.ContentType == "application/x-gzip")
  383. inputStream = new GZipStream(request, CompressionMode.Decompress);
  384. else
  385. inputStream = request;
  386. Encoding encoding = Encoding.UTF8;
  387. StreamReader reader = new StreamReader(inputStream, encoding);
  388. string requestBody = reader.ReadToEnd();
  389. reader.Close();
  390. keysvals.Add("body", requestBody);
  391. httpResponse.StatusCode = 200;
  392. httpResponse.ContentType = "text/html";
  393. httpResponse.KeepAlive = false;
  394. Hashtable responsedata = new Hashtable();
  395. UUID agentID;
  396. UUID regionID;
  397. string action;
  398. if (!Utils.GetParams((string)keysvals["uri"], out agentID, out regionID, out action))
  399. {
  400. m_log.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", keysvals["uri"]);
  401. httpResponse.StatusCode = 404;
  402. return encoding.GetBytes("false");
  403. }
  404. DoAgentPut(keysvals, responsedata);
  405. httpResponse.StatusCode = (int)responsedata["int_response_code"];
  406. return encoding.GetBytes((string)responsedata["str_response_string"]);
  407. }
  408. protected void DoAgentPut(Hashtable request, Hashtable responsedata)
  409. {
  410. OSDMap args = Utils.GetOSDMap((string)request["body"]);
  411. if (args == null)
  412. {
  413. responsedata["int_response_code"] = HttpStatusCode.BadRequest;
  414. responsedata["str_response_string"] = "Bad request";
  415. return;
  416. }
  417. // retrieve the input arguments
  418. int x = 0, y = 0;
  419. UUID uuid = UUID.Zero;
  420. string regionname = string.Empty;
  421. if (args.ContainsKey("destination_x") && args["destination_x"] != null)
  422. Int32.TryParse(args["destination_x"].AsString(), out x);
  423. if (args.ContainsKey("destination_y") && args["destination_y"] != null)
  424. Int32.TryParse(args["destination_y"].AsString(), out y);
  425. if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null)
  426. UUID.TryParse(args["destination_uuid"].AsString(), out uuid);
  427. if (args.ContainsKey("destination_name") && args["destination_name"] != null)
  428. regionname = args["destination_name"].ToString();
  429. GridRegion destination = new GridRegion();
  430. destination.RegionID = uuid;
  431. destination.RegionLocX = x;
  432. destination.RegionLocY = y;
  433. destination.RegionName = regionname;
  434. string messageType;
  435. if (args["message_type"] != null)
  436. messageType = args["message_type"].AsString();
  437. else
  438. {
  439. m_log.Warn("[AGENT HANDLER]: Agent Put Message Type not found. ");
  440. messageType = "AgentData";
  441. }
  442. bool result = true;
  443. if ("AgentData".Equals(messageType))
  444. {
  445. AgentData agent = new AgentData();
  446. try
  447. {
  448. agent.Unpack(args, m_SimulationService.GetScene(destination.RegionID));
  449. }
  450. catch (Exception ex)
  451. {
  452. m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildAgentUpdate message {0}", ex.Message);
  453. responsedata["int_response_code"] = HttpStatusCode.BadRequest;
  454. responsedata["str_response_string"] = "Bad request";
  455. return;
  456. }
  457. //agent.Dump();
  458. // This is one of the meanings of PUT agent
  459. result = UpdateAgent(destination, agent);
  460. }
  461. else if ("AgentPosition".Equals(messageType))
  462. {
  463. AgentPosition agent = new AgentPosition();
  464. try
  465. {
  466. agent.Unpack(args, m_SimulationService.GetScene(destination.RegionID));
  467. }
  468. catch (Exception ex)
  469. {
  470. m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildAgentUpdate message {0}", ex.Message);
  471. return;
  472. }
  473. //agent.Dump();
  474. // This is one of the meanings of PUT agent
  475. result = m_SimulationService.UpdateAgent(destination, agent);
  476. }
  477. responsedata["int_response_code"] = HttpStatusCode.OK;
  478. responsedata["str_response_string"] = result.ToString();
  479. //responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp); ??? instead
  480. }
  481. // subclasses can override this
  482. protected virtual bool UpdateAgent(GridRegion destination, AgentData agent)
  483. {
  484. return m_SimulationService.UpdateAgent(destination, agent);
  485. }
  486. }
  487. }