Merge branch 'master' of ssh://opensimulator.org/var/git/opensim

dsg
Dan Lake 2011-04-18 22:14:35 -07:00
commit f47d1c84cb
202 changed files with 4105 additions and 8864 deletions

View File

@ -94,7 +94,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
public void Initialise()
{
m_log.Info("[RADMIN]: " + Name + " cannot be default-initialized!");
m_log.Error("[RADMIN]: " + Name + " cannot be default-initialized!");
throw new PluginNotInitialisedException(Name);
}
@ -111,7 +111,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
else
{
m_config = m_configSource.Configs["RemoteAdmin"];
m_log.Info("[RADMIN]: Remote Admin Plugin Enabled");
m_log.Debug("[RADMIN]: Remote Admin Plugin Enabled");
m_requiredPassword = m_config.GetString("access_password", String.Empty);
int port = m_config.GetInt("port", 0);
@ -130,6 +130,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
availableMethods["admin_broadcast"] = XmlRpcAlertMethod;
availableMethods["admin_restart"] = XmlRpcRestartMethod;
availableMethods["admin_load_heightmap"] = XmlRpcLoadHeightmapMethod;
availableMethods["admin_save_heightmap"] = XmlRpcSaveHeightmapMethod;
// User management
availableMethods["admin_create_user"] = XmlRpcCreateUserMethod;
availableMethods["admin_create_user_email"] = XmlRpcCreateUserMethod;
@ -230,8 +231,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
}
catch (Exception e)
{
m_log.ErrorFormat("[RADMIN]: Restart region: failed: {0}", e.Message);
m_log.DebugFormat("[RADMIN]: Restart region: failed: {0}", e.ToString());
m_log.ErrorFormat("[RADMIN]: Restart region: failed: {0} {1}", e.Message, e.StackTrace);
responseData["accepted"] = false;
responseData["success"] = false;
responseData["rebooting"] = false;
@ -277,8 +277,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
}
catch (Exception e)
{
m_log.ErrorFormat("[RADMIN]: Broadcasting: failed: {0}", e.Message);
m_log.DebugFormat("[RADMIN]: Broadcasting: failed: {0}", e.ToString());
m_log.ErrorFormat("[RADMIN]: Broadcasting: failed: {0}", e.Message, e.StackTrace);
responseData["accepted"] = false;
responseData["success"] = false;
@ -301,7 +300,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
{
Hashtable requestData = (Hashtable) request.Params[0];
m_log.DebugFormat("[RADMIN]: Load Terrain: XmlRpc {0}", request.ToString());
m_log.DebugFormat("[RADMIN]: Load Terrain: XmlRpc {0}", request);
// foreach (string k in requestData.Keys)
// {
// m_log.DebugFormat("[RADMIN]: Load Terrain: XmlRpc {0}: >{1}< {2}",
@ -348,8 +347,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
}
catch (Exception e)
{
m_log.ErrorFormat("[RADMIN]: Terrain Loading: failed: {0}", e.Message);
m_log.DebugFormat("[RADMIN]: Terrain Loading: failed: {0}", e.ToString());
m_log.ErrorFormat("[RADMIN]: Terrain Loading: failed: {0} {1}", e.Message, e.StackTrace);
responseData["success"] = false;
responseData["error"] = e.Message;
@ -360,6 +358,61 @@ namespace OpenSim.ApplicationPlugins.RemoteController
return response;
}
public XmlRpcResponse XmlRpcSaveHeightmapMethod(XmlRpcRequest request, IPEndPoint remoteClient)
{
XmlRpcResponse response = new XmlRpcResponse();
Hashtable responseData = new Hashtable();
m_log.Info("[RADMIN]: Save height maps request started");
try
{
Hashtable requestData = (Hashtable)request.Params[0];
m_log.DebugFormat("[RADMIN]: Save Terrain: XmlRpc {0}", request.ToString());
CheckStringParameters(request, new string[] { "password", "filename", "regionid" });
if (m_requiredPassword != String.Empty &&
(!requestData.Contains("password") || (string)requestData["password"] != m_requiredPassword))
throw new Exception("wrong password");
string file = (string)requestData["filename"];
UUID regionID = (UUID)(string)requestData["regionid"];
m_log.InfoFormat("[RADMIN]: Terrain Saving: {0}", file);
responseData["accepted"] = true;
Scene region = null;
if (!m_application.SceneManager.TryGetScene(regionID, out region))
throw new Exception("1: unable to get a scene with that name");
ITerrainModule terrainModule = region.RequestModuleInterface<ITerrainModule>();
if (null == terrainModule) throw new Exception("terrain module not available");
terrainModule.SaveToFile(file);
responseData["success"] = false;
response.Value = responseData;
}
catch (Exception e)
{
m_log.ErrorFormat("[RADMIN]: Terrain Saving: failed: {0}", e.Message);
m_log.DebugFormat("[RADMIN]: Terrain Saving: failed: {0}", e.ToString());
responseData["success"] = false;
responseData["error"] = e.Message;
}
m_log.Info("[RADMIN]: Save height maps request complete");
return response;
}
public XmlRpcResponse XmlRpcShutdownMethod(XmlRpcRequest request, IPEndPoint remoteClient)
{
m_log.Info("[RADMIN]: Received Shutdown Administrator Request");
@ -417,14 +470,14 @@ namespace OpenSim.ApplicationPlugins.RemoteController
}
catch (Exception e)
{
m_log.ErrorFormat("[RADMIN] Shutdown: failed: {0}", e.Message);
m_log.DebugFormat("[RADMIN] Shutdown: failed: {0}", e.ToString());
m_log.ErrorFormat("[RADMIN]: Shutdown: failed: {0} {1}", e.Message, e.StackTrace);
responseData["accepted"] = false;
responseData["error"] = e.Message;
response.Value = responseData;
}
m_log.Info("[RADMIN]: Shutdown Administrator Request complete");
return response;
}
@ -725,8 +778,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
}
catch (Exception e)
{
m_log.ErrorFormat("[RADMIN] CreateRegion: failed {0}", e.Message);
m_log.DebugFormat("[RADMIN] CreateRegion: failed {0}", e.ToString());
m_log.ErrorFormat("[RADMIN] CreateRegion: failed {0} {1}", e.Message, e.StackTrace);
responseData["success"] = false;
responseData["error"] = e.Message;
@ -792,8 +844,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
}
catch (Exception e)
{
m_log.ErrorFormat("[RADMIN] DeleteRegion: failed {0}", e.Message);
m_log.DebugFormat("[RADMIN] DeleteRegion: failed {0}", e.ToString());
m_log.ErrorFormat("[RADMIN] DeleteRegion: failed {0} {1}", e.Message, e.StackTrace);
responseData["success"] = false;
responseData["error"] = e.Message;
@ -884,8 +935,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
}
catch (Exception e)
{
m_log.ErrorFormat("[RADMIN] CloseRegion: failed {0}", e.Message);
m_log.DebugFormat("[RADMIN] CloseRegion: failed {0}", e.ToString());
m_log.ErrorFormat("[RADMIN]: CloseRegion: failed {0} {1}", e.Message, e.StackTrace);
responseData["success"] = false;
responseData["error"] = e.Message;
@ -982,8 +1032,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
}
catch (Exception e)
{
m_log.ErrorFormat("[RADMIN] ModifyRegion: failed {0}", e.Message);
m_log.DebugFormat("[RADMIN] ModifyRegion: failed {0}", e.ToString());
m_log.ErrorFormat("[RADMIN] ModifyRegion: failed {0} {1}", e.Message, e.StackTrace);
responseData["success"] = false;
responseData["error"] = e.Message;
@ -1106,8 +1155,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
}
catch (Exception e)
{
m_log.ErrorFormat("[RADMIN] CreateUser: failed: {0}", e.Message);
m_log.DebugFormat("[RADMIN] CreateUser: failed: {0}", e.ToString());
m_log.ErrorFormat("[RADMIN]: CreateUser: failed: {0} {1}", e.Message, e.StackTrace);
responseData["success"] = false;
responseData["avatar_uuid"] = UUID.Zero.ToString();
@ -1198,8 +1246,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
}
catch (Exception e)
{
m_log.ErrorFormat("[RADMIN] UserExists: failed: {0}", e.Message);
m_log.DebugFormat("[RADMIN] UserExists: failed: {0}", e.ToString());
m_log.ErrorFormat("[RADMIN]: UserExists: failed: {0} {1}", e.Message, e.StackTrace);
responseData["success"] = false;
responseData["error"] = e.Message;
@ -1372,9 +1419,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
}
catch (Exception e)
{
m_log.ErrorFormat("[RADMIN] UpdateUserAccount: failed: {0}", e.Message);
m_log.DebugFormat("[RADMIN] UpdateUserAccount: failed: {0}", e.ToString());
m_log.ErrorFormat("[RADMIN] UpdateUserAccount: failed: {0} {1}", e.Message, e.StackTrace);
responseData["success"] = false;
responseData["avatar_uuid"] = UUID.Zero.ToString();
@ -1382,6 +1427,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
response.Value = responseData;
}
m_log.Info("[RADMIN]: UpdateUserAccount: request complete");
return response;
}
@ -1397,7 +1443,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
private void UpdateUserAppearance(Hashtable responseData, Hashtable requestData, UUID userid)
{
m_log.DebugFormat("[RADMIN] updateUserAppearance");
m_log.DebugFormat("[RADMIN]: updateUserAppearance");
string defaultMale = m_config.GetString("default_male", "Default Male");
string defaultFemale = m_config.GetString("default_female", "Default Female");
@ -1437,16 +1483,16 @@ namespace OpenSim.ApplicationPlugins.RemoteController
if (String.IsNullOrEmpty(model))
{
m_log.DebugFormat("[RADMIN] Appearance update not requested");
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[] modelSpecifiers = model.Split();
if (modelSpecifiers.Length != 2)
{
m_log.WarnFormat("[RADMIN] User appearance not set for {0}. Invalid model name : <{1}>", userid, model);
m_log.WarnFormat("[RADMIN]: User appearance not set for {0}. Invalid model name : <{1}>", userid, model);
// modelSpecifiers = dmodel.Split();
return;
}
@ -1457,7 +1503,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
if (modelProfile == null)
{
m_log.WarnFormat("[RADMIN] Requested model ({0}) not found. Appearance unchanged", model);
m_log.WarnFormat("[RADMIN]: Requested model ({0}) not found. Appearance unchanged", model);
return;
}
@ -1467,7 +1513,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
EstablishAppearance(userid, modelProfile.PrincipalID);
m_log.DebugFormat("[RADMIN] Finished setting appearance for avatar {0}, using model {1}",
m_log.DebugFormat("[RADMIN]: Finished setting appearance for avatar {0}, using model {1}",
userid, model);
}
@ -1479,7 +1525,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
private void EstablishAppearance(UUID destination, UUID source)
{
m_log.DebugFormat("[RADMIN] Initializing inventory for {0} from {1}", destination, source);
m_log.DebugFormat("[RADMIN]: Initializing inventory for {0} from {1}", destination, source);
Scene scene = m_application.SceneManager.CurrentOrFirstScene;
// If the model has no associated appearance we're done.
@ -1501,7 +1547,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
}
catch (Exception e)
{
m_log.WarnFormat("[RADMIN] Error transferring appearance for {0} : {1}",
m_log.WarnFormat("[RADMIN]: Error transferring appearance for {0} : {1}",
destination, e.Message);
}
@ -1532,7 +1578,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
}
catch (Exception e)
{
m_log.WarnFormat("[RADMIN] Error transferring appearance for {0} : {1}",
m_log.WarnFormat("[RADMIN]: Error transferring appearance for {0} : {1}",
destination, e.Message);
}
@ -1567,7 +1613,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
destinationFolder.ParentID = inventoryService.GetRootFolder(destination).ID;
destinationFolder.Version = 1;
inventoryService.AddFolder(destinationFolder); // store base record
m_log.ErrorFormat("[RADMIN] Created folder for destination {0}", source);
m_log.ErrorFormat("[RADMIN]: Created folder for destination {0}", source);
}
// Wearables
@ -1587,6 +1633,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
{
InventoryItemBase destinationItem = new InventoryItemBase(UUID.Random(), destination);
destinationItem.Name = item.Name;
destinationItem.Owner = destination;
destinationItem.Description = item.Description;
destinationItem.InvType = item.InvType;
destinationItem.CreatorId = item.CreatorId;
@ -1606,6 +1653,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
destinationItem.Flags = item.Flags;
destinationItem.CreationDate = item.CreationDate;
destinationItem.Folder = destinationFolder.ID;
ApplyNextOwnerPermissions(destinationItem);
m_application.SceneManager.CurrentOrFirstScene.AddInventoryItem(destinationItem);
m_log.DebugFormat("[RADMIN]: Added item {0} to folder {1}", destinationItem.ID, destinationFolder.ID);
@ -1640,6 +1688,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
{
InventoryItemBase destinationItem = new InventoryItemBase(UUID.Random(), destination);
destinationItem.Name = item.Name;
destinationItem.Owner = destination;
destinationItem.Description = item.Description;
destinationItem.InvType = item.InvType;
destinationItem.CreatorId = item.CreatorId;
@ -1659,6 +1708,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
destinationItem.Flags = item.Flags;
destinationItem.CreationDate = item.CreationDate;
destinationItem.Folder = destinationFolder.ID;
ApplyNextOwnerPermissions(destinationItem);
m_application.SceneManager.CurrentOrFirstScene.AddInventoryItem(destinationItem);
m_log.DebugFormat("[RADMIN]: Added item {0} to folder {1}", destinationItem.ID, destinationFolder.ID);
@ -1716,13 +1766,17 @@ namespace OpenSim.ApplicationPlugins.RemoteController
{
destinationFolder = new InventoryFolderBase();
destinationFolder.ID = UUID.Random();
destinationFolder.Name = assetType.ToString();
if (assetType == AssetType.Clothing) {
destinationFolder.Name = "Clothing";
} else {
destinationFolder.Name = "Body Parts";
}
destinationFolder.Owner = destination;
destinationFolder.Type = (short)assetType;
destinationFolder.ParentID = inventoryService.GetRootFolder(destination).ID;
destinationFolder.Version = 1;
inventoryService.AddFolder(destinationFolder); // store base record
m_log.ErrorFormat("[RADMIN] Created folder for destination {0}", source);
m_log.ErrorFormat("[RADMIN]: Created folder for destination {0}", source);
}
InventoryFolderBase extraFolder;
@ -1740,7 +1794,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
extraFolder.ParentID = destinationFolder.ID;
inventoryService.AddFolder(extraFolder);
m_log.DebugFormat("[RADMIN] Added folder {0} to folder {1}", extraFolder.ID, sourceFolder.ID);
m_log.DebugFormat("[RADMIN]: Added folder {0} to folder {1}", extraFolder.ID, sourceFolder.ID);
List<InventoryItemBase> items = inventoryService.GetFolderContent(source, folder.ID).Items;
@ -1748,6 +1802,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
{
InventoryItemBase destinationItem = new InventoryItemBase(UUID.Random(), destination);
destinationItem.Name = item.Name;
destinationItem.Owner = destination;
destinationItem.Description = item.Description;
destinationItem.InvType = item.InvType;
destinationItem.CreatorId = item.CreatorId;
@ -1767,6 +1822,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
destinationItem.Flags = item.Flags;
destinationItem.CreationDate = item.CreationDate;
destinationItem.Folder = extraFolder.ID;
ApplyNextOwnerPermissions(destinationItem);
m_application.SceneManager.CurrentOrFirstScene.AddInventoryItem(destinationItem);
inventoryMap.Add(item.ID, destinationItem.ID);
@ -1783,6 +1839,29 @@ namespace OpenSim.ApplicationPlugins.RemoteController
}
}
/// <summary>
/// Apply next owner permissions.
/// </summary>
private void ApplyNextOwnerPermissions(InventoryItemBase item)
{
if (item.InvType == (int)InventoryType.Object && (item.CurrentPermissions & 7) != 0)
{
if ((item.CurrentPermissions & ((uint)PermissionMask.Copy >> 13)) == 0)
item.CurrentPermissions &= ~(uint)PermissionMask.Copy;
if ((item.CurrentPermissions & ((uint)PermissionMask.Transfer >> 13)) == 0)
item.CurrentPermissions &= ~(uint)PermissionMask.Transfer;
if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0)
item.CurrentPermissions &= ~(uint)PermissionMask.Modify;
}
item.CurrentPermissions &= item.NextPermissions;
item.BasePermissions &= item.NextPermissions;
item.EveryOnePermissions &= item.NextPermissions;
// item.OwnerChanged = true;
// item.PermsMask = 0;
// item.PermsGranter = UUID.Zero;
}
/// <summary>
/// This method is called if a given model avatar name can not be found. If the external
/// file has already been loaded once, then control returns immediately. If not, then it
@ -1792,7 +1871,6 @@ namespace OpenSim.ApplicationPlugins.RemoteController
/// indicate which outfit is the default, and this outfit will be automatically worn. The
/// other outfits are provided to allow "real" avatars a way to easily change their outfits.
/// </summary>
private bool CreateDefaultAvatars()
{
// Only load once
@ -1801,7 +1879,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
return false;
}
m_log.DebugFormat("[RADMIN] Creating default avatar entries");
m_log.DebugFormat("[RADMIN]: Creating default avatar entries");
m_defaultAvatarsLoaded = true;
@ -1857,7 +1935,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
foreach (XmlElement avatar in avatars)
{
m_log.DebugFormat("[RADMIN] Loading appearance for {0}, gender = {1}",
m_log.DebugFormat("[RADMIN]: Loading appearance for {0}, gender = {1}",
GetStringAttribute(avatar,"name","?"), GetStringAttribute(avatar,"gender","?"));
// Create the user identified by the avatar entry
@ -1879,7 +1957,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
account = CreateUser(scopeID, names[0], names[1], password, email);
if (null == account)
{
m_log.ErrorFormat("[RADMIN] Avatar {0} {1} was not created", names[0], names[1]);
m_log.ErrorFormat("[RADMIN]: Avatar {0} {1} was not created", names[0], names[1]);
return false;
}
}
@ -1897,12 +1975,12 @@ namespace OpenSim.ApplicationPlugins.RemoteController
ID = account.PrincipalID;
m_log.DebugFormat("[RADMIN] User {0}[{1}] created or retrieved", name, ID);
m_log.DebugFormat("[RADMIN]: User {0}[{1}] created or retrieved", name, ID);
include = true;
}
catch (Exception e)
{
m_log.DebugFormat("[RADMIN] Error creating user {0} : {1}", name, e.Message);
m_log.DebugFormat("[RADMIN]: Error creating user {0} : {1}", name, e.Message);
include = false;
}
@ -1942,7 +2020,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
clothingFolder.ParentID = inventoryService.GetRootFolder(ID).ID;
clothingFolder.Version = 1;
inventoryService.AddFolder(clothingFolder); // store base record
m_log.ErrorFormat("[RADMIN] Created clothing folder for {0}/{1}", name, ID);
m_log.ErrorFormat("[RADMIN]: Created clothing folder for {0}/{1}", name, ID);
}
// OK, now we have an inventory for the user, read in the outfits from the
@ -1955,7 +2033,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
foreach (XmlElement outfit in outfits)
{
m_log.DebugFormat("[RADMIN] Loading outfit {0} for {1}",
m_log.DebugFormat("[RADMIN]: Loading outfit {0} for {1}",
GetStringAttribute(outfit,"name","?"), GetStringAttribute(avatar,"name","?"));
outfitName = GetStringAttribute(outfit,"name","");
@ -1979,7 +2057,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
// Otherwise, we must create the folder.
if (extraFolder == null)
{
m_log.DebugFormat("[RADMIN] Creating outfit folder {0} for {1}", outfitName, name);
m_log.DebugFormat("[RADMIN]: Creating outfit folder {0} for {1}", outfitName, name);
extraFolder = new InventoryFolderBase();
extraFolder.ID = UUID.Random();
extraFolder.Name = outfitName;
@ -1988,7 +2066,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
extraFolder.Version = 1;
extraFolder.ParentID = clothingFolder.ID;
inventoryService.AddFolder(extraFolder);
m_log.DebugFormat("[RADMIN] Adding outfile folder {0} to folder {1}", extraFolder.ID, clothingFolder.ID);
m_log.DebugFormat("[RADMIN]: Adding outfile folder {0} to folder {1}", extraFolder.ID, clothingFolder.ID);
}
// Now get the pieces that make up the outfit
@ -2003,7 +2081,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
switch (child.Name)
{
case "Permissions" :
m_log.DebugFormat("[RADMIN] Permissions specified");
m_log.DebugFormat("[RADMIN]: Permissions specified");
perms = child;
break;
case "Asset" :
@ -2053,7 +2131,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
inventoryItem.Folder = extraFolder.ID; // Parent folder
m_application.SceneManager.CurrentOrFirstScene.AddInventoryItem(inventoryItem);
m_log.DebugFormat("[RADMIN] Added item {0} to folder {1}", inventoryItem.ID, extraFolder.ID);
m_log.DebugFormat("[RADMIN]: Added item {0} to folder {1}", inventoryItem.ID, extraFolder.ID);
}
// Attach item, if attachpoint is specified
@ -2061,7 +2139,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
if (attachpoint != 0)
{
avatarAppearance.SetAttachment(attachpoint, inventoryItem.ID, inventoryItem.AssetID);
m_log.DebugFormat("[RADMIN] Attached {0}", inventoryItem.ID);
m_log.DebugFormat("[RADMIN]: Attached {0}", inventoryItem.ID);
}
// Record whether or not the item is to be initially worn
@ -2074,32 +2152,32 @@ namespace OpenSim.ApplicationPlugins.RemoteController
}
catch (Exception e)
{
m_log.WarnFormat("[RADMIN] Error wearing item {0} : {1}", inventoryItem.ID, e.Message);
m_log.WarnFormat("[RADMIN]: Error wearing item {0} : {1}", inventoryItem.ID, e.Message);
}
} // foreach item in outfit
m_log.DebugFormat("[RADMIN] Outfit {0} load completed", outfitName);
m_log.DebugFormat("[RADMIN]: Outfit {0} load completed", outfitName);
} // foreach outfit
m_log.DebugFormat("[RADMIN] Inventory update complete for {0}", name);
m_log.DebugFormat("[RADMIN]: Inventory update complete for {0}", name);
scene.AvatarService.SetAppearance(ID, avatarAppearance);
}
catch (Exception e)
{
m_log.WarnFormat("[RADMIN] Inventory processing incomplete for user {0} : {1}",
m_log.WarnFormat("[RADMIN]: Inventory processing incomplete for user {0} : {1}",
name, e.Message);
}
} // End of include
}
m_log.DebugFormat("[RADMIN] Default avatar loading complete");
m_log.DebugFormat("[RADMIN]: Default avatar loading complete");
}
else
{
m_log.DebugFormat("[RADMIN] No default avatar information available");
m_log.DebugFormat("[RADMIN]: No default avatar information available");
return false;
}
}
catch (Exception e)
{
m_log.WarnFormat("[RADMIN] Exception whilst loading default avatars ; {0}", e.Message);
m_log.WarnFormat("[RADMIN]: Exception whilst loading default avatars ; {0}", e.Message);
return false;
}
@ -2194,8 +2272,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
}
catch (Exception e)
{
m_log.InfoFormat("[RADMIN] LoadOAR: {0}", e.Message);
m_log.DebugFormat("[RADMIN] LoadOAR: {0}", e.ToString());
m_log.ErrorFormat("[RADMIN]: LoadOAR: {0} {1}", e.Message, e.StackTrace);
responseData["loaded"] = false;
responseData["error"] = e.Message;
@ -2300,8 +2377,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
}
catch (Exception e)
{
m_log.InfoFormat("[RADMIN] SaveOAR: {0}", e.Message);
m_log.DebugFormat("[RADMIN] SaveOAR: {0}", e.ToString());
m_log.ErrorFormat("[RADMIN]: SaveOAR: {0} {1}", e.Message, e.StackTrace);
responseData["saved"] = false;
responseData["error"] = e.Message;
@ -2315,7 +2391,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
private void RemoteAdminOarSaveCompleted(Guid uuid, string name)
{
m_log.DebugFormat("[RADMIN] File processing complete for {0}", name);
m_log.DebugFormat("[RADMIN]: File processing complete for {0}", name);
lock (m_saveOarLock) Monitor.Pulse(m_saveOarLock);
}
@ -2353,14 +2429,14 @@ namespace OpenSim.ApplicationPlugins.RemoteController
UUID region_uuid = (UUID) (string) requestData["region_uuid"];
if (!m_application.SceneManager.TrySetCurrentScene(region_uuid))
throw new Exception(String.Format("failed to switch to region {0}", region_uuid.ToString()));
m_log.InfoFormat("[RADMIN] Switched to region {0}", region_uuid.ToString());
m_log.InfoFormat("[RADMIN]: Switched to region {0}", region_uuid.ToString());
}
else if (requestData.Contains("region_name"))
{
string region_name = (string) requestData["region_name"];
if (!m_application.SceneManager.TrySetCurrentScene(region_name))
throw new Exception(String.Format("failed to switch to region {0}", region_name));
m_log.InfoFormat("[RADMIN] Switched to region {0}", region_name);
m_log.InfoFormat("[RADMIN]: Switched to region {0}", region_name);
}
else throw new Exception("neither region_name nor region_uuid given");
@ -2391,8 +2467,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
}
catch (Exception e)
{
m_log.InfoFormat("[RADMIN] LoadXml: {0}", e.Message);
m_log.DebugFormat("[RADMIN] LoadXml: {0}", e.ToString());
m_log.ErrorFormat("[RADMIN] LoadXml: {0} {1}", e.Message, e.StackTrace);
responseData["loaded"] = false;
responseData["switched"] = false;
@ -2438,14 +2513,14 @@ namespace OpenSim.ApplicationPlugins.RemoteController
UUID region_uuid = (UUID) (string) requestData["region_uuid"];
if (!m_application.SceneManager.TrySetCurrentScene(region_uuid))
throw new Exception(String.Format("failed to switch to region {0}", region_uuid.ToString()));
m_log.InfoFormat("[RADMIN] Switched to region {0}", region_uuid.ToString());
m_log.InfoFormat("[RADMIN]: Switched to region {0}", region_uuid.ToString());
}
else if (requestData.Contains("region_name"))
{
string region_name = (string) requestData["region_name"];
if (!m_application.SceneManager.TrySetCurrentScene(region_name))
throw new Exception(String.Format("failed to switch to region {0}", region_name));
m_log.InfoFormat("[RADMIN] Switched to region {0}", region_name);
m_log.InfoFormat("[RADMIN]: Switched to region {0}", region_name);
}
else throw new Exception("neither region_name nor region_uuid given");
@ -2477,8 +2552,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
}
catch (Exception e)
{
m_log.InfoFormat("[RADMIN] SaveXml: {0}", e.Message);
m_log.DebugFormat("[RADMIN] SaveXml: {0}", e.ToString());
m_log.ErrorFormat("[RADMIN]: SaveXml: {0} {1}", e.Message, e.StackTrace);
responseData["saved"] = false;
responseData["switched"] = false;
@ -2517,14 +2591,14 @@ namespace OpenSim.ApplicationPlugins.RemoteController
UUID region_uuid = (UUID) (string) requestData["region_uuid"];
if (!m_application.SceneManager.TrySetCurrentScene(region_uuid))
throw new Exception(String.Format("failed to switch to region {0}", region_uuid.ToString()));
m_log.InfoFormat("[RADMIN] Switched to region {0}", region_uuid.ToString());
m_log.InfoFormat("[RADMIN]: Switched to region {0}", region_uuid.ToString());
}
else if (requestData.Contains("region_name"))
{
string region_name = (string) requestData["region_name"];
if (!m_application.SceneManager.TrySetCurrentScene(region_name))
throw new Exception(String.Format("failed to switch to region {0}", region_name));
m_log.InfoFormat("[RADMIN] Switched to region {0}", region_name);
m_log.InfoFormat("[RADMIN]: Switched to region {0}", region_name);
}
else throw new Exception("neither region_name nor region_uuid given");
@ -2536,7 +2610,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
}
catch (Exception e)
{
m_log.InfoFormat("[RADMIN] RegionQuery: {0}", e.Message);
m_log.InfoFormat("[RADMIN]: RegionQuery: {0}", e.Message);
responseData["success"] = false;
responseData["error"] = e.Message;
@ -2577,7 +2651,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
}
catch (Exception e)
{
m_log.InfoFormat("[RADMIN] ConsoleCommand: {0}", e.Message);
m_log.InfoFormat("[RADMIN]: ConsoleCommand: {0}", e.Message);
responseData["success"] = false;
responseData["error"] = e.Message;
@ -2614,14 +2688,14 @@ namespace OpenSim.ApplicationPlugins.RemoteController
UUID region_uuid = (UUID) (string) requestData["region_uuid"];
if (!m_application.SceneManager.TrySetCurrentScene(region_uuid))
throw new Exception(String.Format("failed to switch to region {0}", region_uuid.ToString()));
m_log.InfoFormat("[RADMIN] Switched to region {0}", region_uuid.ToString());
m_log.InfoFormat("[RADMIN]: Switched to region {0}", region_uuid.ToString());
}
else if (requestData.Contains("region_name"))
{
string region_name = (string) requestData["region_name"];
if (!m_application.SceneManager.TrySetCurrentScene(region_name))
throw new Exception(String.Format("failed to switch to region {0}", region_name));
m_log.InfoFormat("[RADMIN] Switched to region {0}", region_name);
m_log.InfoFormat("[RADMIN]: Switched to region {0}", region_name);
}
else throw new Exception("neither region_name nor region_uuid given");
@ -2632,7 +2706,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
}
catch (Exception e)
{
m_log.InfoFormat("[RADMIN] Access List Clear Request: {0}", e.Message);
m_log.ErrorFormat("[RADMIN]: Access List Clear Request: {0} {1}", e.Message, e.StackTrace);
responseData["success"] = false;
responseData["error"] = e.Message;
@ -2671,14 +2745,14 @@ namespace OpenSim.ApplicationPlugins.RemoteController
UUID region_uuid = (UUID) (string) requestData["region_uuid"];
if (!m_application.SceneManager.TrySetCurrentScene(region_uuid))
throw new Exception(String.Format("failed to switch to region {0}", region_uuid.ToString()));
m_log.InfoFormat("[RADMIN] Switched to region {0}", region_uuid.ToString());
m_log.InfoFormat("[RADMIN]: Switched to region {0}", region_uuid.ToString());
}
else if (requestData.Contains("region_name"))
{
string region_name = (string) requestData["region_name"];
if (!m_application.SceneManager.TrySetCurrentScene(region_name))
throw new Exception(String.Format("failed to switch to region {0}", region_name));
m_log.InfoFormat("[RADMIN] Switched to region {0}", region_name);
m_log.InfoFormat("[RADMIN]: Switched to region {0}", region_name);
}
else throw new Exception("neither region_name nor region_uuid given");
@ -2698,7 +2772,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
if (account != null)
{
uuids.Add(account.PrincipalID);
m_log.DebugFormat("[RADMIN] adding \"{0}\" to ACL for \"{1}\"", name, scene.RegionInfo.RegionName);
m_log.DebugFormat("[RADMIN]: adding \"{0}\" to ACL for \"{1}\"", name, scene.RegionInfo.RegionName);
}
}
List<UUID> accessControlList = new List<UUID>(scene.RegionInfo.EstateSettings.EstateAccess);
@ -2719,7 +2793,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
}
catch (Exception e)
{
m_log.InfoFormat("[RADMIN] Access List Add Request: {0}", e.Message);
m_log.ErrorFormat("[RADMIN]: Access List Add Request: {0} {1}", e.Message, e.StackTrace);
responseData["success"] = false;
responseData["error"] = e.Message;
@ -2758,14 +2832,14 @@ namespace OpenSim.ApplicationPlugins.RemoteController
UUID region_uuid = (UUID) (string) requestData["region_uuid"];
if (!m_application.SceneManager.TrySetCurrentScene(region_uuid))
throw new Exception(String.Format("failed to switch to region {0}", region_uuid.ToString()));
m_log.InfoFormat("[RADMIN] Switched to region {0}", region_uuid.ToString());
m_log.InfoFormat("[RADMIN]: Switched to region {0}", region_uuid.ToString());
}
else if (requestData.Contains("region_name"))
{
string region_name = (string) requestData["region_name"];
if (!m_application.SceneManager.TrySetCurrentScene(region_name))
throw new Exception(String.Format("failed to switch to region {0}", region_name));
m_log.InfoFormat("[RADMIN] Switched to region {0}", region_name);
m_log.InfoFormat("[RADMIN]: Switched to region {0}", region_name);
}
else throw new Exception("neither region_name nor region_uuid given");
@ -2806,7 +2880,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
}
catch (Exception e)
{
m_log.InfoFormat("[RADMIN] Access List Remove Request: {0}", e.Message);
m_log.ErrorFormat("[RADMIN]: Access List Remove Request: {0} {1}", e.Message, e.StackTrace);
responseData["success"] = false;
responseData["error"] = e.Message;
@ -2845,14 +2919,14 @@ namespace OpenSim.ApplicationPlugins.RemoteController
UUID region_uuid = (UUID) (string) requestData["region_uuid"];
if (!m_application.SceneManager.TrySetCurrentScene(region_uuid))
throw new Exception(String.Format("failed to switch to region {0}", region_uuid.ToString()));
m_log.InfoFormat("[RADMIN] Switched to region {0}", region_uuid.ToString());
m_log.InfoFormat("[RADMIN]: Switched to region {0}", region_uuid.ToString());
}
else if (requestData.Contains("region_name"))
{
string region_name = (string) requestData["region_name"];
if (!m_application.SceneManager.TrySetCurrentScene(region_name))
throw new Exception(String.Format("failed to switch to region {0}", region_name));
m_log.InfoFormat("[RADMIN] Switched to region {0}", region_name);
m_log.InfoFormat("[RADMIN]: Switched to region {0}", region_name);
}
else throw new Exception("neither region_name nor region_uuid given");
@ -2874,7 +2948,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
}
catch (Exception e)
{
m_log.InfoFormat("[RADMIN] Acces List List: {0}", e.Message);
m_log.ErrorFormat("[RADMIN]: Access List List: {0} {1}", e.Message, e.StackTrace);
responseData["success"] = false;
responseData["error"] = e.Message;

View File

@ -66,8 +66,8 @@ namespace OpenSim.Client.MXP.ClientStack
private readonly IScene m_scene;
private readonly string m_firstName;
private readonly string m_lastName;
private int m_objectsToSynchronize = 0;
private int m_objectsSynchronized = -1;
// private int m_objectsToSynchronize = 0;
// private int m_objectsSynchronized = -1;
private Vector3 m_startPosition=new Vector3(128f, 128f, 128f);
#endregion
@ -462,8 +462,8 @@ namespace OpenSim.Client.MXP.ClientStack
public void MXPSendSynchronizationBegin(int objectCount)
{
m_objectsToSynchronize = objectCount;
m_objectsSynchronized = 0;
// m_objectsToSynchronize = objectCount;
// m_objectsSynchronized = 0;
SynchronizationBeginEventMessage synchronizationBeginEventMessage = new SynchronizationBeginEventMessage();
synchronizationBeginEventMessage.ObjectCount = (uint)objectCount;
Session.Send(synchronizationBeginEventMessage);
@ -1337,12 +1337,12 @@ namespace OpenSim.Client.MXP.ClientStack
// Need to translate to MXP somehow
}
public void SendObjectPropertiesFamilyData(uint RequestFlags, UUID ObjectUUID, UUID OwnerID, UUID GroupID, uint BaseMask, uint OwnerMask, uint GroupMask, uint EveryoneMask, uint NextOwnerMask, int OwnershipCost, byte SaleType, int SalePrice, uint Category, UUID LastOwnerID, string ObjectName, string Description)
public void SendObjectPropertiesFamilyData(ISceneEntity Entity, uint RequestFlags)
{
//throw new System.NotImplementedException();
}
public void SendObjectPropertiesReply(UUID ItemID, ulong CreationDate, UUID CreatorUUID, UUID FolderUUID, UUID FromTaskUUID, UUID GroupUUID, short InventorySerial, UUID LastOwnerUUID, UUID ObjectUUID, UUID OwnerUUID, string TouchTitle, byte[] TextureID, string SitTitle, string ItemName, string ItemDescription, uint OwnerMask, uint NextOwnerMask, uint GroupMask, uint EveryoneMask, uint BaseMask, byte saleType, int salePrice)
public void SendObjectPropertiesReply(ISceneEntity entity)
{
//throw new System.NotImplementedException();
}

View File

@ -884,12 +884,12 @@ namespace OpenSim.Client.VWoHTTP.ClientStack
throw new System.NotImplementedException();
}
public void SendObjectPropertiesFamilyData(uint RequestFlags, UUID ObjectUUID, UUID OwnerID, UUID GroupID, uint BaseMask, uint OwnerMask, uint GroupMask, uint EveryoneMask, uint NextOwnerMask, int OwnershipCost, byte SaleType, int SalePrice, uint Category, UUID LastOwnerID, string ObjectName, string Description)
public void SendObjectPropertiesFamilyData(ISceneEntity Entity, uint RequestFlags)
{
throw new System.NotImplementedException();
}
public void SendObjectPropertiesReply(UUID ItemID, ulong CreationDate, UUID CreatorUUID, UUID FolderUUID, UUID FromTaskUUID, UUID GroupUUID, short InventorySerial, UUID LastOwnerUUID, UUID ObjectUUID, UUID OwnerUUID, string TouchTitle, byte[] TextureID, string SitTitle, string ItemName, string ItemDescription, uint OwnerMask, uint NextOwnerMask, uint GroupMask, uint EveryoneMask, uint BaseMask, byte saleType, int salePrice)
public void SendObjectPropertiesReply(ISceneEntity entity)
{
throw new System.NotImplementedException();
}

