LLLoginService.cs 40 KB

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