Merge branch 'master' into careminster-presence-refactor

This brings careminster on the level of master. To be tested
avinationmerge
Melanie 2010-03-03 02:07:03 +00:00
commit 028a87fe37
501 changed files with 26121 additions and 46964 deletions

View File

@ -128,6 +128,7 @@ what it is today.
* YZh
* Zackary Geers aka Kunnis Basiat
* Zha Ewry
* ziah
= LSL Devs =

View File

@ -1,219 +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.Data;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Communications.Services;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Communications.Osp;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Communications.Hypergrid;
using OpenSim.Region.Communications.Local;
using OpenSim.Region.Communications.OGS1;
namespace OpenSim.ApplicationPlugins.CreateCommsManager
{
public class CreateCommsManagerPlugin : IApplicationPlugin
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
#region IApplicationPlugin Members
// TODO: required by IPlugin, but likely not at all right
private string m_name = "CreateCommsManagerPlugin";
private string m_version = "0.0";
public string Version
{
get { return m_version; }
}
public string Name
{
get { return m_name; }
}
protected OpenSimBase m_openSim;
protected BaseHttpServer m_httpServer;
protected CommunicationsManager m_commsManager;
protected GridInfoService m_gridInfoService;
protected IRegionCreator m_regionCreator;
public void Initialise()
{
m_log.Info("[LOADREGIONS]: " + Name + " cannot be default-initialized!");
throw new PluginNotInitialisedException(Name);
}
public void Initialise(OpenSimBase openSim)
{
m_openSim = openSim;
m_httpServer = openSim.HttpServer;
MainServer.Instance = m_httpServer;
InitialiseCommsManager(openSim);
if (m_commsManager != null)
{
m_openSim.ApplicationRegistry.RegisterInterface<IUserService>(m_commsManager.UserService);
}
}
public void PostInitialise()
{
if (m_openSim.ApplicationRegistry.TryGet<IRegionCreator>(out m_regionCreator))
{
m_regionCreator.OnNewRegionCreated += RegionCreated;
}
}
public void Dispose()
{
}
#endregion
private void RegionCreated(IScene scene)
{
if (m_commsManager != null)
{
scene.RegisterModuleInterface<IUserService>(m_commsManager.UserService);
}
}
protected void InitialiseCommsManager(OpenSimBase openSim)
{
LibraryRootFolder libraryRootFolder = new LibraryRootFolder(m_openSim.ConfigurationSettings.LibrariesXMLFile);
bool hgrid = m_openSim.ConfigSource.Source.Configs["Startup"].GetBoolean("hypergrid", false);
if (hgrid)
{
InitialiseHGServices(openSim, libraryRootFolder);
}
else
{
InitialiseStandardServices(libraryRootFolder);
}
openSim.CommunicationsManager = m_commsManager;
}
protected void InitialiseHGServices(OpenSimBase openSim, LibraryRootFolder libraryRootFolder)
{
// Standalone mode is determined by !startupConfig.GetBoolean("gridmode", false)
if (m_openSim.ConfigurationSettings.Standalone)
{
InitialiseHGStandaloneServices(libraryRootFolder);
}
else
{
// We are in grid mode
InitialiseHGGridServices(libraryRootFolder);
}
}
protected void InitialiseStandardServices(LibraryRootFolder libraryRootFolder)
{
// Standalone mode is determined by !startupConfig.GetBoolean("gridmode", false)
if (m_openSim.ConfigurationSettings.Standalone)
{
InitialiseStandaloneServices(libraryRootFolder);
}
else
{
// We are in grid mode
InitialiseGridServices(libraryRootFolder);
}
}
/// <summary>
/// Initialises the backend services for standalone mode, and registers some http handlers
/// </summary>
/// <param name="libraryRootFolder"></param>
protected virtual void InitialiseStandaloneServices(LibraryRootFolder libraryRootFolder)
{
m_commsManager
= new CommunicationsLocal(
m_openSim.ConfigurationSettings, m_openSim.NetServersInfo,
libraryRootFolder);
CreateGridInfoService();
}
protected virtual void InitialiseGridServices(LibraryRootFolder libraryRootFolder)
{
m_commsManager
= new CommunicationsOGS1(m_openSim.NetServersInfo, libraryRootFolder);
m_httpServer.AddStreamHandler(new OpenSim.SimStatusHandler());
m_httpServer.AddStreamHandler(new OpenSim.XSimStatusHandler(m_openSim));
if (m_openSim.userStatsURI != String.Empty)
m_httpServer.AddStreamHandler(new OpenSim.UXSimStatusHandler(m_openSim));
}
protected virtual void InitialiseHGStandaloneServices(LibraryRootFolder libraryRootFolder)
{
m_commsManager
= new HGCommunicationsStandalone(
m_openSim.ConfigurationSettings, m_openSim.NetServersInfo, m_httpServer,
libraryRootFolder, false);
CreateGridInfoService();
}
protected virtual void InitialiseHGGridServices(LibraryRootFolder libraryRootFolder)
{
m_commsManager
= new HGCommunicationsGridMode(
m_openSim.NetServersInfo,
m_openSim.SceneManager, libraryRootFolder);
m_httpServer.AddStreamHandler(new OpenSim.SimStatusHandler());
m_httpServer.AddStreamHandler(new OpenSim.XSimStatusHandler(m_openSim));
if (m_openSim.userStatsURI != String.Empty)
m_httpServer.AddStreamHandler(new OpenSim.UXSimStatusHandler(m_openSim));
}
private void CreateGridInfoService()
{
// provide grid info
m_gridInfoService = new GridInfoService(m_openSim.ConfigSource.Source);
m_httpServer.AddXmlRPCHandler("get_grid_info", m_gridInfoService.XmlRpcGridInfoMethod);
m_httpServer.AddStreamHandler(
new RestStreamHandler("GET", "/get_grid_info", m_gridInfoService.RestGetGridInfoMethod));
}
}
}

View File

@ -1,11 +0,0 @@
<Addin id="OpenSim.ApplicationPlugins.CreateCommsManager" version="0.1">
<Runtime>
<Import assembly="OpenSim.ApplicationPlugins.CreateCommsManager.dll"/>
</Runtime>
<Dependencies>
<Addin id="OpenSim" version="0.5" />
</Dependencies>
<Extension path = "/OpenSim/Startup">
<Plugin id="CreateCommsManager" type="OpenSim.ApplicationPlugins.CreateCommsManager.CreateCommsManagerPlugin" />
</Extension>
</Addin>

View File

@ -102,8 +102,6 @@ namespace OpenSim.ApplicationPlugins.LoadRegions
m_log.Info("[LOADREGIONSPLUGIN]: Loading specific shared modules...");
m_log.Info("[LOADREGIONSPLUGIN]: DynamicTextureModule...");
m_openSim.ModuleLoader.LoadDefaultSharedModule(new DynamicTextureModule());
m_log.Info("[LOADREGIONSPLUGIN]: InstantMessageModule...");
m_openSim.ModuleLoader.LoadDefaultSharedModule(new InstantMessageModule());
m_log.Info("[LOADREGIONSPLUGIN]: LoadImageURLModule...");
m_openSim.ModuleLoader.LoadDefaultSharedModule(new LoadImageURLModule());
m_log.Info("[LOADREGIONSPLUGIN]: XMLRPCModule...");
@ -217,4 +215,4 @@ namespace OpenSim.ApplicationPlugins.LoadRegions
}
}
}
}
}

View File