View File

@ -43,7 +43,7 @@ namespace OpenSim.Data.MSSQL
public class MSSQLAvatarData : MSSQLGenericTableHandler<AvatarBaseData>,
IAvatarData
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public MSSQLAvatarData(string connectionString, string realm) :
base(connectionString, realm, "Avatar")

View File

@ -372,6 +372,11 @@ namespace OpenSim.Data.MSSQL
return new List<int>();
}
public List<int> GetEstatesByOwner(UUID ownerID)
{
return new List<int>();
}
public bool LinkRegion(UUID regionID, int estateID)
{
// TODO: Implementation!

View File

@ -40,8 +40,8 @@ namespace OpenSim.Data.MSSQL
{
public class MSSQLGenericTableHandler<T> where T : class, new()
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// private static readonly ILog m_log =
// LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected string m_ConnectionString;
protected MSSQLManager m_database; //used for parameter type translation

View File

@ -43,7 +43,7 @@ namespace OpenSim.Data.MSSQL
public class MSSQLGridUserData : MSSQLGenericTableHandler<GridUserData>,
IGridUserData
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public MSSQLGridUserData(string connectionString, string realm) :
base(connectionString, realm, "GridUserStore")

View File

@ -41,7 +41,7 @@ namespace OpenSim.Data.MSSQL
/// </summary>
public class MSSQLManager
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Connection string for ADO.net
@ -180,8 +180,6 @@ namespace OpenSim.Data.MSSQL
return parameter;
}
private static readonly Dictionary<string, string> emptyDictionary = new Dictionary<string, string>();
/// <summary>
/// Checks if we need to do some migrations to the database
/// </summary>

View File

@ -43,7 +43,7 @@ namespace OpenSim.Data.MSSQL
public class MSSQLPresenceData : MSSQLGenericTableHandler<PresenceData>,
IPresenceData
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public MSSQLPresenceData(string connectionString, string realm) :
base(connectionString, realm, "Presence")

View File

@ -40,8 +40,8 @@ namespace OpenSim.Data.MSSQL
{
public class MSSQLXInventoryData : IXInventoryData
{
private static readonly ILog m_log = LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
// private static readonly ILog m_log = LogManager.GetLogger(
// MethodBase.GetCurrentMethod().DeclaringType);
private MSSQLGenericTableHandler<XInventoryFolder> m_Folders;
private MSSQLItemHandler m_Items;

View File

@ -484,6 +484,36 @@ namespace OpenSim.Data.MySQL
return result;
}
public List<int> GetEstatesByOwner(UUID ownerID)
{
List<int> result = new List<int>();
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))
{
dbcon.Open();
using (MySqlCommand cmd = dbcon.CreateCommand())
{
cmd.CommandText = "select estateID from estate_settings where EstateOwner = ?EstateOwner";
cmd.Parameters.AddWithValue("?EstateOwner", ownerID);
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
result.Add(Convert.ToInt32(reader["EstateID"]));
}
reader.Close();
}
}
dbcon.Close();
}
return result;
}
public bool LinkRegion(UUID regionID, int estateID)
{
using (MySqlConnection dbcon = new MySqlConnection(m_connectionString))

View File

@ -39,6 +39,8 @@ 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>();
@ -217,7 +219,6 @@ namespace OpenSim.Data.MySQL
{
using (MySqlCommand cmd = new MySqlCommand())
{
string query = "";
List<String> names = new List<String>();
List<String> values = new List<String>();
@ -226,6 +227,16 @@ namespace OpenSim.Data.MySQL
{
names.Add(fi.Name);
values.Add("?" + fi.Name);
// Temporarily return more information about what field is unexpectedly null for
// http://opensimulator.org/mantis/view.php?id=5403. This might be due to a bug in the
// InventoryTransferModule or we may be required to substitute a DBNull here.
if (fi.GetValue(row) == null)
throw new NullReferenceException(
string.Format(
"[MYSQL GENERIC TABLE HANDLER]: Trying to store field {0} for {1} which is unexpectedly null",
fi.Name, row));
cmd.Parameters.AddWithValue(fi.Name, fi.GetValue(row).ToString());
}

View File

@ -0,0 +1,133 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Data.Null
{
public class NullEstateStore : IEstateDataStore
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// private string m_connectionString;
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
public NullEstateStore()
{
}
public NullEstateStore(string connectionString)
{
Initialise(connectionString);
}
public void Initialise(string connectionString)
{
// m_connectionString = connectionString;
}
private string[] FieldList
{
get { return new string[0]; }
}
public EstateSettings LoadEstateSettings(UUID regionID, bool create)
{
// This fools the initialization caller into thinking an estate was fetched (a check in OpenSimBase).
// The estate info is pretty empty so don't try banning anyone.
EstateSettings oneEstate = new EstateSettings();
oneEstate.EstateID = 1;
return oneEstate;
}
public void StoreEstateSettings(EstateSettings es)
{
return;
}
public EstateSettings LoadEstateSettings(int estateID)
{
return new EstateSettings();
}
public List<EstateSettings> LoadEstateSettingsAll()
{
List<EstateSettings> allEstateSettings = new List<EstateSettings>();
allEstateSettings.Add(new EstateSettings());
return allEstateSettings;
}
public List<int> GetEstatesAll()
{
List<int> result = new List<int>();
return result;
}
public List<int> GetEstates(string search)
{
List<int> result = new List<int>();
return result;
}
public bool LinkRegion(UUID regionID, int estateID)
{
return false;
}
public List<UUID> GetRegions(int estateID)
{
List<UUID> result = new List<UUID>();
return result;
}
public bool DeleteEstate(int estateID)
{
return false;
}
#region IEstateDataStore Members
public List<int> GetEstatesByOwner(UUID ownerID)
{
return new List<int>();
}
#endregion
}
}

View File

@ -38,6 +38,15 @@ namespace OpenSim.Data.Null
/// </summary>
public class NullSimulationData : ISimulationDataStore
{
public NullSimulationData()
{
}
public NullSimulationData(string connectionString)
{
Initialise(connectionString);
}
public void Initialise(string dbfile)
{
return;
@ -85,12 +94,20 @@ namespace OpenSim.Data.Null
return new List<SceneObjectGroup>();
}
Dictionary<UUID, double[,]> m_terrains = new Dictionary<UUID, double[,]>();
public void StoreTerrain(double[,] ter, UUID regionID)
{
if (m_terrains.ContainsKey(regionID))
m_terrains.Remove(regionID);
m_terrains.Add(regionID, ter);
}
public double[,] LoadTerrain(UUID regionID)
{
if (m_terrains.ContainsKey(regionID))
{
return m_terrains[regionID];
}
return null;
}

View File

@ -412,6 +412,28 @@ namespace OpenSim.Data.SQLite
return result;
}
public List<int> GetEstatesByOwner(UUID ownerID)
{
List<int> result = new List<int>();
string sql = "select EstateID from estate_settings where estate_settings.EstateOwner = :EstateOwner";
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = sql;
cmd.Parameters.AddWithValue(":EstateOwner", ownerID);
IDataReader r = cmd.ExecuteReader();
while (r.Read())
{
result.Add(Convert.ToInt32(r["EstateID"]));
}
r.Close();
return result;
}
public bool LinkRegion(UUID regionID, int estateID)
{
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();

View File

@ -1,65 +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.Reflection;
using System.Runtime.InteropServices;
// General information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly : AssemblyTitle("OpenSim.Data.SQLiteLegacy")]
[assembly : AssemblyDescription("")]
[assembly : AssemblyConfiguration("")]
[assembly : AssemblyCompany("http://opensimulator.org")]
[assembly : AssemblyProduct("OpenSim.Data.SQLiteLegacy")]
[assembly : AssemblyCopyright("Copyright (c) OpenSimulator.org Developers 2007-2009")]
[assembly : AssemblyTrademark("")]
[assembly : AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly : ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly : Guid("6113d5ce-4547-49f4-9236-0dcc503457b1")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly : AssemblyVersion("0.6.5.*")]
[assembly : AssemblyFileVersion("0.6.5.0")]

View File

@ -1,12 +0,0 @@
BEGIN TRANSACTION;
CREATE TABLE assets(
UUID varchar(255) primary key,
Name varchar(255),
Description varchar(255),
Type integer,
InvType integer,
Local integer,
Temporary integer,
Data blob);
COMMIT;

View File

@ -1,18 +0,0 @@
BEGIN TRANSACTION;
CREATE TABLE auth (
UUID char(36) NOT NULL,
passwordHash char(32) NOT NULL default '',
passwordSalt char(32) NOT NULL default '',
webLoginKey varchar(255) NOT NULL default '',
accountType VARCHAR(32) NOT NULL DEFAULT 'UserAccount',
PRIMARY KEY (`UUID`)
);
CREATE TABLE tokens (
UUID char(36) NOT NULL,
token varchar(255) NOT NULL,
validity datetime NOT NULL
);
COMMIT;

View File

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

View File

@ -1,10 +0,0 @@
BEGIN TRANSACTION;
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`));
COMMIT;

View File

@ -1,32 +0,0 @@
BEGIN TRANSACTION;
CREATE TABLE inventoryfolders(
UUID varchar(255) primary key,
name varchar(255),
agentID varchar(255),
parentID varchar(255),
type integer,
version integer);
CREATE TABLE inventoryitems(
UUID varchar(255) primary key,
assetID varchar(255),
assetType integer,
invType integer,
parentFolderID varchar(255),
avatarID varchar(255),
creatorsID varchar(255),
inventoryName varchar(255),
inventoryDescription varchar(255),
inventoryNextPermissions integer,
inventoryCurrentPermissions integer,
inventoryBasePermissions integer,
inventoryEveryOnePermissions integer,
salePrice integer default 99,
saleType integer default 0,
creationDate integer default 2000,
groupID varchar(255) default '00000000-0000-0000-0000-000000000000',
groupOwned integer default 0,
flags integer default 0);
COMMIT;

View File

@ -1,144 +0,0 @@
BEGIN TRANSACTION;
CREATE TABLE prims(
UUID varchar(255) primary key,
RegionUUID varchar(255),
ParentID integer,
CreationDate integer,
Name varchar(255),
SceneGroupID varchar(255),
Text varchar(255),
Description varchar(255),
SitName varchar(255),
TouchName varchar(255),
CreatorID varchar(255),
OwnerID varchar(255),
GroupID varchar(255),
LastOwnerID varchar(255),
OwnerMask integer,
NextOwnerMask integer,
GroupMask integer,
EveryoneMask integer,
BaseMask integer,
PositionX float,
PositionY float,
PositionZ float,
GroupPositionX float,
GroupPositionY float,
GroupPositionZ float,
VelocityX float,
VelocityY float,
VelocityZ float,
AngularVelocityX float,
AngularVelocityY float,
AngularVelocityZ float,
AccelerationX float,
AccelerationY float,
AccelerationZ float,
RotationX float,
RotationY float,
RotationZ float,
RotationW float,
ObjectFlags integer,
SitTargetOffsetX float NOT NULL default 0,
SitTargetOffsetY float NOT NULL default 0,
SitTargetOffsetZ float NOT NULL default 0,
SitTargetOrientW float NOT NULL default 0,
SitTargetOrientX float NOT NULL default 0,
SitTargetOrientY float NOT NULL default 0,
SitTargetOrientZ float NOT NULL default 0);
CREATE TABLE primshapes(
UUID varchar(255) primary key,
Shape integer,
ScaleX float,
ScaleY float,
ScaleZ float,
PCode integer,
PathBegin integer,
PathEnd integer,
PathScaleX integer,
PathScaleY integer,
PathShearX integer,
PathShearY integer,
PathSkew integer,
PathCurve integer,
PathRadiusOffset integer,
PathRevolutions integer,
PathTaperX integer,
PathTaperY integer,
PathTwist integer,
PathTwistBegin integer,
ProfileBegin integer,
ProfileEnd integer,
ProfileCurve integer,
ProfileHollow integer,
Texture blob,
ExtraParams blob,
State Integer NOT NULL default 0);
CREATE TABLE primitems(
itemID varchar(255) primary key,
primID varchar(255),
assetID varchar(255),
parentFolderID varchar(255),
invType integer,
assetType integer,
name varchar(255),
description varchar(255),
creationDate integer,
creatorID varchar(255),
ownerID varchar(255),
lastOwnerID varchar(255),
groupID varchar(255),
nextPermissions string,
currentPermissions string,
basePermissions string,
everyonePermissions string,
groupPermissions string);
CREATE TABLE terrain(
RegionUUID varchar(255),
Revision integer,
Heightfield blob);
CREATE TABLE land(
UUID varchar(255) primary key,
RegionUUID varchar(255),
LocalLandID string,
Bitmap blob,
Name varchar(255),
Desc varchar(255),
OwnerUUID varchar(255),
IsGroupOwned string,
Area integer,
AuctionID integer,
Category integer,
ClaimDate integer,
ClaimPrice integer,
GroupUUID varchar(255),
SalePrice integer,
LandStatus integer,
LandFlags string,
LandingType string,
MediaAutoScale string,
MediaTextureUUID varchar(255),
MediaURL varchar(255),
MusicURL varchar(255),
PassHours float,
PassPrice string,
SnapshotUUID varchar(255),
UserLocationX float,
UserLocationY float,
UserLocationZ float,
UserLookAtX float,
UserLookAtY float,
UserLookAtZ float,
AuthbuyerID varchar(36) NOT NULL default '00000000-0000-0000-0000-000000000000');
CREATE TABLE landaccesslist(
LandUUID varchar(255),
AccessUUID varchar(255),
Flags string);
COMMIT;

View File

@ -1,17 +0,0 @@
BEGIN TRANSACTION;
-- useraccounts table
CREATE TABLE UserAccounts (
PrincipalID CHAR(36) primary key,
ScopeID CHAR(36) NOT NULL,
FirstName VARCHAR(64) NOT NULL,
LastName VARCHAR(64) NOT NULL,
Email VARCHAR(64),
ServiceURLs TEXT,
Created INT(11),
UserLevel integer NOT NULL DEFAULT 0,
UserFlags integer NOT NULL DEFAULT 0,
UserTitle varchar(64) NOT NULL DEFAULT ''
);
COMMIT;

View File

@ -1,39 +0,0 @@
BEGIN TRANSACTION;
-- users table
CREATE TABLE users(
UUID varchar(255) primary key,
username varchar(255),
surname varchar(255),
passwordHash varchar(255),
passwordSalt varchar(255),
homeRegionX integer,
homeRegionY integer,
homeLocationX float,
homeLocationY float,
homeLocationZ float,
homeLookAtX float,
homeLookAtY float,
homeLookAtZ float,
created integer,
lastLogin integer,
rootInventoryFolderID varchar(255),
userInventoryURI varchar(255),
userAssetURI varchar(255),
profileCanDoMask integer,
profileWantDoMask integer,
profileAboutText varchar(255),
profileFirstText varchar(255),
profileImage varchar(255),
profileFirstImage varchar(255),
webLoginKey text default '00000000-0000-0000-0000-000000000000');
-- friends table
CREATE TABLE userfriends(
ownerID varchar(255),
friendID varchar(255),
friendPerms integer,
ownerPerms integer,
datetimestamp integer);
COMMIT;

View File

@ -1,10 +0,0 @@
BEGIN TRANSACTION;
CREATE TEMPORARY TABLE assets_backup(UUID,Name,Description,Type,Local,Temporary,Data);
INSERT INTO assets_backup SELECT UUID,Name,Description,Type,Local,Temporary,Data FROM assets;
DROP TABLE assets;
CREATE TABLE assets(UUID,Name,Description,Type,Local,Temporary,Data);
INSERT INTO assets SELECT UUID,Name,Description,Type,Local,Temporary,Data FROM assets_backup;
DROP TABLE assets_backup;
COMMIT;

View File

@ -1,5 +0,0 @@
BEGIN TRANSACTION;
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

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

View File

@ -1,8 +0,0 @@
BEGIN TRANSACTION;
create index inventoryfolders_agentid on inventoryfolders(agentid);
create index inventoryfolders_parentid on inventoryfolders(parentid);
create index inventoryitems_parentfolderid on inventoryitems(parentfolderid);
create index inventoryitems_avatarid on inventoryitems(avatarid);
COMMIT;

View File

@ -1,10 +0,0 @@
BEGIN TRANSACTION;
CREATE TABLE regionban(
regionUUID varchar (255),
bannedUUID varchar (255),
bannedIp varchar (255),
bannedIpHostMask varchar (255)
);
COMMIT;

View File

@ -1,5 +0,0 @@
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, surname AS LastName, '' as Email, '' AS ServiceURLs, created as Created FROM users;
COMMIT;

View File

@ -1,5 +0,0 @@
BEGIN;
ALTER TABLE users add homeRegionID varchar(36) NOT NULL default '00000000-0000-0000-0000-000000000000';
COMMIT;

View File

@ -1 +0,0 @@
DELETE FROM assets WHERE UUID = 'dc4b9f0bd00845c696a401dd947ac621'

View File

@ -1,5 +0,0 @@
BEGIN;
alter table inventoryitems add column inventoryGroupPermissions integer unsigned not null default 0;
COMMIT;

View File

@ -1,5 +0,0 @@
BEGIN;
ALTER TABLE primitems add flags integer not null default 0;
COMMIT;

View File

@ -1,6 +0,0 @@
BEGIN;
ALTER TABLE users add userFlags integer NOT NULL default 0;
ALTER TABLE users add godLevel integer NOT NULL default 0;
COMMIT;

View File

@ -1,7 +0,0 @@
BEGIN;
update assets
set UUID = substr(UUID, 1, 8) || "-" || substr(UUID, 9, 4) || "-" || substr(UUID, 13, 4) || "-" || substr(UUID, 17, 4) || "-" || substr(UUID, 21, 12)
where UUID not like '%-%';
COMMIT;

View File

@ -1,36 +0,0 @@
BEGIN;
update inventoryitems
set UUID = substr(UUID, 1, 8) || "-" || substr(UUID, 9, 4) || "-" || substr(UUID, 13, 4) || "-" || substr(UUID, 17, 4) || "-" || substr(UUID, 21, 12)
where UUID not like '%-%';
update inventoryitems
set assetID = substr(assetID, 1, 8) || "-" || substr(assetID, 9, 4) || "-" || substr(assetID, 13, 4) || "-" || substr(assetID, 17, 4) || "-" || substr(assetID, 21, 12)
where assetID not like '%-%';
update inventoryitems
set parentFolderID = substr(parentFolderID, 1, 8) || "-" || substr(parentFolderID, 9, 4) || "-" || substr(parentFolderID, 13, 4) || "-" || substr(parentFolderID, 17, 4) || "-" || substr(parentFolderID, 21, 12)
where parentFolderID not like '%-%';
update inventoryitems
set avatarID = substr(avatarID, 1, 8) || "-" || substr(avatarID, 9, 4) || "-" || substr(avatarID, 13, 4) || "-" || substr(avatarID, 17, 4) || "-" || substr(avatarID, 21, 12)
where avatarID not like '%-%';
update inventoryitems
set creatorsID = substr(creatorsID, 1, 8) || "-" || substr(creatorsID, 9, 4) || "-" || substr(creatorsID, 13, 4) || "-" || substr(creatorsID, 17, 4) || "-" || substr(creatorsID, 21, 12)
where creatorsID not like '%-%';
update inventoryfolders
set UUID = substr(UUID, 1, 8) || "-" || substr(UUID, 9, 4) || "-" || substr(UUID, 13, 4) || "-" || substr(UUID, 17, 4) || "-" || substr(UUID, 21, 12)
where UUID not like '%-%';
update inventoryfolders
set agentID = substr(agentID, 1, 8) || "-" || substr(agentID, 9, 4) || "-" || substr(agentID, 13, 4) || "-" || substr(agentID, 17, 4) || "-" || substr(agentID, 21, 12)
where agentID not like '%-%';
update inventoryfolders
set parentID = substr(parentID, 1, 8) || "-" || substr(parentID, 9, 4) || "-" || substr(parentID, 13, 4) || "-" || substr(parentID, 17, 4) || "-" || substr(parentID, 21, 12)
where parentID not like '%-%';
COMMIT;

View File

@ -1,38 +0,0 @@
BEGIN;
create table regionsettings (
regionUUID char(36) not null,
block_terraform integer not null,
block_fly integer not null,
allow_damage integer not null,
restrict_pushing integer not null,
allow_land_resell integer not null,
allow_land_join_divide integer not null,
block_show_in_search integer not null,
agent_limit integer not null,
object_bonus float not null,
maturity integer not null,
disable_scripts integer not null,
disable_collisions integer not null,
disable_physics integer not null,
terrain_texture_1 char(36) not null,
terrain_texture_2 char(36) not null,
terrain_texture_3 char(36) not null,
terrain_texture_4 char(36) not null,
elevation_1_nw float not null,
elevation_2_nw float not null,
elevation_1_ne float not null,
elevation_2_ne float not null,
elevation_1_se float not null,
elevation_2_se float not null,
elevation_1_sw float not null,
elevation_2_sw float not null,
water_height float not null,
terrain_raise_limit float not null,
terrain_lower_limit float not null,
use_estate_sun integer not null,
fixed_sun integer not null,
sun_position float not null,
covenant char(36));
COMMIT;

View File

@ -1,6 +0,0 @@
BEGIN;
ALTER TABLE users add customType varchar(32) not null default '';
ALTER TABLE users add partner char(36) not null default '00000000-0000-0000-0000-000000000000';
COMMIT;

View File

@ -1,5 +0,0 @@
BEGIN;
delete from regionsettings;
COMMIT;

View File

@ -1,5 +0,0 @@
BEGIN;
CREATE TABLE `avatarattachments` (`UUID` char(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000', `attachpoint` int(11) NOT NULL DEFAULT 0, `item` char(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000', `asset` char(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000');
COMMIT;

View File

@ -1,102 +0,0 @@
BEGIN TRANSACTION;
CREATE TABLE estate_groups (
EstateID int(10) NOT NULL,
uuid char(36) NOT NULL
);
CREATE TABLE estate_managers (
EstateID int(10) NOT NULL,
uuid char(36) NOT NULL
);
CREATE TABLE estate_map (
RegionID char(36) NOT NULL default '00000000-0000-0000-0000-000000000000',
EstateID int(11) NOT NULL
);
CREATE TABLE estate_settings (
EstateID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
EstateName varchar(64) default NULL,
AbuseEmailToEstateOwner tinyint(4) NOT NULL,
DenyAnonymous tinyint(4) NOT NULL,
ResetHomeOnTeleport tinyint(4) NOT NULL,
FixedSun tinyint(4) NOT NULL,
DenyTransacted tinyint(4) NOT NULL,
BlockDwell tinyint(4) NOT NULL,
DenyIdentified tinyint(4) NOT NULL,
AllowVoice tinyint(4) NOT NULL,
UseGlobalTime tinyint(4) NOT NULL,
PricePerMeter int(11) NOT NULL,
TaxFree tinyint(4) NOT NULL,
AllowDirectTeleport tinyint(4) NOT NULL,
RedirectGridX int(11) NOT NULL,
RedirectGridY int(11) NOT NULL,
ParentEstateID int(10) NOT NULL,
SunPosition double NOT NULL,
EstateSkipScripts tinyint(4) NOT NULL,
BillableFactor float NOT NULL,
PublicAccess tinyint(4) NOT NULL
);
insert into estate_settings (EstateID,EstateName,AbuseEmailToEstateOwner,DenyAnonymous,ResetHomeOnTeleport,FixedSun,DenyTransacted,BlockDwell,DenyIdentified,AllowVoice,UseGlobalTime,PricePerMeter,TaxFree,AllowDirectTeleport,RedirectGridX,RedirectGridY,ParentEstateID,SunPosition,PublicAccess,EstateSkipScripts,BillableFactor) values ( 99, '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
delete from estate_settings;
CREATE TABLE estate_users (
EstateID int(10) NOT NULL,
uuid char(36) NOT NULL
);
CREATE TABLE estateban (
EstateID int(10) NOT NULL,
bannedUUID varchar(36) NOT NULL,
bannedIp varchar(16) NOT NULL,
bannedIpHostMask varchar(16) NOT NULL,
bannedNameMask varchar(64) default NULL
);
drop table regionsettings;
CREATE TABLE regionsettings (
regionUUID char(36) NOT NULL,
block_terraform int(11) NOT NULL,
block_fly int(11) NOT NULL,
allow_damage int(11) NOT NULL,
restrict_pushing int(11) NOT NULL,
allow_land_resell int(11) NOT NULL,
allow_land_join_divide int(11) NOT NULL,
block_show_in_search int(11) NOT NULL,
agent_limit int(11) NOT NULL,
object_bonus float NOT NULL,
maturity int(11) NOT NULL,
disable_scripts int(11) NOT NULL,
disable_collisions int(11) NOT NULL,
disable_physics int(11) NOT NULL,
terrain_texture_1 char(36) NOT NULL,
terrain_texture_2 char(36) NOT NULL,
terrain_texture_3 char(36) NOT NULL,
terrain_texture_4 char(36) NOT NULL,
elevation_1_nw float NOT NULL,
elevation_2_nw float NOT NULL,
elevation_1_ne float NOT NULL,
elevation_2_ne float NOT NULL,
elevation_1_se float NOT NULL,
elevation_2_se float NOT NULL,
elevation_1_sw float NOT NULL,
elevation_2_sw float NOT NULL,
water_height float NOT NULL,
terrain_raise_limit float NOT NULL,
terrain_lower_limit float NOT NULL,
use_estate_sun int(11) NOT NULL,
fixed_sun int(11) NOT NULL,
sun_position float NOT NULL,
covenant char(36) default NULL,
Sandbox tinyint(4) NOT NULL,
PRIMARY KEY (regionUUID)
);
CREATE INDEX estate_ban_estate_id on estateban(EstateID);
CREATE INDEX estate_groups_estate_id on estate_groups(EstateID);
CREATE INDEX estate_managers_estate_id on estate_managers(EstateID);
CREATE INDEX estate_map_estate_id on estate_map(EstateID);
CREATE UNIQUE INDEX estate_map_region_id on estate_map(RegionID);
CREATE INDEX estate_users_estate_id on estate_users(EstateID);
COMMIT;

View File

@ -1,20 +0,0 @@
BEGIN TRANSACTION;
-- usersagents table
CREATE TABLE IF NOT EXISTS useragents(
UUID varchar(255) primary key,
agentIP varchar(255),
agentPort integer,
agentOnline boolean,
sessionID varchar(255),
secureSessionID varchar(255),
regionID varchar(255),
loginTime integer,
logoutTime integer,
currentRegion varchar(255),
currentHandle varchar(255),
currentPosX float,
currentPosY float,
currentPosZ float);
COMMIT;

View File

@ -1,8 +0,0 @@
begin;
alter table estate_settings add column AbuseEmail varchar(255) not null default '';
alter table estate_settings add column EstateOwner varchar(36) not null default '';
commit;

View File

@ -1,7 +0,0 @@
BEGIN TRANSACTION;
ALTER TABLE useragents add currentLookAtX float not null default 128;
ALTER TABLE useragents add currentLookAtY float not null default 128;
ALTER TABLE useragents add currentLookAtZ float not null default 70;
COMMIT;

View File

@ -1,6 +0,0 @@
begin;
alter table estate_settings add column DenyMinors tinyint not null default 0;
commit;

View File

@ -1,5 +0,0 @@
BEGIN TRANSACTION;
ALTER TABLE users add email varchar(250);
COMMIT;

View File

@ -1,8 +0,0 @@
BEGIN;
ALTER TABLE prims ADD COLUMN ColorR integer not null default 0;
ALTER TABLE prims ADD COLUMN ColorG integer not null default 0;
ALTER TABLE prims ADD COLUMN ColorB integer not null default 0;
ALTER TABLE prims ADD COLUMN ColorA integer not null default 0;
COMMIT;

View File

@ -1,11 +0,0 @@
BEGIN;
update users
set UUID = substr(UUID, 1, 8) || "-" || substr(UUID, 9, 4) || "-" || substr(UUID, 13, 4) || "-" || substr(UUID, 17, 4) || "-" || substr(UUID, 21, 12)
where UUID not like '%-%';
update useragents
set UUID = substr(UUID, 1, 8) || "-" || substr(UUID, 9, 4) || "-" || substr(UUID, 13, 4) || "-" || substr(UUID, 17, 4) || "-" || substr(UUID, 21, 12)
where UUID not like '%-%';
COMMIT;

View File

@ -1,5 +0,0 @@
BEGIN;
ALTER TABLE prims ADD COLUMN ClickAction INTEGER NOT NULL default 0;
COMMIT;

View File

@ -1,37 +0,0 @@
BEGIN TRANSACTION;
CREATE TABLE IF NOT EXISTS avatarappearance(
Owner varchar(36) NOT NULL primary key,
BodyItem varchar(36) DEFAULT NULL,
BodyAsset varchar(36) DEFAULT NULL,
SkinItem varchar(36) DEFAULT NULL,
SkinAsset varchar(36) DEFAULT NULL,
HairItem varchar(36) DEFAULT NULL,
HairAsset varchar(36) DEFAULT NULL,
EyesItem varchar(36) DEFAULT NULL,
EyesAsset varchar(36) DEFAULT NULL,
ShirtItem varchar(36) DEFAULT NULL,
ShirtAsset varchar(36) DEFAULT NULL,
PantsItem varchar(36) DEFAULT NULL,
PantsAsset varchar(36) DEFAULT NULL,
ShoesItem varchar(36) DEFAULT NULL,
ShoesAsset varchar(36) DEFAULT NULL,
SocksItem varchar(36) DEFAULT NULL,
SocksAsset varchar(36) DEFAULT NULL,
JacketItem varchar(36) DEFAULT NULL,
JacketAsset varchar(36) DEFAULT NULL,
GlovesItem varchar(36) DEFAULT NULL,
GlovesAsset varchar(36) DEFAULT NULL,
UnderShirtItem varchar(36) DEFAULT NULL,
UnderShirtAsset varchar(36) DEFAULT NULL,
UnderPantsItem varchar(36) DEFAULT NULL,
UnderPantsAsset varchar(36) DEFAULT NULL,
SkirtItem varchar(36) DEFAULT NULL,
SkirtAsset varchar(36) DEFAULT NULL,
Texture blob,
VisualParams blob,
Serial int DEFAULT NULL,
AvatarHeight float DEFAULT NULL
);
COMMIT;

View File

@ -1,28 +0,0 @@
BEGIN;
ALTER TABLE prims ADD COLUMN PayPrice INTEGER NOT NULL default 0;
ALTER TABLE prims ADD COLUMN PayButton1 INTEGER NOT NULL default 0;
ALTER TABLE prims ADD COLUMN PayButton2 INTEGER NOT NULL default 0;
ALTER TABLE prims ADD COLUMN PayButton3 INTEGER NOT NULL default 0;
ALTER TABLE prims ADD COLUMN PayButton4 INTEGER NOT NULL default 0;
ALTER TABLE prims ADD COLUMN LoopedSound varchar(36) NOT NULL default '00000000-0000-0000-0000-000000000000';
ALTER TABLE prims ADD COLUMN LoopedSoundGain float NOT NULL default 0;
ALTER TABLE prims ADD COLUMN TextureAnimation string;
ALTER TABLE prims ADD COLUMN ParticleSystem string;
ALTER TABLE prims ADD COLUMN OmegaX float NOT NULL default 0;
ALTER TABLE prims ADD COLUMN OmegaY float NOT NULL default 0;
ALTER TABLE prims ADD COLUMN OmegaZ float NOT NULL default 0;
ALTER TABLE prims ADD COLUMN CameraEyeOffsetX float NOT NULL default 0;
ALTER TABLE prims ADD COLUMN CameraEyeOffsetY float NOT NULL default 0;
ALTER TABLE prims ADD COLUMN CameraEyeOffsetZ float NOT NULL default 0;
ALTER TABLE prims ADD COLUMN CameraAtOffsetX float NOT NULL default 0;
ALTER TABLE prims ADD COLUMN CameraAtOffsetY float NOT NULL default 0;
ALTER TABLE prims ADD COLUMN CameraAtOffsetZ float NOT NULL default 0;
ALTER TABLE prims ADD COLUMN ForceMouselook string NOT NULL default 0;
ALTER TABLE prims ADD COLUMN ScriptAccessPin INTEGER NOT NULL default 0;
ALTER TABLE prims ADD COLUMN AllowedDrop INTEGER NOT NULL default 0;
ALTER TABLE prims ADD COLUMN DieAtEdge string NOT NULL default 0;
ALTER TABLE prims ADD COLUMN SalePrice INTEGER NOT NULL default 0;
ALTER TABLE prims ADD COLUMN SaleType string NOT NULL default 0;
COMMIT;

View File

@ -1,5 +0,0 @@
BEGIN;
ALTER TABLE prims ADD COLUMN Material INTEGER NOT NULL default 3;
COMMIT;

View File

@ -1,6 +0,0 @@
BEGIN;
ALTER TABLE land ADD COLUMN OtherCleanTime INTEGER NOT NULL default 0;
ALTER TABLE land ADD COLUMN Dwell INTEGER NOT NULL default 0;
COMMIT;

View File

@ -1,8 +0,0 @@
begin;
ALTER TABLE regionsettings ADD COLUMN sunvectorx double NOT NULL default 0;
ALTER TABLE regionsettings ADD COLUMN sunvectory double NOT NULL default 0;
ALTER TABLE regionsettings ADD COLUMN sunvectorz double NOT NULL default 0;
commit;

View File

@ -1,6 +0,0 @@
BEGIN;
ALTER TABLE prims ADD COLUMN CollisionSound varchar(36) NOT NULL default '00000000-0000-0000-0000-000000000000';
ALTER TABLE prims ADD COLUMN CollisionSoundVolume float NOT NULL default 0;
COMMIT;

View File

@ -1,5 +0,0 @@
BEGIN;
ALTER TABLE prims ADD COLUMN VolumeDetect INTEGER NOT NULL DEFAULT 0;
COMMIT;

View File

@ -1,8 +0,0 @@
BEGIN;
CREATE TEMPORARY TABLE prims_backup(UUID,RegionUUID,CreationDate,Name,SceneGroupID,Text,Description,SitName,TouchName,CreatorID,OwnerID,GroupID,LastOwnerID,OwnerMask,NextOwnerMask,GroupMask,EveryoneMask,BaseMask,PositionX,PositionY,PositionZ,GroupPositionX,GroupPositionY,GroupPositionZ,VelocityX,VelocityY,VelocityZ,AngularVelocityX,AngularVelocityY,AngularVelocityZ,AccelerationX,AccelerationY,AccelerationZ,RotationX,RotationY,RotationZ,RotationW,ObjectFlags,SitTargetOffsetX,SitTargetOffsetY,SitTargetOffsetZ,SitTargetOrientW,SitTargetOrientX,SitTargetOrientY,SitTargetOrientZ,ColorR,ColorG,ColorB,ColorA,ClickAction,PayPrice,PayButton1,PayButton2,PayButton3,PayButton4,LoopedSound,LoopedSoundGain,TextureAnimation,ParticleSystem,OmegaX,OmegaY,OmegaZ,CameraEyeOffsetX,CameraEyeOffsetY,CameraEyeOffsetZ,CameraAtOffsetX,CameraAtOffsetY,CameraAtOffsetZ,ForceMouselook,ScriptAccessPin,AllowedDrop,DieAtEdge,SalePrice,SaleType,Material,CollisionSound,CollisionSoundVolume,VolumeDetect);
INSERT INTO prims_backup SELECT UUID,RegionUUID,CreationDate,Name,SceneGroupID,Text,Description,SitName,TouchName,CreatorID,OwnerID,GroupID,LastOwnerID,OwnerMask,NextOwnerMask,GroupMask,EveryoneMask,BaseMask,PositionX,PositionY,PositionZ,GroupPositionX,GroupPositionY,GroupPositionZ,VelocityX,VelocityY,VelocityZ,AngularVelocityX,AngularVelocityY,AngularVelocityZ,AccelerationX,AccelerationY,AccelerationZ,RotationX,RotationY,RotationZ,RotationW,ObjectFlags,SitTargetOffsetX,SitTargetOffsetY,SitTargetOffsetZ,SitTargetOrientW,SitTargetOrientX,SitTargetOrientY,SitTargetOrientZ,ColorR,ColorG,ColorB,ColorA,ClickAction,PayPrice,PayButton1,PayButton2,PayButton3,PayButton4,LoopedSound,LoopedSoundGain,TextureAnimation,ParticleSystem,OmegaX,OmegaY,OmegaZ,CameraEyeOffsetX,CameraEyeOffsetY,CameraEyeOffsetZ,CameraAtOffsetX,CameraAtOffsetY,CameraAtOffsetZ,ForceMouselook,ScriptAccessPin,AllowedDrop,DieAtEdge,SalePrice,SaleType,Material,CollisionSound,CollisionSoundVolume,VolumeDetect FROM prims;
DROP TABLE prims;
CREATE TABLE prims(UUID,RegionUUID,CreationDate,Name,SceneGroupID,Text,Description,SitName,TouchName,CreatorID,OwnerID,GroupID,LastOwnerID,OwnerMask,NextOwnerMask,GroupMask,EveryoneMask,BaseMask,PositionX,PositionY,PositionZ,GroupPositionX,GroupPositionY,GroupPositionZ,VelocityX,VelocityY,VelocityZ,AngularVelocityX,AngularVelocityY,AngularVelocityZ,AccelerationX,AccelerationY,AccelerationZ,RotationX,RotationY,RotationZ,RotationW,ObjectFlags,SitTargetOffsetX,SitTargetOffsetY,SitTargetOffsetZ,SitTargetOrientW,SitTargetOrientX,SitTargetOrientY,SitTargetOrientZ,ColorR,ColorG,ColorB,ColorA,ClickAction,PayPrice,PayButton1,PayButton2,PayButton3,PayButton4,LoopedSound,LoopedSoundGain,TextureAnimation,ParticleSystem,OmegaX,OmegaY,OmegaZ,CameraEyeOffsetX,CameraEyeOffsetY,CameraEyeOffsetZ,CameraAtOffsetX,CameraAtOffsetY,CameraAtOffsetZ,ForceMouselook,ScriptAccessPin,AllowedDrop,DieAtEdge,SalePrice,SaleType,Material,CollisionSound,CollisionSoundVolume,VolumeDetect);
INSERT INTO prims SELECT UUID,RegionUUID,CreationDate,Name,SceneGroupID,Text,Description,SitName,TouchName,CreatorID,OwnerID,GroupID,LastOwnerID,OwnerMask,NextOwnerMask,GroupMask,EveryoneMask,BaseMask,PositionX,PositionY,PositionZ,GroupPositionX,GroupPositionY,GroupPositionZ,VelocityX,VelocityY,VelocityZ,AngularVelocityX,AngularVelocityY,AngularVelocityZ,AccelerationX,AccelerationY,AccelerationZ,RotationX,RotationY,RotationZ,RotationW,ObjectFlags,SitTargetOffsetX,SitTargetOffsetY,SitTargetOffsetZ,SitTargetOrientW,SitTargetOrientX,SitTargetOrientY,SitTargetOrientZ,ColorR,ColorG,ColorB,ColorA,ClickAction,PayPrice,PayButton1,PayButton2,PayButton3,PayButton4,LoopedSound,LoopedSoundGain,TextureAnimation,ParticleSystem,OmegaX,OmegaY,OmegaZ,CameraEyeOffsetX,CameraEyeOffsetY,CameraEyeOffsetZ,CameraAtOffsetX,CameraAtOffsetY,CameraAtOffsetZ,ForceMouselook,ScriptAccessPin,AllowedDrop,DieAtEdge,SalePrice,SaleType,Material,CollisionSound,CollisionSoundVolume,VolumeDetect FROM prims_backup;
DROP TABLE prims_backup;
COMMIT;

View File

@ -1,79 +0,0 @@
BEGIN;
update terrain
set RegionUUID = substr(RegionUUID, 1, 8) || "-" || substr(RegionUUID, 9, 4) || "-" || substr(RegionUUID, 13, 4) || "-" || substr(RegionUUID, 17, 4) || "-" || substr(RegionUUID, 21, 12)
where RegionUUID not like '%-%';
update landaccesslist
set LandUUID = substr(LandUUID, 1, 8) || "-" || substr(LandUUID, 9, 4) || "-" || substr(LandUUID, 13, 4) || "-" || substr(LandUUID, 17, 4) || "-" || substr(LandUUID, 21, 12)
where LandUUID not like '%-%';
update landaccesslist
set AccessUUID = substr(AccessUUID, 1, 8) || "-" || substr(AccessUUID, 9, 4) || "-" || substr(AccessUUID, 13, 4) || "-" || substr(AccessUUID, 17, 4) || "-" || substr(AccessUUID, 21, 12)
where AccessUUID not like '%-%';
update prims
set UUID = substr(UUID, 1, 8) || "-" || substr(UUID, 9, 4) || "-" || substr(UUID, 13, 4) || "-" || substr(UUID, 17, 4) || "-" || substr(UUID, 21, 12)
where UUID not like '%-%';
update prims
set RegionUUID = substr(RegionUUID, 1, 8) || "-" || substr(RegionUUID, 9, 4) || "-" || substr(RegionUUID, 13, 4) || "-" || substr(RegionUUID, 17, 4) || "-" || substr(RegionUUID, 21, 12)
where RegionUUID not like '%-%';
update prims
set SceneGroupID = substr(SceneGroupID, 1, 8) || "-" || substr(SceneGroupID, 9, 4) || "-" || substr(SceneGroupID, 13, 4) || "-" || substr(SceneGroupID, 17, 4) || "-" || substr(SceneGroupID, 21, 12)
where SceneGroupID not like '%-%';
update prims
set CreatorID = substr(CreatorID, 1, 8) || "-" || substr(CreatorID, 9, 4) || "-" || substr(CreatorID, 13, 4) || "-" || substr(CreatorID, 17, 4) || "-" || substr(CreatorID, 21, 12)
where CreatorID not like '%-%';
update prims
set OwnerID = substr(OwnerID, 1, 8) || "-" || substr(OwnerID, 9, 4) || "-" || substr(OwnerID, 13, 4) || "-" || substr(OwnerID, 17, 4) || "-" || substr(OwnerID, 21, 12)
where OwnerID not like '%-%';
update prims
set GroupID = substr(GroupID, 1, 8) || "-" || substr(GroupID, 9, 4) || "-" || substr(GroupID, 13, 4) || "-" || substr(GroupID, 17, 4) || "-" || substr(GroupID, 21, 12)
where GroupID not like '%-%';
update prims
set LastOwnerID = substr(LastOwnerID, 1, 8) || "-" || substr(LastOwnerID, 9, 4) || "-" || substr(LastOwnerID, 13, 4) || "-" || substr(LastOwnerID, 17, 4) || "-" || substr(LastOwnerID, 21, 12)
where LastOwnerID not like '%-%';
update primshapes
set UUID = substr(UUID, 1, 8) || "-" || substr(UUID, 9, 4) || "-" || substr(UUID, 13, 4) || "-" || substr(UUID, 17, 4) || "-" || substr(UUID, 21, 12)
where UUID not like '%-%';
update land
set UUID = substr(UUID, 1, 8) || "-" || substr(UUID, 9, 4) || "-" || substr(UUID, 13, 4) || "-" || substr(UUID, 17, 4) || "-" || substr(UUID, 21, 12)
where UUID not like '%-%';
update land
set RegionUUID = substr(RegionUUID, 1, 8) || "-" || substr(RegionUUID, 9, 4) || "-" || substr(RegionUUID, 13, 4) || "-" || substr(RegionUUID, 17, 4) || "-" || substr(RegionUUID, 21, 12)
where RegionUUID not like '%-%';
update land
set OwnerUUID = substr(OwnerUUID, 1, 8) || "-" || substr(OwnerUUID, 9, 4) || "-" || substr(OwnerUUID, 13, 4) || "-" || substr(OwnerUUID, 17, 4) || "-" || substr(OwnerUUID, 21, 12)
where OwnerUUID not like '%-%';
update land
set GroupUUID = substr(GroupUUID, 1, 8) || "-" || substr(GroupUUID, 9, 4) || "-" || substr(GroupUUID, 13, 4) || "-" || substr(GroupUUID, 17, 4) || "-" || substr(GroupUUID, 21, 12)
where GroupUUID not like '%-%';
update land
set MediaTextureUUID = substr(MediaTextureUUID, 1, 8) || "-" || substr(MediaTextureUUID, 9, 4) || "-" || substr(MediaTextureUUID, 13, 4) || "-" || substr(MediaTextureUUID, 17, 4) || "-" || substr(MediaTextureUUID, 21, 12)
where MediaTextureUUID not like '%-%';
update land
set SnapshotUUID = substr(SnapshotUUID, 1, 8) || "-" || substr(SnapshotUUID, 9, 4) || "-" || substr(SnapshotUUID, 13, 4) || "-" || substr(SnapshotUUID, 17, 4) || "-" || substr(SnapshotUUID, 21, 12)
where SnapshotUUID not like '%-%';
update land
set AuthbuyerID = substr(AuthbuyerID, 1, 8) || "-" || substr(AuthbuyerID, 9, 4) || "-" || substr(AuthbuyerID, 13, 4) || "-" || substr(AuthbuyerID, 17, 4) || "-" || substr(AuthbuyerID, 21, 12)
where AuthbuyerID not like '%-%';
COMMIT;

View File

@ -1,20 +0,0 @@
<Addin id="OpenSim.Data.SQLite" version="0.1">
<Runtime>
<Import assembly="OpenSim.Data.SQLite.dll"/>
</Runtime>
<Dependencies>
<Addin id="OpenSim.Data" version="0.5" />
</Dependencies>
<Extension path = "/OpenSim/GridData">
<Plugin id="SQLiteGridData" provider="OpenSim.Data.SQLite.dll" type="OpenSim.Data.SQLite.SQLiteGridData" />
</Extension>
<Extension path = "/OpenSim/AssetData">
<Plugin id="SQLiteAssetData" provider="OpenSim.Data.SQLite.dll" type="OpenSim.Data.SQLite.SQLiteAssetData" />
</Extension>
<Extension path = "/OpenSim/InventoryData">
<Plugin id="SQLiteInventoryData" provider="OpenSim.Data.SQLite.dll" type="OpenSim.Data.SQLite.SQLiteInventoryStore" />
</Extension>
<Extension path = "/OpenSim/UserData">
<Plugin id="SQLiteUserData" provider="OpenSim.Data.SQLite.dll" type="OpenSim.Data.SQLite.SQLiteUserData" />
</Extension>
</Addin>

View File

@ -1,347 +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.Data;
using System.Reflection;
using System.Collections.Generic;
using log4net;
using Mono.Data.SqliteClient;
using OpenMetaverse;
using OpenSim.Framework;
namespace OpenSim.Data.SQLiteLegacy
{
/// <summary>
/// An asset storage interface for the SQLite database system
/// </summary>
public class SQLiteAssetData : AssetDataBase
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private const string SelectAssetSQL = "select * from assets where UUID=:UUID";
private const string SelectAssetMetadataSQL = "select Name, Description, Type, Temporary, UUID from assets limit :start, :count";
private const string DeleteAssetSQL = "delete from assets where UUID=:UUID";
private const string InsertAssetSQL = "insert into assets(UUID, Name, Description, Type, Local, Temporary, Data) values(:UUID, :Name, :Description, :Type, :Local, :Temporary, :Data)";
private const string UpdateAssetSQL = "update assets set Name=:Name, Description=:Description, Type=:Type, Local=:Local, Temporary=:Temporary, Data=:Data where UUID=:UUID";
private const string assetSelect = "select * from assets";
private SqliteConnection m_conn;
override public void Dispose()
{
if (m_conn != null)
{
m_conn.Close();
m_conn = null;
}
}
/// <summary>
/// <list type="bullet">
/// <item>Initialises AssetData interface</item>
/// <item>Loads and initialises a new SQLite connection and maintains it.</item>
/// <item>use default URI if connect string is empty.</item>
/// </list>
/// </summary>
/// <param name="dbconnect">connect string</param>
override public void Initialise(string dbconnect)
{
if (dbconnect == string.Empty)
{
dbconnect = "URI=file:Asset.db,version=3";
}
m_conn = new SqliteConnection(dbconnect);
m_conn.Open();
Assembly assem = GetType().Assembly;
Migration m = new Migration(m_conn, assem, "AssetStore");
m.Update();
return;
}
/// <summary>
/// Fetch Asset
/// </summary>
/// <param name="uuid">UUID of ... ?</param>
/// <returns>Asset base</returns>
override public AssetBase GetAsset(UUID uuid)
{
lock (this)
{
using (SqliteCommand cmd = new SqliteCommand(SelectAssetSQL, m_conn))
{
cmd.Parameters.Add(new SqliteParameter(":UUID", uuid.ToString()));
using (IDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
AssetBase asset = buildAsset(reader);
reader.Close();
return asset;
}
else
{
reader.Close();
return null;
}
}
}
}
}
/// <summary>
/// Create an asset
/// </summary>
/// <param name="asset">Asset Base</param>
override public void StoreAsset(AssetBase asset)
{
//m_log.Info("[ASSET DB]: Creating Asset " + asset.FullID.ToString());
if (ExistsAsset(asset.FullID))
{
//LogAssetLoad(asset);
lock (this)
{
using (SqliteCommand cmd = new SqliteCommand(UpdateAssetSQL, m_conn))
{
cmd.Parameters.Add(new SqliteParameter(":UUID", asset.FullID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":Name", asset.Name));
cmd.Parameters.Add(new SqliteParameter(":Description", asset.Description));
cmd.Parameters.Add(new SqliteParameter(":Type", asset.Type));
cmd.Parameters.Add(new SqliteParameter(":Local", asset.Local));
cmd.Parameters.Add(new SqliteParameter(":Temporary", asset.Temporary));
cmd.Parameters.Add(new SqliteParameter(":Data", asset.Data));
cmd.ExecuteNonQuery();
}
}
}
else
{
lock (this)
{
using (SqliteCommand cmd = new SqliteCommand(InsertAssetSQL, m_conn))
{
cmd.Parameters.Add(new SqliteParameter(":UUID", asset.FullID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":Name", asset.Name));
cmd.Parameters.Add(new SqliteParameter(":Description", asset.Description));
cmd.Parameters.Add(new SqliteParameter(":Type", asset.Type));
cmd.Parameters.Add(new SqliteParameter(":Local", asset.Local));
cmd.Parameters.Add(new SqliteParameter(":Temporary", asset.Temporary));
cmd.Parameters.Add(new SqliteParameter(":Data", asset.Data));
cmd.ExecuteNonQuery();
}
}
}
}
// /// <summary>
// /// Some... logging functionnality
// /// </summary>
// /// <param name="asset"></param>
// private static void LogAssetLoad(AssetBase asset)
// {
// string temporary = asset.Temporary ? "Temporary" : "Stored";
// string local = asset.Local ? "Local" : "Remote";
//
// int assetLength = (asset.Data != null) ? asset.Data.Length : 0;
//
// m_log.Debug("[ASSET DB]: " +
// string.Format("Loaded {5} {4} Asset: [{0}][{3}] \"{1}\":{2} ({6} bytes)",
// asset.FullID, asset.Name, asset.Description, asset.Type,
// temporary, local, assetLength));
// }
/// <summary>
/// Check if an asset exist in database
/// </summary>
/// <param name="uuid">The asset UUID</param>
/// <returns>True if exist, or false.</returns>
override public bool ExistsAsset(UUID uuid)
{
lock (this) {
using (SqliteCommand cmd = new SqliteCommand(SelectAssetSQL, m_conn))
{
cmd.Parameters.Add(new SqliteParameter(":UUID", uuid.ToString()));
using (IDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
reader.Close();
return true;
}
else
{
reader.Close();
return false;
}
}
}
}
}
/// <summary>
/// Delete an asset from database
/// </summary>
/// <param name="uuid"></param>
public void DeleteAsset(UUID uuid)
{
using (SqliteCommand cmd = new SqliteCommand(DeleteAssetSQL, m_conn))
{
cmd.Parameters.Add(new SqliteParameter(":UUID", uuid.ToString()));
cmd.ExecuteNonQuery();
}
}
/// <summary>
///
/// </summary>
/// <param name="row"></param>
/// <returns></returns>
private static AssetBase buildAsset(IDataReader row)
{
// TODO: this doesn't work yet because something more
// interesting has to be done to actually get these values
// back out. Not enough time to figure it out yet.
AssetBase asset = new AssetBase(
new UUID((String)row["UUID"]),
(String)row["Name"],
Convert.ToSByte(row["Type"]),
UUID.Zero.ToString()
);
asset.Description = (String) row["Description"];
asset.Local = Convert.ToBoolean(row["Local"]);
asset.Temporary = Convert.ToBoolean(row["Temporary"]);
asset.Data = (byte[]) row["Data"];
return asset;
}
private static AssetMetadata buildAssetMetadata(IDataReader row)
{
AssetMetadata metadata = new AssetMetadata();
metadata.FullID = new UUID((string) row["UUID"]);
metadata.Name = (string) row["Name"];
metadata.Description = (string) row["Description"];
metadata.Type = Convert.ToSByte(row["Type"]);
metadata.Temporary = Convert.ToBoolean(row["Temporary"]); // Not sure if this is correct.
// Current SHA1s are not stored/computed.
metadata.SHA1 = new byte[] {};
return metadata;
}
/// <summary>
/// Returns a list of AssetMetadata objects. The list is a subset of
/// the entire data set offset by <paramref name="start" /> containing
/// <paramref name="count" /> elements.
/// </summary>
/// <param name="start">The number of results to discard from the total data set.</param>
/// <param name="count">The number of rows the returned list should contain.</param>
/// <returns>A list of AssetMetadata objects.</returns>
public override List<AssetMetadata> FetchAssetMetadataSet(int start, int count)
{
List<AssetMetadata> retList = new List<AssetMetadata>(count);
lock (this)
{
using (SqliteCommand cmd = new SqliteCommand(SelectAssetMetadataSQL, m_conn))
{
cmd.Parameters.Add(new SqliteParameter(":start", start));
cmd.Parameters.Add(new SqliteParameter(":count", count));
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
AssetMetadata metadata = buildAssetMetadata(reader);
retList.Add(metadata);
}
}
}
}
return retList;
}
/***********************************************************************
*
* Database Binding functions
*
* These will be db specific due to typing, and minor differences
* in databases.
*
**********************************************************************/
#region IPlugin interface
/// <summary>
///
/// </summary>
override public string Version
{
get
{
Module module = GetType().Module;
// string dllName = module.Assembly.ManifestModule.Name;
Version dllVersion = module.Assembly.GetName().Version;
return
string.Format("{0}.{1}.{2}.{3}", dllVersion.Major, dllVersion.Minor, dllVersion.Build,
dllVersion.Revision);
}
}
/// <summary>
/// Initialise the AssetData interface using default URI
/// </summary>
override public void Initialise()
{
Initialise("URI=file:Asset.db,version=3");
}
/// <summary>
/// Name of this DB provider
/// </summary>
override public string Name
{
get { return "SQLite Asset storage engine"; }
}
public override bool Delete(string id)
{
return false;
}
#endregion
}
}

View File

@ -1,266 +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 log4net;
using OpenMetaverse;
using OpenSim.Framework;
using Mono.Data.SqliteClient;
namespace OpenSim.Data.SQLiteLegacy
{
public class SQLiteAuthenticationData : SQLiteFramework, IAuthenticationData
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string m_Realm;
private List<string> m_ColumnNames;
private int m_LastExpire;
private string m_connectionString;
protected static SqliteConnection m_Connection;
private static bool m_initialized = false;
public SQLiteAuthenticationData(string connectionString, string realm)
: base(connectionString)
{
m_Realm = realm;
m_connectionString = connectionString;
if (!m_initialized)
{
m_Connection = new SqliteConnection(connectionString);
m_Connection.Open();
using (SqliteConnection dbcon = (SqliteConnection)((ICloneable)m_Connection).Clone())
{
dbcon.Open();
Migration m = new Migration(dbcon, GetType().Assembly, "AuthStore");
m.Update();
dbcon.Close();
}
m_initialized = true;
}
}
public AuthenticationData Get(UUID principalID)
{
AuthenticationData ret = new AuthenticationData();
ret.Data = new Dictionary<string, object>();
SqliteCommand cmd = new SqliteCommand("select * from `" + m_Realm + "` where UUID = :PrincipalID");
cmd.Parameters.Add(new SqliteParameter(":PrincipalID", principalID.ToString()));
IDataReader result = ExecuteReader(cmd, m_Connection);
try
{
if (result.Read())
{
ret.PrincipalID = principalID;
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;
ret.Data[s] = result[s].ToString();
}
return ret;
}
else
{
return null;
}
}
catch
{
}
finally
{
CloseCommand(cmd);
}
return null;
}
public bool Store(AuthenticationData data)
{
if (data.Data.ContainsKey("UUID"))
data.Data.Remove("UUID");
string[] fields = new List<string>(data.Data.Keys).ToArray();
string[] values = new string[data.Data.Count];
int i = 0;
foreach (object o in data.Data.Values)
values[i++] = o.ToString();
SqliteCommand cmd = new SqliteCommand();
if (Get(data.PrincipalID) != null)
{
string update = "update `" + m_Realm + "` set ";
bool first = true;
foreach (string field in fields)
{
if (!first)
update += ", ";
update += "`" + field + "` = :" + field;
cmd.Parameters.Add(new SqliteParameter(":" + field, data.Data[field]));
first = false;
}
update += " where UUID = :UUID";
cmd.Parameters.Add(new SqliteParameter(":UUID", data.PrincipalID.ToString()));
cmd.CommandText = update;
try
{
if (ExecuteNonQuery(cmd, m_Connection) < 1)
{
CloseCommand(cmd);
return false;
}
}
catch (Exception e)
{
m_log.Error("[SQLITE]: Exception storing authentication data", e);
CloseCommand(cmd);
return false;
}
}
else
{
string insert = "insert into `" + m_Realm + "` (`UUID`, `" +
String.Join("`, `", fields) +
"`) values (:UUID, :" + String.Join(", :", fields) + ")";
cmd.Parameters.Add(new SqliteParameter(":UUID", data.PrincipalID.ToString()));
foreach (string field in fields)
cmd.Parameters.Add(new SqliteParameter(":" + field, data.Data[field]));
cmd.CommandText = insert;
try
{
if (ExecuteNonQuery(cmd, m_Connection) < 1)
{
CloseCommand(cmd);
return false;
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
CloseCommand(cmd);
return false;
}
}
CloseCommand(cmd);
return true;
}
public bool SetDataItem(UUID principalID, string item, string value)
{
SqliteCommand cmd = new SqliteCommand("update `" + m_Realm +
"` set `" + item + "` = " + value + " where UUID = '" + principalID.ToString() + "'");
if (ExecuteNonQuery(cmd, m_Connection) > 0)
return true;
return false;
}
public bool SetToken(UUID principalID, string token, int lifetime)
{
if (System.Environment.TickCount - m_LastExpire > 30000)
DoExpire();
SqliteCommand cmd = new SqliteCommand("insert into tokens (UUID, token, validity) values ('" + principalID.ToString() +
"', '" + token + "', datetime('now', 'localtime', '+" + lifetime.ToString() + " minutes'))");
if (ExecuteNonQuery(cmd, m_Connection) > 0)
{
cmd.Dispose();
return true;
}
cmd.Dispose();
return false;
}
public bool CheckToken(UUID principalID, string token, int lifetime)
{
if (System.Environment.TickCount - m_LastExpire > 30000)
DoExpire();
SqliteCommand cmd = new SqliteCommand("update tokens set validity = datetime('now', 'localtime', '+" + lifetime.ToString() +
" minutes') where UUID = '" + principalID.ToString() + "' and token = '" + token + "' and validity > datetime('now', 'localtime')");
if (ExecuteNonQuery(cmd, m_Connection) > 0)
{
cmd.Dispose();
return true;
}
cmd.Dispose();
return false;
}
private void DoExpire()
{
SqliteCommand cmd = new SqliteCommand("delete from tokens where validity < datetime('now', 'localtime')");
ExecuteNonQuery(cmd, m_Connection);
cmd.Dispose();
m_LastExpire = System.Environment.TickCount;
}
}
}

