HGFriendsService.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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.Generic;
  29. using System.Net;
  30. using System.Reflection;
  31. using OpenSim.Framework;
  32. using OpenSim.Services.Connectors.Friends;
  33. using OpenSim.Services.Connectors.Hypergrid;
  34. using OpenSim.Services.Interfaces;
  35. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  36. using OpenSim.Server.Base;
  37. using FriendInfo = OpenSim.Services.Interfaces.FriendInfo;
  38. using OpenMetaverse;
  39. using log4net;
  40. using Nini.Config;
  41. namespace OpenSim.Services.HypergridService
  42. {
  43. /// <summary>
  44. /// W2W social networking
  45. /// </summary>
  46. public class HGFriendsService : IHGFriendsService
  47. {
  48. private static readonly ILog m_log =
  49. LogManager.GetLogger(
  50. MethodBase.GetCurrentMethod().DeclaringType);
  51. static bool m_Initialized = false;
  52. protected static IGridUserService m_GridUserService;
  53. protected static IGridService m_GridService;
  54. protected static IGatekeeperService m_GatekeeperService;
  55. protected static IFriendsService m_FriendsService;
  56. protected static IPresenceService m_PresenceService;
  57. protected static IUserAccountService m_UserAccountService;
  58. protected static IFriendsSimConnector m_FriendsLocalSimConnector; // standalone, points to HGFriendsModule
  59. protected static FriendsSimConnector m_FriendsSimConnector; // grid
  60. private static string m_ConfigName = "HGFriendsService";
  61. public HGFriendsService(IConfigSource config, String configName, IFriendsSimConnector localSimConn)
  62. {
  63. if (m_FriendsLocalSimConnector == null)
  64. m_FriendsLocalSimConnector = localSimConn;
  65. if (!m_Initialized)
  66. {
  67. m_Initialized = true;
  68. if (configName != String.Empty)
  69. m_ConfigName = configName;
  70. Object[] args = new Object[] { config };
  71. IConfig serverConfig = config.Configs[m_ConfigName];
  72. if (serverConfig == null)
  73. throw new Exception(String.Format("No section {0} in config file", m_ConfigName));
  74. string theService = serverConfig.GetString("FriendsService", string.Empty);
  75. if (theService == String.Empty)
  76. throw new Exception("No FriendsService in config file " + m_ConfigName);
  77. m_FriendsService = ServerUtils.LoadPlugin<IFriendsService>(theService, args);
  78. theService = serverConfig.GetString("UserAccountService", string.Empty);
  79. if (theService == String.Empty)
  80. throw new Exception("No UserAccountService in " + m_ConfigName);
  81. m_UserAccountService = ServerUtils.LoadPlugin<IUserAccountService>(theService, args);
  82. theService = serverConfig.GetString("GridService", string.Empty);
  83. if (theService == String.Empty)
  84. throw new Exception("No GridService in " + m_ConfigName);
  85. m_GridService = ServerUtils.LoadPlugin<IGridService>(theService, args);
  86. theService = serverConfig.GetString("PresenceService", string.Empty);
  87. if (theService == String.Empty)
  88. throw new Exception("No PresenceService in " + m_ConfigName);
  89. m_PresenceService = ServerUtils.LoadPlugin<IPresenceService>(theService, args);
  90. m_FriendsSimConnector = new FriendsSimConnector();
  91. m_log.DebugFormat("[HGFRIENDS SERVICE]: Starting...");
  92. }
  93. }
  94. #region IHGFriendsService
  95. public int GetFriendPerms(UUID userID, UUID friendID)
  96. {
  97. FriendInfo[] friendsInfo = m_FriendsService.GetFriends(userID);
  98. foreach (FriendInfo finfo in friendsInfo)
  99. {
  100. if (finfo.Friend.StartsWith(friendID.ToString()))
  101. return finfo.TheirFlags;
  102. }
  103. return -1;
  104. }
  105. public bool NewFriendship(FriendInfo friend, bool verified)
  106. {
  107. UUID friendID;
  108. string tmp = string.Empty, url = String.Empty, first = String.Empty, last = String.Empty;
  109. if (!Util.ParseUniversalUserIdentifier(friend.Friend, out friendID, out url, out first, out last, out tmp))
  110. return false;
  111. m_log.DebugFormat("[HGFRIENDS SERVICE]: New friendship {0} {1} ({2})", friend.PrincipalID, friend.Friend, verified);
  112. // Does the friendship already exist?
  113. FriendInfo[] finfos = m_FriendsService.GetFriends(friend.PrincipalID);
  114. foreach (FriendInfo finfo in finfos)
  115. {
  116. if (finfo.Friend.StartsWith(friendID.ToString()))
  117. return false;
  118. }
  119. // Verified user session. But the user needs to confirm friendship when he gets home
  120. if (verified)
  121. return m_FriendsService.StoreFriend(friend.PrincipalID.ToString(), friend.Friend, 0);
  122. // Does the reverted friendship exist? meaning that this user initiated the request
  123. finfos = m_FriendsService.GetFriends(friendID);
  124. bool userInitiatedOffer = false;
  125. foreach (FriendInfo finfo in finfos)
  126. {
  127. if (friend.Friend.StartsWith(finfo.PrincipalID.ToString()) && finfo.Friend.StartsWith(friend.PrincipalID.ToString()) && finfo.TheirFlags == -1)
  128. {
  129. userInitiatedOffer = true;
  130. // Let's delete the existing friendship relations that was stored
  131. m_FriendsService.Delete(friendID, finfo.Friend);
  132. break;
  133. }
  134. }
  135. if (userInitiatedOffer)
  136. {
  137. m_FriendsService.StoreFriend(friend.PrincipalID.ToString(), friend.Friend, 1);
  138. m_FriendsService.StoreFriend(friend.Friend, friend.PrincipalID.ToString(), 1);
  139. // notify the user
  140. ForwardToSim("ApproveFriendshipRequest", friendID, Util.UniversalName(first, last, url), "", friend.PrincipalID, "");
  141. return true;
  142. }
  143. return false;
  144. }
  145. public bool DeleteFriendship(FriendInfo friend, string secret)
  146. {
  147. FriendInfo[] finfos = m_FriendsService.GetFriends(friend.PrincipalID);
  148. foreach (FriendInfo finfo in finfos)
  149. {
  150. // We check the secret here. Or if the friendship request was initiated here, and was declined
  151. if (finfo.Friend.StartsWith(friend.Friend) && finfo.Friend.EndsWith(secret))
  152. {
  153. m_log.DebugFormat("[HGFRIENDS SERVICE]: Delete friendship {0} {1}", friend.PrincipalID, friend.Friend);
  154. m_FriendsService.Delete(friend.PrincipalID, finfo.Friend);
  155. m_FriendsService.Delete(finfo.Friend, friend.PrincipalID.ToString());
  156. return true;
  157. }
  158. }
  159. return false;
  160. }
  161. public bool FriendshipOffered(UUID fromID, string fromName, UUID toID, string message)
  162. {
  163. UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero, toID);
  164. if (account == null)
  165. return false;
  166. // OK, we have that user here.
  167. // So let's send back the call, but start a thread to continue
  168. // with the verification and the actual action.
  169. Util.FireAndForget(delegate { ProcessFriendshipOffered(fromID, fromName, toID, message); });
  170. return true;
  171. }
  172. public bool ValidateFriendshipOffered(UUID fromID, UUID toID)
  173. {
  174. FriendInfo[] finfos = m_FriendsService.GetFriends(toID.ToString());
  175. foreach (FriendInfo fi in finfos)
  176. {
  177. if (fi.Friend.StartsWith(fromID.ToString()) && fi.TheirFlags == -1)
  178. return true;
  179. }
  180. return false;
  181. }
  182. public List<UUID> StatusNotification(List<string> friends, UUID foreignUserID, bool online)
  183. {
  184. if (m_FriendsService == null || m_PresenceService == null)
  185. {
  186. m_log.WarnFormat("[HGFRIENDS SERVICE]: Unable to perform status notifications because friends or presence services are missing");
  187. return new List<UUID>();
  188. }
  189. // Let's unblock the caller right now, and take it from here async
  190. List<UUID> localFriendsOnline = new List<UUID>();
  191. m_log.DebugFormat("[HGFRIENDS SERVICE]: Status notification: foreign user {0} wants to notify {1} local friends of {2} status",
  192. foreignUserID, friends.Count, (online ? "online" : "offline"));
  193. // First, let's double check that the reported friends are, indeed, friends of that user
  194. // And let's check that the secret matches
  195. List<string> usersToBeNotified = new List<string>();
  196. foreach (string uui in friends)
  197. {
  198. UUID localUserID;
  199. string secret = string.Empty, tmp = string.Empty;
  200. if (Util.ParseUniversalUserIdentifier(uui, out localUserID, out tmp, out tmp, out tmp, out secret))
  201. {
  202. FriendInfo[] friendInfos = m_FriendsService.GetFriends(localUserID);
  203. foreach (FriendInfo finfo in friendInfos)
  204. {
  205. if (finfo.Friend.StartsWith(foreignUserID.ToString()) && finfo.Friend.EndsWith(secret))
  206. {
  207. // great!
  208. usersToBeNotified.Add(localUserID.ToString());
  209. }
  210. }
  211. }
  212. }
  213. // Now, let's send the notifications
  214. //m_log.DebugFormat("[HGFRIENDS SERVICE]: Status notification: user has {0} local friends", usersToBeNotified.Count);
  215. // First, let's send notifications to local users who are online in the home grid
  216. PresenceInfo[] friendSessions = m_PresenceService.GetAgents(usersToBeNotified.ToArray());
  217. if (friendSessions != null && friendSessions.Length > 0)
  218. {
  219. PresenceInfo friendSession = null;
  220. foreach (PresenceInfo pinfo in friendSessions)
  221. if (pinfo.RegionID != UUID.Zero) // let's guard against traveling agents
  222. {
  223. friendSession = pinfo;
  224. break;
  225. }
  226. if (friendSession != null)
  227. {
  228. ForwardStatusNotificationToSim(friendSession.RegionID, foreignUserID, friendSession.UserID, online);
  229. usersToBeNotified.Remove(friendSession.UserID.ToString());
  230. UUID id;
  231. if (UUID.TryParse(friendSession.UserID, out id))
  232. localFriendsOnline.Add(id);
  233. }
  234. }
  235. // // Lastly, let's notify the rest who may be online somewhere else
  236. // foreach (string user in usersToBeNotified)
  237. // {
  238. // UUID id = new UUID(user);
  239. // //m_UserAgentService.LocateUser(id);
  240. // //etc...
  241. // //if (m_TravelingAgents.ContainsKey(id) && m_TravelingAgents[id].GridExternalName != m_GridName)
  242. // //{
  243. // // string url = m_TravelingAgents[id].GridExternalName;
  244. // // // forward
  245. // //}
  246. // //m_log.WarnFormat("[HGFRIENDS SERVICE]: User {0} is visiting another grid. HG Status notifications still not implemented.", user);
  247. // }
  248. // and finally, let's send the online friends
  249. if (online)
  250. {
  251. return localFriendsOnline;
  252. }
  253. else
  254. return new List<UUID>();
  255. }
  256. #endregion IHGFriendsService
  257. #region Aux
  258. private void ProcessFriendshipOffered(UUID fromID, String fromName, UUID toID, String message)
  259. {
  260. // Great, it's a genuine request. Let's proceed.
  261. // But now we need to confirm that the requester is who he says he is
  262. // before we act on the friendship request.
  263. if (!fromName.Contains("@"))
  264. return;
  265. string[] parts = fromName.Split(new char[] {'@'});
  266. if (parts.Length != 2)
  267. return;
  268. string uriStr = "http://" + parts[1];
  269. try
  270. {
  271. new Uri(uriStr);
  272. }
  273. catch (UriFormatException)
  274. {
  275. return;
  276. }
  277. UserAgentServiceConnector uasConn = new UserAgentServiceConnector(uriStr);
  278. Dictionary<string, object> servers = uasConn.GetServerURLs(fromID);
  279. if (!servers.ContainsKey("FriendsServerURI"))
  280. return;
  281. HGFriendsServicesConnector friendsConn = new HGFriendsServicesConnector(servers["FriendsServerURI"].ToString());
  282. if (!friendsConn.ValidateFriendshipOffered(fromID, toID))
  283. {
  284. m_log.WarnFormat("[HGFRIENDS SERVICE]: Friendship request from {0} to {1} is invalid. Impersonations?", fromID, toID);
  285. return;
  286. }
  287. string fromUUI = Util.UniversalIdentifier(fromID, parts[0], "@" + parts[1], uriStr);
  288. // OK, we're good!
  289. ForwardToSim("FriendshipOffered", fromID, fromName, fromUUI, toID, message);
  290. }
  291. private bool ForwardToSim(string op, UUID fromID, string name, String fromUUI, UUID toID, string message)
  292. {
  293. PresenceInfo session = null;
  294. GridRegion region = null;
  295. PresenceInfo[] sessions = m_PresenceService.GetAgents(new string[] { toID.ToString() });
  296. if (sessions != null && sessions.Length > 0)
  297. session = sessions[0];
  298. if (session != null)
  299. region = m_GridService.GetRegionByUUID(UUID.Zero, session.RegionID);
  300. switch (op)
  301. {
  302. case "FriendshipOffered":
  303. // Let's store backwards
  304. string secret = UUID.Random().ToString().Substring(0, 8);
  305. m_FriendsService.StoreFriend(toID.ToString(), fromUUI + ";" + secret, 0);
  306. if (m_FriendsLocalSimConnector != null) // standalone
  307. {
  308. GridInstantMessage im = new GridInstantMessage(null, fromID, name, toID,
  309. (byte)InstantMessageDialog.FriendshipOffered, message, false, Vector3.Zero);
  310. // !! HACK
  311. im.imSessionID = im.fromAgentID;
  312. return m_FriendsLocalSimConnector.LocalFriendshipOffered(toID, im);
  313. }
  314. else if (region != null) // grid
  315. return m_FriendsSimConnector.FriendshipOffered(region, fromID, toID, message, name);
  316. break;
  317. case "ApproveFriendshipRequest":
  318. if (m_FriendsLocalSimConnector != null) // standalone
  319. return m_FriendsLocalSimConnector.LocalFriendshipApproved(fromID, name, toID);
  320. else if (region != null) //grid
  321. return m_FriendsSimConnector.FriendshipApproved(region, fromID, name, toID);
  322. break;
  323. }
  324. return false;
  325. }
  326. protected void ForwardStatusNotificationToSim(UUID regionID, UUID foreignUserID, string user, bool online)
  327. {
  328. UUID userID;
  329. if (UUID.TryParse(user, out userID))
  330. {
  331. if (m_FriendsLocalSimConnector != null)
  332. {
  333. m_log.DebugFormat("[HGFRIENDS SERVICE]: Local Notify, user {0} is {1}", foreignUserID, (online ? "online" : "offline"));
  334. m_FriendsLocalSimConnector.StatusNotify(foreignUserID, userID, online);
  335. }
  336. else
  337. {
  338. GridRegion region = m_GridService.GetRegionByUUID(UUID.Zero /* !!! */, regionID);
  339. if (region != null)
  340. {
  341. m_log.DebugFormat("[HGFRIENDS SERVICE]: Remote Notify to region {0}, user {1} is {2}", region.RegionName, foreignUserID, (online ? "online" : "offline"));
  342. m_FriendsSimConnector.StatusNotify(region, foreignUserID, userID.ToString(), online);
  343. }
  344. }
  345. }
  346. }
  347. #endregion Aux
  348. }
  349. }