@ -65,9 +65,9 @@ namespace OpenSim.ApplicationPlugins.RegionModulesController
public void Initialise (OpenSimBase openSim)
{
m_log.DebugFormat("[REGIONMODULES]: Initializing...");
m_openSim = openSim;
openSim.ApplicationRegistry.RegisterInterface<IRegionModulesController>(this);
m_openSim.ApplicationRegistry.RegisterInterface<IRegionModulesController>(this);
m_log.DebugFormat("[REGIONMODULES]: Initializing...");
// Who we are
string id = AddinManager.CurrentAddin.Id;
@ -81,9 +81,9 @@ namespace OpenSim.ApplicationPlugins.RegionModulesController
// The [Modules] section in the ini file
IConfig modulesConfig =
openSim.ConfigSource.Source.Configs["Modules"];
m_openSim.ConfigSource.Source.Configs["Modules"];
if (modulesConfig == null)
modulesConfig = openSim.ConfigSource.Source.AddConfig("Modules");
modulesConfig = m_openSim.ConfigSource.Source.AddConfig("Modules");
// Scan modules and load all that aren't disabled
foreach (TypeExtensionNode node in
@ -104,7 +104,7 @@ namespace OpenSim.ApplicationPlugins.RegionModulesController
continue;
// Split off port, if present
string[] moduleParts = moduleString.Split(new char[] {'/'}, 2);
string[] moduleParts = moduleString.Split(new char[] { '/' }, 2);
// Format is [port/][class]
string className = moduleParts[0];
if (moduleParts.Length > 1)
@ -134,7 +134,7 @@ namespace OpenSim.ApplicationPlugins.RegionModulesController
continue;
// Split off port, if present
string[] moduleParts = moduleString.Split(new char[] {'/'}, 2);
string[] moduleParts = moduleString.Split(new char[] { '/' }, 2);
// Format is [port/][class]
string className = moduleParts[0];
if (moduleParts.Length > 1)
@ -162,7 +162,7 @@ namespace OpenSim.ApplicationPlugins.RegionModulesController
//
foreach (TypeExtensionNode node in m_sharedModules)
{
Object[] ctorArgs = new Object[] {(uint)0};
Object[] ctorArgs = new Object[] { (uint)0 };
// Read the config again
string moduleString =
@ -172,7 +172,7 @@ namespace OpenSim.ApplicationPlugins.RegionModulesController
if (moduleString != String.Empty)
{
// Get the port number from the string
string[] moduleParts = moduleString.Split(new char[] {'/'},
string[] moduleParts = moduleString.Split(new char[] { '/' },
2);
if (moduleParts.Length > 1)
ctorArgs[0] = Convert.ToUInt32(moduleParts[0]);
@ -195,18 +195,22 @@ namespace OpenSim.ApplicationPlugins.RegionModulesController
// OK, we're up and running
m_sharedInstances.Add(module);
module.Initialise(openSim.ConfigSource.Source);
module.Initialise(m_openSim.ConfigSource.Source);
}
}
public void PostInitialise ()
{
m_log.DebugFormat("[REGIONMODULES]: PostInitializing...");
// Immediately run PostInitialise on shared modules
foreach (ISharedRegionModule module in m_sharedInstances)
{
module.PostInitialise();
}
}
public void PostInitialise ()
{
}
#endregion

View File

@ -41,7 +41,7 @@ using OpenMetaverse;
using OpenSim;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Console;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
@ -49,6 +49,8 @@ using OpenSim.Region.CoreModules.World.Terrain;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.ApplicationPlugins.RemoteController
{
@ -700,39 +702,8 @@ namespace OpenSim.ApplicationPlugins.RemoteController
{
// ok, client wants us to use an explicit UUID
// regardless of what the avatar name provided
userID = new UUID((string) requestData["region_master_uuid"]);
userID = new UUID((string) requestData["estate_owner_uuid"]);
}
else
{
if (masterFirst != String.Empty && masterLast != String.Empty) // User requests a master avatar
{
// no client supplied UUID: look it up...
CachedUserInfo userInfo
= m_app.CommunicationsManager.UserProfileCacheService.GetUserDetails(
masterFirst, masterLast);
if (null == userInfo)
{
m_log.InfoFormat("master avatar does not exist, creating it");
// ...or create new user
userID = m_app.CommunicationsManager.UserAdminService.AddUser(
masterFirst, masterLast, masterPassword, "", region.RegionLocX, region.RegionLocY);
if (userID == UUID.Zero)
throw new Exception(String.Format("failed to create new user {0} {1}",
masterFirst, masterLast));
}
else
{
userID = userInfo.UserProfile.ID;
}
}
}
region.MasterAvatarFirstName = masterFirst;
region.MasterAvatarLastName = masterLast;
region.MasterAvatarSandboxPassword = masterPassword;
region.MasterAvatarAssignedUUID = userID;
bool persist = Convert.ToBoolean((string) requestData["persist"]);
if (persist)
@ -777,6 +748,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
// If an access specification was provided, use it.
// Otherwise accept the default.
newscene.RegionInfo.EstateSettings.PublicAccess = getBoolean(requestData, "public", m_publicAccess);
newscene.RegionInfo.EstateSettings.EstateOwner = userID;
if (persist)
newscene.RegionInfo.EstateSettings.Save();
@ -1150,30 +1122,37 @@ namespace OpenSim.ApplicationPlugins.RemoteController
if (requestData.Contains("user_email"))
email = (string)requestData["user_email"];
CachedUserInfo userInfo =
m_app.CommunicationsManager.UserProfileCacheService.GetUserDetails(firstname, lastname);
UUID scopeID = m_app.SceneManager.CurrentOrFirstScene.RegionInfo.ScopeID;
if (null != userInfo)
throw new Exception(String.Format("Avatar {0} {1} already exists", firstname, lastname));
UserAccount account = m_app.SceneManager.CurrentOrFirstScene.UserAccountService.GetUserAccount(scopeID, firstname, lastname);
UUID userID =
m_app.CommunicationsManager.UserAdminService.AddUser(firstname, lastname,
passwd, email, regX, regY);
if (null != account)
throw new Exception(String.Format("Account {0} {1} already exists", firstname, lastname));
if (userID == UUID.Zero)
account = new UserAccount(scopeID, firstname, lastname, email);
// REFACTORING PROBLEM: no method to set the password!
bool success = m_app.SceneManager.CurrentOrFirstScene.UserAccountService.StoreUserAccount(account);
if (!success)
throw new Exception(String.Format("failed to create new user {0} {1}",
firstname, lastname));
GridRegion home = m_app.SceneManager.CurrentOrFirstScene.GridService.GetRegionByPosition(scopeID,
(int)(regX * Constants.RegionSize), (int)(regY * Constants.RegionSize));
if (home == null)
m_log.WarnFormat("[RADMIN]: Unable to set home region for newly created user account {0} {1}", firstname, lastname);
// Establish the avatar's initial appearance
updateUserAppearance(responseData, requestData, userID);
updateUserAppearance(responseData, requestData, account.PrincipalID);
responseData["success"] = true;
responseData["avatar_uuid"] = userID.ToString();
responseData["avatar_uuid"] = account.PrincipalID.ToString();
response.Value = responseData;
m_log.InfoFormat("[RADMIN]: CreateUser: User {0} {1} created, UUID {2}", firstname, lastname, userID);
m_log.InfoFormat("[RADMIN]: CreateUser: User {0} {1} created, UUID {2}", firstname, lastname, account.PrincipalID);
}
catch (Exception e)
{
@ -1242,21 +1221,27 @@ namespace OpenSim.ApplicationPlugins.RemoteController
string firstname = (string) requestData["user_firstname"];
string lastname = (string) requestData["user_lastname"];
CachedUserInfo userInfo
= m_app.CommunicationsManager.UserProfileCacheService.GetUserDetails(firstname, lastname);
responseData["user_firstname"] = firstname;
responseData["user_lastname"] = lastname;
if (null == userInfo)
UUID scopeID = m_app.SceneManager.CurrentOrFirstScene.RegionInfo.ScopeID;
UserAccount account = m_app.SceneManager.CurrentOrFirstScene.UserAccountService.GetUserAccount(scopeID, firstname, lastname);
if (null == account)
{
responseData["success"] = false;
responseData["lastlogin"] = 0;
}
else
{
PresenceInfo[] pinfos = m_app.SceneManager.CurrentOrFirstScene.PresenceService.GetAgents(new string[] { account.PrincipalID.ToString() });
if (pinfos != null && pinfos.Length >= 1)
responseData["lastlogin"] = pinfos[0].Login;
else
responseData["lastlogin"] = 0;
responseData["success"] = true;
responseData["lastlogin"] = userInfo.UserProfile.LastLogin;
}
response.Value = responseData;
@ -1318,117 +1303,118 @@ namespace OpenSim.ApplicationPlugins.RemoteController
public XmlRpcResponse XmlRpcUpdateUserAccountMethod(XmlRpcRequest request, IPEndPoint remoteClient)
{
m_log.Info("[RADMIN]: UpdateUserAccount: new request");
m_log.Warn("[RADMIN]: This method needs update for 0.7");
XmlRpcResponse response = new XmlRpcResponse();
Hashtable responseData = new Hashtable();
lock (rslock)
{
try
{
Hashtable requestData = (Hashtable) request.Params[0];
//lock (rslock)
//{
// try
// {
// Hashtable requestData = (Hashtable) request.Params[0];
// check completeness
checkStringParameters(request, new string[] {
"password", "user_firstname",
"user_lastname"});
// // check completeness
// checkStringParameters(request, new string[] {
// "password", "user_firstname",
// "user_lastname"});
// check password
if (!String.IsNullOrEmpty(m_requiredPassword) &&
(string) requestData["password"] != m_requiredPassword) throw new Exception("wrong password");
// // check password
// if (!String.IsNullOrEmpty(m_requiredPassword) &&
// (string) requestData["password"] != m_requiredPassword) throw new Exception("wrong password");
// do the job
string firstname = (string) requestData["user_firstname"];
string lastname = (string) requestData["user_lastname"];
// // do the job
// string firstname = (string) requestData["user_firstname"];
// string lastname = (string) requestData["user_lastname"];
string passwd = String.Empty;
uint? regX = null;
uint? regY = null;
uint? ulaX = null;
uint? ulaY = null;
uint? ulaZ = null;
uint? usaX = null;
uint? usaY = null;
uint? usaZ = null;
string aboutFirstLive = String.Empty;
string aboutAvatar = String.Empty;
// string passwd = String.Empty;
// uint? regX = null;
// uint? regY = null;
// uint? ulaX = null;
// uint? ulaY = null;
// uint? ulaZ = null;
// uint? usaX = null;
// uint? usaY = null;
// uint? usaZ = null;
// string aboutFirstLive = String.Empty;
// string aboutAvatar = String.Empty;
if (requestData.ContainsKey("user_password")) passwd = (string) requestData["user_password"];
if (requestData.ContainsKey("start_region_x"))
regX = Convert.ToUInt32((Int32) requestData["start_region_x"]);
if (requestData.ContainsKey("start_region_y"))
regY = Convert.ToUInt32((Int32) requestData["start_region_y"]);
// if (requestData.ContainsKey("user_password")) passwd = (string) requestData["user_password"];
// if (requestData.ContainsKey("start_region_x"))
// regX = Convert.ToUInt32((Int32) requestData["start_region_x"]);
// if (requestData.ContainsKey("start_region_y"))
// regY = Convert.ToUInt32((Int32) requestData["start_region_y"]);
if (requestData.ContainsKey("start_lookat_x"))
ulaX = Convert.ToUInt32((Int32) requestData["start_lookat_x"]);
if (requestData.ContainsKey("start_lookat_y"))
ulaY = Convert.ToUInt32((Int32) requestData["start_lookat_y"]);
if (requestData.ContainsKey("start_lookat_z"))
ulaZ = Convert.ToUInt32((Int32) requestData["start_lookat_z"]);
// if (requestData.ContainsKey("start_lookat_x"))
// ulaX = Convert.ToUInt32((Int32) requestData["start_lookat_x"]);
// if (requestData.ContainsKey("start_lookat_y"))
// ulaY = Convert.ToUInt32((Int32) requestData["start_lookat_y"]);
// if (requestData.ContainsKey("start_lookat_z"))
// ulaZ = Convert.ToUInt32((Int32) requestData["start_lookat_z"]);
if (requestData.ContainsKey("start_standat_x"))
usaX = Convert.ToUInt32((Int32) requestData["start_standat_x"]);
if (requestData.ContainsKey("start_standat_y"))
usaY = Convert.ToUInt32((Int32) requestData["start_standat_y"]);
if (requestData.ContainsKey("start_standat_z"))
usaZ = Convert.ToUInt32((Int32) requestData["start_standat_z"]);
if (requestData.ContainsKey("about_real_world"))
aboutFirstLive = (string)requestData["about_real_world"];
if (requestData.ContainsKey("about_virtual_world"))
aboutAvatar = (string)requestData["about_virtual_world"];
// if (requestData.ContainsKey("start_standat_x"))
// usaX = Convert.ToUInt32((Int32) requestData["start_standat_x"]);
// if (requestData.ContainsKey("start_standat_y"))
// usaY = Convert.ToUInt32((Int32) requestData["start_standat_y"]);
// if (requestData.ContainsKey("start_standat_z"))
// usaZ = Convert.ToUInt32((Int32) requestData["start_standat_z"]);
// if (requestData.ContainsKey("about_real_world"))
// aboutFirstLive = (string)requestData["about_real_world"];
// if (requestData.ContainsKey("about_virtual_world"))
// aboutAvatar = (string)requestData["about_virtual_world"];
UserProfileData userProfile
= m_app.CommunicationsManager.UserService.GetUserProfile(firstname, lastname);
// UserProfileData userProfile
// = m_app.CommunicationsManager.UserService.GetUserProfile(firstname, lastname);
if (null == userProfile)
throw new Exception(String.Format("avatar {0} {1} does not exist", firstname, lastname));
// if (null == userProfile)
// throw new Exception(String.Format("avatar {0} {1} does not exist", firstname, lastname));
if (!String.IsNullOrEmpty(passwd))
{
m_log.DebugFormat("[RADMIN]: UpdateUserAccount: updating password for avatar {0} {1}", firstname, lastname);
string md5PasswdHash = Util.Md5Hash(Util.Md5Hash(passwd) + ":" + String.Empty);
userProfile.PasswordHash = md5PasswdHash;
}
// if (!String.IsNullOrEmpty(passwd))
// {
// m_log.DebugFormat("[RADMIN]: UpdateUserAccount: updating password for avatar {0} {1}", firstname, lastname);
// string md5PasswdHash = Util.Md5Hash(Util.Md5Hash(passwd) + ":" + String.Empty);
// userProfile.PasswordHash = md5PasswdHash;
// }
if (null != regX) userProfile.HomeRegionX = (uint) regX;
if (null != regY) userProfile.HomeRegionY = (uint) regY;
// if (null != regX) userProfile.HomeRegionX = (uint) regX;
// if (null != regY) userProfile.HomeRegionY = (uint) regY;
if (null != usaX) userProfile.HomeLocationX = (uint) usaX;
if (null != usaY) userProfile.HomeLocationY = (uint) usaY;
if (null != usaZ) userProfile.HomeLocationZ = (uint) usaZ;
// if (null != usaX) userProfile.HomeLocationX = (uint) usaX;
// if (null != usaY) userProfile.HomeLocationY = (uint) usaY;
// if (null != usaZ) userProfile.HomeLocationZ = (uint) usaZ;
if (null != ulaX) userProfile.HomeLookAtX = (uint) ulaX;
if (null != ulaY) userProfile.HomeLookAtY = (uint) ulaY;
if (null != ulaZ) userProfile.HomeLookAtZ = (uint) ulaZ;
// if (null != ulaX) userProfile.HomeLookAtX = (uint) ulaX;
// if (null != ulaY) userProfile.HomeLookAtY = (uint) ulaY;
// if (null != ulaZ) userProfile.HomeLookAtZ = (uint) ulaZ;
if (String.Empty != aboutFirstLive) userProfile.FirstLifeAboutText = aboutFirstLive;
if (String.Empty != aboutAvatar) userProfile.AboutText = aboutAvatar;
// if (String.Empty != aboutFirstLive) userProfile.FirstLifeAboutText = aboutFirstLive;
// if (String.Empty != aboutAvatar) userProfile.AboutText = aboutAvatar;
// User has been created. Now establish gender and appearance.
// // User has been created. Now establish gender and appearance.
updateUserAppearance(responseData, requestData, userProfile.ID);
// updateUserAppearance(responseData, requestData, userProfile.ID);
if (!m_app.CommunicationsManager.UserService.UpdateUserProfile(userProfile))
throw new Exception("did not manage to update user profile");
// if (!m_app.CommunicationsManager.UserService.UpdateUserProfile(userProfile))
// throw new Exception("did not manage to update user profile");
responseData["success"] = true;
// responseData["success"] = true;
response.Value = responseData;
// response.Value = responseData;
m_log.InfoFormat("[RADMIN]: UpdateUserAccount: account for user {0} {1} updated, UUID {2}",
firstname, lastname,
userProfile.ID);
}
catch (Exception e)
{
m_log.ErrorFormat("[RADMIN] UpdateUserAccount: failed: {0}", e.Message);
m_log.DebugFormat("[RADMIN] UpdateUserAccount: failed: {0}", e.ToString());
// m_log.InfoFormat("[RADMIN]: UpdateUserAccount: account for user {0} {1} updated, UUID {2}",
// firstname, lastname,
// userProfile.ID);
// }
// catch (Exception e)
// {
// m_log.ErrorFormat("[RADMIN] UpdateUserAccount: failed: {0}", e.Message);
// m_log.DebugFormat("[RADMIN] UpdateUserAccount: failed: {0}", e.ToString());
responseData["success"] = false;
responseData["error"] = e.Message;
// responseData["success"] = false;
// responseData["error"] = e.Message;
response.Value = responseData;
}
}
// response.Value = responseData;
// }
//}
m_log.Info("[RADMIN]: UpdateUserAccount: request complete");
return response;
@ -1445,72 +1431,73 @@ namespace OpenSim.ApplicationPlugins.RemoteController
private void updateUserAppearance(Hashtable responseData, Hashtable requestData, UUID userid)
{
m_log.DebugFormat("[RADMIN] updateUserAppearance");
m_log.Warn("[RADMIN]: This method needs update for 0.7");
string dmale = m_config.GetString("default_male", "Default Male");
string dfemale = m_config.GetString("default_female", "Default Female");
string dneut = m_config.GetString("default_female", "Default Default");
//string dmale = m_config.GetString("default_male", "Default Male");
//string dfemale = m_config.GetString("default_female", "Default Female");
//string dneut = m_config.GetString("default_female", "Default Default");
string model = String.Empty;
// Has a gender preference been supplied?
//// Has a gender preference been supplied?
if (requestData.Contains("gender"))
{
switch ((string)requestData["gender"])
{
case "m" :
model = dmale;
break;
case "f" :
model = dfemale;
break;
case "n" :
default :
model = dneut;
break;
}
}
//if (requestData.Contains("gender"))
//{
// switch ((string)requestData["gender"])
// {
// case "m" :
// model = dmale;
// break;
// case "f" :
// model = dfemale;
// break;
// case "n" :
// default :
// model = dneut;
// break;
// }
//}
// Has an explicit model been specified?
//// Has an explicit model been specified?
if (requestData.Contains("model"))
{
model = (string)requestData["model"];
}
//if (requestData.Contains("model"))
//{
// model = (string)requestData["model"];
//}
// No appearance attributes were set
//// No appearance attributes were set
if (model == String.Empty)
{
m_log.DebugFormat("[RADMIN] Appearance update not requested");
return;
}
//if (model == String.Empty)
//{
// m_log.DebugFormat("[RADMIN] Appearance update not requested");
// return;
//}
m_log.DebugFormat("[RADMIN] Setting appearance for avatar {0}, using model {1}", userid, model);
//m_log.DebugFormat("[RADMIN] Setting appearance for avatar {0}, using model {1}", userid, model);
string[] nomens = model.Split();
if (nomens.Length != 2)
{
m_log.WarnFormat("[RADMIN] User appearance not set for {0}. Invalid model name : <{1}>", userid, model);
// nomens = dmodel.Split();
return;
}
//string[] nomens = model.Split();
//if (nomens.Length != 2)
//{
// m_log.WarnFormat("[RADMIN] User appearance not set for {0}. Invalid model name : <{1}>", userid, model);
// // nomens = dmodel.Split();
// return;
//}
UserProfileData mprof = m_app.CommunicationsManager.UserService.GetUserProfile(nomens[0], nomens[1]);
//UserProfileData mprof = m_app.CommunicationsManager.UserService.GetUserProfile(nomens[0], nomens[1]);
// Is this the first time one of the default models has been used? Create it if that is the case
// otherwise default to male.
//// Is this the first time one of the default models has been used? Create it if that is the case
//// otherwise default to male.
if (mprof == null)
{
m_log.WarnFormat("[RADMIN] Requested model ({0}) not found. Appearance unchanged", model);
return;
}
//if (mprof == null)
//{
// m_log.WarnFormat("[RADMIN] Requested model ({0}) not found. Appearance unchanged", model);
// return;
//}
// Set current user's appearance. This bit is easy. The appearance structure is populated with
// actual asset ids, however to complete the magic we need to populate the inventory with the
// assets in question.
//// Set current user's appearance. This bit is easy. The appearance structure is populated with
//// actual asset ids, however to complete the magic we need to populate the inventory with the
//// assets in question.
establishAppearance(userid, mprof.ID);
//establishAppearance(userid, mprof.ID);
m_log.DebugFormat("[RADMIN] Finished setting appearance for avatar {0}, using model {1}",
userid, model);
@ -1525,8 +1512,10 @@ namespace OpenSim.ApplicationPlugins.RemoteController
private void establishAppearance(UUID dest, UUID srca)
{
m_log.DebugFormat("[RADMIN] Initializing inventory for {0} from {1}", dest, srca);
AvatarAppearance ava = m_app.CommunicationsManager.AvatarService.GetUserAppearance(srca);
AvatarAppearance ava = null;
AvatarData avatar = m_app.SceneManager.CurrentOrFirstScene.AvatarService.GetAvatar(srca);
if (avatar != null)
ava = avatar.ToAvatarAppearance(srca);
// If the model has no associated appearance we're done.
@ -1619,7 +1608,8 @@ namespace OpenSim.ApplicationPlugins.RemoteController
throw new Exception("Unable to load both inventories");
}
m_app.CommunicationsManager.AvatarService.UpdateUserAppearance(dest, ava);
AvatarData adata = new AvatarData(ava);
m_app.SceneManager.CurrentOrFirstScene.AvatarService.SetAvatar(dest, adata);
}
catch (Exception e)
{
@ -1674,7 +1664,6 @@ namespace OpenSim.ApplicationPlugins.RemoteController
uint regX = 1000;
uint regY = 1000;
string passwd = UUID.Random().ToString(); // No requirement to sign-in.
CachedUserInfo UI;
UUID ID = UUID.Zero;
AvatarAppearance mava;
XmlNodeList avatars;
@ -1693,7 +1682,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
assets = doc.GetElementsByTagName("RequiredAsset");
foreach (XmlNode asset in assets)
{
AssetBase rass = new AssetBase(UUID.Random(), GetStringAttribute(asset,"name",""), SByte.Parse(GetStringAttribute(asset,"type","")));
AssetBase rass = new AssetBase(UUID.Random(), GetStringAttribute(asset, "name", ""), SByte.Parse(GetStringAttribute(asset, "type", "")), UUID.Zero.ToString());
rass.Description = GetStringAttribute(asset,"desc","");
rass.Local = Boolean.Parse(GetStringAttribute(asset,"local",""));
rass.Temporary = Boolean.Parse(GetStringAttribute(asset,"temporary",""));
@ -1722,20 +1711,27 @@ namespace OpenSim.ApplicationPlugins.RemoteController
passwd = GetStringAttribute(avatar,"password",passwd);
string[] nomens = name.Split();
UI = m_app.CommunicationsManager.UserProfileCacheService.GetUserDetails(nomens[0], nomens[1]);
if (null == UI)
UUID scopeID = m_app.SceneManager.CurrentOrFirstScene.RegionInfo.ScopeID;
UserAccount account = m_app.SceneManager.CurrentOrFirstScene.UserAccountService.GetUserAccount(scopeID, nomens[0], nomens[1]);
if (null == account)
{
ID = m_app.CommunicationsManager.UserAdminService.AddUser(nomens[0], nomens[1],
passwd, email, regX, regY);
if (ID == UUID.Zero)
account = new UserAccount(scopeID, nomens[0], nomens[1], email);
bool success = m_app.SceneManager.CurrentOrFirstScene.UserAccountService.StoreUserAccount(account);
if (!success)
{
m_log.ErrorFormat("[RADMIN] Avatar {0} {1} was not created", nomens[0], nomens[1]);
return false;
}
// !!! REFACTORING PROBLEM: need to set the password
GridRegion home = m_app.SceneManager.CurrentOrFirstScene.GridService.GetRegionByPosition(scopeID,
(int)(regX * Constants.RegionSize), (int)(regY * Constants.RegionSize));
if (home != null)
m_app.SceneManager.CurrentOrFirstScene.PresenceService.SetHomeLocation(account.PrincipalID.ToString(), home.RegionID, new Vector3(128, 128, 0), new Vector3(0, 1, 0));
}
else
{
ID = UI.UserProfile.ID;
ID = account.PrincipalID;
}
m_log.DebugFormat("[RADMIN] User {0}[{1}] created or retrieved", name, ID);
@ -1759,10 +1755,11 @@ namespace OpenSim.ApplicationPlugins.RemoteController
iserv.GetUserInventory(ID, uic.callback);
// While the inventory is being fetched, setup for appearance processing
if ((mava = m_app.CommunicationsManager.AvatarService.GetUserAppearance(ID)) == null)
{
AvatarData adata = m_app.SceneManager.CurrentOrFirstScene.AvatarService.GetAvatar(ID);
if (adata != null)
mava = adata.ToAvatarAppearance(ID);
else
mava = new AvatarAppearance();
}
{
AvatarWearable[] wearables = mava.Wearables;
@ -1897,7 +1894,8 @@ namespace OpenSim.ApplicationPlugins.RemoteController
m_log.DebugFormat("[RADMIN] Outfit {0} load completed", oname);
} // foreach outfit
m_log.DebugFormat("[RADMIN] Inventory update complete for {0}", name);
m_app.CommunicationsManager.AvatarService.UpdateUserAppearance(ID, mava);
AvatarData adata2 = new AvatarData(mava);
m_app.SceneManager.CurrentOrFirstScene.AvatarService.SetAvatar(ID, adata2);
}
catch (Exception e)
{
@ -2509,17 +2507,18 @@ namespace OpenSim.ApplicationPlugins.RemoteController
if (requestData.Contains("users"))
{
UserProfileCacheService ups = m_app.CommunicationsManager.UserProfileCacheService;
UUID scopeID = m_app.SceneManager.CurrentOrFirstScene.RegionInfo.ScopeID;
IUserAccountService userService = m_app.SceneManager.CurrentOrFirstScene.UserAccountService;
Scene s = m_app.SceneManager.CurrentScene;
Hashtable users = (Hashtable) requestData["users"];
List<UUID> uuids = new List<UUID>();
foreach (string name in users.Values)
{
string[] parts = name.Split();
CachedUserInfo udata = ups.GetUserDetails(parts[0],parts[1]);
if (udata != null)
UserAccount account = userService.GetUserAccount(scopeID, parts[0], parts[1]);
if (account != null)
{
uuids.Add(udata.UserProfile.ID);
uuids.Add(account.PrincipalID);
m_log.DebugFormat("[RADMIN] adding \"{0}\" to ACL for \"{1}\"", name, s.RegionInfo.RegionName);
}
}
@ -2595,21 +2594,23 @@ namespace OpenSim.ApplicationPlugins.RemoteController
if (requestData.Contains("users"))
{
UserProfileCacheService ups = m_app.CommunicationsManager.UserProfileCacheService;
UUID scopeID = m_app.SceneManager.CurrentOrFirstScene.RegionInfo.ScopeID;
IUserAccountService userService = m_app.SceneManager.CurrentOrFirstScene.UserAccountService;
//UserProfileCacheService ups = m_app.CommunicationsManager.UserProfileCacheService;
Scene s = m_app.SceneManager.CurrentScene;
Hashtable users = (Hashtable) requestData["users"];
List<UUID> uuids = new List<UUID>();
foreach (string name in users.Values)
foreach (string name in users.Values)
{
string[] parts = name.Split();
CachedUserInfo udata = ups.GetUserDetails(parts[0],parts[1]);
if (udata != null)
UserAccount account = userService.GetUserAccount(scopeID, parts[0], parts[1]);
if (account != null)
{
uuids.Add(udata.UserProfile.ID);
uuids.Add(account.PrincipalID);
}
}
List<UUID> acl = new List<UUID>(s.RegionInfo.EstateSettings.EstateAccess);
foreach (UUID uuid in uuids)
foreach (UUID uuid in uuids)
{
if (acl.Contains(uuid))
{
@ -2682,10 +2683,11 @@ namespace OpenSim.ApplicationPlugins.RemoteController
foreach (UUID user in acl)
{
CachedUserInfo udata = m_app.CommunicationsManager.UserProfileCacheService.GetUserDetails(user);
if (udata != null)
UUID scopeID = m_app.SceneManager.CurrentOrFirstScene.RegionInfo.ScopeID;
UserAccount account = m_app.SceneManager.CurrentOrFirstScene.UserAccountService.GetUserAccount(scopeID, user);
if (account != null)
{
users[user.ToString()] = udata.UserProfile.Name;
users[user.ToString()] = account.FirstName + " " + account.LastName;
}
}

View File

@ -35,6 +35,9 @@ using System.Xml;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Services.Interfaces;
using OpenMetaverse;
namespace OpenSim.ApplicationPlugins.Rest.Inventory
{
@ -658,7 +661,6 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory
{
int x;
string HA1;
string first;
string last;
@ -675,17 +677,13 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory
last = String.Empty;
}
UserProfileData udata = Rest.UserServices.GetUserProfile(first, last);
UserAccount account = Rest.UserServices.GetUserAccount(UUID.Zero, first, last);
// If we don't recognize the user id, perhaps it is god?
if (udata == null)
if (account == null)
return pass == Rest.GodKey;
HA1 = HashToString(pass);
HA1 = HashToString(String.Format("{0}:{1}",HA1,udata.PasswordSalt));
return (0 == sc.Compare(HA1, udata.PasswordHash));
return (Rest.AuthServices.Authenticate(account.PrincipalID, pass, 1) != string.Empty);
}
@ -897,11 +895,10 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory
last = String.Empty;
}
UserProfileData udata = Rest.UserServices.GetUserProfile(first, last);
UserAccount account = Rest.UserServices.GetUserAccount(UUID.Zero, first, last);
// If we don;t recognize the user id, perhaps it is god?
if (udata == null)
if (account == null)
{
Rest.Log.DebugFormat("{0} Administrator", MsgId);
return Rest.GodKey;
@ -909,7 +906,12 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory
else
{
Rest.Log.DebugFormat("{0} Normal User {1}", MsgId, user);
return udata.PasswordHash;
// !!! REFACTORING PROBLEM
// This is what it was. It doesn't work in 0.7
// Nothing retrieves the password from the authentication service, there's only authentication.
//return udata.PasswordHash;
return string.Empty;
}
}

View File

@ -35,7 +35,7 @@ using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Services.Interfaces;
using IUserService = OpenSim.Framework.Communications.IUserService;
using IAvatarService = OpenSim.Services.Interfaces.IAvatarService;
namespace OpenSim.ApplicationPlugins.Rest.Inventory
{
@ -92,24 +92,24 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory
/// initializes.
/// </summary>
internal static CommunicationsManager Comms
{
get { return main.CommunicationsManager; }
}
internal static IInventoryService InventoryServices
{
get { return main.SceneManager.CurrentOrFirstScene.InventoryService; }
}
internal static IUserService UserServices
internal static IUserAccountService UserServices
{
get { return Comms.UserService; }
get { return main.SceneManager.CurrentOrFirstScene.UserAccountService; }
}
internal static IAuthenticationService AuthServices
{
get { return main.SceneManager.CurrentOrFirstScene.AuthenticationService; }
}
internal static IAvatarService AvatarServices
{
get { return Comms.AvatarService; }
get { return main.SceneManager.CurrentOrFirstScene.AvatarService; }
}
internal static IAssetService AssetServices

View File

@ -32,6 +32,7 @@ using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Services.Interfaces;
namespace OpenSim.ApplicationPlugins.Rest.Inventory
{
@ -135,152 +136,153 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory
private void DoAppearance(RequestData hdata)
{
// !!! REFACTORIMG PROBLEM. This needs rewriting for 0.7
AppearanceRequestData rdata = (AppearanceRequestData) hdata;
//AppearanceRequestData rdata = (AppearanceRequestData) hdata;
Rest.Log.DebugFormat("{0} DoAppearance ENTRY", MsgId);
//Rest.Log.DebugFormat("{0} DoAppearance ENTRY", MsgId);
// If we're disabled, do nothing.
//// If we're disabled, do nothing.
if (!enabled)
{
return;
}
//if (!enabled)
//{
// return;
//}
// Now that we know this is a serious attempt to
// access inventory data, we should find out who
// is asking, and make sure they are authorized
// to do so. We need to validate the caller's
// identity before revealing anything about the
// status quo. Authenticate throws an exception
// via Fail if no identity information is present.
//
// With the present HTTP server we can't use the
// builtin authentication mechanisms because they
// would be enforced for all in-bound requests.
// Instead we look at the headers ourselves and
// handle authentication directly.
//// Now that we know this is a serious attempt to
//// access inventory data, we should find out who
//// is asking, and make sure they are authorized
//// to do so. We need to validate the caller's
//// identity before revealing anything about the
//// status quo. Authenticate throws an exception
//// via Fail if no identity information is present.
////
//// With the present HTTP server we can't use the
//// builtin authentication mechanisms because they
//// would be enforced for all in-bound requests.
//// Instead we look at the headers ourselves and
//// handle authentication directly.
try
{
if (!rdata.IsAuthenticated)
{
rdata.Fail(Rest.HttpStatusCodeNotAuthorized,String.Format("user \"{0}\" could not be authenticated", rdata.userName));
}
}
catch (RestException e)
{
if (e.statusCode == Rest.HttpStatusCodeNotAuthorized)
{
Rest.Log.WarnFormat("{0} User not authenticated", MsgId);
Rest.Log.DebugFormat("{0} Authorization header: {1}", MsgId, rdata.request.Headers.Get("Authorization"));
}
else
{
Rest.Log.ErrorFormat("{0} User authentication failed", MsgId);
Rest.Log.DebugFormat("{0} Authorization header: {1}", MsgId, rdata.request.Headers.Get("Authorization"));
}
throw (e);
}
//try
//{
// if (!rdata.IsAuthenticated)
// {
// rdata.Fail(Rest.HttpStatusCodeNotAuthorized,String.Format("user \"{0}\" could not be authenticated", rdata.userName));
// }
//}
//catch (RestException e)
//{
// if (e.statusCode == Rest.HttpStatusCodeNotAuthorized)
// {
// Rest.Log.WarnFormat("{0} User not authenticated", MsgId);
// Rest.Log.DebugFormat("{0} Authorization header: {1}", MsgId, rdata.request.Headers.Get("Authorization"));
// }
// else
// {
// Rest.Log.ErrorFormat("{0} User authentication failed", MsgId);
// Rest.Log.DebugFormat("{0} Authorization header: {1}", MsgId, rdata.request.Headers.Get("Authorization"));
// }
// throw (e);
//}
Rest.Log.DebugFormat("{0} Authenticated {1}", MsgId, rdata.userName);
//Rest.Log.DebugFormat("{0} Authenticated {1}", MsgId, rdata.userName);
// We can only get here if we are authorized
//
// The requestor may have specified an UUID or
// a conjoined FirstName LastName string. We'll
// try both. If we fail with the first, UUID,
// attempt, we try the other. As an example, the
// URI for a valid inventory request might be:
//
// http://<host>:<port>/admin/inventory/Arthur Dent
//
// Indicating that this is an inventory request for
// an avatar named Arthur Dent. This is ALL that is
// required to designate a GET for an entire
// inventory.
//
//// We can only get here if we are authorized
////
//// The requestor may have specified an UUID or
//// a conjoined FirstName LastName string. We'll
//// try both. If we fail with the first, UUID,
//// attempt, we try the other. As an example, the
//// URI for a valid inventory request might be:
////
//// http://<host>:<port>/admin/inventory/Arthur Dent
////
//// Indicating that this is an inventory request for
//// an avatar named Arthur Dent. This is ALL that is
//// required to designate a GET for an entire
//// inventory.
////
// Do we have at least a user agent name?
//// Do we have at least a user agent name?
if (rdata.Parameters.Length < 1)
{
Rest.Log.WarnFormat("{0} Appearance: No user agent identifier specified", MsgId);
rdata.Fail(Rest.HttpStatusCodeBadRequest, "no user identity specified");
}
//if (rdata.Parameters.Length < 1)
//{
// Rest.Log.WarnFormat("{0} Appearance: No user agent identifier specified", MsgId);
// rdata.Fail(Rest.HttpStatusCodeBadRequest, "no user identity specified");
//}
// The first parameter MUST be the agent identification, either an UUID
// or a space-separated First-name Last-Name specification. We check for
// an UUID first, if anyone names their character using a valid UUID
// that identifies another existing avatar will cause this a problem...
//// The first parameter MUST be the agent identification, either an UUID
//// or a space-separated First-name Last-Name specification. We check for
//// an UUID first, if anyone names their character using a valid UUID
//// that identifies another existing avatar will cause this a problem...
try
{
rdata.uuid = new UUID(rdata.Parameters[PARM_USERID]);
Rest.Log.DebugFormat("{0} UUID supplied", MsgId);
rdata.userProfile = Rest.UserServices.GetUserProfile(rdata.uuid);
}
catch
{
string[] names = rdata.Parameters[PARM_USERID].Split(Rest.CA_SPACE);
if (names.Length == 2)
{
Rest.Log.DebugFormat("{0} Agent Name supplied [2]", MsgId);
rdata.userProfile = Rest.UserServices.GetUserProfile(names[0],names[1]);
}
else
{
Rest.Log.WarnFormat("{0} A Valid UUID or both first and last names must be specified", MsgId);
rdata.Fail(Rest.HttpStatusCodeBadRequest, "invalid user identity");
}
}
//try
//{
// rdata.uuid = new UUID(rdata.Parameters[PARM_USERID]);
// Rest.Log.DebugFormat("{0} UUID supplied", MsgId);
// rdata.userProfile = Rest.UserServices.GetUserProfile(rdata.uuid);
//}
//catch
//{
// string[] names = rdata.Parameters[PARM_USERID].Split(Rest.CA_SPACE);
// if (names.Length == 2)
// {
// Rest.Log.DebugFormat("{0} Agent Name supplied [2]", MsgId);
// rdata.userProfile = Rest.UserServices.GetUserProfile(names[0],names[1]);
// }
// else
// {
// Rest.Log.WarnFormat("{0} A Valid UUID or both first and last names must be specified", MsgId);
// rdata.Fail(Rest.HttpStatusCodeBadRequest, "invalid user identity");
// }
//}
// If the user profile is null then either the server is broken, or the
// user is not known. We always assume the latter case.
//// If the user profile is null then either the server is broken, or the
//// user is not known. We always assume the latter case.
if (rdata.userProfile != null)
{
Rest.Log.DebugFormat("{0} User profile obtained for agent {1} {2}",
MsgId, rdata.userProfile.FirstName, rdata.userProfile.SurName);
}
else
{
Rest.Log.WarnFormat("{0} No user profile for {1}", MsgId, rdata.path);
rdata.Fail(Rest.HttpStatusCodeNotFound, "unrecognized user identity");
}
//if (rdata.userProfile != null)
//{
// Rest.Log.DebugFormat("{0} User profile obtained for agent {1} {2}",
// MsgId, rdata.userProfile.FirstName, rdata.userProfile.SurName);
//}
//else
//{
// Rest.Log.WarnFormat("{0} No user profile for {1}", MsgId, rdata.path);
// rdata.Fail(Rest.HttpStatusCodeNotFound, "unrecognized user identity");
//}
// If we get to here, then we have effectively validated the user's
//// If we get to here, then we have effectively validated the user's
switch (rdata.method)
{
case Rest.HEAD : // Do the processing, set the status code, suppress entity
DoGet(rdata);
rdata.buffer = null;
break;
//switch (rdata.method)
//{
// case Rest.HEAD : // Do the processing, set the status code, suppress entity
// DoGet(rdata);
// rdata.buffer = null;
// break;
case Rest.GET : // Do the processing, set the status code, return entity
DoGet(rdata);
break;
// case Rest.GET : // Do the processing, set the status code, return entity
// DoGet(rdata);
// break;
case Rest.PUT : // Update named element
DoUpdate(rdata);
break;
// case Rest.PUT : // Update named element
// DoUpdate(rdata);
// break;
case Rest.POST : // Add new information to identified context.
DoExtend(rdata);
break;
// case Rest.POST : // Add new information to identified context.
// DoExtend(rdata);
// break;
case Rest.DELETE : // Delete information
DoDelete(rdata);
break;
// case Rest.DELETE : // Delete information
// DoDelete(rdata);
// break;
default :
Rest.Log.WarnFormat("{0} Method {1} not supported for {2}",
MsgId, rdata.method, rdata.path);
rdata.Fail(Rest.HttpStatusCodeMethodNotAllowed,
String.Format("{0} not supported", rdata.method));
break;
}
// default :
// Rest.Log.WarnFormat("{0} Method {1} not supported for {2}",
// MsgId, rdata.method, rdata.path);
// rdata.Fail(Rest.HttpStatusCodeMethodNotAllowed,
// String.Format("{0} not supported", rdata.method));
// break;
//}
}
#endregion Interface
@ -294,15 +296,15 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory
private void DoGet(AppearanceRequestData rdata)
{
AvatarData adata = Rest.AvatarServices.GetAvatar(rdata.userProfile.ID);
rdata.userAppearance = Rest.AvatarServices.GetUserAppearance(rdata.userProfile.ID);
if (rdata.userAppearance == null)
if (adata == null)
{
rdata.Fail(Rest.HttpStatusCodeNoContent,
String.Format("appearance data not found for user {0} {1}",
rdata.userProfile.FirstName, rdata.userProfile.SurName));
}
rdata.userAppearance = adata.ToAvatarAppearance(rdata.userProfile.ID);
rdata.initXmlWriter();
@ -341,18 +343,20 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory
// increasingly doubtful that it is appropriate for REST. If I attempt to
// add a new record, and it already exists, then it seems to me that the
// attempt should fail, rather than update the existing record.
AvatarData adata = null;
if (GetUserAppearance(rdata))
{
modified = rdata.userAppearance != null;
created = !modified;
Rest.AvatarServices.UpdateUserAppearance(rdata.userProfile.ID, rdata.userAppearance);
adata = new AvatarData(rdata.userAppearance);
Rest.AvatarServices.SetAvatar(rdata.userProfile.ID, adata);
// Rest.UserServices.UpdateUserProfile(rdata.userProfile);
}
else
{
created = true;
Rest.AvatarServices.UpdateUserAppearance(rdata.userProfile.ID, rdata.userAppearance);
adata = new AvatarData(rdata.userAppearance);
Rest.AvatarServices.SetAvatar(rdata.userProfile.ID, adata);
// Rest.UserServices.UpdateUserProfile(rdata.userProfile);
}
@ -391,37 +395,39 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory
private void DoUpdate(AppearanceRequestData rdata)
{
bool created = false;
bool modified = false;
// REFACTORING PROBLEM This was commented out. It doesn't work for 0.7
//bool created = false;
//bool modified = false;
rdata.userAppearance = Rest.AvatarServices.GetUserAppearance(rdata.userProfile.ID);
//rdata.userAppearance = Rest.AvatarServices.GetUserAppearance(rdata.userProfile.ID);
// If the user exists then this is considered a modification regardless
// of what may, or may not be, specified in the payload.
//// If the user exists then this is considered a modification regardless
//// of what may, or may not be, specified in the payload.
if (rdata.userAppearance != null)
{
modified = true;
Rest.AvatarServices.UpdateUserAppearance(rdata.userProfile.ID, rdata.userAppearance);
Rest.UserServices.UpdateUserProfile(rdata.userProfile);
}
//if (rdata.userAppearance != null)
//{
// modified = true;
// Rest.AvatarServices.UpdateUserAppearance(rdata.userProfile.ID, rdata.userAppearance);
// Rest.UserServices.UpdateUserProfile(rdata.userProfile);
//}
if (created)
{
rdata.Complete(Rest.HttpStatusCodeCreated);
}
else
{
if (modified)
{
rdata.Complete(Rest.HttpStatusCodeOK);
}
else
{
rdata.Complete(Rest.HttpStatusCodeNoContent);
}
}
//if (created)
//{
// rdata.Complete(Rest.HttpStatusCodeCreated);
//}
//else
//{
// if (modified)
// {
// rdata.Complete(Rest.HttpStatusCodeOK);
// }
// else
// {
// rdata.Complete(Rest.HttpStatusCodeNoContent);
// }
//}
rdata.Respond(String.Format("Appearance {0} : Normal completion", rdata.method));
@ -436,21 +442,22 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory
private void DoDelete(AppearanceRequestData rdata)
{
AvatarData adata = Rest.AvatarServices.GetAvatar(rdata.userProfile.ID);
AvatarAppearance old = Rest.AvatarServices.GetUserAppearance(rdata.userProfile.ID);
if (old != null)
if (adata != null)
{
AvatarAppearance old = adata.ToAvatarAppearance(rdata.userProfile.ID);
rdata.userAppearance = new AvatarAppearance();
rdata.userAppearance.Owner = old.Owner;
adata = new AvatarData(rdata.userAppearance);
Rest.AvatarServices.UpdateUserAppearance(rdata.userProfile.ID, rdata.userAppearance);
Rest.AvatarServices.SetAvatar(rdata.userProfile.ID, adata);
rdata.Complete();
}
else
{
rdata.Complete(Rest.HttpStatusCodeNoContent);
}

View File

@ -261,7 +261,7 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory
modified = (asset != null);
created = !modified;
asset = new AssetBase(uuid, xml.GetAttribute("name"), SByte.Parse(xml.GetAttribute("type")));
asset = new AssetBase(uuid, xml.GetAttribute("name"), SByte.Parse(xml.GetAttribute("type")), UUID.Zero.ToString());
asset.Description = xml.GetAttribute("desc");
asset.Local = Int32.Parse(xml.GetAttribute("local")) != 0;
asset.Temporary = Int32.Parse(xml.GetAttribute("temporary")) != 0;
@ -338,7 +338,7 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory
modified = (asset != null);
created = !modified;
asset = new AssetBase(uuid, xml.GetAttribute("name"), SByte.Parse(xml.GetAttribute("type")));
asset = new AssetBase(uuid, xml.GetAttribute("name"), SByte.Parse(xml.GetAttribute("type")), UUID.Zero.ToString());
asset.Description = xml.GetAttribute("desc");
asset.Local = Int32.Parse(xml.GetAttribute("local")) != 0;
asset.Temporary = Int32.Parse(xml.GetAttribute("temporary")) != 0;

View File

@ -36,7 +36,7 @@ using System.Xml;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenSim.Framework;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using Timer=System.Timers.Timer;
@ -143,203 +143,205 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory
Rest.Log.DebugFormat("{0} DoInventory ENTRY", MsgId);
// If we're disabled, do nothing.
// !!! REFACTORING PROBLEM
if (!enabled)
{
return;
}
//// If we're disabled, do nothing.
// Now that we know this is a serious attempt to
// access inventory data, we should find out who
// is asking, and make sure they are authorized
// to do so. We need to validate the caller's
// identity before revealing anything about the
// status quo. Authenticate throws an exception
// via Fail if no identity information is present.
//
// With the present HTTP server we can't use the
// builtin authentication mechanisms because they
// would be enforced for all in-bound requests.
// Instead we look at the headers ourselves and
// handle authentication directly.
//if (!enabled)
//{
// return;
//}
try
{
if (!rdata.IsAuthenticated)
{
rdata.Fail(Rest.HttpStatusCodeNotAuthorized,String.Format("user \"{0}\" could not be authenticated", rdata.userName));
}
}
catch (RestException e)
{
if (e.statusCode == Rest.HttpStatusCodeNotAuthorized)
{
Rest.Log.WarnFormat("{0} User not authenticated", MsgId);
Rest.Log.DebugFormat("{0} Authorization header: {1}", MsgId, rdata.request.Headers.Get("Authorization"));
}
else
{
Rest.Log.ErrorFormat("{0} User authentication failed", MsgId);
Rest.Log.DebugFormat("{0} Authorization header: {1}", MsgId, rdata.request.Headers.Get("Authorization"));
}
throw (e);
}
//// Now that we know this is a serious attempt to
//// access inventory data, we should find out who
//// is asking, and make sure they are authorized
//// to do so. We need to validate the caller's
//// identity before revealing anything about the
//// status quo. Authenticate throws an exception
//// via Fail if no identity information is present.
////
//// With the present HTTP server we can't use the
//// builtin authentication mechanisms because they
//// would be enforced for all in-bound requests.
//// Instead we look at the headers ourselves and
//// handle authentication directly.
Rest.Log.DebugFormat("{0} Authenticated {1}", MsgId, rdata.userName);
//try
//{
// if (!rdata.IsAuthenticated)
// {
// rdata.Fail(Rest.HttpStatusCodeNotAuthorized,String.Format("user \"{0}\" could not be authenticated", rdata.userName));
// }
//}
//catch (RestException e)
//{
// if (e.statusCode == Rest.HttpStatusCodeNotAuthorized)
// {
// Rest.Log.WarnFormat("{0} User not authenticated", MsgId);
// Rest.Log.DebugFormat("{0} Authorization header: {1}", MsgId, rdata.request.Headers.Get("Authorization"));
// }
// else
// {
// Rest.Log.ErrorFormat("{0} User authentication failed", MsgId);
// Rest.Log.DebugFormat("{0} Authorization header: {1}", MsgId, rdata.request.Headers.Get("Authorization"));
// }
// throw (e);
//}
// We can only get here if we are authorized
//
// The requestor may have specified an UUID or
// a conjoined FirstName LastName string. We'll
// try both. If we fail with the first, UUID,
// attempt, we try the other. As an example, the
// URI for a valid inventory request might be:
//
// http://<host>:<port>/admin/inventory/Arthur Dent
//
// Indicating that this is an inventory request for
// an avatar named Arthur Dent. This is ALL that is
// required to designate a GET for an entire
// inventory.
//
//Rest.Log.DebugFormat("{0} Authenticated {1}", MsgId, rdata.userName);
//// We can only get here if we are authorized
////
//// The requestor may have specified an UUID or
//// a conjoined FirstName LastName string. We'll
//// try both. If we fail with the first, UUID,
//// attempt, we try the other. As an example, the
//// URI for a valid inventory request might be:
////
//// http://<host>:<port>/admin/inventory/Arthur Dent
////
//// Indicating that this is an inventory request for
//// an avatar named Arthur Dent. This is ALL that is
//// required to designate a GET for an entire
//// inventory.
////
// Do we have at least a user agent name?
//// Do we have at least a user agent name?
if (rdata.Parameters.Length < 1)
{
Rest.Log.WarnFormat("{0} Inventory: No user agent identifier specified", MsgId);
rdata.Fail(Rest.HttpStatusCodeBadRequest, "no user identity specified");
}
//if (rdata.Parameters.Length < 1)
//{
// Rest.Log.WarnFormat("{0} Inventory: No user agent identifier specified", MsgId);
// rdata.Fail(Rest.HttpStatusCodeBadRequest, "no user identity specified");
//}
// The first parameter MUST be the agent identification, either an UUID
// or a space-separated First-name Last-Name specification. We check for
// an UUID first, if anyone names their character using a valid UUID
// that identifies another existing avatar will cause this a problem...
//// The first parameter MUST be the agent identification, either an UUID
//// or a space-separated First-name Last-Name specification. We check for
//// an UUID first, if anyone names their character using a valid UUID
//// that identifies another existing avatar will cause this a problem...
try
{
rdata.uuid = new UUID(rdata.Parameters[PARM_USERID]);
Rest.Log.DebugFormat("{0} UUID supplied", MsgId);
rdata.userProfile = Rest.UserServices.GetUserProfile(rdata.uuid);
}
catch
{
string[] names = rdata.Parameters[PARM_USERID].Split(Rest.CA_SPACE);
if (names.Length == 2)
{
Rest.Log.DebugFormat("{0} Agent Name supplied [2]", MsgId);
rdata.userProfile = Rest.UserServices.GetUserProfile(names[0],names[1]);
}
else
{
Rest.Log.WarnFormat("{0} A Valid UUID or both first and last names must be specified", MsgId);
rdata.Fail(Rest.HttpStatusCodeBadRequest, "invalid user identity");
}
}
//try
//{
// rdata.uuid = new UUID(rdata.Parameters[PARM_USERID]);
// Rest.Log.DebugFormat("{0} UUID supplied", MsgId);
// rdata.userProfile = Rest.UserServices.GetUserProfile(rdata.uuid);
//}
//catch
//{
// string[] names = rdata.Parameters[PARM_USERID].Split(Rest.CA_SPACE);
// if (names.Length == 2)
// {
// Rest.Log.DebugFormat("{0} Agent Name supplied [2]", MsgId);
// rdata.userProfile = Rest.UserServices.GetUserProfile(names[0],names[1]);
// }
// else
// {
// Rest.Log.WarnFormat("{0} A Valid UUID or both first and last names must be specified", MsgId);
// rdata.Fail(Rest.HttpStatusCodeBadRequest, "invalid user identity");
// }
//}
// If the user profile is null then either the server is broken, or the
// user is not known. We always assume the latter case.
//// If the user profile is null then either the server is broken, or the
//// user is not known. We always assume the latter case.
if (rdata.userProfile != null)
{
Rest.Log.DebugFormat("{0} Profile obtained for agent {1} {2}",
MsgId, rdata.userProfile.FirstName, rdata.userProfile.SurName);
}
else
{
Rest.Log.WarnFormat("{0} No profile for {1}", MsgId, rdata.path);
rdata.Fail(Rest.HttpStatusCodeNotFound, "unrecognized user identity");
}
//if (rdata.userProfile != null)
//{
// Rest.Log.DebugFormat("{0} Profile obtained for agent {1} {2}",
// MsgId, rdata.userProfile.FirstName, rdata.userProfile.SurName);
//}
//else
//{
// Rest.Log.WarnFormat("{0} No profile for {1}", MsgId, rdata.path);
// rdata.Fail(Rest.HttpStatusCodeNotFound, "unrecognized user identity");
//}
// If we get to here, then we have effectively validated the user's
// identity. Now we need to get the inventory. If the server does not
// have the inventory, we reject the request with an appropriate explanation.
//
// Note that inventory retrieval is an asynchronous event, we use the rdata
// class instance as the basis for our synchronization.
//
//// If we get to here, then we have effectively validated the user's
//// identity. Now we need to get the inventory. If the server does not
//// have the inventory, we reject the request with an appropriate explanation.
////
//// Note that inventory retrieval is an asynchronous event, we use the rdata
//// class instance as the basis for our synchronization.
////
rdata.uuid = rdata.userProfile.ID;
//rdata.uuid = rdata.userProfile.ID;
if (Rest.InventoryServices.HasInventoryForUser(rdata.uuid))
{
rdata.root = Rest.InventoryServices.GetRootFolder(rdata.uuid);
//if (Rest.InventoryServices.HasInventoryForUser(rdata.uuid))
//{
// rdata.root = Rest.InventoryServices.GetRootFolder(rdata.uuid);
Rest.Log.DebugFormat("{0} Inventory Root retrieved for {1} {2}",
MsgId, rdata.userProfile.FirstName, rdata.userProfile.SurName);
// Rest.Log.DebugFormat("{0} Inventory Root retrieved for {1} {2}",
// MsgId, rdata.userProfile.FirstName, rdata.userProfile.SurName);
Rest.InventoryServices.GetUserInventory(rdata.uuid, rdata.GetUserInventory);
// Rest.InventoryServices.GetUserInventory(rdata.uuid, rdata.GetUserInventory);
Rest.Log.DebugFormat("{0} Inventory catalog requested for {1} {2}",
MsgId, rdata.userProfile.FirstName, rdata.userProfile.SurName);
// Rest.Log.DebugFormat("{0} Inventory catalog requested for {1} {2}",
// MsgId, rdata.userProfile.FirstName, rdata.userProfile.SurName);
lock (rdata)
{
if (!rdata.HaveInventory)
{
rdata.startWD(1000);
rdata.timeout = false;
Monitor.Wait(rdata);
}
}
// lock (rdata)
// {
// if (!rdata.HaveInventory)
// {
// rdata.startWD(1000);
// rdata.timeout = false;
// Monitor.Wait(rdata);
// }
// }
if (rdata.timeout)
{
Rest.Log.WarnFormat("{0} Inventory not available for {1} {2}. No response from service.",
MsgId, rdata.userProfile.FirstName, rdata.userProfile.SurName);
rdata.Fail(Rest.HttpStatusCodeServerError, "inventory server not responding");
}
// if (rdata.timeout)
// {
// Rest.Log.WarnFormat("{0} Inventory not available for {1} {2}. No response from service.",
// MsgId, rdata.userProfile.FirstName, rdata.userProfile.SurName);
// rdata.Fail(Rest.HttpStatusCodeServerError, "inventory server not responding");
// }
if (rdata.root == null)
{
Rest.Log.WarnFormat("{0} Inventory is not available [1] for agent {1} {2}",
MsgId, rdata.userProfile.FirstName, rdata.userProfile.SurName);
rdata.Fail(Rest.HttpStatusCodeServerError, "inventory retrieval failed");
}
// if (rdata.root == null)
// {
// Rest.Log.WarnFormat("{0} Inventory is not available [1] for agent {1} {2}",
// MsgId, rdata.userProfile.FirstName, rdata.userProfile.SurName);
// rdata.Fail(Rest.HttpStatusCodeServerError, "inventory retrieval failed");
// }
}
else
{
Rest.Log.WarnFormat("{0} Inventory is not locally available for agent {1} {2}",
MsgId, rdata.userProfile.FirstName, rdata.userProfile.SurName);
rdata.Fail(Rest.HttpStatusCodeNotFound, "no local inventory for user");
}
//}
//else
//{
// Rest.Log.WarnFormat("{0} Inventory is not locally available for agent {1} {2}",
// MsgId, rdata.userProfile.FirstName, rdata.userProfile.SurName);
// rdata.Fail(Rest.HttpStatusCodeNotFound, "no local inventory for user");
//}
// If we get here, then we have successfully retrieved the user's information
// and inventory information is now available locally.
//// If we get here, then we have successfully retrieved the user's information
//// and inventory information is now available locally.
switch (rdata.method)
{
case Rest.HEAD : // Do the processing, set the status code, suppress entity
DoGet(rdata);
rdata.buffer = null;
break;
//switch (rdata.method)
//{
// case Rest.HEAD : // Do the processing, set the status code, suppress entity
// DoGet(rdata);
// rdata.buffer = null;
// break;
case Rest.GET : // Do the processing, set the status code, return entity
DoGet(rdata);
break;
// case Rest.GET : // Do the processing, set the status code, return entity
// DoGet(rdata);
// break;
case Rest.PUT : // Update named element
DoUpdate(rdata);
break;
// case Rest.PUT : // Update named element
// DoUpdate(rdata);
// break;
case Rest.POST : // Add new information to identified context.
DoExtend(rdata);
break;
// case Rest.POST : // Add new information to identified context.
// DoExtend(rdata);
// break;
case Rest.DELETE : // Delete information
DoDelete(rdata);
break;
// case Rest.DELETE : // Delete information
// DoDelete(rdata);
// break;
default :
Rest.Log.WarnFormat("{0} Method {1} not supported for {2}",
MsgId, rdata.method, rdata.path);
rdata.Fail(Rest.HttpStatusCodeMethodNotAllowed,
String.Format("{0} not supported", rdata.method));
break;
}
// default :
// Rest.Log.WarnFormat("{0} Method {1} not supported for {2}",
// MsgId, rdata.method, rdata.path);
// rdata.Fail(Rest.HttpStatusCodeMethodNotAllowed,
// String.Format("{0} not supported", rdata.method));
// break;
//}
}
#endregion Interface
@ -1869,7 +1871,7 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory
// Create AssetBase entity to hold the inlined asset
asset = new AssetBase(uuid, name, type);
asset = new AssetBase(uuid, name, type, UUID.Zero.ToString());
asset.Description = desc;
asset.Local = local;

View File

@ -113,14 +113,6 @@ namespace OpenSim.ApplicationPlugins.Rest.Regions
rxw.WriteString(s.RegionInfo.ExternalHostName);
rxw.WriteEndAttribute();
rxw.WriteStartAttribute(String.Empty, "master_name", String.Empty);
rxw.WriteString(String.Format("{0} {1}", s.RegionInfo.MasterAvatarFirstName, s.RegionInfo.MasterAvatarLastName));
rxw.WriteEndAttribute();
rxw.WriteStartAttribute(String.Empty, "master_uuid", String.Empty);
rxw.WriteString(s.RegionInfo.MasterAvatarAssignedUUID.ToString());
rxw.WriteEndAttribute();
rxw.WriteStartAttribute(String.Empty, "ip", String.Empty);
rxw.WriteString(s.RegionInfo.InternalEndPoint.ToString());
rxw.WriteEndAttribute();

View File

@ -56,20 +56,13 @@ namespace OpenSim.ApplicationPlugins.Rest.Regions
region_id = regInfo.RegionID.ToString();
region_x = regInfo.RegionLocX;
region_y = regInfo.RegionLocY;
if (regInfo.EstateSettings.EstateOwner != UUID.Zero)
region_owner_id = regInfo.EstateSettings.EstateOwner.ToString();
else
region_owner_id = regInfo.MasterAvatarAssignedUUID.ToString();
region_owner_id = regInfo.EstateSettings.EstateOwner.ToString();
region_http_port = regInfo.HttpPort;
region_server_uri = regInfo.ServerURI;
region_external_hostname = regInfo.ExternalHostName;
Uri uri = new Uri(region_server_uri);
region_port = (uint)uri.Port;
if (!String.IsNullOrEmpty(regInfo.MasterAvatarFirstName))
region_owner = String.Format("{0} {1}", regInfo.MasterAvatarFirstName,
regInfo.MasterAvatarLastName);
}
public string this[string idx]

View File

@ -1,335 +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 System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Security.Authentication;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Servers;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Client.Linden
{
/// <summary>
/// Handles login user (expect user) and logoff user messages from the remote LL login server
/// </summary>
public class LLProxyLoginModule : ISharedRegionModule
{
private uint m_port = 0;
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public LLProxyLoginModule(uint port)
{
m_log.DebugFormat("[CLIENT]: LLProxyLoginModule port {0}", port);
m_port = port;
}
protected List<Scene> m_scenes = new List<Scene>();
protected Scene m_firstScene;
protected bool m_enabled = false; // Module is only enabled if running in grid mode
#region IRegionModule Members
public void Initialise(IConfigSource source)
{
IConfig startupConfig = source.Configs["Modules"];
if (startupConfig != null)
{
m_enabled = startupConfig.GetBoolean("LLProxyLoginModule", false);
}
}
public void AddRegion(Scene scene)
{
if (m_firstScene == null)
{
m_firstScene = scene;
if (m_enabled)
{
AddHttpHandlers();
}
}
if (m_enabled)
{
AddScene(scene);
}
}
public void RemoveRegion(Scene scene)
{
if (m_enabled)
{
RemoveScene(scene);
}
}
public void PostInitialise()
{
}
public void Close()
{
}
public void RegionLoaded(Scene scene)
{
}
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "LLProxyLoginModule"; }
}
public bool IsSharedModule
{
get { return true; }
}
#endregion
/// <summary>
/// Adds "expect_user" and "logoff_user" xmlrpc method handlers
/// </summary>
protected void AddHttpHandlers()
{
//we will add our handlers to the first scene we received, as all scenes share a http server. But will this ever change?
MainServer.GetHttpServer(m_port).AddXmlRPCHandler("expect_user", ExpectUser, false);
MainServer.GetHttpServer(m_port).AddXmlRPCHandler("logoff_user", LogOffUser, false);
}
protected void AddScene(Scene scene)
{
lock (m_scenes)
{
if (!m_scenes.Contains(scene))
{
m_scenes.Add(scene);
}
}
}
protected void RemoveScene(Scene scene)
{
lock (m_scenes)
{
if (m_scenes.Contains(scene))
{
m_scenes.Remove(scene);
}
}
}
/// <summary>
/// Received from the user server when a user starts logging in. This call allows
/// the region to prepare for direct communication from the client. Sends back an empty
/// xmlrpc response on completion.
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public XmlRpcResponse ExpectUser(XmlRpcRequest request, IPEndPoint remoteClient)
{
XmlRpcResponse resp = new XmlRpcResponse();
try
{
ulong regionHandle = 0;
Hashtable requestData = (Hashtable)request.Params[0];
AgentCircuitData agentData = new AgentCircuitData();
if (requestData.ContainsKey("session_id"))
agentData.SessionID = new UUID((string)requestData["session_id"]);
if (requestData.ContainsKey("secure_session_id"))
agentData.SecureSessionID = new UUID((string)requestData["secure_session_id"]);
if (requestData.ContainsKey("firstname"))
agentData.firstname = (string)requestData["firstname"];
if (requestData.ContainsKey("lastname"))
agentData.lastname = (string)requestData["lastname"];
if (requestData.ContainsKey("agent_id"))
agentData.AgentID = new UUID((string)requestData["agent_id"]);
if (requestData.ContainsKey("circuit_code"))
agentData.circuitcode = Convert.ToUInt32(requestData["circuit_code"]);
if (requestData.ContainsKey("caps_path"))
agentData.CapsPath = (string)requestData["caps_path"];
if (requestData.ContainsKey("regionhandle"))
regionHandle = Convert.ToUInt64((string)requestData["regionhandle"]);
else
m_log.Warn("[CLIENT]: request from login server did not contain regionhandle");
// Appearance
if (requestData.ContainsKey("appearance"))
agentData.Appearance = new AvatarAppearance((Hashtable)requestData["appearance"]);
m_log.DebugFormat(
"[CLIENT]: Told by user service to prepare for a connection from {0} {1} {2}, circuit {3}",
agentData.firstname, agentData.lastname, agentData.AgentID, agentData.circuitcode);
if (requestData.ContainsKey("child_agent") && requestData["child_agent"].Equals("1"))
{
//m_log.Debug("[CLIENT]: Child agent detected");
agentData.child = true;
}
else
{
//m_log.Debug("[CLIENT]: Main agent detected");
agentData.startpos =
new Vector3((float)Convert.ToDecimal((string)requestData["startpos_x"], Culture.NumberFormatInfo),
(float)Convert.ToDecimal((string)requestData["startpos_y"], Culture.NumberFormatInfo),
(float)Convert.ToDecimal((string)requestData["startpos_z"], Culture.NumberFormatInfo));
agentData.child = false;
}
bool success = false;
string denyMess = "";
Scene scene;
if (TryGetRegion(regionHandle, out scene))
{
if (scene.RegionInfo.EstateSettings.IsBanned(agentData.AgentID))
{
denyMess = "User is banned from this region";
m_log.InfoFormat(
"[CLIENT]: Denying access for user {0} {1} because user is banned",
agentData.firstname, agentData.lastname);
}
else
{
string reason;
if (scene.NewUserConnection(agentData, (uint)TeleportFlags.ViaLogin, out reason))
{
success = true;
}
else
{
denyMess = String.Format("Login refused by region: {0}", reason);
m_log.InfoFormat(
"[CLIENT]: Denying access for user {0} {1} because user connection was refused by the region",
agentData.firstname, agentData.lastname);
}
}
}
else
{
denyMess = "Region not found";
}
if (success)
{
Hashtable respdata = new Hashtable();
respdata["success"] = "TRUE";
resp.Value = respdata;
}
else
{
Hashtable respdata = new Hashtable();
respdata["success"] = "FALSE";
respdata["reason"] = denyMess;
resp.Value = respdata;
}
}
catch (Exception e)
{
m_log.WarnFormat("[CLIENT]: Unable to receive user. Reason: {0} ({1})", e, e.StackTrace);
Hashtable respdata = new Hashtable();
respdata["success"] = "FALSE";
respdata["reason"] = "Exception occurred";
resp.Value = respdata;
}
return resp;
}
// Grid Request Processing
/// <summary>
/// Ooops, our Agent must be dead if we're getting this request!
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public XmlRpcResponse LogOffUser(XmlRpcRequest request, IPEndPoint remoteClient)
{
m_log.Debug("[CONNECTION DEBUGGING]: LogOff User Called");
Hashtable requestData = (Hashtable)request.Params[0];
string message = (string)requestData["message"];
UUID agentID = UUID.Zero;
UUID RegionSecret = UUID.Zero;
UUID.TryParse((string)requestData["agent_id"], out agentID);
UUID.TryParse((string)requestData["region_secret"], out RegionSecret);
ulong regionHandle = Convert.ToUInt64((string)requestData["regionhandle"]);
Scene scene;
if (TryGetRegion(regionHandle, out scene))
{
scene.HandleLogOffUserFromGrid(agentID, RegionSecret, message);
}
return new XmlRpcResponse();
}
protected bool TryGetRegion(ulong regionHandle, out Scene scene)
{
lock (m_scenes)
{
foreach (Scene nextScene in m_scenes)
{
if (nextScene.RegionInfo.RegionHandle == regionHandle)
{
scene = nextScene;
return true;
}
}
}
scene = null;
return false;
}
}
}

View File

@ -1,290 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using System.Text.RegularExpressions;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Capabilities;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Client.Linden
{
public class LLStandaloneLoginModule : ISharedRegionModule, ILoginServiceToRegionsConnector
{
//private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected List<Scene> m_scenes = new List<Scene>();
protected Scene m_firstScene;
protected bool m_enabled = false; // Module is only enabled if running in standalone mode
protected bool authenticate;
protected string welcomeMessage;
protected LLStandaloneLoginService m_loginService;
#region IRegionModule Members
public void Initialise(IConfigSource source)
{
IConfig startupConfig = source.Configs["Startup"];
if (startupConfig != null)
{
m_enabled = !startupConfig.GetBoolean("gridmode", false);
}
if (m_enabled)
{
authenticate = true;
welcomeMessage = "Welcome to OpenSim";
IConfig standaloneConfig = source.Configs["StandAlone"];
if (standaloneConfig != null)
{
authenticate = standaloneConfig.GetBoolean("accounts_authenticate", true);
welcomeMessage = standaloneConfig.GetString("welcome_message");
}
}
}
public void AddRegion(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
if (m_enabled)
{
RemoveScene(scene);
}
}
public void PostInitialise()
{
}
public void Close()
{
}
public void RegionLoaded(Scene scene)
{
if (m_firstScene == null)
{
m_firstScene = scene;
if (m_enabled)
{
//TODO: fix casting.
LibraryRootFolder rootFolder
= m_firstScene.CommsManager.UserProfileCacheService.LibraryRoot as LibraryRootFolder;
IHttpServer httpServer = MainServer.Instance;
//TODO: fix the casting of the user service, maybe by registering the userManagerBase with scenes, or refactoring so we just need a IUserService reference
m_loginService
= new LLStandaloneLoginService(
(UserManagerBase)m_firstScene.CommsManager.UserAdminService, welcomeMessage,
m_firstScene.InventoryService, m_firstScene.CommsManager.NetworkServersInfo, authenticate,
rootFolder, this);
httpServer.AddXmlRPCHandler("login_to_simulator", m_loginService.XmlRpcLoginMethod);
// provides the web form login
httpServer.AddHTTPHandler("login", m_loginService.ProcessHTMLLogin);
// Provides the LLSD login
httpServer.SetDefaultLLSDHandler(m_loginService.LLSDLoginMethod);
}
}
if (m_enabled)
{
AddScene(scene);
}
}
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "LLStandaloneLoginModule"; }
}
public bool IsSharedModule
{
get { return true; }
}
#endregion
protected void AddScene(Scene scene)
{
lock (m_scenes)
{
if (!m_scenes.Contains(scene))
{
m_scenes.Add(scene);
}
}
}
protected void RemoveScene(Scene scene)
{
lock (m_scenes)
{
if (m_scenes.Contains(scene))
{
m_scenes.Remove(scene);
}
}
}
public bool NewUserConnection(ulong regionHandle, AgentCircuitData agent, out string reason)
{
Scene scene;
if (TryGetRegion(regionHandle, out scene))
{
return scene.NewUserConnection(agent, (uint)TeleportFlags.ViaLogin, out reason);
}
reason = "Region not found.";
return false;
}
public void LogOffUserFromGrid(ulong regionHandle, UUID AvatarID, UUID RegionSecret, string message)
{
Scene scene;
if (TryGetRegion(regionHandle, out scene))
{
scene.HandleLogOffUserFromGrid(AvatarID, RegionSecret, message);
}
}
public RegionInfo RequestNeighbourInfo(ulong regionhandle)
{
Scene scene;
if (TryGetRegion(regionhandle, out scene))
{
return scene.RegionInfo;
}
return null;
}
public RegionInfo RequestClosestRegion(string region)
{
Scene scene;
if (TryGetRegion(region, out scene))
{
return scene.RegionInfo;
}
else if (m_scenes.Count > 0)
{
return m_scenes[0].RegionInfo;
}
return null;
}
public RegionInfo RequestNeighbourInfo(UUID regionID)
{
Scene scene;
if (TryGetRegion(regionID, out scene))
{
return scene.RegionInfo;
}
return null;
}
protected bool TryGetRegion(ulong regionHandle, out Scene scene)
{
lock (m_scenes)
{
foreach (Scene nextScene in m_scenes)
{
if (nextScene.RegionInfo.RegionHandle == regionHandle)
{
scene = nextScene;
return true;
}
}
}
scene = null;
return false;
}
protected bool TryGetRegion(UUID regionID, out Scene scene)
{
lock (m_scenes)
{
foreach (Scene nextScene in m_scenes)
{
if (nextScene.RegionInfo.RegionID == regionID)
{
scene = nextScene;
return true;
}
}
}
scene = null;
return false;
}
protected bool TryGetRegion(string regionName, out Scene scene)
{
lock (m_scenes)
{
foreach (Scene nextScene in m_scenes)
{
if (nextScene.RegionInfo.RegionName.Equals(regionName, StringComparison.InvariantCultureIgnoreCase))
{
scene = nextScene;
return true;
}
}
}
scene = null;
return false;
}
}
}

View File

@ -1,239 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using System.Text.RegularExpressions;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Communications.Services;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Capabilities;
using OpenSim.Framework.Servers;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Services.Interfaces;
namespace OpenSim.Client.Linden
{
public class LLStandaloneLoginService : LoginService
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected NetworkServersInfo m_serversInfo;
protected bool m_authUsers = false;
/// <summary>
/// Used to make requests to the local regions.
/// </summary>
protected ILoginServiceToRegionsConnector m_regionsConnector;
public LLStandaloneLoginService(
UserManagerBase userManager, string welcomeMess,
IInventoryService interServiceInventoryService,
NetworkServersInfo serversInfo,
bool authenticate, LibraryRootFolder libraryRootFolder, ILoginServiceToRegionsConnector regionsConnector)
: base(userManager, libraryRootFolder, welcomeMess)
{
this.m_serversInfo = serversInfo;
m_defaultHomeX = this.m_serversInfo.DefaultHomeLocX;
m_defaultHomeY = this.m_serversInfo.DefaultHomeLocY;
m_authUsers = authenticate;
m_InventoryService = interServiceInventoryService;
m_regionsConnector = regionsConnector;
// Standard behavior: In StandAlone, silent logout of last hung session
m_warn_already_logged = false;
}
public override UserProfileData GetTheUser(string firstname, string lastname)
{
UserProfileData profile = m_userManager.GetUserProfile(firstname, lastname);
if (profile != null)
{
return profile;
}
if (!m_authUsers)
{
//no current user account so make one
m_log.Info("[LOGIN]: No user account found so creating a new one.");
m_userManager.AddUser(firstname, lastname, "test", "", m_defaultHomeX, m_defaultHomeY);
return m_userManager.GetUserProfile(firstname, lastname);
}
return null;
}
public override bool AuthenticateUser(UserProfileData profile, string password)
{
if (!m_authUsers)
{
//for now we will accept any password in sandbox mode
m_log.Info("[LOGIN]: Authorising user (no actual password check)");
return true;
}
else
{
m_log.Info(
"[LOGIN]: Authenticating " + profile.FirstName + " " + profile.SurName);
if (!password.StartsWith("$1$"))
password = "$1$" + Util.Md5Hash(password);
password = password.Remove(0, 3); //remove $1$
string s = Util.Md5Hash(password + ":" + profile.PasswordSalt);
bool loginresult = (profile.PasswordHash.Equals(s.ToString(), StringComparison.InvariantCultureIgnoreCase)
|| profile.PasswordHash.Equals(password, StringComparison.InvariantCulture));
return loginresult;
}
}
protected override RegionInfo RequestClosestRegion(string region)
{
return m_regionsConnector.RequestClosestRegion(region);
}
protected override RegionInfo GetRegionInfo(ulong homeRegionHandle)
{
return m_regionsConnector.RequestNeighbourInfo(homeRegionHandle);
}
protected override RegionInfo GetRegionInfo(UUID homeRegionId)
{
return m_regionsConnector.RequestNeighbourInfo(homeRegionId);
}
protected override bool PrepareLoginToRegion(
RegionInfo regionInfo, UserProfileData user, LoginResponse response, IPEndPoint remoteClient)
{
IPEndPoint endPoint = regionInfo.ExternalEndPoint;
response.SimAddress = endPoint.Address.ToString();
response.SimPort = (uint)endPoint.Port;
response.RegionX = regionInfo.RegionLocX;
response.RegionY = regionInfo.RegionLocY;
string capsPath = CapsUtil.GetRandomCapsObjectPath();
string capsSeedPath = CapsUtil.GetCapsSeedPath(capsPath);
// Don't use the following! It Fails for logging into any region not on the same port as the http server!
// Kept here so it doesn't happen again!
// response.SeedCapability = regionInfo.ServerURI + capsSeedPath;
string seedcap = "http://";
if (m_serversInfo.HttpUsesSSL)
{
// For NAT
string host = NetworkUtil.GetHostFor(remoteClient.Address, m_serversInfo.HttpSSLCN);
seedcap = "https://" + host + ":" + m_serversInfo.httpSSLPort + capsSeedPath;
}
else
{
// For NAT
string host = NetworkUtil.GetHostFor(remoteClient.Address, regionInfo.ExternalHostName);
seedcap = "http://" + host + ":" + m_serversInfo.HttpListenerPort + capsSeedPath;
}
response.SeedCapability = seedcap;
// Notify the target of an incoming user
m_log.InfoFormat(
"[LOGIN]: Telling {0} @ {1},{2} ({3}) to prepare for client connection",
regionInfo.RegionName, response.RegionX, response.RegionY, regionInfo.ServerURI);
// Update agent with target sim
user.CurrentAgent.Region = regionInfo.RegionID;
user.CurrentAgent.Handle = regionInfo.RegionHandle;
AgentCircuitData agent = new AgentCircuitData();
agent.AgentID = user.ID;
agent.firstname = user.FirstName;
agent.lastname = user.SurName;
agent.SessionID = user.CurrentAgent.SessionID;
agent.SecureSessionID = user.CurrentAgent.SecureSessionID;
agent.circuitcode = Convert.ToUInt32(response.CircuitCode);
agent.BaseFolder = UUID.Zero;
agent.InventoryFolder = UUID.Zero;
agent.startpos = user.CurrentAgent.Position;
agent.CapsPath = capsPath;
agent.Appearance = m_userManager.GetUserAppearance(user.ID);
if (agent.Appearance == null)
{
m_log.WarnFormat(
"[INTER]: Appearance not found for {0} {1}. Creating default.", agent.firstname, agent.lastname);
agent.Appearance = new AvatarAppearance(agent.AgentID);
}
string reason;
bool success = m_regionsConnector.NewUserConnection(regionInfo.RegionHandle, agent, out reason);
if (!success)
{
response.ErrorReason = "key";
response.ErrorMessage = reason;
}
return success;
// return m_regionsConnector.NewUserConnection(regionInfo.RegionHandle, agent, out reason);
}
public override void LogOffUser(UserProfileData theUser, string message)
{
RegionInfo SimInfo;
try
{
SimInfo = this.m_regionsConnector.RequestNeighbourInfo(theUser.CurrentAgent.Handle);
if (SimInfo == null)
{
m_log.Error("[LOCAL LOGIN]: Region user was in isn't currently logged in");
return;
}
}
catch (Exception)
{
m_log.Error("[LOCAL LOGIN]: Unable to look up region to log user off");
return;
}
m_regionsConnector.LogOffUserFromGrid(
SimInfo.RegionHandle, theUser.ID, theUser.CurrentAgent.SecureSessionID, "Logging you off");
}
}
}

View File

@ -8,8 +8,6 @@
</Dependencies>
<Extension path = "/OpenSim/RegionModules">
<RegionModule id="LLStandaloneLoginModule" type="OpenSim.Client.Linden.LLStandaloneLoginModule" />
<RegionModule id="LLProxyLoginModule" type="OpenSim.Client.Linden.LLProxyLoginModule" />
<RegionModule id="LLClientStackModule" type="OpenSim.Client.Linden.LLClientStackModule" />
</Extension>
</Addin>

View File

@ -160,6 +160,12 @@ namespace OpenSim.Client.MXP.ClientStack
}
}
public bool IsLoggingOut
{
get { return false ; }
set { }
}
#endregion
#region Constructors
@ -427,7 +433,7 @@ namespace OpenSim.Client.MXP.ClientStack
pe.ObjectFragment.ObjectIndex = (uint)(m_scene.RegionInfo.RegionSettings.RegionUUID.GetHashCode() + ((long)int.MaxValue) / 2);
pe.ObjectFragment.ParentObjectId = UUID.Zero.Guid;
pe.ObjectFragment.ObjectName = "Terrain of " + m_scene.RegionInfo.RegionName;
pe.ObjectFragment.OwnerId = m_scene.RegionInfo.MasterAvatarAssignedUUID.Guid;
pe.ObjectFragment.OwnerId = m_scene.RegionInfo.EstateSettings.EstateOwner.Guid;
pe.ObjectFragment.TypeId = Guid.Empty;
pe.ObjectFragment.TypeName = "Terrain";
pe.ObjectFragment.Acceleration = new MsdVector3f();
@ -591,7 +597,7 @@ namespace OpenSim.Client.MXP.ClientStack
public event DeRezObject OnDeRezObject;
public event Action<IClientAPI> OnRegionHandShakeReply;
public event GenericCall2 OnRequestWearables;
public event GenericCall2 OnCompleteMovementToRegion;
public event GenericCall1 OnCompleteMovementToRegion;
public event UpdateAgent OnAgentUpdate;
public event AgentRequestSit OnAgentRequestSit;
public event AgentSit OnAgentSit;
@ -692,6 +698,8 @@ namespace OpenSim.Client.MXP.ClientStack
public event UUIDNameRequest OnTeleportHomeRequest;
public event ScriptAnswer OnScriptAnswer;
public event AgentSit OnUndo;
public event AgentSit OnRedo;
public event LandUndo OnLandUndo;
public event ForceReleaseControls OnForceReleaseControls;
public event GodLandStatRequest OnLandStatRequest;
public event DetailedEstateDataRequest OnDetailedEstateDataRequest;
@ -898,7 +906,7 @@ namespace OpenSim.Client.MXP.ClientStack
if (OnCompleteMovementToRegion != null)
{
OnCompleteMovementToRegion();
OnCompleteMovementToRegion(this);
}
// Need to translate to MXP somehow
@ -1698,5 +1706,9 @@ namespace OpenSim.Client.MXP.ClientStack
public void SendGroupActiveProposals(UUID groupID, UUID transactionID, GroupActiveProposals[] Proposals)
{
}
public void SendChangeUserRights(UUID agentID, UUID friendID, int rights)
{
}
}
}

View File

@ -41,6 +41,7 @@ using OpenSim.Client.MXP.ClientStack;
using OpenSim.Framework;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Framework.Communications;
using OpenSim.Services.Interfaces;
using System.Security.Cryptography;
namespace OpenSim.Client.MXP.PacketHandler
@ -295,13 +296,11 @@ namespace OpenSim.Client.MXP.PacketHandler
regionExists = false;
}
UserProfileData user = null;
UUID userId = UUID.Zero;
string firstName = null;
string lastName = null;
UserAccount account = null;
bool authorized = regionExists ? AuthoriseUser(joinRequestMessage.ParticipantName,
joinRequestMessage.ParticipantPassphrase,
new UUID(joinRequestMessage.BubbleId), out userId, out firstName, out lastName, out user)
new UUID(joinRequestMessage.BubbleId), out account)
: false;
if (authorized)
@ -316,10 +315,11 @@ namespace OpenSim.Client.MXP.PacketHandler
session.RemoteEndPoint.Port + ")");
m_log.Debug("[MXP ClientStack]: Attaching UserAgent to UserProfile...");
AttachUserAgentToUserProfile(session, mxpSessionID, sceneId, user);
UUID secureSession = UUID.Zero;
AttachUserAgentToUserProfile(account, session, mxpSessionID, sceneId, out secureSession);
m_log.Debug("[MXP ClientStack]: Attached UserAgent to UserProfile.");
m_log.Debug("[MXP ClientStack]: Preparing Scene to Connection...");
if (!PrepareSceneForConnection(mxpSessionID, sceneId, user, out reason))
if (!PrepareSceneForConnection(mxpSessionID, secureSession, sceneId, account, out reason))
{
m_log.DebugFormat("[MXP ClientStack]: Scene refused connection: {0}", reason);
DeclineConnection(session, joinRequestMessage);
@ -332,7 +332,7 @@ namespace OpenSim.Client.MXP.PacketHandler
m_log.Info("[MXP ClientStack]: Accepted connection.");
m_log.Debug("[MXP ClientStack]: Creating ClientView....");
MXPClientView client = new MXPClientView(session, mxpSessionID, userId, scene, firstName, lastName);
MXPClientView client = new MXPClientView(session, mxpSessionID, userId, scene, account.FirstName, account.LastName);
m_clients.Add(client);
m_log.Debug("[MXP ClientStack]: Created ClientView.");
@ -489,12 +489,12 @@ namespace OpenSim.Client.MXP.PacketHandler
session.SetStateDisconnected();
}
public bool AuthoriseUser(string participantName, string password, UUID sceneId, out UUID userId, out string firstName, out string lastName, out UserProfileData userProfile)
public bool AuthoriseUser(string participantName, string password, UUID sceneId, out UserAccount account)
{
userId = UUID.Zero;
firstName = "";
lastName = "";
userProfile = null;
UUID userId = UUID.Zero;
string firstName = "";
string lastName = "";
account = null;
string[] nameParts = participantName.Split(' ');
if (nameParts.Length != 2)
@ -505,103 +505,38 @@ namespace OpenSim.Client.MXP.PacketHandler
firstName = nameParts[0];
lastName = nameParts[1];
userProfile = m_scenes[sceneId].CommsManager.UserService.GetUserProfile(firstName, lastName);
account = m_scenes[sceneId].UserAccountService.GetUserAccount(m_scenes[sceneId].RegionInfo.ScopeID, firstName, lastName);
if (account != null)
return (m_scenes[sceneId].AuthenticationService.Authenticate(account.PrincipalID, password, 1) != string.Empty);
if (userProfile == null && !m_accountsAuthenticate)
{
userId = ((UserManagerBase)m_scenes[sceneId].CommsManager.UserService).AddUser(firstName, lastName, "test", "", 1000, 1000);
}
else
{
if (userProfile == null)
{
m_log.Error("[MXP ClientStack]: Login failed as user was not found: " + participantName);
return false;
}
userId = userProfile.ID;
}
if (m_accountsAuthenticate)
{
if (!password.StartsWith("$1$"))
{
password = "$1$" + Util.Md5Hash(password);
}
password = password.Remove(0, 3); //remove $1$
string s = Util.Md5Hash(password + ":" + userProfile.PasswordSalt);
return (userProfile.PasswordHash.Equals(s.ToString(), StringComparison.InvariantCultureIgnoreCase)
|| userProfile.PasswordHash.Equals(password, StringComparison.InvariantCulture));
}
else
{
return true;
}
return false;
}
private void AttachUserAgentToUserProfile(Session session, UUID sessionId, UUID sceneId, UserProfileData userProfile)
private void AttachUserAgentToUserProfile(UserAccount account, Session session, UUID sessionId, UUID sceneId, out UUID secureSessionId)
{
//Scene scene = m_scenes[sceneId];
CommunicationsManager commsManager = m_scenes[sceneId].CommsManager;
IUserService userService = (IUserService)commsManager.UserService;
UserAgentData agent = new UserAgentData();
// User connection
agent.AgentOnline = true;
agent.AgentIP = session.RemoteEndPoint.Address.ToString();
agent.AgentPort = (uint)session.RemoteEndPoint.Port;
agent.SecureSessionID = UUID.Random();
agent.SessionID = sessionId;
// Profile UUID
agent.ProfileID = userProfile.ID;
// Current location/position/alignment
if (userProfile.CurrentAgent != null)
{
agent.Region = userProfile.CurrentAgent.Region;
agent.Handle = userProfile.CurrentAgent.Handle;
agent.Position = userProfile.CurrentAgent.Position;
agent.LookAt = userProfile.CurrentAgent.LookAt;
}
else
{
agent.Region = userProfile.HomeRegionID;
agent.Handle = userProfile.HomeRegion;
agent.Position = userProfile.HomeLocation;
agent.LookAt = userProfile.HomeLookAt;
}
// What time did the user login?
agent.LoginTime = Util.UnixTimeSinceEpoch();
agent.LogoutTime = 0;
userProfile.CurrentAgent = agent;
userService.UpdateUserProfile(userProfile);
//userService.CommitAgent(ref userProfile);
secureSessionId = UUID.Random();
Scene scene = m_scenes[sceneId];
scene.PresenceService.LoginAgent(account.PrincipalID.ToString(), sessionId, secureSessionId);
}
private bool PrepareSceneForConnection(UUID sessionId, UUID sceneId, UserProfileData userProfile, out string reason)
private bool PrepareSceneForConnection(UUID sessionId, UUID secureSessionId, UUID sceneId, UserAccount account, out string reason)
{
Scene scene = m_scenes[sceneId];
CommunicationsManager commsManager = m_scenes[sceneId].CommsManager;
UserManagerBase userService = (UserManagerBase)commsManager.UserService;
AgentCircuitData agent = new AgentCircuitData();
agent.AgentID = userProfile.ID;
agent.firstname = userProfile.FirstName;
agent.lastname = userProfile.SurName;
agent.AgentID = account.PrincipalID;
agent.firstname = account.FirstName;
agent.lastname = account.LastName;
agent.SessionID = sessionId;
agent.SecureSessionID = userProfile.CurrentAgent.SecureSessionID;
agent.SecureSessionID = secureSessionId;
agent.circuitcode = sessionId.CRC();
agent.BaseFolder = UUID.Zero;
agent.InventoryFolder = UUID.Zero;
agent.startpos = new Vector3(0, 0, 0); // TODO Fill in region start position
agent.CapsPath = "http://localhost/";
agent.Appearance = userService.GetUserAppearance(userProfile.ID);
AvatarData avatar = scene.AvatarService.GetAvatar(account.PrincipalID);
if (avatar != null)
agent.Appearance = avatar.ToAvatarAppearance(account.PrincipalID); //userService.GetUserAppearance(userProfile.ID);
if (agent.Appearance == null)
{

View File

@ -192,6 +192,11 @@ namespace OpenSim.Client.Sirikata.ClientStack
get { return isActive; }
set { isActive = value; }
}
public bool IsLoggingOut
{
get { return false; }
set { }
}
public bool SendLogoutPacketWhenClosing
{
@ -238,7 +243,7 @@ namespace OpenSim.Client.Sirikata.ClientStack
public event DeRezObject OnDeRezObject;
public event Action<IClientAPI> OnRegionHandShakeReply;
public event GenericCall2 OnRequestWearables;
public event GenericCall2 OnCompleteMovementToRegion;
public event GenericCall1 OnCompleteMovementToRegion;
public event UpdateAgent OnAgentUpdate;
public event AgentRequestSit OnAgentRequestSit;
public event AgentSit OnAgentSit;
@ -338,6 +343,8 @@ namespace OpenSim.Client.Sirikata.ClientStack
public event UUIDNameRequest OnTeleportHomeRequest;
public event ScriptAnswer OnScriptAnswer;
public event AgentSit OnUndo;
public event AgentSit OnRedo;
public event LandUndo OnLandUndo;
public event ForceReleaseControls OnForceReleaseControls;
public event GodLandStatRequest OnLandStatRequest;
public event DetailedEstateDataRequest OnDetailedEstateDataRequest;
@ -1188,6 +1195,10 @@ namespace OpenSim.Client.Sirikata.ClientStack
{
}
public void SendChangeUserRights(UUID agentID, UUID friendID, int rights)
{
}
#endregion
}
}

View File

@ -196,7 +196,11 @@ namespace OpenSim.Client.VWoHTTP.ClientStack
get { throw new System.NotImplementedException(); }
set { throw new System.NotImplementedException(); }
}
public bool IsLoggingOut
{
get { throw new System.NotImplementedException(); }
set { throw new System.NotImplementedException(); }
}
public bool SendLogoutPacketWhenClosing
{
set { throw new System.NotImplementedException(); }
@ -242,7 +246,7 @@ namespace OpenSim.Client.VWoHTTP.ClientStack
public event DeRezObject OnDeRezObject = delegate { };
public event Action<IClientAPI> OnRegionHandShakeReply = delegate { };
public event GenericCall2 OnRequestWearables = delegate { };
public event GenericCall2 OnCompleteMovementToRegion = delegate { };
public event GenericCall1 OnCompleteMovementToRegion = delegate { };
public event UpdateAgent OnAgentUpdate = delegate { };
public event AgentRequestSit OnAgentRequestSit = delegate { };
public event AgentSit OnAgentSit = delegate { };
@ -343,6 +347,8 @@ namespace OpenSim.Client.VWoHTTP.ClientStack
public event UUIDNameRequest OnTeleportHomeRequest = delegate { };
public event ScriptAnswer OnScriptAnswer = delegate { };
public event AgentSit OnUndo = delegate { };
public event AgentSit OnRedo = delegate { };
public event LandUndo OnLandUndo = delegate { };
public event ForceReleaseControls OnForceReleaseControls = delegate { };
public event GodLandStatRequest OnLandStatRequest = delegate { };
public event DetailedEstateDataRequest OnDetailedEstateDataRequest = delegate { };
@ -1204,5 +1210,9 @@ namespace OpenSim.Client.VWoHTTP.ClientStack
public void SendGroupActiveProposals(UUID groupID, UUID transactionID, GroupActiveProposals[] Proposals)
{
}
public void SendChangeUserRights(UUID agentID, UUID friendID, int rights)
{
}
}
}

