UserAgentService.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  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 == string.Empty || gridUserService == string.Empty || gatekeeperService == string.Empty)
  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 == string.Empty)
  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. exceptions[level].Add(s.Trim());
  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 != null)
  181. {
  182. if (uinfo.HomeRegionID != UUID.Zero)
  183. {
  184. home = m_GridService.GetRegionByUUID(UUID.Zero, uinfo.HomeRegionID);
  185. position = uinfo.HomePosition;
  186. lookAt = uinfo.HomeLookAt;
  187. }
  188. if (home == null)
  189. {
  190. List<GridRegion> defs = m_GridService.GetDefaultRegions(UUID.Zero);
  191. if (defs != 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 == 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 GridRegion(gatekeeper);
  229. region.ServerURI = gatekeeper.ServerURI;
  230. region.ExternalHostName = finalDestination.ExternalHostName;
  231. region.InternalEndPoint = finalDestination.InternalEndPoint;
  232. region.RegionName = finalDestination.RegionName;
  233. region.RegionID = finalDestination.RegionID;
  234. region.RegionLocX = finalDestination.RegionLocX;
  235. region.RegionLocY = finalDestination.RegionLocY;
  236. // Generate a new service session
  237. agentCircuit.ServiceSessionID = region.ServerURI + ";" + UUID.Random();
  238. TravelingAgentInfo old = null;
  239. TravelingAgentInfo travel = CreateTravelInfo(agentCircuit, region, fromLogin, out old);
  240. if(!fromLogin && old != null && !string.IsNullOrEmpty(old.ClientIPAddress))
  241. {
  242. m_log.DebugFormat("[USER AGENT SERVICE]: stored IP = {0}. Old circuit IP: {1}", old.ClientIPAddress, agentCircuit.IPAddress);
  243. agentCircuit.IPAddress = old.ClientIPAddress;
  244. }
  245. bool success = false;
  246. m_log.DebugFormat("[USER AGENT SERVICE]: this grid: {0}, desired grid: {1}, desired region: {2}", m_GridName, gridName, region.RegionID);
  247. if (m_GridName.Equals(gridName, StringComparison.InvariantCultureIgnoreCase))
  248. {
  249. success = m_GatekeeperService.LoginAgent(source, agentCircuit, finalDestination, out reason);
  250. }
  251. else
  252. {
  253. //TODO: Should there not be a call to QueryAccess here?
  254. EntityTransferContext ctx = new EntityTransferContext();
  255. success = m_GatekeeperConnector.CreateAgent(source, region, agentCircuit, (uint)Constants.TeleportFlags.ViaLogin, ctx, out reason);
  256. }
  257. if (!success)
  258. {
  259. m_log.DebugFormat("[USER AGENT SERVICE]: Unable to login user {0} {1} to grid {2}, reason: {3}",
  260. agentCircuit.firstname, agentCircuit.lastname, region.ServerURI, reason);
  261. if (old != null)
  262. StoreTravelInfo(old);
  263. else
  264. m_Database.Delete(agentCircuit.SessionID);
  265. return false;
  266. }
  267. // Everything is ok
  268. StoreTravelInfo(travel);
  269. return true;
  270. }
  271. public bool LoginAgentToGrid(GridRegion source, AgentCircuitData agentCircuit, GridRegion gatekeeper, GridRegion finalDestination, out string reason)
  272. {
  273. reason = string.Empty;
  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 != 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 TravelingAgentInfo(existing);
  289. travel.SessionID = agentCircuit.SessionID;
  290. travel.UserID = agentCircuit.AgentID;
  291. travel.GridExternalName = region.ServerURI;
  292. travel.ServiceToken = agentCircuit.ServiceSessionID;
  293. if (fromLogin)
  294. travel.ClientIPAddress = agentCircuit.IPAddress;
  295. StoreTravelInfo(travel);
  296. return travel;
  297. }
  298. public void LogoutAgent(UUID userID, UUID sessionID)
  299. {
  300. m_log.DebugFormat("[USER AGENT SERVICE]: User {0} logged out", userID);
  301. m_Database.Delete(sessionID);
  302. GridUserInfo guinfo = m_GridUserService.GetGridUserInfo(userID.ToString());
  303. if (guinfo != null)
  304. m_GridUserService.LoggedOut(userID.ToString(), sessionID, guinfo.LastRegionID, guinfo.LastPosition, guinfo.LastLookAt);
  305. }
  306. // We need to prevent foreign users with the same UUID as a local user
  307. public bool IsAgentComingHome(UUID sessionID, string thisGridExternalName)
  308. {
  309. HGTravelingData hgt = m_Database.Get(sessionID);
  310. if (hgt == null)
  311. return false;
  312. TravelingAgentInfo travel = new TravelingAgentInfo(hgt);
  313. return travel.GridExternalName.ToLower() == thisGridExternalName.ToLower();
  314. }
  315. public bool VerifyClient(UUID sessionID, string reportedIP)
  316. {
  317. if (m_BypassClientVerification)
  318. return true;
  319. m_log.DebugFormat("[USER AGENT SERVICE]: Verifying Client session {0} with reported IP {1}.",
  320. sessionID, reportedIP);
  321. HGTravelingData hgt = m_Database.Get(sessionID);
  322. if (hgt == null)
  323. return false;
  324. TravelingAgentInfo travel = new TravelingAgentInfo(hgt);
  325. bool result = travel.ClientIPAddress == reportedIP;
  326. if(!result && !string.IsNullOrEmpty(m_MyExternalIP))
  327. result = reportedIP == m_MyExternalIP; // NATed
  328. m_log.DebugFormat("[USER AGENT SERVICE]: Comparing {0} with login IP {1} and MyIP {2}; result is {3}",
  329. reportedIP, travel.ClientIPAddress, m_MyExternalIP, result);
  330. return result;
  331. }
  332. public bool VerifyAgent(UUID sessionID, string token)
  333. {
  334. HGTravelingData hgt = m_Database.Get(sessionID);
  335. if (hgt == null)
  336. {
  337. m_log.DebugFormat("[USER AGENT SERVICE]: Token verification for session {0}: no such session", sessionID);
  338. return false;
  339. }
  340. TravelingAgentInfo travel = new TravelingAgentInfo(hgt);
  341. m_log.DebugFormat("[USER AGENT SERVICE]: Verifying agent token {0} against {1}", token, travel.ServiceToken);
  342. return travel.ServiceToken == token;
  343. }
  344. [Obsolete]
  345. public List<UUID> StatusNotification(List<string> friends, UUID foreignUserID, bool online)
  346. {
  347. if (m_FriendsService == null || m_PresenceService == null)
  348. {
  349. m_log.WarnFormat("[USER AGENT SERVICE]: Unable to perform status notifications because friends or presence services are missing");
  350. return new List<UUID>();
  351. }
  352. List<UUID> localFriendsOnline = new List<UUID>();
  353. m_log.DebugFormat("[USER AGENT SERVICE]: Status notification: foreign user {0} wants to notify {1} local friends", foreignUserID, friends.Count);
  354. // First, let's double check that the reported friends are, indeed, friends of that user
  355. // And let's check that the secret matches
  356. List<string> usersToBeNotified = new List<string>();
  357. foreach (string uui in friends)
  358. {
  359. UUID localUserID;
  360. string secret = string.Empty, tmp = string.Empty;
  361. if (Util.ParseUniversalUserIdentifier(uui, out localUserID, out tmp, out tmp, out tmp, out secret))
  362. {
  363. FriendInfo[] friendInfos = m_FriendsService.GetFriends(localUserID);
  364. foreach (FriendInfo finfo in friendInfos)
  365. {
  366. if (finfo.Friend.StartsWith(foreignUserID.ToString()) && finfo.Friend.EndsWith(secret))
  367. {
  368. // great!
  369. usersToBeNotified.Add(localUserID.ToString());
  370. }
  371. }
  372. }
  373. }
  374. // Now, let's send the notifications
  375. m_log.DebugFormat("[USER AGENT SERVICE]: Status notification: user has {0} local friends", usersToBeNotified.Count);
  376. // First, let's send notifications to local users who are online in the home grid
  377. PresenceInfo[] friendSessions = m_PresenceService.GetAgents(usersToBeNotified.ToArray());
  378. if (friendSessions != null && friendSessions.Length > 0)
  379. {
  380. PresenceInfo friendSession = null;
  381. foreach (PresenceInfo pinfo in friendSessions)
  382. if (pinfo.RegionID != UUID.Zero) // let's guard against traveling agents
  383. {
  384. friendSession = pinfo;
  385. break;
  386. }
  387. if (friendSession != null)
  388. {
  389. ForwardStatusNotificationToSim(friendSession.RegionID, foreignUserID, friendSession.UserID, online);
  390. usersToBeNotified.Remove(friendSession.UserID.ToString());
  391. UUID id;
  392. if (UUID.TryParse(friendSession.UserID, out id))
  393. localFriendsOnline.Add(id);
  394. }
  395. }
  396. //// Lastly, let's notify the rest who may be online somewhere else
  397. //foreach (string user in usersToBeNotified)
  398. //{
  399. // UUID id = new UUID(user);
  400. // if (m_Database.ContainsKey(id) && m_Database[id].GridExternalName != m_GridName)
  401. // {
  402. // string url = m_Database[id].GridExternalName;
  403. // // forward
  404. // m_log.WarnFormat("[USER AGENT SERVICE]: User {0} is visiting {1}. HG Status notifications still not implemented.", user, url);
  405. // }
  406. //}
  407. // and finally, let's send the online friends
  408. if (online)
  409. {
  410. return localFriendsOnline;
  411. }
  412. else
  413. return new List<UUID>();
  414. }
  415. [Obsolete]
  416. protected void ForwardStatusNotificationToSim(UUID regionID, UUID foreignUserID, string user, bool online)
  417. {
  418. UUID userID;
  419. if (UUID.TryParse(user, out userID))
  420. {
  421. if (m_FriendsLocalSimConnector != null)
  422. {
  423. m_log.DebugFormat("[USER AGENT SERVICE]: Local Notify, user {0} is {1}", foreignUserID, (online ? "online" : "offline"));
  424. m_FriendsLocalSimConnector.StatusNotify(foreignUserID, userID, online);
  425. }
  426. else
  427. {
  428. GridRegion region = m_GridService.GetRegionByUUID(UUID.Zero /* !!! */, regionID);
  429. if (region != null)
  430. {
  431. m_log.DebugFormat("[USER AGENT SERVICE]: Remote Notify to region {0}, user {1} is {2}", region.RegionName, foreignUserID, (online ? "online" : "offline"));
  432. m_FriendsSimConnector.StatusNotify(region, foreignUserID, userID.ToString(), online);
  433. }
  434. }
  435. }
  436. }
  437. public List<UUID> GetOnlineFriends(UUID foreignUserID, List<string> friends)
  438. {
  439. List<UUID> online = new List<UUID>();
  440. if (m_FriendsService == null || m_PresenceService == null)
  441. {
  442. m_log.WarnFormat("[USER AGENT SERVICE]: Unable to get online friends because friends or presence services are missing");
  443. return online;
  444. }
  445. m_log.DebugFormat("[USER AGENT SERVICE]: Foreign user {0} wants to know status of {1} local friends", foreignUserID, friends.Count);
  446. // First, let's double check that the reported friends are, indeed, friends of that user
  447. // And let's check that the secret matches and the rights
  448. List<string> usersToBeNotified = new List<string>();
  449. foreach (string uui in friends)
  450. {
  451. UUID localUserID;
  452. string secret = string.Empty, tmp = string.Empty;
  453. if (Util.ParseUniversalUserIdentifier(uui, out localUserID, out tmp, out tmp, out tmp, out secret))
  454. {
  455. FriendInfo[] friendInfos = m_FriendsService.GetFriends(localUserID);
  456. foreach (FriendInfo finfo in friendInfos)
  457. {
  458. if (finfo.Friend.StartsWith(foreignUserID.ToString()) && finfo.Friend.EndsWith(secret) &&
  459. (finfo.TheirFlags & (int)FriendRights.CanSeeOnline) != 0 && (finfo.TheirFlags != -1))
  460. {
  461. // great!
  462. usersToBeNotified.Add(localUserID.ToString());
  463. }
  464. }
  465. }
  466. }
  467. // Now, let's find out their status
  468. m_log.DebugFormat("[USER AGENT SERVICE]: GetOnlineFriends: user has {0} local friends with status rights", usersToBeNotified.Count);
  469. // First, let's send notifications to local users who are online in the home grid
  470. PresenceInfo[] friendSessions = m_PresenceService.GetAgents(usersToBeNotified.ToArray());
  471. if (friendSessions != null && friendSessions.Length > 0)
  472. {
  473. foreach (PresenceInfo pi in friendSessions)
  474. {
  475. UUID presenceID;
  476. if (UUID.TryParse(pi.UserID, out presenceID))
  477. online.Add(presenceID);
  478. }
  479. }
  480. return online;
  481. }
  482. public Dictionary<string, object> GetUserInfo(UUID userID)
  483. {
  484. Dictionary<string, object> info = new Dictionary<string, object>();
  485. if (m_UserAccountService == null)
  486. {
  487. m_log.WarnFormat("[USER AGENT SERVICE]: Unable to get user flags because user account service is missing");
  488. info["result"] = "fail";
  489. info["message"] = "UserAccountService is missing!";
  490. return info;
  491. }
  492. UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero /*!!!*/, userID);
  493. if (account != null)
  494. {
  495. info.Add("user_firstname", account.FirstName);
  496. info.Add("user_lastname", account.LastName);
  497. info.Add("result", "success");
  498. if (m_ShowDetails)
  499. {
  500. info.Add("user_flags", account.UserFlags);
  501. info.Add("user_created", account.Created);
  502. info.Add("user_title", account.UserTitle);
  503. }
  504. else
  505. {
  506. info.Add("user_flags", 0);
  507. info.Add("user_created", 0);
  508. info.Add("user_title", string.Empty);
  509. }
  510. }
  511. return info;
  512. }
  513. public Dictionary<string, object> GetServerURLs(UUID userID)
  514. {
  515. if (m_UserAccountService == null)
  516. {
  517. m_log.WarnFormat("[USER AGENT SERVICE]: Unable to get server URLs because user account service is missing");
  518. return new Dictionary<string, object>();
  519. }
  520. UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero /*!!!*/, userID);
  521. if (account != null)
  522. return account.ServiceURLs;
  523. return new Dictionary<string, object>();
  524. }
  525. public string LocateUser(UUID userID)
  526. {
  527. HGTravelingData[] hgts = m_Database.GetSessions(userID);
  528. if (hgts == null)
  529. return string.Empty;
  530. foreach (HGTravelingData t in hgts)
  531. if (t.Data.ContainsKey("GridExternalName") && !m_GridName.Equals(t.Data["GridExternalName"]))
  532. return t.Data["GridExternalName"];
  533. return string.Empty;
  534. }
  535. public string GetUUI(UUID userID, UUID targetUserID)
  536. {
  537. // Let's see if it's a local user
  538. UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero, targetUserID);
  539. if (account != null)
  540. return targetUserID.ToString() + ";" + m_GridName + ";" + account.FirstName + " " + account.LastName ;
  541. // Let's try the list of friends
  542. if(m_FriendsService != null)
  543. {
  544. FriendInfo[] friends = m_FriendsService.GetFriends(userID);
  545. if (friends != null && friends.Length > 0)
  546. {
  547. foreach (FriendInfo f in friends)
  548. if (f.Friend.StartsWith(targetUserID.ToString()))
  549. {
  550. // Let's remove the secret
  551. UUID id; string tmp = string.Empty, secret = string.Empty;
  552. if (Util.ParseUniversalUserIdentifier(f.Friend, out id, out tmp, out tmp, out tmp, out secret))
  553. return f.Friend.Replace(secret, "0");
  554. }
  555. }
  556. }
  557. return string.Empty;
  558. }
  559. public UUID GetUUID(String first, String last)
  560. {
  561. // Let's see if it's a local user
  562. UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero, first, last);
  563. if (account != null)
  564. {
  565. // check user level
  566. if (account.UserLevel < m_LevelOutsideContacts)
  567. return UUID.Zero;
  568. else
  569. return account.PrincipalID;
  570. }
  571. else
  572. return UUID.Zero;
  573. }
  574. #region Misc
  575. private bool IsException(string dest, int level, Dictionary<int, List<string>> exceptions)
  576. {
  577. if (!exceptions.ContainsKey(level))
  578. return false;
  579. bool exception = false;
  580. if (exceptions[level].Count > 0) // we have exceptions
  581. {
  582. string destination = dest;
  583. if (!destination.EndsWith("/"))
  584. destination += "/";
  585. if (exceptions[level].Find(delegate(string s)
  586. {
  587. if (!s.EndsWith("/"))
  588. s += "/";
  589. return s == destination;
  590. }) != null)
  591. exception = true;
  592. }
  593. return exception;
  594. }
  595. private void StoreTravelInfo(TravelingAgentInfo travel)
  596. {
  597. if (travel == null)
  598. return;
  599. HGTravelingData hgt = new HGTravelingData();
  600. hgt.SessionID = travel.SessionID;
  601. hgt.UserID = travel.UserID;
  602. hgt.Data = new Dictionary<string, string>();
  603. hgt.Data["GridExternalName"] = travel.GridExternalName;
  604. hgt.Data["ServiceToken"] = travel.ServiceToken;
  605. hgt.Data["ClientIPAddress"] = travel.ClientIPAddress;
  606. m_Database.Store(hgt);
  607. }
  608. #endregion
  609. }
  610. class TravelingAgentInfo
  611. {
  612. public UUID SessionID;
  613. public UUID UserID;
  614. public string GridExternalName = string.Empty;
  615. public string ServiceToken = string.Empty;
  616. public string ClientIPAddress = string.Empty; // as seen from this user agent service
  617. public TravelingAgentInfo(HGTravelingData t)
  618. {
  619. if (t.Data != null)
  620. {
  621. SessionID = new UUID(t.SessionID);
  622. UserID = new UUID(t.UserID);
  623. GridExternalName = t.Data["GridExternalName"];
  624. ServiceToken = t.Data["ServiceToken"];
  625. ClientIPAddress = t.Data["ClientIPAddress"];
  626. }
  627. }
  628. public TravelingAgentInfo(TravelingAgentInfo old)
  629. {
  630. if (old != null)
  631. {
  632. SessionID = old.SessionID;
  633. UserID = old.UserID;
  634. GridExternalName = old.GridExternalName;
  635. ServiceToken = old.ServiceToken;
  636. ClientIPAddress = old.ClientIPAddress;
  637. }
  638. }
  639. }
  640. }