1
0

AgentHandlers.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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. Stream inputStream = null;
  189. if (httpRequest.ContentType == "application/x-gzip")
  190. inputStream = new GZipStream(request, CompressionMode.Decompress);
  191. else if (httpRequest.ContentType == "application/json")
  192. inputStream = request;
  193. else // no go
  194. {
  195. httpResponse.StatusCode = 406;
  196. return encoding.GetBytes("false");
  197. }
  198. StreamReader reader = new StreamReader(inputStream, encoding);
  199. string requestBody = reader.ReadToEnd();
  200. reader.Close();
  201. keysvals.Add("body", requestBody);
  202. Hashtable responsedata = new Hashtable();
  203. UUID agentID;
  204. UUID regionID;
  205. string action;
  206. if (!Utils.GetParams((string)keysvals["uri"], out agentID, out regionID, out action))
  207. {
  208. m_log.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", keysvals["uri"]);
  209. httpResponse.StatusCode = 404;
  210. return encoding.GetBytes("false");
  211. }
  212. DoAgentPost(keysvals, responsedata, agentID);
  213. httpResponse.StatusCode = (int)responsedata["int_response_code"];
  214. return encoding.GetBytes((string)responsedata["str_response_string"]);
  215. }
  216. protected void DoAgentPost(Hashtable request, Hashtable responsedata, UUID id)
  217. {
  218. OSDMap args = Utils.GetOSDMap((string)request["body"]);
  219. if (args == null)
  220. {
  221. responsedata["int_response_code"] = HttpStatusCode.BadRequest;
  222. responsedata["str_response_string"] = "Bad request";
  223. return;
  224. }
  225. AgentDestinationData data = CreateAgentDestinationData();
  226. UnpackData(args, data, request);
  227. GridRegion destination = new GridRegion();
  228. destination.RegionID = data.uuid;
  229. destination.RegionLocX = data.x;
  230. destination.RegionLocY = data.y;
  231. destination.RegionName = data.name;
  232. GridRegion gatekeeper = ExtractGatekeeper(data);
  233. AgentCircuitData aCircuit = new AgentCircuitData();
  234. try
  235. {
  236. aCircuit.UnpackAgentCircuitData(args);
  237. }
  238. catch (Exception ex)
  239. {
  240. m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildCreate message {0}", ex.Message);
  241. responsedata["int_response_code"] = HttpStatusCode.BadRequest;
  242. responsedata["str_response_string"] = "Bad request";
  243. return;
  244. }
  245. OSDMap resp = new OSDMap(2);
  246. string reason = String.Empty;
  247. // This is the meaning of POST agent
  248. //m_regionClient.AdjustUserInformation(aCircuit);
  249. //bool result = m_SimulationService.CreateAgent(destination, aCircuit, teleportFlags, out reason);
  250. bool result = CreateAgent(gatekeeper, destination, aCircuit, data.flags, data.fromLogin, out reason);
  251. resp["reason"] = OSD.FromString(reason);
  252. resp["success"] = OSD.FromBoolean(result);
  253. // Let's also send out the IP address of the caller back to the caller (HG 1.5)
  254. resp["your_ip"] = OSD.FromString(GetCallerIP(request));
  255. // TODO: add reason if not String.Empty?
  256. responsedata["int_response_code"] = HttpStatusCode.OK;
  257. responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp);
  258. }
  259. protected virtual AgentDestinationData CreateAgentDestinationData()
  260. {
  261. return new AgentDestinationData();
  262. }
  263. protected virtual void UnpackData(OSDMap args, AgentDestinationData data, Hashtable request)
  264. {
  265. // retrieve the input arguments
  266. if (args.ContainsKey("destination_x") && args["destination_x"] != null)
  267. Int32.TryParse(args["destination_x"].AsString(), out data.x);
  268. else
  269. m_log.WarnFormat(" -- request didn't have destination_x");
  270. if (args.ContainsKey("destination_y") && args["destination_y"] != null)
  271. Int32.TryParse(args["destination_y"].AsString(), out data.y);
  272. else
  273. m_log.WarnFormat(" -- request didn't have destination_y");
  274. if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null)
  275. UUID.TryParse(args["destination_uuid"].AsString(), out data.uuid);
  276. if (args.ContainsKey("destination_name") && args["destination_name"] != null)
  277. data.name = args["destination_name"].ToString();
  278. if (args.ContainsKey("teleport_flags") && args["teleport_flags"] != null)
  279. data.flags = args["teleport_flags"].AsUInteger();
  280. }
  281. protected virtual GridRegion ExtractGatekeeper(AgentDestinationData data)
  282. {
  283. return null;
  284. }
  285. protected string GetCallerIP(Hashtable request)
  286. {
  287. if (!m_Proxy)
  288. return Util.GetCallerIP(request);
  289. // We're behind a proxy
  290. Hashtable headers = (Hashtable)request["headers"];
  291. //// DEBUG
  292. //foreach (object o in headers.Keys)
  293. // m_log.DebugFormat("XXX {0} = {1}", o.ToString(), (headers[o] == null? "null" : headers[o].ToString()));
  294. string xff = "X-Forwarded-For";
  295. if (headers.ContainsKey(xff.ToLower()))
  296. xff = xff.ToLower();
  297. if (!headers.ContainsKey(xff) || headers[xff] == null)
  298. {
  299. m_log.WarnFormat("[AGENT HANDLER]: No XFF header");
  300. return Util.GetCallerIP(request);
  301. }
  302. m_log.DebugFormat("[AGENT HANDLER]: XFF is {0}", headers[xff]);
  303. IPEndPoint ep = Util.GetClientIPFromXFF((string)headers[xff]);
  304. if (ep != null)
  305. return ep.Address.ToString();
  306. // Oops
  307. return Util.GetCallerIP(request);
  308. }
  309. // subclasses can override this
  310. protected virtual bool CreateAgent(GridRegion gatekeeper, GridRegion destination, AgentCircuitData aCircuit, uint teleportFlags, bool fromLogin, out string reason)
  311. {
  312. return m_SimulationService.CreateAgent(destination, aCircuit, teleportFlags, out reason);
  313. }
  314. }
  315. public class AgentPutHandler : BaseStreamHandler
  316. {
  317. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  318. private ISimulationService m_SimulationService;
  319. protected bool m_Proxy = false;
  320. public AgentPutHandler(ISimulationService service) :
  321. base("PUT", "/agent")
  322. {
  323. m_SimulationService = service;
  324. }
  325. public AgentPutHandler(string path) :
  326. base("PUT", path)
  327. {
  328. m_SimulationService = null;
  329. }
  330. protected override byte[] ProcessRequest(string path, Stream request,
  331. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  332. {
  333. // m_log.DebugFormat("[SIMULATION]: Stream handler called");
  334. Hashtable keysvals = new Hashtable();
  335. Hashtable headervals = new Hashtable();
  336. string[] querystringkeys = httpRequest.QueryString.AllKeys;
  337. string[] rHeaders = httpRequest.Headers.AllKeys;
  338. keysvals.Add("uri", httpRequest.RawUrl);
  339. keysvals.Add("content-type", httpRequest.ContentType);
  340. keysvals.Add("http-method", httpRequest.HttpMethod);
  341. foreach (string queryname in querystringkeys)
  342. keysvals.Add(queryname, httpRequest.QueryString[queryname]);
  343. foreach (string headername in rHeaders)
  344. headervals[headername] = httpRequest.Headers[headername];
  345. keysvals.Add("headers", headervals);
  346. keysvals.Add("querystringkeys", querystringkeys);
  347. Stream inputStream;
  348. if (httpRequest.ContentType == "application/x-gzip")
  349. inputStream = new GZipStream(request, CompressionMode.Decompress);
  350. else
  351. inputStream = request;
  352. Encoding encoding = Encoding.UTF8;
  353. StreamReader reader = new StreamReader(inputStream, encoding);
  354. string requestBody = reader.ReadToEnd();
  355. reader.Close();
  356. keysvals.Add("body", requestBody);
  357. httpResponse.StatusCode = 200;
  358. httpResponse.ContentType = "text/html";
  359. httpResponse.KeepAlive = false;
  360. Hashtable responsedata = new Hashtable();
  361. UUID agentID;
  362. UUID regionID;
  363. string action;
  364. if (!Utils.GetParams((string)keysvals["uri"], out agentID, out regionID, out action))
  365. {
  366. m_log.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", keysvals["uri"]);
  367. httpResponse.StatusCode = 404;
  368. return encoding.GetBytes("false");
  369. }
  370. DoAgentPut(keysvals, responsedata);
  371. httpResponse.StatusCode = (int)responsedata["int_response_code"];
  372. return encoding.GetBytes((string)responsedata["str_response_string"]);
  373. }
  374. protected void DoAgentPut(Hashtable request, Hashtable responsedata)
  375. {
  376. OSDMap args = Utils.GetOSDMap((string)request["body"]);
  377. if (args == null)
  378. {
  379. responsedata["int_response_code"] = HttpStatusCode.BadRequest;
  380. responsedata["str_response_string"] = "Bad request";
  381. return;
  382. }
  383. // retrieve the input arguments
  384. int x = 0, y = 0;
  385. UUID uuid = UUID.Zero;
  386. string regionname = string.Empty;
  387. if (args.ContainsKey("destination_x") && args["destination_x"] != null)
  388. Int32.TryParse(args["destination_x"].AsString(), out x);
  389. if (args.ContainsKey("destination_y") && args["destination_y"] != null)
  390. Int32.TryParse(args["destination_y"].AsString(), out y);
  391. if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null)
  392. UUID.TryParse(args["destination_uuid"].AsString(), out uuid);
  393. if (args.ContainsKey("destination_name") && args["destination_name"] != null)
  394. regionname = args["destination_name"].ToString();
  395. GridRegion destination = new GridRegion();
  396. destination.RegionID = uuid;
  397. destination.RegionLocX = x;
  398. destination.RegionLocY = y;
  399. destination.RegionName = regionname;
  400. string messageType;
  401. if (args["message_type"] != null)
  402. messageType = args["message_type"].AsString();
  403. else
  404. {
  405. m_log.Warn("[AGENT HANDLER]: Agent Put Message Type not found. ");
  406. messageType = "AgentData";
  407. }
  408. bool result = true;
  409. if ("AgentData".Equals(messageType))
  410. {
  411. AgentData agent = new AgentData();
  412. try
  413. {
  414. agent.Unpack(args, m_SimulationService.GetScene(destination.RegionID));
  415. }
  416. catch (Exception ex)
  417. {
  418. m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildAgentUpdate message {0}", ex.Message);
  419. responsedata["int_response_code"] = HttpStatusCode.BadRequest;
  420. responsedata["str_response_string"] = "Bad request";
  421. return;
  422. }
  423. //agent.Dump();
  424. // This is one of the meanings of PUT agent
  425. result = UpdateAgent(destination, agent);
  426. }
  427. else if ("AgentPosition".Equals(messageType))
  428. {
  429. AgentPosition agent = new AgentPosition();
  430. try
  431. {
  432. agent.Unpack(args, m_SimulationService.GetScene(destination.RegionID));
  433. }
  434. catch (Exception ex)
  435. {
  436. m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildAgentUpdate message {0}", ex.Message);
  437. return;
  438. }
  439. //agent.Dump();
  440. // This is one of the meanings of PUT agent
  441. result = m_SimulationService.UpdateAgent(destination, agent);
  442. }
  443. responsedata["int_response_code"] = HttpStatusCode.OK;
  444. responsedata["str_response_string"] = result.ToString();
  445. //responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp); ??? instead
  446. }
  447. // subclasses can override this
  448. protected virtual bool UpdateAgent(GridRegion destination, AgentData agent)
  449. {
  450. return m_SimulationService.UpdateAgent(destination, agent);
  451. }
  452. }
  453. public class AgentDestinationData
  454. {
  455. public int x;
  456. public int y;
  457. public string name;
  458. public UUID uuid;
  459. public uint flags;
  460. public bool fromLogin;
  461. }
  462. }