View File

@ -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
{
/// <summary>
/// A static class containing methods for obtaining handles to database
/// storage objects.
/// </summary>
public static class DataPluginFactory
{
/// <summary>
/// Based on <typeparam name="T" />, returns the appropriate
/// PluginInitialiserBase instance in <paramref name="init" /> and
/// extension point path in <paramref name="path" />.
/// </summary>
/// <param name="connect">
/// The DB connection string used when creating a new
/// PluginInitialiserBase, returned in <paramref name="init" />.
/// </param>
/// <param name="init">
/// A reference to a PluginInitialiserBase object in which the proper
/// initialiser will be returned.
/// </param>
/// <param name="path">
/// A string in which the proper extension point path will be returned.
/// </param>
/// <typeparam name="T">
/// The type of data plugin requested.
/// </typeparam>
/// <exception cref="NotImplementedException">
/// Thrown if <typeparamref name="T" /> is not one of the expected data
/// interfaces.
/// </exception>
private static void PluginLoaderParamFactory<T>(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));
}
}
/// <summary>
/// Returns a list of new <typeparamref name="T" /> data plugins.
/// Plugins will be requested in the order they were added.
/// </summary>
/// <param name="provider">
/// The filename of the inventory server plugin DLL.
/// </param>
/// <param name="connect">
/// The connection string for the storage backend.
/// </param>
/// <typeparam name="T">
/// The type of data plugin requested.
/// </typeparam>
/// <returns>
/// A list of all loaded plugins matching <typeparamref name="T" />.
/// </returns>
public static List<T> LoadDataPlugins<T>(string provider, string connect) where T : IPlugin
{
PluginInitialiserBase pluginInitialiser;
string extensionPointPath;
PluginLoaderParamFactory<T>(connect, out pluginInitialiser, out extensionPointPath);
using (PluginLoader<T> loader = new PluginLoader<T>(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;
}
}
/// <summary>
/// Returns a new <typeparamref name="T" /> data plugin instance if
/// only one was loaded, otherwise returns null (<c>default(T)</c>).
/// </summary>
/// <param name="provider">
/// The filename of the inventory server plugin DLL.
/// </param>
/// <param name="connect">
/// The connection string for the storage backend.
/// </param>
/// <typeparam name="T">
/// The type of data plugin requested.
/// </typeparam>
/// <returns>
/// A list of all loaded plugins matching <typeparamref name="T" />.
/// </returns>
public static T LoadDataPlugin<T>(string provider, string connect) where T : IPlugin
{
List<T> plugins = LoadDataPlugins<T>(provider, connect);
return (plugins.Count == 1) ? plugins[0] : default(T);
}
}
}