View File

@ -1,74 +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 OpenMetaverse;
using OpenSim.Framework;
using Mono.Data.SqliteClient;
namespace OpenSim.Data.SQLiteLegacy
{
/// <summary>
/// A SQLite Interface for Avatar Data
/// </summary>
public class SQLiteAvatarData : SQLiteGenericTableHandler<AvatarBaseData>,
IAvatarData
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public SQLiteAvatarData(string connectionString, string realm) :
base(connectionString, realm, "Avatar")
{
}
public bool Delete(UUID principalID, string name)
{
SqliteCommand cmd = new SqliteCommand();
cmd.CommandText = String.Format("delete from {0} where `PrincipalID` = :PrincipalID and `Name` = :Name", m_Realm);
cmd.Parameters.Add(":PrincipalID", principalID.ToString());
cmd.Parameters.Add(":Name", name);
try
{
if (ExecuteNonQuery(cmd, m_Connection) > 0)
return true;
return false;
}
finally
{
CloseCommand(cmd);
}
}
}
}

View File

@ -1,429 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using log4net;
using Mono.Data.SqliteClient;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Data.SQLiteLegacy
{
public class SQLiteEstateStore : IEstateDataStore
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private SqliteConnection m_connection;
private string m_connectionString;
private FieldInfo[] m_Fields;
private Dictionary<string, FieldInfo> m_FieldMap =
new Dictionary<string, FieldInfo>();
public SQLiteEstateStore()
{
}
public SQLiteEstateStore(string connectionString)
{
Initialise(connectionString);
}
public void Initialise(string connectionString)
{
m_connectionString = connectionString;
m_log.Info("[ESTATE DB]: Sqlite - connecting: "+m_connectionString);
m_connection = new SqliteConnection(m_connectionString);
m_connection.Open();
Assembly assem = GetType().Assembly;
Migration m = new Migration(m_connection, assem, "EstateStore");
m.Update();
m_connection.Close();
m_connection.Open();
Type t = typeof(EstateSettings);
m_Fields = t.GetFields(BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
foreach (FieldInfo f in m_Fields)
if (f.Name.Substring(0, 2) == "m_")
m_FieldMap[f.Name.Substring(2)] = f;
}
private string[] FieldList
{
get { return new List<string>(m_FieldMap.Keys).ToArray(); }
}
public EstateSettings LoadEstateSettings(UUID regionID, bool create)
{
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";
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = sql;
cmd.Parameters.Add(":RegionID", regionID.ToString());
return DoLoad(cmd, regionID, create);
}
public List<EstateSettings> LoadEstateSettingsAll()
{
List<EstateSettings> estateSettings = new List<EstateSettings>();
List<int> estateIds = GetEstatesAll();
foreach (int estateId in estateIds)
estateSettings.Add(LoadEstateSettings(estateId));
return estateSettings;
}
private EstateSettings DoLoad(SqliteCommand cmd, UUID regionID, bool create)
{
EstateSettings es = new EstateSettings();
es.OnSave += StoreEstateSettings;
IDataReader r = cmd.ExecuteReader();
if (r.Read())
{
foreach (string name in FieldList)
{
if (m_FieldMap[name].GetValue(es) is bool)
{
int v = Convert.ToInt32(r[name]);
if (v != 0)
m_FieldMap[name].SetValue(es, true);
else
m_FieldMap[name].SetValue(es, false);
}
else if (m_FieldMap[name].GetValue(es) is UUID)
{
UUID uuid = UUID.Zero;
UUID.TryParse(r[name].ToString(), out uuid);
m_FieldMap[name].SetValue(es, uuid);
}
else
{
m_FieldMap[name].SetValue(es, Convert.ChangeType(r[name], m_FieldMap[name].FieldType));
}
}
r.Close();
}
else if (create)
{
r.Close();
List<string> names = new List<string>(FieldList);
names.Remove("EstateID");
string sql = "insert into estate_settings ("+String.Join(",", names.ToArray())+") values ( :"+String.Join(", :", names.ToArray())+")";
cmd.CommandText = sql;
cmd.Parameters.Clear();
foreach (string name in FieldList)
{
if (m_FieldMap[name].GetValue(es) is bool)
{
if ((bool)m_FieldMap[name].GetValue(es))
cmd.Parameters.Add(":"+name, "1");
else
cmd.Parameters.Add(":"+name, "0");
}
else
{
cmd.Parameters.Add(":"+name, m_FieldMap[name].GetValue(es).ToString());
}
}
cmd.ExecuteNonQuery();
cmd.CommandText = "select LAST_INSERT_ROWID() as id";
cmd.Parameters.Clear();
r = cmd.ExecuteReader();
r.Read();
es.EstateID = Convert.ToUInt32(r["id"]);
r.Close();
cmd.CommandText = "insert into estate_map values (:RegionID, :EstateID)";
cmd.Parameters.Add(":RegionID", regionID.ToString());
cmd.Parameters.Add(":EstateID", es.EstateID.ToString());
// This will throw on dupe key
try
{
cmd.ExecuteNonQuery();
}
catch (Exception)
{
}
es.Save();
}
LoadBanList(es);
es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers");
es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users");
es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups");
return es;
}
public void StoreEstateSettings(EstateSettings es)
{
List<string> fields = new List<string>(FieldList);
fields.Remove("EstateID");
List<string> terms = new List<string>();
foreach (string f in fields)
terms.Add(f+" = :"+f);
string sql = "update estate_settings set "+String.Join(", ", terms.ToArray())+" where EstateID = :EstateID";
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = sql;
foreach (string name in FieldList)
{
if (m_FieldMap[name].GetValue(es) is bool)
{
if ((bool)m_FieldMap[name].GetValue(es))
cmd.Parameters.Add(":"+name, "1");
else
cmd.Parameters.Add(":"+name, "0");
}
else
{
cmd.Parameters.Add(":"+name, m_FieldMap[name].GetValue(es).ToString());
}
}
cmd.ExecuteNonQuery();
SaveBanList(es);
SaveUUIDList(es.EstateID, "estate_managers", es.EstateManagers);
SaveUUIDList(es.EstateID, "estate_users", es.EstateAccess);
SaveUUIDList(es.EstateID, "estate_groups", es.EstateGroups);
}
private void LoadBanList(EstateSettings es)
{
es.ClearBans();
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = "select bannedUUID from estateban where EstateID = :EstateID";
cmd.Parameters.Add(":EstateID", es.EstateID);
IDataReader r = cmd.ExecuteReader();
while (r.Read())
{
EstateBan eb = new EstateBan();
UUID uuid = new UUID();
UUID.TryParse(r["bannedUUID"].ToString(), out uuid);
eb.BannedUserID = uuid;
eb.BannedHostAddress = "0.0.0.0";
eb.BannedHostIPMask = "0.0.0.0";
es.AddBan(eb);
}
r.Close();
}
private void SaveBanList(EstateSettings es)
{
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = "delete from estateban where EstateID = :EstateID";
cmd.Parameters.Add(":EstateID", es.EstateID.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "insert into estateban (EstateID, bannedUUID, bannedIp, bannedIpHostMask, bannedNameMask) values ( :EstateID, :bannedUUID, '', '', '' )";
foreach (EstateBan b in es.EstateBans)
{
cmd.Parameters.Add(":EstateID", es.EstateID.ToString());
cmd.Parameters.Add(":bannedUUID", b.BannedUserID.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
}
void SaveUUIDList(uint EstateID, string table, UUID[] data)
{
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = "delete from "+table+" where EstateID = :EstateID";
cmd.Parameters.Add(":EstateID", EstateID.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "insert into "+table+" (EstateID, uuid) values ( :EstateID, :uuid )";
foreach (UUID uuid in data)
{
cmd.Parameters.Add(":EstateID", EstateID.ToString());
cmd.Parameters.Add(":uuid", uuid.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
}
UUID[] LoadUUIDList(uint EstateID, string table)
{
List<UUID> uuids = new List<UUID>();
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = "select uuid from "+table+" where EstateID = :EstateID";
cmd.Parameters.Add(":EstateID", EstateID);
IDataReader r = cmd.ExecuteReader();
while (r.Read())
{
// EstateBan eb = new EstateBan();
UUID uuid = new UUID();
UUID.TryParse(r["uuid"].ToString(), out uuid);
uuids.Add(uuid);
}
r.Close();
return uuids.ToArray();
}
public EstateSettings LoadEstateSettings(int estateID)
{
string sql = "select estate_settings."+String.Join(",estate_settings.", FieldList)+" from estate_settings where estate_settings.EstateID = :EstateID";
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = sql;
cmd.Parameters.Add(":EstateID", estateID.ToString());
return DoLoad(cmd, UUID.Zero, false);
}
public List<int> GetEstates(string search)
{
List<int> result = new List<int>();
string sql = "select EstateID from estate_settings where estate_settings.EstateName = :EstateName";
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = sql;
cmd.Parameters.Add(":EstateName", search);
IDataReader r = cmd.ExecuteReader();
while (r.Read())
{
result.Add(Convert.ToInt32(r["EstateID"]));
}
r.Close();
return result;
}
public List<int> GetEstatesAll()
{
List<int> result = new List<int>();
string sql = "select EstateID from estate_settings";
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = sql;
IDataReader r = cmd.ExecuteReader();
while (r.Read())
{
result.Add(Convert.ToInt32(r["EstateID"]));
}
r.Close();
return result;
}
public bool LinkRegion(UUID regionID, int estateID)
{
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = "insert into estate_map values (:RegionID, :EstateID)";
cmd.Parameters.Add(":RegionID", regionID.ToString());
cmd.Parameters.Add(":EstateID", estateID.ToString());
if (cmd.ExecuteNonQuery() == 0)
return false;
return true;
}
public List<UUID> GetRegions(int estateID)
{
return new List<UUID>();
}
public bool DeleteEstate(int estateID)
{
return false;
}
}
}

View File

@ -1,91 +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 OpenMetaverse;
using OpenSim.Framework;
using Mono.Data.SqliteClient;
namespace OpenSim.Data.SQLiteLegacy
{
/// <summary>
/// A database interface class to a user profile storage system
/// </summary>
public class SQLiteFramework
{
protected Object m_lockObject = new Object();
protected SQLiteFramework(string connectionString)
{
}
//////////////////////////////////////////////////////////////
//
// All non queries are funneled through one connection
// to increase performance a little
//
protected int ExecuteNonQuery(SqliteCommand cmd, SqliteConnection connection)
{
lock (connection)
{
SqliteConnection newConnection =
(SqliteConnection)((ICloneable)connection).Clone();
newConnection.Open();
cmd.Connection = newConnection;
//Console.WriteLine("XXX " + cmd.CommandText);
return cmd.ExecuteNonQuery();
}
}
protected IDataReader ExecuteReader(SqliteCommand cmd, SqliteConnection connection)
{
lock (connection)
{
SqliteConnection newConnection =
(SqliteConnection)((ICloneable)connection).Clone();
newConnection.Open();
cmd.Connection = newConnection;
//Console.WriteLine("XXX " + cmd.CommandText);
return cmd.ExecuteReader();
}
}
protected void CloseCommand(SqliteCommand cmd)
{
cmd.Connection.Close();
cmd.Connection.Dispose();
cmd.Dispose();
}
}
}

View File

@ -1,70 +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 OpenMetaverse;
using OpenSim.Framework;
using Mono.Data.SqliteClient;
namespace OpenSim.Data.SQLiteLegacy
{
public class SQLiteFriendsData : SQLiteGenericTableHandler<FriendsData>, IFriendsData
{
public SQLiteFriendsData(string connectionString, string realm)
: base(connectionString, realm, "FriendsStore")
{
}
public FriendsData[] GetFriends(UUID userID)
{
SqliteCommand cmd = new SqliteCommand();
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.Add(":PrincipalID", userID.ToString());
return DoQuery(cmd);
}
public bool Delete(UUID principalID, string friend)
{
SqliteCommand cmd = new SqliteCommand();
cmd.CommandText = String.Format("delete from {0} where PrincipalID = :PrincipalID and Friend = :Friend", m_Realm);
cmd.Parameters.Add(":PrincipalID", principalID.ToString());
cmd.Parameters.Add(":Friend", friend);
ExecuteNonQuery(cmd, cmd.Connection);
return true;
}
}
}

View File

@ -1,268 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using log4net;
using Mono.Data.SqliteClient;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Data.SQLiteLegacy
{
public class SQLiteGenericTableHandler<T> : SQLiteFramework 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>();
protected List<string> m_ColumnNames = null;
protected string m_Realm;
protected FieldInfo m_DataField = null;
protected static SqliteConnection m_Connection;
private static bool m_initialized;
public SQLiteGenericTableHandler(string connectionString,
string realm, string storeName) : base(connectionString)
{
m_Realm = realm;
if (!m_initialized)
{
m_Connection = new SqliteConnection(connectionString);
m_Connection.Open();
if (storeName != String.Empty)
{
Assembly assem = GetType().Assembly;
SqliteConnection newConnection =
(SqliteConnection)((ICloneable)m_Connection).Clone();
newConnection.Open();
Migration m = new Migration(newConnection, assem, storeName);
m.Update();
newConnection.Close();
newConnection.Dispose();
}
m_initialized = true;
}
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(IDataReader 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());
}
}
public T[] Get(string field, string key)
{
return Get(new string[] { field }, new string[] { key });
}
public T[] Get(string[] fields, string[] keys)
{
if (fields.Length != keys.Length)
return new T[0];
List<string> terms = new List<string>();
SqliteCommand cmd = new SqliteCommand();
for (int i = 0 ; i < fields.Length ; i++)
{
cmd.Parameters.Add(new SqliteParameter(":" + 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.CommandText = query;
return DoQuery(cmd);
}
protected T[] DoQuery(SqliteCommand cmd)
{
IDataReader reader = ExecuteReader(cmd, m_Connection);
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);
}
CloseCommand(cmd);
return result.ToArray();
}
public T[] Get(string where)
{
SqliteCommand cmd = new SqliteCommand();
string query = String.Format("select * from {0} where {1}",
m_Realm, where);
cmd.CommandText = query;
return DoQuery(cmd);
}
public bool Store(T row)
{
SqliteCommand cmd = new SqliteCommand();
string query = "";
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);
cmd.Parameters.Add(new SqliteParameter(":" + 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)
{
names.Add(kvp.Key);
values.Add(":" + kvp.Key);
cmd.Parameters.Add(new SqliteParameter(":" + kvp.Key, kvp.Value));
}
}
query = String.Format("replace into {0} (`", m_Realm) + String.Join("`,`", names.ToArray()) + "`) values (" + String.Join(",", values.ToArray()) + ")";
cmd.CommandText = query;
if (ExecuteNonQuery(cmd, m_Connection) > 0)
return true;
return false;
}
public bool Delete(string field, string val)
{
SqliteCommand cmd = new SqliteCommand();
cmd.CommandText = String.Format("delete from {0} where `{1}` = :{1}", m_Realm, field);
cmd.Parameters.Add(new SqliteParameter(field, val));
if (ExecuteNonQuery(cmd, m_Connection) > 0)
return true;
return false;
}
}
}

View File

@ -1,898 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using log4net;
using Mono.Data.SqliteClient;
using OpenMetaverse;
using OpenSim.Framework;
namespace OpenSim.Data.SQLiteLegacy
{
/// <summary>
/// An Inventory Interface to the SQLite database
/// </summary>
public class SQLiteInventoryStore : SQLiteUtil, IInventoryDataPlugin
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private const string invItemsSelect = "select * from inventoryitems";
private const string invFoldersSelect = "select * from inventoryfolders";
private static SqliteConnection conn;
private static DataSet ds;
private static SqliteDataAdapter invItemsDa;
private static SqliteDataAdapter invFoldersDa;
private static bool m_Initialized = false;
public void Initialise()
{
m_log.Info("[SQLiteInventoryData]: " + Name + " cannot be default-initialized!");
throw new PluginNotInitialisedException(Name);
}
/// <summary>
/// <list type="bullet">
/// <item>Initialises Inventory interface</item>
/// <item>Loads and initialises a new SQLite connection and maintains it.</item>
/// <item>use default URI if connect string string is empty.</item>
/// </list>
/// </summary>
/// <param name="dbconnect">connect string</param>
public void Initialise(string dbconnect)
{
if (!m_Initialized)
{
m_Initialized = true;
if (dbconnect == string.Empty)
{
dbconnect = "URI=file:inventoryStore.db,version=3";
}
m_log.Info("[INVENTORY DB]: Sqlite - connecting: " + dbconnect);
conn = new SqliteConnection(dbconnect);
conn.Open();
Assembly assem = GetType().Assembly;
Migration m = new Migration(conn, assem, "InventoryStore");
m.Update();
SqliteCommand itemsSelectCmd = new SqliteCommand(invItemsSelect, conn);
invItemsDa = new SqliteDataAdapter(itemsSelectCmd);
// SqliteCommandBuilder primCb = new SqliteCommandBuilder(primDa);
SqliteCommand foldersSelectCmd = new SqliteCommand(invFoldersSelect, conn);
invFoldersDa = new SqliteDataAdapter(foldersSelectCmd);
ds = new DataSet();
ds.Tables.Add(createInventoryFoldersTable());
invFoldersDa.Fill(ds.Tables["inventoryfolders"]);
setupFoldersCommands(invFoldersDa, conn);
m_log.Info("[INVENTORY DB]: Populated Inventory Folders Definitions");
ds.Tables.Add(createInventoryItemsTable());
invItemsDa.Fill(ds.Tables["inventoryitems"]);
setupItemsCommands(invItemsDa, conn);
m_log.Info("[INVENTORY DB]: Populated Inventory Items Definitions");
ds.AcceptChanges();
}
}
/// <summary>
/// Closes the inventory interface
/// </summary>
public void Dispose()
{
if (conn != null)
{
conn.Close();
conn = null;
}
if (invItemsDa != null)
{
invItemsDa.Dispose();
invItemsDa = null;
}
if (invFoldersDa != null)
{
invFoldersDa.Dispose();
invFoldersDa = null;
}
if (ds != null)
{
ds.Dispose();
ds = null;
}
}
/// <summary>
///
/// </summary>
/// <param name="row"></param>
/// <returns></returns>
public InventoryItemBase buildItem(DataRow row)
{
InventoryItemBase item = new InventoryItemBase();
item.ID = new UUID((string) row["UUID"]);
item.AssetID = new UUID((string) row["assetID"]);
item.AssetType = Convert.ToInt32(row["assetType"]);
item.InvType = Convert.ToInt32(row["invType"]);
item.Folder = new UUID((string) row["parentFolderID"]);
item.Owner = new UUID((string) row["avatarID"]);
item.CreatorIdentification = (string)row["creatorsID"];
item.Name = (string) row["inventoryName"];
item.Description = (string) row["inventoryDescription"];
item.NextPermissions = Convert.ToUInt32(row["inventoryNextPermissions"]);
item.CurrentPermissions = Convert.ToUInt32(row["inventoryCurrentPermissions"]);
item.BasePermissions = Convert.ToUInt32(row["inventoryBasePermissions"]);
item.EveryOnePermissions = Convert.ToUInt32(row["inventoryEveryOnePermissions"]);
item.GroupPermissions = Convert.ToUInt32(row["inventoryGroupPermissions"]);
// new fields
if (!Convert.IsDBNull(row["salePrice"]))
item.SalePrice = Convert.ToInt32(row["salePrice"]);
if (!Convert.IsDBNull(row["saleType"]))
item.SaleType = Convert.ToByte(row["saleType"]);
if (!Convert.IsDBNull(row["creationDate"]))
item.CreationDate = Convert.ToInt32(row["creationDate"]);
if (!Convert.IsDBNull(row["groupID"]))
item.GroupID = new UUID((string)row["groupID"]);
if (!Convert.IsDBNull(row["groupOwned"]))
item.GroupOwned = Convert.ToBoolean(row["groupOwned"]);
if (!Convert.IsDBNull(row["Flags"]))
item.Flags = Convert.ToUInt32(row["Flags"]);
return item;
}
/// <summary>
/// Fill a database row with item data
/// </summary>
/// <param name="row"></param>
/// <param name="item"></param>
private static void fillItemRow(DataRow row, InventoryItemBase item)
{
row["UUID"] = item.ID.ToString();
row["assetID"] = item.AssetID.ToString();
row["assetType"] = item.AssetType;
row["invType"] = item.InvType;
row["parentFolderID"] = item.Folder.ToString();
row["avatarID"] = item.Owner.ToString();
row["creatorsID"] = item.CreatorIdentification.ToString();
row["inventoryName"] = item.Name;
row["inventoryDescription"] = item.Description;
row["inventoryNextPermissions"] = item.NextPermissions;
row["inventoryCurrentPermissions"] = item.CurrentPermissions;
row["inventoryBasePermissions"] = item.BasePermissions;
row["inventoryEveryOnePermissions"] = item.EveryOnePermissions;
row["inventoryGroupPermissions"] = item.GroupPermissions;
// new fields
row["salePrice"] = item.SalePrice;
row["saleType"] = item.SaleType;
row["creationDate"] = item.CreationDate;
row["groupID"] = item.GroupID.ToString();
row["groupOwned"] = item.GroupOwned;
row["flags"] = item.Flags;
}
/// <summary>
/// Add inventory folder
/// </summary>
/// <param name="folder">Folder base</param>
/// <param name="add">true=create folder. false=update existing folder</param>
/// <remarks>nasty</remarks>
private void addFolder(InventoryFolderBase folder, bool add)
{
lock (ds)
{
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
DataRow inventoryRow = inventoryFolderTable.Rows.Find(folder.ID.ToString());
if (inventoryRow == null)
{
if (! add)
m_log.ErrorFormat("Interface Misuse: Attempting to Update non-existant inventory folder: {0}", folder.ID);
inventoryRow = inventoryFolderTable.NewRow();
fillFolderRow(inventoryRow, folder);
inventoryFolderTable.Rows.Add(inventoryRow);
}
else
{
if (add)
m_log.ErrorFormat("Interface Misuse: Attempting to Add inventory folder that already exists: {0}", folder.ID);
fillFolderRow(inventoryRow, folder);
}
invFoldersDa.Update(ds, "inventoryfolders");
}
}
/// <summary>
/// Move an inventory folder
/// </summary>
/// <param name="folder">folder base</param>
private void moveFolder(InventoryFolderBase folder)
{
lock (ds)
{
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
DataRow inventoryRow = inventoryFolderTable.Rows.Find(folder.ID.ToString());
if (inventoryRow == null)
{
inventoryRow = inventoryFolderTable.NewRow();
fillFolderRow(inventoryRow, folder);
inventoryFolderTable.Rows.Add(inventoryRow);
}
else
{
moveFolderRow(inventoryRow, folder);
}
invFoldersDa.Update(ds, "inventoryfolders");
}
}
/// <summary>
/// add an item in inventory
/// </summary>
/// <param name="item">the item</param>
/// <param name="add">true=add item ; false=update existing item</param>
private void addItem(InventoryItemBase item, bool add)
{
lock (ds)
{
DataTable inventoryItemTable = ds.Tables["inventoryitems"];
DataRow inventoryRow = inventoryItemTable.Rows.Find(item.ID.ToString());
if (inventoryRow == null)
{
if (!add)
m_log.ErrorFormat("[INVENTORY DB]: Interface Misuse: Attempting to Update non-existant inventory item: {0}", item.ID);
inventoryRow = inventoryItemTable.NewRow();
fillItemRow(inventoryRow, item);
inventoryItemTable.Rows.Add(inventoryRow);
}
else
{
if (add)
m_log.ErrorFormat("[INVENTORY DB]: Interface Misuse: Attempting to Add inventory item that already exists: {0}", item.ID);
fillItemRow(inventoryRow, item);
}
invItemsDa.Update(ds, "inventoryitems");
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
inventoryRow = inventoryFolderTable.Rows.Find(item.Folder.ToString());
if (inventoryRow != null) //MySQL doesn't throw an exception here, so sqlite shouldn't either.
inventoryRow["version"] = (int)inventoryRow["version"] + 1;
invFoldersDa.Update(ds, "inventoryfolders");
}
}
/// <summary>
/// TODO : DataSet commit
/// </summary>
public void Shutdown()
{
// TODO: DataSet commit
}
/// <summary>
/// The name of this DB provider
/// </summary>
/// <returns>Name of DB provider</returns>
public string Name
{
get { return "SQLite Inventory Data Interface"; }
}
/// <summary>
/// Returns the version of this DB provider
/// </summary>
/// <returns>A string containing the DB provider version</returns>
public string Version
{
get
{
Module module = GetType().Module;
// string dllName = module.Assembly.ManifestModule.Name;
Version dllVersion = module.Assembly.GetName().Version;
return
string.Format("{0}.{1}.{2}.{3}", dllVersion.Major, dllVersion.Minor, dllVersion.Build,
dllVersion.Revision);
}
}
/// <summary>
/// Returns a list of inventory items contained within the specified folder
/// </summary>
/// <param name="folderID">The UUID of the target folder</param>
/// <returns>A List of InventoryItemBase items</returns>
public List<InventoryItemBase> getInventoryInFolder(UUID folderID)
{
lock (ds)
{
List<InventoryItemBase> retval = new List<InventoryItemBase>();
DataTable inventoryItemTable = ds.Tables["inventoryitems"];
string selectExp = "parentFolderID = '" + folderID + "'";
DataRow[] rows = inventoryItemTable.Select(selectExp);
foreach (DataRow row in rows)
{
retval.Add(buildItem(row));
}
return retval;
}
}
/// <summary>
/// Returns a list of the root folders within a users inventory
/// </summary>
/// <param name="user">The user whos inventory is to be searched</param>
/// <returns>A list of folder objects</returns>
public List<InventoryFolderBase> getUserRootFolders(UUID user)
{
return new List<InventoryFolderBase>();
}
// see InventoryItemBase.getUserRootFolder
public InventoryFolderBase getUserRootFolder(UUID user)
{
lock (ds)
{
List<InventoryFolderBase> folders = new List<InventoryFolderBase>();
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
string selectExp = "agentID = '" + user + "' AND parentID = '" + UUID.Zero + "'";
DataRow[] rows = inventoryFolderTable.Select(selectExp);
foreach (DataRow row in rows)
{
folders.Add(buildFolder(row));
}
// There should only ever be one root folder for a user. However, if there's more
// than one we'll simply use the first one rather than failing. It would be even
// nicer to print some message to this effect, but this feels like it's too low a
// to put such a message out, and it's too minor right now to spare the time to
// suitably refactor.
if (folders.Count > 0)
{
return folders[0];
}
return null;
}
}
/// <summary>
/// Append a list of all the child folders of a parent folder
/// </summary>
/// <param name="folders">list where folders will be appended</param>
/// <param name="parentID">ID of parent</param>
protected void getInventoryFolders(ref List<InventoryFolderBase> folders, UUID parentID)
{
lock (ds)
{
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
string selectExp = "parentID = '" + parentID + "'";
DataRow[] rows = inventoryFolderTable.Select(selectExp);
foreach (DataRow row in rows)
{
folders.Add(buildFolder(row));
}
}
}
/// <summary>
/// Returns a list of inventory folders contained in the folder 'parentID'
/// </summary>
/// <param name="parentID">The folder to get subfolders for</param>
/// <returns>A list of inventory folders</returns>
public List<InventoryFolderBase> getInventoryFolders(UUID parentID)
{
List<InventoryFolderBase> folders = new List<InventoryFolderBase>();
getInventoryFolders(ref folders, parentID);
return folders;
}
/// <summary>
/// See IInventoryDataPlugin
/// </summary>
/// <param name="parentID"></param>
/// <returns></returns>
public List<InventoryFolderBase> getFolderHierarchy(UUID parentID)
{
/* Note: There are subtle changes between this implementation of getFolderHierarchy and the previous one
* - We will only need to hit the database twice instead of n times.
* - We assume the database is well-formed - no stranded/dangling folders, all folders in heirarchy owned
* by the same person, each user only has 1 inventory heirarchy
* - The returned list is not ordered, instead of breadth-first ordered
There are basically 2 usage cases for getFolderHeirarchy:
1) Getting the user's entire inventory heirarchy when they log in
2) Finding a subfolder heirarchy to delete when emptying the trash.
This implementation will pull all inventory folders from the database, and then prune away any folder that
is not part of the requested sub-heirarchy. The theory is that it is cheaper to make 1 request from the
database than to make n requests. This pays off only if requested heirarchy is large.
By making this choice, we are making the worst case better at the cost of making the best case worse
- Francis
*/
List<InventoryFolderBase> folders = new List<InventoryFolderBase>();
DataRow[] folderRows = null, parentRow;
InventoryFolderBase parentFolder = null;
lock (ds)
{
/* Fetch the parent folder from the database to determine the agent ID.
* Then fetch all inventory folders for that agent from the agent ID.
*/
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
string selectExp = "UUID = '" + parentID + "'";
parentRow = inventoryFolderTable.Select(selectExp); // Assume at most 1 result
if (parentRow.GetLength(0) >= 1) // No result means parent folder does not exist
{
parentFolder = buildFolder(parentRow[0]);
UUID agentID = parentFolder.Owner;
selectExp = "agentID = '" + agentID + "'";
folderRows = inventoryFolderTable.Select(selectExp);
}
if (folderRows != null && folderRows.GetLength(0) >= 1) // No result means parent folder does not exist
{ // or has no children
/* if we're querying the root folder, just return an unordered list of all folders in the user's
* inventory
*/
if (parentFolder.ParentID == UUID.Zero)
{
foreach (DataRow row in folderRows)
{
InventoryFolderBase curFolder = buildFolder(row);
if (curFolder.ID != parentID) // Return all folders except the parent folder of heirarchy
folders.Add(buildFolder(row));
}
} // If requesting root folder
/* else we are querying a non-root folder. We currently have a list of all of the user's folders,
* we must construct a list of all folders in the heirarchy below parentID.
* Our first step will be to construct a hash table of all folders, indexed by parent ID.
* Once we have constructed the hash table, we will do a breadth-first traversal on the tree using the
* hash table to find child folders.
*/
else
{ // Querying a non-root folder
// Build a hash table of all user's inventory folders, indexed by each folder's parent ID
Dictionary<UUID, List<InventoryFolderBase>> hashtable =
new Dictionary<UUID, List<InventoryFolderBase>>(folderRows.GetLength(0));
foreach (DataRow row in folderRows)
{
InventoryFolderBase curFolder = buildFolder(row);
if (curFolder.ParentID != UUID.Zero) // Discard root of tree - not needed
{
if (hashtable.ContainsKey(curFolder.ParentID))
{
// Current folder already has a sibling - append to sibling list
hashtable[curFolder.ParentID].Add(curFolder);
}
else
{
List<InventoryFolderBase> siblingList = new List<InventoryFolderBase>();
siblingList.Add(curFolder);
// Current folder has no known (yet) siblings
hashtable.Add(curFolder.ParentID, siblingList);
}
}
} // For all inventory folders
// Note: Could release the ds lock here - we don't access folderRows or the database anymore.
// This is somewhat of a moot point as the callers of this function usually lock db anyways.
if (hashtable.ContainsKey(parentID)) // if requested folder does have children
folders.AddRange(hashtable[parentID]);
// BreadthFirstSearch build inventory tree **Note: folders.Count is *not* static
for (int i = 0; i < folders.Count; i++)
if (hashtable.ContainsKey(folders[i].ID))
folders.AddRange(hashtable[folders[i].ID]);
} // if requesting a subfolder heirarchy
} // if folder parentID exists and has children
} // lock ds
return folders;
}
/// <summary>
/// Returns an inventory item by its UUID
/// </summary>
/// <param name="item">The UUID of the item to be returned</param>
/// <returns>A class containing item information</returns>
public InventoryItemBase getInventoryItem(UUID item)
{
lock (ds)
{
DataRow row = ds.Tables["inventoryitems"].Rows.Find(item.ToString());
if (row != null)
{
return buildItem(row);
}
else
{
return null;
}
}
}
/// <summary>
/// Returns a specified inventory folder by its UUID
/// </summary>
/// <param name="folder">The UUID of the folder to be returned</param>
/// <returns>A class containing folder information</returns>
public InventoryFolderBase getInventoryFolder(UUID folder)
{
// TODO: Deep voodoo here. If you enable this code then
// multi region breaks. No idea why, but I figured it was
// better to leave multi region at this point. It does mean
// that you don't get to see system textures why creating
// clothes and the like. :(
lock (ds)
{
DataRow row = ds.Tables["inventoryfolders"].Rows.Find(folder.ToString());
if (row != null)
{
return buildFolder(row);
}
else
{
return null;
}
}
}
/// <summary>
/// Creates a new inventory item based on item
/// </summary>
/// <param name="item">The item to be created</param>
public void addInventoryItem(InventoryItemBase item)
{
addItem(item, true);
}
/// <summary>
/// Updates an inventory item with item (updates based on ID)
/// </summary>
/// <param name="item">The updated item</param>
public void updateInventoryItem(InventoryItemBase item)
{
addItem(item, false);
}
/// <summary>
/// Delete an inventory item
/// </summary>
/// <param name="item">The item UUID</param>
public void deleteInventoryItem(UUID itemID)
{
lock (ds)
{
DataTable inventoryItemTable = ds.Tables["inventoryitems"];
DataRow inventoryRow = inventoryItemTable.Rows.Find(itemID.ToString());
if (inventoryRow != null)
{
inventoryRow.Delete();
}
invItemsDa.Update(ds, "inventoryitems");
}
}
public InventoryItemBase queryInventoryItem(UUID itemID)
{
return getInventoryItem(itemID);
}
public InventoryFolderBase queryInventoryFolder(UUID folderID)
{
return getInventoryFolder(folderID);
}
/// <summary>
/// Delete all items in the specified folder
/// </summary>
/// <param name="folderId">id of the folder, whose item content should be deleted</param>
/// <todo>this is horribly inefficient, but I don't want to ruin the overall structure of this implementation</todo>
private void deleteItemsInFolder(UUID folderId)
{
List<InventoryItemBase> items = getInventoryInFolder(folderId);
foreach (InventoryItemBase i in items)
deleteInventoryItem(i.ID);
}
/// <summary>
/// Adds a new folder specified by folder
/// </summary>
/// <param name="folder">The inventory folder</param>
public void addInventoryFolder(InventoryFolderBase folder)
{
addFolder(folder, true);
}
/// <summary>
/// Updates a folder based on its ID with folder
/// </summary>
/// <param name="folder">The inventory folder</param>
public void updateInventoryFolder(InventoryFolderBase folder)
{
addFolder(folder, false);
}
/// <summary>
/// Moves a folder based on its ID with folder
/// </summary>
/// <param name="folder">The inventory folder</param>
public void moveInventoryFolder(InventoryFolderBase folder)
{
moveFolder(folder);
}
/// <summary>
/// Delete a folder
/// </summary>
/// <remarks>
/// This will clean-up any child folders and child items as well
/// </remarks>
/// <param name="folderID">the folder UUID</param>
public void deleteInventoryFolder(UUID folderID)
{
lock (ds)
{
List<InventoryFolderBase> subFolders = getFolderHierarchy(folderID);
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
DataRow inventoryRow;
//Delete all sub-folders
foreach (InventoryFolderBase f in subFolders)
{
inventoryRow = inventoryFolderTable.Rows.Find(f.ID.ToString());
if (inventoryRow != null)
{
deleteItemsInFolder(f.ID);
inventoryRow.Delete();
}
}
//Delete the actual row
inventoryRow = inventoryFolderTable.Rows.Find(folderID.ToString());
if (inventoryRow != null)
{
deleteItemsInFolder(folderID);
inventoryRow.Delete();
}
invFoldersDa.Update(ds, "inventoryfolders");
}
}
/***********************************************************************
*
* Data Table definitions
*
**********************************************************************/
/// <summary>
/// Create the "inventoryitems" table
/// </summary>
private static DataTable createInventoryItemsTable()
{
DataTable inv = new DataTable("inventoryitems");
createCol(inv, "UUID", typeof (String)); //inventoryID
createCol(inv, "assetID", typeof (String));
createCol(inv, "assetType", typeof (Int32));
createCol(inv, "invType", typeof (Int32));
createCol(inv, "parentFolderID", typeof (String));
createCol(inv, "avatarID", typeof (String));
createCol(inv, "creatorsID", typeof (String));
createCol(inv, "inventoryName", typeof (String));
createCol(inv, "inventoryDescription", typeof (String));
// permissions
createCol(inv, "inventoryNextPermissions", typeof (Int32));
createCol(inv, "inventoryCurrentPermissions", typeof (Int32));
createCol(inv, "inventoryBasePermissions", typeof (Int32));
createCol(inv, "inventoryEveryOnePermissions", typeof (Int32));
createCol(inv, "inventoryGroupPermissions", typeof (Int32));
// sale info
createCol(inv, "salePrice", typeof(Int32));
createCol(inv, "saleType", typeof(Byte));
// creation date
createCol(inv, "creationDate", typeof(Int32));
// group info
createCol(inv, "groupID", typeof(String));
createCol(inv, "groupOwned", typeof(Boolean));
// Flags
createCol(inv, "flags", typeof(UInt32));
inv.PrimaryKey = new DataColumn[] { inv.Columns["UUID"] };
return inv;
}
/// <summary>
/// Creates the "inventoryfolders" table
/// </summary>
/// <returns></returns>
private static DataTable createInventoryFoldersTable()
{
DataTable fol = new DataTable("inventoryfolders");
createCol(fol, "UUID", typeof (String)); //folderID
createCol(fol, "name", typeof (String));
createCol(fol, "agentID", typeof (String));
createCol(fol, "parentID", typeof (String));
createCol(fol, "type", typeof (Int32));
createCol(fol, "version", typeof (Int32));
fol.PrimaryKey = new DataColumn[] {fol.Columns["UUID"]};
return fol;
}
/// <summary>
///
/// </summary>
/// <param name="da"></param>
/// <param name="conn"></param>
private void setupItemsCommands(SqliteDataAdapter da, SqliteConnection conn)
{
lock (ds)
{
da.InsertCommand = createInsertCommand("inventoryitems", ds.Tables["inventoryitems"]);
da.InsertCommand.Connection = conn;
da.UpdateCommand = createUpdateCommand("inventoryitems", "UUID=:UUID", ds.Tables["inventoryitems"]);
da.UpdateCommand.Connection = conn;
SqliteCommand delete = new SqliteCommand("delete from inventoryitems where UUID = :UUID");
delete.Parameters.Add(createSqliteParameter("UUID", typeof(String)));
delete.Connection = conn;
da.DeleteCommand = delete;
}
}
/// <summary>
///
/// </summary>
/// <param name="da"></param>
/// <param name="conn"></param>
private void setupFoldersCommands(SqliteDataAdapter da, SqliteConnection conn)
{
lock (ds)
{
da.InsertCommand = createInsertCommand("inventoryfolders", ds.Tables["inventoryfolders"]);
da.InsertCommand.Connection = conn;
da.UpdateCommand = createUpdateCommand("inventoryfolders", "UUID=:UUID", ds.Tables["inventoryfolders"]);
da.UpdateCommand.Connection = conn;
SqliteCommand delete = new SqliteCommand("delete from inventoryfolders where UUID = :UUID");
delete.Parameters.Add(createSqliteParameter("UUID", typeof(String)));
delete.Connection = conn;
da.DeleteCommand = delete;
}
}
/// <summary>
///
/// </summary>
/// <param name="row"></param>
/// <returns></returns>
private static InventoryFolderBase buildFolder(DataRow row)
{
InventoryFolderBase folder = new InventoryFolderBase();
folder.ID = new UUID((string) row["UUID"]);
folder.Name = (string) row["name"];
folder.Owner = new UUID((string) row["agentID"]);
folder.ParentID = new UUID((string) row["parentID"]);
folder.Type = Convert.ToInt16(row["type"]);
folder.Version = Convert.ToUInt16(row["version"]);
return folder;
}
/// <summary>
///
/// </summary>
/// <param name="row"></param>
/// <param name="folder"></param>
private static void fillFolderRow(DataRow row, InventoryFolderBase folder)
{
row["UUID"] = folder.ID.ToString();
row["name"] = folder.Name;
row["agentID"] = folder.Owner.ToString();
row["parentID"] = folder.ParentID.ToString();
row["type"] = folder.Type;
row["version"] = folder.Version;
}
/// <summary>
///
/// </summary>
/// <param name="row"></param>
/// <param name="folder"></param>
private static void moveFolderRow(DataRow row, InventoryFolderBase folder)
{
row["UUID"] = folder.ID.ToString();
row["parentID"] = folder.ParentID.ToString();
}
public List<InventoryItemBase> fetchActiveGestures (UUID avatarID)
{
lock (ds)
{
List<InventoryItemBase> items = new List<InventoryItemBase>();
DataTable inventoryItemTable = ds.Tables["inventoryitems"];
string selectExp
= "avatarID = '" + avatarID + "' AND assetType = " + (int)AssetType.Gesture + " AND flags = 1";
//m_log.DebugFormat("[SQL]: sql = " + selectExp);
DataRow[] rows = inventoryItemTable.Select(selectExp);
foreach (DataRow row in rows)
{
items.Add(buildItem(row));
}
return items;
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,81 +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 OpenMetaverse;
using OpenSim.Framework;
using Mono.Data.SqliteClient;
namespace OpenSim.Data.SQLiteLegacy
{
public class SQLiteUserAccountData : SQLiteGenericTableHandler<UserAccountData>, IUserAccountData
{
public SQLiteUserAccountData(string connectionString, string realm)
: base(connectionString, realm, "UserAccount")
{
}
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 (i != words.Length - 1)
Array.Copy(words, i + 1, words, i, words.Length - i - 1);
Array.Resize(ref words, words.Length - 1);
}
}
if (words.Length == 0)
return new UserAccountData[0];
if (words.Length > 2)
return new UserAccountData[0];
SqliteCommand cmd = new SqliteCommand();
if (words.Length == 1)
{
cmd.CommandText = String.Format("select * from {0} where (ScopeID='{1}' or ScopeID='00000000-0000-0000-0000-000000000000') and (FirstName like '{2}%' or LastName like '{2}%')",
m_Realm, scopeID.ToString(), words[0]);
}
else
{
cmd.CommandText = String.Format("select * from {0} where (ScopeID='{1}' or ScopeID='00000000-0000-0000-0000-000000000000') and (FirstName like '{2}%' or LastName like '{3}%')",
m_Realm, scopeID.ToString(), words[0], words[1]);
}
return DoQuery(cmd);
}
}
}

View File

@ -1,307 +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.Data;
using Mono.Data.SqliteClient;
namespace OpenSim.Data.SQLiteLegacy
{
/// <summary>
/// A base class for methods needed by all SQLite database classes
/// </summary>
public class SQLiteUtil
{
/***********************************************************************
*
* Database Definition Helper Functions
*
* This should be db agnostic as we define them in ADO.NET terms
*
**********************************************************************/
/// <summary>
///
/// </summary>
/// <param name="dt"></param>
/// <param name="name"></param>
/// <param name="type"></param>
public static void createCol(DataTable dt, string name, Type type)
{
DataColumn col = new DataColumn(name, type);
dt.Columns.Add(col);
}
/***********************************************************************
*
* SQL Statement Creation Functions
*
* These functions create SQL statements for update, insert, and create.
* They can probably be factored later to have a db independant
* portion and a db specific portion
*
**********************************************************************/
/// <summary>
/// Create an insert command
/// </summary>
/// <param name="table">table name</param>
/// <param name="dt">data table</param>
/// <returns>the created command</returns>
/// <remarks>
/// This is subtle enough to deserve some commentary.
/// Instead of doing *lots* and *lots of hardcoded strings
/// for database definitions we'll use the fact that
/// realistically all insert statements look like "insert
/// into A(b, c) values(:b, :c) on the parameterized query
/// front. If we just have a list of b, c, etc... we can
/// generate these strings instead of typing them out.
/// </remarks>
public static SqliteCommand createInsertCommand(string table, DataTable dt)
{
string[] cols = new string[dt.Columns.Count];
for (int i = 0; i < dt.Columns.Count; i++)
{
DataColumn col = dt.Columns[i];
cols[i] = col.ColumnName;
}
string sql = "insert into " + table + "(";
sql += String.Join(", ", cols);
// important, the first ':' needs to be here, the rest get added in the join
sql += ") values (:";
sql += String.Join(", :", cols);
sql += ")";
SqliteCommand cmd = new SqliteCommand(sql);
// this provides the binding for all our parameters, so
// much less code than it used to be
foreach (DataColumn col in dt.Columns)
{
cmd.Parameters.Add(createSqliteParameter(col.ColumnName, col.DataType));
}
return cmd;
}
/// <summary>
/// create an update command
/// </summary>
/// <param name="table">table name</param>
/// <param name="pk"></param>
/// <param name="dt"></param>
/// <returns>the created command</returns>
public static SqliteCommand createUpdateCommand(string table, string pk, DataTable dt)
{
string sql = "update " + table + " set ";
string subsql = String.Empty;
foreach (DataColumn col in dt.Columns)
{
if (subsql.Length > 0)
{
// a map function would rock so much here
subsql += ", ";
}
subsql += col.ColumnName + "= :" + col.ColumnName;
}
sql += subsql;
sql += " where " + pk;
SqliteCommand cmd = new SqliteCommand(sql);
// this provides the binding for all our parameters, so
// much less code than it used to be
foreach (DataColumn col in dt.Columns)
{
cmd.Parameters.Add(createSqliteParameter(col.ColumnName, col.DataType));
}
return cmd;
}
/// <summary>
///
/// </summary>
/// <param name="dt">Data Table</param>
/// <returns></returns>
public 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 + " " + sqliteType(col.DataType);
if (dt.PrimaryKey.Length > 0)
{
if (col == dt.PrimaryKey[0])
{
subsql += " primary key";
}
}
}
sql += subsql;
sql += ")";
return sql;
}
/***********************************************************************
*
* Database Binding functions
*
* These will be db specific due to typing, and minor differences
* in databases.
*
**********************************************************************/
///<summary>
/// <para>
/// This is a convenience function that collapses 5 repetitive
/// lines for defining SqliteParameters to 2 parameters:
/// column name and database type.
/// </para>
///
/// <para>
/// It assumes certain conventions like :param as the param
/// name to replace in parametrized queries, and that source
/// version is always current version, both of which are fine
/// for us.
/// </para>
///</summary>
/// <param name="name"></param>
/// <param name="type"></param>
///<returns>a built sqlite parameter</returns>
public static SqliteParameter createSqliteParameter(string name, Type type)
{
SqliteParameter param = new SqliteParameter();
param.ParameterName = ":" + name;
param.DbType = dbtypeFromType(type);
param.SourceColumn = name;
param.SourceVersion = DataRowVersion.Current;
return param;
}
/***********************************************************************
*
* Type conversion functions
*
**********************************************************************/
/// <summary>
/// Type conversion function
/// </summary>
/// <param name="type">a type</param>
/// <returns>a DbType</returns>
public static DbType dbtypeFromType(Type type)
{
if (type == typeof (String))
{
return DbType.String;
}
else if (type == typeof (Int32))
{
return DbType.Int32;
}
else if (type == typeof (UInt32))
{
return DbType.UInt32;
}
else if (type == typeof (Int64))
{
return DbType.Int64;
}
else if (type == typeof (UInt64))
{
return DbType.UInt64;
}
else if (type == typeof (Double))
{
return DbType.Double;
}
else if (type == typeof (Boolean))
{
return DbType.Boolean;
}
else if (type == typeof (Byte[]))
{
return DbType.Binary;
}
else
{
return DbType.String;
}
}
/// <summary>
/// </summary>
/// <param name="type">a Type</param>
/// <returns>a string</returns>
/// <remarks>this is something we'll need to implement for each db slightly differently.</remarks>
public static string sqliteType(Type type)
{
if (type == typeof (String))
{
return "varchar(255)";
}
else if (type == typeof (Int32))
{
return "integer";
}
else if (type == typeof (UInt32))
{
return "integer";
}
else if (type == typeof (Int64))
{
return "varchar(255)";
}
else if (type == typeof (UInt64))
{
return "varchar(255)";
}
else if (type == typeof (Double))
{
return "float";
}
else if (type == typeof (Boolean))
{
return "integer";
}
else if (type == typeof (Byte[]))
{
return "blob";
}
else
{
return "string";
}
}
}
}

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.Data;
using System.Reflection;
using System.Collections.Generic;
using Mono.Data.SqliteClient;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
namespace OpenSim.Data.SQLiteLegacy
{
/// <summary>
/// A MySQL Interface for the Asset Server
/// </summary>
public class SQLiteXInventoryData : IXInventoryData
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private SQLiteGenericTableHandler<XInventoryFolder> m_Folders;
private SqliteItemHandler m_Items;
public SQLiteXInventoryData(string conn, string realm)
{
m_Folders = new SQLiteGenericTableHandler<XInventoryFolder>(
conn, "inventoryfolders", "InventoryStore");
m_Items = new SqliteItemHandler(
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 SqliteItemHandler : SQLiteGenericTableHandler<XInventoryItem>
{
public SqliteItemHandler(string c, string t, string m) :
base(c, t, m)
{
}
public bool MoveItem(string id, string newParent)
{
SqliteCommand cmd = new SqliteCommand();
cmd.CommandText = String.Format("update {0} set parentFolderID = :ParentFolderID where inventoryID = :InventoryID", m_Realm);
cmd.Parameters.Add(new SqliteParameter(":ParentFolderID", newParent));
cmd.Parameters.Add(new SqliteParameter(":InventoryID", id));
return ExecuteNonQuery(cmd, m_Connection) == 0 ? false : true;
}
public XInventoryItem[] GetActiveGestures(UUID principalID)
{
SqliteCommand cmd = new SqliteCommand();
cmd.CommandText = String.Format("select * from inventoryitems where avatarId = :uuid and assetType = :type and flags = 1", m_Realm);
cmd.Parameters.Add(new SqliteParameter(":uuid", principalID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":type", (int)AssetType.Gesture));
return DoQuery(cmd);
}
public int GetAssetPermissions(UUID principalID, UUID assetID)
{
SqliteCommand cmd = new SqliteCommand();
cmd.CommandText = String.Format("select inventoryCurrentPermissions from inventoryitems where avatarID = :PrincipalID and assetID = :AssetID", m_Realm);
cmd.Parameters.Add(new SqliteParameter(":PrincipalID", principalID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":AssetID", assetID.ToString()));
IDataReader reader = ExecuteReader(cmd, m_Connection);
int perms = 0;
while (reader.Read())
{
perms |= Convert.ToInt32(reader["inventoryCurrentPermissions"]);
}
reader.Close();
CloseCommand(cmd);
return perms;
}
}
}

View File

@ -570,16 +570,35 @@ namespace OpenSim.Framework
public float dwell;
}
public class EntityUpdate
public class IEntityUpdate
{
public ISceneEntity Entity;
public PrimUpdateFlags Flags;
public float TimeDilation;
public uint Flags;
public EntityUpdate(ISceneEntity entity, PrimUpdateFlags flags, float timedilation)
public virtual void Update(IEntityUpdate update)
{
this.Flags |= update.Flags;
}
public IEntityUpdate(ISceneEntity entity, uint flags)
{
Entity = entity;
Flags = flags;
}
}
public class EntityUpdate : IEntityUpdate
{
// public ISceneEntity Entity;
// public PrimUpdateFlags Flags;
public float TimeDilation;
public EntityUpdate(ISceneEntity entity, PrimUpdateFlags flags, float timedilation)
: base(entity,(uint)flags)
{
//Entity = entity;
// Flags = flags;
TimeDilation = timedilation;
}
}
@ -1211,20 +1230,9 @@ namespace OpenSim.Framework
/// <param name="stats"></param>
void SendSimStats(SimStats stats);
void SendObjectPropertiesFamilyData(uint RequestFlags, UUID ObjectUUID, UUID OwnerID, UUID GroupID,
uint BaseMask, uint OwnerMask, uint GroupMask, uint EveryoneMask,
uint NextOwnerMask, int OwnershipCost, byte SaleType, int SalePrice,
uint Category,
UUID LastOwnerID, string ObjectName, string Description);
void SendObjectPropertiesFamilyData(ISceneEntity Entity, uint RequestFlags);
void SendObjectPropertiesReply(UUID ItemID, ulong CreationDate, UUID CreatorUUID, UUID FolderUUID,
UUID FromTaskUUID,
UUID GroupUUID, short InventorySerial, UUID LastOwnerUUID, UUID ObjectUUID,
UUID OwnerUUID, string TouchTitle, byte[] TextureID, string SitTitle,
string ItemName,
string ItemDescription, uint OwnerMask, uint NextOwnerMask, uint GroupMask,
uint EveryoneMask,
uint BaseMask, byte saleType, int salePrice);
void SendObjectPropertiesReply(ISceneEntity Entity);
void SendAgentOffline(UUID[] agentIDs);

View File

@ -77,7 +77,6 @@ namespace OpenSim.Region.Framework.Interfaces
/// </param>
void Clear(bool setupDefaultParcel);
bool IsLandPrimCountTainted();
bool IsForcefulBansAllowed();
void UpdateLandObject(int localID, LandData data);
void ReturnObjectsInParcel(int localID, uint returnType, UUID[] agentIDs, UUID[] taskIDs, IClientAPI remoteClient);

View File

@ -82,14 +82,36 @@ namespace OpenSim.Framework
void ForceUpdateLandInfo();
void SetLandBitmap(bool[,] bitmap);
/// <summary>
/// Get a land bitmap that would cover an entire region.
/// </summary>
/// <returns>The bitmap created.</returns>
bool[,] BasicFullRegionLandBitmap();
/// <summary>
/// Create a square land bitmap.
/// </summary>
/// <remarks>
/// Land co-ordinates are zero indexed. The inputs are treated as points. So if you want to create a bitmap
/// that covers an entire 256 x 256m region apart from a strip of land on the east, then you would need to
/// specify start_x = 0, start_y = 0, end_x = 252 (or anything up to 255), end_y = 256.
///
/// At the moment, the smallest parcel of land is 4m x 4m, so if the
/// region is 256 x 256m (the SL size), the bitmap returned will start at (0,0) and end at (63,63).
/// </remarks>
/// <param name="start_x"></param>
/// <param name="start_y"></param>
/// <param name="end_x"></param>
/// <param name="end_y"></param>
/// <returns>The bitmap created.</returns>
bool[,] GetSquareLandBitmap(int start_x, int start_y, int end_x, int end_y);
bool[,] ModifyLandBitmapSquare(bool[,] land_bitmap, int start_x, int start_y, int end_x, int end_y, bool set_value);
bool[,] MergeLandBitmaps(bool[,] bitmap_base, bool[,] bitmap_add);
void SendForceObjectSelect(int local_id, int request_type, List<UUID> returnIDs, IClientAPI remote_client);
void SendLandObjectOwners(IClientAPI remote_client);
void ReturnLandObjects(uint type, UUID[] owners, UUID[] tasks, IClientAPI remote_client);
void ResetLandPrimCounts();
void ResetOverMeRecord();
void UpdateLandSold(UUID avatarID, UUID groupID, bool groupOwned, uint AuctionID, int claimprice, int area);
void DeedToGroup(UUID groupID);

View File

@ -54,12 +54,10 @@ namespace OpenSim.Framework
private int _claimPrice = 0; //Unemplemented
private UUID _globalID = UUID.Zero;
private UUID _groupID = UUID.Zero;
private int _groupPrims = 0;
private bool _isGroupOwned = false;
private byte[] _bitmap = new byte[512];
private string _description = String.Empty;
private uint _flags = (uint) ParcelFlags.AllowFly | (uint) ParcelFlags.AllowLandmark |
(uint) ParcelFlags.AllowAPrimitiveEntry |
(uint) ParcelFlags.AllowDeedToGroup | (uint) ParcelFlags.AllowTerraform |
@ -72,17 +70,13 @@ namespace OpenSim.Framework
private int _localID = 0;
private byte _mediaAutoScale = 0;
private UUID _mediaID = UUID.Zero;
private string _mediaURL = String.Empty;
private string _musicURL = String.Empty;
private int _otherPrims = 0;
private UUID _ownerID = UUID.Zero;
private int _ownerPrims = 0;
private List<ParcelManager.ParcelAccessEntry> _parcelAccessList = new List<ParcelManager.ParcelAccessEntry>();
private float _passHours = 0;
private int _passPrice = 0;
private int _salePrice = 0; //Unemeplemented. Parcels price.
private int _selectedPrims = 0;
private int _simwideArea = 0;
private int _simwidePrims = 0;
private UUID _snapshotID = UUID.Zero;
@ -283,19 +277,6 @@ namespace OpenSim.Framework
}
}
/// <summary>
/// Number of SceneObjectPart that are owned by a Group
/// </summary>
[XmlIgnore]
public int GroupPrims {
get {
return _groupPrims;
}
set {
_groupPrims = value;
}
}
/// <summary>
/// Returns true if the Land Parcel is owned by a group
/// </summary>
@ -453,20 +434,6 @@ namespace OpenSim.Framework
}
}
/// <summary>
/// Number of SceneObjectPart that are owned by users who do not own the parcel
/// and don't have the 'group. These are elegable for AutoReturn collection
/// </summary>
[XmlIgnore]
public int OtherPrims {
get {
return _otherPrims;
}
set {
_otherPrims = value;
}
}
/// <summary>
/// Owner Avatar or Group of the parcel. Naturally, all land masses must be
/// owned by someone
@ -480,19 +447,6 @@ namespace OpenSim.Framework
}
}
/// <summary>
/// Number of SceneObjectPart that are owned by the owner of the parcel
/// </summary>
[XmlIgnore]
public int OwnerPrims {
get {
return _ownerPrims;
}
set {
_ownerPrims = value;
}
}
/// <summary>
/// List of access data for the parcel. User data, some bitflags, and a time
/// </summary>
@ -541,19 +495,6 @@ namespace OpenSim.Framework
}
}
/// <summary>
/// Number of SceneObjectPart that are currently selected by avatar
/// </summary>
[XmlIgnore]
public int SelectedPrims {
get {
return _selectedPrims;
}
set {
_selectedPrims = value;
}
}
/// <summary>
/// Number of meters^2 in the Simulator
/// </summary>
@ -619,7 +560,7 @@ namespace OpenSim.Framework
}
/// <summary>
/// Number of minutes to return SceneObjectGroup that are owned by someone who doesn't own
/// Autoreturn number of minutes to return SceneObjectGroup that are owned by someone who doesn't own
/// the parcel and isn't set to the same 'group' as the parcel.
/// </summary>
public int OtherCleanTime {
@ -666,10 +607,6 @@ namespace OpenSim.Framework
landData._claimPrice = _claimPrice;
landData._globalID = _globalID;
landData._groupID = _groupID;
landData._groupPrims = _groupPrims;
landData._otherPrims = _otherPrims;
landData._ownerPrims = _ownerPrims;
landData._selectedPrims = _selectedPrims;
landData._isGroupOwned = _isGroupOwned;
landData._localID = _localID;
landData._landingType = _landingType;

View File

@ -347,7 +347,6 @@ namespace OpenSim.Framework
public bool commFailTF = false;
public ConfigurationMember configMember;
public string DataStore = String.Empty;
public string RegionFile = String.Empty;
public bool isSandbox = false;
public bool Persistent = true;
@ -746,10 +745,6 @@ namespace OpenSim.Framework
m_regionLocX = Convert.ToUInt32(locationElements[0]);
m_regionLocY = Convert.ToUInt32(locationElements[1]);
// Datastore (is this implemented? Omitted from example!)
DataStore = config.GetString("Datastore", String.Empty);
// Internal IP
IPAddress address;
@ -846,9 +841,6 @@ namespace OpenSim.Framework
string location = String.Format("{0},{1}", m_regionLocX, m_regionLocY);
config.Set("Location", location);
if (DataStore != String.Empty)
config.Set("Datastore", DataStore);
config.Set("InternalAddress", m_internalEndPoint.Address.ToString());
config.Set("InternalPort", m_internalEndPoint.Port);
@ -1025,9 +1017,6 @@ namespace OpenSim.Framework
case "sim_location_y":
m_regionLocY = (uint) configuration_result;
break;
case "datastore":
DataStore = (string) configuration_result;
break;
case "internal_ip_address":
IPAddress address = (IPAddress) configuration_result;
m_internalEndPoint = new IPEndPoint(address, 0);
@ -1175,11 +1164,6 @@ namespace OpenSim.Framework
return regionInfo;
}
public int getInternalEndPointPort()
{
return m_internalEndPoint.Port;
}
public Dictionary<string, object> ToKeyValuePairs()
{
Dictionary<string, object> kvp = new Dictionary<string, object>();

View File

@ -44,9 +44,6 @@ namespace OpenSim.Framework.Serialization.Tests
private static string preSerialized = "<?xml version=\"1.0\" encoding=\"utf-16\"?>\n<LandData>\n <Area>128</Area>\n <AuctionID>0</AuctionID>\n <AuthBuyerID>00000000-0000-0000-0000-000000000000</AuthBuyerID>\n <Category>10</Category>\n <ClaimDate>0</ClaimDate>\n <ClaimPrice>0</ClaimPrice>\n <GlobalID>54ff9641-dd40-4a2c-b1f1-47dd3af24e50</GlobalID>\n <GroupID>d740204e-bbbf-44aa-949d-02c7d739f6a5</GroupID>\n <IsGroupOwned>False</IsGroupOwned>\n <Bitmap>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</Bitmap>\n <Description>land data to test LandDataSerializer</Description>\n <Flags>536870944</Flags>\n <LandingType>2</LandingType>\n <Name>LandDataSerializerTest Land</Name>\n <Status>0</Status>\n <LocalID>0</LocalID>\n <MediaAutoScale>1</MediaAutoScale>\n <MediaID>d4452578-2f25-4b97-a81b-819af559cfd7</MediaID>\n <MediaURL>http://videos.opensimulator.org/bumblebee.mp4</MediaURL>\n <MusicURL />\n <OwnerID>1b8eedf9-6d15-448b-8015-24286f1756bf</OwnerID>\n <ParcelAccessList />\n <PassHours>0</PassHours>\n <PassPrice>0</PassPrice>\n <SalePrice>0</SalePrice>\n <SnapshotID>00000000-0000-0000-0000-000000000000</SnapshotID>\n <UserLocation>&lt;0, 0, 0&gt;</UserLocation>\n <UserLookAt>&lt;0, 0, 0&gt;</UserLookAt>\n <Dwell>0</Dwell>\n <OtherCleanTime>0</OtherCleanTime>\n</LandData>";
private static string preSerializedWithParcelAccessList = "<?xml version=\"1.0\" encoding=\"utf-16\"?>\n<LandData>\n <Area>128</Area>\n <AuctionID>0</AuctionID>\n <AuthBuyerID>00000000-0000-0000-0000-000000000000</AuthBuyerID>\n <Category>10</Category>\n <ClaimDate>0</ClaimDate>\n <ClaimPrice>0</ClaimPrice>\n <GlobalID>54ff9641-dd40-4a2c-b1f1-47dd3af24e50</GlobalID>\n <GroupID>d740204e-bbbf-44aa-949d-02c7d739f6a5</GroupID>\n <IsGroupOwned>False</IsGroupOwned>\n <Bitmap>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</Bitmap>\n <Description>land data to test LandDataSerializer</Description>\n <Flags>536870944</Flags>\n <LandingType>2</LandingType>\n <Name>LandDataSerializerTest Land</Name>\n <Status>0</Status>\n <LocalID>0</LocalID>\n <MediaAutoScale>1</MediaAutoScale>\n <MediaID>d4452578-2f25-4b97-a81b-819af559cfd7</MediaID>\n <MediaURL>http://videos.opensimulator.org/bumblebee.mp4</MediaURL>\n <MusicURL />\n <OwnerID>1b8eedf9-6d15-448b-8015-24286f1756bf</OwnerID>\n <ParcelAccessList>\n <ParcelAccessEntry>\n <AgentID>62d65d45-c91a-4f77-862c-46557d978b6c</AgentID>\n <Time>2009-10-01T00:00:00</Time>\n <AccessList>2</AccessList>\n </ParcelAccessEntry>\n <ParcelAccessEntry>\n <AgentID>ec2a8d18-2378-4fe0-8b68-2a31b57c481e</AgentID>\n <Time>2010-10-20T00:00:00</Time>\n <AccessList>1</AccessList>\n </ParcelAccessEntry>\n </ParcelAccessList>\n <PassHours>0</PassHours>\n <PassPrice>0</PassPrice>\n <SalePrice>0</SalePrice>\n <SnapshotID>00000000-0000-0000-0000-000000000000</SnapshotID>\n <UserLocation>&lt;0, 0, 0&gt;</UserLocation>\n <UserLookAt>&lt;0, 0, 0&gt;</UserLookAt>\n <Dwell>0</Dwell>\n <OtherCleanTime>0</OtherCleanTime>\n</LandData>";
[SetUp]
public void setup()
{
@ -62,7 +59,6 @@ namespace OpenSim.Framework.Serialization.Tests
this.land.ClaimPrice = 0;
this.land.GlobalID = new UUID("54ff9641-dd40-4a2c-b1f1-47dd3af24e50");
this.land.GroupID = new UUID("d740204e-bbbf-44aa-949d-02c7d739f6a5");
this.land.GroupPrims = 0;
this.land.Description = "land data to test LandDataSerializer";
this.land.Flags = (uint)(ParcelFlags.AllowDamage | ParcelFlags.AllowVoiceChat);
this.land.LandingType = (byte)LandingType.Direct;

View File

@ -1,192 +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.IO;
using System.Net;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using log4net;
namespace OpenSim.Framework.Servers.HttpServer
{
public class AsynchronousRestObjectRequester
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Perform an asynchronous REST request.
/// </summary>
/// <param name="verb">GET or POST</param>
/// <param name="requestUrl"></param>
/// <param name="obj"></param>
/// <param name="action"></param>
/// <returns></returns>
///
/// <exception cref="System.Net.WebException">Thrown if we encounter a
/// network issue while posting the request. You'll want to make
/// sure you deal with this as they're not uncommon</exception>
//
public static void MakeRequest<TRequest, TResponse>(string verb,
string requestUrl, TRequest obj, Action<TResponse> action)
{
// m_log.DebugFormat("[ASYNC REQUEST]: Starting {0} {1}", verb, requestUrl);
Type type = typeof (TRequest);
WebRequest request = WebRequest.Create(requestUrl);
WebResponse response = null;
TResponse deserial = default(TResponse);
XmlSerializer deserializer = new XmlSerializer(typeof (TResponse));
request.Method = verb;
if (verb == "POST")
{
request.ContentType = "text/xml";
MemoryStream buffer = new MemoryStream();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
using (XmlWriter writer = XmlWriter.Create(buffer, settings))
{
XmlSerializer serializer = new XmlSerializer(type);
serializer.Serialize(writer, obj);
writer.Flush();
}
int length = (int) buffer.Length;
request.ContentLength = length;
request.BeginGetRequestStream(delegate(IAsyncResult res)
{
Stream requestStream = request.EndGetRequestStream(res);
requestStream.Write(buffer.ToArray(), 0, length);
requestStream.Close();
request.BeginGetResponse(delegate(IAsyncResult ar)
{
response = request.EndGetResponse(ar);
Stream respStream = null;
try
{
respStream = response.GetResponseStream();
deserial = (TResponse)deserializer.Deserialize(
respStream);
}
catch (System.InvalidOperationException)
{
}
finally
{
// Let's not close this
//buffer.Close();
respStream.Close();
response.Close();
}
action(deserial);
}, null);
}, null);
return;
}
request.BeginGetResponse(delegate(IAsyncResult res2)
{
try
{
// If the server returns a 404, this appears to trigger a System.Net.WebException even though that isn't
// documented in MSDN
response = request.EndGetResponse(res2);
Stream respStream = null;
try
{
respStream = response.GetResponseStream();
deserial = (TResponse)deserializer.Deserialize(respStream);
}
catch (System.InvalidOperationException)
{
}
finally
{
respStream.Close();
response.Close();
}
}
catch (WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError)
{
if (e.Response is HttpWebResponse)
{
HttpWebResponse httpResponse = (HttpWebResponse)e.Response;
if (httpResponse.StatusCode != HttpStatusCode.NotFound)
{
// We don't appear to be handling any other status codes, so log these feailures to that
// people don't spend unnecessary hours hunting phantom bugs.
m_log.DebugFormat(
"[ASYNC REQUEST]: Request {0} {1} failed with unexpected status code {2}",
verb, requestUrl, httpResponse.StatusCode);
}
}
}
else
{
m_log.ErrorFormat("[ASYNC REQUEST]: Request {0} {1} failed with status {2} and message {3}", verb, requestUrl, e.Status, e.Message);
}
}
catch (Exception e)
{
m_log.ErrorFormat("[ASYNC REQUEST]: Request {0} {1} failed with exception {2}", verb, requestUrl, e);
}
// m_log.DebugFormat("[ASYNC REQUEST]: Received {0}", deserial.ToString());
try
{
action(deserial);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[ASYNC REQUEST]: Request {0} {1} callback failed with exception {2}", verb, requestUrl, e);
}
}, null);
}
}
}

