MessageService.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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;
  29. using System.Collections.Generic;
  30. using System.Net;
  31. using System.Reflection;
  32. using System.Threading;
  33. using System.Timers;
  34. using log4net;
  35. using Nwc.XmlRpc;
  36. using OpenMetaverse;
  37. using OpenSim.Data;
  38. using OpenSim.Framework;
  39. using OpenSim.Grid.Framework;
  40. using Timer=System.Timers.Timer;
  41. namespace OpenSim.Grid.MessagingServer.Modules
  42. {
  43. public class MessageService
  44. {
  45. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  46. private MessageServerConfig m_cfg;
  47. private UserDataBaseService m_userDataBaseService;
  48. private IGridServiceCore m_messageCore;
  49. private IInterServiceUserService m_userServerModule;
  50. private IMessageRegionLookup m_regionModule;
  51. // a dictionary of all current presences this server knows about
  52. private Dictionary<UUID, UserPresenceData> m_presences = new Dictionary<UUID,UserPresenceData>();
  53. public MessageService(MessageServerConfig cfg, IGridServiceCore messageCore, UserDataBaseService userDataBaseService)
  54. {
  55. m_cfg = cfg;
  56. m_messageCore = messageCore;
  57. m_userDataBaseService = userDataBaseService;
  58. //???
  59. UserConfig uc = new UserConfig();
  60. uc.DatabaseConnect = cfg.DatabaseConnect;
  61. uc.DatabaseProvider = cfg.DatabaseProvider;
  62. }
  63. public void Initialise()
  64. {
  65. }
  66. public void PostInitialise()
  67. {
  68. IInterServiceUserService messageUserServer;
  69. if (m_messageCore.TryGet<IInterServiceUserService>(out messageUserServer))
  70. {
  71. m_userServerModule = messageUserServer;
  72. }
  73. IMessageRegionLookup messageRegion;
  74. if (m_messageCore.TryGet<IMessageRegionLookup>(out messageRegion))
  75. {
  76. m_regionModule = messageRegion;
  77. }
  78. }
  79. public void RegisterHandlers()
  80. {
  81. //have these in separate method as some servers restart the http server and reregister all the handlers.
  82. }
  83. #region FriendList Methods
  84. /// <summary>
  85. /// Process Friendlist subscriptions for a user
  86. /// The login method calls this for a User
  87. /// </summary>
  88. /// <param name="userpresence">The Agent we're processing the friendlist subscriptions for</param>
  89. private void ProcessFriendListSubscriptions(UserPresenceData userpresence)
  90. {
  91. lock (m_presences)
  92. {
  93. m_presences[userpresence.agentData.AgentID] = userpresence;
  94. }
  95. Dictionary<UUID, FriendListItem> uFriendList = userpresence.friendData;
  96. foreach (KeyValuePair<UUID, FriendListItem> pair in uFriendList)
  97. {
  98. UserPresenceData friendup = null;
  99. lock (m_presences)
  100. {
  101. m_presences.TryGetValue(pair.Key, out friendup);
  102. }
  103. if (friendup != null)
  104. {
  105. SubscribeToPresenceUpdates(userpresence, friendup, pair.Value);
  106. }
  107. }
  108. }
  109. /// <summary>
  110. /// Enqueues a presence update, sending info about user 'talkingAbout' to user 'receiver'.
  111. /// </summary>
  112. /// <param name="talkingAbout">We are sending presence information about this user.</param>
  113. /// <param name="receiver">We are sending the presence update to this user</param>
  114. private void enqueuePresenceUpdate(UserPresenceData talkingAbout, UserPresenceData receiver)
  115. {
  116. UserAgentData p2Handle = m_userDataBaseService.GetUserAgentData(receiver.agentData.AgentID);
  117. if (p2Handle != null)
  118. {
  119. if (receiver.lookupUserRegionYN)
  120. {
  121. receiver.regionData.regionHandle = p2Handle.Handle;
  122. }
  123. else
  124. {
  125. receiver.lookupUserRegionYN = true; // TODO Huh?
  126. }
  127. PresenceInformer friendlistupdater = new PresenceInformer();
  128. friendlistupdater.presence1 = talkingAbout;
  129. friendlistupdater.presence2 = receiver;
  130. friendlistupdater.OnGetRegionData += m_regionModule.GetRegionInfo;
  131. friendlistupdater.OnDone += PresenceUpdateDone;
  132. Util.FireAndForget(friendlistupdater.go);
  133. }
  134. else
  135. {
  136. m_log.WarnFormat("no data found for user {0}", receiver.agentData.AgentID);
  137. // Skip because we can't find any data on the user
  138. }
  139. }
  140. /// <summary>
  141. /// Does the necessary work to subscribe one agent to another's presence notifications
  142. /// Gets called by ProcessFriendListSubscriptions. You shouldn't call this directly
  143. /// unless you know what you're doing
  144. /// </summary>
  145. /// <param name="userpresence">P1</param>
  146. /// <param name="friendpresence">P2</param>
  147. /// <param name="uFriendListItem"></param>
  148. private void SubscribeToPresenceUpdates(UserPresenceData userpresence,
  149. UserPresenceData friendpresence,
  150. FriendListItem uFriendListItem)
  151. {
  152. // Can the friend see me online?
  153. if ((uFriendListItem.FriendListOwnerPerms & (uint)FriendRights.CanSeeOnline) != 0)
  154. {
  155. // tell user to update friend about user's presence changes
  156. if (!userpresence.subscriptionData.Contains(friendpresence.agentData.AgentID))
  157. {
  158. userpresence.subscriptionData.Add(friendpresence.agentData.AgentID);
  159. }
  160. // send an update about user's presence to the friend
  161. enqueuePresenceUpdate(userpresence, friendpresence);
  162. }
  163. // Can I see the friend online?
  164. if ((uFriendListItem.FriendPerms & (uint)FriendRights.CanSeeOnline) != 0)
  165. {
  166. // tell friend to update user about friend's presence changes
  167. if (!friendpresence.subscriptionData.Contains(userpresence.agentData.AgentID))
  168. {
  169. friendpresence.subscriptionData.Add(userpresence.agentData.AgentID);
  170. }
  171. // send an update about friend's presence to user.
  172. enqueuePresenceUpdate(friendpresence, userpresence);
  173. }
  174. }
  175. /// <summary>
  176. /// Logoff Processor. Call this to clean up agent presence data and send logoff presence notifications
  177. /// </summary>
  178. /// <param name="AgentID"></param>
  179. private void ProcessLogOff(UUID AgentID)
  180. {
  181. m_log.Info("[LOGOFF]: Processing Logoff");
  182. UserPresenceData userPresence = null;
  183. lock (m_presences)
  184. {
  185. m_presences.TryGetValue(AgentID, out userPresence);
  186. }
  187. if (userPresence != null) // found the user
  188. {
  189. List<UUID> AgentsNeedingNotification = userPresence.subscriptionData;
  190. userPresence.OnlineYN = false;
  191. for (int i = 0; i < AgentsNeedingNotification.Count; i++)
  192. {
  193. UserPresenceData friendPresence = null;
  194. lock (m_presences)
  195. {
  196. m_presences.TryGetValue(AgentsNeedingNotification[i], out friendPresence);
  197. }
  198. // This might need to be enumerated and checked before we try to remove it.
  199. if (friendPresence != null)
  200. {
  201. lock (friendPresence)
  202. {
  203. // no updates for this user anymore
  204. friendPresence.subscriptionData.Remove(AgentID);
  205. // set user's entry in the friend's list to offline (if it exists)
  206. if (friendPresence.friendData.ContainsKey(AgentID))
  207. {
  208. friendPresence.friendData[AgentID].onlinestatus = false;
  209. }
  210. }
  211. enqueuePresenceUpdate(userPresence, friendPresence);
  212. }
  213. }
  214. }
  215. }
  216. #endregion
  217. private void PresenceUpdateDone(PresenceInformer obj)
  218. {
  219. obj.OnGetRegionData -= m_regionModule.GetRegionInfo;
  220. obj.OnDone -= PresenceUpdateDone;
  221. }
  222. #region UserServer Comms
  223. /// <summary>
  224. /// Returns a list of FriendsListItems that describe the friends and permissions in the friend
  225. /// relationship for UUID friendslistowner. For faster lookup, we index by friend's UUID.
  226. /// </summary>
  227. /// <param name="friendlistowner">The agent that we're retreiving the friends Data for.</param>
  228. private Dictionary<UUID, FriendListItem> GetUserFriendList(UUID friendlistowner)
  229. {
  230. Dictionary<UUID, FriendListItem> buddies = new Dictionary<UUID,FriendListItem>();
  231. try
  232. {
  233. Hashtable param = new Hashtable();
  234. param["ownerID"] = friendlistowner.ToString();
  235. IList parameters = new ArrayList();
  236. parameters.Add(param);
  237. XmlRpcRequest req = new XmlRpcRequest("get_user_friend_list", parameters);
  238. XmlRpcResponse resp = req.Send(m_cfg.UserServerURL, 3000);
  239. Hashtable respData = (Hashtable)resp.Value;
  240. if (respData.Contains("avcount"))
  241. {
  242. buddies = ConvertXMLRPCDataToFriendListItemList(respData);
  243. }
  244. }
  245. catch (WebException e)
  246. {
  247. m_log.Warn("Error when trying to fetch Avatar's friends list: " +
  248. e.Message);
  249. // Return Empty list (no friends)
  250. }
  251. return buddies;
  252. }
  253. /// <summary>
  254. /// Converts XMLRPC Friend List to FriendListItem Object
  255. /// </summary>
  256. /// <param name="data">XMLRPC response data Hashtable</param>
  257. /// <returns></returns>
  258. public Dictionary<UUID, FriendListItem> ConvertXMLRPCDataToFriendListItemList(Hashtable data)
  259. {
  260. Dictionary<UUID, FriendListItem> buddies = new Dictionary<UUID,FriendListItem>();
  261. int buddycount = Convert.ToInt32((string)data["avcount"]);
  262. for (int i = 0; i < buddycount; i++)
  263. {
  264. FriendListItem buddylistitem = new FriendListItem();
  265. buddylistitem.FriendListOwner = new UUID((string)data["ownerID" + i.ToString()]);
  266. buddylistitem.Friend = new UUID((string)data["friendID" + i.ToString()]);
  267. buddylistitem.FriendListOwnerPerms = (uint)Convert.ToInt32((string)data["ownerPerms" + i.ToString()]);
  268. buddylistitem.FriendPerms = (uint)Convert.ToInt32((string)data["friendPerms" + i.ToString()]);
  269. buddies.Add(buddylistitem.Friend, buddylistitem);
  270. }
  271. return buddies;
  272. }
  273. /// <summary>
  274. /// UserServer sends an expect_user method
  275. /// this handles the method and provisions the
  276. /// necessary info for presence to work
  277. /// </summary>
  278. /// <param name="request">UserServer Data</param>
  279. /// <returns></returns>
  280. public XmlRpcResponse UserLoggedOn(XmlRpcRequest request, IPEndPoint remoteClient)
  281. {
  282. try
  283. {
  284. Hashtable requestData = (Hashtable)request.Params[0];
  285. AgentCircuitData agentData = new AgentCircuitData();
  286. agentData.SessionID = new UUID((string)requestData["sessionid"]);
  287. agentData.SecureSessionID = new UUID((string)requestData["secure_session_id"]);
  288. agentData.firstname = (string)requestData["firstname"];
  289. agentData.lastname = (string)requestData["lastname"];
  290. agentData.AgentID = new UUID((string)requestData["agentid"]);
  291. agentData.circuitcode = Convert.ToUInt32(requestData["circuit_code"]);
  292. agentData.CapsPath = (string)requestData["caps_path"];
  293. if (requestData.ContainsKey("child_agent") && requestData["child_agent"].Equals("1"))
  294. {
  295. agentData.child = true;
  296. }
  297. else
  298. {
  299. agentData.startpos =
  300. new Vector3(Convert.ToSingle(requestData["positionx"]),
  301. Convert.ToSingle(requestData["positiony"]),
  302. Convert.ToSingle(requestData["positionz"]));
  303. agentData.child = false;
  304. }
  305. ulong regionHandle = Convert.ToUInt64((string)requestData["regionhandle"]);
  306. m_log.InfoFormat("[LOGON]: User {0} {1} logged into region {2} as {3} agent, building indexes for user",
  307. agentData.firstname, agentData.lastname, regionHandle, agentData.child ? "child" : "root");
  308. UserPresenceData up = new UserPresenceData();
  309. up.agentData = agentData;
  310. up.friendData = GetUserFriendList(agentData.AgentID);
  311. up.regionData = m_regionModule.GetRegionInfo(regionHandle);
  312. up.OnlineYN = true;
  313. up.lookupUserRegionYN = false;
  314. ProcessFriendListSubscriptions(up);
  315. }
  316. catch (Exception e)
  317. {
  318. m_log.WarnFormat("[LOGIN]: Exception on UserLoggedOn: {0}", e);
  319. }
  320. return new XmlRpcResponse();
  321. }
  322. /// <summary>
  323. /// The UserServer got a Logoff message
  324. /// Cleanup time for that user. Send out presence notifications
  325. /// </summary>
  326. /// <param name="request"></param>
  327. /// <returns></returns>
  328. public XmlRpcResponse UserLoggedOff(XmlRpcRequest request, IPEndPoint remoteClient)
  329. {
  330. try
  331. {
  332. m_log.Info("[USERLOGOFF]: User logged off called");
  333. Hashtable requestData = (Hashtable)request.Params[0];
  334. UUID AgentID = new UUID((string)requestData["agentid"]);
  335. ProcessLogOff(AgentID);
  336. }
  337. catch (Exception e)
  338. {
  339. m_log.WarnFormat("[USERLOGOFF]: Exception on UserLoggedOff: {0}", e);
  340. }
  341. return new XmlRpcResponse();
  342. }
  343. #endregion
  344. public XmlRpcResponse GetPresenceInfoBulk(XmlRpcRequest request, IPEndPoint remoteClient)
  345. {
  346. Hashtable paramHash = (Hashtable)request.Params[0];
  347. Hashtable result = new Hashtable();
  348. // TODO check access (recv_key/send_key)
  349. IList list = (IList)paramHash["uuids"];
  350. // convert into List<UUID>
  351. List<UUID> uuids = new List<UUID>();
  352. for (int i = 0; i < list.Count; ++i)
  353. {
  354. UUID uuid;
  355. if (UUID.TryParse((string)list[i], out uuid))
  356. {
  357. uuids.Add(uuid);
  358. }
  359. }
  360. try {
  361. Dictionary<UUID, FriendRegionInfo> infos = m_userDataBaseService.GetFriendRegionInfos(uuids);
  362. m_log.DebugFormat("[FRIEND]: Got {0} region entries back.", infos.Count);
  363. int count = 0;
  364. foreach (KeyValuePair<UUID, FriendRegionInfo> pair in infos)
  365. {
  366. result["uuid_" + count] = pair.Key.ToString();
  367. result["isOnline_" + count] = pair.Value.isOnline;
  368. result["regionHandle_" + count] = pair.Value.regionHandle.ToString(); // XML-RPC doesn't know ulongs
  369. ++count;
  370. }
  371. result["count"] = count;
  372. XmlRpcResponse response = new XmlRpcResponse();
  373. response.Value = result;
  374. return response;
  375. }
  376. catch(Exception e) {
  377. m_log.Error("Got exception:", e);
  378. throw e;
  379. }
  380. }
  381. public XmlRpcResponse AgentLocation(XmlRpcRequest request, IPEndPoint remoteClient)
  382. {
  383. Hashtable requestData = (Hashtable)request.Params[0];
  384. Hashtable result = new Hashtable();
  385. result["success"] = "FALSE";
  386. if (m_userServerModule.SendToUserServer(requestData, "agent_location"))
  387. result["success"] = "TRUE";
  388. XmlRpcResponse response = new XmlRpcResponse();
  389. response.Value = result;
  390. return response;
  391. }
  392. public XmlRpcResponse AgentLeaving(XmlRpcRequest request, IPEndPoint remoteClient)
  393. {
  394. Hashtable requestData = (Hashtable)request.Params[0];
  395. Hashtable result = new Hashtable();
  396. result["success"] = "FALSE";
  397. if (m_userServerModule.SendToUserServer(requestData, "agent_leaving"))
  398. result["success"] = "TRUE";
  399. XmlRpcResponse response = new XmlRpcResponse();
  400. response.Value = result;
  401. return response;
  402. }
  403. public XmlRpcResponse ProcessRegionShutdown(XmlRpcRequest request, IPEndPoint remoteClient)
  404. {
  405. Hashtable requestData = (Hashtable)request.Params[0];
  406. Hashtable result = new Hashtable();
  407. result["success"] = "FALSE";
  408. UUID regionID;
  409. if (UUID.TryParse((string)requestData["regionid"], out regionID))
  410. {
  411. m_log.DebugFormat("[PRESENCE] Processing region restart for {0}", regionID);
  412. result["success"] = "TRUE";
  413. foreach (UserPresenceData up in m_presences.Values)
  414. {
  415. if (up.regionData.UUID == regionID)
  416. {
  417. if (up.OnlineYN)
  418. {
  419. m_log.DebugFormat("[PRESENCE] Logging off {0} because the region they were in has gone", up.agentData.AgentID);
  420. ProcessLogOff(up.agentData.AgentID);
  421. }
  422. }
  423. }
  424. }
  425. XmlRpcResponse response = new XmlRpcResponse();
  426. response.Value = result;
  427. return response;
  428. }
  429. }
  430. }