View File

@ -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<RegionProfileData> 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; }
}
}

View File

@ -27,15 +27,23 @@
using System;
using System.Collections.Generic;
using System.Text;
using OpenMetaverse;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Framework;
namespace OpenSim.Region.Framework.Interfaces
namespace OpenSim.Data
{
public interface ITeleportModule
// This MUST be a ref type!
public class AvatarBaseData
{
void RequestTeleportToLocation(ScenePresence avatar, ulong regionHandle, Vector3 position,
Vector3 lookAt, uint teleportFlags);
public UUID PrincipalID;
public Dictionary<string, string> Data;
}
public interface IAvatarData
{
AvatarBaseData[] Get(string field, string val);
bool Store(AvatarBaseData data);
bool Delete(UUID principalID, string name);
bool Delete(string field, string val);
}
}

View File

@ -26,23 +26,26 @@
*/
using System;
using System.Collections.Generic;
using OpenMetaverse;
using OpenSim.Framework;
namespace OpenSim.Data
{
public class ReservationData
public class FriendsData
{
public UUID userUUID = UUID.Zero;
public int reservationMinX = 0;
public int reservationMinY = 0;
public int reservationMaxX = 65536;
public int reservationMaxY = 65536;
public UUID PrincipalID;
public string Friend;
public Dictionary<string, string> Data;
}
public string reservationName = String.Empty;
public string reservationCompany = String.Empty;
public bool status = true;
public string gridSendKey = String.Empty;
public string gridRecvKey = String.Empty;
/// <summary>
/// An interface for connecting to the friends datastore
/// </summary>
public interface IFriendsData
{
bool Store(FriendsData data);
bool Delete(UUID ownerID, string friend);
FriendsData[] GetFriends(UUID principalID);
}
}

View File

@ -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
}
/// <summary>
/// A standard grid interface
/// </summary>
public interface IGridDataPlugin : IPlugin
{
/// <summary>
/// Initialises the interface
/// </summary>
void Initialise(string connect);
/// <summary>
/// Returns a sim profile from a regionHandle
/// </summary>
/// <param name="regionHandle">A 64bit Region Handle</param>
/// <returns>A simprofile</returns>
RegionProfileData GetProfileByHandle(ulong regionHandle);
/// <summary>
/// Returns a sim profile from a UUID
/// </summary>
/// <param name="UUID">A 128bit UUID</param>
/// <returns>A sim profile</returns>
RegionProfileData GetProfileByUUID(UUID UUID);
/// <summary>
/// Returns a sim profile from a string match
/// </summary>
/// <param name="regionName">A string for a partial region name match</param>
/// <returns>A sim profile</returns>
RegionProfileData GetProfileByString(string regionName);
/// <summary>
/// Returns all profiles within the specified range
/// </summary>
/// <param name="Xmin">Minimum sim coordinate (X)</param>
/// <param name="Ymin">Minimum sim coordinate (Y)</param>
/// <param name="Xmax">Maximum sim coordinate (X)</param>
/// <param name="Ymin">Maximum sim coordinate (Y)</param>
/// <returns>An array containing all the sim profiles in the specified range</returns>
RegionProfileData[] GetProfilesInRange(uint Xmin, uint Ymin, uint Xmax, uint Ymax);
/// <summary>
/// Returns up to maxNum profiles of regions that have a name starting with namePrefix
/// </summary>
/// <param name="name">The name to match against</param>
/// <param name="maxNum">Maximum number of profiles to return</param>
/// <returns>A list of sim profiles</returns>
List<RegionProfileData> GetRegionsByName(string namePrefix, uint maxNum);
/// <summary>
/// Authenticates a sim by use of its recv key.
/// WARNING: Insecure
/// </summary>
/// <param name="UUID">The UUID sent by the sim</param>
/// <param name="regionHandle">The regionhandle sent by the sim</param>
/// <param name="simrecvkey">The receiving key sent by the sim</param>
/// <returns>Whether the sim has been authenticated</returns>
bool AuthenticateSim(UUID UUID, ulong regionHandle, string simrecvkey);
/// <summary>
/// Adds or updates a profile in the database
/// </summary>
/// <param name="profile">The profile to add</param>
/// <returns>RESPONSE_OK if successful, error if not.</returns>
DataResponse StoreProfile(RegionProfileData profile);
/// <summary>
/// Remove a profile from the database
/// </summary>
/// <param name="UUID">ID of profile to remove</param>
/// <returns></returns>
DataResponse DeleteProfile(string UUID);
/// <summary>
/// Function not used????
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
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);
}
}
}

View File

@ -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
{
/// <summary>
/// The severity of an individual log message
/// </summary>
public enum LogSeverity : int
{
/// <summary>
/// Critical: systems failure
/// </summary>
CRITICAL = 1,
/// <summary>
/// Major: warning prior to systems failure
/// </summary>
MAJOR = 2,
/// <summary>
/// Medium: an individual non-critical task failed
/// </summary>
MEDIUM = 3,
/// <summary>
/// Low: Informational warning
/// </summary>
LOW = 4,
/// <summary>
/// Info: Information
/// </summary>
INFO = 5,
/// <summary>
/// Verbose: Debug Information
/// </summary>
VERBOSE = 6
}
/// <summary>
/// An interface to a LogData storage system
/// </summary>
public interface ILogDataPlugin : IPlugin
{
void saveLog(string serverDaemon, string target, string methodCall, string arguments, int priority,
string logMessage);
/// <summary>
/// Initialises the interface
/// </summary>
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);
}
}
}

View File

@ -32,25 +32,28 @@ using OpenSim.Framework;
namespace OpenSim.Data
{
public struct PresenceData
// This MUST be a ref type!
public class PresenceData
{
public UUID UUID;
public UUID currentRegion;
public string UserID;
public UUID RegionID;
public UUID SessionID;
public Dictionary<string, string> Data;
}
/// <summary>
/// An interface for connecting to the authentication datastore
/// An interface for connecting to the presence datastore
/// </summary>
public interface IPresenceData
{
bool Store(PresenceData data);
PresenceData Get(UUID principalID);
bool SetUserDataItem(UUID principalID, string item, string value);
bool SetRegionDataItem(UUID principalID, string item, string value);
bool Delete(UUID regionID);
PresenceData Get(UUID sessionID);
void LogoutRegionAgents(UUID regionID);
bool ReportAgent(UUID sessionID, UUID regionID, string position, string lookAt);
bool SetHomeLocation(string userID, UUID regionID, Vector3 position, Vector3 lookAt);
PresenceData[] Get(string field, string data);
void Prune(string userID);
bool Delete(string field, string val);
}
}

View File

@ -60,5 +60,22 @@ namespace OpenSim.Data
bool Delete(UUID regionID);
List<RegionData> GetDefaultRegions(UUID scopeID);
List<RegionData> GetFallbackRegions(UUID scopeID, int x, int y);
}
[Flags]
public enum RegionFlags : int
{
DefaultRegion = 1, // Used for new Rez. Random if multiple defined
FallbackRegion = 2, // Regions we redirect to when the destination is down
RegionOnline = 4, // Set when a region comes online, unset when it unregisters and DeleteOnUnregister is false
NoDirectLogin = 8, // Region unavailable for direct logins (by name)
Persistent = 16, // Don't remove on unregister
LockedOut = 32, // Don't allow registration
NoMove = 64, // Don't allow moving this region
Reservation = 128, // This is an inactive reservation
Authenticate = 256, // Require authentication
Hyperlink = 512 // Record represents a HG link
}
}

View File

@ -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
{
/// <summary>
/// Returns a region by argument
/// </summary>
/// <param name="uuid">A UUID key of the region to return</param>
/// <returns>A SimProfileData for the region</returns>
RegionProfileData GetRegion(UUID uuid);
/// <summary>
/// Returns a region by argument
/// </summary>
/// <param name="uuid">A regionHandle of the region to return</param>
/// <returns>A SimProfileData for the region</returns>
RegionProfileData GetRegion(ulong handle);
/// <summary>
/// Returns a region by argument
/// </summary>
/// <param name="regionName">A partial regionName of the region to return</param>
/// <returns>A SimProfileData for the region</returns>
RegionProfileData GetRegion(string regionName);
List<RegionProfileData> GetRegions(uint xmin, uint ymin, uint xmax, uint ymax);
List<RegionProfileData> GetRegions(string name, int maxNum);
DataResponse AddUpdateRegion(RegionProfileData sim, RegionProfileData existingSim);
DataResponse DeleteRegion(string uuid);
}
public interface IRegionProfileRouter
{
/// <summary>
/// Request sim profile information from a grid server, by Region UUID
/// </summary>
/// <param name="regionId">The region UUID to look for</param>
/// <param name="gridserverUrl"></param>
/// <param name="gridserverSendkey"></param>
/// <param name="gridserverRecvkey"></param>
/// <returns>The sim profile. Null if there was a request failure</returns>
/// <remarks>This method should be statics</remarks>
RegionProfileData RequestSimProfileData(UUID regionId, Uri gridserverUrl,
string gridserverSendkey, string gridserverRecvkey);
/// <summary>
/// Request sim profile information from a grid server, by Region Handle
/// </summary>
/// <param name="regionHandle">the region handle to look for</param>
/// <param name="gridserverUrl"></param>
/// <param name="gridserverSendkey"></param>
/// <param name="gridserverRecvkey"></param>
/// <returns>The sim profile. Null if there was a request failure</returns>
RegionProfileData RequestSimProfileData(ulong regionHandle, Uri gridserverUrl,
string gridserverSendkey, string gridserverRecvkey);
/// <summary>
/// Request sim profile information from a grid server, by Region Name
/// </summary>
/// <param name="regionName">the region name to look for</param>
/// <param name="gridserverUrl"></param>
/// <param name="gridserverSendkey"></param>
/// <param name="gridserverRecvkey"></param>
/// <returns>The sim profile. Null if there was a request failure</returns>
RegionProfileData RequestSimProfileData(string regionName, Uri gridserverUrl,
string gridserverSendkey, string gridserverRecvkey);
}
}

View File

@ -36,20 +36,18 @@ namespace OpenSim.Data
{
public UUID PrincipalID;
public UUID ScopeID;
public Dictionary<string, object> Data;
public string FirstName;
public string LastName;
public Dictionary<string, string> Data;
}
/// <summary>
/// An interface for connecting to the authentication datastore
/// An interface for connecting to the user accounts datastore
/// </summary>
public interface IUserAccountData
{
UserAccountData Get(UUID principalID, UUID ScopeID);
List<UserAccountData> Query(UUID principalID, UUID ScopeID, string query);
UserAccountData[] Get(string[] fields, string[] values);
bool Store(UserAccountData data);
bool SetDataItem(UUID principalID, string item, string value);
UserAccountData[] GetUsers(UUID scopeID, string query);
}
}

View File

@ -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
{
/// <summary>
/// An interface for connecting to user storage servers.
/// </summary>
public interface IUserDataPlugin : IPlugin
{
/// <summary>
/// Returns a user profile from a database via their UUID
/// </summary>
/// <param name="user">The user's UUID</param>
/// <returns>The user data profile. Returns null if no user is found</returns>
UserProfileData GetUserByUUID(UUID user);
/// <summary>
/// Returns a users profile by searching their username parts
/// </summary>
/// <param name="fname">Account firstname</param>
/// <param name="lname">Account lastname</param>
/// <returns>The user data profile. Null if no user is found</returns>
UserProfileData GetUserByName(string fname, string lname);
/// <summary>
/// Get a user from a given uri.
/// </summary>
/// <param name="uri"></param>
/// <returns>The user data profile. Null if no user is found.</returns>
UserProfileData GetUserByUri(Uri uri);
/// <summary>
/// Returns a list of UUIDs firstnames and lastnames that match string query entered into the avatar picker.
/// </summary>
/// <param name="queryID">ID associated with the user's query. This must match what the client sent</param>
/// <param name="query">The filtered contents of the search box when the user hit search.</param>
/// <returns>A list of user details. If there are no results than either an empty list or null</returns>
List<AvatarPickerAvatar> GeneratePickerResults(UUID queryID, string query);
/// <summary>
/// Returns the current agent for a user searching by it's UUID
/// </summary>
/// <param name="user">The users UUID</param>
/// <returns>The current agent session. Null if no session was found</returns>
UserAgentData GetAgentByUUID(UUID user);
/// <summary>
/// Returns the current session agent for a user searching by username
/// </summary>
/// <param name="name">The users account name</param>
/// <returns>The current agent session</returns>
UserAgentData GetAgentByName(string name);
/// <summary>
/// Returns the current session agent for a user searching by username parts
/// </summary>
/// <param name="fname">The users first account name</param>
/// <param name="lname">The users account surname</param>
/// <returns>The current agent session</returns>
UserAgentData GetAgentByName(string fname, string lname);
/// <summary>
/// Stores new web-login key for user during web page login
/// </summary>
/// <param name="webLoginKey"></param>
void StoreWebLoginKey(UUID agentID, UUID webLoginKey);
/// <summary>
/// Adds a new User profile to the database
/// </summary>
/// <param name="user">UserProfile to add</param>
void AddNewUserProfile(UserProfileData user);
/// <summary>
/// Adds a temporary user profile. A temporary userprofile is one that should exist only for the lifetime of
/// the process.
/// </summary>
/// <param name="userProfile"></param>
void AddTemporaryUserProfile(UserProfileData userProfile);
/// <summary>
/// Updates an existing user profile
/// </summary>
/// <param name="user">UserProfile to update</param>
bool UpdateUserProfile(UserProfileData user);
/// <summary>
/// Adds a new agent to the database
/// </summary>
/// <param name="agent">The agent to add</param>
void AddNewUserAgent(UserAgentData agent);
/// <summary>
/// Adds a new friend to the database for XUser
/// </summary>
/// <param name="friendlistowner">The agent that who's friends list is being added to</param>
/// <param name="friend">The agent that being added to the friends list of the friends list owner</param>
/// <param name="perms">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 </param>
void AddNewUserFriend(UUID friendlistowner, UUID friend, uint perms);
/// <summary>
/// Delete friend on friendlistowner's friendlist.
/// </summary>
/// <param name="friendlistowner">The agent that who's friends list is being updated</param>
/// <param name="friend">The Ex-friend agent</param>
void RemoveUserFriend(UUID friendlistowner, UUID friend);
/// <summary>
/// Update permissions for friend on friendlistowner's friendlist.
/// </summary>
/// <param name="friendlistowner">The agent that who's friends list is being updated</param>
/// <param name="friend">The agent that is getting or loosing permissions</param>
/// <param name="perms">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 </param>
void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms);
/// <summary>
/// Returns a list of FriendsListItems that describe the friends and permissions in the friend relationship for UUID friendslistowner
/// </summary>
/// <param name="friendlistowner">The agent that we're retreiving the friends Data.</param>
/// <returns>The user's friends. If there are no results than either an empty list or null</returns>
List<FriendListItem> GetUserFriendList(UUID friendlistowner);
/// <summary>
/// Returns a list of <see cref="FriendRegionInfo/>s for the specified UUIDs.
/// </summary>
/// <param name="uuids">
/// A <see cref="List"/> of <see cref="UUID/>s to fetch info for
/// </param>
/// <returns>
/// A <see cref="Dictionary"/>, mapping the <see cref="UUID"/>s to <see cref="FriendRegionInfo"/>s.
/// </returns>
Dictionary<UUID, FriendRegionInfo> GetFriendRegionInfos(List<UUID> uuids);
/// <summary>
/// Attempts to move currency units between accounts (NOT RELIABLE / TRUSTWORTHY. DONT TRY RUN YOUR OWN CURRENCY EXCHANGE WITH REAL VALUES)
/// </summary>
/// <param name="from">The account to transfer from</param>
/// <param name="to">The account to transfer to</param>
/// <param name="amount">The amount to transfer</param>
/// <returns>Successful?</returns>
bool MoneyTransferRequest(UUID from, UUID to, uint amount);
/// <summary>
/// Attempts to move inventory between accounts, if inventory is copyable it will be copied into the target account.
/// </summary>
/// <param name="from">User to transfer from</param>
/// <param name="to">User to transfer to</param>
/// <param name="inventory">Specified inventory item</param>
/// <returns>Successful?</returns>
bool InventoryTransferRequest(UUID from, UUID to, UUID inventory);
/// <summary>
/// Initialises the plugin (artificial constructor)
/// </summary>
void Initialise(string connect);
/// <summary>
/// Gets the user appearance
/// </summer>
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);
}
}
}

View File

@ -58,7 +58,7 @@ namespace OpenSim.Data
public int saleType;
public int creationDate;
public UUID groupID;
public bool groupOwned;
public int groupOwned;
public int flags;
public UUID inventoryID;
public UUID avatarID;

View File

@ -1,219 +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.Data;
using System.Data.SqlClient;
namespace OpenSim.Data.MSSQL
{
/// <summary>
/// Encapsulates a SqlCommand object but ensures that when it is disposed, its connection is closed and disposed also.
/// </summary>
internal class AutoClosingSqlCommand : IDbCommand
{
private SqlCommand realCommand;
public AutoClosingSqlCommand(SqlCommand cmd)
{
realCommand = cmd;
}
#region IDbCommand Members
public void Cancel()
{
realCommand.Cancel();
}
public string CommandText
{
get
{
return realCommand.CommandText;
}
set
{
realCommand.CommandText = value;
}
}
public int CommandTimeout
{
get
{
return realCommand.CommandTimeout;
}
set
{
realCommand.CommandTimeout = value;
}
}
public CommandType CommandType
{
get
{
return realCommand.CommandType;
}
set
{
realCommand.CommandType = value;
}
}
IDbConnection IDbCommand.Connection
{
get
{
return realCommand.Connection;
}
set
{
realCommand.Connection = (SqlConnection) value;
}
}
public SqlConnection Connection
{
get
{
return realCommand.Connection;
}
}
IDbDataParameter IDbCommand.CreateParameter()
{
return realCommand.CreateParameter();
}
public SqlParameter CreateParameter()
{
return realCommand.CreateParameter();
}
public int ExecuteNonQuery()
{
return realCommand.ExecuteNonQuery();
}
IDataReader IDbCommand.ExecuteReader(CommandBehavior behavior)
{
return realCommand.ExecuteReader(behavior);
}
public SqlDataReader ExecuteReader(CommandBehavior behavior)
{
return realCommand.ExecuteReader(behavior);
}
IDataReader IDbCommand.ExecuteReader()
{
return realCommand.ExecuteReader();
}
public SqlDataReader ExecuteReader()
{
return realCommand.ExecuteReader();
}
public object ExecuteScalar()
{
return realCommand.ExecuteScalar();
}
IDataParameterCollection IDbCommand.Parameters
{
get { return realCommand.Parameters; }
}
public SqlParameterCollection Parameters
{
get { return realCommand.Parameters; }
}
public void Prepare()
{
realCommand.Prepare();
}
// IDbTransaction IDbCommand.Transaction
// {
// get
// {
// return realCommand.Transaction;
// }
// set
// {
// realCommand.Transaction = (SqlTransaction) value;
// }
// }
public IDbTransaction Transaction
{
get { return realCommand.Transaction; }
set { realCommand.Transaction = (SqlTransaction)value; }
}
UpdateRowSource IDbCommand.UpdatedRowSource
{
get
{
return realCommand.UpdatedRowSource;
}
set
{
realCommand.UpdatedRowSource = value;
}
}
#endregion
#region IDisposable Members
public void Dispose()
{
SqlConnection conn = realCommand.Connection;
try
{
realCommand.Dispose();
}
finally
{
try
{
conn.Close();
}
finally
{
conn.Dispose();
}
}
}
#endregion
}
}

View File

