UserAgentService.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  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.Data;
  32. using OpenSim.Framework;
  33. using OpenSim.Services.Connectors.Friends;
  34. using OpenSim.Services.Connectors.Hypergrid;
  35. using OpenSim.Services.Interfaces;
  36. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  37. using OpenSim.Server.Base;
  38. using FriendInfo = OpenSim.Services.Interfaces.FriendInfo;
  39. using OpenMetaverse;
  40. using log4net;
  41. using Nini.Config;
  42. namespace OpenSim.Services.HypergridService
  43. {
  44. /// <summary>
  45. /// This service is for HG1.5 only, to make up for the fact that clients don't
  46. /// keep any private information in themselves, and that their 'home service'
  47. /// needs to do it for them.
  48. /// Once we have better clients, this shouldn't be needed.
  49. /// </summary>
  50. public class UserAgentService : UserAgentServiceBase, IUserAgentService
  51. {
  52. private static readonly ILog m_log =
  53. LogManager.GetLogger(
  54. MethodBase.GetCurrentMethod().DeclaringType);
  55. // This will need to go into a DB table
  56. //static Dictionary<UUID, TravelingAgentInfo> m_Database = new Dictionary<UUID, TravelingAgentInfo>();
  57. static bool m_Initialized = false;
  58. protected static IGridUserService m_GridUserService;
  59. protected static IGridService m_GridService;
  60. protected static GatekeeperServiceConnector m_GatekeeperConnector;
  61. protected static IGatekeeperService m_GatekeeperService;
  62. protected static IFriendsService m_FriendsService;
  63. protected static IPresenceService m_PresenceService;
  64. protected static IUserAccountService m_UserAccountService;
  65. protected static IFriendsSimConnector m_FriendsLocalSimConnector; // standalone, points to HGFriendsModule
  66. protected static FriendsSimConnector m_FriendsSimConnector; // grid
  67. protected static string m_GridName;
  68. protected static int m_LevelOutsideContacts;
  69. protected static bool m_ShowDetails;
  70. protected static bool m_BypassClientVerification;
  71. private static Dictionary<int, bool> m_ForeignTripsAllowed = new Dictionary<int, bool>();
  72. private static Dictionary<int, List<string>> m_TripsAllowedExceptions = new Dictionary<int, List<string>>();
  73. private static Dictionary<int, List<string>> m_TripsDisallowedExceptions = new Dictionary<int, List<string>>();
  74. public UserAgentService(IConfigSource config) : this(config, null)
  75. {
  76. }
  77. public UserAgentService(IConfigSource config, IFriendsSimConnector friendsConnector)
  78. : base(config)
  79. {
  80. // Let's set this always, because we don't know the sequence
  81. // of instantiations
  82. if (friendsConnector != null)
  83. m_FriendsLocalSimConnector = friendsConnector;
  84. if (!m_Initialized)
  85. {
  86. m_Initialized = true;
  87. m_log.DebugFormat("[HOME USERS SECURITY]: Starting...");
  88. m_FriendsSimConnector = new FriendsSimConnector();
  89. IConfig serverConfig = config.Configs["UserAgentService"];
  90. if (serverConfig == null)
  91. throw new Exception(String.Format("No section UserAgentService in config file"));
  92. string gridService = serverConfig.GetString("GridService", String.Empty);
  93. string gridUserService = serverConfig.GetString("GridUserService", String.Empty);
  94. string gatekeeperService = serverConfig.GetString("GatekeeperService", String.Empty);
  95. string friendsService = serverConfig.GetString("FriendsService", String.Empty);
  96. string presenceService = serverConfig.GetString("PresenceService", String.Empty);
  97. string userAccountService = serverConfig.GetString("UserAccountService", String.Empty);
  98. m_BypassClientVerification = serverConfig.GetBoolean("BypassClientVerification", false);
  99. if (gridService == string.Empty || gridUserService == string.Empty || gatekeeperService == string.Empty)
  100. throw new Exception(String.Format("Incomplete specifications, UserAgent Service cannot function."));
  101. Object[] args = new Object[] { config };
  102. m_GridService = ServerUtils.LoadPlugin<IGridService>(gridService, args);
  103. m_GridUserService = ServerUtils.LoadPlugin<IGridUserService>(gridUserService, args);
  104. m_GatekeeperConnector = new GatekeeperServiceConnector();
  105. m_GatekeeperService = ServerUtils.LoadPlugin<IGatekeeperService>(gatekeeperService, args);
  106. m_FriendsService = ServerUtils.LoadPlugin<IFriendsService>(friendsService, args);
  107. m_PresenceService = ServerUtils.LoadPlugin<IPresenceService>(presenceService, args);
  108. m_UserAccountService = ServerUtils.LoadPlugin<IUserAccountService>(userAccountService, args);
  109. m_LevelOutsideContacts = serverConfig.GetInt("LevelOutsideContacts", 0);
  110. m_ShowDetails = serverConfig.GetBoolean("ShowUserDetailsInHGProfile", true);
  111. LoadTripPermissionsFromConfig(serverConfig, "ForeignTripsAllowed");
  112. LoadDomainExceptionsFromConfig(serverConfig, "AllowExcept", m_TripsAllowedExceptions);
  113. LoadDomainExceptionsFromConfig(serverConfig, "DisallowExcept", m_TripsDisallowedExceptions);
  114. m_GridName = Util.GetConfigVarFromSections<string>(config, "GatekeeperURI",
  115. new string[] { "Startup", "Hypergrid", "UserAgentService" }, String.Empty);
  116. if (string.IsNullOrEmpty(m_GridName)) // Legacy. Remove soon.
  117. {
  118. m_GridName = serverConfig.GetString("ExternalName", string.Empty);
  119. if (m_GridName == string.Empty)
  120. {
  121. serverConfig = config.Configs["GatekeeperService"];
  122. m_GridName = serverConfig.GetString("ExternalName", string.Empty);
  123. }
  124. }
  125. if (!m_GridName.EndsWith("/"))
  126. m_GridName = m_GridName + "/";
  127. // Finally some cleanup
  128. m_Database.DeleteOld();
  129. }
  130. }
  131. protected void LoadTripPermissionsFromConfig(IConfig config, string variable)
  132. {
  133. foreach (string keyName in config.GetKeys())
  134. {
  135. if (keyName.StartsWith(variable + "_Level_"))
  136. {
  137. int level = 0;
  138. if (Int32.TryParse(keyName.Replace(variable + "_Level_", ""), out level))
  139. m_ForeignTripsAllowed.Add(level, config.GetBoolean(keyName, true));
  140. }
  141. }
  142. }
  143. protected void LoadDomainExceptionsFromConfig(IConfig config, string variable, Dictionary<int, List<string>> exceptions)
  144. {
  145. foreach (string keyName in config.GetKeys())
  146. {
  147. if (keyName.StartsWith(variable + "_Level_"))
  148. {
  149. int level = 0;
  150. if (Int32.TryParse(keyName.Replace(variable + "_Level_", ""), out level) && !exceptions.ContainsKey(level))
  151. {
  152. exceptions.Add(level, new List<string>());
  153. string value = config.GetString(keyName, string.Empty);
  154. string[] parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
  155. foreach (string s in parts)
  156. exceptions[level].Add(s.Trim());
  157. }
  158. }
  159. }
  160. }
  161. public GridRegion GetHomeRegion(UUID userID, out Vector3 position, out Vector3 lookAt)
  162. {
  163. position = new Vector3(128, 128, 0); lookAt = Vector3.UnitY;
  164. m_log.DebugFormat("[USER AGENT SERVICE]: Request to get home region of user {0}", userID);
  165. GridRegion home = null;
  166. GridUserInfo uinfo = m_GridUserService.GetGridUserInfo(userID.ToString());
  167. if (uinfo != null)
  168. {
  169. if (uinfo.HomeRegionID != UUID.Zero)
  170. {
  171. home = m_GridService.GetRegionByUUID(UUID.Zero, uinfo.HomeRegionID);
  172. position = uinfo.HomePosition;
  173. lookAt = uinfo.HomeLookAt;
  174. }
  175. if (home == null)
  176. {
  177. List<GridRegion> defs = m_GridService.GetDefaultRegions(UUID.Zero);
  178. if (defs != null && defs.Count > 0)
  179. home = defs[0];
  180. }
  181. }
  182. return home;
  183. }
  184. public bool LoginAgentToGrid(GridRegion source, AgentCircuitData agentCircuit, GridRegion gatekeeper, GridRegion finalDestination, bool fromLogin, out string reason)
  185. {
  186. m_log.DebugFormat("[USER AGENT SERVICE]: Request to login user {0} {1} (@{2}) to grid {3}",
  187. agentCircuit.firstname, agentCircuit.lastname, (fromLogin ? agentCircuit.IPAddress : "stored IP"), gatekeeper.ServerURI);
  188. string gridName = gatekeeper.ServerURI;
  189. UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero, agentCircuit.AgentID);
  190. if (account == null)
  191. {
  192. m_log.WarnFormat("[USER AGENT SERVICE]: Someone attempted to lauch a foreign user from here {0} {1}", agentCircuit.firstname, agentCircuit.lastname);
  193. reason = "Forbidden to launch your agents from here";
  194. return false;
  195. }
  196. // Is this user allowed to go there?
  197. if (m_GridName != gridName)
  198. {
  199. if (m_ForeignTripsAllowed.ContainsKey(account.UserLevel))
  200. {
  201. bool allowed = m_ForeignTripsAllowed[account.UserLevel];
  202. if (m_ForeignTripsAllowed[account.UserLevel] && IsException(gridName, account.UserLevel, m_TripsAllowedExceptions))
  203. allowed = false;
  204. if (!m_ForeignTripsAllowed[account.UserLevel] && IsException(gridName, account.UserLevel, m_TripsDisallowedExceptions))
  205. allowed = true;
  206. if (!allowed)
  207. {
  208. reason = "Your world does not allow you to visit the destination";
  209. m_log.InfoFormat("[USER AGENT SERVICE]: Agents not permitted to visit {0}. Refusing service.", gridName);
  210. return false;
  211. }
  212. }
  213. }
  214. // Take the IP address + port of the gatekeeper (reg) plus the info of finalDestination
  215. GridRegion region = new GridRegion(gatekeeper);
  216. region.ServerURI = gatekeeper.ServerURI;
  217. region.ExternalHostName = finalDestination.ExternalHostName;
  218. region.InternalEndPoint = finalDestination.InternalEndPoint;
  219. region.RegionName = finalDestination.RegionName;
  220. region.RegionID = finalDestination.RegionID;
  221. region.RegionLocX = finalDestination.RegionLocX;
  222. region.RegionLocY = finalDestination.RegionLocY;
  223. // Generate a new service session
  224. agentCircuit.ServiceSessionID = region.ServerURI + ";" + UUID.Random();
  225. TravelingAgentInfo old = null;
  226. TravelingAgentInfo travel = CreateTravelInfo(agentCircuit, region, fromLogin, out old);
  227. bool success = false;
  228. string myExternalIP = string.Empty;
  229. m_log.DebugFormat("[USER AGENT SERVICE]: this grid: {0}, desired grid: {1}, desired region: {2}", m_GridName, gridName, region.RegionID);
  230. if (m_GridName == gridName)
  231. {
  232. success = m_GatekeeperService.LoginAgent(source, agentCircuit, finalDestination, out reason);
  233. }
  234. else
  235. {
  236. //TODO: Should there not be a call to QueryAccess here?
  237. EntityTransferContext ctx = new EntityTransferContext();
  238. success = m_GatekeeperConnector.CreateAgent(source, region, agentCircuit, (uint)Constants.TeleportFlags.ViaLogin, ctx, out myExternalIP, out reason);
  239. }
  240. if (!success)
  241. {
  242. m_log.DebugFormat("[USER AGENT SERVICE]: Unable to login user {0} {1} to grid {2}, reason: {3}",
  243. agentCircuit.firstname, agentCircuit.lastname, region.ServerURI, reason);
  244. if (old != null)
  245. StoreTravelInfo(old);
  246. else
  247. m_Database.Delete(agentCircuit.SessionID);
  248. return false;
  249. }
  250. // Everything is ok
  251. // Update the perceived IP Address of our grid
  252. m_log.DebugFormat("[USER AGENT SERVICE]: Gatekeeper sees me as {0}", myExternalIP);
  253. travel.MyIpAddress = myExternalIP;
  254. StoreTravelInfo(travel);
  255. return true;
  256. }
  257. public bool LoginAgentToGrid(GridRegion source, AgentCircuitData agentCircuit, GridRegion gatekeeper, GridRegion finalDestination, out string reason)
  258. {
  259. reason = string.Empty;
  260. return LoginAgentToGrid(source, agentCircuit, gatekeeper, finalDestination, false, out reason);
  261. }
  262. TravelingAgentInfo CreateTravelInfo(AgentCircuitData agentCircuit, GridRegion region, bool fromLogin, out TravelingAgentInfo existing)
  263. {
  264. HGTravelingData hgt = m_Database.Get(agentCircuit.SessionID);
  265. existing = null;
  266. if (hgt != null)
  267. {
  268. // Very important! Override whatever this agent comes with.
  269. // UserAgentService always sets the IP for every new agent
  270. // with the original IP address.
  271. existing = new TravelingAgentInfo(hgt);
  272. agentCircuit.IPAddress = existing.ClientIPAddress;
  273. }
  274. TravelingAgentInfo travel = new TravelingAgentInfo(existing);
  275. travel.SessionID = agentCircuit.SessionID;
  276. travel.UserID = agentCircuit.AgentID;
  277. travel.GridExternalName = region.ServerURI;
  278. travel.ServiceToken = agentCircuit.ServiceSessionID;
  279. if (fromLogin)
  280. travel.ClientIPAddress = agentCircuit.IPAddress;
  281. StoreTravelInfo(travel);
  282. return travel;
  283. }
  284. public void LogoutAgent(UUID userID, UUID sessionID)
  285. {
  286. m_log.DebugFormat("[USER AGENT SERVICE]: User {0} logged out", userID);
  287. m_Database.Delete(sessionID);
  288. GridUserInfo guinfo = m_GridUserService.GetGridUserInfo(userID.ToString());
  289. if (guinfo != null)
  290. m_GridUserService.LoggedOut(userID.ToString(), sessionID, guinfo.LastRegionID, guinfo.LastPosition, guinfo.LastLookAt);
  291. }
  292. // We need to prevent foreign users with the same UUID as a local user
  293. public bool IsAgentComingHome(UUID sessionID, string thisGridExternalName)
  294. {
  295. HGTravelingData hgt = m_Database.Get(sessionID);
  296. if (hgt == null)
  297. return false;
  298. TravelingAgentInfo travel = new TravelingAgentInfo(hgt);
  299. return travel.GridExternalName.ToLower() == thisGridExternalName.ToLower();
  300. }
  301. public bool VerifyClient(UUID sessionID, string reportedIP)
  302. {
  303. if (m_BypassClientVerification)
  304. return true;
  305. m_log.DebugFormat("[USER AGENT SERVICE]: Verifying Client session {0} with reported IP {1}.",
  306. sessionID, reportedIP);
  307. HGTravelingData hgt = m_Database.Get(sessionID);
  308. if (hgt == null)
  309. return false;
  310. TravelingAgentInfo travel = new TravelingAgentInfo(hgt);
  311. bool result = travel.ClientIPAddress == reportedIP || travel.MyIpAddress == reportedIP; // NATed
  312. m_log.DebugFormat("[USER AGENT SERVICE]: Comparing {0} with login IP {1} and MyIP {1}; result is {3}",
  313. reportedIP, travel.ClientIPAddress, travel.MyIpAddress, result);
  314. return result;
  315. }
  316. public bool VerifyAgent(UUID sessionID, string token)
  317. {
  318. HGTravelingData hgt = m_Database.Get(sessionID);
  319. if (hgt == null)
  320. {
  321. m_log.DebugFormat("[USER AGENT SERVICE]: Token verification for session {0}: no such session", sessionID);
  322. return false;
  323. }
  324. TravelingAgentInfo travel = new TravelingAgentInfo(hgt);
  325. m_log.DebugFormat("[USER AGENT SERVICE]: Verifying agent token {0} against {1}", token, travel.ServiceToken);
  326. return travel.ServiceToken == token;
  327. }
  328. [Obsolete]
  329. public List<UUID> StatusNotification(List<string> friends, UUID foreignUserID, bool online)
  330. {
  331. if (m_FriendsService == null || m_PresenceService == null)
  332. {
  333. m_log.WarnFormat("[USER AGENT SERVICE]: Unable to perform status notifications because friends or presence services are missing");
  334. return new List<UUID>();
  335. }
  336. List<UUID> localFriendsOnline = new List<UUID>();
  337. m_log.DebugFormat("[USER AGENT SERVICE]: Status notification: foreign user {0} wants to notify {1} local friends", foreignUserID, friends.Count);
  338. // First, let's double check that the reported friends are, indeed, friends of that user
  339. // And let's check that the secret matches
  340. List<string> usersToBeNotified = new List<string>();
  341. foreach (string uui in friends)
  342. {
  343. UUID localUserID;
  344. string secret = string.Empty, tmp = string.Empty;
  345. if (Util.ParseUniversalUserIdentifier(uui, out localUserID, out tmp, out tmp, out tmp, out secret))
  346. {
  347. FriendInfo[] friendInfos = m_FriendsService.GetFriends(localUserID);
  348. foreach (FriendInfo finfo in friendInfos)
  349. {
  350. if (finfo.Friend.StartsWith(foreignUserID.ToString()) && finfo.Friend.EndsWith(secret))
  351. {
  352. // great!
  353. usersToBeNotified.Add(localUserID.ToString());
  354. }
  355. }
  356. }
  357. }
  358. // Now, let's send the notifications
  359. m_log.DebugFormat("[USER AGENT SERVICE]: Status notification: user has {0} local friends", usersToBeNotified.Count);
  360. // First, let's send notifications to local users who are online in the home grid
  361. PresenceInfo[] friendSessions = m_PresenceService.GetAgents(usersToBeNotified.ToArray());
  362. if (friendSessions != null && friendSessions.Length > 0)
  363. {
  364. PresenceInfo friendSession = null;
  365. foreach (PresenceInfo pinfo in friendSessions)
  366. if (pinfo.RegionID != UUID.Zero) // let's guard against traveling agents
  367. {
  368. friendSession = pinfo;
  369. break;
  370. }
  371. if (friendSession != null)
  372. {
  373. ForwardStatusNotificationToSim(friendSession.RegionID, foreignUserID, friendSession.UserID, online);
  374. usersToBeNotified.Remove(friendSession.UserID.ToString());
  375. UUID id;
  376. if (UUID.TryParse(friendSession.UserID, out id))
  377. localFriendsOnline.Add(id);
  378. }
  379. }
  380. //// Lastly, let's notify the rest who may be online somewhere else
  381. //foreach (string user in usersToBeNotified)
  382. //{
  383. // UUID id = new UUID(user);
  384. // if (m_Database.ContainsKey(id) && m_Database[id].GridExternalName != m_GridName)
  385. // {
  386. // string url = m_Database[id].GridExternalName;
  387. // // forward
  388. // m_log.WarnFormat("[USER AGENT SERVICE]: User {0} is visiting {1}. HG Status notifications still not implemented.", user, url);
  389. // }
  390. //}
  391. // and finally, let's send the online friends
  392. if (online)
  393. {
  394. return localFriendsOnline;
  395. }
  396. else
  397. return new List<UUID>();
  398. }
  399. [Obsolete]
  400. protected void ForwardStatusNotificationToSim(UUID regionID, UUID foreignUserID, string user, bool online)
  401. {
  402. UUID userID;
  403. if (UUID.TryParse(user, out userID))
  404. {
  405. if (m_FriendsLocalSimConnector != null)
  406. {
  407. m_log.DebugFormat("[USER AGENT SERVICE]: Local Notify, user {0} is {1}", foreignUserID, (online ? "online" : "offline"));
  408. m_FriendsLocalSimConnector.StatusNotify(foreignUserID, userID, online);
  409. }
  410. else
  411. {
  412. GridRegion region = m_GridService.GetRegionByUUID(UUID.Zero /* !!! */, regionID);
  413. if (region != null)
  414. {
  415. m_log.DebugFormat("[USER AGENT SERVICE]: Remote Notify to region {0}, user {1} is {2}", region.RegionName, foreignUserID, (online ? "online" : "offline"));
  416. m_FriendsSimConnector.StatusNotify(region, foreignUserID, userID.ToString(), online);
  417. }
  418. }
  419. }
  420. }
  421. public List<UUID> GetOnlineFriends(UUID foreignUserID, List<string> friends)
  422. {
  423. List<UUID> online = new List<UUID>();
  424. if (m_FriendsService == null || m_PresenceService == null)
  425. {
  426. m_log.WarnFormat("[USER AGENT SERVICE]: Unable to get online friends because friends or presence services are missing");
  427. return online;
  428. }
  429. m_log.DebugFormat("[USER AGENT SERVICE]: Foreign user {0} wants to know status of {1} local friends", foreignUserID, friends.Count);
  430. // First, let's double check that the reported friends are, indeed, friends of that user
  431. // And let's check that the secret matches and the rights
  432. List<string> usersToBeNotified = new List<string>();
  433. foreach (string uui in friends)
  434. {
  435. UUID localUserID;
  436. string secret = string.Empty, tmp = string.Empty;
  437. if (Util.ParseUniversalUserIdentifier(uui, out localUserID, out tmp, out tmp, out tmp, out secret))
  438. {
  439. FriendInfo[] friendInfos = m_FriendsService.GetFriends(localUserID);
  440. foreach (FriendInfo finfo in friendInfos)
  441. {
  442. if (finfo.Friend.StartsWith(foreignUserID.ToString()) && finfo.Friend.EndsWith(secret) &&
  443. (finfo.TheirFlags & (int)FriendRights.CanSeeOnline) != 0 && (finfo.TheirFlags != -1))
  444. {
  445. // great!
  446. usersToBeNotified.Add(localUserID.ToString());
  447. }
  448. }
  449. }
  450. }
  451. // Now, let's find out their status
  452. m_log.DebugFormat("[USER AGENT SERVICE]: GetOnlineFriends: user has {0} local friends with status rights", usersToBeNotified.Count);
  453. // First, let's send notifications to local users who are online in the home grid
  454. PresenceInfo[] friendSessions = m_PresenceService.GetAgents(usersToBeNotified.ToArray());
  455. if (friendSessions != null && friendSessions.Length > 0)
  456. {
  457. foreach (PresenceInfo pi in friendSessions)
  458. {
  459. UUID presenceID;
  460. if (UUID.TryParse(pi.UserID, out presenceID))
  461. online.Add(presenceID);
  462. }
  463. }
  464. return online;
  465. }
  466. public Dictionary<string, object> GetUserInfo(UUID userID)
  467. {
  468. Dictionary<string, object> info = new Dictionary<string, object>();
  469. if (m_UserAccountService == null)
  470. {
  471. m_log.WarnFormat("[USER AGENT SERVICE]: Unable to get user flags because user account service is missing");
  472. info["result"] = "fail";
  473. info["message"] = "UserAccountService is missing!";
  474. return info;
  475. }
  476. UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero /*!!!*/, userID);
  477. if (account != null)
  478. {
  479. info.Add("user_firstname", account.FirstName);
  480. info.Add("user_lastname", account.LastName);
  481. info.Add("result", "success");
  482. if (m_ShowDetails)
  483. {
  484. info.Add("user_flags", account.UserFlags);
  485. info.Add("user_created", account.Created);
  486. info.Add("user_title", account.UserTitle);
  487. }
  488. else
  489. {
  490. info.Add("user_flags", 0);
  491. info.Add("user_created", 0);
  492. info.Add("user_title", string.Empty);
  493. }
  494. }
  495. return info;
  496. }
  497. public Dictionary<string, object> GetServerURLs(UUID userID)
  498. {
  499. if (m_UserAccountService == null)
  500. {
  501. m_log.WarnFormat("[USER AGENT SERVICE]: Unable to get server URLs because user account service is missing");
  502. return new Dictionary<string, object>();
  503. }
  504. UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero /*!!!*/, userID);
  505. if (account != null)
  506. return account.ServiceURLs;
  507. return new Dictionary<string, object>();
  508. }
  509. public string LocateUser(UUID userID)
  510. {
  511. HGTravelingData[] hgts = m_Database.GetSessions(userID);
  512. if (hgts == null)
  513. return string.Empty;
  514. foreach (HGTravelingData t in hgts)
  515. if (t.Data.ContainsKey("GridExternalName") && !m_GridName.Equals(t.Data["GridExternalName"]))
  516. return t.Data["GridExternalName"];
  517. return string.Empty;
  518. }
  519. public string GetUUI(UUID userID, UUID targetUserID)
  520. {
  521. // Let's see if it's a local user
  522. UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero, targetUserID);
  523. if (account != null)
  524. return targetUserID.ToString() + ";" + m_GridName + ";" + account.FirstName + " " + account.LastName ;
  525. // Let's try the list of friends
  526. FriendInfo[] friends = m_FriendsService.GetFriends(userID);
  527. if (friends != null && friends.Length > 0)
  528. {
  529. foreach (FriendInfo f in friends)
  530. if (f.Friend.StartsWith(targetUserID.ToString()))
  531. {
  532. // Let's remove the secret
  533. UUID id; string tmp = string.Empty, secret = string.Empty;
  534. if (Util.ParseUniversalUserIdentifier(f.Friend, out id, out tmp, out tmp, out tmp, out secret))
  535. return f.Friend.Replace(secret, "0");
  536. }
  537. }
  538. return string.Empty;
  539. }
  540. public UUID GetUUID(String first, String last)
  541. {
  542. // Let's see if it's a local user
  543. UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero, first, last);
  544. if (account != null)
  545. {
  546. // check user level
  547. if (account.UserLevel < m_LevelOutsideContacts)
  548. return UUID.Zero;
  549. else
  550. return account.PrincipalID;
  551. }
  552. else
  553. return UUID.Zero;
  554. }
  555. #region Misc
  556. private bool IsException(string dest, int level, Dictionary<int, List<string>> exceptions)
  557. {
  558. if (!exceptions.ContainsKey(level))
  559. return false;
  560. bool exception = false;
  561. if (exceptions[level].Count > 0) // we have exceptions
  562. {
  563. string destination = dest;
  564. if (!destination.EndsWith("/"))
  565. destination += "/";
  566. if (exceptions[level].Find(delegate(string s)
  567. {
  568. if (!s.EndsWith("/"))
  569. s += "/";
  570. return s == destination;
  571. }) != null)
  572. exception = true;
  573. }
  574. return exception;
  575. }
  576. private void StoreTravelInfo(TravelingAgentInfo travel)
  577. {
  578. if (travel == null)
  579. return;
  580. HGTravelingData hgt = new HGTravelingData();
  581. hgt.SessionID = travel.SessionID;
  582. hgt.UserID = travel.UserID;
  583. hgt.Data = new Dictionary<string, string>();
  584. hgt.Data["GridExternalName"] = travel.GridExternalName;
  585. hgt.Data["ServiceToken"] = travel.ServiceToken;
  586. hgt.Data["ClientIPAddress"] = travel.ClientIPAddress;
  587. hgt.Data["MyIPAddress"] = travel.MyIpAddress;
  588. m_Database.Store(hgt);
  589. }
  590. #endregion
  591. }
  592. class TravelingAgentInfo
  593. {
  594. public UUID SessionID;
  595. public UUID UserID;
  596. public string GridExternalName = string.Empty;
  597. public string ServiceToken = string.Empty;
  598. public string ClientIPAddress = string.Empty; // as seen from this user agent service
  599. public string MyIpAddress = string.Empty; // the user agent service's external IP, as seen from the next gatekeeper
  600. public TravelingAgentInfo(HGTravelingData t)
  601. {
  602. if (t.Data != null)
  603. {
  604. SessionID = new UUID(t.SessionID);
  605. UserID = new UUID(t.UserID);
  606. GridExternalName = t.Data["GridExternalName"];
  607. ServiceToken = t.Data["ServiceToken"];
  608. ClientIPAddress = t.Data["ClientIPAddress"];
  609. MyIpAddress = t.Data["MyIPAddress"];
  610. }
  611. }
  612. public TravelingAgentInfo(TravelingAgentInfo old)
  613. {
  614. if (old != null)
  615. {
  616. SessionID = old.SessionID;
  617. UserID = old.UserID;
  618. GridExternalName = old.GridExternalName;
  619. ServiceToken = old.ServiceToken;
  620. ClientIPAddress = old.ClientIPAddress;
  621. MyIpAddress = old.MyIpAddress;
  622. }
  623. }
  624. }
  625. }