From bb171717ceaef37b022a135209c2e0bf031d21f9 Mon Sep 17 00:00:00 2001 From: Diva Canto Date: Sun, 21 Feb 2010 15:38:52 -0800 Subject: Deleted obsolete files in the Data layer. Compiles. --- OpenSim/Data/DataPluginFactory.cs | 155 --- OpenSim/Data/GridDataBase.cs | 52 - OpenSim/Data/IGridData.cs | 134 --- OpenSim/Data/ILogData.cs | 87 -- OpenSim/Data/IRegionProfileService.cs | 100 -- OpenSim/Data/IUserData.cs | 209 ---- OpenSim/Data/MSSQL/MSSQLGridData.cs | 587 --------- OpenSim/Data/MSSQL/MSSQLLogData.cs | 146 --- OpenSim/Data/MSSQL/MSSQLUserData.cs | 1214 ------------------- OpenSim/Data/MySQL/MySQLGridData.cs | 422 ------- OpenSim/Data/MySQL/MySQLLogData.cs | 166 --- OpenSim/Data/MySQL/MySQLManager.cs | 1248 ------------------- OpenSim/Data/MySQL/MySQLSuperManager.cs | 52 - OpenSim/Data/MySQL/MySQLUserData.cs | 766 ------------ OpenSim/Data/MySQL/Tests/MySQLAssetTest.cs | 22 +- OpenSim/Data/MySQL/Tests/MySQLEstateTest.cs | 54 +- OpenSim/Data/MySQL/Tests/MySQLGridTest.cs | 94 -- OpenSim/Data/MySQL/Tests/MySQLInventoryTest.cs | 30 +- OpenSim/Data/MySQL/Tests/MySQLRegionTest.cs | 53 +- OpenSim/Data/MySQL/Tests/MySQLUserTest.cs | 85 -- OpenSim/Data/RegionProfileData.cs | 337 ------ OpenSim/Data/RegionProfileServiceProxy.cs | 119 -- OpenSim/Data/ReservationData.cs | 48 - OpenSim/Data/SQLite/SQLiteGridData.cs | 286 ----- OpenSim/Data/SQLite/SQLiteManager.cs | 225 ---- OpenSim/Data/SQLite/SQLiteUserData.cs | 1262 -------------------- OpenSim/Data/SQLite/Tests/SQLiteUserTest.cs | 64 - OpenSim/Data/Tests/BasicGridTest.cs | 173 --- OpenSim/Data/Tests/BasicUserTest.cs | 703 ----------- OpenSim/Data/UserDataBase.cs | 91 -- .../Communications/TemporaryUserProfilePlugin.cs | 104 -- OpenSim/Tests/Common/Mock/TestUserDataPlugin.cs | 216 ---- 32 files changed, 103 insertions(+), 9201 deletions(-) delete mode 100644 OpenSim/Data/DataPluginFactory.cs delete mode 100644 OpenSim/Data/GridDataBase.cs delete mode 100644 OpenSim/Data/IGridData.cs delete mode 100644 OpenSim/Data/ILogData.cs delete mode 100644 OpenSim/Data/IRegionProfileService.cs delete mode 100644 OpenSim/Data/IUserData.cs delete mode 100644 OpenSim/Data/MSSQL/MSSQLGridData.cs delete mode 100644 OpenSim/Data/MSSQL/MSSQLLogData.cs delete mode 100644 OpenSim/Data/MSSQL/MSSQLUserData.cs delete mode 100644 OpenSim/Data/MySQL/MySQLGridData.cs delete mode 100644 OpenSim/Data/MySQL/MySQLLogData.cs delete mode 100644 OpenSim/Data/MySQL/MySQLManager.cs delete mode 100644 OpenSim/Data/MySQL/MySQLSuperManager.cs delete mode 100644 OpenSim/Data/MySQL/MySQLUserData.cs delete mode 100644 OpenSim/Data/MySQL/Tests/MySQLGridTest.cs delete mode 100644 OpenSim/Data/MySQL/Tests/MySQLUserTest.cs delete mode 100644 OpenSim/Data/RegionProfileData.cs delete mode 100644 OpenSim/Data/RegionProfileServiceProxy.cs delete mode 100644 OpenSim/Data/ReservationData.cs delete mode 100644 OpenSim/Data/SQLite/SQLiteGridData.cs delete mode 100644 OpenSim/Data/SQLite/SQLiteManager.cs delete mode 100644 OpenSim/Data/SQLite/SQLiteUserData.cs delete mode 100644 OpenSim/Data/SQLite/Tests/SQLiteUserTest.cs delete mode 100644 OpenSim/Data/Tests/BasicGridTest.cs delete mode 100644 OpenSim/Data/Tests/BasicUserTest.cs delete mode 100644 OpenSim/Data/UserDataBase.cs delete mode 100644 OpenSim/Framework/Communications/TemporaryUserProfilePlugin.cs delete mode 100644 OpenSim/Tests/Common/Mock/TestUserDataPlugin.cs (limited to 'OpenSim') diff --git a/OpenSim/Data/DataPluginFactory.cs b/OpenSim/Data/DataPluginFactory.cs deleted file mode 100644 index 841f71e..0000000 --- a/OpenSim/Data/DataPluginFactory.cs +++ /dev/null @@ -1,155 +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 OpenSim.Framework; - -namespace OpenSim.Data -{ - /// - /// A static class containing methods for obtaining handles to database - /// storage objects. - /// - public static class DataPluginFactory - { - /// - /// Based on , returns the appropriate - /// PluginInitialiserBase instance in and - /// extension point path in . - /// - /// - /// The DB connection string used when creating a new - /// PluginInitialiserBase, returned in . - /// - /// - /// A reference to a PluginInitialiserBase object in which the proper - /// initialiser will be returned. - /// - /// - /// A string in which the proper extension point path will be returned. - /// - /// - /// The type of data plugin requested. - /// - /// - /// Thrown if is not one of the expected data - /// interfaces. - /// - private static void PluginLoaderParamFactory(string connect, out PluginInitialiserBase init, out string path) where T : IPlugin - { - Type type = typeof(T); - - if (type == typeof(IInventoryDataPlugin)) - { - init = new InventoryDataInitialiser(connect); - path = "/OpenSim/InventoryData"; - } - else if (type == typeof(IUserDataPlugin)) - { - init = new UserDataInitialiser(connect); - path = "/OpenSim/UserData"; - } - else if (type == typeof(IGridDataPlugin)) - { - init = new GridDataInitialiser(connect); - path = "/OpenSim/GridData"; - } - else if (type == typeof(ILogDataPlugin)) - { - init = new LogDataInitialiser(connect); - path = "/OpenSim/LogData"; - } - else if (type == typeof(IAssetDataPlugin)) - { - init = new AssetDataInitialiser(connect); - path = "/OpenSim/AssetData"; - } - else - { - // We don't support this data plugin. - throw new NotImplementedException(String.Format("The type '{0}' is not a valid data plugin.", type)); - } - } - - /// - /// Returns a list of new data plugins. - /// Plugins will be requested in the order they were added. - /// - /// - /// The filename of the inventory server plugin DLL. - /// - /// - /// The connection string for the storage backend. - /// - /// - /// The type of data plugin requested. - /// - /// - /// A list of all loaded plugins matching . - /// - public static List LoadDataPlugins(string provider, string connect) where T : IPlugin - { - PluginInitialiserBase pluginInitialiser; - string extensionPointPath; - - PluginLoaderParamFactory(connect, out pluginInitialiser, out extensionPointPath); - - using (PluginLoader loader = new PluginLoader(pluginInitialiser)) - { - // loader will try to load all providers (MySQL, MSSQL, etc) - // unless it is constrainted to the correct "Provider" entry in the addin.xml - loader.Add(extensionPointPath, new PluginProviderFilter(provider)); - loader.Load(); - - return loader.Plugins; - } - } - - /// - /// Returns a new data plugin instance if - /// only one was loaded, otherwise returns null (default(T)). - /// - /// - /// The filename of the inventory server plugin DLL. - /// - /// - /// The connection string for the storage backend. - /// - /// - /// The type of data plugin requested. - /// - /// - /// A list of all loaded plugins matching . - /// - public static T LoadDataPlugin(string provider, string connect) where T : IPlugin - { - List plugins = LoadDataPlugins(provider, connect); - return (plugins.Count == 1) ? plugins[0] : default(T); - } - } -} diff --git a/OpenSim/Data/GridDataBase.cs b/OpenSim/Data/GridDataBase.cs deleted file mode 100644 index a03488b..0000000 --- a/OpenSim/Data/GridDataBase.cs +++ /dev/null @@ -1,52 +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.Collections.Generic; -using OpenMetaverse; - -namespace OpenSim.Data -{ - public abstract class GridDataBase : IGridDataPlugin - { - public abstract RegionProfileData GetProfileByHandle(ulong regionHandle); - public abstract RegionProfileData GetProfileByUUID(UUID UUID); - public abstract RegionProfileData GetProfileByString(string regionName); - public abstract RegionProfileData[] GetProfilesInRange(uint Xmin, uint Ymin, uint Xmax, uint Ymax); - public abstract List GetRegionsByName(string namePrefix, uint maxNum); - public abstract bool AuthenticateSim(UUID UUID, ulong regionHandle, string simrecvkey); - public abstract DataResponse StoreProfile(RegionProfileData profile); - public abstract ReservationData GetReservationAtPoint(uint x, uint y); - public abstract DataResponse DeleteProfile(string uuid); - - public abstract void Initialise(); - public abstract void Initialise(string connect); - public abstract void Dispose(); - - public abstract string Name { get; } - public abstract string Version { get; } - } -} diff --git a/OpenSim/Data/IGridData.cs b/OpenSim/Data/IGridData.cs deleted file mode 100644 index 8bd3811..0000000 --- a/OpenSim/Data/IGridData.cs +++ /dev/null @@ -1,134 +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.Collections.Generic; -using OpenMetaverse; -using OpenSim.Framework; - -namespace OpenSim.Data -{ - public enum DataResponse - { - RESPONSE_OK, - RESPONSE_AUTHREQUIRED, - RESPONSE_INVALIDCREDENTIALS, - RESPONSE_ERROR - } - - /// - /// A standard grid interface - /// - public interface IGridDataPlugin : IPlugin - { - /// - /// Initialises the interface - /// - void Initialise(string connect); - - /// - /// Returns a sim profile from a regionHandle - /// - /// A 64bit Region Handle - /// A simprofile - RegionProfileData GetProfileByHandle(ulong regionHandle); - - /// - /// Returns a sim profile from a UUID - /// - /// A 128bit UUID - /// A sim profile - RegionProfileData GetProfileByUUID(UUID UUID); - - /// - /// Returns a sim profile from a string match - /// - /// A string for a partial region name match - /// A sim profile - RegionProfileData GetProfileByString(string regionName); - - /// - /// Returns all profiles within the specified range - /// - /// Minimum sim coordinate (X) - /// Minimum sim coordinate (Y) - /// Maximum sim coordinate (X) - /// Maximum sim coordinate (Y) - /// An array containing all the sim profiles in the specified range - RegionProfileData[] GetProfilesInRange(uint Xmin, uint Ymin, uint Xmax, uint Ymax); - - /// - /// Returns up to maxNum profiles of regions that have a name starting with namePrefix - /// - /// The name to match against - /// Maximum number of profiles to return - /// A list of sim profiles - List GetRegionsByName(string namePrefix, uint maxNum); - - /// - /// Authenticates a sim by use of its recv key. - /// WARNING: Insecure - /// - /// The UUID sent by the sim - /// The regionhandle sent by the sim - /// The receiving key sent by the sim - /// Whether the sim has been authenticated - bool AuthenticateSim(UUID UUID, ulong regionHandle, string simrecvkey); - - /// - /// Adds or updates a profile in the database - /// - /// The profile to add - /// RESPONSE_OK if successful, error if not. - DataResponse StoreProfile(RegionProfileData profile); - - /// - /// Remove a profile from the database - /// - /// ID of profile to remove - /// - DataResponse DeleteProfile(string UUID); - - /// - /// Function not used???? - /// - /// - /// - /// - ReservationData GetReservationAtPoint(uint x, uint y); - } - - public class GridDataInitialiser : PluginInitialiserBase - { - private string connect; - public GridDataInitialiser (string s) { connect = s; } - public override void Initialise (IPlugin plugin) - { - IGridDataPlugin p = plugin as IGridDataPlugin; - p.Initialise (connect); - } - } -} diff --git a/OpenSim/Data/ILogData.cs b/OpenSim/Data/ILogData.cs deleted file mode 100644 index 97ca1cc..0000000 --- a/OpenSim/Data/ILogData.cs +++ /dev/null @@ -1,87 +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 OpenSim.Framework; - -namespace OpenSim.Data -{ - /// - /// The severity of an individual log message - /// - public enum LogSeverity : int - { - /// - /// Critical: systems failure - /// - CRITICAL = 1, - /// - /// Major: warning prior to systems failure - /// - MAJOR = 2, - /// - /// Medium: an individual non-critical task failed - /// - MEDIUM = 3, - /// - /// Low: Informational warning - /// - LOW = 4, - /// - /// Info: Information - /// - INFO = 5, - /// - /// Verbose: Debug Information - /// - VERBOSE = 6 - } - - /// - /// An interface to a LogData storage system - /// - public interface ILogDataPlugin : IPlugin - { - void saveLog(string serverDaemon, string target, string methodCall, string arguments, int priority, - string logMessage); - - /// - /// Initialises the interface - /// - void Initialise(string connect); - } - - public class LogDataInitialiser : PluginInitialiserBase - { - private string connect; - public LogDataInitialiser (string s) { connect = s; } - public override void Initialise (IPlugin plugin) - { - ILogDataPlugin p = plugin as ILogDataPlugin; - p.Initialise (connect); - } - } -} diff --git a/OpenSim/Data/IRegionProfileService.cs b/OpenSim/Data/IRegionProfileService.cs deleted file mode 100644 index b3acc52..0000000 --- a/OpenSim/Data/IRegionProfileService.cs +++ /dev/null @@ -1,100 +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 OpenMetaverse; - -namespace OpenSim.Data -{ - public interface IRegionProfileService - { - /// - /// Returns a region by argument - /// - /// A UUID key of the region to return - /// A SimProfileData for the region - RegionProfileData GetRegion(UUID uuid); - - /// - /// Returns a region by argument - /// - /// A regionHandle of the region to return - /// A SimProfileData for the region - RegionProfileData GetRegion(ulong handle); - - /// - /// Returns a region by argument - /// - /// A partial regionName of the region to return - /// A SimProfileData for the region - RegionProfileData GetRegion(string regionName); - - List GetRegions(uint xmin, uint ymin, uint xmax, uint ymax); - List GetRegions(string name, int maxNum); - DataResponse AddUpdateRegion(RegionProfileData sim, RegionProfileData existingSim); - DataResponse DeleteRegion(string uuid); - } - - public interface IRegionProfileRouter - { - /// - /// Request sim profile information from a grid server, by Region UUID - /// - /// The region UUID to look for - /// - /// - /// - /// The sim profile. Null if there was a request failure - /// This method should be statics - RegionProfileData RequestSimProfileData(UUID regionId, Uri gridserverUrl, - string gridserverSendkey, string gridserverRecvkey); - - /// - /// Request sim profile information from a grid server, by Region Handle - /// - /// the region handle to look for - /// - /// - /// - /// The sim profile. Null if there was a request failure - RegionProfileData RequestSimProfileData(ulong regionHandle, Uri gridserverUrl, - string gridserverSendkey, string gridserverRecvkey); - - /// - /// Request sim profile information from a grid server, by Region Name - /// - /// the region name to look for - /// - /// - /// - /// The sim profile. Null if there was a request failure - RegionProfileData RequestSimProfileData(string regionName, Uri gridserverUrl, - string gridserverSendkey, string gridserverRecvkey); - } -} diff --git a/OpenSim/Data/IUserData.cs b/OpenSim/Data/IUserData.cs deleted file mode 100644 index e9a1e81..0000000 --- a/OpenSim/Data/IUserData.cs +++ /dev/null @@ -1,209 +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 OpenMetaverse; -using OpenSim.Framework; - -namespace OpenSim.Data -{ - /// - /// An interface for connecting to user storage servers. - /// - public interface IUserDataPlugin : IPlugin - { - /// - /// Returns a user profile from a database via their UUID - /// - /// The user's UUID - /// The user data profile. Returns null if no user is found - UserProfileData GetUserByUUID(UUID user); - - /// - /// Returns a users profile by searching their username parts - /// - /// Account firstname - /// Account lastname - /// The user data profile. Null if no user is found - UserProfileData GetUserByName(string fname, string lname); - - /// - /// Get a user from a given uri. - /// - /// - /// The user data profile. Null if no user is found. - UserProfileData GetUserByUri(Uri uri); - - /// - /// Returns a list of UUIDs firstnames and lastnames that match string query entered into the avatar picker. - /// - /// ID associated with the user's query. This must match what the client sent - /// The filtered contents of the search box when the user hit search. - /// A list of user details. If there are no results than either an empty list or null - List GeneratePickerResults(UUID queryID, string query); - - /// - /// Returns the current agent for a user searching by it's UUID - /// - /// The users UUID - /// The current agent session. Null if no session was found - UserAgentData GetAgentByUUID(UUID user); - - /// - /// Returns the current session agent for a user searching by username - /// - /// The users account name - /// The current agent session - UserAgentData GetAgentByName(string name); - - /// - /// Returns the current session agent for a user searching by username parts - /// - /// The users first account name - /// The users account surname - /// The current agent session - UserAgentData GetAgentByName(string fname, string lname); - - /// - /// Stores new web-login key for user during web page login - /// - /// - void StoreWebLoginKey(UUID agentID, UUID webLoginKey); - - /// - /// Adds a new User profile to the database - /// - /// UserProfile to add - void AddNewUserProfile(UserProfileData user); - - /// - /// Adds a temporary user profile. A temporary userprofile is one that should exist only for the lifetime of - /// the process. - /// - /// - void AddTemporaryUserProfile(UserProfileData userProfile); - - /// - /// Updates an existing user profile - /// - /// UserProfile to update - bool UpdateUserProfile(UserProfileData user); - - /// - /// Adds a new agent to the database - /// - /// The agent to add - void AddNewUserAgent(UserAgentData agent); - - /// - /// Adds a new friend to the database for XUser - /// - /// The agent that who's friends list is being added to - /// The agent that being added to the friends list of the friends list owner - /// A uint bit vector for set perms that the friend being added has; 0 = none, 1=This friend can see when they sign on, 2 = map, 4 edit objects - void AddNewUserFriend(UUID friendlistowner, UUID friend, uint perms); - - /// - /// Delete friend on friendlistowner's friendlist. - /// - /// The agent that who's friends list is being updated - /// The Ex-friend agent - void RemoveUserFriend(UUID friendlistowner, UUID friend); - - /// - /// Update permissions for friend on friendlistowner's friendlist. - /// - /// The agent that who's friends list is being updated - /// The agent that is getting or loosing permissions - /// A uint bit vector for set perms that the friend being added has; 0 = none, 1=This friend can see when they sign on, 2 = map, 4 edit objects - void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms); - - /// - /// Returns a list of FriendsListItems that describe the friends and permissions in the friend relationship for UUID friendslistowner - /// - /// The agent that we're retreiving the friends Data. - /// The user's friends. If there are no results than either an empty list or null - List GetUserFriendList(UUID friendlistowner); - - /// - /// Returns a list of - /// A of , mapping the s to s. - /// - Dictionary GetFriendRegionInfos(List uuids); - - /// - /// Attempts to move currency units between accounts (NOT RELIABLE / TRUSTWORTHY. DONT TRY RUN YOUR OWN CURRENCY EXCHANGE WITH REAL VALUES) - /// - /// The account to transfer from - /// The account to transfer to - /// The amount to transfer - /// Successful? - bool MoneyTransferRequest(UUID from, UUID to, uint amount); - - /// - /// Attempts to move inventory between accounts, if inventory is copyable it will be copied into the target account. - /// - /// User to transfer from - /// User to transfer to - /// Specified inventory item - /// Successful? - bool InventoryTransferRequest(UUID from, UUID to, UUID inventory); - - /// - /// Initialises the plugin (artificial constructor) - /// - void Initialise(string connect); - - /// - /// Gets the user appearance - /// - AvatarAppearance GetUserAppearance(UUID user); - - void UpdateUserAppearance(UUID user, AvatarAppearance appearance); - - void ResetAttachments(UUID userID); - - void LogoutUsers(UUID regionID); - } - - public class UserDataInitialiser : PluginInitialiserBase - { - private string connect; - public UserDataInitialiser (string s) { connect = s; } - public override void Initialise (IPlugin plugin) - { - IUserDataPlugin p = plugin as IUserDataPlugin; - p.Initialise (connect); - } - } -} diff --git a/OpenSim/Data/MSSQL/MSSQLGridData.cs b/OpenSim/Data/MSSQL/MSSQLGridData.cs deleted file mode 100644 index 8a3d332..0000000 --- a/OpenSim/Data/MSSQL/MSSQLGridData.cs +++ /dev/null @@ -1,587 +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.Data; -using System.Data.SqlClient; -using System.Reflection; -using log4net; -using OpenMetaverse; -using OpenSim.Framework; - -namespace OpenSim.Data.MSSQL -{ - /// - /// A grid data interface for MSSQL Server - /// - public class MSSQLGridData : GridDataBase - { - private const string _migrationStore = "GridStore"; - - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - /// - /// Database manager - /// - private MSSQLManager database; - - private string m_regionsTableName = "regions"; - - #region IPlugin Members - - // [Obsolete("Cannot be default-initialized!")] - override public void Initialise() - { - m_log.Info("[GRID DB]: " + Name + " cannot be default-initialized!"); - throw new PluginNotInitialisedException(Name); - } - - /// - /// Initialises the Grid Interface - /// - /// connect string - /// use mssql_connection.ini - override public void Initialise(string connectionString) - { - if (!string.IsNullOrEmpty(connectionString)) - { - database = new MSSQLManager(connectionString); - } - else - { - // TODO: make the connect string actually do something - IniFile iniFile = new IniFile("mssql_connection.ini"); - - string settingDataSource = iniFile.ParseFileReadValue("data_source"); - string settingInitialCatalog = iniFile.ParseFileReadValue("initial_catalog"); - string settingPersistSecurityInfo = iniFile.ParseFileReadValue("persist_security_info"); - string settingUserId = iniFile.ParseFileReadValue("user_id"); - string settingPassword = iniFile.ParseFileReadValue("password"); - - m_regionsTableName = iniFile.ParseFileReadValue("regionstablename"); - if (m_regionsTableName == null) - { - m_regionsTableName = "regions"; - } - - database = - new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId, - settingPassword); - } - - //New migrations check of store - database.CheckMigration(_migrationStore); - } - - /// - /// Shuts down the grid interface - /// - override public void Dispose() - { - database = null; - } - - /// - /// The name of this DB provider. - /// - /// A string containing the storage system name - override public string Name - { - get { return "MSSQL OpenGridData"; } - } - - /// - /// Database provider version. - /// - /// A string containing the storage system version - override public string Version - { - get { return "0.1"; } - } - - #endregion - - #region Public override GridDataBase methods - - /// - /// Returns a list of regions within the specified ranges - /// - /// minimum X coordinate - /// minimum Y coordinate - /// maximum X coordinate - /// maximum Y coordinate - /// null - /// always return null - override public RegionProfileData[] GetProfilesInRange(uint xmin, uint ymin, uint xmax, uint ymax) - { - using (AutoClosingSqlCommand command = database.Query("SELECT * FROM regions WHERE locX >= @xmin AND locX <= @xmax AND locY >= @ymin AND locY <= @ymax")) - { - command.Parameters.Add(database.CreateParameter("xmin", xmin)); - command.Parameters.Add(database.CreateParameter("ymin", ymin)); - command.Parameters.Add(database.CreateParameter("xmax", xmax)); - command.Parameters.Add(database.CreateParameter("ymax", ymax)); - - List rows = new List(); - - using (SqlDataReader reader = command.ExecuteReader()) - { - while (reader.Read()) - { - rows.Add(ReadSimRow(reader)); - } - } - - if (rows.Count > 0) - { - return rows.ToArray(); - } - } - m_log.Info("[GRID DB] : Found no regions within range."); - return null; - } - - - /// - /// Returns up to maxNum profiles of regions that have a name starting with namePrefix - /// - /// The name to match against - /// Maximum number of profiles to return - /// A list of sim profiles - override public List GetRegionsByName (string namePrefix, uint maxNum) - { - using (AutoClosingSqlCommand command = database.Query("SELECT * FROM regions WHERE regionName LIKE @name")) - { - command.Parameters.Add(database.CreateParameter("name", namePrefix + "%")); - - List rows = new List(); - - using (SqlDataReader reader = command.ExecuteReader()) - { - while (rows.Count < maxNum && reader.Read()) - { - rows.Add(ReadSimRow(reader)); - } - } - - return rows; - } - } - - /// - /// Returns a sim profile from its location - /// - /// Region location handle - /// Sim profile - override public RegionProfileData GetProfileByHandle(ulong handle) - { - using (AutoClosingSqlCommand command = database.Query("SELECT * FROM " + m_regionsTableName + " WHERE regionHandle = @handle")) - { - command.Parameters.Add(database.CreateParameter("handle", handle)); - - using (SqlDataReader reader = command.ExecuteReader()) - { - if (reader.Read()) - { - return ReadSimRow(reader); - } - } - } - m_log.InfoFormat("[GRID DB] : No region found with handle : {0}", handle); - return null; - } - - /// - /// Returns a sim profile from its UUID - /// - /// The region UUID - /// The sim profile - override public RegionProfileData GetProfileByUUID(UUID uuid) - { - using (AutoClosingSqlCommand command = database.Query("SELECT * FROM " + m_regionsTableName + " WHERE uuid = @uuid")) - { - command.Parameters.Add(database.CreateParameter("uuid", uuid)); - - using (SqlDataReader reader = command.ExecuteReader()) - { - if (reader.Read()) - { - return ReadSimRow(reader); - } - } - } - m_log.InfoFormat("[GRID DB] : No region found with UUID : {0}", uuid); - return null; - } - - /// - /// Returns a sim profile from it's Region name string - /// - /// The region name search query - /// The sim profile - override public RegionProfileData GetProfileByString(string regionName) - { - if (regionName.Length > 2) - { - using (AutoClosingSqlCommand command = database.Query("SELECT top 1 * FROM " + m_regionsTableName + " WHERE regionName like @regionName order by regionName")) - { - command.Parameters.Add(database.CreateParameter("regionName", regionName + "%")); - - using (SqlDataReader reader = command.ExecuteReader()) - { - if (reader.Read()) - { - return ReadSimRow(reader); - } - } - } - m_log.InfoFormat("[GRID DB] : No region found with regionName : {0}", regionName); - return null; - } - - m_log.Error("[GRID DB]: Searched for a Region Name shorter then 3 characters"); - return null; - } - - /// - /// Adds a new specified region to the database - /// - /// The profile to add - /// A dataresponse enum indicating success - override public DataResponse StoreProfile(RegionProfileData profile) - { - if (GetProfileByUUID(profile.UUID) == null) - { - if (InsertRegionRow(profile)) - { - return DataResponse.RESPONSE_OK; - } - } - else - { - if (UpdateRegionRow(profile)) - { - return DataResponse.RESPONSE_OK; - } - } - - return DataResponse.RESPONSE_ERROR; - } - - /// - /// Deletes a sim profile from the database - /// - /// the sim UUID - /// Successful? - //public DataResponse DeleteProfile(RegionProfileData profile) - override public DataResponse DeleteProfile(string uuid) - { - using (AutoClosingSqlCommand command = database.Query("DELETE FROM regions WHERE uuid = @uuid;")) - { - command.Parameters.Add(database.CreateParameter("uuid", uuid)); - try - { - command.ExecuteNonQuery(); - return DataResponse.RESPONSE_OK; - } - catch (Exception e) - { - m_log.DebugFormat("[GRID DB] : Error deleting region info, error is : {0}", e.Message); - return DataResponse.RESPONSE_ERROR; - } - } - } - - #endregion - - #region Methods that are not used or deprecated (still needed because of base class) - - /// - /// DEPRECATED. Attempts to authenticate a region by comparing a shared secret. - /// - /// The UUID of the challenger - /// The attempted regionHandle of the challenger - /// The secret - /// Whether the secret and regionhandle match the database entry for UUID - override public bool AuthenticateSim(UUID uuid, ulong handle, string authkey) - { - bool throwHissyFit = false; // Should be true by 1.0 - - if (throwHissyFit) - throw new Exception("CRYPTOWEAK AUTHENTICATE: Refusing to authenticate due to replay potential."); - - RegionProfileData data = GetProfileByUUID(uuid); - - return (handle == data.regionHandle && authkey == data.regionSecret); - } - - /// - /// NOT YET FUNCTIONAL. Provides a cryptographic authentication of a region - /// - /// This requires a security audit. - /// - /// - /// - /// - /// - public bool AuthenticateSim(UUID uuid, ulong handle, string authhash, string challenge) - { - // SHA512Managed HashProvider = new SHA512Managed(); - // Encoding TextProvider = new UTF8Encoding(); - - // byte[] stream = TextProvider.GetBytes(uuid.ToString() + ":" + handle.ToString() + ":" + challenge); - // byte[] hash = HashProvider.ComputeHash(stream); - return false; - } - - /// - /// NOT IMPLEMENTED - /// WHEN IS THIS GONNA BE IMPLEMENTED. - /// - /// - /// - /// null - override public ReservationData GetReservationAtPoint(uint x, uint y) - { - return null; - } - - #endregion - - #region private methods - - /// - /// Reads a region row from a database reader - /// - /// An active database reader - /// A region profile - private static RegionProfileData ReadSimRow(IDataRecord reader) - { - RegionProfileData retval = new RegionProfileData(); - - // Region Main gotta-have-or-we-return-null parts - UInt64 tmp64; - if (!UInt64.TryParse(reader["regionHandle"].ToString(), out tmp64)) - { - return null; - } - - retval.regionHandle = tmp64; - -// UUID tmp_uuid; -// if (!UUID.TryParse((string)reader["uuid"], out tmp_uuid)) -// { -// return null; -// } - - retval.UUID = new UUID((Guid)reader["uuid"]); // tmp_uuid; - - // non-critical parts - retval.regionName = reader["regionName"].ToString(); - retval.originUUID = new UUID((Guid)reader["originUUID"]); - - // Secrets - retval.regionRecvKey = reader["regionRecvKey"].ToString(); - retval.regionSecret = reader["regionSecret"].ToString(); - retval.regionSendKey = reader["regionSendKey"].ToString(); - - // Region Server - retval.regionDataURI = reader["regionDataURI"].ToString(); - retval.regionOnline = false; // Needs to be pinged before this can be set. - retval.serverIP = reader["serverIP"].ToString(); - retval.serverPort = Convert.ToUInt32(reader["serverPort"]); - retval.serverURI = reader["serverURI"].ToString(); - retval.httpPort = Convert.ToUInt32(reader["serverHttpPort"].ToString()); - retval.remotingPort = Convert.ToUInt32(reader["serverRemotingPort"].ToString()); - - // Location - retval.regionLocX = Convert.ToUInt32(reader["locX"].ToString()); - retval.regionLocY = Convert.ToUInt32(reader["locY"].ToString()); - retval.regionLocZ = Convert.ToUInt32(reader["locZ"].ToString()); - - // Neighbours - 0 = No Override - retval.regionEastOverrideHandle = Convert.ToUInt64(reader["eastOverrideHandle"].ToString()); - retval.regionWestOverrideHandle = Convert.ToUInt64(reader["westOverrideHandle"].ToString()); - retval.regionSouthOverrideHandle = Convert.ToUInt64(reader["southOverrideHandle"].ToString()); - retval.regionNorthOverrideHandle = Convert.ToUInt64(reader["northOverrideHandle"].ToString()); - - // Assets - retval.regionAssetURI = reader["regionAssetURI"].ToString(); - retval.regionAssetRecvKey = reader["regionAssetRecvKey"].ToString(); - retval.regionAssetSendKey = reader["regionAssetSendKey"].ToString(); - - // Userserver - retval.regionUserURI = reader["regionUserURI"].ToString(); - retval.regionUserRecvKey = reader["regionUserRecvKey"].ToString(); - retval.regionUserSendKey = reader["regionUserSendKey"].ToString(); - - // World Map Addition - retval.regionMapTextureID = new UUID((Guid)reader["regionMapTexture"]); - retval.owner_uuid = new UUID((Guid)reader["owner_uuid"]); - retval.maturity = Convert.ToUInt32(reader["access"]); - return retval; - } - - /// - /// Update the specified region in the database - /// - /// The profile to update - /// success ? - private bool UpdateRegionRow(RegionProfileData profile) - { - bool returnval = false; - - //Insert new region - string sql = - "UPDATE " + m_regionsTableName + @" SET - [regionHandle]=@regionHandle, [regionName]=@regionName, - [regionRecvKey]=@regionRecvKey, [regionSecret]=@regionSecret, [regionSendKey]=@regionSendKey, - [regionDataURI]=@regionDataURI, [serverIP]=@serverIP, [serverPort]=@serverPort, [serverURI]=@serverURI, - [locX]=@locX, [locY]=@locY, [locZ]=@locZ, [eastOverrideHandle]=@eastOverrideHandle, - [westOverrideHandle]=@westOverrideHandle, [southOverrideHandle]=@southOverrideHandle, - [northOverrideHandle]=@northOverrideHandle, [regionAssetURI]=@regionAssetURI, - [regionAssetRecvKey]=@regionAssetRecvKey, [regionAssetSendKey]=@regionAssetSendKey, - [regionUserURI]=@regionUserURI, [regionUserRecvKey]=@regionUserRecvKey, [regionUserSendKey]=@regionUserSendKey, - [regionMapTexture]=@regionMapTexture, [serverHttpPort]=@serverHttpPort, - [serverRemotingPort]=@serverRemotingPort, [owner_uuid]=@owner_uuid , [originUUID]=@originUUID - where [uuid]=@uuid"; - - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("regionHandle", profile.regionHandle)); - command.Parameters.Add(database.CreateParameter("regionName", profile.regionName)); - command.Parameters.Add(database.CreateParameter("uuid", profile.UUID)); - command.Parameters.Add(database.CreateParameter("regionRecvKey", profile.regionRecvKey)); - command.Parameters.Add(database.CreateParameter("regionSecret", profile.regionSecret)); - command.Parameters.Add(database.CreateParameter("regionSendKey", profile.regionSendKey)); - command.Parameters.Add(database.CreateParameter("regionDataURI", profile.regionDataURI)); - command.Parameters.Add(database.CreateParameter("serverIP", profile.serverIP)); - command.Parameters.Add(database.CreateParameter("serverPort", profile.serverPort)); - command.Parameters.Add(database.CreateParameter("serverURI", profile.serverURI)); - command.Parameters.Add(database.CreateParameter("locX", profile.regionLocX)); - command.Parameters.Add(database.CreateParameter("locY", profile.regionLocY)); - command.Parameters.Add(database.CreateParameter("locZ", profile.regionLocZ)); - command.Parameters.Add(database.CreateParameter("eastOverrideHandle", profile.regionEastOverrideHandle)); - command.Parameters.Add(database.CreateParameter("westOverrideHandle", profile.regionWestOverrideHandle)); - command.Parameters.Add(database.CreateParameter("northOverrideHandle", profile.regionNorthOverrideHandle)); - command.Parameters.Add(database.CreateParameter("southOverrideHandle", profile.regionSouthOverrideHandle)); - command.Parameters.Add(database.CreateParameter("regionAssetURI", profile.regionAssetURI)); - command.Parameters.Add(database.CreateParameter("regionAssetRecvKey", profile.regionAssetRecvKey)); - command.Parameters.Add(database.CreateParameter("regionAssetSendKey", profile.regionAssetSendKey)); - command.Parameters.Add(database.CreateParameter("regionUserURI", profile.regionUserURI)); - command.Parameters.Add(database.CreateParameter("regionUserRecvKey", profile.regionUserRecvKey)); - command.Parameters.Add(database.CreateParameter("regionUserSendKey", profile.regionUserSendKey)); - command.Parameters.Add(database.CreateParameter("regionMapTexture", profile.regionMapTextureID)); - command.Parameters.Add(database.CreateParameter("serverHttpPort", profile.httpPort)); - command.Parameters.Add(database.CreateParameter("serverRemotingPort", profile.remotingPort)); - command.Parameters.Add(database.CreateParameter("owner_uuid", profile.owner_uuid)); - command.Parameters.Add(database.CreateParameter("originUUID", profile.originUUID)); - - try - { - command.ExecuteNonQuery(); - returnval = true; - } - catch (Exception e) - { - m_log.Error("[GRID DB] : Error updating region, error: " + e.Message); - } - } - - return returnval; - } - - /// - /// Creates a new region in the database - /// - /// The region profile to insert - /// Successful? - private bool InsertRegionRow(RegionProfileData profile) - { - bool returnval = false; - - //Insert new region - string sql = - "INSERT INTO " + m_regionsTableName + @" ([regionHandle], [regionName], [uuid], [regionRecvKey], [regionSecret], [regionSendKey], [regionDataURI], - [serverIP], [serverPort], [serverURI], [locX], [locY], [locZ], [eastOverrideHandle], [westOverrideHandle], - [southOverrideHandle], [northOverrideHandle], [regionAssetURI], [regionAssetRecvKey], [regionAssetSendKey], - [regionUserURI], [regionUserRecvKey], [regionUserSendKey], [regionMapTexture], [serverHttpPort], - [serverRemotingPort], [owner_uuid], [originUUID], [access]) - VALUES (@regionHandle, @regionName, @uuid, @regionRecvKey, @regionSecret, @regionSendKey, @regionDataURI, - @serverIP, @serverPort, @serverURI, @locX, @locY, @locZ, @eastOverrideHandle, @westOverrideHandle, - @southOverrideHandle, @northOverrideHandle, @regionAssetURI, @regionAssetRecvKey, @regionAssetSendKey, - @regionUserURI, @regionUserRecvKey, @regionUserSendKey, @regionMapTexture, @serverHttpPort, @serverRemotingPort, @owner_uuid, @originUUID, @access);"; - - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("regionHandle", profile.regionHandle)); - command.Parameters.Add(database.CreateParameter("regionName", profile.regionName)); - command.Parameters.Add(database.CreateParameter("uuid", profile.UUID)); - command.Parameters.Add(database.CreateParameter("regionRecvKey", profile.regionRecvKey)); - command.Parameters.Add(database.CreateParameter("regionSecret", profile.regionSecret)); - command.Parameters.Add(database.CreateParameter("regionSendKey", profile.regionSendKey)); - command.Parameters.Add(database.CreateParameter("regionDataURI", profile.regionDataURI)); - command.Parameters.Add(database.CreateParameter("serverIP", profile.serverIP)); - command.Parameters.Add(database.CreateParameter("serverPort", profile.serverPort)); - command.Parameters.Add(database.CreateParameter("serverURI", profile.serverURI)); - command.Parameters.Add(database.CreateParameter("locX", profile.regionLocX)); - command.Parameters.Add(database.CreateParameter("locY", profile.regionLocY)); - command.Parameters.Add(database.CreateParameter("locZ", profile.regionLocZ)); - command.Parameters.Add(database.CreateParameter("eastOverrideHandle", profile.regionEastOverrideHandle)); - command.Parameters.Add(database.CreateParameter("westOverrideHandle", profile.regionWestOverrideHandle)); - command.Parameters.Add(database.CreateParameter("northOverrideHandle", profile.regionNorthOverrideHandle)); - command.Parameters.Add(database.CreateParameter("southOverrideHandle", profile.regionSouthOverrideHandle)); - command.Parameters.Add(database.CreateParameter("regionAssetURI", profile.regionAssetURI)); - command.Parameters.Add(database.CreateParameter("regionAssetRecvKey", profile.regionAssetRecvKey)); - command.Parameters.Add(database.CreateParameter("regionAssetSendKey", profile.regionAssetSendKey)); - command.Parameters.Add(database.CreateParameter("regionUserURI", profile.regionUserURI)); - command.Parameters.Add(database.CreateParameter("regionUserRecvKey", profile.regionUserRecvKey)); - command.Parameters.Add(database.CreateParameter("regionUserSendKey", profile.regionUserSendKey)); - command.Parameters.Add(database.CreateParameter("regionMapTexture", profile.regionMapTextureID)); - command.Parameters.Add(database.CreateParameter("serverHttpPort", profile.httpPort)); - command.Parameters.Add(database.CreateParameter("serverRemotingPort", profile.remotingPort)); - command.Parameters.Add(database.CreateParameter("owner_uuid", profile.owner_uuid)); - command.Parameters.Add(database.CreateParameter("originUUID", profile.originUUID)); - command.Parameters.Add(database.CreateParameter("access", profile.maturity)); - - try - { - command.ExecuteNonQuery(); - returnval = true; - } - catch (Exception e) - { - m_log.Error("[GRID DB] : Error inserting region, error: " + e.Message); - } - } - - return returnval; - } - - #endregion - } -} diff --git a/OpenSim/Data/MSSQL/MSSQLLogData.cs b/OpenSim/Data/MSSQL/MSSQLLogData.cs deleted file mode 100644 index 72c50e6..0000000 --- a/OpenSim/Data/MSSQL/MSSQLLogData.cs +++ /dev/null @@ -1,146 +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.Reflection; -using log4net; -using OpenSim.Framework; - -namespace OpenSim.Data.MSSQL -{ - /// - /// An interface to the log database for MSSQL - /// - internal class MSSQLLogData : ILogDataPlugin - { - private const string _migrationStore = "LogStore"; - - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - /// - /// The database manager - /// - public MSSQLManager database; - - [Obsolete("Cannot be default-initialized!")] - public void Initialise() - { - m_log.Info("[LOG DB]: " + Name + " cannot be default-initialized!"); - throw new PluginNotInitialisedException (Name); - } - - /// - /// Artificial constructor called when the plugin is loaded - /// - public void Initialise(string connect) - { - if (!string.IsNullOrEmpty(connect)) - { - database = new MSSQLManager(connect); - } - else - { - // TODO: do something with the connect string - IniFile gridDataMSSqlFile = new IniFile("mssql_connection.ini"); - string settingDataSource = gridDataMSSqlFile.ParseFileReadValue("data_source"); - string settingInitialCatalog = gridDataMSSqlFile.ParseFileReadValue("initial_catalog"); - string settingPersistSecurityInfo = gridDataMSSqlFile.ParseFileReadValue("persist_security_info"); - string settingUserId = gridDataMSSqlFile.ParseFileReadValue("user_id"); - string settingPassword = gridDataMSSqlFile.ParseFileReadValue("password"); - - database = - new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId, - settingPassword); - } - - //Updating mechanisme - database.CheckMigration(_migrationStore); - } - - /// - /// Saves a log item to the database - /// - /// The daemon triggering the event - /// The target of the action (region / agent UUID, etc) - /// The method call where the problem occured - /// The arguments passed to the method - /// How critical is this? - /// The message to log - public void saveLog(string serverDaemon, string target, string methodCall, string arguments, int priority, - string logMessage) - { - string sql = "INSERT INTO logs ([target], [server], [method], [arguments], [priority], [message]) VALUES "; - sql += "(@target, @server, @method, @arguments, @priority, @message);"; - - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("server", serverDaemon)); - command.Parameters.Add(database.CreateParameter("target",target)); - command.Parameters.Add(database.CreateParameter("method", methodCall)); - command.Parameters.Add(database.CreateParameter("arguments", arguments)); - command.Parameters.Add(database.CreateParameter("priority", priority.ToString())); - command.Parameters.Add(database.CreateParameter("message", logMessage)); - - try - { - command.ExecuteNonQuery(); - } - catch (Exception e) - { - //Are we not in a loop here - m_log.Error("[LOG DB] Error logging : " + e.Message); - } - } - } - - /// - /// Returns the name of this DB provider - /// - /// A string containing the DB provider name - public string Name - { - get { return "MSSQL Logdata Interface"; } - } - - /// - /// Closes the database provider - /// - public void Dispose() - { - database = null; - } - - /// - /// Returns the version of this DB provider - /// - /// A string containing the provider version - public string Version - { - get { return "0.1"; } - } - } -} diff --git a/OpenSim/Data/MSSQL/MSSQLUserData.cs b/OpenSim/Data/MSSQL/MSSQLUserData.cs deleted file mode 100644 index 3ef1053..0000000 --- a/OpenSim/Data/MSSQL/MSSQLUserData.cs +++ /dev/null @@ -1,1214 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; -using System.Data.SqlClient; -using System.Reflection; -using log4net; -using OpenMetaverse; -using OpenSim.Framework; - -namespace OpenSim.Data.MSSQL -{ - /// - /// A database interface class to a user profile storage system - /// - public class MSSQLUserData : UserDataBase - { - private const string _migrationStore = "UserStore"; - - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - /// - /// Database manager for MSSQL - /// - public MSSQLManager database; - - private const string m_agentsTableName = "agents"; - private const string m_usersTableName = "users"; - private const string m_userFriendsTableName = "userfriends"; - - // [Obsolete("Cannot be default-initialized!")] - override public void Initialise() - { - m_log.Info("[MSSQLUserData]: " + Name + " cannot be default-initialized!"); - throw new PluginNotInitialisedException(Name); - } - - /// - /// Loads and initialises the MSSQL storage plugin - /// - /// connectionstring - /// use mssql_connection.ini - override public void Initialise(string connect) - { - if (!string.IsNullOrEmpty(connect)) - { - database = new MSSQLManager(connect); - } - else - { - IniFile iniFile = new IniFile("mssql_connection.ini"); - - string settingDataSource = iniFile.ParseFileReadValue("data_source"); - string settingInitialCatalog = iniFile.ParseFileReadValue("initial_catalog"); - string settingPersistSecurityInfo = iniFile.ParseFileReadValue("persist_security_info"); - string settingUserId = iniFile.ParseFileReadValue("user_id"); - string settingPassword = iniFile.ParseFileReadValue("password"); - - database = new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId, settingPassword); - } - - //Check migration on DB - database.CheckMigration(_migrationStore); - } - - /// - /// Releases unmanaged and - optionally - managed resources - /// - override public void Dispose() { } - - #region User table methods - - /// - /// Searches the database for a specified user profile by name components - /// - /// The first part of the account name - /// The second part of the account name - /// A user profile - override public UserProfileData GetUserByName(string user, string last) - { - string sql = string.Format(@"SELECT * FROM {0} - WHERE username = @first AND lastname = @second", m_usersTableName); - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("first", user)); - command.Parameters.Add(database.CreateParameter("second", last)); - try - { - using (SqlDataReader reader = command.ExecuteReader()) - { - return ReadUserRow(reader); - } - } - catch (Exception e) - { - m_log.ErrorFormat("[USER DB] Error getting user profile for {0} {1}: {2}", user, last, e.Message); - return null; - } - } - } - - /// - /// See IUserDataPlugin - /// - /// - /// - override public UserProfileData GetUserByUUID(UUID uuid) - { - string sql = string.Format("SELECT * FROM {0} WHERE UUID = @uuid", m_usersTableName); - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("uuid", uuid)); - try - { - using (SqlDataReader reader = command.ExecuteReader()) - { - return ReadUserRow(reader); - } - } - catch (Exception e) - { - m_log.ErrorFormat("[USER DB] Error getting user profile by UUID {0}, error: {1}", uuid, e.Message); - return null; - } - } - } - - - /// - /// Creates a new users profile - /// - /// The user profile to create - override public void AddNewUserProfile(UserProfileData user) - { - try - { - InsertUserRow(user.ID, user.FirstName, user.SurName, user.Email, user.PasswordHash, user.PasswordSalt, - user.HomeRegion, user.HomeLocation.X, user.HomeLocation.Y, - user.HomeLocation.Z, - user.HomeLookAt.X, user.HomeLookAt.Y, user.HomeLookAt.Z, user.Created, - user.LastLogin, user.UserInventoryURI, user.UserAssetURI, - user.CanDoMask, user.WantDoMask, - user.AboutText, user.FirstLifeAboutText, user.Image, - user.FirstLifeImage, user.WebLoginKey, user.HomeRegionID, - user.GodLevel, user.UserFlags, user.CustomType, user.Partner); - } - catch (Exception e) - { - m_log.ErrorFormat("[USER DB] Error adding new profile, error: {0}", e.Message); - } - } - - /// - /// update a user profile - /// - /// the profile to update - /// - override public bool UpdateUserProfile(UserProfileData user) - { - string sql = string.Format(@"UPDATE {0} - SET UUID = @uuid, - username = @username, - lastname = @lastname, - email = @email, - passwordHash = @passwordHash, - passwordSalt = @passwordSalt, - homeRegion = @homeRegion, - homeLocationX = @homeLocationX, - homeLocationY = @homeLocationY, - homeLocationZ = @homeLocationZ, - homeLookAtX = @homeLookAtX, - homeLookAtY = @homeLookAtY, - homeLookAtZ = @homeLookAtZ, - created = @created, - lastLogin = @lastLogin, - userInventoryURI = @userInventoryURI, - userAssetURI = @userAssetURI, - profileCanDoMask = @profileCanDoMask, - profileWantDoMask = @profileWantDoMask, - profileAboutText = @profileAboutText, - profileFirstText = @profileFirstText, - profileImage = @profileImage, - profileFirstImage = @profileFirstImage, - webLoginKey = @webLoginKey, - homeRegionID = @homeRegionID, - userFlags = @userFlags, - godLevel = @godLevel, - customType = @customType, - partner = @partner WHERE UUID = @keyUUUID;",m_usersTableName); - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("uuid", user.ID)); - command.Parameters.Add(database.CreateParameter("username", user.FirstName)); - command.Parameters.Add(database.CreateParameter("lastname", user.SurName)); - command.Parameters.Add(database.CreateParameter("email", user.Email)); - command.Parameters.Add(database.CreateParameter("passwordHash", user.PasswordHash)); - command.Parameters.Add(database.CreateParameter("passwordSalt", user.PasswordSalt)); - command.Parameters.Add(database.CreateParameter("homeRegion", user.HomeRegion)); - command.Parameters.Add(database.CreateParameter("homeLocationX", user.HomeLocation.X)); - command.Parameters.Add(database.CreateParameter("homeLocationY", user.HomeLocation.Y)); - command.Parameters.Add(database.CreateParameter("homeLocationZ", user.HomeLocation.Z)); - command.Parameters.Add(database.CreateParameter("homeLookAtX", user.HomeLookAt.X)); - command.Parameters.Add(database.CreateParameter("homeLookAtY", user.HomeLookAt.Y)); - command.Parameters.Add(database.CreateParameter("homeLookAtZ", user.HomeLookAt.Z)); - command.Parameters.Add(database.CreateParameter("created", user.Created)); - command.Parameters.Add(database.CreateParameter("lastLogin", user.LastLogin)); - command.Parameters.Add(database.CreateParameter("userInventoryURI", user.UserInventoryURI)); - command.Parameters.Add(database.CreateParameter("userAssetURI", user.UserAssetURI)); - command.Parameters.Add(database.CreateParameter("profileCanDoMask", user.CanDoMask)); - command.Parameters.Add(database.CreateParameter("profileWantDoMask", user.WantDoMask)); - command.Parameters.Add(database.CreateParameter("profileAboutText", user.AboutText)); - command.Parameters.Add(database.CreateParameter("profileFirstText", user.FirstLifeAboutText)); - command.Parameters.Add(database.CreateParameter("profileImage", user.Image)); - command.Parameters.Add(database.CreateParameter("profileFirstImage", user.FirstLifeImage)); - command.Parameters.Add(database.CreateParameter("webLoginKey", user.WebLoginKey)); - command.Parameters.Add(database.CreateParameter("homeRegionID", user.HomeRegionID)); - command.Parameters.Add(database.CreateParameter("userFlags", user.UserFlags)); - command.Parameters.Add(database.CreateParameter("godLevel", user.GodLevel)); - command.Parameters.Add(database.CreateParameter("customType", user.CustomType)); - command.Parameters.Add(database.CreateParameter("partner", user.Partner)); - command.Parameters.Add(database.CreateParameter("keyUUUID", user.ID)); - - try - { - int affected = command.ExecuteNonQuery(); - return (affected != 0); - } - catch (Exception e) - { - m_log.ErrorFormat("[USER DB] Error updating profile, error: {0}", e.Message); - } - } - return false; - } - - #endregion - - #region Agent table methods - - /// - /// Returns a user session searching by name - /// - /// The account name - /// The users session - override public UserAgentData GetAgentByName(string name) - { - return GetAgentByName(name.Split(' ')[0], name.Split(' ')[1]); - } - - /// - /// Returns a user session by account name - /// - /// First part of the users account name - /// Second part of the users account name - /// The users session - override public UserAgentData GetAgentByName(string user, string last) - { - UserProfileData profile = GetUserByName(user, last); - return GetAgentByUUID(profile.ID); - } - - /// - /// Returns an agent session by account UUID - /// - /// The accounts UUID - /// The users session - override public UserAgentData GetAgentByUUID(UUID uuid) - { - string sql = string.Format("SELECT * FROM {0} WHERE UUID = @uuid", m_agentsTableName); - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("uuid", uuid)); - try - { - using (SqlDataReader reader = command.ExecuteReader()) - { - return readAgentRow(reader); - } - } - catch (Exception e) - { - m_log.ErrorFormat("[USER DB] Error updating agentdata by UUID, error: {0}", e.Message); - return null; - } - } - } - - /// - /// Creates a new agent - /// - /// The agent to create - override public void AddNewUserAgent(UserAgentData agent) - { - try - { - InsertUpdateAgentRow(agent); - } - catch (Exception e) - { - m_log.ErrorFormat("[USER DB] Error adding new agentdata, error: {0}", e.Message); - } - } - - #endregion - - #region User Friends List Data - - /// - /// Add a new friend in the friendlist - /// - /// UUID of the friendlist owner - /// Friend's UUID - /// Permission flag - override public void AddNewUserFriend(UUID friendlistowner, UUID friend, uint perms) - { - int dtvalue = Util.UnixTimeSinceEpoch(); - string sql = string.Format(@"INSERT INTO {0} - (ownerID,friendID,friendPerms,datetimestamp) - VALUES - (@ownerID,@friendID,@friendPerms,@datetimestamp)", m_userFriendsTableName); - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("ownerID", friendlistowner)); - command.Parameters.Add(database.CreateParameter("friendID", friend)); - command.Parameters.Add(database.CreateParameter("friendPerms", perms)); - command.Parameters.Add(database.CreateParameter("datetimestamp", dtvalue)); - command.ExecuteNonQuery(); - - try - { - sql = string.Format(@"INSERT INTO {0} - (ownerID,friendID,friendPerms,datetimestamp) - VALUES - (@friendID,@ownerID,@friendPerms,@datetimestamp)", m_userFriendsTableName); - command.CommandText = sql; - command.ExecuteNonQuery(); - } - catch (Exception e) - { - m_log.ErrorFormat("[USER DB] Error adding new userfriend, error: {0}", e.Message); - return; - } - } - } - - /// - /// Remove an friend from the friendlist - /// - /// UUID of the friendlist owner - /// UUID of the not-so-friendly user to remove from the list - override public void RemoveUserFriend(UUID friendlistowner, UUID friend) - { - string sql = string.Format(@"DELETE from {0} - WHERE ownerID = @ownerID - AND friendID = @friendID", m_userFriendsTableName); - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("@ownerID", friendlistowner)); - command.Parameters.Add(database.CreateParameter("@friendID", friend)); - command.ExecuteNonQuery(); - sql = string.Format(@"DELETE from {0} - WHERE ownerID = @friendID - AND friendID = @ownerID", m_userFriendsTableName); - command.CommandText = sql; - try - { - command.ExecuteNonQuery(); - } - catch (Exception e) - { - m_log.ErrorFormat("[USER DB] Error removing userfriend, error: {0}", e.Message); - } - } - } - - /// - /// Update friendlist permission flag for a friend - /// - /// UUID of the friendlist owner - /// UUID of the friend - /// new permission flag - override public void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms) - { - string sql = string.Format(@"UPDATE {0} SET friendPerms = @friendPerms - WHERE ownerID = @ownerID - AND friendID = @friendID", m_userFriendsTableName); - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("@ownerID", friendlistowner)); - command.Parameters.Add(database.CreateParameter("@friendID", friend)); - command.Parameters.Add(database.CreateParameter("@friendPerms", perms)); - - try - { - command.ExecuteNonQuery(); - } - catch (Exception e) - { - m_log.ErrorFormat("[USER DB] Error updating userfriend, error: {0}", e.Message); - } - } - } - - /// - /// Get (fetch?) the user's friendlist - /// - /// UUID of the friendlist owner - /// Friendlist list - override public List GetUserFriendList(UUID friendlistowner) - { - List friendList = new List(); - - //Left Join userfriends to itself - string sql = string.Format(@"SELECT a.ownerID, a.friendID, a.friendPerms, b.friendPerms AS ownerperms - FROM {0} as a, {0} as b - WHERE a.ownerID = @ownerID - AND b.ownerID = a.friendID - AND b.friendID = a.ownerID", m_userFriendsTableName); - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("@ownerID", friendlistowner)); - try - { - using (SqlDataReader reader = command.ExecuteReader()) - { - while (reader.Read()) - { - FriendListItem fli = new FriendListItem(); - fli.FriendListOwner = new UUID((Guid)reader["ownerID"]); - fli.Friend = new UUID((Guid)reader["friendID"]); - fli.FriendPerms = (uint)Convert.ToInt32(reader["friendPerms"]); - - // This is not a real column in the database table, it's a joined column from the opposite record - fli.FriendListOwnerPerms = (uint)Convert.ToInt32(reader["ownerperms"]); - friendList.Add(fli); - } - } - } - catch (Exception e) - { - m_log.ErrorFormat("[USER DB] Error updating userfriend, error: {0}", e.Message); - } - } - return friendList; - } - - override public Dictionary GetFriendRegionInfos (List uuids) - { - Dictionary infos = new Dictionary(); - try - { - foreach (UUID uuid in uuids) - { - string sql = string.Format(@"SELECT agentOnline,currentHandle - FROM {0} WHERE UUID = @uuid", m_agentsTableName); - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("@uuid", uuid)); - using (SqlDataReader reader = command.ExecuteReader()) - { - while (reader.Read()) - { - FriendRegionInfo fri = new FriendRegionInfo(); - fri.isOnline = (byte)reader["agentOnline"] != 0; - fri.regionHandle = Convert.ToUInt64(reader["currentHandle"].ToString()); - - infos[uuid] = fri; - } - } - } - } - } - catch (Exception e) - { - m_log.Warn("[MSSQL]: Got exception on trying to find friends regions:", e); - } - - return infos; - } - #endregion - - #region Money functions (not used) - - /// - /// Performs a money transfer request between two accounts - /// - /// The senders account ID - /// The receivers account ID - /// The amount to transfer - /// false - override public bool MoneyTransferRequest(UUID from, UUID to, uint amount) - { - return false; - } - - /// - /// Performs an inventory transfer request between two accounts - /// - /// TODO: Move to inventory server - /// The senders account ID - /// The receivers account ID - /// The item to transfer - /// false - override public bool InventoryTransferRequest(UUID from, UUID to, UUID item) - { - return false; - } - - #endregion - - #region Appearance methods - - /// - /// Gets the user appearance. - /// - /// The user. - /// - override public AvatarAppearance GetUserAppearance(UUID user) - { - try - { - AvatarAppearance appearance = new AvatarAppearance(); - string sql = "SELECT * FROM avatarappearance WHERE owner = @UUID"; - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("@UUID", user)); - using (SqlDataReader reader = command.ExecuteReader()) - { - if (reader.Read()) - appearance = readUserAppearance(reader); - else - { - m_log.WarnFormat("[USER DB] No appearance found for user {0}", user.ToString()); - return null; - } - - } - } - - appearance.SetAttachments(GetUserAttachments(user)); - - return appearance; - } - catch (Exception e) - { - m_log.ErrorFormat("[USER DB] Error updating userfriend, error: {0}", e.Message); - } - return null; - } - - /// - /// Update a user appearence into database - /// - /// the used UUID - /// the appearence - override public void UpdateUserAppearance(UUID user, AvatarAppearance appearance) - { - string sql = @"DELETE FROM avatarappearance WHERE owner=@owner; - INSERT INTO avatarappearance - (owner, serial, visual_params, texture, avatar_height, - body_item, body_asset, skin_item, skin_asset, hair_item, - hair_asset, eyes_item, eyes_asset, shirt_item, shirt_asset, - pants_item, pants_asset, shoes_item, shoes_asset, socks_item, - socks_asset, jacket_item, jacket_asset, gloves_item, gloves_asset, - undershirt_item, undershirt_asset, underpants_item, underpants_asset, - skirt_item, skirt_asset) - VALUES - (@owner, @serial, @visual_params, @texture, @avatar_height, - @body_item, @body_asset, @skin_item, @skin_asset, @hair_item, - @hair_asset, @eyes_item, @eyes_asset, @shirt_item, @shirt_asset, - @pants_item, @pants_asset, @shoes_item, @shoes_asset, @socks_item, - @socks_asset, @jacket_item, @jacket_asset, @gloves_item, @gloves_asset, - @undershirt_item, @undershirt_asset, @underpants_item, @underpants_asset, - @skirt_item, @skirt_asset)"; - - using (AutoClosingSqlCommand cmd = database.Query(sql)) - { - cmd.Parameters.Add(database.CreateParameter("@owner", appearance.Owner)); - cmd.Parameters.Add(database.CreateParameter("@serial", appearance.Serial)); - cmd.Parameters.Add(database.CreateParameter("@visual_params", appearance.VisualParams)); - cmd.Parameters.Add(database.CreateParameter("@texture", appearance.Texture.GetBytes())); - cmd.Parameters.Add(database.CreateParameter("@avatar_height", appearance.AvatarHeight)); - cmd.Parameters.Add(database.CreateParameter("@body_item", appearance.BodyItem)); - cmd.Parameters.Add(database.CreateParameter("@body_asset", appearance.BodyAsset)); - cmd.Parameters.Add(database.CreateParameter("@skin_item", appearance.SkinItem)); - cmd.Parameters.Add(database.CreateParameter("@skin_asset", appearance.SkinAsset)); - cmd.Parameters.Add(database.CreateParameter("@hair_item", appearance.HairItem)); - cmd.Parameters.Add(database.CreateParameter("@hair_asset", appearance.HairAsset)); - cmd.Parameters.Add(database.CreateParameter("@eyes_item", appearance.EyesItem)); - cmd.Parameters.Add(database.CreateParameter("@eyes_asset", appearance.EyesAsset)); - cmd.Parameters.Add(database.CreateParameter("@shirt_item", appearance.ShirtItem)); - cmd.Parameters.Add(database.CreateParameter("@shirt_asset", appearance.ShirtAsset)); - cmd.Parameters.Add(database.CreateParameter("@pants_item", appearance.PantsItem)); - cmd.Parameters.Add(database.CreateParameter("@pants_asset", appearance.PantsAsset)); - cmd.Parameters.Add(database.CreateParameter("@shoes_item", appearance.ShoesItem)); - cmd.Parameters.Add(database.CreateParameter("@shoes_asset", appearance.ShoesAsset)); - cmd.Parameters.Add(database.CreateParameter("@socks_item", appearance.SocksItem)); - cmd.Parameters.Add(database.CreateParameter("@socks_asset", appearance.SocksAsset)); - cmd.Parameters.Add(database.CreateParameter("@jacket_item", appearance.JacketItem)); - cmd.Parameters.Add(database.CreateParameter("@jacket_asset", appearance.JacketAsset)); - cmd.Parameters.Add(database.CreateParameter("@gloves_item", appearance.GlovesItem)); - cmd.Parameters.Add(database.CreateParameter("@gloves_asset", appearance.GlovesAsset)); - cmd.Parameters.Add(database.CreateParameter("@undershirt_item", appearance.UnderShirtItem)); - cmd.Parameters.Add(database.CreateParameter("@undershirt_asset", appearance.UnderShirtAsset)); - cmd.Parameters.Add(database.CreateParameter("@underpants_item", appearance.UnderPantsItem)); - cmd.Parameters.Add(database.CreateParameter("@underpants_asset", appearance.UnderPantsAsset)); - cmd.Parameters.Add(database.CreateParameter("@skirt_item", appearance.SkirtItem)); - cmd.Parameters.Add(database.CreateParameter("@skirt_asset", appearance.SkirtAsset)); - - try - { - cmd.ExecuteNonQuery(); - } - catch (Exception e) - { - m_log.ErrorFormat("[USER DB] Error updating user appearance, error: {0}", e.Message); - } - } - UpdateUserAttachments(user, appearance.GetAttachments()); - } - - #endregion - - #region Attachment methods - - /// - /// Gets all attachment of a agent. - /// - /// agent ID. - /// - public Hashtable GetUserAttachments(UUID agentID) - { - Hashtable returnTable = new Hashtable(); - string sql = "select attachpoint, item, asset from avatarattachments where UUID = @uuid"; - using (AutoClosingSqlCommand command = database.Query(sql, database.CreateParameter("@uuid", agentID))) - { - using (SqlDataReader reader = command.ExecuteReader()) - { - while (reader.Read()) - { - int attachpoint = Convert.ToInt32(reader["attachpoint"]); - if (returnTable.ContainsKey(attachpoint)) - continue; - Hashtable item = new Hashtable(); - item.Add("item", reader["item"].ToString()); - item.Add("asset", reader["asset"].ToString()); - - returnTable.Add(attachpoint, item); - } - } - } - return returnTable; - } - - /// - /// Updates all attachments of the agent. - /// - /// agentID. - /// data with all items on attachmentpoints - public void UpdateUserAttachments(UUID agentID, Hashtable data) - { - string sql = "DELETE FROM avatarattachments WHERE UUID = @uuid"; - - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("uuid", agentID)); - command.ExecuteNonQuery(); - } - if (data == null) - return; - - sql = @"INSERT INTO avatarattachments (UUID, attachpoint, item, asset) - VALUES (@uuid, @attachpoint, @item, @asset)"; - - using (AutoClosingSqlCommand command = database.Query(sql)) - { - bool firstTime = true; - foreach (DictionaryEntry e in data) - { - int attachpoint = Convert.ToInt32(e.Key); - - Hashtable item = (Hashtable)e.Value; - - if (firstTime) - { - command.Parameters.Add(database.CreateParameter("@uuid", agentID)); - command.Parameters.Add(database.CreateParameter("@attachpoint", attachpoint)); - command.Parameters.Add(database.CreateParameter("@item", new UUID(item["item"].ToString()))); - command.Parameters.Add(database.CreateParameter("@asset", new UUID(item["asset"].ToString()))); - firstTime = false; - } - command.Parameters["@uuid"].Value = agentID.Guid; //.ToString(); - command.Parameters["@attachpoint"].Value = attachpoint; - command.Parameters["@item"].Value = new Guid(item["item"].ToString()); - command.Parameters["@asset"].Value = new Guid(item["asset"].ToString()); - - try - { - command.ExecuteNonQuery(); - } - catch (Exception ex) - { - m_log.DebugFormat("[USER DB] : Error adding user attachment. {0}", ex.Message); - } - } - } - } - - /// - /// Resets all attachments of a agent in the database. - /// - /// agentID. - override public void ResetAttachments(UUID agentID) - { - string sql = "UPDATE avatarattachments SET asset = '00000000-0000-0000-0000-000000000000' WHERE UUID = @uuid"; - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("uuid", agentID)); - command.ExecuteNonQuery(); - } - } - - override public void LogoutUsers(UUID regionID) - { - } - - #endregion - - #region Other public methods - - /// - /// - /// - /// - /// - /// - override public List GeneratePickerResults(UUID queryID, string query) - { - List returnlist = new List(); - string[] querysplit = query.Split(' '); - if (querysplit.Length == 2) - { - try - { - string sql = string.Format(@"SELECT UUID,username,lastname FROM {0} - WHERE username LIKE @first AND lastname LIKE @second", m_usersTableName); - using (AutoClosingSqlCommand command = database.Query(sql)) - { - //Add wildcard to the search - command.Parameters.Add(database.CreateParameter("first", querysplit[0] + "%")); - command.Parameters.Add(database.CreateParameter("second", querysplit[1] + "%")); - using (SqlDataReader reader = command.ExecuteReader()) - { - while (reader.Read()) - { - AvatarPickerAvatar user = new AvatarPickerAvatar(); - user.AvatarID = new UUID((Guid)reader["UUID"]); - user.firstName = (string)reader["username"]; - user.lastName = (string)reader["lastname"]; - returnlist.Add(user); - } - } - } - } - catch (Exception e) - { - m_log.Error(e.ToString()); - } - } - else if (querysplit.Length == 1) - { - try - { - string sql = string.Format(@"SELECT UUID,username,lastname FROM {0} - WHERE username LIKE @first OR lastname LIKE @first", m_usersTableName); - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("first", querysplit[0] + "%")); - - using (SqlDataReader reader = command.ExecuteReader()) - { - while (reader.Read()) - { - AvatarPickerAvatar user = new AvatarPickerAvatar(); - user.AvatarID = new UUID((Guid)reader["UUID"]); - user.firstName = (string)reader["username"]; - user.lastName = (string)reader["lastname"]; - returnlist.Add(user); - } - } - } - } - catch (Exception e) - { - m_log.Error(e.ToString()); - } - } - return returnlist; - } - - /// - /// Store a weblogin key - /// - /// The agent UUID - /// the WebLogin Key - /// unused ? - override public void StoreWebLoginKey(UUID AgentID, UUID WebLoginKey) - { - UserProfileData user = GetUserByUUID(AgentID); - user.WebLoginKey = WebLoginKey; - UpdateUserProfile(user); - } - - /// - /// Database provider name - /// - /// Provider name - override public string Name - { - get { return "MSSQL Userdata Interface"; } - } - - /// - /// Database provider version - /// - /// provider version - override public string Version - { - get { return database.getVersion(); } - } - - #endregion - - #region Private functions - - /// - /// Reads a one item from an SQL result - /// - /// The SQL Result - /// the item read - private static AvatarAppearance readUserAppearance(SqlDataReader reader) - { - try - { - AvatarAppearance appearance = new AvatarAppearance(); - - appearance.Owner = new UUID((Guid)reader["owner"]); - appearance.Serial = Convert.ToInt32(reader["serial"]); - appearance.VisualParams = (byte[])reader["visual_params"]; - appearance.Texture = new Primitive.TextureEntry((byte[])reader["texture"], 0, ((byte[])reader["texture"]).Length); - appearance.AvatarHeight = (float)Convert.ToDouble(reader["avatar_height"]); - appearance.BodyItem = new UUID((Guid)reader["body_item"]); - appearance.BodyAsset = new UUID((Guid)reader["body_asset"]); - appearance.SkinItem = new UUID((Guid)reader["skin_item"]); - appearance.SkinAsset = new UUID((Guid)reader["skin_asset"]); - appearance.HairItem = new UUID((Guid)reader["hair_item"]); - appearance.HairAsset = new UUID((Guid)reader["hair_asset"]); - appearance.EyesItem = new UUID((Guid)reader["eyes_item"]); - appearance.EyesAsset = new UUID((Guid)reader["eyes_asset"]); - appearance.ShirtItem = new UUID((Guid)reader["shirt_item"]); - appearance.ShirtAsset = new UUID((Guid)reader["shirt_asset"]); - appearance.PantsItem = new UUID((Guid)reader["pants_item"]); - appearance.PantsAsset = new UUID((Guid)reader["pants_asset"]); - appearance.ShoesItem = new UUID((Guid)reader["shoes_item"]); - appearance.ShoesAsset = new UUID((Guid)reader["shoes_asset"]); - appearance.SocksItem = new UUID((Guid)reader["socks_item"]); - appearance.SocksAsset = new UUID((Guid)reader["socks_asset"]); - appearance.JacketItem = new UUID((Guid)reader["jacket_item"]); - appearance.JacketAsset = new UUID((Guid)reader["jacket_asset"]); - appearance.GlovesItem = new UUID((Guid)reader["gloves_item"]); - appearance.GlovesAsset = new UUID((Guid)reader["gloves_asset"]); - appearance.UnderShirtItem = new UUID((Guid)reader["undershirt_item"]); - appearance.UnderShirtAsset = new UUID((Guid)reader["undershirt_asset"]); - appearance.UnderPantsItem = new UUID((Guid)reader["underpants_item"]); - appearance.UnderPantsAsset = new UUID((Guid)reader["underpants_asset"]); - appearance.SkirtItem = new UUID((Guid)reader["skirt_item"]); - appearance.SkirtAsset = new UUID((Guid)reader["skirt_asset"]); - - return appearance; - } - catch (SqlException e) - { - m_log.Error(e.ToString()); - } - - return null; - } - - /// - /// Insert/Update a agent row in the DB. - /// - /// agentdata. - private void InsertUpdateAgentRow(UserAgentData agentdata) - { - string sql = @" - -IF EXISTS (SELECT * FROM agents WHERE UUID = @UUID) - BEGIN - UPDATE agents SET UUID = @UUID, sessionID = @sessionID, secureSessionID = @secureSessionID, agentIP = @agentIP, agentPort = @agentPort, agentOnline = @agentOnline, loginTime = @loginTime, logoutTime = @logoutTime, currentRegion = @currentRegion, currentHandle = @currentHandle, currentPos = @currentPos - WHERE UUID = @UUID - END -ELSE - BEGIN - INSERT INTO - agents (UUID, sessionID, secureSessionID, agentIP, agentPort, agentOnline, loginTime, logoutTime, currentRegion, currentHandle, currentPos) VALUES - (@UUID, @sessionID, @secureSessionID, @agentIP, @agentPort, @agentOnline, @loginTime, @logoutTime, @currentRegion, @currentHandle, @currentPos) - END -"; - - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("@UUID", agentdata.ProfileID)); - command.Parameters.Add(database.CreateParameter("@sessionID", agentdata.SessionID)); - command.Parameters.Add(database.CreateParameter("@secureSessionID", agentdata.SecureSessionID)); - command.Parameters.Add(database.CreateParameter("@agentIP", agentdata.AgentIP)); - command.Parameters.Add(database.CreateParameter("@agentPort", agentdata.AgentPort)); - command.Parameters.Add(database.CreateParameter("@agentOnline", agentdata.AgentOnline)); - command.Parameters.Add(database.CreateParameter("@loginTime", agentdata.LoginTime)); - command.Parameters.Add(database.CreateParameter("@logoutTime", agentdata.LogoutTime)); - command.Parameters.Add(database.CreateParameter("@currentRegion", agentdata.Region)); - command.Parameters.Add(database.CreateParameter("@currentHandle", agentdata.Handle)); - command.Parameters.Add(database.CreateParameter("@currentPos", "<" + ((int)agentdata.Position.X) + "," + ((int)agentdata.Position.Y) + "," + ((int)agentdata.Position.Z) + ">")); - - command.Transaction = command.Connection.BeginTransaction(IsolationLevel.Serializable); - try - { - if (command.ExecuteNonQuery() > 0) - { - command.Transaction.Commit(); - return; - } - - command.Transaction.Rollback(); - return; - } - catch (Exception e) - { - command.Transaction.Rollback(); - m_log.Error(e.ToString()); - return; - } - } - - } - - /// - /// Reads an agent row from a database reader - /// - /// An active database reader - /// A user session agent - private UserAgentData readAgentRow(SqlDataReader reader) - { - UserAgentData retval = new UserAgentData(); - - if (reader.Read()) - { - // Agent IDs - retval.ProfileID = new UUID((Guid)reader["UUID"]); - retval.SessionID = new UUID((Guid)reader["sessionID"]); - retval.SecureSessionID = new UUID((Guid)reader["secureSessionID"]); - - // Agent Who? - retval.AgentIP = (string)reader["agentIP"]; - retval.AgentPort = Convert.ToUInt32(reader["agentPort"].ToString()); - retval.AgentOnline = Convert.ToInt32(reader["agentOnline"].ToString()) != 0; - - // Login/Logout times (UNIX Epoch) - retval.LoginTime = Convert.ToInt32(reader["loginTime"].ToString()); - retval.LogoutTime = Convert.ToInt32(reader["logoutTime"].ToString()); - - // Current position - retval.Region = new UUID((Guid)reader["currentRegion"]); - retval.Handle = Convert.ToUInt64(reader["currentHandle"].ToString()); - Vector3 tmp_v; - Vector3.TryParse((string)reader["currentPos"], out tmp_v); - retval.Position = tmp_v; - - } - else - { - return null; - } - return retval; - } - - /// - /// Creates a new user and inserts it into the database - /// - /// User ID - /// First part of the login - /// Second part of the login - /// Email of person - /// A salted hash of the users password - /// The salt used for the password hash - /// A regionHandle of the users home region - /// Home region position vector - /// Home region position vector - /// Home region position vector - /// Home region 'look at' vector - /// Home region 'look at' vector - /// Home region 'look at' vector - /// Account created (unix timestamp) - /// Last login (unix timestamp) - /// Users inventory URI - /// Users asset URI - /// I can do mask - /// I want to do mask - /// Profile text - /// Firstlife text - /// UUID for profile image - /// UUID for firstlife image - /// web login key - /// homeregion UUID - /// has the user godlevel - /// unknown - /// unknown - /// UUID of partner - /// Success? - private void InsertUserRow(UUID uuid, string username, string lastname, string email, string passwordHash, - string passwordSalt, UInt64 homeRegion, float homeLocX, float homeLocY, float homeLocZ, - float homeLookAtX, float homeLookAtY, float homeLookAtZ, int created, int lastlogin, - string inventoryURI, string assetURI, uint canDoMask, uint wantDoMask, - string aboutText, string firstText, - UUID profileImage, UUID firstImage, UUID webLoginKey, UUID homeRegionID, - int godLevel, int userFlags, string customType, UUID partnerID) - { - string sql = string.Format(@"INSERT INTO {0} - ([UUID], [username], [lastname], [email], [passwordHash], [passwordSalt], - [homeRegion], [homeLocationX], [homeLocationY], [homeLocationZ], [homeLookAtX], - [homeLookAtY], [homeLookAtZ], [created], [lastLogin], [userInventoryURI], - [userAssetURI], [profileCanDoMask], [profileWantDoMask], [profileAboutText], - [profileFirstText], [profileImage], [profileFirstImage], [webLoginKey], - [homeRegionID], [userFlags], [godLevel], [customType], [partner]) - VALUES - (@UUID, @username, @lastname, @email, @passwordHash, @passwordSalt, - @homeRegion, @homeLocationX, @homeLocationY, @homeLocationZ, @homeLookAtX, - @homeLookAtY, @homeLookAtZ, @created, @lastLogin, @userInventoryURI, - @userAssetURI, @profileCanDoMask, @profileWantDoMask, @profileAboutText, - @profileFirstText, @profileImage, @profileFirstImage, @webLoginKey, - @homeRegionID, @userFlags, @godLevel, @customType, @partner)", m_usersTableName); - - try - { - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("UUID", uuid)); - command.Parameters.Add(database.CreateParameter("username", username)); - command.Parameters.Add(database.CreateParameter("lastname", lastname)); - command.Parameters.Add(database.CreateParameter("email", email)); - command.Parameters.Add(database.CreateParameter("passwordHash", passwordHash)); - command.Parameters.Add(database.CreateParameter("passwordSalt", passwordSalt)); - command.Parameters.Add(database.CreateParameter("homeRegion", homeRegion)); - command.Parameters.Add(database.CreateParameter("homeLocationX", homeLocX)); - command.Parameters.Add(database.CreateParameter("homeLocationY", homeLocY)); - command.Parameters.Add(database.CreateParameter("homeLocationZ", homeLocZ)); - command.Parameters.Add(database.CreateParameter("homeLookAtX", homeLookAtX)); - command.Parameters.Add(database.CreateParameter("homeLookAtY", homeLookAtY)); - command.Parameters.Add(database.CreateParameter("homeLookAtZ", homeLookAtZ)); - command.Parameters.Add(database.CreateParameter("created", created)); - command.Parameters.Add(database.CreateParameter("lastLogin", lastlogin)); - command.Parameters.Add(database.CreateParameter("userInventoryURI", inventoryURI)); - command.Parameters.Add(database.CreateParameter("userAssetURI", assetURI)); - command.Parameters.Add(database.CreateParameter("profileCanDoMask", canDoMask)); - command.Parameters.Add(database.CreateParameter("profileWantDoMask", wantDoMask)); - command.Parameters.Add(database.CreateParameter("profileAboutText", aboutText)); - command.Parameters.Add(database.CreateParameter("profileFirstText", firstText)); - command.Parameters.Add(database.CreateParameter("profileImage", profileImage)); - command.Parameters.Add(database.CreateParameter("profileFirstImage", firstImage)); - command.Parameters.Add(database.CreateParameter("webLoginKey", webLoginKey)); - command.Parameters.Add(database.CreateParameter("homeRegionID", homeRegionID)); - command.Parameters.Add(database.CreateParameter("userFlags", userFlags)); - command.Parameters.Add(database.CreateParameter("godLevel", godLevel)); - command.Parameters.Add(database.CreateParameter("customType", customType)); - command.Parameters.Add(database.CreateParameter("partner", partnerID)); - - command.ExecuteNonQuery(); - return; - } - } - catch (Exception e) - { - m_log.Error(e.ToString()); - return; - } - } - - /// - /// Reads a user profile from an active data reader - /// - /// An active database reader - /// A user profile - private static UserProfileData ReadUserRow(SqlDataReader reader) - { - UserProfileData retval = new UserProfileData(); - - if (reader.Read()) - { - retval.ID = new UUID((Guid)reader["UUID"]); - retval.FirstName = (string)reader["username"]; - retval.SurName = (string)reader["lastname"]; - if (reader.IsDBNull(reader.GetOrdinal("email"))) - retval.Email = ""; - else - retval.Email = (string)reader["email"]; - - retval.PasswordHash = (string)reader["passwordHash"]; - retval.PasswordSalt = (string)reader["passwordSalt"]; - - retval.HomeRegion = Convert.ToUInt64(reader["homeRegion"].ToString()); - retval.HomeLocation = new Vector3( - Convert.ToSingle(reader["homeLocationX"].ToString()), - Convert.ToSingle(reader["homeLocationY"].ToString()), - Convert.ToSingle(reader["homeLocationZ"].ToString())); - retval.HomeLookAt = new Vector3( - Convert.ToSingle(reader["homeLookAtX"].ToString()), - Convert.ToSingle(reader["homeLookAtY"].ToString()), - Convert.ToSingle(reader["homeLookAtZ"].ToString())); - - if (reader.IsDBNull(reader.GetOrdinal("homeRegionID"))) - retval.HomeRegionID = UUID.Zero; - else - retval.HomeRegionID = new UUID((Guid)reader["homeRegionID"]); - - retval.Created = Convert.ToInt32(reader["created"].ToString()); - retval.LastLogin = Convert.ToInt32(reader["lastLogin"].ToString()); - - if (reader.IsDBNull(reader.GetOrdinal("userInventoryURI"))) - retval.UserInventoryURI = ""; - else - retval.UserInventoryURI = (string)reader["userInventoryURI"]; - - if (reader.IsDBNull(reader.GetOrdinal("userAssetURI"))) - retval.UserAssetURI = ""; - else - retval.UserAssetURI = (string)reader["userAssetURI"]; - - retval.CanDoMask = Convert.ToUInt32(reader["profileCanDoMask"].ToString()); - retval.WantDoMask = Convert.ToUInt32(reader["profileWantDoMask"].ToString()); - - - if (reader.IsDBNull(reader.GetOrdinal("profileAboutText"))) - retval.AboutText = ""; - else - retval.AboutText = (string)reader["profileAboutText"]; - - if (reader.IsDBNull(reader.GetOrdinal("profileFirstText"))) - retval.FirstLifeAboutText = ""; - else - retval.FirstLifeAboutText = (string)reader["profileFirstText"]; - - if (reader.IsDBNull(reader.GetOrdinal("profileImage"))) - retval.Image = UUID.Zero; - else - retval.Image = new UUID((Guid)reader["profileImage"]); - - if (reader.IsDBNull(reader.GetOrdinal("profileFirstImage"))) - retval.Image = UUID.Zero; - else - retval.FirstLifeImage = new UUID((Guid)reader["profileFirstImage"]); - - if (reader.IsDBNull(reader.GetOrdinal("webLoginKey"))) - retval.WebLoginKey = UUID.Zero; - else - retval.WebLoginKey = new UUID((Guid)reader["webLoginKey"]); - - retval.UserFlags = Convert.ToInt32(reader["userFlags"].ToString()); - retval.GodLevel = Convert.ToInt32(reader["godLevel"].ToString()); - if (reader.IsDBNull(reader.GetOrdinal("customType"))) - retval.CustomType = ""; - else - retval.CustomType = reader["customType"].ToString(); - - if (reader.IsDBNull(reader.GetOrdinal("partner"))) - retval.Partner = UUID.Zero; - else - retval.Partner = new UUID((Guid)reader["partner"]); - } - else - { - return null; - } - return retval; - } - #endregion - } - -} diff --git a/OpenSim/Data/MySQL/MySQLGridData.cs b/OpenSim/Data/MySQL/MySQLGridData.cs deleted file mode 100644 index f4e7b85..0000000 --- a/OpenSim/Data/MySQL/MySQLGridData.cs +++ /dev/null @@ -1,422 +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.Data; -using System.Reflection; -using System.Threading; -using log4net; -using MySql.Data.MySqlClient; -using OpenMetaverse; -using OpenSim.Framework; - -namespace OpenSim.Data.MySQL -{ - /// - /// A MySQL Interface for the Grid Server - /// - public class MySQLGridData : GridDataBase - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private MySQLManager m_database; - private object m_dbLock = new object(); - private string m_connectionString; - - override public void Initialise() - { - m_log.Info("[MySQLGridData]: " + Name + " cannot be default-initialized!"); - throw new PluginNotInitialisedException (Name); - } - - /// - /// Initialises Grid interface - /// - /// - /// Loads and initialises the MySQL storage plugin - /// Warns and uses the obsolete mysql_connection.ini if connect string is empty. - /// Check for migration - /// - /// - /// - /// connect string. - override public void Initialise(string connect) - { - m_connectionString = connect; - m_database = new MySQLManager(connect); - - // This actually does the roll forward assembly stuff - Assembly assem = GetType().Assembly; - - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - Migration m = new Migration(dbcon, assem, "GridStore"); - m.Update(); - } - } - - /// - /// Shuts down the grid interface - /// - override public void Dispose() - { - } - - /// - /// Returns the plugin name - /// - /// Plugin name - override public string Name - { - get { return "MySql OpenGridData"; } - } - - /// - /// Returns the plugin version - /// - /// Plugin version - override public string Version - { - get { return "0.1"; } - } - - /// - /// Returns all the specified region profiles within coordates -- coordinates are inclusive - /// - /// Minimum X coordinate - /// Minimum Y coordinate - /// Maximum X coordinate - /// Maximum Y coordinate - /// Array of sim profiles - override public RegionProfileData[] GetProfilesInRange(uint xmin, uint ymin, uint xmax, uint ymax) - { - try - { - Dictionary param = new Dictionary(); - param["?xmin"] = xmin.ToString(); - param["?ymin"] = ymin.ToString(); - param["?xmax"] = xmax.ToString(); - param["?ymax"] = ymax.ToString(); - - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - using (IDbCommand result = m_database.Query(dbcon, - "SELECT * FROM regions WHERE locX >= ?xmin AND locX <= ?xmax AND locY >= ?ymin AND locY <= ?ymax", - param)) - { - using (IDataReader reader = result.ExecuteReader()) - { - RegionProfileData row; - - List rows = new List(); - - while ((row = m_database.readSimRow(reader)) != null) - rows.Add(row); - - return rows.ToArray(); - } - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return null; - } - } - - /// - /// Returns up to maxNum profiles of regions that have a name starting with namePrefix - /// - /// The name to match against - /// Maximum number of profiles to return - /// A list of sim profiles - override public List GetRegionsByName(string namePrefix, uint maxNum) - { - try - { - Dictionary param = new Dictionary(); - param["?name"] = namePrefix + "%"; - - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - using (IDbCommand result = m_database.Query(dbcon, - "SELECT * FROM regions WHERE regionName LIKE ?name", - param)) - { - using (IDataReader reader = result.ExecuteReader()) - { - RegionProfileData row; - - List rows = new List(); - - while (rows.Count < maxNum && (row = m_database.readSimRow(reader)) != null) - rows.Add(row); - - return rows; - } - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return null; - } - } - - /// - /// Returns a sim profile from it's location - /// - /// Region location handle - /// Sim profile - override public RegionProfileData GetProfileByHandle(ulong handle) - { - try - { - Dictionary param = new Dictionary(); - param["?handle"] = handle.ToString(); - - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - using (IDbCommand result = m_database.Query(dbcon, "SELECT * FROM regions WHERE regionHandle = ?handle", param)) - { - using (IDataReader reader = result.ExecuteReader()) - { - RegionProfileData row = m_database.readSimRow(reader); - return row; - } - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return null; - } - } - - /// - /// Returns a sim profile from it's UUID - /// - /// The region UUID - /// The sim profile - override public RegionProfileData GetProfileByUUID(UUID uuid) - { - try - { - Dictionary param = new Dictionary(); - param["?uuid"] = uuid.ToString(); - - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - using (IDbCommand result = m_database.Query(dbcon, "SELECT * FROM regions WHERE uuid = ?uuid", param)) - { - using (IDataReader reader = result.ExecuteReader()) - { - RegionProfileData row = m_database.readSimRow(reader); - return row; - } - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return null; - } - } - - /// - /// Returns a sim profile from it's Region name string - /// - /// The sim profile - override public RegionProfileData GetProfileByString(string regionName) - { - if (regionName.Length > 2) - { - try - { - Dictionary param = new Dictionary(); - // Add % because this is a like query. - param["?regionName"] = regionName + "%"; - - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - // Order by statement will return shorter matches first. Only returns one record or no record. - using (IDbCommand result = m_database.Query(dbcon, - "SELECT * FROM regions WHERE regionName like ?regionName order by LENGTH(regionName) asc LIMIT 1", - param)) - { - using (IDataReader reader = result.ExecuteReader()) - { - RegionProfileData row = m_database.readSimRow(reader); - return row; - } - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return null; - } - } - - m_log.Error("[GRID DB]: Searched for a Region Name shorter then 3 characters"); - return null; - } - - /// - /// Adds a new profile to the database - /// - /// The profile to add - /// Successful? - override public DataResponse StoreProfile(RegionProfileData profile) - { - try - { - if (m_database.insertRegion(profile)) - return DataResponse.RESPONSE_OK; - else - return DataResponse.RESPONSE_ERROR; - } - catch - { - return DataResponse.RESPONSE_ERROR; - } - } - - /// - /// Deletes a sim profile from the database - /// - /// the sim UUID - /// Successful? - //public DataResponse DeleteProfile(RegionProfileData profile) - override public DataResponse DeleteProfile(string uuid) - { - try - { - if (m_database.deleteRegion(uuid)) - return DataResponse.RESPONSE_OK; - else - return DataResponse.RESPONSE_ERROR; - } - catch - { - return DataResponse.RESPONSE_ERROR; - } - } - - /// - /// DEPRECATED. Attempts to authenticate a region by comparing a shared secret. - /// - /// The UUID of the challenger - /// The attempted regionHandle of the challenger - /// The secret - /// Whether the secret and regionhandle match the database entry for UUID - override public bool AuthenticateSim(UUID uuid, ulong handle, string authkey) - { - bool throwHissyFit = false; // Should be true by 1.0 - - if (throwHissyFit) - throw new Exception("CRYPTOWEAK AUTHENTICATE: Refusing to authenticate due to replay potential."); - - RegionProfileData data = GetProfileByUUID(uuid); - - return (handle == data.regionHandle && authkey == data.regionSecret); - } - - /// - /// NOT YET FUNCTIONAL. Provides a cryptographic authentication of a region - /// - /// This requires a security audit. - /// - /// - /// - /// - /// - public bool AuthenticateSim(UUID uuid, ulong handle, string authhash, string challenge) - { - // SHA512Managed HashProvider = new SHA512Managed(); - // Encoding TextProvider = new UTF8Encoding(); - - // byte[] stream = TextProvider.GetBytes(uuid.ToString() + ":" + handle.ToString() + ":" + challenge); - // byte[] hash = HashProvider.ComputeHash(stream); - - return false; - } - - /// - /// Adds a location reservation - /// - /// x coordinate - /// y coordinate - /// - override public ReservationData GetReservationAtPoint(uint x, uint y) - { - try - { - Dictionary param = new Dictionary(); - param["?x"] = x.ToString(); - param["?y"] = y.ToString(); - - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - using (IDbCommand result = m_database.Query(dbcon, - "SELECT * FROM reservations WHERE resXMin <= ?x AND resXMax >= ?x AND resYMin <= ?y AND resYMax >= ?y", - param)) - { - using (IDataReader reader = result.ExecuteReader()) - { - ReservationData row = m_database.readReservationRow(reader); - return row; - } - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return null; - } - } - } -} diff --git a/OpenSim/Data/MySQL/MySQLLogData.cs b/OpenSim/Data/MySQL/MySQLLogData.cs deleted file mode 100644 index 304883c..0000000 --- a/OpenSim/Data/MySQL/MySQLLogData.cs +++ /dev/null @@ -1,166 +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.Reflection; -using log4net; -using OpenSim.Framework; - -namespace OpenSim.Data.MySQL -{ - /// - /// An interface to the log database for MySQL - /// - internal class MySQLLogData : ILogDataPlugin - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - /// - /// The database manager - /// - public MySQLManager database; - - public void Initialise() - { - m_log.Info("[MySQLLogData]: " + Name + " cannot be default-initialized!"); - throw new PluginNotInitialisedException (Name); - } - - /// - /// Artificial constructor called when the plugin is loaded - /// Uses the obsolete mysql_connection.ini if connect string is empty. - /// - /// connect string - public void Initialise(string connect) - { - if (connect != String.Empty) - { - database = new MySQLManager(connect); - } - else - { - m_log.Warn("Using deprecated mysql_connection.ini. Please update database_connect in GridServer_Config.xml and we'll use that instead"); - - IniFile GridDataMySqlFile = new IniFile("mysql_connection.ini"); - string settingHostname = GridDataMySqlFile.ParseFileReadValue("hostname"); - string settingDatabase = GridDataMySqlFile.ParseFileReadValue("database"); - string settingUsername = GridDataMySqlFile.ParseFileReadValue("username"); - string settingPassword = GridDataMySqlFile.ParseFileReadValue("password"); - string settingPooling = GridDataMySqlFile.ParseFileReadValue("pooling"); - string settingPort = GridDataMySqlFile.ParseFileReadValue("port"); - - database = new MySQLManager(settingHostname, settingDatabase, settingUsername, settingPassword, - settingPooling, settingPort); - } - - // This actually does the roll forward assembly stuff - Assembly assem = GetType().Assembly; - - using (MySql.Data.MySqlClient.MySqlConnection dbcon = new MySql.Data.MySqlClient.MySqlConnection(connect)) - { - dbcon.Open(); - - Migration m = new Migration(dbcon, assem, "LogStore"); - - // TODO: After rev 6000, remove this. People should have - // been rolled onto the new migration code by then. - TestTables(m); - - m.Update(); - } - } - - /// - /// - private void TestTables(Migration m) - { - // under migrations, bail - if (m.Version > 0) - return; - - Dictionary tableList = new Dictionary(); - tableList["logs"] = null; - database.GetTableVersion(tableList); - - // migrations will handle it - if (tableList["logs"] == null) - return; - - // we have the table, so pretend like we did the first migration in the past - if (m.Version == 0) - m.Version = 1; - } - - /// - /// Saves a log item to the database - /// - /// The daemon triggering the event - /// The target of the action (region / agent UUID, etc) - /// The method call where the problem occured - /// The arguments passed to the method - /// How critical is this? - /// The message to log - public void saveLog(string serverDaemon, string target, string methodCall, string arguments, int priority, - string logMessage) - { - try - { - database.insertLogRow(serverDaemon, target, methodCall, arguments, priority, logMessage); - } - catch - { - } - } - - /// - /// Returns the name of this DB provider - /// - /// A string containing the DB provider name - public string Name - { - get { return "MySQL Logdata Interface";} - } - - /// - /// Closes the database provider - /// - /// do nothing - public void Dispose() - { - // Do nothing. - } - - /// - /// Returns the version of this DB provider - /// - /// A string containing the provider version - public string Version - { - get { return "0.1"; } - } - } -} diff --git a/OpenSim/Data/MySQL/MySQLManager.cs b/OpenSim/Data/MySQL/MySQLManager.cs deleted file mode 100644 index ace2027..0000000 --- a/OpenSim/Data/MySQL/MySQLManager.cs +++ /dev/null @@ -1,1248 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; -using System.IO; -using System.Reflection; -using log4net; -using MySql.Data.MySqlClient; -using OpenMetaverse; -using OpenSim.Framework; - -namespace OpenSim.Data.MySQL -{ - /// - /// A MySQL Database manager - /// - public class MySQLManager - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - /// - /// Connection string for ADO.net - /// - private string connectionString; - - private object m_dbLock = new object(); - - private const string m_waitTimeoutSelect = "select @@wait_timeout"; - - /// - /// Wait timeout for our connection in ticks. - /// - private long m_waitTimeout; - - /// - /// Make our storage of the timeout this amount smaller than it actually is, to give us a margin on long - /// running database operations. - /// - private long m_waitTimeoutLeeway = 60 * TimeSpan.TicksPerSecond; - - /// - /// Holds the last tick time that the connection was used. - /// - private long m_lastConnectionUse; - - /// - /// Initialises and creates a new MySQL connection and maintains it. - /// - /// The MySQL server being connected to - /// The name of the MySQL database being used - /// The username logging into the database - /// The password for the user logging in - /// Whether to use connection pooling or not, can be one of the following: 'yes', 'true', 'no' or 'false', if unsure use 'false'. - /// The MySQL server port - public MySQLManager(string hostname, string database, string username, string password, string cpooling, - string port) - { - string s = "Server=" + hostname + ";Port=" + port + ";Database=" + database + ";User ID=" + - username + ";Password=" + password + ";Pooling=" + cpooling + ";"; - - Initialise(s); - } - - /// - /// Initialises and creates a new MySQL connection and maintains it. - /// - /// connectionString - public MySQLManager(String connect) - { - Initialise(connect); - } - - /// - /// Initialises and creates a new MySQL connection and maintains it. - /// - /// connectionString - public void Initialise(String connect) - { - try - { - connectionString = connect; - //dbcon = new MySqlConnection(connectionString); - - try - { - //dbcon.Open(); - } - catch(Exception e) - { - throw new Exception("Connection error while using connection string ["+connectionString+"]", e); - } - - m_log.Info("[MYSQL]: Connection established"); - GetWaitTimeout(); - } - catch (Exception e) - { - throw new Exception("Error initialising MySql Database: " + e.ToString()); - } - } - - /// - /// Get the wait_timeout value for our connection - /// - protected void GetWaitTimeout() - { - using (MySqlConnection dbcon = new MySqlConnection(connectionString)) - { - dbcon.Open(); - - using (MySqlCommand cmd = new MySqlCommand(m_waitTimeoutSelect, dbcon)) - { - using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow)) - { - if (dbReader.Read()) - { - m_waitTimeout - = Convert.ToInt32(dbReader["@@wait_timeout"]) * TimeSpan.TicksPerSecond + m_waitTimeoutLeeway; - } - } - } - } - - m_lastConnectionUse = DateTime.Now.Ticks; - - m_log.DebugFormat( - "[REGION DB]: Connection wait timeout {0} seconds", m_waitTimeout / TimeSpan.TicksPerSecond); - } - - public string ConnectionString - { - get { return connectionString; } - } - - /// - /// Returns the version of this DB provider - /// - /// A string containing the DB provider - public string getVersion() - { - Module module = GetType().Module; - // string dllName = module.Assembly.ManifestModule.Name; - Version dllVersion = module.Assembly.GetName().Version; - - return - string.Format("{0}.{1}.{2}.{3}", dllVersion.Major, dllVersion.Minor, dllVersion.Build, - dllVersion.Revision); - } - - /// - /// Extract a named string resource from the embedded resources - /// - /// name of embedded resource - /// string contained within the embedded resource - private string getResourceString(string name) - { - Assembly assem = GetType().Assembly; - string[] names = assem.GetManifestResourceNames(); - - foreach (string s in names) - { - if (s.EndsWith(name)) - { - using (Stream resource = assem.GetManifestResourceStream(s)) - { - using (StreamReader resourceReader = new StreamReader(resource)) - { - string resourceString = resourceReader.ReadToEnd(); - return resourceString; - } - } - } - } - throw new Exception(string.Format("Resource '{0}' was not found", name)); - } - - /// - /// Execute a SQL statement stored in a resource, as a string - /// - /// name of embedded resource - public void ExecuteResourceSql(string name) - { - using (MySqlConnection dbcon = new MySqlConnection(connectionString)) - { - dbcon.Open(); - - MySqlCommand cmd = new MySqlCommand(getResourceString(name), dbcon); - cmd.ExecuteNonQuery(); - } - } - - /// - /// Execute a MySqlCommand - /// - /// sql string to execute - public void ExecuteSql(string sql) - { - using (MySqlConnection dbcon = new MySqlConnection(connectionString)) - { - dbcon.Open(); - - MySqlCommand cmd = new MySqlCommand(sql, dbcon); - cmd.ExecuteNonQuery(); - } - } - - public void ExecuteParameterizedSql(string sql, Dictionary parameters) - { - using (MySqlConnection dbcon = new MySqlConnection(connectionString)) - { - dbcon.Open(); - - MySqlCommand cmd = (MySqlCommand)dbcon.CreateCommand(); - cmd.CommandText = sql; - foreach (KeyValuePair param in parameters) - { - cmd.Parameters.AddWithValue(param.Key, param.Value); - } - cmd.ExecuteNonQuery(); - } - } - - /// - /// Given a list of tables, return the version of the tables, as seen in the database - /// - /// - public void GetTableVersion(Dictionary tableList) - { - lock (m_dbLock) - { - using (MySqlConnection dbcon = new MySqlConnection(connectionString)) - { - dbcon.Open(); - - using (MySqlCommand tablesCmd = new MySqlCommand( - "SELECT TABLE_NAME, TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=?dbname", dbcon)) - { - tablesCmd.Parameters.AddWithValue("?dbname", dbcon.Database); - - using (MySqlDataReader tables = tablesCmd.ExecuteReader()) - { - while (tables.Read()) - { - try - { - string tableName = (string)tables["TABLE_NAME"]; - string comment = (string)tables["TABLE_COMMENT"]; - if (tableList.ContainsKey(tableName)) - { - tableList[tableName] = comment; - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - } - } - } - } - } - } - } - - // TODO: at some time this code should be cleaned up - - /// - /// Runs a query with protection against SQL Injection by using parameterised input. - /// - /// Database connection - /// The SQL string - replace any variables such as WHERE x = "y" with WHERE x = @y - /// The parameters - index so that @y is indexed as 'y' - /// A MySQL DB Command - public IDbCommand Query(MySqlConnection dbcon, string sql, Dictionary parameters) - { - try - { - MySqlCommand dbcommand = (MySqlCommand)dbcon.CreateCommand(); - dbcommand.CommandText = sql; - foreach (KeyValuePair param in parameters) - { - dbcommand.Parameters.AddWithValue(param.Key, param.Value); - } - - return (IDbCommand)dbcommand; - } - catch (Exception e) - { - // Return null if it fails. - m_log.Error("Failed during Query generation: " + e.Message, e); - return null; - } - } - - /// - /// Reads a region row from a database reader - /// - /// An active database reader - /// A region profile - public RegionProfileData readSimRow(IDataReader reader) - { - RegionProfileData retval = new RegionProfileData(); - - if (reader.Read()) - { - // Region Main gotta-have-or-we-return-null parts - UInt64 tmp64; - if (!UInt64.TryParse(reader["regionHandle"].ToString(), out tmp64)) - { - return null; - } - else - { - retval.regionHandle = tmp64; - } - UUID tmp_uuid; - if (!UUID.TryParse((string)reader["uuid"], out tmp_uuid)) - { - return null; - } - else - { - retval.UUID = tmp_uuid; - } - - // non-critical parts - retval.regionName = (string)reader["regionName"]; - retval.originUUID = new UUID((string) reader["originUUID"]); - - // Secrets - retval.regionRecvKey = (string) reader["regionRecvKey"]; - retval.regionSecret = (string) reader["regionSecret"]; - retval.regionSendKey = (string) reader["regionSendKey"]; - - // Region Server - retval.regionDataURI = (string) reader["regionDataURI"]; - retval.regionOnline = false; // Needs to be pinged before this can be set. - retval.serverIP = (string) reader["serverIP"]; - retval.serverPort = (uint) reader["serverPort"]; - retval.serverURI = (string) reader["serverURI"]; - retval.httpPort = Convert.ToUInt32(reader["serverHttpPort"].ToString()); - retval.remotingPort = Convert.ToUInt32(reader["serverRemotingPort"].ToString()); - - // Location - retval.regionLocX = Convert.ToUInt32(reader["locX"].ToString()); - retval.regionLocY = Convert.ToUInt32(reader["locY"].ToString()); - retval.regionLocZ = Convert.ToUInt32(reader["locZ"].ToString()); - - // Neighbours - 0 = No Override - retval.regionEastOverrideHandle = Convert.ToUInt64(reader["eastOverrideHandle"].ToString()); - retval.regionWestOverrideHandle = Convert.ToUInt64(reader["westOverrideHandle"].ToString()); - retval.regionSouthOverrideHandle = Convert.ToUInt64(reader["southOverrideHandle"].ToString()); - retval.regionNorthOverrideHandle = Convert.ToUInt64(reader["northOverrideHandle"].ToString()); - - // Assets - retval.regionAssetURI = (string) reader["regionAssetURI"]; - retval.regionAssetRecvKey = (string) reader["regionAssetRecvKey"]; - retval.regionAssetSendKey = (string) reader["regionAssetSendKey"]; - - // Userserver - retval.regionUserURI = (string) reader["regionUserURI"]; - retval.regionUserRecvKey = (string) reader["regionUserRecvKey"]; - retval.regionUserSendKey = (string) reader["regionUserSendKey"]; - - // World Map Addition - UUID.TryParse((string)reader["regionMapTexture"], out retval.regionMapTextureID); - UUID.TryParse((string)reader["owner_uuid"], out retval.owner_uuid); - retval.maturity = Convert.ToUInt32(reader["access"]); - } - else - { - return null; - } - return retval; - } - - /// - /// Reads a reservation row from a database reader - /// - /// An active database reader - /// A reservation data object - public ReservationData readReservationRow(IDataReader reader) - { - ReservationData retval = new ReservationData(); - if (reader.Read()) - { - retval.gridRecvKey = (string) reader["gridRecvKey"]; - retval.gridSendKey = (string) reader["gridSendKey"]; - retval.reservationCompany = (string) reader["resCompany"]; - retval.reservationMaxX = Convert.ToInt32(reader["resXMax"].ToString()); - retval.reservationMaxY = Convert.ToInt32(reader["resYMax"].ToString()); - retval.reservationMinX = Convert.ToInt32(reader["resXMin"].ToString()); - retval.reservationMinY = Convert.ToInt32(reader["resYMin"].ToString()); - retval.reservationName = (string) reader["resName"]; - retval.status = Convert.ToInt32(reader["status"].ToString()) == 1; - UUID tmp; - UUID.TryParse((string) reader["userUUID"], out tmp); - retval.userUUID = tmp; - } - else - { - return null; - } - return retval; - } - - /// - /// Reads an agent row from a database reader - /// - /// An active database reader - /// A user session agent - public UserAgentData readAgentRow(IDataReader reader) - { - UserAgentData retval = new UserAgentData(); - - if (reader.Read()) - { - // Agent IDs - UUID tmp; - if (!UUID.TryParse((string)reader["UUID"], out tmp)) - return null; - retval.ProfileID = tmp; - - UUID.TryParse((string) reader["sessionID"], out tmp); - retval.SessionID = tmp; - - UUID.TryParse((string)reader["secureSessionID"], out tmp); - retval.SecureSessionID = tmp; - - // Agent Who? - retval.AgentIP = (string) reader["agentIP"]; - retval.AgentPort = Convert.ToUInt32(reader["agentPort"].ToString()); - retval.AgentOnline = Convert.ToBoolean(Convert.ToInt16(reader["agentOnline"].ToString())); - - // Login/Logout times (UNIX Epoch) - retval.LoginTime = Convert.ToInt32(reader["loginTime"].ToString()); - retval.LogoutTime = Convert.ToInt32(reader["logoutTime"].ToString()); - - // Current position - retval.Region = new UUID((string)reader["currentRegion"]); - retval.Handle = Convert.ToUInt64(reader["currentHandle"].ToString()); - Vector3 tmp_v; - Vector3.TryParse((string) reader["currentPos"], out tmp_v); - retval.Position = tmp_v; - Vector3.TryParse((string)reader["currentLookAt"], out tmp_v); - retval.LookAt = tmp_v; - } - else - { - return null; - } - return retval; - } - - /// - /// Reads a user profile from an active data reader - /// - /// An active database reader - /// A user profile - public UserProfileData readUserRow(IDataReader reader) - { - UserProfileData retval = new UserProfileData(); - - if (reader.Read()) - { - UUID id; - if (!UUID.TryParse((string)reader["UUID"], out id)) - return null; - - retval.ID = id; - retval.FirstName = (string) reader["username"]; - retval.SurName = (string) reader["lastname"]; - retval.Email = (reader.IsDBNull(reader.GetOrdinal("email"))) ? "" : (string) reader["email"]; - - retval.PasswordHash = (string) reader["passwordHash"]; - retval.PasswordSalt = (string) reader["passwordSalt"]; - - retval.HomeRegion = Convert.ToUInt64(reader["homeRegion"].ToString()); - retval.HomeLocation = new Vector3( - Convert.ToSingle(reader["homeLocationX"].ToString()), - Convert.ToSingle(reader["homeLocationY"].ToString()), - Convert.ToSingle(reader["homeLocationZ"].ToString())); - retval.HomeLookAt = new Vector3( - Convert.ToSingle(reader["homeLookAtX"].ToString()), - Convert.ToSingle(reader["homeLookAtY"].ToString()), - Convert.ToSingle(reader["homeLookAtZ"].ToString())); - - UUID regionID = UUID.Zero; - UUID.TryParse(reader["homeRegionID"].ToString(), out regionID); // it's ok if it doesn't work; just use UUID.Zero - retval.HomeRegionID = regionID; - - retval.Created = Convert.ToInt32(reader["created"].ToString()); - retval.LastLogin = Convert.ToInt32(reader["lastLogin"].ToString()); - - retval.UserInventoryURI = (string) reader["userInventoryURI"]; - retval.UserAssetURI = (string) reader["userAssetURI"]; - - retval.CanDoMask = Convert.ToUInt32(reader["profileCanDoMask"].ToString()); - retval.WantDoMask = Convert.ToUInt32(reader["profileWantDoMask"].ToString()); - - if (reader.IsDBNull(reader.GetOrdinal("profileAboutText"))) - retval.AboutText = ""; - else - retval.AboutText = (string) reader["profileAboutText"]; - - if (reader.IsDBNull(reader.GetOrdinal("profileFirstText"))) - retval.FirstLifeAboutText = ""; - else - retval.FirstLifeAboutText = (string)reader["profileFirstText"]; - - if (reader.IsDBNull(reader.GetOrdinal("profileImage"))) - retval.Image = UUID.Zero; - else { - UUID tmp; - UUID.TryParse((string)reader["profileImage"], out tmp); - retval.Image = tmp; - } - - if (reader.IsDBNull(reader.GetOrdinal("profileFirstImage"))) - retval.FirstLifeImage = UUID.Zero; - else { - UUID tmp; - UUID.TryParse((string)reader["profileFirstImage"], out tmp); - retval.FirstLifeImage = tmp; - } - - if (reader.IsDBNull(reader.GetOrdinal("webLoginKey"))) - { - retval.WebLoginKey = UUID.Zero; - } - else - { - UUID tmp; - UUID.TryParse((string)reader["webLoginKey"], out tmp); - retval.WebLoginKey = tmp; - } - - retval.UserFlags = Convert.ToInt32(reader["userFlags"].ToString()); - retval.GodLevel = Convert.ToInt32(reader["godLevel"].ToString()); - if (reader.IsDBNull(reader.GetOrdinal("customType"))) - retval.CustomType = ""; - else - retval.CustomType = reader["customType"].ToString(); - - if (reader.IsDBNull(reader.GetOrdinal("partner"))) - { - retval.Partner = UUID.Zero; - } - else - { - UUID tmp; - UUID.TryParse((string)reader["partner"], out tmp); - retval.Partner = tmp; - } - } - else - { - return null; - } - return retval; - } - - /// - /// Reads an avatar appearence from an active data reader - /// - /// An active database reader - /// An avatar appearence - public AvatarAppearance readAppearanceRow(IDataReader reader) - { - AvatarAppearance appearance = null; - if (reader.Read()) - { - appearance = new AvatarAppearance(); - appearance.Owner = new UUID((string)reader["owner"]); - appearance.Serial = Convert.ToInt32(reader["serial"]); - appearance.VisualParams = (byte[])reader["visual_params"]; - appearance.Texture = new Primitive.TextureEntry((byte[])reader["texture"], 0, ((byte[])reader["texture"]).Length); - appearance.AvatarHeight = (float)Convert.ToDouble(reader["avatar_height"]); - appearance.BodyItem = new UUID((string)reader["body_item"]); - appearance.BodyAsset = new UUID((string)reader["body_asset"]); - appearance.SkinItem = new UUID((string)reader["skin_item"]); - appearance.SkinAsset = new UUID((string)reader["skin_asset"]); - appearance.HairItem = new UUID((string)reader["hair_item"]); - appearance.HairAsset = new UUID((string)reader["hair_asset"]); - appearance.EyesItem = new UUID((string)reader["eyes_item"]); - appearance.EyesAsset = new UUID((string)reader["eyes_asset"]); - appearance.ShirtItem = new UUID((string)reader["shirt_item"]); - appearance.ShirtAsset = new UUID((string)reader["shirt_asset"]); - appearance.PantsItem = new UUID((string)reader["pants_item"]); - appearance.PantsAsset = new UUID((string)reader["pants_asset"]); - appearance.ShoesItem = new UUID((string)reader["shoes_item"]); - appearance.ShoesAsset = new UUID((string)reader["shoes_asset"]); - appearance.SocksItem = new UUID((string)reader["socks_item"]); - appearance.SocksAsset = new UUID((string)reader["socks_asset"]); - appearance.JacketItem = new UUID((string)reader["jacket_item"]); - appearance.JacketAsset = new UUID((string)reader["jacket_asset"]); - appearance.GlovesItem = new UUID((string)reader["gloves_item"]); - appearance.GlovesAsset = new UUID((string)reader["gloves_asset"]); - appearance.UnderShirtItem = new UUID((string)reader["undershirt_item"]); - appearance.UnderShirtAsset = new UUID((string)reader["undershirt_asset"]); - appearance.UnderPantsItem = new UUID((string)reader["underpants_item"]); - appearance.UnderPantsAsset = new UUID((string)reader["underpants_asset"]); - appearance.SkirtItem = new UUID((string)reader["skirt_item"]); - appearance.SkirtAsset = new UUID((string)reader["skirt_asset"]); - } - return appearance; - } - - // Read attachment list from data reader - public Hashtable readAttachments(IDataReader r) - { - Hashtable ret = new Hashtable(); - - while (r.Read()) - { - int attachpoint = Convert.ToInt32(r["attachpoint"]); - if (ret.ContainsKey(attachpoint)) - continue; - Hashtable item = new Hashtable(); - item.Add("item", r["item"].ToString()); - item.Add("asset", r["asset"].ToString()); - - ret.Add(attachpoint, item); - } - - return ret; - } - - /// - /// Inserts a new row into the log database - /// - /// The daemon which triggered this event - /// Who were we operating on when this occured (region UUID, user UUID, etc) - /// The method call where the problem occured - /// The arguments passed to the method - /// How critical is this? - /// Extra message info - /// Saved successfully? - public bool insertLogRow(string serverDaemon, string target, string methodCall, string arguments, int priority, - string logMessage) - { - string sql = "INSERT INTO logs (`target`, `server`, `method`, `arguments`, `priority`, `message`) VALUES "; - sql += "(?target, ?server, ?method, ?arguments, ?priority, ?message)"; - - Dictionary parameters = new Dictionary(); - parameters["?server"] = serverDaemon; - parameters["?target"] = target; - parameters["?method"] = methodCall; - parameters["?arguments"] = arguments; - parameters["?priority"] = priority.ToString(); - parameters["?message"] = logMessage; - - bool returnval = false; - - try - { - using (MySqlConnection dbcon = new MySqlConnection(connectionString)) - { - dbcon.Open(); - - IDbCommand result = Query(dbcon, sql, parameters); - - if (result.ExecuteNonQuery() == 1) - returnval = true; - - result.Dispose(); - } - } - catch (Exception e) - { - m_log.Error(e.ToString()); - return false; - } - - return returnval; - } - - /// - /// Creates a new user and inserts it into the database - /// - /// User ID - /// First part of the login - /// Second part of the login - /// A salted hash of the users password - /// The salt used for the password hash - /// A regionHandle of the users home region - /// The UUID of the user's home region - /// Home region position vector - /// Home region position vector - /// Home region position vector - /// Home region 'look at' vector - /// Home region 'look at' vector - /// Home region 'look at' vector - /// Account created (unix timestamp) - /// Last login (unix timestamp) - /// Users inventory URI - /// Users asset URI - /// I can do mask - /// I want to do mask - /// Profile text - /// Firstlife text - /// UUID for profile image - /// UUID for firstlife image - /// Ignored - /// Success? - public bool insertUserRow(UUID uuid, string username, string lastname, string email, string passwordHash, - string passwordSalt, UInt64 homeRegion, UUID homeRegionID, float homeLocX, float homeLocY, float homeLocZ, - float homeLookAtX, float homeLookAtY, float homeLookAtZ, int created, int lastlogin, - string inventoryURI, string assetURI, uint canDoMask, uint wantDoMask, - string aboutText, string firstText, - UUID profileImage, UUID firstImage, UUID webLoginKey, int userFlags, int godLevel, string customType, UUID partner) - { - m_log.Debug("[MySQLManager]: Creating profile for \"" + username + " " + lastname + "\" (" + uuid + ")"); - string sql = - "INSERT INTO users (`UUID`, `username`, `lastname`, `email`, `passwordHash`, `passwordSalt`, `homeRegion`, `homeRegionID`, "; - sql += - "`homeLocationX`, `homeLocationY`, `homeLocationZ`, `homeLookAtX`, `homeLookAtY`, `homeLookAtZ`, `created`, "; - sql += - "`lastLogin`, `userInventoryURI`, `userAssetURI`, `profileCanDoMask`, `profileWantDoMask`, `profileAboutText`, "; - sql += "`profileFirstText`, `profileImage`, `profileFirstImage`, `webLoginKey`, `userFlags`, `godLevel`, `customType`, `partner`) VALUES "; - - sql += "(?UUID, ?username, ?lastname, ?email, ?passwordHash, ?passwordSalt, ?homeRegion, ?homeRegionID, "; - sql += - "?homeLocationX, ?homeLocationY, ?homeLocationZ, ?homeLookAtX, ?homeLookAtY, ?homeLookAtZ, ?created, "; - sql += - "?lastLogin, ?userInventoryURI, ?userAssetURI, ?profileCanDoMask, ?profileWantDoMask, ?profileAboutText, "; - sql += "?profileFirstText, ?profileImage, ?profileFirstImage, ?webLoginKey, ?userFlags, ?godLevel, ?customType, ?partner)"; - - Dictionary parameters = new Dictionary(); - parameters["?UUID"] = uuid.ToString(); - parameters["?username"] = username; - parameters["?lastname"] = lastname; - parameters["?email"] = email; - parameters["?passwordHash"] = passwordHash; - parameters["?passwordSalt"] = passwordSalt; - parameters["?homeRegion"] = homeRegion; - parameters["?homeRegionID"] = homeRegionID.ToString(); - parameters["?homeLocationX"] = homeLocX; - parameters["?homeLocationY"] = homeLocY; - parameters["?homeLocationZ"] = homeLocZ; - parameters["?homeLookAtX"] = homeLookAtX; - parameters["?homeLookAtY"] = homeLookAtY; - parameters["?homeLookAtZ"] = homeLookAtZ; - parameters["?created"] = created; - parameters["?lastLogin"] = lastlogin; - parameters["?userInventoryURI"] = inventoryURI; - parameters["?userAssetURI"] = assetURI; - parameters["?profileCanDoMask"] = canDoMask; - parameters["?profileWantDoMask"] = wantDoMask; - parameters["?profileAboutText"] = aboutText; - parameters["?profileFirstText"] = firstText; - parameters["?profileImage"] = profileImage.ToString(); - parameters["?profileFirstImage"] = firstImage.ToString(); - parameters["?webLoginKey"] = webLoginKey.ToString(); - parameters["?userFlags"] = userFlags; - parameters["?godLevel"] = godLevel; - parameters["?customType"] = customType == null ? "" : customType; - parameters["?partner"] = partner.ToString(); - bool returnval = false; - - try - { - using (MySqlConnection dbcon = new MySqlConnection(connectionString)) - { - dbcon.Open(); - - IDbCommand result = Query(dbcon, sql, parameters); - - if (result.ExecuteNonQuery() == 1) - returnval = true; - - result.Dispose(); - } - } - catch (Exception e) - { - m_log.Error(e.ToString()); - return false; - } - - //m_log.Debug("[MySQLManager]: Fetch user retval == " + returnval.ToString()); - return returnval; - } - - /// - /// Update user data into the database where User ID = uuid - /// - /// User ID - /// First part of the login - /// Second part of the login - /// A salted hash of the users password - /// The salt used for the password hash - /// A regionHandle of the users home region - /// Home region position vector - /// Home region position vector - /// Home region position vector - /// Home region 'look at' vector - /// Home region 'look at' vector - /// Home region 'look at' vector - /// Account created (unix timestamp) - /// Last login (unix timestamp) - /// Users inventory URI - /// Users asset URI - /// I can do mask - /// I want to do mask - /// Profile text - /// Firstlife text - /// UUID for profile image - /// UUID for firstlife image - /// UUID for weblogin Key - /// Success? - public bool updateUserRow(UUID uuid, string username, string lastname, string email, string passwordHash, - string passwordSalt, UInt64 homeRegion, UUID homeRegionID, float homeLocX, float homeLocY, float homeLocZ, - float homeLookAtX, float homeLookAtY, float homeLookAtZ, int created, int lastlogin, - string inventoryURI, string assetURI, uint canDoMask, uint wantDoMask, - string aboutText, string firstText, - UUID profileImage, UUID firstImage, UUID webLoginKey, int userFlags, int godLevel, string customType, UUID partner) - { - string sql = "UPDATE users SET `username` = ?username , `lastname` = ?lastname, `email` = ?email "; - sql += ", `passwordHash` = ?passwordHash , `passwordSalt` = ?passwordSalt , "; - sql += "`homeRegion` = ?homeRegion , `homeRegionID` = ?homeRegionID, `homeLocationX` = ?homeLocationX , "; - sql += "`homeLocationY` = ?homeLocationY , `homeLocationZ` = ?homeLocationZ , "; - sql += "`homeLookAtX` = ?homeLookAtX , `homeLookAtY` = ?homeLookAtY , "; - sql += "`homeLookAtZ` = ?homeLookAtZ , `created` = ?created , `lastLogin` = ?lastLogin , "; - sql += "`userInventoryURI` = ?userInventoryURI , `userAssetURI` = ?userAssetURI , "; - sql += "`profileCanDoMask` = ?profileCanDoMask , `profileWantDoMask` = ?profileWantDoMask , "; - sql += "`profileAboutText` = ?profileAboutText , `profileFirstText` = ?profileFirstText, "; - sql += "`profileImage` = ?profileImage , `profileFirstImage` = ?profileFirstImage , "; - sql += "`userFlags` = ?userFlags , `godLevel` = ?godLevel , "; - sql += "`customType` = ?customType , `partner` = ?partner , "; - sql += "`webLoginKey` = ?webLoginKey WHERE UUID = ?UUID"; - - Dictionary parameters = new Dictionary(); - parameters["?UUID"] = uuid.ToString(); - parameters["?username"] = username; - parameters["?lastname"] = lastname; - parameters["?email"] = email; - parameters["?passwordHash"] = passwordHash; - parameters["?passwordSalt"] = passwordSalt; - parameters["?homeRegion"] = homeRegion; - parameters["?homeRegionID"] = homeRegionID.ToString(); - parameters["?homeLocationX"] = homeLocX; - parameters["?homeLocationY"] = homeLocY; - parameters["?homeLocationZ"] = homeLocZ; - parameters["?homeLookAtX"] = homeLookAtX; - parameters["?homeLookAtY"] = homeLookAtY; - parameters["?homeLookAtZ"] = homeLookAtZ; - parameters["?created"] = created; - parameters["?lastLogin"] = lastlogin; - parameters["?userInventoryURI"] = inventoryURI; - parameters["?userAssetURI"] = assetURI; - parameters["?profileCanDoMask"] = canDoMask; - parameters["?profileWantDoMask"] = wantDoMask; - parameters["?profileAboutText"] = aboutText; - parameters["?profileFirstText"] = firstText; - parameters["?profileImage"] = profileImage.ToString(); - parameters["?profileFirstImage"] = firstImage.ToString(); - parameters["?webLoginKey"] = webLoginKey.ToString(); - parameters["?userFlags"] = userFlags; - parameters["?godLevel"] = godLevel; - parameters["?customType"] = customType == null ? "" : customType; - parameters["?partner"] = partner.ToString(); - - bool returnval = false; - try - { - using (MySqlConnection dbcon = new MySqlConnection(connectionString)) - { - dbcon.Open(); - - IDbCommand result = Query(dbcon, sql, parameters); - - if (result.ExecuteNonQuery() == 1) - returnval = true; - - result.Dispose(); - } - } - catch (Exception e) - { - m_log.Error(e.ToString()); - return false; - } - - //m_log.Debug("[MySQLManager]: update user retval == " + returnval.ToString()); - return returnval; - } - - /// - /// Inserts a new region into the database - /// - /// The region to insert - /// Success? - public bool insertRegion(RegionProfileData regiondata) - { - bool GRID_ONLY_UPDATE_NECESSARY_DATA = false; - - string sql = String.Empty; - if (GRID_ONLY_UPDATE_NECESSARY_DATA) - { - sql += "INSERT INTO "; - } - else - { - sql += "REPLACE INTO "; - } - - sql += "regions (regionHandle, regionName, uuid, regionRecvKey, regionSecret, regionSendKey, regionDataURI, "; - sql += - "serverIP, serverPort, serverURI, locX, locY, locZ, eastOverrideHandle, westOverrideHandle, southOverrideHandle, northOverrideHandle, regionAssetURI, regionAssetRecvKey, "; - - // part of an initial brutish effort to provide accurate information (as per the xml region spec) - // wrt the ownership of a given region - // the (very bad) assumption is that this value is being read and handled inconsistently or - // not at all. Current strategy is to put the code in place to support the validity of this information - // and to roll forward debugging any issues from that point - // - // this particular section of the mod attempts to implement the commit of a supplied value - // server for the UUID of the region's owner (master avatar). It consists of the addition of the column and value to the relevant sql, - // as well as the related parameterization - sql += - "regionAssetSendKey, regionUserURI, regionUserRecvKey, regionUserSendKey, regionMapTexture, serverHttpPort, serverRemotingPort, owner_uuid, originUUID, access) VALUES "; - - sql += "(?regionHandle, ?regionName, ?uuid, ?regionRecvKey, ?regionSecret, ?regionSendKey, ?regionDataURI, "; - sql += - "?serverIP, ?serverPort, ?serverURI, ?locX, ?locY, ?locZ, ?eastOverrideHandle, ?westOverrideHandle, ?southOverrideHandle, ?northOverrideHandle, ?regionAssetURI, ?regionAssetRecvKey, "; - sql += - "?regionAssetSendKey, ?regionUserURI, ?regionUserRecvKey, ?regionUserSendKey, ?regionMapTexture, ?serverHttpPort, ?serverRemotingPort, ?owner_uuid, ?originUUID, ?access)"; - - if (GRID_ONLY_UPDATE_NECESSARY_DATA) - { - sql += "ON DUPLICATE KEY UPDATE serverIP = ?serverIP, serverPort = ?serverPort, serverURI = ?serverURI, owner_uuid - ?owner_uuid;"; - } - else - { - sql += ";"; - } - - Dictionary parameters = new Dictionary(); - - parameters["?regionHandle"] = regiondata.regionHandle.ToString(); - parameters["?regionName"] = regiondata.regionName.ToString(); - parameters["?uuid"] = regiondata.UUID.ToString(); - parameters["?regionRecvKey"] = regiondata.regionRecvKey.ToString(); - parameters["?regionSecret"] = regiondata.regionSecret.ToString(); - parameters["?regionSendKey"] = regiondata.regionSendKey.ToString(); - parameters["?regionDataURI"] = regiondata.regionDataURI.ToString(); - parameters["?serverIP"] = regiondata.serverIP.ToString(); - parameters["?serverPort"] = regiondata.serverPort.ToString(); - parameters["?serverURI"] = regiondata.serverURI.ToString(); - parameters["?locX"] = regiondata.regionLocX.ToString(); - parameters["?locY"] = regiondata.regionLocY.ToString(); - parameters["?locZ"] = regiondata.regionLocZ.ToString(); - parameters["?eastOverrideHandle"] = regiondata.regionEastOverrideHandle.ToString(); - parameters["?westOverrideHandle"] = regiondata.regionWestOverrideHandle.ToString(); - parameters["?northOverrideHandle"] = regiondata.regionNorthOverrideHandle.ToString(); - parameters["?southOverrideHandle"] = regiondata.regionSouthOverrideHandle.ToString(); - parameters["?regionAssetURI"] = regiondata.regionAssetURI.ToString(); - parameters["?regionAssetRecvKey"] = regiondata.regionAssetRecvKey.ToString(); - parameters["?regionAssetSendKey"] = regiondata.regionAssetSendKey.ToString(); - parameters["?regionUserURI"] = regiondata.regionUserURI.ToString(); - parameters["?regionUserRecvKey"] = regiondata.regionUserRecvKey.ToString(); - parameters["?regionUserSendKey"] = regiondata.regionUserSendKey.ToString(); - parameters["?regionMapTexture"] = regiondata.regionMapTextureID.ToString(); - parameters["?serverHttpPort"] = regiondata.httpPort.ToString(); - parameters["?serverRemotingPort"] = regiondata.remotingPort.ToString(); - parameters["?owner_uuid"] = regiondata.owner_uuid.ToString(); - parameters["?originUUID"] = regiondata.originUUID.ToString(); - parameters["?access"] = regiondata.maturity.ToString(); - - bool returnval = false; - - try - { - using (MySqlConnection dbcon = new MySqlConnection(connectionString)) - { - dbcon.Open(); - - IDbCommand result = Query(dbcon, sql, parameters); - - // int x; - // if ((x = result.ExecuteNonQuery()) > 0) - // { - // returnval = true; - // } - if (result.ExecuteNonQuery() > 0) - { - returnval = true; - } - result.Dispose(); - } - } - catch (Exception e) - { - m_log.Error(e.ToString()); - return false; - } - - return returnval; - } - - /// - /// Delete a region from the database - /// - /// The region to delete - /// Success? - //public bool deleteRegion(RegionProfileData regiondata) - public bool deleteRegion(string uuid) - { - bool returnval = false; - - string sql = "DELETE FROM regions WHERE uuid = ?uuid;"; - - Dictionary parameters = new Dictionary(); - - try - { - parameters["?uuid"] = uuid; - - using (MySqlConnection dbcon = new MySqlConnection(connectionString)) - { - dbcon.Open(); - - IDbCommand result = Query(dbcon, sql, parameters); - - // int x; - // if ((x = result.ExecuteNonQuery()) > 0) - // { - // returnval = true; - // } - if (result.ExecuteNonQuery() > 0) - { - returnval = true; - } - result.Dispose(); - } - } - catch (Exception e) - { - m_log.Error(e.ToString()); - return false; - } - - return returnval; - } - - /// - /// Creates a new agent and inserts it into the database - /// - /// The agent data to be inserted - /// Success? - public bool insertAgentRow(UserAgentData agentdata) - { - string sql = String.Empty; - sql += "REPLACE INTO "; - sql += "agents (UUID, sessionID, secureSessionID, agentIP, agentPort, agentOnline, loginTime, logoutTime, currentRegion, currentHandle, currentPos, currentLookAt) VALUES "; - sql += "(?UUID, ?sessionID, ?secureSessionID, ?agentIP, ?agentPort, ?agentOnline, ?loginTime, ?logoutTime, ?currentRegion, ?currentHandle, ?currentPos, ?currentLookAt);"; - Dictionary parameters = new Dictionary(); - - parameters["?UUID"] = agentdata.ProfileID.ToString(); - parameters["?sessionID"] = agentdata.SessionID.ToString(); - parameters["?secureSessionID"] = agentdata.SecureSessionID.ToString(); - parameters["?agentIP"] = agentdata.AgentIP.ToString(); - parameters["?agentPort"] = agentdata.AgentPort.ToString(); - parameters["?agentOnline"] = (agentdata.AgentOnline == true) ? "1" : "0"; - parameters["?loginTime"] = agentdata.LoginTime.ToString(); - parameters["?logoutTime"] = agentdata.LogoutTime.ToString(); - parameters["?currentRegion"] = agentdata.Region.ToString(); - parameters["?currentHandle"] = agentdata.Handle.ToString(); - parameters["?currentPos"] = "<" + (agentdata.Position.X).ToString().Replace(",", ".") + "," + (agentdata.Position.Y).ToString().Replace(",", ".") + "," + (agentdata.Position.Z).ToString().Replace(",", ".") + ">"; - parameters["?currentLookAt"] = "<" + (agentdata.LookAt.X).ToString().Replace(",", ".") + "," + (agentdata.LookAt.Y).ToString().Replace(",", ".") + "," + (agentdata.LookAt.Z).ToString().Replace(",", ".") + ">"; - - bool returnval = false; - - try - { - using (MySqlConnection dbcon = new MySqlConnection(connectionString)) - { - dbcon.Open(); - - IDbCommand result = Query(dbcon, sql, parameters); - - // int x; - // if ((x = result.ExecuteNonQuery()) > 0) - // { - // returnval = true; - // } - if (result.ExecuteNonQuery() > 0) - { - returnval = true; - } - result.Dispose(); - } - } - catch (Exception e) - { - m_log.Error(e.ToString()); - return false; - } - - return returnval; - } - - /// - /// Create (or replace if existing) an avatar appearence - /// - /// - /// Succes? - public bool insertAppearanceRow(AvatarAppearance appearance) - { - string sql = String.Empty; - sql += "REPLACE INTO "; - sql += "avatarappearance (owner, serial, visual_params, texture, avatar_height, "; - sql += "body_item, body_asset, skin_item, skin_asset, hair_item, hair_asset, eyes_item, eyes_asset, "; - sql += "shirt_item, shirt_asset, pants_item, pants_asset, shoes_item, shoes_asset, socks_item, socks_asset, "; - sql += "jacket_item, jacket_asset, gloves_item, gloves_asset, undershirt_item, undershirt_asset, underpants_item, underpants_asset, "; - sql += "skirt_item, skirt_asset) values ("; - sql += "?owner, ?serial, ?visual_params, ?texture, ?avatar_height, "; - sql += "?body_item, ?body_asset, ?skin_item, ?skin_asset, ?hair_item, ?hair_asset, ?eyes_item, ?eyes_asset, "; - sql += "?shirt_item, ?shirt_asset, ?pants_item, ?pants_asset, ?shoes_item, ?shoes_asset, ?socks_item, ?socks_asset, "; - sql += "?jacket_item, ?jacket_asset, ?gloves_item, ?gloves_asset, ?undershirt_item, ?undershirt_asset, ?underpants_item, ?underpants_asset, "; - sql += "?skirt_item, ?skirt_asset)"; - - bool returnval = false; - - // we want to send in byte data, which means we can't just pass down strings - try - { - using (MySqlConnection dbcon = new MySqlConnection(connectionString)) - { - dbcon.Open(); - - using (MySqlCommand cmd = (MySqlCommand)dbcon.CreateCommand()) - { - cmd.CommandText = sql; - cmd.Parameters.AddWithValue("?owner", appearance.Owner.ToString()); - cmd.Parameters.AddWithValue("?serial", appearance.Serial); - cmd.Parameters.AddWithValue("?visual_params", appearance.VisualParams); - cmd.Parameters.AddWithValue("?texture", appearance.Texture.GetBytes()); - cmd.Parameters.AddWithValue("?avatar_height", appearance.AvatarHeight); - cmd.Parameters.AddWithValue("?body_item", appearance.BodyItem.ToString()); - cmd.Parameters.AddWithValue("?body_asset", appearance.BodyAsset.ToString()); - cmd.Parameters.AddWithValue("?skin_item", appearance.SkinItem.ToString()); - cmd.Parameters.AddWithValue("?skin_asset", appearance.SkinAsset.ToString()); - cmd.Parameters.AddWithValue("?hair_item", appearance.HairItem.ToString()); - cmd.Parameters.AddWithValue("?hair_asset", appearance.HairAsset.ToString()); - cmd.Parameters.AddWithValue("?eyes_item", appearance.EyesItem.ToString()); - cmd.Parameters.AddWithValue("?eyes_asset", appearance.EyesAsset.ToString()); - cmd.Parameters.AddWithValue("?shirt_item", appearance.ShirtItem.ToString()); - cmd.Parameters.AddWithValue("?shirt_asset", appearance.ShirtAsset.ToString()); - cmd.Parameters.AddWithValue("?pants_item", appearance.PantsItem.ToString()); - cmd.Parameters.AddWithValue("?pants_asset", appearance.PantsAsset.ToString()); - cmd.Parameters.AddWithValue("?shoes_item", appearance.ShoesItem.ToString()); - cmd.Parameters.AddWithValue("?shoes_asset", appearance.ShoesAsset.ToString()); - cmd.Parameters.AddWithValue("?socks_item", appearance.SocksItem.ToString()); - cmd.Parameters.AddWithValue("?socks_asset", appearance.SocksAsset.ToString()); - cmd.Parameters.AddWithValue("?jacket_item", appearance.JacketItem.ToString()); - cmd.Parameters.AddWithValue("?jacket_asset", appearance.JacketAsset.ToString()); - cmd.Parameters.AddWithValue("?gloves_item", appearance.GlovesItem.ToString()); - cmd.Parameters.AddWithValue("?gloves_asset", appearance.GlovesAsset.ToString()); - cmd.Parameters.AddWithValue("?undershirt_item", appearance.UnderShirtItem.ToString()); - cmd.Parameters.AddWithValue("?undershirt_asset", appearance.UnderShirtAsset.ToString()); - cmd.Parameters.AddWithValue("?underpants_item", appearance.UnderPantsItem.ToString()); - cmd.Parameters.AddWithValue("?underpants_asset", appearance.UnderPantsAsset.ToString()); - cmd.Parameters.AddWithValue("?skirt_item", appearance.SkirtItem.ToString()); - cmd.Parameters.AddWithValue("?skirt_asset", appearance.SkirtAsset.ToString()); - - if (cmd.ExecuteNonQuery() > 0) - returnval = true; - } - } - } - catch (Exception e) - { - m_log.Error(e.ToString()); - return false; - } - - return returnval; - - } - - public void writeAttachments(UUID agentID, Hashtable data) - { - string sql = "delete from avatarattachments where UUID = ?uuid"; - - using (MySqlConnection dbcon = new MySqlConnection(connectionString)) - { - dbcon.Open(); - - MySqlCommand cmd = (MySqlCommand)dbcon.CreateCommand(); - cmd.CommandText = sql; - cmd.Parameters.AddWithValue("?uuid", agentID.ToString()); - - cmd.ExecuteNonQuery(); - - if (data == null) - return; - - sql = "insert into avatarattachments (UUID, attachpoint, item, asset) values (?uuid, ?attachpoint, ?item, ?asset)"; - - cmd = (MySqlCommand)dbcon.CreateCommand(); - cmd.CommandText = sql; - - foreach (DictionaryEntry e in data) - { - int attachpoint = Convert.ToInt32(e.Key); - - Hashtable item = (Hashtable)e.Value; - - cmd.Parameters.Clear(); - cmd.Parameters.AddWithValue("?uuid", agentID.ToString()); - cmd.Parameters.AddWithValue("?attachpoint", attachpoint); - cmd.Parameters.AddWithValue("?item", item["item"]); - cmd.Parameters.AddWithValue("?asset", item["asset"]); - - cmd.ExecuteNonQuery(); - } - } - } - } -} diff --git a/OpenSim/Data/MySQL/MySQLSuperManager.cs b/OpenSim/Data/MySQL/MySQLSuperManager.cs deleted file mode 100644 index c579432..0000000 --- a/OpenSim/Data/MySQL/MySQLSuperManager.cs +++ /dev/null @@ -1,52 +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.Threading; - -namespace OpenSim.Data.MySQL -{ - public class MySQLSuperManager - { - public bool Locked; - private readonly Mutex m_lock = new Mutex(false); - public MySQLManager Manager; - public string Running; - - public void GetLock() - { - Locked = true; - m_lock.WaitOne(); - } - - public void Release() - { - m_lock.ReleaseMutex(); - Locked = false; - } - - } -} diff --git a/OpenSim/Data/MySQL/MySQLUserData.cs b/OpenSim/Data/MySQL/MySQLUserData.cs deleted file mode 100644 index 0a9d2e3..0000000 --- a/OpenSim/Data/MySQL/MySQLUserData.cs +++ /dev/null @@ -1,766 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; -using System.Reflection; -using System.Text.RegularExpressions; -using System.Threading; -using log4net; -using MySql.Data.MySqlClient; -using OpenMetaverse; -using OpenSim.Framework; - -namespace OpenSim.Data.MySQL -{ - /// - /// A database interface class to a user profile storage system - /// - public class MySQLUserData : UserDataBase - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private MySQLManager m_database; - private string m_connectionString; - private object m_dbLock = new object(); - - public int m_maxConnections = 10; - public int m_lastConnect; - - private string m_agentsTableName = "agents"; - private string m_usersTableName = "users"; - private string m_userFriendsTableName = "userfriends"; - private string m_appearanceTableName = "avatarappearance"; - private string m_attachmentsTableName = "avatarattachments"; - - public override void Initialise() - { - m_log.Info("[MySQLUserData]: " + Name + " cannot be default-initialized!"); - throw new PluginNotInitialisedException(Name); - } - - /// - /// Initialise User Interface - /// Loads and initialises the MySQL storage plugin - /// Warns and uses the obsolete mysql_connection.ini if connect string is empty. - /// Checks for migration - /// - /// connect string. - public override void Initialise(string connect) - { - m_connectionString = connect; - m_database = new MySQLManager(connect); - - // This actually does the roll forward assembly stuff - Assembly assem = GetType().Assembly; - - using (MySql.Data.MySqlClient.MySqlConnection dbcon = new MySql.Data.MySqlClient.MySqlConnection(m_connectionString)) - { - dbcon.Open(); - Migration m = new Migration(dbcon, assem, "UserStore"); - m.Update(); - } - } - - public override void Dispose() - { - } - - // see IUserDataPlugin - public override UserProfileData GetUserByName(string user, string last) - { - try - { - Dictionary param = new Dictionary(); - param["?first"] = user; - param["?second"] = last; - - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - using (IDbCommand result = m_database.Query(dbcon, - "SELECT * FROM " + m_usersTableName + " WHERE username = ?first AND lastname = ?second", param)) - { - using (IDataReader reader = result.ExecuteReader()) - { - UserProfileData row = m_database.readUserRow(reader); - return row; - } - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return null; - } - } - - #region User Friends List Data - - public override void AddNewUserFriend(UUID friendlistowner, UUID friend, uint perms) - { - int dtvalue = Util.UnixTimeSinceEpoch(); - - Dictionary param = new Dictionary(); - param["?ownerID"] = friendlistowner.ToString(); - param["?friendID"] = friend.ToString(); - param["?friendPerms"] = perms.ToString(); - param["?datetimestamp"] = dtvalue.ToString(); - - try - { - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - using (IDbCommand adder = m_database.Query(dbcon, - "INSERT INTO `" + m_userFriendsTableName + "` " + - "(`ownerID`,`friendID`,`friendPerms`,`datetimestamp`) " + - "VALUES " + - "(?ownerID,?friendID,?friendPerms,?datetimestamp)", - param)) - { - adder.ExecuteNonQuery(); - } - - using (IDbCommand adder = m_database.Query(dbcon, - "INSERT INTO `" + m_userFriendsTableName + "` " + - "(`ownerID`,`friendID`,`friendPerms`,`datetimestamp`) " + - "VALUES " + - "(?friendID,?ownerID,?friendPerms,?datetimestamp)", - param)) - { - adder.ExecuteNonQuery(); - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return; - } - } - - public override void RemoveUserFriend(UUID friendlistowner, UUID friend) - { - Dictionary param = new Dictionary(); - param["?ownerID"] = friendlistowner.ToString(); - param["?friendID"] = friend.ToString(); - - try - { - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - using (IDbCommand updater = m_database.Query(dbcon, - "delete from " + m_userFriendsTableName + " where ownerID = ?ownerID and friendID = ?friendID", - param)) - { - updater.ExecuteNonQuery(); - } - - using (IDbCommand updater = m_database.Query(dbcon, - "delete from " + m_userFriendsTableName + " where ownerID = ?friendID and friendID = ?ownerID", - param)) - { - updater.ExecuteNonQuery(); - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return; - } - } - - public override void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms) - { - Dictionary param = new Dictionary(); - param["?ownerID"] = friendlistowner.ToString(); - param["?friendID"] = friend.ToString(); - param["?friendPerms"] = perms.ToString(); - - try - { - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - using (IDbCommand updater = m_database.Query(dbcon, - "update " + m_userFriendsTableName + - " SET friendPerms = ?friendPerms " + - "where ownerID = ?ownerID and friendID = ?friendID", - param)) - { - updater.ExecuteNonQuery(); - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return; - } - } - - public override List GetUserFriendList(UUID friendlistowner) - { - List Lfli = new List(); - - Dictionary param = new Dictionary(); - param["?ownerID"] = friendlistowner.ToString(); - - try - { - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - //Left Join userfriends to itself - using (IDbCommand result = m_database.Query(dbcon, - "select a.ownerID,a.friendID,a.friendPerms,b.friendPerms as ownerperms from " + - m_userFriendsTableName + " as a, " + m_userFriendsTableName + " as b" + - " where a.ownerID = ?ownerID and b.ownerID = a.friendID and b.friendID = a.ownerID", - param)) - { - using (IDataReader reader = result.ExecuteReader()) - { - while (reader.Read()) - { - FriendListItem fli = new FriendListItem(); - fli.FriendListOwner = new UUID((string)reader["ownerID"]); - fli.Friend = new UUID((string)reader["friendID"]); - fli.FriendPerms = (uint)Convert.ToInt32(reader["friendPerms"]); - - // This is not a real column in the database table, it's a joined column from the opposite record - fli.FriendListOwnerPerms = (uint)Convert.ToInt32(reader["ownerperms"]); - - Lfli.Add(fli); - } - } - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return Lfli; - } - - return Lfli; - } - - override public Dictionary GetFriendRegionInfos (List uuids) - { - Dictionary infos = new Dictionary(); - - try - { - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - foreach (UUID uuid in uuids) - { - Dictionary param = new Dictionary(); - param["?uuid"] = uuid.ToString(); - - using (IDbCommand result = m_database.Query(dbcon, "select agentOnline,currentHandle from " + m_agentsTableName + - " where UUID = ?uuid", param)) - { - using (IDataReader reader = result.ExecuteReader()) - { - while (reader.Read()) - { - FriendRegionInfo fri = new FriendRegionInfo(); - fri.isOnline = (sbyte)reader["agentOnline"] != 0; - fri.regionHandle = (ulong)reader["currentHandle"]; - - infos[uuid] = fri; - } - } - } - } - } - } - catch (Exception e) - { - m_log.Warn("[MYSQL]: Got exception on trying to find friends regions:", e); - m_log.Error(e.Message, e); - } - - return infos; - } - - #endregion - - public override List GeneratePickerResults(UUID queryID, string query) - { - List returnlist = new List(); - - Regex objAlphaNumericPattern = new Regex("[^a-zA-Z0-9]"); - - string[] querysplit; - querysplit = query.Split(' '); - if (querysplit.Length > 1 && querysplit[1].Trim() != String.Empty) - { - Dictionary param = new Dictionary(); - param["?first"] = objAlphaNumericPattern.Replace(querysplit[0], String.Empty) + "%"; - param["?second"] = objAlphaNumericPattern.Replace(querysplit[1], String.Empty) + "%"; - - try - { - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - using (IDbCommand result = m_database.Query(dbcon, - "SELECT UUID,username,lastname FROM " + m_usersTableName + - " WHERE username like ?first AND lastname like ?second LIMIT 100", - param)) - { - using (IDataReader reader = result.ExecuteReader()) - { - while (reader.Read()) - { - AvatarPickerAvatar user = new AvatarPickerAvatar(); - user.AvatarID = new UUID((string)reader["UUID"]); - user.firstName = (string)reader["username"]; - user.lastName = (string)reader["lastname"]; - returnlist.Add(user); - } - } - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return returnlist; - } - } - else - { - try - { - Dictionary param = new Dictionary(); - param["?first"] = objAlphaNumericPattern.Replace(querysplit[0], String.Empty) + "%"; - - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - using (IDbCommand result = m_database.Query(dbcon, - "SELECT UUID,username,lastname FROM " + m_usersTableName + - " WHERE username like ?first OR lastname like ?first LIMIT 100", - param)) - { - using (IDataReader reader = result.ExecuteReader()) - { - while (reader.Read()) - { - AvatarPickerAvatar user = new AvatarPickerAvatar(); - user.AvatarID = new UUID((string)reader["UUID"]); - user.firstName = (string)reader["username"]; - user.lastName = (string)reader["lastname"]; - returnlist.Add(user); - } - } - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return returnlist; - } - } - return returnlist; - } - - /// - /// See IUserDataPlugin - /// - /// User UUID - /// User profile data - public override UserProfileData GetUserByUUID(UUID uuid) - { - try - { - Dictionary param = new Dictionary(); - param["?uuid"] = uuid.ToString(); - - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - using (IDbCommand result = m_database.Query(dbcon, "SELECT * FROM " + m_usersTableName + " WHERE UUID = ?uuid", param)) - { - using (IDataReader reader = result.ExecuteReader()) - { - UserProfileData row = m_database.readUserRow(reader); - return row; - } - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return null; - } - } - - /// - /// Returns a user session searching by name - /// - /// The account name : "Username Lastname" - /// The users session - public override UserAgentData GetAgentByName(string name) - { - return GetAgentByName(name.Split(' ')[0], name.Split(' ')[1]); - } - - /// - /// Returns a user session by account name - /// - /// First part of the users account name - /// Second part of the users account name - /// The users session - public override UserAgentData GetAgentByName(string user, string last) - { - UserProfileData profile = GetUserByName(user, last); - return GetAgentByUUID(profile.ID); - } - - /// - /// - /// - /// - /// is it still used ? - public override void StoreWebLoginKey(UUID AgentID, UUID WebLoginKey) - { - Dictionary param = new Dictionary(); - param["?UUID"] = AgentID.ToString(); - param["?webLoginKey"] = WebLoginKey.ToString(); - - try - { - m_database.ExecuteParameterizedSql( - "update " + m_usersTableName + " SET webLoginKey = ?webLoginKey " + - "where UUID = ?UUID", - param); - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return; - } - } - - /// - /// Returns an agent session by account UUID - /// - /// The accounts UUID - /// The users session - public override UserAgentData GetAgentByUUID(UUID uuid) - { - try - { - Dictionary param = new Dictionary(); - param["?uuid"] = uuid.ToString(); - - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - using (IDbCommand result = m_database.Query(dbcon, "SELECT * FROM " + m_agentsTableName + " WHERE UUID = ?uuid", param)) - { - using (IDataReader reader = result.ExecuteReader()) - { - UserAgentData row = m_database.readAgentRow(reader); - return row; - } - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return null; - } - } - - /// - /// Creates a new users profile - /// - /// The user profile to create - public override void AddNewUserProfile(UserProfileData user) - { - UUID zero = UUID.Zero; - if (user.ID == zero) - { - return; - } - - try - { - m_database.insertUserRow( - user.ID, user.FirstName, user.SurName, user.Email, user.PasswordHash, user.PasswordSalt, - user.HomeRegion, user.HomeRegionID, user.HomeLocation.X, user.HomeLocation.Y, - user.HomeLocation.Z, - user.HomeLookAt.X, user.HomeLookAt.Y, user.HomeLookAt.Z, user.Created, - user.LastLogin, user.UserInventoryURI, user.UserAssetURI, - user.CanDoMask, user.WantDoMask, - user.AboutText, user.FirstLifeAboutText, user.Image, - user.FirstLifeImage, user.WebLoginKey, user.UserFlags, user.GodLevel, user.CustomType, user.Partner); - } - catch (Exception e) - { - m_log.Error(e.Message, e); - } - } - - /// - /// Creates a new agent - /// - /// The agent to create - public override void AddNewUserAgent(UserAgentData agent) - { - UUID zero = UUID.Zero; - if (agent.ProfileID == zero || agent.SessionID == zero) - return; - - try - { - m_database.insertAgentRow(agent); - } - catch (Exception e) - { - m_log.Error(e.Message, e); - } - } - - /// - /// Updates a user profile stored in the DB - /// - /// The profile data to use to update the DB - public override bool UpdateUserProfile(UserProfileData user) - { - try - { - m_database.updateUserRow( - user.ID, user.FirstName, user.SurName, user.Email, user.PasswordHash, user.PasswordSalt, - user.HomeRegion, user.HomeRegionID, user.HomeLocation.X, user.HomeLocation.Y, - user.HomeLocation.Z, user.HomeLookAt.X, - user.HomeLookAt.Y, user.HomeLookAt.Z, user.Created, user.LastLogin, - user.UserInventoryURI, - user.UserAssetURI, user.CanDoMask, user.WantDoMask, user.AboutText, - user.FirstLifeAboutText, user.Image, user.FirstLifeImage, user.WebLoginKey, - user.UserFlags, user.GodLevel, user.CustomType, user.Partner); - - return true; - } - catch - { - return false; - } - } - - /// - /// Performs a money transfer request between two accounts - /// - /// The senders account ID - /// The receivers account ID - /// The amount to transfer - /// Success? - public override bool MoneyTransferRequest(UUID from, UUID to, uint amount) - { - return false; - } - - /// - /// Performs an inventory transfer request between two accounts - /// - /// TODO: Move to inventory server - /// The senders account ID - /// The receivers account ID - /// The item to transfer - /// Success? - public override bool InventoryTransferRequest(UUID from, UUID to, UUID item) - { - return false; - } - - public override AvatarAppearance GetUserAppearance(UUID user) - { - try - { - Dictionary param = new Dictionary(); - param["?owner"] = user.ToString(); - - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - using (IDbCommand result = m_database.Query(dbcon, "SELECT * FROM " + m_appearanceTableName + " WHERE owner = ?owner", param)) - { - using (IDataReader reader = result.ExecuteReader()) - { - AvatarAppearance appearance = m_database.readAppearanceRow(reader); - - if (appearance == null) - { - m_log.WarnFormat("[USER DB] No appearance found for user {0}", user.ToString()); - return null; - } - else - { - appearance.SetAttachments(GetUserAttachments(user)); - return appearance; - } - } - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return null; - } - } - - /// - /// Updates an avatar appearence - /// - /// The user UUID - /// The avatar appearance - // override - public override void UpdateUserAppearance(UUID user, AvatarAppearance appearance) - { - try - { - appearance.Owner = user; - m_database.insertAppearanceRow(appearance); - - UpdateUserAttachments(user, appearance.GetAttachments()); - } - catch (Exception e) - { - m_log.Error(e.Message, e); - } - } - - /// - /// Database provider name - /// - /// Provider name - public override string Name - { - get { return "MySQL Userdata Interface"; } - } - - /// - /// Database provider version - /// - /// provider version - public override string Version - { - get { return "0.1"; } - } - - public Hashtable GetUserAttachments(UUID agentID) - { - Dictionary param = new Dictionary(); - param["?uuid"] = agentID.ToString(); - - try - { - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - using (IDbCommand result = m_database.Query(dbcon, - "SELECT attachpoint, item, asset from " + m_attachmentsTableName + " WHERE UUID = ?uuid", param)) - { - using (IDataReader reader = result.ExecuteReader()) - { - Hashtable ret = m_database.readAttachments(reader); - return ret; - } - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return null; - } - } - - public void UpdateUserAttachments(UUID agentID, Hashtable data) - { - m_database.writeAttachments(agentID, data); - } - - public override void ResetAttachments(UUID userID) - { - Dictionary param = new Dictionary(); - param["?uuid"] = userID.ToString(); - - m_database.ExecuteParameterizedSql( - "UPDATE " + m_attachmentsTableName + - " SET asset = '00000000-0000-0000-0000-000000000000' WHERE UUID = ?uuid", - param); - } - - public override void LogoutUsers(UUID regionID) - { - Dictionary param = new Dictionary(); - param["?regionID"] = regionID.ToString(); - - try - { - m_database.ExecuteParameterizedSql( - "update " + m_agentsTableName + " SET agentOnline = 0 " + - "where currentRegion = ?regionID", - param); - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return; - } - } - } -} diff --git a/OpenSim/Data/MySQL/Tests/MySQLAssetTest.cs b/OpenSim/Data/MySQL/Tests/MySQLAssetTest.cs index e1d3f81..a46fdf8 100644 --- a/OpenSim/Data/MySQL/Tests/MySQLAssetTest.cs +++ b/OpenSim/Data/MySQL/Tests/MySQLAssetTest.cs @@ -31,6 +31,7 @@ using OpenSim.Data.Tests; using log4net; using System.Reflection; using OpenSim.Tests.Common; +using MySql.Data.MySqlClient; namespace OpenSim.Data.MySQL.Tests { @@ -39,7 +40,7 @@ namespace OpenSim.Data.MySQL.Tests { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public string file; - public MySQLManager database; + private string m_connectionString; public string connect = "Server=localhost;Port=3306;Database=opensim-nunit;User ID=opensim-nunit;Password=opensim-nunit;Pooling=false;"; [TestFixtureSetUp] @@ -52,7 +53,6 @@ namespace OpenSim.Data.MySQL.Tests // tests. try { - database = new MySQLManager(connect); db = new MySQLAssetData(); db.Initialise(connect); } @@ -70,10 +70,22 @@ namespace OpenSim.Data.MySQL.Tests { db.Dispose(); } - if (database != null) + ExecuteSql("drop table migrations"); + ExecuteSql("drop table assets"); + } + + /// + /// Execute a MySqlCommand + /// + /// sql string to execute + private void ExecuteSql(string sql) + { + using (MySqlConnection dbcon = new MySqlConnection(connect)) { - database.ExecuteSql("drop table migrations"); - database.ExecuteSql("drop table assets"); + dbcon.Open(); + + MySqlCommand cmd = new MySqlCommand(sql, dbcon); + cmd.ExecuteNonQuery(); } } } diff --git a/OpenSim/Data/MySQL/Tests/MySQLEstateTest.cs b/OpenSim/Data/MySQL/Tests/MySQLEstateTest.cs index 48486b1..01afcae 100644 --- a/OpenSim/Data/MySQL/Tests/MySQLEstateTest.cs +++ b/OpenSim/Data/MySQL/Tests/MySQLEstateTest.cs @@ -31,6 +31,8 @@ using OpenSim.Data.Tests; using log4net; using System.Reflection; using OpenSim.Tests.Common; +using MySql.Data.MySqlClient; + namespace OpenSim.Data.MySQL.Tests { @@ -39,7 +41,6 @@ namespace OpenSim.Data.MySQL.Tests { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public string file; - public MySQLManager database; public string connect = "Server=localhost;Port=3306;Database=opensim-nunit;User ID=opensim-nunit;Password=opensim-nunit;Pooling=false;"; [TestFixtureSetUp] @@ -52,9 +53,8 @@ namespace OpenSim.Data.MySQL.Tests // tests. try { - database = new MySQLManager(connect); // clear db incase to ensure we are in a clean state - ClearDB(database); + ClearDB(); regionDb = new MySQLDataStore(); regionDb.Initialise(connect); @@ -75,29 +75,41 @@ namespace OpenSim.Data.MySQL.Tests { regionDb.Dispose(); } - ClearDB(database); + ClearDB(); } - private void ClearDB(MySQLManager manager) + private void ClearDB() { // if a new table is added, it has to be dropped here - if (manager != null) + ExecuteSql("drop table if exists migrations"); + ExecuteSql("drop table if exists prims"); + ExecuteSql("drop table if exists primshapes"); + ExecuteSql("drop table if exists primitems"); + ExecuteSql("drop table if exists terrain"); + ExecuteSql("drop table if exists land"); + ExecuteSql("drop table if exists landaccesslist"); + ExecuteSql("drop table if exists regionban"); + ExecuteSql("drop table if exists regionsettings"); + ExecuteSql("drop table if exists estate_managers"); + ExecuteSql("drop table if exists estate_groups"); + ExecuteSql("drop table if exists estate_users"); + ExecuteSql("drop table if exists estateban"); + ExecuteSql("drop table if exists estate_settings"); + ExecuteSql("drop table if exists estate_map"); + } + + /// + /// Execute a MySqlCommand + /// + /// sql string to execute + private void ExecuteSql(string sql) + { + using (MySqlConnection dbcon = new MySqlConnection(connect)) { - manager.ExecuteSql("drop table if exists migrations"); - manager.ExecuteSql("drop table if exists prims"); - manager.ExecuteSql("drop table if exists primshapes"); - manager.ExecuteSql("drop table if exists primitems"); - manager.ExecuteSql("drop table if exists terrain"); - manager.ExecuteSql("drop table if exists land"); - manager.ExecuteSql("drop table if exists landaccesslist"); - manager.ExecuteSql("drop table if exists regionban"); - manager.ExecuteSql("drop table if exists regionsettings"); - manager.ExecuteSql("drop table if exists estate_managers"); - manager.ExecuteSql("drop table if exists estate_groups"); - manager.ExecuteSql("drop table if exists estate_users"); - manager.ExecuteSql("drop table if exists estateban"); - manager.ExecuteSql("drop table if exists estate_settings"); - manager.ExecuteSql("drop table if exists estate_map"); + dbcon.Open(); + + MySqlCommand cmd = new MySqlCommand(sql, dbcon); + cmd.ExecuteNonQuery(); } } } diff --git a/OpenSim/Data/MySQL/Tests/MySQLGridTest.cs b/OpenSim/Data/MySQL/Tests/MySQLGridTest.cs deleted file mode 100644 index 8272316..0000000 --- a/OpenSim/Data/MySQL/Tests/MySQLGridTest.cs +++ /dev/null @@ -1,94 +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 NUnit.Framework; -using OpenSim.Data.Tests; -using log4net; -using System.Reflection; -using OpenSim.Tests.Common; -using MySql.Data.MySqlClient; - -namespace OpenSim.Data.MySQL.Tests -{ - [TestFixture, DatabaseTest] - public class MySQLGridTest : BasicGridTest - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - public string file; - public MySQLManager database; - public string connect = "Server=localhost;Port=3306;Database=opensim-nunit;User ID=opensim-nunit;Password=opensim-nunit;Pooling=false;"; - - [TestFixtureSetUp] - public void Init() - { - SuperInit(); - // If we manage to connect to the database with the user - // and password above it is our test database, and run - // these tests. If anything goes wrong, ignore these - // tests. - try - { - database = new MySQLManager(connect); - db = new MySQLGridData(); - db.Initialise(connect); - } - catch (Exception e) - { - m_log.Error("Exception {0}", e); - Assert.Ignore(); - } - - // This actually does the roll forward assembly stuff - Assembly assem = GetType().Assembly; - - using (MySqlConnection dbcon = new MySqlConnection(connect)) - { - dbcon.Open(); - Migration m = new Migration(dbcon, assem, "AssetStore"); - m.Update(); - } - } - - [TestFixtureTearDown] - public void Cleanup() - { - m_log.Warn("Cleaning up."); - if (db != null) - { - db.Dispose(); - } - // if a new table is added, it has to be dropped here - if (database != null) - { - database.ExecuteSql("drop table migrations"); - database.ExecuteSql("drop table regions"); - } - } - } -} diff --git a/OpenSim/Data/MySQL/Tests/MySQLInventoryTest.cs b/OpenSim/Data/MySQL/Tests/MySQLInventoryTest.cs index a3a32dc..4575493 100644 --- a/OpenSim/Data/MySQL/Tests/MySQLInventoryTest.cs +++ b/OpenSim/Data/MySQL/Tests/MySQLInventoryTest.cs @@ -31,6 +31,8 @@ using OpenSim.Data.Tests; using log4net; using System.Reflection; using OpenSim.Tests.Common; +using MySql.Data.MySqlClient; + namespace OpenSim.Data.MySQL.Tests { @@ -39,7 +41,6 @@ namespace OpenSim.Data.MySQL.Tests { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public string file; - public MySQLManager database; public string connect = "Server=localhost;Port=3306;Database=opensim-nunit;User ID=opensim-nunit;Password=opensim-nunit;Pooling=false;"; [TestFixtureSetUp] @@ -52,7 +53,6 @@ namespace OpenSim.Data.MySQL.Tests // tests. try { - database = new MySQLManager(connect); DropTables(); db = new MySQLInventoryData(); db.Initialise(connect); @@ -71,17 +71,29 @@ namespace OpenSim.Data.MySQL.Tests { db.Dispose(); } - if (database != null) - { - DropTables(); - } + DropTables(); } private void DropTables() { - database.ExecuteSql("drop table IF EXISTS inventoryitems"); - database.ExecuteSql("drop table IF EXISTS inventoryfolders"); - database.ExecuteSql("drop table IF EXISTS migrations"); + ExecuteSql("drop table IF EXISTS inventoryitems"); + ExecuteSql("drop table IF EXISTS inventoryfolders"); + ExecuteSql("drop table IF EXISTS migrations"); + } + + /// + /// Execute a MySqlCommand + /// + /// sql string to execute + private void ExecuteSql(string sql) + { + using (MySqlConnection dbcon = new MySqlConnection(connect)) + { + dbcon.Open(); + + MySqlCommand cmd = new MySqlCommand(sql, dbcon); + cmd.ExecuteNonQuery(); + } } } } diff --git a/OpenSim/Data/MySQL/Tests/MySQLRegionTest.cs b/OpenSim/Data/MySQL/Tests/MySQLRegionTest.cs index 0dc8b7d..e7e57e4 100644 --- a/OpenSim/Data/MySQL/Tests/MySQLRegionTest.cs +++ b/OpenSim/Data/MySQL/Tests/MySQLRegionTest.cs @@ -31,6 +31,7 @@ using OpenSim.Data.Tests; using log4net; using System.Reflection; using OpenSim.Tests.Common; +using MySql.Data.MySqlClient; namespace OpenSim.Data.MySQL.Tests { @@ -39,7 +40,6 @@ namespace OpenSim.Data.MySQL.Tests { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public string file; - public MySQLManager database; public string connect = "Server=localhost;Port=3306;Database=opensim-nunit;User ID=opensim-nunit;Password=opensim-nunit;Pooling=false;"; [TestFixtureSetUp] @@ -52,9 +52,8 @@ namespace OpenSim.Data.MySQL.Tests // tests. try { - database = new MySQLManager(connect); // this is important in case a previous run ended badly - ClearDB(database); + ClearDB(); db = new MySQLDataStore(); db.Initialise(connect); @@ -73,28 +72,40 @@ namespace OpenSim.Data.MySQL.Tests { db.Dispose(); } - ClearDB(database); + ClearDB(); } - private void ClearDB(MySQLManager manager) + private void ClearDB() { - if (manager != null) + ExecuteSql("drop table if exists migrations"); + ExecuteSql("drop table if exists prims"); + ExecuteSql("drop table if exists primshapes"); + ExecuteSql("drop table if exists primitems"); + ExecuteSql("drop table if exists terrain"); + ExecuteSql("drop table if exists land"); + ExecuteSql("drop table if exists landaccesslist"); + ExecuteSql("drop table if exists regionban"); + ExecuteSql("drop table if exists regionsettings"); + ExecuteSql("drop table if exists estate_managers"); + ExecuteSql("drop table if exists estate_groups"); + ExecuteSql("drop table if exists estate_users"); + ExecuteSql("drop table if exists estateban"); + ExecuteSql("drop table if exists estate_settings"); + ExecuteSql("drop table if exists estate_map"); + } + + /// + /// Execute a MySqlCommand + /// + /// sql string to execute + private void ExecuteSql(string sql) + { + using (MySqlConnection dbcon = new MySqlConnection(connect)) { - manager.ExecuteSql("drop table if exists migrations"); - manager.ExecuteSql("drop table if exists prims"); - manager.ExecuteSql("drop table if exists primshapes"); - manager.ExecuteSql("drop table if exists primitems"); - manager.ExecuteSql("drop table if exists terrain"); - manager.ExecuteSql("drop table if exists land"); - manager.ExecuteSql("drop table if exists landaccesslist"); - manager.ExecuteSql("drop table if exists regionban"); - manager.ExecuteSql("drop table if exists regionsettings"); - manager.ExecuteSql("drop table if exists estate_managers"); - manager.ExecuteSql("drop table if exists estate_groups"); - manager.ExecuteSql("drop table if exists estate_users"); - manager.ExecuteSql("drop table if exists estateban"); - manager.ExecuteSql("drop table if exists estate_settings"); - manager.ExecuteSql("drop table if exists estate_map"); + dbcon.Open(); + + MySqlCommand cmd = new MySqlCommand(sql, dbcon); + cmd.ExecuteNonQuery(); } } } diff --git a/OpenSim/Data/MySQL/Tests/MySQLUserTest.cs b/OpenSim/Data/MySQL/Tests/MySQLUserTest.cs deleted file mode 100644 index cf8139a..0000000 --- a/OpenSim/Data/MySQL/Tests/MySQLUserTest.cs +++ /dev/null @@ -1,85 +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 NUnit.Framework; -using OpenSim.Data.Tests; -using log4net; -using System.Reflection; -using OpenSim.Tests.Common; - -namespace OpenSim.Data.MySQL.Tests -{ - [TestFixture, DatabaseTest] - public class MySQLUserTest : BasicUserTest - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - public string file; - public MySQLManager database; - public string connect = "Server=localhost;Port=3306;Database=opensim-nunit;User ID=opensim-nunit;Password=opensim-nunit;Pooling=false;"; - - [TestFixtureSetUp] - public void Init() - { - SuperInit(); - // If we manage to connect to the database with the user - // and password above it is our test database, and run - // these tests. If anything goes wrong, ignore these - // tests. - try - { - database = new MySQLManager(connect); - db = new MySQLUserData(); - db.Initialise(connect); - } - catch (Exception e) - { - m_log.Error("Exception {0}", e); - Assert.Ignore(); - } - } - - [TestFixtureTearDown] - public void Cleanup() - { - if (db != null) - { - db.Dispose(); - } - // if a new table is added, it has to be dropped here - if (database != null) - { - database.ExecuteSql("drop table migrations"); - database.ExecuteSql("drop table users"); - database.ExecuteSql("drop table userfriends"); - database.ExecuteSql("drop table agents"); - database.ExecuteSql("drop table avatarappearance"); - database.ExecuteSql("drop table avatarattachments"); - } - } - } -} diff --git a/OpenSim/Data/RegionProfileData.cs b/OpenSim/Data/RegionProfileData.cs deleted file mode 100644 index 90713d2..0000000 --- a/OpenSim/Data/RegionProfileData.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 OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using Nwc.XmlRpc; -using OpenMetaverse; -using OpenSim.Framework; - -namespace OpenSim.Data -{ - /// - /// A class which contains information known to the grid server about a region - /// - [Serializable] - public class RegionProfileData - { - /// - /// The name of the region - /// - public string regionName = String.Empty; - - /// - /// A 64-bit number combining map position into a (mostly) unique ID - /// - public ulong regionHandle; - - /// - /// OGS/OpenSim Specific ID for a region - /// - public UUID UUID; - - /// - /// Coordinates of the region - /// - public uint regionLocX; - public uint regionLocY; - public uint regionLocZ; // Reserved (round-robin, layers, etc) - - /// - /// Authentication secrets - /// - /// Not very secure, needs improvement. - public string regionSendKey = String.Empty; - public string regionRecvKey = String.Empty; - public string regionSecret = String.Empty; - - /// - /// Whether the region is online - /// - public bool regionOnline; - - /// - /// Information about the server that the region is currently hosted on - /// - public string serverIP = String.Empty; - public uint serverPort; - public string serverURI = String.Empty; - - public uint httpPort; - public uint remotingPort; - public string httpServerURI = String.Empty; - - /// - /// Set of optional overrides. Can be used to create non-eulicidean spaces. - /// - public ulong regionNorthOverrideHandle; - public ulong regionSouthOverrideHandle; - public ulong regionEastOverrideHandle; - public ulong regionWestOverrideHandle; - - /// - /// Optional: URI Location of the region database - /// - /// Used for floating sim pools where the region data is not nessecarily coupled to a specific server - public string regionDataURI = String.Empty; - - /// - /// Region Asset Details - /// - public string regionAssetURI = String.Empty; - - public string regionAssetSendKey = String.Empty; - public string regionAssetRecvKey = String.Empty; - - /// - /// Region Userserver Details - /// - public string regionUserURI = String.Empty; - - public string regionUserSendKey = String.Empty; - public string regionUserRecvKey = String.Empty; - - /// - /// Region Map Texture Asset - /// - public UUID regionMapTextureID = new UUID("00000000-0000-1111-9999-000000000006"); - - /// - /// this particular mod to the file provides support within the spec for RegionProfileData for the - /// owner_uuid for the region - /// - public UUID owner_uuid = UUID.Zero; - - /// - /// OGS/OpenSim Specific original ID for a region after move/split - /// - public UUID originUUID; - - /// - /// The Maturity rating of the region - /// - public uint maturity; - - //Data Wrappers - public string RegionName - { - get { return regionName; } - set { regionName = value; } - } - public ulong RegionHandle - { - get { return regionHandle; } - set { regionHandle = value; } - } - public UUID Uuid - { - get { return UUID; } - set { UUID = value; } - } - public uint RegionLocX - { - get { return regionLocX; } - set { regionLocX = value; } - } - public uint RegionLocY - { - get { return regionLocY; } - set { regionLocY = value; } - } - public uint RegionLocZ - { - get { return regionLocZ; } - set { regionLocZ = value; } - } - public string RegionSendKey - { - get { return regionSendKey; } - set { regionSendKey = value; } - } - public string RegionRecvKey - { - get { return regionRecvKey; } - set { regionRecvKey = value; } - } - public string RegionSecret - { - get { return regionSecret; } - set { regionSecret = value; } - } - public bool RegionOnline - { - get { return regionOnline; } - set { regionOnline = value; } - } - public string ServerIP - { - get { return serverIP; } - set { serverIP = value; } - } - public uint ServerPort - { - get { return serverPort; } - set { serverPort = value; } - } - public string ServerURI - { - get { return serverURI; } - set { serverURI = value; } - } - public uint ServerHttpPort - { - get { return httpPort; } - set { httpPort = value; } - } - public uint ServerRemotingPort - { - get { return remotingPort; } - set { remotingPort = value; } - } - - public ulong NorthOverrideHandle - { - get { return regionNorthOverrideHandle; } - set { regionNorthOverrideHandle = value; } - } - public ulong SouthOverrideHandle - { - get { return regionSouthOverrideHandle; } - set { regionSouthOverrideHandle = value; } - } - public ulong EastOverrideHandle - { - get { return regionEastOverrideHandle; } - set { regionEastOverrideHandle = value; } - } - public ulong WestOverrideHandle - { - get { return regionWestOverrideHandle; } - set { regionWestOverrideHandle = value; } - } - public string RegionDataURI - { - get { return regionDataURI; } - set { regionDataURI = value; } - } - public string RegionAssetURI - { - get { return regionAssetURI; } - set { regionAssetURI = value; } - } - public string RegionAssetSendKey - { - get { return regionAssetSendKey; } - set { regionAssetSendKey = value; } - } - public string RegionAssetRecvKey - { - get { return regionAssetRecvKey; } - set { regionAssetRecvKey = value; } - } - public string RegionUserURI - { - get { return regionUserURI; } - set { regionUserURI = value; } - } - public string RegionUserSendKey - { - get { return regionUserSendKey; } - set { regionUserSendKey = value; } - } - public string RegionUserRecvKey - { - get { return regionUserRecvKey; } - set { regionUserRecvKey = value; } - } - public UUID RegionMapTextureID - { - get { return regionMapTextureID; } - set { regionMapTextureID = value; } - } - public UUID Owner_uuid - { - get { return owner_uuid; } - set { owner_uuid = value; } - } - public UUID OriginUUID - { - get { return originUUID; } - set { originUUID = value; } - } - public uint Maturity - { - get { return maturity; } - set { maturity = value; } - } - - public byte AccessLevel - { - get { return Util.ConvertMaturityToAccessLevel(maturity); } - } - - - public RegionInfo ToRegionInfo() - { - return RegionInfo.Create(UUID, regionName, regionLocX, regionLocY, serverIP, httpPort, serverPort, remotingPort, serverURI); - } - - public static RegionProfileData FromRegionInfo(RegionInfo regionInfo) - { - if (regionInfo == null) - { - return null; - } - - return Create(regionInfo.RegionID, regionInfo.RegionName, regionInfo.RegionLocX, - regionInfo.RegionLocY, regionInfo.ExternalHostName, - (uint) regionInfo.ExternalEndPoint.Port, regionInfo.HttpPort, regionInfo.RemotingPort, - regionInfo.ServerURI, regionInfo.AccessLevel); - } - - public static RegionProfileData Create(UUID regionID, string regionName, uint locX, uint locY, string externalHostName, uint regionPort, uint httpPort, uint remotingPort, string serverUri, byte access) - { - RegionProfileData regionProfile; - regionProfile = new RegionProfileData(); - regionProfile.regionLocX = locX; - regionProfile.regionLocY = locY; - regionProfile.regionHandle = - Utils.UIntsToLong((regionProfile.regionLocX * Constants.RegionSize), - (regionProfile.regionLocY*Constants.RegionSize)); - regionProfile.serverIP = externalHostName; - regionProfile.serverPort = regionPort; - regionProfile.httpPort = httpPort; - regionProfile.remotingPort = remotingPort; - regionProfile.serverURI = serverUri; - regionProfile.httpServerURI = "http://" + externalHostName + ":" + httpPort + "/"; - regionProfile.UUID = regionID; - regionProfile.regionName = regionName; - regionProfile.maturity = access; - return regionProfile; - } - } -} diff --git a/OpenSim/Data/RegionProfileServiceProxy.cs b/OpenSim/Data/RegionProfileServiceProxy.cs deleted file mode 100644 index 20d7df0..0000000 --- a/OpenSim/Data/RegionProfileServiceProxy.cs +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Text; -using Nwc.XmlRpc; -using OpenMetaverse; -using OpenSim.Framework; - -namespace OpenSim.Data -{ - public class RegionProfileServiceProxy : IRegionProfileRouter - { - /// - /// Request sim data based on arbitrary key/value - /// - private RegionProfileData RequestSimData(Uri gridserverUrl, string gridserverSendkey, string keyField, string keyValue) - { - Hashtable requestData = new Hashtable(); - requestData[keyField] = keyValue; - requestData["authkey"] = gridserverSendkey; - ArrayList SendParams = new ArrayList(); - SendParams.Add(requestData); - XmlRpcRequest GridReq = new XmlRpcRequest("simulator_data_request", SendParams); - XmlRpcResponse GridResp = GridReq.Send(gridserverUrl.ToString(), 3000); - - Hashtable responseData = (Hashtable) GridResp.Value; - - RegionProfileData simData = null; - - if (!responseData.ContainsKey("error")) - { - uint locX = Convert.ToUInt32((string)responseData["region_locx"]); - uint locY = Convert.ToUInt32((string)responseData["region_locy"]); - string externalHostName = (string)responseData["sim_ip"]; - uint simPort = Convert.ToUInt32((string)responseData["sim_port"]); - uint httpPort = Convert.ToUInt32((string)responseData["http_port"]); - uint remotingPort = Convert.ToUInt32((string)responseData["remoting_port"]); - string serverUri = (string)responseData["server_uri"]; - UUID regionID = new UUID((string)responseData["region_UUID"]); - string regionName = (string)responseData["region_name"]; - byte access = Convert.ToByte((string)responseData["access"]); - - simData = RegionProfileData.Create(regionID, regionName, locX, locY, externalHostName, simPort, httpPort, remotingPort, serverUri, access); - } - - return simData; - } - - /// - /// Request sim profile information from a grid server, by Region UUID - /// - /// The region UUID to look for - /// - /// - /// - /// The sim profile. Null if there was a request failure - /// This method should be statics - public RegionProfileData RequestSimProfileData(UUID regionId, Uri gridserverUrl, - string gridserverSendkey, string gridserverRecvkey) - { - return RequestSimData(gridserverUrl, gridserverSendkey, "region_UUID", regionId.Guid.ToString()); - } - - /// - /// Request sim profile information from a grid server, by Region Handle - /// - /// the region handle to look for - /// - /// - /// - /// The sim profile. Null if there was a request failure - public RegionProfileData RequestSimProfileData(ulong regionHandle, Uri gridserverUrl, - string gridserverSendkey, string gridserverRecvkey) - { - return RequestSimData(gridserverUrl, gridserverSendkey, "region_handle", regionHandle.ToString()); - } - - /// - /// Request sim profile information from a grid server, by Region Name - /// - /// the region name to look for - /// - /// - /// - /// The sim profile. Null if there was a request failure - public RegionProfileData RequestSimProfileData(string regionName, Uri gridserverUrl, - string gridserverSendkey, string gridserverRecvkey) - { - return RequestSimData(gridserverUrl, gridserverSendkey, "region_name_search", regionName); - } - } -} diff --git a/OpenSim/Data/ReservationData.cs b/OpenSim/Data/ReservationData.cs deleted file mode 100644 index 3956fe6..0000000 --- a/OpenSim/Data/ReservationData.cs +++ /dev/null @@ -1,48 +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 OpenMetaverse; - -namespace OpenSim.Data -{ - public class ReservationData - { - public UUID userUUID = UUID.Zero; - public int reservationMinX = 0; - public int reservationMinY = 0; - public int reservationMaxX = 65536; - public int reservationMaxY = 65536; - - public string reservationName = String.Empty; - public string reservationCompany = String.Empty; - public bool status = true; - - public string gridSendKey = String.Empty; - public string gridRecvKey = String.Empty; - } -} diff --git a/OpenSim/Data/SQLite/SQLiteGridData.cs b/OpenSim/Data/SQLite/SQLiteGridData.cs deleted file mode 100644 index 18abb88..0000000 --- a/OpenSim/Data/SQLite/SQLiteGridData.cs +++ /dev/null @@ -1,286 +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.Data; -using System.Reflection; -using log4net; -using OpenMetaverse; -using OpenSim.Framework; - -namespace OpenSim.Data.SQLite -{ - /// - /// A Grid Interface to the SQLite database - /// - public class SQLiteGridData : GridDataBase - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - /// - /// SQLite database manager - /// - private SQLiteManager database; - - override public void Initialise() - { - m_log.Info("[SQLite]: " + Name + " cannot be default-initialized!"); - throw new PluginNotInitialisedException (Name); - } - - /// - /// - /// Initialises Inventory interface - /// Loads and initialises a new SQLite connection and maintains it. - /// use default URI if connect string is empty. - /// - /// - /// connect string - override public void Initialise(string connect) - { - database = new SQLiteManager(connect); - } - - /// - /// Shuts down the grid interface - /// - override public void Dispose() - { - database.Close(); - } - - /// - /// Returns the name of this grid interface - /// - /// A string containing the grid interface - override public string Name - { - get { return "SQLite OpenGridData"; } - } - - /// - /// Returns the version of this grid interface - /// - /// A string containing the version - override public string Version - { - get { return "0.1"; } - } - - /// - /// Returns a list of regions within the specified ranges - /// - /// minimum X coordinate - /// minimum Y coordinate - /// maximum X coordinate - /// maximum Y coordinate - /// An array of region profiles - /// NOT IMPLEMENTED ? always return null - override public RegionProfileData[] GetProfilesInRange(uint a, uint b, uint c, uint d) - { - return null; - } - - - /// - /// Returns up to maxNum profiles of regions that have a name starting with namePrefix - /// - /// The name to match against - /// Maximum number of profiles to return - /// A list of sim profiles - override public List GetRegionsByName (string namePrefix, uint maxNum) - { - return null; - } - - /// - /// Returns a sim profile from it's handle - /// - /// Region location handle - /// Sim profile - override public RegionProfileData GetProfileByHandle(ulong handle) - { - Dictionary param = new Dictionary(); - param["handle"] = handle.ToString(); - - IDbCommand result = database.Query("SELECT * FROM regions WHERE handle = @handle", param); - IDataReader reader = result.ExecuteReader(); - - RegionProfileData row = database.getRow(reader); - reader.Close(); - result.Dispose(); - - return row; - } - - /// - /// Returns a sim profile from it's Region name string - /// - /// The region name search query - /// The sim profile - override public RegionProfileData GetProfileByString(string regionName) - { - if (regionName.Length > 2) - { - Dictionary param = new Dictionary(); - // Add % because this is a like query. - param["?regionName"] = regionName + "%"; - // Only returns one record or no record. - IDbCommand result = database.Query("SELECT * FROM regions WHERE regionName like ?regionName LIMIT 1", param); - IDataReader reader = result.ExecuteReader(); - - RegionProfileData row = database.getRow(reader); - reader.Close(); - result.Dispose(); - - return row; - } - else - { - //m_log.Error("[DATABASE]: Searched for a Region Name shorter then 3 characters"); - return null; - } - } - - /// - /// Returns a sim profile from it's UUID - /// - /// The region UUID - /// The sim profile - override public RegionProfileData GetProfileByUUID(UUID uuid) - { - Dictionary param = new Dictionary(); - param["uuid"] = uuid.ToString(); - - IDbCommand result = database.Query("SELECT * FROM regions WHERE uuid = @uuid", param); - IDataReader reader = result.ExecuteReader(); - - RegionProfileData row = database.getRow(reader); - reader.Close(); - result.Dispose(); - - return row; - } - - /// - /// Returns a list of avatar and UUIDs that match the query - /// - /// do nothing yet - public List GeneratePickerResults(UUID queryID, string query) - { - //Do nothing yet - List returnlist = new List(); - return returnlist; - } - - /// - /// Adds a new specified region to the database - /// - /// The profile to add - /// A dataresponse enum indicating success - override public DataResponse StoreProfile(RegionProfileData profile) - { - if (database.insertRow(profile)) - { - return DataResponse.RESPONSE_OK; - } - else - { - return DataResponse.RESPONSE_ERROR; - } - } - - /// - /// Deletes a sim profile from the database - /// - /// the sim UUID - /// Successful? - override public DataResponse DeleteProfile(string uuid) - { - Dictionary param = new Dictionary(); - param["uuid"] = uuid; - - IDbCommand result = database.Query("DELETE FROM regions WHERE uuid = @uuid", param); - if (result.ExecuteNonQuery() > 0) - { - return DataResponse.RESPONSE_OK; - } - return DataResponse.RESPONSE_ERROR; - } - - /// - /// DEPRECATED. Attempts to authenticate a region by comparing a shared secret. - /// - /// The UUID of the challenger - /// The attempted regionHandle of the challenger - /// The secret - /// Whether the secret and regionhandle match the database entry for UUID - override public bool AuthenticateSim(UUID uuid, ulong handle, string authkey) - { - bool throwHissyFit = false; // Should be true by 1.0 - - if (throwHissyFit) - throw new Exception("CRYPTOWEAK AUTHENTICATE: Refusing to authenticate due to replay potential."); - - RegionProfileData data = GetProfileByUUID(uuid); - - return (handle == data.regionHandle && authkey == data.regionSecret); - } - - /// - /// NOT YET FUNCTIONAL. Provides a cryptographic authentication of a region - /// - /// This requires a security audit. - /// - /// - /// - /// - /// - public bool AuthenticateSim(UUID uuid, ulong handle, string authhash, string challenge) - { - // SHA512Managed HashProvider = new SHA512Managed(); - // Encoding TextProvider = new UTF8Encoding(); - - // byte[] stream = TextProvider.GetBytes(uuid.ToString() + ":" + handle.ToString() + ":" + challenge); - // byte[] hash = HashProvider.ComputeHash(stream); - - return false; - } - - /// - /// NOT IMPLEMENTED - /// - /// x coordinate - /// y coordinate - /// always return null - override public ReservationData GetReservationAtPoint(uint x, uint y) - { - return null; - } - } -} diff --git a/OpenSim/Data/SQLite/SQLiteManager.cs b/OpenSim/Data/SQLite/SQLiteManager.cs deleted file mode 100644 index b6d4a1c..0000000 --- a/OpenSim/Data/SQLite/SQLiteManager.cs +++ /dev/null @@ -1,225 +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.Data; -using System.Data.SQLite; -using System.Reflection; -using log4net; -using OpenMetaverse; - -namespace OpenSim.Data.SQLite -{ - /// - /// SQLite Manager - /// - internal class SQLiteManager : SQLiteUtil - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private IDbConnection dbcon; - - /// - /// - /// Initialises and creates a new SQLite connection and maintains it. - /// use default URI if connect string is empty. - /// - /// - /// connect string - public SQLiteManager(string connect) - { - try - { - string connectionString = String.Empty; - if (connect != String.Empty) - { - connectionString = connect; - } - else - { - m_log.Warn("[SQLITE] grid db not specified, using default"); - connectionString = "URI=file:GridServerSqlite.db;"; - } - - dbcon = new SQLiteConnection(connectionString); - - dbcon.Open(); - } - catch (Exception e) - { - throw new Exception("Error initialising SQLite Database: " + e.ToString()); - } - } - - /// - /// Shuts down the database connection - /// - public void Close() - { - dbcon.Close(); - dbcon = null; - } - - /// - /// Runs a query with protection against SQL Injection by using parameterised input. - /// - /// The SQL string - replace any variables such as WHERE x = "y" with WHERE x = @y - /// The parameters - index so that @y is indexed as 'y' - /// A SQLite DB Command - public IDbCommand Query(string sql, Dictionary parameters) - { - SQLiteCommand dbcommand = (SQLiteCommand) dbcon.CreateCommand(); - dbcommand.CommandText = sql; - foreach (KeyValuePair param in parameters) - { - SQLiteParameter paramx = new SQLiteParameter(param.Key, param.Value); - dbcommand.Parameters.Add(paramx); - } - - return (IDbCommand) dbcommand; - } - - /// - /// Reads a region row from a database reader - /// - /// An active database reader - /// A region profile - public RegionProfileData getRow(IDataReader reader) - { - RegionProfileData retval = new RegionProfileData(); - - if (reader.Read()) - { - // Region Main - retval.regionHandle = (ulong) reader["regionHandle"]; - retval.regionName = (string) reader["regionName"]; - retval.UUID = new UUID((string) reader["uuid"]); - - // Secrets - retval.regionRecvKey = (string) reader["regionRecvKey"]; - retval.regionSecret = (string) reader["regionSecret"]; - retval.regionSendKey = (string) reader["regionSendKey"]; - - // Region Server - retval.regionDataURI = (string) reader["regionDataURI"]; - retval.regionOnline = false; // Needs to be pinged before this can be set. - retval.serverIP = (string) reader["serverIP"]; - retval.serverPort = (uint) reader["serverPort"]; - retval.serverURI = (string) reader["serverURI"]; - - // Location - retval.regionLocX = (uint) ((int) reader["locX"]); - retval.regionLocY = (uint) ((int) reader["locY"]); - retval.regionLocZ = (uint) ((int) reader["locZ"]); - - // Neighbours - 0 = No Override - retval.regionEastOverrideHandle = (ulong) reader["eastOverrideHandle"]; - retval.regionWestOverrideHandle = (ulong) reader["westOverrideHandle"]; - retval.regionSouthOverrideHandle = (ulong) reader["southOverrideHandle"]; - retval.regionNorthOverrideHandle = (ulong) reader["northOverrideHandle"]; - - // Assets - retval.regionAssetURI = (string) reader["regionAssetURI"]; - retval.regionAssetRecvKey = (string) reader["regionAssetRecvKey"]; - retval.regionAssetSendKey = (string) reader["regionAssetSendKey"]; - - // Userserver - retval.regionUserURI = (string) reader["regionUserURI"]; - retval.regionUserRecvKey = (string) reader["regionUserRecvKey"]; - retval.regionUserSendKey = (string) reader["regionUserSendKey"]; - } - else - { - throw new Exception("No rows to return"); - } - return retval; - } - - /// - /// Inserts a new region into the database - /// - /// The region to insert - /// Success? - public bool insertRow(RegionProfileData profile) - { - string sql = - "REPLACE INTO regions VALUES (regionHandle, regionName, uuid, regionRecvKey, regionSecret, regionSendKey, regionDataURI, "; - sql += - "serverIP, serverPort, serverURI, locX, locY, locZ, eastOverrideHandle, westOverrideHandle, southOverrideHandle, northOverrideHandle, regionAssetURI, regionAssetRecvKey, "; - sql += "regionAssetSendKey, regionUserURI, regionUserRecvKey, regionUserSendKey) VALUES "; - - sql += "(@regionHandle, @regionName, @uuid, @regionRecvKey, @regionSecret, @regionSendKey, @regionDataURI, "; - sql += - "@serverIP, @serverPort, @serverURI, @locX, @locY, @locZ, @eastOverrideHandle, @westOverrideHandle, @southOverrideHandle, @northOverrideHandle, @regionAssetURI, @regionAssetRecvKey, "; - sql += "@regionAssetSendKey, @regionUserURI, @regionUserRecvKey, @regionUserSendKey);"; - - Dictionary parameters = new Dictionary(); - - parameters["regionHandle"] = profile.regionHandle.ToString(); - parameters["regionName"] = profile.regionName; - parameters["uuid"] = profile.UUID.ToString(); - parameters["regionRecvKey"] = profile.regionRecvKey; - parameters["regionSendKey"] = profile.regionSendKey; - parameters["regionDataURI"] = profile.regionDataURI; - parameters["serverIP"] = profile.serverIP; - parameters["serverPort"] = profile.serverPort.ToString(); - parameters["serverURI"] = profile.serverURI; - parameters["locX"] = profile.regionLocX.ToString(); - parameters["locY"] = profile.regionLocY.ToString(); - parameters["locZ"] = profile.regionLocZ.ToString(); - parameters["eastOverrideHandle"] = profile.regionEastOverrideHandle.ToString(); - parameters["westOverrideHandle"] = profile.regionWestOverrideHandle.ToString(); - parameters["northOverrideHandle"] = profile.regionNorthOverrideHandle.ToString(); - parameters["southOverrideHandle"] = profile.regionSouthOverrideHandle.ToString(); - parameters["regionAssetURI"] = profile.regionAssetURI; - parameters["regionAssetRecvKey"] = profile.regionAssetRecvKey; - parameters["regionAssetSendKey"] = profile.regionAssetSendKey; - parameters["regionUserURI"] = profile.regionUserURI; - parameters["regionUserRecvKey"] = profile.regionUserRecvKey; - parameters["regionUserSendKey"] = profile.regionUserSendKey; - - bool returnval = false; - - try - { - IDbCommand result = Query(sql, parameters); - - if (result.ExecuteNonQuery() == 1) - returnval = true; - - result.Dispose(); - } - catch (Exception) - { - return false; - } - - return returnval; - } - } -} diff --git a/OpenSim/Data/SQLite/SQLiteUserData.cs b/OpenSim/Data/SQLite/SQLiteUserData.cs deleted file mode 100644 index caddcf8..0000000 --- a/OpenSim/Data/SQLite/SQLiteUserData.cs +++ /dev/null @@ -1,1262 +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.Data; -using System.Reflection; -using log4net; -using Mono.Data.SqliteClient; -using OpenMetaverse; -using OpenSim.Framework; - -namespace OpenSim.Data.SQLite -{ - /// - /// A User storage interface for the SQLite database system - /// - public class SQLiteUserData : UserDataBase - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - /// - /// The database manager - /// - /// - /// Artificial constructor called upon plugin load - /// - private const string SelectUserByUUID = "select * from users where UUID=:UUID"; - private const string SelectUserByName = "select * from users where username=:username and surname=:surname"; - private const string SelectFriendsByUUID = "select a.friendID, a.friendPerms, b.friendPerms from userfriends as a, userfriends as b where a.ownerID=:ownerID and b.ownerID=a.friendID and b.friendID=a.ownerID"; - - private const string userSelect = "select * from users"; - private const string userFriendsSelect = "select a.ownerID as ownerID,a.friendID as friendID,a.friendPerms as friendPerms,b.friendPerms as ownerperms, b.ownerID as fownerID, b.friendID as ffriendID from userfriends as a, userfriends as b"; - private const string userAgentSelect = "select * from useragents"; - private const string AvatarAppearanceSelect = "select * from avatarappearance"; - - private const string AvatarPickerAndSQL = "select * from users where username like :username and surname like :surname"; - private const string AvatarPickerOrSQL = "select * from users where username like :username or surname like :surname"; - - private DataSet ds; - private SqliteDataAdapter da; - private SqliteDataAdapter daf; - private SqliteDataAdapter dua; - private SqliteDataAdapter daa; - SqliteConnection g_conn; - - public override void Initialise() - { - m_log.Info("[SQLiteUserData]: " + Name + " cannot be default-initialized!"); - throw new PluginNotInitialisedException (Name); - } - - /// - /// - /// Initialises User Interface - /// Loads and initialises a new SQLite connection and maintains it. - /// use default URI if connect string string is empty. - /// - /// - /// connect string - override public void Initialise(string connect) - { - // default to something sensible - if (connect == "") - connect = "URI=file:userprofiles.db,version=3"; - - SqliteConnection conn = new SqliteConnection(connect); - - // This sucks, but It doesn't seem to work with the dataset Syncing :P - g_conn = conn; - g_conn.Open(); - - Assembly assem = GetType().Assembly; - Migration m = new Migration(g_conn, assem, "UserStore"); - m.Update(); - - - ds = new DataSet(); - da = new SqliteDataAdapter(new SqliteCommand(userSelect, conn)); - dua = new SqliteDataAdapter(new SqliteCommand(userAgentSelect, conn)); - daf = new SqliteDataAdapter(new SqliteCommand(userFriendsSelect, conn)); - daa = new SqliteDataAdapter(new SqliteCommand(AvatarAppearanceSelect, conn)); - //if (daa == null) m_log.Info("[SQLiteUserData]: daa = null"); - - lock (ds) - { - ds.Tables.Add(createUsersTable()); - ds.Tables.Add(createUserAgentsTable()); - ds.Tables.Add(createUserFriendsTable()); - ds.Tables.Add(createAvatarAppearanceTable()); - - setupUserCommands(da, conn); - da.Fill(ds.Tables["users"]); - - setupAgentCommands(dua, conn); - dua.Fill(ds.Tables["useragents"]); - - setupUserFriendsCommands(daf, conn); - daf.Fill(ds.Tables["userfriends"]); - - setupAvatarAppearanceCommands(daa, conn); - daa.Fill(ds.Tables["avatarappearance"]); - } - - return; - } - - public override void Dispose () - { - if (g_conn != null) - { - g_conn.Close(); - g_conn = null; - } - if (ds != null) - { - ds.Dispose(); - ds = null; - } - if (da != null) - { - da.Dispose(); - da = null; - } - if (daf != null) - { - daf.Dispose(); - daf = null; - } - if (dua != null) - { - dua.Dispose(); - dua = null; - } - if (daa != null) - { - daa.Dispose(); - daa = null; - } - } - - /// - /// see IUserDataPlugin, - /// Get user data profile by UUID - /// - /// User UUID - /// user profile data - override public UserProfileData GetUserByUUID(UUID uuid) - { - lock (ds) - { - DataRow row = ds.Tables["users"].Rows.Find(uuid.ToString()); - if (row != null) - { - UserProfileData user = buildUserProfile(row); - return user; - } - else - { - return null; - } - } - } - - /// - /// see IUserDataPlugin, - /// Get user data profile by name - /// - /// first name - /// last name - /// user profile data - override public UserProfileData GetUserByName(string fname, string lname) - { - string select = "surname = '" + lname + "' and username = '" + fname + "'"; - lock (ds) - { - DataRow[] rows = ds.Tables["users"].Select(select); - if (rows.Length > 0) - { - UserProfileData user = buildUserProfile(rows[0]); - return user; - } - else - { - return null; - } - } - } - - #region User Friends List Data - - private bool ExistsFriend(UUID owner, UUID friend) - { - string FindFriends = "select * from userfriends where (ownerID=:ownerID and friendID=:friendID) or (ownerID=:friendID and friendID=:ownerID)"; - using (SqliteCommand cmd = new SqliteCommand(FindFriends, g_conn)) - { - cmd.Parameters.Add(new SqliteParameter(":ownerID", owner.ToString())); - cmd.Parameters.Add(new SqliteParameter(":friendID", friend.ToString())); - try - { - using (IDataReader reader = cmd.ExecuteReader()) - { - if (reader.Read()) - { - reader.Close(); - return true; - } - else - { - reader.Close(); - return false; - } - } - } - catch (Exception ex) - { - m_log.Error("[USER DB]: Exception getting friends list for user: " + ex.ToString()); - return false; - } - } - } - /// - /// Add a new friend in the friendlist - /// - /// UUID of the friendlist owner - /// UUID of the friend to add - /// permission flag - override public void AddNewUserFriend(UUID friendlistowner, UUID friend, uint perms) - { - if (ExistsFriend(friendlistowner, friend)) - return; - - string InsertFriends = "insert into userfriends(ownerID, friendID, friendPerms) values(:ownerID, :friendID, :perms)"; - using (SqliteCommand cmd = new SqliteCommand(InsertFriends, g_conn)) - { - cmd.Parameters.Add(new SqliteParameter(":ownerID", friendlistowner.ToString())); - cmd.Parameters.Add(new SqliteParameter(":friendID", friend.ToString())); - cmd.Parameters.Add(new SqliteParameter(":perms", perms)); - cmd.ExecuteNonQuery(); - } - using (SqliteCommand cmd = new SqliteCommand(InsertFriends, g_conn)) - { - cmd.Parameters.Add(new SqliteParameter(":ownerID", friend.ToString())); - cmd.Parameters.Add(new SqliteParameter(":friendID", friendlistowner.ToString())); - cmd.Parameters.Add(new SqliteParameter(":perms", perms)); - cmd.ExecuteNonQuery(); - } - } - - /// - /// Remove a user from the friendlist - /// - /// UUID of the friendlist owner - /// UUID of the friend to remove - override public void RemoveUserFriend(UUID friendlistowner, UUID friend) - { - string DeletePerms = "delete from userfriends where (ownerID=:ownerID and friendID=:friendID) or (ownerID=:friendID and friendID=:ownerID)"; - using (SqliteCommand cmd = new SqliteCommand(DeletePerms, g_conn)) - { - cmd.Parameters.Add(new SqliteParameter(":ownerID", friendlistowner.ToString())); - cmd.Parameters.Add(new SqliteParameter(":friendID", friend.ToString())); - cmd.ExecuteNonQuery(); - } - } - - /// - /// Update the friendlist permission - /// - /// UUID of the friendlist owner - /// UUID of the friend to modify - /// updated permission flag - override public void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms) - { - string UpdatePerms = "update userfriends set friendPerms=:perms where ownerID=:ownerID and friendID=:friendID"; - using (SqliteCommand cmd = new SqliteCommand(UpdatePerms, g_conn)) - { - cmd.Parameters.Add(new SqliteParameter(":perms", perms)); - cmd.Parameters.Add(new SqliteParameter(":ownerID", friendlistowner.ToString())); - cmd.Parameters.Add(new SqliteParameter(":friendID", friend.ToString())); - cmd.ExecuteNonQuery(); - } - } - - /// - /// Get (fetch?) the friendlist for a user - /// - /// UUID of the friendlist owner - /// The friendlist list - override public List GetUserFriendList(UUID friendlistowner) - { - List returnlist = new List(); - - using (SqliteCommand cmd = new SqliteCommand(SelectFriendsByUUID, g_conn)) - { - cmd.Parameters.Add(new SqliteParameter(":ownerID", friendlistowner.ToString())); - - try - { - using (IDataReader reader = cmd.ExecuteReader()) - { - while (reader.Read()) - { - FriendListItem user = new FriendListItem(); - user.FriendListOwner = friendlistowner; - user.Friend = new UUID((string)reader[0]); - user.FriendPerms = Convert.ToUInt32(reader[1]); - user.FriendListOwnerPerms = Convert.ToUInt32(reader[2]); - returnlist.Add(user); - } - reader.Close(); - } - } - catch (Exception ex) - { - m_log.Error("[USER DB]: Exception getting friends list for user: " + ex.ToString()); - } - } - - return returnlist; - } - - override public Dictionary GetFriendRegionInfos (List uuids) - { - Dictionary infos = new Dictionary(); - - DataTable agents = ds.Tables["useragents"]; - foreach (UUID uuid in uuids) - { - lock (ds) - { - DataRow row = agents.Rows.Find(uuid.ToString()); - if (row == null) infos[uuid] = null; - else - { - FriendRegionInfo fri = new FriendRegionInfo(); - fri.isOnline = (bool)row["agentOnline"]; - fri.regionHandle = Convert.ToUInt64(row["currentHandle"]); - infos[uuid] = fri; - } - } - } - return infos; - } - - #endregion - - /// - /// - /// - /// - /// - /// - override public List GeneratePickerResults(UUID queryID, string query) - { - List returnlist = new List(); - string[] querysplit; - querysplit = query.Split(' '); - if (querysplit.Length == 2) - { - using (SqliteCommand cmd = new SqliteCommand(AvatarPickerAndSQL, g_conn)) - { - cmd.Parameters.Add(new SqliteParameter(":username", querysplit[0] + "%")); - cmd.Parameters.Add(new SqliteParameter(":surname", querysplit[1] + "%")); - - using (IDataReader reader = cmd.ExecuteReader()) - { - while (reader.Read()) - { - AvatarPickerAvatar user = new AvatarPickerAvatar(); - user.AvatarID = new UUID((string) reader["UUID"]); - user.firstName = (string) reader["username"]; - user.lastName = (string) reader["surname"]; - returnlist.Add(user); - } - reader.Close(); - } - } - } - else if (querysplit.Length == 1) - { - using (SqliteCommand cmd = new SqliteCommand(AvatarPickerOrSQL, g_conn)) - { - cmd.Parameters.Add(new SqliteParameter(":username", querysplit[0] + "%")); - cmd.Parameters.Add(new SqliteParameter(":surname", querysplit[0] + "%")); - - using (IDataReader reader = cmd.ExecuteReader()) - { - while (reader.Read()) - { - AvatarPickerAvatar user = new AvatarPickerAvatar(); - user.AvatarID = new UUID((string) reader["UUID"]); - user.firstName = (string) reader["username"]; - user.lastName = (string) reader["surname"]; - returnlist.Add(user); - } - reader.Close(); - } - } - } - return returnlist; - } - - /// - /// Returns a user by UUID direct - /// - /// The user's account ID - /// A matching user profile - override public UserAgentData GetAgentByUUID(UUID uuid) - { - lock (ds) - { - DataRow row = ds.Tables["useragents"].Rows.Find(uuid.ToString()); - if (row != null) - { - return buildUserAgent(row); - } - else - { - return null; - } - } - } - - /// - /// Returns a session by account name - /// - /// The account name - /// The user's session agent - override public UserAgentData GetAgentByName(string name) - { - return GetAgentByName(name.Split(' ')[0], name.Split(' ')[1]); - } - - /// - /// Returns a session by account name - /// - /// The first part of the user's account name - /// The second part of the user's account name - /// A user agent - override public UserAgentData GetAgentByName(string fname, string lname) - { - UserAgentData agent = null; - - UserProfileData profile = GetUserByName(fname, lname); - if (profile != null) - { - agent = GetAgentByUUID(profile.ID); - } - return agent; - } - - /// - /// DEPRECATED? Store the weblogin key - /// - /// UUID of the user - /// UUID of the weblogin - override public void StoreWebLoginKey(UUID AgentID, UUID WebLoginKey) - { - DataTable users = ds.Tables["users"]; - lock (ds) - { - DataRow row = users.Rows.Find(AgentID.ToString()); - if (row == null) - { - m_log.Warn("[USER DB]: Unable to store new web login key for non-existant user"); - } - else - { - UserProfileData user = GetUserByUUID(AgentID); - user.WebLoginKey = WebLoginKey; - fillUserRow(row, user); - da.Update(ds, "users"); - } - } - } - - private bool ExistsFirstLastName(String fname, String lname) - { - string FindUser = "select * from users where (username=:username and surname=:surname)"; - using (SqliteCommand cmd = new SqliteCommand(FindUser, g_conn)) - { - cmd.Parameters.Add(new SqliteParameter(":username", fname)); - cmd.Parameters.Add(new SqliteParameter(":surname", lname)); - try - { - using (IDataReader reader = cmd.ExecuteReader()) - { - if (reader.Read()) - { - reader.Close(); - return true; - } - else - { - reader.Close(); - return false; - } - } - } - catch (Exception ex) - { - m_log.Error("[USER DB]: Exception searching for user's first and last name: " + ex.ToString()); - return false; - } - } - } - - /// - /// Creates a new user profile - /// - /// The profile to add to the database - override public void AddNewUserProfile(UserProfileData user) - { - DataTable users = ds.Tables["users"]; - UUID zero = UUID.Zero; - if (ExistsFirstLastName(user.FirstName, user.SurName) || user.ID == zero) - return; - - lock (ds) - { - DataRow row = users.Rows.Find(user.ID.ToString()); - if (row == null) - { - row = users.NewRow(); - fillUserRow(row, user); - users.Rows.Add(row); - - m_log.Debug("[USER DB]: Syncing user database: " + ds.Tables["users"].Rows.Count + " users stored"); - - // save changes off to disk - da.Update(ds, "users"); - } - else - { - m_log.WarnFormat("[USER DB]: Ignoring add since user with id {0} already exists", user.ID); - } - } - } - - /// - /// Creates a new user profile - /// - /// The profile to add to the database - /// True on success, false on error - override public bool UpdateUserProfile(UserProfileData user) - { - DataTable users = ds.Tables["users"]; - lock (ds) - { - DataRow row = users.Rows.Find(user.ID.ToString()); - if (row == null) - { - return false; - } - else - { - fillUserRow(row, user); - da.Update(ds, "users"); - } - } - - //AddNewUserProfile(user); - return true; - } - - /// - /// Creates a new user agent - /// - /// The agent to add to the database - override public void AddNewUserAgent(UserAgentData agent) - { - UUID zero = UUID.Zero; - if (agent.SessionID == zero || agent.ProfileID == zero) - return; - - DataTable agents = ds.Tables["useragents"]; - lock (ds) - { - DataRow row = agents.Rows.Find(agent.ProfileID.ToString()); - if (row == null) - { - row = agents.NewRow(); - fillUserAgentRow(row, agent); - agents.Rows.Add(row); - } - else - { - fillUserAgentRow(row, agent); - - } - m_log.Info("[USER DB]: Syncing useragent database: " + ds.Tables["useragents"].Rows.Count + " agents stored"); - // save changes off to disk - dua.Update(ds, "useragents"); - } - } - - /// - /// Transfers money between two user accounts - /// - /// Starting account - /// End account - /// The amount to move - /// Success? - override public bool MoneyTransferRequest(UUID from, UUID to, uint amount) - { - return false; // for consistency with the MySQL impl - } - - /// - /// Transfers inventory between two accounts - /// - /// Move to inventory server - /// Senders account - /// Receivers account - /// Inventory item - /// Success? - override public bool InventoryTransferRequest(UUID from, UUID to, UUID item) - { - return false; //for consistency with the MySQL impl - } - - - /// - /// Appearance. - /// TODO: stubs for now to do in memory appearance. - /// - /// The user UUID - /// Avatar Appearence - override public AvatarAppearance GetUserAppearance(UUID user) - { - m_log.Info("[APPEARANCE] GetUserAppearance " + user.ToString()); - - AvatarAppearance aa = new AvatarAppearance(user); - //try { - aa.Owner = user; - - DataTable aap = ds.Tables["avatarappearance"]; - lock (ds) - { - DataRow row = aap.Rows.Find(Util.ToRawUuidString(user)); - if (row == null) - { - m_log.Info("[APPEARANCE] Could not find appearance for " + user.ToString()); - - //m_log.Debug("[USER DB]: Creating avatarappearance For: " + user.ToString()); - - //row = aap.NewRow(); - //fillAvatarAppearanceRow(row, user, appearance); - //aap.Rows.Add(row); - // m_log.Debug("[USER DB]: Syncing user database: " + ds.Tables["users"].Rows.Count + " users stored"); - // save changes off to disk - //daa.Update(ds, "avatarappearance"); - } - else - { - m_log.InfoFormat("[APPEARANCE] appearance found for {0}", user.ToString()); - - aa.BodyAsset = new UUID((String)row["BodyAsset"]); - aa.BodyItem = new UUID((String)row["BodyItem"]); - aa.SkinItem = new UUID((String)row["SkinItem"]); - aa.SkinAsset = new UUID((String)row["SkinAsset"]); - aa.HairItem = new UUID((String)row["HairItem"]); - aa.HairAsset = new UUID((String)row["HairAsset"]); - aa.EyesItem = new UUID((String)row["EyesItem"]); - aa.EyesAsset = new UUID((String)row["EyesAsset"]); - aa.ShirtItem = new UUID((String)row["ShirtItem"]); - aa.ShirtAsset = new UUID((String)row["ShirtAsset"]); - aa.PantsItem = new UUID((String)row["PantsItem"]); - aa.PantsAsset = new UUID((String)row["PantsAsset"]); - aa.ShoesItem = new UUID((String)row["ShoesItem"]); - aa.ShoesAsset = new UUID((String)row["ShoesAsset"]); - aa.SocksItem = new UUID((String)row["SocksItem"]); - aa.SocksAsset = new UUID((String)row["SocksAsset"]); - aa.JacketItem = new UUID((String)row["JacketItem"]); - aa.JacketAsset = new UUID((String)row["JacketAsset"]); - aa.GlovesItem = new UUID((String)row["GlovesItem"]); - aa.GlovesAsset = new UUID((String)row["GlovesAsset"]); - aa.UnderShirtItem = new UUID((String)row["UnderShirtItem"]); - aa.UnderShirtAsset = new UUID((String)row["UnderShirtAsset"]); - aa.UnderPantsItem = new UUID((String)row["UnderPantsItem"]); - aa.UnderPantsAsset = new UUID((String)row["UnderPantsAsset"]); - aa.SkirtItem = new UUID((String)row["SkirtItem"]); - aa.SkirtAsset = new UUID((String)row["SkirtAsset"]); - - // Ewe Loon - // Used Base64String because for some reason it wont accept using Byte[] (which works in Region date) - - String str = (String)row["Texture"]; - byte[] texture = Convert.FromBase64String(str); - aa.Texture = new Primitive.TextureEntry(texture, 0, texture.Length); - - str = (String)row["VisualParams"]; - byte[] VisualParams = Convert.FromBase64String(str); - aa.VisualParams = VisualParams; - - aa.Serial = Convert.ToInt32(row["Serial"]); - aa.AvatarHeight = Convert.ToSingle(row["AvatarHeight"]); - m_log.InfoFormat("[APPEARANCE] appearance set for {0}", user.ToString()); - } - } - - // m_log.Info("[APPEARANCE] Found appearance for " + user.ToString() + aa.ToString()); - // } catch (KeyNotFoundException) { - // m_log.InfoFormat("[APPEARANCE] No appearance found for {0}", user.ToString()); - // } - return aa; - } - - /// - /// Update a user appearence - /// - /// the user UUID - /// appearence - override public void UpdateUserAppearance(UUID user, AvatarAppearance appearance) - { - appearance.Owner = user; - DataTable aap = ds.Tables["avatarappearance"]; - lock (ds) - { - DataRow row = aap.Rows.Find(Util.ToRawUuidString(user)); - if (row == null) - { - m_log.Debug("[USER DB]: Creating UserAppearance For: " + user.ToString()); - - row = aap.NewRow(); - fillAvatarAppearanceRow(row, user, appearance); - aap.Rows.Add(row); - // m_log.Debug("[USER DB]: Syncing user database: " + ds.Tables["users"].Rows.Count + " users stored"); - // save changes off to disk - daa.Update(ds, "avatarappearance"); - } - else - { - m_log.Debug("[USER DB]: Updating UserAppearance For: " + user.ToString()); - fillAvatarAppearanceRow(row, user, appearance); - daa.Update(ds, "avatarappearance"); - } - } - } - - /// - /// Returns the name of the storage provider - /// - /// Storage provider name - override public string Name - { - get {return "Sqlite Userdata";} - } - - /// - /// Returns the version of the storage provider - /// - /// Storage provider version - override public string Version - { - get {return "0.1";} - } - - /*********************************************************************** - * - * DataTable creation - * - **********************************************************************/ - /*********************************************************************** - * - * Database Definition Functions - * - * This should be db agnostic as we define them in ADO.NET terms - * - **********************************************************************/ - - /// - /// Create the "users" table - /// - /// DataTable - private static DataTable createUsersTable() - { - DataTable users = new DataTable("users"); - - SQLiteUtil.createCol(users, "UUID", typeof (String)); - SQLiteUtil.createCol(users, "username", typeof (String)); - SQLiteUtil.createCol(users, "surname", typeof (String)); - SQLiteUtil.createCol(users, "email", typeof (String)); - SQLiteUtil.createCol(users, "passwordHash", typeof (String)); - SQLiteUtil.createCol(users, "passwordSalt", typeof (String)); - - SQLiteUtil.createCol(users, "homeRegionX", typeof (Int32)); - SQLiteUtil.createCol(users, "homeRegionY", typeof (Int32)); - SQLiteUtil.createCol(users, "homeRegionID", typeof (String)); - SQLiteUtil.createCol(users, "homeLocationX", typeof (Double)); - SQLiteUtil.createCol(users, "homeLocationY", typeof (Double)); - SQLiteUtil.createCol(users, "homeLocationZ", typeof (Double)); - SQLiteUtil.createCol(users, "homeLookAtX", typeof (Double)); - SQLiteUtil.createCol(users, "homeLookAtY", typeof (Double)); - SQLiteUtil.createCol(users, "homeLookAtZ", typeof (Double)); - SQLiteUtil.createCol(users, "created", typeof (Int32)); - SQLiteUtil.createCol(users, "lastLogin", typeof (Int32)); - - //TODO: Please delete this column. It's now a brick - SQLiteUtil.createCol(users, "rootInventoryFolderID", typeof (String)); - - SQLiteUtil.createCol(users, "userInventoryURI", typeof (String)); - SQLiteUtil.createCol(users, "userAssetURI", typeof (String)); - SQLiteUtil.createCol(users, "profileCanDoMask", typeof (Int32)); - SQLiteUtil.createCol(users, "profileWantDoMask", typeof (Int32)); - SQLiteUtil.createCol(users, "profileAboutText", typeof (String)); - SQLiteUtil.createCol(users, "profileFirstText", typeof (String)); - SQLiteUtil.createCol(users, "profileImage", typeof (String)); - SQLiteUtil.createCol(users, "profileFirstImage", typeof (String)); - SQLiteUtil.createCol(users, "webLoginKey", typeof(String)); - SQLiteUtil.createCol(users, "userFlags", typeof (Int32)); - SQLiteUtil.createCol(users, "godLevel", typeof (Int32)); - SQLiteUtil.createCol(users, "customType", typeof (String)); - SQLiteUtil.createCol(users, "partner", typeof (String)); - // Add in contraints - users.PrimaryKey = new DataColumn[] {users.Columns["UUID"]}; - return users; - } - - /// - /// Create the "useragents" table - /// - /// Data Table - private static DataTable createUserAgentsTable() - { - DataTable ua = new DataTable("useragents"); - // this is the UUID of the user - SQLiteUtil.createCol(ua, "UUID", typeof (String)); - SQLiteUtil.createCol(ua, "agentIP", typeof (String)); - SQLiteUtil.createCol(ua, "agentPort", typeof (Int32)); - SQLiteUtil.createCol(ua, "agentOnline", typeof (Boolean)); - SQLiteUtil.createCol(ua, "sessionID", typeof (String)); - SQLiteUtil.createCol(ua, "secureSessionID", typeof (String)); - SQLiteUtil.createCol(ua, "regionID", typeof (String)); - SQLiteUtil.createCol(ua, "loginTime", typeof (Int32)); - SQLiteUtil.createCol(ua, "logoutTime", typeof (Int32)); - SQLiteUtil.createCol(ua, "currentRegion", typeof (String)); - SQLiteUtil.createCol(ua, "currentHandle", typeof (String)); - // vectors - SQLiteUtil.createCol(ua, "currentPosX", typeof (Double)); - SQLiteUtil.createCol(ua, "currentPosY", typeof (Double)); - SQLiteUtil.createCol(ua, "currentPosZ", typeof (Double)); - // constraints - ua.PrimaryKey = new DataColumn[] {ua.Columns["UUID"]}; - - return ua; - } - - /// - /// Create the "userfriends" table - /// - /// Data Table - private static DataTable createUserFriendsTable() - { - DataTable ua = new DataTable("userfriends"); - // table contains user <----> user relationship with perms - SQLiteUtil.createCol(ua, "ownerID", typeof(String)); - SQLiteUtil.createCol(ua, "friendID", typeof(String)); - SQLiteUtil.createCol(ua, "friendPerms", typeof(Int32)); - SQLiteUtil.createCol(ua, "ownerPerms", typeof(Int32)); - SQLiteUtil.createCol(ua, "datetimestamp", typeof(Int32)); - - return ua; - } - - /// - /// Create the "avatarappearance" table - /// - /// Data Table - private static DataTable createAvatarAppearanceTable() - { - DataTable aa = new DataTable("avatarappearance"); - // table contains user appearance items - - SQLiteUtil.createCol(aa, "Owner", typeof(String)); - SQLiteUtil.createCol(aa, "BodyItem", typeof(String)); - SQLiteUtil.createCol(aa, "BodyAsset", typeof(String)); - SQLiteUtil.createCol(aa, "SkinItem", typeof(String)); - SQLiteUtil.createCol(aa, "SkinAsset", typeof(String)); - SQLiteUtil.createCol(aa, "HairItem", typeof(String)); - SQLiteUtil.createCol(aa, "HairAsset", typeof(String)); - SQLiteUtil.createCol(aa, "EyesItem", typeof(String)); - SQLiteUtil.createCol(aa, "EyesAsset", typeof(String)); - SQLiteUtil.createCol(aa, "ShirtItem", typeof(String)); - SQLiteUtil.createCol(aa, "ShirtAsset", typeof(String)); - SQLiteUtil.createCol(aa, "PantsItem", typeof(String)); - SQLiteUtil.createCol(aa, "PantsAsset", typeof(String)); - SQLiteUtil.createCol(aa, "ShoesItem", typeof(String)); - SQLiteUtil.createCol(aa, "ShoesAsset", typeof(String)); - SQLiteUtil.createCol(aa, "SocksItem", typeof(String)); - SQLiteUtil.createCol(aa, "SocksAsset", typeof(String)); - SQLiteUtil.createCol(aa, "JacketItem", typeof(String)); - SQLiteUtil.createCol(aa, "JacketAsset", typeof(String)); - SQLiteUtil.createCol(aa, "GlovesItem", typeof(String)); - SQLiteUtil.createCol(aa, "GlovesAsset", typeof(String)); - SQLiteUtil.createCol(aa, "UnderShirtItem", typeof(String)); - SQLiteUtil.createCol(aa, "UnderShirtAsset", typeof(String)); - SQLiteUtil.createCol(aa, "UnderPantsItem", typeof(String)); - SQLiteUtil.createCol(aa, "UnderPantsAsset", typeof(String)); - SQLiteUtil.createCol(aa, "SkirtItem", typeof(String)); - SQLiteUtil.createCol(aa, "SkirtAsset", typeof(String)); - - // Used Base64String because for some reason it wont accept using Byte[] (which works in Region date) - SQLiteUtil.createCol(aa, "Texture", typeof (String)); - SQLiteUtil.createCol(aa, "VisualParams", typeof (String)); - - SQLiteUtil.createCol(aa, "Serial", typeof(Int32)); - SQLiteUtil.createCol(aa, "AvatarHeight", typeof(Double)); - - aa.PrimaryKey = new DataColumn[] { aa.Columns["Owner"] }; - - return aa; - } - - /*********************************************************************** - * - * Convert between ADO.NET <=> OpenSim Objects - * - * These should be database independant - * - **********************************************************************/ - - /// - /// TODO: this doesn't work yet because something more - /// interesting has to be done to actually get these values - /// back out. Not enough time to figure it out yet. - /// - /// - /// - private static UserProfileData buildUserProfile(DataRow row) - { - UserProfileData user = new UserProfileData(); - UUID tmp; - UUID.TryParse((String)row["UUID"], out tmp); - user.ID = tmp; - user.FirstName = (String) row["username"]; - user.SurName = (String) row["surname"]; - user.Email = (row.IsNull("email")) ? "" : (String) row["email"]; - - user.PasswordHash = (String) row["passwordHash"]; - user.PasswordSalt = (String) row["passwordSalt"]; - - user.HomeRegionX = Convert.ToUInt32(row["homeRegionX"]); - user.HomeRegionY = Convert.ToUInt32(row["homeRegionY"]); - user.HomeLocation = new Vector3( - Convert.ToSingle(row["homeLocationX"]), - Convert.ToSingle(row["homeLocationY"]), - Convert.ToSingle(row["homeLocationZ"]) - ); - user.HomeLookAt = new Vector3( - Convert.ToSingle(row["homeLookAtX"]), - Convert.ToSingle(row["homeLookAtY"]), - Convert.ToSingle(row["homeLookAtZ"]) - ); - - UUID regionID = UUID.Zero; - UUID.TryParse(row["homeRegionID"].ToString(), out regionID); // it's ok if it doesn't work; just use UUID.Zero - user.HomeRegionID = regionID; - - user.Created = Convert.ToInt32(row["created"]); - user.LastLogin = Convert.ToInt32(row["lastLogin"]); - user.UserInventoryURI = (String) row["userInventoryURI"]; - user.UserAssetURI = (String) row["userAssetURI"]; - user.CanDoMask = Convert.ToUInt32(row["profileCanDoMask"]); - user.WantDoMask = Convert.ToUInt32(row["profileWantDoMask"]); - user.AboutText = (String) row["profileAboutText"]; - user.FirstLifeAboutText = (String) row["profileFirstText"]; - UUID.TryParse((String)row["profileImage"], out tmp); - user.Image = tmp; - UUID.TryParse((String)row["profileFirstImage"], out tmp); - user.FirstLifeImage = tmp; - user.WebLoginKey = new UUID((String) row["webLoginKey"]); - user.UserFlags = Convert.ToInt32(row["userFlags"]); - user.GodLevel = Convert.ToInt32(row["godLevel"]); - user.CustomType = row["customType"].ToString(); - user.Partner = new UUID((String) row["partner"]); - - return user; - } - - /// - /// Persist user profile data - /// - /// - /// - private void fillUserRow(DataRow row, UserProfileData user) - { - row["UUID"] = user.ID.ToString(); - row["username"] = user.FirstName; - row["surname"] = user.SurName; - row["email"] = user.Email; - row["passwordHash"] = user.PasswordHash; - row["passwordSalt"] = user.PasswordSalt; - - row["homeRegionX"] = user.HomeRegionX; - row["homeRegionY"] = user.HomeRegionY; - row["homeRegionID"] = user.HomeRegionID.ToString(); - row["homeLocationX"] = user.HomeLocation.X; - row["homeLocationY"] = user.HomeLocation.Y; - row["homeLocationZ"] = user.HomeLocation.Z; - row["homeLookAtX"] = user.HomeLookAt.X; - row["homeLookAtY"] = user.HomeLookAt.Y; - row["homeLookAtZ"] = user.HomeLookAt.Z; - - row["created"] = user.Created; - row["lastLogin"] = user.LastLogin; - //TODO: Get rid of rootInventoryFolderID in a safe way. - row["rootInventoryFolderID"] = UUID.Zero.ToString(); - row["userInventoryURI"] = user.UserInventoryURI; - row["userAssetURI"] = user.UserAssetURI; - row["profileCanDoMask"] = user.CanDoMask; - row["profileWantDoMask"] = user.WantDoMask; - row["profileAboutText"] = user.AboutText; - row["profileFirstText"] = user.FirstLifeAboutText; - row["profileImage"] = user.Image.ToString(); - row["profileFirstImage"] = user.FirstLifeImage.ToString(); - row["webLoginKey"] = user.WebLoginKey.ToString(); - row["userFlags"] = user.UserFlags; - row["godLevel"] = user.GodLevel; - row["customType"] = user.CustomType == null ? "" : user.CustomType; - row["partner"] = user.Partner.ToString(); - - // ADO.NET doesn't handle NULL very well - foreach (DataColumn col in ds.Tables["users"].Columns) - { - if (row[col] == null) - { - row[col] = String.Empty; - } - } - } - - /// - /// - /// - /// - /// - private void fillAvatarAppearanceRow(DataRow row, UUID user, AvatarAppearance appearance) - { - row["Owner"] = Util.ToRawUuidString(user); - row["BodyItem"] = appearance.BodyItem.ToString(); - row["BodyAsset"] = appearance.BodyAsset.ToString(); - row["SkinItem"] = appearance.SkinItem.ToString(); - row["SkinAsset"] = appearance.SkinAsset.ToString(); - row["HairItem"] = appearance.HairItem.ToString(); - row["HairAsset"] = appearance.HairAsset.ToString(); - row["EyesItem"] = appearance.EyesItem.ToString(); - row["EyesAsset"] = appearance.EyesAsset.ToString(); - row["ShirtItem"] = appearance.ShirtItem.ToString(); - row["ShirtAsset"] = appearance.ShirtAsset.ToString(); - row["PantsItem"] = appearance.PantsItem.ToString(); - row["PantsAsset"] = appearance.PantsAsset.ToString(); - row["ShoesItem"] = appearance.ShoesItem.ToString(); - row["ShoesAsset"] = appearance.ShoesAsset.ToString(); - row["SocksItem"] = appearance.SocksItem.ToString(); - row["SocksAsset"] = appearance.SocksAsset.ToString(); - row["JacketItem"] = appearance.JacketItem.ToString(); - row["JacketAsset"] = appearance.JacketAsset.ToString(); - row["GlovesItem"] = appearance.GlovesItem.ToString(); - row["GlovesAsset"] = appearance.GlovesAsset.ToString(); - row["UnderShirtItem"] = appearance.UnderShirtItem.ToString(); - row["UnderShirtAsset"] = appearance.UnderShirtAsset.ToString(); - row["UnderPantsItem"] = appearance.UnderPantsItem.ToString(); - row["UnderPantsAsset"] = appearance.UnderPantsAsset.ToString(); - row["SkirtItem"] = appearance.SkirtItem.ToString(); - row["SkirtAsset"] = appearance.SkirtAsset.ToString(); - - // Used Base64String because for some reason it wont accept using Byte[] (which works in Region date) - row["Texture"] = Convert.ToBase64String(appearance.Texture.GetBytes()); - row["VisualParams"] = Convert.ToBase64String(appearance.VisualParams); - - row["Serial"] = appearance.Serial; - row["AvatarHeight"] = appearance.AvatarHeight; - - // ADO.NET doesn't handle NULL very well - foreach (DataColumn col in ds.Tables["avatarappearance"].Columns) - { - if (row[col] == null) - { - row[col] = String.Empty; - } - } - } - - /// - /// - /// - /// - /// - private static UserAgentData buildUserAgent(DataRow row) - { - UserAgentData ua = new UserAgentData(); - - UUID tmp; - UUID.TryParse((String)row["UUID"], out tmp); - ua.ProfileID = tmp; - ua.AgentIP = (String)row["agentIP"]; - ua.AgentPort = Convert.ToUInt32(row["agentPort"]); - ua.AgentOnline = Convert.ToBoolean(row["agentOnline"]); - ua.SessionID = new UUID((String) row["sessionID"]); - ua.SecureSessionID = new UUID((String) row["secureSessionID"]); - ua.InitialRegion = new UUID((String) row["regionID"]); - ua.LoginTime = Convert.ToInt32(row["loginTime"]); - ua.LogoutTime = Convert.ToInt32(row["logoutTime"]); - ua.Region = new UUID((String) row["currentRegion"]); - ua.Handle = Convert.ToUInt64(row["currentHandle"]); - ua.Position = new Vector3( - Convert.ToSingle(row["currentPosX"]), - Convert.ToSingle(row["currentPosY"]), - Convert.ToSingle(row["currentPosZ"]) - ); - ua.LookAt = new Vector3( - Convert.ToSingle(row["currentLookAtX"]), - Convert.ToSingle(row["currentLookAtY"]), - Convert.ToSingle(row["currentLookAtZ"]) - ); - return ua; - } - - /// - /// - /// - /// - /// - private static void fillUserAgentRow(DataRow row, UserAgentData ua) - { - row["UUID"] = ua.ProfileID.ToString(); - row["agentIP"] = ua.AgentIP; - row["agentPort"] = ua.AgentPort; - row["agentOnline"] = ua.AgentOnline; - row["sessionID"] = ua.SessionID.ToString(); - row["secureSessionID"] = ua.SecureSessionID.ToString(); - row["regionID"] = ua.InitialRegion.ToString(); - row["loginTime"] = ua.LoginTime; - row["logoutTime"] = ua.LogoutTime; - row["currentRegion"] = ua.Region.ToString(); - row["currentHandle"] = ua.Handle.ToString(); - // vectors - row["currentPosX"] = ua.Position.X; - row["currentPosY"] = ua.Position.Y; - row["currentPosZ"] = ua.Position.Z; - row["currentLookAtX"] = ua.LookAt.X; - row["currentLookAtY"] = ua.LookAt.Y; - row["currentLookAtZ"] = ua.LookAt.Z; - } - - /*********************************************************************** - * - * Database Binding functions - * - * These will be db specific due to typing, and minor differences - * in databases. - * - **********************************************************************/ - - /// - /// - /// - /// - /// - private void setupUserCommands(SqliteDataAdapter da, SqliteConnection conn) - { - da.InsertCommand = SQLiteUtil.createInsertCommand("users", ds.Tables["users"]); - da.InsertCommand.Connection = conn; - - da.UpdateCommand = SQLiteUtil.createUpdateCommand("users", "UUID=:UUID", ds.Tables["users"]); - da.UpdateCommand.Connection = conn; - - SqliteCommand delete = new SqliteCommand("delete from users where UUID = :UUID"); - delete.Parameters.Add(SQLiteUtil.createSqliteParameter("UUID", typeof(String))); - delete.Connection = conn; - da.DeleteCommand = delete; - } - - private void setupAgentCommands(SqliteDataAdapter da, SqliteConnection conn) - { - da.InsertCommand = SQLiteUtil.createInsertCommand("useragents", ds.Tables["useragents"]); - da.InsertCommand.Connection = conn; - - da.UpdateCommand = SQLiteUtil.createUpdateCommand("useragents", "UUID=:UUID", ds.Tables["useragents"]); - da.UpdateCommand.Connection = conn; - - SqliteCommand delete = new SqliteCommand("delete from useragents where UUID = :ProfileID"); - delete.Parameters.Add(SQLiteUtil.createSqliteParameter("ProfileID", typeof(String))); - delete.Connection = conn; - da.DeleteCommand = delete; - } - - /// - /// - /// - /// - /// - private void setupUserFriendsCommands(SqliteDataAdapter daf, SqliteConnection conn) - { - daf.InsertCommand = SQLiteUtil.createInsertCommand("userfriends", ds.Tables["userfriends"]); - daf.InsertCommand.Connection = conn; - - daf.UpdateCommand = SQLiteUtil.createUpdateCommand("userfriends", "ownerID=:ownerID and friendID=:friendID", ds.Tables["userfriends"]); - daf.UpdateCommand.Connection = conn; - - SqliteCommand delete = new SqliteCommand("delete from userfriends where ownerID=:ownerID and friendID=:friendID"); - delete.Parameters.Add(SQLiteUtil.createSqliteParameter("ownerID", typeof(String))); - delete.Parameters.Add(SQLiteUtil.createSqliteParameter("friendID", typeof(String))); - delete.Connection = conn; - daf.DeleteCommand = delete; - - } - - /// - /// - /// - /// - /// - private void setupAvatarAppearanceCommands(SqliteDataAdapter daa, SqliteConnection conn) - { - daa.InsertCommand = SQLiteUtil.createInsertCommand("avatarappearance", ds.Tables["avatarappearance"]); - daa.InsertCommand.Connection = conn; - - daa.UpdateCommand = SQLiteUtil.createUpdateCommand("avatarappearance", "Owner=:Owner", ds.Tables["avatarappearance"]); - daa.UpdateCommand.Connection = conn; - - SqliteCommand delete = new SqliteCommand("delete from avatarappearance where Owner=:Owner"); - delete.Parameters.Add(SQLiteUtil.createSqliteParameter("Owner", typeof(String))); - delete.Connection = conn; - daa.DeleteCommand = delete; - } - - - override public void ResetAttachments(UUID userID) - { - } - - override public void LogoutUsers(UUID regionID) - { - } - } -} diff --git a/OpenSim/Data/SQLite/Tests/SQLiteUserTest.cs b/OpenSim/Data/SQLite/Tests/SQLiteUserTest.cs deleted file mode 100644 index c9953c5..0000000 --- a/OpenSim/Data/SQLite/Tests/SQLiteUserTest.cs +++ /dev/null @@ -1,64 +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.IO; -using NUnit.Framework; -using OpenSim.Data.Tests; -using OpenSim.Tests.Common; - -namespace OpenSim.Data.SQLite.Tests -{ - [TestFixture, DatabaseTest] - public class SQLiteUserTest : BasicUserTest - { - public string file; - public string connect; - - [TestFixtureSetUp] - public void Init() - { - // SQLite doesn't work on power or z linux - if (Directory.Exists("/proc/ppc64") || Directory.Exists("/proc/dasd")) - { - Assert.Ignore(); - } - - SuperInit(); - file = Path.GetTempFileName() + ".db"; - connect = "URI=file:" + file + ",version=3"; - db = new SQLiteUserData(); - db.Initialise(connect); - } - - [TestFixtureTearDown] - public void Cleanup() - { - db.Dispose(); - File.Delete(file); - } - } -} diff --git a/OpenSim/Data/Tests/BasicGridTest.cs b/OpenSim/Data/Tests/BasicGridTest.cs deleted file mode 100644 index df6c669..0000000 --- a/OpenSim/Data/Tests/BasicGridTest.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 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 NUnit.Framework; -using NUnit.Framework.SyntaxHelpers; -using OpenMetaverse; - -namespace OpenSim.Data.Tests -{ - public class BasicGridTest - { - public IGridDataPlugin db; - public UUID region1, region2, region3; - public UUID zero = UUID.Zero; - public static Random random = new Random(); - - [TearDown] - public void removeAllRegions() - { - // Clean up all the regions. - List regions = db.GetRegionsByName("", 100); - if (regions != null) - { - foreach (RegionProfileData region in regions) - { - db.DeleteProfile(region.Uuid.ToString()); - } - } - } - - public void SuperInit() - { - OpenSim.Tests.Common.TestLogging.LogToConsole(); - region1 = UUID.Random(); - region2 = UUID.Random(); - region3 = UUID.Random(); - } - - protected RegionProfileData createRegion(UUID regionUUID, string regionName) - { - RegionProfileData reg = new RegionProfileData(); - new PropertyScrambler().Scramble(reg); - reg.Uuid = regionUUID; - reg.RegionName = regionName; - - db.StoreProfile(reg); - - return reg; - } - - [Test] - public void T001_LoadEmpty() - { - Assert.That(db.GetProfileByUUID(region1),Is.Null); - Assert.That(db.GetProfileByUUID(region2),Is.Null); - Assert.That(db.GetProfileByUUID(region3),Is.Null); - Assert.That(db.GetProfileByUUID(zero),Is.Null); - } - - [Test] - public void T011_AddRetrieveCompleteTest() - { - RegionProfileData newreg = createRegion(region2, "||"); - RegionProfileData retreg = db.GetProfileByUUID(region2); - - Assert.That(retreg, Constraints.PropertyCompareConstraint(newreg).IgnoreProperty(x => x.RegionOnline)); - - retreg = db.GetProfileByHandle(newreg.RegionHandle); - Assert.That(retreg.Uuid, Is.EqualTo(region2), "Assert.That(retreg.Uuid, Is.EqualTo(region2))"); - - retreg = db.GetProfileByString(newreg.RegionName); - Assert.That(retreg.Uuid, Is.EqualTo(region2), "Assert.That(retreg.Uuid, Is.EqualTo(region2))"); - - RegionProfileData[] retregs = db.GetProfilesInRange(newreg.RegionLocX,newreg.RegionLocY,newreg.RegionLocX,newreg.RegionLocY); - Assert.That(retregs[0].Uuid, Is.EqualTo(region2), "Assert.That(retregs[0].Uuid, Is.EqualTo(region2))"); - } - - [Test] - public void T012_DeleteProfile() - { - createRegion(region1, "doesn't matter"); - - db.DeleteProfile(region1.ToString()); - RegionProfileData retreg = db.GetProfileByUUID(region1); - Assert.That(retreg,Is.Null); - } - - [Test] - public void T013_UpdateProfile() - { - createRegion(region2, "||"); - - RegionProfileData retreg = db.GetProfileByUUID(region2); - retreg.regionName = "Gotham City"; - - db.StoreProfile(retreg); - - retreg = db.GetProfileByUUID(region2); - Assert.That(retreg.RegionName, Is.EqualTo("Gotham City"), "Assert.That(retreg.RegionName, Is.EqualTo(\"Gotham City\"))"); - } - - [Test] - public void T014_RegionList() - { - createRegion(region2, "Gotham City"); - - RegionProfileData retreg = db.GetProfileByUUID(region2); - retreg.RegionName = "Gotham Town"; - retreg.Uuid = region1; - - db.StoreProfile(retreg); - - retreg = db.GetProfileByUUID(region2); - retreg.RegionName = "Gothan Town"; - retreg.Uuid = region3; - - db.StoreProfile(retreg); - - List listreg = db.GetRegionsByName("Gotham",10); - - Assert.That(listreg.Count,Is.EqualTo(2), "Assert.That(listreg.Count,Is.EqualTo(2))"); - Assert.That(listreg[0].Uuid,Is.Not.EqualTo(listreg[1].Uuid), "Assert.That(listreg[0].Uuid,Is.Not.EqualTo(listreg[1].Uuid))"); - Assert.That(listreg[0].Uuid, Is.EqualTo(region1) | Is.EqualTo(region2), "Assert.That(listreg[0].Uuid, Is.EqualTo(region1) | Is.EqualTo(region2))"); - Assert.That(listreg[1].Uuid, Is.EqualTo(region1) | Is.EqualTo(region2), "Assert.That(listreg[1].Uuid, Is.EqualTo(region1) | Is.EqualTo(region2))"); - } - - [Test] - public void T999_StillNull() - { - Assert.That(db.GetProfileByUUID(zero), Is.Null); - } - - protected static string RandomName() - { - StringBuilder name = new StringBuilder(); - int size = random.Next(5,12); - char ch ; - for (int i=0; i> 8); - homeregy = ((homeregy << 8) >> 8); - - u.ID = id; - u.WebLoginKey = webloginkey; - u.HomeRegionID = homeregion; - u.FirstName = fname; - u.SurName = lname; - u.Email = email; - u.PasswordHash = passhash; - u.PasswordSalt = passsalt; - u.HomeRegionX = homeregx; - u.HomeRegionY = homeregy; - ulong homereg = u.HomeRegion; - u.HomeLocation = homeloc; - u.HomeLookAt = homelookat; - u.Created = created; - u.LastLogin = lastlogin; - u.UserInventoryURI = userinvuri; - u.UserAssetURI = userasseturi; - u.CanDoMask = candomask; - u.WantDoMask = wantdomask; - u.AboutText = abouttext; - u.FirstLifeAboutText = flabouttext; - u.Image = image; - u.FirstLifeImage = firstimage; - u.CurrentAgent = agent; - u.UserFlags = userflags; - u.GodLevel = godlevel; - u.CustomType = customtype; - u.Partner = partner; - - db.AddNewUserProfile(u); - UserProfileData u1a = db.GetUserByUUID(id); - Assert.That(u1a,Is.Not.Null); - Assert.That(id,Is.EqualTo(u1a.ID), "Assert.That(id,Is.EqualTo(u1a.ID))"); - Assert.That(homeregion,Is.EqualTo(u1a.HomeRegionID), "Assert.That(homeregion,Is.EqualTo(u1a.HomeRegionID))"); - Assert.That(webloginkey,Is.EqualTo(u1a.WebLoginKey), "Assert.That(webloginkey,Is.EqualTo(u1a.WebLoginKey))"); - Assert.That(fname,Is.EqualTo(u1a.FirstName), "Assert.That(fname,Is.EqualTo(u1a.FirstName))"); - Assert.That(lname,Is.EqualTo(u1a.SurName), "Assert.That(lname,Is.EqualTo(u1a.SurName))"); - Assert.That(email,Is.EqualTo(u1a.Email), "Assert.That(email,Is.EqualTo(u1a.Email))"); - Assert.That(passhash,Is.EqualTo(u1a.PasswordHash), "Assert.That(passhash,Is.EqualTo(u1a.PasswordHash))"); - Assert.That(passsalt,Is.EqualTo(u1a.PasswordSalt), "Assert.That(passsalt,Is.EqualTo(u1a.PasswordSalt))"); - Assert.That(homeregx,Is.EqualTo(u1a.HomeRegionX), "Assert.That(homeregx,Is.EqualTo(u1a.HomeRegionX))"); - Assert.That(homeregy,Is.EqualTo(u1a.HomeRegionY), "Assert.That(homeregy,Is.EqualTo(u1a.HomeRegionY))"); - Assert.That(homereg,Is.EqualTo(u1a.HomeRegion), "Assert.That(homereg,Is.EqualTo(u1a.HomeRegion))"); - Assert.That(homeloc,Is.EqualTo(u1a.HomeLocation), "Assert.That(homeloc,Is.EqualTo(u1a.HomeLocation))"); - Assert.That(homelookat,Is.EqualTo(u1a.HomeLookAt), "Assert.That(homelookat,Is.EqualTo(u1a.HomeLookAt))"); - Assert.That(created,Is.EqualTo(u1a.Created), "Assert.That(created,Is.EqualTo(u1a.Created))"); - Assert.That(lastlogin,Is.EqualTo(u1a.LastLogin), "Assert.That(lastlogin,Is.EqualTo(u1a.LastLogin))"); - Assert.That(userinvuri,Is.EqualTo(u1a.UserInventoryURI), "Assert.That(userinvuri,Is.EqualTo(u1a.UserInventoryURI))"); - Assert.That(userasseturi,Is.EqualTo(u1a.UserAssetURI), "Assert.That(userasseturi,Is.EqualTo(u1a.UserAssetURI))"); - Assert.That(candomask,Is.EqualTo(u1a.CanDoMask), "Assert.That(candomask,Is.EqualTo(u1a.CanDoMask))"); - Assert.That(wantdomask,Is.EqualTo(u1a.WantDoMask), "Assert.That(wantdomask,Is.EqualTo(u1a.WantDoMask))"); - Assert.That(abouttext,Is.EqualTo(u1a.AboutText), "Assert.That(abouttext,Is.EqualTo(u1a.AboutText))"); - Assert.That(flabouttext,Is.EqualTo(u1a.FirstLifeAboutText), "Assert.That(flabouttext,Is.EqualTo(u1a.FirstLifeAboutText))"); - Assert.That(image,Is.EqualTo(u1a.Image), "Assert.That(image,Is.EqualTo(u1a.Image))"); - Assert.That(firstimage,Is.EqualTo(u1a.FirstLifeImage), "Assert.That(firstimage,Is.EqualTo(u1a.FirstLifeImage))"); - Assert.That(u1a.CurrentAgent,Is.Null); - Assert.That(userflags,Is.EqualTo(u1a.UserFlags), "Assert.That(userflags,Is.EqualTo(u1a.UserFlags))"); - Assert.That(godlevel,Is.EqualTo(u1a.GodLevel), "Assert.That(godlevel,Is.EqualTo(u1a.GodLevel))"); - Assert.That(customtype,Is.EqualTo(u1a.CustomType), "Assert.That(customtype,Is.EqualTo(u1a.CustomType))"); - Assert.That(partner,Is.EqualTo(u1a.Partner), "Assert.That(partner,Is.EqualTo(u1a.Partner))"); - } - - [Test] - public void T016_UserUpdatePersistency() - { - UUID id = user5; - UserProfileData u = db.GetUserByUUID(id); - string fname = RandomName(); - string lname = RandomName(); - string email = RandomName(); - string passhash = RandomName(); - string passsalt = RandomName(); - UUID homeregionid = UUID.Random(); - UUID webloginkey = UUID.Random(); - uint homeregx = (uint) random.Next(); - uint homeregy = (uint) random.Next(); - Vector3 homeloc = new Vector3((float)Math.Round(random.NextDouble(),5),(float)Math.Round(random.NextDouble(),5),(float)Math.Round(random.NextDouble(),5)); - Vector3 homelookat = new Vector3((float)Math.Round(random.NextDouble(),5),(float)Math.Round(random.NextDouble(),5),(float)Math.Round(random.NextDouble(),5)); - int created = random.Next(); - int lastlogin = random.Next(); - string userinvuri = RandomName(); - string userasseturi = RandomName(); - uint candomask = (uint) random.Next(); - uint wantdomask = (uint) random.Next(); - string abouttext = RandomName(); - string flabouttext = RandomName(); - UUID image = UUID.Random(); - UUID firstimage = UUID.Random(); - UserAgentData agent = NewAgent(id,UUID.Random()); - int userflags = random.Next(); - int godlevel = random.Next(); - string customtype = RandomName(); - UUID partner = UUID.Random(); - - //HomeRegionX and HomeRegionY must only use 24 bits - homeregx = ((homeregx << 8) >> 8); - homeregy = ((homeregy << 8) >> 8); - - u.WebLoginKey = webloginkey; - u.HomeRegionID = homeregionid; - u.FirstName = fname; - u.SurName = lname; - u.Email = email; - u.PasswordHash = passhash; - u.PasswordSalt = passsalt; - u.HomeRegionX = homeregx; - u.HomeRegionY = homeregy; - ulong homereg = u.HomeRegion; - u.HomeLocation = homeloc; - u.HomeLookAt = homelookat; - u.Created = created; - u.LastLogin = lastlogin; - u.UserInventoryURI = userinvuri; - u.UserAssetURI = userasseturi; - u.CanDoMask = candomask; - u.WantDoMask = wantdomask; - u.AboutText = abouttext; - u.FirstLifeAboutText = flabouttext; - u.Image = image; - u.FirstLifeImage = firstimage; - u.CurrentAgent = agent; - u.UserFlags = userflags; - u.GodLevel = godlevel; - u.CustomType = customtype; - u.Partner = partner; - - db.UpdateUserProfile(u); - UserProfileData u1a = db.GetUserByUUID(id); - Assert.That(u1a,Is.Not.Null); - Assert.That(id,Is.EqualTo(u1a.ID), "Assert.That(id,Is.EqualTo(u1a.ID))"); - Assert.That(homeregionid,Is.EqualTo(u1a.HomeRegionID), "Assert.That(homeregionid,Is.EqualTo(u1a.HomeRegionID))"); - Assert.That(webloginkey,Is.EqualTo(u1a.WebLoginKey), "Assert.That(webloginkey,Is.EqualTo(u1a.WebLoginKey))"); - Assert.That(fname,Is.EqualTo(u1a.FirstName), "Assert.That(fname,Is.EqualTo(u1a.FirstName))"); - Assert.That(lname,Is.EqualTo(u1a.SurName), "Assert.That(lname,Is.EqualTo(u1a.SurName))"); - Assert.That(email,Is.EqualTo(u1a.Email), "Assert.That(email,Is.EqualTo(u1a.Email))"); - Assert.That(passhash,Is.EqualTo(u1a.PasswordHash), "Assert.That(passhash,Is.EqualTo(u1a.PasswordHash))"); - Assert.That(passsalt,Is.EqualTo(u1a.PasswordSalt), "Assert.That(passsalt,Is.EqualTo(u1a.PasswordSalt))"); - Assert.That(homereg,Is.EqualTo(u1a.HomeRegion), "Assert.That(homereg,Is.EqualTo(u1a.HomeRegion))"); - Assert.That(homeregx,Is.EqualTo(u1a.HomeRegionX), "Assert.That(homeregx,Is.EqualTo(u1a.HomeRegionX))"); - Assert.That(homeregy,Is.EqualTo(u1a.HomeRegionY), "Assert.That(homeregy,Is.EqualTo(u1a.HomeRegionY))"); - Assert.That(homereg,Is.EqualTo(u1a.HomeRegion), "Assert.That(homereg,Is.EqualTo(u1a.HomeRegion))"); - Assert.That(homeloc,Is.EqualTo(u1a.HomeLocation), "Assert.That(homeloc,Is.EqualTo(u1a.HomeLocation))"); - Assert.That(homelookat,Is.EqualTo(u1a.HomeLookAt), "Assert.That(homelookat,Is.EqualTo(u1a.HomeLookAt))"); - Assert.That(created,Is.EqualTo(u1a.Created), "Assert.That(created,Is.EqualTo(u1a.Created))"); - Assert.That(lastlogin,Is.EqualTo(u1a.LastLogin), "Assert.That(lastlogin,Is.EqualTo(u1a.LastLogin))"); - Assert.That(userasseturi,Is.EqualTo(u1a.UserAssetURI), "Assert.That(userasseturi,Is.EqualTo(u1a.UserAssetURI))"); - Assert.That(candomask,Is.EqualTo(u1a.CanDoMask), "Assert.That(candomask,Is.EqualTo(u1a.CanDoMask))"); - Assert.That(wantdomask,Is.EqualTo(u1a.WantDoMask), "Assert.That(wantdomask,Is.EqualTo(u1a.WantDoMask))"); - Assert.That(abouttext,Is.EqualTo(u1a.AboutText), "Assert.That(abouttext,Is.EqualTo(u1a.AboutText))"); - Assert.That(flabouttext,Is.EqualTo(u1a.FirstLifeAboutText), "Assert.That(flabouttext,Is.EqualTo(u1a.FirstLifeAboutText))"); - Assert.That(image,Is.EqualTo(u1a.Image), "Assert.That(image,Is.EqualTo(u1a.Image))"); - Assert.That(firstimage,Is.EqualTo(u1a.FirstLifeImage), "Assert.That(firstimage,Is.EqualTo(u1a.FirstLifeImage))"); - Assert.That(u1a.CurrentAgent,Is.Null); - Assert.That(userflags,Is.EqualTo(u1a.UserFlags), "Assert.That(userflags,Is.EqualTo(u1a.UserFlags))"); - Assert.That(godlevel,Is.EqualTo(u1a.GodLevel), "Assert.That(godlevel,Is.EqualTo(u1a.GodLevel))"); - Assert.That(customtype,Is.EqualTo(u1a.CustomType), "Assert.That(customtype,Is.EqualTo(u1a.CustomType))"); - Assert.That(partner,Is.EqualTo(u1a.Partner), "Assert.That(partner,Is.EqualTo(u1a.Partner))"); - } - - [Test] - public void T017_UserUpdateRandomPersistency() - { - UUID id = user5; - UserProfileData u = db.GetUserByUUID(id); - new PropertyScrambler().DontScramble(x=>x.ID).Scramble(u); - - db.UpdateUserProfile(u); - UserProfileData u1a = db.GetUserByUUID(id); - Assert.That(u1a, Constraints.PropertyCompareConstraint(u) - .IgnoreProperty(x=>x.HomeRegionX) - .IgnoreProperty(x=>x.HomeRegionY) - ); - } - - [Test] - public void T020_CreateAgent() - { - UserAgentData a1 = NewAgent(user1,agent1); - UserAgentData a2 = NewAgent(user2,agent2); - UserAgentData a3 = NewAgent(user3,agent3); - db.AddNewUserAgent(a1); - db.AddNewUserAgent(a2); - db.AddNewUserAgent(a3); - UserAgentData a1a = db.GetAgentByUUID(user1); - UserAgentData a2a = db.GetAgentByUUID(user2); - UserAgentData a3a = db.GetAgentByUUID(user3); - Assert.That(agent1,Is.EqualTo(a1a.SessionID), "Assert.That(agent1,Is.EqualTo(a1a.SessionID))"); - Assert.That(user1,Is.EqualTo(a1a.ProfileID), "Assert.That(user1,Is.EqualTo(a1a.ProfileID))"); - Assert.That(agent2,Is.EqualTo(a2a.SessionID), "Assert.That(agent2,Is.EqualTo(a2a.SessionID))"); - Assert.That(user2,Is.EqualTo(a2a.ProfileID), "Assert.That(user2,Is.EqualTo(a2a.ProfileID))"); - Assert.That(agent3,Is.EqualTo(a3a.SessionID), "Assert.That(agent3,Is.EqualTo(a3a.SessionID))"); - Assert.That(user3,Is.EqualTo(a3a.ProfileID), "Assert.That(user3,Is.EqualTo(a3a.ProfileID))"); - } - - [Test] - public void T021_FetchAgentByName() - { - String name3 = fname3 + " " + lname3; - UserAgentData a2 = db.GetAgentByName(fname2,lname2); - UserAgentData a3 = db.GetAgentByName(name3); - Assert.That(user2,Is.EqualTo(a2.ProfileID), "Assert.That(user2,Is.EqualTo(a2.ProfileID))"); - Assert.That(user3,Is.EqualTo(a3.ProfileID), "Assert.That(user3,Is.EqualTo(a3.ProfileID))"); - } - - [Test] - public void T022_ExceptionalCases() - { - UserAgentData a0 = NewAgent(user4,zero); - UserAgentData a4 = NewAgent(zero,agent4); - db.AddNewUserAgent(a0); - db.AddNewUserAgent(a4); - - Assert.That(db.GetAgentByUUID(user4),Is.Null); - Assert.That(db.GetAgentByUUID(zero),Is.Null); - } - - [Test] - public void T023_AgentPersistency() - { - UUID user = user4; - UUID agent = agent4; - UUID secureagent = UUID.Random(); - string agentip = RandomName(); - uint agentport = (uint)random.Next(); - bool agentonline = (random.NextDouble() > 0.5); - int logintime = random.Next(); - int logouttime = random.Next(); - UUID regionid = UUID.Random(); - ulong regionhandle = (ulong) random.Next(); - Vector3 currentpos = new Vector3((float)Math.Round(random.NextDouble(),5),(float)Math.Round(random.NextDouble(),5),(float)Math.Round(random.NextDouble(),5)); - Vector3 currentlookat = new Vector3((float)Math.Round(random.NextDouble(),5),(float)Math.Round(random.NextDouble(),5),(float)Math.Round(random.NextDouble(),5)); - UUID orgregionid = UUID.Random(); - - UserAgentData a = new UserAgentData(); - a.ProfileID = user; - a.SessionID = agent; - a.SecureSessionID = secureagent; - a.AgentIP = agentip; - a.AgentPort = agentport; - a.AgentOnline = agentonline; - a.LoginTime = logintime; - a.LogoutTime = logouttime; - a.Region = regionid; - a.Handle = regionhandle; - a.Position = currentpos; - a.LookAt = currentlookat; - a.InitialRegion = orgregionid; - - db.AddNewUserAgent(a); - - UserAgentData a1 = db.GetAgentByUUID(user4); - Assert.That(user,Is.EqualTo(a1.ProfileID), "Assert.That(user,Is.EqualTo(a1.ProfileID))"); - Assert.That(agent,Is.EqualTo(a1.SessionID), "Assert.That(agent,Is.EqualTo(a1.SessionID))"); - Assert.That(secureagent,Is.EqualTo(a1.SecureSessionID), "Assert.That(secureagent,Is.EqualTo(a1.SecureSessionID))"); - Assert.That(agentip,Is.EqualTo(a1.AgentIP), "Assert.That(agentip,Is.EqualTo(a1.AgentIP))"); - Assert.That(agentport,Is.EqualTo(a1.AgentPort), "Assert.That(agentport,Is.EqualTo(a1.AgentPort))"); - Assert.That(agentonline,Is.EqualTo(a1.AgentOnline), "Assert.That(agentonline,Is.EqualTo(a1.AgentOnline))"); - Assert.That(logintime,Is.EqualTo(a1.LoginTime), "Assert.That(logintime,Is.EqualTo(a1.LoginTime))"); - Assert.That(logouttime,Is.EqualTo(a1.LogoutTime), "Assert.That(logouttime,Is.EqualTo(a1.LogoutTime))"); - Assert.That(regionid,Is.EqualTo(a1.Region), "Assert.That(regionid,Is.EqualTo(a1.Region))"); - Assert.That(regionhandle,Is.EqualTo(a1.Handle), "Assert.That(regionhandle,Is.EqualTo(a1.Handle))"); - Assert.That(currentpos,Is.EqualTo(a1.Position), "Assert.That(currentpos,Is.EqualTo(a1.Position))"); - Assert.That(currentlookat,Is.EqualTo(a1.LookAt), "Assert.That(currentlookat,Is.EqualTo(a1.LookAt))"); - } - - [Test] - public void T030_CreateFriendList() - { - Dictionary perms = new Dictionary(); - Dictionary friends = new Dictionary(); - uint temp; - int tempu1, tempu2; - db.AddNewUserFriend(user1,user2, 1); - db.AddNewUserFriend(user1,user3, 2); - db.AddNewUserFriend(user1,user2, 4); - List fl1 = db.GetUserFriendList(user1); - Assert.That(fl1.Count,Is.EqualTo(2), "Assert.That(fl1.Count,Is.EqualTo(2))"); - perms.Add(user2,1); - perms.Add(user3,2); - for (int i = 0; i < fl1.Count; i++) - { - Assert.That(user1,Is.EqualTo(fl1[i].FriendListOwner), "Assert.That(user1,Is.EqualTo(fl1[i].FriendListOwner))"); - friends.Add(fl1[i].Friend,1); - temp = perms[fl1[i].Friend]; - Assert.That(temp,Is.EqualTo(fl1[i].FriendPerms), "Assert.That(temp,Is.EqualTo(fl1[i].FriendPerms))"); - } - tempu1 = friends[user2]; - tempu2 = friends[user3]; - Assert.That(1,Is.EqualTo(tempu1) & Is.EqualTo(tempu2), "Assert.That(1,Is.EqualTo(tempu1) & Is.EqualTo(tempu2))"); - } - - [Test] - public void T031_RemoveUserFriend() - // user1 has 2 friends, user2 and user3. - { - List fl1 = db.GetUserFriendList(user1); - List fl2 = db.GetUserFriendList(user2); - - Assert.That(fl1.Count,Is.EqualTo(2), "Assert.That(fl1.Count,Is.EqualTo(2))"); - Assert.That(fl1[0].Friend,Is.EqualTo(user2) | Is.EqualTo(user3), "Assert.That(fl1[0].Friend,Is.EqualTo(user2) | Is.EqualTo(user3))"); - Assert.That(fl2[0].Friend,Is.EqualTo(user1), "Assert.That(fl2[0].Friend,Is.EqualTo(user1))"); - db.RemoveUserFriend(user2, user1); - - fl1 = db.GetUserFriendList(user1); - fl2 = db.GetUserFriendList(user2); - Assert.That(fl1.Count,Is.EqualTo(1), "Assert.That(fl1.Count,Is.EqualTo(1))"); - Assert.That(fl1[0].Friend, Is.EqualTo(user3), "Assert.That(fl1[0].Friend, Is.EqualTo(user3))"); - Assert.That(fl2, Is.Empty); - } - - [Test] - public void T032_UpdateFriendPerms() - // user1 has 1 friend, user3, who has permission 2 in T030. - { - List fl1 = db.GetUserFriendList(user1); - Assert.That(fl1[0].FriendPerms,Is.EqualTo(2), "Assert.That(fl1[0].FriendPerms,Is.EqualTo(2))"); - db.UpdateUserFriendPerms(user1, user3, 4); - - fl1 = db.GetUserFriendList(user1); - Assert.That(fl1[0].FriendPerms,Is.EqualTo(4), "Assert.That(fl1[0].FriendPerms,Is.EqualTo(4))"); - } - - [Test] - public void T040_UserAppearance() - { - AvatarAppearance appear = new AvatarAppearance(); - appear.Owner = user1; - db.UpdateUserAppearance(user1, appear); - AvatarAppearance user1app = db.GetUserAppearance(user1); - Assert.That(user1,Is.EqualTo(user1app.Owner), "Assert.That(user1,Is.EqualTo(user1app.Owner))"); - } - - [Test] - public void T041_UserAppearancePersistency() - { - AvatarAppearance appear = new AvatarAppearance(); - UUID owner = UUID.Random(); - int serial = random.Next(); - byte[] visualp = new byte[218]; - random.NextBytes(visualp); - UUID bodyitem = UUID.Random(); - UUID bodyasset = UUID.Random(); - UUID skinitem = UUID.Random(); - UUID skinasset = UUID.Random(); - UUID hairitem = UUID.Random(); - UUID hairasset = UUID.Random(); - UUID eyesitem = UUID.Random(); - UUID eyesasset = UUID.Random(); - UUID shirtitem = UUID.Random(); - UUID shirtasset = UUID.Random(); - UUID pantsitem = UUID.Random(); - UUID pantsasset = UUID.Random(); - UUID shoesitem = UUID.Random(); - UUID shoesasset = UUID.Random(); - UUID socksitem = UUID.Random(); - UUID socksasset = UUID.Random(); - UUID jacketitem = UUID.Random(); - UUID jacketasset = UUID.Random(); - UUID glovesitem = UUID.Random(); - UUID glovesasset = UUID.Random(); - UUID ushirtitem = UUID.Random(); - UUID ushirtasset = UUID.Random(); - UUID upantsitem = UUID.Random(); - UUID upantsasset = UUID.Random(); - UUID skirtitem = UUID.Random(); - UUID skirtasset = UUID.Random(); - Primitive.TextureEntry texture = AvatarAppearance.GetDefaultTexture(); - float avatarheight = (float) (Math.Round(random.NextDouble(),5)); - - appear.Owner = owner; - appear.Serial = serial; - appear.VisualParams = visualp; - appear.BodyItem = bodyitem; - appear.BodyAsset = bodyasset; - appear.SkinItem = skinitem; - appear.SkinAsset = skinasset; - appear.HairItem = hairitem; - appear.HairAsset = hairasset; - appear.EyesItem = eyesitem; - appear.EyesAsset = eyesasset; - appear.ShirtItem = shirtitem; - appear.ShirtAsset = shirtasset; - appear.PantsItem = pantsitem; - appear.PantsAsset = pantsasset; - appear.ShoesItem = shoesitem; - appear.ShoesAsset = shoesasset; - appear.SocksItem = socksitem; - appear.SocksAsset = socksasset; - appear.JacketItem = jacketitem; - appear.JacketAsset = jacketasset; - appear.GlovesItem = glovesitem; - appear.GlovesAsset = glovesasset; - appear.UnderShirtItem = ushirtitem; - appear.UnderShirtAsset = ushirtasset; - appear.UnderPantsItem = upantsitem; - appear.UnderPantsAsset = upantsasset; - appear.SkirtItem = skirtitem; - appear.SkirtAsset = skirtasset; - appear.Texture = texture; - appear.AvatarHeight = avatarheight; - - db.UpdateUserAppearance(owner, appear); - AvatarAppearance app = db.GetUserAppearance(owner); - - Assert.That(owner,Is.EqualTo(app.Owner), "Assert.That(owner,Is.EqualTo(app.Owner))"); - Assert.That(serial,Is.EqualTo(app.Serial), "Assert.That(serial,Is.EqualTo(app.Serial))"); - Assert.That(visualp,Is.EqualTo(app.VisualParams), "Assert.That(visualp,Is.EqualTo(app.VisualParams))"); - Assert.That(bodyitem,Is.EqualTo(app.BodyItem), "Assert.That(bodyitem,Is.EqualTo(app.BodyItem))"); - Assert.That(bodyasset,Is.EqualTo(app.BodyAsset), "Assert.That(bodyasset,Is.EqualTo(app.BodyAsset))"); - Assert.That(skinitem,Is.EqualTo(app.SkinItem), "Assert.That(skinitem,Is.EqualTo(app.SkinItem))"); - Assert.That(skinasset,Is.EqualTo(app.SkinAsset), "Assert.That(skinasset,Is.EqualTo(app.SkinAsset))"); - Assert.That(hairitem,Is.EqualTo(app.HairItem), "Assert.That(hairitem,Is.EqualTo(app.HairItem))"); - Assert.That(hairasset,Is.EqualTo(app.HairAsset), "Assert.That(hairasset,Is.EqualTo(app.HairAsset))"); - Assert.That(eyesitem,Is.EqualTo(app.EyesItem), "Assert.That(eyesitem,Is.EqualTo(app.EyesItem))"); - Assert.That(eyesasset,Is.EqualTo(app.EyesAsset), "Assert.That(eyesasset,Is.EqualTo(app.EyesAsset))"); - Assert.That(shirtitem,Is.EqualTo(app.ShirtItem), "Assert.That(shirtitem,Is.EqualTo(app.ShirtItem))"); - Assert.That(shirtasset,Is.EqualTo(app.ShirtAsset), "Assert.That(shirtasset,Is.EqualTo(app.ShirtAsset))"); - Assert.That(pantsitem,Is.EqualTo(app.PantsItem), "Assert.That(pantsitem,Is.EqualTo(app.PantsItem))"); - Assert.That(pantsasset,Is.EqualTo(app.PantsAsset), "Assert.That(pantsasset,Is.EqualTo(app.PantsAsset))"); - Assert.That(shoesitem,Is.EqualTo(app.ShoesItem), "Assert.That(shoesitem,Is.EqualTo(app.ShoesItem))"); - Assert.That(shoesasset,Is.EqualTo(app.ShoesAsset), "Assert.That(shoesasset,Is.EqualTo(app.ShoesAsset))"); - Assert.That(socksitem,Is.EqualTo(app.SocksItem), "Assert.That(socksitem,Is.EqualTo(app.SocksItem))"); - Assert.That(socksasset,Is.EqualTo(app.SocksAsset), "Assert.That(socksasset,Is.EqualTo(app.SocksAsset))"); - Assert.That(jacketitem,Is.EqualTo(app.JacketItem), "Assert.That(jacketitem,Is.EqualTo(app.JacketItem))"); - Assert.That(jacketasset,Is.EqualTo(app.JacketAsset), "Assert.That(jacketasset,Is.EqualTo(app.JacketAsset))"); - Assert.That(glovesitem,Is.EqualTo(app.GlovesItem), "Assert.That(glovesitem,Is.EqualTo(app.GlovesItem))"); - Assert.That(glovesasset,Is.EqualTo(app.GlovesAsset), "Assert.That(glovesasset,Is.EqualTo(app.GlovesAsset))"); - Assert.That(ushirtitem,Is.EqualTo(app.UnderShirtItem), "Assert.That(ushirtitem,Is.EqualTo(app.UnderShirtItem))"); - Assert.That(ushirtasset,Is.EqualTo(app.UnderShirtAsset), "Assert.That(ushirtasset,Is.EqualTo(app.UnderShirtAsset))"); - Assert.That(upantsitem,Is.EqualTo(app.UnderPantsItem), "Assert.That(upantsitem,Is.EqualTo(app.UnderPantsItem))"); - Assert.That(upantsasset,Is.EqualTo(app.UnderPantsAsset), "Assert.That(upantsasset,Is.EqualTo(app.UnderPantsAsset))"); - Assert.That(skirtitem,Is.EqualTo(app.SkirtItem), "Assert.That(skirtitem,Is.EqualTo(app.SkirtItem))"); - Assert.That(skirtasset,Is.EqualTo(app.SkirtAsset), "Assert.That(skirtasset,Is.EqualTo(app.SkirtAsset))"); - Assert.That(texture.ToString(),Is.EqualTo(app.Texture.ToString()), "Assert.That(texture.ToString(),Is.EqualTo(app.Texture.ToString()))"); - Assert.That(avatarheight,Is.EqualTo(app.AvatarHeight), "Assert.That(avatarheight,Is.EqualTo(app.AvatarHeight))"); - } - - [Test] - public void T999_StillNull() - { - Assert.That(db.GetUserByUUID(zero), Is.Null); - Assert.That(db.GetAgentByUUID(zero), Is.Null); - } - - public UserProfileData NewUser(UUID id,string fname,string lname) - { - UserProfileData u = new UserProfileData(); - u.ID = id; - u.FirstName = fname; - u.SurName = lname; - u.PasswordHash = "NOTAHASH"; - u.PasswordSalt = "NOTSALT"; - // MUST specify at least these 5 parameters or an exception is raised - - return u; - } - - public UserAgentData NewAgent(UUID user_profile, UUID agent) - { - UserAgentData a = new UserAgentData(); - a.ProfileID = user_profile; - a.SessionID = agent; - a.SecureSessionID = UUID.Random(); - a.AgentIP = RandomName(); - return a; - } - - public static string RandomName() - { - StringBuilder name = new StringBuilder(); - int size = random.Next(5,12); - char ch ; - for (int i=0; i aplist = new Dictionary(); - - public abstract UserProfileData GetUserByUUID(UUID user); - public abstract UserProfileData GetUserByName(string fname, string lname); - public abstract UserAgentData GetAgentByUUID(UUID user); - public abstract UserAgentData GetAgentByName(string name); - public abstract UserAgentData GetAgentByName(string fname, string lname); - public UserProfileData GetUserByUri(Uri uri) { return null; } - public abstract void StoreWebLoginKey(UUID agentID, UUID webLoginKey); - public abstract void AddNewUserProfile(UserProfileData user); - - public virtual void AddTemporaryUserProfile(UserProfileData userProfile) - { - // Deliberately blank - database plugins shouldn't store temporary profiles. - } - - public abstract bool UpdateUserProfile(UserProfileData user); - public abstract void AddNewUserAgent(UserAgentData agent); - public abstract void AddNewUserFriend(UUID friendlistowner, UUID friend, uint perms); - public abstract void RemoveUserFriend(UUID friendlistowner, UUID friend); - public abstract void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms); - public abstract List GetUserFriendList(UUID friendlistowner); - public abstract Dictionary GetFriendRegionInfos (List uuids); - public abstract bool MoneyTransferRequest(UUID from, UUID to, uint amount); - public abstract bool InventoryTransferRequest(UUID from, UUID to, UUID inventory); - public abstract List GeneratePickerResults(UUID queryID, string query); - public abstract AvatarAppearance GetUserAppearance(UUID user); - public abstract void UpdateUserAppearance(UUID user, AvatarAppearance appearance); - // public virtual AvatarAppearance GetUserAppearance(UUID user) { - // AvatarAppearance aa = null; - // try { - // aa = aplist[user]; - // m_log.Info("[APPEARANCE] Found appearance for " + user.ToString() + aa.ToString()); - // } catch (System.Collections.Generic.KeyNotFoundException e) { - // m_log.Info("[APPEARANCE] No appearance found for " + user.ToString()); - // } - // return aa; - // } - // public virtual void UpdateUserAppearance(UUID user, AvatarAppearance appearance) { - // aplist[user] = appearance; - // m_log.Info("[APPEARANCE] Setting appearance for " + user.ToString() + appearance.ToString()); - // } - public abstract void ResetAttachments(UUID userID); - - public abstract void LogoutUsers(UUID regionID); - - public abstract string Version {get;} - public abstract string Name {get;} - public abstract void Initialise(string connect); - public abstract void Initialise(); - public abstract void Dispose(); - } -} diff --git a/OpenSim/Framework/Communications/TemporaryUserProfilePlugin.cs b/OpenSim/Framework/Communications/TemporaryUserProfilePlugin.cs deleted file mode 100644 index 2413055..0000000 --- a/OpenSim/Framework/Communications/TemporaryUserProfilePlugin.cs +++ /dev/null @@ -1,104 +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.Reflection; -using log4net; -using OpenMetaverse; -using OpenSim.Data; - -namespace OpenSim.Framework.Communications -{ - /// - /// Plugin for managing temporary user profiles. - /// - public class TemporaryUserProfilePlugin : IUserDataPlugin - { - //private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - protected Dictionary m_profiles = new Dictionary(); - - public string Name { get { return "TemporaryUserProfilePlugin"; } } - public string Version { get { return "0.1"; } } - public void Initialise() {} - public void Initialise(string connect) {} - public void Dispose() {} - - public UserProfileData GetUserByUUID(UUID user) - { - //m_log.DebugFormat("[TEMP USER PROFILE]: Received request for {0}", user); - - lock (m_profiles) - { - if (m_profiles.ContainsKey(user)) - return m_profiles[user]; - else - return null; - } - } - - public UserProfileData GetUserByName(string fname, string lname) - { - // We deliberately don't look up a temporary profile by name so that we don't obscure non-temporary - // profiles. - - return null; - } - - public virtual void AddTemporaryUserProfile(UserProfileData userProfile) - { - //m_log.DebugFormat("[TEMP USER PROFILE]: Adding {0} {1}", userProfile.Name, userProfile.ID); - - lock (m_profiles) - { - m_profiles[userProfile.ID] = userProfile; - } - } - - public UserProfileData GetUserByUri(Uri uri) { return null; } - public List GeneratePickerResults(UUID queryID, string query) { return null; } - public UserAgentData GetAgentByUUID(UUID user) { return null; } - public UserAgentData GetAgentByName(string name) { return null; } - public UserAgentData GetAgentByName(string fname, string lname) { return null; } - public void StoreWebLoginKey(UUID agentID, UUID webLoginKey) {} - public void AddNewUserProfile(UserProfileData user) {} - public bool UpdateUserProfile(UserProfileData user) { return false; } - public void AddNewUserAgent(UserAgentData agent) {} - public void AddNewUserFriend(UUID friendlistowner, UUID friend, uint perms) {} - public void RemoveUserFriend(UUID friendlistowner, UUID friend) {} - public void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms) {} - public List GetUserFriendList(UUID friendlistowner) { return null; } - public Dictionary GetFriendRegionInfos(List uuids) { return null; } - public bool MoneyTransferRequest(UUID from, UUID to, uint amount) { return false; } - public bool InventoryTransferRequest(UUID from, UUID to, UUID inventory) { return false; } - public AvatarAppearance GetUserAppearance(UUID user) { return null; } - public void UpdateUserAppearance(UUID user, AvatarAppearance appearance) {} - public void ResetAttachments(UUID userID) {} - public void LogoutUsers(UUID regionID) {} - } -} diff --git a/OpenSim/Tests/Common/Mock/TestUserDataPlugin.cs b/OpenSim/Tests/Common/Mock/TestUserDataPlugin.cs deleted file mode 100644 index 5188cf6..0000000 --- a/OpenSim/Tests/Common/Mock/TestUserDataPlugin.cs +++ /dev/null @@ -1,216 +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 OpenMetaverse; -using OpenSim.Framework; -using OpenSim.Data; - -namespace OpenSim.Tests.Common.Mock -{ - /// - /// In memory user data provider. Might be quite useful as a proper user data plugin, though getting mono addins - /// to load any plugins when running unit tests has proven impossible so far. Currently no locking since unit - /// tests are single threaded. - /// - public class TestUserDataPlugin : IUserDataPlugin - { - public string Version { get { return "0"; } } - public string Name { get { return "TestUserDataPlugin"; } } - - /// - /// User profiles keyed by name - /// - private Dictionary m_userProfilesByName = new Dictionary(); - - /// - /// User profiles keyed by uuid - /// - private Dictionary m_userProfilesByUuid = new Dictionary(); - - /// - /// User profiles and their agents - /// - private Dictionary m_agentByProfileUuid = new Dictionary(); - - /// - /// Friends list by uuid - /// - private Dictionary> m_friendsListByUuid = new Dictionary>(); - - public void Initialise() {} - public void Dispose() {} - - public void AddTemporaryUserProfile(UserProfileData userProfile) - { - // Not interested - } - - public void AddNewUserProfile(UserProfileData user) - { - UpdateUserProfile(user); - } - - public UserProfileData GetUserByUUID(UUID user) - { - UserProfileData userProfile = null; - m_userProfilesByUuid.TryGetValue(user, out userProfile); - - return userProfile; - } - - public UserProfileData GetUserByName(string fname, string lname) - { - UserProfileData userProfile = null; - m_userProfilesByName.TryGetValue(fname + " " + lname, out userProfile); - - return userProfile; - } - - public UserProfileData GetUserByUri(Uri uri) { return null; } - - public bool UpdateUserProfile(UserProfileData user) - { - m_userProfilesByUuid[user.ID] = user; - m_userProfilesByName[user.FirstName + " " + user.SurName] = user; - - return true; - } - - public List GeneratePickerResults(UUID queryID, string query) { return null; } - - public UserAgentData GetAgentByUUID(UUID user) - { - UserAgentData userAgent = null; - m_agentByProfileUuid.TryGetValue(user, out userAgent); - - return userAgent; - } - - public UserAgentData GetAgentByName(string name) - { - UserProfileData userProfile = null; - m_userProfilesByName.TryGetValue(name, out userProfile); - UserAgentData userAgent = null; - m_agentByProfileUuid.TryGetValue(userProfile.ID, out userAgent); - - return userAgent; - } - - public UserAgentData GetAgentByName(string fname, string lname) - { - UserProfileData userProfile = GetUserByName(fname,lname); - UserAgentData userAgent = null; - m_agentByProfileUuid.TryGetValue(userProfile.ID, out userAgent); - - return userAgent; - } - - public void StoreWebLoginKey(UUID agentID, UUID webLoginKey) {} - - public void AddNewUserAgent(UserAgentData agent) - { - m_agentByProfileUuid[agent.ProfileID] = agent; - } - public void AddNewUserFriend(UUID friendlistowner, UUID friend, uint perms) - { - FriendListItem newfriend = new FriendListItem(); - newfriend.FriendPerms = perms; - newfriend.Friend = friend; - newfriend.FriendListOwner = friendlistowner; - - if (!m_friendsListByUuid.ContainsKey(friendlistowner)) - { - List friendslist = new List(); - m_friendsListByUuid[friendlistowner] = friendslist; - - } - m_friendsListByUuid[friendlistowner].Add(newfriend); - } - - public void RemoveUserFriend(UUID friendlistowner, UUID friend) - { - if (m_friendsListByUuid.ContainsKey(friendlistowner)) - { - List friendslist = m_friendsListByUuid[friendlistowner]; - foreach (FriendListItem frienditem in friendslist) - { - if (frienditem.Friend == friend) - { - friendslist.Remove(frienditem); - break; - } - } - } - } - - public void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms) - { - if (m_friendsListByUuid.ContainsKey(friendlistowner)) - { - List friendslist = m_friendsListByUuid[friendlistowner]; - foreach (FriendListItem frienditem in friendslist) - { - if (frienditem.Friend == friend) - { - frienditem.FriendPerms = perms; - break; - } - } - } - } - - public List GetUserFriendList(UUID friendlistowner) - { - if (m_friendsListByUuid.ContainsKey(friendlistowner)) - { - return m_friendsListByUuid[friendlistowner]; - } - else - return new List(); - - - } - - public Dictionary GetFriendRegionInfos(List uuids) { return null; } - - public bool MoneyTransferRequest(UUID from, UUID to, uint amount) { return false; } - - public bool InventoryTransferRequest(UUID from, UUID to, UUID inventory) { return false; } - - public void Initialise(string connect) { return; } - - public AvatarAppearance GetUserAppearance(UUID user) { return null; } - - public void UpdateUserAppearance(UUID user, AvatarAppearance appearance) {} - - public void ResetAttachments(UUID userID) {} - - public void LogoutUsers(UUID regionID) {} - } -} -- cgit v1.1