@ -49,6 +49,7 @@ namespace OpenSim.Data.MSSQL
/// Database manager
/// </summary>
private MSSQLManager m_database;
private string m_connectionString;
#region IPlugin Members
@ -75,23 +76,8 @@ namespace OpenSim.Data.MSSQL
{
m_ticksToEpoch = new System.DateTime(1970, 1, 1).Ticks;
if (!string.IsNullOrEmpty(connectionString))
{
m_database = new MSSQLManager(connectionString);
}
else
{
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");
m_database =
new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId,
settingPassword);
}
m_database = new MSSQLManager(connectionString);
m_connectionString = connectionString;
//New migration to check for DB changes
m_database.CheckMigration(_migrationStore);
@ -125,17 +111,20 @@ namespace OpenSim.Data.MSSQL
override public AssetBase GetAsset(UUID assetID)
{
string sql = "SELECT * FROM assets WHERE id = @id";
using (AutoClosingSqlCommand command = m_database.Query(sql))
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
command.Parameters.Add(m_database.CreateParameter("id", assetID));
using (SqlDataReader reader = command.ExecuteReader())
cmd.Parameters.Add(m_database.CreateParameter("id", assetID));
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
AssetBase asset = new AssetBase(
new UUID((Guid)reader["id"]),
(string)reader["name"],
Convert.ToSByte(reader["assetType"])
Convert.ToSByte(reader["assetType"]),
String.Empty
);
// Region Main
asset.Description = (string)reader["description"];
@ -190,7 +179,8 @@ namespace OpenSim.Data.MSSQL
m_log.Warn("[ASSET DB]: Description field truncated from " + asset.Description.Length + " to " + assetDescription.Length + " characters on add");
}
using (AutoClosingSqlCommand command = m_database.Query(sql))
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand command = new SqlCommand(sql, conn))
{
int now = (int)((System.DateTime.Now.Ticks - m_ticksToEpoch) / 10000000);
command.Parameters.Add(m_database.CreateParameter("id", asset.FullID));
@ -202,7 +192,7 @@ namespace OpenSim.Data.MSSQL
command.Parameters.Add(m_database.CreateParameter("access_time", now));
command.Parameters.Add(m_database.CreateParameter("create_time", now));
command.Parameters.Add(m_database.CreateParameter("data", asset.Data));
conn.Open();
try
{
command.ExecuteNonQuery();
@ -238,7 +228,8 @@ namespace OpenSim.Data.MSSQL
m_log.Warn("[ASSET DB]: Description field truncated from " + asset.Description.Length + " to " + assetDescription.Length + " characters on update");
}
using (AutoClosingSqlCommand command = m_database.Query(sql))
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand command = new SqlCommand(sql, conn))
{
command.Parameters.Add(m_database.CreateParameter("id", asset.FullID));
command.Parameters.Add(m_database.CreateParameter("name", assetName));
@ -248,7 +239,7 @@ namespace OpenSim.Data.MSSQL
command.Parameters.Add(m_database.CreateParameter("temporary", asset.Temporary));
command.Parameters.Add(m_database.CreateParameter("data", asset.Data));
command.Parameters.Add(m_database.CreateParameter("@keyId", asset.FullID));
conn.Open();
try
{
command.ExecuteNonQuery();
@ -307,13 +298,14 @@ namespace OpenSim.Data.MSSQL
string sql = @"SELECT (name,description,assetType,temporary,id), Row = ROW_NUMBER()
OVER (ORDER BY (some column to order by))
WHERE Row >= @Start AND Row < @Start + @Count";
using (AutoClosingSqlCommand command = m_database.Query(sql))
{
command.Parameters.Add(m_database.CreateParameter("start", start));
command.Parameters.Add(m_database.CreateParameter("count", count));
using (SqlDataReader reader = command.ExecuteReader())
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("start", start));
cmd.Parameters.Add(m_database.CreateParameter("count", count));
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{

View File

@ -53,6 +53,7 @@ namespace OpenSim.Data.MSSQL
{
conn.Open();
Migration m = new Migration(conn, GetType().Assembly, "AuthStore");
m_database = new MSSQLManager(m_ConnectionString);
m.Update();
}
}
@ -168,13 +169,14 @@ namespace OpenSim.Data.MSSQL
{
if (System.Environment.TickCount - m_LastExpire > 30000)
DoExpire();
string sql = "insert into tokens (UUID, token, validity) values (@principalID, @token, date_add(now(), interval @lifetime minute))";
string sql = "insert into tokens (UUID, token, validity) values (@principalID, @token, @lifetime)";
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("@principalID", principalID));
cmd.Parameters.Add(m_database.CreateParameter("@token", token));
cmd.Parameters.Add(m_database.CreateParameter("@lifetime", lifetime));
cmd.Parameters.Add(m_database.CreateParameter("@lifetime", DateTime.Now.AddMinutes(lifetime)));
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
@ -189,13 +191,15 @@ namespace OpenSim.Data.MSSQL
{
if (System.Environment.TickCount - m_LastExpire > 30000)
DoExpire();
string sql = "update tokens set validity = date_add(now(), interval @lifetime minute) where UUID = @principalID and token = @token and validity > now()";
DateTime validDate = DateTime.Now.AddMinutes(lifetime);
string sql = "update tokens set validity = @validDate where UUID = @principalID and token = @token and validity > GetDate()";
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("@principalID", principalID));
cmd.Parameters.Add(m_database.CreateParameter("@token", token));
cmd.Parameters.Add(m_database.CreateParameter("@lifetime", lifetime));
cmd.Parameters.Add(m_database.CreateParameter("@validDate", validDate));
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
@ -208,11 +212,13 @@ namespace OpenSim.Data.MSSQL
private void DoExpire()
{
string sql = "delete from tokens where validity < now()";
DateTime currentDateTime = DateTime.Now;
string sql = "delete from tokens where validity < @currentDateTime";
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
conn.Open();
cmd.Parameters.Add(m_database.CreateParameter("@currentDateTime", currentDateTime));
cmd.ExecuteNonQuery();
}
m_LastExpire = System.Environment.TickCount;

View File

@ -27,34 +27,45 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Xml;
using System.Threading;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Console;
using OpenSim.Region.Framework;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Hypergrid;
using System.Data.SqlClient;
namespace OpenSim
namespace OpenSim.Data.MSSQL
{
public class HGCommands
/// <summary>
/// A MSSQL Interface for Avatar Storage
/// </summary>
public class MSSQLAvatarData : MSSQLGenericTableHandler<AvatarBaseData>,
IAvatarData
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public static Scene CreateScene(RegionInfo regionInfo, AgentCircuitManager circuitManager, CommunicationsManager m_commsManager,
StorageManager storageManager, ModuleLoader m_moduleLoader, ConfigSettings m_configSettings, OpenSimConfigSource m_config, string m_version)
{
HGSceneCommunicationService sceneGridService = new HGSceneCommunicationService(m_commsManager);
return
new HGScene(
regionInfo, circuitManager, m_commsManager, sceneGridService, storageManager,
m_moduleLoader, false, m_configSettings.PhysicalPrim,
m_configSettings.See_into_region_from_neighbor, m_config.Source, m_version);
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public MSSQLAvatarData(string connectionString, string realm) :
base(connectionString, realm, "Avatar")
{
}
public bool Delete(UUID principalID, string name)
{
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = String.Format("DELETE FROM {0} where [PrincipalID] = @PrincipalID and [Name] = @Name", m_Realm);
cmd.Parameters.Add(m_database.CreateParameter("@PrincipalID", principalID.ToString()));
cmd.Parameters.Add(m_database.CreateParameter("@Name", name));
cmd.Connection = conn;
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
return true;
return false;
}
}
}
}

View File

@ -44,7 +44,7 @@ namespace OpenSim.Data.MSSQL
private static readonly ILog _Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private MSSQLManager _Database;
private string m_connectionString;
private FieldInfo[] _Fields;
private Dictionary<string, FieldInfo> _FieldMap = new Dictionary<string, FieldInfo>();
@ -58,22 +58,9 @@ namespace OpenSim.Data.MSSQL
{
if (!string.IsNullOrEmpty(connectionString))
{
m_connectionString = connectionString;
_Database = new MSSQLManager(connectionString);
}
else
{
//TODO when can this be deleted
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);
}
//Migration settings
_Database.CheckMigration(_migrationStore);
@ -103,11 +90,11 @@ namespace OpenSim.Data.MSSQL
string sql = "select estate_settings." + String.Join(",estate_settings.", FieldList) + " from estate_map left join estate_settings on estate_map.EstateID = estate_settings.EstateID where estate_settings.EstateID is not null and RegionID = @RegionID";
bool insertEstate = false;
using (AutoClosingSqlCommand cmd = _Database.Query(sql))
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(_Database.CreateParameter("@RegionID", regionID));
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
@ -124,7 +111,7 @@ namespace OpenSim.Data.MSSQL
}
else if (_FieldMap[name].GetValue(es) is UUID)
{
_FieldMap[name].SetValue(es, new UUID((Guid) reader[name])); // uuid);
_FieldMap[name].SetValue(es, new UUID((Guid)reader[name])); // uuid);
}
else
{
@ -149,34 +136,36 @@ namespace OpenSim.Data.MSSQL
sql = string.Format("insert into estate_settings ({0}) values ( @{1})", String.Join(",", names.ToArray()), String.Join(", @", names.ToArray()));
//_Log.Debug("[DB ESTATE]: SQL: " + sql);
using (SqlConnection connection = _Database.DatabaseConnection())
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand insertCommand = new SqlCommand(sql, conn))
{
using (SqlCommand insertCommand = connection.CreateCommand())
insertCommand.CommandText = sql + " SET @ID = SCOPE_IDENTITY()";
foreach (string name in names)
{
insertCommand.CommandText = sql + " SET @ID = SCOPE_IDENTITY()";
foreach (string name in names)
{
insertCommand.Parameters.Add(_Database.CreateParameter("@" + name, _FieldMap[name].GetValue(es)));
}
SqlParameter idParameter = new SqlParameter("@ID", SqlDbType.Int);
idParameter.Direction = ParameterDirection.Output;
insertCommand.Parameters.Add(idParameter);
insertCommand.ExecuteNonQuery();
es.EstateID = Convert.ToUInt32(idParameter.Value);
insertCommand.Parameters.Add(_Database.CreateParameter("@" + name, _FieldMap[name].GetValue(es)));
}
SqlParameter idParameter = new SqlParameter("@ID", SqlDbType.Int);
idParameter.Direction = ParameterDirection.Output;
insertCommand.Parameters.Add(idParameter);
conn.Open();
insertCommand.ExecuteNonQuery();
es.EstateID = Convert.ToUInt32(idParameter.Value);
}
using (AutoClosingSqlCommand cmd = _Database.Query("INSERT INTO [estate_map] ([RegionID] ,[EstateID]) VALUES (@RegionID, @EstateID)"))
sql = "INSERT INTO [estate_map] ([RegionID] ,[EstateID]) VALUES (@RegionID, @EstateID)";
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(_Database.CreateParameter("@RegionID", regionID));
cmd.Parameters.Add(_Database.CreateParameter("@EstateID", es.EstateID));
// This will throw on dupe key
try
{
cmd.ExecuteNonQuery();
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
@ -187,12 +176,14 @@ namespace OpenSim.Data.MSSQL
// Munge and transfer the ban list
sql = string.Format("insert into estateban select {0}, bannedUUID, bannedIp, bannedIpHostMask, '' from regionban where regionban.regionUUID = @UUID", es.EstateID);
using (AutoClosingSqlCommand cmd = _Database.Query(sql))
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(_Database.CreateParameter("@UUID", regionID));
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception)
@ -226,7 +217,7 @@ namespace OpenSim.Data.MSSQL
names.Remove("EstateID");
string sql = string.Format("UPDATE estate_settings SET ") ;
string sql = string.Format("UPDATE estate_settings SET ");
foreach (string name in names)
{
sql += name + " = @" + name + ", ";
@ -234,7 +225,8 @@ namespace OpenSim.Data.MSSQL
sql = sql.Remove(sql.LastIndexOf(","));
sql += " WHERE EstateID = @EstateID";
using (AutoClosingSqlCommand cmd = _Database.Query(sql))
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
foreach (string name in names)
{
@ -242,6 +234,7 @@ namespace OpenSim.Data.MSSQL
}
cmd.Parameters.Add(_Database.CreateParameter("@EstateID", es.EstateID));
conn.Open();
cmd.ExecuteNonQuery();
}
@ -266,12 +259,13 @@ namespace OpenSim.Data.MSSQL
string sql = "select bannedUUID from estateban where EstateID = @EstateID";
using (AutoClosingSqlCommand cmd = _Database.Query(sql))
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
SqlParameter idParameter = new SqlParameter("@EstateID", SqlDbType.Int);
idParameter.Value = es.EstateID;
cmd.Parameters.Add(idParameter);
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
@ -293,10 +287,11 @@ namespace OpenSim.Data.MSSQL
string sql = string.Format("select uuid from {0} where EstateID = @EstateID", table);
using (AutoClosingSqlCommand cmd = _Database.Query(sql))
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(_Database.CreateParameter("@EstateID", estateID));
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
@ -313,20 +308,24 @@ namespace OpenSim.Data.MSSQL
{
//Delete first
string sql = "delete from estateban where EstateID = @EstateID";
using (AutoClosingSqlCommand cmd = _Database.Query(sql))
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(_Database.CreateParameter("@EstateID", es.EstateID));
conn.Open();
cmd.ExecuteNonQuery();
}
//Insert after
sql = "insert into estateban (EstateID, bannedUUID) values ( @EstateID, @bannedUUID )";
using (AutoClosingSqlCommand cmd = _Database.Query(sql))
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
foreach (EstateBan b in es.EstateBans)
{
cmd.Parameters.Add(_Database.CreateParameter("@EstateID", es.EstateID));
cmd.Parameters.Add(_Database.CreateParameter("@bannedUUID", b.BannedUserID));
conn.Open();
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
@ -337,14 +336,16 @@ namespace OpenSim.Data.MSSQL
{
//Delete first
string sql = string.Format("delete from {0} where EstateID = @EstateID", table);
using (AutoClosingSqlCommand cmd = _Database.Query(sql))
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(_Database.CreateParameter("@EstateID", estateID));
cmd.ExecuteNonQuery();
}
sql = string.Format("insert into {0} (EstateID, uuid) values ( @EstateID, @uuid )", table);
using (AutoClosingSqlCommand cmd = _Database.Query(sql))
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(_Database.CreateParameter("@EstateID", estateID));
@ -359,7 +360,7 @@ namespace OpenSim.Data.MSSQL
}
else
cmd.Parameters["@uuid"].Value = uuid.Guid; //.ToString(); //TODO check if this works
conn.Open();
cmd.ExecuteNonQuery();
}
}

View File

