HGInstantMessageService.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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.TryGetValue(toAgentID, out object o))
  148. {
  149. if (o is PresenceInfo)
  150. upd = (PresenceInfo)o;
  151. else if (o is string)
  152. url = (string)o;
  153. // We need to compare the current location with the previous
  154. // or the recursive loop will never end because it will never try to lookup the agent again
  155. if (!firstTime)
  156. {
  157. lookupAgent = true;
  158. upd = null;
  159. }
  160. }
  161. else
  162. {
  163. lookupAgent = true;
  164. }
  165. }
  166. //m_log.DebugFormat("[XXX] Neeed lookup ? {0}", (lookupAgent ? "yes" : "no"));
  167. // Are we needing to look-up an agent?
  168. if (lookupAgent)
  169. {
  170. // Non-cached user agent lookup.
  171. PresenceInfo[] presences = m_PresenceService.GetAgents(new string[] { toAgentID.ToString() });
  172. if (presences != null && presences.Length > 0)
  173. {
  174. foreach (PresenceInfo p in presences)
  175. {
  176. if (p.RegionID != UUID.Zero)
  177. {
  178. //m_log.DebugFormat("[XXX]: Found presence in {0}", p.RegionID);
  179. upd = p;
  180. break;
  181. }
  182. }
  183. }
  184. if (upd == null && !foreigner)
  185. {
  186. // Let's check with the UAS if the user is elsewhere
  187. m_log.DebugFormat("[HG IM SERVICE]: User is not present. Checking location with User Agent service");
  188. try
  189. {
  190. url = m_UserAgentService.LocateUser(toAgentID);
  191. }
  192. catch (Exception e)
  193. {
  194. m_log.Warn("[HG IM SERVICE]: LocateUser call failed ", e);
  195. url = string.Empty;
  196. }
  197. }
  198. // check if we've tried this before..
  199. // This is one way to end the recursive loop
  200. //
  201. if (!firstTime && ((previousLocation is PresenceInfo && upd != null && upd.RegionID == ((PresenceInfo)previousLocation).RegionID) ||
  202. (previousLocation is string && upd == null && previousLocation.Equals(url))))
  203. {
  204. // m_log.Error("[GRID INSTANT MESSAGE]: Unable to deliver an instant message");
  205. m_log.DebugFormat("[HG IM SERVICE]: Fail 2 {0} {1}", previousLocation, url);
  206. return false;
  207. }
  208. }
  209. if (upd != null)
  210. {
  211. // ok, the user is around somewhere. Let's send back the reply with "success"
  212. // even though the IM may still fail. Just don't keep the caller waiting for
  213. // the entire time we're trying to deliver the IM
  214. return SendIMToRegion(upd, im, toAgentID, foreigner);
  215. }
  216. else if (url != string.Empty)
  217. {
  218. // ok, the user is around somewhere. Let's send back the reply with "success"
  219. // even though the IM may still fail. Just don't keep the caller waiting for
  220. // the entire time we're trying to deliver the IM
  221. return ForwardIMToGrid(url, im, toAgentID, foreigner);
  222. }
  223. else if (firstTime && previousLocation is string && (string)previousLocation != string.Empty)
  224. {
  225. return ForwardIMToGrid((string)previousLocation, im, toAgentID, foreigner);
  226. }
  227. else
  228. m_log.DebugFormat("[HG IM SERVICE]: Unable to locate user {0}", toAgentID);
  229. return false;
  230. }
  231. bool SendIMToRegion(PresenceInfo upd, GridInstantMessage im, UUID toAgentID, bool foreigner)
  232. {
  233. GridRegion reginfo = null;
  234. if (!m_RegionCache.TryGetValue(upd.RegionID, REGIONCACHE_EXPIRATION, out reginfo) )
  235. {
  236. reginfo = m_GridService.GetRegionByUUID(UUID.Zero /*!!!*/, upd.RegionID);
  237. m_RegionCache.AddOrUpdate(upd.RegionID, reginfo, reginfo == null ? 60000 : REGIONCACHE_EXPIRATION);
  238. }
  239. if (reginfo == null)
  240. return false;
  241. bool imresult = InstantMessageServiceConnector.SendInstantMessage(reginfo.ServerURI, im, m_messageKey);
  242. if (imresult)
  243. {
  244. // IM delivery successful, so store the Agent's location in our local cache.
  245. lock (m_UserLocationMap)
  246. m_UserLocationMap[toAgentID] = upd;
  247. return true;
  248. }
  249. else
  250. {
  251. // try again, but lookup user this time.
  252. // Warning, this must call the Async version
  253. // of this method or we'll be making thousands of threads
  254. // The version within the spawned thread is SendGridInstantMessageViaXMLRPCAsync
  255. // The version that spawns the thread is SendGridInstantMessageViaXMLRPC
  256. // This is recursive!!!!!
  257. return TrySendInstantMessage(im, upd, false, foreigner);
  258. }
  259. }
  260. bool ForwardIMToGrid(string url, GridInstantMessage im, UUID toAgentID, bool foreigner)
  261. {
  262. if (InstantMessageServiceConnector.SendInstantMessage(url, im, m_messageKey))
  263. {
  264. // IM delivery successful, so store the Agent's location in our local cache.
  265. lock (m_UserLocationMap)
  266. m_UserLocationMap[toAgentID] = url;
  267. return true;
  268. }
  269. else
  270. {
  271. // try again, but lookup user this time.
  272. // This is recursive!!!!!
  273. return TrySendInstantMessage(im, url, false, foreigner);
  274. }
  275. }
  276. private bool UndeliveredMessage(GridInstantMessage im)
  277. {
  278. if (m_OfflineIMService == null)
  279. return false;
  280. if (im.dialog != (byte)InstantMessageDialog.MessageFromObject &&
  281. im.dialog != (byte)InstantMessageDialog.MessageFromAgent &&
  282. im.dialog != (byte)InstantMessageDialog.GroupNotice &&
  283. im.dialog != (byte)InstantMessageDialog.GroupInvitation &&
  284. im.dialog != (byte)InstantMessageDialog.InventoryOffered)
  285. {
  286. return false;
  287. }
  288. if (!m_ForwardOfflineGroupMessages)
  289. {
  290. if (im.dialog == (byte)InstantMessageDialog.GroupNotice ||
  291. im.dialog == (byte)InstantMessageDialog.GroupInvitation)
  292. return false;
  293. }
  294. // m_log.DebugFormat("[HG IM SERVICE]: Message saved");
  295. string reason = string.Empty;
  296. return m_OfflineIMService.StoreMessage(im, out reason);
  297. }
  298. }
  299. }