Merge branch 'careminster' into tests

avinationmerge
KittoFlora 2009-11-16 01:40:15 +01:00
commit 873c9098d8
177 changed files with 5520 additions and 4206 deletions

View File

@ -123,6 +123,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
availableMethods["admin_region_query"] = XmlRpcRegionQueryMethod;
availableMethods["admin_shutdown"] = XmlRpcShutdownMethod;
availableMethods["admin_broadcast"] = XmlRpcAlertMethod;
availableMethods["admin_dialog"] = XmlRpcDialogMethod;
availableMethods["admin_restart"] = XmlRpcRestartMethod;
availableMethods["admin_load_heightmap"] = XmlRpcLoadHeightmapMethod;
// User management
@ -277,6 +278,53 @@ namespace OpenSim.ApplicationPlugins.RemoteController
m_log.Info("[RADMIN]: Alert request complete");
return response;
}
public XmlRpcResponse XmlRpcDialogMethod(XmlRpcRequest request, IPEndPoint remoteClient)
{
XmlRpcResponse response = new XmlRpcResponse();
Hashtable responseData = new Hashtable();
m_log.Info("[RADMIN]: Dialog request started");
try
{
Hashtable requestData = (Hashtable)request.Params[0];
checkStringParameters(request, new string[] { "password", "from", "message" });
if (m_requiredPassword != String.Empty &&
(!requestData.Contains("password") || (string)requestData["password"] != m_requiredPassword))
throw new Exception("wrong password");
string message = (string)requestData["message"];
string fromuuid = (string)requestData["from"];
m_log.InfoFormat("[RADMIN]: Broadcasting: {0}", message);
responseData["accepted"] = true;
responseData["success"] = true;
response.Value = responseData;
m_app.SceneManager.ForEachScene(
delegate(Scene scene)
{
IDialogModule dialogModule = scene.RequestModuleInterface<IDialogModule>();
if (dialogModule != null)
dialogModule.SendNotificationToUsersInRegion(UUID.Zero, fromuuid, message);
});
}
catch (Exception e)
{
m_log.ErrorFormat("[RADMIN]: Broadcasting: failed: {0}", e.Message);
m_log.DebugFormat("[RADMIN]: Broadcasting: failed: {0}", e.ToString());
responseData["accepted"] = false;
responseData["success"] = false;
responseData["error"] = e.Message;
response.Value = responseData;
}
m_log.Info("[RADMIN]: Alert request complete");
return response;
}
public XmlRpcResponse XmlRpcLoadHeightmapMethod(XmlRpcRequest request, IPEndPoint remoteClient)
{
@ -360,7 +408,7 @@ namespace OpenSim.ApplicationPlugins.RemoteController
&& ((string) requestData["shutdown"] == "delayed")
&& requestData.ContainsKey("milliseconds"))
{
timeout = (Int32) requestData["milliseconds"];
timeout = Int32.Parse(requestData["milliseconds"].ToString());
message
= "Region is going down in " + ((int) (timeout/1000)).ToString()
@ -1562,11 +1610,8 @@ namespace OpenSim.ApplicationPlugins.RemoteController
assets = doc.GetElementsByTagName("RequiredAsset");
foreach (XmlNode asset in assets)
{
AssetBase rass = new AssetBase();
rass.FullID = UUID.Random();
rass.Name = GetStringAttribute(asset,"name","");
AssetBase rass = new AssetBase(UUID.Random(), GetStringAttribute(asset,"name",""), SByte.Parse(GetStringAttribute(asset,"type","")));
rass.Description = GetStringAttribute(asset,"desc","");
rass.Type = SByte.Parse(GetStringAttribute(asset,"type",""));
rass.Local = Boolean.Parse(GetStringAttribute(asset,"local",""));
rass.Temporary = Boolean.Parse(GetStringAttribute(asset,"temporary",""));
rass.Data = Convert.FromBase64String(asset.InnerText);

View File

@ -261,11 +261,8 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory
modified = (asset != null);
created = !modified;
asset = new AssetBase();
asset.FullID = uuid;
asset.Name = xml.GetAttribute("name");
asset = new AssetBase(uuid, xml.GetAttribute("name"), SByte.Parse(xml.GetAttribute("type")));
asset.Description = xml.GetAttribute("desc");
asset.Type = SByte.Parse(xml.GetAttribute("type"));
asset.Local = Int32.Parse(xml.GetAttribute("local")) != 0;
asset.Temporary = Int32.Parse(xml.GetAttribute("temporary")) != 0;
asset.Data = Convert.FromBase64String(xml.ReadElementContentAsString("Asset", ""));
@ -341,11 +338,8 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory
modified = (asset != null);
created = !modified;
asset = new AssetBase();
asset.FullID = uuid;
asset.Name = xml.GetAttribute("name");
asset = new AssetBase(uuid, xml.GetAttribute("name"), SByte.Parse(xml.GetAttribute("type")));
asset.Description = xml.GetAttribute("desc");
asset.Type = SByte.Parse(xml.GetAttribute("type"));
asset.Local = Int32.Parse(xml.GetAttribute("local")) != 0;
asset.Temporary = Int32.Parse(xml.GetAttribute("temporary")) != 0;
asset.Data = Convert.FromBase64String(xml.ReadElementContentAsString("Asset", ""));

View File

@ -1869,10 +1869,9 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory
// Create AssetBase entity to hold the inlined asset
asset = new AssetBase(uuid, name);
asset = new AssetBase(uuid, name, type);
asset.Description = desc;
asset.Type = type; // type == 0 == texture
asset.Local = local;
asset.Temporary = temp;

View File

@ -231,6 +231,10 @@ namespace OpenSim.Client.Linden
{
return scene.RegionInfo;
}
else if (m_scenes.Count > 0)
{
return m_scenes[0].RegionInfo;
}
return null;
}

View File

@ -676,6 +676,7 @@ namespace OpenSim.Client.MXP.ClientStack
public event FriendActionDelegate OnApproveFriendRequest;
public event FriendActionDelegate OnDenyFriendRequest;
public event FriendshipTermination OnTerminateFriendship;
public event GrantUserFriendRights OnGrantUserRights;
public event MoneyTransferRequest OnMoneyTransferRequest;
public event EconomyDataRequest OnEconomyDataRequest;
public event MoneyBalanceRequest OnMoneyBalanceRequest;
@ -1052,7 +1053,7 @@ namespace OpenSim.Client.MXP.ClientStack
{
}
public void SendInventoryFolderDetails(UUID ownerID, UUID folderID, List<InventoryItemBase> items, List<InventoryFolderBase> folders, bool fetchFolders, bool fetchItems)
public void SendInventoryFolderDetails(UUID ownerID, UUID folderID, List<InventoryItemBase> items, List<InventoryFolderBase> folders, int version, bool fetchFolders, bool fetchItems)
{
// Need to translate to MXP somehow
}

View File

@ -110,9 +110,12 @@ namespace OpenSim.Client.MXP
public void Close()
{
m_shutdown = true;
if (m_ticker != null)
{
lock (m_ticker)
m_ticker.Stop();
}
}
public string Name
{

View File

@ -327,6 +327,7 @@ namespace OpenSim.Client.VWoHTTP.ClientStack
public event FriendActionDelegate OnApproveFriendRequest = delegate { };
public event FriendActionDelegate OnDenyFriendRequest = delegate { };
public event FriendshipTermination OnTerminateFriendship = delegate { };
public event GrantUserFriendRights OnGrantUserRights = delegate { };
public event MoneyTransferRequest OnMoneyTransferRequest = delegate { };
public event EconomyDataRequest OnEconomyDataRequest = delegate { };
public event MoneyBalanceRequest OnMoneyBalanceRequest = delegate { };
@ -406,6 +407,7 @@ namespace OpenSim.Client.VWoHTTP.ClientStack
public event PlacesQuery OnPlacesQuery = delegate { };
public void SetDebugPacketLevel(int newDebug)
{
throw new System.NotImplementedException();
@ -606,7 +608,7 @@ namespace OpenSim.Client.VWoHTTP.ClientStack
throw new System.NotImplementedException();
}
public void SendInventoryFolderDetails(UUID ownerID, UUID folderID, List<InventoryItemBase> items, List<InventoryFolderBase> folders, bool fetchFolders, bool fetchItems)
public void SendInventoryFolderDetails(UUID ownerID, UUID folderID, List<InventoryItemBase> items, List<InventoryFolderBase> folders, int version, bool fetchFolders, bool fetchItems)
{
throw new System.NotImplementedException();
}

View File

@ -197,11 +197,20 @@ namespace OpenSim.Data.MSSQL
public void Dispose()
{
SqlConnection conn = realCommand.Connection;
try { realCommand.Dispose(); }
try
{
realCommand.Dispose();
}
finally
{
try { conn.Dispose(); }
finally { }
try
{
conn.Close();
}
finally
{
conn.Dispose();
}
}
}

View File

@ -132,12 +132,13 @@ namespace OpenSim.Data.MSSQL
{
if (reader.Read())
{
AssetBase asset = new AssetBase();
AssetBase asset = new AssetBase(
new UUID((Guid)reader["id"]),
(string)reader["name"],
Convert.ToSByte(reader["assetType"])
);
// Region Main
asset.FullID = new UUID((Guid)reader["id"]);
asset.Name = (string)reader["name"];
asset.Description = (string)reader["description"];
asset.Type = Convert.ToSByte(reader["assetType"]);
asset.Local = Convert.ToBoolean(reader["local"]);
asset.Temporary = Convert.ToBoolean(reader["temporary"]);
asset.Data = (byte[])reader["data"];

View File

@ -348,6 +348,8 @@ namespace OpenSim.Data.MSSQL
//Delete the actual row
DeleteOneFolder(folderID, connection);
DeleteItemsInFolder(folderID, connection);
connection.Close();
}
}

View File

@ -1049,7 +1049,7 @@ VALUES
if (!(primRow["ParticleSystem"] is DBNull))
prim.ParticleSystem = (Byte[])primRow["ParticleSystem"];
prim.RotationalVelocity = new Vector3(
prim.AngularVelocity = new Vector3(
Convert.ToSingle(primRow["OmegaX"]),
Convert.ToSingle(primRow["OmegaY"]),
Convert.ToSingle(primRow["OmegaZ"]));
@ -1429,9 +1429,9 @@ VALUES
parameters.Add(_Database.CreateParameter("TextureAnimation", prim.TextureAnimation));
parameters.Add(_Database.CreateParameter("ParticleSystem", prim.ParticleSystem));
parameters.Add(_Database.CreateParameter("OmegaX", prim.RotationalVelocity.X));
parameters.Add(_Database.CreateParameter("OmegaY", prim.RotationalVelocity.Y));
parameters.Add(_Database.CreateParameter("OmegaZ", prim.RotationalVelocity.Z));
parameters.Add(_Database.CreateParameter("OmegaX", prim.AngularVelocity.X));
parameters.Add(_Database.CreateParameter("OmegaY", prim.AngularVelocity.Y));
parameters.Add(_Database.CreateParameter("OmegaZ", prim.AngularVelocity.Z));
parameters.Add(_Database.CreateParameter("CameraEyeOffsetX", prim.GetCameraEyeOffset().X));
parameters.Add(_Database.CreateParameter("CameraEyeOffsetY", prim.GetCameraEyeOffset().Y));

View File

@ -340,6 +340,8 @@ namespace OpenSim.Data.MSSQL
MSSQLMigration migration = new MSSQLMigration(connection, assem, migrationStore);
migration.Update();
connection.Close();
}
}
@ -383,7 +385,9 @@ namespace OpenSim.Data.MSSQL
m_log.Error(e.ToString());
}
}
tables.Close();
}
}
/// <summary>

View File

@ -56,6 +56,7 @@ namespace OpenSim.Data.MSSQL
{
version = Convert.ToInt32(reader["version"]);
}
reader.Close();
}
}
catch

View File

@ -131,8 +131,7 @@ namespace OpenSim.Data
m_log.InfoFormat("[MIGRATIONS] Upgrading {0} to latest revision.", _type);
m_log.Info("[MIGRATIONS] NOTE: this may take a while, don't interupt this process!");
using (DbCommand cmd = _conn.CreateCommand())
{
DbCommand cmd = _conn.CreateCommand();
foreach (KeyValuePair<int, string> kvp in migrations)
{
int newversion = kvp.Key;
@ -150,7 +149,7 @@ namespace OpenSim.Data
UpdateVersion(_type, newversion);
}
version = newversion;
}
cmd.Dispose();
}
}
@ -190,45 +189,43 @@ namespace OpenSim.Data
protected virtual int FindVersion(DbConnection conn, string type)
{
int version = 0;
using (DbCommand cmd = conn.CreateCommand())
{
DbCommand cmd = conn.CreateCommand();
try
{
cmd.CommandText = "select version from migrations where name='" + type + "' order by version desc";
cmd.CommandText = "select version from migrations where name='" + type +"' order by version desc";
using (IDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
version = Convert.ToInt32(reader["version"]);
}
reader.Close();
}
}
catch
{
// Something went wrong, so we're version 0
}
}
cmd.Dispose();
return version;
}
private void InsertVersion(string type, int version)
{
using (DbCommand cmd = _conn.CreateCommand())
{
DbCommand cmd = _conn.CreateCommand();
cmd.CommandText = "insert into migrations(name, version) values('" + type + "', " + version + ")";
m_log.InfoFormat("[MIGRATIONS]: Creating {0} at version {1}", type, version);
cmd.ExecuteNonQuery();
}
cmd.Dispose();
}
private void UpdateVersion(string type, int version)
{
using (DbCommand cmd = _conn.CreateCommand())
{
DbCommand cmd = _conn.CreateCommand();
cmd.CommandText = "update migrations set version=" + version + " where name='" + type + "'";
m_log.InfoFormat("[MIGRATIONS]: Updating {0} to version {1}", type, version);
cmd.ExecuteNonQuery();
}
cmd.Dispose();
}
// private SortedList<int, string> GetAllMigrations()

View File

@ -139,10 +139,10 @@ namespace OpenSim.Data.MySQL
{
_dbConnection.CheckConnection();
using (MySqlCommand cmd = new MySqlCommand(
MySqlCommand cmd =
new MySqlCommand(
"SELECT name, description, assetType, local, temporary, data FROM assets WHERE id=?id",
_dbConnection.Connection))
{
_dbConnection.Connection);
cmd.Parameters.AddWithValue("?id", assetID.ToString());
try
@ -151,10 +151,9 @@ namespace OpenSim.Data.MySQL
{
if (dbReader.Read())
{
asset = new AssetBase();
asset.Data = (byte[])dbReader["data"];
asset.Description = (string)dbReader["description"];
asset.FullID = assetID;
asset = new AssetBase(assetID, (string)dbReader["name"], (sbyte)dbReader["assetType"]);
asset.Data = (byte[]) dbReader["data"];
asset.Description = (string) dbReader["description"];
string local = dbReader["local"].ToString();
if (local.Equals("1") || local.Equals("true", StringComparison.InvariantCultureIgnoreCase))
@ -162,11 +161,13 @@ namespace OpenSim.Data.MySQL
else
asset.Local = false;
asset.Name = (string)dbReader["name"];
asset.Type = (sbyte)dbReader["assetType"];
asset.Temporary = Convert.ToBoolean(dbReader["temporary"]);
}
dbReader.Close();
cmd.Dispose();
}
if (asset != null)
UpdateAccessTime(asset);
}
catch (Exception e)
{
@ -176,7 +177,6 @@ namespace OpenSim.Data.MySQL
_dbConnection.Reconnect();
}
}
}
return asset;
}
@ -291,10 +291,11 @@ namespace OpenSim.Data.MySQL
{
_dbConnection.CheckConnection();
using (MySqlCommand cmd = new MySqlCommand(
MySqlCommand cmd =
new MySqlCommand(
"SELECT id FROM assets WHERE id=?id",
_dbConnection.Connection))
{
_dbConnection.Connection);
cmd.Parameters.AddWithValue("?id", uuid.ToString());
try
@ -302,8 +303,13 @@ namespace OpenSim.Data.MySQL
using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if (dbReader.Read())
{
assetExists = true;
}
dbReader.Close();
cmd.Dispose();
}
}
catch (Exception e)
{
@ -313,7 +319,6 @@ namespace OpenSim.Data.MySQL
_dbConnection.Reconnect();
}
}
}
return assetExists;
}

View File

@ -55,7 +55,9 @@ namespace OpenSim.Data.MySQL
AuthenticationData ret = new AuthenticationData();
ret.Data = new Dictionary<string, object>();
MySqlCommand cmd = new MySqlCommand("select * from `" + m_Realm + "` where UUID = ?principalID");
MySqlCommand cmd = new MySqlCommand(
"select * from `"+m_Realm+"` where UUID = ?principalID"
);
cmd.Parameters.AddWithValue("?principalID", principalID.ToString());
@ -82,15 +84,17 @@ namespace OpenSim.Data.MySQL
ret.Data[s] = result[s].ToString();
}
CloseDBConnection(result, cmd);
result.Close();
CloseReaderCommand(cmd);
return ret;
}
else
{
CloseDBConnection(result, cmd);
result.Close();
CloseReaderCommand(cmd);
return null;
}
}
public bool Store(AuthenticationData data)
{

View File

@ -95,9 +95,11 @@ namespace OpenSim.Data.MySQL
protected void GetWaitTimeout()
{
using (MySqlCommand cmd = new MySqlCommand(m_waitTimeoutSelect, m_connection))
{
using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
MySqlCommand cmd = new MySqlCommand(m_waitTimeoutSelect,
m_connection);
using (MySqlDataReader dbReader =
cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if (dbReader.Read())
{
@ -105,7 +107,9 @@ namespace OpenSim.Data.MySQL
= Convert.ToInt32(dbReader["@@wait_timeout"]) *
TimeSpan.TicksPerSecond + m_waitTimeoutLeeway;
}
}
dbReader.Close();
cmd.Dispose();
}
m_lastConnectionUse = DateTime.Now.Ticks;
@ -143,19 +147,15 @@ namespace OpenSim.Data.MySQL
CheckConnection();
bool migration = true;
MySqlCommand cmd = m_connection.CreateCommand();
using (MySqlCommand cmd = m_connection.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("?RegionID", regionID.ToString());
using (IDataReader r = cmd.ExecuteReader())
{
IDataReader r = cmd.ExecuteReader();
if (r.Read())
{
migration = false;
foreach (string name in FieldList)
{
if (m_FieldMap[name].GetValue(es) is bool)
@ -178,21 +178,20 @@ namespace OpenSim.Data.MySQL
m_FieldMap[name].SetValue(es, r[name]);
}
}
r.Close();
}
}
}
if (migration)
else
{
// Migration case
//
r.Close();
List<string> names = new List<string>(FieldList);
names.Remove("EstateID");
sql = "insert into estate_settings (" + String.Join(",", names.ToArray()) + ") values ( ?" + String.Join(", ?", names.ToArray()) + ")";
using (MySqlCommand cmd = m_connection.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.Clear();
@ -216,31 +215,43 @@ namespace OpenSim.Data.MySQL
cmd.CommandText = "select LAST_INSERT_ID() as id";
cmd.Parameters.Clear();
using (IDataReader r = cmd.ExecuteReader())
{
r = cmd.ExecuteReader();
r.Read();
es.EstateID = Convert.ToUInt32(r["id"]);
}
r.Close();
cmd.CommandText = "insert into estate_map values (?RegionID, ?EstateID)";
cmd.Parameters.AddWithValue("?RegionID", regionID.ToString());
cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString());
// This will throw on dupe key
try { cmd.ExecuteNonQuery(); }
catch (Exception) { }
try
{
cmd.ExecuteNonQuery();
}
catch (Exception)
{
}
// Munge and transfer the ban list
//
cmd.Parameters.Clear();
cmd.CommandText = "insert into estateban select " + es.EstateID.ToString() + ", bannedUUID, bannedIp, bannedIpHostMask, '' from regionban where regionban.regionUUID = ?UUID";
cmd.Parameters.AddWithValue("?UUID", regionID.ToString());
try { cmd.ExecuteNonQuery(); }
catch (Exception) { }
try
{
cmd.ExecuteNonQuery();
}
catch (Exception)
{
}
es.Save();
}
}
LoadBanList(es);
@ -256,8 +267,8 @@ namespace OpenSim.Data.MySQL
CheckConnection();
using (MySqlCommand cmd = m_connection.CreateCommand())
{
MySqlCommand cmd = m_connection.CreateCommand();
cmd.CommandText = sql;
foreach (string name in FieldList)
@ -276,7 +287,6 @@ namespace OpenSim.Data.MySQL
}
cmd.ExecuteNonQuery();
}
SaveBanList(es);
SaveUUIDList(es.EstateID, "estate_managers", es.EstateManagers);
@ -290,13 +300,13 @@ namespace OpenSim.Data.MySQL
CheckConnection();
using (MySqlCommand cmd = m_connection.CreateCommand())
{
MySqlCommand cmd = m_connection.CreateCommand();
cmd.CommandText = "select bannedUUID from estateban where EstateID = ?EstateID";
cmd.Parameters.AddWithValue("?EstateID", es.EstateID);
using (IDataReader r = cmd.ExecuteReader())
{
IDataReader r = cmd.ExecuteReader();
while (r.Read())
{
EstateBan eb = new EstateBan();
@ -309,16 +319,15 @@ namespace OpenSim.Data.MySQL
eb.BannedHostIPMask = "0.0.0.0";
es.AddBan(eb);
}
}
}
r.Close();
}
private void SaveBanList(EstateSettings es)
{
CheckConnection();
using (MySqlCommand cmd = m_connection.CreateCommand())
{
MySqlCommand cmd = m_connection.CreateCommand();
cmd.CommandText = "delete from estateban where EstateID = ?EstateID";
cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString());
@ -337,14 +346,13 @@ namespace OpenSim.Data.MySQL
cmd.Parameters.Clear();
}
}
}
void SaveUUIDList(uint EstateID, string table, UUID[] data)
{
CheckConnection();
using (MySqlCommand cmd = m_connection.CreateCommand())
{
MySqlCommand cmd = m_connection.CreateCommand();
cmd.CommandText = "delete from " + table + " where EstateID = ?EstateID";
cmd.Parameters.AddWithValue("?EstateID", EstateID.ToString());
@ -363,7 +371,6 @@ namespace OpenSim.Data.MySQL
cmd.Parameters.Clear();
}
}
}
UUID[] LoadUUIDList(uint EstateID, string table)
{
@ -371,13 +378,13 @@ namespace OpenSim.Data.MySQL
CheckConnection();
using (MySqlCommand cmd = m_connection.CreateCommand())
{
MySqlCommand cmd = m_connection.CreateCommand();
cmd.CommandText = "select uuid from " + table + " where EstateID = ?EstateID";
cmd.Parameters.AddWithValue("?EstateID", EstateID);
using (IDataReader r = cmd.ExecuteReader())
{
IDataReader r = cmd.ExecuteReader();
while (r.Read())
{
// EstateBan eb = new EstateBan();
@ -387,8 +394,7 @@ namespace OpenSim.Data.MySQL
uuids.Add(uuid);
}
}
}
r.Close();
return uuids.ToArray();
}

View File

@ -40,10 +40,6 @@ namespace OpenSim.Data.MySQL
/// </summary>
public class MySqlFramework
{
private static readonly log4net.ILog m_log =
log4net.LogManager.GetLogger(
System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
protected MySqlConnection m_Connection;
protected MySqlFramework(string connectionString)
@ -73,11 +69,11 @@ namespace OpenSim.Data.MySQL
}
catch (MySqlException e)
{
m_log.Error(e.Message, e);
if (errorSeen)
throw;
// This is "Server has gone away" and "Server lost"
//
if (e.Number == 2006 || e.Number == 2013)
{
errorSeen = true;
@ -96,7 +92,6 @@ namespace OpenSim.Data.MySQL
}
catch (Exception e)
{
m_log.Error(e.Message, e);
return 0;
}
}
@ -113,11 +108,11 @@ namespace OpenSim.Data.MySQL
return cmd.ExecuteReader();
}
protected void CloseDBConnection(IDataReader reader, MySqlCommand cmd)
protected void CloseReaderCommand(MySqlCommand cmd)
{
reader.Close();
cmd.Connection.Close();
cmd.Connection.Dispose();
cmd.Dispose();
}
}
}

View File

