UserAgentService.cs 33 KB

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