MessageService.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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. WaitCallback cb = new WaitCallback(friendlistupdater.go);
  133. ThreadPool.QueueUserWorkItem(cb);
  134. }
  135. else
  136. {
  137. m_log.WarnFormat("no data found for user {0}", receiver.agentData.AgentID);
  138. // Skip because we can't find any data on the user
  139. }
  140. }
  141. /// <summary>
  142. /// Does the necessary work to subscribe one agent to another's presence notifications
  143. /// Gets called by ProcessFriendListSubscriptions. You shouldn't call this directly
  144. /// unless you know what you're doing
  145. /// </summary>
  146. /// <param name="userpresence">P1</param>
  147. /// <param name="friendpresence">P2</param>
  148. /// <param name="uFriendListItem"></param>
  149. private void SubscribeToPresenceUpdates(UserPresenceData userpresence,
  150. UserPresenceData friendpresence,
  151. FriendListItem uFriendListItem)
  152. {
  153. // Can the friend see me online?
  154. if ((uFriendListItem.FriendListOwnerPerms & (uint)FriendRights.CanSeeOnline) != 0)
  155. {
  156. // tell user to update friend about user's presence changes
  157. if (!userpresence.subscriptionData.Contains(friendpresence.agentData.AgentID))
  158. {
  159. userpresence.subscriptionData.Add(friendpresence.agentData.AgentID);
  160. }
  161. // send an update about user's presence to the friend
  162. enqueuePresenceUpdate(userpresence, friendpresence);
  163. }
  164. // Can I see the friend online?
  165. if ((uFriendListItem.FriendPerms & (uint)FriendRights.CanSeeOnline) != 0)
  166. {
  167. // tell friend to update user about friend's presence changes
  168. if (!friendpresence.subscriptionData.Contains(userpresence.agentData.AgentID))
  169. {
  170. friendpresence.subscriptionData.Add(userpresence.agentData.AgentID);
  171. }
  172. // send an update about friend's presence to user.
  173. enqueuePresenceUpdate(friendpresence, userpresence);
  174. }
  175. }
  176. /// <summary>
  177. /// Logoff Processor. Call this to clean up agent presence data and send logoff presence notifications
  178. /// </summary>
  179. /// <param name="AgentID"></param>
  180. private void ProcessLogOff(UUID AgentID)
  181. {
  182. m_log.Info("[LOGOFF]: Processing Logoff");
  183. UserPresenceData userPresence = null;
  184. lock (m_presences)
  185. {
  186. m_presences.TryGetValue(AgentID, out userPresence);
  187. }
  188. if (userPresence != null) // found the user
  189. {
  190. List<UUID> AgentsNeedingNotification = userPresence.subscriptionData;
  191. userPresence.OnlineYN = false;
  192. for (int i = 0; i < AgentsNeedingNotification.Count; i++)
  193. {
  194. UserPresenceData friendPresence = null;
  195. lock (m_presences)
  196. {
  197. m_presences.TryGetValue(AgentsNeedingNotification[i], out friendPresence);
  198. }
  199. // This might need to be enumerated and checked before we try to remove it.
  200. if (friendPresence != null)
  201. {
  202. lock (friendPresence)
  203. {
  204. // no updates for this user anymore
  205. friendPresence.subscriptionData.Remove(AgentID);
  206. // set user's entry in the friend's list to offline (if it exists)
  207. if (friendPresence.friendData.ContainsKey(AgentID))
  208. {
  209. friendPresence.friendData[AgentID].onlinestatus = false;
  210. }
  211. }
  212. enqueuePresenceUpdate(userPresence, friendPresence);
  213. }
  214. }
  215. }
  216. }
  217. #endregion
  218. private void PresenceUpdateDone(PresenceInformer obj)
  219. {
  220. obj.OnGetRegionData -= m_regionModule.GetRegionInfo;
  221. obj.OnDone -= PresenceUpdateDone;
  222. }
  223. #region UserServer Comms
  224. /// <summary>
  225. /// Returns a list of FriendsListItems that describe the friends and permissions in the friend
  226. /// relationship for UUID friendslistowner. For faster lookup, we index by friend's UUID.
  227. /// </summary>
  228. /// <param name="friendlistowner">The agent that we're retreiving the friends Data for.</param>
  229. private Dictionary<UUID, FriendListItem> GetUserFriendList(UUID friendlistowner)
  230. {
  231. Dictionary<UUID, FriendListItem> buddies = new Dictionary<UUID,FriendListItem>();
  232. try
  233. {
  234. Hashtable param = new Hashtable();
  235. param["ownerID"] = friendlistowner.ToString();
  236. IList parameters = new ArrayList();
  237. parameters.Add(param);
  238. XmlRpcRequest req = new XmlRpcRequest("get_user_friend_list", parameters);
  239. XmlRpcResponse resp = req.Send(m_cfg.UserServerURL, 3000);
  240. Hashtable respData = (Hashtable)resp.Value;
  241. if (respData.Contains("avcount"))
  242. {
  243. buddies = ConvertXMLRPCDataToFriendListItemList(respData);
  244. }
  245. }
  246. catch (WebException e)
  247. {
  248. m_log.Warn("Error when trying to fetch Avatar's friends list: " +
  249. e.Message);
  250. // Return Empty list (no friends)
  251. }
  252. return buddies;
  253. }
  254. /// <summary>
  255. /// Converts XMLRPC Friend List to FriendListItem Object
  256. /// </summary>
  257. /// <param name="data">XMLRPC response data Hashtable</param>
  258. /// <returns></returns>
  259. public Dictionary<UUID, FriendListItem> ConvertXMLRPCDataToFriendListItemList(Hashtable data)
  260. {
  261. Dictionary<UUID, FriendListItem> buddies = new Dictionary<UUID,FriendListItem>();
  262. int buddycount = Convert.ToInt32((string)data["avcount"]);
  263. for (int i = 0; i < buddycount; i++)
  264. {
  265. FriendListItem buddylistitem = new FriendListItem();
  266. buddylistitem.FriendListOwner = new UUID((string)data["ownerID" + i.ToString()]);
  267. buddylistitem.Friend = new UUID((string)data["friendID" + i.ToString()]);
  268. buddylistitem.FriendListOwnerPerms = (uint)Convert.ToInt32((string)data["ownerPerms" + i.ToString()]);
  269. buddylistitem.FriendPerms = (uint)Convert.ToInt32((string)data["friendPerms" + i.ToString()]);
  270. buddies.Add(buddylistitem.Friend, buddylistitem);
  271. }
  272. return buddies;
  273. }
  274. /// <summary>
  275. /// UserServer sends an expect_user method
  276. /// this handles the method and provisions the
  277. /// necessary info for presence to work
  278. /// </summary>
  279. /// <param name="request">UserServer Data</param>
  280. /// <returns></returns>
  281. public XmlRpcResponse UserLoggedOn(XmlRpcRequest request, IPEndPoint remoteClient)
  282. {
  283. Hashtable requestData = (Hashtable)request.Params[0];
  284. AgentCircuitData agentData = new AgentCircuitData();
  285. agentData.SessionID = new UUID((string)requestData["sessionid"]);
  286. agentData.SecureSessionID = new UUID((string)requestData["secure_session_id"]);
  287. agentData.firstname = (string)requestData["firstname"];
  288. agentData.lastname = (string)requestData["lastname"];
  289. agentData.AgentID = new UUID((string)requestData["agentid"]);
  290. agentData.circuitcode = Convert.ToUInt32(requestData["circuit_code"]);
  291. agentData.CapsPath = (string)requestData["caps_path"];
  292. if (requestData.ContainsKey("child_agent") && requestData["child_agent"].Equals("1"))
  293. {
  294. agentData.child = true;
  295. }
  296. else
  297. {
  298. agentData.startpos =
  299. new Vector3(Convert.ToSingle(requestData["positionx"]),
  300. Convert.ToSingle(requestData["positiony"]),
  301. Convert.ToSingle(requestData["positionz"]));
  302. agentData.child = false;
  303. }
  304. ulong regionHandle = Convert.ToUInt64((string)requestData["regionhandle"]);
  305. m_log.InfoFormat("[LOGON]: User {0} {1} logged into region {2} as {3} agent, building indexes for user",
  306. agentData.firstname, agentData.lastname, regionHandle, agentData.child ? "child" : "root");
  307. UserPresenceData up = new UserPresenceData();
  308. up.agentData = agentData;
  309. up.friendData = GetUserFriendList(agentData.AgentID);
  310. up.regionData = m_regionModule.GetRegionInfo(regionHandle);
  311. up.OnlineYN = true;
  312. up.lookupUserRegionYN = false;
  313. ProcessFriendListSubscriptions(up);
  314. return new XmlRpcResponse();
  315. }
  316. /// <summary>
  317. /// The UserServer got a Logoff message
  318. /// Cleanup time for that user. Send out presence notifications
  319. /// </summary>
  320. /// <param name="request"></param>
  321. /// <returns></returns>
  322. public XmlRpcResponse UserLoggedOff(XmlRpcRequest request, IPEndPoint remoteClient)
  323. {
  324. m_log.Info("[USERLOGOFF]: User logged off called");
  325. Hashtable requestData = (Hashtable)request.Params[0];
  326. UUID AgentID = new UUID((string)requestData["agentid"]);
  327. ProcessLogOff(AgentID);
  328. return new XmlRpcResponse();
  329. }
  330. #endregion
  331. public XmlRpcResponse GetPresenceInfoBulk(XmlRpcRequest request, IPEndPoint remoteClient)
  332. {
  333. Hashtable paramHash = (Hashtable)request.Params[0];
  334. Hashtable result = new Hashtable();
  335. // TODO check access (recv_key/send_key)
  336. IList list = (IList)paramHash["uuids"];
  337. // convert into List<UUID>
  338. List<UUID> uuids = new List<UUID>();
  339. for (int i = 0; i < list.Count; ++i)
  340. {
  341. UUID uuid;
  342. if (UUID.TryParse((string)list[i], out uuid))
  343. {
  344. uuids.Add(uuid);
  345. }
  346. }
  347. try {
  348. Dictionary<UUID, FriendRegionInfo> infos = m_userDataBaseService.GetFriendRegionInfos(uuids);
  349. m_log.DebugFormat("[FRIEND]: Got {0} region entries back.", infos.Count);
  350. int count = 0;
  351. foreach (KeyValuePair<UUID, FriendRegionInfo> pair in infos)
  352. {
  353. result["uuid_" + count] = pair.Key.ToString();
  354. result["isOnline_" + count] = pair.Value.isOnline;
  355. result["regionHandle_" + count] = pair.Value.regionHandle.ToString(); // XML-RPC doesn't know ulongs
  356. ++count;
  357. }
  358. result["count"] = count;
  359. XmlRpcResponse response = new XmlRpcResponse();
  360. response.Value = result;
  361. return response;
  362. }
  363. catch(Exception e) {
  364. m_log.Error("Got exception:", e);
  365. throw e;
  366. }
  367. }
  368. public XmlRpcResponse AgentLocation(XmlRpcRequest request, IPEndPoint remoteClient)
  369. {
  370. Hashtable requestData = (Hashtable)request.Params[0];
  371. Hashtable result = new Hashtable();
  372. result["success"] = "FALSE";
  373. if (m_userServerModule.SendToUserServer(requestData, "agent_location"))
  374. result["success"] = "TRUE";
  375. XmlRpcResponse response = new XmlRpcResponse();
  376. response.Value = result;
  377. return response;
  378. }
  379. public XmlRpcResponse AgentLeaving(XmlRpcRequest request, IPEndPoint remoteClient)
  380. {
  381. Hashtable requestData = (Hashtable)request.Params[0];
  382. Hashtable result = new Hashtable();
  383. result["success"] = "FALSE";
  384. if (m_userServerModule.SendToUserServer(requestData, "agent_leaving"))
  385. result["success"] = "TRUE";
  386. XmlRpcResponse response = new XmlRpcResponse();
  387. response.Value = result;
  388. return response;
  389. }
  390. public XmlRpcResponse ProcessRegionShutdown(XmlRpcRequest request, IPEndPoint remoteClient)
  391. {
  392. Hashtable requestData = (Hashtable)request.Params[0];
  393. Hashtable result = new Hashtable();
  394. result["success"] = "FALSE";
  395. UUID regionID;
  396. if (UUID.TryParse((string)requestData["regionid"], out regionID))
  397. {
  398. m_log.DebugFormat("[PRESENCE] Processing region restart for {0}", regionID);
  399. result["success"] = "TRUE";
  400. foreach (UserPresenceData up in m_presences.Values)
  401. {
  402. if (up.regionData.UUID == regionID)
  403. {
  404. if (up.OnlineYN)
  405. {
  406. m_log.DebugFormat("[PRESENCE] Logging off {0} because the region they were in has gone", up.agentData.AgentID);
  407. ProcessLogOff(up.agentData.AgentID);
  408. }
  409. }
  410. }
  411. }
  412. XmlRpcResponse response = new XmlRpcResponse();
  413. response.Value = result;
  414. return response;
  415. }
  416. }
  417. }