LLLoginService.cs 49 KB

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