PresenceModule.cs 18 KB

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