MessageTransferModule.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  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.Net;
  31. using System.Reflection;
  32. using log4net;
  33. using Mono.Addins;
  34. using Nini.Config;
  35. using Nwc.XmlRpc;
  36. using OpenMetaverse;
  37. using OpenSim.Framework;
  38. using OpenSim.Framework.Servers;
  39. using OpenSim.Region.Framework.Interfaces;
  40. using OpenSim.Region.Framework.Scenes;
  41. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  42. using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
  43. using OpenSim.Services.Interfaces;
  44. namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
  45. {
  46. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MessageTransferModule")]
  47. public class MessageTransferModule : ISharedRegionModule, IMessageTransferModule
  48. {
  49. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  50. private bool m_Enabled = false;
  51. protected List<Scene> m_Scenes = new List<Scene>();
  52. protected Dictionary<UUID, UUID> m_UserRegionMap = new Dictionary<UUID, UUID>();
  53. public event UndeliveredMessage OnUndeliveredMessage;
  54. private IPresenceService m_PresenceService;
  55. protected IPresenceService PresenceService
  56. {
  57. get
  58. {
  59. if (m_PresenceService == null)
  60. m_PresenceService = m_Scenes[0].RequestModuleInterface<IPresenceService>();
  61. return m_PresenceService;
  62. }
  63. }
  64. public virtual void Initialise(IConfigSource config)
  65. {
  66. IConfig cnf = config.Configs["Messaging"];
  67. if (cnf != null && cnf.GetString(
  68. "MessageTransferModule", "MessageTransferModule") !=
  69. "MessageTransferModule")
  70. {
  71. m_log.Debug("[MESSAGE TRANSFER]: Disabled by configuration");
  72. return;
  73. }
  74. m_Enabled = true;
  75. }
  76. public virtual void AddRegion(Scene scene)
  77. {
  78. if (!m_Enabled)
  79. return;
  80. lock (m_Scenes)
  81. {
  82. m_log.Debug("[MESSAGE TRANSFER]: Message transfer module active");
  83. scene.RegisterModuleInterface<IMessageTransferModule>(this);
  84. m_Scenes.Add(scene);
  85. }
  86. }
  87. public virtual void PostInitialise()
  88. {
  89. if (!m_Enabled)
  90. return;
  91. MainServer.Instance.AddXmlRPCHandler(
  92. "grid_instant_message", processXMLRPCGridInstantMessage);
  93. }
  94. public virtual void RegionLoaded(Scene scene)
  95. {
  96. }
  97. public virtual void RemoveRegion(Scene scene)
  98. {
  99. if (!m_Enabled)
  100. return;
  101. lock (m_Scenes)
  102. {
  103. m_Scenes.Remove(scene);
  104. }
  105. }
  106. public virtual void Close()
  107. {
  108. }
  109. public virtual string Name
  110. {
  111. get { return "MessageTransferModule"; }
  112. }
  113. public virtual Type ReplaceableInterface
  114. {
  115. get { return null; }
  116. }
  117. public virtual void SendInstantMessage(GridInstantMessage im, MessageResultNotification result)
  118. {
  119. UUID toAgentID = new UUID(im.toAgentID);
  120. // Try root avatar only first
  121. foreach (Scene scene in m_Scenes)
  122. {
  123. // m_log.DebugFormat(
  124. // "[INSTANT MESSAGE]: Looking for root agent {0} in {1}",
  125. // toAgentID.ToString(), scene.RegionInfo.RegionName);
  126. ScenePresence sp = scene.GetScenePresence(toAgentID);
  127. if (sp != null && !sp.IsChildAgent)
  128. {
  129. // Local message
  130. // m_log.DebugFormat("[INSTANT MESSAGE]: Delivering IM to root agent {0} {1}", sp.Name, toAgentID);
  131. sp.ControllingClient.SendInstantMessage(im);
  132. // Message sent
  133. result(true);
  134. return;
  135. }
  136. }
  137. // try child avatar second
  138. foreach (Scene scene in m_Scenes)
  139. {
  140. // m_log.DebugFormat(
  141. // "[INSTANT MESSAGE]: Looking for child of {0} in {1}", toAgentID, scene.RegionInfo.RegionName);
  142. ScenePresence sp = scene.GetScenePresence(toAgentID);
  143. if (sp != null)
  144. {
  145. // Local message
  146. // m_log.DebugFormat("[INSTANT MESSAGE]: Delivering IM to child agent {0} {1}", sp.Name, toAgentID);
  147. sp.ControllingClient.SendInstantMessage(im);
  148. // Message sent
  149. result(true);
  150. return;
  151. }
  152. }
  153. // m_log.DebugFormat("[INSTANT MESSAGE]: Delivering IM to {0} via XMLRPC", im.toAgentID);
  154. SendGridInstantMessageViaXMLRPC(im, result);
  155. }
  156. public void HandleUndeliverableMessage(GridInstantMessage im, MessageResultNotification result)
  157. {
  158. UndeliveredMessage handlerUndeliveredMessage = OnUndeliveredMessage;
  159. // If this event has handlers, then an IM from an agent will be
  160. // considered delivered. This will suppress the error message.
  161. //
  162. if (handlerUndeliveredMessage != null)
  163. {
  164. handlerUndeliveredMessage(im);
  165. if (im.dialog == (byte)InstantMessageDialog.MessageFromAgent)
  166. result(true);
  167. else
  168. result(false);
  169. return;
  170. }
  171. //m_log.DebugFormat("[INSTANT MESSAGE]: Undeliverable");
  172. result(false);
  173. }
  174. /// <summary>
  175. /// Process a XMLRPC Grid Instant Message
  176. /// </summary>
  177. /// <param name="request">XMLRPC parameters
  178. /// </param>
  179. /// <returns>Nothing much</returns>
  180. protected virtual XmlRpcResponse processXMLRPCGridInstantMessage(XmlRpcRequest request, IPEndPoint remoteClient)
  181. {
  182. bool successful = false;
  183. // TODO: For now, as IMs seem to be a bit unreliable on OSGrid, catch all exception that
  184. // happen here and aren't caught and log them.
  185. try
  186. {
  187. // various rational defaults
  188. UUID fromAgentID = UUID.Zero;
  189. UUID toAgentID = UUID.Zero;
  190. UUID imSessionID = UUID.Zero;
  191. uint timestamp = 0;
  192. string fromAgentName = "";
  193. string message = "";
  194. byte dialog = (byte)0;
  195. bool fromGroup = false;
  196. byte offline = (byte)0;
  197. uint ParentEstateID=0;
  198. Vector3 Position = Vector3.Zero;
  199. UUID RegionID = UUID.Zero ;
  200. byte[] binaryBucket = new byte[0];
  201. float pos_x = 0;
  202. float pos_y = 0;
  203. float pos_z = 0;
  204. //m_log.Info("Processing IM");
  205. Hashtable requestData = (Hashtable)request.Params[0];
  206. // Check if it's got all the data
  207. if (requestData.ContainsKey("from_agent_id")
  208. && requestData.ContainsKey("to_agent_id") && requestData.ContainsKey("im_session_id")
  209. && requestData.ContainsKey("timestamp") && requestData.ContainsKey("from_agent_name")
  210. && requestData.ContainsKey("message") && requestData.ContainsKey("dialog")
  211. && requestData.ContainsKey("from_group")
  212. && requestData.ContainsKey("offline") && requestData.ContainsKey("parent_estate_id")
  213. && requestData.ContainsKey("position_x") && requestData.ContainsKey("position_y")
  214. && requestData.ContainsKey("position_z") && requestData.ContainsKey("region_id")
  215. && requestData.ContainsKey("binary_bucket"))
  216. {
  217. // Do the easy way of validating the UUIDs
  218. UUID.TryParse((string)requestData["from_agent_id"], out fromAgentID);
  219. UUID.TryParse((string)requestData["to_agent_id"], out toAgentID);
  220. UUID.TryParse((string)requestData["im_session_id"], out imSessionID);
  221. UUID.TryParse((string)requestData["region_id"], out RegionID);
  222. try
  223. {
  224. timestamp = (uint)Convert.ToInt32((string)requestData["timestamp"]);
  225. }
  226. catch (ArgumentException)
  227. {
  228. }
  229. catch (FormatException)
  230. {
  231. }
  232. catch (OverflowException)
  233. {
  234. }
  235. fromAgentName = (string)requestData["from_agent_name"];
  236. message = (string)requestData["message"];
  237. if (message == null)
  238. message = string.Empty;
  239. // Bytes don't transfer well over XMLRPC, so, we Base64 Encode them.
  240. string requestData1 = (string)requestData["dialog"];
  241. if (string.IsNullOrEmpty(requestData1))
  242. {
  243. dialog = 0;
  244. }
  245. else
  246. {
  247. byte[] dialogdata = Convert.FromBase64String(requestData1);
  248. dialog = dialogdata[0];
  249. }
  250. if ((string)requestData["from_group"] == "TRUE")
  251. fromGroup = true;
  252. string requestData2 = (string)requestData["offline"];
  253. if (String.IsNullOrEmpty(requestData2))
  254. {
  255. offline = 0;
  256. }
  257. else
  258. {
  259. byte[] offlinedata = Convert.FromBase64String(requestData2);
  260. offline = offlinedata[0];
  261. }
  262. try
  263. {
  264. ParentEstateID = (uint)Convert.ToInt32((string)requestData["parent_estate_id"]);
  265. }
  266. catch (ArgumentException)
  267. {
  268. }
  269. catch (FormatException)
  270. {
  271. }
  272. catch (OverflowException)
  273. {
  274. }
  275. try
  276. {
  277. pos_x = (uint)Convert.ToInt32((string)requestData["position_x"]);
  278. }
  279. catch (ArgumentException)
  280. {
  281. }
  282. catch (FormatException)
  283. {
  284. }
  285. catch (OverflowException)
  286. {
  287. }
  288. try
  289. {
  290. pos_y = (uint)Convert.ToInt32((string)requestData["position_y"]);
  291. }
  292. catch (ArgumentException)
  293. {
  294. }
  295. catch (FormatException)
  296. {
  297. }
  298. catch (OverflowException)
  299. {
  300. }
  301. try
  302. {
  303. pos_z = (uint)Convert.ToInt32((string)requestData["position_z"]);
  304. }
  305. catch (ArgumentException)
  306. {
  307. }
  308. catch (FormatException)
  309. {
  310. }
  311. catch (OverflowException)
  312. {
  313. }
  314. Position = new Vector3(pos_x, pos_y, pos_z);
  315. string requestData3 = (string)requestData["binary_bucket"];
  316. if (string.IsNullOrEmpty(requestData3))
  317. {
  318. binaryBucket = new byte[0];
  319. }
  320. else
  321. {
  322. binaryBucket = Convert.FromBase64String(requestData3);
  323. }
  324. // Create a New GridInstantMessageObject the the data
  325. GridInstantMessage gim = new GridInstantMessage();
  326. gim.fromAgentID = fromAgentID.Guid;
  327. gim.fromAgentName = fromAgentName;
  328. gim.fromGroup = fromGroup;
  329. gim.imSessionID = imSessionID.Guid;
  330. gim.RegionID = RegionID.Guid;
  331. gim.timestamp = timestamp;
  332. gim.toAgentID = toAgentID.Guid;
  333. gim.message = message;
  334. gim.dialog = dialog;
  335. gim.offline = offline;
  336. gim.ParentEstateID = ParentEstateID;
  337. gim.Position = Position;
  338. gim.binaryBucket = binaryBucket;
  339. // Trigger the Instant message in the scene.
  340. foreach (Scene scene in m_Scenes)
  341. {
  342. ScenePresence sp = scene.GetScenePresence(toAgentID);
  343. if (sp != null && !sp.IsChildAgent)
  344. {
  345. scene.EventManager.TriggerIncomingInstantMessage(gim);
  346. successful = true;
  347. }
  348. }
  349. if (!successful)
  350. {
  351. // If the message can't be delivered to an agent, it
  352. // is likely to be a group IM. On a group IM, the
  353. // imSessionID = toAgentID = group id. Raise the
  354. // unhandled IM event to give the groups module
  355. // a chance to pick it up. We raise that in a random
  356. // scene, since the groups module is shared.
  357. //
  358. m_Scenes[0].EventManager.TriggerUnhandledInstantMessage(gim);
  359. }
  360. }
  361. }
  362. catch (Exception e)
  363. {
  364. m_log.Error("[INSTANT MESSAGE]: Caught unexpected exception:", e);
  365. successful = false;
  366. }
  367. //Send response back to region calling if it was successful
  368. // calling region uses this to know when to look up a user's location again.
  369. XmlRpcResponse resp = new XmlRpcResponse();
  370. Hashtable respdata = new Hashtable();
  371. if (successful)
  372. respdata["success"] = "TRUE";
  373. else
  374. respdata["success"] = "FALSE";
  375. resp.Value = respdata;
  376. return resp;
  377. }
  378. /// <summary>
  379. /// delegate for sending a grid instant message asynchronously
  380. /// </summary>
  381. public delegate void GridInstantMessageDelegate(GridInstantMessage im, MessageResultNotification result);
  382. protected virtual void GridInstantMessageCompleted(IAsyncResult iar)
  383. {
  384. GridInstantMessageDelegate icon =
  385. (GridInstantMessageDelegate)iar.AsyncState;
  386. icon.EndInvoke(iar);
  387. }
  388. protected virtual void SendGridInstantMessageViaXMLRPC(GridInstantMessage im, MessageResultNotification result)
  389. {
  390. GridInstantMessageDelegate d = SendGridInstantMessageViaXMLRPCAsync;
  391. d.BeginInvoke(im, result, GridInstantMessageCompleted, d);
  392. }
  393. /// <summary>
  394. /// Internal SendGridInstantMessage over XMLRPC method.
  395. /// </summary>
  396. /// <remarks>
  397. /// This is called from within a dedicated thread.
  398. /// </remarks>
  399. private void SendGridInstantMessageViaXMLRPCAsync(GridInstantMessage im, MessageResultNotification result)
  400. {
  401. UUID toAgentID = new UUID(im.toAgentID);
  402. UUID regionID;
  403. bool needToLookupAgent;
  404. lock (m_UserRegionMap)
  405. needToLookupAgent = !m_UserRegionMap.TryGetValue(toAgentID, out regionID);
  406. while (true)
  407. {
  408. if (needToLookupAgent)
  409. {
  410. PresenceInfo[] presences = PresenceService.GetAgents(new string[] { toAgentID.ToString() });
  411. UUID foundRegionID = UUID.Zero;
  412. if (presences != null)
  413. {
  414. foreach (PresenceInfo p in presences)
  415. {
  416. if (p.RegionID != UUID.Zero)
  417. {
  418. foundRegionID = p.RegionID;
  419. break;
  420. }
  421. }
  422. }
  423. // If not found or the found region is the same as the last lookup, then message is undeliverable
  424. if (foundRegionID == UUID.Zero || foundRegionID == regionID)
  425. break;
  426. else
  427. regionID = foundRegionID;
  428. }
  429. GridRegion reginfo = m_Scenes[0].GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, regionID);
  430. if (reginfo == null)
  431. {
  432. m_log.WarnFormat("[GRID INSTANT MESSAGE]: Unable to find region {0}", regionID);
  433. break;
  434. }
  435. // Try to send the message to the agent via the retrieved region.
  436. Hashtable msgdata = ConvertGridInstantMessageToXMLRPC(im);
  437. msgdata["region_handle"] = 0;
  438. bool imresult = doIMSending(reginfo, msgdata);
  439. // If the message delivery was successful, then cache the entry.
  440. if (imresult)
  441. {
  442. lock (m_UserRegionMap)
  443. {
  444. m_UserRegionMap[toAgentID] = regionID;
  445. }
  446. result(true);
  447. return;
  448. }
  449. // If we reach this point in the first iteration of the while, then we may have unsuccessfully tried
  450. // to use a locally cached region ID. All subsequent attempts need to lookup agent details from
  451. // the presence service.
  452. needToLookupAgent = true;
  453. }
  454. // If we reached this point then the message was not deliverable. Remove the bad cache entry and
  455. // signal the delivery failure.
  456. lock (m_UserRegionMap)
  457. m_UserRegionMap.Remove(toAgentID);
  458. // m_log.Error("[GRID INSTANT MESSAGE]: Unable to deliver an instant message");
  459. HandleUndeliverableMessage(im, result);
  460. }
  461. /// <summary>
  462. /// This actually does the XMLRPC Request
  463. /// </summary>
  464. /// <param name="reginfo">RegionInfo we pull the data out of to send the request to</param>
  465. /// <param name="xmlrpcdata">The Instant Message data Hashtable</param>
  466. /// <returns>Bool if the message was successfully delivered at the other side.</returns>
  467. protected virtual bool doIMSending(GridRegion reginfo, Hashtable xmlrpcdata)
  468. {
  469. ArrayList SendParams = new ArrayList();
  470. SendParams.Add(xmlrpcdata);
  471. XmlRpcRequest GridReq = new XmlRpcRequest("grid_instant_message", SendParams);
  472. try
  473. {
  474. XmlRpcResponse GridResp = GridReq.Send(reginfo.ServerURI, 3000);
  475. Hashtable responseData = (Hashtable)GridResp.Value;
  476. if (responseData.ContainsKey("success"))
  477. {
  478. if ((string)responseData["success"] == "TRUE")
  479. {
  480. return true;
  481. }
  482. else
  483. {
  484. return false;
  485. }
  486. }
  487. else
  488. {
  489. return false;
  490. }
  491. }
  492. catch (WebException e)
  493. {
  494. m_log.ErrorFormat("[GRID INSTANT MESSAGE]: Error sending message to {0} the host didn't respond " + e.ToString(), reginfo.ServerURI.ToString());
  495. }
  496. return false;
  497. }
  498. /// <summary>
  499. /// Get ulong region handle for region by it's Region UUID.
  500. /// We use region handles over grid comms because there's all sorts of free and cool caching.
  501. /// </summary>
  502. /// <param name="regionID">UUID of region to get the region handle for</param>
  503. /// <returns></returns>
  504. // private virtual ulong getLocalRegionHandleFromUUID(UUID regionID)
  505. // {
  506. // ulong returnhandle = 0;
  507. //
  508. // lock (m_Scenes)
  509. // {
  510. // foreach (Scene sn in m_Scenes)
  511. // {
  512. // if (sn.RegionInfo.RegionID == regionID)
  513. // {
  514. // returnhandle = sn.RegionInfo.RegionHandle;
  515. // break;
  516. // }
  517. // }
  518. // }
  519. // return returnhandle;
  520. // }
  521. /// <summary>
  522. /// Takes a GridInstantMessage and converts it into a Hashtable for XMLRPC
  523. /// </summary>
  524. /// <param name="msg">The GridInstantMessage object</param>
  525. /// <returns>Hashtable containing the XMLRPC request</returns>
  526. protected virtual Hashtable ConvertGridInstantMessageToXMLRPC(GridInstantMessage msg)
  527. {
  528. Hashtable gim = new Hashtable();
  529. gim["from_agent_id"] = msg.fromAgentID.ToString();
  530. // Kept for compatibility
  531. gim["from_agent_session"] = UUID.Zero.ToString();
  532. gim["to_agent_id"] = msg.toAgentID.ToString();
  533. gim["im_session_id"] = msg.imSessionID.ToString();
  534. gim["timestamp"] = msg.timestamp.ToString();
  535. gim["from_agent_name"] = msg.fromAgentName;
  536. gim["message"] = msg.message;
  537. byte[] dialogdata = new byte[1];dialogdata[0] = msg.dialog;
  538. gim["dialog"] = Convert.ToBase64String(dialogdata,Base64FormattingOptions.None);
  539. if (msg.fromGroup)
  540. gim["from_group"] = "TRUE";
  541. else
  542. gim["from_group"] = "FALSE";
  543. byte[] offlinedata = new byte[1]; offlinedata[0] = msg.offline;
  544. gim["offline"] = Convert.ToBase64String(offlinedata, Base64FormattingOptions.None);
  545. gim["parent_estate_id"] = msg.ParentEstateID.ToString();
  546. gim["position_x"] = msg.Position.X.ToString();
  547. gim["position_y"] = msg.Position.Y.ToString();
  548. gim["position_z"] = msg.Position.Z.ToString();
  549. gim["region_id"] = new UUID(msg.RegionID).ToString();
  550. gim["binary_bucket"] = Convert.ToBase64String(msg.binaryBucket,Base64FormattingOptions.None);
  551. return gim;
  552. }
  553. }
  554. }