View File

@ -1,131 +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.IO;
using System.Net;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using log4net;
namespace OpenSim.Framework.Servers.HttpServer
{
public class SynchronousRestFormsRequester
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Perform a synchronous REST request.
/// </summary>
/// <param name="verb"></param>
/// <param name="requestUrl"></param>
/// <param name="obj"> </param>
/// <returns></returns>
///
/// <exception cref="System.Net.WebException">Thrown if we encounter a network issue while posting
/// the request. You'll want to make sure you deal with this as they're not uncommon</exception>
public static string MakeRequest(string verb, string requestUrl, string obj)
{
WebRequest request = WebRequest.Create(requestUrl);
request.Method = verb;
string respstring = String.Empty;
using (MemoryStream buffer = new MemoryStream())
{
if ((verb == "POST") || (verb == "PUT"))
{
request.ContentType = "text/www-form-urlencoded";
int length = 0;
using (StreamWriter writer = new StreamWriter(buffer))
{
writer.Write(obj);
writer.Flush();
}
length = (int)obj.Length;
request.ContentLength = length;
Stream requestStream = null;
try
{
requestStream = request.GetRequestStream();
requestStream.Write(buffer.ToArray(), 0, length);
}
catch (Exception e)
{
m_log.DebugFormat("[FORMS]: exception occured on sending request to {0}: " + e.ToString(), requestUrl);
}
finally
{
if (requestStream != null)
requestStream.Close();
}
}
try
{
using (WebResponse resp = request.GetResponse())
{
if (resp.ContentLength != 0)
{
Stream respStream = null;
try
{
respStream = resp.GetResponseStream();
using (StreamReader reader = new StreamReader(respStream))
{
respstring = reader.ReadToEnd();
}
}
catch (Exception e)
{
m_log.DebugFormat("[FORMS]: exception occured on receiving reply " + e.ToString());
}
finally
{
if (respStream != null)
respStream.Close();
}
}
}
}
catch (System.InvalidOperationException)
{
// This is what happens when there is invalid XML
m_log.DebugFormat("[FORMS]: InvalidOperationException on receiving request");
}
}
return respstring;
}
}
}

