HGInstantMessageService.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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.Generic;
  29. using System.Net;
  30. using System.Reflection;
  31. using OpenSim.Framework;
  32. using OpenSim.Services.Connectors.Friends;
  33. using OpenSim.Services.Connectors.Hypergrid;
  34. using OpenSim.Services.Interfaces;
  35. using OpenSim.Services.Connectors.InstantMessage;
  36. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  37. using OpenSim.Server.Base;
  38. using FriendInfo = OpenSim.Services.Interfaces.FriendInfo;
  39. using OpenMetaverse;
  40. using log4net;
  41. using Nini.Config;
  42. namespace OpenSim.Services.HypergridService
  43. {
  44. /// <summary>
  45. /// Inter-grid IM
  46. /// </summary>
  47. public class HGInstantMessageService : IInstantMessage
  48. {
  49. private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType);
  50. private const int REGIONCACHE_EXPIRATION = 300000;
  51. static bool m_Initialized = false;
  52. protected static IGridService m_GridService;
  53. protected static IPresenceService m_PresenceService;
  54. protected static IUserAgentService m_UserAgentService;
  55. protected static IOfflineIMService m_OfflineIMService;
  56. protected static IInstantMessageSimConnector m_IMSimConnector;
  57. protected static readonly Dictionary<UUID, object> m_UserLocationMap = new Dictionary<UUID, object>();
  58. private static readonly ExpiringCacheOS<UUID, GridRegion> m_RegionCache = new ExpiringCacheOS<UUID, GridRegion>(60000);
  59. private static bool m_ForwardOfflineGroupMessages;
  60. private static bool m_InGatekeeper;
  61. private string m_messageKey;
  62. public HGInstantMessageService(IConfigSource config)
  63. : this(config, null)
  64. {
  65. }
  66. public HGInstantMessageService(IConfigSource config, IInstantMessageSimConnector imConnector)
  67. {
  68. if (imConnector != null)
  69. m_IMSimConnector = imConnector;
  70. if (!m_Initialized)
  71. {
  72. m_Initialized = true;
  73. IConfig serverConfig = config.Configs["HGInstantMessageService"];
  74. if (serverConfig == null)
  75. throw new Exception(String.Format("No section HGInstantMessageService in config file"));
  76. string gridService = serverConfig.GetString("GridService", String.Empty);
  77. string presenceService = serverConfig.GetString("PresenceService", String.Empty);
  78. string userAgentService = serverConfig.GetString("UserAgentService", String.Empty);
  79. m_InGatekeeper = serverConfig.GetBoolean("InGatekeeper", false);
  80. m_log.DebugFormat("[HG IM SERVICE]: Starting... InRobust? {0}", m_InGatekeeper);
  81. if (gridService == string.Empty || presenceService == string.Empty)
  82. throw new Exception(String.Format("Incomplete specifications, InstantMessage Service cannot function."));
  83. Object[] args = new Object[] { config };
  84. m_GridService = ServerUtils.LoadPlugin<IGridService>(gridService, args);
  85. m_PresenceService = ServerUtils.LoadPlugin<IPresenceService>(presenceService, args);
  86. try
  87. {
  88. m_UserAgentService = ServerUtils.LoadPlugin<IUserAgentService>(userAgentService, args);
  89. }
  90. catch
  91. {
  92. m_log.WarnFormat("[HG IM SERVICE]: Unable to create User Agent Service. Missing config var in [HGInstantMessageService]?");
  93. }
  94. IConfig cnf = config.Configs["Messaging"];
  95. if (cnf == null)
  96. {
  97. return;
  98. }
  99. m_messageKey = cnf.GetString("MessageKey", String.Empty);
  100. m_ForwardOfflineGroupMessages = cnf.GetBoolean("ForwardOfflineGroupMessages", false);
  101. if (m_InGatekeeper)
  102. {
  103. string offlineIMService = cnf.GetString("OfflineIMService", string.Empty);
  104. if (offlineIMService != string.Empty)
  105. m_OfflineIMService = ServerUtils.LoadPlugin<IOfflineIMService>(offlineIMService, args);
  106. }
  107. }
  108. }
  109. public bool IncomingInstantMessage(GridInstantMessage im)
  110. {
  111. // m_log.DebugFormat("[HG IM SERVICE]: Received message from {0} to {1}", im.fromAgentID, im.toAgentID);
  112. // UUID toAgentID = new UUID(im.toAgentID);
  113. bool success = false;
  114. if (m_IMSimConnector != null)
  115. {
  116. //m_log.DebugFormat("[XXX] SendIMToRegion local im connector");
  117. success = m_IMSimConnector.SendInstantMessage(im);
  118. }
  119. else
  120. {
  121. success = TrySendInstantMessage(im, "", true, false);
  122. }
  123. if (!success && m_InGatekeeper) // we do this only in the Gatekeeper IM service
  124. UndeliveredMessage(im);
  125. return success;
  126. }
  127. public bool OutgoingInstantMessage(GridInstantMessage im, string url, bool foreigner)
  128. {
  129. // m_log.DebugFormat("[HG IM SERVICE]: Sending message from {0} to {1}@{2}", im.fromAgentID, im.toAgentID, url);
  130. if (url != string.Empty)
  131. return TrySendInstantMessage(im, url, true, foreigner);
  132. else
  133. {
  134. PresenceInfo upd = new PresenceInfo();
  135. upd.RegionID = UUID.Zero;
  136. return TrySendInstantMessage(im, upd, true, foreigner);
  137. }
  138. }
  139. protected bool TrySendInstantMessage(GridInstantMessage im, object previousLocation, bool firstTime, bool foreigner)
  140. {
  141. UUID toAgentID = new UUID(im.toAgentID);
  142. PresenceInfo upd = null;
  143. string url = string.Empty;
  144. bool lookupAgent = false;
  145. lock (m_UserLocationMap)
  146. {
  147. if (m_UserLocationMap.ContainsKey(toAgentID))
  148. {
  149. object o = m_UserLocationMap[toAgentID];
  150. if (o is PresenceInfo)
  151. upd = (PresenceInfo)o;
  152. else if (o is string)
  153. url = (string)o;
  154. // We need to compare the current location with the previous
  155. // or the recursive loop will never end because it will never try to lookup the agent again
  156. if (!firstTime)
  157. {
  158. lookupAgent = true;
  159. upd = null;
  160. }
  161. }
  162. else
  163. {
  164. lookupAgent = true;
  165. }
  166. }
  167. //m_log.DebugFormat("[XXX] Neeed lookup ? {0}", (lookupAgent ? "yes" : "no"));
  168. // Are we needing to look-up an agent?
  169. if (lookupAgent)
  170. {
  171. // Non-cached user agent lookup.
  172. PresenceInfo[] presences = m_PresenceService.GetAgents(new string[] { toAgentID.ToString() });
  173. if (presences != null && presences.Length > 0)
  174. {
  175. foreach (PresenceInfo p in presences)
  176. {
  177. if (p.RegionID != UUID.Zero)
  178. {
  179. //m_log.DebugFormat("[XXX]: Found presence in {0}", p.RegionID);
  180. upd = p;
  181. break;
  182. }
  183. }
  184. }
  185. if (upd == null && !foreigner)
  186. {
  187. // Let's check with the UAS if the user is elsewhere
  188. m_log.DebugFormat("[HG IM SERVICE]: User is not present. Checking location with User Agent service");
  189. try
  190. {
  191. url = m_UserAgentService.LocateUser(toAgentID);
  192. }
  193. catch (Exception e)
  194. {
  195. m_log.Warn("[HG IM SERVICE]: LocateUser call failed ", e);
  196. url = string.Empty;
  197. }
  198. }
  199. // check if we've tried this before..
  200. // This is one way to end the recursive loop
  201. //
  202. if (!firstTime && ((previousLocation is PresenceInfo && upd != null && upd.RegionID == ((PresenceInfo)previousLocation).RegionID) ||
  203. (previousLocation is string && upd == null && previousLocation.Equals(url))))
  204. {
  205. // m_log.Error("[GRID INSTANT MESSAGE]: Unable to deliver an instant message");
  206. m_log.DebugFormat("[HG IM SERVICE]: Fail 2 {0} {1}", previousLocation, url);
  207. return false;
  208. }
  209. }
  210. if (upd != null)
  211. {
  212. // ok, the user is around somewhere. Let's send back the reply with "success"
  213. // even though the IM may still fail. Just don't keep the caller waiting for
  214. // the entire time we're trying to deliver the IM
  215. return SendIMToRegion(upd, im, toAgentID, foreigner);
  216. }
  217. else if (url != string.Empty)
  218. {
  219. // ok, the user is around somewhere. Let's send back the reply with "success"
  220. // even though the IM may still fail. Just don't keep the caller waiting for
  221. // the entire time we're trying to deliver the IM
  222. return ForwardIMToGrid(url, im, toAgentID, foreigner);
  223. }
  224. else if (firstTime && previousLocation is string && (string)previousLocation != string.Empty)
  225. {
  226. return ForwardIMToGrid((string)previousLocation, im, toAgentID, foreigner);
  227. }
  228. else
  229. m_log.DebugFormat("[HG IM SERVICE]: Unable to locate user {0}", toAgentID);
  230. return false;
  231. }
  232. bool SendIMToRegion(PresenceInfo upd, GridInstantMessage im, UUID toAgentID, bool foreigner)
  233. {
  234. bool imresult = false;
  235. GridRegion reginfo = null;
  236. if (!m_RegionCache.TryGetValue(upd.RegionID, REGIONCACHE_EXPIRATION, out reginfo))
  237. {
  238. reginfo = m_GridService.GetRegionByUUID(UUID.Zero /*!!!*/, upd.RegionID);
  239. m_RegionCache.AddOrUpdate(upd.RegionID, reginfo, reginfo == null ? 60000 : REGIONCACHE_EXPIRATION);
  240. }
  241. if (reginfo != null)
  242. {
  243. imresult = InstantMessageServiceConnector.SendInstantMessage(reginfo.ServerURI, im, m_messageKey);
  244. }
  245. else
  246. {
  247. m_log.DebugFormat("[HG IM SERVICE]: Failed to deliver message to {0}", reginfo.ServerURI);
  248. return false;
  249. }
  250. if (imresult)
  251. {
  252. // IM delivery successful, so store the Agent's location in our local cache.
  253. lock (m_UserLocationMap)
  254. {
  255. if (m_UserLocationMap.ContainsKey(toAgentID))
  256. {
  257. m_UserLocationMap[toAgentID] = upd;
  258. }
  259. else
  260. {
  261. m_UserLocationMap.Add(toAgentID, upd);
  262. }
  263. }
  264. return true;
  265. }
  266. else
  267. {
  268. // try again, but lookup user this time.
  269. // Warning, this must call the Async version
  270. // of this method or we'll be making thousands of threads
  271. // The version within the spawned thread is SendGridInstantMessageViaXMLRPCAsync
  272. // The version that spawns the thread is SendGridInstantMessageViaXMLRPC
  273. // This is recursive!!!!!
  274. return TrySendInstantMessage(im, upd, false, foreigner);
  275. }
  276. }
  277. bool ForwardIMToGrid(string url, GridInstantMessage im, UUID toAgentID, bool foreigner)
  278. {
  279. if (InstantMessageServiceConnector.SendInstantMessage(url, im, m_messageKey))
  280. {
  281. // IM delivery successful, so store the Agent's location in our local cache.
  282. lock (m_UserLocationMap)
  283. {
  284. if (m_UserLocationMap.ContainsKey(toAgentID))
  285. {
  286. m_UserLocationMap[toAgentID] = url;
  287. }
  288. else
  289. {
  290. m_UserLocationMap.Add(toAgentID, url);
  291. }
  292. }
  293. return true;
  294. }
  295. else
  296. {
  297. // try again, but lookup user this time.
  298. // This is recursive!!!!!
  299. return TrySendInstantMessage(im, url, false, foreigner);
  300. }
  301. }
  302. private bool UndeliveredMessage(GridInstantMessage im)
  303. {
  304. if (m_OfflineIMService == null)
  305. return false;
  306. if (im.dialog != (byte)InstantMessageDialog.MessageFromObject &&
  307. im.dialog != (byte)InstantMessageDialog.MessageFromAgent &&
  308. im.dialog != (byte)InstantMessageDialog.GroupNotice &&
  309. im.dialog != (byte)InstantMessageDialog.GroupInvitation &&
  310. im.dialog != (byte)InstantMessageDialog.InventoryOffered)
  311. {
  312. return false;
  313. }
  314. if (!m_ForwardOfflineGroupMessages)
  315. {
  316. if (im.dialog == (byte)InstantMessageDialog.GroupNotice ||
  317. im.dialog == (byte)InstantMessageDialog.GroupInvitation)
  318. return false;
  319. }
  320. // m_log.DebugFormat("[HG IM SERVICE]: Message saved");
  321. string reason = string.Empty;
  322. return m_OfflineIMService.StoreMessage(im, out reason);
  323. }
  324. }
  325. }