@ -0,0 +1,83 @@
/*
* 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 OpenMetaverse;
using OpenSim.Framework;
using System.Data.SqlClient;
using System.Reflection;
using System.Text;
namespace OpenSim.Data.MSSQL
{
public class MSSQLFriendsData : MSSQLGenericTableHandler<FriendsData>, IFriendsData
{
public MSSQLFriendsData(string connectionString, string realm)
: base(connectionString, realm, "FriendsStore")
{
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
{
conn.Open();
Migration m = new Migration(conn, GetType().Assembly, "FriendsStore");
m.Update();
}
}
public bool Delete(UUID principalID, string friend)
{
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = String.Format("delete from {0} where PrincipalID = @PrincipalID and Friend = @Friend", m_Realm);
cmd.Parameters.Add(m_database.CreateParameter("@PrincipalID", principalID.ToString()));
cmd.Parameters.Add(m_database.CreateParameter("@Friend", friend));
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
return true;
}
}
public FriendsData[] GetFriends(UUID principalID)
{
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = String.Format("select a.*,b.Flags as TheirFlags from {0} as a left join {0} as b on a.PrincipalID = b.Friend and a.Friend = b.PrincipalID where a.PrincipalID = ?PrincipalID and b.Flags is not null", m_Realm);
cmd.Parameters.Add(m_database.CreateParameter("@PrincipalID", principalID.ToString()));
cmd.Connection = conn;
conn.Open();
return DoQuery(cmd);
}
}
}
}

View File

@ -0,0 +1,359 @@
/*
* 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 System.Data.SqlClient;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using System.Text;
namespace OpenSim.Data.MSSQL
{
public class MSSQLGenericTableHandler<T> where T : class, new()
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected string m_ConnectionString;
protected MSSQLManager m_database; //used for parameter type translation
protected Dictionary<string, FieldInfo> m_Fields =
new Dictionary<string, FieldInfo>();
protected List<string> m_ColumnNames = null;
protected string m_Realm;
protected FieldInfo m_DataField = null;
public MSSQLGenericTableHandler(string connectionString,
string realm, string storeName)
{
m_Realm = realm;
if (storeName != String.Empty)
{
Assembly assem = GetType().Assembly;
m_ConnectionString = connectionString;
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
{
conn.Open();
Migration m = new Migration(conn, assem, storeName);
m.Update();
}
}
m_database = new MSSQLManager(m_ConnectionString);
Type t = typeof(T);
FieldInfo[] fields = t.GetFields(BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
if (fields.Length == 0)
return;
foreach (FieldInfo f in fields)
{
if (f.Name != "Data")
m_Fields[f.Name] = f;
else
m_DataField = f;
}
}
private void CheckColumnNames(SqlDataReader reader)
{
if (m_ColumnNames != null)
return;
m_ColumnNames = new List<string>();
DataTable schemaTable = reader.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows)
{
if (row["ColumnName"] != null &&
(!m_Fields.ContainsKey(row["ColumnName"].ToString())))
m_ColumnNames.Add(row["ColumnName"].ToString());
}
}
private List<string> GetConstraints()
{
List<string> constraints = new List<string>();
string query = string.Format(@"SELECT
COL_NAME(ic.object_id,ic.column_id) AS column_name
FROM sys.indexes AS i
INNER JOIN sys.index_columns AS ic
ON i.object_id = ic.object_id AND i.index_id = ic.index_id
WHERE i.is_primary_key = 1
AND i.object_id = OBJECT_ID('{0}');", m_Realm);
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
// query produces 0 to many rows of single column, so always add the first item in each row
constraints.Add((string)rdr[0]);
}
}
return constraints;
}
}
public virtual T[] Get(string field, string key)
{
return Get(new string[] { field }, new string[] { key });
}
public virtual T[] Get(string[] fields, string[] keys)
{
if (fields.Length != keys.Length)
return new T[0];
List<string> terms = new List<string>();
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand())
{
for (int i = 0; i < fields.Length; i++)
{
cmd.Parameters.Add(m_database.CreateParameter(fields[i], keys[i]));
terms.Add("[" + fields[i] + "] = @" + fields[i]);
}
string where = String.Join(" AND ", terms.ToArray());
string query = String.Format("SELECT * FROM {0} WHERE {1}",
m_Realm, where);
cmd.Connection = conn;
cmd.CommandText = query;
conn.Open();
return DoQuery(cmd);
}
}
protected T[] DoQuery(SqlCommand cmd)
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader == null)
return new T[0];
CheckColumnNames(reader);
List<T> result = new List<T>();
while (reader.Read())
{
T row = new T();
foreach (string name in m_Fields.Keys)
{
if (m_Fields[name].GetValue(row) is bool)
{
int v = Convert.ToInt32(reader[name]);
m_Fields[name].SetValue(row, v != 0 ? true : false);
}
else if (m_Fields[name].GetValue(row) is UUID)
{
UUID uuid = UUID.Zero;
UUID.TryParse(reader[name].ToString(), out uuid);
m_Fields[name].SetValue(row, uuid);
}
else if (m_Fields[name].GetValue(row) is int)
{
int v = Convert.ToInt32(reader[name]);
m_Fields[name].SetValue(row, v);
}
else
{
m_Fields[name].SetValue(row, reader[name]);
}
}
if (m_DataField != null)
{
Dictionary<string, string> data =
new Dictionary<string, string>();
foreach (string col in m_ColumnNames)
{
data[col] = reader[col].ToString();
if (data[col] == null)
data[col] = String.Empty;
}
m_DataField.SetValue(row, data);
}
result.Add(row);
}
return result.ToArray();
}
}
public virtual T[] Get(string where)
{
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand())
{
string query = String.Format("SELECT * FROM {0} WHERE {1}",
m_Realm, where);
cmd.Connection = conn;
cmd.CommandText = query;
//m_log.WarnFormat("[MSSQLGenericTable]: SELECT {0} WHERE {1}", m_Realm, where);
conn.Open();
return DoQuery(cmd);
}
}
public virtual bool Store(T row)
{
List<string> constraintFields = GetConstraints();
List<KeyValuePair<string, string>> constraints = new List<KeyValuePair<string, string>>();
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand())
{
StringBuilder query = new StringBuilder();
List<String> names = new List<String>();
List<String> values = new List<String>();
foreach (FieldInfo fi in m_Fields.Values)
{
names.Add(fi.Name);
values.Add("@" + fi.Name);
if (constraintFields.Count > 0 && constraintFields.Contains(fi.Name))
{
constraints.Add(new KeyValuePair<string, string>(fi.Name, fi.GetValue(row).ToString()));
}
cmd.Parameters.Add(m_database.CreateParameter(fi.Name, fi.GetValue(row).ToString()));
}
if (m_DataField != null)
{
Dictionary<string, string> data =
(Dictionary<string, string>)m_DataField.GetValue(row);
foreach (KeyValuePair<string, string> kvp in data)
{
if (constraintFields.Count > 0 && constraintFields.Contains(kvp.Key))
{
constraints.Add(new KeyValuePair<string, string>(kvp.Key, kvp.Key));
}
names.Add(kvp.Key);
values.Add("@" + kvp.Key);
cmd.Parameters.Add(m_database.CreateParameter("@" + kvp.Key, kvp.Value));
}
}
query.AppendFormat("UPDATE {0} SET ", m_Realm);
int i = 0;
for (i = 0; i < names.Count - 1; i++)
{
query.AppendFormat("[{0}] = {1}, ", names[i], values[i]);
}
query.AppendFormat("[{0}] = {1} ", names[i], values[i]);
if (constraints.Count > 0)
{
List<string> terms = new List<string>();
for (int j = 0; j < constraints.Count; j++)
{
terms.Add(" [" + constraints[j].Key + "] = @" + constraints[j].Key);
}
string where = String.Join(" AND ", terms.ToArray());
query.AppendFormat(" WHERE {0} ", where);
}
cmd.Connection = conn;
cmd.CommandText = query.ToString();
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
{
//m_log.WarnFormat("[MSSQLGenericTable]: Updating {0}", m_Realm);
return true;
}
else
{
// assume record has not yet been inserted
query = new StringBuilder();
query.AppendFormat("INSERT INTO {0} ([", m_Realm);
query.Append(String.Join("],[", names.ToArray()));
query.Append("]) values (" + String.Join(",", values.ToArray()) + ")");
cmd.Connection = conn;
cmd.CommandText = query.ToString();
//m_log.WarnFormat("[MSSQLGenericTable]: Inserting into {0}", m_Realm);
if (conn.State != ConnectionState.Open)
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
return true;
}
return false;
}
}
public virtual bool Delete(string field, string val)
{
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand())
{
string deleteCommand = String.Format("DELETE FROM {0} WHERE [{1}] = @{1}", m_Realm, field);
cmd.CommandText = deleteCommand;
cmd.Parameters.Add(m_database.CreateParameter(field, val));
cmd.Connection = conn;
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
{
//m_log.Warn("[MSSQLGenericTable]: " + deleteCommand);
return true;
}
return false;
}
}
}
}

View File

@ -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
{
/// <summary>
/// A grid data interface for MSSQL Server
/// </summary>
public class MSSQLGridData : GridDataBase
{
private const string _migrationStore = "GridStore";
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Database manager
/// </summary>
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);
}
/// <summary>
/// Initialises the Grid Interface
/// </summary>
/// <param name="connectionString">connect string</param>
/// <remarks>use mssql_connection.ini</remarks>
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);
}
/// <summary>
/// Shuts down the grid interface
/// </summary>
override public void Dispose()
{
database = null;
}
/// <summary>
/// The name of this DB provider.
/// </summary>
/// <returns>A string containing the storage system name</returns>
override public string Name
{
get { return "MSSQL OpenGridData"; }
}
/// <summary>
/// Database provider version.
/// </summary>
/// <returns>A string containing the storage system version</returns>
override public string Version
{
get { return "0.1"; }
}
#endregion
#region Public override GridDataBase methods
/// <summary>
/// Returns a list of regions within the specified ranges
/// </summary>
/// <param name="xmin">minimum X coordinate</param>
/// <param name="ymin">minimum Y coordinate</param>
/// <param name="xmax">maximum X coordinate</param>
/// <param name="ymax">maximum Y coordinate</param>
/// <returns>null</returns>
/// <remarks>always return null</remarks>
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<RegionProfileData> rows = new List<RegionProfileData>();
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;
}
/// <summary>
/// Returns up to maxNum profiles of regions that have a name starting with namePrefix
/// </summary>
/// <param name="namePrefix">The name to match against</param>
/// <param name="maxNum">Maximum number of profiles to return</param>
/// <returns>A list of sim profiles</returns>
override public List<RegionProfileData> 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<RegionProfileData> rows = new List<RegionProfileData>();
using (SqlDataReader reader = command.ExecuteReader())
{
while (rows.Count < maxNum && reader.Read())
{
rows.Add(ReadSimRow(reader));
}
}
return rows;
}
}
/// <summary>
/// Returns a sim profile from its location
/// </summary>
/// <param name="handle">Region location handle</param>
/// <returns>Sim profile</returns>
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;
}
/// <summary>
/// Returns a sim profile from its UUID
/// </summary>
/// <param name="uuid">The region UUID</param>
/// <returns>The sim profile</returns>
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;
}
/// <summary>
/// Returns a sim profile from it's Region name string
/// </summary>
/// <param name="regionName">The region name search query</param>
/// <returns>The sim profile</returns>
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;
}
/// <summary>
/// Adds a new specified region to the database
/// </summary>
/// <param name="profile">The profile to add</param>
/// <returns>A dataresponse enum indicating success</returns>
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;
}
/// <summary>
/// Deletes a sim profile from the database
/// </summary>
/// <param name="uuid">the sim UUID</param>
/// <returns>Successful?</returns>
//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)
/// <summary>
/// DEPRECATED. Attempts to authenticate a region by comparing a shared secret.
/// </summary>
/// <param name="uuid">The UUID of the challenger</param>
/// <param name="handle">The attempted regionHandle of the challenger</param>
/// <param name="authkey">The secret</param>
/// <returns>Whether the secret and regionhandle match the database entry for UUID</returns>
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);
}
/// <summary>
/// NOT YET FUNCTIONAL. Provides a cryptographic authentication of a region
/// </summary>
/// <remarks>This requires a security audit.</remarks>
/// <param name="uuid"></param>
/// <param name="handle"></param>
/// <param name="authhash"></param>
/// <param name="challenge"></param>
/// <returns></returns>
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;
}
/// <summary>
/// NOT IMPLEMENTED
/// WHEN IS THIS GONNA BE IMPLEMENTED.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns>null</returns>
override public ReservationData GetReservationAtPoint(uint x, uint y)
{
return null;
}
#endregion
#region private methods
/// <summary>
/// Reads a region row from a database reader
/// </summary>
/// <param name="reader">An active database reader</param>
/// <returns>A region profile</returns>
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;
}
/// <summary>
/// Update the specified region in the database
/// </summary>
/// <param name="profile">The profile to update</param>
/// <returns>success ?</returns>
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;
}
/// <summary>
/// Creates a new region in the database
/// </summary>
/// <param name="profile">The region profile to insert</param>
/// <returns>Successful?</returns>
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
}
}

View File

@ -49,6 +49,7 @@ namespace OpenSim.Data.MSSQL
/// The database manager
/// </summary>
private MSSQLManager database;
private string m_connectionString;
#region IPlugin members
@ -66,24 +67,9 @@ namespace OpenSim.Data.MSSQL
/// <remarks>use mssql_connection.ini</remarks>
public void Initialise(string connectionString)
{
if (!string.IsNullOrEmpty(connectionString))
{
database = new MSSQLManager(connectionString);
}
else
{
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);
}
m_connectionString = connectionString;
database = new MSSQLManager(connectionString);
//New migrations check of store
database.CheckMigration(_migrationStore);
}
@ -169,11 +155,13 @@ namespace OpenSim.Data.MSSQL
/// <returns>A folder class</returns>
public InventoryFolderBase getInventoryFolder(UUID folderID)
{
using (AutoClosingSqlCommand command = database.Query("SELECT * FROM inventoryfolders WHERE folderID = @folderID"))
string sql = "SELECT * FROM inventoryfolders WHERE folderID = @folderID";
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
command.Parameters.Add(database.CreateParameter("folderID", folderID));
using (IDataReader reader = command.ExecuteReader())
cmd.Parameters.Add(database.CreateParameter("folderID", folderID));
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
@ -197,18 +185,19 @@ namespace OpenSim.Data.MSSQL
//Note this is changed so it opens only one connection to the database and not everytime it wants to get data.
List<InventoryFolderBase> folders = new List<InventoryFolderBase>();
using (AutoClosingSqlCommand command = database.Query("SELECT * FROM inventoryfolders WHERE parentFolderID = @parentID"))
string sql = "SELECT * FROM inventoryfolders WHERE parentFolderID = @parentID";
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
command.Parameters.Add(database.CreateParameter("@parentID", parentID));
folders.AddRange(getInventoryFolders(command));
cmd.Parameters.Add(database.CreateParameter("@parentID", parentID));
conn.Open();
folders.AddRange(getInventoryFolders(cmd));
List<InventoryFolderBase> tempFolders = new List<InventoryFolderBase>();
foreach (InventoryFolderBase folderBase in folders)
{
tempFolders.AddRange(getFolderHierarchy(folderBase.ID, command));
tempFolders.AddRange(getFolderHierarchy(folderBase.ID, cmd));
}
if (tempFolders.Count > 0)
{
@ -233,20 +222,19 @@ namespace OpenSim.Data.MSSQL
folderName = folderName.Substring(0, 64);
m_log.Warn("[INVENTORY DB]: Name field truncated from " + folder.Name.Length.ToString() + " to " + folderName.Length + " characters on add");
}
using (AutoClosingSqlCommand command = database.Query(sql))
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
command.Parameters.Add(database.CreateParameter("folderID", folder.ID));
command.Parameters.Add(database.CreateParameter("agentID", folder.Owner));
command.Parameters.Add(database.CreateParameter("parentFolderID", folder.ParentID));
command.Parameters.Add(database.CreateParameter("folderName", folderName));
command.Parameters.Add(database.CreateParameter("type", folder.Type));
command.Parameters.Add(database.CreateParameter("version", folder.Version));
cmd.Parameters.Add(database.CreateParameter("folderID", folder.ID));
cmd.Parameters.Add(database.CreateParameter("agentID", folder.Owner));
cmd.Parameters.Add(database.CreateParameter("parentFolderID", folder.ParentID));
cmd.Parameters.Add(database.CreateParameter("folderName", folderName));
cmd.Parameters.Add(database.CreateParameter("type", folder.Type));
cmd.Parameters.Add(database.CreateParameter("version", folder.Version));
conn.Open();
try
{
//IDbCommand result = database.Query(sql, param);
command.ExecuteNonQuery();
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
@ -275,20 +263,20 @@ namespace OpenSim.Data.MSSQL
folderName = folderName.Substring(0, 64);
m_log.Warn("[INVENTORY DB]: Name field truncated from " + folder.Name.Length.ToString() + " to " + folderName.Length + " characters on update");
}
using (AutoClosingSqlCommand command = database.Query(sql))
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
command.Parameters.Add(database.CreateParameter("folderID", folder.ID));
command.Parameters.Add(database.CreateParameter("agentID", folder.Owner));
command.Parameters.Add(database.CreateParameter("parentFolderID", folder.ParentID));
command.Parameters.Add(database.CreateParameter("folderName", folderName));
command.Parameters.Add(database.CreateParameter("type", folder.Type));
command.Parameters.Add(database.CreateParameter("version", folder.Version));
command.Parameters.Add(database.CreateParameter("@keyFolderID", folder.ID));
cmd.Parameters.Add(database.CreateParameter("folderID", folder.ID));
cmd.Parameters.Add(database.CreateParameter("agentID", folder.Owner));
cmd.Parameters.Add(database.CreateParameter("parentFolderID", folder.ParentID));
cmd.Parameters.Add(database.CreateParameter("folderName", folderName));
cmd.Parameters.Add(database.CreateParameter("type", folder.Type));
cmd.Parameters.Add(database.CreateParameter("version", folder.Version));
cmd.Parameters.Add(database.CreateParameter("@keyFolderID", folder.ID));
conn.Open();
try
{
command.ExecuteNonQuery();
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
@ -304,14 +292,15 @@ namespace OpenSim.Data.MSSQL
public void moveInventoryFolder(InventoryFolderBase folder)
{
string sql = @"UPDATE inventoryfolders SET parentFolderID = @parentFolderID WHERE folderID = @folderID";
using (IDbCommand command = database.Query(sql))
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
command.Parameters.Add(database.CreateParameter("parentFolderID", folder.ParentID));
command.Parameters.Add(database.CreateParameter("@folderID", folder.ID));
cmd.Parameters.Add(database.CreateParameter("parentFolderID", folder.ParentID));
cmd.Parameters.Add(database.CreateParameter("@folderID", folder.ID));
conn.Open();
try
{
command.ExecuteNonQuery();
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
@ -326,30 +315,27 @@ namespace OpenSim.Data.MSSQL
/// <param name="folderID">Id of folder to delete</param>
public void deleteInventoryFolder(UUID folderID)
{
using (SqlConnection connection = database.DatabaseConnection())
string sql = "SELECT * FROM inventoryfolders WHERE parentFolderID = @parentID";
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
List<InventoryFolderBase> subFolders;
using (SqlCommand command = new SqlCommand("SELECT * FROM inventoryfolders WHERE parentFolderID = @parentID", connection))
{
command.Parameters.Add(database.CreateParameter("@parentID", UUID.Zero));
AutoClosingSqlCommand autoCommand = new AutoClosingSqlCommand(command);
subFolders = getFolderHierarchy(folderID, autoCommand);
}
cmd.Parameters.Add(database.CreateParameter("@parentID", UUID.Zero));
conn.Open();
subFolders = getFolderHierarchy(folderID, cmd);
//Delete all sub-folders
foreach (InventoryFolderBase f in subFolders)
{
DeleteOneFolder(f.ID, connection);
DeleteItemsInFolder(f.ID, connection);
DeleteOneFolder(f.ID, conn);
DeleteItemsInFolder(f.ID, conn);
}
//Delete the actual row
DeleteOneFolder(folderID, connection);
DeleteItemsInFolder(folderID, connection);
connection.Close();
DeleteOneFolder(folderID, conn);
DeleteItemsInFolder(folderID, conn);
}
}
@ -364,13 +350,15 @@ namespace OpenSim.Data.MSSQL
/// <returns>A list containing inventory items</returns>
public List<InventoryItemBase> getInventoryInFolder(UUID folderID)
{
using (AutoClosingSqlCommand command = database.Query("SELECT * FROM inventoryitems WHERE parentFolderID = @parentFolderID"))
string sql = "SELECT * FROM inventoryitems WHERE parentFolderID = @parentFolderID";
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
command.Parameters.Add(database.CreateParameter("parentFolderID", folderID));
cmd.Parameters.Add(database.CreateParameter("parentFolderID", folderID));
conn.Open();
List<InventoryItemBase> items = new List<InventoryItemBase>();
using (SqlDataReader reader = command.ExecuteReader())
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
@ -388,11 +376,13 @@ namespace OpenSim.Data.MSSQL
/// <returns>An inventory item</returns>
public InventoryItemBase getInventoryItem(UUID itemID)
{
using (AutoClosingSqlCommand result = database.Query("SELECT * FROM inventoryitems WHERE inventoryID = @inventoryID"))
string sql = "SELECT * FROM inventoryitems WHERE inventoryID = @inventoryID";
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
result.Parameters.Add(database.CreateParameter("inventoryID", itemID));
using (IDataReader reader = result.ExecuteReader())
cmd.Parameters.Add(database.CreateParameter("inventoryID", itemID));
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
@ -441,8 +431,9 @@ namespace OpenSim.Data.MSSQL
itemDesc = item.Description.Substring(0, 128);
m_log.Warn("[INVENTORY DB]: Description field truncated from " + item.Description.Length.ToString() + " to " + itemDesc.Length.ToString() + " characters");
}
using (AutoClosingSqlCommand command = database.Query(sql))
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand command = new SqlCommand(sql, conn))
{
command.Parameters.Add(database.CreateParameter("inventoryID", item.ID));
command.Parameters.Add(database.CreateParameter("assetID", item.AssetID));
@ -464,7 +455,7 @@ namespace OpenSim.Data.MSSQL
command.Parameters.Add(database.CreateParameter("groupID", item.GroupID));
command.Parameters.Add(database.CreateParameter("groupOwned", item.GroupOwned));
command.Parameters.Add(database.CreateParameter("flags", item.Flags));
conn.Open();
try
{
command.ExecuteNonQuery();
@ -476,9 +467,11 @@ namespace OpenSim.Data.MSSQL
}
sql = "UPDATE inventoryfolders SET version = version + 1 WHERE folderID = @folderID";
using (AutoClosingSqlCommand command = database.Query(sql))
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand command = new SqlCommand(sql, conn))
{
command.Parameters.Add(database.CreateParameter("folderID", item.Folder.ToString()));
conn.Open();
try
{
command.ExecuteNonQuery();
@ -530,8 +523,9 @@ namespace OpenSim.Data.MSSQL
itemDesc = item.Description.Substring(0, 128);
m_log.Warn("[INVENTORY DB]: Description field truncated from " + item.Description.Length.ToString() + " to " + itemDesc.Length.ToString() + " characters on update");
}
using (AutoClosingSqlCommand command = database.Query(sql))
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand command = new SqlCommand(sql, conn))
{
command.Parameters.Add(database.CreateParameter("inventoryID", item.ID));
command.Parameters.Add(database.CreateParameter("assetID", item.AssetID));
@ -552,8 +546,8 @@ namespace OpenSim.Data.MSSQL
command.Parameters.Add(database.CreateParameter("groupID", item.GroupID));
command.Parameters.Add(database.CreateParameter("groupOwned", item.GroupOwned));
command.Parameters.Add(database.CreateParameter("flags", item.Flags));
command.Parameters.Add(database.CreateParameter("@keyInventoryID", item.ID));
command.Parameters.Add(database.CreateParameter("keyInventoryID", item.ID));
conn.Open();
try
{
command.ExecuteNonQuery();
@ -573,13 +567,15 @@ namespace OpenSim.Data.MSSQL
/// <param name="itemID">the item UUID</param>
public void deleteInventoryItem(UUID itemID)
{
using (AutoClosingSqlCommand command = database.Query("DELETE FROM inventoryitems WHERE inventoryID=@inventoryID"))
string sql = "DELETE FROM inventoryitems WHERE inventoryID=@inventoryID";
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
command.Parameters.Add(database.CreateParameter("inventoryID", itemID));
cmd.Parameters.Add(database.CreateParameter("inventoryID", itemID));
try
{
command.ExecuteNonQuery();
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
@ -607,12 +603,14 @@ namespace OpenSim.Data.MSSQL
/// </returns>
public List<InventoryItemBase> fetchActiveGestures(UUID avatarID)
{
using (AutoClosingSqlCommand command = database.Query("SELECT * FROM inventoryitems WHERE avatarId = @uuid AND assetType = @assetType and flags = 1"))
string sql = "SELECT * FROM inventoryitems WHERE avatarId = @uuid AND assetType = @assetType and flags = 1";
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
command.Parameters.Add(database.CreateParameter("uuid", avatarID));
command.Parameters.Add(database.CreateParameter("assetType", (int)AssetType.Gesture));
using (IDataReader reader = command.ExecuteReader())
cmd.Parameters.Add(database.CreateParameter("uuid", avatarID));
cmd.Parameters.Add(database.CreateParameter("assetType", (int)AssetType.Gesture));
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
List<InventoryItemBase> gestureList = new List<InventoryItemBase>();
while (reader.Read())
@ -656,7 +654,7 @@ namespace OpenSim.Data.MSSQL
/// <param name="parentID">parent ID.</param>
/// <param name="command">SQL command/connection to database</param>
/// <returns></returns>
private static List<InventoryFolderBase> getFolderHierarchy(UUID parentID, AutoClosingSqlCommand command)
private static List<InventoryFolderBase> getFolderHierarchy(UUID parentID, SqlCommand command)
{
command.Parameters["@parentID"].Value = parentID.Guid; //.ToString();
@ -687,7 +685,9 @@ namespace OpenSim.Data.MSSQL
/// <returns></returns>
private List<InventoryFolderBase> getInventoryFolders(UUID parentID, UUID user)
{
using (AutoClosingSqlCommand command = database.Query("SELECT * FROM inventoryfolders WHERE parentFolderID = @parentID AND agentID LIKE @uuid"))
string sql = "SELECT * FROM inventoryfolders WHERE parentFolderID = @parentID AND agentID LIKE @uuid";
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand command = new SqlCommand(sql, conn))
{
if (user == UUID.Zero)
{
@ -698,7 +698,7 @@ namespace OpenSim.Data.MSSQL
command.Parameters.Add(database.CreateParameter("uuid", user));
}
command.Parameters.Add(database.CreateParameter("parentID", parentID));
conn.Open();
return getInventoryFolders(command);
}
}
@ -708,9 +708,9 @@ namespace OpenSim.Data.MSSQL
/// </summary>
/// <param name="command">SQLcommand.</param>
/// <returns></returns>
private static List<InventoryFolderBase> getInventoryFolders(AutoClosingSqlCommand command)
private static List<InventoryFolderBase> getInventoryFolders(SqlCommand command)
{
using (IDataReader reader = command.ExecuteReader())
using (SqlDataReader reader = command.ExecuteReader())
{
List<InventoryFolderBase> items = new List<InventoryFolderBase>();
@ -727,7 +727,7 @@ namespace OpenSim.Data.MSSQL
/// </summary>
/// <param name="reader">A MSSQL Data Reader</param>
/// <returns>A List containing inventory folders</returns>
protected static InventoryFolderBase readInventoryFolder(IDataReader reader)
protected static InventoryFolderBase readInventoryFolder(SqlDataReader reader)
{
try
{

View File

@ -54,28 +54,16 @@ namespace OpenSim.Data.MSSQL
/// The database manager
/// </summary>
private MSSQLManager _Database;
private string m_connectionString;
/// <summary>
/// Initialises the region datastore
/// </summary>
/// <param name="connectionString">The connection string.</param>
public void Initialise(string connectionString)
{
if (!string.IsNullOrEmpty(connectionString))
{
_Database = new MSSQLManager(connectionString);
}
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");
m_connectionString = connectionString;
_Database = new MSSQLManager(connectionString);
_Database = new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId, settingPassword);
}
//Migration settings
_Database.CheckMigration(_migrationStore);
@ -102,17 +90,18 @@ namespace OpenSim.Data.MSSQL
SceneObjectGroup grp = null;
string query = "SELECT *, " +
string sql = "SELECT *, " +
"sort = CASE WHEN prims.UUID = prims.SceneGroupID THEN 0 ELSE 1 END " +
"FROM prims " +
"LEFT JOIN primshapes ON prims.UUID = primshapes.UUID " +
"WHERE RegionUUID = @RegionUUID " +
"ORDER BY SceneGroupID asc, sort asc, LinkNumber asc";
using (AutoClosingSqlCommand command = _Database.Query(query))
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand command = new SqlCommand(sql, conn))
{
command.Parameters.Add(_Database.CreateParameter("@regionUUID", regionUUID));
conn.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
@ -122,7 +111,7 @@ namespace OpenSim.Data.MSSQL
sceneObjectPart.Shape = PrimitiveBaseShape.Default;
else
sceneObjectPart.Shape = BuildShape(reader);
prims[sceneObjectPart.UUID] = sceneObjectPart;
UUID groupID = new UUID((Guid)reader["SceneGroupID"]);
@ -133,7 +122,7 @@ namespace OpenSim.Data.MSSQL
objects[grp.UUID] = grp;
lastGroupID = groupID;
// There sometimes exist OpenSim bugs that 'orphan groups' so that none of the prims are
// recorded as the root prim (for which the UUID must equal the persisted group UUID). In
// this case, force the UUID to be the same as the group UUID so that at least these can be
@ -142,7 +131,7 @@ namespace OpenSim.Data.MSSQL
if (sceneObjectPart.UUID != groupID && groupID != UUID.Zero)
{
_Log.WarnFormat(
"[REGION DB]: Found root prim {0} {1} at {2} where group was actually {3}. Forcing UUID to group UUID",
"[REGION DB]: Found root prim {0} {1} at {2} where group was actually {3}. Forcing UUID to group UUID",
sceneObjectPart.Name, sceneObjectPart.UUID, sceneObjectPart.GroupPosition, groupID);
sceneObjectPart.UUID = groupID;
@ -174,8 +163,10 @@ namespace OpenSim.Data.MSSQL
// LoadItems only on those
List<SceneObjectPart> primsWithInventory = new List<SceneObjectPart>();
string qry = "select distinct primID from primitems";
using (AutoClosingSqlCommand command = _Database.Query(qry))
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand command = new SqlCommand(qry, conn))
{
conn.Open();
using (SqlDataReader itemReader = command.ExecuteReader())
{
while (itemReader.Read())
@ -205,14 +196,16 @@ namespace OpenSim.Data.MSSQL
/// <param name="allPrims">all prims with inventory on a region</param>
private void LoadItems(List<SceneObjectPart> allPrimsWithInventory)
{
using (AutoClosingSqlCommand command = _Database.Query("SELECT * FROM primitems WHERE PrimID = @PrimID"))
string sql = "SELECT * FROM primitems WHERE PrimID = @PrimID";
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand command = new SqlCommand(sql, conn))
{
conn.Open();
foreach (SceneObjectPart objectPart in allPrimsWithInventory)
{
command.Parameters.Clear();
command.Parameters.Add(_Database.CreateParameter("@PrimID", objectPart.UUID));
List<TaskInventoryItem> inventory = new List<TaskInventoryItem>();
using (SqlDataReader reader = command.ExecuteReader())
@ -241,8 +234,9 @@ namespace OpenSim.Data.MSSQL
{
_Log.InfoFormat("[MSSQL]: Adding/Changing SceneObjectGroup: {0} to region: {1}, object has {2} prims.", obj.UUID, regionUUID, obj.Children.Count);
using (SqlConnection conn = _Database.DatabaseConnection())
using (SqlConnection conn = new SqlConnection(m_connectionString))
{
conn.Open();
SqlTransaction transaction = conn.BeginTransaction();
try
@ -437,8 +431,12 @@ ELSE
lock (_Database)
{
//Using the non transaction mode.
using (AutoClosingSqlCommand cmd = _Database.Query(sqlPrimShapes))
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = sqlPrimShapes;
conn.Open();
cmd.Parameters.Add(_Database.CreateParameter("objectID", objectID));
cmd.ExecuteNonQuery();
@ -466,24 +464,30 @@ ELSE
//Delete everything from PrimID
//TODO add index on PrimID in DB, if not already exist
using (AutoClosingSqlCommand cmd = _Database.Query("DELETE PRIMITEMS WHERE primID = @primID"))
string sql = "DELETE PRIMITEMS WHERE primID = @primID";
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(_Database.CreateParameter("@primID", primID));
conn.Open();
cmd.ExecuteNonQuery();
}
string sql =
sql =
@"INSERT INTO primitems (
itemID,primID,assetID,parentFolderID,invType,assetType,name,description,creationDate,creatorID,ownerID,lastOwnerID,groupID,
nextPermissions,currentPermissions,basePermissions,everyonePermissions,groupPermissions,flags)
VALUES (@itemID,@primID,@assetID,@parentFolderID,@invType,@assetType,@name,@description,@creationDate,@creatorID,@ownerID,
@lastOwnerID,@groupID,@nextPermissions,@currentPermissions,@basePermissions,@everyonePermissions,@groupPermissions,@flags)";
using (AutoClosingSqlCommand cmd = _Database.Query(sql))
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
foreach (TaskInventoryItem taskItem in items)
{
cmd.Parameters.AddRange(CreatePrimInventoryParameters(taskItem));
conn.Open();
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
@ -505,11 +509,12 @@ ELSE
string sql = "select top 1 RegionUUID, Revision, Heightfield from terrain where RegionUUID = @RegionUUID order by Revision desc";
using (AutoClosingSqlCommand cmd = _Database.Query(sql))
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
// MySqlParameter param = new MySqlParameter();
cmd.Parameters.Add(_Database.CreateParameter("@RegionUUID", regionID));
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
int rev;
@ -549,19 +554,23 @@ ELSE
//Delete old terrain map
string sql = "delete from terrain where RegionUUID=@RegionUUID";
using (AutoClosingSqlCommand cmd = _Database.Query(sql))
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(_Database.CreateParameter("@RegionUUID", regionID));
conn.Open();
cmd.ExecuteNonQuery();
}
sql = "insert into terrain(RegionUUID, Revision, Heightfield) values(@RegionUUID, @Revision, @Heightfield)";
using (AutoClosingSqlCommand cmd = _Database.Query(sql))
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(_Database.CreateParameter("@RegionUUID", regionID));
cmd.Parameters.Add(_Database.CreateParameter("@Revision", revision));
cmd.Parameters.Add(_Database.CreateParameter("@Heightfield", serializeTerrain(terrain)));
conn.Open();
cmd.ExecuteNonQuery();
}
@ -580,11 +589,12 @@ ELSE
string sql = "select * from land where RegionUUID = @RegionUUID";
//Retrieve all land data from region
using (AutoClosingSqlCommand cmdLandData = _Database.Query(sql))
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmdLandData.Parameters.Add(_Database.CreateParameter("@RegionUUID", regionUUID));
using (SqlDataReader readerLandData = cmdLandData.ExecuteReader())
cmd.Parameters.Add(_Database.CreateParameter("@RegionUUID", regionUUID));
conn.Open();
using (SqlDataReader readerLandData = cmd.ExecuteReader())
{
while (readerLandData.Read())
{
@ -597,10 +607,12 @@ ELSE
foreach (LandData LandData in LandDataForRegion)
{
sql = "select * from landaccesslist where LandUUID = @LandUUID";
using (AutoClosingSqlCommand cmdAccessList = _Database.Query(sql))
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmdAccessList.Parameters.Add(_Database.CreateParameter("@LandUUID", LandData.GlobalID));
using (SqlDataReader readerAccessList = cmdAccessList.ExecuteReader())
cmd.Parameters.Add(_Database.CreateParameter("@LandUUID", LandData.GlobalID));
conn.Open();
using (SqlDataReader readerAccessList = cmd.ExecuteReader())
{
while (readerAccessList.Read())
{
@ -632,17 +644,20 @@ ELSE
VALUES
(@UUID,@RegionUUID,@LocalLandID,@Bitmap,@Name,@Description,@OwnerUUID,@IsGroupOwned,@Area,@AuctionID,@Category,@ClaimDate,@ClaimPrice,@GroupUUID,@SalePrice,@LandStatus,@LandFlags,@LandingType,@MediaAutoScale,@MediaTextureUUID,@MediaURL,@MusicURL,@PassHours,@PassPrice,@SnapshotUUID,@UserLocationX,@UserLocationY,@UserLocationZ,@UserLookAtX,@UserLookAtY,@UserLookAtZ,@AuthbuyerID,@OtherCleanTime,@Dwell)";
using (AutoClosingSqlCommand cmd = _Database.Query(sql))
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddRange(CreateLandParameters(parcel.LandData, parcel.RegionUUID));
conn.Open();
cmd.ExecuteNonQuery();
}
sql = "INSERT INTO [landaccesslist] ([LandUUID],[AccessUUID],[Flags]) VALUES (@LandUUID,@AccessUUID,@Flags)";
using (AutoClosingSqlCommand cmd = _Database.Query(sql))
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
conn.Open();
foreach (ParcelManager.ParcelAccessEntry parcelAccessEntry in parcel.LandData.ParcelAccessList)
{
cmd.Parameters.AddRange(CreateLandAccessParameters(parcelAccessEntry, parcel.RegionUUID));
@ -659,15 +674,20 @@ VALUES
/// <param name="globalID">UUID of landobject</param>
public void RemoveLandObject(UUID globalID)
{
using (AutoClosingSqlCommand cmd = _Database.Query("delete from land where UUID=@UUID"))
string sql = "delete from land where UUID=@UUID";
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(_Database.CreateParameter("@UUID", globalID));
conn.Open();
cmd.ExecuteNonQuery();
}
using (AutoClosingSqlCommand cmd = _Database.Query("delete from landaccesslist where LandUUID=@UUID"))
sql = "delete from landaccesslist where LandUUID=@UUID";
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(_Database.CreateParameter("@UUID", globalID));
conn.Open();
cmd.ExecuteNonQuery();
}
}
@ -690,9 +710,11 @@ VALUES
{
string sql = "select * from regionsettings where regionUUID = @regionUUID";
RegionSettings regionSettings;
using (AutoClosingSqlCommand cmd = _Database.Query(sql))
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(_Database.CreateParameter("@regionUUID", regionUUID));
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
@ -724,9 +746,12 @@ VALUES
{
//Little check if regionUUID already exist in DB
string regionUUID;
using (AutoClosingSqlCommand cmd = _Database.Query("SELECT regionUUID FROM regionsettings WHERE regionUUID = @regionUUID"))
string sql = "SELECT regionUUID FROM regionsettings WHERE regionUUID = @regionUUID";
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(_Database.CreateParameter("@regionUUID", regionSettings.RegionUUID));
conn.Open();
regionUUID = cmd.ExecuteScalar().ToString();
}
@ -737,8 +762,8 @@ VALUES
else
{
//This method only updates region settings!!! First call LoadRegionSettings to create new region settings in DB
string sql =
@"UPDATE [regionsettings] SET [block_terraform] = @block_terraform ,[block_fly] = @block_fly ,[allow_damage] = @allow_damage
sql =
@"UPDATE [regionsettings] SET [block_terraform] = @block_terraform ,[block_fly] = @block_fly ,[allow_damage] = @allow_damage
,[restrict_pushing] = @restrict_pushing ,[allow_land_resell] = @allow_land_resell ,[allow_land_join_divide] = @allow_land_join_divide
,[block_show_in_search] = @block_show_in_search ,[agent_limit] = @agent_limit ,[object_bonus] = @object_bonus ,[maturity] = @maturity
,[disable_scripts] = @disable_scripts ,[disable_collisions] = @disable_collisions ,[disable_physics] = @disable_physics
@ -750,10 +775,11 @@ VALUES
,[covenant] = @covenant , [sunvectorx] = @sunvectorx, [sunvectory] = @sunvectory, [sunvectorz] = @sunvectorz, [Sandbox] = @Sandbox, [loaded_creation_datetime] = @loaded_creation_datetime, [loaded_creation_id] = @loaded_creation_id
WHERE [regionUUID] = @regionUUID";
using (AutoClosingSqlCommand cmd = _Database.Query(sql))
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddRange(CreateRegionSettingParameters(regionSettings));
conn.Open();
cmd.ExecuteNonQuery();
}
}
@ -810,9 +836,11 @@ VALUES
@elevation_2_ne,@elevation_1_se,@elevation_2_se,@elevation_1_sw,@elevation_2_sw,@water_height,@terrain_raise_limit,
@terrain_lower_limit,@use_estate_sun,@fixed_sun,@sun_position,@covenant,@sunvectorx,@sunvectory, @sunvectorz, @Sandbox, @loaded_creation_datetime, @loaded_creation_id)";
using (AutoClosingSqlCommand cmd = _Database.Query(sql))
using (SqlConnection conn = new SqlConnection(m_connectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddRange(CreateRegionSettingParameters(regionSettings));
conn.Open();
cmd.ExecuteNonQuery();
}
}
@ -916,15 +944,15 @@ VALUES
newData.PassHours = Convert.ToSingle(row["PassHours"]);
newData.PassPrice = Convert.ToInt32(row["PassPrice"]);
// UUID authedbuyer;
// UUID snapshotID;
//
// if (UUID.TryParse((string)row["AuthBuyerID"], out authedbuyer))
// newData.AuthBuyerID = authedbuyer;
//
// if (UUID.TryParse((string)row["SnapshotUUID"], out snapshotID))
// newData.SnapshotID = snapshotID;
newData.AuthBuyerID = new UUID((Guid) row["AuthBuyerID"]);
// UUID authedbuyer;
// UUID snapshotID;
//
// if (UUID.TryParse((string)row["AuthBuyerID"], out authedbuyer))
// newData.AuthBuyerID = authedbuyer;
//
// if (UUID.TryParse((string)row["SnapshotUUID"], out snapshotID))
// newData.SnapshotID = snapshotID;
newData.AuthBuyerID = new UUID((Guid)row["AuthBuyerID"]);
newData.SnapshotID = new UUID((Guid)row["SnapshotUUID"]);
newData.OtherCleanTime = Convert.ToInt32(row["OtherCleanTime"]);
@ -1193,7 +1221,7 @@ VALUES
#endregion
#region Create parameters methods
/// <summary>
/// Creates the prim inventory parameters.
/// </summary>
@ -1477,7 +1505,7 @@ VALUES
parameters.Add(_Database.CreateParameter("CollisionSound", prim.CollisionSound));
parameters.Add(_Database.CreateParameter("CollisionSoundVolume", prim.CollisionSoundVolume));
if (prim.PassTouches)
if (prim.PassTouches)
parameters.Add(_Database.CreateParameter("PassTouches", 1));
else
parameters.Add(_Database.CreateParameter("PassTouches", 0));
@ -1532,7 +1560,7 @@ VALUES
return parameters.ToArray();
}
#endregion
#endregion

View File

@ -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
{
/// <summary>
/// An interface to the log database for MSSQL
/// </summary>
internal class MSSQLLogData : ILogDataPlugin
{
private const string _migrationStore = "LogStore";
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// The database manager
/// </summary>
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);
}
/// <summary>
/// Artificial constructor called when the plugin is loaded
/// </summary>
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);
}
/// <summary>
/// Saves a log item to the database
/// </summary>
/// <param name="serverDaemon">The daemon triggering the event</param>
/// <param name="target">The target of the action (region / agent UUID, etc)</param>
/// <param name="methodCall">The method call where the problem occured</param>
/// <param name="arguments">The arguments passed to the method</param>
/// <param name="priority">How critical is this?</param>
/// <param name="logMessage">The message to log</param>
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);
}
}
}
/// <summary>
/// Returns the name of this DB provider
/// </summary>
/// <returns>A string containing the DB provider name</returns>
public string Name
{
get { return "MSSQL Logdata Interface"; }
}
/// <summary>
/// Closes the database provider
/// </summary>
public void Dispose()
{
database = null;
}
/// <summary>
/// Returns the version of this DB provider
/// </summary>
/// <returns>A string containing the provider version</returns>
public string Version
{
get { return "0.1"; }
}
}
}

View File

@ -46,22 +46,7 @@ namespace OpenSim.Data.MSSQL
/// <summary>
/// Connection string for ADO.net
/// </summary>
private readonly string connectionString;
public MSSQLManager(string dataSource, string initialCatalog, string persistSecurityInfo, string userId,
string password)
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = dataSource;
builder.InitialCatalog = initialCatalog;
builder.PersistSecurityInfo = Convert.ToBoolean(persistSecurityInfo);
builder.UserID = userId;
builder.Password = password;
builder.ApplicationName = Assembly.GetEntryAssembly().Location;
connectionString = builder.ToString();
}
private readonly string connectionString;
/// <summary>
/// Initialize the manager and set the connectionstring
@ -72,94 +57,6 @@ namespace OpenSim.Data.MSSQL
connectionString = connection;
}
public SqlConnection DatabaseConnection()
{
SqlConnection conn = new SqlConnection(connectionString);
//TODO is this good??? Opening connection here
conn.Open();
return conn;
}
#region Obsolete functions, can be removed!
/// <summary>
///
/// </summary>
/// <param name="dt"></param>
/// <param name="name"></param>
/// <param name="type"></param>
[Obsolete("Do not use!")]
protected static void createCol(DataTable dt, string name, Type type)
{
DataColumn col = new DataColumn(name, type);
dt.Columns.Add(col);
}
/// <summary>
/// Define Table function
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
/*
[Obsolete("Do not use!")]
protected static string defineTable(DataTable dt)
{
string sql = "create table " + dt.TableName + "(";
string subsql = String.Empty;
foreach (DataColumn col in dt.Columns)
{
if (subsql.Length > 0)
{
// a map function would rock so much here
subsql += ",\n";
}
subsql += col.ColumnName + " " + SqlType(col.DataType);
if (col == dt.PrimaryKey[0])
{
subsql += " primary key";
}
}
sql += subsql;
sql += ")";
return sql;
}
*/
#endregion
/// <summary>
/// Type conversion function
/// </summary>
/// <param name="type">a type</param>
/// <returns>a sqltype</returns>
/// <remarks>this is something we'll need to implement for each db slightly differently.</remarks>
/*
[Obsolete("Used by a obsolete methods")]
public static string SqlType(Type type)
{
if (type == typeof(String))
{
return "varchar(255)";
}
if (type == typeof(Int32))
{
return "integer";
}
if (type == typeof(Double))
{
return "float";
}
if (type == typeof(Byte[]))
{
return "image";
}
return "varchar(255)";
}
*/
/// <summary>
/// Type conversion to a SQLDbType functions
/// </summary>
@ -285,135 +182,21 @@ namespace OpenSim.Data.MSSQL
private static readonly Dictionary<string, string> emptyDictionary = new Dictionary<string, string>();
/// <summary>
/// Run a query and return a sql db command
/// </summary>
/// <param name="sql">The SQL query.</param>
/// <returns></returns>
internal AutoClosingSqlCommand Query(string sql)
{
return Query(sql, emptyDictionary);
}
/// <summary>
/// Runs a query with protection against SQL Injection by using parameterised input.
/// </summary>
/// <param name="sql">The SQL string - replace any variables such as WHERE x = "y" with WHERE x = @y</param>
/// <param name="parameters">The parameters - index so that @y is indexed as 'y'</param>
/// <returns>A Sql DB Command</returns>
internal AutoClosingSqlCommand Query(string sql, Dictionary<string, string> parameters)
{
SqlCommand dbcommand = DatabaseConnection().CreateCommand();
dbcommand.CommandText = sql;
foreach (KeyValuePair<string, string> param in parameters)
{
dbcommand.Parameters.AddWithValue(param.Key, param.Value);
}
return new AutoClosingSqlCommand(dbcommand);
}
/// <summary>
/// Runs a query with protection against SQL Injection by using parameterised input.
/// </summary>
/// <param name="sql">The SQL string - replace any variables such as WHERE x = "y" with WHERE x = @y</param>
/// <param name="sqlParameter">A parameter - use createparameter to create parameter</param>
/// <returns></returns>
internal AutoClosingSqlCommand Query(string sql, SqlParameter sqlParameter)
{
SqlCommand dbcommand = DatabaseConnection().CreateCommand();
dbcommand.CommandText = sql;
dbcommand.Parameters.Add(sqlParameter);
return new AutoClosingSqlCommand(dbcommand);
}
/// <summary>
/// Checks if we need to do some migrations to the database
/// </summary>
/// <param name="migrationStore">migrationStore.</param>
public void CheckMigration(string migrationStore)
{
using (SqlConnection connection = DatabaseConnection())
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
Assembly assem = GetType().Assembly;
MSSQLMigration migration = new MSSQLMigration(connection, assem, migrationStore);
migration.Update();
connection.Close();
}
}
#region Old Testtable functions
/// <summary>
/// Execute a SQL statement stored in a resource, as a string
/// </summary>
/// <param name="name">the ressource string</param>
public void ExecuteResourceSql(string name)
{
using (IDbCommand cmd = Query(getResourceString(name), new Dictionary<string, string>()))
{
cmd.ExecuteNonQuery();
}
}
/// <summary>
/// Given a list of tables, return the version of the tables, as seen in the database
/// </summary>
/// <param name="tableList"></param>
public void GetTableVersion(Dictionary<string, string> tableList)
{
Dictionary<string, string> param = new Dictionary<string, string>();
param["dbname"] = new SqlConnectionStringBuilder(connectionString).InitialCatalog;
using (IDbCommand tablesCmd =
Query("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_CATALOG=@dbname", param))
using (IDataReader tables = tablesCmd.ExecuteReader())
{
while (tables.Read())
{
try
{
string tableName = (string)tables["TABLE_NAME"];
if (tableList.ContainsKey(tableName))
tableList[tableName] = tableName;
}
catch (Exception e)
{
m_log.Error(e.ToString());
}
}
tables.Close();
}
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
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));
}
#endregion
}
/// <summary>
/// Returns the version of this DB provider

View File

