LLLoginService.cs 44 KB

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