AgentHandlers.cs 22 KB

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