@ -0,0 +1,200 @@
/*
* 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 MySql.Data.MySqlClient;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Data.MySQL
{
public class MySQLGenericTableHandler<T> : MySqlFramework where T: struct
{
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;
public MySQLGenericTableHandler(string connectionString,
string realm, string storeName) : base(connectionString)
{
m_Realm = realm;
if (storeName != String.Empty)
{
Assembly assem = GetType().Assembly;
Migration m = new Migration(m_Connection, assem, storeName);
m.Update();
}
Type t = typeof(T);
FieldInfo[] fields = t.GetFields(BindingFlags.NonPublic |
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>();
MySqlCommand cmd = new MySqlCommand();
for (int i = 0 ; i < fields.Length ; i++)
{
cmd.Parameters.AddWithValue(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(MySqlCommand cmd)
{
IDataReader reader = ExecuteReader(cmd);
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
{
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();
m_DataField.SetValue(row, data);
}
result.Add(row);
}
CloseReaderCommand(cmd);
return result.ToArray();
}
public T[] Get(string where)
{
MySqlCommand cmd = new MySqlCommand();
string query = String.Format("select * from {0} where {1}",
m_Realm, where);
cmd.CommandText = query;
return DoQuery(cmd);
}
public void Store(T row)
{
MySqlCommand cmd = new MySqlCommand();
string query = "";
}
}
}

View File

@ -197,27 +197,29 @@ namespace OpenSim.Data.MySQL
param["?xmax"] = xmax.ToString();
param["?ymax"] = ymax.ToString();
using (IDbCommand result = dbm.Manager.Query(
IDbCommand result =
dbm.Manager.Query(
"SELECT * FROM regions WHERE locX >= ?xmin AND locX <= ?xmax AND locY >= ?ymin AND locY <= ?ymax",
param))
{
using (IDataReader reader = result.ExecuteReader())
{
param);
IDataReader reader = result.ExecuteReader();
RegionProfileData row;
List<RegionProfileData> rows = new List<RegionProfileData>();
while ((row = dbm.Manager.readSimRow(reader)) != null)
{
rows.Add(row);
}
reader.Close();
result.Dispose();
return rows.ToArray();
}
}
}
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
return null;
}
finally
@ -241,27 +243,29 @@ namespace OpenSim.Data.MySQL
Dictionary<string, object> param = new Dictionary<string, object>();
param["?name"] = namePrefix + "%";
using (IDbCommand result = dbm.Manager.Query(
IDbCommand result =
dbm.Manager.Query(
"SELECT * FROM regions WHERE regionName LIKE ?name",
param))
{
using (IDataReader reader = result.ExecuteReader())
{
param);
IDataReader reader = result.ExecuteReader();
RegionProfileData row;
List<RegionProfileData> rows = new List<RegionProfileData>();
while (rows.Count < maxNum && (row = dbm.Manager.readSimRow(reader)) != null)
{
rows.Add(row);
}
reader.Close();
result.Dispose();
return rows;
}
}
}
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
return null;
}
finally
@ -284,19 +288,19 @@ namespace OpenSim.Data.MySQL
Dictionary<string, object> param = new Dictionary<string, object>();
param["?handle"] = handle.ToString();
using (IDbCommand result = dbm.Manager.Query("SELECT * FROM regions WHERE regionHandle = ?handle", param))
{
using (IDataReader reader = result.ExecuteReader())
{
IDbCommand result = dbm.Manager.Query("SELECT * FROM regions WHERE regionHandle = ?handle", param);
IDataReader reader = result.ExecuteReader();
RegionProfileData row = dbm.Manager.readSimRow(reader);
reader.Close();
result.Dispose();
return row;
}
}
}
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
return null;
}
finally
@ -319,22 +323,21 @@ namespace OpenSim.Data.MySQL
Dictionary<string, object> param = new Dictionary<string, object>();
param["?uuid"] = uuid.ToString();
using (IDbCommand result = dbm.Manager.Query("SELECT * FROM regions WHERE uuid = ?uuid", param))
{
using (IDataReader reader = result.ExecuteReader())
{
IDbCommand result = dbm.Manager.Query("SELECT * FROM regions WHERE uuid = ?uuid", param);
IDataReader reader = result.ExecuteReader();
RegionProfileData row = dbm.Manager.readSimRow(reader);
reader.Close();
result.Dispose();
return row;
}
}
}
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
return null;
}
finally
} finally
{
dbm.Release();
}
@ -356,21 +359,22 @@ namespace OpenSim.Data.MySQL
// Add % because this is a like query.
param["?regionName"] = regionName + "%";
// Order by statement will return shorter matches first. Only returns one record or no record.
using (IDbCommand result = dbm.Manager.Query(
IDbCommand result =
dbm.Manager.Query(
"SELECT * FROM regions WHERE regionName like ?regionName order by LENGTH(regionName) asc LIMIT 1",
param))
{
using (IDataReader reader = result.ExecuteReader())
{
param);
IDataReader reader = result.ExecuteReader();
RegionProfileData row = dbm.Manager.readSimRow(reader);
reader.Close();
result.Dispose();
return row;
}
}
}
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
return null;
}
finally
@ -378,7 +382,6 @@ namespace OpenSim.Data.MySQL
dbm.Release();
}
}
m_log.Error("[GRID DB]: Searched for a Region Name shorter then 3 characters");
return null;
}
@ -391,11 +394,11 @@ namespace OpenSim.Data.MySQL
override public DataResponse StoreProfile(RegionProfileData profile)
{
MySQLSuperManager dbm = GetLockedConnection();
try
{
try {
if (dbm.Manager.insertRegion(profile))
{
return DataResponse.RESPONSE_OK;
else
}
return DataResponse.RESPONSE_ERROR;
}
finally
@ -414,14 +417,14 @@ namespace OpenSim.Data.MySQL
{
MySQLSuperManager dbm = GetLockedConnection();
try
{
try {
if (dbm.Manager.deleteRegion(uuid))
{
return DataResponse.RESPONSE_OK;
else
return DataResponse.RESPONSE_ERROR;
}
finally
return DataResponse.RESPONSE_ERROR;
} finally
{
dbm.Release();
}
@ -481,24 +484,24 @@ namespace OpenSim.Data.MySQL
Dictionary<string, object> param = new Dictionary<string, object>();
param["?x"] = x.ToString();
param["?y"] = y.ToString();
using (IDbCommand result = dbm.Manager.Query(
IDbCommand result =
dbm.Manager.Query(
"SELECT * FROM reservations WHERE resXMin <= ?x AND resXMax >= ?x AND resYMin <= ?y AND resYMax >= ?y",
param))
{
using (IDataReader reader = result.ExecuteReader())
{
param);
IDataReader reader = result.ExecuteReader();
ReservationData row = dbm.Manager.readReservationRow(reader);
reader.Close();
result.Dispose();
return row;
}
}
}
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
return null;
}
finally
} finally
{
dbm.Release();
}

View File

@ -135,13 +135,12 @@ namespace OpenSim.Data.MySQL
database.CheckConnection();
using (MySqlCommand result = new MySqlCommand("SELECT * FROM inventoryitems WHERE parentFolderID = ?uuid",
database.Connection))
{
MySqlCommand result =
new MySqlCommand("SELECT * FROM inventoryitems WHERE parentFolderID = ?uuid",
database.Connection);
result.Parameters.AddWithValue("?uuid", folderID.ToString());
MySqlDataReader reader = result.ExecuteReader();
using (MySqlDataReader reader = result.ExecuteReader())
{
while (reader.Read())
{
// A null item (because something went wrong) breaks everything in the folder
@ -150,15 +149,16 @@ namespace OpenSim.Data.MySQL
items.Add(item);
}
reader.Close();
result.Dispose();
return items;
}
}
}
}
catch (Exception e)
{
database.Reconnect();
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
return null;
}
}
@ -176,28 +176,29 @@ namespace OpenSim.Data.MySQL
{
database.CheckConnection();
using (MySqlCommand result = new MySqlCommand(
MySqlCommand result =
new MySqlCommand(
"SELECT * FROM inventoryfolders WHERE parentFolderID = ?zero AND agentID = ?uuid",
database.Connection))
{
database.Connection);
result.Parameters.AddWithValue("?uuid", user.ToString());
result.Parameters.AddWithValue("?zero", UUID.Zero.ToString());
MySqlDataReader reader = result.ExecuteReader();
using (MySqlDataReader reader = result.ExecuteReader())
{
List<InventoryFolderBase> items = new List<InventoryFolderBase>();
while (reader.Read())
items.Add(readInventoryFolder(reader));
reader.Close();
result.Dispose();
return items;
}
}
}
}
catch (Exception e)
{
database.Reconnect();
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
return null;
}
}
@ -216,15 +217,15 @@ namespace OpenSim.Data.MySQL
{
database.CheckConnection();
using (MySqlCommand result = new MySqlCommand(
MySqlCommand result =
new MySqlCommand(
"SELECT * FROM inventoryfolders WHERE parentFolderID = ?zero AND agentID = ?uuid",
database.Connection))
{
database.Connection);
result.Parameters.AddWithValue("?uuid", user.ToString());
result.Parameters.AddWithValue("?zero", UUID.Zero.ToString());
using (MySqlDataReader reader = result.ExecuteReader())
{
MySqlDataReader reader = result.ExecuteReader();
List<InventoryFolderBase> items = new List<InventoryFolderBase>();
while (reader.Read())
items.Add(readInventoryFolder(reader));
@ -237,17 +238,20 @@ namespace OpenSim.Data.MySQL
// to put such a message out, and it's too minor right now to spare the time to
// suitably refactor.
if (items.Count > 0)
{
rootFolder = items[0];
}
reader.Close();
result.Dispose();
return rootFolder;
}
}
}
}
catch (Exception e)
{
database.Reconnect();
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
return null;
}
}
@ -267,26 +271,27 @@ namespace OpenSim.Data.MySQL
{
database.CheckConnection();
using (MySqlCommand result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE parentFolderID = ?uuid",
database.Connection))
{
MySqlCommand result =
new MySqlCommand("SELECT * FROM inventoryfolders WHERE parentFolderID = ?uuid",
database.Connection);
result.Parameters.AddWithValue("?uuid", parentID.ToString());
using (MySqlDataReader reader = result.ExecuteReader())
{
MySqlDataReader reader = result.ExecuteReader();
List<InventoryFolderBase> items = new List<InventoryFolderBase>();
while (reader.Read())
items.Add(readInventoryFolder(reader));
reader.Close();
result.Dispose();
return items;
}
}
}
}
catch (Exception e)
{
database.Reconnect();
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
return null;
}
}
@ -365,25 +370,25 @@ namespace OpenSim.Data.MySQL
{
database.CheckConnection();
using (MySqlCommand result = new MySqlCommand("SELECT * FROM inventoryitems WHERE inventoryID = ?uuid", database.Connection))
{
MySqlCommand result =
new MySqlCommand("SELECT * FROM inventoryitems WHERE inventoryID = ?uuid", database.Connection);
result.Parameters.AddWithValue("?uuid", itemID.ToString());
MySqlDataReader reader = result.ExecuteReader();
using (MySqlDataReader reader = result.ExecuteReader())
{
InventoryItemBase item = null;
if (reader.Read())
item = readInventoryItem(reader);
reader.Close();
result.Dispose();
return item;
}
}
}
}
catch (Exception e)
{
database.Reconnect();
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
}
return null;
}
@ -408,7 +413,7 @@ namespace OpenSim.Data.MySQL
}
catch (Exception e)
{
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
}
return null;
@ -428,25 +433,24 @@ namespace OpenSim.Data.MySQL
{
database.CheckConnection();
using (MySqlCommand result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE folderID = ?uuid", database.Connection))
{
MySqlCommand result =
new MySqlCommand("SELECT * FROM inventoryfolders WHERE folderID = ?uuid", database.Connection);
result.Parameters.AddWithValue("?uuid", folderID.ToString());
MySqlDataReader reader = result.ExecuteReader();
using (MySqlDataReader reader = result.ExecuteReader())
{
InventoryFolderBase folder = null;
if (reader.Read())
folder = readInventoryFolder(reader);
reader.Close();
result.Dispose();
return folder;
}
}
}
}
catch (Exception e)
{
database.Reconnect();
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
return null;
}
}
@ -694,58 +698,54 @@ namespace OpenSim.Data.MySQL
try
{
List<InventoryFolderBase> folders = new List<InventoryFolderBase>();
Dictionary<UUID, List<InventoryFolderBase>> hashtable = new Dictionary<UUID, List<InventoryFolderBase>>(); ;
Dictionary<UUID, List<InventoryFolderBase>> hashtable
= new Dictionary<UUID, List<InventoryFolderBase>>(); ;
List<InventoryFolderBase> parentFolder = new List<InventoryFolderBase>();
bool buildResultsFromHashTable = false;
lock (database)
{
MySqlCommand result;
MySqlDataReader reader;
bool buildResultsFromHashTable = false;
database.CheckConnection();
/* Fetch the parent folder from the database to determine the agent ID, and if
* we're querying the root of the inventory folder tree */
using (MySqlCommand result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE folderID = ?uuid", database.Connection))
{
result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE folderID = ?uuid",
database.Connection);
result.Parameters.AddWithValue("?uuid", parentID.ToString());
using (MySqlDataReader reader = result.ExecuteReader())
{
// Should be at most 1 result
while (reader.Read())
reader = result.ExecuteReader();
while (reader.Read()) // Should be at most 1 result
parentFolder.Add(readInventoryFolder(reader));
}
}
reader.Close();
result.Dispose();
if (parentFolder.Count >= 1) // No result means parent folder does not exist
{
if (parentFolder[0].ParentID == UUID.Zero) // We are querying the root folder
{
/* Get all of the agent's folders from the database, put them in a list and return it */
using (MySqlCommand result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE agentID = ?uuid", database.Connection))
{
result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE agentID = ?uuid",
database.Connection);
result.Parameters.AddWithValue("?uuid", parentFolder[0].Owner.ToString());
using (MySqlDataReader reader = result.ExecuteReader())
{
reader = result.ExecuteReader();
while (reader.Read())
{
InventoryFolderBase curFolder = readInventoryFolder(reader);
if (curFolder.ID != parentID) // Do not need to add the root node of the tree to the list
folders.Add(curFolder);
}
}
}
reader.Close();
result.Dispose();
} // if we are querying the root folder
else // else we are querying a subtree of the inventory folder tree
{
/* Get all of the agent's folders from the database, put them all in a hash table
* indexed by their parent ID */
using (MySqlCommand result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE agentID = ?uuid", database.Connection))
{
result = new MySqlCommand("SELECT * FROM inventoryfolders WHERE agentID = ?uuid",
database.Connection);
result.Parameters.AddWithValue("?uuid", parentFolder[0].Owner.ToString());
using (MySqlDataReader reader = result.ExecuteReader())
{
reader = result.ExecuteReader();
while (reader.Read())
{
InventoryFolderBase curFolder = readInventoryFolder(reader);
@ -759,8 +759,8 @@ namespace OpenSim.Data.MySQL
hashtable.Add(curFolder.ParentID, siblingList);
}
} // while more items to read from the database
}
}
reader.Close();
result.Dispose();
// Set flag so we know we need to build the results from the hash table after
// we unlock the database
@ -781,13 +781,12 @@ namespace OpenSim.Data.MySQL
folders.AddRange(hashtable[folders[i].ID]);
}
} // lock (database)
return folders;
}
catch (Exception e)
{
database.Reconnect();
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
return null;
}
}
@ -802,18 +801,19 @@ namespace OpenSim.Data.MySQL
{
database.CheckConnection();
using (MySqlCommand cmd = new MySqlCommand("DELETE FROM inventoryfolders WHERE folderID=?uuid", database.Connection))
{
MySqlCommand cmd =
new MySqlCommand("DELETE FROM inventoryfolders WHERE folderID=?uuid", database.Connection);
cmd.Parameters.AddWithValue("?uuid", folderID.ToString());
lock (database)
{
cmd.ExecuteNonQuery();
}
}
catch (MySqlException e)
{
database.Reconnect();
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
}
}
@ -827,11 +827,12 @@ namespace OpenSim.Data.MySQL
{
database.CheckConnection();
using (MySqlCommand cmd = new MySqlCommand("DELETE FROM inventoryitems WHERE parentFolderID=?uuid", database.Connection))
{
MySqlCommand cmd =
new MySqlCommand("DELETE FROM inventoryitems WHERE parentFolderID=?uuid", database.Connection);
cmd.Parameters.AddWithValue("?uuid", folderID.ToString());
lock (database)
{
cmd.ExecuteNonQuery();
}
}
@ -864,21 +865,20 @@ namespace OpenSim.Data.MySQL
public List<InventoryItemBase> fetchActiveGestures(UUID avatarID)
{
MySqlDataReader result = null;
MySqlCommand sqlCmd = null;
lock (database)
{
try
{
database.CheckConnection();
using (MySqlCommand sqlCmd = new MySqlCommand(
sqlCmd = new MySqlCommand(
"SELECT * FROM inventoryitems WHERE avatarId = ?uuid AND assetType = ?type and flags = 1",
database.Connection))
{
database.Connection);
sqlCmd.Parameters.AddWithValue("?uuid", avatarID.ToString());
sqlCmd.Parameters.AddWithValue("?type", (int)AssetType.Gesture);
result = sqlCmd.ExecuteReader();
using (MySqlDataReader result = sqlCmd.ExecuteReader())
{
List<InventoryItemBase> list = new List<InventoryItemBase>();
while (result.Read())
{
@ -888,14 +888,17 @@ namespace OpenSim.Data.MySQL
}
return list;
}
}
}
catch (Exception e)
{
database.Reconnect();
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
return null;
}
finally
{
if (result != null) result.Close();
if (sqlCmd != null) sqlCmd.Dispose();
}
}
}
}

View File

@ -908,7 +908,7 @@ namespace OpenSim.Data.MySQL
if (!(row["ParticleSystem"] is DBNull))
prim.ParticleSystem = (byte[])row["ParticleSystem"];
prim.RotationalVelocity = new Vector3(
prim.AngularVelocity = new Vector3(
(float)(double)row["OmegaX"],
(float)(double)row["OmegaY"],
(float)(double)row["OmegaZ"]
@ -1240,9 +1240,9 @@ namespace OpenSim.Data.MySQL
cmd.Parameters.AddWithValue("TextureAnimation", prim.TextureAnimation);
cmd.Parameters.AddWithValue("ParticleSystem", prim.ParticleSystem);
cmd.Parameters.AddWithValue("OmegaX", (double)prim.RotationalVelocity.X);
cmd.Parameters.AddWithValue("OmegaY", (double)prim.RotationalVelocity.Y);
cmd.Parameters.AddWithValue("OmegaZ", (double)prim.RotationalVelocity.Z);
cmd.Parameters.AddWithValue("OmegaX", (double)prim.AngularVelocity.X);
cmd.Parameters.AddWithValue("OmegaY", (double)prim.AngularVelocity.Y);
cmd.Parameters.AddWithValue("OmegaZ", (double)prim.AngularVelocity.Z);
cmd.Parameters.AddWithValue("CameraEyeOffsetX", (double)prim.GetCameraEyeOffset().X);
cmd.Parameters.AddWithValue("CameraEyeOffsetY", (double)prim.GetCameraEyeOffset().Y);

View File

@ -134,8 +134,8 @@ namespace OpenSim.Data.MySQL
/// </summary>
protected void GetWaitTimeout()
{
using (MySqlCommand cmd = new MySqlCommand(m_waitTimeoutSelect, dbcon))
{
MySqlCommand cmd = new MySqlCommand(m_waitTimeoutSelect, dbcon);
using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if (dbReader.Read())
@ -143,7 +143,9 @@ namespace OpenSim.Data.MySQL
m_waitTimeout
= Convert.ToInt32(dbReader["@@wait_timeout"]) * TimeSpan.TicksPerSecond + m_waitTimeoutLeeway;
}
}
dbReader.Close();
cmd.Dispose();
}
m_lastConnectionUse = DateTime.Now.Ticks;
@ -301,10 +303,10 @@ namespace OpenSim.Data.MySQL
{
CheckConnection();
using (MySqlCommand tablesCmd = new MySqlCommand(
MySqlCommand tablesCmd =
new MySqlCommand(
"SELECT TABLE_NAME, TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=?dbname",
dbcon))
{
dbcon);
tablesCmd.Parameters.AddWithValue("?dbname", dbcon.Database);
using (MySqlDataReader tables = tablesCmd.ExecuteReader())
@ -313,8 +315,8 @@ namespace OpenSim.Data.MySQL
{
try
{
string tableName = (string)tables["TABLE_NAME"];
string comment = (string)tables["TABLE_COMMENT"];
string tableName = (string) tables["TABLE_NAME"];
string comment = (string) tables["TABLE_COMMENT"];
if (tableList.ContainsKey(tableName))
{
tableList[tableName] = comment;
@ -322,10 +324,10 @@ namespace OpenSim.Data.MySQL
}
catch (Exception e)
{
m_log.Error(e.Message, e);
}
m_log.Error(e.ToString());
}
}
tables.Close();
}
}
}
@ -344,19 +346,19 @@ namespace OpenSim.Data.MySQL
{
CheckConnection(); // Not sure if this one is necessary
MySqlCommand dbcommand = (MySqlCommand)dbcon.CreateCommand();
MySqlCommand dbcommand = (MySqlCommand) dbcon.CreateCommand();
dbcommand.CommandText = sql;
foreach (KeyValuePair<string, object> param in parameters)
{
dbcommand.Parameters.AddWithValue(param.Key, param.Value);
}
return (IDbCommand)dbcommand;
return (IDbCommand) dbcommand;
}
catch (Exception e)
{
// Return null if it fails.
m_log.Error("Failed during Query generation: " + e.Message, e);
m_log.Error("Failed during Query generation: " + e.ToString());
return null;
}
}
@ -692,6 +694,8 @@ namespace OpenSim.Data.MySQL
ret.Add(attachpoint, item);
}
r.Close();
return ret;
}

View File

@ -56,14 +56,13 @@ namespace OpenSim.Data.MySQL
if (scopeID != UUID.Zero)
command += " and ScopeID = ?scopeID";
using (MySqlCommand cmd = new MySqlCommand(command))
{
MySqlCommand cmd = new MySqlCommand(command);
cmd.Parameters.AddWithValue("?regionName", regionName);
cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
return RunCommand(cmd);
}
}
public RegionData Get(int posX, int posY, UUID scopeID)
{
@ -71,8 +70,8 @@ namespace OpenSim.Data.MySQL
if (scopeID != UUID.Zero)
command += " and ScopeID = ?scopeID";
using (MySqlCommand cmd = new MySqlCommand(command))
{
MySqlCommand cmd = new MySqlCommand(command);
cmd.Parameters.AddWithValue("?posX", posX.ToString());
cmd.Parameters.AddWithValue("?posY", posY.ToString());
cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
@ -83,7 +82,6 @@ namespace OpenSim.Data.MySQL
return ret[0];
}
}
public RegionData Get(UUID regionID, UUID scopeID)
{
@ -91,8 +89,8 @@ namespace OpenSim.Data.MySQL
if (scopeID != UUID.Zero)
command += " and ScopeID = ?scopeID";
using (MySqlCommand cmd = new MySqlCommand(command))
{
MySqlCommand cmd = new MySqlCommand(command);
cmd.Parameters.AddWithValue("?regionID", regionID.ToString());
cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
@ -102,7 +100,6 @@ namespace OpenSim.Data.MySQL
return ret[0];
}
}
public List<RegionData> Get(int startX, int startY, int endX, int endY, UUID scopeID)
{
@ -110,8 +107,8 @@ namespace OpenSim.Data.MySQL
if (scopeID != UUID.Zero)
command += " and ScopeID = ?scopeID";
using (MySqlCommand cmd = new MySqlCommand(command))
{
MySqlCommand cmd = new MySqlCommand(command);
cmd.Parameters.AddWithValue("?startX", startX.ToString());
cmd.Parameters.AddWithValue("?startY", startY.ToString());
cmd.Parameters.AddWithValue("?endX", endX.ToString());
@ -120,14 +117,13 @@ namespace OpenSim.Data.MySQL
return RunCommand(cmd);
}
}
public List<RegionData> RunCommand(MySqlCommand cmd)
{
List<RegionData> retList = new List<RegionData>();
using (IDataReader result = ExecuteReader(cmd))
{
IDataReader result = ExecuteReader(cmd);
while (result.Read())
{
RegionData ret = new RegionData();
@ -176,8 +172,8 @@ namespace OpenSim.Data.MySQL
retList.Add(ret);
}
CloseDBConnection(result, cmd);
}
result.Close();
CloseReaderCommand(cmd);
return retList;
}
@ -205,15 +201,15 @@ namespace OpenSim.Data.MySQL
string[] fields = new List<string>(data.Data.Keys).ToArray();
using (MySqlCommand cmd = new MySqlCommand())
{
string update = "update `" + m_Realm + "` set locX=?posX, locY=?posY, sizeX=?sizeX, sizeY=?sizeY";
MySqlCommand cmd = new MySqlCommand();
string update = "update `"+m_Realm+"` set locX=?posX, locY=?posY, sizeX=?sizeX, sizeY=?sizeY";
foreach (string field in fields)
{
update += ", ";
update += "`" + field + "` = ?" + field;
update += "`" + field + "` = ?"+field;
cmd.Parameters.AddWithValue("?" + field, data.Data[field]);
cmd.Parameters.AddWithValue("?"+field, data.Data[field]);
}
update += " where uuid = ?regionID";
@ -240,37 +236,41 @@ namespace OpenSim.Data.MySQL
if (ExecuteNonQuery(cmd) < 1)
{
cmd.Dispose();
return false;
}
}
}
cmd.Dispose();
return true;
}
public bool SetDataItem(UUID regionID, string item, string value)
{
using (MySqlCommand cmd = new MySqlCommand("update `" + m_Realm + "` set `" + item + "` = ?" + item + " where uuid = ?UUID"))
{
cmd.Parameters.AddWithValue("?" + item, value);
MySqlCommand cmd = new MySqlCommand("update `" + m_Realm +
"` set `" + item + "` = ?" + item + " where uuid = ?UUID");
cmd.Parameters.AddWithValue("?"+item, value);
cmd.Parameters.AddWithValue("?UUID", regionID.ToString());
if (ExecuteNonQuery(cmd) > 0)
return true;
}
return false;
}
public bool Delete(UUID regionID)
{
using (MySqlCommand cmd = new MySqlCommand("delete from `" + m_Realm + "` where uuid = ?UUID"))
{
MySqlCommand cmd = new MySqlCommand("delete from `" + m_Realm +
"` where uuid = ?UUID");
cmd.Parameters.AddWithValue("?UUID", regionID.ToString());
if (ExecuteNonQuery(cmd) > 0)
return true;
}
return false;
}

View File

@ -97,15 +97,17 @@ namespace OpenSim.Data.MySQL
ret.Data[s] = result[s].ToString();
}
CloseDBConnection(result, cmd);
result.Close();
CloseReaderCommand(cmd);
return ret;
}
else
{
CloseDBConnection(result, cmd);
result.Close();
CloseReaderCommand(cmd);
return null;
}
}
public bool Store(UserAccountData data)
{
@ -116,19 +118,19 @@ namespace OpenSim.Data.MySQL
string[] fields = new List<string>(data.Data.Keys).ToArray();
using (MySqlCommand cmd = new MySqlCommand())
{
string update = "update `" + m_Realm + "` set ";
MySqlCommand cmd = new MySqlCommand();
string update = "update `"+m_Realm+"` set ";
bool first = true;
foreach (string field in fields)
{
if (!first)
update += ", ";
update += "`" + field + "` = ?" + field;
update += "`" + field + "` = ?"+field;
first = false;
cmd.Parameters.AddWithValue("?" + field, data.Data[field]);
cmd.Parameters.AddWithValue("?"+field, data.Data[field]);
}
update += " where UUID = ?principalID";
@ -154,22 +156,23 @@ namespace OpenSim.Data.MySQL
return false;
}
}
}
cmd.Dispose();
return true;
}
public bool SetDataItem(UUID principalID, string item, string value)
{
using (MySqlCommand cmd = new MySqlCommand("update `" + m_Realm + "` set `" +
item + "` = ?" + item + " where UUID = ?UUID"))
{
cmd.Parameters.AddWithValue("?" + item, value);
MySqlCommand cmd = new MySqlCommand("update `" + m_Realm +
"` set `" + item + "` = ?" + item + " where UUID = ?UUID");
cmd.Parameters.AddWithValue("?"+item, value);
cmd.Parameters.AddWithValue("?UUID", principalID.ToString());
if (ExecuteNonQuery(cmd) > 0)
return true;
}
return false;
}

View File