View File

@ -1,122 +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.IO;
using System.Net;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace OpenSim.Framework.Servers.HttpServer
{
public class SynchronousRestObjectPoster
{
[Obsolete]
public static TResponse BeginPostObject<TRequest, TResponse>(string verb, string requestUrl, TRequest obj)
{
return SynchronousRestObjectRequester.MakeRequest<TRequest, TResponse>(verb, requestUrl, obj);
}
}
public class SynchronousRestObjectRequester
{
/// <summary>
/// Perform a synchronous REST request.
/// </summary>
/// <param name="verb"></param>
/// <param name="requestUrl"></param>
/// <param name="obj"> </param>
/// <returns></returns>
///
/// <exception cref="System.Net.WebException">Thrown if we encounter a network issue while posting
/// the request. You'll want to make sure you deal with this as they're not uncommon</exception>
public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj)
{
Type type = typeof (TRequest);
TResponse deserial = default(TResponse);
WebRequest request = WebRequest.Create(requestUrl);
request.Method = verb;
if ((verb == "POST") || (verb == "PUT"))
{
request.ContentType = "text/xml";
MemoryStream buffer = new MemoryStream();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
using (XmlWriter writer = XmlWriter.Create(buffer, settings))
{
XmlSerializer serializer = new XmlSerializer(type);
serializer.Serialize(writer, obj);
writer.Flush();
}
int length = (int) buffer.Length;
request.ContentLength = length;
Stream requestStream = null;
try
{
requestStream = request.GetRequestStream();
requestStream.Write(buffer.ToArray(), 0, length);
}
catch (Exception)
{
return deserial;
}
finally
{
if (requestStream != null)
requestStream.Close();
}
}
try
{
using (WebResponse resp = request.GetResponse())
{
if (resp.ContentLength > 0)
{
Stream respStream = resp.GetResponseStream();
XmlSerializer deserializer = new XmlSerializer(typeof(TResponse));
deserial = (TResponse)deserializer.Deserialize(respStream);
respStream.Close();
}
}
}
catch (System.InvalidOperationException)
{
// This is what happens when there is invalid XML
}
return deserial;
}
}
}