@ -0,0 +1,170 @@
/*
* 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 OpenMetaverse;
using OpenSim.Framework;
using System.Data.SqlClient;
namespace OpenSim.Data.MSSQL
{
/// <summary>
/// A MySQL Interface for the Presence Server
/// </summary>
public class MSSQLPresenceData : MSSQLGenericTableHandler<PresenceData>,
IPresenceData
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public MSSQLPresenceData(string connectionString, string realm) :
base(connectionString, realm, "Presence")
{
}
public PresenceData Get(UUID sessionID)
{
PresenceData[] ret = Get("SessionID",
sessionID.ToString());
if (ret.Length == 0)
return null;
return ret[0];
}
public void LogoutRegionAgents(UUID regionID)
{
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = String.Format("UPDATE {0} SET Online='false' WHERE [RegionID]=@RegionID", m_Realm);
cmd.Parameters.Add(m_database.CreateParameter("@RegionID", regionID.ToString()));
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
}
}
public bool ReportAgent(UUID sessionID, UUID regionID, string position,
string lookAt)
{
PresenceData[] pd = Get("SessionID", sessionID.ToString());
if (pd.Length == 0)
return false;
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = String.Format(@"UPDATE {0} SET
[RegionID] = @RegionID,
[Position] = @Position,
[LookAt] = @LookAt,
[Online] = 'true'
WHERE [SessionID] = @SessionID", m_Realm);
cmd.Parameters.Add(m_database.CreateParameter("@SessionID", sessionID.ToString()));
cmd.Parameters.Add(m_database.CreateParameter("@RegionID", regionID.ToString()));
cmd.Parameters.Add(m_database.CreateParameter("@Position", position.ToString()));
cmd.Parameters.Add(m_database.CreateParameter("@LookAt", lookAt.ToString()));
cmd.Connection = conn;
conn.Open();
if (cmd.ExecuteNonQuery() == 0)
return false;
}
return true;
}
public bool SetHomeLocation(string userID, UUID regionID, Vector3 position, Vector3 lookAt)
{
PresenceData[] pd = Get("UserID", userID);
if (pd.Length == 0)
return false;
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = String.Format(@"UPDATE {0} SET
[HomeRegionID] = @HomeRegionID,
[HomePosition] = @HomePosition,
[HomeLookAt] = @HomeLookAt
WHERE [UserID] = @UserID", m_Realm);
cmd.Parameters.Add(m_database.CreateParameter("@UserID", userID));
cmd.Parameters.Add(m_database.CreateParameter("@HomeRegionID", regionID.ToString()));
cmd.Parameters.Add(m_database.CreateParameter("@HomePosition", position));
cmd.Parameters.Add(m_database.CreateParameter("@HomeLookAt", lookAt));
cmd.Connection = conn;
conn.Open();
if (cmd.ExecuteNonQuery() == 0)
return false;
}
return true;
}
public void Prune(string userID)
{
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = String.Format("SELECT * from {0} WHERE [UserID] = @UserID", m_Realm);
cmd.Parameters.Add(m_database.CreateParameter("@UserID", userID));
cmd.Connection = conn;
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
List<UUID> deleteSessions = new List<UUID>();
int online = 0;
while (reader.Read())
{
if (bool.Parse(reader["Online"].ToString()))
online++;
else
deleteSessions.Add(new UUID(reader["SessionID"].ToString()));
}
if (online == 0 && deleteSessions.Count > 0)
deleteSessions.RemoveAt(0);
foreach (UUID s in deleteSessions)
Delete("SessionID", s.ToString());
}
}
}
}
}

View File

@ -129,10 +129,10 @@ namespace OpenSim.Data.MSSQL
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("@startX", startX.ToString()));
cmd.Parameters.Add(m_database.CreateParameter("@startY", startY.ToString()));
cmd.Parameters.Add(m_database.CreateParameter("@endX", endX.ToString()));
cmd.Parameters.Add(m_database.CreateParameter("@endY", endY.ToString()));
cmd.Parameters.Add(m_database.CreateParameter("@startX", startX));
cmd.Parameters.Add(m_database.CreateParameter("@startY", startY));
cmd.Parameters.Add(m_database.CreateParameter("@endX", endX));
cmd.Parameters.Add(m_database.CreateParameter("@endY", endY));
cmd.Parameters.Add(m_database.CreateParameter("@scopeID", scopeID));
conn.Open();
return RunCommand(cmd);
@ -307,5 +307,37 @@ namespace OpenSim.Data.MSSQL
}
return false;
}
public List<RegionData> GetDefaultRegions(UUID scopeID)
{
string sql = "SELECT * FROM [" + m_Realm + "] WHERE (flags & 1) <> 0";
if (scopeID != UUID.Zero)
sql += " AND ScopeID = @scopeID";
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("@scopeID", scopeID));
conn.Open();
return RunCommand(cmd);
}
}
public List<RegionData> GetFallbackRegions(UUID scopeID, int x, int y)
{
string sql = "SELECT * FROM [" + m_Realm + "] WHERE (flags & 2) <> 0";
if (scopeID != UUID.Zero)
sql += " AND ScopeID = @scopeID";
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("@scopeID", scopeID));
conn.Open();
// TODO: distance-sort results
return RunCommand(cmd);
}
}
}
}

View File

@ -36,153 +36,207 @@ using System.Text;
namespace OpenSim.Data.MSSQL
{
public class MSSQLUserAccountData : IUserAccountData
public class MSSQLUserAccountData : MSSQLGenericTableHandler<UserAccountData>,IUserAccountData
{
private string m_Realm;
private List<string> m_ColumnNames = null;
private string m_ConnectionString;
private MSSQLManager m_database;
public MSSQLUserAccountData(string connectionString, string realm)
public MSSQLUserAccountData(string connectionString, string realm) :
base(connectionString, realm, "UserAccount")
{
m_Realm = realm;
m_ConnectionString = connectionString;
m_database = new MSSQLManager(connectionString);
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
{
conn.Open();
Migration m = new Migration(conn, GetType().Assembly, "UserStore");
m.Update();
}
}
//private string m_Realm;
//private List<string> m_ColumnNames = null;
//private MSSQLManager m_database;
public List<UserAccountData> Query(UUID principalID, UUID scopeID, string query)
{
return null;
}
//public MSSQLUserAccountData(string connectionString, string realm)
//{
// m_Realm = realm;
// m_ConnectionString = connectionString;
// m_database = new MSSQLManager(connectionString);
public UserAccountData Get(UUID principalID, UUID scopeID)
{
UserAccountData ret = new UserAccountData();
ret.Data = new Dictionary<string, object>();
// using (SqlConnection conn = new SqlConnection(m_ConnectionString))
// {
// conn.Open();
// Migration m = new Migration(conn, GetType().Assembly, "UserStore");
// m.Update();
// }
//}
string sql = string.Format("select * from {0} where UUID = @principalID", m_Realm);
if (scopeID != UUID.Zero)
sql += " and ScopeID = @scopeID";
//public List<UserAccountData> Query(UUID principalID, UUID scopeID, string query)
//{
// return null;
//}
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("@principalID", principalID));
cmd.Parameters.Add(m_database.CreateParameter("@scopeID", scopeID));
//public UserAccountData Get(UUID principalID, UUID scopeID)
//{
// UserAccountData ret = new UserAccountData();
// ret.Data = new Dictionary<string, string>();
// string sql = string.Format("select * from {0} where UUID = @principalID", m_Realm);
// if (scopeID != UUID.Zero)
// sql += " and ScopeID = @scopeID";
// using (SqlConnection conn = new SqlConnection(m_ConnectionString))
// using (SqlCommand cmd = new SqlCommand(sql, conn))
// {
// cmd.Parameters.Add(m_database.CreateParameter("@principalID", principalID));
// cmd.Parameters.Add(m_database.CreateParameter("@scopeID", scopeID));
conn.Open();
using (SqlDataReader result = cmd.ExecuteReader())
// conn.Open();
// using (SqlDataReader result = cmd.ExecuteReader())
// {
// if (result.Read())
// {
// ret.PrincipalID = principalID;
// UUID scope;
// UUID.TryParse(result["ScopeID"].ToString(), out scope);
// ret.ScopeID = scope;
// if (m_ColumnNames == null)
// {
// m_ColumnNames = new List<string>();
// DataTable schemaTable = result.GetSchemaTable();
// foreach (DataRow row in schemaTable.Rows)
// m_ColumnNames.Add(row["ColumnName"].ToString());
// }
// foreach (string s in m_ColumnNames)
// {
// if (s == "UUID")
// continue;
// if (s == "ScopeID")
// continue;
// ret.Data[s] = result[s].ToString();
// }
// return ret;
// }
// }
// }
// return null;
//}
//public bool Store(UserAccountData data)
//{
// if (data.Data.ContainsKey("UUID"))
// data.Data.Remove("UUID");
// if (data.Data.ContainsKey("ScopeID"))
// data.Data.Remove("ScopeID");
// string[] fields = new List<string>(data.Data.Keys).ToArray();
// using (SqlConnection conn = new SqlConnection(m_ConnectionString))
// using (SqlCommand cmd = new SqlCommand())
// {
// StringBuilder updateBuilder = new StringBuilder();
// updateBuilder.AppendFormat("update {0} set ", m_Realm);
// bool first = true;
// foreach (string field in fields)
// {
// if (!first)
// updateBuilder.Append(", ");
// updateBuilder.AppendFormat("{0} = @{0}", field);
// first = false;
// cmd.Parameters.Add(m_database.CreateParameter("@" + field, data.Data[field]));
// }
// updateBuilder.Append(" where UUID = @principalID");
// if (data.ScopeID != UUID.Zero)
// updateBuilder.Append(" and ScopeID = @scopeID");
// cmd.CommandText = updateBuilder.ToString();
// cmd.Connection = conn;
// cmd.Parameters.Add(m_database.CreateParameter("@principalID", data.PrincipalID));
// cmd.Parameters.Add(m_database.CreateParameter("@scopeID", data.ScopeID));
// conn.Open();
// if (cmd.ExecuteNonQuery() < 1)
// {
// StringBuilder insertBuilder = new StringBuilder();
// insertBuilder.AppendFormat("insert into {0} (UUID, ScopeID, ", m_Realm);
// insertBuilder.Append(String.Join(", ", fields));
// insertBuilder.Append(") values (@principalID, @scopeID, @");
// insertBuilder.Append(String.Join(", @", fields));
// insertBuilder.Append(")");
// cmd.CommandText = insertBuilder.ToString();
// if (cmd.ExecuteNonQuery() < 1)
// {
// return false;
// }
// }
// }
// return true;
//}
//public bool Store(UserAccountData data, UUID principalID, string token)
//{
// return false;
//}
//public bool SetDataItem(UUID principalID, string item, string value)
//{
// string sql = string.Format("update {0} set {1} = @{1} where UUID = @UUID", m_Realm, item);
// using (SqlConnection conn = new SqlConnection(m_ConnectionString))
// using (SqlCommand cmd = new SqlCommand(sql, conn))
// {
// cmd.Parameters.Add(m_database.CreateParameter("@" + item, value));
// cmd.Parameters.Add(m_database.CreateParameter("@UUID", principalID));
// conn.Open();
// if (cmd.ExecuteNonQuery() > 0)
// return true;
// }
// return false;
//}
//public UserAccountData[] Get(string[] keys, string[] vals)
//{
// return null;
//}
public UserAccountData[] GetUsers(UUID scopeID, string query)
{
string[] words = query.Split(new char[] { ' ' });
for (int i = 0; i < words.Length; i++)
{
if (words[i].Length < 3)
{
if (result.Read())
{
ret.PrincipalID = principalID;
UUID scope;
UUID.TryParse(result["ScopeID"].ToString(), out scope);
ret.ScopeID = scope;
if (m_ColumnNames == null)
{
m_ColumnNames = new List<string>();
DataTable schemaTable = result.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows)
m_ColumnNames.Add(row["ColumnName"].ToString());
}
foreach (string s in m_ColumnNames)
{
if (s == "UUID")
continue;
if (s == "ScopeID")
continue;
ret.Data[s] = result[s].ToString();
}
return ret;
}
if (i != words.Length - 1)
Array.Copy(words, i + 1, words, i, words.Length - i - 1);
Array.Resize(ref words, words.Length - 1);
}
}
return null;
}
public bool Store(UserAccountData data)
{
if (data.Data.ContainsKey("UUID"))
data.Data.Remove("UUID");
if (data.Data.ContainsKey("ScopeID"))
data.Data.Remove("ScopeID");
if (words.Length == 0)
return new UserAccountData[0];
string[] fields = new List<string>(data.Data.Keys).ToArray();
if (words.Length > 2)
return new UserAccountData[0];
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand())
{
StringBuilder updateBuilder = new StringBuilder();
updateBuilder.AppendFormat("update {0} set ", m_Realm);
bool first = true;
foreach (string field in fields)
if (words.Length == 1)
{
if (!first)
updateBuilder.Append(", ");
updateBuilder.AppendFormat("{0} = @{0}", field);
first = false;
cmd.Parameters.Add(m_database.CreateParameter("@" + field, data.Data[field]));
cmd.CommandText = String.Format("select * from {0} where ([ScopeID]=@ScopeID or [ScopeID]='00000000-0000-0000-0000-000000000000') and ([FirstName] like @search or [LastName] like @search)", m_Realm);
cmd.Parameters.Add(m_database.CreateParameter("@scopeID", scopeID));
cmd.Parameters.Add(m_database.CreateParameter("@search", "%" + words[0] + "%"));
}
else
{
cmd.CommandText = String.Format("select * from {0} where ([ScopeID]=@ScopeID or [ScopeID]='00000000-0000-0000-0000-000000000000') and ([FirstName] like @searchFirst or [LastName] like @searchLast)", m_Realm);
cmd.Parameters.Add(m_database.CreateParameter("@searchFirst", "%" + words[0] + "%"));
cmd.Parameters.Add(m_database.CreateParameter("@searchLast", "%" + words[1] + "%"));
cmd.Parameters.Add(m_database.CreateParameter("@ScopeID", scopeID.ToString()));
}
updateBuilder.Append(" where UUID = @principalID");
if (data.ScopeID != UUID.Zero)
updateBuilder.Append(" and ScopeID = @scopeID");
cmd.CommandText = updateBuilder.ToString();
cmd.Connection = conn;
cmd.Parameters.Add(m_database.CreateParameter("@principalID", data.PrincipalID));
cmd.Parameters.Add(m_database.CreateParameter("@scopeID", data.ScopeID));
conn.Open();
if (cmd.ExecuteNonQuery() < 1)
{
StringBuilder insertBuilder = new StringBuilder();
insertBuilder.AppendFormat("insert into {0} (UUID, ScopeID, ", m_Realm);
insertBuilder.Append(String.Join(", ", fields));
insertBuilder.Append(") values (@principalID, @scopeID, @");
insertBuilder.Append(String.Join(", @", fields));
insertBuilder.Append(")");
cmd.CommandText = insertBuilder.ToString();
if (cmd.ExecuteNonQuery() < 1)
{
return false;
}
}
return DoQuery(cmd);
}
return true;
}
public bool SetDataItem(UUID principalID, string item, string value)
{
string sql = string.Format("update {0} set {1} = @{1} where UUID = @UUID", m_Realm, item);
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(m_database.CreateParameter("@" + item, value));
cmd.Parameters.Add(m_database.CreateParameter("@UUID", principalID));
conn.Open();
if (cmd.ExecuteNonQuery() > 0)
return true;
}
return false;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,166 @@
/*
* 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 OpenMetaverse;
using OpenSim.Framework;
using System.Data.SqlClient;
using System.Reflection;
using System.Text;
using log4net;
namespace OpenSim.Data.MSSQL
{
public class MSSQLXInventoryData : IXInventoryData
{
private static readonly ILog m_log = LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private MSSQLGenericTableHandler<XInventoryFolder> m_Folders;
private MSSQLItemHandler m_Items;
public MSSQLXInventoryData(string conn, string realm)
{
m_Folders = new MSSQLGenericTableHandler<XInventoryFolder>(
conn, "inventoryfolders", "InventoryStore");
m_Items = new MSSQLItemHandler(
conn, "inventoryitems", String.Empty);
}
public XInventoryFolder[] GetFolders(string[] fields, string[] vals)
{
return m_Folders.Get(fields, vals);
}
public XInventoryItem[] GetItems(string[] fields, string[] vals)
{
return m_Items.Get(fields, vals);
}
public bool StoreFolder(XInventoryFolder folder)
{
return m_Folders.Store(folder);
}
public bool StoreItem(XInventoryItem item)
{
return m_Items.Store(item);
}
public bool DeleteFolders(string field, string val)
{
return m_Folders.Delete(field, val);
}
public bool DeleteItems(string field, string val)
{
return m_Items.Delete(field, val);
}
public bool MoveItem(string id, string newParent)
{
return m_Items.MoveItem(id, newParent);
}
public XInventoryItem[] GetActiveGestures(UUID principalID)
{
return m_Items.GetActiveGestures(principalID);
}
public int GetAssetPermissions(UUID principalID, UUID assetID)
{
return m_Items.GetAssetPermissions(principalID, assetID);
}
}
public class MSSQLItemHandler : MSSQLGenericTableHandler<XInventoryItem>
{
public MSSQLItemHandler(string c, string t, string m) :
base(c, t, m)
{
}
public bool MoveItem(string id, string newParent)
{
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = String.Format("update {0} set parentFolderID = @ParentFolderID where inventoryID = @InventoryID", m_Realm);
cmd.Parameters.Add(m_database.CreateParameter("@ParentFolderID", newParent));
cmd.Parameters.Add(m_database.CreateParameter("@InventoryID", id));
cmd.Connection = conn;
conn.Open();
return cmd.ExecuteNonQuery() == 0 ? false : true;
}
}
public XInventoryItem[] GetActiveGestures(UUID principalID)
{
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = String.Format("select * from inventoryitems where avatarId = @uuid and assetType = @type and flags = 1", m_Realm);
cmd.Parameters.Add(m_database.CreateParameter("@uuid", principalID.ToString()));
cmd.Parameters.Add(m_database.CreateParameter("@type", (int)AssetType.Gesture));
cmd.Connection = conn;
conn.Open();
return DoQuery(cmd);
}
}
public int GetAssetPermissions(UUID principalID, UUID assetID)
{
using (SqlConnection conn = new SqlConnection(m_ConnectionString))
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = String.Format("select bit_or(inventoryCurrentPermissions) as inventoryCurrentPermissions from inventoryitems where avatarID = @PrincipalID and assetID = @AssetID group by assetID", m_Realm);
cmd.Parameters.Add(m_database.CreateParameter("@PrincipalID", principalID.ToString()));
cmd.Parameters.Add(m_database.CreateParameter("@AssetID", assetID.ToString()));
cmd.Connection = conn;
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
int perms = 0;
if (reader.Read())
{
perms = Convert.ToInt32(reader["inventoryCurrentPermissions"]);
}
return perms;
}
}
}
}
}

View File

@ -0,0 +1,17 @@
BEGIN TRANSACTION
CREATE TABLE [auth] (
[uuid] [uniqueidentifier] NOT NULL default '00000000-0000-0000-0000-000000000000',
[passwordHash] [varchar](32) NOT NULL,
[passwordSalt] [varchar](32) NOT NULL,
[webLoginKey] [varchar](255) NOT NULL,
[accountType] VARCHAR(32) NOT NULL DEFAULT 'UserAccount',
) ON [PRIMARY]
CREATE TABLE [tokens] (
[uuid] [uniqueidentifier] NOT NULL default '00000000-0000-0000-0000-000000000000',
[token] [varchar](255) NOT NULL,
[validity] [datetime] NOT NULL )
ON [PRIMARY]
COMMIT

View File

@ -0,0 +1,15 @@
BEGIN TRANSACTION
CREATE TABLE [Avatars] (
[PrincipalID] uniqueidentifier NOT NULL,
[Name] varchar(32) NOT NULL,
[Value] varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY CLUSTERED
(
[PrincipalID] ASC, [Name] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
COMMIT

View File

@ -0,0 +1,11 @@
BEGIN TRANSACTION
CREATE TABLE [Friends] (
[PrincipalID] uniqueidentifier NOT NULL,
[FriendID] varchar(255) NOT NULL,
[Flags] char(16) NOT NULL DEFAULT '0',
[Offered] varchar(32) NOT NULL DEFAULT 0)
ON [PRIMARY]
COMMIT

View File

@ -0,0 +1,19 @@
BEGIN TRANSACTION
CREATE TABLE [Presence] (
[UserID] varchar(255) NOT NULL,
[RegionID] uniqueidentifier NOT NULL,
[SessionID] uniqueidentifier NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000',
[SecureSessionID] uniqueidentifier NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000',
[Online] char(5) NOT NULL DEFAULT 'false',
[Login] char(16) NOT NULL DEFAULT '0',
[Logout] char(16) NOT NULL DEFAULT '0',
[Position] char(64) NOT NULL DEFAULT '<0,0,0>',
[LookAt] char(64) NOT NULL DEFAULT '<0,0,0>',
[HomeRegionID] uniqueidentifier NOT NULL,
[HomePosition] CHAR(64) NOT NULL DEFAULT '<0,0,0>',
[HomeLookAt] CHAR(64) NOT NULL DEFAULT '<0,0,0>',
)
ON [PRIMARY]
COMMIT

View File

@ -0,0 +1,6 @@
BEGIN TRANSACTION
INSERT INTO auth (UUID, passwordHash, passwordSalt, webLoginKey, accountType) SELECT [UUID] AS UUID, [passwordHash] AS passwordHash, [passwordSalt] AS passwordSalt, [webLoginKey] AS webLoginKey, 'UserAccount' as [accountType] FROM users;
COMMIT

View File

@ -0,0 +1,6 @@
BEGIN TRANSACTION
INSERT INTO Friends (PrincipalID, FriendID, Flags, Offered) SELECT [ownerID], [friendID], [friendPerms], 0 FROM userfriends;
COMMIT

View File

@ -0,0 +1,6 @@
BEGIN TRANSACTION
CREATE UNIQUE INDEX SessionID ON Presence(SessionID);
CREATE INDEX UserID ON Presence(UserID);
COMMIT

View File

@ -0,0 +1,12 @@
BEGIN TRANSACTION
INSERT INTO UserAccounts (PrincipalID, ScopeID, FirstName, LastName, Email, ServiceURLs, Created) SELECT [UUID] AS PrincipalID, '00000000-0000-0000-0000-000000000000' AS ScopeID,
username AS FirstName,
lastname AS LastName,
email as Email, (
'AssetServerURI=' +
userAssetURI + ' InventoryServerURI=' + userInventoryURI + ' GatewayURI= HomeURI=') AS ServiceURLs,
created as Created FROM users;
COMMIT

View File

@ -0,0 +1,9 @@
BEGIN TRANSACTION
ALTER TABLE regions ADD [flags] integer NOT NULL DEFAULT 0;
CREATE INDEX [flags] ON regions(flags);
ALTER TABLE [regions] ADD [last_seen] integer NOT NULL DEFAULT 0;
ALTER TABLE [regions] ADD [PrincipalID] uniqueidentifier NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000';
ALTER TABLE [regions] ADD [Token] varchar(255) NOT NULL DEFAULT 0;
COMMIT

View File

@ -128,7 +128,7 @@ namespace OpenSim.Data
return;
// to prevent people from killing long migrations.
m_log.InfoFormat("[MIGRATIONS] Upgrading {0} to latest revision.", _type);
m_log.InfoFormat("[MIGRATIONS] Upgrading {0} to latest revision {1}.", _type, migrations.Keys[migrations.Count - 1]);
m_log.Info("[MIGRATIONS] NOTE: this may take a while, don't interupt this process!");
DbCommand cmd = _conn.CreateCommand();
@ -138,7 +138,15 @@ namespace OpenSim.Data
cmd.CommandText = kvp.Value;
// we need to up the command timeout to infinite as we might be doing long migrations.
cmd.CommandTimeout = 0;
cmd.ExecuteNonQuery();
try
{
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
m_log.DebugFormat("[MIGRATIONS] Cmd was {0}", cmd.CommandText);
m_log.DebugFormat("[MIGRATIONS]: An error has occurred in the migration {0}.\n This may mean you could see errors trying to run OpenSim. If you see database related errors, you will need to fix the issue manually. Continuing.", e.Message);
}
if (version == 0)
{
@ -246,7 +254,8 @@ namespace OpenSim.Data
if (m.Success)
{
int version = int.Parse(m.Groups[1].ToString());
if (version > after) {
if (version > after)
{
using (Stream resource = _assem.GetManifestResourceStream(s))
{
using (StreamReader resourceReader = new StreamReader(resource))

View File

@ -122,7 +122,7 @@ namespace OpenSim.Data.MySQL
{
if (dbReader.Read())
{
asset = new AssetBase(assetID, (string)dbReader["name"], (sbyte)dbReader["assetType"]);
asset = new AssetBase(assetID, (string)dbReader["name"], (sbyte)dbReader["assetType"], UUID.Zero.ToString());
asset.Data = (byte[])dbReader["data"];
asset.Description = (string)dbReader["description"];

View File

@ -26,51 +26,42 @@
*/
using System;
using System.Reflection;
using Nini.Config;
using OpenSim.Data;
using OpenSim.Services.Interfaces;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Threading;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using MySql.Data.MySqlClient;
namespace OpenSim.Services.UserAccountService
namespace OpenSim.Data.MySQL
{
public class UserAccountService : UserAccountServiceBase, IUserAccountService
/// <summary>
/// A MySQL Interface for the Grid Server
/// </summary>
public class MySQLAvatarData : MySQLGenericTableHandler<AvatarBaseData>,
IAvatarData
{
public UserAccountService(IConfigSource config) : base(config)
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public MySQLAvatarData(string connectionString, string realm) :
base(connectionString, realm, "Avatar")
{
}
public UserAccount GetUserAccount(UUID scopeID, string firstName,
string lastName)
public bool Delete(UUID principalID, string name)
{
return null;
}
MySqlCommand cmd = new MySqlCommand();
public UserAccount GetUserAccount(UUID scopeID, UUID userID)
{
return null;
}
cmd.CommandText = String.Format("delete from {0} where `PrincipalID` = ?PrincipalID and `Name` = ?Name", m_Realm);
cmd.Parameters.AddWithValue("?PrincipalID", principalID.ToString());
cmd.Parameters.AddWithValue("?Name", name);
if (ExecuteNonQuery(cmd) > 0)
return true;
public bool SetHomePosition(UserAccount data, UUID regionID, UUID regionSecret)
{
return false;
}
public bool SetUserAccount(UserAccount data, UUID principalID, string token)
{
return false;
}
public bool CreateUserAccount(UserAccount data, UUID principalID, string token)
{
return false;
}
public List<UserAccount> GetUserAccount(UUID scopeID,
string query)
{
return null;
}
}
}

View File

@ -0,0 +1,68 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the 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 OpenMetaverse;
using OpenSim.Framework;
using MySql.Data.MySqlClient;
namespace OpenSim.Data.MySQL
{
public class MySqlFriendsData : MySQLGenericTableHandler<FriendsData>, IFriendsData
{
public MySqlFriendsData(string connectionString, string realm)
: base(connectionString, realm, "FriendsStore")
{
}
public bool Delete(UUID principalID, string friend)
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = String.Format("delete from {0} where PrincipalID = ?PrincipalID and Friend = ?Friend", m_Realm);
cmd.Parameters.AddWithValue("?PrincipalID", principalID.ToString());
cmd.Parameters.AddWithValue("?Friend", friend);
ExecuteNonQuery(cmd);
return true;
}
public FriendsData[] GetFriends(UUID principalID)
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = String.Format("select a.*,case when b.Flags is null then -1 else b.Flags end as TheirFlags from {0} as a left join {0} as b on a.PrincipalID = b.Friend and a.Friend = b.PrincipalID where a.PrincipalID = ?PrincipalID", m_Realm);
cmd.Parameters.AddWithValue("?PrincipalID", principalID.ToString());
return DoQuery(cmd);
}
}
}

View File

@ -39,10 +39,6 @@ namespace OpenSim.Data.MySQL
{
public class MySQLGenericTableHandler<T> : MySqlFramework where T: class, new()
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected Dictionary<string, FieldInfo> m_Fields =
new Dictionary<string, FieldInfo>();
@ -99,12 +95,12 @@ namespace OpenSim.Data.MySQL
}
}
public T[] Get(string field, string key)
public virtual T[] Get(string field, string key)
{
return Get(new string[] { field }, new string[] { key });
}
public T[] Get(string[] fields, string[] keys)
public virtual T[] Get(string[] fields, string[] keys)
{
if (fields.Length != keys.Length)
return new T[0];
@ -198,7 +194,7 @@ namespace OpenSim.Data.MySQL
return result.ToArray();
}
public T[] Get(string where)
public virtual T[] Get(string where)
{
using (MySqlCommand cmd = new MySqlCommand())
{
@ -212,7 +208,7 @@ namespace OpenSim.Data.MySQL
}
}
public bool Store(T row)
public virtual bool Store(T row)
{
using (MySqlCommand cmd = new MySqlCommand())
{
@ -252,7 +248,7 @@ namespace OpenSim.Data.MySQL
}
}
public bool Delete(string field, string val)
public virtual bool Delete(string field, string val)
{
using (MySqlCommand cmd = new MySqlCommand())
{

View File

@ -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
{
/// <summary>
/// A MySQL Interface for the Grid Server
/// </summary>
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);
}
/// <summary>
/// <para>Initialises Grid interface</para>
/// <para>
/// <list type="bullet">
/// <item>Loads and initialises the MySQL storage plugin</item>
/// <item>Warns and uses the obsolete mysql_connection.ini if connect string is empty.</item>
/// <item>Check for migration</item>
/// </list>
/// </para>
/// </summary>
/// <param name="connect">connect string.</param>
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();
}
}
/// <summary>
/// Shuts down the grid interface
/// </summary>
override public void Dispose()
{
}
/// <summary>
/// Returns the plugin name
/// </summary>
/// <returns>Plugin name</returns>
override public string Name
{
get { return "MySql OpenGridData"; }
}
/// <summary>
/// Returns the plugin version
/// </summary>
/// <returns>Plugin version</returns>
override public string Version
{
get { return "0.1"; }
}
/// <summary>
/// Returns all the specified region profiles within coordates -- coordinates are inclusive
/// </summary>
/// <param name="xmin">Minimum X coordinate</param>
/// <param name="ymin">Minimum Y coordinate</param>
/// <param name="xmax">Maximum X coordinate</param>
/// <param name="ymax">Maximum Y coordinate</param>
/// <returns>Array of sim profiles</returns>
override public RegionProfileData[] GetProfilesInRange(uint xmin, uint ymin, uint xmax, uint ymax)
{
try
{
Dictionary<string, object> param = new Dictionary<string, object>();
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<RegionProfileData> rows = new List<RegionProfileData>();
while ((row = m_database.readSimRow(reader)) != null)
rows.Add(row);
return rows.ToArray();
}
}
}
}
catch (Exception e)
{
m_log.Error(e.Message, e);
return null;
}
}
/// <summary>
/// Returns up to maxNum profiles of regions that have a name starting with namePrefix
/// </summary>
/// <param name="name">The name to match against</param>
/// <param name="maxNum">Maximum number of profiles to return</param>
/// <returns>A list of sim profiles</returns>
override public List<RegionProfileData> GetRegionsByName(string namePrefix, uint maxNum)
{
try
{
Dictionary<string, object> param = new Dictionary<string, object>();
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<RegionProfileData> rows = new List<RegionProfileData>();
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;
}
}
/// <summary>
/// Returns a sim profile from it's location
/// </summary>
/// <param name="handle">Region location handle</param>
/// <returns>Sim profile</returns>
override public RegionProfileData GetProfileByHandle(ulong handle)
{
try
{
Dictionary<string, object> param = new Dictionary<string, object>();
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;
}
}
/// <summary>
/// Returns a sim profile from it's UUID
/// </summary>
/// <param name="uuid">The region UUID</param>
/// <returns>The sim profile</returns>
override public RegionProfileData GetProfileByUUID(UUID uuid)
{
try
{
Dictionary<string, object> param = new Dictionary<string, object>();
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;
}
}
/// <summary>
/// Returns a sim profile from it's Region name string
/// </summary>
/// <returns>The sim profile</returns>
override public RegionProfileData GetProfileByString(string regionName)
{
if (regionName.Length > 2)
{
try
{
Dictionary<string, object> param = new Dictionary<string, object>();
// 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;
}
/// <summary>
/// Adds a new profile to the database
/// </summary>
/// <param name="profile">The profile to add</param>
/// <returns>Successful?</returns>
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;
}
}
/// <summary>
/// Deletes a sim profile from the database
/// </summary>
/// <param name="uuid">the sim UUID</param>
/// <returns>Successful?</returns>
//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;
}
}
/// <summary>
/// DEPRECATED. Attempts to authenticate a region by comparing a shared secret.
/// </summary>
/// <param name="uuid">The UUID of the challenger</param>
/// <param name="handle">The attempted regionHandle of the challenger</param>
/// <param name="authkey">The secret</param>
/// <returns>Whether the secret and regionhandle match the database entry for UUID</returns>
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);
}
/// <summary>
/// NOT YET FUNCTIONAL. Provides a cryptographic authentication of a region
/// </summary>
/// <remarks>This requires a security audit.</remarks>
/// <param name="uuid"></param>
/// <param name="handle"></param>
/// <param name="authhash"></param>
/// <param name="challenge"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Adds a location reservation
/// </summary>
/// <param name="x">x coordinate</param>
/// <param name="y">y coordinate</param>
/// <returns></returns>
override public ReservationData GetReservationAtPoint(uint x, uint y)
{
try
{
Dictionary<string, object> param = new Dictionary<string, object>();
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;
}
}
}
}

View File

