From ea26bd415329fb3f030819c9cbaf210825cf5c34 Mon Sep 17 00:00:00 2001 From: MW Date: Tue, 24 Feb 2009 15:37:03 +0000 Subject: First step in separating out the Userserver console command handling to a "module". Added OpenSim.Grid.UserServer.Modules project/dll which now contains the components of the userserver. With the OpenSim.Grid.UserServer being the setup and initiate exe. --- .../UserServer.Modules/MessageServersConnector.cs | 509 +++++++++++++++ OpenSim/Grid/UserServer.Modules/OpenIdService.cs | 337 ++++++++++ .../Grid/UserServer.Modules/UserDataBaseService.cs | 68 ++ .../Grid/UserServer.Modules/UserLoginService.cs | 600 ++++++++++++++++++ OpenSim/Grid/UserServer.Modules/UserManager.cs | 686 +++++++++++++++++++++ .../UserServerAvatarAppearanceModule.cs | 124 ++++ .../UserServer.Modules/UserServerFriendsModule.cs | 173 ++++++ OpenSim/Grid/UserServer/IUGAIMCore.cs | 43 -- OpenSim/Grid/UserServer/Main.cs | 276 +-------- OpenSim/Grid/UserServer/MessageServersConnector.cs | 509 --------------- OpenSim/Grid/UserServer/OpenIdService.cs | 337 ---------- OpenSim/Grid/UserServer/UserDataBaseService.cs | 68 -- OpenSim/Grid/UserServer/UserLoginService.cs | 600 ------------------ OpenSim/Grid/UserServer/UserManager.cs | 686 --------------------- .../UserServer/UserServerAvatarAppearanceModule.cs | 124 ---- OpenSim/Grid/UserServer/UserServerCommandModule.cs | 349 +++++++++++ OpenSim/Grid/UserServer/UserServerFriendsModule.cs | 173 ------ 17 files changed, 2857 insertions(+), 2805 deletions(-) create mode 100644 OpenSim/Grid/UserServer.Modules/MessageServersConnector.cs create mode 100644 OpenSim/Grid/UserServer.Modules/OpenIdService.cs create mode 100644 OpenSim/Grid/UserServer.Modules/UserDataBaseService.cs create mode 100644 OpenSim/Grid/UserServer.Modules/UserLoginService.cs create mode 100644 OpenSim/Grid/UserServer.Modules/UserManager.cs create mode 100644 OpenSim/Grid/UserServer.Modules/UserServerAvatarAppearanceModule.cs create mode 100644 OpenSim/Grid/UserServer.Modules/UserServerFriendsModule.cs delete mode 100644 OpenSim/Grid/UserServer/IUGAIMCore.cs delete mode 100644 OpenSim/Grid/UserServer/MessageServersConnector.cs delete mode 100644 OpenSim/Grid/UserServer/OpenIdService.cs delete mode 100644 OpenSim/Grid/UserServer/UserDataBaseService.cs delete mode 100644 OpenSim/Grid/UserServer/UserLoginService.cs delete mode 100644 OpenSim/Grid/UserServer/UserManager.cs delete mode 100644 OpenSim/Grid/UserServer/UserServerAvatarAppearanceModule.cs create mode 100644 OpenSim/Grid/UserServer/UserServerCommandModule.cs delete mode 100644 OpenSim/Grid/UserServer/UserServerFriendsModule.cs (limited to 'OpenSim/Grid') diff --git a/OpenSim/Grid/UserServer.Modules/MessageServersConnector.cs b/OpenSim/Grid/UserServer.Modules/MessageServersConnector.cs new file mode 100644 index 0000000..b98c614 --- /dev/null +++ b/OpenSim/Grid/UserServer.Modules/MessageServersConnector.cs @@ -0,0 +1,509 @@ +/* + * 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 OpenSim 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.Collections; +using System.Collections.Generic; +using System.Net; +using System.Reflection; +using System.Threading; +using log4net; +using Nwc.XmlRpc; +using OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Framework.Servers; + +namespace OpenSim.Grid.UserServer.Modules +{ + public enum NotificationRequest : int + { + Login = 0, + Logout = 1, + Shutdown = 2 + } + + public struct PresenceNotification + { + public NotificationRequest request; + public UUID agentID; + public UUID sessionID; + public UUID RegionID; + public ulong regionhandle; + public float positionX; + public float positionY; + public float positionZ; + public string firstname; + public string lastname; + } + + public delegate void AgentLocationDelegate(UUID agentID, UUID regionID, ulong regionHandle); + public delegate void AgentLeavingDelegate(UUID agentID, UUID regionID, ulong regionHandle); + public delegate void RegionStartupDelegate(UUID regionID); + public delegate void RegionShutdownDelegate(UUID regionID); + + + public class MessageServersConnector + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + public Dictionary MessageServers; + + private BaseHttpServer m_httpServer; + + private BlockingQueue m_NotifyQueue = + new BlockingQueue(); + + Thread m_NotifyThread; + + public event AgentLocationDelegate OnAgentLocation; + public event AgentLeavingDelegate OnAgentLeaving; + public event RegionStartupDelegate OnRegionStartup; + public event RegionShutdownDelegate OnRegionShutdown; + + public MessageServersConnector() + { + MessageServers = new Dictionary(); + m_NotifyThread = new Thread(new ThreadStart(NotifyQueueRunner)); + m_NotifyThread.Start(); + } + + public void Initialise() + { + + } + + public void PostInitialise() + { + + } + + public void RegisterHandlers(BaseHttpServer httpServer) + { + m_httpServer = httpServer; + + m_httpServer.AddXmlRPCHandler("region_startup", RegionStartup); + m_httpServer.AddXmlRPCHandler("region_shutdown", RegionShutdown); + m_httpServer.AddXmlRPCHandler("agent_location", AgentLocation); + m_httpServer.AddXmlRPCHandler("agent_leaving", AgentLeaving); + // Message Server ---> User Server + m_httpServer.AddXmlRPCHandler("register_messageserver", XmlRPCRegisterMessageServer); + m_httpServer.AddXmlRPCHandler("agent_change_region", XmlRPCUserMovedtoRegion); + m_httpServer.AddXmlRPCHandler("deregister_messageserver", XmlRPCDeRegisterMessageServer); + } + + public void RegisterMessageServer(string URI, MessageServerInfo serverData) + { + lock (MessageServers) + { + if (!MessageServers.ContainsKey(URI)) + MessageServers.Add(URI, serverData); + } + } + + public void DeRegisterMessageServer(string URI) + { + lock (MessageServers) + { + if (MessageServers.ContainsKey(URI)) + MessageServers.Remove(URI); + } + } + + public void AddResponsibleRegion(string URI, ulong regionhandle) + { + if (!MessageServers.ContainsKey(URI)) + { + m_log.Warn("[MSGSERVER]: Got addResponsibleRegion Request for a MessageServer that isn't registered"); + } + else + { + MessageServerInfo msginfo = MessageServers["URI"]; + msginfo.responsibleForRegions.Add(regionhandle); + MessageServers["URI"] = msginfo; + } + } + public void RemoveResponsibleRegion(string URI, ulong regionhandle) + { + if (!MessageServers.ContainsKey(URI)) + { + m_log.Warn("[MSGSERVER]: Got RemoveResponsibleRegion Request for a MessageServer that isn't registered"); + } + else + { + MessageServerInfo msginfo = MessageServers["URI"]; + if (msginfo.responsibleForRegions.Contains(regionhandle)) + { + msginfo.responsibleForRegions.Remove(regionhandle); + MessageServers["URI"] = msginfo; + } + } + + } + public XmlRpcResponse XmlRPCRegisterMessageServer(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable responseData = new Hashtable(); + + if (requestData.Contains("uri")) + { + string URI = (string)requestData["uri"]; + string sendkey=(string)requestData["sendkey"]; + string recvkey=(string)requestData["recvkey"]; + MessageServerInfo m = new MessageServerInfo(); + m.URI = URI; + m.sendkey = sendkey; + m.recvkey = recvkey; + RegisterMessageServer(URI, m); + responseData["responsestring"] = "TRUE"; + response.Value = responseData; + } + return response; + } + public XmlRpcResponse XmlRPCDeRegisterMessageServer(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable responseData = new Hashtable(); + + if (requestData.Contains("uri")) + { + string URI = (string)requestData["uri"]; + + DeRegisterMessageServer(URI); + responseData["responsestring"] = "TRUE"; + response.Value = responseData; + } + return response; + } + public XmlRpcResponse XmlRPCUserMovedtoRegion(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable responseData = new Hashtable(); + + if (requestData.Contains("fromuri")) + { + // string sURI = (string)requestData["fromuri"]; + // string sagentID = (string)requestData["agentid"]; + // string ssessionID = (string)requestData["sessionid"]; + // string scurrentRegionID = (string)requestData["regionid"]; + // string sregionhandle = (string)requestData["regionhandle"]; + // string scurrentpos = (string)requestData["currentpos"]; + //Vector3.TryParse((string)reader["currentPos"], out retval.currentPos); + // TODO: Okay now raise event so the user server can pass this data to the Usermanager + + responseData["responsestring"] = "TRUE"; + response.Value = responseData; + } + return response; + } + + public void TellMessageServersAboutUser(UUID agentID, UUID sessionID, UUID RegionID, + ulong regionhandle, float positionX, float positionY, + float positionZ, string firstname, string lastname) + { + PresenceNotification notification = new PresenceNotification(); + + notification.request = NotificationRequest.Login; + notification.agentID = agentID; + notification.sessionID = sessionID; + notification.RegionID = RegionID; + notification.regionhandle = regionhandle; + notification.positionX = positionX; + notification.positionY = positionY; + notification.positionZ = positionZ; + notification.firstname = firstname; + notification.lastname = lastname; + + m_NotifyQueue.Enqueue(notification); + } + + private void TellMessageServersAboutUserInternal(UUID agentID, UUID sessionID, UUID RegionID, + ulong regionhandle, float positionX, float positionY, + float positionZ, string firstname, string lastname) + { + // Loop over registered Message Servers (AND THERE WILL BE MORE THEN ONE :D) + lock (MessageServers) + { + if (MessageServers.Count > 0) + { + m_log.Info("[MSGCONNECTOR]: Sending login notice to registered message servers"); + } +// else +// { +// m_log.Debug("[MSGCONNECTOR]: No Message Servers registered, ignoring"); +// } + foreach (MessageServerInfo serv in MessageServers.Values) + { + NotifyMessageServerAboutUser(serv, agentID, sessionID, RegionID, + regionhandle, positionX, positionY, positionZ, + firstname, lastname); + } + } + } + + private void TellMessageServersAboutUserLogoffInternal(UUID agentID) + { + lock (MessageServers) + { + if (MessageServers.Count > 0) + { + m_log.Info("[MSGCONNECTOR]: Sending logoff notice to registered message servers"); + } + else + { +// m_log.Debug("[MSGCONNECTOR]: No Message Servers registered, ignoring"); + } + foreach (MessageServerInfo serv in MessageServers.Values) + { + NotifyMessageServerAboutUserLogoff(serv,agentID); + } + } + } + + private void TellMessageServersAboutRegionShutdownInternal(UUID regionID) + { + lock (MessageServers) + { + if (MessageServers.Count > 0) + { + m_log.Info("[MSGCONNECTOR]: Sending region down notice to registered message servers"); + } + else + { +// m_log.Debug("[MSGCONNECTOR]: No Message Servers registered, ignoring"); + } + foreach (MessageServerInfo serv in MessageServers.Values) + { + NotifyMessageServerAboutRegionShutdown(serv,regionID); + } + } + } + + public void TellMessageServersAboutUserLogoff(UUID agentID) + { + PresenceNotification notification = new PresenceNotification(); + + notification.request = NotificationRequest.Logout; + notification.agentID = agentID; + + m_NotifyQueue.Enqueue(notification); + } + + public void TellMessageServersAboutRegionShutdown(UUID regionID) + { + PresenceNotification notification = new PresenceNotification(); + + notification.request = NotificationRequest.Shutdown; + notification.RegionID = regionID; + + m_NotifyQueue.Enqueue(notification); + } + + private void NotifyMessageServerAboutUserLogoff(MessageServerInfo serv, UUID agentID) + { + Hashtable reqparams = new Hashtable(); + reqparams["sendkey"] = serv.sendkey; + reqparams["agentid"] = agentID.ToString(); + ArrayList SendParams = new ArrayList(); + SendParams.Add(reqparams); + + XmlRpcRequest GridReq = new XmlRpcRequest("logout_of_simulator", SendParams); + try + { + GridReq.Send(serv.URI, 6000); + } + catch (WebException) + { + m_log.Warn("[MSGCONNECTOR]: Unable to notify Message Server about log out. Other users might still think this user is online"); + } + m_log.Info("[LOGOUT]: Notified : " + serv.URI + " about user logout"); + } + + private void NotifyMessageServerAboutRegionShutdown(MessageServerInfo serv, UUID regionID) + { + Hashtable reqparams = new Hashtable(); + reqparams["sendkey"] = serv.sendkey; + reqparams["regionid"] = regionID.ToString(); + ArrayList SendParams = new ArrayList(); + SendParams.Add(reqparams); + + XmlRpcRequest GridReq = new XmlRpcRequest("process_region_shutdown", SendParams); + try + { + GridReq.Send(serv.URI, 6000); + } + catch (WebException) + { + m_log.Warn("[MSGCONNECTOR]: Unable to notify Message Server about region shutdown."); + } + m_log.Info("[REGION UPDOWN]: Notified : " + serv.URI + " about region state change"); + } + + private void NotifyMessageServerAboutUser(MessageServerInfo serv, + UUID agentID, UUID sessionID, UUID RegionID, + ulong regionhandle, float positionX, float positionY, float positionZ, + string firstname, string lastname) + { + Hashtable reqparams = new Hashtable(); + reqparams["sendkey"] = serv.sendkey; + reqparams["agentid"] = agentID.ToString(); + reqparams["sessionid"] = sessionID.ToString(); + reqparams["regionid"] = RegionID.ToString(); + reqparams["regionhandle"] = regionhandle.ToString(); + reqparams["positionx"] = positionX.ToString(); + reqparams["positiony"] = positionY.ToString(); + reqparams["positionz"] = positionZ.ToString(); + reqparams["firstname"] = firstname; + reqparams["lastname"] = lastname; + + //reqparams["position"] = Position.ToString(); + + ArrayList SendParams = new ArrayList(); + SendParams.Add(reqparams); + + XmlRpcRequest GridReq = new XmlRpcRequest("login_to_simulator", SendParams); + try + { + GridReq.Send(serv.URI, 6000); + m_log.Info("[LOGIN]: Notified : " + serv.URI + " about user login"); + } + catch (WebException) + { + m_log.Warn("[MSGCONNECTOR]: Unable to notify Message Server about login. Presence might be borked for this user"); + } + + } + + private void NotifyQueueRunner() + { + while (true) + { + PresenceNotification presence = m_NotifyQueue.Dequeue(); + + if (presence.request == NotificationRequest.Shutdown) + { + TellMessageServersAboutRegionShutdownInternal(presence.RegionID); + } + + if (presence.request == NotificationRequest.Login) + { + TellMessageServersAboutUserInternal(presence.agentID, + presence.sessionID, presence.RegionID, + presence.regionhandle, presence.positionX, + presence.positionY, presence.positionZ, + presence.firstname, presence.lastname); + } + + if (presence.request == NotificationRequest.Logout) + { + TellMessageServersAboutUserLogoffInternal(presence.agentID); + } + } + } + + public XmlRpcResponse RegionStartup(XmlRpcRequest request) + { + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable result = new Hashtable(); + + UUID regionID; + if (UUID.TryParse((string)requestData["RegionUUID"], out regionID)) + { + if (OnRegionStartup != null) + OnRegionStartup(regionID); + + result["responsestring"] = "TRUE"; + } + + XmlRpcResponse response = new XmlRpcResponse(); + response.Value = result; + return response; + } + + public XmlRpcResponse RegionShutdown(XmlRpcRequest request) + { + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable result = new Hashtable(); + + UUID regionID; + if (UUID.TryParse((string)requestData["RegionUUID"], out regionID)) + { + if (OnRegionShutdown != null) + OnRegionShutdown(regionID); + + result["responsestring"] = "TRUE"; + } + + XmlRpcResponse response = new XmlRpcResponse(); + response.Value = result; + return response; + } + + public XmlRpcResponse AgentLocation(XmlRpcRequest request) + { + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable result = new Hashtable(); + + UUID agentID; + UUID regionID; + ulong regionHandle; + if (UUID.TryParse((string)requestData["AgentID"], out agentID) && UUID.TryParse((string)requestData["RegionUUID"], out regionID) && ulong.TryParse((string)requestData["RegionHandle"], out regionHandle)) + { + if (OnAgentLocation != null) + OnAgentLocation(agentID, regionID, regionHandle); + + result["responsestring"] = "TRUE"; + } + + XmlRpcResponse response = new XmlRpcResponse(); + response.Value = result; + return response; + } + + public XmlRpcResponse AgentLeaving(XmlRpcRequest request) + { + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable result = new Hashtable(); + + UUID agentID; + UUID regionID; + ulong regionHandle; + if (UUID.TryParse((string)requestData["AgentID"], out agentID) && UUID.TryParse((string)requestData["RegionUUID"], out regionID) && ulong.TryParse((string)requestData["RegionHandle"], out regionHandle)) + { + if (OnAgentLeaving != null) + OnAgentLeaving(agentID, regionID, regionHandle); + + result["responsestring"] = "TRUE"; + } + + XmlRpcResponse response = new XmlRpcResponse(); + response.Value = result; + return response; + } + } +} diff --git a/OpenSim/Grid/UserServer.Modules/OpenIdService.cs b/OpenSim/Grid/UserServer.Modules/OpenIdService.cs new file mode 100644 index 0000000..5c8501f --- /dev/null +++ b/OpenSim/Grid/UserServer.Modules/OpenIdService.cs @@ -0,0 +1,337 @@ +/* + * 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 OpenSim 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.Collections.Specialized; +using System.IO; +using System.Net; +using System.Web; +using DotNetOpenId; +using DotNetOpenId.Provider; +using OpenSim.Framework; +using OpenSim.Framework.Servers; + +namespace OpenSim.Grid.UserServer.Modules +{ + /// + /// Temporary, in-memory store for OpenID associations + /// + public class ProviderMemoryStore : IAssociationStore + { + private class AssociationItem + { + public AssociationRelyingPartyType DistinguishingFactor; + public string Handle; + public DateTime Expires; + public byte[] PrivateData; + } + + Dictionary m_store = new Dictionary(); + SortedList m_sortedStore = new SortedList(); + object m_syncRoot = new object(); + + #region IAssociationStore Members + + public void StoreAssociation(AssociationRelyingPartyType distinguishingFactor, Association assoc) + { + AssociationItem item = new AssociationItem(); + item.DistinguishingFactor = distinguishingFactor; + item.Handle = assoc.Handle; + item.Expires = assoc.Expires.ToLocalTime(); + item.PrivateData = assoc.SerializePrivateData(); + + lock (m_syncRoot) + { + m_store[item.Handle] = item; + m_sortedStore[item.Expires] = item; + } + } + + public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor) + { + lock (m_syncRoot) + { + if (m_sortedStore.Count > 0) + { + AssociationItem item = m_sortedStore.Values[m_sortedStore.Count - 1]; + return Association.Deserialize(item.Handle, item.Expires.ToUniversalTime(), item.PrivateData); + } + else + { + return null; + } + } + } + + public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor, string handle) + { + AssociationItem item; + bool success = false; + lock (m_syncRoot) + success = m_store.TryGetValue(handle, out item); + + if (success) + return Association.Deserialize(item.Handle, item.Expires.ToUniversalTime(), item.PrivateData); + else + return null; + } + + public bool RemoveAssociation(AssociationRelyingPartyType distinguishingFactor, string handle) + { + lock (m_syncRoot) + { + for (int i = 0; i < m_sortedStore.Values.Count; i++) + { + AssociationItem item = m_sortedStore.Values[i]; + if (item.Handle == handle) + { + m_sortedStore.RemoveAt(i); + break; + } + } + + return m_store.Remove(handle); + } + } + + public void ClearExpiredAssociations() + { + lock (m_syncRoot) + { + List itemsCopy = new List(m_sortedStore.Values); + DateTime now = DateTime.Now; + + for (int i = 0; i < itemsCopy.Count; i++) + { + AssociationItem item = itemsCopy[i]; + + if (item.Expires <= now) + { + m_sortedStore.RemoveAt(i); + m_store.Remove(item.Handle); + } + } + } + } + + #endregion + } + + public class OpenIdStreamHandler : IStreamHandler + { + #region HTML + + /// Login form used to authenticate OpenID requests + const string LOGIN_PAGE = +@" +OpenSim OpenID Login + +

OpenSim Login

+
+ + + + +
+ +"; + + /// Page shown for a valid OpenID identity + const string OPENID_PAGE = +@" + +{2} {3} + + +OpenID identifier for {2} {3} + +"; + + /// Page shown for an invalid OpenID identity + const string INVALID_OPENID_PAGE = +@"Identity not found +Invalid OpenID identity"; + + /// Page shown if the OpenID endpoint is requested directly + const string ENDPOINT_PAGE = +@"OpenID Endpoint +This is an OpenID server endpoint, not a human-readable resource. +For more information, see http://openid.net/. +"; + + #endregion HTML + + public string ContentType { get { return m_contentType; } } + public string HttpMethod { get { return m_httpMethod; } } + public string Path { get { return m_path; } } + + string m_contentType; + string m_httpMethod; + string m_path; + UserLoginService m_loginService; + ProviderMemoryStore m_openidStore = new ProviderMemoryStore(); + + /// + /// Constructor + /// + public OpenIdStreamHandler(string httpMethod, string path, UserLoginService loginService) + { + m_loginService = loginService; + m_httpMethod = httpMethod; + m_path = path; + + m_contentType = "text/html"; + } + + /// + /// Handles all GET and POST requests for OpenID identifier pages and endpoint + /// server communication + /// + public void Handle(string path, Stream request, Stream response, OSHttpRequest httpRequest, OSHttpResponse httpResponse) + { + Uri providerEndpoint = new Uri(String.Format("{0}://{1}{2}", httpRequest.Url.Scheme, httpRequest.Url.Authority, httpRequest.Url.AbsolutePath)); + + // Defult to returning HTML content + m_contentType = "text/html"; + + try + { + NameValueCollection postQuery = HttpUtility.ParseQueryString(new StreamReader(httpRequest.InputStream).ReadToEnd()); + NameValueCollection getQuery = HttpUtility.ParseQueryString(httpRequest.Url.Query); + NameValueCollection openIdQuery = (postQuery.GetValues("openid.mode") != null ? postQuery : getQuery); + + OpenIdProvider provider = new OpenIdProvider(m_openidStore, providerEndpoint, httpRequest.Url, openIdQuery); + + if (provider.Request != null) + { + if (!provider.Request.IsResponseReady && provider.Request is IAuthenticationRequest) + { + IAuthenticationRequest authRequest = (IAuthenticationRequest)provider.Request; + string[] passwordValues = postQuery.GetValues("pass"); + + UserProfileData profile; + if (TryGetProfile(new Uri(authRequest.ClaimedIdentifier.ToString()), out profile)) + { + // Check for form POST data + if (passwordValues != null && passwordValues.Length == 1) + { + if (profile != null && m_loginService.AuthenticateUser(profile, passwordValues[0])) + authRequest.IsAuthenticated = true; + else + authRequest.IsAuthenticated = false; + } + else + { + // Authentication was requested, send the client a login form + using (StreamWriter writer = new StreamWriter(response)) + writer.Write(String.Format(LOGIN_PAGE, profile.FirstName, profile.SurName)); + return; + } + } + else + { + // Cannot find an avatar matching the claimed identifier + authRequest.IsAuthenticated = false; + } + } + + // Add OpenID headers to the response + foreach (string key in provider.Request.Response.Headers.Keys) + httpResponse.AddHeader(key, provider.Request.Response.Headers[key]); + + string[] contentTypeValues = provider.Request.Response.Headers.GetValues("Content-Type"); + if (contentTypeValues != null && contentTypeValues.Length == 1) + m_contentType = contentTypeValues[0]; + + // Set the response code and document body based on the OpenID result + httpResponse.StatusCode = (int)provider.Request.Response.Code; + response.Write(provider.Request.Response.Body, 0, provider.Request.Response.Body.Length); + response.Close(); + } + else if (httpRequest.Url.AbsolutePath.Contains("/openid/server")) + { + // Standard HTTP GET was made on the OpenID endpoint, send the client the default error page + using (StreamWriter writer = new StreamWriter(response)) + writer.Write(ENDPOINT_PAGE); + } + else + { + // Try and lookup this avatar + UserProfileData profile; + if (TryGetProfile(httpRequest.Url, out profile)) + { + using (StreamWriter writer = new StreamWriter(response)) + { + // TODO: Print out a full profile page for this avatar + writer.Write(String.Format(OPENID_PAGE, httpRequest.Url.Scheme, + httpRequest.Url.Authority, profile.FirstName, profile.SurName)); + } + } + else + { + // Couldn't parse an avatar name, or couldn't find the avatar in the user server + using (StreamWriter writer = new StreamWriter(response)) + writer.Write(INVALID_OPENID_PAGE); + } + } + } + catch (Exception ex) + { + httpResponse.StatusCode = (int)HttpStatusCode.InternalServerError; + using (StreamWriter writer = new StreamWriter(response)) + writer.Write(ex.Message); + } + } + + /// + /// Parse a URL with a relative path of the form /users/First_Last and try to + /// retrieve the profile matching that avatar name + /// + /// URL to parse for an avatar name + /// Profile data for the avatar + /// True if the parse and lookup were successful, otherwise false + bool TryGetProfile(Uri requestUrl, out UserProfileData profile) + { + if (requestUrl.Segments.Length == 3 && requestUrl.Segments[1] == "users/") + { + // Parse the avatar name from the path + string username = requestUrl.Segments[requestUrl.Segments.Length - 1]; + string[] name = username.Split('_'); + + if (name.Length == 2) + { + profile = m_loginService.GetTheUser(name[0], name[1]); + return (profile != null); + } + } + + profile = null; + return false; + } + } +} diff --git a/OpenSim/Grid/UserServer.Modules/UserDataBaseService.cs b/OpenSim/Grid/UserServer.Modules/UserDataBaseService.cs new file mode 100644 index 0000000..1fcc623 --- /dev/null +++ b/OpenSim/Grid/UserServer.Modules/UserDataBaseService.cs @@ -0,0 +1,68 @@ +/* + * 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 OpenSim 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 OpenSim.Framework; +using OpenSim.Framework.Communications; +using OpenSim.Framework.Servers; + +namespace OpenSim.Grid.UserServer.Modules +{ + public class UserDataBaseService : UserManagerBase + { + public UserDataBaseService() + : base(null) + { + } + + public UserDataBaseService(IInterServiceInventoryServices interServiceInventoryService) + : base(interServiceInventoryService) + { + } + + public override UserProfileData SetupMasterUser(string firstName, string lastName) + { + throw new Exception("The method or operation is not implemented."); + } + + public override UserProfileData SetupMasterUser(string firstName, string lastName, string password) + { + throw new Exception("The method or operation is not implemented."); + } + + public override UserProfileData SetupMasterUser(UUID uuid) + { + throw new Exception("The method or operation is not implemented."); + } + } +} diff --git a/OpenSim/Grid/UserServer.Modules/UserLoginService.cs b/OpenSim/Grid/UserServer.Modules/UserLoginService.cs new file mode 100644 index 0000000..928753f --- /dev/null +++ b/OpenSim/Grid/UserServer.Modules/UserLoginService.cs @@ -0,0 +1,600 @@ +/* + * 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 OpenSim 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 System.Text.RegularExpressions; +using log4net; +using Nwc.XmlRpc; +using OpenMetaverse; +using OpenSim.Data; +using OpenSim.Framework; +using OpenSim.Framework.Communications; +using OpenSim.Framework.Communications.Cache; +using OpenSim.Framework.Communications.Capabilities; +using OpenSim.Framework.Servers; + +namespace OpenSim.Grid.UserServer.Modules +{ + public delegate void UserLoggedInAtLocation(UUID agentID, UUID sessionID, UUID RegionID, + ulong regionhandle, float positionX, float positionY, float positionZ, + string firstname, string lastname); + + /// + /// Login service used in grid mode. + /// + public class UserLoginService : LoginService + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + protected IInterServiceInventoryServices m_inventoryService; + + public event UserLoggedInAtLocation OnUserLoggedInAtLocation; + + private UserLoggedInAtLocation handlerUserLoggedInAtLocation; + + public UserConfig m_config; + private readonly IRegionProfileService m_regionProfileService; + + protected BaseHttpServer m_httpServer; + + public UserLoginService( + UserManagerBase userManager, IInterServiceInventoryServices inventoryService, + LibraryRootFolder libraryRootFolder, + UserConfig config, string welcomeMess, IRegionProfileService regionProfileService) + : base(userManager, libraryRootFolder, welcomeMess) + { + m_config = config; + m_inventoryService = inventoryService; + m_regionProfileService = regionProfileService; + } + + public void RegisterHandlers(BaseHttpServer httpServer, bool registerLLSDHandler, bool registerOpenIDHandlers) + { + m_httpServer = httpServer; + + m_httpServer.AddXmlRPCHandler("login_to_simulator", XmlRpcLoginMethod); + m_httpServer.AddHTTPHandler("login", ProcessHTMLLogin); + m_httpServer.AddXmlRPCHandler("set_login_params", XmlRPCSetLoginParams); + + if (registerLLSDHandler) + { + m_httpServer.SetDefaultLLSDHandler(LLSDLoginMethod); + } + + if (registerOpenIDHandlers) + { + // Handler for OpenID avatar identity pages + m_httpServer.AddStreamHandler(new OpenIdStreamHandler("GET", "/users/", this)); + // Handlers for the OpenID endpoint server + m_httpServer.AddStreamHandler(new OpenIdStreamHandler("POST", "/openid/server/", this)); + m_httpServer.AddStreamHandler(new OpenIdStreamHandler("GET", "/openid/server/", this)); + } + } + + public void setloginlevel(int level) + { + m_minLoginLevel = level; + m_log.InfoFormat("[GRID]: Login Level set to {0} ", level); + } + public void setwelcometext(string text) + { + m_welcomeMessage = text; + m_log.InfoFormat("[GRID]: Login text set to {0} ", text); + } + + public override void LogOffUser(UserProfileData theUser, string message) + { + RegionProfileData SimInfo; + try + { + SimInfo = m_regionProfileService.RequestSimProfileData( + theUser.CurrentAgent.Handle, m_config.GridServerURL, + m_config.GridSendKey, m_config.GridRecvKey); + + if (SimInfo == null) + { + m_log.Error("[GRID]: Region user was in isn't currently logged in"); + return; + } + } + catch (Exception) + { + m_log.Error("[GRID]: Unable to look up region to log user off"); + return; + } + + // Prepare notification + Hashtable SimParams = new Hashtable(); + SimParams["agent_id"] = theUser.ID.ToString(); + SimParams["region_secret"] = theUser.CurrentAgent.SecureSessionID.ToString(); + SimParams["region_secret2"] = SimInfo.regionSecret; + //m_log.Info(SimInfo.regionSecret); + SimParams["regionhandle"] = theUser.CurrentAgent.Handle.ToString(); + SimParams["message"] = message; + ArrayList SendParams = new ArrayList(); + SendParams.Add(SimParams); + + m_log.InfoFormat( + "[ASSUMED CRASH]: Telling region {0} @ {1},{2} ({3}) that their agent is dead: {4}", + SimInfo.regionName, SimInfo.regionLocX, SimInfo.regionLocY, SimInfo.httpServerURI, + theUser.FirstName + " " + theUser.SurName); + + try + { + XmlRpcRequest GridReq = new XmlRpcRequest("logoff_user", SendParams); + XmlRpcResponse GridResp = GridReq.Send(SimInfo.httpServerURI, 6000); + + if (GridResp.IsFault) + { + m_log.ErrorFormat( + "[LOGIN]: XMLRPC request for {0} failed, fault code: {1}, reason: {2}, This is likely an old region revision.", + SimInfo.httpServerURI, GridResp.FaultCode, GridResp.FaultString); + } + } + catch (Exception) + { + m_log.Error("[LOGIN]: Error telling region to logout user!"); + } + + // Prepare notification + SimParams = new Hashtable(); + SimParams["agent_id"] = theUser.ID.ToString(); + SimParams["region_secret"] = SimInfo.regionSecret; + //m_log.Info(SimInfo.regionSecret); + SimParams["regionhandle"] = theUser.CurrentAgent.Handle.ToString(); + SimParams["message"] = message; + SendParams = new ArrayList(); + SendParams.Add(SimParams); + + m_log.InfoFormat( + "[ASSUMED CRASH]: Telling region {0} @ {1},{2} ({3}) that their agent is dead: {4}", + SimInfo.regionName, SimInfo.regionLocX, SimInfo.regionLocY, SimInfo.httpServerURI, + theUser.FirstName + " " + theUser.SurName); + + try + { + XmlRpcRequest GridReq = new XmlRpcRequest("logoff_user", SendParams); + XmlRpcResponse GridResp = GridReq.Send(SimInfo.httpServerURI, 6000); + + if (GridResp.IsFault) + { + m_log.ErrorFormat( + "[LOGIN]: XMLRPC request for {0} failed, fault code: {1}, reason: {2}, This is likely an old region revision.", + SimInfo.httpServerURI, GridResp.FaultCode, GridResp.FaultString); + } + } + catch (Exception) + { + m_log.Error("[LOGIN]: Error telling region to logout user!"); + } + //base.LogOffUser(theUser); + } + + /// + /// Customises the login response and fills in missing values. + /// + /// The existing response + /// The user profile + /// The requested start location + public override bool CustomiseResponse(LoginResponse response, UserProfileData theUser, string startLocationRequest) + { + // add active gestures to login-response + AddActiveGestures(response, theUser); + + // HomeLocation + RegionProfileData 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 + { + // 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 + RegionProfileData regionInfo = null; + if (startLocationRequest == "home") + { + regionInfo = homeInfo; + theUser.CurrentAgent.Position = theUser.HomeLocation; + response.LookAt = "[r" + theUser.HomeLookAt.X.ToString() + ",r" + theUser.HomeLookAt.Y.ToString() + ",r" + theUser.HomeLookAt.Z.ToString() + "]"; + } + else if (startLocationRequest == "last") + { + UUID lastRegion = theUser.CurrentAgent.Region; + regionInfo = GetRegionInfo(lastRegion); + response.LookAt = "[r" + theUser.CurrentAgent.LookAt.X.ToString() + ",r" + theUser.CurrentAgent.LookAt.Y.ToString() + ",r" + 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))) + { + return true; + } + + // StartLocation not available, send him to a nearby region instead + //regionInfo = RegionProfileData.RequestSimProfileData("", m_config.GridServerURL, m_config.GridSendKey, m_config.GridRecvKey); + //m_log.InfoFormat("[LOGIN]: StartLocation not available sending to region {0}", regionInfo.regionName); + + // Send him to default region instead + // Load information from the gridserver + ulong defaultHandle = (((ulong) m_config.DefaultX * Constants.RegionSize) << 32) | + ((ulong) m_config.DefaultY * Constants.RegionSize); + + if ((regionInfo != null) && (defaultHandle == regionInfo.regionHandle)) + { + m_log.ErrorFormat("[LOGIN]: Not trying the default region since this is the same as the selected region"); + return false; + } + + m_log.Error("[LOGIN]: Sending user to default region " + defaultHandle + " instead"); + regionInfo = GetRegionInfo(defaultHandle); + + // Customise the response + //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}]}}", + // (SimInfo.regionLocX * Constants.RegionSize), + // (SimInfo.regionLocY*Constants.RegionSize), + // theUser.HomeLocation.X, theUser.HomeLocation.Y, theUser.HomeLocation.Z, + // theUser.HomeLookAt.X, theUser.HomeLookAt.Y, theUser.HomeLookAt.Z); + theUser.CurrentAgent.Position = new Vector3(128,128,0); + response.StartLocation = "safe"; + + return PrepareLoginToRegion(regionInfo, theUser, response); + } + + protected RegionProfileData RequestClosestRegion(string region) + { + return m_regionProfileService.RequestSimProfileData(region, + m_config.GridServerURL, m_config.GridSendKey, m_config.GridRecvKey); + } + + protected RegionProfileData GetRegionInfo(ulong homeRegionHandle) + { + return m_regionProfileService.RequestSimProfileData(homeRegionHandle, + m_config.GridServerURL, m_config.GridSendKey, + m_config.GridRecvKey); + } + + protected RegionProfileData GetRegionInfo(UUID homeRegionId) + { + return m_regionProfileService.RequestSimProfileData(homeRegionId, + m_config.GridServerURL, m_config.GridSendKey, + m_config.GridRecvKey); + } + + /// + /// Add active gestures of the user to the login response. + /// + /// + /// A + /// + /// + /// A + /// + private void AddActiveGestures(LoginResponse response, UserProfileData theUser) + { + List gestures = m_inventoryService.GetActiveGestures(theUser.ID); + //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; + } + + /// + /// 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 + private bool PrepareLoginToRegion(RegionProfileData regionInfo, UserProfileData user, LoginResponse response) + { + try + { + response.SimAddress = Util.GetHostFromURL(regionInfo.serverURI).ToString(); + response.SimPort = uint.Parse(regionInfo.serverURI.Split(new char[] { '/', ':' })[4]); + response.RegionX = regionInfo.regionLocX; + response.RegionY = regionInfo.regionLocY; + + string capsPath = CapsUtil.GetRandomCapsObjectPath(); + + // Take off trailing / so that the caps path isn't //CAPS/someUUID + if (regionInfo.httpServerURI.EndsWith("/")) + regionInfo.httpServerURI = regionInfo.httpServerURI.Substring(0, regionInfo.httpServerURI.Length - 1); + response.SeedCapability = regionInfo.httpServerURI + CapsUtil.GetCapsSeedPath(capsPath); + + // 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.httpServerURI); + + // Update agent with target sim + user.CurrentAgent.Region = regionInfo.UUID; + user.CurrentAgent.Handle = regionInfo.regionHandle; + + // Prepare notification + Hashtable loginParams = new Hashtable(); + loginParams["session_id"] = user.CurrentAgent.SessionID.ToString(); + loginParams["secure_session_id"] = user.CurrentAgent.SecureSessionID.ToString(); + loginParams["firstname"] = user.FirstName; + loginParams["lastname"] = user.SurName; + loginParams["agent_id"] = user.ID.ToString(); + loginParams["circuit_code"] = (Int32) Convert.ToUInt32(response.CircuitCode); + loginParams["startpos_x"] = user.CurrentAgent.Position.X.ToString(); + loginParams["startpos_y"] = user.CurrentAgent.Position.Y.ToString(); + loginParams["startpos_z"] = user.CurrentAgent.Position.Z.ToString(); + loginParams["regionhandle"] = user.CurrentAgent.Handle.ToString(); + loginParams["caps_path"] = capsPath; + + // Get appearance + AvatarAppearance appearance = m_userManager.GetUserAppearance(user.ID); + if (appearance != null) + { + loginParams["appearance"] = appearance.ToHashTable(); + m_log.DebugFormat("[LOGIN]: Found appearance for {0} {1}", user.FirstName, user.SurName); + } + else + { + m_log.DebugFormat("[LOGIN]: Appearance not for {0} {1}. Creating default.", user.FirstName, user.SurName); + appearance = new AvatarAppearance(user.ID); + } + + ArrayList SendParams = new ArrayList(); + SendParams.Add(loginParams); + + // Send + XmlRpcRequest GridReq = new XmlRpcRequest("expect_user", SendParams); + XmlRpcResponse GridResp = GridReq.Send(regionInfo.httpServerURI, 6000); + + if (!GridResp.IsFault) + { + bool responseSuccess = true; + + if (GridResp.Value != null) + { + Hashtable resp = (Hashtable) GridResp.Value; + if (resp.ContainsKey("success")) + { + if ((string) resp["success"] == "FALSE") + { + responseSuccess = false; + } + } + } + if (responseSuccess) + { + handlerUserLoggedInAtLocation = OnUserLoggedInAtLocation; + if (handlerUserLoggedInAtLocation != null) + { + handlerUserLoggedInAtLocation(user.ID, user.CurrentAgent.SessionID, + user.CurrentAgent.Region, + user.CurrentAgent.Handle, + user.CurrentAgent.Position.X, + user.CurrentAgent.Position.Y, + user.CurrentAgent.Position.Z, + user.FirstName, user.SurName); + } + } + else + { + m_log.ErrorFormat("[LOGIN]: Region responded that it is not available to receive clients"); + return false; + } + } + else + { + m_log.ErrorFormat("[LOGIN]: XmlRpc request to region failed with message {0}, code {1} ", GridResp.FaultString, GridResp.FaultCode); + return false; + } + } + catch (Exception e) + { + m_log.ErrorFormat("[LOGIN]: Region not available for login, {0}", e); + return false; + } + + return true; + } + + // See LoginService + protected override InventoryData GetInventorySkeleton(UUID userID) + { + m_log.DebugFormat( + "[LOGIN]: Contacting inventory service at {0} for inventory skeleton of user {1}", + m_config.InventoryUrl, userID); + + List folders = m_inventoryService.GetInventorySkeleton(userID); + + if (null == folders || 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_inventoryService.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)); + } + m_log.InfoFormat("[LOGIN]: A new inventory skeleton was successfully created for user {0}", userID); + + folders = m_inventoryService.GetInventorySkeleton(userID); + } + + if (folders != null && folders.Count > 0) + { + UUID rootID = UUID.Zero; + ArrayList AgentInventoryArray = new ArrayList(); + Hashtable TempHash; + + foreach (InventoryFolderBase InvFolder in folders) + { +// m_log.DebugFormat("[LOGIN]: Received agent inventory folder {0}", InvFolder.name); + + 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); + } + throw new Exception( + String.Format( + "A root inventory folder for user {0} could not be retrieved from the inventory service", + userID)); + } + + public XmlRpcResponse XmlRPCSetLoginParams(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable) request.Params[0]; + UserProfileData userProfile; + Hashtable responseData = new Hashtable(); + + UUID uid; + string pass = requestData["password"].ToString(); + + if (!UUID.TryParse((string) requestData["avatar_uuid"], out uid)) + { + responseData["error"] = "No authorization"; + response.Value = responseData; + return response; + } + + userProfile = m_userManager.GetUserProfile(uid); + + if (userProfile == null || + (!AuthenticateUser(userProfile, pass)) || + userProfile.GodLevel < 200) + { + responseData["error"] = "No authorization"; + response.Value = responseData; + return response; + } + + if (requestData.ContainsKey("login_level")) + { + m_minLoginLevel = Convert.ToInt32(requestData["login_level"]); + } + + if (requestData.ContainsKey("login_motd")) + { + m_welcomeMessage = requestData["login_motd"].ToString(); + } + + response.Value = responseData; + return response; + } + + } +} diff --git a/OpenSim/Grid/UserServer.Modules/UserManager.cs b/OpenSim/Grid/UserServer.Modules/UserManager.cs new file mode 100644 index 0000000..dd9f495 --- /dev/null +++ b/OpenSim/Grid/UserServer.Modules/UserManager.cs @@ -0,0 +1,686 @@ +/* + * 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 OpenSim 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 OpenSim.Framework; +using OpenSim.Framework.Communications; +using OpenSim.Framework.Servers; + +namespace OpenSim.Grid.UserServer.Modules +{ + public delegate void logOffUser(UUID AgentID); + + public class UserManager + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + public event logOffUser OnLogOffUser; + private logOffUser handlerLogOffUser; + + private UserDataBaseService m_userDataBaseService; + private BaseHttpServer m_httpServer; + + /// + /// + /// + /// + public UserManager( UserDataBaseService userDataBaseService) + { + m_userDataBaseService = userDataBaseService; + } + + public void Initialise() + { + + } + + public void PostInitialise() + { + + } + + public void RegisterHandlers(BaseHttpServer httpServer) + { + m_httpServer = httpServer; + + m_httpServer.AddXmlRPCHandler("get_user_by_name", XmlRPCGetUserMethodName); + m_httpServer.AddXmlRPCHandler("get_user_by_uuid", XmlRPCGetUserMethodUUID); + m_httpServer.AddXmlRPCHandler("get_avatar_picker_avatar", XmlRPCGetAvatarPickerAvatar); + + m_httpServer.AddXmlRPCHandler("update_user_current_region", XmlRPCAtRegion); + m_httpServer.AddXmlRPCHandler("logout_of_simulator", XmlRPCLogOffUserMethodUUID); + m_httpServer.AddXmlRPCHandler("get_agent_by_uuid", XmlRPCGetAgentMethodUUID); + m_httpServer.AddXmlRPCHandler("check_auth_session", XmlRPCCheckAuthSession); + + m_httpServer.AddXmlRPCHandler("update_user_profile", XmlRpcResponseXmlRPCUpdateUserProfile); + + m_httpServer.AddStreamHandler(new RestStreamHandler("DELETE", "/usersessions/", RestDeleteUserSessionMethod)); + } + + /// + /// Deletes an active agent session + /// + /// The request + /// The path (eg /bork/narf/test) + /// Parameters sent + /// HTTP request header object + /// HTTP response header object + /// Success "OK" else error + public string RestDeleteUserSessionMethod(string request, string path, string param, + OSHttpRequest httpRequest, OSHttpResponse httpResponse) + { + // TODO! Important! + + return "OK"; + } + + /// + /// Returns an error message that the user could not be found in the database + /// + /// XML string consisting of a error element containing individual error(s) + public XmlRpcResponse CreateUnknownUserErrorResponse() + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable responseData = new Hashtable(); + responseData["error_type"] = "unknown_user"; + responseData["error_desc"] = "The user requested is not in the database"; + + response.Value = responseData; + return response; + } + + public XmlRpcResponse AvatarPickerListtoXmlRPCResponse(UUID queryID, List returnUsers) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable responseData = new Hashtable(); + // Query Result Information + responseData["queryid"] = queryID.ToString(); + responseData["avcount"] = returnUsers.Count.ToString(); + + for (int i = 0; i < returnUsers.Count; i++) + { + responseData["avatarid" + i] = returnUsers[i].AvatarID.ToString(); + responseData["firstname" + i] = returnUsers[i].firstName; + responseData["lastname" + i] = returnUsers[i].lastName; + } + response.Value = responseData; + + return response; + } + + /// + /// Converts a user profile to an XML element which can be returned + /// + /// The user profile + /// A string containing an XML Document of the user profile + public XmlRpcResponse ProfileToXmlRPCResponse(UserProfileData profile) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable responseData = new Hashtable(); + + // Account information + responseData["firstname"] = profile.FirstName; + responseData["lastname"] = profile.SurName; + responseData["uuid"] = profile.ID.ToString(); + // Server Information + responseData["server_inventory"] = profile.UserInventoryURI; + responseData["server_asset"] = profile.UserAssetURI; + // Profile Information + responseData["profile_about"] = profile.AboutText; + responseData["profile_firstlife_about"] = profile.FirstLifeAboutText; + responseData["profile_firstlife_image"] = profile.FirstLifeImage.ToString(); + responseData["profile_can_do"] = profile.CanDoMask.ToString(); + responseData["profile_want_do"] = profile.WantDoMask.ToString(); + responseData["profile_image"] = profile.Image.ToString(); + responseData["profile_created"] = profile.Created.ToString(); + responseData["profile_lastlogin"] = profile.LastLogin.ToString(); + // Home region information + responseData["home_coordinates_x"] = profile.HomeLocation.X.ToString(); + responseData["home_coordinates_y"] = profile.HomeLocation.Y.ToString(); + responseData["home_coordinates_z"] = profile.HomeLocation.Z.ToString(); + + responseData["home_region"] = profile.HomeRegion.ToString(); + responseData["home_region_id"] = profile.HomeRegionID.ToString(); + + responseData["home_look_x"] = profile.HomeLookAt.X.ToString(); + responseData["home_look_y"] = profile.HomeLookAt.Y.ToString(); + responseData["home_look_z"] = profile.HomeLookAt.Z.ToString(); + + responseData["user_flags"] = profile.UserFlags.ToString(); + responseData["god_level"] = profile.GodLevel.ToString(); + responseData["custom_type"] = profile.CustomType; + responseData["partner"] = profile.Partner.ToString(); + response.Value = responseData; + + return response; + } + + #region XMLRPC User Methods + + public XmlRpcResponse XmlRPCGetAvatarPickerAvatar(XmlRpcRequest request) + { + // XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable) request.Params[0]; + List returnAvatar = new List(); + UUID queryID = new UUID(UUID.Zero.ToString()); + + if (requestData.Contains("avquery") && requestData.Contains("queryid")) + { + queryID = new UUID((string) requestData["queryid"]); + returnAvatar = m_userDataBaseService.GenerateAgentPickerRequestResponse(queryID, (string) requestData["avquery"]); + } + + m_log.InfoFormat("[AVATARINFO]: Servicing Avatar Query: " + (string) requestData["avquery"]); + return AvatarPickerListtoXmlRPCResponse(queryID, returnAvatar); + } + + public XmlRpcResponse XmlRPCAtRegion(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable) request.Params[0]; + Hashtable responseData = new Hashtable(); + string returnstring = "FALSE"; + + if (requestData.Contains("avatar_id") && requestData.Contains("region_handle") && + requestData.Contains("region_uuid")) + { + // ulong cregionhandle = 0; + UUID regionUUID; + UUID avatarUUID; + + UUID.TryParse((string) requestData["avatar_id"], out avatarUUID); + UUID.TryParse((string) requestData["region_uuid"], out regionUUID); + + if (avatarUUID != UUID.Zero) + { + UserProfileData userProfile = m_userDataBaseService.GetUserProfile(avatarUUID); + userProfile.CurrentAgent.Region = regionUUID; + userProfile.CurrentAgent.Handle = (ulong) Convert.ToInt64((string) requestData["region_handle"]); + //userProfile.CurrentAgent. + m_userDataBaseService.CommitAgent(ref userProfile); + //setUserProfile(userProfile); + + + returnstring = "TRUE"; + } + } + responseData.Add("returnString", returnstring); + response.Value = responseData; + return response; + } + + public XmlRpcResponse XmlRPCGetUserMethodName(XmlRpcRequest request) + { + // XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable) request.Params[0]; + UserProfileData userProfile; + if (requestData.Contains("avatar_name")) + { + string query = (string) requestData["avatar_name"]; + + // Regex objAlphaNumericPattern = new Regex("[^a-zA-Z0-9]"); + + string[] querysplit = query.Split(' '); + + if (querysplit.Length == 2) + { + userProfile = m_userDataBaseService.GetUserProfile(querysplit[0], querysplit[1]); + if (userProfile == null) + { + return CreateUnknownUserErrorResponse(); + } + } + else + { + return CreateUnknownUserErrorResponse(); + } + } + else + { + return CreateUnknownUserErrorResponse(); + } + + return ProfileToXmlRPCResponse(userProfile); + } + + public XmlRpcResponse XmlRPCGetUserMethodUUID(XmlRpcRequest request) + { + // XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable) request.Params[0]; + UserProfileData userProfile; + //CFK: this clogs the UserServer log and is not necessary at this time. + //CFK: m_log.Debug("METHOD BY UUID CALLED"); + if (requestData.Contains("avatar_uuid")) + { + try + { + UUID guess = new UUID((string) requestData["avatar_uuid"]); + + userProfile = m_userDataBaseService.GetUserProfile(guess); + } + catch (FormatException) + { + return CreateUnknownUserErrorResponse(); + } + + if (userProfile == null) + { + return CreateUnknownUserErrorResponse(); + } + } + else + { + return CreateUnknownUserErrorResponse(); + } + + return ProfileToXmlRPCResponse(userProfile); + } + + public XmlRpcResponse XmlRPCGetAgentMethodUUID(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable) request.Params[0]; + UserProfileData userProfile; + //CFK: this clogs the UserServer log and is not necessary at this time. + //CFK: m_log.Debug("METHOD BY UUID CALLED"); + if (requestData.Contains("avatar_uuid")) + { + UUID guess; + + UUID.TryParse((string) requestData["avatar_uuid"], out guess); + + if (guess == UUID.Zero) + { + return CreateUnknownUserErrorResponse(); + } + + userProfile = m_userDataBaseService.GetUserProfile(guess); + + if (userProfile == null) + { + return CreateUnknownUserErrorResponse(); + } + + // no agent??? + if (userProfile.CurrentAgent == null) + { + return CreateUnknownUserErrorResponse(); + } + Hashtable responseData = new Hashtable(); + + responseData["handle"] = userProfile.CurrentAgent.Handle.ToString(); + responseData["session"] = userProfile.CurrentAgent.SessionID.ToString(); + if (userProfile.CurrentAgent.AgentOnline) + responseData["agent_online"] = "TRUE"; + else + responseData["agent_online"] = "FALSE"; + + response.Value = responseData; + } + else + { + return CreateUnknownUserErrorResponse(); + } + + return response; + } + + public XmlRpcResponse XmlRPCCheckAuthSession(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable) request.Params[0]; + UserProfileData userProfile; + + 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 CreateUnknownUserErrorResponse(); + } + UUID.TryParse((string) requestData["session_id"], out guess_sid); + if (guess_sid == UUID.Zero) + { + return CreateUnknownUserErrorResponse(); + } + userProfile = m_userDataBaseService.GetUserProfile(guess_aid); + if (userProfile != null && userProfile.CurrentAgent != null && + userProfile.CurrentAgent.SessionID == guess_sid) + { + authed = "TRUE"; + } + m_log.InfoFormat("[UserManager]: CheckAuthSession TRUE for user {0}", guess_aid); + } + else + { + m_log.InfoFormat("[UserManager]: CheckAuthSession FALSE"); + return CreateUnknownUserErrorResponse(); + } + Hashtable responseData = new Hashtable(); + responseData["auth_session"] = authed; + response.Value = responseData; + return response; + } + + public XmlRpcResponse XmlRpcResponseXmlRPCUpdateUserProfile(XmlRpcRequest request) + { + m_log.Debug("[UserManager]: Got request to update user profile"); + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable) request.Params[0]; + Hashtable responseData = new Hashtable(); + + if (!requestData.Contains("avatar_uuid")) + { + return CreateUnknownUserErrorResponse(); + } + + UUID UserUUID = new UUID((string) requestData["avatar_uuid"]); + UserProfileData userProfile = m_userDataBaseService.GetUserProfile(UserUUID); + if (null == userProfile) + { + return CreateUnknownUserErrorResponse(); + } + // don't know how yet. + if (requestData.Contains("AllowPublish")) + { + } + if (requestData.Contains("FLImageID")) + { + userProfile.FirstLifeImage = new UUID((string) requestData["FLImageID"]); + } + if (requestData.Contains("ImageID")) + { + userProfile.Image = new UUID((string) requestData["ImageID"]); + } + // dont' know how yet + if (requestData.Contains("MaturePublish")) + { + } + if (requestData.Contains("AboutText")) + { + userProfile.AboutText = (string) requestData["AboutText"]; + } + if (requestData.Contains("FLAboutText")) + { + userProfile.FirstLifeAboutText = (string) requestData["FLAboutText"]; + } + // not in DB yet. + if (requestData.Contains("ProfileURL")) + { + } + if (requestData.Contains("home_region")) + { + try + { + userProfile.HomeRegion = Convert.ToUInt64((string) requestData["home_region"]); + } + catch (ArgumentException) + { + m_log.Error("[PROFILE]:Failed to set home region, Invalid Argument"); + } + catch (FormatException) + { + m_log.Error("[PROFILE]:Failed to set home region, Invalid Format"); + } + catch (OverflowException) + { + m_log.Error("[PROFILE]:Failed to set home region, Value was too large"); + } + } + if (requestData.Contains("home_region_id")) + { + UUID regionID; + UUID.TryParse((string) requestData["home_region_id"], out regionID); + userProfile.HomeRegionID = regionID; + } + if (requestData.Contains("home_pos_x")) + { + try + { + userProfile.HomeLocationX = (float) Convert.ToDecimal((string) requestData["home_pos_x"]); + } + catch (InvalidCastException) + { + m_log.Error("[PROFILE]:Failed to set home postion x"); + } + } + if (requestData.Contains("home_pos_y")) + { + try + { + userProfile.HomeLocationY = (float) Convert.ToDecimal((string) requestData["home_pos_y"]); + } + catch (InvalidCastException) + { + m_log.Error("[PROFILE]:Failed to set home postion y"); + } + } + if (requestData.Contains("home_pos_z")) + { + try + { + userProfile.HomeLocationZ = (float) Convert.ToDecimal((string) requestData["home_pos_z"]); + } + catch (InvalidCastException) + { + m_log.Error("[PROFILE]:Failed to set home postion z"); + } + } + if (requestData.Contains("home_look_x")) + { + try + { + userProfile.HomeLookAtX = (float) Convert.ToDecimal((string) requestData["home_look_x"]); + } + catch (InvalidCastException) + { + m_log.Error("[PROFILE]:Failed to set home lookat x"); + } + } + if (requestData.Contains("home_look_y")) + { + try + { + userProfile.HomeLookAtY = (float) Convert.ToDecimal((string) requestData["home_look_y"]); + } + catch (InvalidCastException) + { + m_log.Error("[PROFILE]:Failed to set home lookat y"); + } + } + if (requestData.Contains("home_look_z")) + { + try + { + userProfile.HomeLookAtZ = (float) Convert.ToDecimal((string) requestData["home_look_z"]); + } + catch (InvalidCastException) + { + m_log.Error("[PROFILE]:Failed to set home lookat z"); + } + } + if (requestData.Contains("user_flags")) + { + try + { + userProfile.UserFlags = Convert.ToInt32((string) requestData["user_flags"]); + } + catch (InvalidCastException) + { + m_log.Error("[PROFILE]:Failed to set user flags"); + } + } + if (requestData.Contains("god_level")) + { + try + { + userProfile.GodLevel = Convert.ToInt32((string) requestData["god_level"]); + } + catch (InvalidCastException) + { + m_log.Error("[PROFILE]:Failed to set god level"); + } + } + if (requestData.Contains("custom_type")) + { + try + { + userProfile.CustomType = (string) requestData["custom_type"]; + } + catch (InvalidCastException) + { + m_log.Error("[PROFILE]:Failed to set custom type"); + } + } + if (requestData.Contains("partner")) + { + try + { + userProfile.Partner = new UUID((string) requestData["partner"]); + } + catch (InvalidCastException) + { + m_log.Error("[PROFILE]:Failed to set partner"); + } + } + else + { + userProfile.Partner = UUID.Zero; + } + + // call plugin! + bool ret = m_userDataBaseService.UpdateUserProfile(userProfile); + responseData["returnString"] = ret.ToString(); + response.Value = responseData; + return response; + } + + public XmlRpcResponse XmlRPCLogOffUserMethodUUID(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable) request.Params[0]; + + if (requestData.Contains("avatar_uuid")) + { + try + { + UUID userUUID = new UUID((string)requestData["avatar_uuid"]); + UUID RegionID = new UUID((string)requestData["region_uuid"]); + ulong regionhandle = (ulong)Convert.ToInt64((string)requestData["region_handle"]); + Vector3 position = new Vector3( + (float)Convert.ToDecimal((string)requestData["region_pos_x"]), + (float)Convert.ToDecimal((string)requestData["region_pos_y"]), + (float)Convert.ToDecimal((string)requestData["region_pos_z"])); + Vector3 lookat = new Vector3( + (float)Convert.ToDecimal((string)requestData["lookat_x"]), + (float)Convert.ToDecimal((string)requestData["lookat_y"]), + (float)Convert.ToDecimal((string)requestData["lookat_z"])); + + handlerLogOffUser = OnLogOffUser; + if (handlerLogOffUser != null) + handlerLogOffUser(userUUID); + + m_userDataBaseService.LogOffUser(userUUID, RegionID, regionhandle, position, lookat); + } + catch (FormatException) + { + m_log.Warn("[LOGOUT]: Error in Logout XMLRPC Params"); + return response; + } + } + else + { + return CreateUnknownUserErrorResponse(); + } + + return response; + } + + #endregion + + + public void HandleAgentLocation(UUID agentID, UUID regionID, ulong regionHandle) + { + UserProfileData userProfile = m_userDataBaseService.GetUserProfile(agentID); + if (userProfile != null) + { + userProfile.CurrentAgent.Region = regionID; + userProfile.CurrentAgent.Handle = regionHandle; + m_userDataBaseService.CommitAgent(ref userProfile); + } + } + + public void HandleAgentLeaving(UUID agentID, UUID regionID, ulong regionHandle) + { + UserProfileData userProfile = m_userDataBaseService.GetUserProfile(agentID); + if (userProfile != null) + { + if (userProfile.CurrentAgent.Region == regionID) + { + UserAgentData userAgent = userProfile.CurrentAgent; + if (userAgent != null && userAgent.AgentOnline) + { + userAgent.AgentOnline = false; + userAgent.LogoutTime = Util.UnixTimeSinceEpoch(); + if (regionID != UUID.Zero) + { + userAgent.Region = regionID; + } + userAgent.Handle = regionHandle; + userProfile.LastLogin = userAgent.LogoutTime; + + m_userDataBaseService.CommitAgent(ref userProfile); + + handlerLogOffUser = OnLogOffUser; + if (handlerLogOffUser != null) + handlerLogOffUser(agentID); + } + } + } + } + + public void HandleRegionStartup(UUID regionID) + { + m_userDataBaseService.LogoutUsers(regionID); + } + + public void HandleRegionShutdown(UUID regionID) + { + m_userDataBaseService.LogoutUsers(regionID); + } + } +} diff --git a/OpenSim/Grid/UserServer.Modules/UserServerAvatarAppearanceModule.cs b/OpenSim/Grid/UserServer.Modules/UserServerAvatarAppearanceModule.cs new file mode 100644 index 0000000..1c8c0c8 --- /dev/null +++ b/OpenSim/Grid/UserServer.Modules/UserServerAvatarAppearanceModule.cs @@ -0,0 +1,124 @@ +/* + * 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 OpenSim 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 OpenSim.Framework; +using OpenSim.Framework.Communications; +using OpenSim.Framework.Servers; + +namespace OpenSim.Grid.UserServer.Modules +{ + public class UserServerAvatarAppearanceModule + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private UserDataBaseService m_userDataBaseService; + private BaseHttpServer m_httpServer; + + public UserServerAvatarAppearanceModule(UserDataBaseService userDataBaseService) + { + m_userDataBaseService = userDataBaseService; + } + + public void Initialise() + { + + } + + public void PostInitialise() + { + + } + + public void RegisterHandlers(BaseHttpServer httpServer) + { + m_httpServer = httpServer; + + m_httpServer.AddXmlRPCHandler("get_avatar_appearance", XmlRPCGetAvatarAppearance); + m_httpServer.AddXmlRPCHandler("update_avatar_appearance", XmlRPCUpdateAvatarAppearance); + } + + public XmlRpcResponse XmlRPCGetAvatarAppearance(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable)request.Params[0]; + AvatarAppearance appearance; + Hashtable responseData; + if (requestData.Contains("owner")) + { + appearance = m_userDataBaseService.GetUserAppearance(new UUID((string)requestData["owner"])); + if (appearance == null) + { + responseData = new Hashtable(); + responseData["error_type"] = "no appearance"; + responseData["error_desc"] = "There was no appearance found for this avatar"; + } + else + { + responseData = appearance.ToHashTable(); + } + } + else + { + responseData = new Hashtable(); + responseData["error_type"] = "unknown_avatar"; + responseData["error_desc"] = "The avatar appearance requested is not in the database"; + } + + response.Value = responseData; + return response; + } + + public XmlRpcResponse XmlRPCUpdateAvatarAppearance(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable responseData; + if (requestData.Contains("owner")) + { + AvatarAppearance appearance = new AvatarAppearance(requestData); + m_userDataBaseService.UpdateUserAppearance(new UUID((string)requestData["owner"]), appearance); + responseData = new Hashtable(); + responseData["returnString"] = "TRUE"; + } + else + { + responseData = new Hashtable(); + responseData["error_type"] = "unknown_avatar"; + responseData["error_desc"] = "The avatar appearance requested is not in the database"; + } + response.Value = responseData; + return response; + } + } +} diff --git a/OpenSim/Grid/UserServer.Modules/UserServerFriendsModule.cs b/OpenSim/Grid/UserServer.Modules/UserServerFriendsModule.cs new file mode 100644 index 0000000..fec2dc0 --- /dev/null +++ b/OpenSim/Grid/UserServer.Modules/UserServerFriendsModule.cs @@ -0,0 +1,173 @@ +/* + * 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 OpenSim 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 OpenSim.Framework; +using OpenSim.Framework.Communications; +using OpenSim.Framework.Servers; + +namespace OpenSim.Grid.UserServer.Modules +{ + public class UserServerFriendsModule + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private UserDataBaseService m_userDataBaseService; + + private BaseHttpServer m_httpServer; + + public UserServerFriendsModule(UserDataBaseService userDataBaseService) + { + m_userDataBaseService = userDataBaseService; + } + + public void Initialise() + { + + } + + public void PostInitialise() + { + + } + + public void RegisterHandlers(BaseHttpServer httpServer) + { + m_httpServer = httpServer; + + m_httpServer.AddXmlRPCHandler("add_new_user_friend", XmlRpcResponseXmlRPCAddUserFriend); + m_httpServer.AddXmlRPCHandler("remove_user_friend", XmlRpcResponseXmlRPCRemoveUserFriend); + m_httpServer.AddXmlRPCHandler("update_user_friend_perms", XmlRpcResponseXmlRPCUpdateUserFriendPerms); + m_httpServer.AddXmlRPCHandler("get_user_friend_list", XmlRpcResponseXmlRPCGetUserFriendList); + } + + public XmlRpcResponse FriendListItemListtoXmlRPCResponse(List returnUsers) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable responseData = new Hashtable(); + // Query Result Information + + responseData["avcount"] = returnUsers.Count.ToString(); + + for (int i = 0; i < returnUsers.Count; i++) + { + responseData["ownerID" + i] = returnUsers[i].FriendListOwner.ToString(); + responseData["friendID" + i] = returnUsers[i].Friend.ToString(); + responseData["ownerPerms" + i] = returnUsers[i].FriendListOwnerPerms.ToString(); + responseData["friendPerms" + i] = returnUsers[i].FriendPerms.ToString(); + } + response.Value = responseData; + + return response; + } + + public XmlRpcResponse XmlRpcResponseXmlRPCAddUserFriend(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable responseData = new Hashtable(); + string returnString = "FALSE"; + // Query Result Information + + if (requestData.Contains("ownerID") && requestData.Contains("friendID") && + requestData.Contains("friendPerms")) + { + // UserManagerBase.AddNewuserFriend + m_userDataBaseService.AddNewUserFriend(new UUID((string)requestData["ownerID"]), + new UUID((string)requestData["friendID"]), + (uint)Convert.ToInt32((string)requestData["friendPerms"])); + returnString = "TRUE"; + } + responseData["returnString"] = returnString; + response.Value = responseData; + return response; + } + + public XmlRpcResponse XmlRpcResponseXmlRPCRemoveUserFriend(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable responseData = new Hashtable(); + string returnString = "FALSE"; + // Query Result Information + + if (requestData.Contains("ownerID") && requestData.Contains("friendID")) + { + // UserManagerBase.AddNewuserFriend + m_userDataBaseService.RemoveUserFriend(new UUID((string)requestData["ownerID"]), + new UUID((string)requestData["friendID"])); + returnString = "TRUE"; + } + responseData["returnString"] = returnString; + response.Value = responseData; + return response; + } + + public XmlRpcResponse XmlRpcResponseXmlRPCUpdateUserFriendPerms(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable)request.Params[0]; + Hashtable responseData = new Hashtable(); + string returnString = "FALSE"; + + if (requestData.Contains("ownerID") && requestData.Contains("friendID") && + requestData.Contains("friendPerms")) + { + m_userDataBaseService.UpdateUserFriendPerms(new UUID((string)requestData["ownerID"]), + new UUID((string)requestData["friendID"]), + (uint)Convert.ToInt32((string)requestData["friendPerms"])); + // UserManagerBase. + returnString = "TRUE"; + } + responseData["returnString"] = returnString; + response.Value = responseData; + return response; + } + + public XmlRpcResponse XmlRpcResponseXmlRPCGetUserFriendList(XmlRpcRequest request) + { + // XmlRpcResponse response = new XmlRpcResponse(); + Hashtable requestData = (Hashtable)request.Params[0]; + // Hashtable responseData = new Hashtable(); + + List returndata = new List(); + + if (requestData.Contains("ownerID")) + { + returndata = m_userDataBaseService.GetUserFriendList(new UUID((string)requestData["ownerID"])); + } + + return FriendListItemListtoXmlRPCResponse(returndata); + } + } +} diff --git a/OpenSim/Grid/UserServer/IUGAIMCore.cs b/OpenSim/Grid/UserServer/IUGAIMCore.cs deleted file mode 100644 index 0783fe5..0000000 --- a/OpenSim/Grid/UserServer/IUGAIMCore.cs +++ /dev/null @@ -1,43 +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.Text; -using OpenSim.Framework.Servers; - -namespace OpenSim.Grid.UserServer -{ - public interface IUGAIMCore - { - T Get(); - void RegisterInterface(T iface); - bool TryGet(out T iface); - BaseHttpServer GetHttpServer(); - - } -} diff --git a/OpenSim/Grid/UserServer/Main.cs b/OpenSim/Grid/UserServer/Main.cs index efa090e..61f9800 100644 --- a/OpenSim/Grid/UserServer/Main.cs +++ b/OpenSim/Grid/UserServer/Main.cs @@ -40,6 +40,8 @@ using OpenSim.Framework.Console; using OpenSim.Framework.Servers; using OpenSim.Framework.Statistics; using OpenSim.Grid.Communications.OGS1; +using OpenSim.Grid.Framework; +using OpenSim.Grid.UserServer.Modules; namespace OpenSim.Grid.UserServer { @@ -63,6 +65,8 @@ namespace OpenSim.Grid.UserServer public GridInfoService m_gridInfoService; public MessageServersConnector m_messagesService; + protected UserServerCommandModule m_consoleCommandModule; + private UUID m_lastCreatedUser = UUID.Random(); public static void Main(string[] args) @@ -123,6 +127,8 @@ namespace OpenSim.Grid.UserServer m_messagesService = new MessageServersConnector(); + m_consoleCommandModule = new UserServerCommandModule(m_console, Cfg, m_userDataBaseService, m_loginService); + //register event handlers RegisterEventHandlers(); @@ -172,34 +178,7 @@ namespace OpenSim.Grid.UserServer protected virtual void RegisterConsoleCommands() { - m_console.Commands.AddCommand("userserver", false, "create user", - "create user [ [ [ [email]]]]", - "Create a new user account", RunCommand); - - m_console.Commands.AddCommand("userserver", false, "reset user password", - "reset user password [ [ []]]", - "Reset a user's password", RunCommand); - - m_console.Commands.AddCommand("userserver", false, "login level", - "login level ", - "Set the minimum user level to log in", HandleLoginCommand); - - m_console.Commands.AddCommand("userserver", false, "login reset", - "login reset", - "Reset the login level to allow all users", - HandleLoginCommand); - - m_console.Commands.AddCommand("userserver", false, "login text", - "login text ", - "Set the text users will see on login", HandleLoginCommand); - - m_console.Commands.AddCommand("userserver", false, "test-inventory", - "test-inventory", - "Perform a test inventory transaction", RunCommand); - - m_console.Commands.AddCommand("userserver", false, "logoff-user", - "logoff-user ", - "Log off a named user", RunCommand); + m_consoleCommandModule.RegisterConsoleCommands(); } protected virtual void RegisterHttpHandlers() @@ -261,247 +240,14 @@ namespace OpenSim.Grid.UserServer return m_httpServer; } #endregion - - #region Console Command Handlers - public void do_create(string[] args) - { - switch (args[0]) - { - case "user": - CreateUser(args); - break; - } - } - - /// - /// Execute switch for some of the reset commands - /// - /// - protected void Reset(string[] args) - { - if (args.Length == 0) - return; - - switch (args[0]) - { - case "user": - - switch (args[1]) - { - case "password": - ResetUserPassword(args); - break; - } - - break; - } - } - - /// - /// Create a new user - /// - /// string array with parameters: firstname, lastname, password, locationX, locationY, email - protected void CreateUser(string[] cmdparams) - { - string firstName; - string lastName; - string password; - string email; - uint regX = 1000; - uint regY = 1000; - - if (cmdparams.Length < 2) - firstName = MainConsole.Instance.CmdPrompt("First name", "Default"); - else firstName = cmdparams[1]; - - if (cmdparams.Length < 3) - lastName = MainConsole.Instance.CmdPrompt("Last name", "User"); - else lastName = cmdparams[2]; - - if (cmdparams.Length < 4) - password = MainConsole.Instance.PasswdPrompt("Password"); - else password = cmdparams[3]; - - if (cmdparams.Length < 5) - regX = Convert.ToUInt32(MainConsole.Instance.CmdPrompt("Start Region X", regX.ToString())); - else regX = Convert.ToUInt32(cmdparams[4]); - - if (cmdparams.Length < 6) - regY = Convert.ToUInt32(MainConsole.Instance.CmdPrompt("Start Region Y", regY.ToString())); - else regY = Convert.ToUInt32(cmdparams[5]); - - if (cmdparams.Length < 7) - email = MainConsole.Instance.CmdPrompt("Email", ""); - else email = cmdparams[6]; - - if (null == m_userDataBaseService.GetUserProfile(firstName, lastName)) - { - m_lastCreatedUser = m_userDataBaseService.AddUser(firstName, lastName, password, email, regX, regY); - } - else - { - m_log.ErrorFormat("[USERS]: A user with the name {0} {1} already exists!", firstName, lastName); - } - } - - /// - /// Reset a user password. - /// - /// - private void ResetUserPassword(string[] cmdparams) - { - string firstName; - string lastName; - string newPassword; - - if (cmdparams.Length < 3) - firstName = MainConsole.Instance.CmdPrompt("First name"); - else firstName = cmdparams[2]; - - if ( cmdparams.Length < 4 ) - lastName = MainConsole.Instance.CmdPrompt("Last name"); - else lastName = cmdparams[3]; - - if ( cmdparams.Length < 5 ) - newPassword = MainConsole.Instance.PasswdPrompt("New password"); - else newPassword = cmdparams[4]; - - m_userDataBaseService.ResetUserPassword(firstName, lastName, newPassword); - } - - private void HandleLoginCommand(string module, string[] cmd) - { - string subcommand = cmd[1]; - - switch (subcommand) - { - case "level": - // Set the minimal level to allow login - // Useful to allow grid update without worrying about users. - // or fixing critical issues - // - if (cmd.Length > 2) - { - int level = Convert.ToInt32(cmd[2]); - m_loginService.setloginlevel(level); - } - break; - case "reset": - m_loginService.setloginlevel(0); - break; - case "text": - if (cmd.Length > 2) - { - m_loginService.setwelcometext(cmd[2]); - } - break; - } - } - - public void RunCommand(string module, string[] cmd) - { - List args = new List(cmd); - string command = cmd[0]; - - args.RemoveAt(0); - - string[] cmdparams = args.ToArray(); - - switch (command) - { - case "create": - do_create(cmdparams); - break; - - case "reset": - Reset(cmdparams); - break; - - - case "test-inventory": - // RestObjectPosterResponse> requester = new RestObjectPosterResponse>(); - // requester.ReturnResponseVal = TestResponse; - // requester.BeginPostObject(m_userManager._config.InventoryUrl + "RootFolders/", m_lastCreatedUser); - SynchronousRestObjectPoster.BeginPostObject>( - "POST", Cfg.InventoryUrl + "RootFolders/", m_lastCreatedUser); - break; - - case "logoff-user": - if (cmdparams.Length >= 3) - { - string firstname = cmdparams[0]; - string lastname = cmdparams[1]; - string message = ""; - - for (int i = 2; i < cmdparams.Length; i++) - message += " " + cmdparams[i]; - - UserProfileData theUser = null; - try - { - theUser = m_loginService.GetTheUser(firstname, lastname); - } - catch (Exception) - { - m_log.Error("[LOGOFF]: Error getting user data from the database."); - } - - if (theUser != null) - { - if (theUser.CurrentAgent != null) - { - if (theUser.CurrentAgent.AgentOnline) - { - m_log.Info("[LOGOFF]: Logging off requested user!"); - m_loginService.LogOffUser(theUser, message); - - theUser.CurrentAgent.AgentOnline = false; - - m_loginService.CommitAgent(ref theUser); - } - else - { - m_log.Info( - "[LOGOFF]: User Doesn't appear to be online, sending the logoff message anyway."); - m_loginService.LogOffUser(theUser, message); - - theUser.CurrentAgent.AgentOnline = false; - - m_loginService.CommitAgent(ref theUser); - } - } - else - { - m_log.Error( - "[LOGOFF]: Unable to logoff-user. User doesn't have an agent record so I can't find the simulator to notify"); - } - } - else - { - m_log.Info("[LOGOFF]: User doesn't exist in the database"); - } - } - else - { - m_log.Error( - "[LOGOFF]: Invalid amount of parameters. logoff-user takes at least three. Firstname, Lastname, and message"); - } - - break; - } - } + #region Console Command Handlers + protected override void ShowHelp(string[] helpArgs) { - base.ShowHelp(helpArgs); - - m_console.Notice("create user - create a new user"); - m_console.Notice("logoff-user - logs off the specified user from the grid"); - m_console.Notice("reset user password - reset a user's password."); - m_console.Notice("login-level - Set the miminim userlevel allowed To login."); - m_console.Notice("login-reset - reset the login level to its default value."); - m_console.Notice("login-text "); + base.ShowHelp(helpArgs); + m_consoleCommandModule.ShowHelp(helpArgs); } #endregion diff --git a/OpenSim/Grid/UserServer/MessageServersConnector.cs b/OpenSim/Grid/UserServer/MessageServersConnector.cs deleted file mode 100644 index 1d0649c..0000000 --- a/OpenSim/Grid/UserServer/MessageServersConnector.cs +++ /dev/null @@ -1,509 +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 OpenSim 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.Collections; -using System.Collections.Generic; -using System.Net; -using System.Reflection; -using System.Threading; -using log4net; -using Nwc.XmlRpc; -using OpenMetaverse; -using OpenSim.Framework; -using OpenSim.Framework.Servers; - -namespace OpenSim.Grid.UserServer -{ - public enum NotificationRequest : int - { - Login = 0, - Logout = 1, - Shutdown = 2 - } - - public struct PresenceNotification - { - public NotificationRequest request; - public UUID agentID; - public UUID sessionID; - public UUID RegionID; - public ulong regionhandle; - public float positionX; - public float positionY; - public float positionZ; - public string firstname; - public string lastname; - } - - public delegate void AgentLocationDelegate(UUID agentID, UUID regionID, ulong regionHandle); - public delegate void AgentLeavingDelegate(UUID agentID, UUID regionID, ulong regionHandle); - public delegate void RegionStartupDelegate(UUID regionID); - public delegate void RegionShutdownDelegate(UUID regionID); - - - public class MessageServersConnector - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - public Dictionary MessageServers; - - private BaseHttpServer m_httpServer; - - private BlockingQueue m_NotifyQueue = - new BlockingQueue(); - - Thread m_NotifyThread; - - public event AgentLocationDelegate OnAgentLocation; - public event AgentLeavingDelegate OnAgentLeaving; - public event RegionStartupDelegate OnRegionStartup; - public event RegionShutdownDelegate OnRegionShutdown; - - public MessageServersConnector() - { - MessageServers = new Dictionary(); - m_NotifyThread = new Thread(new ThreadStart(NotifyQueueRunner)); - m_NotifyThread.Start(); - } - - public void Initialise() - { - - } - - public void PostInitialise() - { - - } - - public void RegisterHandlers(BaseHttpServer httpServer) - { - m_httpServer = httpServer; - - m_httpServer.AddXmlRPCHandler("region_startup", RegionStartup); - m_httpServer.AddXmlRPCHandler("region_shutdown", RegionShutdown); - m_httpServer.AddXmlRPCHandler("agent_location", AgentLocation); - m_httpServer.AddXmlRPCHandler("agent_leaving", AgentLeaving); - // Message Server ---> User Server - m_httpServer.AddXmlRPCHandler("register_messageserver", XmlRPCRegisterMessageServer); - m_httpServer.AddXmlRPCHandler("agent_change_region", XmlRPCUserMovedtoRegion); - m_httpServer.AddXmlRPCHandler("deregister_messageserver", XmlRPCDeRegisterMessageServer); - } - - public void RegisterMessageServer(string URI, MessageServerInfo serverData) - { - lock (MessageServers) - { - if (!MessageServers.ContainsKey(URI)) - MessageServers.Add(URI, serverData); - } - } - - public void DeRegisterMessageServer(string URI) - { - lock (MessageServers) - { - if (MessageServers.ContainsKey(URI)) - MessageServers.Remove(URI); - } - } - - public void AddResponsibleRegion(string URI, ulong regionhandle) - { - if (!MessageServers.ContainsKey(URI)) - { - m_log.Warn("[MSGSERVER]: Got addResponsibleRegion Request for a MessageServer that isn't registered"); - } - else - { - MessageServerInfo msginfo = MessageServers["URI"]; - msginfo.responsibleForRegions.Add(regionhandle); - MessageServers["URI"] = msginfo; - } - } - public void RemoveResponsibleRegion(string URI, ulong regionhandle) - { - if (!MessageServers.ContainsKey(URI)) - { - m_log.Warn("[MSGSERVER]: Got RemoveResponsibleRegion Request for a MessageServer that isn't registered"); - } - else - { - MessageServerInfo msginfo = MessageServers["URI"]; - if (msginfo.responsibleForRegions.Contains(regionhandle)) - { - msginfo.responsibleForRegions.Remove(regionhandle); - MessageServers["URI"] = msginfo; - } - } - - } - public XmlRpcResponse XmlRPCRegisterMessageServer(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable)request.Params[0]; - Hashtable responseData = new Hashtable(); - - if (requestData.Contains("uri")) - { - string URI = (string)requestData["uri"]; - string sendkey=(string)requestData["sendkey"]; - string recvkey=(string)requestData["recvkey"]; - MessageServerInfo m = new MessageServerInfo(); - m.URI = URI; - m.sendkey = sendkey; - m.recvkey = recvkey; - RegisterMessageServer(URI, m); - responseData["responsestring"] = "TRUE"; - response.Value = responseData; - } - return response; - } - public XmlRpcResponse XmlRPCDeRegisterMessageServer(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable)request.Params[0]; - Hashtable responseData = new Hashtable(); - - if (requestData.Contains("uri")) - { - string URI = (string)requestData["uri"]; - - DeRegisterMessageServer(URI); - responseData["responsestring"] = "TRUE"; - response.Value = responseData; - } - return response; - } - public XmlRpcResponse XmlRPCUserMovedtoRegion(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable)request.Params[0]; - Hashtable responseData = new Hashtable(); - - if (requestData.Contains("fromuri")) - { - // string sURI = (string)requestData["fromuri"]; - // string sagentID = (string)requestData["agentid"]; - // string ssessionID = (string)requestData["sessionid"]; - // string scurrentRegionID = (string)requestData["regionid"]; - // string sregionhandle = (string)requestData["regionhandle"]; - // string scurrentpos = (string)requestData["currentpos"]; - //Vector3.TryParse((string)reader["currentPos"], out retval.currentPos); - // TODO: Okay now raise event so the user server can pass this data to the Usermanager - - responseData["responsestring"] = "TRUE"; - response.Value = responseData; - } - return response; - } - - public void TellMessageServersAboutUser(UUID agentID, UUID sessionID, UUID RegionID, - ulong regionhandle, float positionX, float positionY, - float positionZ, string firstname, string lastname) - { - PresenceNotification notification = new PresenceNotification(); - - notification.request = NotificationRequest.Login; - notification.agentID = agentID; - notification.sessionID = sessionID; - notification.RegionID = RegionID; - notification.regionhandle = regionhandle; - notification.positionX = positionX; - notification.positionY = positionY; - notification.positionZ = positionZ; - notification.firstname = firstname; - notification.lastname = lastname; - - m_NotifyQueue.Enqueue(notification); - } - - private void TellMessageServersAboutUserInternal(UUID agentID, UUID sessionID, UUID RegionID, - ulong regionhandle, float positionX, float positionY, - float positionZ, string firstname, string lastname) - { - // Loop over registered Message Servers (AND THERE WILL BE MORE THEN ONE :D) - lock (MessageServers) - { - if (MessageServers.Count > 0) - { - m_log.Info("[MSGCONNECTOR]: Sending login notice to registered message servers"); - } -// else -// { -// m_log.Debug("[MSGCONNECTOR]: No Message Servers registered, ignoring"); -// } - foreach (MessageServerInfo serv in MessageServers.Values) - { - NotifyMessageServerAboutUser(serv, agentID, sessionID, RegionID, - regionhandle, positionX, positionY, positionZ, - firstname, lastname); - } - } - } - - private void TellMessageServersAboutUserLogoffInternal(UUID agentID) - { - lock (MessageServers) - { - if (MessageServers.Count > 0) - { - m_log.Info("[MSGCONNECTOR]: Sending logoff notice to registered message servers"); - } - else - { -// m_log.Debug("[MSGCONNECTOR]: No Message Servers registered, ignoring"); - } - foreach (MessageServerInfo serv in MessageServers.Values) - { - NotifyMessageServerAboutUserLogoff(serv,agentID); - } - } - } - - private void TellMessageServersAboutRegionShutdownInternal(UUID regionID) - { - lock (MessageServers) - { - if (MessageServers.Count > 0) - { - m_log.Info("[MSGCONNECTOR]: Sending region down notice to registered message servers"); - } - else - { -// m_log.Debug("[MSGCONNECTOR]: No Message Servers registered, ignoring"); - } - foreach (MessageServerInfo serv in MessageServers.Values) - { - NotifyMessageServerAboutRegionShutdown(serv,regionID); - } - } - } - - public void TellMessageServersAboutUserLogoff(UUID agentID) - { - PresenceNotification notification = new PresenceNotification(); - - notification.request = NotificationRequest.Logout; - notification.agentID = agentID; - - m_NotifyQueue.Enqueue(notification); - } - - public void TellMessageServersAboutRegionShutdown(UUID regionID) - { - PresenceNotification notification = new PresenceNotification(); - - notification.request = NotificationRequest.Shutdown; - notification.RegionID = regionID; - - m_NotifyQueue.Enqueue(notification); - } - - private void NotifyMessageServerAboutUserLogoff(MessageServerInfo serv, UUID agentID) - { - Hashtable reqparams = new Hashtable(); - reqparams["sendkey"] = serv.sendkey; - reqparams["agentid"] = agentID.ToString(); - ArrayList SendParams = new ArrayList(); - SendParams.Add(reqparams); - - XmlRpcRequest GridReq = new XmlRpcRequest("logout_of_simulator", SendParams); - try - { - GridReq.Send(serv.URI, 6000); - } - catch (WebException) - { - m_log.Warn("[MSGCONNECTOR]: Unable to notify Message Server about log out. Other users might still think this user is online"); - } - m_log.Info("[LOGOUT]: Notified : " + serv.URI + " about user logout"); - } - - private void NotifyMessageServerAboutRegionShutdown(MessageServerInfo serv, UUID regionID) - { - Hashtable reqparams = new Hashtable(); - reqparams["sendkey"] = serv.sendkey; - reqparams["regionid"] = regionID.ToString(); - ArrayList SendParams = new ArrayList(); - SendParams.Add(reqparams); - - XmlRpcRequest GridReq = new XmlRpcRequest("process_region_shutdown", SendParams); - try - { - GridReq.Send(serv.URI, 6000); - } - catch (WebException) - { - m_log.Warn("[MSGCONNECTOR]: Unable to notify Message Server about region shutdown."); - } - m_log.Info("[REGION UPDOWN]: Notified : " + serv.URI + " about region state change"); - } - - private void NotifyMessageServerAboutUser(MessageServerInfo serv, - UUID agentID, UUID sessionID, UUID RegionID, - ulong regionhandle, float positionX, float positionY, float positionZ, - string firstname, string lastname) - { - Hashtable reqparams = new Hashtable(); - reqparams["sendkey"] = serv.sendkey; - reqparams["agentid"] = agentID.ToString(); - reqparams["sessionid"] = sessionID.ToString(); - reqparams["regionid"] = RegionID.ToString(); - reqparams["regionhandle"] = regionhandle.ToString(); - reqparams["positionx"] = positionX.ToString(); - reqparams["positiony"] = positionY.ToString(); - reqparams["positionz"] = positionZ.ToString(); - reqparams["firstname"] = firstname; - reqparams["lastname"] = lastname; - - //reqparams["position"] = Position.ToString(); - - ArrayList SendParams = new ArrayList(); - SendParams.Add(reqparams); - - XmlRpcRequest GridReq = new XmlRpcRequest("login_to_simulator", SendParams); - try - { - GridReq.Send(serv.URI, 6000); - m_log.Info("[LOGIN]: Notified : " + serv.URI + " about user login"); - } - catch (WebException) - { - m_log.Warn("[MSGCONNECTOR]: Unable to notify Message Server about login. Presence might be borked for this user"); - } - - } - - private void NotifyQueueRunner() - { - while (true) - { - PresenceNotification presence = m_NotifyQueue.Dequeue(); - - if (presence.request == NotificationRequest.Shutdown) - { - TellMessageServersAboutRegionShutdownInternal(presence.RegionID); - } - - if (presence.request == NotificationRequest.Login) - { - TellMessageServersAboutUserInternal(presence.agentID, - presence.sessionID, presence.RegionID, - presence.regionhandle, presence.positionX, - presence.positionY, presence.positionZ, - presence.firstname, presence.lastname); - } - - if (presence.request == NotificationRequest.Logout) - { - TellMessageServersAboutUserLogoffInternal(presence.agentID); - } - } - } - - public XmlRpcResponse RegionStartup(XmlRpcRequest request) - { - Hashtable requestData = (Hashtable)request.Params[0]; - Hashtable result = new Hashtable(); - - UUID regionID; - if (UUID.TryParse((string)requestData["RegionUUID"], out regionID)) - { - if (OnRegionStartup != null) - OnRegionStartup(regionID); - - result["responsestring"] = "TRUE"; - } - - XmlRpcResponse response = new XmlRpcResponse(); - response.Value = result; - return response; - } - - public XmlRpcResponse RegionShutdown(XmlRpcRequest request) - { - Hashtable requestData = (Hashtable)request.Params[0]; - Hashtable result = new Hashtable(); - - UUID regionID; - if (UUID.TryParse((string)requestData["RegionUUID"], out regionID)) - { - if (OnRegionShutdown != null) - OnRegionShutdown(regionID); - - result["responsestring"] = "TRUE"; - } - - XmlRpcResponse response = new XmlRpcResponse(); - response.Value = result; - return response; - } - - public XmlRpcResponse AgentLocation(XmlRpcRequest request) - { - Hashtable requestData = (Hashtable)request.Params[0]; - Hashtable result = new Hashtable(); - - UUID agentID; - UUID regionID; - ulong regionHandle; - if (UUID.TryParse((string)requestData["AgentID"], out agentID) && UUID.TryParse((string)requestData["RegionUUID"], out regionID) && ulong.TryParse((string)requestData["RegionHandle"], out regionHandle)) - { - if (OnAgentLocation != null) - OnAgentLocation(agentID, regionID, regionHandle); - - result["responsestring"] = "TRUE"; - } - - XmlRpcResponse response = new XmlRpcResponse(); - response.Value = result; - return response; - } - - public XmlRpcResponse AgentLeaving(XmlRpcRequest request) - { - Hashtable requestData = (Hashtable)request.Params[0]; - Hashtable result = new Hashtable(); - - UUID agentID; - UUID regionID; - ulong regionHandle; - if (UUID.TryParse((string)requestData["AgentID"], out agentID) && UUID.TryParse((string)requestData["RegionUUID"], out regionID) && ulong.TryParse((string)requestData["RegionHandle"], out regionHandle)) - { - if (OnAgentLeaving != null) - OnAgentLeaving(agentID, regionID, regionHandle); - - result["responsestring"] = "TRUE"; - } - - XmlRpcResponse response = new XmlRpcResponse(); - response.Value = result; - return response; - } - } -} diff --git a/OpenSim/Grid/UserServer/OpenIdService.cs b/OpenSim/Grid/UserServer/OpenIdService.cs deleted file mode 100644 index 187758f..0000000 --- a/OpenSim/Grid/UserServer/OpenIdService.cs +++ /dev/null @@ -1,337 +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 OpenSim 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.Collections.Specialized; -using System.IO; -using System.Net; -using System.Web; -using DotNetOpenId; -using DotNetOpenId.Provider; -using OpenSim.Framework; -using OpenSim.Framework.Servers; - -namespace OpenSim.Grid.UserServer -{ - /// - /// Temporary, in-memory store for OpenID associations - /// - public class ProviderMemoryStore : IAssociationStore - { - private class AssociationItem - { - public AssociationRelyingPartyType DistinguishingFactor; - public string Handle; - public DateTime Expires; - public byte[] PrivateData; - } - - Dictionary m_store = new Dictionary(); - SortedList m_sortedStore = new SortedList(); - object m_syncRoot = new object(); - - #region IAssociationStore Members - - public void StoreAssociation(AssociationRelyingPartyType distinguishingFactor, Association assoc) - { - AssociationItem item = new AssociationItem(); - item.DistinguishingFactor = distinguishingFactor; - item.Handle = assoc.Handle; - item.Expires = assoc.Expires.ToLocalTime(); - item.PrivateData = assoc.SerializePrivateData(); - - lock (m_syncRoot) - { - m_store[item.Handle] = item; - m_sortedStore[item.Expires] = item; - } - } - - public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor) - { - lock (m_syncRoot) - { - if (m_sortedStore.Count > 0) - { - AssociationItem item = m_sortedStore.Values[m_sortedStore.Count - 1]; - return Association.Deserialize(item.Handle, item.Expires.ToUniversalTime(), item.PrivateData); - } - else - { - return null; - } - } - } - - public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor, string handle) - { - AssociationItem item; - bool success = false; - lock (m_syncRoot) - success = m_store.TryGetValue(handle, out item); - - if (success) - return Association.Deserialize(item.Handle, item.Expires.ToUniversalTime(), item.PrivateData); - else - return null; - } - - public bool RemoveAssociation(AssociationRelyingPartyType distinguishingFactor, string handle) - { - lock (m_syncRoot) - { - for (int i = 0; i < m_sortedStore.Values.Count; i++) - { - AssociationItem item = m_sortedStore.Values[i]; - if (item.Handle == handle) - { - m_sortedStore.RemoveAt(i); - break; - } - } - - return m_store.Remove(handle); - } - } - - public void ClearExpiredAssociations() - { - lock (m_syncRoot) - { - List itemsCopy = new List(m_sortedStore.Values); - DateTime now = DateTime.Now; - - for (int i = 0; i < itemsCopy.Count; i++) - { - AssociationItem item = itemsCopy[i]; - - if (item.Expires <= now) - { - m_sortedStore.RemoveAt(i); - m_store.Remove(item.Handle); - } - } - } - } - - #endregion - } - - public class OpenIdStreamHandler : IStreamHandler - { - #region HTML - - /// Login form used to authenticate OpenID requests - const string LOGIN_PAGE = -@" -OpenSim OpenID Login - -

OpenSim Login

-
- - - - -
- -"; - - /// Page shown for a valid OpenID identity - const string OPENID_PAGE = -@" - -{2} {3} - - -OpenID identifier for {2} {3} - -"; - - /// Page shown for an invalid OpenID identity - const string INVALID_OPENID_PAGE = -@"Identity not found -Invalid OpenID identity"; - - /// Page shown if the OpenID endpoint is requested directly - const string ENDPOINT_PAGE = -@"OpenID Endpoint -This is an OpenID server endpoint, not a human-readable resource. -For more information, see http://openid.net/. -"; - - #endregion HTML - - public string ContentType { get { return m_contentType; } } - public string HttpMethod { get { return m_httpMethod; } } - public string Path { get { return m_path; } } - - string m_contentType; - string m_httpMethod; - string m_path; - UserLoginService m_loginService; - ProviderMemoryStore m_openidStore = new ProviderMemoryStore(); - - /// - /// Constructor - /// - public OpenIdStreamHandler(string httpMethod, string path, UserLoginService loginService) - { - m_loginService = loginService; - m_httpMethod = httpMethod; - m_path = path; - - m_contentType = "text/html"; - } - - /// - /// Handles all GET and POST requests for OpenID identifier pages and endpoint - /// server communication - /// - public void Handle(string path, Stream request, Stream response, OSHttpRequest httpRequest, OSHttpResponse httpResponse) - { - Uri providerEndpoint = new Uri(String.Format("{0}://{1}{2}", httpRequest.Url.Scheme, httpRequest.Url.Authority, httpRequest.Url.AbsolutePath)); - - // Defult to returning HTML content - m_contentType = "text/html"; - - try - { - NameValueCollection postQuery = HttpUtility.ParseQueryString(new StreamReader(httpRequest.InputStream).ReadToEnd()); - NameValueCollection getQuery = HttpUtility.ParseQueryString(httpRequest.Url.Query); - NameValueCollection openIdQuery = (postQuery.GetValues("openid.mode") != null ? postQuery : getQuery); - - OpenIdProvider provider = new OpenIdProvider(m_openidStore, providerEndpoint, httpRequest.Url, openIdQuery); - - if (provider.Request != null) - { - if (!provider.Request.IsResponseReady && provider.Request is IAuthenticationRequest) - { - IAuthenticationRequest authRequest = (IAuthenticationRequest)provider.Request; - string[] passwordValues = postQuery.GetValues("pass"); - - UserProfileData profile; - if (TryGetProfile(new Uri(authRequest.ClaimedIdentifier.ToString()), out profile)) - { - // Check for form POST data - if (passwordValues != null && passwordValues.Length == 1) - { - if (profile != null && m_loginService.AuthenticateUser(profile, passwordValues[0])) - authRequest.IsAuthenticated = true; - else - authRequest.IsAuthenticated = false; - } - else - { - // Authentication was requested, send the client a login form - using (StreamWriter writer = new StreamWriter(response)) - writer.Write(String.Format(LOGIN_PAGE, profile.FirstName, profile.SurName)); - return; - } - } - else - { - // Cannot find an avatar matching the claimed identifier - authRequest.IsAuthenticated = false; - } - } - - // Add OpenID headers to the response - foreach (string key in provider.Request.Response.Headers.Keys) - httpResponse.AddHeader(key, provider.Request.Response.Headers[key]); - - string[] contentTypeValues = provider.Request.Response.Headers.GetValues("Content-Type"); - if (contentTypeValues != null && contentTypeValues.Length == 1) - m_contentType = contentTypeValues[0]; - - // Set the response code and document body based on the OpenID result - httpResponse.StatusCode = (int)provider.Request.Response.Code; - response.Write(provider.Request.Response.Body, 0, provider.Request.Response.Body.Length); - response.Close(); - } - else if (httpRequest.Url.AbsolutePath.Contains("/openid/server")) - { - // Standard HTTP GET was made on the OpenID endpoint, send the client the default error page - using (StreamWriter writer = new StreamWriter(response)) - writer.Write(ENDPOINT_PAGE); - } - else - { - // Try and lookup this avatar - UserProfileData profile; - if (TryGetProfile(httpRequest.Url, out profile)) - { - using (StreamWriter writer = new StreamWriter(response)) - { - // TODO: Print out a full profile page for this avatar - writer.Write(String.Format(OPENID_PAGE, httpRequest.Url.Scheme, - httpRequest.Url.Authority, profile.FirstName, profile.SurName)); - } - } - else - { - // Couldn't parse an avatar name, or couldn't find the avatar in the user server - using (StreamWriter writer = new StreamWriter(response)) - writer.Write(INVALID_OPENID_PAGE); - } - } - } - catch (Exception ex) - { - httpResponse.StatusCode = (int)HttpStatusCode.InternalServerError; - using (StreamWriter writer = new StreamWriter(response)) - writer.Write(ex.Message); - } - } - - /// - /// Parse a URL with a relative path of the form /users/First_Last and try to - /// retrieve the profile matching that avatar name - /// - /// URL to parse for an avatar name - /// Profile data for the avatar - /// True if the parse and lookup were successful, otherwise false - bool TryGetProfile(Uri requestUrl, out UserProfileData profile) - { - if (requestUrl.Segments.Length == 3 && requestUrl.Segments[1] == "users/") - { - // Parse the avatar name from the path - string username = requestUrl.Segments[requestUrl.Segments.Length - 1]; - string[] name = username.Split('_'); - - if (name.Length == 2) - { - profile = m_loginService.GetTheUser(name[0], name[1]); - return (profile != null); - } - } - - profile = null; - return false; - } - } -} diff --git a/OpenSim/Grid/UserServer/UserDataBaseService.cs b/OpenSim/Grid/UserServer/UserDataBaseService.cs deleted file mode 100644 index 85c98a6..0000000 --- a/OpenSim/Grid/UserServer/UserDataBaseService.cs +++ /dev/null @@ -1,68 +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 OpenSim 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 OpenSim.Framework; -using OpenSim.Framework.Communications; -using OpenSim.Framework.Servers; - -namespace OpenSim.Grid.UserServer -{ - public class UserDataBaseService : UserManagerBase - { - public UserDataBaseService() - : base(null) - { - } - - public UserDataBaseService(IInterServiceInventoryServices interServiceInventoryService) - : base(interServiceInventoryService) - { - } - - public override UserProfileData SetupMasterUser(string firstName, string lastName) - { - throw new Exception("The method or operation is not implemented."); - } - - public override UserProfileData SetupMasterUser(string firstName, string lastName, string password) - { - throw new Exception("The method or operation is not implemented."); - } - - public override UserProfileData SetupMasterUser(UUID uuid) - { - throw new Exception("The method or operation is not implemented."); - } - } -} diff --git a/OpenSim/Grid/UserServer/UserLoginService.cs b/OpenSim/Grid/UserServer/UserLoginService.cs deleted file mode 100644 index 0cb4976..0000000 --- a/OpenSim/Grid/UserServer/UserLoginService.cs +++ /dev/null @@ -1,600 +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 OpenSim 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 System.Text.RegularExpressions; -using log4net; -using Nwc.XmlRpc; -using OpenMetaverse; -using OpenSim.Data; -using OpenSim.Framework; -using OpenSim.Framework.Communications; -using OpenSim.Framework.Communications.Cache; -using OpenSim.Framework.Communications.Capabilities; -using OpenSim.Framework.Servers; - -namespace OpenSim.Grid.UserServer -{ - public delegate void UserLoggedInAtLocation(UUID agentID, UUID sessionID, UUID RegionID, - ulong regionhandle, float positionX, float positionY, float positionZ, - string firstname, string lastname); - - /// - /// Login service used in grid mode. - /// - public class UserLoginService : LoginService - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - protected IInterServiceInventoryServices m_inventoryService; - - public event UserLoggedInAtLocation OnUserLoggedInAtLocation; - - private UserLoggedInAtLocation handlerUserLoggedInAtLocation; - - public UserConfig m_config; - private readonly IRegionProfileService m_regionProfileService; - - protected BaseHttpServer m_httpServer; - - public UserLoginService( - UserManagerBase userManager, IInterServiceInventoryServices inventoryService, - LibraryRootFolder libraryRootFolder, - UserConfig config, string welcomeMess, IRegionProfileService regionProfileService) - : base(userManager, libraryRootFolder, welcomeMess) - { - m_config = config; - m_inventoryService = inventoryService; - m_regionProfileService = regionProfileService; - } - - public void RegisterHandlers(BaseHttpServer httpServer, bool registerLLSDHandler, bool registerOpenIDHandlers) - { - m_httpServer = httpServer; - - m_httpServer.AddXmlRPCHandler("login_to_simulator", XmlRpcLoginMethod); - m_httpServer.AddHTTPHandler("login", ProcessHTMLLogin); - m_httpServer.AddXmlRPCHandler("set_login_params", XmlRPCSetLoginParams); - - if (registerLLSDHandler) - { - m_httpServer.SetDefaultLLSDHandler(LLSDLoginMethod); - } - - if (registerOpenIDHandlers) - { - // Handler for OpenID avatar identity pages - m_httpServer.AddStreamHandler(new OpenIdStreamHandler("GET", "/users/", this)); - // Handlers for the OpenID endpoint server - m_httpServer.AddStreamHandler(new OpenIdStreamHandler("POST", "/openid/server/", this)); - m_httpServer.AddStreamHandler(new OpenIdStreamHandler("GET", "/openid/server/", this)); - } - } - - public void setloginlevel(int level) - { - m_minLoginLevel = level; - m_log.InfoFormat("[GRID]: Login Level set to {0} ", level); - } - public void setwelcometext(string text) - { - m_welcomeMessage = text; - m_log.InfoFormat("[GRID]: Login text set to {0} ", text); - } - - public override void LogOffUser(UserProfileData theUser, string message) - { - RegionProfileData SimInfo; - try - { - SimInfo = m_regionProfileService.RequestSimProfileData( - theUser.CurrentAgent.Handle, m_config.GridServerURL, - m_config.GridSendKey, m_config.GridRecvKey); - - if (SimInfo == null) - { - m_log.Error("[GRID]: Region user was in isn't currently logged in"); - return; - } - } - catch (Exception) - { - m_log.Error("[GRID]: Unable to look up region to log user off"); - return; - } - - // Prepare notification - Hashtable SimParams = new Hashtable(); - SimParams["agent_id"] = theUser.ID.ToString(); - SimParams["region_secret"] = theUser.CurrentAgent.SecureSessionID.ToString(); - SimParams["region_secret2"] = SimInfo.regionSecret; - //m_log.Info(SimInfo.regionSecret); - SimParams["regionhandle"] = theUser.CurrentAgent.Handle.ToString(); - SimParams["message"] = message; - ArrayList SendParams = new ArrayList(); - SendParams.Add(SimParams); - - m_log.InfoFormat( - "[ASSUMED CRASH]: Telling region {0} @ {1},{2} ({3}) that their agent is dead: {4}", - SimInfo.regionName, SimInfo.regionLocX, SimInfo.regionLocY, SimInfo.httpServerURI, - theUser.FirstName + " " + theUser.SurName); - - try - { - XmlRpcRequest GridReq = new XmlRpcRequest("logoff_user", SendParams); - XmlRpcResponse GridResp = GridReq.Send(SimInfo.httpServerURI, 6000); - - if (GridResp.IsFault) - { - m_log.ErrorFormat( - "[LOGIN]: XMLRPC request for {0} failed, fault code: {1}, reason: {2}, This is likely an old region revision.", - SimInfo.httpServerURI, GridResp.FaultCode, GridResp.FaultString); - } - } - catch (Exception) - { - m_log.Error("[LOGIN]: Error telling region to logout user!"); - } - - // Prepare notification - SimParams = new Hashtable(); - SimParams["agent_id"] = theUser.ID.ToString(); - SimParams["region_secret"] = SimInfo.regionSecret; - //m_log.Info(SimInfo.regionSecret); - SimParams["regionhandle"] = theUser.CurrentAgent.Handle.ToString(); - SimParams["message"] = message; - SendParams = new ArrayList(); - SendParams.Add(SimParams); - - m_log.InfoFormat( - "[ASSUMED CRASH]: Telling region {0} @ {1},{2} ({3}) that their agent is dead: {4}", - SimInfo.regionName, SimInfo.regionLocX, SimInfo.regionLocY, SimInfo.httpServerURI, - theUser.FirstName + " " + theUser.SurName); - - try - { - XmlRpcRequest GridReq = new XmlRpcRequest("logoff_user", SendParams); - XmlRpcResponse GridResp = GridReq.Send(SimInfo.httpServerURI, 6000); - - if (GridResp.IsFault) - { - m_log.ErrorFormat( - "[LOGIN]: XMLRPC request for {0} failed, fault code: {1}, reason: {2}, This is likely an old region revision.", - SimInfo.httpServerURI, GridResp.FaultCode, GridResp.FaultString); - } - } - catch (Exception) - { - m_log.Error("[LOGIN]: Error telling region to logout user!"); - } - //base.LogOffUser(theUser); - } - - /// - /// Customises the login response and fills in missing values. - /// - /// The existing response - /// The user profile - /// The requested start location - public override bool CustomiseResponse(LoginResponse response, UserProfileData theUser, string startLocationRequest) - { - // add active gestures to login-response - AddActiveGestures(response, theUser); - - // HomeLocation - RegionProfileData 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 - { - // 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 - RegionProfileData regionInfo = null; - if (startLocationRequest == "home") - { - regionInfo = homeInfo; - theUser.CurrentAgent.Position = theUser.HomeLocation; - response.LookAt = "[r" + theUser.HomeLookAt.X.ToString() + ",r" + theUser.HomeLookAt.Y.ToString() + ",r" + theUser.HomeLookAt.Z.ToString() + "]"; - } - else if (startLocationRequest == "last") - { - UUID lastRegion = theUser.CurrentAgent.Region; - regionInfo = GetRegionInfo(lastRegion); - response.LookAt = "[r" + theUser.CurrentAgent.LookAt.X.ToString() + ",r" + theUser.CurrentAgent.LookAt.Y.ToString() + ",r" + 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))) - { - return true; - } - - // StartLocation not available, send him to a nearby region instead - //regionInfo = RegionProfileData.RequestSimProfileData("", m_config.GridServerURL, m_config.GridSendKey, m_config.GridRecvKey); - //m_log.InfoFormat("[LOGIN]: StartLocation not available sending to region {0}", regionInfo.regionName); - - // Send him to default region instead - // Load information from the gridserver - ulong defaultHandle = (((ulong) m_config.DefaultX * Constants.RegionSize) << 32) | - ((ulong) m_config.DefaultY * Constants.RegionSize); - - if ((regionInfo != null) && (defaultHandle == regionInfo.regionHandle)) - { - m_log.ErrorFormat("[LOGIN]: Not trying the default region since this is the same as the selected region"); - return false; - } - - m_log.Error("[LOGIN]: Sending user to default region " + defaultHandle + " instead"); - regionInfo = GetRegionInfo(defaultHandle); - - // Customise the response - //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}]}}", - // (SimInfo.regionLocX * Constants.RegionSize), - // (SimInfo.regionLocY*Constants.RegionSize), - // theUser.HomeLocation.X, theUser.HomeLocation.Y, theUser.HomeLocation.Z, - // theUser.HomeLookAt.X, theUser.HomeLookAt.Y, theUser.HomeLookAt.Z); - theUser.CurrentAgent.Position = new Vector3(128,128,0); - response.StartLocation = "safe"; - - return PrepareLoginToRegion(regionInfo, theUser, response); - } - - protected RegionProfileData RequestClosestRegion(string region) - { - return m_regionProfileService.RequestSimProfileData(region, - m_config.GridServerURL, m_config.GridSendKey, m_config.GridRecvKey); - } - - protected RegionProfileData GetRegionInfo(ulong homeRegionHandle) - { - return m_regionProfileService.RequestSimProfileData(homeRegionHandle, - m_config.GridServerURL, m_config.GridSendKey, - m_config.GridRecvKey); - } - - protected RegionProfileData GetRegionInfo(UUID homeRegionId) - { - return m_regionProfileService.RequestSimProfileData(homeRegionId, - m_config.GridServerURL, m_config.GridSendKey, - m_config.GridRecvKey); - } - - /// - /// Add active gestures of the user to the login response. - /// - /// - /// A - /// - /// - /// A - /// - private void AddActiveGestures(LoginResponse response, UserProfileData theUser) - { - List gestures = m_inventoryService.GetActiveGestures(theUser.ID); - //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; - } - - /// - /// 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 - private bool PrepareLoginToRegion(RegionProfileData regionInfo, UserProfileData user, LoginResponse response) - { - try - { - response.SimAddress = Util.GetHostFromURL(regionInfo.serverURI).ToString(); - response.SimPort = uint.Parse(regionInfo.serverURI.Split(new char[] { '/', ':' })[4]); - response.RegionX = regionInfo.regionLocX; - response.RegionY = regionInfo.regionLocY; - - string capsPath = CapsUtil.GetRandomCapsObjectPath(); - - // Take off trailing / so that the caps path isn't //CAPS/someUUID - if (regionInfo.httpServerURI.EndsWith("/")) - regionInfo.httpServerURI = regionInfo.httpServerURI.Substring(0, regionInfo.httpServerURI.Length - 1); - response.SeedCapability = regionInfo.httpServerURI + CapsUtil.GetCapsSeedPath(capsPath); - - // 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.httpServerURI); - - // Update agent with target sim - user.CurrentAgent.Region = regionInfo.UUID; - user.CurrentAgent.Handle = regionInfo.regionHandle; - - // Prepare notification - Hashtable loginParams = new Hashtable(); - loginParams["session_id"] = user.CurrentAgent.SessionID.ToString(); - loginParams["secure_session_id"] = user.CurrentAgent.SecureSessionID.ToString(); - loginParams["firstname"] = user.FirstName; - loginParams["lastname"] = user.SurName; - loginParams["agent_id"] = user.ID.ToString(); - loginParams["circuit_code"] = (Int32) Convert.ToUInt32(response.CircuitCode); - loginParams["startpos_x"] = user.CurrentAgent.Position.X.ToString(); - loginParams["startpos_y"] = user.CurrentAgent.Position.Y.ToString(); - loginParams["startpos_z"] = user.CurrentAgent.Position.Z.ToString(); - loginParams["regionhandle"] = user.CurrentAgent.Handle.ToString(); - loginParams["caps_path"] = capsPath; - - // Get appearance - AvatarAppearance appearance = m_userManager.GetUserAppearance(user.ID); - if (appearance != null) - { - loginParams["appearance"] = appearance.ToHashTable(); - m_log.DebugFormat("[LOGIN]: Found appearance for {0} {1}", user.FirstName, user.SurName); - } - else - { - m_log.DebugFormat("[LOGIN]: Appearance not for {0} {1}. Creating default.", user.FirstName, user.SurName); - appearance = new AvatarAppearance(user.ID); - } - - ArrayList SendParams = new ArrayList(); - SendParams.Add(loginParams); - - // Send - XmlRpcRequest GridReq = new XmlRpcRequest("expect_user", SendParams); - XmlRpcResponse GridResp = GridReq.Send(regionInfo.httpServerURI, 6000); - - if (!GridResp.IsFault) - { - bool responseSuccess = true; - - if (GridResp.Value != null) - { - Hashtable resp = (Hashtable) GridResp.Value; - if (resp.ContainsKey("success")) - { - if ((string) resp["success"] == "FALSE") - { - responseSuccess = false; - } - } - } - if (responseSuccess) - { - handlerUserLoggedInAtLocation = OnUserLoggedInAtLocation; - if (handlerUserLoggedInAtLocation != null) - { - handlerUserLoggedInAtLocation(user.ID, user.CurrentAgent.SessionID, - user.CurrentAgent.Region, - user.CurrentAgent.Handle, - user.CurrentAgent.Position.X, - user.CurrentAgent.Position.Y, - user.CurrentAgent.Position.Z, - user.FirstName, user.SurName); - } - } - else - { - m_log.ErrorFormat("[LOGIN]: Region responded that it is not available to receive clients"); - return false; - } - } - else - { - m_log.ErrorFormat("[LOGIN]: XmlRpc request to region failed with message {0}, code {1} ", GridResp.FaultString, GridResp.FaultCode); - return false; - } - } - catch (Exception e) - { - m_log.ErrorFormat("[LOGIN]: Region not available for login, {0}", e); - return false; - } - - return true; - } - - // See LoginService - protected override InventoryData GetInventorySkeleton(UUID userID) - { - m_log.DebugFormat( - "[LOGIN]: Contacting inventory service at {0} for inventory skeleton of user {1}", - m_config.InventoryUrl, userID); - - List folders = m_inventoryService.GetInventorySkeleton(userID); - - if (null == folders || 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_inventoryService.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)); - } - m_log.InfoFormat("[LOGIN]: A new inventory skeleton was successfully created for user {0}", userID); - - folders = m_inventoryService.GetInventorySkeleton(userID); - } - - if (folders != null && folders.Count > 0) - { - UUID rootID = UUID.Zero; - ArrayList AgentInventoryArray = new ArrayList(); - Hashtable TempHash; - - foreach (InventoryFolderBase InvFolder in folders) - { -// m_log.DebugFormat("[LOGIN]: Received agent inventory folder {0}", InvFolder.name); - - 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); - } - throw new Exception( - String.Format( - "A root inventory folder for user {0} could not be retrieved from the inventory service", - userID)); - } - - public XmlRpcResponse XmlRPCSetLoginParams(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable) request.Params[0]; - UserProfileData userProfile; - Hashtable responseData = new Hashtable(); - - UUID uid; - string pass = requestData["password"].ToString(); - - if (!UUID.TryParse((string) requestData["avatar_uuid"], out uid)) - { - responseData["error"] = "No authorization"; - response.Value = responseData; - return response; - } - - userProfile = m_userManager.GetUserProfile(uid); - - if (userProfile == null || - (!AuthenticateUser(userProfile, pass)) || - userProfile.GodLevel < 200) - { - responseData["error"] = "No authorization"; - response.Value = responseData; - return response; - } - - if (requestData.ContainsKey("login_level")) - { - m_minLoginLevel = Convert.ToInt32(requestData["login_level"]); - } - - if (requestData.ContainsKey("login_motd")) - { - m_welcomeMessage = requestData["login_motd"].ToString(); - } - - response.Value = responseData; - return response; - } - - } -} diff --git a/OpenSim/Grid/UserServer/UserManager.cs b/OpenSim/Grid/UserServer/UserManager.cs deleted file mode 100644 index ca50421..0000000 --- a/OpenSim/Grid/UserServer/UserManager.cs +++ /dev/null @@ -1,686 +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 OpenSim 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 OpenSim.Framework; -using OpenSim.Framework.Communications; -using OpenSim.Framework.Servers; - -namespace OpenSim.Grid.UserServer -{ - public delegate void logOffUser(UUID AgentID); - - public class UserManager - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - public event logOffUser OnLogOffUser; - private logOffUser handlerLogOffUser; - - private UserDataBaseService m_userDataBaseService; - private BaseHttpServer m_httpServer; - - /// - /// - /// - /// - public UserManager( UserDataBaseService userDataBaseService) - { - m_userDataBaseService = userDataBaseService; - } - - public void Initialise() - { - - } - - public void PostInitialise() - { - - } - - public void RegisterHandlers(BaseHttpServer httpServer) - { - m_httpServer = httpServer; - - m_httpServer.AddXmlRPCHandler("get_user_by_name", XmlRPCGetUserMethodName); - m_httpServer.AddXmlRPCHandler("get_user_by_uuid", XmlRPCGetUserMethodUUID); - m_httpServer.AddXmlRPCHandler("get_avatar_picker_avatar", XmlRPCGetAvatarPickerAvatar); - - m_httpServer.AddXmlRPCHandler("update_user_current_region", XmlRPCAtRegion); - m_httpServer.AddXmlRPCHandler("logout_of_simulator", XmlRPCLogOffUserMethodUUID); - m_httpServer.AddXmlRPCHandler("get_agent_by_uuid", XmlRPCGetAgentMethodUUID); - m_httpServer.AddXmlRPCHandler("check_auth_session", XmlRPCCheckAuthSession); - - m_httpServer.AddXmlRPCHandler("update_user_profile", XmlRpcResponseXmlRPCUpdateUserProfile); - - m_httpServer.AddStreamHandler(new RestStreamHandler("DELETE", "/usersessions/", RestDeleteUserSessionMethod)); - } - - /// - /// Deletes an active agent session - /// - /// The request - /// The path (eg /bork/narf/test) - /// Parameters sent - /// HTTP request header object - /// HTTP response header object - /// Success "OK" else error - public string RestDeleteUserSessionMethod(string request, string path, string param, - OSHttpRequest httpRequest, OSHttpResponse httpResponse) - { - // TODO! Important! - - return "OK"; - } - - /// - /// Returns an error message that the user could not be found in the database - /// - /// XML string consisting of a error element containing individual error(s) - public XmlRpcResponse CreateUnknownUserErrorResponse() - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable responseData = new Hashtable(); - responseData["error_type"] = "unknown_user"; - responseData["error_desc"] = "The user requested is not in the database"; - - response.Value = responseData; - return response; - } - - public XmlRpcResponse AvatarPickerListtoXmlRPCResponse(UUID queryID, List returnUsers) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable responseData = new Hashtable(); - // Query Result Information - responseData["queryid"] = queryID.ToString(); - responseData["avcount"] = returnUsers.Count.ToString(); - - for (int i = 0; i < returnUsers.Count; i++) - { - responseData["avatarid" + i] = returnUsers[i].AvatarID.ToString(); - responseData["firstname" + i] = returnUsers[i].firstName; - responseData["lastname" + i] = returnUsers[i].lastName; - } - response.Value = responseData; - - return response; - } - - /// - /// Converts a user profile to an XML element which can be returned - /// - /// The user profile - /// A string containing an XML Document of the user profile - public XmlRpcResponse ProfileToXmlRPCResponse(UserProfileData profile) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable responseData = new Hashtable(); - - // Account information - responseData["firstname"] = profile.FirstName; - responseData["lastname"] = profile.SurName; - responseData["uuid"] = profile.ID.ToString(); - // Server Information - responseData["server_inventory"] = profile.UserInventoryURI; - responseData["server_asset"] = profile.UserAssetURI; - // Profile Information - responseData["profile_about"] = profile.AboutText; - responseData["profile_firstlife_about"] = profile.FirstLifeAboutText; - responseData["profile_firstlife_image"] = profile.FirstLifeImage.ToString(); - responseData["profile_can_do"] = profile.CanDoMask.ToString(); - responseData["profile_want_do"] = profile.WantDoMask.ToString(); - responseData["profile_image"] = profile.Image.ToString(); - responseData["profile_created"] = profile.Created.ToString(); - responseData["profile_lastlogin"] = profile.LastLogin.ToString(); - // Home region information - responseData["home_coordinates_x"] = profile.HomeLocation.X.ToString(); - responseData["home_coordinates_y"] = profile.HomeLocation.Y.ToString(); - responseData["home_coordinates_z"] = profile.HomeLocation.Z.ToString(); - - responseData["home_region"] = profile.HomeRegion.ToString(); - responseData["home_region_id"] = profile.HomeRegionID.ToString(); - - responseData["home_look_x"] = profile.HomeLookAt.X.ToString(); - responseData["home_look_y"] = profile.HomeLookAt.Y.ToString(); - responseData["home_look_z"] = profile.HomeLookAt.Z.ToString(); - - responseData["user_flags"] = profile.UserFlags.ToString(); - responseData["god_level"] = profile.GodLevel.ToString(); - responseData["custom_type"] = profile.CustomType; - responseData["partner"] = profile.Partner.ToString(); - response.Value = responseData; - - return response; - } - - #region XMLRPC User Methods - - public XmlRpcResponse XmlRPCGetAvatarPickerAvatar(XmlRpcRequest request) - { - // XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable) request.Params[0]; - List returnAvatar = new List(); - UUID queryID = new UUID(UUID.Zero.ToString()); - - if (requestData.Contains("avquery") && requestData.Contains("queryid")) - { - queryID = new UUID((string) requestData["queryid"]); - returnAvatar = m_userDataBaseService.GenerateAgentPickerRequestResponse(queryID, (string) requestData["avquery"]); - } - - m_log.InfoFormat("[AVATARINFO]: Servicing Avatar Query: " + (string) requestData["avquery"]); - return AvatarPickerListtoXmlRPCResponse(queryID, returnAvatar); - } - - public XmlRpcResponse XmlRPCAtRegion(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable) request.Params[0]; - Hashtable responseData = new Hashtable(); - string returnstring = "FALSE"; - - if (requestData.Contains("avatar_id") && requestData.Contains("region_handle") && - requestData.Contains("region_uuid")) - { - // ulong cregionhandle = 0; - UUID regionUUID; - UUID avatarUUID; - - UUID.TryParse((string) requestData["avatar_id"], out avatarUUID); - UUID.TryParse((string) requestData["region_uuid"], out regionUUID); - - if (avatarUUID != UUID.Zero) - { - UserProfileData userProfile = m_userDataBaseService.GetUserProfile(avatarUUID); - userProfile.CurrentAgent.Region = regionUUID; - userProfile.CurrentAgent.Handle = (ulong) Convert.ToInt64((string) requestData["region_handle"]); - //userProfile.CurrentAgent. - m_userDataBaseService.CommitAgent(ref userProfile); - //setUserProfile(userProfile); - - - returnstring = "TRUE"; - } - } - responseData.Add("returnString", returnstring); - response.Value = responseData; - return response; - } - - public XmlRpcResponse XmlRPCGetUserMethodName(XmlRpcRequest request) - { - // XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable) request.Params[0]; - UserProfileData userProfile; - if (requestData.Contains("avatar_name")) - { - string query = (string) requestData["avatar_name"]; - - // Regex objAlphaNumericPattern = new Regex("[^a-zA-Z0-9]"); - - string[] querysplit = query.Split(' '); - - if (querysplit.Length == 2) - { - userProfile = m_userDataBaseService.GetUserProfile(querysplit[0], querysplit[1]); - if (userProfile == null) - { - return CreateUnknownUserErrorResponse(); - } - } - else - { - return CreateUnknownUserErrorResponse(); - } - } - else - { - return CreateUnknownUserErrorResponse(); - } - - return ProfileToXmlRPCResponse(userProfile); - } - - public XmlRpcResponse XmlRPCGetUserMethodUUID(XmlRpcRequest request) - { - // XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable) request.Params[0]; - UserProfileData userProfile; - //CFK: this clogs the UserServer log and is not necessary at this time. - //CFK: m_log.Debug("METHOD BY UUID CALLED"); - if (requestData.Contains("avatar_uuid")) - { - try - { - UUID guess = new UUID((string) requestData["avatar_uuid"]); - - userProfile = m_userDataBaseService.GetUserProfile(guess); - } - catch (FormatException) - { - return CreateUnknownUserErrorResponse(); - } - - if (userProfile == null) - { - return CreateUnknownUserErrorResponse(); - } - } - else - { - return CreateUnknownUserErrorResponse(); - } - - return ProfileToXmlRPCResponse(userProfile); - } - - public XmlRpcResponse XmlRPCGetAgentMethodUUID(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable) request.Params[0]; - UserProfileData userProfile; - //CFK: this clogs the UserServer log and is not necessary at this time. - //CFK: m_log.Debug("METHOD BY UUID CALLED"); - if (requestData.Contains("avatar_uuid")) - { - UUID guess; - - UUID.TryParse((string) requestData["avatar_uuid"], out guess); - - if (guess == UUID.Zero) - { - return CreateUnknownUserErrorResponse(); - } - - userProfile = m_userDataBaseService.GetUserProfile(guess); - - if (userProfile == null) - { - return CreateUnknownUserErrorResponse(); - } - - // no agent??? - if (userProfile.CurrentAgent == null) - { - return CreateUnknownUserErrorResponse(); - } - Hashtable responseData = new Hashtable(); - - responseData["handle"] = userProfile.CurrentAgent.Handle.ToString(); - responseData["session"] = userProfile.CurrentAgent.SessionID.ToString(); - if (userProfile.CurrentAgent.AgentOnline) - responseData["agent_online"] = "TRUE"; - else - responseData["agent_online"] = "FALSE"; - - response.Value = responseData; - } - else - { - return CreateUnknownUserErrorResponse(); - } - - return response; - } - - public XmlRpcResponse XmlRPCCheckAuthSession(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable) request.Params[0]; - UserProfileData userProfile; - - 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 CreateUnknownUserErrorResponse(); - } - UUID.TryParse((string) requestData["session_id"], out guess_sid); - if (guess_sid == UUID.Zero) - { - return CreateUnknownUserErrorResponse(); - } - userProfile = m_userDataBaseService.GetUserProfile(guess_aid); - if (userProfile != null && userProfile.CurrentAgent != null && - userProfile.CurrentAgent.SessionID == guess_sid) - { - authed = "TRUE"; - } - m_log.InfoFormat("[UserManager]: CheckAuthSession TRUE for user {0}", guess_aid); - } - else - { - m_log.InfoFormat("[UserManager]: CheckAuthSession FALSE"); - return CreateUnknownUserErrorResponse(); - } - Hashtable responseData = new Hashtable(); - responseData["auth_session"] = authed; - response.Value = responseData; - return response; - } - - public XmlRpcResponse XmlRpcResponseXmlRPCUpdateUserProfile(XmlRpcRequest request) - { - m_log.Debug("[UserManager]: Got request to update user profile"); - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable) request.Params[0]; - Hashtable responseData = new Hashtable(); - - if (!requestData.Contains("avatar_uuid")) - { - return CreateUnknownUserErrorResponse(); - } - - UUID UserUUID = new UUID((string) requestData["avatar_uuid"]); - UserProfileData userProfile = m_userDataBaseService.GetUserProfile(UserUUID); - if (null == userProfile) - { - return CreateUnknownUserErrorResponse(); - } - // don't know how yet. - if (requestData.Contains("AllowPublish")) - { - } - if (requestData.Contains("FLImageID")) - { - userProfile.FirstLifeImage = new UUID((string) requestData["FLImageID"]); - } - if (requestData.Contains("ImageID")) - { - userProfile.Image = new UUID((string) requestData["ImageID"]); - } - // dont' know how yet - if (requestData.Contains("MaturePublish")) - { - } - if (requestData.Contains("AboutText")) - { - userProfile.AboutText = (string) requestData["AboutText"]; - } - if (requestData.Contains("FLAboutText")) - { - userProfile.FirstLifeAboutText = (string) requestData["FLAboutText"]; - } - // not in DB yet. - if (requestData.Contains("ProfileURL")) - { - } - if (requestData.Contains("home_region")) - { - try - { - userProfile.HomeRegion = Convert.ToUInt64((string) requestData["home_region"]); - } - catch (ArgumentException) - { - m_log.Error("[PROFILE]:Failed to set home region, Invalid Argument"); - } - catch (FormatException) - { - m_log.Error("[PROFILE]:Failed to set home region, Invalid Format"); - } - catch (OverflowException) - { - m_log.Error("[PROFILE]:Failed to set home region, Value was too large"); - } - } - if (requestData.Contains("home_region_id")) - { - UUID regionID; - UUID.TryParse((string) requestData["home_region_id"], out regionID); - userProfile.HomeRegionID = regionID; - } - if (requestData.Contains("home_pos_x")) - { - try - { - userProfile.HomeLocationX = (float) Convert.ToDecimal((string) requestData["home_pos_x"]); - } - catch (InvalidCastException) - { - m_log.Error("[PROFILE]:Failed to set home postion x"); - } - } - if (requestData.Contains("home_pos_y")) - { - try - { - userProfile.HomeLocationY = (float) Convert.ToDecimal((string) requestData["home_pos_y"]); - } - catch (InvalidCastException) - { - m_log.Error("[PROFILE]:Failed to set home postion y"); - } - } - if (requestData.Contains("home_pos_z")) - { - try - { - userProfile.HomeLocationZ = (float) Convert.ToDecimal((string) requestData["home_pos_z"]); - } - catch (InvalidCastException) - { - m_log.Error("[PROFILE]:Failed to set home postion z"); - } - } - if (requestData.Contains("home_look_x")) - { - try - { - userProfile.HomeLookAtX = (float) Convert.ToDecimal((string) requestData["home_look_x"]); - } - catch (InvalidCastException) - { - m_log.Error("[PROFILE]:Failed to set home lookat x"); - } - } - if (requestData.Contains("home_look_y")) - { - try - { - userProfile.HomeLookAtY = (float) Convert.ToDecimal((string) requestData["home_look_y"]); - } - catch (InvalidCastException) - { - m_log.Error("[PROFILE]:Failed to set home lookat y"); - } - } - if (requestData.Contains("home_look_z")) - { - try - { - userProfile.HomeLookAtZ = (float) Convert.ToDecimal((string) requestData["home_look_z"]); - } - catch (InvalidCastException) - { - m_log.Error("[PROFILE]:Failed to set home lookat z"); - } - } - if (requestData.Contains("user_flags")) - { - try - { - userProfile.UserFlags = Convert.ToInt32((string) requestData["user_flags"]); - } - catch (InvalidCastException) - { - m_log.Error("[PROFILE]:Failed to set user flags"); - } - } - if (requestData.Contains("god_level")) - { - try - { - userProfile.GodLevel = Convert.ToInt32((string) requestData["god_level"]); - } - catch (InvalidCastException) - { - m_log.Error("[PROFILE]:Failed to set god level"); - } - } - if (requestData.Contains("custom_type")) - { - try - { - userProfile.CustomType = (string) requestData["custom_type"]; - } - catch (InvalidCastException) - { - m_log.Error("[PROFILE]:Failed to set custom type"); - } - } - if (requestData.Contains("partner")) - { - try - { - userProfile.Partner = new UUID((string) requestData["partner"]); - } - catch (InvalidCastException) - { - m_log.Error("[PROFILE]:Failed to set partner"); - } - } - else - { - userProfile.Partner = UUID.Zero; - } - - // call plugin! - bool ret = m_userDataBaseService.UpdateUserProfile(userProfile); - responseData["returnString"] = ret.ToString(); - response.Value = responseData; - return response; - } - - public XmlRpcResponse XmlRPCLogOffUserMethodUUID(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable) request.Params[0]; - - if (requestData.Contains("avatar_uuid")) - { - try - { - UUID userUUID = new UUID((string)requestData["avatar_uuid"]); - UUID RegionID = new UUID((string)requestData["region_uuid"]); - ulong regionhandle = (ulong)Convert.ToInt64((string)requestData["region_handle"]); - Vector3 position = new Vector3( - (float)Convert.ToDecimal((string)requestData["region_pos_x"]), - (float)Convert.ToDecimal((string)requestData["region_pos_y"]), - (float)Convert.ToDecimal((string)requestData["region_pos_z"])); - Vector3 lookat = new Vector3( - (float)Convert.ToDecimal((string)requestData["lookat_x"]), - (float)Convert.ToDecimal((string)requestData["lookat_y"]), - (float)Convert.ToDecimal((string)requestData["lookat_z"])); - - handlerLogOffUser = OnLogOffUser; - if (handlerLogOffUser != null) - handlerLogOffUser(userUUID); - - m_userDataBaseService.LogOffUser(userUUID, RegionID, regionhandle, position, lookat); - } - catch (FormatException) - { - m_log.Warn("[LOGOUT]: Error in Logout XMLRPC Params"); - return response; - } - } - else - { - return CreateUnknownUserErrorResponse(); - } - - return response; - } - - #endregion - - - public void HandleAgentLocation(UUID agentID, UUID regionID, ulong regionHandle) - { - UserProfileData userProfile = m_userDataBaseService.GetUserProfile(agentID); - if (userProfile != null) - { - userProfile.CurrentAgent.Region = regionID; - userProfile.CurrentAgent.Handle = regionHandle; - m_userDataBaseService.CommitAgent(ref userProfile); - } - } - - public void HandleAgentLeaving(UUID agentID, UUID regionID, ulong regionHandle) - { - UserProfileData userProfile = m_userDataBaseService.GetUserProfile(agentID); - if (userProfile != null) - { - if (userProfile.CurrentAgent.Region == regionID) - { - UserAgentData userAgent = userProfile.CurrentAgent; - if (userAgent != null && userAgent.AgentOnline) - { - userAgent.AgentOnline = false; - userAgent.LogoutTime = Util.UnixTimeSinceEpoch(); - if (regionID != UUID.Zero) - { - userAgent.Region = regionID; - } - userAgent.Handle = regionHandle; - userProfile.LastLogin = userAgent.LogoutTime; - - m_userDataBaseService.CommitAgent(ref userProfile); - - handlerLogOffUser = OnLogOffUser; - if (handlerLogOffUser != null) - handlerLogOffUser(agentID); - } - } - } - } - - public void HandleRegionStartup(UUID regionID) - { - m_userDataBaseService.LogoutUsers(regionID); - } - - public void HandleRegionShutdown(UUID regionID) - { - m_userDataBaseService.LogoutUsers(regionID); - } - } -} diff --git a/OpenSim/Grid/UserServer/UserServerAvatarAppearanceModule.cs b/OpenSim/Grid/UserServer/UserServerAvatarAppearanceModule.cs deleted file mode 100644 index 28ac2dc..0000000 --- a/OpenSim/Grid/UserServer/UserServerAvatarAppearanceModule.cs +++ /dev/null @@ -1,124 +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 OpenSim 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 OpenSim.Framework; -using OpenSim.Framework.Communications; -using OpenSim.Framework.Servers; - -namespace OpenSim.Grid.UserServer -{ - public class UserServerAvatarAppearanceModule - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private UserDataBaseService m_userDataBaseService; - private BaseHttpServer m_httpServer; - - public UserServerAvatarAppearanceModule(UserDataBaseService userDataBaseService) - { - m_userDataBaseService = userDataBaseService; - } - - public void Initialise() - { - - } - - public void PostInitialise() - { - - } - - public void RegisterHandlers(BaseHttpServer httpServer) - { - m_httpServer = httpServer; - - m_httpServer.AddXmlRPCHandler("get_avatar_appearance", XmlRPCGetAvatarAppearance); - m_httpServer.AddXmlRPCHandler("update_avatar_appearance", XmlRPCUpdateAvatarAppearance); - } - - public XmlRpcResponse XmlRPCGetAvatarAppearance(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable)request.Params[0]; - AvatarAppearance appearance; - Hashtable responseData; - if (requestData.Contains("owner")) - { - appearance = m_userDataBaseService.GetUserAppearance(new UUID((string)requestData["owner"])); - if (appearance == null) - { - responseData = new Hashtable(); - responseData["error_type"] = "no appearance"; - responseData["error_desc"] = "There was no appearance found for this avatar"; - } - else - { - responseData = appearance.ToHashTable(); - } - } - else - { - responseData = new Hashtable(); - responseData["error_type"] = "unknown_avatar"; - responseData["error_desc"] = "The avatar appearance requested is not in the database"; - } - - response.Value = responseData; - return response; - } - - public XmlRpcResponse XmlRPCUpdateAvatarAppearance(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable)request.Params[0]; - Hashtable responseData; - if (requestData.Contains("owner")) - { - AvatarAppearance appearance = new AvatarAppearance(requestData); - m_userDataBaseService.UpdateUserAppearance(new UUID((string)requestData["owner"]), appearance); - responseData = new Hashtable(); - responseData["returnString"] = "TRUE"; - } - else - { - responseData = new Hashtable(); - responseData["error_type"] = "unknown_avatar"; - responseData["error_desc"] = "The avatar appearance requested is not in the database"; - } - response.Value = responseData; - return response; - } - } -} diff --git a/OpenSim/Grid/UserServer/UserServerCommandModule.cs b/OpenSim/Grid/UserServer/UserServerCommandModule.cs new file mode 100644 index 0000000..fbdd73f --- /dev/null +++ b/OpenSim/Grid/UserServer/UserServerCommandModule.cs @@ -0,0 +1,349 @@ +/* + * 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 OpenSim 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.Reflection; +using log4net; +using log4net.Config; +using OpenMetaverse; +using OpenSim.Data; +using OpenSim.Framework; +using OpenSim.Framework.Communications; +using OpenSim.Framework.Communications.Cache; +using OpenSim.Framework.Console; +using OpenSim.Framework.Servers; +using OpenSim.Framework.Statistics; +using OpenSim.Grid.Communications.OGS1; +using OpenSim.Grid.Framework; +using OpenSim.Grid.UserServer.Modules; + +namespace OpenSim.Grid.UserServer +{ + public class UserServerCommandModule + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + protected ConsoleBase m_console; + protected UserConfig Cfg; + + protected UserDataBaseService m_userDataBaseService; + protected UserLoginService m_loginService; + + private UUID m_lastCreatedUser = UUID.Random(); + + public UserServerCommandModule(ConsoleBase console, UserConfig cfg, UserDataBaseService userDBservice, UserLoginService loginService) + { + m_console = console; + Cfg = cfg; + m_userDataBaseService = userDBservice; + m_loginService = loginService; + } + + public virtual void RegisterConsoleCommands() + { + m_console.Commands.AddCommand("userserver", false, "create user", + "create user [ [ [ [email]]]]", + "Create a new user account", RunCommand); + + m_console.Commands.AddCommand("userserver", false, "reset user password", + "reset user password [ [ []]]", + "Reset a user's password", RunCommand); + + m_console.Commands.AddCommand("userserver", false, "login level", + "login level ", + "Set the minimum user level to log in", HandleLoginCommand); + + m_console.Commands.AddCommand("userserver", false, "login reset", + "login reset", + "Reset the login level to allow all users", + HandleLoginCommand); + + m_console.Commands.AddCommand("userserver", false, "login text", + "login text ", + "Set the text users will see on login", HandleLoginCommand); + + m_console.Commands.AddCommand("userserver", false, "test-inventory", + "test-inventory", + "Perform a test inventory transaction", RunCommand); + + m_console.Commands.AddCommand("userserver", false, "logoff-user", + "logoff-user ", + "Log off a named user", RunCommand); + + m_console.Commands.AddCommand("userserver", false, "test-command", + "test-command", + "test command", HandleTestCommand); + } + + #region Console Command Handlers + public void do_create(string[] args) + { + switch (args[0]) + { + case "user": + CreateUser(args); + break; + } + } + + /// + /// Execute switch for some of the reset commands + /// + /// + protected void Reset(string[] args) + { + if (args.Length == 0) + return; + + switch (args[0]) + { + case "user": + + switch (args[1]) + { + case "password": + ResetUserPassword(args); + break; + } + + break; + } + } + + /// + /// Create a new user + /// + /// string array with parameters: firstname, lastname, password, locationX, locationY, email + protected void CreateUser(string[] cmdparams) + { + string firstName; + string lastName; + string password; + string email; + uint regX = 1000; + uint regY = 1000; + + if (cmdparams.Length < 2) + firstName = MainConsole.Instance.CmdPrompt("First name", "Default"); + else firstName = cmdparams[1]; + + if (cmdparams.Length < 3) + lastName = MainConsole.Instance.CmdPrompt("Last name", "User"); + else lastName = cmdparams[2]; + + if (cmdparams.Length < 4) + password = MainConsole.Instance.PasswdPrompt("Password"); + else password = cmdparams[3]; + + if (cmdparams.Length < 5) + regX = Convert.ToUInt32(MainConsole.Instance.CmdPrompt("Start Region X", regX.ToString())); + else regX = Convert.ToUInt32(cmdparams[4]); + + if (cmdparams.Length < 6) + regY = Convert.ToUInt32(MainConsole.Instance.CmdPrompt("Start Region Y", regY.ToString())); + else regY = Convert.ToUInt32(cmdparams[5]); + + if (cmdparams.Length < 7) + email = MainConsole.Instance.CmdPrompt("Email", ""); + else email = cmdparams[6]; + + if (null == m_userDataBaseService.GetUserProfile(firstName, lastName)) + { + m_lastCreatedUser = m_userDataBaseService.AddUser(firstName, lastName, password, email, regX, regY); + } + else + { + m_log.ErrorFormat("[USERS]: A user with the name {0} {1} already exists!", firstName, lastName); + } + } + + /// + /// Reset a user password. + /// + /// + private void ResetUserPassword(string[] cmdparams) + { + string firstName; + string lastName; + string newPassword; + + if (cmdparams.Length < 3) + firstName = MainConsole.Instance.CmdPrompt("First name"); + else firstName = cmdparams[2]; + + if (cmdparams.Length < 4) + lastName = MainConsole.Instance.CmdPrompt("Last name"); + else lastName = cmdparams[3]; + + if (cmdparams.Length < 5) + newPassword = MainConsole.Instance.PasswdPrompt("New password"); + else newPassword = cmdparams[4]; + + m_userDataBaseService.ResetUserPassword(firstName, lastName, newPassword); + } + + private void HandleTestCommand(string module, string[] cmd) + { + m_log.Info("test command received"); + } + + private void HandleLoginCommand(string module, string[] cmd) + { + string subcommand = cmd[1]; + + switch (subcommand) + { + case "level": + // Set the minimal level to allow login + // Useful to allow grid update without worrying about users. + // or fixing critical issues + // + if (cmd.Length > 2) + { + int level = Convert.ToInt32(cmd[2]); + m_loginService.setloginlevel(level); + } + break; + case "reset": + m_loginService.setloginlevel(0); + break; + case "text": + if (cmd.Length > 2) + { + m_loginService.setwelcometext(cmd[2]); + } + break; + } + } + + public void RunCommand(string module, string[] cmd) + { + List args = new List(cmd); + string command = cmd[0]; + + args.RemoveAt(0); + + string[] cmdparams = args.ToArray(); + + switch (command) + { + case "create": + do_create(cmdparams); + break; + + case "reset": + Reset(cmdparams); + break; + + + case "test-inventory": + // RestObjectPosterResponse> requester = new RestObjectPosterResponse>(); + // requester.ReturnResponseVal = TestResponse; + // requester.BeginPostObject(m_userManager._config.InventoryUrl + "RootFolders/", m_lastCreatedUser); + SynchronousRestObjectPoster.BeginPostObject>( + "POST", Cfg.InventoryUrl + "RootFolders/", m_lastCreatedUser); + break; + + case "logoff-user": + if (cmdparams.Length >= 3) + { + string firstname = cmdparams[0]; + string lastname = cmdparams[1]; + string message = ""; + + for (int i = 2; i < cmdparams.Length; i++) + message += " " + cmdparams[i]; + + UserProfileData theUser = null; + try + { + theUser = m_loginService.GetTheUser(firstname, lastname); + } + catch (Exception) + { + m_log.Error("[LOGOFF]: Error getting user data from the database."); + } + + if (theUser != null) + { + if (theUser.CurrentAgent != null) + { + if (theUser.CurrentAgent.AgentOnline) + { + m_log.Info("[LOGOFF]: Logging off requested user!"); + m_loginService.LogOffUser(theUser, message); + + theUser.CurrentAgent.AgentOnline = false; + + m_loginService.CommitAgent(ref theUser); + } + else + { + m_log.Info( + "[LOGOFF]: User Doesn't appear to be online, sending the logoff message anyway."); + m_loginService.LogOffUser(theUser, message); + + theUser.CurrentAgent.AgentOnline = false; + + m_loginService.CommitAgent(ref theUser); + } + } + else + { + m_log.Error( + "[LOGOFF]: Unable to logoff-user. User doesn't have an agent record so I can't find the simulator to notify"); + } + } + else + { + m_log.Info("[LOGOFF]: User doesn't exist in the database"); + } + } + else + { + m_log.Error( + "[LOGOFF]: Invalid amount of parameters. logoff-user takes at least three. Firstname, Lastname, and message"); + } + + break; + } + } + + public virtual void ShowHelp(string[] helpArgs) + { + m_console.Notice("create user - create a new user"); + m_console.Notice("logoff-user - logs off the specified user from the grid"); + m_console.Notice("reset user password - reset a user's password."); + m_console.Notice("login-level - Set the miminim userlevel allowed To login."); + m_console.Notice("login-reset - reset the login level to its default value."); + m_console.Notice("login-text "); + } + } + #endregion +} diff --git a/OpenSim/Grid/UserServer/UserServerFriendsModule.cs b/OpenSim/Grid/UserServer/UserServerFriendsModule.cs deleted file mode 100644 index 4a3efe0..0000000 --- a/OpenSim/Grid/UserServer/UserServerFriendsModule.cs +++ /dev/null @@ -1,173 +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 OpenSim 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 OpenSim.Framework; -using OpenSim.Framework.Communications; -using OpenSim.Framework.Servers; - -namespace OpenSim.Grid.UserServer -{ - public class UserServerFriendsModule - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private UserDataBaseService m_userDataBaseService; - - private BaseHttpServer m_httpServer; - - public UserServerFriendsModule(UserDataBaseService userDataBaseService) - { - m_userDataBaseService = userDataBaseService; - } - - public void Initialise() - { - - } - - public void PostInitialise() - { - - } - - public void RegisterHandlers(BaseHttpServer httpServer) - { - m_httpServer = httpServer; - - m_httpServer.AddXmlRPCHandler("add_new_user_friend", XmlRpcResponseXmlRPCAddUserFriend); - m_httpServer.AddXmlRPCHandler("remove_user_friend", XmlRpcResponseXmlRPCRemoveUserFriend); - m_httpServer.AddXmlRPCHandler("update_user_friend_perms", XmlRpcResponseXmlRPCUpdateUserFriendPerms); - m_httpServer.AddXmlRPCHandler("get_user_friend_list", XmlRpcResponseXmlRPCGetUserFriendList); - } - - public XmlRpcResponse FriendListItemListtoXmlRPCResponse(List returnUsers) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable responseData = new Hashtable(); - // Query Result Information - - responseData["avcount"] = returnUsers.Count.ToString(); - - for (int i = 0; i < returnUsers.Count; i++) - { - responseData["ownerID" + i] = returnUsers[i].FriendListOwner.ToString(); - responseData["friendID" + i] = returnUsers[i].Friend.ToString(); - responseData["ownerPerms" + i] = returnUsers[i].FriendListOwnerPerms.ToString(); - responseData["friendPerms" + i] = returnUsers[i].FriendPerms.ToString(); - } - response.Value = responseData; - - return response; - } - - public XmlRpcResponse XmlRpcResponseXmlRPCAddUserFriend(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable)request.Params[0]; - Hashtable responseData = new Hashtable(); - string returnString = "FALSE"; - // Query Result Information - - if (requestData.Contains("ownerID") && requestData.Contains("friendID") && - requestData.Contains("friendPerms")) - { - // UserManagerBase.AddNewuserFriend - m_userDataBaseService.AddNewUserFriend(new UUID((string)requestData["ownerID"]), - new UUID((string)requestData["friendID"]), - (uint)Convert.ToInt32((string)requestData["friendPerms"])); - returnString = "TRUE"; - } - responseData["returnString"] = returnString; - response.Value = responseData; - return response; - } - - public XmlRpcResponse XmlRpcResponseXmlRPCRemoveUserFriend(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable)request.Params[0]; - Hashtable responseData = new Hashtable(); - string returnString = "FALSE"; - // Query Result Information - - if (requestData.Contains("ownerID") && requestData.Contains("friendID")) - { - // UserManagerBase.AddNewuserFriend - m_userDataBaseService.RemoveUserFriend(new UUID((string)requestData["ownerID"]), - new UUID((string)requestData["friendID"])); - returnString = "TRUE"; - } - responseData["returnString"] = returnString; - response.Value = responseData; - return response; - } - - public XmlRpcResponse XmlRpcResponseXmlRPCUpdateUserFriendPerms(XmlRpcRequest request) - { - XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable)request.Params[0]; - Hashtable responseData = new Hashtable(); - string returnString = "FALSE"; - - if (requestData.Contains("ownerID") && requestData.Contains("friendID") && - requestData.Contains("friendPerms")) - { - m_userDataBaseService.UpdateUserFriendPerms(new UUID((string)requestData["ownerID"]), - new UUID((string)requestData["friendID"]), - (uint)Convert.ToInt32((string)requestData["friendPerms"])); - // UserManagerBase. - returnString = "TRUE"; - } - responseData["returnString"] = returnString; - response.Value = responseData; - return response; - } - - public XmlRpcResponse XmlRpcResponseXmlRPCGetUserFriendList(XmlRpcRequest request) - { - // XmlRpcResponse response = new XmlRpcResponse(); - Hashtable requestData = (Hashtable)request.Params[0]; - // Hashtable responseData = new Hashtable(); - - List returndata = new List(); - - if (requestData.Contains("ownerID")) - { - returndata = m_userDataBaseService.GetUserFriendList(new UUID((string)requestData["ownerID"])); - } - - return FriendListItemListtoXmlRPCResponse(returndata); - } - } -} -- cgit v1.1