1
0

UserAgentService.cs 32 KB

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