UserLoginService.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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.Net;
  31. using System.Reflection;
  32. using System.Text.RegularExpressions;
  33. using log4net;
  34. using Nwc.XmlRpc;
  35. using OpenMetaverse;
  36. using Nini.Config;
  37. using OpenSim.Data;
  38. using OpenSim.Framework;
  39. using OpenSim.Framework.Communications;
  40. using OpenSim.Framework.Communications.Services;
  41. using OpenSim.Framework.Communications.Cache;
  42. using OpenSim.Framework.Capabilities;
  43. using OpenSim.Framework.Servers;
  44. using OpenSim.Framework.Servers.HttpServer;
  45. using OpenSim.Services.Interfaces;
  46. using OpenSim.Services.Connectors;
  47. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  48. namespace OpenSim.Grid.UserServer.Modules
  49. {
  50. public delegate void UserLoggedInAtLocation(UUID agentID, UUID sessionID, UUID RegionID,
  51. ulong regionhandle, float positionX, float positionY, float positionZ,
  52. string firstname, string lastname);
  53. /// <summary>
  54. /// Login service used in grid mode.
  55. /// </summary>
  56. public class UserLoginService : LoginService
  57. {
  58. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  59. public event UserLoggedInAtLocation OnUserLoggedInAtLocation;
  60. private UserLoggedInAtLocation handlerUserLoggedInAtLocation;
  61. public UserConfig m_config;
  62. private readonly IRegionProfileRouter m_regionProfileService;
  63. private IGridService m_GridService;
  64. protected BaseHttpServer m_httpServer;
  65. public UserLoginService(
  66. UserManagerBase userManager, IInterServiceInventoryServices inventoryService,
  67. LibraryRootFolder libraryRootFolder,
  68. UserConfig config, string welcomeMess, IRegionProfileRouter regionProfileService)
  69. : base(userManager, libraryRootFolder, welcomeMess)
  70. {
  71. m_config = config;
  72. m_defaultHomeX = m_config.DefaultX;
  73. m_defaultHomeY = m_config.DefaultY;
  74. m_interInventoryService = inventoryService;
  75. m_regionProfileService = regionProfileService;
  76. m_GridService = new GridServicesConnector(config.GridServerURL.ToString());
  77. }
  78. public void RegisterHandlers(BaseHttpServer httpServer, bool registerLLSDHandler, bool registerOpenIDHandlers)
  79. {
  80. m_httpServer = httpServer;
  81. m_httpServer.AddXmlRPCHandler("login_to_simulator", XmlRpcLoginMethod);
  82. m_httpServer.AddHTTPHandler("login", ProcessHTMLLogin);
  83. m_httpServer.AddXmlRPCHandler("set_login_params", XmlRPCSetLoginParams);
  84. m_httpServer.AddXmlRPCHandler("check_auth_session", XmlRPCCheckAuthSession, false);
  85. if (registerLLSDHandler)
  86. {
  87. m_httpServer.SetDefaultLLSDHandler(LLSDLoginMethod);
  88. }
  89. if (registerOpenIDHandlers)
  90. {
  91. // Handler for OpenID avatar identity pages
  92. m_httpServer.AddStreamHandler(new OpenIdStreamHandler("GET", "/users/", this));
  93. // Handlers for the OpenID endpoint server
  94. m_httpServer.AddStreamHandler(new OpenIdStreamHandler("POST", "/openid/server/", this));
  95. m_httpServer.AddStreamHandler(new OpenIdStreamHandler("GET", "/openid/server/", this));
  96. }
  97. }
  98. public void setloginlevel(int level)
  99. {
  100. m_minLoginLevel = level;
  101. m_log.InfoFormat("[GRID]: Login Level set to {0} ", level);
  102. }
  103. public void setwelcometext(string text)
  104. {
  105. m_welcomeMessage = text;
  106. m_log.InfoFormat("[GRID]: Login text set to {0} ", text);
  107. }
  108. public override void LogOffUser(UserProfileData theUser, string message)
  109. {
  110. RegionProfileData SimInfo;
  111. try
  112. {
  113. SimInfo = m_regionProfileService.RequestSimProfileData(
  114. theUser.CurrentAgent.Handle, m_config.GridServerURL,
  115. m_config.GridSendKey, m_config.GridRecvKey);
  116. if (SimInfo == null)
  117. {
  118. m_log.Error("[GRID]: Region user was in isn't currently logged in");
  119. return;
  120. }
  121. }
  122. catch (Exception)
  123. {
  124. m_log.Error("[GRID]: Unable to look up region to log user off");
  125. return;
  126. }
  127. // Prepare notification
  128. Hashtable SimParams = new Hashtable();
  129. SimParams["agent_id"] = theUser.ID.ToString();
  130. SimParams["region_secret"] = theUser.CurrentAgent.SecureSessionID.ToString();
  131. SimParams["region_secret2"] = SimInfo.regionSecret;
  132. //m_log.Info(SimInfo.regionSecret);
  133. SimParams["regionhandle"] = theUser.CurrentAgent.Handle.ToString();
  134. SimParams["message"] = message;
  135. ArrayList SendParams = new ArrayList();
  136. SendParams.Add(SimParams);
  137. m_log.InfoFormat(
  138. "[ASSUMED CRASH]: Telling region {0} @ {1},{2} ({3}) that their agent is dead: {4}",
  139. SimInfo.regionName, SimInfo.regionLocX, SimInfo.regionLocY, SimInfo.httpServerURI,
  140. theUser.FirstName + " " + theUser.SurName);
  141. try
  142. {
  143. XmlRpcRequest GridReq = new XmlRpcRequest("logoff_user", SendParams);
  144. XmlRpcResponse GridResp = GridReq.Send(SimInfo.httpServerURI, 6000);
  145. if (GridResp.IsFault)
  146. {
  147. m_log.ErrorFormat(
  148. "[LOGIN]: XMLRPC request for {0} failed, fault code: {1}, reason: {2}, This is likely an old region revision.",
  149. SimInfo.httpServerURI, GridResp.FaultCode, GridResp.FaultString);
  150. }
  151. }
  152. catch (Exception)
  153. {
  154. m_log.Error("[LOGIN]: Error telling region to logout user!");
  155. }
  156. // Prepare notification
  157. SimParams = new Hashtable();
  158. SimParams["agent_id"] = theUser.ID.ToString();
  159. SimParams["region_secret"] = SimInfo.regionSecret;
  160. //m_log.Info(SimInfo.regionSecret);
  161. SimParams["regionhandle"] = theUser.CurrentAgent.Handle.ToString();
  162. SimParams["message"] = message;
  163. SendParams = new ArrayList();
  164. SendParams.Add(SimParams);
  165. m_log.InfoFormat(
  166. "[ASSUMED CRASH]: Telling region {0} @ {1},{2} ({3}) that their agent is dead: {4}",
  167. SimInfo.regionName, SimInfo.regionLocX, SimInfo.regionLocY, SimInfo.httpServerURI,
  168. theUser.FirstName + " " + theUser.SurName);
  169. try
  170. {
  171. XmlRpcRequest GridReq = new XmlRpcRequest("logoff_user", SendParams);
  172. XmlRpcResponse GridResp = GridReq.Send(SimInfo.httpServerURI, 6000);
  173. if (GridResp.IsFault)
  174. {
  175. m_log.ErrorFormat(
  176. "[LOGIN]: XMLRPC request for {0} failed, fault code: {1}, reason: {2}, This is likely an old region revision.",
  177. SimInfo.httpServerURI, GridResp.FaultCode, GridResp.FaultString);
  178. }
  179. }
  180. catch (Exception)
  181. {
  182. m_log.Error("[LOGIN]: Error telling region to logout user!");
  183. }
  184. //base.LogOffUser(theUser);
  185. }
  186. protected override RegionInfo RequestClosestRegion(string region)
  187. {
  188. return GridRegionToRegionInfo(m_GridService.GetRegionByName(UUID.Zero, region));
  189. }
  190. protected override RegionInfo GetRegionInfo(ulong homeRegionHandle)
  191. {
  192. uint x = 0, y = 0;
  193. Utils.LongToUInts(homeRegionHandle, out x, out y);
  194. return GridRegionToRegionInfo(m_GridService.GetRegionByPosition(UUID.Zero, (int)x, (int)y));
  195. }
  196. protected override RegionInfo GetRegionInfo(UUID homeRegionId)
  197. {
  198. return GridRegionToRegionInfo(m_GridService.GetRegionByUUID(UUID.Zero, homeRegionId));
  199. }
  200. private RegionInfo GridRegionToRegionInfo(GridRegion gregion)
  201. {
  202. if (gregion == null)
  203. return null;
  204. RegionInfo rinfo = new RegionInfo();
  205. rinfo.ExternalHostName = gregion.ExternalHostName;
  206. rinfo.HttpPort = gregion.HttpPort;
  207. rinfo.InternalEndPoint = gregion.InternalEndPoint;
  208. rinfo.RegionID = gregion.RegionID;
  209. rinfo.RegionLocX = (uint)(gregion.RegionLocX / Constants.RegionSize);
  210. rinfo.RegionLocY = (uint)(gregion.RegionLocY / Constants.RegionSize);
  211. rinfo.RegionName = gregion.RegionName;
  212. rinfo.ScopeID = gregion.ScopeID;
  213. rinfo.ServerURI = gregion.ServerURI;
  214. return rinfo;
  215. }
  216. protected override bool PrepareLoginToRegion(RegionInfo regionInfo, UserProfileData user, LoginResponse response, IPEndPoint remoteClient)
  217. {
  218. return PrepareLoginToRegion(RegionProfileData.FromRegionInfo(regionInfo), user, response, remoteClient);
  219. }
  220. /// <summary>
  221. /// Prepare a login to the given region. This involves both telling the region to expect a connection
  222. /// and appropriately customising the response to the user.
  223. /// </summary>
  224. /// <param name="regionInfo"></param>
  225. /// <param name="user"></param>
  226. /// <param name="response"></param>
  227. /// <returns>true if the region was successfully contacted, false otherwise</returns>
  228. private bool PrepareLoginToRegion(RegionProfileData regionInfo, UserProfileData user, LoginResponse response, IPEndPoint remoteClient)
  229. {
  230. try
  231. {
  232. response.SimAddress = Util.GetHostFromURL(regionInfo.serverURI).ToString();
  233. response.SimPort = uint.Parse(regionInfo.serverURI.Split(new char[] { '/', ':' })[4]);
  234. response.RegionX = regionInfo.regionLocX;
  235. response.RegionY = regionInfo.regionLocY;
  236. string capsPath = CapsUtil.GetRandomCapsObjectPath();
  237. // Adam's working code commented for now -- Diva 5/25/2009
  238. //// For NAT
  239. ////string host = NetworkUtil.GetHostFor(remoteClient.Address, regionInfo.ServerIP);
  240. //string host = response.SimAddress;
  241. //// TODO: This doesnt support SSL. -Adam
  242. //string serverURI = "http://" + host + ":" + regionInfo.ServerPort;
  243. //response.SeedCapability = serverURI + CapsUtil.GetCapsSeedPath(capsPath);
  244. // Take off trailing / so that the caps path isn't //CAPS/someUUID
  245. string uri = regionInfo.httpServerURI.Trim(new char[] { '/' });
  246. response.SeedCapability = uri + CapsUtil.GetCapsSeedPath(capsPath);
  247. // Notify the target of an incoming user
  248. m_log.InfoFormat(
  249. "[LOGIN]: Telling {0} @ {1},{2} ({3}) to prepare for client connection",
  250. regionInfo.regionName, response.RegionX, response.RegionY, regionInfo.httpServerURI);
  251. // Update agent with target sim
  252. user.CurrentAgent.Region = regionInfo.UUID;
  253. user.CurrentAgent.Handle = regionInfo.regionHandle;
  254. // Prepare notification
  255. Hashtable loginParams = new Hashtable();
  256. loginParams["session_id"] = user.CurrentAgent.SessionID.ToString();
  257. loginParams["secure_session_id"] = user.CurrentAgent.SecureSessionID.ToString();
  258. loginParams["firstname"] = user.FirstName;
  259. loginParams["lastname"] = user.SurName;
  260. loginParams["agent_id"] = user.ID.ToString();
  261. loginParams["circuit_code"] = (Int32)Convert.ToUInt32(response.CircuitCode);
  262. loginParams["startpos_x"] = user.CurrentAgent.Position.X.ToString();
  263. loginParams["startpos_y"] = user.CurrentAgent.Position.Y.ToString();
  264. loginParams["startpos_z"] = user.CurrentAgent.Position.Z.ToString();
  265. loginParams["regionhandle"] = user.CurrentAgent.Handle.ToString();
  266. loginParams["caps_path"] = capsPath;
  267. // Get appearance
  268. AvatarAppearance appearance = m_userManager.GetUserAppearance(user.ID);
  269. if (appearance != null)
  270. {
  271. loginParams["appearance"] = appearance.ToHashTable();
  272. m_log.DebugFormat("[LOGIN]: Found appearance for {0} {1}", user.FirstName, user.SurName);
  273. }
  274. else
  275. {
  276. m_log.DebugFormat("[LOGIN]: Appearance not for {0} {1}. Creating default.", user.FirstName, user.SurName);
  277. appearance = new AvatarAppearance(user.ID);
  278. loginParams["appearance"] = appearance.ToHashTable();
  279. }
  280. ArrayList SendParams = new ArrayList();
  281. SendParams.Add(loginParams);
  282. // Send
  283. XmlRpcRequest GridReq = new XmlRpcRequest("expect_user", SendParams);
  284. XmlRpcResponse GridResp = GridReq.Send(regionInfo.httpServerURI, 6000);
  285. if (!GridResp.IsFault)
  286. {
  287. bool responseSuccess = true;
  288. if (GridResp.Value != null)
  289. {
  290. Hashtable resp = (Hashtable)GridResp.Value;
  291. if (resp.ContainsKey("success"))
  292. {
  293. if ((string)resp["success"] == "FALSE")
  294. {
  295. responseSuccess = false;
  296. }
  297. }
  298. }
  299. if (responseSuccess)
  300. {
  301. handlerUserLoggedInAtLocation = OnUserLoggedInAtLocation;
  302. if (handlerUserLoggedInAtLocation != null)
  303. {
  304. handlerUserLoggedInAtLocation(user.ID, user.CurrentAgent.SessionID,
  305. user.CurrentAgent.Region,
  306. user.CurrentAgent.Handle,
  307. user.CurrentAgent.Position.X,
  308. user.CurrentAgent.Position.Y,
  309. user.CurrentAgent.Position.Z,
  310. user.FirstName, user.SurName);
  311. }
  312. }
  313. else
  314. {
  315. m_log.ErrorFormat("[LOGIN]: Region responded that it is not available to receive clients");
  316. return false;
  317. }
  318. }
  319. else
  320. {
  321. m_log.ErrorFormat("[LOGIN]: XmlRpc request to region failed with message {0}, code {1} ", GridResp.FaultString, GridResp.FaultCode);
  322. return false;
  323. }
  324. }
  325. catch (Exception e)
  326. {
  327. m_log.ErrorFormat("[LOGIN]: Region not available for login, {0}", e);
  328. return false;
  329. }
  330. return true;
  331. }
  332. public XmlRpcResponse XmlRPCSetLoginParams(XmlRpcRequest request, IPEndPoint remoteClient)
  333. {
  334. XmlRpcResponse response = new XmlRpcResponse();
  335. Hashtable requestData = (Hashtable)request.Params[0];
  336. UserProfileData userProfile;
  337. Hashtable responseData = new Hashtable();
  338. UUID uid;
  339. string pass = requestData["password"].ToString();
  340. if (!UUID.TryParse((string)requestData["avatar_uuid"], out uid))
  341. {
  342. responseData["error"] = "No authorization";
  343. response.Value = responseData;
  344. return response;
  345. }
  346. userProfile = m_userManager.GetUserProfile(uid);
  347. if (userProfile == null ||
  348. (!AuthenticateUser(userProfile, pass)) ||
  349. userProfile.GodLevel < 200)
  350. {
  351. responseData["error"] = "No authorization";
  352. response.Value = responseData;
  353. return response;
  354. }
  355. if (requestData.ContainsKey("login_level"))
  356. {
  357. m_minLoginLevel = Convert.ToInt32(requestData["login_level"]);
  358. }
  359. if (requestData.ContainsKey("login_motd"))
  360. {
  361. m_welcomeMessage = requestData["login_motd"].ToString();
  362. }
  363. response.Value = responseData;
  364. return response;
  365. }
  366. }
  367. }