View File

@ -36,6 +36,9 @@ using System.Net.Security;
using System.Reflection;
using System.Text;
using System.Web;
using System.Xml;
using System.Xml.Serialization;
using log4net;
using OpenSim.Framework.Servers.HttpServer;
using OpenMetaverse.StructuredData;
@ -220,7 +223,7 @@ namespace OpenSim.Framework
reqnum,url,method,tickdiff,tickdata);
}
m_log.WarnFormat("[WEB UTIL] <{0}> osd request failed: {1}",reqnum,errorMessage);
m_log.WarnFormat("[WEB UTIL]: <{0}> osd request for {1}, method {2} FAILED: {3}", reqnum, url, method, errorMessage);
return ErrorResponseMap(errorMessage);
}
@ -625,4 +628,336 @@ namespace OpenSim.Framework
}
public static class AsynchronousRestObjectRequester
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Perform an asynchronous REST request.
/// </summary>
/// <param name="verb">GET or POST</param>
/// <param name="requestUrl"></param>
/// <param name="obj"></param>
/// <param name="action"></param>
/// <returns></returns>
///
/// <exception cref="System.Net.WebException">Thrown if we encounter a
/// network issue while posting the request. You'll want to make
/// sure you deal with this as they're not uncommon</exception>
//
public static void MakeRequest<TRequest, TResponse>(string verb,
string requestUrl, TRequest obj, Action<TResponse> action)
{
// m_log.DebugFormat("[ASYNC REQUEST]: Starting {0} {1}", verb, requestUrl);
Type type = typeof(TRequest);
WebRequest request = WebRequest.Create(requestUrl);
WebResponse response = null;
TResponse deserial = default(TResponse);
XmlSerializer deserializer = new XmlSerializer(typeof(TResponse));
request.Method = verb;
if (verb == "POST")
{
request.ContentType = "text/xml";
MemoryStream buffer = new MemoryStream();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
using (XmlWriter writer = XmlWriter.Create(buffer, settings))
{
XmlSerializer serializer = new XmlSerializer(type);
serializer.Serialize(writer, obj);
writer.Flush();
}
int length = (int)buffer.Length;
request.ContentLength = length;
request.BeginGetRequestStream(delegate(IAsyncResult res)
{
Stream requestStream = request.EndGetRequestStream(res);
requestStream.Write(buffer.ToArray(), 0, length);
requestStream.Close();
request.BeginGetResponse(delegate(IAsyncResult ar)
{
response = request.EndGetResponse(ar);
Stream respStream = null;
try
{
respStream = response.GetResponseStream();
deserial = (TResponse)deserializer.Deserialize(
respStream);
}
catch (System.InvalidOperationException)
{
}
finally
{
// Let's not close this
//buffer.Close();
respStream.Close();
response.Close();
}
action(deserial);
}, null);
}, null);
return;
}
request.BeginGetResponse(delegate(IAsyncResult res2)
{
try
{
// If the server returns a 404, this appears to trigger a System.Net.WebException even though that isn't
// documented in MSDN
response = request.EndGetResponse(res2);
Stream respStream = null;
try
{
respStream = response.GetResponseStream();
deserial = (TResponse)deserializer.Deserialize(respStream);
}
catch (System.InvalidOperationException)
{
}
finally
{
respStream.Close();
response.Close();
}
}
catch (WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError)
{
if (e.Response is HttpWebResponse)
{
HttpWebResponse httpResponse = (HttpWebResponse)e.Response;
if (httpResponse.StatusCode != HttpStatusCode.NotFound)
{
// We don't appear to be handling any other status codes, so log these feailures to that
// people don't spend unnecessary hours hunting phantom bugs.
m_log.DebugFormat(
"[ASYNC REQUEST]: Request {0} {1} failed with unexpected status code {2}",
verb, requestUrl, httpResponse.StatusCode);
}
}
}
else
{
m_log.ErrorFormat("[ASYNC REQUEST]: Request {0} {1} failed with status {2} and message {3}", verb, requestUrl, e.Status, e.Message);
}
}
catch (Exception e)
{
m_log.ErrorFormat("[ASYNC REQUEST]: Request {0} {1} failed with exception {2}", verb, requestUrl, e);
}
// m_log.DebugFormat("[ASYNC REQUEST]: Received {0}", deserial.ToString());
try
{
action(deserial);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[ASYNC REQUEST]: Request {0} {1} callback failed with exception {2}", verb, requestUrl, e);
}
}, null);
}
}
public static class SynchronousRestFormsRequester
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Perform a synchronous REST request.
/// </summary>
/// <param name="verb"></param>
/// <param name="requestUrl"></param>
/// <param name="obj"> </param>
/// <returns></returns>
///
/// <exception cref="System.Net.WebException">Thrown if we encounter a network issue while posting
/// the request. You'll want to make sure you deal with this as they're not uncommon</exception>
public static string MakeRequest(string verb, string requestUrl, string obj)
{
WebRequest request = WebRequest.Create(requestUrl);
request.Method = verb;
string respstring = String.Empty;
using (MemoryStream buffer = new MemoryStream())
{
if ((verb == "POST") || (verb == "PUT"))
{
request.ContentType = "text/www-form-urlencoded";
int length = 0;
using (StreamWriter writer = new StreamWriter(buffer))
{
writer.Write(obj);
writer.Flush();
}
length = (int)obj.Length;
request.ContentLength = length;
Stream requestStream = null;
try
{
requestStream = request.GetRequestStream();
requestStream.Write(buffer.ToArray(), 0, length);
}
catch (Exception e)
{
m_log.DebugFormat("[FORMS]: exception occured on sending request to {0}: " + e.ToString(), requestUrl);
}
finally
{
if (requestStream != null)
requestStream.Close();
}
}
try
{
using (WebResponse resp = request.GetResponse())
{
if (resp.ContentLength != 0)
{
Stream respStream = null;
try
{
respStream = resp.GetResponseStream();
using (StreamReader reader = new StreamReader(respStream))
{
respstring = reader.ReadToEnd();
}
}
catch (Exception e)
{
m_log.DebugFormat("[FORMS]: exception occured on receiving reply " + e.ToString());
}
finally
{
if (respStream != null)
respStream.Close();
}
}
}
}
catch (System.InvalidOperationException)
{
// This is what happens when there is invalid XML
m_log.DebugFormat("[FORMS]: InvalidOperationException on receiving request");
}
}
return respstring;
}
}
public class SynchronousRestObjectPoster
{
[Obsolete]
public static TResponse BeginPostObject<TRequest, TResponse>(string verb, string requestUrl, TRequest obj)
{
return SynchronousRestObjectRequester.MakeRequest<TRequest, TResponse>(verb, requestUrl, obj);
}
}
public class SynchronousRestObjectRequester
{
/// <summary>
/// Perform a synchronous REST request.
/// </summary>
/// <param name="verb"></param>
/// <param name="requestUrl"></param>
/// <param name="obj"> </param>
/// <returns></returns>
///
/// <exception cref="System.Net.WebException">Thrown if we encounter a network issue while posting
/// the request. You'll want to make sure you deal with this as they're not uncommon</exception>
public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj)
{
Type type = typeof(TRequest);
TResponse deserial = default(TResponse);
WebRequest request = WebRequest.Create(requestUrl);
request.Method = verb;
if ((verb == "POST") || (verb == "PUT"))
{
request.ContentType = "text/xml";
MemoryStream buffer = new MemoryStream();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
using (XmlWriter writer = XmlWriter.Create(buffer, settings))
{
XmlSerializer serializer = new XmlSerializer(type);
serializer.Serialize(writer, obj);
writer.Flush();
}
int length = (int)buffer.Length;
request.ContentLength = length;
Stream requestStream = null;
try
{
requestStream = request.GetRequestStream();
requestStream.Write(buffer.ToArray(), 0, length);
}
catch (Exception)
{
return deserial;
}
finally
{
if (requestStream != null)
requestStream.Close();
}
}
try
{
using (WebResponse resp = request.GetResponse())
{
if (resp.ContentLength > 0)
{
Stream respStream = resp.GetResponseStream();
XmlSerializer deserializer = new XmlSerializer(typeof(TResponse));
deserial = (TResponse)deserializer.Deserialize(respStream);
respStream.Close();
}
}
}
catch (System.InvalidOperationException)
{
// This is what happens when there is invalid XML
}
return deserial;
}
}
}

View File

