HGFriendsService.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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(
  170. o => ProcessFriendshipOffered(fromID, fromName, toID, message), null, "HGFriendsService.ProcessFriendshipOffered");
  171. return true;
  172. }
  173. public bool ValidateFriendshipOffered(UUID fromID, UUID toID)
  174. {
  175. FriendInfo[] finfos = m_FriendsService.GetFriends(toID.ToString());
  176. foreach (FriendInfo fi in finfos)
  177. {
  178. if (fi.Friend.StartsWith(fromID.ToString()) && fi.TheirFlags == -1)
  179. return true;
  180. }
  181. return false;
  182. }
  183. public List<UUID> StatusNotification(List<string> friends, UUID foreignUserID, bool online)
  184. {
  185. if (m_FriendsService == null || m_PresenceService == null)
  186. {
  187. m_log.WarnFormat("[HGFRIENDS SERVICE]: Unable to perform status notifications because friends or presence services are missing");
  188. return new List<UUID>();
  189. }
  190. // Let's unblock the caller right now, and take it from here async
  191. List<UUID> localFriendsOnline = new List<UUID>();
  192. m_log.DebugFormat("[HGFRIENDS SERVICE]: Status notification: foreign user {0} wants to notify {1} local friends of {2} status",
  193. foreignUserID, friends.Count, (online ? "online" : "offline"));
  194. // First, let's double check that the reported friends are, indeed, friends of that user
  195. // And let's check that the secret matches
  196. List<string> usersToBeNotified = new List<string>();
  197. foreach (string uui in friends)
  198. {
  199. UUID localUserID;
  200. string secret = string.Empty, tmp = string.Empty;
  201. if (Util.ParseUniversalUserIdentifier(uui, out localUserID, out tmp, out tmp, out tmp, out secret))
  202. {
  203. FriendInfo[] friendInfos = m_FriendsService.GetFriends(localUserID);
  204. foreach (FriendInfo finfo in friendInfos)
  205. {
  206. if (finfo.Friend.StartsWith(foreignUserID.ToString()) && finfo.Friend.EndsWith(secret))
  207. {
  208. // great!
  209. usersToBeNotified.Add(localUserID.ToString());
  210. }
  211. }
  212. }
  213. }
  214. // Now, let's send the notifications
  215. //m_log.DebugFormat("[HGFRIENDS SERVICE]: Status notification: user has {0} local friends", usersToBeNotified.Count);
  216. // First, let's send notifications to local users who are online in the home grid
  217. PresenceInfo[] friendSessions = m_PresenceService.GetAgents(usersToBeNotified.ToArray());
  218. if (friendSessions != null && friendSessions.Length > 0)
  219. {
  220. PresenceInfo friendSession = null;
  221. foreach (PresenceInfo pinfo in friendSessions)
  222. if (pinfo.RegionID != UUID.Zero) // let's guard against traveling agents
  223. {
  224. friendSession = pinfo;
  225. break;
  226. }
  227. if (friendSession != null)
  228. {
  229. ForwardStatusNotificationToSim(friendSession.RegionID, foreignUserID, friendSession.UserID, online);
  230. usersToBeNotified.Remove(friendSession.UserID.ToString());
  231. UUID id;
  232. if (UUID.TryParse(friendSession.UserID, out id))
  233. localFriendsOnline.Add(id);
  234. }
  235. }
  236. // // Lastly, let's notify the rest who may be online somewhere else
  237. // foreach (string user in usersToBeNotified)
  238. // {
  239. // UUID id = new UUID(user);
  240. // //m_UserAgentService.LocateUser(id);
  241. // //etc...
  242. // //if (m_TravelingAgents.ContainsKey(id) && m_TravelingAgents[id].GridExternalName != m_GridName)
  243. // //{
  244. // // string url = m_TravelingAgents[id].GridExternalName;
  245. // // // forward
  246. // //}
  247. // //m_log.WarnFormat("[HGFRIENDS SERVICE]: User {0} is visiting another grid. HG Status notifications still not implemented.", user);
  248. // }
  249. // and finally, let's send the online friends
  250. if (online)
  251. {
  252. return localFriendsOnline;
  253. }
  254. else
  255. return new List<UUID>();
  256. }
  257. #endregion IHGFriendsService
  258. #region Aux
  259. private void ProcessFriendshipOffered(UUID fromID, String fromName, UUID toID, String message)
  260. {
  261. // Great, it's a genuine request. Let's proceed.
  262. // But now we need to confirm that the requester is who he says he is
  263. // before we act on the friendship request.
  264. if (!fromName.Contains("@"))
  265. return;
  266. string[] parts = fromName.Split(new char[] {'@'});
  267. if (parts.Length != 2)
  268. return;
  269. string uriStr = "http://" + parts[1];
  270. try
  271. {
  272. new Uri(uriStr);
  273. }
  274. catch (UriFormatException)
  275. {
  276. return;
  277. }
  278. UserAgentServiceConnector uasConn = new UserAgentServiceConnector(uriStr);
  279. Dictionary<string, object> servers = uasConn.GetServerURLs(fromID);
  280. if (!servers.ContainsKey("FriendsServerURI"))
  281. return;
  282. HGFriendsServicesConnector friendsConn = new HGFriendsServicesConnector(servers["FriendsServerURI"].ToString());
  283. if (!friendsConn.ValidateFriendshipOffered(fromID, toID))
  284. {
  285. m_log.WarnFormat("[HGFRIENDS SERVICE]: Friendship request from {0} to {1} is invalid. Impersonations?", fromID, toID);
  286. return;
  287. }
  288. string fromUUI = Util.UniversalIdentifier(fromID, parts[0], "@" + parts[1], uriStr);
  289. // OK, we're good!
  290. ForwardToSim("FriendshipOffered", fromID, fromName, fromUUI, toID, message);
  291. }
  292. private bool ForwardToSim(string op, UUID fromID, string name, String fromUUI, UUID toID, string message)
  293. {
  294. PresenceInfo session = null;
  295. GridRegion region = null;
  296. PresenceInfo[] sessions = m_PresenceService.GetAgents(new string[] { toID.ToString() });
  297. if (sessions != null && sessions.Length > 0)
  298. session = sessions[0];
  299. if (session != null)
  300. region = m_GridService.GetRegionByUUID(UUID.Zero, session.RegionID);
  301. switch (op)
  302. {
  303. case "FriendshipOffered":
  304. // Let's store backwards
  305. string secret = UUID.Random().ToString().Substring(0, 8);
  306. m_FriendsService.StoreFriend(toID.ToString(), fromUUI + ";" + secret, 0);
  307. if (m_FriendsLocalSimConnector != null) // standalone
  308. {
  309. GridInstantMessage im = new GridInstantMessage(null, fromID, name, toID,
  310. (byte)InstantMessageDialog.FriendshipOffered, message, false, Vector3.Zero);
  311. // !! HACK
  312. im.imSessionID = im.fromAgentID;
  313. return m_FriendsLocalSimConnector.LocalFriendshipOffered(toID, im);
  314. }
  315. else if (region != null) // grid
  316. return m_FriendsSimConnector.FriendshipOffered(region, fromID, toID, message, name);
  317. break;
  318. case "ApproveFriendshipRequest":
  319. if (m_FriendsLocalSimConnector != null) // standalone
  320. return m_FriendsLocalSimConnector.LocalFriendshipApproved(fromID, name, toID);
  321. else if (region != null) //grid
  322. return m_FriendsSimConnector.FriendshipApproved(region, fromID, name, toID);
  323. break;
  324. }
  325. return false;
  326. }
  327. protected void ForwardStatusNotificationToSim(UUID regionID, UUID foreignUserID, string user, bool online)
  328. {
  329. UUID userID;
  330. if (UUID.TryParse(user, out userID))
  331. {
  332. if (m_FriendsLocalSimConnector != null)
  333. {
  334. m_log.DebugFormat("[HGFRIENDS SERVICE]: Local Notify, user {0} is {1}", foreignUserID, (online ? "online" : "offline"));
  335. m_FriendsLocalSimConnector.StatusNotify(foreignUserID, userID, online);
  336. }
  337. else
  338. {
  339. GridRegion region = m_GridService.GetRegionByUUID(UUID.Zero /* !!! */, regionID);
  340. if (region != null)
  341. {
  342. m_log.DebugFormat("[HGFRIENDS SERVICE]: Remote Notify to region {0}, user {1} is {2}", region.RegionName, foreignUserID, (online ? "online" : "offline"));
  343. m_FriendsSimConnector.StatusNotify(region, foreignUserID, userID.ToString(), online);
  344. }
  345. }
  346. }
  347. }
  348. #endregion Aux
  349. }
  350. }