UserAgentServiceConnector.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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.IO;
  31. using System.Net;
  32. using System.Reflection;
  33. using System.Text;
  34. using OpenSim.Framework;
  35. using OpenSim.Services.Interfaces;
  36. using OpenSim.Services.Connectors.Simulation;
  37. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  38. using OpenMetaverse;
  39. using OpenMetaverse.StructuredData;
  40. using log4net;
  41. using Nwc.XmlRpc;
  42. using Nini.Config;
  43. namespace OpenSim.Services.Connectors.Hypergrid
  44. {
  45. public class UserAgentServiceConnector : IUserAgentService
  46. {
  47. private static readonly ILog m_log =
  48. LogManager.GetLogger(
  49. MethodBase.GetCurrentMethod().DeclaringType);
  50. string m_ServerURL;
  51. public UserAgentServiceConnector(string url)
  52. {
  53. m_ServerURL = url;
  54. // Doing this here, because XML-RPC or mono have some strong ideas about
  55. // caching DNS translations.
  56. try
  57. {
  58. Uri m_Uri = new Uri(m_ServerURL);
  59. IPAddress ip = Util.GetHostFromDNS(m_Uri.Host);
  60. m_ServerURL = m_ServerURL.Replace(m_Uri.Host, ip.ToString());
  61. if (!m_ServerURL.EndsWith("/"))
  62. m_ServerURL += "/";
  63. }
  64. catch (Exception e)
  65. {
  66. m_log.DebugFormat("[USER AGENT CONNECTOR]: Malformed Uri {0}: {1}", m_ServerURL, e.Message);
  67. }
  68. m_log.DebugFormat("[USER AGENT CONNECTOR]: new connector to {0} ({1})", url, m_ServerURL);
  69. }
  70. public UserAgentServiceConnector(IConfigSource config)
  71. {
  72. IConfig serviceConfig = config.Configs["UserAgentService"];
  73. if (serviceConfig == null)
  74. {
  75. m_log.Error("[USER AGENT CONNECTOR]: UserAgentService missing from ini");
  76. throw new Exception("UserAgent connector init error");
  77. }
  78. string serviceURI = serviceConfig.GetString("UserAgentServerURI",
  79. String.Empty);
  80. if (serviceURI == String.Empty)
  81. {
  82. m_log.Error("[USER AGENT CONNECTOR]: No Server URI named in section UserAgentService");
  83. throw new Exception("UserAgent connector init error");
  84. }
  85. m_ServerURL = serviceURI;
  86. if (!m_ServerURL.EndsWith("/"))
  87. m_ServerURL += "/";
  88. m_log.DebugFormat("[USER AGENT CONNECTOR]: UserAgentServiceConnector started for {0}", m_ServerURL);
  89. }
  90. // The Login service calls this interface with a non-null [client] ipaddress
  91. public bool LoginAgentToGrid(AgentCircuitData aCircuit, GridRegion gatekeeper, GridRegion destination, IPEndPoint ipaddress, out string reason)
  92. {
  93. reason = String.Empty;
  94. if (destination == null)
  95. {
  96. reason = "Destination is null";
  97. m_log.Debug("[USER AGENT CONNECTOR]: Given destination is null");
  98. return false;
  99. }
  100. string uri = m_ServerURL + "homeagent/" + aCircuit.AgentID + "/";
  101. Console.WriteLine(" >>> LoginAgentToGrid <<< " + uri);
  102. HttpWebRequest AgentCreateRequest = (HttpWebRequest)WebRequest.Create(uri);
  103. AgentCreateRequest.Method = "POST";
  104. AgentCreateRequest.ContentType = "application/json";
  105. AgentCreateRequest.Timeout = 10000;
  106. //AgentCreateRequest.KeepAlive = false;
  107. //AgentCreateRequest.Headers.Add("Authorization", authKey);
  108. // Fill it in
  109. OSDMap args = PackCreateAgentArguments(aCircuit, gatekeeper, destination, ipaddress);
  110. string strBuffer = "";
  111. byte[] buffer = new byte[1];
  112. try
  113. {
  114. strBuffer = OSDParser.SerializeJsonString(args);
  115. Encoding str = Util.UTF8;
  116. buffer = str.GetBytes(strBuffer);
  117. }
  118. catch (Exception e)
  119. {
  120. m_log.WarnFormat("[USER AGENT CONNECTOR]: Exception thrown on serialization of ChildCreate: {0}", e.Message);
  121. // ignore. buffer will be empty, caller should check.
  122. }
  123. Stream os = null;
  124. try
  125. { // send the Post
  126. AgentCreateRequest.ContentLength = buffer.Length; //Count bytes to send
  127. os = AgentCreateRequest.GetRequestStream();
  128. os.Write(buffer, 0, strBuffer.Length); //Send it
  129. m_log.InfoFormat("[USER AGENT CONNECTOR]: Posted CreateAgent request to remote sim {0}, region {1}, x={2} y={3}",
  130. uri, destination.RegionName, destination.RegionLocX, destination.RegionLocY);
  131. }
  132. //catch (WebException ex)
  133. catch
  134. {
  135. //m_log.InfoFormat("[USER AGENT CONNECTOR]: Bad send on ChildAgentUpdate {0}", ex.Message);
  136. reason = "cannot contact remote region";
  137. return false;
  138. }
  139. finally
  140. {
  141. if (os != null)
  142. os.Close();
  143. }
  144. // Let's wait for the response
  145. //m_log.Info("[USER AGENT CONNECTOR]: Waiting for a reply after DoCreateChildAgentCall");
  146. WebResponse webResponse = null;
  147. StreamReader sr = null;
  148. try
  149. {
  150. webResponse = AgentCreateRequest.GetResponse();
  151. if (webResponse == null)
  152. {
  153. m_log.Info("[USER AGENT CONNECTOR]: Null reply on DoCreateChildAgentCall post");
  154. }
  155. else
  156. {
  157. sr = new StreamReader(webResponse.GetResponseStream());
  158. string response = sr.ReadToEnd().Trim();
  159. m_log.InfoFormat("[USER AGENT CONNECTOR]: DoCreateChildAgentCall reply was {0} ", response);
  160. if (!String.IsNullOrEmpty(response))
  161. {
  162. try
  163. {
  164. // we assume we got an OSDMap back
  165. OSDMap r = Util.GetOSDMap(response);
  166. bool success = r["success"].AsBoolean();
  167. reason = r["reason"].AsString();
  168. return success;
  169. }
  170. catch (NullReferenceException e)
  171. {
  172. m_log.InfoFormat("[USER AGENT CONNECTOR]: exception on reply of DoCreateChildAgentCall {0}", e.Message);
  173. // check for old style response
  174. if (response.ToLower().StartsWith("true"))
  175. return true;
  176. return false;
  177. }
  178. }
  179. }
  180. }
  181. catch (WebException ex)
  182. {
  183. m_log.InfoFormat("[USER AGENT CONNECTOR]: exception on reply of DoCreateChildAgentCall {0}", ex.Message);
  184. reason = "Destination did not reply";
  185. return false;
  186. }
  187. finally
  188. {
  189. if (sr != null)
  190. sr.Close();
  191. }
  192. return true;
  193. }
  194. // The simulators call this interface
  195. public bool LoginAgentToGrid(AgentCircuitData aCircuit, GridRegion gatekeeper, GridRegion destination, out string reason)
  196. {
  197. return LoginAgentToGrid(aCircuit, gatekeeper, destination, null, out reason);
  198. }
  199. protected OSDMap PackCreateAgentArguments(AgentCircuitData aCircuit, GridRegion gatekeeper, GridRegion destination, IPEndPoint ipaddress)
  200. {
  201. OSDMap args = null;
  202. try
  203. {
  204. args = aCircuit.PackAgentCircuitData();
  205. }
  206. catch (Exception e)
  207. {
  208. m_log.Debug("[USER AGENT CONNECTOR]: PackAgentCircuitData failed with exception: " + e.Message);
  209. }
  210. // Add the input arguments
  211. args["gatekeeper_serveruri"] = OSD.FromString(gatekeeper.ServerURI);
  212. args["gatekeeper_host"] = OSD.FromString(gatekeeper.ExternalHostName);
  213. args["gatekeeper_port"] = OSD.FromString(gatekeeper.HttpPort.ToString());
  214. args["destination_x"] = OSD.FromString(destination.RegionLocX.ToString());
  215. args["destination_y"] = OSD.FromString(destination.RegionLocY.ToString());
  216. args["destination_name"] = OSD.FromString(destination.RegionName);
  217. args["destination_uuid"] = OSD.FromString(destination.RegionID.ToString());
  218. args["destination_serveruri"] = OSD.FromString(destination.ServerURI);
  219. // 10/3/2010
  220. // I added the client_ip up to the regular AgentCircuitData, so this doesn't need to be here.
  221. // This need cleaning elsewhere...
  222. //if (ipaddress != null)
  223. // args["client_ip"] = OSD.FromString(ipaddress.Address.ToString());
  224. return args;
  225. }
  226. public void SetClientToken(UUID sessionID, string token)
  227. {
  228. // no-op
  229. }
  230. public GridRegion GetHomeRegion(UUID userID, out Vector3 position, out Vector3 lookAt)
  231. {
  232. position = Vector3.UnitY; lookAt = Vector3.UnitY;
  233. Hashtable hash = new Hashtable();
  234. hash["userID"] = userID.ToString();
  235. IList paramList = new ArrayList();
  236. paramList.Add(hash);
  237. XmlRpcRequest request = new XmlRpcRequest("get_home_region", paramList);
  238. XmlRpcResponse response = null;
  239. try
  240. {
  241. response = request.Send(m_ServerURL, 10000);
  242. }
  243. catch (Exception)
  244. {
  245. return null;
  246. }
  247. if (response.IsFault)
  248. {
  249. return null;
  250. }
  251. hash = (Hashtable)response.Value;
  252. //foreach (Object o in hash)
  253. // m_log.Debug(">> " + ((DictionaryEntry)o).Key + ":" + ((DictionaryEntry)o).Value);
  254. try
  255. {
  256. bool success = false;
  257. Boolean.TryParse((string)hash["result"], out success);
  258. if (success)
  259. {
  260. GridRegion region = new GridRegion();
  261. UUID.TryParse((string)hash["uuid"], out region.RegionID);
  262. //m_log.Debug(">> HERE, uuid: " + region.RegionID);
  263. int n = 0;
  264. if (hash["x"] != null)
  265. {
  266. Int32.TryParse((string)hash["x"], out n);
  267. region.RegionLocX = n;
  268. //m_log.Debug(">> HERE, x: " + region.RegionLocX);
  269. }
  270. if (hash["y"] != null)
  271. {
  272. Int32.TryParse((string)hash["y"], out n);
  273. region.RegionLocY = n;
  274. //m_log.Debug(">> HERE, y: " + region.RegionLocY);
  275. }
  276. if (hash["region_name"] != null)
  277. {
  278. region.RegionName = (string)hash["region_name"];
  279. //m_log.Debug(">> HERE, name: " + region.RegionName);
  280. }
  281. if (hash["hostname"] != null)
  282. region.ExternalHostName = (string)hash["hostname"];
  283. if (hash["http_port"] != null)
  284. {
  285. uint p = 0;
  286. UInt32.TryParse((string)hash["http_port"], out p);
  287. region.HttpPort = p;
  288. }
  289. if (hash["internal_port"] != null)
  290. {
  291. int p = 0;
  292. Int32.TryParse((string)hash["internal_port"], out p);
  293. region.InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), p);
  294. }
  295. if (hash["position"] != null)
  296. Vector3.TryParse((string)hash["position"], out position);
  297. if (hash["lookAt"] != null)
  298. Vector3.TryParse((string)hash["lookAt"], out lookAt);
  299. // Successful return
  300. return region;
  301. }
  302. }
  303. catch (Exception)
  304. {
  305. return null;
  306. }
  307. return null;
  308. }
  309. public bool AgentIsComingHome(UUID sessionID, string thisGridExternalName)
  310. {
  311. Hashtable hash = new Hashtable();
  312. hash["sessionID"] = sessionID.ToString();
  313. hash["externalName"] = thisGridExternalName;
  314. IList paramList = new ArrayList();
  315. paramList.Add(hash);
  316. XmlRpcRequest request = new XmlRpcRequest("agent_is_coming_home", paramList);
  317. string reason = string.Empty;
  318. return GetBoolResponse(request, out reason);
  319. }
  320. public bool VerifyAgent(UUID sessionID, string token)
  321. {
  322. Hashtable hash = new Hashtable();
  323. hash["sessionID"] = sessionID.ToString();
  324. hash["token"] = token;
  325. IList paramList = new ArrayList();
  326. paramList.Add(hash);
  327. XmlRpcRequest request = new XmlRpcRequest("verify_agent", paramList);
  328. string reason = string.Empty;
  329. return GetBoolResponse(request, out reason);
  330. }
  331. public bool VerifyClient(UUID sessionID, string token)
  332. {
  333. Hashtable hash = new Hashtable();
  334. hash["sessionID"] = sessionID.ToString();
  335. hash["token"] = token;
  336. IList paramList = new ArrayList();
  337. paramList.Add(hash);
  338. XmlRpcRequest request = new XmlRpcRequest("verify_client", paramList);
  339. string reason = string.Empty;
  340. return GetBoolResponse(request, out reason);
  341. }
  342. public void LogoutAgent(UUID userID, UUID sessionID)
  343. {
  344. Hashtable hash = new Hashtable();
  345. hash["sessionID"] = sessionID.ToString();
  346. hash["userID"] = userID.ToString();
  347. IList paramList = new ArrayList();
  348. paramList.Add(hash);
  349. XmlRpcRequest request = new XmlRpcRequest("logout_agent", paramList);
  350. string reason = string.Empty;
  351. GetBoolResponse(request, out reason);
  352. }
  353. private bool GetBoolResponse(XmlRpcRequest request, out string reason)
  354. {
  355. //m_log.Debug("[USER AGENT CONNECTOR]: GetBoolResponse from/to " + m_ServerURL);
  356. XmlRpcResponse response = null;
  357. try
  358. {
  359. response = request.Send(m_ServerURL, 10000);
  360. }
  361. catch (Exception e)
  362. {
  363. m_log.DebugFormat("[USER AGENT CONNECTOR]: Unable to contact remote server {0}", m_ServerURL);
  364. reason = "Exception: " + e.Message;
  365. return false;
  366. }
  367. if (response.IsFault)
  368. {
  369. m_log.ErrorFormat("[USER AGENT CONNECTOR]: remote call to {0} returned an error: {1}", m_ServerURL, response.FaultString);
  370. reason = "XMLRPC Fault";
  371. return false;
  372. }
  373. Hashtable hash = (Hashtable)response.Value;
  374. //foreach (Object o in hash)
  375. // m_log.Debug(">> " + ((DictionaryEntry)o).Key + ":" + ((DictionaryEntry)o).Value);
  376. try
  377. {
  378. if (hash == null)
  379. {
  380. m_log.ErrorFormat("[USER AGENT CONNECTOR]: Got null response from {0}! THIS IS BAAAAD", m_ServerURL);
  381. reason = "Internal error 1";
  382. return false;
  383. }
  384. bool success = false;
  385. reason = string.Empty;
  386. if (hash.ContainsKey("result"))
  387. Boolean.TryParse((string)hash["result"], out success);
  388. else
  389. {
  390. reason = "Internal error 2";
  391. m_log.WarnFormat("[USER AGENT CONNECTOR]: response from {0} does not have expected key 'result'", m_ServerURL);
  392. }
  393. return success;
  394. }
  395. catch (Exception e)
  396. {
  397. m_log.ErrorFormat("[USER AGENT CONNECTOR]: Got exception on GetBoolResponse response.");
  398. if (hash.ContainsKey("result") && hash["result"] != null)
  399. m_log.ErrorFormat("Reply was ", (string)hash["result"]);
  400. reason = "Exception: " + e.Message;
  401. return false;
  402. }
  403. }
  404. }
  405. }