LLLoginService.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928
  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;
  29. using System.Collections.Generic;
  30. using System.Linq;
  31. using System.Net;
  32. using System.Reflection;
  33. using System.Text.RegularExpressions;
  34. using log4net;
  35. using Nini.Config;
  36. using OpenMetaverse;
  37. using OpenSim.Framework;
  38. using OpenSim.Framework.Console;
  39. using OpenSim.Server.Base;
  40. using OpenSim.Services.Interfaces;
  41. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  42. using FriendInfo = OpenSim.Services.Interfaces.FriendInfo;
  43. using OpenSim.Services.Connectors.Hypergrid;
  44. namespace OpenSim.Services.LLLoginService
  45. {
  46. public class LLLoginService : ILoginService
  47. {
  48. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  49. private static bool Initialized = false;
  50. protected IUserAccountService m_UserAccountService;
  51. protected IGridUserService m_GridUserService;
  52. protected IAuthenticationService m_AuthenticationService;
  53. protected IInventoryService m_InventoryService;
  54. protected IGridService m_GridService;
  55. protected IPresenceService m_PresenceService;
  56. protected ISimulationService m_LocalSimulationService;
  57. protected ISimulationService m_RemoteSimulationService;
  58. protected ILibraryService m_LibraryService;
  59. protected IFriendsService m_FriendsService;
  60. protected IAvatarService m_AvatarService;
  61. protected IUserAgentService m_UserAgentService;
  62. protected GatekeeperServiceConnector m_GatekeeperConnector;
  63. protected string m_DefaultRegionName;
  64. protected string m_WelcomeMessage;
  65. protected bool m_RequireInventory;
  66. protected int m_MinLoginLevel;
  67. protected string m_GatekeeperURL;
  68. protected bool m_AllowRemoteSetLoginLevel;
  69. protected string m_MapTileURL;
  70. protected string m_SearchURL;
  71. protected string m_Currency;
  72. protected string m_AllowedClients;
  73. protected string m_DeniedClients;
  74. IConfig m_LoginServerConfig;
  75. IConfig m_ClientsConfig;
  76. public LLLoginService(IConfigSource config, ISimulationService simService, ILibraryService libraryService)
  77. {
  78. m_LoginServerConfig = config.Configs["LoginService"];
  79. if (m_LoginServerConfig == null)
  80. throw new Exception(String.Format("No section LoginService in config file"));
  81. string accountService = m_LoginServerConfig.GetString("UserAccountService", String.Empty);
  82. string gridUserService = m_LoginServerConfig.GetString("GridUserService", String.Empty);
  83. string agentService = m_LoginServerConfig.GetString("UserAgentService", String.Empty);
  84. string authService = m_LoginServerConfig.GetString("AuthenticationService", String.Empty);
  85. string invService = m_LoginServerConfig.GetString("InventoryService", String.Empty);
  86. string gridService = m_LoginServerConfig.GetString("GridService", String.Empty);
  87. string presenceService = m_LoginServerConfig.GetString("PresenceService", String.Empty);
  88. string libService = m_LoginServerConfig.GetString("LibraryService", String.Empty);
  89. string friendsService = m_LoginServerConfig.GetString("FriendsService", String.Empty);
  90. string avatarService = m_LoginServerConfig.GetString("AvatarService", String.Empty);
  91. string simulationService = m_LoginServerConfig.GetString("SimulationService", String.Empty);
  92. m_DefaultRegionName = m_LoginServerConfig.GetString("DefaultRegion", String.Empty);
  93. m_WelcomeMessage = m_LoginServerConfig.GetString("WelcomeMessage", "Welcome to OpenSim!");
  94. m_RequireInventory = m_LoginServerConfig.GetBoolean("RequireInventory", true);
  95. m_AllowRemoteSetLoginLevel = m_LoginServerConfig.GetBoolean("AllowRemoteSetLoginLevel", false);
  96. m_MinLoginLevel = m_LoginServerConfig.GetInt("MinLoginLevel", 0);
  97. m_GatekeeperURL = m_LoginServerConfig.GetString("GatekeeperURI", string.Empty);
  98. m_MapTileURL = m_LoginServerConfig.GetString("MapTileURL", string.Empty);
  99. m_SearchURL = m_LoginServerConfig.GetString("SearchURL", string.Empty);
  100. m_Currency = m_LoginServerConfig.GetString("Currency", string.Empty);
  101. m_AllowedClients = m_LoginServerConfig.GetString("AllowedClients", string.Empty);
  102. m_DeniedClients = m_LoginServerConfig.GetString("DeniedClients", string.Empty);
  103. // Clean up some of these vars
  104. if (m_MapTileURL != String.Empty)
  105. {
  106. m_MapTileURL = m_MapTileURL.Trim();
  107. if (!m_MapTileURL.EndsWith("/"))
  108. m_MapTileURL = m_MapTileURL + "/";
  109. }
  110. // These are required; the others aren't
  111. if (accountService == string.Empty || authService == string.Empty)
  112. throw new Exception("LoginService is missing service specifications");
  113. Object[] args = new Object[] { config };
  114. m_UserAccountService = ServerUtils.LoadPlugin<IUserAccountService>(accountService, args);
  115. m_GridUserService = ServerUtils.LoadPlugin<IGridUserService>(gridUserService, args);
  116. m_AuthenticationService = ServerUtils.LoadPlugin<IAuthenticationService>(authService, args);
  117. m_InventoryService = ServerUtils.LoadPlugin<IInventoryService>(invService, args);
  118. if (gridService != string.Empty)
  119. m_GridService = ServerUtils.LoadPlugin<IGridService>(gridService, args);
  120. if (presenceService != string.Empty)
  121. m_PresenceService = ServerUtils.LoadPlugin<IPresenceService>(presenceService, args);
  122. if (avatarService != string.Empty)
  123. m_AvatarService = ServerUtils.LoadPlugin<IAvatarService>(avatarService, args);
  124. if (friendsService != string.Empty)
  125. m_FriendsService = ServerUtils.LoadPlugin<IFriendsService>(friendsService, args);
  126. if (simulationService != string.Empty)
  127. m_RemoteSimulationService = ServerUtils.LoadPlugin<ISimulationService>(simulationService, args);
  128. if (agentService != string.Empty)
  129. m_UserAgentService = ServerUtils.LoadPlugin<IUserAgentService>(agentService, args);
  130. //
  131. // deal with the services given as argument
  132. //
  133. m_LocalSimulationService = simService;
  134. if (libraryService != null)
  135. {
  136. m_log.DebugFormat("[LLOGIN SERVICE]: Using LibraryService given as argument");
  137. m_LibraryService = libraryService;
  138. }
  139. else if (libService != string.Empty)
  140. {
  141. m_log.DebugFormat("[LLOGIN SERVICE]: Using instantiated LibraryService");
  142. m_LibraryService = ServerUtils.LoadPlugin<ILibraryService>(libService, args);
  143. }
  144. m_GatekeeperConnector = new GatekeeperServiceConnector();
  145. if (!Initialized)
  146. {
  147. Initialized = true;
  148. RegisterCommands();
  149. }
  150. m_log.DebugFormat("[LLOGIN SERVICE]: Starting...");
  151. }
  152. public LLLoginService(IConfigSource config) : this(config, null, null)
  153. {
  154. }
  155. public Hashtable SetLevel(string firstName, string lastName, string passwd, int level, IPEndPoint clientIP)
  156. {
  157. Hashtable response = new Hashtable();
  158. response["success"] = "false";
  159. if (!m_AllowRemoteSetLoginLevel)
  160. return response;
  161. try
  162. {
  163. UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero, firstName, lastName);
  164. if (account == null)
  165. {
  166. m_log.InfoFormat("[LLOGIN SERVICE]: Set Level failed, user {0} {1} not found", firstName, lastName);
  167. return response;
  168. }
  169. if (account.UserLevel < 200)
  170. {
  171. m_log.InfoFormat("[LLOGIN SERVICE]: Set Level failed, reason: user level too low");
  172. return response;
  173. }
  174. //
  175. // Authenticate this user
  176. //
  177. // We don't support clear passwords here
  178. //
  179. string token = m_AuthenticationService.Authenticate(account.PrincipalID, passwd, 30);
  180. UUID secureSession = UUID.Zero;
  181. if ((token == string.Empty) || (token != string.Empty && !UUID.TryParse(token, out secureSession)))
  182. {
  183. m_log.InfoFormat("[LLOGIN SERVICE]: SetLevel failed, reason: authentication failed");
  184. return response;
  185. }
  186. }
  187. catch (Exception e)
  188. {
  189. m_log.Error("[LLOGIN SERVICE]: SetLevel failed, exception " + e.ToString());
  190. return response;
  191. }
  192. m_MinLoginLevel = level;
  193. m_log.InfoFormat("[LLOGIN SERVICE]: Login level set to {0} by {1} {2}", level, firstName, lastName);
  194. response["success"] = true;
  195. return response;
  196. }
  197. public LoginResponse Login(string firstName, string lastName, string passwd, string startLocation, UUID scopeID,
  198. string clientVersion, string channel, string mac, string id0, IPEndPoint clientIP)
  199. {
  200. bool success = false;
  201. UUID session = UUID.Random();
  202. m_log.InfoFormat("[LLOGIN SERVICE]: Login request for {0} {1} at {2} using viewer {3}, channel {4}, IP {5}, Mac {6}, Id0 {7}",
  203. firstName, lastName, startLocation, clientVersion, channel, clientIP.Address.ToString(), mac, id0);
  204. try
  205. {
  206. //
  207. // Check client
  208. //
  209. if (m_AllowedClients != string.Empty)
  210. {
  211. Regex arx = new Regex(m_AllowedClients);
  212. Match am = arx.Match(clientVersion);
  213. if (!am.Success)
  214. {
  215. m_log.InfoFormat("[LLOGIN SERVICE]: Login failed, reason: client {0} is not allowed", clientVersion);
  216. return LLFailedLoginResponse.LoginBlockedProblem;
  217. }
  218. }
  219. if (m_DeniedClients != string.Empty)
  220. {
  221. Regex drx = new Regex(m_DeniedClients);
  222. Match dm = drx.Match(clientVersion);
  223. if (dm.Success)
  224. {
  225. m_log.InfoFormat("[LLOGIN SERVICE]: Login failed, reason: client {0} is denied", clientVersion);
  226. return LLFailedLoginResponse.LoginBlockedProblem;
  227. }
  228. }
  229. //
  230. // Get the account and check that it exists
  231. //
  232. UserAccount account = m_UserAccountService.GetUserAccount(scopeID, firstName, lastName);
  233. if (account == null)
  234. {
  235. m_log.InfoFormat("[LLOGIN SERVICE]: Login failed, reason: user not found");
  236. return LLFailedLoginResponse.UserProblem;
  237. }
  238. if (account.UserLevel < m_MinLoginLevel)
  239. {
  240. m_log.InfoFormat("[LLOGIN SERVICE]: Login failed, reason: login is blocked for user level {0}", account.UserLevel);
  241. return LLFailedLoginResponse.LoginBlockedProblem;
  242. }
  243. // If a scope id is requested, check that the account is in
  244. // that scope, or unscoped.
  245. //
  246. if (scopeID != UUID.Zero)
  247. {
  248. if (account.ScopeID != scopeID && account.ScopeID != UUID.Zero)
  249. {
  250. m_log.InfoFormat("[LLOGIN SERVICE]: Login failed, reason: user not found");
  251. return LLFailedLoginResponse.UserProblem;
  252. }
  253. }
  254. else
  255. {
  256. scopeID = account.ScopeID;
  257. }
  258. //
  259. // Authenticate this user
  260. //
  261. if (!passwd.StartsWith("$1$"))
  262. passwd = "$1$" + Util.Md5Hash(passwd);
  263. passwd = passwd.Remove(0, 3); //remove $1$
  264. string token = m_AuthenticationService.Authenticate(account.PrincipalID, passwd, 30);
  265. UUID secureSession = UUID.Zero;
  266. if ((token == string.Empty) || (token != string.Empty && !UUID.TryParse(token, out secureSession)))
  267. {
  268. m_log.InfoFormat("[LLOGIN SERVICE]: Login failed, reason: authentication failed");
  269. return LLFailedLoginResponse.UserProblem;
  270. }
  271. //
  272. // Get the user's inventory
  273. //
  274. if (m_RequireInventory && m_InventoryService == null)
  275. {
  276. m_log.WarnFormat("[LLOGIN SERVICE]: Login failed, reason: inventory service not set up");
  277. return LLFailedLoginResponse.InventoryProblem;
  278. }
  279. List<InventoryFolderBase> inventorySkel = m_InventoryService.GetInventorySkeleton(account.PrincipalID);
  280. if (m_RequireInventory && ((inventorySkel == null) || (inventorySkel != null && inventorySkel.Count == 0)))
  281. {
  282. m_log.InfoFormat("[LLOGIN SERVICE]: Login failed, reason: unable to retrieve user inventory");
  283. return LLFailedLoginResponse.InventoryProblem;
  284. }
  285. // Get active gestures
  286. List<InventoryItemBase> gestures = m_InventoryService.GetActiveGestures(account.PrincipalID);
  287. // m_log.DebugFormat("[LLOGIN SERVICE]: {0} active gestures", gestures.Count);
  288. //
  289. // Login the presence
  290. //
  291. if (m_PresenceService != null)
  292. {
  293. success = m_PresenceService.LoginAgent(account.PrincipalID.ToString(), session, secureSession);
  294. if (!success)
  295. {
  296. m_log.InfoFormat("[LLOGIN SERVICE]: Login failed, reason: could not login presence");
  297. return LLFailedLoginResponse.GridProblem;
  298. }
  299. }
  300. //
  301. // Change Online status and get the home region
  302. //
  303. GridRegion home = null;
  304. GridUserInfo guinfo = m_GridUserService.LoggedIn(account.PrincipalID.ToString());
  305. if (guinfo != null && (guinfo.HomeRegionID != UUID.Zero) && m_GridService != null)
  306. {
  307. home = m_GridService.GetRegionByUUID(scopeID, guinfo.HomeRegionID);
  308. }
  309. if (guinfo == null)
  310. {
  311. // something went wrong, make something up, so that we don't have to test this anywhere else
  312. guinfo = new GridUserInfo();
  313. guinfo.LastPosition = guinfo.HomePosition = new Vector3(128, 128, 30);
  314. }
  315. //
  316. // Find the destination region/grid
  317. //
  318. string where = string.Empty;
  319. Vector3 position = Vector3.Zero;
  320. Vector3 lookAt = Vector3.Zero;
  321. GridRegion gatekeeper = null;
  322. TeleportFlags flags;
  323. GridRegion destination = FindDestination(account, scopeID, guinfo, session, startLocation, home, out gatekeeper, out where, out position, out lookAt, out flags);
  324. if (destination == null)
  325. {
  326. m_PresenceService.LogoutAgent(session);
  327. m_log.InfoFormat("[LLOGIN SERVICE]: Login failed, reason: destination not found");
  328. return LLFailedLoginResponse.GridProblem;
  329. }
  330. if (account.UserLevel >= 200)
  331. flags |= TeleportFlags.Godlike;
  332. //
  333. // Get the avatar
  334. //
  335. AvatarAppearance avatar = null;
  336. if (m_AvatarService != null)
  337. {
  338. avatar = m_AvatarService.GetAppearance(account.PrincipalID);
  339. }
  340. //
  341. // Instantiate/get the simulation interface and launch an agent at the destination
  342. //
  343. string reason = string.Empty;
  344. GridRegion dest;
  345. AgentCircuitData aCircuit = LaunchAgentAtGrid(gatekeeper, destination, account, avatar, session, secureSession, position, where,
  346. clientVersion, channel, mac, id0, clientIP, flags, out where, out reason, out dest);
  347. destination = dest;
  348. if (aCircuit == null)
  349. {
  350. m_PresenceService.LogoutAgent(session);
  351. m_log.InfoFormat("[LLOGIN SERVICE]: Login failed, reason: {0}", reason);
  352. return new LLFailedLoginResponse("key", reason, "false");
  353. }
  354. // Get Friends list
  355. FriendInfo[] friendsList = new FriendInfo[0];
  356. if (m_FriendsService != null)
  357. {
  358. friendsList = m_FriendsService.GetFriends(account.PrincipalID);
  359. // m_log.DebugFormat("[LLOGIN SERVICE]: Retrieved {0} friends", friendsList.Length);
  360. }
  361. //
  362. // Finally, fill out the response and return it
  363. //
  364. LLLoginResponse response = new LLLoginResponse(account, aCircuit, guinfo, destination, inventorySkel, friendsList, m_LibraryService,
  365. where, startLocation, position, lookAt, gestures, m_WelcomeMessage, home, clientIP, m_MapTileURL, m_SearchURL, m_Currency);
  366. m_log.DebugFormat("[LLOGIN SERVICE]: All clear. Sending login response to client.");
  367. return response;
  368. }
  369. catch (Exception e)
  370. {
  371. m_log.WarnFormat("[LLOGIN SERVICE]: Exception processing login for {0} {1}: {2} {3}", firstName, lastName, e.ToString(), e.StackTrace);
  372. if (m_PresenceService != null)
  373. m_PresenceService.LogoutAgent(session);
  374. return LLFailedLoginResponse.InternalError;
  375. }
  376. }
  377. protected GridRegion FindDestination(UserAccount account, UUID scopeID, GridUserInfo pinfo, UUID sessionID, string startLocation, GridRegion home, out GridRegion gatekeeper, out string where, out Vector3 position, out Vector3 lookAt, out TeleportFlags flags)
  378. {
  379. flags = TeleportFlags.ViaLogin;
  380. m_log.DebugFormat("[LLOGIN SERVICE]: FindDestination for start location {0}", startLocation);
  381. gatekeeper = null;
  382. where = "home";
  383. position = new Vector3(128, 128, 0);
  384. lookAt = new Vector3(0, 1, 0);
  385. if (m_GridService == null)
  386. return null;
  387. if (startLocation.Equals("home"))
  388. {
  389. // logging into home region
  390. if (pinfo == null)
  391. return null;
  392. GridRegion region = null;
  393. bool tryDefaults = false;
  394. if (home == null)
  395. {
  396. m_log.WarnFormat(
  397. "[LLOGIN SERVICE]: User {0} {1} tried to login to a 'home' start location but they have none set",
  398. account.FirstName, account.LastName);
  399. tryDefaults = true;
  400. }
  401. else
  402. {
  403. region = home;
  404. position = pinfo.HomePosition;
  405. lookAt = pinfo.HomeLookAt;
  406. }
  407. if (tryDefaults)
  408. {
  409. List<GridRegion> defaults = m_GridService.GetDefaultRegions(scopeID);
  410. if (defaults != null && defaults.Count > 0)
  411. {
  412. region = defaults[0];
  413. where = "safe";
  414. }
  415. else
  416. {
  417. m_log.WarnFormat("[LLOGIN SERVICE]: User {0} {1} does not have a valid home and this grid does not have default locations. Attempting to find random region",
  418. account.FirstName, account.LastName);
  419. region = FindAlternativeRegion(scopeID);
  420. if (region != null)
  421. where = "safe";
  422. }
  423. }
  424. return region;
  425. }
  426. else if (startLocation.Equals("last"))
  427. {
  428. // logging into last visited region
  429. where = "last";
  430. if (pinfo == null)
  431. return null;
  432. GridRegion region = null;
  433. if (pinfo.LastRegionID.Equals(UUID.Zero) || (region = m_GridService.GetRegionByUUID(scopeID, pinfo.LastRegionID)) == null)
  434. {
  435. List<GridRegion> defaults = m_GridService.GetDefaultRegions(scopeID);
  436. if (defaults != null && defaults.Count > 0)
  437. {
  438. region = defaults[0];
  439. where = "safe";
  440. }
  441. else
  442. {
  443. m_log.Info("[LLOGIN SERVICE]: Last Region Not Found Attempting to find random region");
  444. region = FindAlternativeRegion(scopeID);
  445. if (region != null)
  446. where = "safe";
  447. }
  448. }
  449. else
  450. {
  451. position = pinfo.LastPosition;
  452. lookAt = pinfo.LastLookAt;
  453. }
  454. return region;
  455. }
  456. else
  457. {
  458. flags |= TeleportFlags.ViaRegionID;
  459. // free uri form
  460. // e.g. New Moon&135&46 New [email protected]:8002&153&34
  461. where = "url";
  462. GridRegion region = null;
  463. Regex reURI = new Regex(@"^uri:(?<region>[^&]+)&(?<x>\d+)&(?<y>\d+)&(?<z>\d+)$");
  464. Match uriMatch = reURI.Match(startLocation);
  465. if (uriMatch == null)
  466. {
  467. m_log.InfoFormat("[LLLOGIN SERVICE]: Got Custom Login URI {0}, but can't process it", startLocation);
  468. return null;
  469. }
  470. else
  471. {
  472. position = new Vector3(float.Parse(uriMatch.Groups["x"].Value, Culture.NumberFormatInfo),
  473. float.Parse(uriMatch.Groups["y"].Value, Culture.NumberFormatInfo),
  474. float.Parse(uriMatch.Groups["z"].Value, Culture.NumberFormatInfo));
  475. string regionName = uriMatch.Groups["region"].ToString();
  476. if (regionName != null)
  477. {
  478. if (!regionName.Contains("@"))
  479. {
  480. List<GridRegion> regions = m_GridService.GetRegionsByName(scopeID, regionName, 1);
  481. if ((regions == null) || (regions != null && regions.Count == 0))
  482. {
  483. m_log.InfoFormat("[LLLOGIN SERVICE]: Got Custom Login URI {0}, can't locate region {1}. Trying defaults.", startLocation, regionName);
  484. regions = m_GridService.GetDefaultRegions(scopeID);
  485. if (regions != null && regions.Count > 0)
  486. {
  487. where = "safe";
  488. return regions[0];
  489. }
  490. else
  491. {
  492. m_log.Info("[LLOGIN SERVICE]: Last Region Not Found Attempting to find random region");
  493. region = FindAlternativeRegion(scopeID);
  494. if (region != null)
  495. {
  496. where = "safe";
  497. return region;
  498. }
  499. else
  500. {
  501. m_log.InfoFormat("[LLLOGIN SERVICE]: Got Custom Login URI {0}, Grid does not provide default regions and no alternative found.", startLocation);
  502. return null;
  503. }
  504. }
  505. }
  506. return regions[0];
  507. }
  508. else
  509. {
  510. if (m_UserAgentService == null)
  511. {
  512. m_log.WarnFormat("[LLLOGIN SERVICE]: This llogin service is not running a user agent service, as such it can't lauch agents at foreign grids");
  513. return null;
  514. }
  515. string[] parts = regionName.Split(new char[] { '@' });
  516. if (parts.Length < 2)
  517. {
  518. m_log.InfoFormat("[LLLOGIN SERVICE]: Got Custom Login URI {0}, can't locate region {1}", startLocation, regionName);
  519. return null;
  520. }
  521. // Valid specification of a remote grid
  522. regionName = parts[0];
  523. string domainLocator = parts[1];
  524. parts = domainLocator.Split(new char[] {':'});
  525. string domainName = parts[0];
  526. uint port = 0;
  527. if (parts.Length > 1)
  528. UInt32.TryParse(parts[1], out port);
  529. // GridRegion region = FindForeignRegion(domainName, port, regionName, out gatekeeper);
  530. region = FindForeignRegion(domainName, port, regionName, out gatekeeper);
  531. return region;
  532. }
  533. }
  534. else
  535. {
  536. List<GridRegion> defaults = m_GridService.GetDefaultRegions(scopeID);
  537. if (defaults != null && defaults.Count > 0)
  538. {
  539. where = "safe";
  540. return defaults[0];
  541. }
  542. else
  543. return null;
  544. }
  545. }
  546. //response.LookAt = "[r0,r1,r0]";
  547. //// can be: last, home, safe, url
  548. //response.StartLocation = "url";
  549. }
  550. }
  551. private GridRegion FindAlternativeRegion(UUID scopeID)
  552. {
  553. List<GridRegion> hyperlinks = null;
  554. List<GridRegion> regions = m_GridService.GetFallbackRegions(scopeID, 1000 * (int)Constants.RegionSize, 1000 * (int)Constants.RegionSize);
  555. if (regions != null && regions.Count > 0)
  556. {
  557. hyperlinks = m_GridService.GetHyperlinks(scopeID);
  558. IEnumerable<GridRegion> availableRegions = regions.Except(hyperlinks);
  559. if (availableRegions.Count() > 0)
  560. return availableRegions.ElementAt(0);
  561. }
  562. // No fallbacks, try to find an arbitrary region that is not a hyperlink
  563. // maxNumber is fixed for now; maybe use some search pattern with increasing maxSize here?
  564. regions = m_GridService.GetRegionsByName(scopeID, "", 10);
  565. if (regions != null && regions.Count > 0)
  566. {
  567. if (hyperlinks == null)
  568. hyperlinks = m_GridService.GetHyperlinks(scopeID);
  569. IEnumerable<GridRegion> availableRegions = regions.Except(hyperlinks);
  570. if (availableRegions.Count() > 0)
  571. return availableRegions.ElementAt(0);
  572. }
  573. return null;
  574. }
  575. private GridRegion FindForeignRegion(string domainName, uint port, string regionName, out GridRegion gatekeeper)
  576. {
  577. m_log.Debug("[LLLOGIN SERVICE]: attempting to findforeignregion " + domainName + ":" + port.ToString() + ":" + regionName);
  578. gatekeeper = new GridRegion();
  579. gatekeeper.ExternalHostName = domainName;
  580. gatekeeper.HttpPort = port;
  581. gatekeeper.RegionName = regionName;
  582. gatekeeper.InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), 0);
  583. UUID regionID;
  584. ulong handle;
  585. string imageURL = string.Empty, reason = string.Empty;
  586. if (m_GatekeeperConnector.LinkRegion(gatekeeper, out regionID, out handle, out domainName, out imageURL, out reason))
  587. {
  588. GridRegion destination = m_GatekeeperConnector.GetHyperlinkRegion(gatekeeper, regionID);
  589. return destination;
  590. }
  591. return null;
  592. }
  593. private string hostName = string.Empty;
  594. private int port = 0;
  595. private void SetHostAndPort(string url)
  596. {
  597. try
  598. {
  599. Uri uri = new Uri(url);
  600. hostName = uri.Host;
  601. port = uri.Port;
  602. }
  603. catch
  604. {
  605. m_log.WarnFormat("[LLLogin SERVICE]: Unable to parse GatekeeperURL {0}", url);
  606. }
  607. }
  608. protected AgentCircuitData LaunchAgentAtGrid(GridRegion gatekeeper, GridRegion destination, UserAccount account, AvatarAppearance avatar,
  609. UUID session, UUID secureSession, Vector3 position, string currentWhere, string viewer, string channel, string mac, string id0,
  610. IPEndPoint clientIP, TeleportFlags flags, out string where, out string reason, out GridRegion dest)
  611. {
  612. where = currentWhere;
  613. ISimulationService simConnector = null;
  614. reason = string.Empty;
  615. uint circuitCode = 0;
  616. AgentCircuitData aCircuit = null;
  617. if (m_UserAgentService == null)
  618. {
  619. // HG standalones have both a localSimulatonDll and a remoteSimulationDll
  620. // non-HG standalones have just a localSimulationDll
  621. // independent login servers have just a remoteSimulationDll
  622. if (m_LocalSimulationService != null)
  623. simConnector = m_LocalSimulationService;
  624. else if (m_RemoteSimulationService != null)
  625. simConnector = m_RemoteSimulationService;
  626. }
  627. else // User Agent Service is on
  628. {
  629. if (gatekeeper == null) // login to local grid
  630. {
  631. if (hostName == string.Empty)
  632. SetHostAndPort(m_GatekeeperURL);
  633. gatekeeper = new GridRegion(destination);
  634. gatekeeper.ExternalHostName = hostName;
  635. gatekeeper.HttpPort = (uint)port;
  636. gatekeeper.ServerURI = m_GatekeeperURL;
  637. }
  638. m_log.Debug("[LLLOGIN SERVICE]: no gatekeeper detected..... using " + m_GatekeeperURL);
  639. }
  640. bool success = false;
  641. if (m_UserAgentService == null && simConnector != null)
  642. {
  643. circuitCode = (uint)Util.RandomClass.Next(); ;
  644. aCircuit = MakeAgent(destination, account, avatar, session, secureSession, circuitCode, position, clientIP.Address.ToString(), viewer, channel, mac, id0);
  645. success = LaunchAgentDirectly(simConnector, destination, aCircuit, flags, out reason);
  646. if (!success && m_GridService != null)
  647. {
  648. // Try the fallback regions
  649. List<GridRegion> fallbacks = m_GridService.GetFallbackRegions(account.ScopeID, destination.RegionLocX, destination.RegionLocY);
  650. if (fallbacks != null)
  651. {
  652. foreach (GridRegion r in fallbacks)
  653. {
  654. success = LaunchAgentDirectly(simConnector, r, aCircuit, flags | TeleportFlags.ViaRegionID, out reason);
  655. if (success)
  656. {
  657. where = "safe";
  658. destination = r;
  659. break;
  660. }
  661. }
  662. }
  663. }
  664. }
  665. if (m_UserAgentService != null)
  666. {
  667. circuitCode = (uint)Util.RandomClass.Next(); ;
  668. aCircuit = MakeAgent(destination, account, avatar, session, secureSession, circuitCode, position, clientIP.Address.ToString(), viewer, channel, mac, id0);
  669. success = LaunchAgentIndirectly(gatekeeper, destination, aCircuit, clientIP, out reason);
  670. if (!success && m_GridService != null)
  671. {
  672. // Try the fallback regions
  673. List<GridRegion> fallbacks = m_GridService.GetFallbackRegions(account.ScopeID, destination.RegionLocX, destination.RegionLocY);
  674. if (fallbacks != null)
  675. {
  676. foreach (GridRegion r in fallbacks)
  677. {
  678. success = LaunchAgentIndirectly(gatekeeper, r, aCircuit, clientIP, out reason);
  679. if (success)
  680. {
  681. where = "safe";
  682. destination = r;
  683. break;
  684. }
  685. }
  686. }
  687. }
  688. }
  689. dest = destination;
  690. if (success)
  691. return aCircuit;
  692. else
  693. return null;
  694. }
  695. private AgentCircuitData MakeAgent(GridRegion region, UserAccount account,
  696. AvatarAppearance avatar, UUID session, UUID secureSession, uint circuit, Vector3 position,
  697. string ipaddress, string viewer, string channel, string mac, string id0)
  698. {
  699. AgentCircuitData aCircuit = new AgentCircuitData();
  700. aCircuit.AgentID = account.PrincipalID;
  701. if (avatar != null)
  702. aCircuit.Appearance = new AvatarAppearance(avatar);
  703. else
  704. aCircuit.Appearance = new AvatarAppearance();
  705. //aCircuit.BaseFolder = irrelevant
  706. aCircuit.CapsPath = CapsUtil.GetRandomCapsObjectPath();
  707. aCircuit.child = false; // the first login agent is root
  708. aCircuit.ChildrenCapSeeds = new Dictionary<ulong, string>();
  709. aCircuit.circuitcode = circuit;
  710. aCircuit.firstname = account.FirstName;
  711. //aCircuit.InventoryFolder = irrelevant
  712. aCircuit.lastname = account.LastName;
  713. aCircuit.SecureSessionID = secureSession;
  714. aCircuit.SessionID = session;
  715. aCircuit.startpos = position;
  716. aCircuit.IPAddress = ipaddress;
  717. aCircuit.Viewer = viewer;
  718. aCircuit.Channel = channel;
  719. aCircuit.Mac = mac;
  720. aCircuit.Id0 = id0;
  721. SetServiceURLs(aCircuit, account);
  722. return aCircuit;
  723. //m_UserAgentService.LoginAgentToGrid(aCircuit, GatekeeperServiceConnector, region, out reason);
  724. //if (simConnector.CreateAgent(region, aCircuit, 0, out reason))
  725. // return aCircuit;
  726. //return null;
  727. }
  728. private void SetServiceURLs(AgentCircuitData aCircuit, UserAccount account)
  729. {
  730. aCircuit.ServiceURLs = new Dictionary<string, object>();
  731. if (account.ServiceURLs == null)
  732. return;
  733. // Old style: get the service keys from the DB
  734. foreach (KeyValuePair<string, object> kvp in account.ServiceURLs)
  735. {
  736. if (kvp.Value != null)
  737. {
  738. aCircuit.ServiceURLs[kvp.Key] = kvp.Value;
  739. if (!aCircuit.ServiceURLs[kvp.Key].ToString().EndsWith("/"))
  740. aCircuit.ServiceURLs[kvp.Key] = aCircuit.ServiceURLs[kvp.Key] + "/";
  741. }
  742. }
  743. // New style: service keys start with SRV_; override the previous
  744. string[] keys = m_LoginServerConfig.GetKeys();
  745. if (keys.Length > 0)
  746. {
  747. bool newUrls = false;
  748. IEnumerable<string> serviceKeys = keys.Where(value => value.StartsWith("SRV_"));
  749. foreach (string serviceKey in serviceKeys)
  750. {
  751. string keyName = serviceKey.Replace("SRV_", "");
  752. string keyValue = m_LoginServerConfig.GetString(serviceKey, string.Empty);
  753. if (!keyValue.EndsWith("/"))
  754. keyValue = keyValue + "/";
  755. if (!account.ServiceURLs.ContainsKey(keyName) || (account.ServiceURLs.ContainsKey(keyName) && account.ServiceURLs[keyName] != keyValue))
  756. {
  757. account.ServiceURLs[keyName] = keyValue;
  758. newUrls = true;
  759. }
  760. aCircuit.ServiceURLs[keyName] = keyValue;
  761. m_log.DebugFormat("[LLLOGIN SERVICE]: found new key {0} {1}", keyName, aCircuit.ServiceURLs[keyName]);
  762. }
  763. // The grid operator decided to override the defaults in the
  764. // [LoginService] configuration. Let's store the correct ones.
  765. if (newUrls)
  766. m_UserAccountService.StoreUserAccount(account);
  767. }
  768. }
  769. private bool LaunchAgentDirectly(ISimulationService simConnector, GridRegion region, AgentCircuitData aCircuit, TeleportFlags flags, out string reason)
  770. {
  771. return simConnector.CreateAgent(region, aCircuit, (uint)flags, out reason);
  772. }
  773. private bool LaunchAgentIndirectly(GridRegion gatekeeper, GridRegion destination, AgentCircuitData aCircuit, IPEndPoint clientIP, out string reason)
  774. {
  775. m_log.Debug("[LLOGIN SERVICE] Launching agent at " + destination.RegionName);
  776. if (m_UserAgentService.LoginAgentToGrid(aCircuit, gatekeeper, destination, clientIP, out reason))
  777. return true;
  778. return false;
  779. }
  780. #region Console Commands
  781. private void RegisterCommands()
  782. {
  783. //MainConsole.Instance.Commands.AddCommand
  784. MainConsole.Instance.Commands.AddCommand("loginservice", false, "login level",
  785. "login level <level>",
  786. "Set the minimum user level to log in", HandleLoginCommand);
  787. MainConsole.Instance.Commands.AddCommand("loginservice", false, "login reset",
  788. "login reset",
  789. "Reset the login level to allow all users",
  790. HandleLoginCommand);
  791. MainConsole.Instance.Commands.AddCommand("loginservice", false, "login text",
  792. "login text <text>",
  793. "Set the text users will see on login", HandleLoginCommand);
  794. }
  795. private void HandleLoginCommand(string module, string[] cmd)
  796. {
  797. string subcommand = cmd[1];
  798. switch (subcommand)
  799. {
  800. case "level":
  801. // Set the minimum level to allow login
  802. // Useful to allow grid update without worrying about users.
  803. // or fixing critical issues
  804. //
  805. if (cmd.Length > 2)
  806. Int32.TryParse(cmd[2], out m_MinLoginLevel);
  807. break;
  808. case "reset":
  809. m_MinLoginLevel = 0;
  810. break;
  811. case "text":
  812. if (cmd.Length > 2)
  813. m_WelcomeMessage = cmd[2];
  814. break;
  815. }
  816. }
  817. }
  818. #endregion
  819. }