@ -181,20 +181,21 @@ namespace OpenSim.Data.MySQL
param["?first"] = user;
param["?second"] = last;
using (IDbCommand result = dbm.Manager.Query(
"SELECT * FROM " + m_usersTableName + " WHERE username = ?first AND lastname = ?second", param))
{
using (IDataReader reader = result.ExecuteReader())
{
IDbCommand result =
dbm.Manager.Query(
"SELECT * FROM " + m_usersTableName + " WHERE username = ?first AND lastname = ?second", param);
IDataReader reader = result.ExecuteReader();
UserProfileData row = dbm.Manager.readUserRow(reader);
reader.Dispose();
result.Dispose();
return row;
}
}
}
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
return null;
}
finally
@ -219,30 +220,28 @@ namespace OpenSim.Data.MySQL
try
{
using (IDbCommand adder = dbm.Manager.Query(
IDbCommand adder =
dbm.Manager.Query(
"INSERT INTO `" + m_userFriendsTableName + "` " +
"(`ownerID`,`friendID`,`friendPerms`,`datetimestamp`) " +
"VALUES " +
"(?ownerID,?friendID,?friendPerms,?datetimestamp)",
param))
{
param);
adder.ExecuteNonQuery();
}
using (IDbCommand adder = dbm.Manager.Query(
adder =
dbm.Manager.Query(
"INSERT INTO `" + m_userFriendsTableName + "` " +
"(`ownerID`,`friendID`,`friendPerms`,`datetimestamp`) " +
"VALUES " +
"(?friendID,?ownerID,?friendPerms,?datetimestamp)",
param))
{
param);
adder.ExecuteNonQuery();
}
}
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
return;
}
finally
@ -261,24 +260,22 @@ namespace OpenSim.Data.MySQL
try
{
using (IDbCommand updater = dbm.Manager.Query(
IDbCommand updater =
dbm.Manager.Query(
"delete from " + m_userFriendsTableName + " where ownerID = ?ownerID and friendID = ?friendID",
param))
{
param);
updater.ExecuteNonQuery();
}
using (IDbCommand updater = dbm.Manager.Query(
updater =
dbm.Manager.Query(
"delete from " + m_userFriendsTableName + " where ownerID = ?friendID and friendID = ?ownerID",
param))
{
param);
updater.ExecuteNonQuery();
}
}
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
return;
}
finally
@ -298,19 +295,18 @@ namespace OpenSim.Data.MySQL
try
{
using (IDbCommand updater = dbm.Manager.Query(
IDbCommand updater =
dbm.Manager.Query(
"update " + m_userFriendsTableName +
" SET friendPerms = ?friendPerms " +
"where ownerID = ?ownerID and friendID = ?friendID",
param))
{
param);
updater.ExecuteNonQuery();
}
}
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
return;
}
finally
@ -331,33 +327,34 @@ namespace OpenSim.Data.MySQL
try
{
//Left Join userfriends to itself
using (IDbCommand result = dbm.Manager.Query(
IDbCommand result =
dbm.Manager.Query(
"select a.ownerID,a.friendID,a.friendPerms,b.friendPerms as ownerperms from " +
m_userFriendsTableName + " as a, " + m_userFriendsTableName + " as b" +
" where a.ownerID = ?ownerID and b.ownerID = a.friendID and b.friendID = a.ownerID",
param))
{
using (IDataReader reader = result.ExecuteReader())
{
param);
IDataReader reader = result.ExecuteReader();
while (reader.Read())
{
FriendListItem fli = new FriendListItem();
fli.FriendListOwner = new UUID((string)reader["ownerID"]);
fli.Friend = new UUID((string)reader["friendID"]);
fli.FriendPerms = (uint)Convert.ToInt32(reader["friendPerms"]);
fli.FriendListOwner = new UUID((string) reader["ownerID"]);
fli.Friend = new UUID((string) reader["friendID"]);
fli.FriendPerms = (uint) Convert.ToInt32(reader["friendPerms"]);
// This is not a real column in the database table, it's a joined column from the opposite record
fli.FriendListOwnerPerms = (uint)Convert.ToInt32(reader["ownerperms"]);
fli.FriendListOwnerPerms = (uint) Convert.ToInt32(reader["ownerperms"]);
Lfli.Add(fli);
}
}
}
reader.Dispose();
result.Dispose();
}
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
return Lfli;
}
finally
@ -379,12 +376,11 @@ namespace OpenSim.Data.MySQL
{
Dictionary<string, object> param = new Dictionary<string, object>();
param["?uuid"] = uuid.ToString();
IDbCommand result =
dbm.Manager.Query("select agentOnline,currentHandle from " + m_agentsTableName +
" where UUID = ?uuid", param);
using (IDbCommand result = dbm.Manager.Query("select agentOnline,currentHandle from " + m_agentsTableName +
" where UUID = ?uuid", param))
{
using (IDataReader reader = result.ExecuteReader())
{
IDataReader reader = result.ExecuteReader();
while (reader.Read())
{
FriendRegionInfo fri = new FriendRegionInfo();
@ -393,15 +389,16 @@ namespace OpenSim.Data.MySQL
infos[uuid] = fri;
}
}
}
reader.Dispose();
result.Dispose();
}
}
catch (Exception e)
{
m_log.Warn("[MYSQL]: Got exception on trying to find friends regions:", e);
dbm.Manager.Reconnect();
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
}
finally
{
@ -430,28 +427,28 @@ namespace OpenSim.Data.MySQL
try
{
using (IDbCommand result = dbm.Manager.Query(
IDbCommand result =
dbm.Manager.Query(
"SELECT UUID,username,lastname FROM " + m_usersTableName +
" WHERE username like ?first AND lastname like ?second LIMIT 100",
param))
{
using (IDataReader reader = result.ExecuteReader())
{
param);
IDataReader reader = result.ExecuteReader();
while (reader.Read())
{
AvatarPickerAvatar user = new AvatarPickerAvatar();
user.AvatarID = new UUID((string)reader["UUID"]);
user.firstName = (string)reader["username"];
user.lastName = (string)reader["lastname"];
user.AvatarID = new UUID((string) reader["UUID"]);
user.firstName = (string) reader["username"];
user.lastName = (string) reader["lastname"];
returnlist.Add(user);
}
}
}
reader.Dispose();
result.Dispose();
}
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
return returnlist;
}
finally
@ -468,28 +465,28 @@ namespace OpenSim.Data.MySQL
Dictionary<string, object> param = new Dictionary<string, object>();
param["?first"] = objAlphaNumericPattern.Replace(querysplit[0], String.Empty) + "%";
using (IDbCommand result = dbm.Manager.Query(
IDbCommand result =
dbm.Manager.Query(
"SELECT UUID,username,lastname FROM " + m_usersTableName +
" WHERE username like ?first OR lastname like ?first LIMIT 100",
param))
{
using (IDataReader reader = result.ExecuteReader())
{
param);
IDataReader reader = result.ExecuteReader();
while (reader.Read())
{
AvatarPickerAvatar user = new AvatarPickerAvatar();
user.AvatarID = new UUID((string)reader["UUID"]);
user.firstName = (string)reader["username"];
user.lastName = (string)reader["lastname"];
user.AvatarID = new UUID((string) reader["UUID"]);
user.firstName = (string) reader["username"];
user.lastName = (string) reader["lastname"];
returnlist.Add(user);
}
}
}
reader.Dispose();
result.Dispose();
}
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
return returnlist;
}
finally
@ -513,19 +510,20 @@ namespace OpenSim.Data.MySQL
Dictionary<string, object> param = new Dictionary<string, object>();
param["?uuid"] = uuid.ToString();
using (IDbCommand result = dbm.Manager.Query("SELECT * FROM " + m_usersTableName + " WHERE UUID = ?uuid", param))
{
using (IDataReader reader = result.ExecuteReader())
{
IDbCommand result = dbm.Manager.Query("SELECT * FROM " + m_usersTableName + " WHERE UUID = ?uuid", param);
IDataReader reader = result.ExecuteReader();
UserProfileData row = dbm.Manager.readUserRow(reader);
reader.Dispose();
result.Dispose();
return row;
}
}
}
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
return null;
}
finally
@ -579,7 +577,7 @@ namespace OpenSim.Data.MySQL
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
return;
}
finally
@ -602,19 +600,21 @@ namespace OpenSim.Data.MySQL
Dictionary<string, object> param = new Dictionary<string, object>();
param["?uuid"] = uuid.ToString();
using (IDbCommand result = dbm.Manager.Query("SELECT * FROM " + m_agentsTableName + " WHERE UUID = ?uuid", param))
{
using (IDataReader reader = result.ExecuteReader())
{
IDbCommand result = dbm.Manager.Query("SELECT * FROM " + m_agentsTableName + " WHERE UUID = ?uuid",
param);
IDataReader reader = result.ExecuteReader();
UserAgentData row = dbm.Manager.readAgentRow(reader);
reader.Dispose();
result.Dispose();
return row;
}
}
}
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
return null;
}
finally
@ -638,8 +638,7 @@ namespace OpenSim.Data.MySQL
try
{
dbm.Manager.insertUserRow(
user.ID, user.FirstName, user.SurName, user.Email, user.PasswordHash, user.PasswordSalt,
dbm.Manager.insertUserRow(user.ID, user.FirstName, user.SurName, user.Email, user.PasswordHash, user.PasswordSalt,
user.HomeRegion, user.HomeRegionID, user.HomeLocation.X, user.HomeLocation.Y,
user.HomeLocation.Z,
user.HomeLookAt.X, user.HomeLookAt.Y, user.HomeLookAt.Z, user.Created,
@ -651,7 +650,7 @@ namespace OpenSim.Data.MySQL
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
}
finally
{
@ -677,7 +676,7 @@ namespace OpenSim.Data.MySQL
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
}
finally
{
@ -694,8 +693,7 @@ namespace OpenSim.Data.MySQL
MySQLSuperManager dbm = GetLockedConnection("UpdateUserProfile");
try
{
dbm.Manager.updateUserRow(
user.ID, user.FirstName, user.SurName, user.Email, user.PasswordHash, user.PasswordSalt,
dbm.Manager.updateUserRow(user.ID, user.FirstName, user.SurName, user.Email, user.PasswordHash, user.PasswordSalt,
user.HomeRegion, user.HomeRegionID, user.HomeLocation.X, user.HomeLocation.Y,
user.HomeLocation.Z, user.HomeLookAt.X,
user.HomeLookAt.Y, user.HomeLookAt.Z, user.Created, user.LastLogin,
@ -750,29 +748,29 @@ namespace OpenSim.Data.MySQL
Dictionary<string, object> param = new Dictionary<string, object>();
param["?owner"] = user.ToString();
using (IDbCommand result = dbm.Manager.Query("SELECT * FROM " + m_appearanceTableName + " WHERE owner = ?owner", param))
{
using (IDataReader reader = result.ExecuteReader())
{
IDbCommand result = dbm.Manager.Query(
"SELECT * FROM " + m_appearanceTableName + " WHERE owner = ?owner", param);
IDataReader reader = result.ExecuteReader();
AvatarAppearance appearance = dbm.Manager.readAppearanceRow(reader);
if (appearance == null)
reader.Dispose();
result.Dispose();
if (null == appearance)
{
m_log.WarnFormat("[USER DB] No appearance found for user {0}", user.ToString());
return null;
}
else
{
appearance.SetAttachments(GetUserAttachments(user));
return appearance;
}
}
}
}
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
return null;
}
finally
@ -800,7 +798,7 @@ namespace OpenSim.Data.MySQL
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
}
finally
{
@ -835,20 +833,20 @@ namespace OpenSim.Data.MySQL
try
{
using (IDbCommand result = dbm.Manager.Query(
"SELECT attachpoint, item, asset from " + m_attachmentsTableName + " WHERE UUID = ?uuid", param))
{
using (IDataReader reader = result.ExecuteReader())
{
IDbCommand result = dbm.Manager.Query(
"SELECT attachpoint, item, asset from " + m_attachmentsTableName + " WHERE UUID = ?uuid", param);
IDataReader reader = result.ExecuteReader();
Hashtable ret = dbm.Manager.readAttachments(reader);
reader.Dispose();
result.Dispose();
return ret;
}
}
}
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
return null;
}
finally
@ -907,7 +905,7 @@ namespace OpenSim.Data.MySQL
catch (Exception e)
{
dbm.Manager.Reconnect();
m_log.Error(e.Message, e);
m_log.Error(e.ToString());
return;
}
finally

View File

@ -162,22 +162,22 @@ namespace OpenSim.Data.SQLite
}
}
/// <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>
// /// 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
@ -231,12 +231,13 @@ namespace OpenSim.Data.SQLite
// 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();
AssetBase asset = new AssetBase(
new UUID((String)row["UUID"]),
(String)row["Name"],
Convert.ToSByte(row["Type"])
);
asset.FullID = new UUID((String) row["UUID"]);
asset.Name = (String) row["Name"];
asset.Description = (String) row["Description"];
asset.Type = Convert.ToSByte(row["Type"]);
asset.Local = Convert.ToBoolean(row["Local"]);
asset.Temporary = Convert.ToBoolean(row["Temporary"]);
asset.Data = (byte[]) row["Data"];

View File

@ -1213,7 +1213,7 @@ namespace OpenSim.Data.SQLite
if (!row.IsNull("ParticleSystem"))
prim.ParticleSystem = Convert.FromBase64String(row["ParticleSystem"].ToString());
prim.RotationalVelocity = new Vector3(
prim.AngularVelocity = new Vector3(
Convert.ToSingle(row["OmegaX"]),
Convert.ToSingle(row["OmegaY"]),
Convert.ToSingle(row["OmegaZ"])
@ -1530,9 +1530,9 @@ namespace OpenSim.Data.SQLite
row["TextureAnimation"] = Convert.ToBase64String(prim.TextureAnimation);
row["ParticleSystem"] = Convert.ToBase64String(prim.ParticleSystem);
row["OmegaX"] = prim.RotationalVelocity.X;
row["OmegaY"] = prim.RotationalVelocity.Y;
row["OmegaZ"] = prim.RotationalVelocity.Z;
row["OmegaX"] = prim.AngularVelocity.X;
row["OmegaY"] = prim.AngularVelocity.Y;
row["OmegaZ"] = prim.AngularVelocity.Z;
row["CameraEyeOffsetX"] = prim.GetCameraEyeOffset().X;
row["CameraEyeOffsetY"] = prim.GetCameraEyeOffset().Y;

View File

@ -66,9 +66,9 @@ namespace OpenSim.Data.Tests
[Test]
public void T010_StoreSimpleAsset()
{
AssetBase a1 = new AssetBase(uuid1, "asset one");
AssetBase a2 = new AssetBase(uuid2, "asset two");
AssetBase a3 = new AssetBase(uuid3, "asset three");
AssetBase a1 = new AssetBase(uuid1, "asset one", (sbyte)AssetType.Texture);
AssetBase a2 = new AssetBase(uuid2, "asset two", (sbyte)AssetType.Texture);
AssetBase a3 = new AssetBase(uuid3, "asset three", (sbyte)AssetType.Texture);
a1.Data = asset1;
a2.Data = asset1;
a3.Data = asset1;

View File

@ -252,7 +252,7 @@ namespace OpenSim.Data.Tests
regionInfo.RegionLocX = 0;
regionInfo.RegionLocY = 0;
Scene scene = new Scene(regionInfo);
// Scene scene = new Scene(regionInfo);
SceneObjectPart sop = new SceneObjectPart();
sop.RegionHandle = regionh;

View File

@ -297,8 +297,8 @@ namespace OpenSim.Data.Tests
public void AssetShouldMatch()
{
UUID uuid1 = UUID.Random();
AssetBase actual = new AssetBase(uuid1, "asset one");
AssetBase expected = new AssetBase(uuid1, "asset one");
AssetBase actual = new AssetBase(uuid1, "asset one", (sbyte)AssetType.Texture);
AssetBase expected = new AssetBase(uuid1, "asset one", (sbyte)AssetType.Texture);
var constraint = Constraints.PropertyCompareConstraint(expected);
@ -309,8 +309,8 @@ namespace OpenSim.Data.Tests
public void AssetShouldNotMatch()
{
UUID uuid1 = UUID.Random();
AssetBase actual = new AssetBase(uuid1, "asset one");
AssetBase expected = new AssetBase(UUID.Random(), "asset one");
AssetBase actual = new AssetBase(uuid1, "asset one", (sbyte)AssetType.Texture);
AssetBase expected = new AssetBase(UUID.Random(), "asset one", (sbyte)AssetType.Texture);
var constraint = Constraints.PropertyCompareConstraint(expected);
@ -321,8 +321,8 @@ namespace OpenSim.Data.Tests
public void AssetShouldNotMatch2()
{
UUID uuid1 = UUID.Random();
AssetBase actual = new AssetBase(uuid1, "asset one");
AssetBase expected = new AssetBase(uuid1, "asset two");
AssetBase actual = new AssetBase(uuid1, "asset one", (sbyte)AssetType.Texture);
AssetBase expected = new AssetBase(uuid1, "asset two", (sbyte)AssetType.Texture);
var constraint = Constraints.PropertyCompareConstraint(expected);

View File

@ -165,7 +165,7 @@ namespace OpenSim.Data.Tests
[Test]
public void TestScramble()
{
AssetBase actual = new AssetBase(UUID.Random(), "asset one");
AssetBase actual = new AssetBase(UUID.Random(), "asset one", (sbyte)AssetType.Texture);
new PropertyScrambler<AssetBase>().Scramble(actual);
}
@ -173,8 +173,7 @@ namespace OpenSim.Data.Tests
public void DontScramble()
{
UUID uuid = UUID.Random();
AssetBase asset = new AssetBase();
asset.FullID = uuid;
AssetBase asset = new AssetBase(uuid, "asset", (sbyte)AssetType.Texture);
new PropertyScrambler<AssetBase>()
.DontScramble(x => x.Metadata)
.DontScramble(x => x.FullID)

View File

@ -248,35 +248,5 @@ namespace OpenSim.Framework
#endregion
#region Tests
/// <summary>
/// ACL Test class
/// </summary>
internal class ACLTester
{
public ACLTester()
{
ACL acl = new ACL();
Role Guests = new Role("Guests");
acl.AddRole(Guests);
Role[] parents = new Role[0];
parents[0] = Guests;
Role JoeGuest = new Role("JoeGuest", parents);
acl.AddRole(JoeGuest);
Resource CanBuild = new Resource("CanBuild");
acl.AddResource(CanBuild);
acl.GrantPermission("Guests", "CanBuild");
acl.HasPermission("JoeGuest", "CanBuild");
}
}
#endregion
}

View File

@ -27,6 +27,8 @@
using System;
using System.Xml.Serialization;
using System.Reflection;
using log4net;
using OpenMetaverse;
namespace OpenSim.Framework
@ -37,6 +39,8 @@ namespace OpenSim.Framework
[Serializable]
public class AssetBase
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Data of the Asset
/// </summary>
@ -47,16 +51,44 @@ namespace OpenSim.Framework
/// </summary>
private AssetMetadata m_metadata;
// This is needed for .NET serialization!!!
// Do NOT "Optimize" away!
public AssetBase()
{
m_metadata = new AssetMetadata();
m_metadata.FullID = UUID.Zero;
m_metadata.ID = UUID.Zero.ToString();
m_metadata.Type = (sbyte)AssetType.Unknown;
}
public AssetBase(UUID assetId, string name)
public AssetBase(UUID assetID, string name, sbyte assetType)
{
if (assetType == (sbyte)AssetType.Unknown)
{
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(true);
m_log.ErrorFormat("[ASSETBASE]: Creating asset '{0}' ({1}) with an unknown asset type\n{2}",
name, assetID, trace.ToString());
}
m_metadata = new AssetMetadata();
m_metadata.FullID = assetId;
m_metadata.FullID = assetID;
m_metadata.Name = name;
m_metadata.Type = assetType;
}
public AssetBase(string assetID, string name, sbyte assetType)
{
if (assetType == (sbyte)AssetType.Unknown)
{
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(true);
m_log.ErrorFormat("[ASSETBASE]: Creating asset '{0}' ({1}) with an unknown asset type\n{2}",
name, assetID, trace.ToString());
}
m_metadata = new AssetMetadata();
m_metadata.ID = assetID;
m_metadata.Name = name;
m_metadata.Type = assetType;
}
public bool ContainsReferences
@ -193,11 +225,11 @@ namespace OpenSim.Framework
private string m_name = String.Empty;
private string m_description = String.Empty;
private DateTime m_creation_date;
private sbyte m_type;
private sbyte m_type = (sbyte)AssetType.Unknown;
private string m_content_type;
private byte[] m_sha1;
private bool m_local = false;
private bool m_temporary = false;
private bool m_local;
private bool m_temporary;
//private Dictionary<string, Uri> m_methods = new Dictionary<string, Uri>();
//private OSDMap m_extra_data;
@ -211,7 +243,13 @@ namespace OpenSim.Framework
{
//get { return m_fullid.ToString(); }
//set { m_fullid = new UUID(value); }
get { return m_id; }
get
{
if (String.IsNullOrEmpty(m_id))
m_id = m_fullid.ToString();
return m_id;
}
set
{
UUID uuid = UUID.Zero;

View File

@ -38,11 +38,9 @@ namespace OpenSim.Framework
public int Version;
public AssetLandmark(AssetBase a)
: base(a.FullID, a.Name, a.Type)
{
Data = a.Data;
FullID = a.FullID;
Type = a.Type;
Name = a.Name;
Description = a.Description;
InternData();
}

View File

@ -43,18 +43,15 @@ namespace OpenSim.Framework.AssetLoader.Filesystem
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected static AssetBase CreateAsset(string assetIdStr, string name, string path, bool isImage)
protected static AssetBase CreateAsset(string assetIdStr, string name, string path, sbyte type)
{
AssetBase asset = new AssetBase(
new UUID(assetIdStr),
name
);
AssetBase asset = new AssetBase(new UUID(assetIdStr), name, type);
if (!String.IsNullOrEmpty(path))
{
//m_log.InfoFormat("[ASSETS]: Loading: [{0}][{1}]", name, path);
LoadAsset(asset, isImage, path);
LoadAsset(asset, path);
}
else
{
@ -64,8 +61,14 @@ namespace OpenSim.Framework.AssetLoader.Filesystem
return asset;
}
protected static void LoadAsset(AssetBase info, bool image, string path)
protected static void LoadAsset(AssetBase info, string path)
{
// bool image =
// (info.Type == (sbyte)AssetType.Texture ||
// info.Type == (sbyte)AssetType.TextureTGA ||
// info.Type == (sbyte)AssetType.ImageJPEG ||
// info.Type == (sbyte)AssetType.ImageTGA);
FileInfo fInfo = new FileInfo(path);
long numBytes = fInfo.Length;
if (fInfo.Exists)
@ -138,10 +141,10 @@ namespace OpenSim.Framework.AssetLoader.Filesystem
{
string assetIdStr = source.Configs[i].GetString("assetID", UUID.Random().ToString());
string name = source.Configs[i].GetString("name", String.Empty);
sbyte type = (sbyte) source.Configs[i].GetInt("assetType", 0);
sbyte type = (sbyte)source.Configs[i].GetInt("assetType", 0);
string assetPath = Path.Combine(dir, source.Configs[i].GetString("fileName", String.Empty));
AssetBase newAsset = CreateAsset(assetIdStr, name, assetPath, false);
AssetBase newAsset = CreateAsset(assetIdStr, name, assetPath, type);
newAsset.Type = type;
assets.Add(newAsset);

View File

@ -89,7 +89,7 @@ namespace OpenSim.Framework.Capabilities
//private static readonly string m_requestTexture = "0003/";
private static readonly string m_notecardUpdatePath = "0004/";
private static readonly string m_notecardTaskUpdatePath = "0005/";
private static readonly string m_fetchInventoryPath = "0006/";
// private static readonly string m_fetchInventoryPath = "0006/";
// The following entries are in a module, however, they are also here so that we don't re-assign
// the path to another cap by mistake.
@ -208,7 +208,7 @@ namespace OpenSim.Framework.Capabilities
// As of RC 1.22.9 of the Linden client this is
// supported
m_capsHandlers["WebFetchInventoryDescendents"] =new RestStreamHandler("POST", capsBase + m_fetchInventoryPath, FetchInventoryDescendentsRequest);
//m_capsHandlers["WebFetchInventoryDescendents"] =new RestStreamHandler("POST", capsBase + m_fetchInventoryPath, FetchInventoryDescendentsRequest);
// justincc: I've disabled the CAPS service for now to fix problems with selecting textures, and
// subsequent inventory breakage, in the edit object pane (such as mantis 1085). This requires
@ -888,10 +888,7 @@ namespace OpenSim.Framework.Capabilities
}
AssetBase asset;
asset = new AssetBase();
asset.FullID = assetID;
asset.Type = assType;
asset.Name = assetName;
asset = new AssetBase(assetID, assetName, assType);
asset.Data = data;
if (AddNewAsset != null)
AddNewAsset(asset);

View File

@ -679,7 +679,7 @@ namespace OpenSim.Framework.Communications.Cache
/// <param name="fetchFolders"></param>
/// <param name="fetchItems"></param>
/// <returns>true if the request was queued or successfully processed, false otherwise</returns>
public bool SendInventoryDecendents(IClientAPI client, UUID folderID, bool fetchFolders, bool fetchItems)
public bool SendInventoryDecendents(IClientAPI client, UUID folderID, int version, bool fetchFolders, bool fetchItems)
{
if (m_hasReceivedInventory)
{
@ -693,7 +693,7 @@ namespace OpenSim.Framework.Communications.Cache
client.SendInventoryFolderDetails(
client.AgentId, folderID, folder.RequestListOfItems(),
folder.RequestListOfFolders(), fetchFolders, fetchItems);
folder.RequestListOfFolders(), version, fetchFolders, fetchItems);
return true;
}

View File

@ -93,7 +93,7 @@ namespace OpenSim.Framework.Communications.Osp
if (!ospa.StartsWith(OSPA_PREFIX))
return UUID.Zero;
m_log.DebugFormat("[OSP RESOLVER]: Resolving {0}", ospa);
// m_log.DebugFormat("[OSP RESOLVER]: Resolving {0}", ospa);
string ospaMeat = ospa.Substring(OSPA_PREFIX.Length);
string[] ospaTuples = ospaMeat.Split(OSPA_TUPLE_SEPARATOR_ARRAY);

View File

@ -1031,30 +1031,26 @@ namespace OpenSim.Framework.Communications.Services
return true;
}
// StartLocation not available, send him to a nearby region instead
// regionInfo = m_gridService.RequestClosestRegion("");
//m_log.InfoFormat("[LOGIN]: StartLocation not available sending to region {0}", regionInfo.regionName);
// Get the default region handle
ulong defaultHandle = Utils.UIntsToLong(m_defaultHomeX * Constants.RegionSize, m_defaultHomeY * Constants.RegionSize);
// Send him to default region instead
ulong defaultHandle = (((ulong)m_defaultHomeX * Constants.RegionSize) << 32) |
((ulong)m_defaultHomeY * Constants.RegionSize);
if ((regionInfo != null) && (defaultHandle == regionInfo.RegionHandle))
{
m_log.ErrorFormat("[LOGIN]: Not trying the default region since this is the same as the selected region");
return false;
}
m_log.Error("[LOGIN]: Sending user to default region " + defaultHandle + " instead");
regionInfo = GetRegionInfo(defaultHandle);
// If we haven't already tried the default region, reset regionInfo
if (regionInfo != null && defaultHandle != regionInfo.RegionHandle)
regionInfo = null;
if (regionInfo == null)
{
m_log.ErrorFormat("[LOGIN]: No default region available. Aborting.");
return false;
m_log.Error("[LOGIN]: Sending user to default region " + defaultHandle + " instead");
regionInfo = GetRegionInfo(defaultHandle);
}
theUser.CurrentAgent.Position = new Vector3(128, 128, 0);
if (regionInfo == null)
{
m_log.ErrorFormat("[LOGIN]: Sending user to any region");
regionInfo = RequestClosestRegion(String.Empty);
}
theUser.CurrentAgent.Position = new Vector3(128f, 128f, 0f);
response.StartLocation = "safe";
return PrepareLoginToRegion(regionInfo, theUser, response, client);

View File

@ -1,159 +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.Threading;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Services.Interfaces;
using OpenSim.Tests.Common.Mock;
namespace OpenSim.Framework.Communications.Tests
{
/// <summary>
/// Asset cache tests
/// </summary>
[TestFixture]
public class AssetCacheTests
{
private class FakeUserService : IUserService
{
public void AddTemporaryUserProfile(UserProfileData userProfile)
{
throw new NotImplementedException();
}
public UserProfileData GetUserProfile(string firstName, string lastName)
{
throw new NotImplementedException();
}
public UserProfileData GetUserProfile(UUID userId)
{
throw new NotImplementedException();
}
public UserProfileData GetUserProfile(Uri uri)
{
UserProfileData userProfile = new UserProfileData();
// userProfile.ID = new UUID(Util.GetHashGuid(uri.ToString(), AssetCache.AssetInfo.Secret));
return userProfile;
}
public Uri GetUserUri(UserProfileData userProfile)
{
throw new NotImplementedException();
}
public UserAgentData GetAgentByUUID(UUID userId)
{
throw new NotImplementedException();
}
public void ClearUserAgent(UUID avatarID)
{
throw new NotImplementedException();
}
public List<AvatarPickerAvatar> GenerateAgentPickerRequestResponse(UUID QueryID, string Query)
{
throw new NotImplementedException();
}
public UserProfileData SetupMasterUser(string firstName, string lastName)
{
throw new NotImplementedException();
}
public UserProfileData SetupMasterUser(string firstName, string lastName, string password)
{
throw new NotImplementedException();
}
public UserProfileData SetupMasterUser(UUID userId)
{
throw new NotImplementedException();
}
public bool UpdateUserProfile(UserProfileData data)
{
throw new NotImplementedException();
}
public void AddNewUserFriend(UUID friendlistowner, UUID friend, uint perms)
{
throw new NotImplementedException();
}
public void RemoveUserFriend(UUID friendlistowner, UUID friend)
{
throw new NotImplementedException();
}
public void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms)
{
throw new NotImplementedException();
}
public void LogOffUser(UUID userid, UUID regionid, ulong regionhandle, Vector3 position, Vector3 lookat)
{
throw new NotImplementedException();
}
public void LogOffUser(UUID userid, UUID regionid, ulong regionhandle, float posx, float posy, float posz)
{
throw new NotImplementedException();
}
public List<FriendListItem> GetUserFriendList(UUID friendlistowner)
{
throw new NotImplementedException();
}
public bool VerifySession(UUID userID, UUID sessionID)
{
return true;
}
public void SetInventoryService(IInventoryService inv)
{
throw new NotImplementedException();
}
public virtual bool AuthenticateUserByPassword(UUID userID, string password)
{
throw new NotImplementedException();
}
}
}
}

View File

@ -75,7 +75,7 @@ namespace OpenSim.Framework.Communications.Tests
m_regionConnector.AddRegion(new RegionInfo(42, 43, m_capsEndPoint, m_regionExternalName));
//IInventoryService m_inventoryService = new TestInventoryService();
//IInventoryService m_inventoryService = new MockInventoryService();
m_localUserServices = (LocalUserServices) m_commsManager.UserService;
m_localUserServices.AddUser(m_firstName,m_lastName,"boingboing","abc@ftw.com",42,43);
@ -95,7 +95,8 @@ namespace OpenSim.Framework.Communications.Tests
TestHelper.InMethod();
// We want to use our own LoginService for this test, one that
// doesn't require authentication.
new LLStandaloneLoginService((UserManagerBase)m_commsManager.UserService, "Hello folks", new TestInventoryService(),
new LLStandaloneLoginService(
(UserManagerBase)m_commsManager.UserService, "Hello folks", new MockInventoryService(),
m_commsManager.NetworkServersInfo, false, new LibraryRootFolder(String.Empty), m_regionConnector);
Hashtable loginParams = new Hashtable();
@ -457,148 +458,4 @@ namespace OpenSim.Framework.Communications.Tests
#endregion
}
}
class TestInventoryService : IInventoryService
{
public TestInventoryService()
{
}
/// <summary>
/// <see cref="OpenSim.Framework.Communications.IInterServiceInventoryServices"/>
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public bool CreateUserInventory(UUID userId)
{
return false;
}
/// <summary>
/// <see cref="OpenSim.Framework.Communications.IInterServiceInventoryServices"/>
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public List<InventoryFolderBase> GetInventorySkeleton(UUID userId)
{
List<InventoryFolderBase> folders = new List<InventoryFolderBase>();
InventoryFolderBase folder = new InventoryFolderBase();
folder.ID = UUID.Random();
folder.Owner = userId;
folders.Add(folder);
return folders;
}
/// <summary>
/// Returns a list of all the active gestures in a user's inventory.
/// </summary>
/// <param name="userId">
/// The <see cref="UUID"/> of the user
/// </param>
/// <returns>
/// A flat list of the gesture items.
/// </returns>
public List<InventoryItemBase> GetActiveGestures(UUID userId)
{
return null;
}
public InventoryCollection GetUserInventory(UUID userID)
{
return null;
}
public void GetUserInventory(UUID userID, OpenSim.Services.Interfaces.InventoryReceiptCallback callback)
{
}
public InventoryFolderBase GetFolderForType(UUID userID, AssetType type)
{
return null;
}
public InventoryCollection GetFolderContent(UUID userID, UUID folderID)
{
return null;
}
public List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID)
{
return null;
}
public bool AddFolder(InventoryFolderBase folder)
{
return false;
}
public bool UpdateFolder(InventoryFolderBase folder)
{
return false;
}
public bool MoveFolder(InventoryFolderBase folder)
{
return false;
}
public bool DeleteFolders(UUID ownerID, List<UUID> ids)
{
return false;
}
public bool PurgeFolder(InventoryFolderBase folder)
{
return false;
}
public bool AddItem(InventoryItemBase item)
{
return false;
}
public bool UpdateItem(InventoryItemBase item)
{
return false;
}
public bool MoveItems(UUID owner, List<InventoryItemBase> items)
{
return false;
}
public bool DeleteItems(UUID owner, List<UUID> items)
{
return false;
}
public InventoryItemBase GetItem(InventoryItemBase item)
{
return null;
}
public InventoryFolderBase GetFolder(InventoryFolderBase folder)
{
return null;
}
public bool HasInventoryForUser(UUID userID)
{
return false;
}
public InventoryFolderBase GetRootFolder(UUID userID)
{
InventoryFolderBase root = new InventoryFolderBase();
root.ID = UUID.Random();
root.Owner = userID;
root.ParentID = UUID.Zero;
return root;
}
public int GetAssetPermissions(UUID userID, UUID assetID)
{
return 1;
}
}
}

View File

@ -446,6 +446,7 @@ namespace OpenSim.Framework
public delegate void AvatarNotesUpdate(IClientAPI client, UUID targetID, string notes);
public delegate void MuteListRequest(IClientAPI client, uint muteCRC);
public delegate void AvatarInterestUpdate(IClientAPI client, uint wantmask, string wanttext, uint skillsmask, string skillstext, string languages);
public delegate void GrantUserFriendRights(IClientAPI client, UUID requester, UUID target, int rights);
public delegate void PlacesQuery(UUID QueryID, UUID TransactionID, string QueryText, uint QueryFlags, byte Category, string SimName, IClientAPI client);
public delegate void AgentFOV(IClientAPI client, float verticalAngle);
@ -591,7 +592,6 @@ namespace OpenSim.Framework
public readonly Vector3 Velocity;
public readonly Vector3 Acceleration;
public readonly Vector3 AngularVelocity;
public readonly byte State;
public readonly UUID AssetID;
public readonly UUID OwnerID;
public readonly int AttachPoint;
@ -599,7 +599,7 @@ namespace OpenSim.Framework
public readonly double Priority;
public SendPrimitiveTerseData(ulong regionHandle, ushort timeDilation, uint localID, Vector3 position,
Quaternion rotation, Vector3 velocity, Vector3 acceleration, Vector3 rotationalvelocity, byte state,
Quaternion rotation, Vector3 velocity, Vector3 acceleration, Vector3 rotationalvelocity,
UUID assetID, UUID ownerID, int attachPoint, byte[] textureEntry, double priority)
{
RegionHandle = regionHandle;
@ -610,7 +610,6 @@ namespace OpenSim.Framework
Velocity = velocity;
Acceleration = acceleration;
AngularVelocity = rotationalvelocity;
State = state;
AssetID = assetID;
OwnerID = ownerID;
AttachPoint = attachPoint;
@ -1023,6 +1022,7 @@ namespace OpenSim.Framework
event PickInfoUpdate OnPickInfoUpdate;
event AvatarNotesUpdate OnAvatarNotesUpdate;
event AvatarInterestUpdate OnAvatarInterestUpdate;
event GrantUserFriendRights OnGrantUserRights;
event MuteListRequest OnMuteListRequest;
@ -1124,7 +1124,7 @@ namespace OpenSim.Framework
void ReprioritizeUpdates(StateUpdateTypes type, UpdatePriorityHandler handler);
void SendInventoryFolderDetails(UUID ownerID, UUID folderID, List<InventoryItemBase> items,
List<InventoryFolderBase> folders, bool fetchFolders,
List<InventoryFolderBase> folders, int version, bool fetchFolders,
bool fetchItems);
void FlushPrimUpdates();

View File

@ -69,7 +69,7 @@ namespace OpenSim.Framework
Util.FireAndForget(
delegate(object o)
{
int threadIndex = (int)o;
// int threadIndex = (int)o;
while (exception == null)
{
@ -126,7 +126,7 @@ namespace OpenSim.Framework
Util.FireAndForget(
delegate(object o)
{
int threadIndex = (int)o;
// int threadIndex = (int)o;
while (exception == null)
{
@ -182,7 +182,7 @@ namespace OpenSim.Framework
Util.FireAndForget(
delegate(object o)
{
int threadIndex = (int)o;
// int threadIndex = (int)o;
while (exception == null)
{

View File

@ -1066,5 +1066,106 @@ namespace OpenSim.Framework
return data;
}
/// <summary>
/// Creates a OpenMetaverse.Primitive and populates it with converted PrimitiveBaseShape values
/// </summary>
/// <returns></returns>
public Primitive ToOmvPrimitive()
{
// position and rotation defaults here since they are not available in PrimitiveBaseShape
return ToOmvPrimitive(new Vector3(0.0f, 0.0f, 0.0f),
new Quaternion(0.0f, 0.0f, 0.0f, 1.0f));
}
/// <summary>
/// Creates a OpenMetaverse.Primitive and populates it with converted PrimitiveBaseShape values
/// </summary>
/// <param name="position"></param>
/// <param name="rotation"></param>
/// <returns></returns>
public Primitive ToOmvPrimitive(Vector3 position, Quaternion rotation)
{
OpenMetaverse.Primitive prim = new OpenMetaverse.Primitive();
prim.Scale = this.Scale;
prim.Position = position;
prim.Rotation = rotation;
if (this.SculptEntry)
{
prim.Sculpt = new Primitive.SculptData();
prim.Sculpt.Type = (OpenMetaverse.SculptType)this.SculptType;
prim.Sculpt.SculptTexture = this.SculptTexture;
return prim;
}
prim.PrimData.PathShearX = this.PathShearX < 128 ? (float)this.PathShearX * 0.01f : (float)(this.PathShearX - 256) * 0.01f;
prim.PrimData.PathShearY = this.PathShearY < 128 ? (float)this.PathShearY * 0.01f : (float)(this.PathShearY - 256) * 0.01f;
prim.PrimData.PathBegin = (float)this.PathBegin * 2.0e-5f;
prim.PrimData.PathEnd = 1.0f - (float)this.PathEnd * 2.0e-5f;
prim.PrimData.PathScaleX = (200 - this.PathScaleX) * 0.01f;
prim.PrimData.PathScaleY = (200 - this.PathScaleY) * 0.01f;
prim.PrimData.PathTaperX = this.PathTaperX * 0.01f;
prim.PrimData.PathTaperY = this.PathTaperY * 0.01f;
prim.PrimData.PathTwistBegin = this.PathTwistBegin * 0.01f;
prim.PrimData.PathTwist = this.PathTwist * 0.01f;
prim.PrimData.ProfileBegin = (float)this.ProfileBegin * 2.0e-5f;
prim.PrimData.ProfileEnd = 1.0f - (float)this.ProfileEnd * 2.0e-5f;
prim.PrimData.ProfileHollow = (float)this.ProfileHollow * 2.0e-5f;
prim.PrimData.profileCurve = this.ProfileCurve;
prim.PrimData.ProfileHole = (HoleType)this.HollowShape;
prim.PrimData.PathCurve = (PathCurve)this.PathCurve;
prim.PrimData.PathRadiusOffset = 0.01f * this.PathRadiusOffset;
prim.PrimData.PathRevolutions = 1.0f + 0.015f * this.PathRevolutions;
prim.PrimData.PathSkew = 0.01f * this.PathSkew;
prim.PrimData.PCode = OpenMetaverse.PCode.Prim;
prim.PrimData.State = 0;
if (this.FlexiEntry)
{
prim.Flexible = new Primitive.FlexibleData();
prim.Flexible.Drag = this.FlexiDrag;
prim.Flexible.Force = new Vector3(this.FlexiForceX, this.FlexiForceY, this.FlexiForceZ);
prim.Flexible.Gravity = this.FlexiGravity;
prim.Flexible.Softness = this.FlexiSoftness;
prim.Flexible.Tension = this.FlexiTension;
prim.Flexible.Wind = this.FlexiWind;
}
if (this.LightEntry)
{
prim.Light = new Primitive.LightData();
prim.Light.Color = new Color4(this.LightColorR, this.LightColorG, this.LightColorB, this.LightColorA);
prim.Light.Cutoff = this.LightCutoff;
prim.Light.Falloff = this.LightFalloff;
prim.Light.Intensity = this.LightIntensity;
prim.Light.Radius = this.LightRadius;
}
prim.Textures = new Primitive.TextureEntry(this.TextureEntry, 0, this.TextureEntry.Length);
prim.Properties = new Primitive.ObjectProperties();
prim.Properties.Name = "Primitive";
prim.Properties.Description = "";
prim.Properties.CreatorID = UUID.Zero;
prim.Properties.GroupID = UUID.Zero;
prim.Properties.OwnerID = UUID.Zero;
prim.Properties.Permissions = new Permissions();
prim.Properties.SalePrice = 10;
prim.Properties.SaleType = new SaleType();
return prim;
}
}
}

View File

@ -0,0 +1,98 @@
using System;
using NUnit.Framework;
using System.Collections.Generic;
namespace OpenSim.Framework.Tests
{
[TestFixture]
public class ACLTest
{
#region Tests
/// <summary>
/// ACL Test class
/// </summary>
[Test]
public void ACLTest01()
{
ACL acl = new ACL();
Role Guests = new Role("Guests");
acl.AddRole(Guests);
Role[] parents = new Role[1];
parents[0] = Guests;
Role JoeGuest = new Role("JoeGuest", parents);
acl.AddRole(JoeGuest);
Resource CanBuild = new Resource("CanBuild");
acl.AddResource(CanBuild);
acl.GrantPermission("Guests", "CanBuild");
Permission perm = acl.HasPermission("JoeGuest", "CanBuild");
Assert.That(perm == Permission.Allow, "JoeGuest should have permission to build");
perm = Permission.None;
try
{
perm = acl.HasPermission("unknownGuest", "CanBuild");
}
catch (KeyNotFoundException)
{
}
catch (Exception)
{
Assert.That(false,"Exception thrown should have been KeyNotFoundException");
}
Assert.That(perm == Permission.None,"Permission None should be set because exception should have been thrown");
}
[Test]
public void KnownButPermissionDenyAndPermissionNoneUserTest()
{
ACL acl = new ACL();
Role Guests = new Role("Guests");
acl.AddRole(Guests);
Role Administrators = new Role("Administrators");
acl.AddRole(Administrators);
Role[] Guestparents = new Role[1];
Role[] Adminparents = new Role[1];
Guestparents[0] = Guests;
Adminparents[0] = Administrators;
Role JoeGuest = new Role("JoeGuest", Guestparents);
acl.AddRole(JoeGuest);
Resource CanBuild = new Resource("CanBuild");
acl.AddResource(CanBuild);
Resource CanScript = new Resource("CanScript");
acl.AddResource(CanScript);
Resource CanRestart = new Resource("CanRestart");
acl.AddResource(CanRestart);
acl.GrantPermission("Guests", "CanBuild");
acl.DenyPermission("Guests", "CanRestart");
acl.GrantPermission("Administrators", "CanScript");
acl.GrantPermission("Administrators", "CanRestart");
Permission setPermission = acl.HasPermission("JoeGuest", "CanRestart");
Assert.That(setPermission == Permission.Deny, "Guests Should not be able to restart");
Assert.That(acl.HasPermission("JoeGuest", "CanScript") == Permission.None,
"No Explicit Permissions set so should be Permission.None");
}
#endregion
}
}

View File

@ -67,8 +67,7 @@ namespace OpenSim.Framework.Tests
private void CheckContainsReferences(AssetType assetType, bool expected)
{
AssetBase asset = new AssetBase();
asset.Type = (sbyte)assetType;
AssetBase asset = new AssetBase(UUID.Zero, String.Empty, (sbyte)assetType);
bool actual = asset.ContainsReferences;
Assert.AreEqual(expected, actual, "Expected "+assetType+".ContainsReferences to be "+expected+" but was "+actual+".");
}

View File

@ -0,0 +1,75 @@
using System;
using NUnit.Framework;
using OpenMetaverse;
namespace OpenSim.Framework.Tests
{
[TestFixture]
public class CacheTests
{
private Cache cache;
private UUID cacheItemUUID;
[SetUp]
public void Build()
{
cache = new Cache();
cacheItemUUID = UUID.Random();
MemoryCacheItem cachedItem = new MemoryCacheItem(cacheItemUUID.ToString(),DateTime.Now + TimeSpan.FromDays(1));
byte[] foo = new byte[1];
foo[0] = 255;
cachedItem.Store(foo);
cache.Store(cacheItemUUID.ToString(), cachedItem);
}
[Test]
public void TestRetreive()
{
CacheItemBase citem = (CacheItemBase)cache.Get(cacheItemUUID.ToString());
byte[] data = (byte[]) citem.Retrieve();
Assert.That(data.Length == 1, "Cached Item should have one byte element");
Assert.That(data[0] == 255, "Cached Item element should be 255");
}
[Test]
public void TestNotInCache()
{
UUID randomNotIn = UUID.Random();
while (randomNotIn == cacheItemUUID)
{
randomNotIn = UUID.Random();
}
object citem = cache.Get(randomNotIn.ToString());
Assert.That(citem == null, "Item should not be in Cache" );
}
//NOTE: Test Case disabled until Cache is fixed
[Test]
public void TestTTLExpiredEntry()
{
UUID ImmediateExpiryUUID = UUID.Random();
MemoryCacheItem cachedItem = new MemoryCacheItem(ImmediateExpiryUUID.ToString(), TimeSpan.FromDays(-1));
byte[] foo = new byte[1];
foo[0] = 1;
cachedItem.Store(foo);
cache.Store(cacheItemUUID.ToString(), cachedItem);
object citem = cache.Get(cacheItemUUID.ToString());
//Assert.That(citem == null, "Item should not be in Cache because the expiry time was before now");
}
//NOTE: Test Case disabled until Cache is fixed
[Test]
public void ExpireItemManually()
{
UUID ImmediateExpiryUUID = UUID.Random();
MemoryCacheItem cachedItem = new MemoryCacheItem(ImmediateExpiryUUID.ToString(), TimeSpan.FromDays(1));
byte[] foo = new byte[1];
foo[0] = 1;
cachedItem.Store(foo);
cache.Store(cacheItemUUID.ToString(), cachedItem);
cache.Invalidate(ImmediateExpiryUUID.ToString());
object citem = cache.Get(cacheItemUUID.ToString());
//Assert.That(citem == null, "Item should not be in Cache because we manually invalidated it");
}
}
}

View File

@ -35,7 +35,7 @@ namespace OpenSim.Framework
{
public static class ThreadTracker
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public static ProcessThreadCollection GetThreads()
{

View File

@ -48,7 +48,7 @@ namespace OpenSim.Grid.MessagingServer.Modules
{
public class MessageRegionModule : IMessageRegionLookup
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private MessageServerConfig m_cfg;

View File

@ -343,6 +343,10 @@ namespace OpenSim
"Add-InventoryHost <host>",
String.Empty, RunCommand);
m_console.Commands.AddCommand("region", false, "kill uuid",
"kill uuid <UUID>",
"Kill an object by UUID", KillUUID);
if (ConfigurationSettings.Standalone)
{
m_console.Commands.AddCommand("region", false, "create user",
@ -1332,6 +1336,58 @@ namespace OpenSim
return result;
}
/// <summary>
/// Kill an object given its UUID.
/// </summary>
/// <param name="cmdparams"></param>
protected void KillUUID(string module, string[] cmdparams)
{
if (cmdparams.Length > 2)
{
UUID id = UUID.Zero;
SceneObjectGroup grp = null;
Scene sc = null;
if (!UUID.TryParse(cmdparams[2], out id))
{
MainConsole.Instance.Output("[KillUUID]: Error bad UUID format!");
return;
}
m_sceneManager.ForEachScene(
delegate(Scene scene)
{
SceneObjectPart part = scene.GetSceneObjectPart(id);
if (part == null)
return;
grp = part.ParentGroup;
sc = scene;
});
if (grp == null)
{
MainConsole.Instance.Output(String.Format("[KillUUID]: Given UUID {0} not found!", id));
}
else
{
MainConsole.Instance.Output(String.Format("[KillUUID]: Found UUID {0} in scene {1}", id, sc.RegionInfo.RegionName));
try
{
sc.DeleteSceneObject(grp, false);
}
catch (Exception e)
{
m_log.ErrorFormat("[KillUUID]: Error while removing objects from scene: " + e);
}
}
}
else
{
MainConsole.Instance.Output("[KillUUID]: Usage: kill uuid <UUID>");
}
}
#endregion
}
}

View File

@ -37,6 +37,7 @@ using System.Xml;
using log4net;
using OpenMetaverse;
using OpenMetaverse.Packets;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Client;
using OpenSim.Framework.Communications.Cache;
@ -219,6 +220,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
public event FriendActionDelegate OnApproveFriendRequest;
public event FriendActionDelegate OnDenyFriendRequest;
public event FriendshipTermination OnTerminateFriendship;
public event GrantUserFriendRights OnGrantUserRights;
public event MoneyTransferRequest OnMoneyTransferRequest;
public event EconomyDataRequest OnEconomyDataRequest;
public event MoneyBalanceRequest OnMoneyBalanceRequest;
@ -314,14 +316,14 @@ namespace OpenSim.Region.ClientStack.LindenUDP
private readonly LLUDPClient m_udpClient;
private readonly UUID m_sessionId;
private readonly UUID m_secureSessionId;
private readonly UUID m_agentId;
protected readonly UUID m_agentId;
private readonly uint m_circuitCode;
private readonly byte[] m_channelVersion = Utils.EmptyBytes;
private readonly Dictionary<string, UUID> m_defaultAnimations = new Dictionary<string, UUID>();
private readonly IGroupsModule m_GroupsModule;
private int m_cachedTextureSerial;
private PriorityQueue<double, ImprovedTerseObjectUpdatePacket.ObjectDataBlock> m_avatarTerseUpdates;
protected PriorityQueue<double, ImprovedTerseObjectUpdatePacket.ObjectDataBlock> m_avatarTerseUpdates;
private PriorityQueue<double, ImprovedTerseObjectUpdatePacket.ObjectDataBlock> m_primTerseUpdates;
private PriorityQueue<double, ObjectUpdatePacket.ObjectDataBlock> m_primFullUpdates;
private int m_moneyBalance;
@ -783,6 +785,10 @@ namespace OpenSim.Region.ClientStack.LindenUDP
public virtual void SendLayerData(float[] map)
{
Util.FireAndForget(DoSendLayerData, map);
// Send it sync, and async. It's not that much data
// and it improves user experience just so much!
DoSendLayerData(map);
}
/// <summary>
@ -795,16 +801,13 @@ namespace OpenSim.Region.ClientStack.LindenUDP
try
{
//for (int y = 0; y < 16; y++)
//{
// for (int x = 0; x < 16; x++)
// {
// SendLayerData(x, y, map);
// }
//}
// Send LayerData in a spiral pattern. Fun!
SendLayerTopRight(map, 0, 0, 15, 15);
for (int y = 0; y < 16; y++)
{
for (int x = 0; x < 16; x+=4)
{
SendLayerPacket(x, y, map);
}
}
}
catch (Exception e)
{
@ -812,51 +815,35 @@ namespace OpenSim.Region.ClientStack.LindenUDP
}
}
private void SendLayerTopRight(float[] map, int x1, int y1, int x2, int y2)
{
// Row
for (int i = x1; i <= x2; i++)
SendLayerData(i, y1, map);
// Column
for (int j = y1 + 1; j <= y2; j++)
SendLayerData(x2, j, map);
if (x2 - x1 > 0)
SendLayerBottomLeft(map, x1, y1 + 1, x2 - 1, y2);
}
void SendLayerBottomLeft(float[] map, int x1, int y1, int x2, int y2)
{
// Row in reverse
for (int i = x2; i >= x1; i--)
SendLayerData(i, y2, map);
// Column in reverse
for (int j = y2 - 1; j >= y1; j--)
SendLayerData(x1, j, map);
if (x2 - x1 > 0)
SendLayerTopRight(map, x1 + 1, y1, x2, y2 - 1);
}
/// <summary>
/// Sends a set of four patches (x, x+1, ..., x+3) to the client
/// </summary>
/// <param name="map">heightmap</param>
/// <param name="px">X coordinate for patches 0..12</param>
/// <param name="py">Y coordinate for patches 0..15</param>
// private void SendLayerPacket(float[] map, int y, int x)
// {
// int[] patches = new int[4];
// patches[0] = x + 0 + y * 16;
// patches[1] = x + 1 + y * 16;
// patches[2] = x + 2 + y * 16;
// patches[3] = x + 3 + y * 16;
private void SendLayerPacket(int x, int y, float[] map)
{
int[] patches = new int[4];
patches[0] = x + 0 + y * 16;
patches[1] = x + 1 + y * 16;
patches[2] = x + 2 + y * 16;
patches[3] = x + 3 + y * 16;
// Packet layerpack = LLClientView.TerrainManager.CreateLandPacket(map, patches);
// OutPacket(layerpack, ThrottleOutPacketType.Land);
// }
float[] heightmap = (map.Length == 65536) ?
map :
LLHeightFieldMoronize(map);
try
{
Packet layerpack = TerrainCompressor.CreateLandPacket(heightmap, patches);
OutPacket(layerpack, ThrottleOutPacketType.Land);
}
catch
{
for (int px = x ; px < x + 4 ; px++)
SendLayerData(px, y, map);
}
}
/// <summary>
/// Sends a specified patch to a client
@ -1250,7 +1237,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
/// <param name="fetchFolders">Do we need to send folder information?</param>
/// <param name="fetchItems">Do we need to send item information?</param>
public void SendInventoryFolderDetails(UUID ownerID, UUID folderID, List<InventoryItemBase> items,
List<InventoryFolderBase> folders,
List<InventoryFolderBase> folders, int version,
bool fetchFolders, bool fetchItems)
{
// An inventory descendents packet consists of a single agent section and an inventory details
@ -1263,174 +1250,107 @@ namespace OpenSim.Region.ClientStack.LindenUDP
//
// for one example of this kind of thing. In fact, the Linden servers appear to only send about
// 6 to 7 items at a time, so let's stick with 6
int MAX_ITEMS_PER_PACKET = 6;
//Ckrinke This variable is not used, so comment out to remove the warning from the compiler (3-21-08)
//Ckrinke uint FULL_MASK_PERMISSIONS = 2147483647;
int MAX_ITEMS_PER_PACKET = 5;
int MAX_FOLDERS_PER_PACKET = 6;
int totalItems = fetchItems ? items.Count : 0;
int totalFolders = fetchFolders ? folders.Count : 0;
int itemsSent = 0;
if (fetchItems)
{
InventoryDescendentsPacket descend = CreateInventoryDescendentsPacket(ownerID, folderID);
int foldersSent = 0;
int foldersToSend = 0;
int itemsToSend = 0;
if (items.Count < MAX_ITEMS_PER_PACKET)
InventoryDescendentsPacket currentPacket = null;
// Handle empty folders
//
if (totalItems == 0 && totalFolders == 0)
currentPacket = CreateInventoryDescendentsPacket(ownerID, folderID, version, items.Count + folders.Count, 0, 0);
// To preserve SL compatibility, we will NOT combine folders and items in one packet
//
while(itemsSent < totalItems || foldersSent < totalFolders)
{
descend.ItemData = new InventoryDescendentsPacket.ItemDataBlock[items.Count];
if (currentPacket == null) // Start a new packet
{
foldersToSend = totalFolders - foldersSent;
if (foldersToSend > MAX_FOLDERS_PER_PACKET)
foldersToSend = MAX_FOLDERS_PER_PACKET;
if (foldersToSend == 0)
{
itemsToSend = totalItems - itemsSent;
if (itemsToSend > MAX_ITEMS_PER_PACKET)
itemsToSend = MAX_ITEMS_PER_PACKET;
}
currentPacket = CreateInventoryDescendentsPacket(ownerID, folderID, version, items.Count + folders.Count, foldersToSend, itemsToSend);
}
if (foldersToSend-- > 0)
currentPacket.FolderData[foldersSent % MAX_FOLDERS_PER_PACKET] = CreateFolderDataBlock(folders[foldersSent++]);
else if(itemsToSend-- > 0)
currentPacket.ItemData[itemsSent % MAX_ITEMS_PER_PACKET] = CreateItemDataBlock(items[itemsSent++]);
else
{
descend.ItemData = new InventoryDescendentsPacket.ItemDataBlock[MAX_ITEMS_PER_PACKET];
OutPacket(currentPacket, ThrottleOutPacketType.Asset, false);
currentPacket = null;
}
// Descendents must contain the *total* number of descendents (plus folders, whether we
// fetch them or not), not the number of entries we send in this packet. For consistency,
// I'll use it for folder-requests, too, although I wasn't able to get one with
// FetchFolders = true.
// TODO this should be checked with FetchFolders = true
descend.AgentData.Descendents = items.Count + folders.Count;
int count = 0;
int i = 0;
foreach (InventoryItemBase item in items)
{
descend.ItemData[i] = new InventoryDescendentsPacket.ItemDataBlock();
descend.ItemData[i].ItemID = item.ID;
descend.ItemData[i].AssetID = item.AssetID;
descend.ItemData[i].CreatorID = item.CreatorIdAsUuid;
descend.ItemData[i].BaseMask = item.BasePermissions;
descend.ItemData[i].Description = Util.StringToBytes256(item.Description);
descend.ItemData[i].EveryoneMask = item.EveryOnePermissions;
descend.ItemData[i].OwnerMask = item.CurrentPermissions;
descend.ItemData[i].FolderID = item.Folder;
descend.ItemData[i].InvType = (sbyte)item.InvType;
descend.ItemData[i].Name = Util.StringToBytes256(item.Name);
descend.ItemData[i].NextOwnerMask = item.NextPermissions;
descend.ItemData[i].OwnerID = item.Owner;
descend.ItemData[i].Type = (sbyte)item.AssetType;
descend.ItemData[i].GroupID = item.GroupID;
descend.ItemData[i].GroupOwned = item.GroupOwned;
descend.ItemData[i].GroupMask = item.GroupPermissions;
descend.ItemData[i].CreationDate = item.CreationDate;
descend.ItemData[i].SalePrice = item.SalePrice;
descend.ItemData[i].SaleType = item.SaleType;
descend.ItemData[i].Flags = item.Flags;
descend.ItemData[i].CRC =
Helpers.InventoryCRC(descend.ItemData[i].CreationDate, descend.ItemData[i].SaleType,
descend.ItemData[i].InvType, descend.ItemData[i].Type,
descend.ItemData[i].AssetID, descend.ItemData[i].GroupID,
descend.ItemData[i].SalePrice,
descend.ItemData[i].OwnerID, descend.ItemData[i].CreatorID,
descend.ItemData[i].ItemID, descend.ItemData[i].FolderID,
descend.ItemData[i].EveryoneMask,
descend.ItemData[i].Flags, descend.ItemData[i].OwnerMask,
descend.ItemData[i].GroupMask, item.CurrentPermissions);
i++;
count++;
itemsSent++;
if (i == MAX_ITEMS_PER_PACKET)
{
descend.Header.Zerocoded = true;
AddNullFolderBlockToDecendentsPacket(ref descend);
OutPacket(descend, ThrottleOutPacketType.Asset);
if ((items.Count - count) > 0)
{
descend = CreateInventoryDescendentsPacket(ownerID, folderID);
if ((items.Count - count) < MAX_ITEMS_PER_PACKET)
{
descend.ItemData = new InventoryDescendentsPacket.ItemDataBlock[items.Count - count];
}
else
{
descend.ItemData = new InventoryDescendentsPacket.ItemDataBlock[MAX_ITEMS_PER_PACKET];
}
descend.AgentData.Descendents = items.Count + folders.Count;
i = 0;
}
}
}
if (0 < i && i < MAX_ITEMS_PER_PACKET)
{
AddNullFolderBlockToDecendentsPacket(ref descend);
OutPacket(descend, ThrottleOutPacketType.Asset);
}
if (currentPacket != null)
OutPacket(currentPacket, ThrottleOutPacketType.Asset, false);
}
//send subfolders
if (fetchFolders)
private InventoryDescendentsPacket.FolderDataBlock CreateFolderDataBlock(InventoryFolderBase folder)
{
InventoryDescendentsPacket descend = CreateInventoryDescendentsPacket(ownerID, folderID);
InventoryDescendentsPacket.FolderDataBlock newBlock = new InventoryDescendentsPacket.FolderDataBlock();
newBlock.FolderID = folder.ID;
newBlock.Name = Util.StringToBytes256(folder.Name);
newBlock.ParentID = folder.ParentID;
newBlock.Type = (sbyte)folder.Type;
if (folders.Count < MAX_ITEMS_PER_PACKET)
{
descend.FolderData = new InventoryDescendentsPacket.FolderDataBlock[folders.Count];
}
else
{
descend.FolderData = new InventoryDescendentsPacket.FolderDataBlock[MAX_ITEMS_PER_PACKET];
return newBlock;
}
// Not sure if this scenario ever actually occurs, but nonetheless we include the items
// count even if we're not sending item data for the same reasons as above.
descend.AgentData.Descendents = items.Count + folders.Count;
private InventoryDescendentsPacket.ItemDataBlock CreateItemDataBlock(InventoryItemBase item)
{
InventoryDescendentsPacket.ItemDataBlock newBlock = new InventoryDescendentsPacket.ItemDataBlock();
newBlock.ItemID = item.ID;
newBlock.AssetID = item.AssetID;
newBlock.CreatorID = item.CreatorIdAsUuid;
newBlock.BaseMask = item.BasePermissions;
newBlock.Description = Util.StringToBytes256(item.Description);
newBlock.EveryoneMask = item.EveryOnePermissions;
newBlock.OwnerMask = item.CurrentPermissions;
newBlock.FolderID = item.Folder;
newBlock.InvType = (sbyte)item.InvType;
newBlock.Name = Util.StringToBytes256(item.Name);
newBlock.NextOwnerMask = item.NextPermissions;
newBlock.OwnerID = item.Owner;
newBlock.Type = (sbyte)item.AssetType;
int i = 0;
int count = 0;
foreach (InventoryFolderBase folder in folders)
{
descend.FolderData[i] = new InventoryDescendentsPacket.FolderDataBlock();
descend.FolderData[i].FolderID = folder.ID;
descend.FolderData[i].Name = Util.StringToBytes256(folder.Name);
descend.FolderData[i].ParentID = folder.ParentID;
descend.FolderData[i].Type = (sbyte)folder.Type;
newBlock.GroupID = item.GroupID;
newBlock.GroupOwned = item.GroupOwned;
newBlock.GroupMask = item.GroupPermissions;
newBlock.CreationDate = item.CreationDate;
newBlock.SalePrice = item.SalePrice;
newBlock.SaleType = item.SaleType;
newBlock.Flags = item.Flags;
i++;
count++;
itemsSent++;
if (i == MAX_ITEMS_PER_PACKET)
{
AddNullItemBlockToDescendentsPacket(ref descend);
OutPacket(descend, ThrottleOutPacketType.Asset);
newBlock.CRC =
Helpers.InventoryCRC(newBlock.CreationDate, newBlock.SaleType,
newBlock.InvType, newBlock.Type,
newBlock.AssetID, newBlock.GroupID,
newBlock.SalePrice,
newBlock.OwnerID, newBlock.CreatorID,
newBlock.ItemID, newBlock.FolderID,
newBlock.EveryoneMask,
newBlock.Flags, newBlock.OwnerMask,
newBlock.GroupMask, newBlock.NextOwnerMask);
if ((folders.Count - count) > 0)
{
descend = CreateInventoryDescendentsPacket(ownerID, folderID);
if ((folders.Count - count) < MAX_ITEMS_PER_PACKET)
{
descend.FolderData =
new InventoryDescendentsPacket.FolderDataBlock[folders.Count - count];
}
else
{
descend.FolderData =
new InventoryDescendentsPacket.FolderDataBlock[MAX_ITEMS_PER_PACKET];
}
descend.AgentData.Descendents = items.Count + folders.Count;
i = 0;
}
}
}
if (0 < i && i < MAX_ITEMS_PER_PACKET)
{
AddNullItemBlockToDescendentsPacket(ref descend);
OutPacket(descend, ThrottleOutPacketType.Asset);
}
}
if (itemsSent == 0)
{
// no items found.
InventoryDescendentsPacket descend = CreateInventoryDescendentsPacket(ownerID, folderID);
descend.AgentData.Descendents = 0;
AddNullItemBlockToDescendentsPacket(ref descend);
AddNullFolderBlockToDecendentsPacket(ref descend);
OutPacket(descend, ThrottleOutPacketType.Asset);
}
return newBlock;
}
private void AddNullFolderBlockToDecendentsPacket(ref InventoryDescendentsPacket packet)
@ -1472,14 +1392,25 @@ namespace OpenSim.Region.ClientStack.LindenUDP
// No need to add CRC
}
private InventoryDescendentsPacket CreateInventoryDescendentsPacket(UUID ownerID, UUID folderID)
private InventoryDescendentsPacket CreateInventoryDescendentsPacket(UUID ownerID, UUID folderID, int version, int descendents, int folders, int items)
{
InventoryDescendentsPacket descend = (InventoryDescendentsPacket)PacketPool.Instance.GetPacket(PacketType.InventoryDescendents);
descend.Header.Zerocoded = true;
descend.AgentData.AgentID = AgentId;
descend.AgentData.OwnerID = ownerID;
descend.AgentData.FolderID = folderID;
descend.AgentData.Version = 1;
descend.AgentData.Version = version;
descend.AgentData.Descendents = descendents;
if (folders > 0)
descend.FolderData = new InventoryDescendentsPacket.FolderDataBlock[folders];
else
AddNullFolderBlockToDecendentsPacket(ref descend);
if (items > 0)
descend.ItemData = new InventoryDescendentsPacket.ItemDataBlock[items];
else
AddNullItemBlockToDescendentsPacket(ref descend);
return descend;
}
@ -1856,7 +1787,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
economyData.Info.TeleportMinPrice = TeleportMinPrice;
economyData.Info.TeleportPriceExponent = TeleportPriceExponent;
economyData.Header.Reliable = true;
OutPacket(economyData, ThrottleOutPacketType.Unknown);
OutPacket(economyData, ThrottleOutPacketType.Task);
}
public void SendAvatarPickerReply(AvatarPickerReplyAgentDataArgs AgentData, List<AvatarPickerReplyDataArgs> Data)
@ -2786,30 +2717,37 @@ namespace OpenSim.Region.ClientStack.LindenUDP
public void SendAvatarGroupsReply(UUID avatarID, GroupMembershipData[] data)
{
AvatarGroupsReplyPacket p = (AvatarGroupsReplyPacket)PacketPool.Instance.GetPacket(PacketType.AvatarGroupsReply);
p.AgentData = new AvatarGroupsReplyPacket.AgentDataBlock();
p.AgentData.AgentID = AgentId;
p.AgentData.AvatarID = avatarID;
p.GroupData = new AvatarGroupsReplyPacket.GroupDataBlock[data.Length];
int i = 0;
OSDMap llsd = new OSDMap(3);
OSDArray AgentData = new OSDArray(1);
OSDMap AgentDataMap = new OSDMap(1);
AgentDataMap.Add("AgentID", OSD.FromUUID(this.AgentId));
AgentDataMap.Add("AvatarID", OSD.FromUUID(avatarID));
AgentData.Add(AgentDataMap);
llsd.Add("AgentData", AgentData);
OSDArray GroupData = new OSDArray(data.Length);
OSDArray NewGroupData = new OSDArray(data.Length);
foreach (GroupMembershipData m in data)
{
p.GroupData[i] = new AvatarGroupsReplyPacket.GroupDataBlock();
p.GroupData[i].GroupPowers = m.GroupPowers;
p.GroupData[i].AcceptNotices = m.AcceptNotices;
p.GroupData[i].GroupTitle = Utils.StringToBytes(m.GroupTitle);
p.GroupData[i].GroupID = m.GroupID;
p.GroupData[i].GroupName = Utils.StringToBytes(m.GroupName);
p.GroupData[i].GroupInsigniaID = m.GroupPicture;
i++;
OSDMap GroupDataMap = new OSDMap(6);
OSDMap NewGroupDataMap = new OSDMap(1);
GroupDataMap.Add("GroupPowers", OSD.FromBinary(m.GroupPowers));
GroupDataMap.Add("AcceptNotices", OSD.FromBoolean(m.AcceptNotices));
GroupDataMap.Add("GroupTitle", OSD.FromString(m.GroupTitle));
GroupDataMap.Add("GroupID", OSD.FromUUID(m.GroupID));
GroupDataMap.Add("GroupName", OSD.FromString(m.GroupName));
GroupDataMap.Add("GroupInsigniaID", OSD.FromUUID(m.GroupPicture));
NewGroupDataMap.Add("ListInProfile", OSD.FromBoolean(m.ListInProfile));
GroupData.Add(GroupDataMap);
NewGroupData.Add(NewGroupDataMap);
}
llsd.Add("GroupData", GroupData);
llsd.Add("NewGroupData", NewGroupData);
p.NewGroupData = new AvatarGroupsReplyPacket.NewGroupDataBlock();
p.NewGroupData.ListInProfile = true;
OutPacket(p, ThrottleOutPacketType.Task);
IEventQueue eq = this.Scene.RequestModuleInterface<IEventQueue>();
if (eq != null)
{
eq.Enqueue(BuildEvent("AvatarGroupsReply", llsd), this.AgentId);
}
}
public void SendJoinGroupReply(UUID groupID, bool success)
@ -3168,107 +3106,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP
#endregion
#region Prim/Avatar Updates
/*void SendObjectUpdate(SceneObjectPart obj, PrimFlags creatorFlags, PrimUpdateFlags updateFlags)
{
bool canUseCompressed, canUseImproved;
UpdateFlagsToPacketType(creatorFlags, updateFlags, out canUseCompressed, out canUseImproved);
if (!canUseImproved && !canUseCompressed)
SendFullObjectUpdate(obj, creatorFlags, updateFlags);
else if (!canUseImproved)
SendObjectUpdateCompressed(obj, creatorFlags, updateFlags);
else
SendImprovedTerseObjectUpdate(obj, creatorFlags, updateFlags);
}
void SendFullObjectUpdate(SceneObjectPart obj, PrimFlags creatorFlags, PrimUpdateFlags updateFlags)
{
IClientAPI owner;
if (m_scene.ClientManager.TryGetValue(obj.OwnerID, out owner) && owner is LLClientView)
{
LLClientView llOwner = (LLClientView)owner;
// Send an update out to the owner
ObjectUpdatePacket updateToOwner = new ObjectUpdatePacket();
updateToOwner.RegionData.RegionHandle = obj.RegionHandle;
//updateToOwner.RegionData.TimeDilation = (ushort)(timeDilation * (float)UInt16.MaxValue);
updateToOwner.ObjectData = new ObjectUpdatePacket.ObjectDataBlock[1];
updateToOwner.ObjectData[0] = BuildUpdateBlock(obj, obj.Flags | creatorFlags | PrimFlags.ObjectYouOwner, 0);
m_udpServer.SendPacket(llOwner.UDPClient, updateToOwner, ThrottleOutPacketType.State, true);
}
// Send an update out to everyone else
ObjectUpdatePacket updateToOthers = new ObjectUpdatePacket();
updateToOthers.RegionData.RegionHandle = obj.RegionHandle;
//updateToOthers.RegionData.TimeDilation = (ushort)(timeDilation * (float)UInt16.MaxValue);
updateToOthers.ObjectData = new ObjectUpdatePacket.ObjectDataBlock[1];
updateToOthers.ObjectData[0] = BuildUpdateBlock(obj, obj.Flags, 0);
m_scene.ClientManager.ForEach(
delegate(IClientAPI client)
{
if (client.AgentId != obj.OwnerID && client is LLClientView)
{
LLClientView llClient = (LLClientView)client;
m_udpServer.SendPacket(llClient.UDPClient, updateToOthers, ThrottleOutPacketType.State, true);
}
}
);
}
void SendObjectUpdateCompressed(SceneObjectPart obj, PrimFlags creatorFlags, PrimUpdateFlags updateFlags)
{
}
void SendImprovedTerseObjectUpdate(SceneObjectPart obj, PrimFlags creatorFlags, PrimUpdateFlags updateFlags)
{
}
void UpdateFlagsToPacketType(PrimFlags creatorFlags, PrimUpdateFlags updateFlags, out bool canUseCompressed, out bool canUseImproved)
{
canUseCompressed = true;
canUseImproved = true;
if ((updateFlags & PrimUpdateFlags.FullUpdate) == PrimUpdateFlags.FullUpdate || creatorFlags != PrimFlags.None)
{
canUseCompressed = false;
canUseImproved = false;
}
else
{
if ((updateFlags & PrimUpdateFlags.Velocity) != 0 ||
(updateFlags & PrimUpdateFlags.Acceleration) != 0 ||
(updateFlags & PrimUpdateFlags.CollisionPlane) != 0 ||
(updateFlags & PrimUpdateFlags.Joint) != 0)
{
canUseCompressed = false;
}
if ((updateFlags & PrimUpdateFlags.PrimFlags) != 0 ||
(updateFlags & PrimUpdateFlags.ParentID) != 0 ||
(updateFlags & PrimUpdateFlags.Scale) != 0 ||
(updateFlags & PrimUpdateFlags.PrimData) != 0 ||
(updateFlags & PrimUpdateFlags.Text) != 0 ||
(updateFlags & PrimUpdateFlags.NameValue) != 0 ||
(updateFlags & PrimUpdateFlags.ExtraData) != 0 ||
(updateFlags & PrimUpdateFlags.TextureAnim) != 0 ||
(updateFlags & PrimUpdateFlags.Sound) != 0 ||
(updateFlags & PrimUpdateFlags.Particles) != 0 ||
(updateFlags & PrimUpdateFlags.Material) != 0 ||
(updateFlags & PrimUpdateFlags.ClickAction) != 0 ||
(updateFlags & PrimUpdateFlags.MediaURL) != 0 ||
(updateFlags & PrimUpdateFlags.Joint) != 0)
{
canUseImproved = false;
}
}
}*/
#endregion Prim/Avatar Updates
#region Avatar Packet/Data Sending Methods
/// <summary>
@ -3314,7 +3151,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
ProcessAvatarTerseUpdates();
}
private void ProcessAvatarTerseUpdates()
protected void ProcessAvatarTerseUpdates()
{
ImprovedTerseObjectUpdatePacket terse = (ImprovedTerseObjectUpdatePacket)PacketPool.Instance.GetPacket(PacketType.ImprovedTerseObjectUpdate);
terse.Header.Reliable = false;
@ -3335,6 +3172,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
terse.ObjectData[i] = m_avatarTerseUpdates.Dequeue();
}
// HACK: Using the task category until the tiered reprioritization code is in
OutPacket(terse, ThrottleOutPacketType.Task);
}
@ -3343,12 +3181,17 @@ namespace OpenSim.Region.ClientStack.LindenUDP
if (!IsActive) return; // We don't need to update inactive clients.
CoarseLocationUpdatePacket loc = (CoarseLocationUpdatePacket)PacketPool.Instance.GetPacket(PacketType.CoarseLocationUpdate);
// TODO: don't create new blocks if recycling an old packet
int total = CoarseLocations.Count;
CoarseLocationUpdatePacket.IndexBlock ib =
new CoarseLocationUpdatePacket.IndexBlock();
loc.Header.Reliable = false;
// Each packet can only hold around 62 avatar positions and the client clears the mini-map each time
// a CoarseLocationUpdate packet is received. Oh well.
int total = Math.Min(CoarseLocations.Count, 60);
CoarseLocationUpdatePacket.IndexBlock ib = new CoarseLocationUpdatePacket.IndexBlock();
loc.Location = new CoarseLocationUpdatePacket.LocationBlock[total];
loc.AgentData = new CoarseLocationUpdatePacket.AgentDataBlock[total];
int selfindex = -1;
for (int i = 0; i < total; i++)
{
@ -3358,18 +3201,17 @@ namespace OpenSim.Region.ClientStack.LindenUDP
lb.X = (byte)CoarseLocations[i].X;
lb.Y = (byte)CoarseLocations[i].Y;
lb.Z = CoarseLocations[i].Z > 1024 ? (byte)0 : (byte)(CoarseLocations[i].Z * 0.25);
lb.Z = CoarseLocations[i].Z > 1024 ? (byte)0 : (byte)(CoarseLocations[i].Z * 0.25f);
loc.Location[i] = lb;
loc.AgentData[i] = new CoarseLocationUpdatePacket.AgentDataBlock();
loc.AgentData[i].AgentID = users[i];
if (users[i] == AgentId)
selfindex = i;
}
ib.You = (short)selfindex;
ib.Prey = -1;
loc.Index = ib;
loc.Header.Reliable = false;
loc.Header.Zerocoded = true;
OutPacket(loc, ThrottleOutPacketType.Task);
}
@ -4180,11 +4022,11 @@ namespace OpenSim.Region.ClientStack.LindenUDP
protected ImprovedTerseObjectUpdatePacket.ObjectDataBlock CreateImprovedTerseBlock(SendPrimitiveTerseData data)
{
return CreateImprovedTerseBlock(false, data.LocalID, data.State, Vector4.Zero, data.Position, data.Velocity,
return CreateImprovedTerseBlock(false, data.LocalID, data.AttachPoint, Vector4.Zero, data.Position, data.Velocity,
data.Acceleration, data.Rotation, data.AngularVelocity, data.TextureEntry);
}
protected ImprovedTerseObjectUpdatePacket.ObjectDataBlock CreateImprovedTerseBlock(bool avatar, uint localID, byte state,
protected ImprovedTerseObjectUpdatePacket.ObjectDataBlock CreateImprovedTerseBlock(bool avatar, uint localID, int attachPoint,
Vector4 collisionPlane, Vector3 position, Vector3 velocity, Vector3 acceleration, Quaternion rotation,
Vector3 angularVelocity, byte[] textureEntry)
{
@ -4196,7 +4038,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
pos += 4;
// Avatar/CollisionPlane
data[pos++] = state;
data[pos++] = (byte)((attachPoint % 16) * 16 + (attachPoint / 16)); ;
if (avatar)
{
data[pos++] = 1;
@ -4430,11 +4272,11 @@ namespace OpenSim.Region.ClientStack.LindenUDP
/// </summary>
protected virtual void RegisterLocalPacketHandlers()
{
AddLocalPacketHandler(PacketType.LogoutRequest, Logout);
AddLocalPacketHandler(PacketType.LogoutRequest, HandleLogout);
AddLocalPacketHandler(PacketType.AgentUpdate, HandleAgentUpdate);
AddLocalPacketHandler(PacketType.ViewerEffect, HandleViewerEffect);
AddLocalPacketHandler(PacketType.AgentCachedTexture, AgentTextureCached);
AddLocalPacketHandler(PacketType.MultipleObjectUpdate, MultipleObjUpdate);
AddLocalPacketHandler(PacketType.AgentCachedTexture, HandleAgentTextureCached);
AddLocalPacketHandler(PacketType.MultipleObjectUpdate, HandleMultipleObjUpdate);
AddLocalPacketHandler(PacketType.MoneyTransferRequest, HandleMoneyTransferRequest);
AddLocalPacketHandler(PacketType.ParcelBuy, HandleParcelBuyRequest);
AddLocalPacketHandler(PacketType.UUIDGroupNameRequest, HandleUUIDGroupNameRequest);
@ -4703,7 +4545,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
/// <param name="client"></param>
/// <param name="packet"></param>
/// <returns></returns>
protected virtual bool Logout(IClientAPI client, Packet packet)
protected virtual bool HandleLogout(IClientAPI client, Packet packet)
{
if (packet.Type == PacketType.LogoutRequest)
{
@ -4741,7 +4583,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
/// <param name="simclient"></param>
/// <param name="packet"></param>
/// <returns></returns>
protected bool AgentTextureCached(IClientAPI simclient, Packet packet)
protected bool HandleAgentTextureCached(IClientAPI simclient, Packet packet)
{
//m_log.Debug("texture cached: " + packet.ToString());
AgentCachedTexturePacket cachedtex = (AgentCachedTexturePacket)packet;
@ -4771,7 +4613,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
return true;
}
protected bool MultipleObjUpdate(IClientAPI simClient, Packet packet)
protected bool HandleMultipleObjUpdate(IClientAPI simClient, Packet packet)
{
MultipleObjectUpdatePacket multipleupdate = (MultipleObjectUpdatePacket)packet;
if (multipleupdate.AgentData.SessionID != SessionId) return false;
@ -5050,11 +4892,28 @@ namespace OpenSim.Region.ClientStack.LindenUDP
/// </summary>
/// <param name="packet">Packet to send</param>
/// <param name="throttlePacketType">Throttling category for the packet</param>
private void OutPacket(Packet packet, ThrottleOutPacketType throttlePacketType)
protected void OutPacket(Packet packet, ThrottleOutPacketType throttlePacketType)
{
#region BinaryStats
LLUDPServer.LogPacketHeader(false, m_circuitCode, 0, packet.Type, (ushort)packet.Length);
#endregion BinaryStats
m_udpServer.SendPacket(m_udpClient, packet, throttlePacketType, true);
}
/// <summary>
/// This is the starting point for sending a simulator packet out to the client
/// </summary>
/// <param name="packet">Packet to send</param>
/// <param name="throttlePacketType">Throttling category for the packet</param>
/// <param name="doAutomaticSplitting">True to automatically split oversized
/// packets (the default), or false to disable splitting if the calling code
/// handles splitting manually</param>
protected void OutPacket(Packet packet, ThrottleOutPacketType throttlePacketType, bool doAutomaticSplitting)
{
m_udpServer.SendPacket(m_udpClient, packet, throttlePacketType, doAutomaticSplitting);
}
public bool AddMoney(int debit)
{
if (m_moneyBalance + debit >= 0)
@ -9855,6 +9714,25 @@ namespace OpenSim.Region.ClientStack.LindenUDP
Utils.BytesToString(avatarInterestUpdate.PropertiesData.LanguagesText));
break;
case PacketType.GrantUserRights:
GrantUserRightsPacket GrantUserRights =
(GrantUserRightsPacket)Pack;
#region Packet Session and User Check
if (m_checkPackets)
{
if (GrantUserRights.AgentData.SessionID != SessionId ||
GrantUserRights.AgentData.AgentID != AgentId)
break;
}
#endregion
GrantUserFriendRights GrantUserRightsHandler = OnGrantUserRights;
if (GrantUserRightsHandler != null)
GrantUserRightsHandler(this,
GrantUserRights.AgentData.AgentID,
GrantUserRights.Rights[0].AgentRelated,
GrantUserRights.Rights[0].RelatedRights);
break;
case PacketType.PlacesQuery:
PlacesQueryPacket placesQueryPacket =
(PlacesQueryPacket)Pack;
@ -9944,7 +9822,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
commandMessagePacket.CommandBlock.Command = (uint)command;
commandMessagePacket.CommandBlock.Time = time;
OutPacket(commandMessagePacket, ThrottleOutPacketType.Unknown);
OutPacket(commandMessagePacket, ThrottleOutPacketType.Task);
}
public void SendParcelMediaUpdate(string mediaUrl, UUID mediaTextureID,
@ -9962,7 +9840,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
updatePacket.DataBlockExtended.MediaHeight = mediaHeight;
updatePacket.DataBlockExtended.MediaLoop = mediaLoop;
OutPacket(updatePacket, ThrottleOutPacketType.Unknown);
OutPacket(updatePacket, ThrottleOutPacketType.Task);
}
#endregion
@ -10236,7 +10114,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
}
#region PriorityQueue
private class PriorityQueue<TPriority, TValue>
public class PriorityQueue<TPriority, TValue>
{
internal delegate bool UpdatePriorityHandler(ref TPriority priority, uint local_id);
@ -10264,7 +10142,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
this.m_comparison = comparison;
}
internal object SyncRoot { get { return this.m_syncRoot; } }
public object SyncRoot { get { return this.m_syncRoot; } }
internal int Count
{
get
@ -10276,7 +10154,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
}
}
internal bool Enqueue(TPriority priority, TValue value, uint local_id)
public bool Enqueue(TPriority priority, TValue value, uint local_id)
{
LookupItem item;
@ -10396,5 +10274,13 @@ namespace OpenSim.Region.ClientStack.LindenUDP
}
#endregion
public static OSD BuildEvent(string eventName, OSD eventBody)
{
OSDMap osdEvent = new OSDMap(2);
osdEvent.Add("message", new OSDString(eventName));
osdEvent.Add("body", eventBody);
return osdEvent;
}
}
}

View File

@ -197,11 +197,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP
private void Initialise(UUID fileID, string fileName)
{
m_asset = new AssetBase();
m_asset.FullID = fileID;
m_asset.Type = type;
m_asset = new AssetBase(fileID, fileName, type);
m_asset.Data = new byte[0];
m_asset.Name = fileName;
m_asset.Description = "empty";
m_asset.Local = true;
m_asset.Temporary = true;

View File

@ -135,8 +135,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP
private readonly TokenBucket m_throttle;
/// <summary>Throttle buckets for each packet category</summary>
private readonly TokenBucket[] m_throttleCategories;
/// <summary>Throttle rate defaults and limits</summary>
private readonly ThrottleRates m_defaultThrottleRates;
/// <summary>Outgoing queues for throttled packets</summary>
private readonly OpenSim.Framework.LocklessQueue<OutgoingPacket>[] m_packetOutboxes = new OpenSim.Framework.LocklessQueue<OutgoingPacket>[THROTTLE_CATEGORY_COUNT];
/// <summary>A container that can hold one packet for each outbox, used to store
@ -145,6 +143,9 @@ namespace OpenSim.Region.ClientStack.LindenUDP
/// <summary>A reference to the LLUDPServer that is managing this client</summary>
private readonly LLUDPServer m_udpServer;
private int m_defaultRTO = 3000;
private int m_maxRTO = 60000;
/// <summary>
/// Default constructor
/// </summary>
@ -155,13 +156,17 @@ namespace OpenSim.Region.ClientStack.LindenUDP
/// <param name="circuitCode">Circuit code for this connection</param>
/// <param name="agentID">AgentID for the connected agent</param>
/// <param name="remoteEndPoint">Remote endpoint for this connection</param>
public LLUDPClient(LLUDPServer server, ThrottleRates rates, TokenBucket parentThrottle, uint circuitCode, UUID agentID, IPEndPoint remoteEndPoint)
public LLUDPClient(LLUDPServer server, ThrottleRates rates, TokenBucket parentThrottle, uint circuitCode, UUID agentID, IPEndPoint remoteEndPoint, int defaultRTO, int maxRTO)
{
AgentID = agentID;
RemoteEndPoint = remoteEndPoint;
CircuitCode = circuitCode;
m_udpServer = server;
m_defaultThrottleRates = rates;
if (defaultRTO != 0)
m_defaultRTO = defaultRTO;
if (maxRTO != 0)
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);
// Create an array of token buckets for this clients different throttle categories
@ -178,7 +183,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
}
// Default the retransmission timeout to three seconds
RTO = 3000;
RTO = m_defaultRTO;
// Initialize this to a sane value to prevent early disconnects
TickLastPacketReceived = Environment.TickCount & Int32.MaxValue;
@ -500,7 +505,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, 3000, 60000);
rto = Utils.Clamp(RTO, m_defaultRTO, m_maxRTO);
RTO = rto;
@ -520,7 +525,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
RTTVAR = 0.0f;
// Double the retransmission timeout
RTO = Math.Min(RTO * 2, 60000);
RTO = Math.Min(RTO * 2, m_maxRTO);
}
/// <summary>

View File

@ -27,6 +27,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
@ -118,13 +119,13 @@ namespace OpenSim.Region.ClientStack.LindenUDP
/// <summary></summary>
//private UDPClientCollection m_clients = new UDPClientCollection();
/// <summary>Bandwidth throttle for this UDP server</summary>
private TokenBucket m_throttle;
protected TokenBucket m_throttle;
/// <summary>Bandwidth throttle rates for this UDP server</summary>
private ThrottleRates m_throttleRates;
protected ThrottleRates m_throttleRates;
/// <summary>Manages authentication for agent circuits</summary>
private AgentCircuitManager m_circuitManager;
/// <summary>Reference to the scene this UDP server is attached to</summary>
private Scene m_scene;
protected Scene m_scene;
/// <summary>The X/Y coordinates of the scene this UDP server is attached to</summary>
private Location m_location;
/// <summary>The size of the receive buffer for the UDP socket. This value
@ -153,6 +154,9 @@ namespace OpenSim.Region.ClientStack.LindenUDP
/// <summary>Flag to signal when clients should send pings</summary>
private bool m_sendPing;
private int m_defaultRTO = 0;
private int m_maxRTO = 0;
public Socket Server { get { return null; } }
public LLUDPServer(IPAddress listenIP, ref uint port, int proxyPortOffsetParm, bool allow_alternate_port, IConfigSource configSource, AgentCircuitManager circuitManager)
@ -189,6 +193,9 @@ namespace OpenSim.Region.ClientStack.LindenUDP
AvatarTerseUpdatesPerPacket = config.GetInt("AvatarTerseUpdatesPerPacket", 10);
PrimFullUpdatesPerPacket = config.GetInt("PrimFullUpdatesPerPacket", 100);
TextureSendLimit = config.GetInt("TextureSendLimit", 20);
m_defaultRTO = config.GetInt("DefaultRTO", 0);
m_maxRTO = config.GetInt("MaxRTO", 0);
}
else
{
@ -198,6 +205,31 @@ namespace OpenSim.Region.ClientStack.LindenUDP
TextureSendLimit = 20;
}
#region BinaryStats
config = configSource.Configs["Statistics.Binary"];
m_shouldCollectStats = false;
if (config != null)
{
if (config.Contains("enabled") && config.GetBoolean("enabled"))
{
if (config.Contains("collect_packet_headers"))
m_shouldCollectStats = config.GetBoolean("collect_packet_headers");
if (config.Contains("packet_headers_period_seconds"))
{
binStatsMaxFilesize = TimeSpan.FromSeconds(config.GetInt("region_stats_period_seconds"));
}
if (config.Contains("stats_dir"))
{
binStatsDir = config.GetString("stats_dir");
}
}
else
{
m_shouldCollectStats = false;
}
}
#endregion BinaryStats
m_throttle = new TokenBucket(null, sceneThrottleBps, sceneThrottleBps);
m_throttleRates = new ThrottleRates(configSource);
}
@ -247,8 +279,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP
public void BroadcastPacket(Packet packet, ThrottleOutPacketType category, bool sendToPausedAgents, bool allowSplitting)
{
// CoarseLocationUpdate packets cannot be split in an automated way
if (packet.Type == PacketType.CoarseLocationUpdate && allowSplitting)
// CoarseLocationUpdate and AvatarGroupsReply packets cannot be split in an automated way
if ((packet.Type == PacketType.CoarseLocationUpdate || packet.Type == PacketType.AvatarGroupsReply) && allowSplitting)
allowSplitting = false;
if (allowSplitting && packet.HasVariableBlocks)
@ -256,8 +288,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP
byte[][] datas = packet.ToBytesMultiple();
int packetCount = datas.Length;
//if (packetCount > 1)
// m_log.Debug("[LLUDPSERVER]: Split " + packet.Type + " packet into " + packetCount + " packets");
if (packetCount < 1)
m_log.Error("[LLUDPSERVER]: Failed to split " + packet.Type + " with estimated length " + packet.Length);
for (int i = 0; i < packetCount; i++)
{
@ -295,8 +327,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP
byte[][] datas = packet.ToBytesMultiple();
int packetCount = datas.Length;
//if (packetCount > 1)
// m_log.Debug("[LLUDPSERVER]: Split " + packet.Type + " packet into " + packetCount + " packets");
if (packetCount < 1)
m_log.Error("[LLUDPSERVER]: Failed to split " + packet.Type + " with estimated length " + packet.Length);
for (int i = 0; i < packetCount; i++)
{
@ -353,9 +385,12 @@ namespace OpenSim.Region.ClientStack.LindenUDP
}
else
{
m_log.Error("[LLUDPSERVER]: Packet exceeded buffer size! This could be an indication of packet assembly not obeying the MTU. Type=" +
type + ", DataLength=" + dataLength + ", BufferLength=" + buffer.Data.Length + ". Dropping packet");
return;
bufferSize = dataLength;
buffer = new UDPPacketBuffer(udpClient.RemoteEndPoint, bufferSize);
// m_log.Error("[LLUDPSERVER]: Packet exceeded buffer size! This could be an indication of packet assembly not obeying the MTU. Type=" +
// type + ", DataLength=" + dataLength + ", BufferLength=" + buffer.Data.Length + ". Dropping packet");
Buffer.BlockCopy(data, 0, buffer.Data, 0, dataLength);
}
}
@ -364,6 +399,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
#region Queue or Send
OutgoingPacket outgoingPacket = new OutgoingPacket(udpClient, buffer, category);
outgoingPacket.Type = type;
if (!outgoingPacket.Client.EnqueueOutgoing(outgoingPacket))
SendPacketFinal(outgoingPacket);
@ -409,6 +445,13 @@ namespace OpenSim.Region.ClientStack.LindenUDP
SendPacket(udpClient, pc, ThrottleOutPacketType.Unknown, false);
}
public void CompletePing(LLUDPClient udpClient, byte pingID)
{
CompletePingCheckPacket completePing = new CompletePingCheckPacket();
completePing.PingID.PingID = pingID;
SendPacket(udpClient, completePing, ThrottleOutPacketType.Unknown, false);
}
public void ResendUnacked(LLUDPClient udpClient)
{
if (!udpClient.IsConnected)
@ -429,7 +472,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
if (expiredPackets != null)
{
m_log.Debug("[LLUDPSERVER]: Resending " + expiredPackets.Count + " packets to " + udpClient.AgentID + ", RTO=" + udpClient.RTO);
//m_log.Debug("[LLUDPSERVER]: Resending " + expiredPackets.Count + " packets to " + udpClient.AgentID + ", RTO=" + udpClient.RTO);
// Exponential backoff of the retransmission timeout
udpClient.BackoffRTO();
@ -468,6 +511,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
byte flags = buffer.Data[0];
bool isResend = (flags & Helpers.MSG_RESENT) != 0;
bool isReliable = (flags & Helpers.MSG_RELIABLE) != 0;
bool sendSynchronous = false;
LLUDPClient udpClient = outgoingPacket.Client;
if (!udpClient.IsConnected)
@ -523,9 +567,27 @@ namespace OpenSim.Region.ClientStack.LindenUDP
if (isReliable)
Interlocked.Add(ref udpClient.UnackedBytes, outgoingPacket.Buffer.DataLength);
// Put the UDP payload on the wire
AsyncBeginSend(buffer);
//Some packet types need to be sent synchonously.
//Sorry, i know it's not optimal, but until the LL client
//manages packets correctly and re-orders them as required, this is necessary.
if (outgoingPacket.Type == PacketType.ImprovedTerseObjectUpdate
|| outgoingPacket.Type == PacketType.ChatFromSimulator
|| outgoingPacket.Type == PacketType.ObjectUpdate
|| outgoingPacket.Type == PacketType.LayerData)
{
sendSynchronous = true;
}
// Put the UDP payload on the wire
if (sendSynchronous == true)
{
SyncBeginSend(buffer);
}
else
{
AsyncBeginSend(buffer);
}
// Keep track of when this packet was sent out (right now)
outgoingPacket.TickCount = Environment.TickCount & Int32.MaxValue;
}
@ -585,7 +647,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
IClientAPI client;
if (!m_scene.TryGetClient(address, out client) || !(client is LLClientView))
{
m_log.Debug("[LLUDPSERVER]: Received a " + packet.Type + " packet from an unrecognized source: " + address + " in " + m_scene.RegionInfo.RegionName);
//m_log.Debug("[LLUDPSERVER]: Received a " + packet.Type + " packet from an unrecognized source: " + address + " in " + m_scene.RegionInfo.RegionName);
return;
}
@ -663,16 +725,17 @@ namespace OpenSim.Region.ClientStack.LindenUDP
#endregion Incoming Packet Accounting
#region BinaryStats
LogPacketHeader(true, udpClient.CircuitCode, 0, packet.Type, (ushort)packet.Length);
#endregion BinaryStats
#region Ping Check Handling
if (packet.Type == PacketType.StartPingCheck)
{
// We don't need to do anything else with ping checks
StartPingCheckPacket startPing = (StartPingCheckPacket)packet;
CompletePingCheckPacket completePing = new CompletePingCheckPacket();
completePing.PingID.PingID = startPing.PingID.PingID;
SendPacket(udpClient, completePing, ThrottleOutPacketType.Unknown, false);
CompletePing(udpClient, startPing.PingID.PingID);
return;
}
else if (packet.Type == PacketType.CompletePingCheck)
@ -687,6 +750,87 @@ namespace OpenSim.Region.ClientStack.LindenUDP
packetInbox.Enqueue(new IncomingPacket(udpClient, packet));
}
#region BinaryStats
public class PacketLogger
{
public DateTime StartTime;
public string Path = null;
public System.IO.BinaryWriter Log = null;
}
public static PacketLogger PacketLog;
protected static bool m_shouldCollectStats = false;
// Number of seconds to log for
static TimeSpan binStatsMaxFilesize = TimeSpan.FromSeconds(300);
static object binStatsLogLock = new object();
static string binStatsDir = "";
public static void LogPacketHeader(bool incoming, uint circuit, byte flags, PacketType packetType, ushort size)
{
if (!m_shouldCollectStats) return;
// Binary logging format is TTTTTTTTCCCCFPPPSS, T=Time, C=Circuit, F=Flags, P=PacketType, S=size
// Put the incoming bit into the least significant bit of the flags byte
if (incoming)
flags |= 0x01;
else
flags &= 0xFE;
// Put the flags byte into the most significant bits of the type integer
uint type = (uint)packetType;
type |= (uint)flags << 24;
// m_log.Debug("1 LogPacketHeader(): Outside lock");
lock (binStatsLogLock)
{
DateTime now = DateTime.Now;
// m_log.Debug("2 LogPacketHeader(): Inside lock. now is " + now.Ticks);
try
{
if (PacketLog == null || (now > PacketLog.StartTime + binStatsMaxFilesize))
{
if (PacketLog != null && PacketLog.Log != null)
{
PacketLog.Log.Close();
}
// First log file or time has expired, start writing to a new log file
PacketLog = new PacketLogger();
PacketLog.StartTime = now;
PacketLog.Path = (binStatsDir.Length > 0 ? binStatsDir + System.IO.Path.DirectorySeparatorChar.ToString() : "")
+ String.Format("packets-{0}.log", now.ToString("yyyyMMddHHmmss"));
PacketLog.Log = new BinaryWriter(File.Open(PacketLog.Path, FileMode.Append, FileAccess.Write));
}
// Serialize the data
byte[] output = new byte[18];
Buffer.BlockCopy(BitConverter.GetBytes(now.Ticks), 0, output, 0, 8);
Buffer.BlockCopy(BitConverter.GetBytes(circuit), 0, output, 8, 4);
Buffer.BlockCopy(BitConverter.GetBytes(type), 0, output, 12, 4);
Buffer.BlockCopy(BitConverter.GetBytes(size), 0, output, 16, 2);
// Write the serialized data to disk
if (PacketLog != null && PacketLog.Log != null)
PacketLog.Log.Write(output);
}
catch (Exception ex)
{
m_log.Error("Packet statistics gathering failed: " + ex.Message, ex);
if (PacketLog.Log != null)
{
PacketLog.Log.Close();
}
PacketLog = null;
}
}
}
#endregion BinaryStats
private void HandleUseCircuitCode(object o)
{
object[] array = (object[])o;
@ -759,10 +903,10 @@ namespace OpenSim.Region.ClientStack.LindenUDP
}
}
private void AddClient(uint circuitCode, UUID agentID, UUID sessionID, IPEndPoint remoteEndPoint, AuthenticateResponse sessionInfo)
protected virtual void AddClient(uint circuitCode, UUID agentID, UUID sessionID, IPEndPoint remoteEndPoint, AuthenticateResponse sessionInfo)
{
// Create the LLUDPClient
LLUDPClient udpClient = new LLUDPClient(this, m_throttleRates, m_throttle, circuitCode, agentID, remoteEndPoint);
LLUDPClient udpClient = new LLUDPClient(this, m_throttleRates, m_throttle, circuitCode, agentID, remoteEndPoint, m_defaultRTO, m_maxRTO);
IClientAPI existingClient;
if (!m_scene.TryGetClient(agentID, out existingClient))
@ -976,7 +1120,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
}
}
private void LogoutHandler(IClientAPI client)
protected void LogoutHandler(IClientAPI client)
{
client.SendLogoutPacket();
if (client.IsActive)

View File

@ -246,6 +246,24 @@ namespace OpenMetaverse
}
}
public void SyncBeginSend(UDPPacketBuffer buf)
{
if (!m_shutdownFlag)
{
try
{
m_udpSocket.SendTo(
buf.Data,
0,
buf.DataLength,
SocketFlags.None,
buf.RemoteEndPoint);
}
catch (SocketException) { }
catch (ObjectDisposedException) { }
}
}
public void AsyncBeginSend(UDPPacketBuffer buf)
{
if (!m_shutdownFlag)
@ -270,8 +288,8 @@ namespace OpenMetaverse
{
try
{
UDPPacketBuffer buf = (UDPPacketBuffer)result.AsyncState;
int bytesSent = m_udpSocket.EndSendTo(result);
// UDPPacketBuffer buf = (UDPPacketBuffer)result.AsyncState;
m_udpSocket.EndSendTo(result);
}
catch (SocketException) { }
catch (ObjectDisposedException) { }

View File

@ -28,6 +28,7 @@
using System;
using OpenSim.Framework;
using OpenMetaverse;
using OpenMetaverse.Packets;
namespace OpenSim.Region.ClientStack.LindenUDP
{
@ -52,7 +53,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP
public int TickCount;
/// <summary>Category this packet belongs to</summary>
public ThrottleOutPacketType Category;
/// <summary>The type of packet so its delivery method can be determined</summary>
public PacketType Type;
/// <summary>
/// Default constructor
/// </summary>

View File

@ -87,15 +87,13 @@ namespace OpenSim.Region.ClientStack.LindenUDP
IConfig throttleConfig = config.Configs["ClientStack.LindenUDP"];
Resend = throttleConfig.GetInt("resend_default", 12500);
Land = throttleConfig.GetInt("land_default", 500);
Wind = throttleConfig.GetInt("wind_default", 500);
Cloud = throttleConfig.GetInt("cloud_default", 500);
Task = throttleConfig.GetInt("task_default", 500);
Texture = throttleConfig.GetInt("texture_default", 500);
Asset = throttleConfig.GetInt("asset_default", 500);
State = throttleConfig.GetInt("state_default", 500);
Total = throttleConfig.GetInt("client_throttle_max_bps", 0);
Land = throttleConfig.GetInt("land_default", 1000);
Wind = throttleConfig.GetInt("wind_default", 1000);
Cloud = throttleConfig.GetInt("cloud_default", 1000);
Task = throttleConfig.GetInt("task_default", 1000);
Texture = throttleConfig.GetInt("texture_default", 1000);
Asset = throttleConfig.GetInt("asset_default", 1000);
State = throttleConfig.GetInt("state_default", 1000);
ResendLimit = throttleConfig.GetInt("resend_limit", 18750);
LandLimit = throttleConfig.GetInt("land_limit", 29750);
@ -104,9 +102,10 @@ namespace OpenSim.Region.ClientStack.LindenUDP
TaskLimit = throttleConfig.GetInt("task_limit", 18750);
TextureLimit = throttleConfig.GetInt("texture_limit", 55750);
AssetLimit = throttleConfig.GetInt("asset_limit", 27500);
State = throttleConfig.GetInt("state_limit", 37000);
StateLimit = throttleConfig.GetInt("state_limit", 37000);
TotalLimit = throttleConfig.GetInt("client_throttle_max_bps", 0);
Total = throttleConfig.GetInt("client_throttle_max_bps", 0);
TotalLimit = Total;
}
catch (Exception) { }
}

View File

@ -204,6 +204,14 @@ namespace OpenSim.Region.Communications.Hypergrid
return base.UpdateUserProfile(userProfile);
}
public override bool AuthenticateUserByPassword(UUID userID, string password)
{
if (m_localUserServices != null)
return m_localUserServices.AuthenticateUserByPassword(userID, password);
else
return base.AuthenticateUserByPassword(userID, password);
}
#region IUserServices Friend Methods
// NOTE: We're still not dealing with foreign user friends

View File

@ -112,11 +112,8 @@ namespace OpenSim.Region.CoreModules.Agent.AssetTransaction
bool storeLocal, bool tempFile)
{
ourClient = remoteClient;
m_asset = new AssetBase();
m_asset.FullID = assetID;
m_asset.Type = type;
m_asset = new AssetBase(assetID, "blank", type);
m_asset.Data = data;
m_asset.Name = "blank";
m_asset.Description = "empty";
m_asset.Local = storeLocal;
m_asset.Temporary = tempFile;

View File

@ -144,8 +144,8 @@ namespace OpenSim.Region.CoreModules.Agent.TextureSender
/// <param name="j2kData">JPEG2000 data</param>
private void DoJ2KDecode(UUID assetID, byte[] j2kData)
{
int DecodeTime = 0;
DecodeTime = Environment.TickCount;
// int DecodeTime = 0;
// DecodeTime = Environment.TickCount;
OpenJPEG.J2KLayerInfo[] layers;
if (!TryLoadCacheForAsset(assetID, out layers))
@ -238,12 +238,11 @@ namespace OpenSim.Region.CoreModules.Agent.TextureSender
if (m_cache != null)
{
AssetBase layerDecodeAsset = new AssetBase();
layerDecodeAsset.ID = "j2kCache_" + AssetId.ToString();
string assetID = "j2kCache_" + AssetId.ToString();
AssetBase layerDecodeAsset = new AssetBase(assetID, assetID, (sbyte)AssetType.Notecard);
layerDecodeAsset.Local = true;
layerDecodeAsset.Name = layerDecodeAsset.ID;
layerDecodeAsset.Temporary = true;
layerDecodeAsset.Type = (sbyte)AssetType.Notecard;
#region Serialize Layer Data

View File

@ -831,7 +831,7 @@ namespace Flotsam.RegionModules.AssetCache
public string Store(AssetBase asset)
{
if ((asset.FullID == null) || (asset.FullID == UUID.Zero))
if (asset.FullID == UUID.Zero)
{
asset.FullID = UUID.Random();
}

View File

@ -395,6 +395,8 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends
// if it leaves, we want to know, too
client.OnLogout += OnLogout;
client.OnGrantUserRights += GrantUserFriendRights;
}
private void ClientClosed(UUID AgentId, Scene scene)
@ -1108,7 +1110,22 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends
// tell everyone that we are offline
SendPresenceState(remoteClient, fl, false);
}
private void GrantUserFriendRights(IClientAPI remoteClient, UUID requester, UUID target, int rights)
{
((Scene)remoteClient.Scene).CommsManager.UpdateUserFriendPerms(requester, target, (uint)rights);
}
public List<FriendListItem> GetUserFriends(UUID agentID)
{
List<FriendListItem> fl;
lock (m_friendLists)
{
fl = (List<FriendListItem>)m_friendLists.Get(agentID.ToString(),
m_initialScene.GetFriendList);
}
return fl;
}
}
#endregion
}

View File

@ -164,6 +164,8 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
List<GridInstantMessage>msglist = SynchronousRestObjectPoster.BeginPostObject<UUID, List<GridInstantMessage>>(
"POST", m_RestURL+"/RetrieveMessages/", client.AgentId);
if (msglist != null)
{
foreach (GridInstantMessage im in msglist)
{
// client.SendInstantMessage(im);
@ -179,6 +181,7 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
s.EventManager.TriggerIncomingInstantMessage(im);
}
}
}
private void UndeliveredMessage(GridInstantMessage im)
{

View File

@ -100,36 +100,6 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
int successfulItemRestores = 0;
List<InventoryNodeBase> nodesLoaded = new List<InventoryNodeBase>();
/*
if (!m_userInfo.HasReceivedInventory)
{
// If the region server has access to the user admin service (by which users are created),
// then we'll assume that it's okay to fiddle with the user's inventory even if they are not on the
// server.
//
// FIXME: FetchInventory should probably be assumed to by async anyway, since even standalones might
// use a remote inventory service, though this is vanishingly rare at the moment.
if (null == m_scene.CommsManager.UserAdminService)
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Have not yet received inventory info for user {0} {1}",
m_userInfo.UserProfile.Name, m_userInfo.UserProfile.ID);
return nodesLoaded;
}
else
{
m_userInfo.FetchInventory();
for (int i = 0 ; i < 50 ; i++)
{
if (m_userInfo.HasReceivedInventory == true)
break;
Thread.Sleep(200);
}
}
}
*/
//InventoryFolderImpl rootDestinationFolder = m_userInfo.RootFolder.FindFolderByPath(m_invPath);
InventoryFolderBase rootDestinationFolder
= InventoryArchiveUtils.FindFolderByPath(
@ -159,6 +129,11 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
successfulAssetRestores++;
else
failedAssetRestores++;
if ((successfulAssetRestores) % 50 == 0)
m_log.DebugFormat(
"[INVENTORY ARCHIVER]: Loaded {0} assets...",
successfulAssetRestores);
}
else if (filePath.StartsWith(ArchiveConstants.INVENTORY_PATH))
{
@ -169,24 +144,10 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY != entryType)
{
InventoryItemBase item = UserInventoryItemSerializer.Deserialize(data);
InventoryItemBase item = LoadItem(data, foundFolder);
// Don't use the item ID that's in the file
item.ID = UUID.Random();
UUID ospResolvedId = OspResolver.ResolveOspa(item.CreatorId, m_scene.CommsManager);
if (UUID.Zero != ospResolvedId)
item.CreatorIdAsUuid = ospResolvedId;
else
item.CreatorIdAsUuid = m_userInfo.UserProfile.ID;
item.Owner = m_userInfo.UserProfile.ID;
// Reset folder ID to the one in which we want to load it
item.Folder = foundFolder.ID;
//m_userInfo.AddItem(item);
m_scene.InventoryService.AddItem(item);
if (item != null)
{
successfulItemRestores++;
// If we're loading an item directly into the given destination folder then we need to record
@ -196,11 +157,14 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
}
}
}
}
archive.Close();
m_log.DebugFormat("[INVENTORY ARCHIVER]: Restored {0} assets", successfulAssetRestores);
m_log.InfoFormat("[INVENTORY ARCHIVER]: Restored {0} items", successfulItemRestores);
m_log.DebugFormat(
"[INVENTORY ARCHIVER]: Successfully loaded {0} assets with {1} failures",
successfulAssetRestores, failedAssetRestores);
m_log.InfoFormat("[INVENTORY ARCHIVER]: Successfully loaded {0} items", successfulItemRestores);
return nodesLoaded;
}
@ -234,8 +198,8 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
string originalArchivePath = archivePath;
m_log.DebugFormat(
"[INVENTORY ARCHIVER]: Loading to folder {0} {1}", rootDestFolder.Name, rootDestFolder.ID);
// m_log.DebugFormat(
// "[INVENTORY ARCHIVER]: Loading folder {0} {1}", rootDestFolder.Name, rootDestFolder.ID);
InventoryFolderBase destFolder = null;
@ -246,8 +210,8 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
{
if (foldersCreated.ContainsKey(archivePath))
{
m_log.DebugFormat(
"[INVENTORY ARCHIVER]: Found previously created folder from archive path {0}", archivePath);
// m_log.DebugFormat(
// "[INVENTORY ARCHIVER]: Found previously created folder from archive path {0}", archivePath);
destFolder = foldersCreated[archivePath];
}
else
@ -289,6 +253,8 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR);
string newFolderName = rawDirsToCreate[i].Remove(identicalNameIdentifierIndex);
newFolderName = InventoryArchiveUtils.UnescapeArchivePath(newFolderName);
UUID newFolderId = UUID.Random();
// Asset type has to be Unknown here rather than Folder, otherwise the created folder can't be
@ -360,6 +326,37 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
*/
}
/// <summary>
/// Load an item from the archive
/// </summary>
/// <param name="filePath">The archive path for the item</param>
/// <param name="data">The raw item data</param>
/// <param name="rootDestinationFolder">The root destination folder for loaded items</param>
/// <param name="nodesLoaded">All the inventory nodes (items and folders) loaded so far</param>
protected InventoryItemBase LoadItem(byte[] data, InventoryFolderBase loadFolder)
{
InventoryItemBase item = UserInventoryItemSerializer.Deserialize(data);
// Don't use the item ID that's in the file
item.ID = UUID.Random();
UUID ospResolvedId = OspResolver.ResolveOspa(item.CreatorId, m_scene.CommsManager);
if (UUID.Zero != ospResolvedId)
item.CreatorIdAsUuid = ospResolvedId;
else
item.CreatorIdAsUuid = m_userInfo.UserProfile.ID;
item.Owner = m_userInfo.UserProfile.ID;
// Reset folder ID to the one in which we want to load it
item.Folder = loadFolder.ID;
//m_userInfo.AddItem(item);
m_scene.InventoryService.AddItem(item);
return item;
}
/// <summary>
/// Load an asset
/// </summary>
@ -389,11 +386,12 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
{
sbyte assetType = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension];
if (assetType == (sbyte)AssetType.Unknown)
m_log.WarnFormat("[INVENTORY ARCHIVER]: Importing {0} byte asset {1} with unknown type", data.Length, uuid);
//m_log.DebugFormat("[INVENTORY ARCHIVER]: Importing asset {0}, type {1}", uuid, assetType);
AssetBase asset = new AssetBase(new UUID(uuid), "RandomName");
asset.Type = assetType;
AssetBase asset = new AssetBase(new UUID(uuid), "RandomName", assetType);
asset.Data = data;
m_scene.AssetService.Store(asset);

View File

@ -27,6 +27,9 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Services.Interfaces;
@ -38,7 +41,13 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
/// </summary>
public static class InventoryArchiveUtils
{
public static readonly string PATH_DELIMITER = "/";
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// Character used for escaping the path delimter ("\/") and itself ("\\") in human escaped strings
public static readonly char ESCAPE_CHARACTER = '\\';
// The character used to separate inventory path components (different folders and items)
public static readonly char PATH_DELIMITER = '/';
/// <summary>
/// Find a folder given a PATH_DELIMITER delimited path starting from a user's root folder
@ -103,10 +112,14 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
path = path.Trim();
if (path == PATH_DELIMITER)
if (path == PATH_DELIMITER.ToString())
return startFolder;
string[] components = path.Split(new string[] { PATH_DELIMITER }, 2, StringSplitOptions.None);
string[] components = SplitEscapedPath(path);
components[0] = UnescapePath(components[0]);
//string[] components = path.Split(new string[] { PATH_DELIMITER.ToString() }, 2, StringSplitOptions.None);
InventoryCollection contents = inventoryService.GetFolderContent(startFolder.Owner, startFolder.ID);
foreach (InventoryFolderBase folder in contents.Folders)
@ -181,10 +194,15 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
public static InventoryItemBase FindItemByPath(
IInventoryService inventoryService, InventoryFolderBase startFolder, string path)
{
string[] components = path.Split(new string[] { PATH_DELIMITER }, 2, StringSplitOptions.None);
string[] components = SplitEscapedPath(path);
components[0] = UnescapePath(components[0]);
//string[] components = path.Split(new string[] { PATH_DELIMITER }, 2, StringSplitOptions.None);
if (components.Length == 1)
{
// m_log.DebugFormat("FOUND SINGLE COMPONENT [{0}]", components[0]);
List<InventoryItemBase> items = inventoryService.GetFolderItems(startFolder.Owner, startFolder.ID);
foreach (InventoryItemBase item in items)
{
@ -194,6 +212,8 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
}
else
{
// m_log.DebugFormat("FOUND COMPONENTS [{0}] and [{1}]", components[0], components[1]);
InventoryCollection contents = inventoryService.GetFolderContent(startFolder.Owner, startFolder.ID);
foreach (InventoryFolderBase folder in contents.Folders)
@ -206,5 +226,97 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
// We didn't find an item or intermediate folder with the given name
return null;
}
/// <summary>
/// Split a human escaped path into two components if it contains an unescaped path delimiter, or one component
/// if no delimiter is present
/// </summary>
/// <param name="path"></param>
/// <returns>
/// The split path. We leave the components in their originally unescaped state (though we remove the delimiter
/// which originally split them if applicable).
/// </returns>
public static string[] SplitEscapedPath(string path)
{
// m_log.DebugFormat("SPLITTING PATH {0}", path);
bool singleEscapeChar = false;
for (int i = 0; i < path.Length; i++)
{
if (path[i] == ESCAPE_CHARACTER && !singleEscapeChar)
{
singleEscapeChar = true;
}
else
{
if (PATH_DELIMITER == path[i] && !singleEscapeChar)
return new string[2] { path.Remove(i), path.Substring(i + 1) };
else
singleEscapeChar = false;
}
}
// We didn't find a delimiter
return new string[1] { path };
}
/// <summary>
/// Unescapes a human escaped path. This means that "\\" goes to "\", and "\/" goes to "/"
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string UnescapePath(string path)
{
// m_log.DebugFormat("ESCAPING PATH {0}", path);
StringBuilder sb = new StringBuilder();
bool singleEscapeChar = false;
for (int i = 0; i < path.Length; i++)
{
if (path[i] == ESCAPE_CHARACTER && !singleEscapeChar)
singleEscapeChar = true;
else
singleEscapeChar = false;
if (singleEscapeChar)
{
if (PATH_DELIMITER == path[i])
sb.Append(PATH_DELIMITER);
}
else
{
sb.Append(path[i]);
}
}
// m_log.DebugFormat("ESCAPED PATH TO {0}", sb);
return sb.ToString();
}
/// <summary>
/// Escape an archive path.
/// </summary>
/// This has to be done differently from human paths because we can't leave in any "/" characters (due to
/// problems if the archive is built from or extracted to a filesystem
/// <param name="path"></param>
/// <returns></returns>
public static string EscapeArchivePath(string path)
{
// Only encode ampersands (for escaping anything) and / (since this is used as general dir separator).
return path.Replace("&", "&amp;").Replace("/", "&#47;");
}
/// <summary>
/// Unescape an archive path.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string UnescapeArchivePath(string path)
{
return path.Replace("&#47;", "/").Replace("&amp;", "&");
}
}
}

View File

@ -217,37 +217,6 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
InventoryItemBase inventoryItem = null;
InventoryFolderBase rootFolder = m_scene.InventoryService.GetRootFolder(m_userInfo.UserProfile.ID);
// XXX: Very temporarily, drop and refetch inventory to make sure we have any newly created items in cache
// This will disappear very soon once we stop using the old cached inventory.
/*
m_userInfo.DropInventory();
m_userInfo.FetchInventory();
*/
/*
if (!m_userInfo.HasReceivedInventory)
{
// If the region server has access to the user admin service (by which users are created),
// then we'll assume that it's okay to fiddle with the user's inventory even if they are not on the
// server.
//
// FIXME: FetchInventory should probably be assumed to by async anyway, since even standalones might
// use a remote inventory service, though this is vanishingly rare at the moment.
if (null == m_scene.CommsManager.UserAdminService)
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Have not yet received inventory info for user {0} {1}",
m_userInfo.UserProfile.Name, m_userInfo.UserProfile.ID);
return;
}
else
{
m_userInfo.FetchInventory();
}
}
*/
bool foundStar = false;
// Eliminate double slashes and any leading / on the path.
@ -294,27 +263,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
m_archiveWriter = new TarArchiveWriter(m_saveStream);
if (null == inventoryFolder)
{
if (null == inventoryItem)
{
// We couldn't find the path indicated
m_saveStream.Close();
m_module.TriggerInventoryArchiveSaved(
m_id, false, m_userInfo, m_invPath, m_saveStream,
new Exception(string.Format("Could not find inventory entry at path {0}", m_invPath)));
return;
}
else
{
m_log.DebugFormat(
"[INVENTORY ARCHIVER]: Found item {0} {1} at {2}",
inventoryItem.Name, inventoryItem.ID, m_invPath);
SaveInvItem(inventoryItem, ArchiveConstants.INVENTORY_PATH);
}
}
else
if (inventoryFolder != null)
{
m_log.DebugFormat(
"[INVENTORY ARCHIVER]: Found folder {0} {1} at {2}",
@ -323,6 +272,25 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
//recurse through all dirs getting dirs and files
SaveInvFolder(inventoryFolder, ArchiveConstants.INVENTORY_PATH, !foundStar);
}
else if (inventoryItem != null)
{
m_log.DebugFormat(
"[INVENTORY ARCHIVER]: Found item {0} {1} at {2}",
inventoryItem.Name, inventoryItem.ID, m_invPath);
SaveInvItem(inventoryItem, ArchiveConstants.INVENTORY_PATH);
}
else
{
// We couldn't find the path indicated
m_saveStream.Close();
string errorMessage = string.Format("Aborted save. Could not find inventory path {0}", m_invPath);
m_log.ErrorFormat("[INVENTORY ARCHIVER]: {0}", errorMessage);
m_module.TriggerInventoryArchiveSaved(
m_id, false, m_userInfo, m_invPath, m_saveStream,
new Exception(errorMessage));
return;
}
// Don't put all this profile information into the archive right now.
//SaveUsers();
@ -396,7 +364,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
{
return string.Format(
"{0}{1}{2}/",
name,
InventoryArchiveUtils.EscapeArchivePath(name),
ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR,
id);
}
@ -411,7 +379,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
{
return string.Format(
"{0}{1}{2}.xml",
name,
InventoryArchiveUtils.EscapeArchivePath(name),
ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR,
id);
}

View File

@ -29,7 +29,6 @@ using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
@ -122,9 +121,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
}
UUID asset1Id = UUID.Parse("00000000-0000-0000-0000-000000000060");
AssetBase asset1 = new AssetBase();
asset1.FullID = asset1Id;
asset1.Data = Encoding.ASCII.GetBytes(SceneObjectSerializer.ToXml2Format(object1));
AssetBase asset1 = AssetHelpers.CreateAsset(asset1Id, object1);
scene.AssetService.Store(asset1);
// Create item
@ -218,14 +215,14 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
string userItemCreatorLastName = "Lucan";
UUID userItemCreatorUuid = UUID.Parse("00000000-0000-0000-0000-000000000666");
string itemName = "b.lsl";
string archiveItemName = InventoryArchiveWriteRequest.CreateArchiveItemName(itemName, UUID.Random());
string item1Name = "b.lsl";
string archiveItemName = InventoryArchiveWriteRequest.CreateArchiveItemName(item1Name, UUID.Random());
MemoryStream archiveWriteStream = new MemoryStream();
TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream);
InventoryItemBase item1 = new InventoryItemBase();
item1.Name = itemName;
item1.Name = item1Name;
item1.AssetID = UUID.Random();
item1.GroupID = UUID.Random();
item1.CreatorId = OspResolver.MakeOspa(userItemCreatorFirstName, userItemCreatorLastName);
@ -259,7 +256,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
= scene.CommsManager.UserProfileCacheService.GetUserDetails(userFirstName, userLastName);
InventoryItemBase foundItem1
= InventoryArchiveUtils.FindItemByPath(scene.InventoryService, userInfo.UserProfile.ID, itemName);
= InventoryArchiveUtils.FindItemByPath(scene.InventoryService, userInfo.UserProfile.ID, item1Name);
Assert.That(foundItem1, Is.Not.Null, "Didn't find loaded item 1");
Assert.That(
@ -277,7 +274,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
archiverModule.DearchiveInventory(userFirstName, userLastName, "xA", "meowfood", archiveReadStream);
InventoryItemBase foundItem2
= InventoryArchiveUtils.FindItemByPath(scene.InventoryService, userInfo.UserProfile.ID, "xA/" + itemName);
= InventoryArchiveUtils.FindItemByPath(scene.InventoryService, userInfo.UserProfile.ID, "xA/" + item1Name);
Assert.That(foundItem2, Is.Not.Null, "Didn't find loaded item 2");
// Now try loading to a more deeply nested folder
@ -286,10 +283,99 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
archiverModule.DearchiveInventory(userFirstName, userLastName, "xB/xC", "meowfood", archiveReadStream);
InventoryItemBase foundItem3
= InventoryArchiveUtils.FindItemByPath(scene.InventoryService, userInfo.UserProfile.ID, "xB/xC/" + itemName);
= InventoryArchiveUtils.FindItemByPath(scene.InventoryService, userInfo.UserProfile.ID, "xB/xC/" + item1Name);
Assert.That(foundItem3, Is.Not.Null, "Didn't find loaded item 3");
}
[Test]
public void TestIarV0_1WithEscapedChars()
{
TestHelper.InMethod();
// log4net.Config.XmlConfigurator.Configure();
string itemName = "You & you are a mean/man/";
string humanEscapedItemName = @"You & you are a mean\/man\/";
string userPassword = "meowfood";
InventoryArchiverModule archiverModule = new InventoryArchiverModule(true);
Scene scene = SceneSetupHelpers.SetupScene("Inventory");
SceneSetupHelpers.SetupSceneModules(scene, archiverModule);
CommunicationsManager cm = scene.CommsManager;
// Create user
string userFirstName = "Jock";
string userLastName = "Stirrup";
UUID userId = UUID.Parse("00000000-0000-0000-0000-000000000020");
lock (this)
{
UserProfileTestUtils.CreateUserWithInventory(
cm, userFirstName, userLastName, userPassword, userId, InventoryReceived);
Monitor.Wait(this, 60000);
}
// Create asset
SceneObjectGroup object1;
SceneObjectPart part1;
{
string partName = "part name";
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);
}
UUID asset1Id = UUID.Parse("00000000-0000-0000-0000-000000000060");
AssetBase asset1 = AssetHelpers.CreateAsset(asset1Id, object1);
scene.AssetService.Store(asset1);
// Create item
UUID item1Id = UUID.Parse("00000000-0000-0000-0000-000000000080");
InventoryItemBase item1 = new InventoryItemBase();
item1.Name = itemName;
item1.AssetID = asset1.FullID;
item1.ID = item1Id;
InventoryFolderBase objsFolder
= InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, userId, "Objects");
item1.Folder = objsFolder.ID;
scene.AddInventoryItem(userId, item1);
MemoryStream archiveWriteStream = new MemoryStream();
archiverModule.OnInventoryArchiveSaved += SaveCompleted;
mre.Reset();
archiverModule.ArchiveInventory(
Guid.NewGuid(), userFirstName, userLastName, "Objects", userPassword, archiveWriteStream);
mre.WaitOne(60000, false);
// LOAD ITEM
MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray());
archiverModule.DearchiveInventory(userFirstName, userLastName, "Scripts", userPassword, archiveReadStream);
InventoryItemBase foundItem1
= InventoryArchiveUtils.FindItemByPath(
scene.InventoryService, userId, "Scripts/Objects/" + humanEscapedItemName);
Assert.That(foundItem1, Is.Not.Null, "Didn't find loaded item 1");
// Assert.That(
// foundItem1.CreatorId, Is.EqualTo(userUuid),
// "Loaded item non-uuid creator doesn't match that of the loading user");
Assert.That(
foundItem1.Name, Is.EqualTo(itemName),
"Loaded item name doesn't match saved name");
}
/// <summary>
/// Test loading a V0.1 OpenSim Inventory Archive (subject to change since there is no fixed format yet) where
/// embedded creators do not exist in the system
@ -302,7 +388,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
{
TestHelper.InMethod();
log4net.Config.XmlConfigurator.Configure();
//log4net.Config.XmlConfigurator.Configure();
string userFirstName = "Charlie";
string userLastName = "Chan";
@ -370,7 +456,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
{
TestHelper.InMethod();
log4net.Config.XmlConfigurator.Configure();
//log4net.Config.XmlConfigurator.Configure();
string userFirstName = "Dennis";
string userLastName = "Menace";

View File

@ -0,0 +1,37 @@
using OpenSim.Region.CoreModules.Framework.Monitoring.Monitors;
namespace OpenSim.Region.CoreModules.Framework.Monitoring.Alerts
{
class DeadlockAlert : IAlert
{
private LastFrameTimeMonitor m_monitor;
public DeadlockAlert(LastFrameTimeMonitor m_monitor)
{
this.m_monitor = m_monitor;
}
#region Implementation of IAlert
public string GetName()
{
return "Potential Deadlock Alert";
}
public void Test()
{
if (m_monitor.GetValue() > 60 * 1000)
{
if(OnTriggerAlert != null)
{
OnTriggerAlert(typeof (DeadlockAlert),
(int) (m_monitor.GetValue()/1000) + " second(s) since last frame processed.", true);
}
}
}
public event Alert OnTriggerAlert;
#endregion
}
}

View File

@ -0,0 +1,13 @@
using System;
namespace OpenSim.Region.CoreModules.Framework.Monitoring
{
internal delegate void Alert(Type reporter, string reason, bool fatal);
interface IAlert
{
string GetName();
void Test();
event Alert OnTriggerAlert;
}
}

View File

@ -0,0 +1,9 @@
namespace OpenSim.Region.CoreModules.Framework.Monitoring
{
interface IMonitor
{
double GetValue();
string GetName();
string GetFriendlyValue(); // Convert to readable numbers
}
}

View File

@ -0,0 +1,146 @@
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.CoreModules.Framework.Monitoring.Alerts;
using OpenSim.Region.CoreModules.Framework.Monitoring.Monitors;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.Framework.Monitoring
{
public class MonitorModule : IRegionModule
{
private Scene m_scene;
private readonly List<IMonitor> m_monitors = new List<IMonitor>();
private readonly List<IAlert> m_alerts = new List<IAlert>();
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public void DebugMonitors(string module, string[] args)
{
foreach (IMonitor monitor in m_monitors)
{
m_log.Info("[MonitorModule] " + m_scene.RegionInfo.RegionName + " reports " + monitor.GetName() + " = " + monitor.GetFriendlyValue());
}
}
public void TestAlerts()
{
foreach (IAlert alert in m_alerts)
{
alert.Test();
}
}
#region Implementation of IRegionModule
public void Initialise(Scene scene, IConfigSource source)
{
m_scene = scene;
m_scene.AddCommand(this, "monitor report",
"monitor report",
"Returns a variety of statistics about the current region and/or simulator",
DebugMonitors);
MainServer.Instance.AddHTTPHandler("/monitorstats/" + m_scene.RegionInfo.RegionID + "/", StatsPage);
}
public Hashtable StatsPage(Hashtable request)
{
// If request was for a specific monitor
// eg url/?monitor=Monitor.Name
if (request.ContainsKey("monitor"))
{
string monID = (string) request["monitor"];
foreach (IMonitor monitor in m_monitors)
{
if (monitor.ToString() == monID)
{
Hashtable ereply3 = new Hashtable();
ereply3["int_response_code"] = 404; // 200 OK
ereply3["str_response_string"] = monitor.GetValue().ToString();
ereply3["content_type"] = "text/plain";
return ereply3;
}
}
// No monitor with that name
Hashtable ereply2 = new Hashtable();
ereply2["int_response_code"] = 404; // 200 OK
ereply2["str_response_string"] = "No such monitor";
ereply2["content_type"] = "text/plain";
return ereply2;
}
string xml = "<data>";
foreach (IMonitor monitor in m_monitors)
{
xml += "<" + monitor.ToString() + ">" + monitor.GetValue() + "</" + monitor.ToString() + ">";
}
xml += "</data>";
Hashtable ereply = new Hashtable();
ereply["int_response_code"] = 200; // 200 OK
ereply["str_response_string"] = xml;
ereply["content_type"] = "text/xml";
return ereply;
}
public void PostInitialise()
{
m_monitors.Add(new AgentCountMonitor(m_scene));
m_monitors.Add(new ChildAgentCountMonitor(m_scene));
m_monitors.Add(new GCMemoryMonitor());
m_monitors.Add(new ObjectCountMonitor(m_scene));
m_monitors.Add(new PhysicsFrameMonitor(m_scene));
m_monitors.Add(new PhysicsUpdateFrameMonitor(m_scene));
m_monitors.Add(new PWSMemoryMonitor());
m_monitors.Add(new ThreadCountMonitor());
m_monitors.Add(new TotalFrameMonitor(m_scene));
m_monitors.Add(new EventFrameMonitor(m_scene));
m_monitors.Add(new LandFrameMonitor(m_scene));
m_monitors.Add(new LastFrameTimeMonitor(m_scene));
m_alerts.Add(new DeadlockAlert(m_monitors.Find(x => x is LastFrameTimeMonitor) as LastFrameTimeMonitor));
foreach (IAlert alert in m_alerts)
{
alert.OnTriggerAlert += OnTriggerAlert;
}
}
void OnTriggerAlert(System.Type reporter, string reason, bool fatal)
{
m_log.Error("[Monitor] " + reporter.Name + " for " + m_scene.RegionInfo.RegionName + " reports " + reason + " (Fatal: " + fatal + ")");
}
public void Close()
{
}
public string Name
{
get { return "Region Health Monitoring Module"; }
}
public bool IsSharedModule
{
get { return false; }
}
#endregion
}
}

View File

@ -0,0 +1,33 @@
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.Framework.Monitoring.Monitors
{
class AgentCountMonitor : IMonitor
{
private readonly Scene m_scene;
public AgentCountMonitor(Scene scene)
{
m_scene = scene;
}
#region Implementation of IMonitor
public double GetValue()
{
return m_scene.SceneGraph.GetRootAgentCount();
}
public string GetName()
{
return "Root Agent Count";
}
public string GetFriendlyValue()
{
return (int)GetValue() + " agent(s)";
}
#endregion
}
}

View File

@ -0,0 +1,33 @@
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.Framework.Monitoring.Monitors
{
class ChildAgentCountMonitor : IMonitor
{
private readonly Scene m_scene;
public ChildAgentCountMonitor(Scene scene)
{
m_scene = scene;
}
#region Implementation of IMonitor
public double GetValue()
{
return m_scene.SceneGraph.GetChildAgentCount();
}
public string GetName()
{
return "Child Agent Count";
}
public string GetFriendlyValue()
{
return (int)GetValue() + " child agent(s)";
}
#endregion
}
}

View File

@ -0,0 +1,33 @@
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.Framework.Monitoring.Monitors
{
class EventFrameMonitor : IMonitor
{
private readonly Scene m_scene;
public EventFrameMonitor(Scene scene)
{
m_scene = scene;
}
#region Implementation of IMonitor
public double GetValue()
{
return m_scene.MonitorEventTime;
}
public string GetName()
{
return "Total Event Frame Time";
}
public string GetFriendlyValue()
{
return (int)GetValue() + "ms";
}
#endregion
}
}

View File

@ -0,0 +1,26 @@
using System;
namespace OpenSim.Region.CoreModules.Framework.Monitoring.Monitors
{
class GCMemoryMonitor : IMonitor
{
#region Implementation of IMonitor
public double GetValue()
{
return GC.GetTotalMemory(false);
}
public string GetName()
{
return "GC Reported Memory";
}
public string GetFriendlyValue()
{
return (int)(GetValue() / (1024*1024)) + "MB (Global)";
}
#endregion
}
}

View File

@ -0,0 +1,33 @@
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.Framework.Monitoring.Monitors
{
class LandFrameMonitor : IMonitor
{
private readonly Scene m_scene;
public LandFrameMonitor(Scene scene)
{
m_scene = scene;
}
#region Implementation of IMonitor
public double GetValue()
{
return m_scene.MonitorLandTime;
}
public string GetName()
{
return "Land Frame Time";
}
public string GetFriendlyValue()
{
return (int)GetValue() + "ms";
}
#endregion
}
}

View File

@ -0,0 +1,34 @@
using System;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.Framework.Monitoring.Monitors
{
class LastFrameTimeMonitor : IMonitor
{
private readonly Scene m_scene;
public LastFrameTimeMonitor(Scene scene)
{
m_scene = scene;
}
#region Implementation of IMonitor
public double GetValue()
{
return Environment.TickCount - m_scene.MonitorLastFrameTick;
}
public string GetName()
{
return "Last Completed Frame At";
}
public string GetFriendlyValue()
{
return (int)GetValue() + "ms ago";
}
#endregion
}
}

View File

@ -0,0 +1,33 @@
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.Framework.Monitoring.Monitors
{
class ObjectCountMonitor : IMonitor
{
private readonly Scene m_scene;
public ObjectCountMonitor(Scene scene)
{
m_scene = scene;
}
#region Implementation of IMonitor
public double GetValue()
{
return m_scene.SceneGraph.GetTotalObjectsCount();
}
public string GetName()
{
return "Total Objects Count";
}
public string GetFriendlyValue()
{
return (int)GetValue() + " Object(s)";
}
#endregion
}
}

View File

@ -0,0 +1,26 @@
using System;
namespace OpenSim.Region.CoreModules.Framework.Monitoring.Monitors
{
class PWSMemoryMonitor : IMonitor
{
#region Implementation of IMonitor
public double GetValue()
{
return System.Diagnostics.Process.GetCurrentProcess().PrivateMemorySize64;
}
public string GetName()
{
return "Private Working Set Memory";
}
public string GetFriendlyValue()
{
return (int)(GetValue() / (1024 * 1024)) + "MB (Global)";
}
#endregion
}
}

View File

@ -0,0 +1,33 @@
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.Framework.Monitoring.Monitors
{
class PhysicsFrameMonitor : IMonitor
{
private readonly Scene m_scene;
public PhysicsFrameMonitor(Scene scene)
{
m_scene = scene;
}
#region Implementation of IMonitor
public double GetValue()
{
return m_scene.MonitorPhysicsSyncTime + m_scene.MonitorPhysicsUpdateTime;
}
public string GetName()
{
return "Total Physics Frame Time";
}
public string GetFriendlyValue()
{
return (int)GetValue() + "ms";
}
#endregion
}
}

View File

@ -0,0 +1,33 @@
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.Framework.Monitoring.Monitors
{
class PhysicsUpdateFrameMonitor : IMonitor
{
private readonly Scene m_scene;
public PhysicsUpdateFrameMonitor(Scene scene)
{
m_scene = scene;
}
#region Implementation of IMonitor
public double GetValue()
{
return m_scene.MonitorPhysicsUpdateTime;
}
public string GetName()
{
return "Physics Update Frame Time";
}
public string GetFriendlyValue()
{
return (int)GetValue() + "ms";
}
#endregion
}
}

View File

@ -0,0 +1,25 @@

namespace OpenSim.Region.CoreModules.Framework.Monitoring.Monitors
{
class ThreadCountMonitor : IMonitor
{
#region Implementation of IMonitor
public double GetValue()
{
return System.Diagnostics.Process.GetCurrentProcess().Threads.Count;
}
public string GetName()
{
return "Total Threads";
}
public string GetFriendlyValue()
{
return (int)GetValue() + " Thread(s) (Global)";
}
#endregion
}
}

View File

@ -0,0 +1,33 @@
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.Framework.Monitoring.Monitors
{
class TotalFrameMonitor : IMonitor
{
private readonly Scene m_scene;
public TotalFrameMonitor(Scene scene)
{
m_scene = scene;
}
#region Implementation of IMonitor
public double GetValue()
{
return m_scene.MonitorFrameTime;
}
public string GetName()
{
return "Total Frame Time";
}
public string GetFriendlyValue()
{
return (int)GetValue() + "ms";
}
#endregion
}
}

View File

@ -193,6 +193,10 @@ namespace OpenSim.Region.CoreModules.Hypergrid
{
return scene.RegionInfo;
}
else if (m_scenes.Count > 0)
{
return m_scenes[0].RegionInfo;
}
return null;
}
@ -248,7 +252,7 @@ namespace OpenSim.Region.CoreModules.Hypergrid
{
foreach (Scene nextScene in m_scenes)
{
if (nextScene.RegionInfo.RegionName == regionName)
if (nextScene.RegionInfo.RegionName.Equals(regionName, StringComparison.InvariantCultureIgnoreCase))
{
scene = nextScene;
return true;

View File

@ -13,7 +13,6 @@
<RegionModule id="ArchiverModule" type="OpenSim.Region.CoreModules.World.Archiver.ArchiverModule" />
<RegionModule id="CapabilitiesModule" type="OpenSim.Region.CoreModules.Agent.Capabilities.CapabilitiesModule" />
<RegionModule id="TerrainModule" type="OpenSim.Region.CoreModules.World.Terrain.TerrainModule" />
<RegionModule id="RegionCombinerModule" type="OpenSim.Region.CoreModules.World.Land.RegionCombinerModule" />
<RegionModule id="WorldMapModule" type="OpenSim.Region.CoreModules.World.WorldMap.WorldMapModule" />
<RegionModule id="HGWorldMapModule" type="OpenSim.Region.CoreModules.Hypergrid.HGWorldMapModule" />
<RegionModule id="UrlModule" type="OpenSim.Region.CoreModules.Scripting.LSLHttp.UrlModule" />

View File

@ -311,11 +311,8 @@ namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture
}
// Create a new asset for user
AssetBase asset = new AssetBase();
asset.FullID = UUID.Random();
AssetBase asset = new AssetBase(UUID.Random(), "DynamicImage" + Util.RandomClass.Next(1, 10000), (sbyte)AssetType.Texture);
asset.Data = assetData;
asset.Name = "DynamicImage" + Util.RandomClass.Next(1, 10000);
asset.Type = 0;
asset.Description = String.Format("URL image : {0}", Url);
asset.Local = false;
asset.Temporary = ((Disp & DISP_TEMP) != 0);

View File

@ -689,7 +689,7 @@ namespace OpenSim.Region.CoreModules.Scripting.XMLRPC
}
if (respParms.Contains("IntValue"))
{
Idata = Convert.ToInt32((string) respParms["IntValue"]);
Idata = Convert.ToInt32(respParms["IntValue"]);
}
if (respParms.Contains("faultString"))
{

View File

@ -118,7 +118,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsIn.Grid
m_log.Info("[HypergridService]: Starting...");
Object[] args = new Object[] { m_Config, MainServer.Instance };
// Object[] args = new Object[] { m_Config, MainServer.Instance };
m_HypergridHandler = new HypergridServiceInConnector(m_Config, MainServer.Instance, scene.RequestModuleInterface<IHyperlinkService>());
//ServerUtils.LoadPlugin<HypergridServiceInConnector>("OpenSim.Server.Handlers.dll:HypergridServiceInConnector", args);

View File

@ -322,10 +322,12 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
{
List<GridRegion> rinfos = new List<GridRegion>();
// Commenting until regionname exists
//foreach (SimpleRegionInfo r in m_HyperlinkRegions.Values)
// if ((r.RegionName != null) && r.RegionName.StartsWith(name))
// rinfos.Add(r);
if (name == string.Empty)
return rinfos;
foreach (GridRegion r in m_HyperlinkRegions.Values)
if ((r.RegionName != null) && r.RegionName.ToLower().StartsWith(name.ToLower()))
rinfos.Add(r);
rinfos.AddRange(m_GridServiceConnector.GetRegionsByName(scopeID, name, maxNumber));
return rinfos;
@ -334,7 +336,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
public List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax)
{
int snapXmin = (int)(xmin / Constants.RegionSize) * (int)Constants.RegionSize;
int snapXmax = (int)(xmax / Constants.RegionSize) * (int)Constants.RegionSize;
// int snapXmax = (int)(xmax / Constants.RegionSize) * (int)Constants.RegionSize;
int snapYmin = (int)(ymin / Constants.RegionSize) * (int)Constants.RegionSize;
int snapYmax = (int)(ymax / Constants.RegionSize) * (int)Constants.RegionSize;
@ -602,13 +604,16 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
{
CachedUserInfo uinfo = m_aScene.CommsManager.UserProfileCacheService.GetUserDetails(agentData.AgentID);
if (uinfo == null)
return false;
if ((IsLocalUser(uinfo) && (GetHyperlinkRegion(regInfo.RegionHandle) != null)) ||
(!IsLocalUser(uinfo) && !IsGoingHome(uinfo, regInfo)))
{
m_log.Info("[HGrid]: Local user is going to foreign region or foreign user is going elsewhere");
// Set the position of the region on the remote grid
ulong realHandle = FindRegionHandle(regInfo.RegionHandle);
// ulong realHandle = FindRegionHandle(regInfo.RegionHandle);
uint x = 0, y = 0;
Utils.LongToUInts(regInfo.RegionHandle, out x, out y);
GridRegion clonedRegion = new GridRegion(regInfo);
@ -735,6 +740,9 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
// Is the user going back to the home region or the home grid?
protected bool IsGoingHome(CachedUserInfo uinfo, GridRegion rinfo)
{
if (uinfo == null)
return false;
if (uinfo.UserProfile == null)
return false;

View File

@ -129,6 +129,9 @@ namespace OpenSim.Region.CoreModules.World.Archiver
successfulAssetRestores++;
else
failedAssetRestores++;
if ((successfulAssetRestores + failedAssetRestores) % 250 == 0)
m_log.Debug("[ARCHIVER]: Loaded " + successfulAssetRestores + " assets and failed to load " + failedAssetRestores + " assets...");
}
else if (!m_merge && filePath.StartsWith(ArchiveConstants.TERRAINS_PATH))
{
@ -329,10 +332,12 @@ namespace OpenSim.Region.CoreModules.World.Archiver
{
sbyte assetType = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension];
if (assetType == (sbyte)AssetType.Unknown)
m_log.WarnFormat("[ARCHIVER]: Importing {0} byte asset {1} with unknown type", data.Length, uuid);
//m_log.DebugFormat("[ARCHIVER]: Importing asset {0}, type {1}", uuid, assetType);
AssetBase asset = new AssetBase(new UUID(uuid), String.Empty);
asset.Type = assetType;
AssetBase asset = new AssetBase(new UUID(uuid), String.Empty, assetType);
asset.Data = data;
// We're relying on the asset service to do the sensible thing and not store the asset if it already

View File

@ -158,9 +158,8 @@ namespace OpenSim.Region.CoreModules.World.Archiver
m_log.DebugFormat("[ARCHIVER]: Importing asset {0}", filename);
AssetBase asset = new AssetBase(new UUID(filename), metadata.Name);
AssetBase asset = new AssetBase(new UUID(filename), metadata.Name, metadata.AssetType);
asset.Description = metadata.Description;
asset.Type = metadata.AssetType;
asset.Data = data;
m_cache.Store(asset);

View File

@ -52,16 +52,11 @@ namespace OpenSim.Region.CoreModules.World.Estate
public EstateTerrainXferHandler(IClientAPI pRemoteClient, string pClientFilename)
{
m_asset = new AssetBase();
m_asset.FullID = UUID.Zero;
m_asset.Type = type;
m_asset = new AssetBase(UUID.Zero, pClientFilename, type);
m_asset.Data = new byte[0];
m_asset.Name = pClientFilename;
m_asset.Description = "empty";
m_asset.Local = true;
m_asset.Temporary = true;
}
public ulong XferID

View File

@ -1059,9 +1059,11 @@ namespace OpenSim.Region.CoreModules.World.Land
if (m_scene.Permissions.IsGod(remote_client.AgentId))
{
land.LandData.OwnerID = ownerID;
land.LandData.GroupID = UUID.Zero;
land.LandData.IsGroupOwned = false;
m_scene.ForEachClient(SendParcelOverlay);
land.SendLandUpdateToClient(remote_client);
land.SendLandUpdateToClient(true, remote_client);
}
}
}
@ -1082,8 +1084,10 @@ namespace OpenSim.Region.CoreModules.World.Land
land.LandData.OwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner;
else
land.LandData.OwnerID = m_scene.RegionInfo.MasterAvatarAssignedUUID;
land.LandData.GroupID = UUID.Zero;
land.LandData.IsGroupOwned = false;
m_scene.ForEachClient(SendParcelOverlay);
land.SendLandUpdateToClient(remote_client);
land.SendLandUpdateToClient(true, remote_client);
}
}
}
@ -1105,9 +1109,10 @@ namespace OpenSim.Region.CoreModules.World.Land
else
land.LandData.OwnerID = m_scene.RegionInfo.MasterAvatarAssignedUUID;
land.LandData.ClaimDate = Util.UnixTimeSinceEpoch();
land.LandData.GroupID = UUID.Zero;
land.LandData.IsGroupOwned = false;
m_scene.ForEachClient(SendParcelOverlay);
land.SendLandUpdateToClient(remote_client);
land.SendLandUpdateToClient(true, remote_client);
}
}
}

