HGInstantMessageService.cs 15 KB

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