AgentHandlers.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  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(2);
  124. resp["success"] = OSD.FromBoolean(result);
  125. resp["reason"] = OSD.FromString(reason);
  126. resp["version"] = OSD.FromString(version);
  127. responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp);
  128. }
  129. protected virtual void DoAgentGet(Hashtable request, Hashtable responsedata, UUID id, UUID regionID)
  130. {
  131. if (m_SimulationService == null)
  132. {
  133. m_log.Debug("[AGENT HANDLER]: Agent GET called. Harmless but useless.");
  134. responsedata["content_type"] = "application/json";
  135. responsedata["int_response_code"] = HttpStatusCode.NotImplemented;
  136. responsedata["str_response_string"] = string.Empty;
  137. return;
  138. }
  139. GridRegion destination = new GridRegion();
  140. destination.RegionID = regionID;
  141. IAgentData agent = null;
  142. bool result = m_SimulationService.RetrieveAgent(destination, id, out agent);
  143. OSDMap map = null;
  144. if (result)
  145. {
  146. if (agent != null) // just to make sure
  147. {
  148. map = agent.Pack();
  149. string strBuffer = "";
  150. try
  151. {
  152. strBuffer = OSDParser.SerializeJsonString(map);
  153. }
  154. catch (Exception e)
  155. {
  156. m_log.WarnFormat("[AGENT HANDLER]: Exception thrown on serialization of DoAgentGet: {0}", e.Message);
  157. responsedata["int_response_code"] = HttpStatusCode.InternalServerError;
  158. // ignore. buffer will be empty, caller should check.
  159. }
  160. responsedata["content_type"] = "application/json";
  161. responsedata["int_response_code"] = HttpStatusCode.OK;
  162. responsedata["str_response_string"] = strBuffer;
  163. }
  164. else
  165. {
  166. responsedata["int_response_code"] = HttpStatusCode.InternalServerError;
  167. responsedata["str_response_string"] = "Internal error";
  168. }
  169. }
  170. else
  171. {
  172. responsedata["int_response_code"] = HttpStatusCode.NotFound;
  173. responsedata["str_response_string"] = "Not Found";
  174. }
  175. }
  176. protected void DoAgentDelete(Hashtable request, Hashtable responsedata, UUID id, string action, UUID regionID)
  177. {
  178. m_log.Debug(" >>> DoDelete action:" + action + "; RegionID:" + regionID);
  179. GridRegion destination = new GridRegion();
  180. destination.RegionID = regionID;
  181. if (action.Equals("release"))
  182. ReleaseAgent(regionID, id);
  183. else
  184. m_SimulationService.CloseAgent(destination, id);
  185. responsedata["int_response_code"] = HttpStatusCode.OK;
  186. responsedata["str_response_string"] = "OpenSim agent " + id.ToString();
  187. m_log.Debug("[AGENT HANDLER]: Agent Released/Deleted.");
  188. }
  189. protected virtual void ReleaseAgent(UUID regionID, UUID id)
  190. {
  191. m_SimulationService.ReleaseAgent(regionID, id, "");
  192. }
  193. }
  194. public class AgentPostHandler : BaseStreamHandler
  195. {
  196. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  197. private ISimulationService m_SimulationService;
  198. protected bool m_Proxy = false;
  199. public AgentPostHandler(ISimulationService service) :
  200. base("POST", "/agent")
  201. {
  202. m_SimulationService = service;
  203. }
  204. public AgentPostHandler(string path) :
  205. base("POST", path)
  206. {
  207. m_SimulationService = null;
  208. }
  209. public override byte[] Handle(string path, Stream request,
  210. OSHttpRequest httpRequest, OSHttpResponse httpResponse)
  211. {
  212. m_log.DebugFormat("[SIMULATION]: Stream handler called");
  213. Hashtable keysvals = new Hashtable();
  214. Hashtable headervals = new Hashtable();
  215. string[] querystringkeys = httpRequest.QueryString.AllKeys;
  216. string[] rHeaders = httpRequest.Headers.AllKeys;
  217. keysvals.Add("uri", httpRequest.RawUrl);
  218. keysvals.Add("content-type", httpRequest.ContentType);
  219. keysvals.Add("http-method", httpRequest.HttpMethod);
  220. foreach (string queryname in querystringkeys)
  221. keysvals.Add(queryname, httpRequest.QueryString[queryname]);
  222. foreach (string headername in rHeaders)
  223. headervals[headername] = httpRequest.Headers[headername];
  224. keysvals.Add("headers", headervals);
  225. keysvals.Add("querystringkeys", querystringkeys);
  226. Stream inputStream;
  227. if (httpRequest.ContentType == "application/x-gzip")
  228. inputStream = new GZipStream(request, CompressionMode.Decompress);
  229. else
  230. inputStream = request;
  231. Encoding encoding = Encoding.UTF8;
  232. StreamReader reader = new StreamReader(inputStream, encoding);
  233. string requestBody = reader.ReadToEnd();
  234. reader.Close();
  235. keysvals.Add("body", requestBody);
  236. httpResponse.StatusCode = 200;
  237. httpResponse.ContentType = "text/html";
  238. httpResponse.KeepAlive = false;
  239. Hashtable responsedata = new Hashtable();
  240. UUID agentID;
  241. UUID regionID;
  242. string action;
  243. if (!Utils.GetParams((string)keysvals["uri"], out agentID, out regionID, out action))
  244. {
  245. m_log.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", keysvals["uri"]);
  246. httpResponse.StatusCode = 404;
  247. return encoding.GetBytes("false");
  248. }
  249. DoAgentPost(keysvals, responsedata, agentID);
  250. httpResponse.StatusCode = (int)responsedata["int_response_code"];
  251. return encoding.GetBytes((string)responsedata["str_response_string"]);
  252. }
  253. protected void DoAgentPost(Hashtable request, Hashtable responsedata, UUID id)
  254. {
  255. OSDMap args = Utils.GetOSDMap((string)request["body"]);
  256. if (args == null)
  257. {
  258. responsedata["int_response_code"] = HttpStatusCode.BadRequest;
  259. responsedata["str_response_string"] = "Bad request";
  260. return;
  261. }
  262. // retrieve the input arguments
  263. int x = 0, y = 0;
  264. UUID uuid = UUID.Zero;
  265. string regionname = string.Empty;
  266. uint teleportFlags = 0;
  267. if (args.ContainsKey("destination_x") && args["destination_x"] != null)
  268. Int32.TryParse(args["destination_x"].AsString(), out x);
  269. else
  270. m_log.WarnFormat(" -- request didn't have destination_x");
  271. if (args.ContainsKey("destination_y") && args["destination_y"] != null)
  272. Int32.TryParse(args["destination_y"].AsString(), out y);
  273. else
  274. m_log.WarnFormat(" -- request didn't have destination_y");
  275. if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null)
  276. UUID.TryParse(args["destination_uuid"].AsString(), out uuid);
  277. if (args.ContainsKey("destination_name") && args["destination_name"] != null)
  278. regionname = args["destination_name"].ToString();
  279. if (args.ContainsKey("teleport_flags") && args["teleport_flags"] != null)
  280. teleportFlags = args["teleport_flags"].AsUInteger();
  281. GridRegion destination = new GridRegion();
  282. destination.RegionID = uuid;
  283. destination.RegionLocX = x;
  284. destination.RegionLocY = y;
  285. destination.RegionName = regionname;
  286. AgentCircuitData aCircuit = new AgentCircuitData();
  287. try
  288. {
  289. aCircuit.UnpackAgentCircuitData(args);
  290. }
  291. catch (Exception ex)
  292. {
  293. m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildCreate message {0}", ex.Message);
  294. responsedata["int_response_code"] = HttpStatusCode.BadRequest;
  295. responsedata["str_response_string"] = "Bad request";
  296. return;
  297. }
  298. OSDMap resp = new OSDMap(2);
  299. string reason = String.Empty;
  300. // This is the meaning of POST agent
  301. //m_regionClient.AdjustUserInformation(aCircuit);
  302. //bool result = m_SimulationService.CreateAgent(destination, aCircuit, teleportFlags, out reason);
  303. bool result = CreateAgent(destination, aCircuit, teleportFlags, out reason);
  304. resp["reason"] = OSD.FromString(reason);
  305. resp["success"] = OSD.FromBoolean(result);
  306. // Let's also send out the IP address of the caller back to the caller (HG 1.5)
  307. resp["your_ip"] = OSD.FromString(GetCallerIP(request));
  308. // TODO: add reason if not String.Empty?
  309. responsedata["int_response_code"] = HttpStatusCode.OK;
  310. responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp);
  311. }
  312. private string GetCallerIP(Hashtable request)
  313. {
  314. if (!m_Proxy)
  315. return Util.GetCallerIP(request);
  316. // We're behind a proxy
  317. Hashtable headers = (Hashtable)request["headers"];
  318. //// DEBUG
  319. //foreach (object o in headers.Keys)
  320. // m_log.DebugFormat("XXX {0} = {1}", o.ToString(), (headers[o] == null? "null" : headers[o].ToString()));
  321. string xff = "X-Forwarded-For";
  322. if (headers.ContainsKey(xff.ToLower()))
  323. xff = xff.ToLower();
  324. if (!headers.ContainsKey(xff) || headers[xff] == null)
  325. {
  326. m_log.WarnFormat("[AGENT HANDLER]: No XFF header");
  327. return Util.GetCallerIP(request);
  328. }
  329. m_log.DebugFormat("[AGENT HANDLER]: XFF is {0}", headers[xff]);
  330. IPEndPoint ep = Util.GetClientIPFromXFF((string)headers[xff]);
  331. if (ep != null)
  332. return ep.Address.ToString();
  333. // Oops
  334. return Util.GetCallerIP(request);
  335. }
  336. // subclasses can override this
  337. protected virtual bool CreateAgent(GridRegion destination, AgentCircuitData aCircuit, uint teleportFlags, out string reason)
  338. {
  339. return m_SimulationService.CreateAgent(destination, aCircuit, teleportFlags, out reason);
  340. }
  341. }
  342. public class AgentPutHandler : BaseStreamHandler
  343. {
  344. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  345. private ISimulationService m_SimulationService;
  346. protected bool m_Proxy = false;
  347. public AgentPutHandler(ISimulationService service) :
  348. base("PUT", "/agent")
  349. {
  350. m_SimulationService = service;
  351. }
  352. public AgentPutHandler(string path) :
  353. base("PUT", path)
  354. {
  355. m_SimulationService = null;
  356. }
  357. public override byte[] Handle(string path, Stream request,
  358. OSHttpRequest httpRequest, OSHttpResponse httpResponse)
  359. {
  360. m_log.DebugFormat("[SIMULATION]: Stream handler called");
  361. Hashtable keysvals = new Hashtable();
  362. Hashtable headervals = new Hashtable();
  363. string[] querystringkeys = httpRequest.QueryString.AllKeys;
  364. string[] rHeaders = httpRequest.Headers.AllKeys;
  365. keysvals.Add("uri", httpRequest.RawUrl);
  366. keysvals.Add("content-type", httpRequest.ContentType);
  367. keysvals.Add("http-method", httpRequest.HttpMethod);
  368. foreach (string queryname in querystringkeys)
  369. keysvals.Add(queryname, httpRequest.QueryString[queryname]);
  370. foreach (string headername in rHeaders)
  371. headervals[headername] = httpRequest.Headers[headername];
  372. keysvals.Add("headers", headervals);
  373. keysvals.Add("querystringkeys", querystringkeys);
  374. Stream inputStream;
  375. if (httpRequest.ContentType == "application/x-gzip")
  376. inputStream = new GZipStream(request, CompressionMode.Decompress);
  377. else
  378. inputStream = request;
  379. Encoding encoding = Encoding.UTF8;
  380. StreamReader reader = new StreamReader(inputStream, encoding);
  381. string requestBody = reader.ReadToEnd();
  382. reader.Close();
  383. keysvals.Add("body", requestBody);
  384. httpResponse.StatusCode = 200;
  385. httpResponse.ContentType = "text/html";
  386. httpResponse.KeepAlive = false;
  387. Hashtable responsedata = new Hashtable();
  388. UUID agentID;
  389. UUID regionID;
  390. string action;
  391. if (!Utils.GetParams((string)keysvals["uri"], out agentID, out regionID, out action))
  392. {
  393. m_log.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", keysvals["uri"]);
  394. httpResponse.StatusCode = 404;
  395. return encoding.GetBytes("false");
  396. }
  397. DoAgentPut(keysvals, responsedata);
  398. httpResponse.StatusCode = (int)responsedata["int_response_code"];
  399. return encoding.GetBytes((string)responsedata["str_response_string"]);
  400. }
  401. protected void DoAgentPut(Hashtable request, Hashtable responsedata)
  402. {
  403. OSDMap args = Utils.GetOSDMap((string)request["body"]);
  404. if (args == null)
  405. {
  406. responsedata["int_response_code"] = HttpStatusCode.BadRequest;
  407. responsedata["str_response_string"] = "Bad request";
  408. return;
  409. }
  410. // retrieve the input arguments
  411. int x = 0, y = 0;
  412. UUID uuid = UUID.Zero;
  413. string regionname = string.Empty;
  414. if (args.ContainsKey("destination_x") && args["destination_x"] != null)
  415. Int32.TryParse(args["destination_x"].AsString(), out x);
  416. if (args.ContainsKey("destination_y") && args["destination_y"] != null)
  417. Int32.TryParse(args["destination_y"].AsString(), out y);
  418. if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null)
  419. UUID.TryParse(args["destination_uuid"].AsString(), out uuid);
  420. if (args.ContainsKey("destination_name") && args["destination_name"] != null)
  421. regionname = args["destination_name"].ToString();
  422. GridRegion destination = new GridRegion();
  423. destination.RegionID = uuid;
  424. destination.RegionLocX = x;
  425. destination.RegionLocY = y;
  426. destination.RegionName = regionname;
  427. string messageType;
  428. if (args["message_type"] != null)
  429. messageType = args["message_type"].AsString();
  430. else
  431. {
  432. m_log.Warn("[AGENT HANDLER]: Agent Put Message Type not found. ");
  433. messageType = "AgentData";
  434. }
  435. bool result = true;
  436. if ("AgentData".Equals(messageType))
  437. {
  438. AgentData agent = new AgentData();
  439. try
  440. {
  441. agent.Unpack(args, m_SimulationService.GetScene(destination.RegionHandle));
  442. }
  443. catch (Exception ex)
  444. {
  445. m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildAgentUpdate message {0}", ex.Message);
  446. responsedata["int_response_code"] = HttpStatusCode.BadRequest;
  447. responsedata["str_response_string"] = "Bad request";
  448. return;
  449. }
  450. //agent.Dump();
  451. // This is one of the meanings of PUT agent
  452. result = UpdateAgent(destination, agent);
  453. }
  454. else if ("AgentPosition".Equals(messageType))
  455. {
  456. AgentPosition agent = new AgentPosition();
  457. try
  458. {
  459. agent.Unpack(args, m_SimulationService.GetScene(destination.RegionHandle));
  460. }
  461. catch (Exception ex)
  462. {
  463. m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildAgentUpdate message {0}", ex.Message);
  464. return;
  465. }
  466. //agent.Dump();
  467. // This is one of the meanings of PUT agent
  468. result = m_SimulationService.UpdateAgent(destination, agent);
  469. }
  470. responsedata["int_response_code"] = HttpStatusCode.OK;
  471. responsedata["str_response_string"] = result.ToString();
  472. //responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp); ??? instead
  473. }
  474. // subclasses can override this
  475. protected virtual bool UpdateAgent(GridRegion destination, AgentData agent)
  476. {
  477. return m_SimulationService.UpdateAgent(destination, agent);
  478. }
  479. }
  480. }