PresenceModule.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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 OpenSim 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;
  29. using System.Collections.Generic;
  30. using System.Reflection;
  31. using System.Net;
  32. using System.Threading;
  33. using OpenMetaverse;
  34. using log4net;
  35. using Nini.Config;
  36. using Nwc.XmlRpc;
  37. using OpenSim.Framework;
  38. using OpenSim.Framework.Client;
  39. using OpenSim.Region.Interfaces;
  40. using OpenSim.Region.Environment.Interfaces;
  41. using OpenSim.Region.Environment.Scenes;
  42. namespace OpenSim.Region.Environment.Modules.Avatar.InstantMessage
  43. {
  44. public class PresenceModule : IRegionModule, IPresenceModule
  45. {
  46. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  47. private bool m_Enabled = false;
  48. private bool m_Gridmode = false;
  49. // some default scene for doing things that aren't connected to a specific scene. Avoids locking.
  50. private Scene m_initialScene;
  51. private List<Scene> m_Scenes = new List<Scene>();
  52. // we currently are only interested in root-agents. If the root isn't here, we don't know the region the
  53. // user is in, so we have to ask the messaging server anyway.
  54. private Dictionary<UUID, Scene> m_RootAgents =
  55. new Dictionary<UUID, Scene>();
  56. public event PresenceChange OnPresenceChange;
  57. public event BulkPresenceData OnBulkPresenceData;
  58. public void Initialise(Scene scene, IConfigSource config)
  59. {
  60. lock (m_Scenes)
  61. {
  62. // This is a shared module; Initialise will be called for every region on this server.
  63. // Only check config once for the first region.
  64. if (m_Scenes.Count == 0)
  65. {
  66. IConfig cnf = config.Configs["Messaging"];
  67. if (cnf != null && cnf.GetString(
  68. "PresenceModule", "PresenceModule") !=
  69. "PresenceModule")
  70. return;
  71. cnf = config.Configs["Startup"];
  72. if (cnf != null)
  73. m_Gridmode = cnf.GetBoolean("gridmode", false);
  74. m_Enabled = true;
  75. m_initialScene = scene;
  76. }
  77. if (m_Gridmode)
  78. NotifyMessageServerOfStartup(scene);
  79. m_Scenes.Add(scene);
  80. }
  81. scene.RegisterModuleInterface<IPresenceModule>(this);
  82. scene.EventManager.OnNewClient += OnNewClient;
  83. scene.EventManager.OnSetRootAgentScene += OnSetRootAgentScene;
  84. scene.EventManager.OnMakeChildAgent += OnMakeChildAgent;
  85. }
  86. public void PostInitialise()
  87. {
  88. }
  89. public void Close()
  90. {
  91. if (!m_Gridmode || !m_Enabled)
  92. return;
  93. if (OnPresenceChange != null)
  94. {
  95. lock (m_RootAgents)
  96. {
  97. // on shutdown, users are kicked, too
  98. foreach (KeyValuePair<UUID, Scene> pair in m_RootAgents)
  99. {
  100. OnPresenceChange(new PresenceInfo(pair.Key, UUID.Zero));
  101. }
  102. }
  103. }
  104. lock (m_Scenes)
  105. {
  106. foreach (Scene scene in m_Scenes)
  107. NotifyMessageServerOfShutdown(scene);
  108. }
  109. }
  110. public string Name
  111. {
  112. get { return "PresenceModule"; }
  113. }
  114. public bool IsSharedModule
  115. {
  116. get { return true; }
  117. }
  118. public void RequestBulkPresenceData(UUID[] users)
  119. {
  120. if (OnBulkPresenceData != null)
  121. {
  122. PresenceInfo[] result = new PresenceInfo[users.Length];
  123. if (m_Gridmode)
  124. {
  125. // first check the local information
  126. List<UUID> uuids = new List<UUID>(); // the uuids to check remotely
  127. List<int> indices = new List<int>(); // just for performance.
  128. lock (m_RootAgents)
  129. {
  130. for (int i = 0; i < uuids.Count; ++i)
  131. {
  132. Scene scene;
  133. if (m_RootAgents.TryGetValue(users[i], out scene))
  134. {
  135. result[i] = new PresenceInfo(users[i], scene.RegionInfo.RegionID);
  136. }
  137. else
  138. {
  139. uuids.Add(users[i]);
  140. indices.Add(i);
  141. }
  142. }
  143. }
  144. // now we have filtered out all the local root agents. The rest we have to request info about
  145. Dictionary<UUID, FriendRegionInfo> infos = m_initialScene.GetFriendRegionInfos(uuids);
  146. for (int i = 0; i < uuids.Count; ++i)
  147. {
  148. FriendRegionInfo info;
  149. if (infos.TryGetValue(uuids[i], out info) && info.isOnline)
  150. {
  151. UUID regionID = info.regionID;
  152. if (regionID == UUID.Zero)
  153. {
  154. // TODO this is the old messaging-server protocol; only the regionHandle is available.
  155. // Fetch region-info to get the id
  156. RegionInfo regionInfo = m_initialScene.RequestNeighbouringRegionInfo(info.regionHandle);
  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. NotifyMessageServerOfAgentLocation(agentID, scene.RegionInfo.RegionID, scene.RegionInfo.RegionHandle);
  246. }
  247. private void OnEconomyDataRequest(UUID agentID)
  248. {
  249. // KLUDGE: This is the only way I found to get a message (only) after login was completed and the
  250. // client is connected enough to receive UDP packets.
  251. // This packet seems to be sent only once, just after connection was established to the first
  252. // region after login.
  253. // We use it here to trigger a presence update; the old update-on-login was never be heard by
  254. // the freshly logged in viewer, as it wasn't connected to the region at that time.
  255. // TODO: Feel free to replace this by a better solution if you find one.
  256. // get the agent. This should work every time, as we just got a packet from it
  257. ScenePresence agent = null;
  258. lock (m_Scenes)
  259. {
  260. foreach (Scene scene in m_Scenes)
  261. {
  262. agent = scene.GetScenePresence(agentID);
  263. if (agent != null) break;
  264. }
  265. }
  266. // just to be paranoid...
  267. if (agent == null)
  268. {
  269. m_log.ErrorFormat("[PRESENCE]: Got a packet from agent {0} who can't be found anymore!?", agentID);
  270. return;
  271. }
  272. // we are a bit premature here, but the next packet will switch this child agent to root.
  273. if (OnPresenceChange != null) OnPresenceChange(new PresenceInfo(agentID, agent.Scene.RegionInfo.RegionID));
  274. }
  275. public void OnMakeChildAgent(ScenePresence agent)
  276. {
  277. // OnMakeChildAgent can be called from several threads at once (with different agent).
  278. // Concurrent access to m_RootAgents is prone to failure on multi-core/-processor systems without
  279. // correct locking).
  280. lock (m_RootAgents)
  281. {
  282. Scene rootScene;
  283. if (m_RootAgents.TryGetValue(agent.UUID, out rootScene) && agent.Scene == rootScene)
  284. {
  285. m_RootAgents.Remove(agent.UUID);
  286. }
  287. }
  288. // don't notify the messaging-server; either this agent just had been downgraded and another one will be upgraded
  289. // to root momentarily (which will notify the messaging-server), or possibly it will be closed in a moment,
  290. // which will update the messaging-server, too.
  291. }
  292. private void NotifyMessageServerOfStartup(Scene scene)
  293. {
  294. Hashtable xmlrpcdata = new Hashtable();
  295. xmlrpcdata["RegionUUID"] = scene.RegionInfo.RegionID.ToString();
  296. ArrayList SendParams = new ArrayList();
  297. SendParams.Add(xmlrpcdata);
  298. try
  299. {
  300. XmlRpcRequest UpRequest = new XmlRpcRequest("region_startup", SendParams);
  301. XmlRpcResponse resp = UpRequest.Send(scene.CommsManager.NetworkServersInfo.MessagingURL, 5000);
  302. Hashtable responseData = (Hashtable)resp.Value;
  303. if (responseData == null || (!responseData.ContainsKey("success")) || (string)responseData["success"] != "TRUE")
  304. {
  305. m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of region startup for region {0}", scene.RegionInfo.RegionName);
  306. }
  307. }
  308. catch (System.Net.WebException)
  309. {
  310. m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of region startup for region {0}", scene.RegionInfo.RegionName);
  311. }
  312. }
  313. private void NotifyMessageServerOfShutdown(Scene scene)
  314. {
  315. Hashtable xmlrpcdata = new Hashtable();
  316. xmlrpcdata["RegionUUID"] = scene.RegionInfo.RegionID.ToString();
  317. ArrayList SendParams = new ArrayList();
  318. SendParams.Add(xmlrpcdata);
  319. try
  320. {
  321. XmlRpcRequest DownRequest = new XmlRpcRequest("region_shutdown", SendParams);
  322. XmlRpcResponse resp = DownRequest.Send(scene.CommsManager.NetworkServersInfo.MessagingURL, 5000);
  323. Hashtable responseData = (Hashtable)resp.Value;
  324. if ((!responseData.ContainsKey("success")) || (string)responseData["success"] != "TRUE")
  325. {
  326. m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of region shutdown for region {0}", scene.RegionInfo.RegionName);
  327. }
  328. }
  329. catch (System.Net.WebException)
  330. {
  331. m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of region shutdown for region {0}", scene.RegionInfo.RegionName);
  332. }
  333. }
  334. private void NotifyMessageServerOfAgentLocation(UUID agentID, UUID region, ulong regionHandle)
  335. {
  336. Hashtable xmlrpcdata = new Hashtable();
  337. xmlrpcdata["AgentID"] = agentID.ToString();
  338. xmlrpcdata["RegionUUID"] = region.ToString();
  339. xmlrpcdata["RegionHandle"] = regionHandle.ToString();
  340. ArrayList SendParams = new ArrayList();
  341. SendParams.Add(xmlrpcdata);
  342. try
  343. {
  344. XmlRpcRequest LocationRequest = new XmlRpcRequest("agent_location", SendParams);
  345. XmlRpcResponse resp = LocationRequest.Send(m_Scenes[0].CommsManager.NetworkServersInfo.MessagingURL, 5000);
  346. Hashtable responseData = (Hashtable)resp.Value;
  347. if ((!responseData.ContainsKey("success")) || (string)responseData["success"] != "TRUE")
  348. {
  349. m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of agent location for {0}", agentID.ToString());
  350. }
  351. }
  352. catch (System.Net.WebException)
  353. {
  354. m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of agent location for {0}", agentID.ToString());
  355. }
  356. }
  357. private void NotifyMessageServerOfAgentLeaving(UUID agentID, UUID region, ulong regionHandle)
  358. {
  359. Hashtable xmlrpcdata = new Hashtable();
  360. xmlrpcdata["AgentID"] = agentID.ToString();
  361. xmlrpcdata["RegionUUID"] = region.ToString();
  362. xmlrpcdata["RegionHandle"] = regionHandle.ToString();
  363. ArrayList SendParams = new ArrayList();
  364. SendParams.Add(xmlrpcdata);
  365. try
  366. {
  367. XmlRpcRequest LeavingRequest = new XmlRpcRequest("agent_leaving", SendParams);
  368. XmlRpcResponse resp = LeavingRequest.Send(m_Scenes[0].CommsManager.NetworkServersInfo.MessagingURL, 5000);
  369. Hashtable responseData = (Hashtable)resp.Value;
  370. if ((!responseData.ContainsKey("success")) || (string)responseData["success"] != "TRUE")
  371. {
  372. m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of agent leaving for {0}", agentID.ToString());
  373. }
  374. }
  375. catch (System.Net.WebException)
  376. {
  377. m_log.ErrorFormat("[PRESENCE]: Failed to notify message server of agent leaving for {0}", agentID.ToString());
  378. }
  379. }
  380. }
  381. }