@ -252,8 +252,6 @@ namespace OpenSim
// load Crash directory config
m_crashDir = configSource.Configs["Startup"].GetString("crash_dir", m_crashDir);
if (background)
{
m_sim = new OpenSimBackground(configSource);
@ -261,14 +259,8 @@ namespace OpenSim
}
else
{
m_sim = new OpenSim(configSource);
m_sim.Startup();
while (true)

View File

@ -123,7 +123,7 @@ namespace OpenSim
m_log.Info("====================================================================");
m_log.Info("========================= STARTING OPENSIM =========================");
m_log.Info("====================================================================");
m_log.InfoFormat("[OPENSIM MAIN]: Running ");
//m_log.InfoFormat("[OPENSIM MAIN]: GC Is Server GC: {0}", GCSettings.IsServerGC.ToString());
// http://msdn.microsoft.com/en-us/library/bb384202.aspx
//GCSettings.LatencyMode = GCLatencyMode.Batch;
@ -341,7 +341,12 @@ namespace OpenSim
m_console.Commands.AddCommand("region", false, "config get",
"config get [<section>] [<key>]",
"Show a config option",
"Synonym for config show",
HandleConfig);
m_console.Commands.AddCommand("region", false, "config show",
"config show [<section>] [<key>]",
"Show config information",
"If neither section nor field are specified, then the whole current configuration is printed." + Environment.NewLine
+ "If a section is given but not a field, then all fields in that section are printed.",
HandleConfig);
@ -593,7 +598,9 @@ namespace OpenSim
if (cmdparams.Length > 0)
{
switch (cmdparams[0].ToLower())
string firstParam = cmdparams[0].ToLower();
switch (firstParam)
{
case "set":
if (cmdparams.Length < 4)
@ -618,6 +625,7 @@ namespace OpenSim
break;
case "get":
case "show":
if (cmdparams.Length == 1)
{
foreach (IConfig config in m_config.Source.Configs)
@ -654,8 +662,8 @@ namespace OpenSim
}
else
{
Notice("Syntax: config get [<section>] [<key>]");
Notice("Example: config get ScriptEngine.DotNetEngine NumberOfScriptThreads");
Notice("Syntax: config {0} [<section>] [<key>]", firstParam);
Notice("Example: config {0} ScriptEngine.DotNetEngine NumberOfScriptThreads", firstParam);
}
break;

View File

@ -860,7 +860,7 @@ namespace OpenSim
= MainConsole.Instance.CmdPrompt(
string.Format(
"Do you wish to join region {0} to an existing estate (yes/no)?", regInfo.RegionName),
"no",
"yes",
new List<string>() { "yes", "no" });
if (response == "no")
@ -876,10 +876,7 @@ namespace OpenSim
= MainConsole.Instance.CmdPrompt(
string.Format(
"Name of estate to join. Existing estate names are ({0})", string.Join(", ", estateNames.ToArray())),
"None");
if (response == "None")
continue;
estateNames[0]);
List<int> estateIDs = EstateDataService.GetEstates(response);
if (estateIDs.Count < 1)

View File

@ -49,6 +49,8 @@ using Timer = System.Timers.Timer;
using AssetLandmark = OpenSim.Framework.AssetLandmark;
using Nini.Config;
using System.IO;
namespace OpenSim.Region.ClientStack.LindenUDP
{
public delegate bool PacketMethod(IClientAPI simClient, Packet packet);
@ -313,6 +315,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
private int m_cachedTextureSerial;
private PriorityQueue m_entityUpdates;
private PriorityQueue m_entityProps;
private Prioritizer m_prioritizer;
private bool m_disableFacelights = false;
@ -360,9 +363,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP
protected IAssetService m_assetService;
private const bool m_checkPackets = true;
private Timer m_propertiesPacketTimer;
private List<ObjectPropertiesPacket.ObjectDataBlock> m_propertiesBlocks = new List<ObjectPropertiesPacket.ObjectDataBlock>();
#endregion Class Members
#region Properties
@ -438,6 +438,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
m_scene = scene;
m_entityUpdates = new PriorityQueue(m_scene.Entities.Count);
m_entityProps = new PriorityQueue(m_scene.Entities.Count);
m_fullUpdateDataBlocksBuilder = new List<ObjectUpdatePacket.ObjectDataBlock>();
m_killRecord = new HashSet<uint>();
// m_attachmentsSent = new HashSet<uint>();
@ -461,9 +462,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP
m_udpClient.OnQueueEmpty += HandleQueueEmpty;
m_udpClient.OnPacketStats += PopulateStats;
m_propertiesPacketTimer = new Timer(100);
m_propertiesPacketTimer.Elapsed += ProcessObjectPropertiesPacket;
m_prioritizer = new Prioritizer(m_scene);
RegisterLocalPacketHandlers();
@ -1537,7 +1535,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP
}
else
{
OutPacket(kill, ThrottleOutPacketType.State);
// OutPacket(kill, ThrottleOutPacketType.State);
OutPacket(kill, ThrottleOutPacketType.Task);
}
}
@ -2367,7 +2366,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP
packet.Effect = effectBlocks;
OutPacket(packet, ThrottleOutPacketType.State);
// OutPacket(packet, ThrottleOutPacketType.State);
OutPacket(packet, ThrottleOutPacketType.Task);
}
public void SendAvatarProperties(UUID avatarID, string aboutText, string bornOn, Byte[] charterMember,
@ -3547,16 +3547,18 @@ namespace OpenSim.Region.ClientStack.LindenUDP
#region Primitive Packet/Data Sending Methods
/// <summary>
/// Generate one of the object update packets based on PrimUpdateFlags
/// and broadcast the packet to clients
/// </summary>
public void SendPrimUpdate(ISceneEntity entity, PrimUpdateFlags updateFlags)
{
double priority = m_prioritizer.GetUpdatePriority(this, entity);
//double priority = m_prioritizer.GetUpdatePriority(this, entity);
uint priority = m_prioritizer.GetUpdatePriority(this, entity);
lock (m_entityUpdates.SyncRoot)
m_entityUpdates.Enqueue(priority, new EntityUpdate(entity, updateFlags, m_scene.TimeDilation), entity.LocalId);
m_entityUpdates.Enqueue(priority, new EntityUpdate(entity, updateFlags, m_scene.TimeDilation));
}
private void ProcessEntityUpdates(int maxUpdates)
@ -3566,7 +3568,12 @@ namespace OpenSim.Region.ClientStack.LindenUDP
OpenSim.Framework.Lazy<List<ImprovedTerseObjectUpdatePacket.ObjectDataBlock>> terseUpdateBlocks = new OpenSim.Framework.Lazy<List<ImprovedTerseObjectUpdatePacket.ObjectDataBlock>>();
OpenSim.Framework.Lazy<List<ImprovedTerseObjectUpdatePacket.ObjectDataBlock>> terseAgentUpdateBlocks = new OpenSim.Framework.Lazy<List<ImprovedTerseObjectUpdatePacket.ObjectDataBlock>>();
if (maxUpdates <= 0) maxUpdates = Int32.MaxValue;
// Check to see if this is a flush
if (maxUpdates <= 0)
{
maxUpdates = Int32.MaxValue;
}
int updatesThisCall = 0;
// We must lock for both manipulating the kill record and sending the packet, in order to avoid a race
@ -3574,12 +3581,17 @@ namespace OpenSim.Region.ClientStack.LindenUDP
lock (m_killRecord)
{
float avgTimeDilation = 1.0f;
EntityUpdate update;
IEntityUpdate iupdate;
Int32 timeinqueue; // this is just debugging code & can be dropped later
while (updatesThisCall < maxUpdates)
{
lock (m_entityUpdates.SyncRoot)
if (!m_entityUpdates.TryDequeue(out update))
if (!m_entityUpdates.TryDequeue(out iupdate, out timeinqueue))
break;
EntityUpdate update = (EntityUpdate)iupdate;
avgTimeDilation += update.TimeDilation;
avgTimeDilation *= 0.5f;
@ -3619,7 +3631,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
#region UpdateFlags to packet type conversion
PrimUpdateFlags updateFlags = update.Flags;
PrimUpdateFlags updateFlags = (PrimUpdateFlags)update.Flags;
bool canUseCompressed = true;
bool canUseImproved = true;
@ -3679,36 +3691,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
}
else
{
// if (update.Entity is SceneObjectPart && ((SceneObjectPart)update.Entity).IsAttachment)
// {
// SceneObjectPart sop = (SceneObjectPart)update.Entity;
// string text = sop.Text;
// if (text.IndexOf("\n") >= 0)
// text = text.Remove(text.IndexOf("\n"));
//
// if (m_attachmentsSent.Contains(sop.ParentID))
// {
//// m_log.DebugFormat(
//// "[CLIENT]: Sending full info about attached prim {0} text {1}",
//// sop.LocalId, text);
//
// objectUpdateBlocks.Value.Add(CreatePrimUpdateBlock(sop, this.m_agentId));
//
// m_attachmentsSent.Add(sop.LocalId);
// }
// else
// {
// m_log.DebugFormat(
// "[CLIENT]: Requeueing full update of prim {0} text {1} since we haven't sent its parent {2} yet",
// sop.LocalId, text, sop.ParentID);
//
// m_entityUpdates.Enqueue(double.MaxValue, update, sop.LocalId);
// }
// }
// else
// {
objectUpdateBlocks.Value.Add(CreatePrimUpdateBlock((SceneObjectPart)update.Entity, this.m_agentId));
// }
}
}
else if (!canUseImproved)
@ -3728,6 +3711,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
#endregion Block Construction
}
#region Packet Sending
//const float TIME_DILATION = 1.0f;
@ -3802,26 +3786,24 @@ namespace OpenSim.Region.ClientStack.LindenUDP
public void ReprioritizeUpdates()
{
//m_log.Debug("[CLIENT]: Reprioritizing prim updates for " + m_firstName + " " + m_lastName);
lock (m_entityUpdates.SyncRoot)
m_entityUpdates.Reprioritize(UpdatePriorityHandler);
}
private bool UpdatePriorityHandler(ref double priority, uint localID)
private bool UpdatePriorityHandler(ref uint priority, ISceneEntity entity)
{
EntityBase entity;
if (m_scene.Entities.TryGetValue(localID, out entity))
if (entity != null)
{
priority = m_prioritizer.GetUpdatePriority(this, entity);
return true;
}
return priority != double.NaN;
return false;
}
public void FlushPrimUpdates()
{
m_log.Debug("[CLIENT]: Flushing prim updates to " + m_firstName + " " + m_lastName);
m_log.WarnFormat("[CLIENT]: Flushing prim updates to " + m_firstName + " " + m_lastName);
while (m_entityUpdates.Count > 0)
ProcessEntityUpdates(-1);
@ -3829,12 +3811,36 @@ namespace OpenSim.Region.ClientStack.LindenUDP
#endregion Primitive Packet/Data Sending Methods
// These are used to implement an adaptive backoff in the number
// of updates converted to packets. Since we don't want packets
// to sit in the queue with old data, only convert enough updates
// to packets that can be sent in 200ms.
private Int32 m_LastQueueFill = 0;
private Int32 m_maxUpdates = 0;
void HandleQueueEmpty(ThrottleOutPacketTypeFlags categories)
{
if ((categories & ThrottleOutPacketTypeFlags.Task) != 0)
{
if (m_maxUpdates == 0 || m_LastQueueFill == 0)
{
m_maxUpdates = m_udpServer.PrimUpdatesPerCallback;
}
else
{
if (Util.EnvironmentTickCountSubtract(m_LastQueueFill) < 200)
m_maxUpdates += 5;
else
m_maxUpdates = m_maxUpdates >> 1;
}
m_maxUpdates = Util.Clamp<Int32>(m_maxUpdates,10,500);
m_LastQueueFill = Util.EnvironmentTickCount();
if (m_entityUpdates.Count > 0)
ProcessEntityUpdates(m_udpServer.PrimUpdatesPerCallback);
ProcessEntityUpdates(m_maxUpdates);
if (m_entityProps.Count > 0)
ProcessEntityPropertyRequests(m_maxUpdates);
}
if ((categories & ThrottleOutPacketTypeFlags.Texture) != 0)
@ -3948,47 +3954,167 @@ namespace OpenSim.Region.ClientStack.LindenUDP
OutPacket(pack, ThrottleOutPacketType.Task);
}
public void SendObjectPropertiesFamilyData(uint RequestFlags, UUID ObjectUUID, UUID OwnerID, UUID GroupID,
uint BaseMask, uint OwnerMask, uint GroupMask, uint EveryoneMask,
uint NextOwnerMask, int OwnershipCost, byte SaleType, int SalePrice, uint Category,
UUID LastOwnerID, string ObjectName, string Description)
private class ObjectPropertyUpdate : IEntityUpdate
{
ObjectPropertiesFamilyPacket objPropFamilyPack = (ObjectPropertiesFamilyPacket)PacketPool.Instance.GetPacket(PacketType.ObjectPropertiesFamily);
// TODO: don't create new blocks if recycling an old packet
internal bool SendFamilyProps;
internal bool SendObjectProps;
ObjectPropertiesFamilyPacket.ObjectDataBlock objPropDB = new ObjectPropertiesFamilyPacket.ObjectDataBlock();
objPropDB.RequestFlags = RequestFlags;
objPropDB.ObjectID = ObjectUUID;
if (OwnerID == GroupID)
objPropDB.OwnerID = UUID.Zero;
else
objPropDB.OwnerID = OwnerID;
objPropDB.GroupID = GroupID;
objPropDB.BaseMask = BaseMask;
objPropDB.OwnerMask = OwnerMask;
objPropDB.GroupMask = GroupMask;
objPropDB.EveryoneMask = EveryoneMask;
objPropDB.NextOwnerMask = NextOwnerMask;
// TODO: More properties are needed in SceneObjectPart!
objPropDB.OwnershipCost = OwnershipCost;
objPropDB.SaleType = SaleType;
objPropDB.SalePrice = SalePrice;
objPropDB.Category = Category;
objPropDB.LastOwnerID = LastOwnerID;
objPropDB.Name = Util.StringToBytes256(ObjectName);
objPropDB.Description = Util.StringToBytes256(Description);
objPropFamilyPack.ObjectData = objPropDB;
objPropFamilyPack.Header.Zerocoded = true;
OutPacket(objPropFamilyPack, ThrottleOutPacketType.Task);
public ObjectPropertyUpdate(ISceneEntity entity, uint flags, bool sendfam, bool sendobj)
: base(entity,flags)
{
SendFamilyProps = sendfam;
SendObjectProps = sendobj;
}
public void Update(ObjectPropertyUpdate update)
{
SendFamilyProps = SendFamilyProps || update.SendFamilyProps;
SendObjectProps = SendObjectProps || update.SendObjectProps;
Flags |= update.Flags;
}
}
public void SendObjectPropertiesReply(
UUID ItemID, ulong CreationDate, UUID CreatorUUID, UUID FolderUUID, UUID FromTaskUUID,
UUID GroupUUID, short InventorySerial, UUID LastOwnerUUID, UUID ObjectUUID,
UUID OwnerUUID, string TouchTitle, byte[] TextureID, string SitTitle, string ItemName,
string ItemDescription, uint OwnerMask, uint NextOwnerMask, uint GroupMask, uint EveryoneMask,
uint BaseMask, byte saleType, int salePrice)
public void SendObjectPropertiesFamilyData(ISceneEntity entity, uint requestFlags)
{
uint priority = 0; // time based ordering only
lock (m_entityProps.SyncRoot)
m_entityProps.Enqueue(priority, new ObjectPropertyUpdate(entity,requestFlags,true,false));
}
public void SendObjectPropertiesReply(ISceneEntity entity)
{
uint priority = 0; // time based ordering only
lock (m_entityProps.SyncRoot)
m_entityProps.Enqueue(priority, new ObjectPropertyUpdate(entity,0,false,true));
}
private void ProcessEntityPropertyRequests(int maxUpdates)
{
OpenSim.Framework.Lazy<List<ObjectPropertiesFamilyPacket.ObjectDataBlock>> objectFamilyBlocks =
new OpenSim.Framework.Lazy<List<ObjectPropertiesFamilyPacket.ObjectDataBlock>>();
OpenSim.Framework.Lazy<List<ObjectPropertiesPacket.ObjectDataBlock>> objectPropertiesBlocks =
new OpenSim.Framework.Lazy<List<ObjectPropertiesPacket.ObjectDataBlock>>();
IEntityUpdate iupdate;
Int32 timeinqueue; // this is just debugging code & can be dropped later
int updatesThisCall = 0;
while (updatesThisCall < m_maxUpdates)
{
lock (m_entityProps.SyncRoot)
if (!m_entityProps.TryDequeue(out iupdate, out timeinqueue))
break;
ObjectPropertyUpdate update = (ObjectPropertyUpdate)iupdate;
if (update.SendFamilyProps)
{
if (update.Entity is SceneObjectPart)
{
SceneObjectPart sop = (SceneObjectPart)update.Entity;
ObjectPropertiesFamilyPacket.ObjectDataBlock objPropDB = CreateObjectPropertiesFamilyBlock(sop,update.Flags);
objectFamilyBlocks.Value.Add(objPropDB);
}
}
if (update.SendObjectProps)
{
if (update.Entity is SceneObjectPart)
{
SceneObjectPart sop = (SceneObjectPart)update.Entity;
ObjectPropertiesPacket.ObjectDataBlock objPropDB = CreateObjectPropertiesBlock(sop);
objectPropertiesBlocks.Value.Add(objPropDB);
}
}
updatesThisCall++;
}
Int32 ppcnt = 0;
Int32 pbcnt = 0;
if (objectPropertiesBlocks.IsValueCreated)
{
List<ObjectPropertiesPacket.ObjectDataBlock> blocks = objectPropertiesBlocks.Value;
ObjectPropertiesPacket packet = (ObjectPropertiesPacket)PacketPool.Instance.GetPacket(PacketType.ObjectProperties);
packet.ObjectData = new ObjectPropertiesPacket.ObjectDataBlock[blocks.Count];
for (int i = 0; i < blocks.Count; i++)
packet.ObjectData[i] = blocks[i];
packet.Header.Zerocoded = true;
OutPacket(packet, ThrottleOutPacketType.Task, true);
pbcnt += blocks.Count;
ppcnt++;
}
Int32 fpcnt = 0;
Int32 fbcnt = 0;
if (objectFamilyBlocks.IsValueCreated)
{
List<ObjectPropertiesFamilyPacket.ObjectDataBlock> blocks = objectFamilyBlocks.Value;
// ObjectPropertiesFamilyPacket objPropFamilyPack =
// (ObjectPropertiesFamilyPacket)PacketPool.Instance.GetPacket(PacketType.ObjectPropertiesFamily);
//
// objPropFamilyPack.ObjectData = new ObjectPropertiesFamilyPacket.ObjectDataBlock[blocks.Count];
// for (int i = 0; i < blocks.Count; i++)
// objPropFamilyPack.ObjectData[i] = blocks[i];
//
// OutPacket(objPropFamilyPack, ThrottleOutPacketType.Task, true);
// one packet per object block... uggh...
for (int i = 0; i < blocks.Count; i++)
{
ObjectPropertiesFamilyPacket packet =
(ObjectPropertiesFamilyPacket)PacketPool.Instance.GetPacket(PacketType.ObjectPropertiesFamily);
packet.ObjectData = blocks[i];
packet.Header.Zerocoded = true;
OutPacket(packet, ThrottleOutPacketType.Task);
fpcnt++;
fbcnt++;
}
}
// m_log.WarnFormat("[PACKETCOUNTS] queued {0} property packets with {1} blocks",ppcnt,pbcnt);
// m_log.WarnFormat("[PACKETCOUNTS] queued {0} family property packets with {1} blocks",fpcnt,fbcnt);
}
private ObjectPropertiesFamilyPacket.ObjectDataBlock CreateObjectPropertiesFamilyBlock(SceneObjectPart sop, uint requestFlags)
{
ObjectPropertiesFamilyPacket.ObjectDataBlock block = new ObjectPropertiesFamilyPacket.ObjectDataBlock();
block.RequestFlags = requestFlags;
block.ObjectID = sop.UUID;
if (sop.OwnerID == sop.GroupID)
block.OwnerID = UUID.Zero;
else
block.OwnerID = sop.OwnerID;
block.GroupID = sop.GroupID;
block.BaseMask = sop.BaseMask;
block.OwnerMask = sop.OwnerMask;
block.GroupMask = sop.GroupMask;
block.EveryoneMask = sop.EveryoneMask;
block.NextOwnerMask = sop.NextOwnerMask;
// TODO: More properties are needed in SceneObjectPart!
block.OwnershipCost = sop.OwnershipCost;
block.SaleType = sop.ObjectSaleType;
block.SalePrice = sop.SalePrice;
block.Category = sop.Category;
block.LastOwnerID = sop.CreatorID; // copied from old SOG call... is this right?
block.Name = Util.StringToBytes256(sop.Name);
block.Description = Util.StringToBytes256(sop.Description);
return block;
}
private ObjectPropertiesPacket.ObjectDataBlock CreateObjectPropertiesBlock(SceneObjectPart sop)
{
//ObjectPropertiesPacket proper = (ObjectPropertiesPacket)PacketPool.Instance.GetPacket(PacketType.ObjectProperties);
// TODO: don't create new blocks if recycling an old packet
@ -3996,84 +4122,38 @@ namespace OpenSim.Region.ClientStack.LindenUDP
ObjectPropertiesPacket.ObjectDataBlock block =
new ObjectPropertiesPacket.ObjectDataBlock();
block.ItemID = ItemID;
block.CreationDate = CreationDate;
block.CreatorID = CreatorUUID;
block.FolderID = FolderUUID;
block.FromTaskID = FromTaskUUID;
block.GroupID = GroupUUID;
block.InventorySerial = InventorySerial;
block.ObjectID = sop.UUID;
block.Name = Util.StringToBytes256(sop.Name);
block.Description = Util.StringToBytes256(sop.Description);
block.LastOwnerID = LastOwnerUUID;
// proper.ObjectData[0].LastOwnerID = UUID.Zero;
block.ObjectID = ObjectUUID;
if (OwnerUUID == GroupUUID)
block.CreationDate = (ulong)sop.CreationDate * 1000000; // viewer wants date in microseconds
block.CreatorID = sop.CreatorID;
block.GroupID = sop.GroupID;
block.LastOwnerID = sop.LastOwnerID;
if (sop.OwnerID == sop.GroupID)
block.OwnerID = UUID.Zero;
else
block.OwnerID = OwnerUUID;
block.TouchName = Util.StringToBytes256(TouchTitle);
block.TextureID = TextureID;
block.SitName = Util.StringToBytes256(SitTitle);
block.Name = Util.StringToBytes256(ItemName);
block.Description = Util.StringToBytes256(ItemDescription);
block.OwnerMask = OwnerMask;
block.NextOwnerMask = NextOwnerMask;
block.GroupMask = GroupMask;
block.EveryoneMask = EveryoneMask;
block.BaseMask = BaseMask;
// proper.ObjectData[0].AggregatePerms = 53;
// proper.ObjectData[0].AggregatePermTextures = 0;
// proper.ObjectData[0].AggregatePermTexturesOwner = 0;
block.SaleType = saleType;
block.SalePrice = salePrice;
block.OwnerID = sop.OwnerID;
lock (m_propertiesPacketTimer)
{
m_propertiesBlocks.Add(block);
block.ItemID = sop.FromUserInventoryItemID;
block.FolderID = UUID.Zero; // sop.FromFolderID ??
block.FromTaskID = UUID.Zero; // ???
block.InventorySerial = (short)sop.InventorySerial;
int length = 0;
foreach (ObjectPropertiesPacket.ObjectDataBlock b in m_propertiesBlocks)
{
length += b.Length;
}
if (length > 1100) // FIXME: use real MTU
{
ProcessObjectPropertiesPacket(null, null);
m_propertiesPacketTimer.Stop();
return;
}
SceneObjectPart root = sop.ParentGroup.RootPart;
m_propertiesPacketTimer.Stop();
m_propertiesPacketTimer.Start();
}
block.TouchName = Util.StringToBytes256(root.TouchName);
block.TextureID = new byte[0]; // TextureID ???
block.SitName = Util.StringToBytes256(root.SitName);
block.OwnerMask = root.OwnerMask;
block.NextOwnerMask = root.NextOwnerMask;
block.GroupMask = root.GroupMask;
block.EveryoneMask = root.EveryoneMask;
block.BaseMask = root.BaseMask;
block.SaleType = root.ObjectSaleType;
block.SalePrice = root.SalePrice;
//proper.Header.Zerocoded = true;
//OutPacket(proper, ThrottleOutPacketType.Task);
}
private void ProcessObjectPropertiesPacket(Object sender, ElapsedEventArgs e)
{
ObjectPropertiesPacket proper = (ObjectPropertiesPacket)PacketPool.Instance.GetPacket(PacketType.ObjectProperties);
lock (m_propertiesPacketTimer)
{
m_propertiesPacketTimer.Stop();
proper.ObjectData = new ObjectPropertiesPacket.ObjectDataBlock[m_propertiesBlocks.Count];
int index = 0;
foreach (ObjectPropertiesPacket.ObjectDataBlock b in m_propertiesBlocks)
{
proper.ObjectData[index++] = b;
}
m_propertiesBlocks.Clear();
}
proper.Header.Zerocoded = true;
OutPacket(proper, ThrottleOutPacketType.Task);
return block;
}
#region Estate Data Sending Methods
@ -4217,6 +4297,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP
public void SendEstateCovenantInformation(UUID covenant)
{
// m_log.DebugFormat("[LLCLIENTVIEW]: Sending estate covenant asset id of {0} to {1}", covenant, Name);
EstateCovenantReplyPacket einfopack = new EstateCovenantReplyPacket();
EstateCovenantReplyPacket.DataBlock edata = new EstateCovenantReplyPacket.DataBlock();
edata.CovenantID = covenant;
@ -4227,8 +4309,13 @@ namespace OpenSim.Region.ClientStack.LindenUDP
OutPacket(einfopack, ThrottleOutPacketType.Task);
}
public void SendDetailedEstateData(UUID invoice, string estateName, uint estateID, uint parentEstate, uint estateFlags, uint sunPosition, UUID covenant, string abuseEmail, UUID estateOwner)
public void SendDetailedEstateData(
UUID invoice, string estateName, uint estateID, uint parentEstate, uint estateFlags, uint sunPosition,
UUID covenant, string abuseEmail, UUID estateOwner)
{
// m_log.DebugFormat(
// "[LLCLIENTVIEW]: Sending detailed estate data to {0} with covenant asset id {1}", Name, covenant);
EstateOwnerMessagePacket packet = new EstateOwnerMessagePacket();
packet.MethodData.Invoice = invoice;
packet.AgentData.TransactionID = UUID.Random();
@ -4407,6 +4494,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP
public void SendForceClientSelectObjects(List<uint> ObjectIDs)
{
m_log.WarnFormat("[LLCLIENTVIEW] sending select with {0} objects", ObjectIDs.Count);
bool firstCall = true;
const int MAX_OBJECTS_PER_PACKET = 251;
ForceObjectSelectPacket pack = (ForceObjectSelectPacket)PacketPool.Instance.GetPacket(PacketType.ForceObjectSelect);
@ -4938,7 +5027,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
AddLocalPacketHandler(PacketType.TeleportLocationRequest, HandleTeleportLocationRequest);
AddLocalPacketHandler(PacketType.UUIDNameRequest, HandleUUIDNameRequest, false);
AddLocalPacketHandler(PacketType.RegionHandleRequest, HandleRegionHandleRequest);
AddLocalPacketHandler(PacketType.ParcelInfoRequest, HandleParcelInfoRequest, false);
AddLocalPacketHandler(PacketType.ParcelInfoRequest, HandleParcelInfoRequest);
AddLocalPacketHandler(PacketType.ParcelAccessListRequest, HandleParcelAccessListRequest, false);
AddLocalPacketHandler(PacketType.ParcelAccessListUpdate, HandleParcelAccessListUpdate, false);
AddLocalPacketHandler(PacketType.ParcelPropertiesRequest, HandleParcelPropertiesRequest, false);
@ -8809,13 +8898,29 @@ namespace OpenSim.Region.ClientStack.LindenUDP
case "instantmessage":
if (((Scene)m_scene).Permissions.CanIssueEstateCommand(AgentId, false))
{
if (messagePacket.ParamList.Length < 5)
if (messagePacket.ParamList.Length < 2)
return true;
UUID invoice = messagePacket.MethodData.Invoice;
UUID SenderID = new UUID(Utils.BytesToString(messagePacket.ParamList[2].Parameter));
string SenderName = Utils.BytesToString(messagePacket.ParamList[3].Parameter);
string Message = Utils.BytesToString(messagePacket.ParamList[4].Parameter);
UUID sessionID = messagePacket.AgentData.SessionID;
UUID SenderID;
string SenderName;
string Message;
if (messagePacket.ParamList.Length < 5)
{
SenderID = AgentId;
SenderName = Utils.BytesToString(messagePacket.ParamList[0].Parameter);
Message = Utils.BytesToString(messagePacket.ParamList[1].Parameter);
}
else
{
SenderID = new UUID(Utils.BytesToString(messagePacket.ParamList[2].Parameter));
SenderName = Utils.BytesToString(messagePacket.ParamList[3].Parameter);
Message = Utils.BytesToString(messagePacket.ParamList[4].Parameter);
}
OnEstateBlueBoxMessageRequest(this, invoice, SenderID, sessionID, SenderName, Message);
}
return true;
@ -11710,171 +11815,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP
OutPacket(pack, ThrottleOutPacketType.Task);
}
#region PriorityQueue
public class PriorityQueue
{
internal delegate bool UpdatePriorityHandler(ref double priority, uint local_id);
private MinHeap<MinHeapItem>[] m_heaps = new MinHeap<MinHeapItem>[1];
private Dictionary<uint, LookupItem> m_lookupTable;
private Comparison<double> m_comparison;
private object m_syncRoot = new object();
internal PriorityQueue() :
this(MinHeap<MinHeapItem>.DEFAULT_CAPACITY, Comparer<double>.Default) { }
internal PriorityQueue(int capacity) :
this(capacity, Comparer<double>.Default) { }
internal PriorityQueue(IComparer<double> comparer) :
this(new Comparison<double>(comparer.Compare)) { }
internal PriorityQueue(Comparison<double> comparison) :
this(MinHeap<MinHeapItem>.DEFAULT_CAPACITY, comparison) { }
internal PriorityQueue(int capacity, IComparer<double> comparer) :
this(capacity, new Comparison<double>(comparer.Compare)) { }
internal PriorityQueue(int capacity, Comparison<double> comparison)
{
m_lookupTable = new Dictionary<uint, LookupItem>(capacity);
for (int i = 0; i < m_heaps.Length; ++i)
m_heaps[i] = new MinHeap<MinHeapItem>(capacity);
this.m_comparison = comparison;
}
public object SyncRoot { get { return this.m_syncRoot; } }
internal int Count
{
get
{
int count = 0;
for (int i = 0; i < m_heaps.Length; ++i)
count = m_heaps[i].Count;
return count;
}
}
public bool Enqueue(double priority, EntityUpdate value, uint local_id)
{
LookupItem item;
if (m_lookupTable.TryGetValue(local_id, out item))
{
// Combine flags
value.Flags |= item.Heap[item.Handle].Value.Flags;
item.Heap[item.Handle] = new MinHeapItem(priority, value, local_id, this.m_comparison);
return false;
}
else
{
item.Heap = m_heaps[0];
item.Heap.Add(new MinHeapItem(priority, value, local_id, this.m_comparison), ref item.Handle);
m_lookupTable.Add(local_id, item);
return true;
}
}
internal EntityUpdate Peek()
{
for (int i = 0; i < m_heaps.Length; ++i)
if (m_heaps[i].Count > 0)
return m_heaps[i].Min().Value;
throw new InvalidOperationException(string.Format("The {0} is empty", this.GetType().ToString()));
}
internal bool TryDequeue(out EntityUpdate value)
{
for (int i = 0; i < m_heaps.Length; ++i)
{
if (m_heaps[i].Count > 0)
{
MinHeapItem item = m_heaps[i].RemoveMin();
m_lookupTable.Remove(item.LocalID);
value = item.Value;
return true;
}
}
value = default(EntityUpdate);
return false;
}
internal void Reprioritize(UpdatePriorityHandler handler)
{
MinHeapItem item;
double priority;
foreach (LookupItem lookup in new List<LookupItem>(this.m_lookupTable.Values))
{
if (lookup.Heap.TryGetValue(lookup.Handle, out item))
{
priority = item.Priority;
if (handler(ref priority, item.LocalID))
{
if (lookup.Heap.ContainsHandle(lookup.Handle))
lookup.Heap[lookup.Handle] =
new MinHeapItem(priority, item.Value, item.LocalID, this.m_comparison);
}
else
{
m_log.Warn("[LLCLIENTVIEW]: UpdatePriorityHandler returned false, dropping update");
lookup.Heap.Remove(lookup.Handle);
this.m_lookupTable.Remove(item.LocalID);
}
}
}
}
#region MinHeapItem
private struct MinHeapItem : IComparable<MinHeapItem>
{
private double priority;
private EntityUpdate value;
private uint local_id;
private Comparison<double> comparison;
internal MinHeapItem(double priority, EntityUpdate value, uint local_id) :
this(priority, value, local_id, Comparer<double>.Default) { }
internal MinHeapItem(double priority, EntityUpdate value, uint local_id, IComparer<double> comparer) :
this(priority, value, local_id, new Comparison<double>(comparer.Compare)) { }
internal MinHeapItem(double priority, EntityUpdate value, uint local_id, Comparison<double> comparison)
{
this.priority = priority;
this.value = value;
this.local_id = local_id;
this.comparison = comparison;
}
internal double Priority { get { return this.priority; } }
internal EntityUpdate Value { get { return this.value; } }
internal uint LocalID { get { return this.local_id; } }
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("[");
sb.Append(this.priority.ToString());
sb.Append(",");
if (this.value != null)
sb.Append(this.value.ToString());
sb.Append("]");
return sb.ToString();
}
public int CompareTo(MinHeapItem other)
{
return this.comparison(this.priority, other.priority);
}
}
#endregion
#region LookupItem
private struct LookupItem
{
internal MinHeap<MinHeapItem> Heap;
internal IHandle Handle;
}
#endregion
}
public struct PacketProcessor
{
public PacketMethod method;
@ -11895,8 +11835,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP
}
}
#endregion
public static OSD BuildEvent(string eventName, OSD eventBody)
{
OSDMap osdEvent = new OSDMap(2);

View File

@ -135,7 +135,9 @@ namespace OpenSim.Region.ClientStack.LindenUDP
private int m_nextOnQueueEmpty = 1;
/// <summary>Throttle bucket for this agent's connection</summary>
private readonly TokenBucket m_throttle;
private readonly TokenBucket m_throttleClient;
/// <summary>Throttle bucket for this agent's connection</summary>
private readonly TokenBucket m_throttleCategory;
/// <summary>Throttle buckets for each packet category</summary>
private readonly TokenBucket[] m_throttleCategories;
/// <summary>Outgoing queues for throttled packets</summary>
@ -149,7 +151,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
/// <summary>Caches packed throttle information</summary>
private byte[] m_packedThrottles;
private int m_defaultRTO = 3000;
private int m_defaultRTO = 1000; // 1sec is the recommendation in the RFC
private int m_maxRTO = 60000;
/// <summary>
@ -174,7 +176,9 @@ namespace OpenSim.Region.ClientStack.LindenUDP
m_maxRTO = maxRTO;
// Create a token bucket throttle for this client that has the scene token bucket as a parent
m_throttle = new TokenBucket(parentThrottle, rates.TotalLimit, rates.Total);
m_throttleClient = new TokenBucket(parentThrottle, rates.TotalLimit);
// Create a token bucket throttle for the total categary with the client bucket as a throttle
m_throttleCategory = new TokenBucket(m_throttleClient, rates.TotalLimit);
// Create an array of token buckets for this clients different throttle categories
m_throttleCategories = new TokenBucket[THROTTLE_CATEGORY_COUNT];
@ -185,7 +189,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
// Initialize the packet outboxes, where packets sit while they are waiting for tokens
m_packetOutboxes[i] = new OpenSim.Framework.LocklessQueue<OutgoingPacket>();
// Initialize the token buckets that control the throttling for each category
m_throttleCategories[i] = new TokenBucket(m_throttle, rates.GetLimit(type), rates.GetRate(type));
m_throttleCategories[i] = new TokenBucket(m_throttleCategory, rates.GetLimit(type));
}
// Default the retransmission timeout to three seconds
@ -206,6 +210,9 @@ namespace OpenSim.Region.ClientStack.LindenUDP
m_packetOutboxes[i].Clear();
m_nextPackets[i] = null;
}
// pull the throttle out of the scene throttle
m_throttleClient.Parent.UnregisterRequest(m_throttleClient);
OnPacketStats = null;
OnQueueEmpty = null;
}
@ -216,6 +223,26 @@ namespace OpenSim.Region.ClientStack.LindenUDP
/// <returns>Information about the client connection</returns>
public ClientInfo GetClientInfo()
{
///<mic>
TokenBucket tb;
tb = m_throttleClient.Parent;
m_log.WarnFormat("[TOKENS] {3}: Actual={0},Request={1},TotalRequest={2}",tb.DripRate,tb.RequestedDripRate,tb.TotalDripRequest,"ROOT");
tb = m_throttleClient;
m_log.WarnFormat("[TOKENS] {3}: Actual={0},Request={1},TotalRequest={2}",tb.DripRate,tb.RequestedDripRate,tb.TotalDripRequest," CLIENT");
tb = m_throttleCategory;
m_log.WarnFormat("[TOKENS] {3}: Actual={0},Request={1},TotalRequest={2}",tb.DripRate,tb.RequestedDripRate,tb.TotalDripRequest," CATEGORY");
for (int i = 0; i < THROTTLE_CATEGORY_COUNT; i++)
{
tb = m_throttleCategories[i];
m_log.WarnFormat("[TOKENS] {4} <{0}:{1}>: Actual={2},Requested={3}",AgentID,i,tb.DripRate,tb.RequestedDripRate," BUCKET");
}
///</mic>
// TODO: This data structure is wrong in so many ways. Locking and copying the entire lists
// of pending and needed ACKs for every client every time some method wants information about
// this connection is a recipe for poor performance
@ -223,13 +250,14 @@ namespace OpenSim.Region.ClientStack.LindenUDP
info.pendingAcks = new Dictionary<uint, uint>();
info.needAck = new Dictionary<uint, byte[]>();
info.resendThrottle = m_throttleCategories[(int)ThrottleOutPacketType.Resend].DripRate;
info.landThrottle = m_throttleCategories[(int)ThrottleOutPacketType.Land].DripRate;
info.windThrottle = m_throttleCategories[(int)ThrottleOutPacketType.Wind].DripRate;
info.cloudThrottle = m_throttleCategories[(int)ThrottleOutPacketType.Cloud].DripRate;
info.taskThrottle = m_throttleCategories[(int)ThrottleOutPacketType.State].DripRate + m_throttleCategories[(int)ThrottleOutPacketType.Task].DripRate;
info.assetThrottle = m_throttleCategories[(int)ThrottleOutPacketType.Asset].DripRate;
info.textureThrottle = m_throttleCategories[(int)ThrottleOutPacketType.Texture].DripRate;
info.resendThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Resend].DripRate;
info.landThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Land].DripRate;
info.windThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Wind].DripRate;
info.cloudThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Cloud].DripRate;
// info.taskThrottle = m_throttleCategories[(int)ThrottleOutPacketType.State].DripRate + m_throttleCategories[(int)ThrottleOutPacketType.Task].DripRate;
info.taskThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Task].DripRate;
info.assetThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Asset].DripRate;
info.textureThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Texture].DripRate;
info.totalThrottle = info.resendThrottle + info.landThrottle + info.windThrottle + info.cloudThrottle +
info.taskThrottle + info.assetThrottle + info.textureThrottle;
@ -317,8 +345,9 @@ namespace OpenSim.Region.ClientStack.LindenUDP
int texture = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); pos += 4;
int asset = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f);
// State is a subcategory of task that we allocate a percentage to
int state = (int)((float)task * STATE_TASK_PERCENTAGE);
task -= state;
int state = 0;
// int state = (int)((float)task * STATE_TASK_PERCENTAGE);
// task -= state;
// Make sure none of the throttles are set below our packet MTU,
// otherwise a throttle could become permanently clogged
@ -339,40 +368,32 @@ namespace OpenSim.Region.ClientStack.LindenUDP
// Update the token buckets with new throttle values
TokenBucket bucket;
bucket = m_throttle;
bucket.MaxBurst = total;
bucket = m_throttleCategory;
bucket.RequestedDripRate = total;
bucket = m_throttleCategories[(int)ThrottleOutPacketType.Resend];
bucket.DripRate = resend;
bucket.MaxBurst = resend;
bucket.RequestedDripRate = resend;
bucket = m_throttleCategories[(int)ThrottleOutPacketType.Land];
bucket.DripRate = land;
bucket.MaxBurst = land;
bucket.RequestedDripRate = land;
bucket = m_throttleCategories[(int)ThrottleOutPacketType.Wind];
bucket.DripRate = wind;
bucket.MaxBurst = wind;
bucket.RequestedDripRate = wind;
bucket = m_throttleCategories[(int)ThrottleOutPacketType.Cloud];
bucket.DripRate = cloud;
bucket.MaxBurst = cloud;
bucket.RequestedDripRate = cloud;
bucket = m_throttleCategories[(int)ThrottleOutPacketType.Asset];
bucket.DripRate = asset;
bucket.MaxBurst = asset;
bucket.RequestedDripRate = asset;
bucket = m_throttleCategories[(int)ThrottleOutPacketType.Task];
bucket.DripRate = task + state;
bucket.MaxBurst = task + state;
bucket.RequestedDripRate = task;
bucket = m_throttleCategories[(int)ThrottleOutPacketType.State];
bucket.DripRate = state;
bucket.MaxBurst = state;
bucket.RequestedDripRate = state;
bucket = m_throttleCategories[(int)ThrottleOutPacketType.Texture];
bucket.DripRate = texture;
bucket.MaxBurst = texture;
bucket.RequestedDripRate = texture;
// Reset the packed throttles cached data
m_packedThrottles = null;
@ -387,14 +408,13 @@ namespace OpenSim.Region.ClientStack.LindenUDP
data = new byte[7 * 4];
int i = 0;
Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Resend].DripRate), 0, data, i, 4); i += 4;
Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Land].DripRate), 0, data, i, 4); i += 4;
Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Wind].DripRate), 0, data, i, 4); i += 4;
Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Cloud].DripRate), 0, data, i, 4); i += 4;
Buffer.BlockCopy(Utils.FloatToBytes((float)(m_throttleCategories[(int)ThrottleOutPacketType.Task].DripRate) +
m_throttleCategories[(int)ThrottleOutPacketType.State].DripRate), 0, data, i, 4); i += 4;
Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Texture].DripRate), 0, data, i, 4); i += 4;
Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Asset].DripRate), 0, data, i, 4); i += 4;
Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Resend].RequestedDripRate), 0, data, i, 4); i += 4;
Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Land].RequestedDripRate), 0, data, i, 4); i += 4;
Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Wind].RequestedDripRate), 0, data, i, 4); i += 4;
Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Cloud].RequestedDripRate), 0, data, i, 4); i += 4;
Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Task].RequestedDripRate), 0, data, i, 4); i += 4;
Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Texture].RequestedDripRate), 0, data, i, 4); i += 4;
Buffer.BlockCopy(Utils.FloatToBytes((float)m_throttleCategories[(int)ThrottleOutPacketType.Asset].RequestedDripRate), 0, data, i, 4); i += 4;
m_packedThrottles = data;
}
@ -420,6 +440,16 @@ namespace OpenSim.Region.ClientStack.LindenUDP
OpenSim.Framework.LocklessQueue<OutgoingPacket> queue = m_packetOutboxes[category];
TokenBucket bucket = m_throttleCategories[category];
// Don't send this packet if there is already a packet waiting in the queue
// even if we have the tokens to send it, tokens should go to the already
// queued packets
if (queue.Count > 0)
{
queue.Enqueue(packet);
return true;
}
if (!forceQueue && bucket.RemoveTokens(packet.Buffer.DataLength))
{
// Enough tokens were removed from the bucket, the packet will not be queued
@ -557,7 +587,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
int rto = (int)(SRTT + Math.Max(m_udpServer.TickCountResolution, K * RTTVAR));
// Clamp the retransmission timeout to manageable values
rto = Utils.Clamp(RTO, m_defaultRTO, m_maxRTO);
rto = Utils.Clamp(rto, m_defaultRTO, m_maxRTO);
RTO = rto;

View File

@ -228,7 +228,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
}
#endregion BinaryStats
m_throttle = new TokenBucket(null, sceneThrottleBps, sceneThrottleBps);
m_throttle = new TokenBucket(null, sceneThrottleBps);
ThrottleRates = new ThrottleRates(configSource);
}

View File

