LLLoginService.cs 45 KB

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