@ -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
{
/// <summary>
/// An interface to the log database for MySQL
/// </summary>
internal class MySQLLogData : ILogDataPlugin
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// The database manager
/// </summary>
public MySQLManager database;
public void Initialise()
{
m_log.Info("[MySQLLogData]: " + Name + " cannot be default-initialized!");
throw new PluginNotInitialisedException (Name);
}
/// <summary>
/// Artificial constructor called when the plugin is loaded
/// Uses the obsolete mysql_connection.ini if connect string is empty.
/// </summary>
/// <param name="connect">connect string</param>
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();
}
}
/// <summary></summary>
/// <param name="m"></param>
private void TestTables(Migration m)
{
// under migrations, bail
if (m.Version > 0)
return;
Dictionary<string, string> tableList = new Dictionary<string, string>();
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;
}
/// <summary>
/// Saves a log item to the database
/// </summary>
/// <param name="serverDaemon">The daemon triggering the event</param>
/// <param name="target">The target of the action (region / agent UUID, etc)</param>
/// <param name="methodCall">The method call where the problem occured</param>
/// <param name="arguments">The arguments passed to the method</param>
/// <param name="priority">How critical is this?</param>
/// <param name="logMessage">The message to log</param>
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
{
}
}
/// <summary>
/// Returns the name of this DB provider
/// </summary>
/// <returns>A string containing the DB provider name</returns>
public string Name
{
get { return "MySQL Logdata Interface";}
}
/// <summary>
/// Closes the database provider
/// </summary>
/// <remarks>do nothing</remarks>
public void Dispose()
{
// Do nothing.
}
/// <summary>
/// Returns the version of this DB provider
/// </summary>
/// <returns>A string containing the provider version</returns>
public string Version
{
get { return "0.1"; }
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,155 @@
/*
* 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 OpenMetaverse;
using OpenSim.Framework;
using MySql.Data.MySqlClient;
namespace OpenSim.Data.MySQL
{
/// <summary>
/// A MySQL Interface for the Grid Server
/// </summary>
public class MySQLPresenceData : MySQLGenericTableHandler<PresenceData>,
IPresenceData
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public MySQLPresenceData(string connectionString, string realm) :
base(connectionString, realm, "Presence")
{
}
public PresenceData Get(UUID sessionID)
{
PresenceData[] ret = Get("SessionID",
sessionID.ToString());
if (ret.Length == 0)
return null;
return ret[0];
}
public void LogoutRegionAgents(UUID regionID)
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = String.Format("update {0} set Online='false' where `RegionID`=?RegionID", m_Realm);
cmd.Parameters.AddWithValue("?RegionID", regionID.ToString());
ExecuteNonQuery(cmd);
}
public bool ReportAgent(UUID sessionID, UUID regionID, string position,
string lookAt)
{
PresenceData[] pd = Get("SessionID", sessionID.ToString());
if (pd.Length == 0)
return false;
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = String.Format("update {0} set RegionID=?RegionID, Position=?Position, LookAt=?LookAt, Online='true' where `SessionID`=?SessionID", m_Realm);
cmd.Parameters.AddWithValue("?SessionID", sessionID.ToString());
cmd.Parameters.AddWithValue("?RegionID", regionID.ToString());
cmd.Parameters.AddWithValue("?Position", position.ToString());
cmd.Parameters.AddWithValue("?LookAt", lookAt.ToString());
if (ExecuteNonQuery(cmd) == 0)
return false;
return true;
}
public bool SetHomeLocation(string userID, UUID regionID, Vector3 position, Vector3 lookAt)
{
PresenceData[] pd = Get("UserID", userID);
if (pd.Length == 0)
return false;
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = String.Format("update {0} set HomeRegionID=?HomeRegionID, HomePosition=?HomePosition, HomeLookAt=?HomeLookAt where UserID=?UserID", m_Realm);
cmd.Parameters.AddWithValue("?UserID", userID);
cmd.Parameters.AddWithValue("?HomeRegionID", regionID.ToString());
cmd.Parameters.AddWithValue("?HomePosition", position);
cmd.Parameters.AddWithValue("?HomeLookAt", lookAt);
if (ExecuteNonQuery(cmd) == 0)
return false;
return true;
}
public void Prune(string userID)
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = String.Format("select * from {0} where UserID=?UserID", m_Realm);
cmd.Parameters.AddWithValue("?UserID", userID);
;
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
cmd.Connection = dbcon;
using (IDataReader reader = cmd.ExecuteReader())
{
List<UUID> deleteSessions = new List<UUID>();
int online = 0;
while(reader.Read())
{
if (bool.Parse(reader["Online"].ToString()))
online++;
else
deleteSessions.Add(new UUID(reader["SessionID"].ToString()));
}
if (online == 0 && deleteSessions.Count > 0)
deleteSessions.RemoveAt(0);
foreach (UUID s in deleteSessions)
Delete("SessionID", s.ToString());
}
}
}
}
}

View File

@ -283,5 +283,31 @@ namespace OpenSim.Data.MySQL
return false;
}
public List<RegionData> GetDefaultRegions(UUID scopeID)
{
string command = "select * from `"+m_Realm+"` where (flags & 1) <> 0";
if (scopeID != UUID.Zero)
command += " and ScopeID = ?scopeID";
MySqlCommand cmd = new MySqlCommand(command);
cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
return RunCommand(cmd);
}
public List<RegionData> GetFallbackRegions(UUID scopeID, int x, int y)
{
string command = "select * from `"+m_Realm+"` where (flags & 2) <> 0";
if (scopeID != UUID.Zero)
command += " and ScopeID = ?scopeID";
MySqlCommand cmd = new MySqlCommand(command);
cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
// TODO: distance-sort results
return RunCommand(cmd);
}
}
}

View File

@ -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;
}
}
}

View File

@ -35,150 +35,50 @@ using MySql.Data.MySqlClient;
namespace OpenSim.Data.MySQL
{
public class MySqlUserAccountData : MySqlFramework, IUserAccountData
public class MySqlUserAccountData : MySQLGenericTableHandler<UserAccountData>, IUserAccountData
{
private string m_Realm;
private List<string> m_ColumnNames;
// private string m_connectionString;
public MySqlUserAccountData(string connectionString, string realm)
: base(connectionString)
: base(connectionString, realm, "UserAccount")
{
m_Realm = realm;
m_connectionString = connectionString;
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
Migration m = new Migration(dbcon, GetType().Assembly, "UserStore");
m.Update();
}
}
public List<UserAccountData> Query(UUID principalID, UUID scopeID, string query)
public UserAccountData[] GetUsers(UUID scopeID, string query)
{
return null;
}
string[] words = query.Split(new char[] {' '});
public UserAccountData Get(UUID principalID, UUID scopeID)
{
UserAccountData ret = new UserAccountData();
ret.Data = new Dictionary<string, object>();
string command = "select * from `"+m_Realm+"` where UUID = ?principalID";
if (scopeID != UUID.Zero)
command += " and ScopeID = ?scopeID";
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
for (int i = 0 ; i < words.Length ; i++)
{
dbcon.Open();
MySqlCommand cmd = new MySqlCommand(command, dbcon);
cmd.Parameters.AddWithValue("?principalID", principalID.ToString());
cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
IDataReader result = cmd.ExecuteReader();
if (result.Read())
if (words[i].Length < 3)
{
ret.PrincipalID = principalID;
UUID scope;
UUID.TryParse(result["ScopeID"].ToString(), out scope);
ret.ScopeID = scope;
if (m_ColumnNames == null)
{
m_ColumnNames = new List<string>();
DataTable schemaTable = result.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows)
m_ColumnNames.Add(row["ColumnName"].ToString());
}
foreach (string s in m_ColumnNames)
{
if (s == "UUID")
continue;
if (s == "ScopeID")
continue;
ret.Data[s] = result[s].ToString();
}
return ret;
}
else
{
return null;
}
}
}
public bool Store(UserAccountData data)
{
if (data.Data.ContainsKey("UUID"))
data.Data.Remove("UUID");
if (data.Data.ContainsKey("ScopeID"))
data.Data.Remove("ScopeID");
string[] fields = new List<string>(data.Data.Keys).ToArray();
using (MySqlCommand cmd = new MySqlCommand())
{
string update = "update `" + m_Realm + "` set ";
bool first = true;
foreach (string field in fields)
{
if (!first)
update += ", ";
update += "`" + field + "` = ?" + field;
first = false;
cmd.Parameters.AddWithValue("?" + field, data.Data[field]);
}
update += " where UUID = ?principalID";
if (data.ScopeID != UUID.Zero)
update += " and ScopeID = ?scopeID";
cmd.CommandText = update;
cmd.Parameters.AddWithValue("?principalID", data.PrincipalID.ToString());
cmd.Parameters.AddWithValue("?scopeID", data.ScopeID.ToString());
if (ExecuteNonQuery(cmd) < 1)
{
string insert = "insert into `" + m_Realm + "` (`UUID`, `ScopeID`, `" +
String.Join("`, `", fields) +
"`) values (?principalID, ?scopeID, ?" + String.Join(", ?", fields) + ")";
cmd.CommandText = insert;
if (ExecuteNonQuery(cmd) < 1)
{
cmd.Dispose();
return false;
}
if (i != words.Length - 1)
Array.Copy(words, i + 1, words, i, words.Length - i - 1);
Array.Resize(ref words, words.Length - 1);
}
}
return true;
}
if (words.Length == 0)
return new UserAccountData[0];
public bool SetDataItem(UUID principalID, string item, string value)
{
using (MySqlCommand cmd = new MySqlCommand("update `" + m_Realm + "` set `" +
item + "` = ?" + item + " where UUID = ?UUID"))
if (words.Length > 2)
return new UserAccountData[0];
MySqlCommand cmd = new MySqlCommand();
if (words.Length == 1)
{
cmd.Parameters.AddWithValue("?" + item, value);
cmd.Parameters.AddWithValue("?UUID", principalID.ToString());
if (ExecuteNonQuery(cmd) > 0)
return true;
cmd.CommandText = String.Format("select * from {0} where (ScopeID=?ScopeID or ScopeID='00000000-0000-0000-0000-000000000000') and (FirstName like ?search or LastName like ?search)", m_Realm);
cmd.Parameters.AddWithValue("?search", "%" + words[0] + "%");
cmd.Parameters.AddWithValue("?ScopeID", scopeID.ToString());
}
else
{
cmd.CommandText = String.Format("select * from {0} where (ScopeID=?ScopeID or ScopeID='00000000-0000-0000-0000-000000000000') and (FirstName like ?searchFirst or LastName like ?searchLast)", m_Realm);
cmd.Parameters.AddWithValue("?searchFirst", "%" + words[0] + "%");
cmd.Parameters.AddWithValue("?searchLast", "%" + words[1] + "%");
cmd.Parameters.AddWithValue("?ScopeID", scopeID.ToString());
}
return false;
return DoQuery(cmd);
}
}
}

View File

@ -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
{
/// <summary>
/// A database interface class to a user profile storage system
/// </summary>
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);
}
/// <summary>
/// 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
/// </summary>
/// <param name="connect">connect string.</param>
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<string, object> param = new Dictionary<string, object>();
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<string, object> param = new Dictionary<string, object>();
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<string, object> param = new Dictionary<string, object>();
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<string, object> param = new Dictionary<string, object>();
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<FriendListItem> GetUserFriendList(UUID friendlistowner)
{
List<FriendListItem> Lfli = new List<FriendListItem>();
Dictionary<string, object> param = new Dictionary<string, object>();
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<UUID, FriendRegionInfo> GetFriendRegionInfos (List<UUID> uuids)
{
Dictionary<UUID, FriendRegionInfo> infos = new Dictionary<UUID,FriendRegionInfo>();
try
{
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
foreach (UUID uuid in uuids)
{
Dictionary<string, object> param = new Dictionary<string, object>();
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<AvatarPickerAvatar> GeneratePickerResults(UUID queryID, string query)
{
List<AvatarPickerAvatar> returnlist = new List<AvatarPickerAvatar>();
Regex objAlphaNumericPattern = new Regex("[^a-zA-Z0-9]");
string[] querysplit;
querysplit = query.Split(' ');
if (querysplit.Length > 1 && querysplit[1].Trim() != String.Empty)
{
Dictionary<string, object> param = new Dictionary<string, object>();
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<string, object> param = new Dictionary<string, object>();
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;
}
/// <summary>
/// See IUserDataPlugin
/// </summary>
/// <param name="uuid">User UUID</param>
/// <returns>User profile data</returns>
public override UserProfileData GetUserByUUID(UUID uuid)
{
try
{
Dictionary<string, object> param = new Dictionary<string, object>();
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;
}
}
/// <summary>
/// Returns a user session searching by name
/// </summary>
/// <param name="name">The account name : "Username Lastname"</param>
/// <returns>The users session</returns>
public override UserAgentData GetAgentByName(string name)
{
return GetAgentByName(name.Split(' ')[0], name.Split(' ')[1]);
}
/// <summary>
/// Returns a user session by account name
/// </summary>
/// <param name="user">First part of the users account name</param>
/// <param name="last">Second part of the users account name</param>
/// <returns>The users session</returns>
public override UserAgentData GetAgentByName(string user, string last)
{
UserProfileData profile = GetUserByName(user, last);
return GetAgentByUUID(profile.ID);
}
/// <summary>
/// </summary>
/// <param name="AgentID"></param>
/// <param name="WebLoginKey"></param>
/// <remarks>is it still used ?</remarks>
public override void StoreWebLoginKey(UUID AgentID, UUID WebLoginKey)
{
Dictionary<string, string> param = new Dictionary<string, string>();
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;
}
}
/// <summary>
/// Returns an agent session by account UUID
/// </summary>
/// <param name="uuid">The accounts UUID</param>
/// <returns>The users session</returns>
public override UserAgentData GetAgentByUUID(UUID uuid)
{
try
{
Dictionary<string, object> param = new Dictionary<string, object>();
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;
}
}
/// <summary>
/// Creates a new users profile
/// </summary>
/// <param name="user">The user profile to create</param>
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);
}
}
/// <summary>
/// Creates a new agent
/// </summary>
/// <param name="agent">The agent to create</param>
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);
}
}
/// <summary>
/// Updates a user profile stored in the DB
/// </summary>
/// <param name="user">The profile data to use to update the DB</param>
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;
}
}
/// <summary>
/// Performs a money transfer request between two accounts
/// </summary>
/// <param name="from">The senders account ID</param>
/// <param name="to">The receivers account ID</param>
/// <param name="amount">The amount to transfer</param>
/// <returns>Success?</returns>
public override bool MoneyTransferRequest(UUID from, UUID to, uint amount)
{
return false;
}
/// <summary>
/// Performs an inventory transfer request between two accounts
/// </summary>
/// <remarks>TODO: Move to inventory server</remarks>
/// <param name="from">The senders account ID</param>
/// <param name="to">The receivers account ID</param>
/// <param name="item">The item to transfer</param>
/// <returns>Success?</returns>
public override bool InventoryTransferRequest(UUID from, UUID to, UUID item)
{
return false;
}
public override AvatarAppearance GetUserAppearance(UUID user)
{
try
{
Dictionary<string, object> param = new Dictionary<string, object>();
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;
}
}
/// <summary>
/// Updates an avatar appearence
/// </summary>
/// <param name="user">The user UUID</param>
/// <param name="appearance">The avatar appearance</param>
// 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);
}
}
/// <summary>
/// Database provider name
/// </summary>
/// <returns>Provider name</returns>
public override string Name
{
get { return "MySQL Userdata Interface"; }
}
/// <summary>
/// Database provider version
/// </summary>
/// <returns>provider version</returns>
public override string Version
{
get { return "0.1"; }
}
public Hashtable GetUserAttachments(UUID agentID)
{
Dictionary<string, object> param = new Dictionary<string, object>();
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<string, string> param = new Dictionary<string, string>();
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<string, string> param = new Dictionary<string, string>();
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;
}
}
}
}

View File

@ -41,9 +41,6 @@ namespace OpenSim.Data.MySQL
/// </summary>
public class MySQLXInventoryData : IXInventoryData
{
private static readonly ILog m_log = LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private MySQLGenericTableHandler<XInventoryFolder> m_Folders;
private MySqlItemHandler m_Items;

View File

@ -0,0 +1,5 @@
BEGIN;
CREATE TABLE Avatars (PrincipalID CHAR(36) NOT NULL, Name VARCHAR(32) NOT NULL, Value VARCHAR(255) NOT NULL DEFAULT '', PRIMARY KEY(PrincipalID, Name), KEY(PrincipalID));
COMMIT;

View File

@ -0,0 +1,9 @@
BEGIN;
CREATE TABLE `Friends` (
`PrincipalID` CHAR(36) NOT NULL,
`FriendID` VARCHAR(255) NOT NULL,
`Flags` CHAR(16) NOT NULL DEFAULT '0'
) ENGINE=InnoDB;
COMMIT;

View File

@ -0,0 +1,5 @@
BEGIN;
CREATE TABLE `Friends` (`PrincipalID` CHAR(36) NOT NULL, `Friend` VARCHAR(255) NOT NULL, `Flags` VARCHAR(16) NOT NULL DEFAULT 0, `Offered` VARCHAR(32) NOT NULL DEFAULT 0, PRIMARY KEY(`PrincipalID`, `Friend`), KEY(`PrincipalID`));
COMMIT;

View File

@ -0,0 +1,15 @@
BEGIN;
CREATE TABLE `Presence` (
`UserID` VARCHAR(255) NOT NULL,
`RegionID` CHAR(36) NOT NULL,
`SessionID` CHAR(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000',
`SecureSessionID` CHAR(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000',
`Online` CHAR(5) NOT NULL DEFAULT 'false',
`Login` CHAR(16) NOT NULL DEFAULT '0',
`Logout` CHAR(16) NOT NULL DEFAULT '0',
`Position` CHAR(64) NOT NULL DEFAULT '<0,0,0>',
`LookAt` CHAR(64) NOT NULL DEFAULT '<0,0,0>'
) ENGINE=InnoDB;
COMMIT;

View File

@ -0,0 +1,13 @@
BEGIN;
CREATE TABLE `UserAccounts` (
`PrincipalID` CHAR(36) NOT NULL,
`ScopeID` CHAR(36) NOT NULL,
`FirstName` VARCHAR(64) NOT NULL,
`LastName` VARCHAR(64) NOT NULL,
`Email` VARCHAR(64),
`ServiceURLs` TEXT,
`Created` INT(11)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
COMMIT;

View File

@ -0,0 +1,5 @@
BEGIN;
INSERT INTO auth (UUID, passwordHash, passwordSalt, webLoginKey) SELECT `UUID` AS UUID, `passwordHash` AS passwordHash, `passwordSalt` AS passwordSalt, `webLoginKey` AS webLoginKey FROM users;
COMMIT;

View File

@ -0,0 +1,5 @@
BEGIN;
INSERT INTO Friends (PrincipalID, FriendID, Flags) SELECT ownerID, friendID, friendPerms FROM userfriends;
COMMIT;

View File

@ -0,0 +1,5 @@
BEGIN;
INSERT INTO `Friends` SELECT `ownerID`, `friendID`, `friendPerms`, 0 FROM `userfriends`;
COMMIT;

View File

@ -0,0 +1,7 @@
BEGIN;
ALTER TABLE Presence ADD COLUMN `HomeRegionID` CHAR(36) NOT NULL;
ALTER TABLE Presence ADD COLUMN `HomePosition` CHAR(64) NOT NULL DEFAULT '<0,0,0>';
ALTER TABLE Presence ADD COLUMN `HomeLookAt` CHAR(64) NOT NULL DEFAULT '<0,0,0>';
COMMIT;

View File

@ -0,0 +1,5 @@
BEGIN;
INSERT INTO UserAccounts (PrincipalID, ScopeID, FirstName, LastName, Email, ServiceURLs, Created) SELECT `UUID` AS PrincipalID, '00000000-0000-0000-0000-000000000000' AS ScopeID, username AS FirstName, lastname AS LastName, email as Email, CONCAT('AssetServerURI=', userAssetURI, ' InventoryServerURI=', userInventoryURI, ' GatewayURI= HomeURI=') AS ServiceURLs, created as Created FROM users;
COMMIT;

View File

@ -0,0 +1,5 @@
BEGIN;
ALTER TABLE `auth` ADD COLUMN `accountType` VARCHAR(32) NOT NULL DEFAULT 'UserAccount';
COMMIT;

View File

@ -0,0 +1,6 @@
BEGIN;
CREATE UNIQUE INDEX SessionID ON Presence(SessionID);
CREATE INDEX UserID ON Presence(UserID);
COMMIT;

View File

@ -0,0 +1,9 @@
BEGIN;
CREATE UNIQUE INDEX PrincipalID ON UserAccounts(PrincipalID);
CREATE INDEX Email ON UserAccounts(Email);
CREATE INDEX FirstName ON UserAccounts(FirstName);
CREATE INDEX LastName ON UserAccounts(LastName);
CREATE INDEX Name ON UserAccounts(FirstName,LastName);
COMMIT;

View File

@ -0,0 +1,8 @@
BEGIN;
ALTER TABLE UserAccounts ADD COLUMN UserLevel integer NOT NULL DEFAULT 0;
ALTER TABLE UserAccounts ADD COLUMN UserFlags integer NOT NULL DEFAULT 0;
ALTER TABLE UserAccounts ADD COLUMN UserTitle varchar(64) NOT NULL DEFAULT '';
COMMIT;

View File

@ -0,0 +1,6 @@
BEGIN;
ALTER TABLE `regions` ADD COLUMN `flags` integer NOT NULL DEFAULT 0;
CREATE INDEX flags ON regions(flags);
COMMIT;

View File

@ -0,0 +1,5 @@
BEGIN;
ALTER TABLE `regions` ADD COLUMN `last_seen` integer NOT NULL DEFAULT 0;
COMMIT;

View File

@ -0,0 +1,7 @@
BEGIN;
ALTER TABLE `regions` ADD COLUMN `PrincipalID` char(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000';
ALTER TABLE `regions` ADD COLUMN `Token` varchar(255) NOT NULL;
COMMIT;

View File

@ -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");
}
/// <summary>
/// Execute a MySqlCommand
/// </summary>
/// <param name="sql">sql string to execute</param>
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();
}
}
}

View File

@ -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");
}
/// <summary>
/// Execute a MySqlCommand
/// </summary>
/// <param name="sql">sql string to execute</param>
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();
}
}
}

View File

@ -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");
}
/// <summary>
/// Execute a MySqlCommand
/// </summary>
/// <param name="sql">sql string to execute</param>
private void ExecuteSql(string sql)
{
using (MySqlConnection dbcon = new MySqlConnection(connect))
{
dbcon.Open();
MySqlCommand cmd = new MySqlCommand(sql, dbcon);
cmd.ExecuteNonQuery();
}
}
}
}

View File

@ -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");
}
/// <summary>
/// Execute a MySqlCommand
/// </summary>
/// <param name="sql">sql string to execute</param>
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();
}
}
}

View File

@ -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");
}
}
}
}

View File

@ -1,4 +1,4 @@
/*
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
@ -26,54 +26,56 @@
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using log4net;
using log4net.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Communications.Services;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Grid.Communications.OGS1;
using OpenSim.Grid.Framework;
using OpenSim.Data;
namespace OpenSim.Grid.UserServer.Modules
namespace OpenSim.Data.Null
{
public class GridInfoServiceModule
public class NullAuthenticationData : IAuthenticationData
{
protected IGridServiceCore m_core;
protected GridInfoService m_gridInfoService;
protected BaseHttpServer m_httpServer;
private static Dictionary<UUID, AuthenticationData> m_DataByUUID = new Dictionary<UUID, AuthenticationData>();
private static Dictionary<UUID, string> m_Tokens = new Dictionary<UUID, string>();
public GridInfoServiceModule()
public NullAuthenticationData(string connectionString, string realm)
{
}
public void Initialise(IGridServiceCore core)
public AuthenticationData Get(UUID principalID)
{
m_core = core;
m_gridInfoService = new GridInfoService();
if (m_DataByUUID.ContainsKey(principalID))
return m_DataByUUID[principalID];
return null;
}
public void PostInitialise()
public bool Store(AuthenticationData data)
{
m_DataByUUID[data.PrincipalID] = data;
return true;
}
public void RegisterHandlers(BaseHttpServer httpServer)
public bool SetDataItem(UUID principalID, string item, string value)
{
m_httpServer = httpServer;
m_httpServer.AddStreamHandler(new RestStreamHandler("GET", "/get_grid_info",
m_gridInfoService.RestGetGridInfoMethod));
m_httpServer.AddXmlRPCHandler("get_grid_info", m_gridInfoService.XmlRpcGridInfoMethod);
// Not implemented
return false;
}
public void Close()
public bool SetToken(UUID principalID, string token, int lifetime)
{
m_Tokens[principalID] = token;
return true;
}
public bool CheckToken(UUID principalID, string token, int lifetime)
{
if (m_Tokens.ContainsKey(principalID))
return m_Tokens[principalID] == token;
return false;
}
}
}

View File

@ -0,0 +1,93 @@
/*
* 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 OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Data;
namespace OpenSim.Data.Null
{
public class NullAvatarData : IAvatarData
{
private static Dictionary<UUID, AvatarBaseData> m_DataByUUID = new Dictionary<UUID, AvatarBaseData>();
public NullAvatarData(string connectionString, string realm)
{
}
public AvatarBaseData[] Get(string field, string val)
{
if (field == "PrincipalID")
{
UUID id = UUID.Zero;
if (UUID.TryParse(val, out id))
if (m_DataByUUID.ContainsKey(id))
return new AvatarBaseData[] { m_DataByUUID[id] };
}
// Fail
return new AvatarBaseData[0];
}
public bool Store(AvatarBaseData data)
{
m_DataByUUID[data.PrincipalID] = data;
return true;
}
public bool Delete(UUID principalID, string name)
{
if (m_DataByUUID.ContainsKey(principalID) && m_DataByUUID[principalID].Data.ContainsKey(name))
{
m_DataByUUID[principalID].Data.Remove(name);
return true;
}
return false;
}
public bool Delete(string field, string val)
{
if (field == "PrincipalID")
{
UUID id = UUID.Zero;
if (UUID.TryParse(val, out id))
if (m_DataByUUID.ContainsKey(id))
{
m_DataByUUID.Remove(id);
return true;
}
}
return false;
}
}
}

View File

@ -25,51 +25,68 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Data;
namespace OpenSim.Grid.MessagingServer.Modules
namespace OpenSim.Data.Null
{
public class UserDataBaseService : UserManagerBase
public class NullFriendsData : IFriendsData
{
/// <summary>
/// Constructor.
/// </summary>
/// Passing null to parent because we never use any function that requires an interservice inventory call.
public UserDataBaseService()
: base(null)
private static List<FriendsData> m_Data = new List<FriendsData>();
public NullFriendsData(string connectionString, string realm)
{
}
public UserAgentData GetUserAgentData(UUID AgentID)
{
UserProfileData userProfile = GetUserProfile(AgentID);
if (userProfile != null)
/// <summary>
/// Tries to implement the Get [] semantics, but it cuts corners.
/// Specifically, it gets all friendships even if they weren't accepted yet.
/// </summary>
/// <param name="fields"></param>
/// <param name="values"></param>
/// <returns></returns>
public FriendsData[] GetFriends(UUID userID)
{
List<FriendsData> lst = m_Data.FindAll(delegate (FriendsData fdata)
{
return userProfile.CurrentAgent;
return fdata.PrincipalID == userID;
});
if (lst != null)
return lst.ToArray();
return new FriendsData[0];
}
public bool Store(FriendsData data)
{
if (data == null)
return false;
m_Data.Add(data);
return true;
}
public bool Delete(UUID userID, string friendID)
{
List<FriendsData> lst = m_Data.FindAll(delegate(FriendsData fdata) { return fdata.PrincipalID == userID; });
if (lst != null)
{
FriendsData friend = lst.Find(delegate(FriendsData fdata) { return fdata.Friend == friendID; });
if (friendID != null)
{
m_Data.Remove(friend);
return true;
}
}
return null;
return false;
}
public override UserProfileData SetupMasterUser(string firstName, string lastName)
{
//throw new Exception("The method or operation is not implemented.");
return null;
}
public override UserProfileData SetupMasterUser(string firstName, string lastName, string password)
{
//throw new Exception("The method or operation is not implemented.");
return null;
}
public override UserProfileData SetupMasterUser(UUID uuid)
{
//throw new Exception("The method or operation is not implemented.");
return null;
}
}
}

View File

@ -0,0 +1,261 @@
/*
* 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 OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Data;
namespace OpenSim.Data.Null
{
public class NullPresenceData : IPresenceData
{
private static NullPresenceData Instance;
Dictionary<UUID, PresenceData> m_presenceData = new Dictionary<UUID, PresenceData>();
public NullPresenceData(string connectionString, string realm)
{
if (Instance == null)
{
Instance = this;
//Console.WriteLine("[XXX] NullRegionData constructor");
// Let's stick in a test presence
PresenceData p = new PresenceData();
p.SessionID = UUID.Zero;
p.UserID = UUID.Zero.ToString();
p.Data = new Dictionary<string, string>();
p.Data["Online"] = true.ToString();
m_presenceData.Add(UUID.Zero, p);
}
}
public bool Store(PresenceData data)
{
if (Instance != this)
return Instance.Store(data);
m_presenceData[data.SessionID] = data;
return true;
}
public PresenceData Get(UUID sessionID)
{
if (Instance != this)
return Instance.Get(sessionID);
if (m_presenceData.ContainsKey(sessionID))
{
return m_presenceData[sessionID];
}
return null;
}
public void LogoutRegionAgents(UUID regionID)
{
if (Instance != this)
{
Instance.LogoutRegionAgents(regionID);
return;
}
List<UUID> toBeDeleted = new List<UUID>();
foreach (KeyValuePair<UUID, PresenceData> kvp in m_presenceData)
if (kvp.Value.RegionID == regionID)
toBeDeleted.Add(kvp.Key);
foreach (UUID u in toBeDeleted)
m_presenceData.Remove(u);
}
public bool ReportAgent(UUID sessionID, UUID regionID, string position, string lookAt)
{
if (Instance != this)
return Instance.ReportAgent(sessionID, regionID, position, lookAt);
if (m_presenceData.ContainsKey(sessionID))
{
m_presenceData[sessionID].RegionID = regionID;
m_presenceData[sessionID].Data["Position"] = position;
m_presenceData[sessionID].Data["LookAt"] = lookAt;
return true;
}
return false;
}
public bool SetHomeLocation(string userID, UUID regionID, Vector3 position, Vector3 lookAt)
{
if (Instance != this)
return Instance.SetHomeLocation(userID, regionID, position, lookAt);
bool foundone = false;
foreach (PresenceData p in m_presenceData.Values)
{
if (p.UserID == userID)
{
p.Data["HomeRegionID"] = regionID.ToString();
p.Data["HomePosition"] = position.ToString();
p.Data["HomeLookAt"] = lookAt.ToString();
foundone = true;
}
}
return foundone;
}
public PresenceData[] Get(string field, string data)
{
if (Instance != this)
return Instance.Get(field, data);
List<PresenceData> presences = new List<PresenceData>();
if (field == "UserID")
{
foreach (PresenceData p in m_presenceData.Values)
if (p.UserID == data)
presences.Add(p);
return presences.ToArray();
}
else if (field == "SessionID")
{
UUID session = UUID.Zero;
if (!UUID.TryParse(data, out session))
return presences.ToArray();
if (m_presenceData.ContainsKey(session))
{
presences.Add(m_presenceData[session]);
return presences.ToArray();
}
}
else if (field == "RegionID")
{
UUID region = UUID.Zero;
if (!UUID.TryParse(data, out region))
return presences.ToArray();
foreach (PresenceData p in m_presenceData.Values)
if (p.RegionID == region)
presences.Add(p);
return presences.ToArray();
}
else
{
foreach (PresenceData p in m_presenceData.Values)
{
if (p.Data.ContainsKey(field) && p.Data[field] == data)
presences.Add(p);
}
return presences.ToArray();
}
return presences.ToArray();
}
public void Prune(string userID)
{
if (Instance != this)
{
Instance.Prune(userID);
return;
}
List<UUID> deleteSessions = new List<UUID>();
int online = 0;
foreach (KeyValuePair<UUID, PresenceData> kvp in m_presenceData)
{
bool on = false;
if (bool.TryParse(kvp.Value.Data["Online"], out on) && on)
online++;
else
deleteSessions.Add(kvp.Key);
}
if (online == 0 && deleteSessions.Count > 0)
deleteSessions.RemoveAt(0);
foreach (UUID s in deleteSessions)
m_presenceData.Remove(s);
}
public bool Delete(string field, string data)
{
if (Instance != this)
return Delete(field, data);
List<UUID> presences = new List<UUID>();
if (field == "UserID")
{
foreach (KeyValuePair<UUID, PresenceData> p in m_presenceData)
if (p.Value.UserID == data)
presences.Add(p.Key);
}
else if (field == "SessionID")
{
UUID session = UUID.Zero;
if (UUID.TryParse(data, out session))
{
if (m_presenceData.ContainsKey(session))
{
presences.Add(session);
}
}
}
else if (field == "RegionID")
{
UUID region = UUID.Zero;
if (UUID.TryParse(data, out region))
{
foreach (KeyValuePair<UUID, PresenceData> p in m_presenceData)
if (p.Value.RegionID == region)
presences.Add(p.Key);
}
}
else
{
foreach (KeyValuePair<UUID, PresenceData> p in m_presenceData)
{
if (p.Value.Data.ContainsKey(field) && p.Value.Data[field] == data)
presences.Add(p.Key);
}
}
foreach (UUID u in presences)
m_presenceData.Remove(u);
if (presences.Count == 0)
return false;
return true;
}
}
}

View File

@ -31,20 +31,31 @@ using System.Collections.Generic;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Data;
using System.Reflection;
using log4net;
namespace OpenSim.Data.Null
{
public class NullRegionData : IRegionData
{
private static NullRegionData Instance = null;
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
Dictionary<UUID, RegionData> m_regionData = new Dictionary<UUID, RegionData>();
public NullRegionData(string connectionString, string realm)
{
if (Instance == null)
Instance = this;
//Console.WriteLine("[XXX] NullRegionData constructor");
}
public List<RegionData> Get(string regionName, UUID scopeID)
{
if (Instance != this)
return Instance.Get(regionName, scopeID);
List<RegionData> ret = new List<RegionData>();
foreach (RegionData r in m_regionData.Values)
@ -69,6 +80,9 @@ namespace OpenSim.Data.Null
public RegionData Get(int posX, int posY, UUID scopeID)
{
if (Instance != this)
return Instance.Get(posX, posY, scopeID);
List<RegionData> ret = new List<RegionData>();
foreach (RegionData r in m_regionData.Values)
@ -85,6 +99,9 @@ namespace OpenSim.Data.Null
public RegionData Get(UUID regionID, UUID scopeID)
{
if (Instance != this)
return Instance.Get(regionID, scopeID);
if (m_regionData.ContainsKey(regionID))
return m_regionData[regionID];
@ -93,6 +110,9 @@ namespace OpenSim.Data.Null
public List<RegionData> Get(int startX, int startY, int endX, int endY, UUID scopeID)
{
if (Instance != this)
return Instance.Get(startX, startY, endX, endY, scopeID);
List<RegionData> ret = new List<RegionData>();
foreach (RegionData r in m_regionData.Values)
@ -106,6 +126,9 @@ namespace OpenSim.Data.Null
public bool Store(RegionData data)
{
if (Instance != this)
return Instance.Store(data);
m_regionData[data.RegionID] = data;
return true;
@ -113,6 +136,9 @@ namespace OpenSim.Data.Null
public bool SetDataItem(UUID regionID, string item, string value)
{
if (Instance != this)
return Instance.SetDataItem(regionID, item, value);
if (!m_regionData.ContainsKey(regionID))
return false;
@ -123,6 +149,9 @@ namespace OpenSim.Data.Null
public bool Delete(UUID regionID)
{
if (Instance != this)
return Instance.Delete(regionID);
if (!m_regionData.ContainsKey(regionID))
return false;
@ -130,5 +159,37 @@ namespace OpenSim.Data.Null
return true;
}
public List<RegionData> GetDefaultRegions(UUID scopeID)
{
if (Instance != this)
return Instance.GetDefaultRegions(scopeID);
List<RegionData> ret = new List<RegionData>();
foreach (RegionData r in m_regionData.Values)
{
if ((Convert.ToInt32(r.Data["flags"]) & 1) != 0)
ret.Add(r);
}
return ret;
}
public List<RegionData> GetFallbackRegions(UUID scopeID, int x, int y)
{
if (Instance != this)
return Instance.GetFallbackRegions(scopeID, x, y);
List<RegionData> ret = new List<RegionData>();
foreach (RegionData r in m_regionData.Values)
{
if ((Convert.ToInt32(r.Data["flags"]) & 2) != 0)
ret.Add(r);
}
return ret;
}
}
}

Some files were not shown because too many files have changed in this diff Show More