PresenceModule.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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.Collections;
  28. using System.Collections.Generic;
  29. using System.Net;
  30. using System.Reflection;
  31. using log4net;
  32. using Nini.Config;
  33. using Nwc.XmlRpc;
  34. using OpenMetaverse;
  35. using OpenSim.Framework;
  36. using OpenSim.Region.Framework.Interfaces;
  37. using OpenSim.Region.Framework.Scenes;
  38. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  39. namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
  40. {
  41. public class PresenceModule : IRegionModule, IPresenceModule
  42. {
  43. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  44. private bool m_Enabled = false;
  45. private bool m_Gridmode = false;
  46. // some default scene for doing things that aren't connected to a specific scene. Avoids locking.
  47. private Scene m_initialScene;
  48. private List<Scene> m_Scenes = new List<Scene>();
  49. // we currently are only interested in root-agents. If the root isn't here, we don't know the region the
  50. // user is in, so we have to ask the messaging server anyway.
  51. private Dictionary<UUID, Scene> m_RootAgents =
  52. new Dictionary<UUID, Scene>();
  53. public event PresenceChange OnPresenceChange;
  54. public event BulkPresenceData OnBulkPresenceData;
  55. public void Initialise(Scene scene, IConfigSource config)
  56. {
  57. lock (m_Scenes)
  58. {
  59. // This is a shared module; Initialise will be called for every region on this server.
  60. // Only check config once for the first region.
  61. if (m_Scenes.Count == 0)
  62. {
  63. IConfig cnf = config.Configs["Messaging"];
  64. if (cnf != null && cnf.GetString(
  65. "PresenceModule", "PresenceModule") !=
  66. "PresenceModule")
  67. return;
  68. cnf = config.Configs["Startup"];
  69. if (cnf != null)
  70. m_Gridmode = cnf.GetBoolean("gridmode", false);
  71. m_Enabled = true;
  72. m_initialScene = scene;
  73. }
  74. if (m_Gridmode)
  75. NotifyMessageServerOfStartup(scene);
  76. m_Scenes.Add(scene);
  77. }
  78. scene.RegisterModuleInterface<IPresenceModule>(this);
  79. scene.EventManager.OnNewClient += OnNewClient;
  80. scene.EventManager.OnSetRootAgentScene += OnSetRootAgentScene;
  81. scene.EventManager.OnMakeChildAgent += OnMakeChildAgent;
  82. }
  83. public void PostInitialise()
  84. {
  85. }
  86. public void Close()
  87. {
  88. if (!m_Gridmode || !m_Enabled)
  89. return;
  90. if (OnPresenceChange != null)
  91. {
  92. lock (m_RootAgents)
  93. {
  94. // on shutdown, users are kicked, too
  95. foreach (KeyValuePair<UUID, Scene> pair in m_RootAgents)
  96. {
  97. OnPresenceChange(new PresenceInfo(pair.Key, UUID.Zero));
  98. }
  99. }
  100. }
  101. lock (m_Scenes)
  102. {
  103. foreach (Scene scene in m_Scenes)
  104. NotifyMessageServerOfShutdown(scene);
  105. }
  106. }
  107. public string Name
  108. {
  109. get { return "PresenceModule"; }
  110. }
  111. public bool IsSharedModule
  112. {
  113. get { return true; }
  114. }
  115. public void RequestBulkPresenceData(UUID[] users)
  116. {
  117. if (OnBulkPresenceData != null)
  118. {
  119. PresenceInfo[] result = new PresenceInfo[users.Length];
  120. if (m_Gridmode)
  121. {
  122. // first check the local information
  123. List<UUID> uuids = new List<UUID>(); // the uuids to check remotely
  124. List<int> indices = new List<int>(); // just for performance.
  125. lock (m_RootAgents)
  126. {
  127. for (int i = 0; i < uuids.Count; ++i)
  128. {
  129. Scene scene;
  130. if (m_RootAgents.TryGetValue(users[i], out scene))
  131. {
  132. result[i] = new PresenceInfo(users[i], scene.RegionInfo.RegionID);
  133. }
  134. else
  135. {
  136. uuids.Add(users[i]);
  137. indices.Add(i);
  138. }
  139. }
  140. }
  141. // now we have filtered out all the local root agents. The rest we have to request info about
  142. Dictionary<UUID, FriendRegionInfo> infos = m_initialScene.GetFriendRegionInfos(uuids);
  143. for (int i = 0; i < uuids.Count; ++i)
  144. {
  145. FriendRegionInfo info;
  146. if (infos.TryGetValue(uuids[i], out info) && info.isOnline)
  147. {
  148. UUID regionID = info.regionID;
  149. if (regionID == UUID.Zero)
  150. {
  151. // TODO this is the old messaging-server protocol; only the regionHandle is available.
  152. // Fetch region-info to get the id
  153. uint x = 0, y = 0;
  154. Utils.LongToUInts(info.regionHandle, out x, out y);
  155. GridRegion regionInfo = m_initialScene.GridService.GetRegionByPosition(m_initialScene.RegionInfo.ScopeID,
  156. (int)x, (int)y);
  157. regionID = regionInfo.RegionID;
  158. }
  159. result[indices[i]] = new PresenceInfo(uuids[i], regionID);
  160. }
  161. else result[indices[i]] = new PresenceInfo(uuids[i], UUID.Zero);
  162. }
  163. }
  164. else
  165. {
  166. // in standalone mode, we have all the info locally available.
  167. lock (m_RootAgents)
  168. {
  169. for (int i = 0; i < users.Length; ++i)
  170. {
  171. Scene scene;
  172. if (m_RootAgents.TryGetValue(users[i], out scene))
  173. {
  174. result[i] = new PresenceInfo(users[i], scene.RegionInfo.RegionID);
  175. }
  176. else
  177. {
  178. result[i] = new PresenceInfo(users[i], UUID.Zero);
  179. }
  180. }
  181. }
  182. }
  183. // tell everyone
  184. OnBulkPresenceData(result);
  185. }
  186. }
  187. // new client doesn't mean necessarily that user logged in, it just means it entered one of the
  188. // the regions on this server
  189. public void OnNewClient(IClientAPI client)
  190. {
  191. client.OnConnectionClosed += OnConnectionClosed;
  192. client.OnLogout += OnLogout;
  193. // KLUDGE: See handler for details.
  194. client.OnEconomyDataRequest += OnEconomyDataRequest;
  195. }
  196. // connection closed just means *one* client connection has been closed. It doesn't mean that the
  197. // user has logged off; it might have just TPed away.
  198. public void OnConnectionClosed(IClientAPI client)
  199. {
  200. // TODO: Have to think what we have to do here...
  201. // Should we just remove the root from the list (if scene matches)?
  202. if (!(client.Scene is Scene))
  203. return;
  204. Scene scene = (Scene)client.Scene;
  205. lock (m_RootAgents)
  206. {
  207. Scene rootScene;
  208. if (!(m_RootAgents.TryGetValue(client.AgentId, out rootScene)) || scene != rootScene)
  209. return;
  210. m_RootAgents.Remove(client.AgentId);
  211. }
  212. // Should it have logged off, we'll do the logout part in OnLogout, even if no root is stored
  213. // anymore. It logged off, after all...
  214. }
  215. // Triggered when the user logs off.
  216. public void OnLogout(IClientAPI client)
  217. {
  218. if (!(client.Scene is Scene))
  219. return;
  220. Scene scene = (Scene)client.Scene;
  221. // On logout, we really remove the client from rootAgents, even if the scene doesn't match
  222. lock (m_RootAgents)
  223. {
  224. if (m_RootAgents.ContainsKey(client.AgentId)) m_RootAgents.Remove(client.AgentId);
  225. }
  226. // now inform the messaging server and anyone who is interested
  227. NotifyMessageServerOfAgentLeaving(client.AgentId, scene.RegionInfo.RegionID, scene.RegionInfo.RegionHandle);
  228. if (OnPresenceChange != null) OnPresenceChange(new PresenceInfo(client.AgentId, UUID.Zero));
  229. }
  230. public void OnSetRootAgentScene(UUID agentID, Scene scene)
  231. {
  232. // OnSetRootAgentScene can be called from several threads at once (with different agentID).
  233. // Concurrent access to m_RootAgents is prone to failure on multi-core/-processor systems without
  234. // correct locking).
  235. lock (m_RootAgents)
  236. {
  237. Scene rootScene;
  238. if (m_RootAgents.TryGetValue(agentID, out rootScene) && scene == rootScene)
  239. {
  240. return;
  241. }
  242. m_RootAgents[agentID] = scene;
  243. }
  244. // inform messaging server that agent changed the region
  245. Util.FireAndForget(
  246. delegate(object o)
  247. {
  248. NotifyMessageServerOfAgentLocation(agentID, scene.RegionInfo.RegionID, scene.RegionInfo.RegionHandle);
  249. }
  250. );
  251. }
  252. private void OnEconomyDataRequest(UUID agentID)
  253. {
  254. // KLUDGE: This is the only way I found to get a message (only) after login was completed and the
  255. // client is connected enough to receive UDP packets.
  256. // This packet seems to be sent only once, just after connection was established to the first
  257. // region after login.
  258. // We use it here to trigger a presence update; the old update-on-login was never be heard by
  259. // the freshly logged in viewer, as it wasn't connected to the region at that time.
  260. // TODO: Feel free to replace this by a better solution if you find one.
  261. // get the agent. This should work every time, as we just got a packet from it
  262. ScenePresence agent = null;
  263. lock (m_Scenes)
  264. {
  265. foreach (Scene scene in m_Scenes)
  266. {
  267. agent = scene.GetScenePresence(agentID);
  268. if (agent != null) break;
  269. }
  270. }
  271. // just to be paranoid...
  272. if (agent == null)
  273. {
  274. m_log.ErrorFormat("[PRESENCE]: Got a packet from agent {0} who can't be found anymore!?", agentID);
  275. return;
  276. }
  277. // we are a bit premature here, but the next packet will switch this child agent to root.
  278. if (OnPresenceChange != null) OnPresenceChange(new PresenceInfo(agentID, agent.Scene.RegionInfo.RegionID));
  279. }
  280. public void OnMakeChildAgent(ScenePresence agent)
  281. {
  282. // OnMakeChildAgent can be called from several threads at once (with different agent).
  283. // Concurrent access to m_RootAgents is prone to failure on multi-core/-processor systems without
  284. // correct locking).
  285. lock (m_RootAgents)
  286. {
  287. Scene rootScene;
  288. if (m_RootAgents.TryGetValue(agent.UUID, out rootScene) && agent.Scene == rootScene)
  289. {
  290. m_RootAgents.Remove(agent.UUID);
  291. }
  292. }
  293. // don't notify the messaging-server; either this agent just had been downgraded and another one will be upgraded
  294. // to root momentarily (which will notify the messaging-server), or possibly it will be closed in a moment,
  295. // which will update the messaging-server, too.
  296. }
  297. private void NotifyMessageServerOfStartup(Scene scene)
  298. {
  299. Hashtable xmlrpcdata = new Hashtable();
  300. xmlrpcdata["RegionUUID"] = scene.RegionInfo.RegionID.ToString();
  301. ArrayList SendParams = new ArrayList();
  302. SendParams.Add(xmlrpcdata);
  303. try
  304. {
  305. XmlRpcRequest UpRequest = new XmlRpcRequest("region_startup", SendParams);
  306. XmlRpcResponse resp = UpRequest.Send(scene.CommsManager.NetworkServersInfo.MessagingURL, 5000);
  307. Hashtable responseData = (Hashtable)resp.Value;
  308. if (responseData == null || (!responseData.ContainsKey("success")) || (string)responseData["success"] != "TRUE")
  309. {
  310. m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of region startup for region {0}", scene.RegionInfo.RegionName);
  311. }
  312. }
  313. catch (WebException)
  314. {
  315. m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of region startup for region {0}", scene.RegionInfo.RegionName);
  316. }
  317. }
  318. private void NotifyMessageServerOfShutdown(Scene scene)
  319. {
  320. if (m_Scenes[0].CommsManager.NetworkServersInfo.MessagingURL == string.Empty)
  321. return;
  322. Hashtable xmlrpcdata = new Hashtable();
  323. xmlrpcdata["RegionUUID"] = scene.RegionInfo.RegionID.ToString();
  324. ArrayList SendParams = new ArrayList();
  325. SendParams.Add(xmlrpcdata);
  326. try
  327. {
  328. XmlRpcRequest DownRequest = new XmlRpcRequest("region_shutdown", SendParams);
  329. XmlRpcResponse resp = DownRequest.Send(scene.CommsManager.NetworkServersInfo.MessagingURL, 5000);
  330. Hashtable responseData = (Hashtable)resp.Value;
  331. if ((!responseData.ContainsKey("success")) || (string)responseData["success"] != "TRUE")
  332. {
  333. m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of region shutdown for region {0}", scene.RegionInfo.RegionName);
  334. }
  335. }
  336. catch (WebException)
  337. {
  338. m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of region shutdown for region {0}", scene.RegionInfo.RegionName);
  339. }
  340. }
  341. private void NotifyMessageServerOfAgentLocation(UUID agentID, UUID region, ulong regionHandle)
  342. {
  343. if (m_Scenes[0].CommsManager.NetworkServersInfo.MessagingURL == string.Empty)
  344. return;
  345. Hashtable xmlrpcdata = new Hashtable();
  346. xmlrpcdata["AgentID"] = agentID.ToString();
  347. xmlrpcdata["RegionUUID"] = region.ToString();
  348. xmlrpcdata["RegionHandle"] = regionHandle.ToString();
  349. ArrayList SendParams = new ArrayList();
  350. SendParams.Add(xmlrpcdata);
  351. try
  352. {
  353. XmlRpcRequest LocationRequest = new XmlRpcRequest("agent_location", SendParams);
  354. XmlRpcResponse resp = LocationRequest.Send(m_Scenes[0].CommsManager.NetworkServersInfo.MessagingURL, 5000);
  355. Hashtable responseData = (Hashtable)resp.Value;
  356. if ((!responseData.ContainsKey("success")) || (string)responseData["success"] != "TRUE")
  357. {
  358. m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of agent location for {0}", agentID.ToString());
  359. }
  360. }
  361. catch (WebException)
  362. {
  363. m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of agent location for {0}", agentID.ToString());
  364. }
  365. }
  366. private void NotifyMessageServerOfAgentLeaving(UUID agentID, UUID region, ulong regionHandle)
  367. {
  368. if (m_Scenes[0].CommsManager.NetworkServersInfo.MessagingURL == string.Empty)
  369. return;
  370. Hashtable xmlrpcdata = new Hashtable();
  371. xmlrpcdata["AgentID"] = agentID.ToString();
  372. xmlrpcdata["RegionUUID"] = region.ToString();
  373. xmlrpcdata["RegionHandle"] = regionHandle.ToString();
  374. ArrayList SendParams = new ArrayList();
  375. SendParams.Add(xmlrpcdata);
  376. try
  377. {
  378. XmlRpcRequest LeavingRequest = new XmlRpcRequest("agent_leaving", SendParams);
  379. XmlRpcResponse resp = LeavingRequest.Send(m_Scenes[0].CommsManager.NetworkServersInfo.MessagingURL, 5000);
  380. Hashtable responseData = (Hashtable)resp.Value;
  381. if ((!responseData.ContainsKey("success")) || (string)responseData["success"] != "TRUE")
  382. {
  383. m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of agent leaving for {0}", agentID.ToString());
  384. }
  385. }
  386. catch (WebException)
  387. {
  388. m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of agent leaving for {0}", agentID.ToString());
  389. }
  390. }
  391. }
  392. }