View File

@ -49,6 +49,8 @@ namespace OpenSim.Region.CoreModules.World.Land
#pragma warning restore 0429
private bool[,] m_landBitmap = new bool[landArrayMax,landArrayMax];
private int m_lastSeqId = 0;
protected LandData m_landData = new LandData();
protected Scene m_scene;
protected List<SceneObjectGroup> primsOverMe = new List<SceneObjectGroup>();
@ -81,6 +83,10 @@ namespace OpenSim.Region.CoreModules.World.Land
{
m_scene = scene;
LandData.OwnerID = owner_id;
if (is_group_owned)
LandData.GroupID = owner_id;
else
LandData.GroupID = UUID.Zero;
LandData.IsGroupOwned = is_group_owned;
}
@ -172,7 +178,19 @@ namespace OpenSim.Region.CoreModules.World.Land
// regionFlags |= (uint)RegionFlags.AllowLandmark;
// if (landData.OwnerID == remote_client.AgentId)
// regionFlags |= (uint)RegionFlags.AllowSetHome;
remote_client.SendLandProperties(sequence_id,
int seq_id;
if (snap_selection && (sequence_id == 0))
{
seq_id = m_lastSeqId;
}
else
{
seq_id = sequence_id;
m_lastSeqId = seq_id;
}
remote_client.SendLandProperties(seq_id,
snap_selection, request_result, LandData,
(float)m_scene.RegionInfo.RegionSettings.ObjectBonus,
GetParcelMaxPrimCount(this),
@ -184,6 +202,7 @@ namespace OpenSim.Region.CoreModules.World.Land
if (m_scene.Permissions.CanEditParcel(remote_client.AgentId,this))
{
//Needs later group support
bool snap_selection = false;
LandData newData = LandData.Copy();
if (args.AuthBuyerID != newData.AuthBuyerID || args.SalePrice != newData.SalePrice)
@ -192,6 +211,7 @@ namespace OpenSim.Region.CoreModules.World.Land
{
newData.AuthBuyerID = args.AuthBuyerID;
newData.SalePrice = args.SalePrice;
snap_selection = true;
}
}
newData.Category = args.Category;
@ -212,7 +232,7 @@ namespace OpenSim.Region.CoreModules.World.Land
m_scene.LandChannel.UpdateLandObject(LandData.LocalID, newData);
SendLandUpdateToAvatarsOverMe();
SendLandUpdateToAvatarsOverMe(snap_selection);
}
}
@ -230,7 +250,7 @@ namespace OpenSim.Region.CoreModules.World.Land
newData.Flags &= ~(uint) (ParcelFlags.ForSale | ParcelFlags.ForSaleObjects | ParcelFlags.SellParcelObjects);
m_scene.LandChannel.UpdateLandObject(LandData.LocalID, newData);
SendLandUpdateToAvatarsOverMe();
SendLandUpdateToAvatarsOverMe(true);
}
public void DeedToGroup(UUID groupID)
@ -242,7 +262,7 @@ namespace OpenSim.Region.CoreModules.World.Land
m_scene.LandChannel.UpdateLandObject(LandData.LocalID, newData);
SendLandUpdateToAvatarsOverMe();
SendLandUpdateToAvatarsOverMe(true);
}
public bool IsEitherBannedOrRestricted(UUID avatar)
@ -297,7 +317,17 @@ namespace OpenSim.Region.CoreModules.World.Land
SendLandProperties(0, false, 0, remote_client);
}
public void SendLandUpdateToClient(bool snap_selection, IClientAPI remote_client)
{
SendLandProperties(0, snap_selection, 0, remote_client);
}
public void SendLandUpdateToAvatarsOverMe()
{
SendLandUpdateToAvatarsOverMe(false);
}
public void SendLandUpdateToAvatarsOverMe(bool snap_selection)
{
List<ScenePresence> avatars = m_scene.GetAvatars();
ILandObject over = null;
@ -325,7 +355,7 @@ namespace OpenSim.Region.CoreModules.World.Land
else
avatars[i].Invulnerable = true;
SendLandUpdateToClient(avatars[i].ControllingClient);
SendLandUpdateToClient(snap_selection, avatars[i].ControllingClient);
}
}
}