@ -101,6 +101,10 @@ namespace OpenMetaverse
IPEndPoint ipep = new IPEndPoint(m_localBindAddress, m_udpPort);
m_log.DebugFormat(
"[UDPBASE]: Binding UDP listener using internal IP address config {0}:{1}",
ipep.Address, ipep.Port);
m_udpSocket = new Socket(
AddressFamily.InterNetwork,
SocketType.Dgram,

View File

@ -0,0 +1,245 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using OpenSim.Framework;
using OpenSim.Framework.Client;
using log4net;
namespace OpenSim.Region.ClientStack.LindenUDP
{
public class PriorityQueue
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
internal delegate bool UpdatePriorityHandler(ref uint priority, ISceneEntity entity);
// Heap[0] for self updates
// Heap[1..12] for entity updates
internal const uint m_numberOfQueues = 12;
private MinHeap<MinHeapItem>[] m_heaps = new MinHeap<MinHeapItem>[m_numberOfQueues];
private Dictionary<uint, LookupItem> m_lookupTable;
private uint m_nextQueue = 0;
private UInt64 m_nextRequest = 0;
private object m_syncRoot = new object();
public object SyncRoot {
get { return this.m_syncRoot; }
}
internal PriorityQueue() : this(MinHeap<MinHeapItem>.DEFAULT_CAPACITY) { }
internal PriorityQueue(int capacity)
{
m_lookupTable = new Dictionary<uint, LookupItem>(capacity);
for (int i = 0; i < m_heaps.Length; ++i)
m_heaps[i] = new MinHeap<MinHeapItem>(capacity);
}
internal int Count
{
get
{
int count = 0;
for (int i = 0; i < m_heaps.Length; ++i)
count += m_heaps[i].Count;
return count;
}
}
public bool Enqueue(uint pqueue, IEntityUpdate value)
{
LookupItem lookup;
uint localid = value.Entity.LocalId;
UInt64 entry = m_nextRequest++;
if (m_lookupTable.TryGetValue(localid, out lookup))
{
entry = lookup.Heap[lookup.Handle].EntryOrder;
value.Update(lookup.Heap[lookup.Handle].Value);
lookup.Heap.Remove(lookup.Handle);
}
pqueue = Util.Clamp<uint>(pqueue, 0, m_numberOfQueues - 1);
lookup.Heap = m_heaps[pqueue];
lookup.Heap.Add(new MinHeapItem(pqueue, entry, value), ref lookup.Handle);
m_lookupTable[localid] = lookup;
return true;
}
internal bool TryDequeue(out IEntityUpdate value, out Int32 timeinqueue)
{
for (int i = 0; i < m_numberOfQueues; ++i)
{
// To get the fair queing, we cycle through each of the
// queues when finding an element to dequeue, this code
// assumes that the distribution of updates in the queues
// is polynomial, probably quadractic (eg distance of PI * R^2)
uint h = (uint)((m_nextQueue + i) % m_numberOfQueues);
if (m_heaps[h].Count > 0)
{
m_nextQueue = (uint)((h + 1) % m_numberOfQueues);
MinHeapItem item = m_heaps[h].RemoveMin();
m_lookupTable.Remove(item.Value.Entity.LocalId);
timeinqueue = Util.EnvironmentTickCountSubtract(item.EntryTime);
value = item.Value;
return true;
}
}
timeinqueue = 0;
value = default(IEntityUpdate);
return false;
}
internal void Reprioritize(UpdatePriorityHandler handler)
{
MinHeapItem item;
foreach (LookupItem lookup in new List<LookupItem>(this.m_lookupTable.Values))
{
if (lookup.Heap.TryGetValue(lookup.Handle, out item))
{
uint pqueue = item.PriorityQueue;
uint localid = item.Value.Entity.LocalId;
if (handler(ref pqueue, item.Value.Entity))
{
// unless the priority queue has changed, there is no need to modify
// the entry
pqueue = Util.Clamp<uint>(pqueue, 0, m_numberOfQueues - 1);
if (pqueue != item.PriorityQueue)
{
lookup.Heap.Remove(lookup.Handle);
LookupItem litem = lookup;
litem.Heap = m_heaps[pqueue];
litem.Heap.Add(new MinHeapItem(pqueue, item), ref litem.Handle);
m_lookupTable[localid] = litem;
}
}
else
{
// m_log.WarnFormat("[PQUEUE]: UpdatePriorityHandler returned false for {0}",item.Value.Entity.UUID);
lookup.Heap.Remove(lookup.Handle);
this.m_lookupTable.Remove(localid);
}
}
}
}
public override string ToString()
{
string s = "";
for (int i = 0; i < m_numberOfQueues; i++)
{
if (s != "") s += ",";
s += m_heaps[i].Count.ToString();
}
return s;
}
#region MinHeapItem
private struct MinHeapItem : IComparable<MinHeapItem>
{
private IEntityUpdate value;
internal IEntityUpdate Value {
get {
return this.value;
}
}
private uint pqueue;
internal uint PriorityQueue {
get {
return this.pqueue;
}
}
private Int32 entrytime;
internal Int32 EntryTime {
get {
return this.entrytime;
}
}
private UInt64 entryorder;
internal UInt64 EntryOrder
{
get {
return this.entryorder;
}
}
internal MinHeapItem(uint pqueue, MinHeapItem other)
{
this.entrytime = other.entrytime;
this.entryorder = other.entryorder;
this.value = other.value;
this.pqueue = pqueue;
}
internal MinHeapItem(uint pqueue, UInt64 entryorder, IEntityUpdate value)
{
this.entrytime = Util.EnvironmentTickCount();
this.entryorder = entryorder;
this.value = value;
this.pqueue = pqueue;
}
public override string ToString()
{
return String.Format("[{0},{1},{2}]",pqueue,entryorder,value.Entity.LocalId);
}
public int CompareTo(MinHeapItem other)
{
// I'm assuming that the root part of an SOG is added to the update queue
// before the component parts
return Comparer<UInt64>.Default.Compare(this.EntryOrder, other.EntryOrder);
}
}
#endregion
#region LookupItem
private struct LookupItem
{
internal MinHeap<MinHeapItem> Heap;
internal IHandle Handle;
}
#endregion
}
}

View File

@ -26,6 +26,10 @@
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using log4net;
namespace OpenSim.Region.ClientStack.LindenUDP
{
@ -35,89 +39,126 @@ namespace OpenSim.Region.ClientStack.LindenUDP
/// </summary>
public class TokenBucket
{
/// <summary>Parent bucket to this bucket, or null if this is a root
/// bucket</summary>
TokenBucket parent;
/// <summary>Size of the bucket in bytes. If zero, the bucket has
/// infinite capacity</summary>
int maxBurst;
/// <summary>Rate that the bucket fills, in bytes per millisecond. If
/// zero, the bucket always remains full</summary>
int tokensPerMS;
/// <summary>Number of tokens currently in the bucket</summary>
int content;
/// <summary>Time of the last drip, in system ticks</summary>
int lastDrip;
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static Int32 m_counter = 0;
#region Properties
private Int32 m_identifier;
/// <summary>
/// Number of ticks (ms) per quantum, drip rate and max burst
/// are defined over this interval.
/// </summary>
private const Int32 m_ticksPerQuantum = 1000;
/// <summary>
/// This is the number of quantums worth of packets that can
/// be accommodated during a burst
/// </summary>
private const Double m_quantumsPerBurst = 1.5;
/// <summary>
/// </summary>
private const Int32 m_minimumDripRate = 1400;
/// <summary>Time of the last drip, in system ticks</summary>
private Int32 m_lastDrip;
/// <summary>
/// The number of bytes that can be sent at this moment. This is the
/// current number of tokens in the bucket
/// </summary>
private Int64 m_tokenCount;
/// <summary>
/// Map of children buckets and their requested maximum burst rate
/// </summary>
private Dictionary<TokenBucket,Int64> m_children = new Dictionary<TokenBucket,Int64>();
#region Properties
/// <summary>
/// The parent bucket of this bucket, or null if this bucket has no
/// parent. The parent bucket will limit the aggregate bandwidth of all
/// of its children buckets
/// </summary>
private TokenBucket m_parent;
public TokenBucket Parent
{
get { return parent; }
get { return m_parent; }
set { m_parent = value; }
}
/// <summary>
/// Maximum burst rate in bytes per second. This is the maximum number
/// of tokens that can accumulate in the bucket at any one time
/// of tokens that can accumulate in the bucket at any one time. This
/// also sets the total request for leaf nodes
/// </summary>
public int MaxBurst
private Int64 m_burstRate;
public Int64 RequestedBurstRate
{
get { return maxBurst; }
set { maxBurst = (value >= 0 ? value : 0); }
get { return m_burstRate; }
set { m_burstRate = (value < 0 ? 0 : value); }
}
public Int64 BurstRate
{
get {
double rate = RequestedBurstRate * BurstRateModifier();
if (rate < m_minimumDripRate * m_quantumsPerBurst)
rate = m_minimumDripRate * m_quantumsPerBurst;
return (Int64) rate;
}
}
/// <summary>
/// The speed limit of this bucket in bytes per second. This is the
/// number of tokens that are added to the bucket per second
/// number of tokens that are added to the bucket per quantum
/// </summary>
/// <remarks>Tokens are added to the bucket any time
/// <seealso cref="RemoveTokens"/> is called, at the granularity of
/// the system tick interval (typically around 15-22ms)</remarks>
public int DripRate
private Int64 m_dripRate;
public Int64 RequestedDripRate
{
get { return tokensPerMS * 1000; }
set
{
if (value == 0)
tokensPerMS = 0;
else
{
int bpms = (int)((float)value / 1000.0f);
if (bpms <= 0)
tokensPerMS = 1; // 1 byte/ms is the minimum granularity
else
tokensPerMS = bpms;
get { return (m_dripRate == 0 ? m_totalDripRequest : m_dripRate); }
set {
m_dripRate = (value < 0 ? 0 : value);
m_burstRate = (Int64)((double)m_dripRate * m_quantumsPerBurst);
m_totalDripRequest = m_dripRate;
if (m_parent != null)
m_parent.RegisterRequest(this,m_dripRate);
}
}
public Int64 DripRate
{
get {
if (m_parent == null)
return Math.Min(RequestedDripRate,TotalDripRequest);
double rate = (double)RequestedDripRate * m_parent.DripRateModifier();
if (rate < m_minimumDripRate)
rate = m_minimumDripRate;
return (Int64)rate;
}
}
/// <summary>
/// The speed limit of this bucket in bytes per millisecond
/// The current total of the requested maximum burst rates of
/// this bucket's children buckets.
/// </summary>
public int DripPerMS
private Int64 m_totalDripRequest;
public Int64 TotalDripRequest
{
get { return tokensPerMS; }
get { return m_totalDripRequest; }
set { m_totalDripRequest = value; }
}
/// <summary>
/// The number of bytes that can be sent at this moment. This is the
/// current number of tokens in the bucket
/// <remarks>If this bucket has a parent bucket that does not have
/// enough tokens for a request, <seealso cref="RemoveTokens"/> will
/// return false regardless of the content of this bucket</remarks>
/// </summary>
public int Content
{
get { return content; }
}
#endregion Properties
#endregion Properties
#region Constructor
/// <summary>
/// Default constructor
@ -128,12 +169,76 @@ namespace OpenSim.Region.ClientStack.LindenUDP
/// zero if this bucket has no maximum capacity</param>
/// <param name="dripRate">Rate that the bucket fills, in bytes per
/// second. If zero, the bucket always remains full</param>
public TokenBucket(TokenBucket parent, int maxBurst, int dripRate)
public TokenBucket(TokenBucket parent, Int64 dripRate)
{
this.parent = parent;
MaxBurst = maxBurst;
DripRate = dripRate;
lastDrip = Environment.TickCount & Int32.MaxValue;
m_identifier = m_counter++;
Parent = parent;
RequestedDripRate = dripRate;
// TotalDripRequest = dripRate; // this will be overwritten when a child node registers
// MaxBurst = (Int64)((double)dripRate * m_quantumsPerBurst);
m_lastDrip = Environment.TickCount & Int32.MaxValue;
}
#endregion Constructor
/// <summary>
/// Compute a modifier for the MaxBurst rate. This is 1.0, meaning
/// no modification if the requested bandwidth is less than the
/// max burst bandwidth all the way to the root of the throttle
/// hierarchy. However, if any of the parents is over-booked, then
/// the modifier will be less than 1.
/// </summary>
private double DripRateModifier()
{
Int64 driprate = DripRate;
return driprate >= TotalDripRequest ? 1.0 : (double)driprate / (double)TotalDripRequest;
}
/// <summary>
/// </summary>
private double BurstRateModifier()
{
// for now... burst rate is always m_quantumsPerBurst (constant)
// larger than drip rate so the ratio of burst requests is the
// same as the drip ratio
return DripRateModifier();
}
/// <summary>
/// Register drip rate requested by a child of this throttle. Pass the
/// changes up the hierarchy.
/// </summary>
public void RegisterRequest(TokenBucket child, Int64 request)
{
m_children[child] = request;
// m_totalDripRequest = m_children.Values.Sum();
m_totalDripRequest = 0;
foreach (KeyValuePair<TokenBucket, Int64> cref in m_children)
m_totalDripRequest += cref.Value;
// Pass the new values up to the parent
if (m_parent != null)
m_parent.RegisterRequest(this,Math.Min(RequestedDripRate, TotalDripRequest));
}
/// <summary>
/// Remove the rate requested by a child of this throttle. Pass the
/// changes up the hierarchy.
/// </summary>
public void UnregisterRequest(TokenBucket child)
{
m_children.Remove(child);
// m_totalDripRequest = m_children.Values.Sum();
m_totalDripRequest = 0;
foreach (KeyValuePair<TokenBucket, Int64> cref in m_children)
m_totalDripRequest += cref.Value;
// Pass the new values up to the parent
if (m_parent != null)
m_parent.RegisterRequest(this,Math.Min(RequestedDripRate, TotalDripRequest));
}
/// <summary>
@ -142,42 +247,36 @@ namespace OpenSim.Region.ClientStack.LindenUDP
/// <param name="amount">Number of tokens to remove from the bucket</param>
/// <returns>True if the requested number of tokens were removed from
/// the bucket, otherwise false</returns>
public bool RemoveTokens(int amount)
public bool RemoveTokens(Int64 amount)
{
bool dummy;
return RemoveTokens(amount, out dummy);
// Deposit tokens for this interval
Drip();
// If we have enough tokens then remove them and return
if (m_tokenCount - amount >= 0)
{
// we don't have to remove from the parent, the drip rate is already
// reflective of the drip rate limits in the parent
m_tokenCount -= amount;
return true;
}
return false;
}
/// <summary>
/// Remove a given number of tokens from the bucket
/// Deposit tokens into the bucket from a child bucket that did
/// not use all of its available tokens
/// </summary>
/// <param name="amount">Number of tokens to remove from the bucket</param>
/// <param name="dripSucceeded">True if tokens were added to the bucket
/// during this call, otherwise false</param>
/// <returns>True if the requested number of tokens were removed from
/// the bucket, otherwise false</returns>
public bool RemoveTokens(int amount, out bool dripSucceeded)
private void Deposit(Int64 count)
{
if (maxBurst == 0)
{
dripSucceeded = true;
return true;
}
m_tokenCount += count;
dripSucceeded = Drip();
if (content - amount >= 0)
{
if (parent != null && !parent.RemoveTokens(amount))
return false;
content -= amount;
return true;
}
else
{
return false;
}
// Deposit the overflow in the parent bucket, this is how we share
// unused bandwidth
Int64 burstrate = BurstRate;
if (m_tokenCount > burstrate)
m_tokenCount = burstrate;
}
/// <summary>
@ -186,37 +285,29 @@ namespace OpenSim.Region.ClientStack.LindenUDP
/// call to Drip
/// </summary>
/// <returns>True if tokens were added to the bucket, otherwise false</returns>
public bool Drip()
private void Drip()
{
if (tokensPerMS == 0)
// This should never happen... means we are a leaf node and were created
// with no drip rate...
if (DripRate == 0)
{
content = maxBurst;
return true;
m_log.WarnFormat("[TOKENBUCKET] something odd is happening and drip rate is 0");
return;
}
else
{
int now = Environment.TickCount & Int32.MaxValue;
int deltaMS = now - lastDrip;
// Determine the interval over which we are adding tokens, never add
// more than a single quantum of tokens
Int32 now = Environment.TickCount & Int32.MaxValue;
Int32 deltaMS = Math.Min(now - m_lastDrip, m_ticksPerQuantum);
m_lastDrip = now;
// This can be 0 in the very unusual case that the timer wrapped
// It can be 0 if we try add tokens at a sub-tick rate
if (deltaMS <= 0)
{
if (deltaMS < 0)
lastDrip = now;
return false;
}
return;
int dripAmount = deltaMS * tokensPerMS;
content = Math.Min(content + dripAmount, maxBurst);
lastDrip = now;
if (dripAmount < 0 || content < 0)
// sim has been idle for too long, integer has overflown
// previous calculation is meaningless, let's put it at correct max
content = maxBurst;
return true;
}
Deposit(deltaMS * DripRate / m_ticksPerQuantum);
}
}
}

View File

@ -54,6 +54,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Assets
private Scene m_scene;
private IAssetService m_assetService;
private bool m_enabled = true;
#region IRegionModuleBase Members
@ -65,7 +66,11 @@ namespace OpenSim.Region.CoreModules.Avatar.Assets
public void Initialise(IConfigSource source)
{
IConfig meshConfig = source.Configs["Mesh"];
if (meshConfig == null)
return;
m_enabled = meshConfig.GetBoolean("ColladaMesh", true);
}
public void AddRegion(Scene pScene)
@ -101,16 +106,19 @@ namespace OpenSim.Region.CoreModules.Avatar.Assets
public void RegisterCaps(UUID agentID, Caps caps)
{
if(!m_enabled)
return;
UUID capID = UUID.Random();
// m_log.Info("[GETMESH]: /CAPS/" + capID);
caps.RegisterHandler("GetMesh",
new RestHTTPHandler("GET", "/CAPS/" + capID,
delegate(Hashtable m_dhttpMethod)
{
return ProcessGetMesh(m_dhttpMethod, agentID, caps);
}));
}
#endregion

View File

@ -56,6 +56,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Assets
private Scene m_scene;
// private IAssetService m_assetService;
private bool m_dumpAssetsToFile = false;
private bool m_enabled = true;
#region IRegionModuleBase Members
@ -67,7 +68,11 @@ namespace OpenSim.Region.CoreModules.Avatar.Assets
public void Initialise(IConfigSource source)
{
IConfig meshConfig = source.Configs["Mesh"];
if (meshConfig == null)
return;
m_enabled = meshConfig.GetBoolean("ColladaMesh", true);
}
public void AddRegion(Scene pScene)
@ -103,6 +108,9 @@ namespace OpenSim.Region.CoreModules.Avatar.Assets
public void RegisterCaps(UUID agentID, Caps caps)
{
if(!m_enabled)
return;
UUID capID = UUID.Random();
// m_log.Debug("[NEW FILE AGENT INVENTORY VARIABLE PRICE]: /CAPS/" + capID);

View File

@ -34,13 +34,13 @@ using Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Framework.Communications;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenSim.Services.Connectors.Friends;
using OpenSim.Server.Base;
using OpenSim.Framework.Servers.HttpServer;
using FriendInfo = OpenSim.Services.Interfaces.FriendInfo;
using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;

View File

@ -33,7 +33,6 @@ using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Framework.Client;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;

View File

@ -77,7 +77,17 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
/// </value>
private Stream m_loadStream;
protected bool m_controlFileLoaded;
/// <summary>
/// Has the control file been loaded for this archive?
/// </summary>
public bool ControlFileLoaded { get; private set; }
/// <summary>
/// Do we want to enforce the check. IAR versions before 0.2 and 1.1 do not guarantee this order, so we can't
/// enforce.
/// </summary>
public bool EnforceControlFileCheck { get; private set; }
protected bool m_assetsLoaded;
protected bool m_inventoryNodesLoaded;
@ -126,6 +136,11 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
m_userInfo = userInfo;
m_invPath = invPath;
m_loadStream = loadStream;
// FIXME: Do not perform this check since older versions of OpenSim do save the control file after other things
// (I thought they weren't). We will need to bump the version number and perform this check on all
// subsequent IAR versions only
ControlFileLoaded = true;
}
/// <summary>
@ -466,16 +481,30 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
if (m_creatorIdForAssetId.ContainsKey(assetId))
{
string xmlData = Utils.BytesToString(data);
SceneObjectGroup sog = SceneObjectSerializer.FromOriginalXmlFormat(xmlData);
foreach (SceneObjectPart sop in sog.Parts)
List<SceneObjectGroup> sceneObjects = new List<SceneObjectGroup>();
CoalescedSceneObjects coa = null;
if (CoalescedSceneObjectsSerializer.TryFromXml(xmlData, out coa))
{
if (sop.CreatorData == null || sop.CreatorData == "")
{
sop.CreatorID = m_creatorIdForAssetId[assetId];
// m_log.DebugFormat(
// "[INVENTORY ARCHIVER]: Loaded coalescence {0} has {1} objects", assetId, coa.Count);
sceneObjects.AddRange(coa.Objects);
}
else
{
sceneObjects.Add(SceneObjectSerializer.FromOriginalXmlFormat(xmlData));
}
data = Utils.StringToBytes(SceneObjectSerializer.ToOriginalXmlFormat(sog));
foreach (SceneObjectGroup sog in sceneObjects)
foreach (SceneObjectPart sop in sog.Parts)
if (sop.CreatorData == null || sop.CreatorData == "")
sop.CreatorID = m_creatorIdForAssetId[assetId];
if (coa != null)
data = Utils.StringToBytes(CoalescedSceneObjectsSerializer.ToXml(coa));
else
data = Utils.StringToBytes(SceneObjectSerializer.ToOriginalXmlFormat(sceneObjects[0]));
}
}
@ -503,7 +532,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
/// </summary>
/// <param name="path"></param>
/// <param name="data"></param>
protected void LoadControlFile(string path, byte[] data)
public void LoadControlFile(string path, byte[] data)
{
XDocument doc = XDocument.Parse(Encoding.ASCII.GetString(data));
XElement archiveElement = doc.Element("archive");
@ -519,7 +548,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
majorVersion, MAX_MAJOR_VERSION));
}
m_controlFileLoaded = true;
ControlFileLoaded = true;
m_log.InfoFormat("[INVENTORY ARCHIVER]: Loading IAR with version {0}", version);
}
@ -531,7 +560,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
/// <param name="data"></param>
protected void LoadInventoryFile(string path, TarArchiveReader.TarEntryType entryType, byte[] data)
{
if (!m_controlFileLoaded)
if (!ControlFileLoaded)
throw new Exception(
string.Format(
"The IAR you are trying to load does not list {0} before {1}. Aborting load",
@ -578,7 +607,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
/// <param name="data"></param>
protected void LoadAssetFile(string path, byte[] data)
{
if (!m_controlFileLoaded)
if (!ControlFileLoaded)
throw new Exception(
string.Format(
"The IAR you are trying to load does not list {0} before {1}. Aborting load",

View File

@ -394,12 +394,12 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
if (options.ContainsKey("profile"))
{
majorVersion = 1;
minorVersion = 0;
minorVersion = 1;
}
else
{
majorVersion = 0;
minorVersion = 1;
minorVersion = 2;
}
m_log.InfoFormat("[INVENTORY ARCHIVER]: Creating version {0}.{1} IAR", majorVersion, minorVersion);

View File

@ -68,17 +68,21 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
PrincipalID = UUID.Parse("00000000-0000-0000-0000-000000000555"),
FirstName = "Mr",
LastName = "Tiddles" };
protected UserAccount m_uaLL1
= new UserAccount {
PrincipalID = UUID.Parse("00000000-0000-0000-0000-000000000666"),
FirstName = "Lord",
LastName = "Lucan" };
protected UserAccount m_uaLL2
= new UserAccount {
PrincipalID = UUID.Parse("00000000-0000-0000-0000-000000000777"),
FirstName = "Lord",
LastName = "Lucan" };
protected string m_item1Name = "Ray Gun Item";
protected string m_coaItemName = "Coalesced Item";
[SetUp]
public virtual void SetUp()
@ -97,38 +101,22 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
// log4net.Config.XmlConfigurator.Configure();
InventoryArchiverModule archiverModule = new InventoryArchiverModule();
Scene scene = SceneSetupHelpers.SetupScene("Inventory");
Scene scene = SceneSetupHelpers.SetupScene();
SceneSetupHelpers.SetupSceneModules(scene, archiverModule);
UserProfileTestUtils.CreateUserWithInventory(scene, m_uaLL1, "hampshire");
MemoryStream archiveWriteStream = new MemoryStream();
// Create asset
SceneObjectGroup object1;
SceneObjectPart part1;
{
string partName = "Ray Gun Object";
// Create scene object asset
UUID ownerId = UUID.Parse("00000000-0000-0000-0000-000000000040");
PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere();
Vector3 groupPosition = new Vector3(10, 20, 30);
Quaternion rotationOffset = new Quaternion(20, 30, 40, 50);
Vector3 offsetPosition = new Vector3(5, 10, 15);
part1
= new SceneObjectPart(
ownerId, shape, groupPosition, rotationOffset, offsetPosition);
part1.Name = partName;
object1 = new SceneObjectGroup(part1);
scene.AddNewSceneObject(object1, false);
}
SceneObjectGroup object1 = SceneSetupHelpers.CreateSceneObject(1, ownerId, "Ray Gun Object", 0x50);
UUID asset1Id = UUID.Parse("00000000-0000-0000-0000-000000000060");
AssetBase asset1 = AssetHelpers.CreateAsset(asset1Id, object1);
scene.AssetService.Store(asset1);
// Create item
// Create scene object item
InventoryItemBase item1 = new InventoryItemBase();
item1.Name = m_item1Name;
item1.ID = UUID.Parse("00000000-0000-0000-0000-000000000020");
@ -139,8 +127,31 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
item1.Folder = scene.InventoryService.GetRootFolder(m_uaLL1.PrincipalID).ID;
scene.AddInventoryItem(item1);
// Create coalesced objects asset
SceneObjectGroup cobj1 = SceneSetupHelpers.CreateSceneObject(1, m_uaLL1.PrincipalID, "Object1", 0x120);
cobj1.AbsolutePosition = new Vector3(15, 30, 45);
SceneObjectGroup cobj2 = SceneSetupHelpers.CreateSceneObject(1, m_uaLL1.PrincipalID, "Object2", 0x140);
cobj2.AbsolutePosition = new Vector3(25, 50, 75);
CoalescedSceneObjects coa = new CoalescedSceneObjects(m_uaLL1.PrincipalID, cobj1, cobj2);
AssetBase coaAsset = AssetHelpers.CreateAsset(0x160, coa);
scene.AssetService.Store(coaAsset);
// Create coalesced objects inventory item
InventoryItemBase coaItem = new InventoryItemBase();
coaItem.Name = m_coaItemName;
coaItem.ID = UUID.Parse("00000000-0000-0000-0000-000000000180");
coaItem.AssetID = coaAsset.FullID;
coaItem.GroupID = UUID.Random();
coaItem.CreatorIdAsUuid = m_uaLL1.PrincipalID;
coaItem.Owner = m_uaLL1.PrincipalID;
coaItem.Folder = scene.InventoryService.GetRootFolder(m_uaLL1.PrincipalID).ID;
scene.AddInventoryItem(coaItem);
archiverModule.ArchiveInventory(
Guid.NewGuid(), m_uaLL1.FirstName, m_uaLL1.LastName, m_item1Name, "hampshire", archiveWriteStream);
Guid.NewGuid(), m_uaLL1.FirstName, m_uaLL1.LastName, "/*", "hampshire", archiveWriteStream);
m_iarStreamBytes = archiveWriteStream.ToArray();
}

View File

@ -62,10 +62,67 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
SerialiserModule serialiserModule = new SerialiserModule();
m_archiverModule = new InventoryArchiverModule();
m_scene = SceneSetupHelpers.SetupScene("Inventory");
m_scene = SceneSetupHelpers.SetupScene();
SceneSetupHelpers.SetupSceneModules(m_scene, serialiserModule, m_archiverModule);
}
[Test]
public void TestLoadCoalesecedItem()
{
TestHelper.InMethod();
// log4net.Config.XmlConfigurator.Configure();
UserProfileTestUtils.CreateUserWithInventory(m_scene, m_uaLL1, "password");
m_archiverModule.DearchiveInventory(m_uaLL1.FirstName, m_uaLL1.LastName, "/", "password", m_iarStream);
InventoryItemBase coaItem
= InventoryArchiveUtils.FindItemByPath(m_scene.InventoryService, m_uaLL1.PrincipalID, m_coaItemName);
Assert.That(coaItem, Is.Not.Null, "Didn't find loaded item 1");
string assetXml = AssetHelpers.ReadAssetAsString(m_scene.AssetService, coaItem.AssetID);
CoalescedSceneObjects coa;
bool readResult = CoalescedSceneObjectsSerializer.TryFromXml(assetXml, out coa);
Assert.That(readResult, Is.True);
Assert.That(coa.Count, Is.EqualTo(2));
List<SceneObjectGroup> coaObjects = coa.Objects;
Assert.That(coaObjects[0].UUID, Is.EqualTo(UUID.Parse("00000000-0000-0000-0000-000000000120")));
Assert.That(coaObjects[0].AbsolutePosition, Is.EqualTo(new Vector3(15, 30, 45)));
Assert.That(coaObjects[1].UUID, Is.EqualTo(UUID.Parse("00000000-0000-0000-0000-000000000140")));
Assert.That(coaObjects[1].AbsolutePosition, Is.EqualTo(new Vector3(25, 50, 75)));
}
/// <summary>
/// Test that the IAR has the required files in the right order.
/// </summary>
/// <remarks>
/// At the moment, the only thing that matters is that the control file is the very first one.
/// </remarks>
[Test]
public void TestOrder()
{
TestHelper.InMethod();
// log4net.Config.XmlConfigurator.Configure();
MemoryStream archiveReadStream = new MemoryStream(m_iarStreamBytes);
TarArchiveReader tar = new TarArchiveReader(archiveReadStream);
string filePath;
TarArchiveReader.TarEntryType tarEntryType;
byte[] data = tar.ReadEntry(out filePath, out tarEntryType);
Assert.That(filePath, Is.EqualTo(ArchiveConstants.CONTROL_FILE_PATH));
InventoryArchiveReadRequest iarr
= new InventoryArchiveReadRequest(null, null, null, (Stream)null, false);
iarr.LoadControlFile(filePath, data);
Assert.That(iarr.ControlFileLoaded, Is.True);
}
/// <summary>
/// Test saving a single inventory item to a V0.1 OpenSim Inventory Archive
/// (subject to change since there is no fixed format yet).
@ -84,24 +141,8 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
UserProfileTestUtils.CreateUserWithInventory(m_scene, userFirstName, userLastName, userId, userPassword);
// Create asset
SceneObjectGroup object1;
SceneObjectPart part1;
{
string partName = "My Little Dog Object";
UUID ownerId = UUID.Parse("00000000-0000-0000-0000-000000000040");
PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere();
Vector3 groupPosition = new Vector3(10, 20, 30);
Quaternion rotationOffset = new Quaternion(20, 30, 40, 50);
Vector3 offsetPosition = new Vector3(5, 10, 15);
part1
= new SceneObjectPart(
ownerId, shape, groupPosition, rotationOffset, offsetPosition);
part1.Name = partName;
object1 = new SceneObjectGroup(part1);
m_scene.AddNewSceneObject(object1, false);
}
SceneObjectGroup object1 = SceneSetupHelpers.CreateSceneObject(1, ownerId, "My Little Dog Object", 0x50);
UUID asset1Id = UUID.Parse("00000000-0000-0000-0000-000000000060");
AssetBase asset1 = AssetHelpers.CreateAsset(asset1Id, object1);

View File

@ -63,7 +63,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
InventoryArchiverModule archiverModule = new InventoryArchiverModule();
Scene scene = SceneSetupHelpers.SetupScene("Inventory");
Scene scene = SceneSetupHelpers.SetupScene();
SceneSetupHelpers.SetupSceneModules(scene, archiverModule);
// Create user
@ -180,7 +180,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
InventoryArchiverModule archiverModule = new InventoryArchiverModule();
// Annoyingly, we have to set up a scene even though inventory loading has nothing to do with a scene
Scene scene = SceneSetupHelpers.SetupScene("inventory");
Scene scene = SceneSetupHelpers.SetupScene();
SceneSetupHelpers.SetupSceneModules(scene, serialiserModule, archiverModule);
@ -223,7 +223,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
SerialiserModule serialiserModule = new SerialiserModule();
InventoryArchiverModule archiverModule = new InventoryArchiverModule();
Scene scene = SceneSetupHelpers.SetupScene("inventory");
Scene scene = SceneSetupHelpers.SetupScene();
SceneSetupHelpers.SetupSceneModules(scene, serialiserModule, archiverModule);
UserProfileTestUtils.CreateUserWithInventory(scene, m_uaMT, "password");
@ -248,7 +248,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
InventoryArchiverModule archiverModule = new InventoryArchiverModule();
Scene scene = SceneSetupHelpers.SetupScene("Inventory");
Scene scene = SceneSetupHelpers.SetupScene();
SceneSetupHelpers.SetupSceneModules(scene, archiverModule);
// Create user
@ -327,7 +327,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
TestHelper.InMethod();
// log4net.Config.XmlConfigurator.Configure();
Scene scene = SceneSetupHelpers.SetupScene("inventory");
Scene scene = SceneSetupHelpers.SetupScene();
UserAccount ua1 = UserProfileTestUtils.CreateUserWithInventory(scene);
Dictionary <string, InventoryFolderBase> foldersCreated = new Dictionary<string, InventoryFolderBase>();
@ -394,7 +394,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
TestHelper.InMethod();
//log4net.Config.XmlConfigurator.Configure();
Scene scene = SceneSetupHelpers.SetupScene("inventory");
Scene scene = SceneSetupHelpers.SetupScene();
UserAccount ua1 = UserProfileTestUtils.CreateUserWithInventory(scene);
string folder1ExistingName = "a";
@ -445,7 +445,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
TestHelper.InMethod();
// log4net.Config.XmlConfigurator.Configure();
Scene scene = SceneSetupHelpers.SetupScene("inventory");
Scene scene = SceneSetupHelpers.SetupScene();
UserAccount ua1 = UserProfileTestUtils.CreateUserWithInventory(scene);
string folder1ExistingName = "a";

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