From dc4bbf6065ad4cb914c9d44f2e6496a2e3d99814 Mon Sep 17 00:00:00 2001 From: Diva Canto Date: Sun, 10 Jan 2010 20:29:09 -0800 Subject: All Framework.Communications.Clients and Framework.Communications.Services deleted, including old LoginService. --- .../Framework/Communications/Clients/AuthClient.cs | 151 --- .../Framework/Communications/Clients/GridClient.cs | 389 ------ .../Communications/Clients/InventoryClient.cs | 79 -- .../Communications/Clients/RegionClient.cs | 755 ------------ .../Communications/Services/HGLoginAuthService.cs | 339 ------ .../Communications/Services/LoginResponse.cs | 823 ------------- .../Communications/Services/LoginService.cs | 1243 -------------------- 7 files changed, 3779 deletions(-) delete mode 100644 OpenSim/Framework/Communications/Clients/AuthClient.cs delete mode 100644 OpenSim/Framework/Communications/Clients/GridClient.cs delete mode 100644 OpenSim/Framework/Communications/Clients/InventoryClient.cs delete mode 100644 OpenSim/Framework/Communications/Clients/RegionClient.cs delete mode 100644 OpenSim/Framework/Communications/Services/HGLoginAuthService.cs delete mode 100644 OpenSim/Framework/Communications/Services/LoginResponse.cs delete mode 100644 OpenSim/Framework/Communications/Services/LoginService.cs (limited to 'OpenSim/Framework/Communications') diff --git a/OpenSim/Framework/Communications/Clients/AuthClient.cs b/OpenSim/Framework/Communications/Clients/AuthClient.cs deleted file mode 100644 index adae637..0000000 --- a/OpenSim/Framework/Communications/Clients/AuthClient.cs +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using Nwc.XmlRpc; -using OpenMetaverse; - -namespace OpenSim.Framework.Communications.Clients -{ - public class AuthClient - { - public static string GetNewKey(string authurl, UUID userID, UUID authToken) - { - //Hashtable keyParams = new Hashtable(); - //keyParams["user_id"] = userID; - //keyParams["auth_token"] = authKey; - - List SendParams = new List(); - SendParams.Add(userID.ToString()); - SendParams.Add(authToken.ToString()); - - XmlRpcRequest request = new XmlRpcRequest("hg_new_auth_key", SendParams); - XmlRpcResponse reply; - try - { - reply = request.Send(authurl, 6000); - } - catch (Exception e) - { - System.Console.WriteLine("[HGrid]: Failed to get new key. Reason: " + e.Message); - return string.Empty; - } - - if (!reply.IsFault) - { - string newKey = string.Empty; - if (reply.Value != null) - newKey = (string)reply.Value; - - return newKey; - } - else - { - System.Console.WriteLine("[HGrid]: XmlRpc request to get auth key failed with message {0}" + reply.FaultString + ", code " + reply.FaultCode); - return string.Empty; - } - - } - - public static bool VerifyKey(string authurl, UUID userID, string authKey) - { - List SendParams = new List(); - SendParams.Add(userID.ToString()); - SendParams.Add(authKey); - - System.Console.WriteLine("[HGrid]: Verifying user key with authority " + authurl); - - XmlRpcRequest request = new XmlRpcRequest("hg_verify_auth_key", SendParams); - XmlRpcResponse reply; - try - { - reply = request.Send(authurl, 10000); - } - catch (Exception e) - { - System.Console.WriteLine("[HGrid]: Failed to verify key. Reason: " + e.Message); - return false; - } - - if (reply != null) - { - if (!reply.IsFault) - { - bool success = false; - if (reply.Value != null) - success = (bool)reply.Value; - - return success; - } - else - { - System.Console.WriteLine("[HGrid]: XmlRpc request to verify key failed with message {0}" + reply.FaultString + ", code " + reply.FaultCode); - return false; - } - } - else - { - System.Console.WriteLine("[HGrid]: XmlRpc request to verify key returned null reply"); - return false; - } - } - - public static bool VerifySession(string authurl, UUID userID, UUID sessionID) - { - Hashtable requestData = new Hashtable(); - requestData["avatar_uuid"] = userID.ToString(); - requestData["session_id"] = sessionID.ToString(); - ArrayList SendParams = new ArrayList(); - SendParams.Add(requestData); - XmlRpcRequest UserReq = new XmlRpcRequest("check_auth_session", SendParams); - XmlRpcResponse UserResp = null; - try - { - UserResp = UserReq.Send(authurl, 3000); - } - catch (Exception e) - { - System.Console.WriteLine("[Session Auth]: VerifySession XmlRpc: " + e.Message); - return false; - } - - Hashtable responseData = (Hashtable)UserResp.Value; - if (responseData != null && responseData.ContainsKey("auth_session") && responseData["auth_session"] != null && responseData["auth_session"].ToString() == "TRUE") - { - //System.Console.WriteLine("[Authorization]: userserver reported authorized session for user " + userID); - return true; - } - else - { - //System.Console.WriteLine("[Authorization]: userserver reported unauthorized session for user " + userID); - return false; - } - } - } -} diff --git a/OpenSim/Framework/Communications/Clients/GridClient.cs b/OpenSim/Framework/Communications/Clients/GridClient.cs deleted file mode 100644 index 0198d75..0000000 --- a/OpenSim/Framework/Communications/Clients/GridClient.cs +++ /dev/null @@ -1,389 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Net; -using System.Reflection; - -using log4net; -using OpenMetaverse; -using Nwc.XmlRpc; - -namespace OpenSim.Framework.Communications.Clients -{ - public class GridClient - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - public bool RegisterRegion( - string gridServerURL, string sendKey, string receiveKey, RegionInfo regionInfo, out bool forcefulBanLines) - { - m_log.InfoFormat( - "[GRID CLIENT]: Registering region {0} with grid at {1}", regionInfo.RegionName, gridServerURL); - - forcefulBanLines = true; - - Hashtable GridParams = new Hashtable(); - // Login / Authentication - - GridParams["authkey"] = sendKey; - GridParams["recvkey"] = receiveKey; - GridParams["UUID"] = regionInfo.RegionID.ToString(); - GridParams["sim_ip"] = regionInfo.ExternalHostName; - GridParams["sim_port"] = regionInfo.InternalEndPoint.Port.ToString(); - GridParams["region_locx"] = regionInfo.RegionLocX.ToString(); - GridParams["region_locy"] = regionInfo.RegionLocY.ToString(); - GridParams["sim_name"] = regionInfo.RegionName; - GridParams["http_port"] = regionInfo.HttpPort.ToString(); - GridParams["remoting_port"] = ConfigSettings.DefaultRegionRemotingPort.ToString(); - GridParams["map-image-id"] = regionInfo.RegionSettings.TerrainImageID.ToString(); - GridParams["originUUID"] = regionInfo.originRegionID.ToString(); - GridParams["server_uri"] = regionInfo.ServerURI; - GridParams["region_secret"] = regionInfo.regionSecret; - GridParams["major_interface_version"] = VersionInfo.MajorInterfaceVersion.ToString(); - - GridParams["master_avatar_uuid"] = regionInfo.EstateSettings.EstateOwner.ToString(); - - // Package into an XMLRPC Request - ArrayList SendParams = new ArrayList(); - SendParams.Add(GridParams); - - // Send Request - XmlRpcRequest GridReq = new XmlRpcRequest("simulator_login", SendParams); - XmlRpcResponse GridResp; - - try - { - // The timeout should always be significantly larger than the timeout for the grid server to request - // the initial status of the region before confirming registration. - GridResp = GridReq.Send(gridServerURL, 90000); - } - catch (Exception e) - { - Exception e2 - = new Exception( - String.Format( - "Unable to register region with grid at {0}. Grid service not running?", - gridServerURL), - e); - - throw e2; - } - - Hashtable GridRespData = (Hashtable)GridResp.Value; - // Hashtable griddatahash = GridRespData; - - // Process Response - if (GridRespData.ContainsKey("error")) - { - string errorstring = (string)GridRespData["error"]; - - Exception e = new Exception( - String.Format("Unable to connect to grid at {0}: {1}", gridServerURL, errorstring)); - - throw e; - } - else - { - // m_knownRegions = RequestNeighbours(regionInfo.RegionLocX, regionInfo.RegionLocY); - if (GridRespData.ContainsKey("allow_forceful_banlines")) - { - if ((string)GridRespData["allow_forceful_banlines"] != "TRUE") - { - forcefulBanLines = false; - } - } - - } - return true; - } - - public bool DeregisterRegion(string gridServerURL, string sendKey, string receiveKey, RegionInfo regionInfo, out string errorMsg) - { - errorMsg = ""; - Hashtable GridParams = new Hashtable(); - - GridParams["UUID"] = regionInfo.RegionID.ToString(); - - // Package into an XMLRPC Request - ArrayList SendParams = new ArrayList(); - SendParams.Add(GridParams); - - // Send Request - XmlRpcRequest GridReq = new XmlRpcRequest("simulator_after_region_moved", SendParams); - XmlRpcResponse GridResp = null; - - try - { - GridResp = GridReq.Send(gridServerURL, 10000); - } - catch (Exception e) - { - Exception e2 - = new Exception( - String.Format( - "Unable to deregister region with grid at {0}. Grid service not running?", - gridServerURL), - e); - - throw e2; - } - - Hashtable GridRespData = (Hashtable)GridResp.Value; - - // Hashtable griddatahash = GridRespData; - - // Process Response - if (GridRespData != null && GridRespData.ContainsKey("error")) - { - errorMsg = (string)GridRespData["error"]; - return false; - } - - return true; - } - - public bool RequestNeighborInfo( - string gridServerURL, string sendKey, string receiveKey, UUID regionUUID, - out RegionInfo regionInfo, out string errorMsg) - { - // didn't find it so far, we have to go the long way - regionInfo = null; - errorMsg = string.Empty; - Hashtable requestData = new Hashtable(); - requestData["region_UUID"] = regionUUID.ToString(); - requestData["authkey"] = sendKey; - ArrayList SendParams = new ArrayList(); - SendParams.Add(requestData); - XmlRpcRequest gridReq = new XmlRpcRequest("simulator_data_request", SendParams); - XmlRpcResponse gridResp = null; - - try - { - gridResp = gridReq.Send(gridServerURL, 3000); - } - catch (Exception e) - { - errorMsg = e.Message; - return false; - } - - Hashtable responseData = (Hashtable)gridResp.Value; - - if (responseData.ContainsKey("error")) - { - errorMsg = (string)responseData["error"]; - return false; ; - } - - regionInfo = BuildRegionInfo(responseData, String.Empty); - - return true; - } - - public bool RequestNeighborInfo( - string gridServerURL, string sendKey, string receiveKey, ulong regionHandle, - out RegionInfo regionInfo, out string errorMsg) - { - // didn't find it so far, we have to go the long way - regionInfo = null; - errorMsg = string.Empty; - - try - { - Hashtable requestData = new Hashtable(); - requestData["region_handle"] = regionHandle.ToString(); - requestData["authkey"] = sendKey; - ArrayList SendParams = new ArrayList(); - SendParams.Add(requestData); - XmlRpcRequest GridReq = new XmlRpcRequest("simulator_data_request", SendParams); - XmlRpcResponse GridResp = GridReq.Send(gridServerURL, 3000); - - Hashtable responseData = (Hashtable)GridResp.Value; - - if (responseData.ContainsKey("error")) - { - errorMsg = (string)responseData["error"]; - return false; - } - - uint regX = Convert.ToUInt32((string)responseData["region_locx"]); - uint regY = Convert.ToUInt32((string)responseData["region_locy"]); - string externalHostName = (string)responseData["sim_ip"]; - uint simPort = Convert.ToUInt32(responseData["sim_port"]); - string regionName = (string)responseData["region_name"]; - UUID regionID = new UUID((string)responseData["region_UUID"]); - uint remotingPort = Convert.ToUInt32((string)responseData["remoting_port"]); - - uint httpPort = 9000; - if (responseData.ContainsKey("http_port")) - { - httpPort = Convert.ToUInt32((string)responseData["http_port"]); - } - - // Ok, so this is definitively the wrong place to do this, way too hard coded, but it doesn't seem we GET this info? - - string simURI = "http://" + externalHostName + ":" + simPort; - - // string externalUri = (string) responseData["sim_uri"]; - - //IPEndPoint neighbourInternalEndPoint = new IPEndPoint(IPAddress.Parse(internalIpStr), (int) port); - regionInfo = RegionInfo.Create(regionID, regionName, regX, regY, externalHostName, httpPort, simPort, remotingPort, simURI); - } - catch (Exception e) - { - errorMsg = e.Message; - return false; - } - - return true; - } - - public bool RequestClosestRegion( - string gridServerURL, string sendKey, string receiveKey, string regionName, - out RegionInfo regionInfo, out string errorMsg) - { - regionInfo = null; - errorMsg = string.Empty; - try - { - Hashtable requestData = new Hashtable(); - requestData["region_name_search"] = regionName; - requestData["authkey"] = sendKey; - ArrayList SendParams = new ArrayList(); - SendParams.Add(requestData); - XmlRpcRequest GridReq = new XmlRpcRequest("simulator_data_request", SendParams); - XmlRpcResponse GridResp = GridReq.Send(gridServerURL, 3000); - - Hashtable responseData = (Hashtable)GridResp.Value; - - if (responseData.ContainsKey("error")) - { - errorMsg = (string)responseData["error"]; - return false; - } - - regionInfo = BuildRegionInfo(responseData, ""); - - } - catch (Exception e) - { - errorMsg = e.Message; - return false; - } - return true; - } - - /// - /// Performs a XML-RPC query against the grid server returning mapblock information in the specified coordinates - /// - /// REDUNDANT - OGS1 is to be phased out in favour of OGS2 - /// Minimum X value - /// Minimum Y value - /// Maximum X value - /// Maximum Y value - /// Hashtable of hashtables containing map data elements - public bool MapBlockQuery( - string gridServerURL, int minX, int minY, int maxX, int maxY, out Hashtable respData, out string errorMsg) - { - respData = new Hashtable(); - errorMsg = string.Empty; - - Hashtable param = new Hashtable(); - param["xmin"] = minX; - param["ymin"] = minY; - param["xmax"] = maxX; - param["ymax"] = maxY; - IList parameters = new ArrayList(); - parameters.Add(param); - - try - { - XmlRpcRequest req = new XmlRpcRequest("map_block", parameters); - XmlRpcResponse resp = req.Send(gridServerURL, 10000); - respData = (Hashtable)resp.Value; - return true; - } - catch (Exception e) - { - errorMsg = e.Message; - return false; - } - } - - public bool SearchRegionByName(string gridServerURL, IList parameters, out Hashtable respData, out string errorMsg) - { - respData = null; - errorMsg = string.Empty; - try - { - XmlRpcRequest request = new XmlRpcRequest("search_for_region_by_name", parameters); - XmlRpcResponse resp = request.Send(gridServerURL, 10000); - respData = (Hashtable)resp.Value; - if (respData != null && respData.Contains("faultCode")) - { - errorMsg = (string)respData["faultString"]; - return false; - } - - return true; - } - catch (Exception e) - { - errorMsg = e.Message; - return false; - } - } - - public RegionInfo BuildRegionInfo(Hashtable responseData, string prefix) - { - uint regX = Convert.ToUInt32((string)responseData[prefix + "region_locx"]); - uint regY = Convert.ToUInt32((string)responseData[prefix + "region_locy"]); - string internalIpStr = (string)responseData[prefix + "sim_ip"]; - uint port = Convert.ToUInt32(responseData[prefix + "sim_port"]); - - IPEndPoint neighbourInternalEndPoint = new IPEndPoint(Util.GetHostFromDNS(internalIpStr), (int)port); - - RegionInfo regionInfo = new RegionInfo(regX, regY, neighbourInternalEndPoint, internalIpStr); - regionInfo.RemotingPort = Convert.ToUInt32((string)responseData[prefix + "remoting_port"]); - regionInfo.RemotingAddress = internalIpStr; - - if (responseData.ContainsKey(prefix + "http_port")) - { - regionInfo.HttpPort = Convert.ToUInt32((string)responseData[prefix + "http_port"]); - } - - regionInfo.RegionID = new UUID((string)responseData[prefix + "region_UUID"]); - regionInfo.RegionName = (string)responseData[prefix + "region_name"]; - - regionInfo.RegionSettings.TerrainImageID = new UUID((string)responseData[prefix + "map_UUID"]); - return regionInfo; - } - } -} diff --git a/OpenSim/Framework/Communications/Clients/InventoryClient.cs b/OpenSim/Framework/Communications/Clients/InventoryClient.cs deleted file mode 100644 index e4f5e2a..0000000 --- a/OpenSim/Framework/Communications/Clients/InventoryClient.cs +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Copyright (c), Contributors. All rights reserved. - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * * Neither the name of the Organizations nor the names of Individual - * Contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL - * THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE - * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED - * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED - * OF THE POSSIBILITY OF SUCH DAMAGE. - * - */ - -using System; -using OpenSim.Framework.Servers; -using OpenSim.Framework.Servers.HttpServer; - -using OpenMetaverse; - -namespace OpenSim.Framework.Communications.Clients -{ - public class InventoryClient - { - private string ServerURL; - - public InventoryClient(string url) - { - ServerURL = url; - } - - public void GetInventoryItemAsync(InventoryItemBase item, ReturnResponse callBack) - { - System.Console.WriteLine("[HGrid] GetInventory from " + ServerURL); - try - { - RestSessionObjectPosterResponse requester - = new RestSessionObjectPosterResponse(); - requester.ResponseCallback = callBack; - - requester.BeginPostObject(ServerURL + "/GetItem/", item, string.Empty, string.Empty); - } - catch (Exception e) - { - System.Console.WriteLine("[HGrid]: Exception posting to inventory: " + e); - } - } - - public InventoryItemBase GetInventoryItem(InventoryItemBase item) - { - System.Console.WriteLine("[HGrid] GetInventory " + item.ID + " from " + ServerURL); - try - { - item = SynchronousRestSessionObjectPoster.BeginPostObject("POST", ServerURL + "/GetItem/", item.ID.Guid, "", ""); - return item; - } - catch (Exception e) - { - System.Console.WriteLine("[HGrid]: Exception posting to inventory: " + e); - } - return null; - } - - } -} diff --git a/OpenSim/Framework/Communications/Clients/RegionClient.cs b/OpenSim/Framework/Communications/Clients/RegionClient.cs deleted file mode 100644 index ee7dec8..0000000 --- a/OpenSim/Framework/Communications/Clients/RegionClient.cs +++ /dev/null @@ -1,755 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.IO; -using System.Net; -using System.Reflection; -using System.Text; - -using OpenMetaverse; -using OpenMetaverse.StructuredData; - -using GridRegion = OpenSim.Services.Interfaces.GridRegion; - -using log4net; - -namespace OpenSim.Framework.Communications.Clients -{ - public class RegionClient - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - public bool DoCreateChildAgentCall(GridRegion region, AgentCircuitData aCircuit, string authKey, uint teleportFlags, out string reason) - { - reason = String.Empty; - - // Eventually, we want to use a caps url instead of the agentID - string uri = string.Empty; - try - { - uri = "http://" + region.ExternalEndPoint.Address + ":" + region.HttpPort + "/agent/" + aCircuit.AgentID + "/"; - } - catch (Exception e) - { - m_log.Debug("[REST COMMS]: Unable to resolve external endpoint on agent create. Reason: " + e.Message); - reason = e.Message; - return false; - } - - //Console.WriteLine(" >>> DoCreateChildAgentCall <<< " + uri); - - HttpWebRequest AgentCreateRequest = (HttpWebRequest)WebRequest.Create(uri); - AgentCreateRequest.Method = "POST"; - AgentCreateRequest.ContentType = "application/json"; - AgentCreateRequest.Timeout = 10000; - //AgentCreateRequest.KeepAlive = false; - AgentCreateRequest.Headers.Add("Authorization", authKey); - - // Fill it in - OSDMap args = null; - try - { - args = aCircuit.PackAgentCircuitData(); - } - catch (Exception e) - { - m_log.Debug("[REST COMMS]: PackAgentCircuitData failed with exception: " + e.Message); - } - // Add the regionhandle of the destination region - ulong regionHandle = GetRegionHandle(region.RegionHandle); - args["destination_handle"] = OSD.FromString(regionHandle.ToString()); - args["teleport_flags"] = OSD.FromString(teleportFlags.ToString()); - - string strBuffer = ""; - byte[] buffer = new byte[1]; - try - { - strBuffer = OSDParser.SerializeJsonString(args); - Encoding str = Util.UTF8; - buffer = str.GetBytes(strBuffer); - - } - catch (Exception e) - { - m_log.WarnFormat("[REST COMMS]: Exception thrown on serialization of ChildCreate: {0}", e.Message); - // ignore. buffer will be empty, caller should check. - } - - Stream os = null; - try - { // send the Post - AgentCreateRequest.ContentLength = buffer.Length; //Count bytes to send - os = AgentCreateRequest.GetRequestStream(); - os.Write(buffer, 0, strBuffer.Length); //Send it - //m_log.InfoFormat("[REST COMMS]: Posted CreateChildAgent request to remote sim {0}", uri); - } - //catch (WebException ex) - catch - { - //m_log.InfoFormat("[REST COMMS]: Bad send on ChildAgentUpdate {0}", ex.Message); - reason = "cannot contact remote region"; - return false; - } - finally - { - if (os != null) - os.Close(); - } - - // Let's wait for the response - //m_log.Info("[REST COMMS]: Waiting for a reply after DoCreateChildAgentCall"); - - WebResponse webResponse = null; - StreamReader sr = null; - try - { - webResponse = AgentCreateRequest.GetResponse(); - if (webResponse == null) - { - m_log.Info("[REST COMMS]: Null reply on DoCreateChildAgentCall post"); - } - else - { - - sr = new StreamReader(webResponse.GetResponseStream()); - string response = sr.ReadToEnd().Trim(); - m_log.InfoFormat("[REST COMMS]: DoCreateChildAgentCall reply was {0} ", response); - - if (!String.IsNullOrEmpty(response)) - { - try - { - // we assume we got an OSDMap back - OSDMap r = GetOSDMap(response); - bool success = r["success"].AsBoolean(); - reason = r["reason"].AsString(); - return success; - } - catch (NullReferenceException e) - { - m_log.InfoFormat("[REST COMMS]: exception on reply of DoCreateChildAgentCall {0}", e.Message); - - // check for old style response - if (response.ToLower().StartsWith("true")) - return true; - - return false; - } - } - } - } - catch (WebException ex) - { - m_log.InfoFormat("[REST COMMS]: exception on reply of DoCreateChildAgentCall {0}", ex.Message); - // ignore, really - } - finally - { - if (sr != null) - sr.Close(); - } - - return true; - - } - - public bool DoChildAgentUpdateCall(GridRegion region, IAgentData cAgentData) - { - // Eventually, we want to use a caps url instead of the agentID - string uri = string.Empty; - try - { - uri = "http://" + region.ExternalEndPoint.Address + ":" + region.HttpPort + "/agent/" + cAgentData.AgentID + "/"; - } - catch (Exception e) - { - m_log.Debug("[REST COMMS]: Unable to resolve external endpoint on agent update. Reason: " + e.Message); - return false; - } - //Console.WriteLine(" >>> DoChildAgentUpdateCall <<< " + uri); - - HttpWebRequest ChildUpdateRequest = (HttpWebRequest)WebRequest.Create(uri); - ChildUpdateRequest.Method = "PUT"; - ChildUpdateRequest.ContentType = "application/json"; - ChildUpdateRequest.Timeout = 10000; - //ChildUpdateRequest.KeepAlive = false; - - // Fill it in - OSDMap args = null; - try - { - args = cAgentData.Pack(); - } - catch (Exception e) - { - m_log.Debug("[REST COMMS]: PackUpdateMessage failed with exception: " + e.Message); - } - // Add the regionhandle of the destination region - ulong regionHandle = GetRegionHandle(region.RegionHandle); - args["destination_handle"] = OSD.FromString(regionHandle.ToString()); - - string strBuffer = ""; - byte[] buffer = new byte[1]; - try - { - strBuffer = OSDParser.SerializeJsonString(args); - Encoding str = Util.UTF8; - buffer = str.GetBytes(strBuffer); - - } - catch (Exception e) - { - m_log.WarnFormat("[REST COMMS]: Exception thrown on serialization of ChildUpdate: {0}", e.Message); - // ignore. buffer will be empty, caller should check. - } - - Stream os = null; - try - { // send the Post - ChildUpdateRequest.ContentLength = buffer.Length; //Count bytes to send - os = ChildUpdateRequest.GetRequestStream(); - os.Write(buffer, 0, strBuffer.Length); //Send it - //m_log.InfoFormat("[REST COMMS]: Posted ChildAgentUpdate request to remote sim {0}", uri); - } - //catch (WebException ex) - catch - { - //m_log.InfoFormat("[REST COMMS]: Bad send on ChildAgentUpdate {0}", ex.Message); - - return false; - } - finally - { - if (os != null) - os.Close(); - } - - // Let's wait for the response - //m_log.Info("[REST COMMS]: Waiting for a reply after ChildAgentUpdate"); - - WebResponse webResponse = null; - StreamReader sr = null; - try - { - webResponse = ChildUpdateRequest.GetResponse(); - if (webResponse == null) - { - m_log.Info("[REST COMMS]: Null reply on ChilAgentUpdate post"); - } - - sr = new StreamReader(webResponse.GetResponseStream()); - //reply = sr.ReadToEnd().Trim(); - sr.ReadToEnd().Trim(); - sr.Close(); - //m_log.InfoFormat("[REST COMMS]: ChilAgentUpdate reply was {0} ", reply); - - } - catch (WebException ex) - { - m_log.InfoFormat("[REST COMMS]: exception on reply of ChilAgentUpdate {0}", ex.Message); - // ignore, really - } - finally - { - if (sr != null) - sr.Close(); - } - - return true; - } - - public bool DoRetrieveRootAgentCall(GridRegion region, UUID id, out IAgentData agent) - { - agent = null; - // Eventually, we want to use a caps url instead of the agentID - string uri = "http://" + region.ExternalEndPoint.Address + ":" + region.HttpPort + "/agent/" + id + "/" + region.RegionHandle.ToString() + "/"; - //Console.WriteLine(" >>> DoRetrieveRootAgentCall <<< " + uri); - - HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); - request.Method = "GET"; - request.Timeout = 10000; - //request.Headers.Add("authorization", ""); // coming soon - - HttpWebResponse webResponse = null; - string reply = string.Empty; - StreamReader sr = null; - try - { - webResponse = (HttpWebResponse)request.GetResponse(); - if (webResponse == null) - { - m_log.Info("[REST COMMS]: Null reply on agent get "); - } - - sr = new StreamReader(webResponse.GetResponseStream()); - reply = sr.ReadToEnd().Trim(); - - //Console.WriteLine("[REST COMMS]: ChilAgentUpdate reply was " + reply); - - } - catch (WebException ex) - { - m_log.InfoFormat("[REST COMMS]: exception on reply of agent get {0}", ex.Message); - // ignore, really - return false; - } - finally - { - if (sr != null) - sr.Close(); - } - - if (webResponse.StatusCode == HttpStatusCode.OK) - { - // we know it's jason - OSDMap args = GetOSDMap(reply); - if (args == null) - { - //Console.WriteLine("[REST COMMS]: Error getting OSDMap from reply"); - return false; - } - - agent = new CompleteAgentData(); - agent.Unpack(args); - return true; - } - - //Console.WriteLine("[REST COMMS]: DoRetrieveRootAgentCall returned status " + webResponse.StatusCode); - return false; - } - - public bool DoReleaseAgentCall(ulong regionHandle, UUID id, string uri) - { - //m_log.Debug(" >>> DoReleaseAgentCall <<< " + uri); - - WebRequest request = WebRequest.Create(uri); - request.Method = "DELETE"; - request.Timeout = 10000; - - StreamReader sr = null; - try - { - WebResponse webResponse = request.GetResponse(); - if (webResponse == null) - { - m_log.Info("[REST COMMS]: Null reply on agent delete "); - } - - sr = new StreamReader(webResponse.GetResponseStream()); - //reply = sr.ReadToEnd().Trim(); - sr.ReadToEnd().Trim(); - sr.Close(); - //m_log.InfoFormat("[REST COMMS]: ChilAgentUpdate reply was {0} ", reply); - - } - catch (WebException ex) - { - m_log.InfoFormat("[REST COMMS]: exception on reply of agent delete {0}", ex.Message); - // ignore, really - } - finally - { - if (sr != null) - sr.Close(); - } - - return true; - } - - - public bool DoCloseAgentCall(GridRegion region, UUID id) - { - string uri = string.Empty; - try - { - uri = "http://" + region.ExternalEndPoint.Address + ":" + region.HttpPort + "/agent/" + id + "/" + region.RegionHandle.ToString() + "/"; - } - catch (Exception e) - { - m_log.Debug("[REST COMMS]: Unable to resolve external endpoint on agent close. Reason: " + e.Message); - return false; - } - - //Console.WriteLine(" >>> DoCloseAgentCall <<< " + uri); - - WebRequest request = WebRequest.Create(uri); - request.Method = "DELETE"; - request.Timeout = 10000; - - StreamReader sr = null; - try - { - WebResponse webResponse = request.GetResponse(); - if (webResponse == null) - { - m_log.Info("[REST COMMS]: Null reply on agent delete "); - } - - sr = new StreamReader(webResponse.GetResponseStream()); - //reply = sr.ReadToEnd().Trim(); - sr.ReadToEnd().Trim(); - sr.Close(); - //m_log.InfoFormat("[REST COMMS]: ChilAgentUpdate reply was {0} ", reply); - - } - catch (WebException ex) - { - m_log.InfoFormat("[REST COMMS]: exception on reply of agent delete {0}", ex.Message); - // ignore, really - } - finally - { - if (sr != null) - sr.Close(); - } - - return true; - } - - public bool DoCreateObjectCall(GridRegion region, ISceneObject sog, string sogXml2, bool allowScriptCrossing) - { - ulong regionHandle = GetRegionHandle(region.RegionHandle); - string uri - = "http://" + region.ExternalEndPoint.Address + ":" + region.HttpPort - + "/object/" + sog.UUID + "/" + regionHandle.ToString() + "/"; - //m_log.Debug(" >>> DoCreateChildAgentCall <<< " + uri); - - WebRequest ObjectCreateRequest = WebRequest.Create(uri); - ObjectCreateRequest.Method = "POST"; - ObjectCreateRequest.ContentType = "application/json"; - ObjectCreateRequest.Timeout = 10000; - - OSDMap args = new OSDMap(2); - args["sog"] = OSD.FromString(sogXml2); - args["extra"] = OSD.FromString(sog.ExtraToXmlString()); - if (allowScriptCrossing) - { - string state = sog.GetStateSnapshot(); - if (state.Length > 0) - args["state"] = OSD.FromString(state); - } - - string strBuffer = ""; - byte[] buffer = new byte[1]; - try - { - strBuffer = OSDParser.SerializeJsonString(args); - Encoding str = Util.UTF8; - buffer = str.GetBytes(strBuffer); - - } - catch (Exception e) - { - m_log.WarnFormat("[REST COMMS]: Exception thrown on serialization of CreateObject: {0}", e.Message); - // ignore. buffer will be empty, caller should check. - } - - Stream os = null; - try - { // send the Post - ObjectCreateRequest.ContentLength = buffer.Length; //Count bytes to send - os = ObjectCreateRequest.GetRequestStream(); - os.Write(buffer, 0, strBuffer.Length); //Send it - m_log.InfoFormat("[REST COMMS]: Posted ChildAgentUpdate request to remote sim {0}", uri); - } - //catch (WebException ex) - catch - { - // m_log.InfoFormat("[REST COMMS]: Bad send on CreateObject {0}", ex.Message); - - return false; - } - finally - { - if (os != null) - os.Close(); - } - - // Let's wait for the response - //m_log.Info("[REST COMMS]: Waiting for a reply after DoCreateChildAgentCall"); - - StreamReader sr = null; - try - { - WebResponse webResponse = ObjectCreateRequest.GetResponse(); - if (webResponse == null) - { - m_log.Info("[REST COMMS]: Null reply on DoCreateObjectCall post"); - } - - sr = new StreamReader(webResponse.GetResponseStream()); - //reply = sr.ReadToEnd().Trim(); - sr.ReadToEnd().Trim(); - //m_log.InfoFormat("[REST COMMS]: DoCreateChildAgentCall reply was {0} ", reply); - - } - catch (WebException ex) - { - m_log.InfoFormat("[REST COMMS]: exception on reply of DoCreateObjectCall {0}", ex.Message); - // ignore, really - } - finally - { - if (sr != null) - sr.Close(); - } - - return true; - - } - - public bool DoCreateObjectCall(GridRegion region, UUID userID, UUID itemID) - { - ulong regionHandle = GetRegionHandle(region.RegionHandle); - string uri = "http://" + region.ExternalEndPoint.Address + ":" + region.HttpPort + "/object/" + UUID.Zero + "/" + regionHandle.ToString() + "/"; - //m_log.Debug(" >>> DoCreateChildAgentCall <<< " + uri); - - WebRequest ObjectCreateRequest = WebRequest.Create(uri); - ObjectCreateRequest.Method = "PUT"; - ObjectCreateRequest.ContentType = "application/json"; - ObjectCreateRequest.Timeout = 10000; - - OSDMap args = new OSDMap(2); - args["userid"] = OSD.FromUUID(userID); - args["itemid"] = OSD.FromUUID(itemID); - - string strBuffer = ""; - byte[] buffer = new byte[1]; - try - { - strBuffer = OSDParser.SerializeJsonString(args); - Encoding str = Util.UTF8; - buffer = str.GetBytes(strBuffer); - - } - catch (Exception e) - { - m_log.WarnFormat("[REST COMMS]: Exception thrown on serialization of CreateObject: {0}", e.Message); - // ignore. buffer will be empty, caller should check. - } - - Stream os = null; - try - { // send the Post - ObjectCreateRequest.ContentLength = buffer.Length; //Count bytes to send - os = ObjectCreateRequest.GetRequestStream(); - os.Write(buffer, 0, strBuffer.Length); //Send it - //m_log.InfoFormat("[REST COMMS]: Posted CreateObject request to remote sim {0}", uri); - } - //catch (WebException ex) - catch - { - // m_log.InfoFormat("[REST COMMS]: Bad send on CreateObject {0}", ex.Message); - - return false; - } - finally - { - if (os != null) - os.Close(); - } - - // Let's wait for the response - //m_log.Info("[REST COMMS]: Waiting for a reply after DoCreateChildAgentCall"); - - StreamReader sr = null; - try - { - WebResponse webResponse = ObjectCreateRequest.GetResponse(); - if (webResponse == null) - { - m_log.Info("[REST COMMS]: Null reply on DoCreateObjectCall post"); - } - - sr = new StreamReader(webResponse.GetResponseStream()); - sr.ReadToEnd().Trim(); - sr.ReadToEnd().Trim(); - - //m_log.InfoFormat("[REST COMMS]: DoCreateChildAgentCall reply was {0} ", reply); - - } - catch (WebException ex) - { - m_log.InfoFormat("[REST COMMS]: exception on reply of DoCreateObjectCall {0}", ex.Message); - // ignore, really - } - finally - { - if (sr != null) - sr.Close(); - } - - return true; - - } - - public bool DoHelloNeighbourCall(RegionInfo region, RegionInfo thisRegion) - { - string uri = "http://" + region.ExternalEndPoint.Address + ":" + region.HttpPort + "/region/" + thisRegion.RegionID + "/"; - //m_log.Debug(" >>> DoHelloNeighbourCall <<< " + uri); - - WebRequest HelloNeighbourRequest = WebRequest.Create(uri); - HelloNeighbourRequest.Method = "POST"; - HelloNeighbourRequest.ContentType = "application/json"; - HelloNeighbourRequest.Timeout = 10000; - - // Fill it in - OSDMap args = null; - try - { - args = thisRegion.PackRegionInfoData(); - } - catch (Exception e) - { - m_log.Debug("[REST COMMS]: PackRegionInfoData failed with exception: " + e.Message); - } - // Add the regionhandle of the destination region - ulong regionHandle = GetRegionHandle(region.RegionHandle); - args["destination_handle"] = OSD.FromString(regionHandle.ToString()); - - string strBuffer = ""; - byte[] buffer = new byte[1]; - try - { - strBuffer = OSDParser.SerializeJsonString(args); - Encoding str = Util.UTF8; - buffer = str.GetBytes(strBuffer); - - } - catch (Exception e) - { - m_log.WarnFormat("[REST COMMS]: Exception thrown on serialization of HelloNeighbour: {0}", e.Message); - // ignore. buffer will be empty, caller should check. - } - - Stream os = null; - try - { // send the Post - HelloNeighbourRequest.ContentLength = buffer.Length; //Count bytes to send - os = HelloNeighbourRequest.GetRequestStream(); - os.Write(buffer, 0, strBuffer.Length); //Send it - //m_log.InfoFormat("[REST COMMS]: Posted HelloNeighbour request to remote sim {0}", uri); - } - //catch (WebException ex) - catch - { - //m_log.InfoFormat("[REST COMMS]: Bad send on HelloNeighbour {0}", ex.Message); - - return false; - } - finally - { - if (os != null) - os.Close(); - } - // Let's wait for the response - //m_log.Info("[REST COMMS]: Waiting for a reply after DoHelloNeighbourCall"); - - StreamReader sr = null; - try - { - WebResponse webResponse = HelloNeighbourRequest.GetResponse(); - if (webResponse == null) - { - m_log.Info("[REST COMMS]: Null reply on DoHelloNeighbourCall post"); - } - - sr = new StreamReader(webResponse.GetResponseStream()); - //reply = sr.ReadToEnd().Trim(); - sr.ReadToEnd().Trim(); - //m_log.InfoFormat("[REST COMMS]: DoHelloNeighbourCall reply was {0} ", reply); - - } - catch (WebException ex) - { - m_log.InfoFormat("[REST COMMS]: exception on reply of DoHelloNeighbourCall {0}", ex.Message); - // ignore, really - } - finally - { - if (sr != null) - sr.Close(); - } - - return true; - - } - - #region Hyperlinks - - public virtual ulong GetRegionHandle(ulong handle) - { - return handle; - } - - public virtual bool IsHyperlink(ulong handle) - { - return false; - } - - public virtual void SendUserInformation(GridRegion regInfo, AgentCircuitData aCircuit) - { - } - - public virtual void AdjustUserInformation(AgentCircuitData aCircuit) - { - } - - #endregion /* Hyperlinks */ - - public static OSDMap GetOSDMap(string data) - { - OSDMap args = null; - try - { - OSD buffer; - // We should pay attention to the content-type, but let's assume we know it's Json - buffer = OSDParser.DeserializeJson(data); - if (buffer.Type == OSDType.Map) - { - args = (OSDMap)buffer; - return args; - } - else - { - // uh? - System.Console.WriteLine("[REST COMMS]: Got OSD of type " + buffer.Type.ToString()); - return null; - } - } - catch (Exception ex) - { - System.Console.WriteLine("[REST COMMS]: exception on parse of REST message " + ex.Message); - return null; - } - } - - - } -} diff --git a/OpenSim/Framework/Communications/Services/HGLoginAuthService.cs b/OpenSim/Framework/Communications/Services/HGLoginAuthService.cs deleted file mode 100644 index d3f813e..0000000 --- a/OpenSim/Framework/Communications/Services/HGLoginAuthService.cs +++ /dev/null @@ -1,339 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Net; -using System.Reflection; -using System.Text.RegularExpressions; -using OpenSim.Framework; -using OpenSim.Framework.Communications.Cache; -using OpenSim.Framework.Capabilities; -using OpenSim.Framework.Servers; - -using OpenMetaverse; - -using log4net; -using Nini.Config; -using Nwc.XmlRpc; - -namespace OpenSim.Framework.Communications.Services -{ - public class HGLoginAuthService : LoginService - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - protected NetworkServersInfo m_serversInfo; - protected bool m_authUsers = false; - - /// - /// Used by the login service to make requests to the inventory service. - /// - protected IInterServiceInventoryServices m_interServiceInventoryService; - - /// - /// Used to make requests to the local regions. - /// - protected ILoginServiceToRegionsConnector m_regionsConnector; - - public HGLoginAuthService( - UserManagerBase userManager, string welcomeMess, - IInterServiceInventoryServices interServiceInventoryService, - NetworkServersInfo serversInfo, - bool authenticate, LibraryRootFolder libraryRootFolder, ILoginServiceToRegionsConnector regionsConnector) - : base(userManager, libraryRootFolder, welcomeMess) - { - this.m_serversInfo = serversInfo; - if (m_serversInfo != null) - { - m_defaultHomeX = this.m_serversInfo.DefaultHomeLocX; - m_defaultHomeY = this.m_serversInfo.DefaultHomeLocY; - } - m_authUsers = authenticate; - - m_interServiceInventoryService = interServiceInventoryService; - m_regionsConnector = regionsConnector; - m_interInventoryService = interServiceInventoryService; - } - - public void SetServersInfo(NetworkServersInfo sinfo) - { - m_serversInfo = sinfo; - } - - public override XmlRpcResponse XmlRpcLoginMethod(XmlRpcRequest request, IPEndPoint remoteClient) - { - m_log.Info("[HGLOGIN]: HGLogin called " + request.MethodName); - XmlRpcResponse response = base.XmlRpcLoginMethod(request, remoteClient); - Hashtable responseData = (Hashtable)response.Value; - - responseData["grid_service"] = m_serversInfo.GridURL; - responseData["grid_service_send_key"] = m_serversInfo.GridSendKey; - responseData["inventory_service"] = m_serversInfo.InventoryURL; - responseData["asset_service"] = m_serversInfo.AssetURL; - responseData["asset_service_send_key"] = m_serversInfo.AssetSendKey; - int x = (Int32)responseData["region_x"]; - int y = (Int32)responseData["region_y"]; - uint ux = (uint)(x / Constants.RegionSize); - uint uy = (uint)(y / Constants.RegionSize); - ulong regionHandle = Util.UIntsToLong(ux, uy); - responseData["region_handle"] = regionHandle.ToString(); - - // Let's remove the seed cap from the login - //responseData.Remove("seed_capability"); - - // Let's add the appearance - UUID userID = UUID.Zero; - UUID.TryParse((string)responseData["agent_id"], out userID); - AvatarAppearance appearance = m_userManager.GetUserAppearance(userID); - if (appearance == null) - { - m_log.WarnFormat("[INTER]: Appearance not found for {0}. Creating default.", userID); - appearance = new AvatarAppearance(); - } - - responseData["appearance"] = appearance.ToHashTable(); - - // Let's also send the auth token - UUID token = UUID.Random(); - responseData["auth_token"] = token.ToString(); - UserProfileData userProfile = m_userManager.GetUserProfile(userID); - if (userProfile != null) - { - userProfile.WebLoginKey = token; - m_userManager.CommitAgent(ref userProfile); - } - m_log.Warn("[HGLOGIN]: Auth token: " + token); - - - return response; - } - - public XmlRpcResponse XmlRpcGenerateKeyMethod(XmlRpcRequest request, IPEndPoint remoteClient) - { - // Verify the key of who's calling - UUID userID = UUID.Zero; - UUID authKey = UUID.Zero; - UUID.TryParse((string)request.Params[0], out userID); - UUID.TryParse((string)request.Params[1], out authKey); - - m_log.InfoFormat("[HGLOGIN] HGGenerateKey called with authToken ", authKey); - string newKey = string.Empty; - - if (!(m_userManager is IAuthentication)) - { - m_log.Debug("[HGLOGIN]: UserManager is not IAuthentication service. Returning empty key."); - } - else - { - newKey = ((IAuthentication)m_userManager).GetNewKey(m_serversInfo.UserURL, userID, authKey); - } - - XmlRpcResponse response = new XmlRpcResponse(); - response.Value = (string) newKey; - return response; - } - - public XmlRpcResponse XmlRpcVerifyKeyMethod(XmlRpcRequest request, IPEndPoint remoteClient) - { - bool success = false; - - if (request.Params.Count >= 2) - { - // Verify the key of who's calling - UUID userID = UUID.Zero; - string authKey = string.Empty; - if (UUID.TryParse((string)request.Params[0], out userID)) - { - authKey = (string)request.Params[1]; - - m_log.InfoFormat("[HGLOGIN] HGVerifyKey called with key {0}", authKey); - - if (!(m_userManager is IAuthentication)) - { - m_log.Debug("[HGLOGIN]: UserManager is not IAuthentication service. Denying."); - } - else - { - success = ((IAuthentication)m_userManager).VerifyKey(userID, authKey); - } - } - } - - m_log.DebugFormat("[HGLOGIN]: Response to VerifyKey is {0}", success); - XmlRpcResponse response = new XmlRpcResponse(); - response.Value = success; - return response; - } - - public override UserProfileData GetTheUser(string firstname, string lastname) - { - UserProfileData profile = m_userManager.GetUserProfile(firstname, lastname); - if (profile != null) - { - return profile; - } - - if (!m_authUsers) - { - //no current user account so make one - m_log.Info("[LOGIN]: No user account found so creating a new one."); - - m_userManager.AddUser(firstname, lastname, "test", "", m_defaultHomeX, m_defaultHomeY); - - return m_userManager.GetUserProfile(firstname, lastname); - } - - return null; - } - - public override bool AuthenticateUser(UserProfileData profile, string password) - { - if (!m_authUsers) - { - //for now we will accept any password in sandbox mode - m_log.Info("[LOGIN]: Authorising user (no actual password check)"); - - return true; - } - else - { - m_log.Info( - "[LOGIN]: Authenticating " + profile.FirstName + " " + profile.SurName); - - if (!password.StartsWith("$1$")) - password = "$1$" + Util.Md5Hash(password); - - password = password.Remove(0, 3); //remove $1$ - - string s = Util.Md5Hash(password + ":" + profile.PasswordSalt); - - bool loginresult = (profile.PasswordHash.Equals(s.ToString(), StringComparison.InvariantCultureIgnoreCase) - || profile.PasswordHash.Equals(password, StringComparison.InvariantCulture)); - return loginresult; - } - } - - protected override RegionInfo RequestClosestRegion(string region) - { - return m_regionsConnector.RequestClosestRegion(region); - } - - protected override RegionInfo GetRegionInfo(ulong homeRegionHandle) - { - return m_regionsConnector.RequestNeighbourInfo(homeRegionHandle); - } - - protected override RegionInfo GetRegionInfo(UUID homeRegionId) - { - return m_regionsConnector.RequestNeighbourInfo(homeRegionId); - } - - /// - /// Not really informing the region. Just filling out the response fields related to the region. - /// - /// - /// - /// - /// true if the region was successfully contacted, false otherwise - protected override bool PrepareLoginToRegion(RegionInfo regionInfo, UserProfileData user, LoginResponse response, IPEndPoint remoteClient) - { - IPEndPoint endPoint = regionInfo.ExternalEndPoint; - response.SimAddress = endPoint.Address.ToString(); - response.SimPort = (uint)endPoint.Port; - response.RegionX = regionInfo.RegionLocX; - response.RegionY = regionInfo.RegionLocY; - response.SimHttpPort = regionInfo.HttpPort; - - string capsPath = CapsUtil.GetRandomCapsObjectPath(); - string capsSeedPath = CapsUtil.GetCapsSeedPath(capsPath); - - // Don't use the following! It Fails for logging into any region not on the same port as the http server! - // Kept here so it doesn't happen again! - // response.SeedCapability = regionInfo.ServerURI + capsSeedPath; - - string seedcap = "http://"; - - if (m_serversInfo.HttpUsesSSL) - { - // For NAT - string host = NetworkUtil.GetHostFor(remoteClient.Address, m_serversInfo.HttpSSLCN); - - seedcap = "https://" + host + ":" + m_serversInfo.httpSSLPort + capsSeedPath; - } - else - { - // For NAT - string host = NetworkUtil.GetHostFor(remoteClient.Address, regionInfo.ExternalHostName); - - seedcap = "http://" + host + ":" + m_serversInfo.HttpListenerPort + capsSeedPath; - } - - response.SeedCapability = seedcap; - - // Notify the target of an incoming user - m_log.InfoFormat( - "[LOGIN]: Telling {0} @ {1},{2} ({3}) to prepare for client connection", - regionInfo.RegionName, response.RegionX, response.RegionY, regionInfo.ServerURI); - - // Update agent with target sim - user.CurrentAgent.Region = regionInfo.RegionID; - user.CurrentAgent.Handle = regionInfo.RegionHandle; - - return true; - } - - public override void LogOffUser(UserProfileData theUser, string message) - { - RegionInfo SimInfo; - try - { - SimInfo = this.m_regionsConnector.RequestNeighbourInfo(theUser.CurrentAgent.Handle); - - if (SimInfo == null) - { - m_log.Error("[LOCAL LOGIN]: Region user was in isn't currently logged in"); - return; - } - } - catch (Exception) - { - m_log.Error("[LOCAL LOGIN]: Unable to look up region to log user off"); - return; - } - - m_regionsConnector.LogOffUserFromGrid(SimInfo.RegionHandle, theUser.ID, theUser.CurrentAgent.SecureSessionID, "Logging you off"); - } - - protected override bool AllowLoginWithoutInventory() - { - return true; - } - - } -} diff --git a/OpenSim/Framework/Communications/Services/LoginResponse.cs b/OpenSim/Framework/Communications/Services/LoginResponse.cs deleted file mode 100644 index ec5f428..0000000 --- a/OpenSim/Framework/Communications/Services/LoginResponse.cs +++ /dev/null @@ -1,823 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using log4net; -using Nwc.XmlRpc; -using OpenMetaverse; -using OpenMetaverse.StructuredData; - -namespace OpenSim.Framework.Communications.Services -{ - /// - /// A temp class to handle login response. - /// Should make use of UserProfileManager where possible. - /// - public class LoginResponse - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private Hashtable loginFlagsHash; - private Hashtable globalTexturesHash; - private Hashtable loginError; - private Hashtable uiConfigHash; - - private ArrayList loginFlags; - private ArrayList globalTextures; - private ArrayList eventCategories; - private ArrayList uiConfig; - private ArrayList classifiedCategories; - private ArrayList inventoryRoot; - private ArrayList initialOutfit; - private ArrayList agentInventory; - private ArrayList inventoryLibraryOwner; - private ArrayList inventoryLibRoot; - private ArrayList inventoryLibrary; - private ArrayList activeGestures; - - private UserInfo userProfile; - - private UUID agentID; - private UUID sessionID; - private UUID secureSessionID; - - // Login Flags - private string dst; - private string stipendSinceLogin; - private string gendered; - private string everLoggedIn; - private string login; - private uint simPort; - private uint simHttpPort; - private string simAddress; - private string agentAccess; - private string agentAccessMax; - private Int32 circuitCode; - private uint regionX; - private uint regionY; - - // Login - private string firstname; - private string lastname; - - // Global Textures - private string sunTexture; - private string cloudTexture; - private string moonTexture; - - // Error Flags - private string errorReason; - private string errorMessage; - - // Response - private XmlRpcResponse xmlRpcResponse; - // private XmlRpcResponse defaultXmlRpcResponse; - - private string welcomeMessage; - private string startLocation; - private string allowFirstLife; - private string home; - private string seedCapability; - private string lookAt; - - private BuddyList m_buddyList = null; - - public LoginResponse() - { - loginFlags = new ArrayList(); - globalTextures = new ArrayList(); - eventCategories = new ArrayList(); - uiConfig = new ArrayList(); - classifiedCategories = new ArrayList(); - - loginError = new Hashtable(); - uiConfigHash = new Hashtable(); - - // defaultXmlRpcResponse = new XmlRpcResponse(); - userProfile = new UserInfo(); - inventoryRoot = new ArrayList(); - initialOutfit = new ArrayList(); - agentInventory = new ArrayList(); - inventoryLibrary = new ArrayList(); - inventoryLibraryOwner = new ArrayList(); - activeGestures = new ArrayList(); - - xmlRpcResponse = new XmlRpcResponse(); - // defaultXmlRpcResponse = new XmlRpcResponse(); - - SetDefaultValues(); - } - - private void SetDefaultValues() - { - DST = TimeZone.CurrentTimeZone.IsDaylightSavingTime(DateTime.Now) ? "Y" : "N"; - StipendSinceLogin = "N"; - Gendered = "Y"; - EverLoggedIn = "Y"; - login = "false"; - firstname = "Test"; - lastname = "User"; - agentAccess = "M"; - agentAccessMax = "A"; - startLocation = "last"; - allowFirstLife = "Y"; - - SunTexture = "cce0f112-878f-4586-a2e2-a8f104bba271"; - CloudTexture = "dc4b9f0b-d008-45c6-96a4-01dd947ac621"; - MoonTexture = "ec4b9f0b-d008-45c6-96a4-01dd947ac621"; - - ErrorMessage = "You have entered an invalid name/password combination. Check Caps/lock."; - ErrorReason = "key"; - welcomeMessage = "Welcome to OpenSim!"; - seedCapability = String.Empty; - home = "{'region_handle':[r" + (1000*Constants.RegionSize).ToString() + ",r" + (1000*Constants.RegionSize).ToString() + "], 'position':[r" + - userProfile.homepos.X.ToString() + ",r" + userProfile.homepos.Y.ToString() + ",r" + - userProfile.homepos.Z.ToString() + "], 'look_at':[r" + userProfile.homelookat.X.ToString() + ",r" + - userProfile.homelookat.Y.ToString() + ",r" + userProfile.homelookat.Z.ToString() + "]}"; - lookAt = "[r0.99949799999999999756,r0.03166859999999999814,r0]"; - RegionX = (uint) 255232; - RegionY = (uint) 254976; - - // Classifieds; - AddClassifiedCategory((Int32) 1, "Shopping"); - AddClassifiedCategory((Int32) 2, "Land Rental"); - AddClassifiedCategory((Int32) 3, "Property Rental"); - AddClassifiedCategory((Int32) 4, "Special Attraction"); - AddClassifiedCategory((Int32) 5, "New Products"); - AddClassifiedCategory((Int32) 6, "Employment"); - AddClassifiedCategory((Int32) 7, "Wanted"); - AddClassifiedCategory((Int32) 8, "Service"); - AddClassifiedCategory((Int32) 9, "Personal"); - - SessionID = UUID.Random(); - SecureSessionID = UUID.Random(); - AgentID = UUID.Random(); - - Hashtable InitialOutfitHash = new Hashtable(); - InitialOutfitHash["folder_name"] = "Nightclub Female"; - InitialOutfitHash["gender"] = "female"; - initialOutfit.Add(InitialOutfitHash); - } - - #region Login Failure Methods - - public XmlRpcResponse GenerateFailureResponse(string reason, string message, string login) - { - // Overwrite any default values; - xmlRpcResponse = new XmlRpcResponse(); - - // Ensure Login Failed message/reason; - ErrorMessage = message; - ErrorReason = reason; - - loginError["reason"] = ErrorReason; - loginError["message"] = ErrorMessage; - loginError["login"] = login; - xmlRpcResponse.Value = loginError; - return (xmlRpcResponse); - } - - public OSD GenerateFailureResponseLLSD(string reason, string message, string login) - { - OSDMap map = new OSDMap(); - - // Ensure Login Failed message/reason; - ErrorMessage = message; - ErrorReason = reason; - - map["reason"] = OSD.FromString(ErrorReason); - map["message"] = OSD.FromString(ErrorMessage); - map["login"] = OSD.FromString(login); - - return map; - } - - public XmlRpcResponse CreateFailedResponse() - { - return (CreateLoginFailedResponse()); - } - - public OSD CreateFailedResponseLLSD() - { - return CreateLoginFailedResponseLLSD(); - } - - public XmlRpcResponse CreateLoginFailedResponse() - { - return - (GenerateFailureResponse("key", - "Could not authenticate your avatar. Please check your username and password, and check the grid if problems persist.", - "false")); - } - - public OSD CreateLoginFailedResponseLLSD() - { - return GenerateFailureResponseLLSD( - "key", - "Could not authenticate your avatar. Please check your username and password, and check the grid if problems persist.", - "false"); - } - - /// - /// Response to indicate that login failed because the agent's inventory was not available. - /// - /// - public XmlRpcResponse CreateLoginInventoryFailedResponse() - { - return GenerateFailureResponse( - "key", - "The avatar inventory service is not responding. Please notify your login region operator.", - "false"); - } - - public XmlRpcResponse CreateAlreadyLoggedInResponse() - { - return - (GenerateFailureResponse("presence", - "You appear to be already logged in. " + - "If this is not the case please wait for your session to timeout. " + - "If this takes longer than a few minutes please contact the grid owner. " + - "Please wait 5 minutes if you are going to connect to a region nearby to the region you were at previously.", - "false")); - } - - public OSD CreateAlreadyLoggedInResponseLLSD() - { - return GenerateFailureResponseLLSD( - "presence", - "You appear to be already logged in. " + - "If this is not the case please wait for your session to timeout. " + - "If this takes longer than a few minutes please contact the grid owner", - "false"); - } - - public XmlRpcResponse CreateLoginBlockedResponse() - { - return - (GenerateFailureResponse("presence", - "Logins are currently restricted. Please try again later", - "false")); - } - - public OSD CreateLoginBlockedResponseLLSD() - { - return GenerateFailureResponseLLSD( - "presence", - "Logins are currently restricted. Please try again later", - "false"); - } - - public XmlRpcResponse CreateDeadRegionResponse() - { - return - (GenerateFailureResponse("key", - "The region you are attempting to log into is not responding. Please select another region and try again.", - "false")); - } - - public OSD CreateDeadRegionResponseLLSD() - { - return GenerateFailureResponseLLSD( - "key", - "The region you are attempting to log into is not responding. Please select another region and try again.", - "false"); - } - - public XmlRpcResponse CreateGridErrorResponse() - { - return - (GenerateFailureResponse("key", - "Error connecting to grid. Could not percieve credentials from login XML.", - "false")); - } - - public OSD CreateGridErrorResponseLLSD() - { - return GenerateFailureResponseLLSD( - "key", - "Error connecting to grid. Could not perceive credentials from login XML.", - "false"); - } - - #endregion - - public virtual XmlRpcResponse ToXmlRpcResponse() - { - try - { - Hashtable responseData = new Hashtable(); - - loginFlagsHash = new Hashtable(); - loginFlagsHash["daylight_savings"] = DST; - loginFlagsHash["stipend_since_login"] = StipendSinceLogin; - loginFlagsHash["gendered"] = Gendered; - loginFlagsHash["ever_logged_in"] = EverLoggedIn; - loginFlags.Add(loginFlagsHash); - - responseData["first_name"] = Firstname; - responseData["last_name"] = Lastname; - responseData["agent_access"] = agentAccess; - responseData["agent_access_max"] = agentAccessMax; - - globalTexturesHash = new Hashtable(); - globalTexturesHash["sun_texture_id"] = SunTexture; - globalTexturesHash["cloud_texture_id"] = CloudTexture; - globalTexturesHash["moon_texture_id"] = MoonTexture; - globalTextures.Add(globalTexturesHash); - // this.eventCategories.Add(this.eventCategoriesHash); - - AddToUIConfig("allow_first_life", allowFirstLife); - uiConfig.Add(uiConfigHash); - - responseData["sim_port"] = (Int32) SimPort; - responseData["sim_ip"] = SimAddress; - responseData["http_port"] = (Int32)SimHttpPort; - - responseData["agent_id"] = AgentID.ToString(); - responseData["session_id"] = SessionID.ToString(); - responseData["secure_session_id"] = SecureSessionID.ToString(); - responseData["circuit_code"] = CircuitCode; - responseData["seconds_since_epoch"] = (Int32) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; - responseData["login-flags"] = loginFlags; - responseData["global-textures"] = globalTextures; - responseData["seed_capability"] = seedCapability; - - responseData["event_categories"] = eventCategories; - responseData["event_notifications"] = new ArrayList(); // todo - responseData["classified_categories"] = classifiedCategories; - responseData["ui-config"] = uiConfig; - - if (agentInventory != null) - { - responseData["inventory-skeleton"] = agentInventory; - responseData["inventory-root"] = inventoryRoot; - } - responseData["inventory-skel-lib"] = inventoryLibrary; - responseData["inventory-lib-root"] = inventoryLibRoot; - responseData["gestures"] = activeGestures; - responseData["inventory-lib-owner"] = inventoryLibraryOwner; - responseData["initial-outfit"] = initialOutfit; - responseData["start_location"] = startLocation; - responseData["seed_capability"] = seedCapability; - responseData["home"] = home; - responseData["look_at"] = lookAt; - responseData["message"] = welcomeMessage; - responseData["region_x"] = (Int32)(RegionX * Constants.RegionSize); - responseData["region_y"] = (Int32)(RegionY * Constants.RegionSize); - - if (m_buddyList != null) - { - responseData["buddy-list"] = m_buddyList.ToArray(); - } - - responseData["login"] = "true"; - xmlRpcResponse.Value = responseData; - - return (xmlRpcResponse); - } - catch (Exception e) - { - m_log.Warn("[CLIENT]: LoginResponse: Error creating XML-RPC Response: " + e.Message); - - return (GenerateFailureResponse("Internal Error", "Error generating Login Response", "false")); - } - } - - public OSD ToLLSDResponse() - { - try - { - OSDMap map = new OSDMap(); - - map["first_name"] = OSD.FromString(Firstname); - map["last_name"] = OSD.FromString(Lastname); - map["agent_access"] = OSD.FromString(agentAccess); - map["agent_access_max"] = OSD.FromString(agentAccessMax); - - map["sim_port"] = OSD.FromInteger(SimPort); - map["sim_ip"] = OSD.FromString(SimAddress); - - map["agent_id"] = OSD.FromUUID(AgentID); - map["session_id"] = OSD.FromUUID(SessionID); - map["secure_session_id"] = OSD.FromUUID(SecureSessionID); - map["circuit_code"] = OSD.FromInteger(CircuitCode); - map["seconds_since_epoch"] = OSD.FromInteger((int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds); - - #region Login Flags - - OSDMap loginFlagsLLSD = new OSDMap(); - loginFlagsLLSD["daylight_savings"] = OSD.FromString(DST); - loginFlagsLLSD["stipend_since_login"] = OSD.FromString(StipendSinceLogin); - loginFlagsLLSD["gendered"] = OSD.FromString(Gendered); - loginFlagsLLSD["ever_logged_in"] = OSD.FromString(EverLoggedIn); - map["login-flags"] = WrapOSDMap(loginFlagsLLSD); - - #endregion Login Flags - - #region Global Textures - - OSDMap globalTexturesLLSD = new OSDMap(); - globalTexturesLLSD["sun_texture_id"] = OSD.FromString(SunTexture); - globalTexturesLLSD["cloud_texture_id"] = OSD.FromString(CloudTexture); - globalTexturesLLSD["moon_texture_id"] = OSD.FromString(MoonTexture); - - map["global-textures"] = WrapOSDMap(globalTexturesLLSD); - - #endregion Global Textures - - map["seed_capability"] = OSD.FromString(seedCapability); - - map["event_categories"] = ArrayListToOSDArray(eventCategories); - //map["event_notifications"] = new OSDArray(); // todo - map["classified_categories"] = ArrayListToOSDArray(classifiedCategories); - - #region UI Config - - OSDMap uiConfigLLSD = new OSDMap(); - uiConfigLLSD["allow_first_life"] = OSD.FromString(allowFirstLife); - map["ui-config"] = WrapOSDMap(uiConfigLLSD); - - #endregion UI Config - - #region Inventory - - map["inventory-skeleton"] = ArrayListToOSDArray(agentInventory); - - map["inventory-skel-lib"] = ArrayListToOSDArray(inventoryLibrary); - map["inventory-root"] = ArrayListToOSDArray(inventoryRoot); ; - map["inventory-lib-root"] = ArrayListToOSDArray(inventoryLibRoot); - map["inventory-lib-owner"] = ArrayListToOSDArray(inventoryLibraryOwner); - - #endregion Inventory - - map["gestures"] = ArrayListToOSDArray(activeGestures); - - map["initial-outfit"] = ArrayListToOSDArray(initialOutfit); - map["start_location"] = OSD.FromString(startLocation); - - map["seed_capability"] = OSD.FromString(seedCapability); - map["home"] = OSD.FromString(home); - map["look_at"] = OSD.FromString(lookAt); - map["message"] = OSD.FromString(welcomeMessage); - map["region_x"] = OSD.FromInteger(RegionX * Constants.RegionSize); - map["region_y"] = OSD.FromInteger(RegionY * Constants.RegionSize); - - if (m_buddyList != null) - { - map["buddy-list"] = ArrayListToOSDArray(m_buddyList.ToArray()); - } - - map["login"] = OSD.FromString("true"); - - return map; - } - catch (Exception e) - { - m_log.Warn("[CLIENT]: LoginResponse: Error creating LLSD Response: " + e.Message); - - return GenerateFailureResponseLLSD("Internal Error", "Error generating Login Response", "false"); - } - } - - public OSDArray ArrayListToOSDArray(ArrayList arrlst) - { - OSDArray llsdBack = new OSDArray(); - foreach (Hashtable ht in arrlst) - { - OSDMap mp = new OSDMap(); - foreach (DictionaryEntry deHt in ht) - { - mp.Add((string)deHt.Key, OSDString.FromObject(deHt.Value)); - } - llsdBack.Add(mp); - } - return llsdBack; - } - - private static OSDArray WrapOSDMap(OSDMap wrapMe) - { - OSDArray array = new OSDArray(); - array.Add(wrapMe); - return array; - } - - public void SetEventCategories(string category, string value) - { - // this.eventCategoriesHash[category] = value; - //TODO - } - - public void AddToUIConfig(string itemName, string item) - { - uiConfigHash[itemName] = item; - } - - public void AddClassifiedCategory(Int32 ID, string categoryName) - { - Hashtable hash = new Hashtable(); - hash["category_name"] = categoryName; - hash["category_id"] = ID; - classifiedCategories.Add(hash); - // this.classifiedCategoriesHash.Clear(); - } - - #region Properties - - public string Login - { - get { return login; } - set { login = value; } - } - - public string DST - { - get { return dst; } - set { dst = value; } - } - - public string StipendSinceLogin - { - get { return stipendSinceLogin; } - set { stipendSinceLogin = value; } - } - - public string Gendered - { - get { return gendered; } - set { gendered = value; } - } - - public string EverLoggedIn - { - get { return everLoggedIn; } - set { everLoggedIn = value; } - } - - public uint SimPort - { - get { return simPort; } - set { simPort = value; } - } - - public uint SimHttpPort - { - get { return simHttpPort; } - set { simHttpPort = value; } - } - - public string SimAddress - { - get { return simAddress; } - set { simAddress = value; } - } - - public UUID AgentID - { - get { return agentID; } - set { agentID = value; } - } - - public UUID SessionID - { - get { return sessionID; } - set { sessionID = value; } - } - - public UUID SecureSessionID - { - get { return secureSessionID; } - set { secureSessionID = value; } - } - - public Int32 CircuitCode - { - get { return circuitCode; } - set { circuitCode = value; } - } - - public uint RegionX - { - get { return regionX; } - set { regionX = value; } - } - - public uint RegionY - { - get { return regionY; } - set { regionY = value; } - } - - public string SunTexture - { - get { return sunTexture; } - set { sunTexture = value; } - } - - public string CloudTexture - { - get { return cloudTexture; } - set { cloudTexture = value; } - } - - public string MoonTexture - { - get { return moonTexture; } - set { moonTexture = value; } - } - - public string Firstname - { - get { return firstname; } - set { firstname = value; } - } - - public string Lastname - { - get { return lastname; } - set { lastname = value; } - } - - public string AgentAccess - { - get { return agentAccess; } - set { agentAccess = value; } - } - - public string AgentAccessMax - { - get { return agentAccessMax; } - set { agentAccessMax = value; } - } - - public string StartLocation - { - get { return startLocation; } - set { startLocation = value; } - } - - public string LookAt - { - get { return lookAt; } - set { lookAt = value; } - } - - public string SeedCapability - { - get { return seedCapability; } - set { seedCapability = value; } - } - - public string ErrorReason - { - get { return errorReason; } - set { errorReason = value; } - } - - public string ErrorMessage - { - get { return errorMessage; } - set { errorMessage = value; } - } - - public ArrayList InventoryRoot - { - get { return inventoryRoot; } - set { inventoryRoot = value; } - } - - public ArrayList InventorySkeleton - { - get { return agentInventory; } - set { agentInventory = value; } - } - - public ArrayList InventoryLibrary - { - get { return inventoryLibrary; } - set { inventoryLibrary = value; } - } - - public ArrayList InventoryLibraryOwner - { - get { return inventoryLibraryOwner; } - set { inventoryLibraryOwner = value; } - } - - public ArrayList InventoryLibRoot - { - get { return inventoryLibRoot; } - set { inventoryLibRoot = value; } - } - - public ArrayList ActiveGestures - { - get { return activeGestures; } - set { activeGestures = value; } - } - - public string Home - { - get { return home; } - set { home = value; } - } - - public string Message - { - get { return welcomeMessage; } - set { welcomeMessage = value; } - } - - public BuddyList BuddList - { - get { return m_buddyList; } - set { m_buddyList = value; } - } - - #endregion - - public class UserInfo - { - public string firstname; - public string lastname; - public ulong homeregionhandle; - public Vector3 homepos; - public Vector3 homelookat; - } - - public class BuddyList - { - public List Buddies = new List(); - - public void AddNewBuddy(BuddyInfo buddy) - { - if (!Buddies.Contains(buddy)) - { - Buddies.Add(buddy); - } - } - - public ArrayList ToArray() - { - ArrayList buddyArray = new ArrayList(); - foreach (BuddyInfo buddy in Buddies) - { - buddyArray.Add(buddy.ToHashTable()); - } - return buddyArray; - } - - public class BuddyInfo - { - public int BuddyRightsHave = 1; - public int BuddyRightsGiven = 1; - public UUID BuddyID; - - public BuddyInfo(string buddyID) - { - BuddyID = new UUID(buddyID); - } - - public BuddyInfo(UUID buddyID) - { - BuddyID = buddyID; - } - - public Hashtable ToHashTable() - { - Hashtable hTable = new Hashtable(); - hTable["buddy_rights_has"] = BuddyRightsHave; - hTable["buddy_rights_given"] = BuddyRightsGiven; - hTable["buddy_id"] = BuddyID.ToString(); - return hTable; - } - } - } - } -} diff --git a/OpenSim/Framework/Communications/Services/LoginService.cs b/OpenSim/Framework/Communications/Services/LoginService.cs deleted file mode 100644 index 57ca704..0000000 --- a/OpenSim/Framework/Communications/Services/LoginService.cs +++ /dev/null @@ -1,1243 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Net; -using System.Reflection; -using System.Text.RegularExpressions; -using System.Threading; -using System.Web; -using log4net; -using Nwc.XmlRpc; -using OpenMetaverse; -using OpenMetaverse.StructuredData; -using OpenSim.Framework; -using OpenSim.Framework.Communications.Cache; -using OpenSim.Framework.Statistics; -using OpenSim.Services.Interfaces; - -namespace OpenSim.Framework.Communications.Services -{ - public abstract class LoginService - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - protected string m_welcomeMessage = "Welcome to OpenSim"; - protected int m_minLoginLevel = 0; - protected UserManagerBase m_userManager = null; - protected Mutex m_loginMutex = new Mutex(false); - - /// - /// Used during login to send the skeleton of the OpenSim Library to the client. - /// - protected LibraryRootFolder m_libraryRootFolder; - - protected uint m_defaultHomeX; - protected uint m_defaultHomeY; - - protected bool m_warn_already_logged = true; - - /// - /// Used by the login service to make requests to the inventory service. - /// - protected IInterServiceInventoryServices m_interInventoryService; - // Hack - protected IInventoryService m_InventoryService; - - /// - /// Constructor - /// - /// - /// - /// - public LoginService(UserManagerBase userManager, LibraryRootFolder libraryRootFolder, - string welcomeMess) - { - m_userManager = userManager; - m_libraryRootFolder = libraryRootFolder; - - if (welcomeMess != String.Empty) - { - m_welcomeMessage = welcomeMess; - } - } - - /// - /// If the user is already logged in, try to notify the region that the user they've got is dead. - /// - /// - public virtual void LogOffUser(UserProfileData theUser, string message) - { - } - - /// - /// Called when we receive the client's initial XMLRPC login_to_simulator request message - /// - /// The XMLRPC request - /// The response to send - public virtual XmlRpcResponse XmlRpcLoginMethod(XmlRpcRequest request, IPEndPoint remoteClient) - { - // Temporary fix - m_loginMutex.WaitOne(); - - try - { - //CFK: CustomizeResponse contains sufficient strings to alleviate the need for this. - //CKF: m_log.Info("[LOGIN]: Attempting login now..."); - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable)request.Params[0]; - - SniffLoginKey((Uri)request.Params[2], requestData); - - bool GoodXML = (requestData.Contains("first") && requestData.Contains("last") && - (requestData.Contains("passwd") || requestData.Contains("web_login_key"))); - - string startLocationRequest = "last"; - - UserProfileData userProfile; - LoginResponse logResponse = new LoginResponse(); - - string firstname; - string lastname; - - if (GoodXML) - { - if (requestData.Contains("start")) - { - startLocationRequest = (string)requestData["start"]; - } - - firstname = (string)requestData["first"]; - lastname = (string)requestData["last"]; - - m_log.InfoFormat( - "[LOGIN BEGIN]: XMLRPC Received login request message from user '{0}' '{1}'", - firstname, lastname); - - string clientVersion = "Unknown"; - - if (requestData.Contains("version")) - { - clientVersion = (string)requestData["version"]; - } - - m_log.DebugFormat( - "[LOGIN]: XMLRPC Client is {0}, start location is {1}", clientVersion, startLocationRequest); - - if (!TryAuthenticateXmlRpcLogin(request, firstname, lastname, out userProfile)) - { - return logResponse.CreateLoginFailedResponse(); - } - } - else - { - m_log.Info( - "[LOGIN END]: XMLRPC login_to_simulator login message did not contain all the required data"); - - return logResponse.CreateGridErrorResponse(); - } - - if (userProfile.GodLevel < m_minLoginLevel) - { - return logResponse.CreateLoginBlockedResponse(); - } - else - { - // If we already have a session... - if (userProfile.CurrentAgent != null && userProfile.CurrentAgent.AgentOnline) - { - //TODO: The following statements can cause trouble: - // If agentOnline could not turn from true back to false normally - // because of some problem, for instance, the crashment of server or client, - // the user cannot log in any longer. - userProfile.CurrentAgent.AgentOnline = false; - - m_userManager.CommitAgent(ref userProfile); - - // try to tell the region that their user is dead. - LogOffUser(userProfile, " XMLRPC You were logged off because you logged in from another location"); - - if (m_warn_already_logged) - { - // This is behavior for for grid, reject login - m_log.InfoFormat( - "[LOGIN END]: XMLRPC Notifying user {0} {1} that they are already logged in", - firstname, lastname); - - return logResponse.CreateAlreadyLoggedInResponse(); - } - else - { - // This is behavior for standalone (silent logout of last hung session) - m_log.InfoFormat( - "[LOGIN]: XMLRPC User {0} {1} is already logged in, not notifying user, kicking old presence and starting new login.", - firstname, lastname); - } - } - - // Otherwise... - // Create a new agent session - - // XXYY we don't need this - //m_userManager.ResetAttachments(userProfile.ID); - - CreateAgent(userProfile, request); - - // We need to commit the agent right here, even though the userProfile info is not complete - // at this point. There is another commit further down. - // This is for the new sessionID to be stored so that the region can check it for session authentication. - // CustomiseResponse->PrepareLoginToRegion - CommitAgent(ref userProfile); - - try - { - UUID agentID = userProfile.ID; - InventoryData inventData = null; - - try - { - inventData = GetInventorySkeleton(agentID); - } - catch (Exception e) - { - m_log.ErrorFormat( - "[LOGIN END]: Error retrieving inventory skeleton of agent {0} - {1}", - agentID, e); - - // Let's not panic - if (!AllowLoginWithoutInventory()) - return logResponse.CreateLoginInventoryFailedResponse(); - } - - if (inventData != null) - { - ArrayList AgentInventoryArray = inventData.InventoryArray; - - Hashtable InventoryRootHash = new Hashtable(); - InventoryRootHash["folder_id"] = inventData.RootFolderID.ToString(); - ArrayList InventoryRoot = new ArrayList(); - InventoryRoot.Add(InventoryRootHash); - - logResponse.InventoryRoot = InventoryRoot; - logResponse.InventorySkeleton = AgentInventoryArray; - } - - // Inventory Library Section - Hashtable InventoryLibRootHash = new Hashtable(); - InventoryLibRootHash["folder_id"] = "00000112-000f-0000-0000-000100bba000"; - ArrayList InventoryLibRoot = new ArrayList(); - InventoryLibRoot.Add(InventoryLibRootHash); - - logResponse.InventoryLibRoot = InventoryLibRoot; - logResponse.InventoryLibraryOwner = GetLibraryOwner(); - logResponse.InventoryLibrary = GetInventoryLibrary(); - - logResponse.CircuitCode = Util.RandomClass.Next(); - logResponse.Lastname = userProfile.SurName; - logResponse.Firstname = userProfile.FirstName; - logResponse.AgentID = agentID; - logResponse.SessionID = userProfile.CurrentAgent.SessionID; - logResponse.SecureSessionID = userProfile.CurrentAgent.SecureSessionID; - logResponse.Message = GetMessage(); - logResponse.BuddList = ConvertFriendListItem(m_userManager.GetUserFriendList(agentID)); - logResponse.StartLocation = startLocationRequest; - - if (CustomiseResponse(logResponse, userProfile, startLocationRequest, remoteClient)) - { - userProfile.LastLogin = userProfile.CurrentAgent.LoginTime; - CommitAgent(ref userProfile); - - // If we reach this point, then the login has successfully logged onto the grid - if (StatsManager.UserStats != null) - StatsManager.UserStats.AddSuccessfulLogin(); - - m_log.DebugFormat( - "[LOGIN END]: XMLRPC Authentication of user {0} {1} successful. Sending response to client.", - firstname, lastname); - - return logResponse.ToXmlRpcResponse(); - } - else - { - m_log.ErrorFormat("[LOGIN END]: XMLRPC informing user {0} {1} that login failed due to an unavailable region", firstname, lastname); - return logResponse.CreateDeadRegionResponse(); - } - } - catch (Exception e) - { - m_log.Error("[LOGIN END]: XMLRPC Login failed, " + e); - m_log.Error(e.StackTrace); - } - } - - m_log.Info("[LOGIN END]: XMLRPC Login failed. Sending back blank XMLRPC response"); - return response; - } - finally - { - m_loginMutex.ReleaseMutex(); - } - } - - protected virtual bool TryAuthenticateXmlRpcLogin( - XmlRpcRequest request, string firstname, string lastname, out UserProfileData userProfile) - { - Hashtable requestData = (Hashtable)request.Params[0]; - - userProfile = GetTheUser(firstname, lastname); - if (userProfile == null) - { - m_log.Debug("[LOGIN END]: XMLRPC Could not find a profile for " + firstname + " " + lastname); - return false; - } - else - { - if (requestData.Contains("passwd")) - { - string passwd = (string)requestData["passwd"]; - bool authenticated = AuthenticateUser(userProfile, passwd); - - if (!authenticated) - m_log.DebugFormat("[LOGIN END]: XMLRPC User {0} {1} failed password authentication", - firstname, lastname); - - return authenticated; - } - - if (requestData.Contains("web_login_key")) - { - try - { - UUID webloginkey = new UUID((string)requestData["web_login_key"]); - bool authenticated = AuthenticateUser(userProfile, webloginkey); - - if (!authenticated) - m_log.DebugFormat("[LOGIN END]: XMLRPC User {0} {1} failed web login key authentication", - firstname, lastname); - - return authenticated; - } - catch (Exception e) - { - m_log.DebugFormat( - "[LOGIN END]: XMLRPC Bad web_login_key: {0} for user {1} {2}, exception {3}", - requestData["web_login_key"], firstname, lastname, e); - - return false; - } - } - - m_log.DebugFormat( - "[LOGIN END]: XMLRPC login request for {0} {1} contained neither a password nor a web login key", - firstname, lastname); - } - - return false; - } - - protected virtual bool TryAuthenticateLLSDLogin(string firstname, string lastname, string passwd, out UserProfileData userProfile) - { - bool GoodLogin = false; - userProfile = GetTheUser(firstname, lastname); - if (userProfile == null) - { - m_log.Info("[LOGIN]: LLSD Could not find a profile for " + firstname + " " + lastname); - - return false; - } - - GoodLogin = AuthenticateUser(userProfile, passwd); - return GoodLogin; - } - - /// - /// Called when we receive the client's initial LLSD login_to_simulator request message - /// - /// The LLSD request - /// The response to send - public OSD LLSDLoginMethod(OSD request, IPEndPoint remoteClient) - { - // Temporary fix - m_loginMutex.WaitOne(); - - try - { - // bool GoodLogin = false; - - string startLocationRequest = "last"; - - UserProfileData userProfile = null; - LoginResponse logResponse = new LoginResponse(); - - if (request.Type == OSDType.Map) - { - OSDMap map = (OSDMap)request; - - if (map.ContainsKey("first") && map.ContainsKey("last") && map.ContainsKey("passwd")) - { - string firstname = map["first"].AsString(); - string lastname = map["last"].AsString(); - string passwd = map["passwd"].AsString(); - - if (map.ContainsKey("start")) - { - m_log.Info("[LOGIN]: LLSD StartLocation Requested: " + map["start"].AsString()); - startLocationRequest = map["start"].AsString(); - } - m_log.Info("[LOGIN]: LLSD Login Requested for: '" + firstname + "' '" + lastname + "' / " + passwd); - - if (!TryAuthenticateLLSDLogin(firstname, lastname, passwd, out userProfile)) - { - return logResponse.CreateLoginFailedResponseLLSD(); - } - } - else - return logResponse.CreateLoginFailedResponseLLSD(); - } - else - return logResponse.CreateLoginFailedResponseLLSD(); - - - if (userProfile.GodLevel < m_minLoginLevel) - { - return logResponse.CreateLoginBlockedResponseLLSD(); - } - else - { - // If we already have a session... - if (userProfile.CurrentAgent != null && userProfile.CurrentAgent.AgentOnline) - { - userProfile.CurrentAgent.AgentOnline = false; - - m_userManager.CommitAgent(ref userProfile); - // try to tell the region that their user is dead. - LogOffUser(userProfile, " LLSD You were logged off because you logged in from another location"); - - if (m_warn_already_logged) - { - // This is behavior for for grid, reject login - m_log.InfoFormat( - "[LOGIN END]: LLSD Notifying user {0} {1} that they are already logged in", - userProfile.FirstName, userProfile.SurName); - - userProfile.CurrentAgent = null; - return logResponse.CreateAlreadyLoggedInResponseLLSD(); - } - else - { - // This is behavior for standalone (silent logout of last hung session) - m_log.InfoFormat( - "[LOGIN]: LLSD User {0} {1} is already logged in, not notifying user, kicking old presence and starting new login.", - userProfile.FirstName, userProfile.SurName); - } - } - - // Otherwise... - // Create a new agent session - - // XXYY We don't need this - //m_userManager.ResetAttachments(userProfile.ID); - - CreateAgent(userProfile, request); - - // We need to commit the agent right here, even though the userProfile info is not complete - // at this point. There is another commit further down. - // This is for the new sessionID to be stored so that the region can check it for session authentication. - // CustomiseResponse->PrepareLoginToRegion - CommitAgent(ref userProfile); - - try - { - UUID agentID = userProfile.ID; - - //InventoryData inventData = GetInventorySkeleton(agentID); - InventoryData inventData = null; - - try - { - inventData = GetInventorySkeleton(agentID); - } - catch (Exception e) - { - m_log.ErrorFormat( - "[LOGIN END]: LLSD Error retrieving inventory skeleton of agent {0}, {1} - {2}", - agentID, e.GetType(), e.Message); - - return logResponse.CreateLoginFailedResponseLLSD();// .CreateLoginInventoryFailedResponseLLSD (); - } - - - ArrayList AgentInventoryArray = inventData.InventoryArray; - - Hashtable InventoryRootHash = new Hashtable(); - InventoryRootHash["folder_id"] = inventData.RootFolderID.ToString(); - ArrayList InventoryRoot = new ArrayList(); - InventoryRoot.Add(InventoryRootHash); - - - // Inventory Library Section - Hashtable InventoryLibRootHash = new Hashtable(); - InventoryLibRootHash["folder_id"] = "00000112-000f-0000-0000-000100bba000"; - ArrayList InventoryLibRoot = new ArrayList(); - InventoryLibRoot.Add(InventoryLibRootHash); - - logResponse.InventoryLibRoot = InventoryLibRoot; - logResponse.InventoryLibraryOwner = GetLibraryOwner(); - logResponse.InventoryRoot = InventoryRoot; - logResponse.InventorySkeleton = AgentInventoryArray; - logResponse.InventoryLibrary = GetInventoryLibrary(); - - logResponse.CircuitCode = (Int32)Util.RandomClass.Next(); - logResponse.Lastname = userProfile.SurName; - logResponse.Firstname = userProfile.FirstName; - logResponse.AgentID = agentID; - logResponse.SessionID = userProfile.CurrentAgent.SessionID; - logResponse.SecureSessionID = userProfile.CurrentAgent.SecureSessionID; - logResponse.Message = GetMessage(); - logResponse.BuddList = ConvertFriendListItem(m_userManager.GetUserFriendList(agentID)); - logResponse.StartLocation = startLocationRequest; - - try - { - CustomiseResponse(logResponse, userProfile, startLocationRequest, remoteClient); - } - catch (Exception ex) - { - m_log.Info("[LOGIN]: LLSD " + ex.ToString()); - return logResponse.CreateDeadRegionResponseLLSD(); - } - - userProfile.LastLogin = userProfile.CurrentAgent.LoginTime; - CommitAgent(ref userProfile); - - // If we reach this point, then the login has successfully logged onto the grid - if (StatsManager.UserStats != null) - StatsManager.UserStats.AddSuccessfulLogin(); - - m_log.DebugFormat( - "[LOGIN END]: LLSD Authentication of user {0} {1} successful. Sending response to client.", - userProfile.FirstName, userProfile.SurName); - - return logResponse.ToLLSDResponse(); - } - catch (Exception ex) - { - m_log.Info("[LOGIN]: LLSD " + ex.ToString()); - return logResponse.CreateFailedResponseLLSD(); - } - } - } - finally - { - m_loginMutex.ReleaseMutex(); - } - } - - public Hashtable ProcessHTMLLogin(Hashtable keysvals) - { - // Matches all unspecified characters - // Currently specified,; lowercase letters, upper case letters, numbers, underline - // period, space, parens, and dash. - - Regex wfcut = new Regex("[^a-zA-Z0-9_\\.\\$ \\(\\)\\-]"); - - Hashtable returnactions = new Hashtable(); - int statuscode = 200; - - string firstname = String.Empty; - string lastname = String.Empty; - string location = String.Empty; - string region = String.Empty; - string grid = String.Empty; - string channel = String.Empty; - string version = String.Empty; - string lang = String.Empty; - string password = String.Empty; - string errormessages = String.Empty; - - // the client requires the HTML form field be named 'username' - // however, the data it sends when it loads the first time is 'firstname' - // another one of those little nuances. - - if (keysvals.Contains("firstname")) - firstname = wfcut.Replace((string)keysvals["firstname"], String.Empty, 99999); - - if (keysvals.Contains("username")) - firstname = wfcut.Replace((string)keysvals["username"], String.Empty, 99999); - - if (keysvals.Contains("lastname")) - lastname = wfcut.Replace((string)keysvals["lastname"], String.Empty, 99999); - - if (keysvals.Contains("location")) - location = wfcut.Replace((string)keysvals["location"], String.Empty, 99999); - - if (keysvals.Contains("region")) - region = wfcut.Replace((string)keysvals["region"], String.Empty, 99999); - - if (keysvals.Contains("grid")) - grid = wfcut.Replace((string)keysvals["grid"], String.Empty, 99999); - - if (keysvals.Contains("channel")) - channel = wfcut.Replace((string)keysvals["channel"], String.Empty, 99999); - - if (keysvals.Contains("version")) - version = wfcut.Replace((string)keysvals["version"], String.Empty, 99999); - - if (keysvals.Contains("lang")) - lang = wfcut.Replace((string)keysvals["lang"], String.Empty, 99999); - - if (keysvals.Contains("password")) - password = wfcut.Replace((string)keysvals["password"], String.Empty, 99999); - - // load our login form. - string loginform = GetLoginForm(firstname, lastname, location, region, grid, channel, version, lang, password, errormessages); - - if (keysvals.ContainsKey("show_login_form")) - { - UserProfileData user = GetTheUser(firstname, lastname); - bool goodweblogin = false; - - if (user != null) - goodweblogin = AuthenticateUser(user, password); - - if (goodweblogin) - { - UUID webloginkey = UUID.Random(); - m_userManager.StoreWebLoginKey(user.ID, webloginkey); - //statuscode = 301; - - // string redirectURL = "about:blank?redirect-http-hack=" + - // HttpUtility.UrlEncode("secondlife:///app/login?first_name=" + firstname + "&last_name=" + - // lastname + - // "&location=" + location + "&grid=Other&web_login_key=" + webloginkey.ToString()); - //m_log.Info("[WEB]: R:" + redirectURL); - returnactions["int_response_code"] = statuscode; - //returnactions["str_redirect_location"] = redirectURL; - //returnactions["str_response_string"] = "GoodLogin"; - returnactions["str_response_string"] = webloginkey.ToString(); - } - else - { - errormessages = "The Username and password supplied did not match our records. Check your caps lock and try again"; - - loginform = GetLoginForm(firstname, lastname, location, region, grid, channel, version, lang, password, errormessages); - returnactions["int_response_code"] = statuscode; - returnactions["str_response_string"] = loginform; - } - } - else - { - returnactions["int_response_code"] = statuscode; - returnactions["str_response_string"] = loginform; - } - return returnactions; - } - - public string GetLoginForm(string firstname, string lastname, string location, string region, - string grid, string channel, string version, string lang, - string password, string errormessages) - { - // inject our values in the form at the markers - - string loginform = String.Empty; - string file = Path.Combine(Util.configDir(), "http_loginform.html"); - if (!File.Exists(file)) - { - loginform = GetDefaultLoginForm(); - } - else - { - StreamReader sr = File.OpenText(file); - loginform = sr.ReadToEnd(); - sr.Close(); - } - - loginform = loginform.Replace("[$firstname]", firstname); - loginform = loginform.Replace("[$lastname]", lastname); - loginform = loginform.Replace("[$location]", location); - loginform = loginform.Replace("[$region]", region); - loginform = loginform.Replace("[$grid]", grid); - loginform = loginform.Replace("[$channel]", channel); - loginform = loginform.Replace("[$version]", version); - loginform = loginform.Replace("[$lang]", lang); - loginform = loginform.Replace("[$password]", password); - loginform = loginform.Replace("[$errors]", errormessages); - - return loginform; - } - - public string GetDefaultLoginForm() - { - string responseString = - ""; - responseString += ""; - responseString += ""; - responseString += ""; - responseString += ""; - responseString += ""; - responseString += "OpenSim Login"; - responseString += "
"; - responseString += "
"; - - responseString += "
"; - - responseString += "
[$errors]
"; - responseString += "
"; - responseString += "First Name:"; - responseString += ""; - responseString += "
"; - responseString += "
"; - responseString += "Last Name:"; - responseString += ""; - responseString += "
"; - responseString += "
"; - responseString += "Password:"; - responseString += ""; - responseString += ""; - responseString += ""; - responseString += ""; - responseString += ""; - responseString += ""; - responseString += ""; - responseString += ""; - responseString += "
"; - responseString += "
"; - responseString += ""; - responseString += ""; - responseString += ""; - responseString += ""; - responseString += ""; - responseString += ""; - responseString += ""; - responseString += ""; - responseString += "
"; - responseString += ""; - responseString += "
"; - responseString += "
Connecting...
"; - - responseString += "
"; - - responseString += "
[$channel] | [$version]=[$lang]
"; - responseString += "
"; - responseString += ""; - responseString += "
"; - responseString += ""; - responseString += ""; - responseString += ""; - - return responseString; - } - - /// - /// Saves a target agent to the database - /// - /// The users profile - /// Successful? - public bool CommitAgent(ref UserProfileData profile) - { - return m_userManager.CommitAgent(ref profile); - } - - /// - /// Checks a user against it's password hash - /// - /// The users profile - /// The supplied password - /// Authenticated? - public virtual bool AuthenticateUser(UserProfileData profile, string password) - { - bool passwordSuccess = false; - //m_log.InfoFormat("[LOGIN]: Authenticating {0} {1} ({2})", profile.FirstName, profile.SurName, profile.ID); - - // Web Login method seems to also occasionally send the hashed password itself - - // we do this to get our hash in a form that the server password code can consume - // when the web-login-form submits the password in the clear (supposed to be over SSL!) - if (!password.StartsWith("$1$")) - password = "$1$" + Util.Md5Hash(password); - - password = password.Remove(0, 3); //remove $1$ - - string s = Util.Md5Hash(password + ":" + profile.PasswordSalt); - // Testing... - //m_log.Info("[LOGIN]: SubHash:" + s + " userprofile:" + profile.passwordHash); - //m_log.Info("[LOGIN]: userprofile:" + profile.passwordHash + " SubCT:" + password); - - passwordSuccess = (profile.PasswordHash.Equals(s.ToString(), StringComparison.InvariantCultureIgnoreCase) - || profile.PasswordHash.Equals(password, StringComparison.InvariantCulture)); - - return passwordSuccess; - } - - public virtual bool AuthenticateUser(UserProfileData profile, UUID webloginkey) - { - bool passwordSuccess = false; - m_log.InfoFormat("[LOGIN]: Authenticating {0} {1} ({2})", profile.FirstName, profile.SurName, profile.ID); - - // Match web login key unless it's the default weblogin key UUID.Zero - passwordSuccess = ((profile.WebLoginKey == webloginkey) && profile.WebLoginKey != UUID.Zero); - - return passwordSuccess; - } - - /// - /// - /// - /// - /// - public void CreateAgent(UserProfileData profile, XmlRpcRequest request) - { - m_userManager.CreateAgent(profile, request); - } - - public void CreateAgent(UserProfileData profile, OSD request) - { - m_userManager.CreateAgent(profile, request); - } - - /// - /// - /// - /// - /// - /// - public virtual UserProfileData GetTheUser(string firstname, string lastname) - { - return m_userManager.GetUserProfile(firstname, lastname); - } - - /// - /// - /// - /// - public virtual string GetMessage() - { - return m_welcomeMessage; - } - - private static LoginResponse.BuddyList ConvertFriendListItem(List LFL) - { - LoginResponse.BuddyList buddylistreturn = new LoginResponse.BuddyList(); - foreach (FriendListItem fl in LFL) - { - LoginResponse.BuddyList.BuddyInfo buddyitem = new LoginResponse.BuddyList.BuddyInfo(fl.Friend); - buddyitem.BuddyID = fl.Friend; - buddyitem.BuddyRightsHave = (int)fl.FriendListOwnerPerms; - buddyitem.BuddyRightsGiven = (int)fl.FriendPerms; - buddylistreturn.AddNewBuddy(buddyitem); - } - return buddylistreturn; - } - - /// - /// Converts the inventory library skeleton into the form required by the rpc request. - /// - /// - protected virtual ArrayList GetInventoryLibrary() - { - Dictionary rootFolders - = m_libraryRootFolder.RequestSelfAndDescendentFolders(); - ArrayList folderHashes = new ArrayList(); - - foreach (InventoryFolderBase folder in rootFolders.Values) - { - Hashtable TempHash = new Hashtable(); - TempHash["name"] = folder.Name; - TempHash["parent_id"] = folder.ParentID.ToString(); - TempHash["version"] = (Int32)folder.Version; - TempHash["type_default"] = (Int32)folder.Type; - TempHash["folder_id"] = folder.ID.ToString(); - folderHashes.Add(TempHash); - } - - return folderHashes; - } - - /// - /// - /// - /// - protected virtual ArrayList GetLibraryOwner() - { - //for now create random inventory library owner - Hashtable TempHash = new Hashtable(); - TempHash["agent_id"] = "11111111-1111-0000-0000-000100bba000"; - ArrayList inventoryLibOwner = new ArrayList(); - inventoryLibOwner.Add(TempHash); - return inventoryLibOwner; - } - - public class InventoryData - { - public ArrayList InventoryArray = null; - public UUID RootFolderID = UUID.Zero; - - public InventoryData(ArrayList invList, UUID rootID) - { - InventoryArray = invList; - RootFolderID = rootID; - } - } - - protected void SniffLoginKey(Uri uri, Hashtable requestData) - { - string uri_str = uri.ToString(); - string[] parts = uri_str.Split(new char[] { '=' }); - if (parts.Length > 1) - { - string web_login_key = parts[1]; - requestData.Add("web_login_key", web_login_key); - m_log.InfoFormat("[LOGIN]: Login with web_login_key {0}", web_login_key); - } - } - - /// - /// Customises the login response and fills in missing values. This method also tells the login region to - /// expect a client connection. - /// - /// The existing response - /// The user profile - /// The requested start location - /// true on success, false if the region was not successfully told to expect a user connection - public bool CustomiseResponse(LoginResponse response, UserProfileData theUser, string startLocationRequest, IPEndPoint client) - { - // add active gestures to login-response - AddActiveGestures(response, theUser); - - // HomeLocation - RegionInfo homeInfo = null; - - // use the homeRegionID if it is stored already. If not, use the regionHandle as before - UUID homeRegionId = theUser.HomeRegionID; - ulong homeRegionHandle = theUser.HomeRegion; - if (homeRegionId != UUID.Zero) - { - homeInfo = GetRegionInfo(homeRegionId); - } - else - { - homeInfo = GetRegionInfo(homeRegionHandle); - } - - if (homeInfo != null) - { - response.Home = - string.Format( - "{{'region_handle':[r{0},r{1}], 'position':[r{2},r{3},r{4}], 'look_at':[r{5},r{6},r{7}]}}", - (homeInfo.RegionLocX * Constants.RegionSize), - (homeInfo.RegionLocY * Constants.RegionSize), - theUser.HomeLocation.X, theUser.HomeLocation.Y, theUser.HomeLocation.Z, - theUser.HomeLookAt.X, theUser.HomeLookAt.Y, theUser.HomeLookAt.Z); - } - else - { - m_log.InfoFormat("not found the region at {0} {1}", theUser.HomeRegionX, theUser.HomeRegionY); - // Emergency mode: Home-region isn't available, so we can't request the region info. - // Use the stored home regionHandle instead. - // NOTE: If the home-region moves, this will be wrong until the users update their user-profile again - ulong regionX = homeRegionHandle >> 32; - ulong regionY = homeRegionHandle & 0xffffffff; - response.Home = - string.Format( - "{{'region_handle':[r{0},r{1}], 'position':[r{2},r{3},r{4}], 'look_at':[r{5},r{6},r{7}]}}", - regionX, regionY, - theUser.HomeLocation.X, theUser.HomeLocation.Y, theUser.HomeLocation.Z, - theUser.HomeLookAt.X, theUser.HomeLookAt.Y, theUser.HomeLookAt.Z); - - m_log.InfoFormat("[LOGIN] Home region of user {0} {1} is not available; using computed region position {2} {3}", - theUser.FirstName, theUser.SurName, - regionX, regionY); - } - - // StartLocation - RegionInfo regionInfo = null; - if (startLocationRequest == "home") - { - regionInfo = homeInfo; - theUser.CurrentAgent.Position = theUser.HomeLocation; - response.LookAt = String.Format("[r{0},r{1},r{2}]", theUser.HomeLookAt.X.ToString(), - theUser.HomeLookAt.Y.ToString(), theUser.HomeLookAt.Z.ToString()); - } - else if (startLocationRequest == "last") - { - UUID lastRegion = theUser.CurrentAgent.Region; - regionInfo = GetRegionInfo(lastRegion); - response.LookAt = String.Format("[r{0},r{1},r{2}]", theUser.CurrentAgent.LookAt.X.ToString(), - theUser.CurrentAgent.LookAt.Y.ToString(), theUser.CurrentAgent.LookAt.Z.ToString()); - } - else - { - Regex reURI = new Regex(@"^uri:(?[^&]+)&(?\d+)&(?\d+)&(?\d+)$"); - Match uriMatch = reURI.Match(startLocationRequest); - if (uriMatch == null) - { - m_log.InfoFormat("[LOGIN]: Got Custom Login URL {0}, but can't process it", startLocationRequest); - } - else - { - string region = uriMatch.Groups["region"].ToString(); - regionInfo = RequestClosestRegion(region); - if (regionInfo == null) - { - m_log.InfoFormat("[LOGIN]: Got Custom Login URL {0}, can't locate region {1}", startLocationRequest, region); - } - else - { - theUser.CurrentAgent.Position = new Vector3(float.Parse(uriMatch.Groups["x"].Value), - float.Parse(uriMatch.Groups["y"].Value), float.Parse(uriMatch.Groups["z"].Value)); - } - } - response.LookAt = "[r0,r1,r0]"; - // can be: last, home, safe, url - response.StartLocation = "url"; - } - - if ((regionInfo != null) && (PrepareLoginToRegion(regionInfo, theUser, response, client))) - { - return true; - } - - // Get the default region handle - ulong defaultHandle = Utils.UIntsToLong(m_defaultHomeX * Constants.RegionSize, m_defaultHomeY * Constants.RegionSize); - - // If we haven't already tried the default region, reset regionInfo - if (regionInfo != null && defaultHandle != regionInfo.RegionHandle) - regionInfo = null; - - if (regionInfo == null) - { - m_log.Error("[LOGIN]: Sending user to default region " + defaultHandle + " instead"); - regionInfo = GetRegionInfo(defaultHandle); - } - - if (regionInfo == null) - { - m_log.ErrorFormat("[LOGIN]: Sending user to any region"); - regionInfo = RequestClosestRegion(String.Empty); - } - - theUser.CurrentAgent.Position = new Vector3(128f, 128f, 0f); - response.StartLocation = "safe"; - - return PrepareLoginToRegion(regionInfo, theUser, response, client); - } - - protected abstract RegionInfo RequestClosestRegion(string region); - protected abstract RegionInfo GetRegionInfo(ulong homeRegionHandle); - protected abstract RegionInfo GetRegionInfo(UUID homeRegionId); - - /// - /// Prepare a login to the given region. This involves both telling the region to expect a connection - /// and appropriately customising the response to the user. - /// - /// - /// - /// - /// - /// true if the region was successfully contacted, false otherwise - protected abstract bool PrepareLoginToRegion( - RegionInfo regionInfo, UserProfileData user, LoginResponse response, IPEndPoint client); - - /// - /// Add active gestures of the user to the login response. - /// - /// - /// A - /// - /// - /// A - /// - protected void AddActiveGestures(LoginResponse response, UserProfileData theUser) - { - List gestures = null; - try - { - if (m_InventoryService != null) - gestures = m_InventoryService.GetActiveGestures(theUser.ID); - else - gestures = m_interInventoryService.GetActiveGestures(theUser.ID); - } - catch (Exception e) - { - m_log.Debug("[LOGIN]: Unable to retrieve active gestures from inventory server. Reason: " + e.Message); - } - //m_log.DebugFormat("[LOGIN]: AddActiveGestures, found {0}", gestures == null ? 0 : gestures.Count); - ArrayList list = new ArrayList(); - if (gestures != null) - { - foreach (InventoryItemBase gesture in gestures) - { - Hashtable item = new Hashtable(); - item["item_id"] = gesture.ID.ToString(); - item["asset_id"] = gesture.AssetID.ToString(); - list.Add(item); - } - } - response.ActiveGestures = list; - } - - /// - /// Get the initial login inventory skeleton (in other words, the folder structure) for the given user. - /// - /// - /// - /// This will be thrown if there is a problem with the inventory service - protected InventoryData GetInventorySkeleton(UUID userID) - { - List folders = null; - if (m_InventoryService != null) - { - folders = m_InventoryService.GetInventorySkeleton(userID); - } - else - { - folders = m_interInventoryService.GetInventorySkeleton(userID); - } - - // If we have user auth but no inventory folders for some reason, create a new set of folders. - if (folders == null || folders.Count == 0) - { - m_log.InfoFormat( - "[LOGIN]: A root inventory folder for user {0} was not found. Requesting creation.", userID); - - // Although the create user function creates a new agent inventory along with a new user profile, some - // tools are creating the user profile directly in the database without creating the inventory. At - // this time we'll accomodate them by lazily creating the user inventory now if it doesn't already - // exist. - if (m_interInventoryService != null) - { - if (!m_interInventoryService.CreateNewUserInventory(userID)) - { - throw new Exception( - String.Format( - "The inventory creation request for user {0} did not succeed." - + " Please contact your inventory service provider for more information.", - userID)); - } - } - else if ((m_InventoryService != null) && !m_InventoryService.CreateUserInventory(userID)) - { - throw new Exception( - String.Format( - "The inventory creation request for user {0} did not succeed." - + " Please contact your inventory service provider for more information.", - userID)); - } - - - m_log.InfoFormat("[LOGIN]: A new inventory skeleton was successfully created for user {0}", userID); - - if (m_InventoryService != null) - folders = m_InventoryService.GetInventorySkeleton(userID); - else - folders = m_interInventoryService.GetInventorySkeleton(userID); - - if (folders == null || folders.Count == 0) - { - throw new Exception( - String.Format( - "A root inventory folder for user {0} could not be retrieved from the inventory service", - userID)); - } - } - - UUID rootID = UUID.Zero; - ArrayList AgentInventoryArray = new ArrayList(); - Hashtable TempHash; - foreach (InventoryFolderBase InvFolder in folders) - { - if (InvFolder.ParentID == UUID.Zero) - { - rootID = InvFolder.ID; - } - TempHash = new Hashtable(); - TempHash["name"] = InvFolder.Name; - TempHash["parent_id"] = InvFolder.ParentID.ToString(); - TempHash["version"] = (Int32)InvFolder.Version; - TempHash["type_default"] = (Int32)InvFolder.Type; - TempHash["folder_id"] = InvFolder.ID.ToString(); - AgentInventoryArray.Add(TempHash); - } - - return new InventoryData(AgentInventoryArray, rootID); - } - - protected virtual bool AllowLoginWithoutInventory() - { - return false; - } - - public XmlRpcResponse XmlRPCCheckAuthSession(XmlRpcRequest request, IPEndPoint remoteClient) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable)request.Params[0]; - - string authed = "FALSE"; - if (requestData.Contains("avatar_uuid") && requestData.Contains("session_id")) - { - UUID guess_aid; - UUID guess_sid; - - UUID.TryParse((string)requestData["avatar_uuid"], out guess_aid); - if (guess_aid == UUID.Zero) - { - return Util.CreateUnknownUserErrorResponse(); - } - - UUID.TryParse((string)requestData["session_id"], out guess_sid); - if (guess_sid == UUID.Zero) - { - return Util.CreateUnknownUserErrorResponse(); - } - - if (m_userManager.VerifySession(guess_aid, guess_sid)) - { - authed = "TRUE"; - m_log.InfoFormat("[UserManager]: CheckAuthSession TRUE for user {0}", guess_aid); - } - else - { - m_log.InfoFormat("[UserManager]: CheckAuthSession FALSE"); - return Util.CreateUnknownUserErrorResponse(); - } - } - - Hashtable responseData = new Hashtable(); - responseData["auth_session"] = authed; - response.Value = responseData; - return response; - } - } -} \ No newline at end of file -- cgit v1.1