View File

@ -144,6 +144,8 @@ namespace OpenSim.Region.CoreModules.World.Permissions
private Dictionary<string, bool> GrantVB = new Dictionary<string, bool>();
private Dictionary<string, bool> GrantJS = new Dictionary<string, bool>();
private Dictionary<string, bool> GrantYP = new Dictionary<string, bool>();
private IFriendsModule m_friendsModule = null;
#endregion
#region IRegionModule Members
@ -363,6 +365,12 @@ namespace OpenSim.Region.CoreModules.World.Permissions
public void PostInitialise()
{
m_friendsModule = m_scene.RequestModuleInterface<IFriendsModule>();
if (m_friendsModule == null)
m_log.Error("[PERMISSIONS]: Friends module not found, friend permissions will not work");
else
m_log.Info("[PERMISSIONS]: Friends module found, friend permissions enabled");
}
public void Close()
@ -476,6 +484,24 @@ namespace OpenSim.Region.CoreModules.World.Permissions
return false;
}
protected bool IsFriendWithPerms(UUID user,UUID objectOwner)
{
if (user == UUID.Zero)
return false;
if (m_friendsModule == null)
return false;
List<FriendListItem> profile = m_friendsModule.GetUserFriends(user);
foreach (FriendListItem item in profile)
{
if(item.Friend == objectOwner && (item.FriendPerms & (uint)FriendRights.CanModifyObjects) != 0)
return true;
}
return false;
}
protected bool IsEstateManager(UUID user)
{
@ -566,6 +592,9 @@ namespace OpenSim.Region.CoreModules.World.Permissions
if (user == objectOwner)
return objectOwnerMask;
if (IsFriendWithPerms(user, objectOwner))
return objectOwnerMask;
// Estate users should be able to edit anything in the sim
if (IsEstateManager(user) && m_RegionOwnerIsGod && !IsAdministrator(objectOwner))
return objectOwnerMask;

View File

@ -1077,14 +1077,12 @@ namespace OpenSim.Region.CoreModules.World.WorldMap
m_scene.RegionInfo.RegionSettings.TerrainImageID = TerrainImageUUID;
AssetBase asset = new AssetBase();
asset.FullID = m_scene.RegionInfo.RegionSettings.TerrainImageID;
AssetBase asset = new AssetBase(
m_scene.RegionInfo.RegionSettings.TerrainImageID,
"terrainImage_" + m_scene.RegionInfo.RegionID.ToString() + "_" + lastMapRefresh.ToString(),
(sbyte)AssetType.Texture);
asset.Data = data;
asset.Name
= "terrainImage_" + m_scene.RegionInfo.RegionID.ToString() + "_" + lastMapRefresh.ToString();
asset.Description = m_scene.RegionInfo.RegionName;
asset.Type = 0;
asset.Temporary = temporary;
m_scene.AssetService.Store(asset);
}

