LLLoginService.cs 45 KB

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