HGInstantMessageService.cs 15 KB

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