View File

@ -179,6 +179,7 @@ namespace OpenSim.Region.Examples.SimpleModule
public event FriendActionDelegate OnApproveFriendRequest;
public event FriendActionDelegate OnDenyFriendRequest;
public event FriendshipTermination OnTerminateFriendship;
public event GrantUserFriendRights OnGrantUserRights;
public event EconomyDataRequest OnEconomyDataRequest;
public event MoneyBalanceRequest OnMoneyBalanceRequest;
@ -538,6 +539,7 @@ namespace OpenSim.Region.Examples.SimpleModule
public virtual void SendInventoryFolderDetails(UUID ownerID, UUID folderID,
List<InventoryItemBase> items,
List<InventoryFolderBase> folders,
int version,
bool fetchFolders,
bool fetchItems)
{

View File

@ -27,6 +27,7 @@
using OpenMetaverse;
using OpenSim.Framework;
using System.Collections.Generic;
namespace OpenSim.Region.Framework.Interfaces
{
@ -45,5 +46,6 @@ namespace OpenSim.Region.Framework.Interfaces
/// </param>
/// <param name="offerMessage"></param>
void OfferFriendship(UUID fromUserId, IClientAPI toUserClient, string offerMessage);
List<FriendListItem> GetUserFriends(UUID agentID);
}
}

View File

@ -54,6 +54,7 @@ namespace OpenSim.Region.Framework.Interfaces
bool IsBannedFromLand(UUID avatar);
bool IsRestrictedFromLand(UUID avatar);
void SendLandUpdateToClient(IClientAPI remote_client);
void SendLandUpdateToClient(bool snap_selection, IClientAPI remote_client);
List<UUID> CreateAccessListArrayByFlag(AccessList flag);
void SendAccessList(UUID agentID, UUID sessionID, uint flags, int sequenceID, IClientAPI remote_client);
void UpdateAccessList(uint flags, List<ParcelManager.ParcelAccessEntry> entries, IClientAPI remote_client);

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