diff --git a/CONTRIBUTORS.txt b/CONTRIBUTORS.txt index 38343a4bbc..a0af1ca941 100644 --- a/CONTRIBUTORS.txt +++ b/CONTRIBUTORS.txt @@ -28,7 +28,7 @@ people that make the day to day of OpenSim happen. * Diva (Crista Lopes, University of California, Irvine) * nlin (3Di) * Arthur Rodrigo S Valadares (IBM) - +* BlueWall (James Hughes) = Past Open Sim Developers = These folks are alumns of the OpenSim core group, but are now diff --git a/OpenSim/ApplicationPlugins/LoadRegions/LoadRegionsPlugin.cs b/OpenSim/ApplicationPlugins/LoadRegions/LoadRegionsPlugin.cs index 7ef0f5f455..f37c399050 100644 --- a/OpenSim/ApplicationPlugins/LoadRegions/LoadRegionsPlugin.cs +++ b/OpenSim/ApplicationPlugins/LoadRegions/LoadRegionsPlugin.cs @@ -122,9 +122,11 @@ namespace OpenSim.ApplicationPlugins.LoadRegions m_log.Debug("[LOADREGIONS]: Creating Region: " + regionsToLoad[i].RegionName + " (ThreadID: " + Thread.CurrentThread.ManagedThreadId.ToString() + ")"); + m_openSim.PopulateRegionEstateInfo(regionsToLoad[i]); m_openSim.CreateRegion(regionsToLoad[i], true, out scene); regionsToLoad[i].EstateSettings.Save(); + if (scene != null) { m_newRegionCreatedHandler = OnNewRegionCreated; diff --git a/OpenSim/ApplicationPlugins/Rest/Inventory/RestAppearanceServices.cs b/OpenSim/ApplicationPlugins/Rest/Inventory/RestAppearanceServices.cs index 019ca73dd1..0188eb716e 100644 --- a/OpenSim/ApplicationPlugins/Rest/Inventory/RestAppearanceServices.cs +++ b/OpenSim/ApplicationPlugins/Rest/Inventory/RestAppearanceServices.cs @@ -44,7 +44,7 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory // private static readonly int PARM_PATH = 1; - private bool enabled = false; +// private bool enabled = false; private string qPrefix = "appearance"; /// @@ -74,7 +74,7 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory // Activate if everything went OK - enabled = true; +// enabled = true; Rest.Log.InfoFormat("{0} User appearance services initialization complete", MsgId); } @@ -95,7 +95,7 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory public void Close() { - enabled = false; +// enabled = false; Rest.Log.InfoFormat("{0} User appearance services closing down", MsgId); } diff --git a/OpenSim/ApplicationPlugins/Rest/Inventory/RestInventoryServices.cs b/OpenSim/ApplicationPlugins/Rest/Inventory/RestInventoryServices.cs index c3cf08c18d..536f167793 100644 --- a/OpenSim/ApplicationPlugins/Rest/Inventory/RestInventoryServices.cs +++ b/OpenSim/ApplicationPlugins/Rest/Inventory/RestInventoryServices.cs @@ -46,12 +46,12 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory public class RestInventoryServices : IRest { // private static readonly int PARM_USERID = 0; - private static readonly int PARM_PATH = 1; +// private static readonly int PARM_PATH = 1; // private bool enabled = false; private string qPrefix = "inventory"; - private static readonly string PRIVATE_ROOT_NAME = "My Inventory"; +// private static readonly string PRIVATE_ROOT_NAME = "My Inventory"; /// /// The constructor makes sure that the service prefix is absolute @@ -2129,17 +2129,17 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory } catch (DllNotFoundException) { - Rest.Log.ErrorFormat("OpenJpeg is not installed correctly on this system. Asset Data is emtpy for {0}", ic.Item.Name); + Rest.Log.ErrorFormat("OpenJpeg is not installed correctly on this system. Asset Data is empty for {0}", ic.Item.Name); ic.Asset.Data = new Byte[0]; } catch (IndexOutOfRangeException) { - Rest.Log.ErrorFormat("OpenJpeg was unable to encode this. Asset Data is emtpy for {0}", ic.Item.Name); + Rest.Log.ErrorFormat("OpenJpeg was unable to encode this. Asset Data is empty for {0}", ic.Item.Name); ic.Asset.Data = new Byte[0]; } catch (Exception) { - Rest.Log.ErrorFormat("OpenJpeg was unable to encode this. Asset Data is emtpy for {0}", ic.Item.Name); + Rest.Log.ErrorFormat("OpenJpeg was unable to encode this. Asset Data is empty for {0}", ic.Item.Name); ic.Asset.Data = new Byte[0]; } } diff --git a/OpenSim/Data/MySQL/MySQLAssetData.cs b/OpenSim/Data/MySQL/MySQLAssetData.cs index 0b0a6385d0..94e2da4d25 100644 --- a/OpenSim/Data/MySQL/MySQLAssetData.cs +++ b/OpenSim/Data/MySQL/MySQLAssetData.cs @@ -47,6 +47,11 @@ namespace OpenSim.Data.MySQL private string m_connectionString; private object m_dbLock = new object(); + protected virtual Assembly Assembly + { + get { return GetType().Assembly; } + } + #region IPlugin Members public override string Version { get { return "1.0.0.0"; } } @@ -66,13 +71,10 @@ namespace OpenSim.Data.MySQL { m_connectionString = connect; - // This actually does the roll forward assembly stuff - Assembly assem = GetType().Assembly; - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); - Migration m = new Migration(dbcon, assem, "AssetStore"); + Migration m = new Migration(dbcon, Assembly, "AssetStore"); m.Update(); } } diff --git a/OpenSim/Data/MySQL/MySQLAuthenticationData.cs b/OpenSim/Data/MySQL/MySQLAuthenticationData.cs index 5056aee6c1..8d82f61bda 100644 --- a/OpenSim/Data/MySQL/MySQLAuthenticationData.cs +++ b/OpenSim/Data/MySQL/MySQLAuthenticationData.cs @@ -28,6 +28,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Reflection; using System.Data; using OpenMetaverse; using OpenSim.Framework; @@ -42,6 +43,11 @@ namespace OpenSim.Data.MySQL private int m_LastExpire; // private string m_connectionString; + protected virtual Assembly Assembly + { + get { return GetType().Assembly; } + } + public MySqlAuthenticationData(string connectionString, string realm) : base(connectionString) { @@ -51,7 +57,7 @@ namespace OpenSim.Data.MySQL using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); - Migration m = new Migration(dbcon, GetType().Assembly, "AuthStore"); + Migration m = new Migration(dbcon, Assembly, "AuthStore"); m.Update(); } } diff --git a/OpenSim/Data/MySQL/MySQLEstateData.cs b/OpenSim/Data/MySQL/MySQLEstateData.cs index c42c687ed9..de72a6a931 100644 --- a/OpenSim/Data/MySQL/MySQLEstateData.cs +++ b/OpenSim/Data/MySQL/MySQLEstateData.cs @@ -54,6 +54,11 @@ namespace OpenSim.Data.MySQL private Dictionary m_FieldMap = new Dictionary(); + protected virtual Assembly Assembly + { + get { return GetType().Assembly; } + } + public MySQLEstateStore() { } @@ -82,8 +87,7 @@ namespace OpenSim.Data.MySQL { dbcon.Open(); - Assembly assem = GetType().Assembly; - Migration m = new Migration(dbcon, assem, "EstateStore"); + Migration m = new Migration(dbcon, Assembly, "EstateStore"); m.Update(); Type t = typeof(EstateSettings); diff --git a/OpenSim/Data/MySQL/MySQLGenericTableHandler.cs b/OpenSim/Data/MySQL/MySQLGenericTableHandler.cs index 7c23a47d04..8efe4e9bd6 100644 --- a/OpenSim/Data/MySQL/MySQLGenericTableHandler.cs +++ b/OpenSim/Data/MySQL/MySQLGenericTableHandler.cs @@ -46,6 +46,11 @@ namespace OpenSim.Data.MySQL protected string m_Realm; protected FieldInfo m_DataField = null; + protected virtual Assembly Assembly + { + get { return GetType().Assembly; } + } + public MySQLGenericTableHandler(string connectionString, string realm, string storeName) : base(connectionString) { @@ -57,7 +62,7 @@ namespace OpenSim.Data.MySQL using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); - Migration m = new Migration(dbcon, GetType().Assembly, storeName); + Migration m = new Migration(dbcon, Assembly, storeName); m.Update(); } } diff --git a/OpenSim/Data/MySQL/MySQLRegionData.cs b/OpenSim/Data/MySQL/MySQLRegionData.cs index d04e3dc996..c20c39263a 100644 --- a/OpenSim/Data/MySQL/MySQLRegionData.cs +++ b/OpenSim/Data/MySQL/MySQLRegionData.cs @@ -29,6 +29,8 @@ using System; using System.Collections; using System.Collections.Generic; using System.Data; +using System.Reflection; + using OpenMetaverse; using OpenSim.Framework; using OpenSim.Data; @@ -42,6 +44,11 @@ namespace OpenSim.Data.MySQL private List m_ColumnNames; //private string m_connectionString; + protected virtual Assembly Assembly + { + get { return GetType().Assembly; } + } + public MySqlRegionData(string connectionString, string realm) : base(connectionString) { @@ -51,7 +58,7 @@ namespace OpenSim.Data.MySQL using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); - Migration m = new Migration(dbcon, GetType().Assembly, "GridStore"); + Migration m = new Migration(dbcon, Assembly, "GridStore"); m.Update(); } } diff --git a/OpenSim/Data/MySQL/MySQLSimulationData.cs b/OpenSim/Data/MySQL/MySQLSimulationData.cs index 02997b3278..e14d775b45 100644 --- a/OpenSim/Data/MySQL/MySQLSimulationData.cs +++ b/OpenSim/Data/MySQL/MySQLSimulationData.cs @@ -52,6 +52,11 @@ namespace OpenSim.Data.MySQL private string m_connectionString; private object m_dbLock = new object(); + protected virtual Assembly Assembly + { + get { return GetType().Assembly; } + } + public MySQLSimulationData() { } @@ -71,8 +76,7 @@ namespace OpenSim.Data.MySQL // Apply new Migrations // - Assembly assem = GetType().Assembly; - Migration m = new Migration(dbcon, assem, "RegionStore"); + Migration m = new Migration(dbcon, Assembly, "RegionStore"); m.Update(); // Clean dropped attachments diff --git a/OpenSim/Data/MySQL/MySQLUserAccountData.cs b/OpenSim/Data/MySQL/MySQLUserAccountData.cs index 3b3522225c..92afa75b3f 100644 --- a/OpenSim/Data/MySQL/MySQLUserAccountData.cs +++ b/OpenSim/Data/MySQL/MySQLUserAccountData.cs @@ -72,7 +72,7 @@ namespace OpenSim.Data.MySQL } else { - cmd.CommandText = String.Format("select * from {0} where (ScopeID=?ScopeID or ScopeID='00000000-0000-0000-0000-000000000000') and (FirstName like ?searchFirst or LastName like ?searchLast)", m_Realm); + cmd.CommandText = String.Format("select * from {0} where (ScopeID=?ScopeID or ScopeID='00000000-0000-0000-0000-000000000000') and (FirstName like ?searchFirst and LastName like ?searchLast)", m_Realm); cmd.Parameters.AddWithValue("?searchFirst", "%" + words[0] + "%"); cmd.Parameters.AddWithValue("?searchLast", "%" + words[1] + "%"); cmd.Parameters.AddWithValue("?ScopeID", scopeID.ToString()); diff --git a/OpenSim/Data/Null/NullRegionData.cs b/OpenSim/Data/Null/NullRegionData.cs index 2065355890..53e5207a6e 100644 --- a/OpenSim/Data/Null/NullRegionData.cs +++ b/OpenSim/Data/Null/NullRegionData.cs @@ -51,27 +51,55 @@ namespace OpenSim.Data.Null //Console.WriteLine("[XXX] NullRegionData constructor"); } + private delegate bool Matcher(string value); + public List Get(string regionName, UUID scopeID) { if (Instance != this) return Instance.Get(regionName, scopeID); + string cleanName = regionName.ToLower(); + + // Handle SQL wildcards + const string wildcard = "%"; + bool wildcardPrefix = false; + bool wildcardSuffix = false; + if (cleanName.Equals(wildcard)) + { + wildcardPrefix = wildcardSuffix = true; + cleanName = string.Empty; + } + else + { + if (cleanName.StartsWith(wildcard)) + { + wildcardPrefix = true; + cleanName = cleanName.Substring(1); + } + if (regionName.EndsWith(wildcard)) + { + wildcardSuffix = true; + cleanName = cleanName.Remove(cleanName.Length - 1); + } + } + Matcher queryMatch; + if (wildcardPrefix && wildcardSuffix) + queryMatch = delegate(string s) { return s.Contains(cleanName); }; + else if (wildcardSuffix) + queryMatch = delegate(string s) { return s.StartsWith(cleanName); }; + else if (wildcardPrefix) + queryMatch = delegate(string s) { return s.EndsWith(cleanName); }; + else + queryMatch = delegate(string s) { return s.Equals(cleanName); }; + + // Find region data List ret = new List(); foreach (RegionData r in m_regionData.Values) { - if (regionName.Contains("%")) - { - string cleanname = regionName.Replace("%", ""); - m_log.DebugFormat("[NULL REGION DATA]: comparing {0} to {1}", cleanname.ToLower(), r.RegionName.ToLower()); - if (r.RegionName.ToLower().Contains(cleanname.ToLower())) + m_log.DebugFormat("[NULL REGION DATA]: comparing {0} to {1}", cleanName, r.RegionName.ToLower()); + if (queryMatch(r.RegionName.ToLower())) ret.Add(r); - } - else - { - if (r.RegionName.ToLower() == regionName.ToLower()) - ret.Add(r); - } } if (ret.Count > 0) diff --git a/OpenSim/Data/Null/NullUserAccountData.cs b/OpenSim/Data/Null/NullUserAccountData.cs index 772d821731..241616ba3c 100644 --- a/OpenSim/Data/Null/NullUserAccountData.cs +++ b/OpenSim/Data/Null/NullUserAccountData.cs @@ -28,6 +28,9 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Reflection; +using System.Text; +using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Data; @@ -36,12 +39,17 @@ namespace OpenSim.Data.Null { public class NullUserAccountData : IUserAccountData { - private static Dictionary m_DataByUUID = new Dictionary(); - private static Dictionary m_DataByName = new Dictionary(); - private static Dictionary m_DataByEmail = new Dictionary(); + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private Dictionary m_DataByUUID = new Dictionary(); + private Dictionary m_DataByName = new Dictionary(); + private Dictionary m_DataByEmail = new Dictionary(); public NullUserAccountData(string connectionString, string realm) { +// m_log.DebugFormat( +// "[NULL USER ACCOUNT DATA]: Initializing new NullUserAccountData with connectionString [{0}], realm [{1}]", +// connectionString, realm); } /// @@ -54,6 +62,15 @@ namespace OpenSim.Data.Null /// public UserAccountData[] Get(string[] fields, string[] values) { +// if (m_log.IsDebugEnabled) +// { +// m_log.DebugFormat( +// "[NULL USER ACCOUNT DATA]: Called Get with fields [{0}], values [{1}]", +// string.Join(", ", fields), string.Join(", ", values)); +// } + + UserAccountData[] userAccounts = new UserAccountData[0]; + List fieldsLst = new List(fields); if (fieldsLst.Contains("PrincipalID")) { @@ -61,41 +78,61 @@ namespace OpenSim.Data.Null UUID id = UUID.Zero; if (UUID.TryParse(values[i], out id)) if (m_DataByUUID.ContainsKey(id)) - return new UserAccountData[] { m_DataByUUID[id] }; - } - if (fieldsLst.Contains("FirstName") && fieldsLst.Contains("LastName")) + userAccounts = new UserAccountData[] { m_DataByUUID[id] }; + } + else if (fieldsLst.Contains("FirstName") && fieldsLst.Contains("LastName")) { int findex = fieldsLst.IndexOf("FirstName"); int lindex = fieldsLst.IndexOf("LastName"); if (m_DataByName.ContainsKey(values[findex] + " " + values[lindex])) - return new UserAccountData[] { m_DataByName[values[findex] + " " + values[lindex]] }; - } - if (fieldsLst.Contains("Email")) + { + userAccounts = new UserAccountData[] { m_DataByName[values[findex] + " " + values[lindex]] }; + } + } + else if (fieldsLst.Contains("Email")) { int i = fieldsLst.IndexOf("Email"); if (m_DataByEmail.ContainsKey(values[i])) - return new UserAccountData[] { m_DataByEmail[values[i]] }; + userAccounts = new UserAccountData[] { m_DataByEmail[values[i]] }; } - - // Fail - return new UserAccountData[0]; + +// if (m_log.IsDebugEnabled) +// { +// StringBuilder sb = new StringBuilder(); +// foreach (UserAccountData uad in userAccounts) +// sb.AppendFormat("({0} {1} {2}) ", uad.FirstName, uad.LastName, uad.PrincipalID); +// +// m_log.DebugFormat( +// "[NULL USER ACCOUNT DATA]: Returning {0} user accounts out of {1}: [{2}]", userAccounts.Length, m_DataByName.Count, sb); +// } + + return userAccounts; } public bool Store(UserAccountData data) { if (data == null) return false; - + + m_log.DebugFormat( + "[NULL USER ACCOUNT DATA]: Storing user account {0} {1} {2} {3}", + data.FirstName, data.LastName, data.PrincipalID, this.GetHashCode()); + m_DataByUUID[data.PrincipalID] = data; m_DataByName[data.FirstName + " " + data.LastName] = data; if (data.Data.ContainsKey("Email") && data.Data["Email"] != null && data.Data["Email"] != string.Empty) m_DataByEmail[data.Data["Email"]] = data; + +// m_log.DebugFormat("m_DataByUUID count is {0}, m_DataByName count is {1}", m_DataByUUID.Count, m_DataByName.Count); return true; } public UserAccountData[] GetUsers(UUID scopeID, string query) { +// m_log.DebugFormat( +// "[NULL USER ACCOUNT DATA]: Called GetUsers with scope [{0}], query [{1}]", scopeID, query); + string[] words = query.Split(new char[] { ' ' }); for (int i = 0; i < words.Length; i++) diff --git a/OpenSim/Data/SQLite/SQLiteSimulationData.cs b/OpenSim/Data/SQLite/SQLiteSimulationData.cs index 8d93354391..377c680d70 100644 --- a/OpenSim/Data/SQLite/SQLiteSimulationData.cs +++ b/OpenSim/Data/SQLite/SQLiteSimulationData.cs @@ -669,10 +669,6 @@ namespace OpenSim.Data.SQLite } } - /// - /// - /// - /// public void RemoveLandObject(UUID globalID) { lock (ds) @@ -698,7 +694,6 @@ namespace OpenSim.Data.SQLite if (landRow != null) { landRow.Delete(); - land.Rows.Remove(landRow); } List rowsToDelete = new List(); foreach (DataRow rowToCheck in landaccesslist.Rows) @@ -709,7 +704,6 @@ namespace OpenSim.Data.SQLite for (int iter = 0; iter < rowsToDelete.Count; iter++) { rowsToDelete[iter].Delete(); - landaccesslist.Rows.Remove(rowsToDelete[iter]); } } Commit(); diff --git a/OpenSim/Data/Tests/AssetTests.cs b/OpenSim/Data/Tests/AssetTests.cs index 800b9bfba2..b5ae2444eb 100644 --- a/OpenSim/Data/Tests/AssetTests.cs +++ b/OpenSim/Data/Tests/AssetTests.cs @@ -32,13 +32,10 @@ using NUnit.Framework; using NUnit.Framework.Constraints; using OpenMetaverse; using OpenSim.Framework; +using OpenSim.Tests.Common; using System.Data.Common; using log4net; -#if !NUNIT25 -using NUnit.Framework.SyntaxHelpers; -#endif - // DBMS-specific: using MySql.Data.MySqlClient; using OpenSim.Data.MySQL; @@ -51,15 +48,6 @@ using OpenSim.Data.SQLite; namespace OpenSim.Data.Tests { - -#if NUNIT25 - - [TestFixture(typeof(MySqlConnection), typeof(MySQLAssetData), Description="Basic Asset store tests (MySQL)")] - [TestFixture(typeof(SqlConnection), typeof(MSSQLAssetData), Description = "Basic Asset store tests (MS SQL Server)")] - [TestFixture(typeof(SqliteConnection), typeof(SQLiteAssetData), Description = "Basic Asset store tests (SQLite)")] - -#else - [TestFixture(Description = "Asset store tests (SQLite)")] public class SQLiteAssetTests : AssetTests { @@ -75,9 +63,6 @@ namespace OpenSim.Data.Tests { } -#endif - - public class AssetTests : BasicDataServiceTest where TConn : DbConnection, new() where TAssetData : AssetDataBase, new() @@ -121,6 +106,8 @@ namespace OpenSim.Data.Tests [Test] public void T001_LoadEmpty() { + TestHelper.InMethod(); + Assert.That(m_db.ExistsAsset(uuid1), Is.False); Assert.That(m_db.ExistsAsset(uuid2), Is.False); Assert.That(m_db.ExistsAsset(uuid3), Is.False); @@ -129,6 +116,8 @@ namespace OpenSim.Data.Tests [Test] public void T010_StoreReadVerifyAssets() { + TestHelper.InMethod(); + AssetBase a1 = new AssetBase(uuid1, "asset one", (sbyte)AssetType.Texture, critter1.ToString()); AssetBase a2 = new AssetBase(uuid2, "asset two", (sbyte)AssetType.Texture, critter2.ToString()); AssetBase a3 = new AssetBase(uuid3, "asset three", (sbyte)AssetType.Texture, critter3.ToString()); @@ -194,6 +183,8 @@ namespace OpenSim.Data.Tests [Test] public void T020_CheckForWeirdCreatorID() { + TestHelper.InMethod(); + // It is expected that eventually the CreatorID might be an arbitrary string (an URI) // rather than a valid UUID (?). This test is to make sure that the database layer does not // attempt to convert CreatorID to GUID, but just passes it both ways as a string. @@ -218,4 +209,4 @@ namespace OpenSim.Data.Tests Assert.That(a3a, Constraints.PropertyCompareConstraint(a3)); } } -} +} \ No newline at end of file diff --git a/OpenSim/Data/Tests/EstateTests.cs b/OpenSim/Data/Tests/EstateTests.cs index fbf8ba658e..8d332daa2f 100644 --- a/OpenSim/Data/Tests/EstateTests.cs +++ b/OpenSim/Data/Tests/EstateTests.cs @@ -28,10 +28,10 @@ using System; using log4net.Config; using NUnit.Framework; -using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; +using OpenSim.Tests.Common; using System.Text; using log4net; using System.Reflection; @@ -49,15 +49,6 @@ using OpenSim.Data.SQLite; namespace OpenSim.Data.Tests { - -#if NUNIT25 - - [TestFixture(typeof(MySqlConnection), typeof(MySQLEstateStore), Description = "Estate store tests (MySQL)")] - [TestFixture(typeof(SqlConnection), typeof(MSSQLEstateStore), Description = "Estate store tests (MS SQL Server)")] - [TestFixture(typeof(SqliteConnection), typeof(SQLiteEstateStore), Description = "Estate store tests (SQLite)")] - -#else - [TestFixture(Description = "Estate store tests (SQLite)")] public class SQLiteEstateTests : EstateTests { @@ -73,8 +64,6 @@ namespace OpenSim.Data.Tests { } -#endif - public class EstateTests : BasicDataServiceTest where TConn : DbConnection, new() where TEstateStore : class, IEstateDataStore, new() @@ -118,6 +107,8 @@ namespace OpenSim.Data.Tests [Test] public void T010_EstateSettingsSimpleStorage_MinimumParameterSet() { + TestHelper.InMethod(); + EstateSettingsSimpleStorage( REGION_ID, DataTestUtil.STRING_MIN, @@ -149,6 +140,8 @@ namespace OpenSim.Data.Tests [Test] public void T011_EstateSettingsSimpleStorage_MaximumParameterSet() { + TestHelper.InMethod(); + EstateSettingsSimpleStorage( REGION_ID, DataTestUtil.STRING_MAX(64), @@ -180,6 +173,8 @@ namespace OpenSim.Data.Tests [Test] public void T012_EstateSettingsSimpleStorage_AccurateParameterSet() { + TestHelper.InMethod(); + EstateSettingsSimpleStorage( REGION_ID, DataTestUtil.STRING_MAX(1), @@ -211,6 +206,8 @@ namespace OpenSim.Data.Tests [Test] public void T012_EstateSettingsRandomStorage() { + TestHelper.InMethod(); + // Letting estate store generate rows to database for us EstateSettings originalSettings = db.LoadEstateSettings(REGION_ID, true); new PropertyScrambler() @@ -230,6 +227,8 @@ namespace OpenSim.Data.Tests [Test] public void T020_EstateSettingsManagerList() { + TestHelper.InMethod(); + // Letting estate store generate rows to database for us EstateSettings originalSettings = db.LoadEstateSettings(REGION_ID, true); @@ -249,6 +248,8 @@ namespace OpenSim.Data.Tests [Test] public void T021_EstateSettingsUserList() { + TestHelper.InMethod(); + // Letting estate store generate rows to database for us EstateSettings originalSettings = db.LoadEstateSettings(REGION_ID, true); @@ -268,6 +269,8 @@ namespace OpenSim.Data.Tests [Test] public void T022_EstateSettingsGroupList() { + TestHelper.InMethod(); + // Letting estate store generate rows to database for us EstateSettings originalSettings = db.LoadEstateSettings(REGION_ID, true); @@ -287,6 +290,8 @@ namespace OpenSim.Data.Tests [Test] public void T022_EstateSettingsBanList() { + TestHelper.InMethod(); + // Letting estate store generate rows to database for us EstateSettings originalSettings = db.LoadEstateSettings(REGION_ID, true); @@ -520,6 +525,5 @@ namespace OpenSim.Data.Tests } #endregion - } -} +} \ No newline at end of file diff --git a/OpenSim/Data/Tests/InventoryTests.cs b/OpenSim/Data/Tests/InventoryTests.cs index 9c2a2d6fd5..cf3bac1cf9 100644 --- a/OpenSim/Data/Tests/InventoryTests.cs +++ b/OpenSim/Data/Tests/InventoryTests.cs @@ -25,14 +25,12 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -// #define NUNIT25 - using System; using log4net.Config; using NUnit.Framework; -using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenSim.Framework; +using OpenSim.Tests.Common; using log4net; using System.Reflection; using System.Data.Common; @@ -49,14 +47,6 @@ using OpenSim.Data.SQLite; namespace OpenSim.Data.Tests { -#if NUNIT25 - - [TestFixture(typeof(SqliteConnection), typeof(SQLiteInventoryStore), Description = "Inventory store tests (SQLite)")] - [TestFixture(typeof(MySqlConnection), typeof(MySQLInventoryData), Description = "Inventory store tests (MySQL)")] - [TestFixture(typeof(SqlConnection), typeof(MSSQLInventoryData), Description = "Inventory store tests (MS SQL Server)")] - -#else - [TestFixture(Description = "Inventory store tests (SQLite)")] public class SQLiteInventoryTests : InventoryTests { @@ -71,7 +61,6 @@ namespace OpenSim.Data.Tests public class MSSQLInventoryTests : InventoryTests { } -#endif public class InventoryTests : BasicDataServiceTest where TConn : DbConnection, new() @@ -125,6 +114,8 @@ namespace OpenSim.Data.Tests [Test] public void T001_LoadEmpty() { + TestHelper.InMethod(); + Assert.That(db.getInventoryFolder(zero), Is.Null); Assert.That(db.getInventoryFolder(folder1), Is.Null); Assert.That(db.getInventoryFolder(folder2), Is.Null); @@ -143,6 +134,8 @@ namespace OpenSim.Data.Tests [Test] public void T010_FolderNonParent() { + TestHelper.InMethod(); + InventoryFolderBase f1 = NewFolder(folder2, folder1, owner1, name2); // the folder will go in db.addInventoryFolder(f1); @@ -153,6 +146,8 @@ namespace OpenSim.Data.Tests [Test] public void T011_FolderCreate() { + TestHelper.InMethod(); + InventoryFolderBase f1 = NewFolder(folder1, zero, owner1, name1); // TODO: this is probably wrong behavior, but is what we have // db.updateInventoryFolder(f1); @@ -165,7 +160,7 @@ namespace OpenSim.Data.Tests db.addInventoryFolder(f1); InventoryFolderBase f1a = db.getUserRootFolder(owner1); Assert.That(folder1, Is.EqualTo(f1a.ID), "Assert.That(folder1, Is.EqualTo(f1a.ID))"); - Assert.That(name1, Text.Matches(f1a.Name), "Assert.That(name1, Text.Matches(f1a.Name))"); + Assert.That(name1, Is.StringMatching(f1a.Name), "Assert.That(name1, Text.Matches(f1a.Name))"); } // we now have the following tree @@ -176,6 +171,8 @@ namespace OpenSim.Data.Tests [Test] public void T012_FolderList() { + TestHelper.InMethod(); + InventoryFolderBase f2 = NewFolder(folder3, folder1, owner1, name3); db.addInventoryFolder(f2); @@ -190,6 +187,8 @@ namespace OpenSim.Data.Tests [Test] public void T013_FolderHierarchy() { + TestHelper.InMethod(); + int n = db.getFolderHierarchy(zero).Count; // (for dbg - easier to see what's returned) Assert.That(n, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(zero).Count, Is.EqualTo(0))"); n = db.getFolderHierarchy(folder1).Count; @@ -203,6 +202,8 @@ namespace OpenSim.Data.Tests [Test] public void T014_MoveFolder() { + TestHelper.InMethod(); + InventoryFolderBase f2 = db.getInventoryFolder(folder2); f2.ParentID = folder3; db.moveInventoryFolder(f2); @@ -217,6 +218,8 @@ namespace OpenSim.Data.Tests [Test] public void T015_FolderHierarchy() { + TestHelper.InMethod(); + Assert.That(db.getFolderHierarchy(zero).Count, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(zero).Count, Is.EqualTo(0))"); Assert.That(db.getFolderHierarchy(folder1).Count, Is.EqualTo(2), "Assert.That(db.getFolderHierarchy(folder1).Count, Is.EqualTo(2))"); Assert.That(db.getFolderHierarchy(folder2).Count, Is.EqualTo(0), "Assert.That(db.getFolderHierarchy(folder2).Count, Is.EqualTo(0))"); @@ -228,6 +231,8 @@ namespace OpenSim.Data.Tests [Test] public void T100_NoItems() { + TestHelper.InMethod(); + Assert.That(db.getInventoryInFolder(zero).Count, Is.EqualTo(0), "Assert.That(db.getInventoryInFolder(zero).Count, Is.EqualTo(0))"); Assert.That(db.getInventoryInFolder(folder1).Count, Is.EqualTo(0), "Assert.That(db.getInventoryInFolder(folder1).Count, Is.EqualTo(0))"); Assert.That(db.getInventoryInFolder(folder2).Count, Is.EqualTo(0), "Assert.That(db.getInventoryInFolder(folder2).Count, Is.EqualTo(0))"); @@ -240,6 +245,8 @@ namespace OpenSim.Data.Tests [Test] public void T101_CreatItems() { + TestHelper.InMethod(); + db.addInventoryItem(NewItem(item1, folder3, owner1, iname1, asset1)); db.addInventoryItem(NewItem(item2, folder3, owner1, iname2, asset2)); db.addInventoryItem(NewItem(item3, folder3, owner1, iname3, asset3)); @@ -249,6 +256,8 @@ namespace OpenSim.Data.Tests [Test] public void T102_CompareItems() { + TestHelper.InMethod(); + InventoryItemBase i1 = db.getInventoryItem(item1); InventoryItemBase i2 = db.getInventoryItem(item2); InventoryItemBase i3 = db.getInventoryItem(item3); @@ -266,6 +275,8 @@ namespace OpenSim.Data.Tests [Test] public void T103_UpdateItem() { + TestHelper.InMethod(); + // TODO: probably shouldn't have the ability to have an // owner of an item in a folder not owned by the user @@ -284,6 +295,8 @@ namespace OpenSim.Data.Tests [Test] public void T104_RandomUpdateItem() { + TestHelper.InMethod(); + PropertyScrambler folderScrambler = new PropertyScrambler() .DontScramble(x => x.Owner) @@ -341,6 +354,8 @@ namespace OpenSim.Data.Tests [Test] public void T999_StillNull() { + TestHelper.InMethod(); + // After all tests are run, these should still return no results Assert.That(db.getInventoryFolder(zero), Is.Null); Assert.That(db.getInventoryItem(zero), Is.Null); diff --git a/OpenSim/Data/Tests/PropertyCompareConstraint.cs b/OpenSim/Data/Tests/PropertyCompareConstraint.cs index f3d41df586..6c79bda9ec 100644 --- a/OpenSim/Data/Tests/PropertyCompareConstraint.cs +++ b/OpenSim/Data/Tests/PropertyCompareConstraint.cs @@ -34,7 +34,6 @@ using System.Linq.Expressions; using System.Reflection; using NUnit.Framework; using NUnit.Framework.Constraints; -using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenSim.Framework; diff --git a/OpenSim/Data/Tests/PropertyScrambler.cs b/OpenSim/Data/Tests/PropertyScrambler.cs index 132294ad30..c5d40c2373 100644 --- a/OpenSim/Data/Tests/PropertyScrambler.cs +++ b/OpenSim/Data/Tests/PropertyScrambler.cs @@ -32,13 +32,11 @@ using System.Linq.Expressions; using System.Reflection; using System.Text; using NUnit.Framework; -using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenSim.Framework; namespace OpenSim.Data.Tests { - //This is generic so that the lambda expressions will work right in IDEs. public class PropertyScrambler { diff --git a/OpenSim/Data/Tests/RegionTests.cs b/OpenSim/Data/Tests/RegionTests.cs index 23d498d6fa..44cf1ab3ef 100644 --- a/OpenSim/Data/Tests/RegionTests.cs +++ b/OpenSim/Data/Tests/RegionTests.cs @@ -31,11 +31,11 @@ using System.Drawing; using System.Text; using log4net.Config; using NUnit.Framework; -using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; +using OpenSim.Tests.Common; using log4net; using System.Reflection; using System.Data.Common; @@ -52,14 +52,6 @@ using OpenSim.Data.SQLite; namespace OpenSim.Data.Tests { -#if NUNIT25 - - [TestFixture(typeof(SqliteConnection), typeof(SQLiteRegionData), Description = "Region store tests (SQLite)")] - [TestFixture(typeof(MySqlConnection), typeof(MySqlRegionData), Description = "Region store tests (MySQL)")] - [TestFixture(typeof(SqlConnection), typeof(MSSQLRegionData), Description = "Region store tests (MS SQL Server)")] - -#else - [TestFixture(Description = "Region store tests (SQLite)")] public class SQLiteRegionTests : RegionTests { @@ -75,8 +67,6 @@ namespace OpenSim.Data.Tests { } -#endif - public class RegionTests : BasicDataServiceTest where TConn : DbConnection, new() where TRegStore : class, ISimulationDataStore, new() @@ -131,15 +121,18 @@ namespace OpenSim.Data.Tests string[] reg_tables = new string[] { "prims", "primshapes", "primitems", "terrain", "land", "landaccesslist", "regionban", "regionsettings" }; + if (m_rebuildDB) { DropTables(reg_tables); ResetMigrations("RegionStore"); - }else + } + else + { ClearTables(reg_tables); + } } - // Test Plan // Prims // - empty test - 001 @@ -158,6 +151,8 @@ namespace OpenSim.Data.Tests [Test] public void T001_LoadEmpty() { + TestHelper.InMethod(); + List objs = db.LoadObjects(region1); List objs3 = db.LoadObjects(region3); List land = db.LoadLandObjects(region1); @@ -174,6 +169,8 @@ namespace OpenSim.Data.Tests [Test] public void T010_StoreSimpleObject() { + TestHelper.InMethod(); + SceneObjectGroup sog = NewSOG("object1", prim1, region1); SceneObjectGroup sog2 = NewSOG("object2", prim2, region1); @@ -207,6 +204,8 @@ namespace OpenSim.Data.Tests [Test] public void T011_ObjectNames() { + TestHelper.InMethod(); + List objs = db.LoadObjects(region1); foreach (SceneObjectGroup sog in objs) { @@ -219,6 +218,8 @@ namespace OpenSim.Data.Tests [Test] public void T012_SceneParts() { + TestHelper.InMethod(); + UUID tmp0 = UUID.Random(); UUID tmp1 = UUID.Random(); UUID tmp2 = UUID.Random(); @@ -252,6 +253,8 @@ namespace OpenSim.Data.Tests [Test] public void T013_DatabasePersistency() { + TestHelper.InMethod(); + // Sets all ScenePart parameters, stores and retrieves them, then check for consistency with initial data // The commented Asserts are the ones that are unchangeable (when storing on the database, their "Set" values are ignored // The ObjectFlags is an exception, if it is entered incorrectly, the object IS REJECTED on the database silently. @@ -427,6 +430,8 @@ namespace OpenSim.Data.Tests [Test] public void T014_UpdateObject() { + TestHelper.InMethod(); + string text1 = "object1 text"; SceneObjectGroup sog = FindSOG("object1", region1); sog.RootPart.Text = text1; @@ -528,15 +533,20 @@ namespace OpenSim.Data.Tests Assert.That(clickaction,Is.EqualTo(p.ClickAction), "Assert.That(clickaction,Is.EqualTo(p.ClickAction))"); Assert.That(scale,Is.EqualTo(p.Scale), "Assert.That(scale,Is.EqualTo(p.Scale))"); } - + + /// + /// Test storage and retrieval of a scene object with a large number of parts. + /// [Test] public void T015_LargeSceneObjects() { + TestHelper.InMethod(); + UUID id = UUID.Random(); Dictionary mydic = new Dictionary(); SceneObjectGroup sog = NewSOG("Test SOG", id, region4); mydic.Add(sog.RootPart.UUID,sog.RootPart); - for (int i=0;i<30;i++) + for (int i = 0; i < 30; i++) { UUID tmp = UUID.Random(); SceneObjectPart sop = NewSOP(("Test SOP " + i.ToString()),tmp); @@ -555,13 +565,14 @@ namespace OpenSim.Data.Tests sop.Acceleration = accel; mydic.Add(tmp,sop); - sog.AddPart(sop); - db.StoreObject(sog, region4); + sog.AddPart(sop); } + db.StoreObject(sog, region4); + SceneObjectGroup retsog = FindSOG("Test SOG", region4); SceneObjectPart[] parts = retsog.Parts; - for (int i=0;i<30;i++) + for (int i = 0; i < 30; i++) { SceneObjectPart cursop = mydic[parts[i].UUID]; Assert.That(cursop.GroupPosition,Is.EqualTo(parts[i].GroupPosition), "Assert.That(cursop.GroupPosition,Is.EqualTo(parts[i].GroupPosition))"); @@ -576,6 +587,8 @@ namespace OpenSim.Data.Tests //[Test] public void T016_RandomSogWithSceneParts() { + TestHelper.InMethod(); + PropertyScrambler scrambler = new PropertyScrambler() .DontScramble(x => x.UUID); @@ -642,15 +655,16 @@ namespace OpenSim.Data.Tests return sog; } - // NOTE: it is a bad practice to rely on some of the previous tests having been run before. // If the tests are run manually, one at a time, each starts with full class init (DB cleared). // Even when all tests are run, NUnit 2.5+ no longer guarantee a specific test order. // We shouldn't expect to find anything in the DB if we haven't put it there *in the same test*! - + [Test] public void T020_PrimInventoryEmpty() { + TestHelper.InMethod(); + SceneObjectGroup sog = GetMySOG("object1"); TaskInventoryItem t = sog.GetInventoryItem(sog.RootPart.LocalId, item1); Assert.That(t, Is.Null); @@ -670,10 +684,11 @@ namespace OpenSim.Data.Tests db.StorePrimInventory(sog.RootPart.UUID, list); } - [Test] public void T021_PrimInventoryBasic() { + TestHelper.InMethod(); + SceneObjectGroup sog = GetMySOG("object1"); InventoryItemBase i = NewItem(item1, zero, zero, itemname1, zero); @@ -701,20 +716,19 @@ namespace OpenSim.Data.Tests Assert.That(t2.Name, Is.EqualTo("My New Name"), "Assert.That(t.Name, Is.EqualTo(\"My New Name\"))"); // Removing inventory - List list = new List(); db.StorePrimInventory(prim1, list); sog = FindSOG("object1", region1); t = sog.GetInventoryItem(sog.RootPart.LocalId, item1); Assert.That(t, Is.Null); - } - [Test] public void T025_PrimInventoryPersistency() { + TestHelper.InMethod(); + InventoryItemBase i = new InventoryItemBase(); UUID id = UUID.Random(); i.ID = id; @@ -786,6 +800,8 @@ namespace OpenSim.Data.Tests [ExpectedException(typeof(ArgumentException))] public void T026_PrimInventoryMany() { + TestHelper.InMethod(); + UUID i1,i2,i3,i4; i1 = UUID.Random(); i2 = UUID.Random(); @@ -816,15 +832,18 @@ namespace OpenSim.Data.Tests [Test] public void T052_RemoveObject() { + TestHelper.InMethod(); + db.RemoveObject(prim1, region1); SceneObjectGroup sog = FindSOG("object1", region1); Assert.That(sog, Is.Null); } - [Test] public void T100_DefaultRegionInfo() { + TestHelper.InMethod(); + RegionSettings r1 = db.LoadRegionSettings(region1); Assert.That(r1.RegionUUID, Is.EqualTo(region1), "Assert.That(r1.RegionUUID, Is.EqualTo(region1))"); @@ -835,6 +854,8 @@ namespace OpenSim.Data.Tests [Test] public void T101_UpdateRegionInfo() { + TestHelper.InMethod(); + int agentlimit = random.Next(); double objectbonus = random.Next(); int maturity = random.Next(); @@ -933,13 +954,14 @@ namespace OpenSim.Data.Tests //Assert.That(r1a.TerrainImageID,Is.EqualTo(terimgid), "Assert.That(r1a.TerrainImageID,Is.EqualTo(terimgid))"); Assert.That(r1a.FixedSun,Is.True); Assert.That(r1a.SunPosition, Is.EqualTo(sunpos), "Assert.That(r1a.SunPosition, Is.EqualTo(sunpos))"); - Assert.That(r1a.Covenant, Is.EqualTo(cov), "Assert.That(r1a.Covenant, Is.EqualTo(cov))"); - + Assert.That(r1a.Covenant, Is.EqualTo(cov), "Assert.That(r1a.Covenant, Is.EqualTo(cov))"); } [Test] public void T300_NoTerrain() { + TestHelper.InMethod(); + Assert.That(db.LoadTerrain(zero), Is.Null); Assert.That(db.LoadTerrain(region1), Is.Null); Assert.That(db.LoadTerrain(region2), Is.Null); @@ -949,6 +971,8 @@ namespace OpenSim.Data.Tests [Test] public void T301_CreateTerrain() { + TestHelper.InMethod(); + double[,] t1 = GenTerrain(height1); db.StoreTerrain(t1, region1); @@ -961,6 +985,8 @@ namespace OpenSim.Data.Tests [Test] public void T302_FetchTerrain() { + TestHelper.InMethod(); + double[,] baseterrain1 = GenTerrain(height1); double[,] baseterrain2 = GenTerrain(height2); double[,] t1 = db.LoadTerrain(region1); @@ -971,6 +997,8 @@ namespace OpenSim.Data.Tests [Test] public void T303_UpdateTerrain() { + TestHelper.InMethod(); + double[,] baseterrain1 = GenTerrain(height1); double[,] baseterrain2 = GenTerrain(height2); db.StoreTerrain(baseterrain2, region1); @@ -983,6 +1011,8 @@ namespace OpenSim.Data.Tests [Test] public void T400_EmptyLand() { + TestHelper.InMethod(); + Assert.That(db.LoadLandObjects(zero).Count, Is.EqualTo(0), "Assert.That(db.LoadLandObjects(zero).Count, Is.EqualTo(0))"); Assert.That(db.LoadLandObjects(region1).Count, Is.EqualTo(0), "Assert.That(db.LoadLandObjects(region1).Count, Is.EqualTo(0))"); Assert.That(db.LoadLandObjects(region2).Count, Is.EqualTo(0), "Assert.That(db.LoadLandObjects(region2).Count, Is.EqualTo(0))"); @@ -1018,25 +1048,12 @@ namespace OpenSim.Data.Tests return true; } - private SceneObjectGroup FindSOG(string name, UUID r) { List objs = db.LoadObjects(r); foreach (SceneObjectGroup sog in objs) - { - SceneObjectPart p = sog.RootPart; - if (p.Name == name) { - RegionInfo regionInfo = new RegionInfo(); - regionInfo.RegionID = r; - regionInfo.RegionLocX = 0; - regionInfo.RegionLocY = 0; - - Scene scene = new Scene(regionInfo); - sog.SetScene(scene); - + if (sog.Name == name) return sog; - } - } return null; } diff --git a/OpenSim/Framework/AgentCircuitData.cs b/OpenSim/Framework/AgentCircuitData.cs index 1600bdc00d..3dbc215d46 100644 --- a/OpenSim/Framework/AgentCircuitData.cs +++ b/OpenSim/Framework/AgentCircuitData.cs @@ -220,6 +220,8 @@ namespace OpenSim.Framework args["packed_appearance"] = appmap; } + // Old, bad way. Keeping it fow now for backwards compatibility + // OBSOLETE -- soon to be deleted if (ServiceURLs != null && ServiceURLs.Count > 0) { OSDArray urls = new OSDArray(ServiceURLs.Count * 2); @@ -232,6 +234,19 @@ namespace OpenSim.Framework args["service_urls"] = urls; } + // again, this time the right way + if (ServiceURLs != null && ServiceURLs.Count > 0) + { + OSDMap urls = new OSDMap(); + foreach (KeyValuePair kvp in ServiceURLs) + { + //System.Console.WriteLine("XXX " + kvp.Key + "=" + kvp.Value); + urls[kvp.Key] = OSD.FromString((kvp.Value == null) ? string.Empty : kvp.Value.ToString()); + } + args["serviceurls"] = urls; + } + + return args; } @@ -327,7 +342,20 @@ namespace OpenSim.Framework } ServiceURLs = new Dictionary(); - if (args.ContainsKey("service_urls") && args["service_urls"] != null && (args["service_urls"]).Type == OSDType.Array) + // Try parse the new way, OSDMap + if (args.ContainsKey("serviceurls") && args["serviceurls"] != null && (args["serviceurls"]).Type == OSDType.Map) + { + OSDMap urls = (OSDMap)(args["serviceurls"]); + foreach (KeyValuePair kvp in urls) + { + ServiceURLs[kvp.Key] = kvp.Value.AsString(); + //System.Console.WriteLine("XXX " + kvp.Key + "=" + ServiceURLs[kvp.Key]); + + } + } + // else try the old way, OSDArray + // OBSOLETE -- soon to be deleted + else if (args.ContainsKey("service_urls") && args["service_urls"] != null && (args["service_urls"]).Type == OSDType.Array) { OSDArray urls = (OSDArray)(args["service_urls"]); for (int i = 0; i < urls.Count / 2; i++) diff --git a/OpenSim/Framework/Capabilities/Caps.cs b/OpenSim/Framework/Capabilities/Caps.cs index c2f9c3ab7b..3be97b5c89 100644 --- a/OpenSim/Framework/Capabilities/Caps.cs +++ b/OpenSim/Framework/Capabilities/Caps.cs @@ -181,7 +181,6 @@ namespace OpenSim.Framework.Capabilities RegisterRegionServiceHandlers(capsBase); RegisterInventoryServiceHandlers(capsBase); - } public void RegisterRegionServiceHandlers(string capsBase) diff --git a/OpenSim/Framework/Capabilities/CapsHandlers.cs b/OpenSim/Framework/Capabilities/CapsHandlers.cs index 864e6ddb7e..e1c800e907 100644 --- a/OpenSim/Framework/Capabilities/CapsHandlers.cs +++ b/OpenSim/Framework/Capabilities/CapsHandlers.cs @@ -88,8 +88,8 @@ namespace OpenSim.Framework.Capabilities /// handler to be removed public void Remove(string capsName) { - // This line must be here, or caps will break! m_httpListener.RemoveStreamHandler("POST", m_capsHandlers[capsName].Path); + m_httpListener.RemoveStreamHandler("GET", m_capsHandlers[capsName].Path); m_capsHandlers.Remove(capsName); } diff --git a/OpenSim/Framework/EstateSettings.cs b/OpenSim/Framework/EstateSettings.cs index f9c13f32bd..afbdd49e27 100644 --- a/OpenSim/Framework/EstateSettings.cs +++ b/OpenSim/Framework/EstateSettings.cs @@ -58,6 +58,30 @@ namespace OpenSim.Framework set { m_EstateName = value; } } + private bool m_AllowLandmark = true; + + public bool AllowLandmark + { + get { return m_AllowLandmark; } + set { m_AllowLandmark = value; } + } + + private bool m_AllowParcelChanges = true; + + public bool AllowParcelChanges + { + get { return m_AllowParcelChanges; } + set { m_AllowParcelChanges = value; } + } + + private bool m_AllowSetHome = true; + + public bool AllowSetHome + { + get { return m_AllowSetHome; } + set { m_AllowSetHome = value; } + } + private uint m_ParentEstateID = 1; public uint ParentEstateID @@ -392,5 +416,14 @@ namespace OpenSim.Framework return l_EstateAccess.Contains(user); } + + public void SetFromFlags(ulong regionFlags) + { + ResetHomeOnTeleport = ((regionFlags & (ulong)RegionFlags.ResetHomeOnTeleport) == (ulong)RegionFlags.ResetHomeOnTeleport); + BlockDwell = ((regionFlags & (ulong)RegionFlags.BlockDwell) == (ulong)RegionFlags.BlockDwell); + AllowLandmark = ((regionFlags & (ulong)RegionFlags.AllowLandmark) == (ulong)RegionFlags.AllowLandmark); + AllowParcelChanges = ((regionFlags & (ulong)RegionFlags.AllowParcelChanges) == (ulong)RegionFlags.AllowParcelChanges); + AllowSetHome = ((regionFlags & (ulong)RegionFlags.AllowSetHome) == (ulong)RegionFlags.AllowSetHome); + } } } diff --git a/OpenSim/Framework/IMoneyModule.cs b/OpenSim/Framework/IMoneyModule.cs index 3d4873df0c..ea6ed4bff8 100644 --- a/OpenSim/Framework/IMoneyModule.cs +++ b/OpenSim/Framework/IMoneyModule.cs @@ -40,6 +40,7 @@ namespace OpenSim.Framework bool AmountCovered(IClientAPI client, int amount); void ApplyCharge(UUID agentID, int amount, string text); void ApplyUploadCharge(UUID agentID, int amount, string text); + void MoveMoney(UUID fromUser, UUID toUser, int amount, string text); int UploadCharge { get; } int GroupCreationCharge { get; } diff --git a/OpenSim/Framework/PrimitiveBaseShape.cs b/OpenSim/Framework/PrimitiveBaseShape.cs index 9a38f23bc4..44f484e73d 100644 --- a/OpenSim/Framework/PrimitiveBaseShape.cs +++ b/OpenSim/Framework/PrimitiveBaseShape.cs @@ -250,7 +250,7 @@ namespace OpenSim.Framework { get { - //m_log.DebugFormat("[SHAPE]: get m_textureEntry length {0}", m_textureEntry.Length); +// m_log.DebugFormat("[SHAPE]: get m_textureEntry length {0}", m_textureEntry.Length); try { return new Primitive.TextureEntry(m_textureEntry, 0, m_textureEntry.Length); } catch { } diff --git a/OpenSim/Framework/Serialization/External/OspResolver.cs b/OpenSim/Framework/Serialization/External/OspResolver.cs index 7e3dd1b79b..d31d27c4a6 100644 --- a/OpenSim/Framework/Serialization/External/OspResolver.cs +++ b/OpenSim/Framework/Serialization/External/OspResolver.cs @@ -66,6 +66,8 @@ namespace OpenSim.Framework.Serialization UserAccount account = userService.GetUserAccount(UUID.Zero, userId); if (account != null) return MakeOspa(account.FirstName, account.LastName); +// else +// m_log.WarnFormat("[OSP RESOLVER]: No user account for {0}", userId); return null; } @@ -77,6 +79,8 @@ namespace OpenSim.Framework.Serialization /// public static string MakeOspa(string firstName, string lastName) { +// m_log.DebugFormat("[OSP RESOLVER]: Making OSPA for {0} {1}", firstName, lastName); + return OSPA_PREFIX + OSPA_NAME_KEY + OSPA_PAIR_SEPARATOR + firstName + OSPA_NAME_VALUE_SEPARATOR + lastName; } @@ -97,7 +101,10 @@ namespace OpenSim.Framework.Serialization public static UUID ResolveOspa(string ospa, IUserAccountService userService) { if (!ospa.StartsWith(OSPA_PREFIX)) - return UUID.Zero; + { +// m_log.DebugFormat("[OSP RESOLVER]: ResolveOspa() got unrecognized format [{0}]", ospa); + return UUID.Zero; + } // m_log.DebugFormat("[OSP RESOLVER]: Resolving {0}", ospa); @@ -161,7 +168,17 @@ namespace OpenSim.Framework.Serialization UserAccount account = userService.GetUserAccount(UUID.Zero, firstName, lastName); if (account != null) + { +// m_log.DebugFormat( +// "[OSP RESOLVER]: Found user account with uuid {0} for {1} {2}", +// account.PrincipalID, firstName, lastName); + return account.PrincipalID; + } +// else +// { +// m_log.DebugFormat("[OSP RESOLVER]: No resolved OSPA user account for {0}", name); +// } // XXX: Disable temporary user profile creation for now as implementation is incomplete - justincc /* diff --git a/OpenSim/Framework/Serialization/External/UserInventoryItemSerializer.cs b/OpenSim/Framework/Serialization/External/UserInventoryItemSerializer.cs index d5e84c779e..f138437ad5 100644 --- a/OpenSim/Framework/Serialization/External/UserInventoryItemSerializer.cs +++ b/OpenSim/Framework/Serialization/External/UserInventoryItemSerializer.cs @@ -303,7 +303,7 @@ namespace OpenSim.Framework.Serialization.External writer.WriteStartElement("GroupOwned"); writer.WriteString(inventoryItem.GroupOwned.ToString()); writer.WriteEndElement(); - if (inventoryItem.CreatorData != null && inventoryItem.CreatorData != string.Empty) + if (options.ContainsKey("creators") && inventoryItem.CreatorData != null && inventoryItem.CreatorData != string.Empty) writer.WriteElementString("CreatorData", inventoryItem.CreatorData); else if (options.ContainsKey("profile")) { diff --git a/OpenSim/Framework/Servers/BaseOpenSimServer.cs b/OpenSim/Framework/Servers/BaseOpenSimServer.cs index ebf7ded925..5c3cad4e69 100644 --- a/OpenSim/Framework/Servers/BaseOpenSimServer.cs +++ b/OpenSim/Framework/Servers/BaseOpenSimServer.cs @@ -319,18 +319,21 @@ namespace OpenSim.Framework.Servers return; } - string rawLevel = cmd[3]; - - ILoggerRepository repository = LogManager.GetRepository(); - Level consoleLevel = repository.LevelMap[rawLevel]; - - if (consoleLevel != null) - m_consoleAppender.Threshold = consoleLevel; - else - Notice( - String.Format( - "{0} is not a valid logging level. Valid logging levels are ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF", - rawLevel)); + if (cmd.Length > 3) + { + string rawLevel = cmd[3]; + + ILoggerRepository repository = LogManager.GetRepository(); + Level consoleLevel = repository.LevelMap[rawLevel]; + + if (consoleLevel != null) + m_consoleAppender.Threshold = consoleLevel; + else + Notice( + String.Format( + "{0} is not a valid logging level. Valid logging levels are ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF", + rawLevel)); + } Notice(String.Format("Console log level is {0}", m_consoleAppender.Threshold)); } diff --git a/OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs b/OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs index d4ee7ba56d..ccec9b70eb 100644 --- a/OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs +++ b/OpenSim/Framework/Servers/HttpServer/BaseHttpServer.cs @@ -143,6 +143,11 @@ namespace OpenSim.Framework.Servers.HttpServer } } + public List GetStreamHandlerKeys() + { + return new List(m_streamHandlers.Keys); + } + private static string GetHandlerKey(string httpMethod, string path) { return httpMethod + ":" + path; @@ -179,6 +184,11 @@ namespace OpenSim.Framework.Servers.HttpServer } } + public List GetXmlRpcHandlerKeys() + { + return new List(m_rpcHandlers.Keys); + } + public bool AddHTTPHandler(string methodName, GenericHTTPMethod handler) { //m_log.DebugFormat("[BASE HTTP SERVER]: Registering {0}", methodName); @@ -196,6 +206,12 @@ namespace OpenSim.Framework.Servers.HttpServer return false; } + public List GetHTTPHandlerKeys() + { + return new List(m_HTTPHandlers.Keys); + } + + public bool AddPollServiceHTTPHandler(string methodName, GenericHTTPMethod handler, PollServiceEventArgs args) { bool pollHandlerResult = false; @@ -214,6 +230,12 @@ namespace OpenSim.Framework.Servers.HttpServer return false; } + public List GetPollServiceHandlerKeys() + { + return new List(m_pollHandlers.Keys); + } + + // Note that the agent string is provided simply to differentiate // the handlers - it is NOT required to be an actual agent header // value. @@ -232,6 +254,11 @@ namespace OpenSim.Framework.Servers.HttpServer return false; } + public List GetAgentHandlerKeys() + { + return new List(m_agentHandlers.Keys); + } + public bool AddLLSDHandler(string path, LLSDMethod handler) { lock (m_llsdHandlers) @@ -245,6 +272,11 @@ namespace OpenSim.Framework.Servers.HttpServer return false; } + public List GetLLSDHandlerKeys() + { + return new List(m_llsdHandlers.Keys); + } + public bool SetDefaultLLSDHandler(DefaultLLSDMethod handler) { m_defaultLlsdHandler = handler; @@ -346,6 +378,22 @@ namespace OpenSim.Framework.Servers.HttpServer /// public virtual void HandleRequest(OSHttpRequest request, OSHttpResponse response) { + if (request.HttpMethod == String.Empty) // Can't handle empty requests, not wasting a thread + { + try + { + SendHTML500(response); + } + catch + { + } + + return; + } + + string requestMethod = request.HttpMethod; + string uriString = request.RawUrl; + string reqnum = "unknown"; int tickstart = Environment.TickCount; @@ -463,7 +511,7 @@ namespace OpenSim.Framework.Servers.HttpServer request.InputStream.Close(); - // HTTP IN support. The script engine taes it from here + // HTTP IN support. The script engine takes it from here // Nothing to worry about for us. // if (buffer == null) @@ -577,19 +625,19 @@ namespace OpenSim.Framework.Servers.HttpServer { m_log.ErrorFormat("[BASE HTTP SERVER]: HandleRequest() threw ", e); } - catch (InvalidOperationException e) + catch (Exception e) { - m_log.ErrorFormat("[BASE HTTP SERVER]: HandleRequest() threw {0}", e); + m_log.ErrorFormat("[BASE HTTP SERVER]: HandleRequest() threw " + e.ToString()); SendHTML500(response); } finally { // Every month or so this will wrap and give bad numbers, not really a problem - // since its just for reporting, 200ms limit can be adjusted + // since its just for reporting, tickdiff limit can be adjusted int tickdiff = Environment.TickCount - tickstart; - if (tickdiff > 500) + if (tickdiff > 3000) m_log.InfoFormat( - "[BASE HTTP SERVER]: slow request <{0}> for {1} took {2} ms", reqnum, request.RawUrl, tickdiff); + "[BASE HTTP SERVER]: slow {0} request for {1} from {2} took {3} ms", requestMethod, uriString, request.RemoteIPEndPoint.ToString(), tickdiff); } } @@ -753,7 +801,19 @@ namespace OpenSim.Framework.Servers.HttpServer if (methodWasFound) { xmlRprcRequest.Params.Add(request.Url); // Param[2] - xmlRprcRequest.Params.Add(request.Headers.Get("X-Forwarded-For")); // Param[3] + + string xff = "X-Forwarded-For"; + string xfflower = xff.ToLower(); + foreach (string s in request.Headers.AllKeys) + { + if (s != null && s.Equals(xfflower)) + { + xff = xfflower; + break; + } + } + xmlRprcRequest.Params.Add(request.Headers.Get(xff)); // Param[3] + try { diff --git a/OpenSim/Framework/Servers/HttpServer/OSHttpHandler.cs b/OpenSim/Framework/Servers/HttpServer/OSHttpHandler.cs index 129a5449fb..2c2b47ded2 100644 --- a/OpenSim/Framework/Servers/HttpServer/OSHttpHandler.cs +++ b/OpenSim/Framework/Servers/HttpServer/OSHttpHandler.cs @@ -83,7 +83,7 @@ namespace OpenSim.Framework.Servers.HttpServer /// /// Regular expression used to match against path of the /// incoming HTTP request. If you want to match any string - /// either use '.*' or null. To match on the emtpy string use + /// either use '.*' or null. To match on the empty string use /// '^$'. /// public virtual Regex Path diff --git a/OpenSim/Framework/Servers/Tests/OSHttpTests.cs b/OpenSim/Framework/Servers/Tests/OSHttpTests.cs index e62407adfa..dc4eb8f4bf 100644 --- a/OpenSim/Framework/Servers/Tests/OSHttpTests.cs +++ b/OpenSim/Framework/Servers/Tests/OSHttpTests.cs @@ -34,7 +34,6 @@ using System.Text; using HttpServer; using HttpServer.FormDecoders; using NUnit.Framework; -using NUnit.Framework.SyntaxHelpers; using OpenSim.Framework.Servers.HttpServer; namespace OpenSim.Framework.Servers.Tests diff --git a/OpenSim/Framework/Tests/AnimationTests.cs b/OpenSim/Framework/Tests/AnimationTests.cs index 719ddce306..9aa95afa43 100644 --- a/OpenSim/Framework/Tests/AnimationTests.cs +++ b/OpenSim/Framework/Tests/AnimationTests.cs @@ -28,7 +28,6 @@ using System; using System.Reflection; using NUnit.Framework; -using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; diff --git a/OpenSim/Framework/Tests/PrimeNumberHelperTests.cs b/OpenSim/Framework/Tests/PrimeNumberHelperTests.cs index d741f9116d..36bc6e75f9 100644 --- a/OpenSim/Framework/Tests/PrimeNumberHelperTests.cs +++ b/OpenSim/Framework/Tests/PrimeNumberHelperTests.cs @@ -28,7 +28,6 @@ using System; using System.Reflection; using NUnit.Framework; -using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; @@ -38,8 +37,6 @@ namespace OpenSim.Framework.Tests [TestFixture] public class PrimeNumberHelperTests { - - [Test] public void TestGetPrime() { diff --git a/OpenSim/Framework/Tests/UtilTest.cs b/OpenSim/Framework/Tests/UtilTest.cs index 89f5c0cba9..5eac411944 100644 --- a/OpenSim/Framework/Tests/UtilTest.cs +++ b/OpenSim/Framework/Tests/UtilTest.cs @@ -27,7 +27,6 @@ using System; using NUnit.Framework; -using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenSim.Tests.Common; diff --git a/OpenSim/Framework/Util.cs b/OpenSim/Framework/Util.cs index 96292fff2e..3f676f9275 100644 --- a/OpenSim/Framework/Util.cs +++ b/OpenSim/Framework/Util.cs @@ -471,10 +471,17 @@ namespace OpenSim.Framework /// Old region y-coord /// New region y-coord /// - public static bool IsOutsideView(uint oldx, uint newx, uint oldy, uint newy) + public static bool IsOutsideView(float drawdist, uint oldx, uint newx, uint oldy, uint newy) { - // Eventually this will be a function of the draw distance / camera position too. - return (((int)Math.Abs((int)(oldx - newx)) > 1) || ((int)Math.Abs((int)(oldy - newy)) > 1)); + int dd = (int)((drawdist + Constants.RegionSize - 1) / Constants.RegionSize); + + int startX = (int)oldx - dd; + int startY = (int)oldy - dd; + + int endX = (int)oldx + dd; + int endY = (int)oldy + dd; + + return (newx < startX || endX < newx || newy < startY || endY < newy); } public static string FieldToString(byte[] bytes) @@ -1346,6 +1353,11 @@ namespace OpenSim.Framework return (ipaddr1 != null) ? "http://" + ipaddr1.ToString() + ":" + port1 : uri; } + public static byte[] StringToBytes256(string str, params object[] args) + { + return StringToBytes256(string.Format(str, args)); + } + public static byte[] StringToBytes256(string str) { if (String.IsNullOrEmpty(str)) { return Utils.EmptyBytes; } @@ -1364,6 +1376,11 @@ namespace OpenSim.Framework return data; } + public static byte[] StringToBytes1024(string str, params object[] args) + { + return StringToBytes1024(string.Format(str, args)); + } + public static byte[] StringToBytes1024(string str) { if (String.IsNullOrEmpty(str)) { return Utils.EmptyBytes; } diff --git a/OpenSim/Framework/WebUtil.cs b/OpenSim/Framework/WebUtil.cs index 05933419b9..4f5add9320 100644 --- a/OpenSim/Framework/WebUtil.cs +++ b/OpenSim/Framework/WebUtil.cs @@ -29,6 +29,7 @@ using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; +using System.Globalization; using System.IO; using System.Net; using System.Net.Security; @@ -557,34 +558,27 @@ namespace OpenSim.Framework { float qx = GetQ(x); float qy = GetQ(y); - if (qx < qy) - return -1; - if (qx == qy) - return 0; - return 1; + return qy.CompareTo(qx); // descending order } private float GetQ(Object o) { // Example: image/png;q=0.9 + float qvalue = 1F; if (o is String) { string mime = (string)o; - string[] parts = mime.Split(new char[] { ';' }); + string[] parts = mime.Split(';'); if (parts.Length > 1) { - string[] kvp = parts[1].Split(new char[] { '=' }); + string[] kvp = parts[1].Split('='); if (kvp.Length == 2 && kvp[0] == "q") - { - float qvalue = 1F; - float.TryParse(kvp[1], out qvalue); - return qvalue; - } + float.TryParse(kvp[1], NumberStyles.Number, CultureInfo.InvariantCulture, out qvalue); } } - return 1F; + return qvalue; } } diff --git a/OpenSim/Region/Application/OpenSim.cs b/OpenSim/Region/Application/OpenSim.cs index 1c84e3f3cd..313cdcafae 100644 --- a/OpenSim/Region/Application/OpenSim.cs +++ b/OpenSim/Region/Application/OpenSim.cs @@ -294,6 +294,18 @@ namespace OpenSim "show connections", "Show connection data", HandleShow); + m_console.Commands.AddCommand("region", false, "show circuits", + "show circuits", + "Show agent circuit data", HandleShow); + + m_console.Commands.AddCommand("region", false, "show http-handlers", + "show http-handlers", + "Show all registered http handlers", HandleShow); + + m_console.Commands.AddCommand("region", false, "show pending-objects", + "show pending-objects", + "Show # of objects on the pending queues of all scene viewers", HandleShow); + m_console.Commands.AddCommand("region", false, "show modules", "show modules", "Show module data", HandleShow); @@ -943,6 +955,66 @@ namespace OpenSim MainConsole.Instance.Output(connections.ToString()); break; + case "circuits": + System.Text.StringBuilder acd = new System.Text.StringBuilder("Agent Circuits:\n"); + m_sceneManager.ForEachScene( + delegate(Scene scene) + { + //this.HttpServer. + acd.AppendFormat("{0}:\n", scene.RegionInfo.RegionName); + foreach (AgentCircuitData aCircuit in scene.AuthenticateHandler.AgentCircuits.Values) + acd.AppendFormat("\t{0} {1} ({2})\n", aCircuit.firstname, aCircuit.lastname, (aCircuit.child ? "Child" : "Root")); + } + ); + + MainConsole.Instance.Output(acd.ToString()); + break; + + case "http-handlers": + System.Text.StringBuilder handlers = new System.Text.StringBuilder("Registered HTTP Handlers:\n"); + + handlers.AppendFormat("* XMLRPC:\n"); + foreach (String s in HttpServer.GetXmlRpcHandlerKeys()) + handlers.AppendFormat("\t{0}\n", s); + + handlers.AppendFormat("* HTTP:\n"); + List poll = HttpServer.GetPollServiceHandlerKeys(); + foreach (String s in HttpServer.GetHTTPHandlerKeys()) + handlers.AppendFormat("\t{0} {1}\n", s, (poll.Contains(s) ? "(poll service)" : string.Empty)); + + handlers.AppendFormat("* Agent:\n"); + foreach (String s in HttpServer.GetAgentHandlerKeys()) + handlers.AppendFormat("\t{0}\n", s); + + handlers.AppendFormat("* LLSD:\n"); + foreach (String s in HttpServer.GetLLSDHandlerKeys()) + handlers.AppendFormat("\t{0}\n", s); + + handlers.AppendFormat("* StreamHandlers ({0}):\n", HttpServer.GetStreamHandlerKeys().Count); + foreach (String s in HttpServer.GetStreamHandlerKeys()) + handlers.AppendFormat("\t{0}\n", s); + + MainConsole.Instance.Output(handlers.ToString()); + break; + + case "pending-objects": + System.Text.StringBuilder pending = new System.Text.StringBuilder("Pending objects:\n"); + m_sceneManager.ForEachScene( + delegate(Scene scene) + { + scene.ForEachScenePresence( + delegate(ScenePresence sp) + { + pending.AppendFormat("{0}: {1} {2} pending\n", + scene.RegionInfo.RegionName, sp.Name, sp.SceneViewer.GetPendingObjectsCount()); + } + ); + } + ); + + MainConsole.Instance.Output(pending.ToString()); + break; + case "modules": MainConsole.Instance.Output("The currently loaded shared modules are:"); foreach (IRegionModule module in m_moduleLoader.GetLoadedSharedModules) @@ -958,11 +1030,12 @@ namespace OpenSim delegate(Scene scene) { MainConsole.Instance.Output(String.Format( - "Region Name: {0}, Region XLoc: {1}, Region YLoc: {2}, Region Port: {3}", + "Region Name: {0}, Region XLoc: {1}, Region YLoc: {2}, Region Port: {3}, Estate Name: {4}", scene.RegionInfo.RegionName, scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY, - scene.RegionInfo.InternalEndPoint.Port)); + scene.RegionInfo.InternalEndPoint.Port, + scene.RegionInfo.EstateSettings.EstateName)); }); break; diff --git a/OpenSim/Region/Application/OpenSimBase.cs b/OpenSim/Region/Application/OpenSimBase.cs index b74a392e6b..9960a54f0b 100644 --- a/OpenSim/Region/Application/OpenSimBase.cs +++ b/OpenSim/Region/Application/OpenSimBase.cs @@ -877,9 +877,7 @@ namespace OpenSim /// /// Load the estate information for the provided RegionInfo object. /// - /// - /// A - /// + /// public void PopulateRegionEstateInfo(RegionInfo regInfo) { IEstateDataService estateDataService = EstateDataService; @@ -901,7 +899,13 @@ namespace OpenSim regInfo.EstateSettings = estateDataService.LoadEstateSettings(regInfo.RegionID, true); regInfo.EstateSettings.EstateName = MainConsole.Instance.CmdPrompt("New estate name", regInfo.EstateSettings.EstateName); - //regInfo.EstateSettings.Save(); + + // FIXME: Later on, the scene constructor will reload the estate settings no matter what. + // Therefore, we need to do an initial save here otherwise the new estate name will be reset + // back to the default. The reloading of estate settings by scene could be eliminated if it + // knows that the passed in settings in RegionInfo are already valid. Also, it might be + // possible to eliminate some additional later saves made by callers of this method. + regInfo.EstateSettings.Save(); break; } else diff --git a/OpenSim/Region/ClientStack/LindenUDP/LLUDPClient.cs b/OpenSim/Region/ClientStack/LindenUDP/LLUDPClient.cs index f1fdbc513a..d6159cd52e 100644 --- a/OpenSim/Region/ClientStack/LindenUDP/LLUDPClient.cs +++ b/OpenSim/Region/ClientStack/LindenUDP/LLUDPClient.cs @@ -122,6 +122,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP public int PacketsReceived; /// Number of packets sent to this client public int PacketsSent; + /// Number of packets resent to this client + public int PacketsResent; /// Total byte count of unacked packets sent to this client public int UnackedBytes; @@ -257,9 +259,10 @@ namespace OpenSim.Region.ClientStack.LindenUDP public string GetStats() { return string.Format( - "{0,7} {1,7} {2,9} {3,8} {4,7} {5,7} {6,7} {7,7} {8,9} {9,7} {10,7}", + "{0,7} {1,7} {2,7} {3,9} {4,7} {5,7} {6,7} {7,7} {8,7} {9,8} {10,7} {11,7}", + PacketsReceived, PacketsSent, - PacketsReceived, + PacketsResent, UnackedBytes, m_packetOutboxes[(int)ThrottleOutPacketType.Resend].Count, m_packetOutboxes[(int)ThrottleOutPacketType.Land].Count, @@ -449,13 +452,16 @@ namespace OpenSim.Region.ClientStack.LindenUDP /// an outgoing packet from each, obeying the throttling bucket limits /// /// + /// /// Packet queues are inspected in ascending numerical order starting from 0. Therefore, queues with a lower /// ThrottleOutPacketType number will see their packet get sent first (e.g. if both Land and Wind queues have /// packets, then the packet at the front of the Land queue will be sent before the packet at the front of the /// wind queue). /// - /// This function is only called from a synchronous loop in the - /// UDPServer so we don't need to bother making this thread safe + /// This function is only called from a synchronous loop in the + /// UDPServer so we don't need to bother making this thread safe + /// + /// /// True if any packets were sent, otherwise false public bool DequeueOutgoing() { @@ -486,7 +492,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP m_udpServer.SendPacketFinal(nextPacket); m_nextPackets[i] = null; packetSent = true; - this.PacketsSent++; } } else @@ -503,7 +508,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP // Send the packet m_udpServer.SendPacketFinal(packet); packetSent = true; - this.PacketsSent++; } else { diff --git a/OpenSim/Region/ClientStack/LindenUDP/LLUDPServer.cs b/OpenSim/Region/ClientStack/LindenUDP/LLUDPServer.cs index 703176c21c..c865c0f6a8 100644 --- a/OpenSim/Region/ClientStack/LindenUDP/LLUDPServer.cs +++ b/OpenSim/Region/ClientStack/LindenUDP/LLUDPServer.cs @@ -27,6 +27,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.IO; using System.Net; using System.Net.Sockets; @@ -506,7 +507,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP // Bump up the resend count on this packet Interlocked.Increment(ref outgoingPacket.ResendCount); - //Interlocked.Increment(ref Stats.ResentPackets); // Requeue or resend the packet if (!outgoingPacket.Client.EnqueueOutgoing(outgoingPacket, false)) @@ -582,6 +582,10 @@ namespace OpenSim.Region.ClientStack.LindenUDP udpClient.NeedAcks.Add(outgoingPacket); } } + else + { + Interlocked.Increment(ref udpClient.PacketsResent); + } #endregion Sequence Number Assignment @@ -636,10 +640,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP { object[] array = new object[] { buffer, packet }; - if (m_asyncPacketHandling) - Util.FireAndForget(HandleUseCircuitCode, array); - else - HandleUseCircuitCode(array); + Util.FireAndForget(HandleUseCircuitCode, array); return; } @@ -844,7 +845,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP private void HandleUseCircuitCode(object o) { - DateTime startTime = DateTime.Now; +// DateTime startTime = DateTime.Now; object[] array = (object[])o; UDPPacketBuffer buffer = (UDPPacketBuffer)array[0]; UseCircuitCodePacket packet = (UseCircuitCodePacket)array[1]; @@ -856,10 +857,10 @@ namespace OpenSim.Region.ClientStack.LindenUDP // Begin the process of adding the client to the simulator AddNewClient((UseCircuitCodePacket)packet, remoteEndPoint); - // Acknowledge the UseCircuitCode packet + // Send ack SendAckImmediate(remoteEndPoint, packet.Header.Sequence); - -// m_log.DebugFormat( + + // m_log.DebugFormat( // "[LLUDPSERVER]: Handling UseCircuitCode request from {0} took {1}ms", // buffer.RemoteEndPoint, (DateTime.Now - startTime).Milliseconds); } @@ -923,25 +924,32 @@ namespace OpenSim.Region.ClientStack.LindenUDP protected virtual void AddClient(uint circuitCode, UUID agentID, UUID sessionID, IPEndPoint remoteEndPoint, AuthenticateResponse sessionInfo) { - // Create the LLUDPClient - LLUDPClient udpClient = new LLUDPClient(this, ThrottleRates, m_throttle, circuitCode, agentID, remoteEndPoint, m_defaultRTO, m_maxRTO); - IClientAPI existingClient; - - if (!m_scene.TryGetClient(agentID, out existingClient)) + // In priciple there shouldn't be more than one thread here, ever. + // But in case that happens, we need to synchronize this piece of code + // because it's too important + lock (this) { - // Create the LLClientView - LLClientView client = new LLClientView(remoteEndPoint, m_scene, this, udpClient, sessionInfo, agentID, sessionID, circuitCode); - client.OnLogout += LogoutHandler; + IClientAPI existingClient; - client.DisableFacelights = m_disableFacelights; + if (!m_scene.TryGetClient(agentID, out existingClient)) + { + // Create the LLUDPClient + LLUDPClient udpClient = new LLUDPClient(this, ThrottleRates, m_throttle, circuitCode, agentID, remoteEndPoint, m_defaultRTO, m_maxRTO); + // Create the LLClientView + LLClientView client = new LLClientView(remoteEndPoint, m_scene, this, udpClient, sessionInfo, agentID, sessionID, circuitCode); + client.OnLogout += LogoutHandler; - // Start the IClientAPI - client.Start(); - } - else - { - m_log.WarnFormat("[LLUDPSERVER]: Ignoring a repeated UseCircuitCode from {0} at {1} for circuit {2}", - udpClient.AgentID, remoteEndPoint, circuitCode); + client.DisableFacelights = m_disableFacelights; + + // Start the IClientAPI + client.Start(); + + } + else + { + m_log.WarnFormat("[LLUDPSERVER]: Ignoring a repeated UseCircuitCode from {0} at {1} for circuit {2}", + existingClient.AgentId, remoteEndPoint, circuitCode); + } } } @@ -1052,6 +1060,12 @@ namespace OpenSim.Region.ClientStack.LindenUDP #endregion Update Timers + // Use this for emergency monitoring -- bug hunting + //if (m_scene.EmergencyMonitoring) + // clientPacketHandler = MonitoredClientOutgoingPacketHandler; + //else + // clientPacketHandler = ClientOutgoingPacketHandler; + // Handle outgoing packets, resends, acknowledgements, and pings for each // client. m_packetSent will be set to true if a packet is sent m_scene.ForEachClient(clientPacketHandler); @@ -1067,6 +1081,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP { m_log.Error("[LLUDPSERVER]: OutgoingPacketHandler loop threw an exception: " + ex.Message, ex); } + } Watchdog.RemoveThread(); @@ -1104,6 +1119,112 @@ namespace OpenSim.Region.ClientStack.LindenUDP } } + #region Emergency Monitoring + // Alternative packet handler fuull of instrumentation + // Handy for hunting bugs + private Stopwatch watch1 = new Stopwatch(); + private Stopwatch watch2 = new Stopwatch(); + + private float avgProcessingTicks = 0; + private float avgResendUnackedTicks = 0; + private float avgSendAcksTicks = 0; + private float avgSendPingTicks = 0; + private float avgDequeueTicks = 0; + private long nticks = 0; + private long nticksUnack = 0; + private long nticksAck = 0; + private long nticksPing = 0; + private int npacksSent = 0; + private int npackNotSent = 0; + + private void MonitoredClientOutgoingPacketHandler(IClientAPI client) + { + nticks++; + watch1.Start(); + try + { + if (client is LLClientView) + { + LLUDPClient udpClient = ((LLClientView)client).UDPClient; + + if (udpClient.IsConnected) + { + if (m_resendUnacked) + { + nticksUnack++; + watch2.Start(); + + ResendUnacked(udpClient); + + watch2.Stop(); + avgResendUnackedTicks = (nticksUnack - 1)/(float)nticksUnack * avgResendUnackedTicks + (watch2.ElapsedTicks / (float)nticksUnack); + watch2.Reset(); + } + + if (m_sendAcks) + { + nticksAck++; + watch2.Start(); + + SendAcks(udpClient); + + watch2.Stop(); + avgSendAcksTicks = (nticksAck - 1) / (float)nticksAck * avgSendAcksTicks + (watch2.ElapsedTicks / (float)nticksAck); + watch2.Reset(); + } + + if (m_sendPing) + { + nticksPing++; + watch2.Start(); + + SendPing(udpClient); + + watch2.Stop(); + avgSendPingTicks = (nticksPing - 1) / (float)nticksPing * avgSendPingTicks + (watch2.ElapsedTicks / (float)nticksPing); + watch2.Reset(); + } + + watch2.Start(); + // Dequeue any outgoing packets that are within the throttle limits + if (udpClient.DequeueOutgoing()) + { + m_packetSent = true; + npacksSent++; + } + else + npackNotSent++; + + watch2.Stop(); + avgDequeueTicks = (nticks - 1) / (float)nticks * avgDequeueTicks + (watch2.ElapsedTicks / (float)nticks); + watch2.Reset(); + + } + else + m_log.WarnFormat("[LLUDPSERVER]: Client is not connected"); + } + } + catch (Exception ex) + { + m_log.Error("[LLUDPSERVER]: OutgoingPacketHandler iteration for " + client.Name + + " threw an exception: " + ex.Message, ex); + } + watch1.Stop(); + avgProcessingTicks = (nticks - 1) / (float)nticks * avgProcessingTicks + (watch1.ElapsedTicks / (float)nticks); + watch1.Reset(); + + // reuse this -- it's every ~100ms + if (m_scene.EmergencyMonitoring && nticks % 100 == 0) + { + m_log.InfoFormat("[LLUDPSERVER]: avg processing ticks: {0} avg unacked: {1} avg acks: {2} avg ping: {3} avg dequeue: {4} (TickCountRes: {5} sent: {6} notsent: {7})", + avgProcessingTicks, avgResendUnackedTicks, avgSendAcksTicks, avgSendPingTicks, avgDequeueTicks, TickCountResolution, npacksSent, npackNotSent); + npackNotSent = npacksSent = 0; + } + + } + + #endregion + private void ProcessInPacket(object state) { IncomingPacket incomingPacket = (IncomingPacket)state; diff --git a/OpenSim/Region/ClientStack/LindenUDP/UnackedPacketCollection.cs b/OpenSim/Region/ClientStack/LindenUDP/UnackedPacketCollection.cs index 9d40688ac6..d195110a23 100644 --- a/OpenSim/Region/ClientStack/LindenUDP/UnackedPacketCollection.cs +++ b/OpenSim/Region/ClientStack/LindenUDP/UnackedPacketCollection.cs @@ -143,7 +143,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP // Process all the pending adds OutgoingPacket pendingAdd; while (m_pendingAdds.TryDequeue(out pendingAdd)) - m_packets[pendingAdd.SequenceNumber] = pendingAdd; + if (pendingAdd != null) + m_packets[pendingAdd.SequenceNumber] = pendingAdd; // Process all the pending removes, including updating statistics and round-trip times PendingAck pendingRemove; @@ -152,17 +153,20 @@ namespace OpenSim.Region.ClientStack.LindenUDP { if (m_packets.TryGetValue(pendingRemove.SequenceNumber, out ackedPacket)) { - m_packets.Remove(pendingRemove.SequenceNumber); - - // Update stats - Interlocked.Add(ref ackedPacket.Client.UnackedBytes, -ackedPacket.Buffer.DataLength); - - if (!pendingRemove.FromResend) + if (ackedPacket != null) { - // Calculate the round-trip time for this packet and its ACK - int rtt = pendingRemove.RemoveTime - ackedPacket.TickCount; - if (rtt > 0) - ackedPacket.Client.UpdateRoundTrip(rtt); + m_packets.Remove(pendingRemove.SequenceNumber); + + // Update stats + Interlocked.Add(ref ackedPacket.Client.UnackedBytes, -ackedPacket.Buffer.DataLength); + + if (!pendingRemove.FromResend) + { + // Calculate the round-trip time for this packet and its ACK + int rtt = pendingRemove.RemoveTime - ackedPacket.TickCount; + if (rtt > 0) + ackedPacket.Client.UpdateRoundTrip(rtt); + } } } } diff --git a/OpenSim/Region/CoreModules/Agent/Capabilities/CapabilitiesModule.cs b/OpenSim/Region/CoreModules/Agent/Capabilities/CapabilitiesModule.cs index 5c5cb70e28..7526bd2de9 100644 --- a/OpenSim/Region/CoreModules/Agent/Capabilities/CapabilitiesModule.cs +++ b/OpenSim/Region/CoreModules/Agent/Capabilities/CapabilitiesModule.cs @@ -26,12 +26,14 @@ */ using System; +using System.Collections; using System.Collections.Generic; using System.Reflection; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; +using OpenSim.Framework.Console; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using Caps=OpenSim.Framework.Capabilities.Caps; @@ -61,6 +63,9 @@ namespace OpenSim.Region.CoreModules.Agent.Capabilities { m_scene = scene; m_scene.RegisterModuleInterface(this); + MainConsole.Instance.Commands.AddCommand("Capabilities", false, "show caps", + "show capabilities", + "Shows all registered capabilities", CapabilitiesCommand); } public void RegionLoaded(Scene scene) @@ -72,7 +77,9 @@ namespace OpenSim.Region.CoreModules.Agent.Capabilities m_scene.UnregisterModuleInterface(this); } - public void PostInitialise() {} + public void PostInitialise() + { + } public void Close() {} @@ -227,5 +234,23 @@ namespace OpenSim.Region.CoreModules.Agent.Capabilities m_log.Info(" >> "+x+", "+y+": "+kvp.Value); } } + + private void CapabilitiesCommand(string module, string[] cmdparams) + { + System.Text.StringBuilder caps = new System.Text.StringBuilder(); + caps.AppendFormat("Region {0}:\n", m_scene.RegionInfo.RegionName); + + foreach (KeyValuePair kvp in m_capsHandlers) + { + caps.AppendFormat("** User {0}:\n", kvp.Key); + for (IDictionaryEnumerator kvp2 = kvp.Value.CapsHandlers.CapsDetails.GetEnumerator(); kvp2.MoveNext(); ) + { + Uri uri = new Uri(kvp2.Value.ToString()); + caps.AppendFormat(" {0} = {1}\n", kvp2.Key, uri.PathAndQuery); + } + } + + MainConsole.Instance.Output(caps.ToString()); + } } } diff --git a/OpenSim/Region/CoreModules/Asset/FlotsamAssetCache.cs b/OpenSim/Region/CoreModules/Asset/FlotsamAssetCache.cs index e542d7d351..7cba702298 100644 --- a/OpenSim/Region/CoreModules/Asset/FlotsamAssetCache.cs +++ b/OpenSim/Region/CoreModules/Asset/FlotsamAssetCache.cs @@ -92,9 +92,9 @@ namespace Flotsam.RegionModules.AssetCache // Expiration is expressed in hours. private const double m_DefaultMemoryExpiration = 1.0; private const double m_DefaultFileExpiration = 48; - private TimeSpan m_MemoryExpiration = TimeSpan.Zero; - private TimeSpan m_FileExpiration = TimeSpan.Zero; - private TimeSpan m_FileExpirationCleanupTimer = TimeSpan.Zero; + private TimeSpan m_MemoryExpiration = TimeSpan.FromHours(m_DefaultMemoryExpiration); + private TimeSpan m_FileExpiration = TimeSpan.FromHours(m_DefaultFileExpiration); + private TimeSpan m_FileExpirationCleanupTimer = TimeSpan.FromHours(m_DefaultFileExpiration); private static int m_CacheDirectoryTiers = 1; private static int m_CacheDirectoryTierLen = 3; @@ -147,7 +147,7 @@ namespace Flotsam.RegionModules.AssetCache } m_CacheDirectory = assetConfig.GetString("CacheDirectory", m_DefaultCacheDirectory); - m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Cache Directory", m_DefaultCacheDirectory); + m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Cache Directory", m_CacheDirectory); m_MemoryCacheEnabled = assetConfig.GetBoolean("MemoryCacheEnabled", false); m_MemoryExpiration = TimeSpan.FromHours(assetConfig.GetDouble("MemoryCacheTimeout", m_DefaultMemoryExpiration)); @@ -245,16 +245,7 @@ namespace Flotsam.RegionModules.AssetCache private void UpdateMemoryCache(string key, AssetBase asset) { if (m_MemoryCacheEnabled) - { - if (m_MemoryExpiration > TimeSpan.Zero) - { - m_MemoryCache.AddOrUpdate(key, asset, m_MemoryExpiration); - } - else - { - m_MemoryCache.AddOrUpdate(key, asset, Double.MaxValue); - } - } + m_MemoryCache.AddOrUpdate(key, asset, m_MemoryExpiration); } public void Cache(AssetBase asset) @@ -459,7 +450,7 @@ namespace Flotsam.RegionModules.AssetCache private void CleanupExpiredFiles(object source, ElapsedEventArgs e) { if (m_LogLevel >= 2) - m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Checking for expired files older then {0}.", m_FileExpiration.ToString()); + m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Checking for expired files older then {0}.", m_FileExpiration); // Purge all files last accessed prior to this point DateTime purgeLine = DateTime.Now - m_FileExpiration; diff --git a/OpenSim/Region/CoreModules/Avatar/Assets/GetTextureModule.cs b/OpenSim/Region/CoreModules/Avatar/Assets/GetTextureModule.cs index 6fb8b4625c..df4d561024 100644 --- a/OpenSim/Region/CoreModules/Avatar/Assets/GetTextureModule.cs +++ b/OpenSim/Region/CoreModules/Avatar/Assets/GetTextureModule.cs @@ -245,14 +245,12 @@ namespace OpenSim.Region.CoreModules.Avatar.ObjectCaps WriteTextureData(httpRequest, httpResponse, texture, format); return true; } - } // not found - m_log.Warn("[GETTEXTURE]: Texture " + textureID + " not found"); +// m_log.Warn("[GETTEXTURE]: Texture " + textureID + " not found"); httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound; return true; - } private void WriteTextureData(OSHttpRequest request, OSHttpResponse response, AssetBase texture, string format) diff --git a/OpenSim/Region/CoreModules/Avatar/Attachments/AttachmentsModule.cs b/OpenSim/Region/CoreModules/Avatar/Attachments/AttachmentsModule.cs index 8c925889cb..dc33dbbd90 100644 --- a/OpenSim/Region/CoreModules/Avatar/Attachments/AttachmentsModule.cs +++ b/OpenSim/Region/CoreModules/Avatar/Attachments/AttachmentsModule.cs @@ -119,6 +119,13 @@ namespace OpenSim.Region.CoreModules.Avatar.Attachments return; } + if (part.OwnerID != remoteClient.AgentId) // Not ours + { + remoteClient.SendAgentAlertMessage( + "You don't have sufficient permissions to attach this object", false); + return; + } + // TODO: this short circuits multiple attachments functionality in LL viewer 2.1+ and should // be removed when that functionality is implemented in opensim AttachmentPt &= 0x7f; diff --git a/OpenSim/Region/CoreModules/Avatar/AvatarFactory/AvatarFactoryModule.cs b/OpenSim/Region/CoreModules/Avatar/AvatarFactory/AvatarFactoryModule.cs index f8ce444b50..08ac62418e 100644 --- a/OpenSim/Region/CoreModules/Avatar/AvatarFactory/AvatarFactoryModule.cs +++ b/OpenSim/Region/CoreModules/Avatar/AvatarFactory/AvatarFactoryModule.cs @@ -167,7 +167,7 @@ namespace OpenSim.Region.CoreModules.Avatar.AvatarFactory } } - m_log.InfoFormat("[AVFACTORY]: complete texture check for {0}", client.AgentId); + m_log.DebugFormat("[AVFACTORY]: complete texture check for {0}", client.AgentId); // If we only found default textures, then the appearance is not cached return (defonly ? false : true); diff --git a/OpenSim/Region/CoreModules/Avatar/Dialog/DialogModule.cs b/OpenSim/Region/CoreModules/Avatar/Dialog/DialogModule.cs index a514a83542..ded8743a70 100644 --- a/OpenSim/Region/CoreModules/Avatar/Dialog/DialogModule.cs +++ b/OpenSim/Region/CoreModules/Avatar/Dialog/DialogModule.cs @@ -49,16 +49,15 @@ namespace OpenSim.Region.CoreModules.Avatar.Dialog { m_scene = scene; m_scene.RegisterModuleInterface(this); - + m_scene.AddCommand( - this, "alert", "alert ", - "Send an alert to a user", + this, "alert", "alert ", + "Send an alert to everyone", HandleAlertConsoleCommand); m_scene.AddCommand( - this, "alert general", "alert [general] ", - "Send an alert to everyone", - "If keyword 'general' is omitted, then must be surrounded by quotation marks.", + this, "alert-user", "alert-user ", + "Send an alert to a user", HandleAlertConsoleCommand); } @@ -177,55 +176,32 @@ namespace OpenSim.Region.CoreModules.Avatar.Dialog { if (m_scene.ConsoleScene() != null && m_scene.ConsoleScene() != m_scene) return; - - bool isGeneral = false; - string firstName = string.Empty; - string lastName = string.Empty; + string message = string.Empty; - if (cmdparams.Length > 1) + if (cmdparams[0].ToLower().Equals("alert")) { - firstName = cmdparams[1]; - isGeneral = firstName.ToLower().Equals("general"); - } - if (cmdparams.Length == 2 && !isGeneral) - { - // alert "message" - message = cmdparams[1]; - isGeneral = true; - } - else if (cmdparams.Length > 2 && isGeneral) - { - // alert general - message = CombineParams(cmdparams, 2); + message = CombineParams(cmdparams, 1); + m_log.InfoFormat("[DIALOG]: Sending general alert in region {0} with message {1}", + m_scene.RegionInfo.RegionName, message); + SendGeneralAlert(message); } else if (cmdparams.Length > 3) { - // alert - lastName = cmdparams[2]; + string firstName = cmdparams[1]; + string lastName = cmdparams[2]; message = CombineParams(cmdparams, 3); + m_log.InfoFormat( + "[DIALOG]: Sending alert in region {0} to {1} {2} with message {3}", + m_scene.RegionInfo.RegionName, firstName, lastName, message); + SendAlertToUser(firstName, lastName, message, false); } else { OpenSim.Framework.Console.MainConsole.Instance.Output( - "Usage: alert \"message\" | alert general | alert "); + "Usage: alert | alert-user "); return; } - - if (isGeneral) - { - m_log.InfoFormat( - "[DIALOG]: Sending general alert in region {0} with message {1}", - m_scene.RegionInfo.RegionName, message); - SendGeneralAlert(message); - } - else - { - m_log.InfoFormat( - "[DIALOG]: Sending alert in region {0} to {1} {2} with message {3}", - m_scene.RegionInfo.RegionName, firstName, lastName, message); - SendAlertToUser(firstName, lastName, message, false); - } } private string CombineParams(string[] commandParams, int pos) diff --git a/OpenSim/Region/CoreModules/Avatar/InstantMessage/MessageTransferModule.cs b/OpenSim/Region/CoreModules/Avatar/InstantMessage/MessageTransferModule.cs index dd9819aac3..a81ec7c650 100644 --- a/OpenSim/Region/CoreModules/Avatar/InstantMessage/MessageTransferModule.cs +++ b/OpenSim/Region/CoreModules/Avatar/InstantMessage/MessageTransferModule.cs @@ -449,24 +449,37 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage return resp; } - /// - /// delegate for sending a grid instant message asynchronously - /// - public delegate void GridInstantMessageDelegate(GridInstantMessage im, MessageResultNotification result, UUID prevRegionID); + private delegate void GridInstantMessageDelegate(GridInstantMessage im, MessageResultNotification result); - protected virtual void GridInstantMessageCompleted(IAsyncResult iar) + private class GIM { + public GridInstantMessage im; + public MessageResultNotification result; + }; + + private Queue pendingInstantMessages = new Queue(); + private int numInstantMessageThreads = 0; + + private void SendGridInstantMessageViaXMLRPC(GridInstantMessage im, MessageResultNotification result) { - GridInstantMessageDelegate icon = - (GridInstantMessageDelegate)iar.AsyncState; - icon.EndInvoke(iar); + lock (pendingInstantMessages) { + if (numInstantMessageThreads >= 4) { + GIM gim = new GIM(); + gim.im = im; + gim.result = result; + pendingInstantMessages.Enqueue(gim); + } else { + ++ numInstantMessageThreads; + m_log.DebugFormat("[SendGridInstantMessageViaXMLRPC]: ++numInstantMessageThreads={0}", numInstantMessageThreads); + GridInstantMessageDelegate d = SendGridInstantMessageViaXMLRPCAsyncMain; + d.BeginInvoke(im, result, GridInstantMessageCompleted, d); + } + } } - - protected virtual void SendGridInstantMessageViaXMLRPC(GridInstantMessage im, MessageResultNotification result) + private void GridInstantMessageCompleted(IAsyncResult iar) { - GridInstantMessageDelegate d = SendGridInstantMessageViaXMLRPCAsync; - - d.BeginInvoke(im, result, UUID.Zero, GridInstantMessageCompleted, d); + GridInstantMessageDelegate d = (GridInstantMessageDelegate)iar.AsyncState; + d.EndInvoke(iar); } /// @@ -481,8 +494,31 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage /// Pass in 0 the first time this method is called. It will be called recursively with the last /// regionhandle tried /// - protected virtual void SendGridInstantMessageViaXMLRPCAsync(GridInstantMessage im, MessageResultNotification result, UUID prevRegionID) + private void SendGridInstantMessageViaXMLRPCAsyncMain(GridInstantMessage im, MessageResultNotification result) { + GIM gim; + do { + try { + SendGridInstantMessageViaXMLRPCAsync(im, result, UUID.Zero); + } catch (Exception e) { + m_log.Error("[SendGridInstantMessageViaXMLRPC]: exception " + e.Message); + } + lock (pendingInstantMessages) { + if (pendingInstantMessages.Count > 0) { + gim = pendingInstantMessages.Dequeue(); + im = gim.im; + result = gim.result; + } else { + gim = null; + -- numInstantMessageThreads; + m_log.DebugFormat("[SendGridInstantMessageViaXMLRPC]: --numInstantMessageThreads={0}", numInstantMessageThreads); + } + } + } while (gim != null); + } + private void SendGridInstantMessageViaXMLRPCAsync(GridInstantMessage im, MessageResultNotification result, UUID prevRegionID) + { + UUID toAgentID = new UUID(im.toAgentID); PresenceInfo upd = null; diff --git a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveReadRequest.cs b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveReadRequest.cs index 603070614c..9b98de3b67 100644 --- a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveReadRequest.cs +++ b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiveReadRequest.cs @@ -41,6 +41,7 @@ using OpenSim.Framework.Serialization; using OpenSim.Framework.Serialization.External; using OpenSim.Region.CoreModules.World.Archiver; using OpenSim.Region.Framework.Scenes; +using OpenSim.Region.Framework.Scenes.Serialization; using OpenSim.Region.Framework.Interfaces; using OpenSim.Services.Interfaces; @@ -75,6 +76,36 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver /// The stream from which the inventory archive will be loaded. /// private Stream m_loadStream; + + protected bool m_controlFileLoaded; + protected bool m_assetsLoaded; + protected bool m_inventoryNodesLoaded; + + protected int m_successfulAssetRestores; + protected int m_failedAssetRestores; + protected int m_successfulItemRestores; + + /// + /// Root destination folder for the IAR load. + /// + protected InventoryFolderBase m_rootDestinationFolder; + + /// + /// Inventory nodes loaded from the iar. + /// + protected HashSet m_loadedNodes = new HashSet(); + + /// + /// In order to load identically named folders, we need to keep track of the folders that we have already + /// resolved. + /// + Dictionary m_resolvedFolders = new Dictionary(); + + /// + /// Record the creator id that should be associated with an asset. This is used to adjust asset creator ids + /// after OSP resolution (since OSP creators are only stored in the item + /// + protected Dictionary m_creatorIdForAssetId = new Dictionary(); public InventoryArchiveReadRequest( Scene scene, UserAccount userInfo, string invPath, string loadPath, bool merge) @@ -100,20 +131,19 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver /// /// Execute the request /// + /// + /// Only call this once. To load another IAR, construct another request object. + /// /// /// A list of the inventory nodes loaded. If folders were loaded then only the root folders are /// returned /// + /// Thrown if load fails. public HashSet Execute() { try { string filePath = "ERROR"; - int successfulAssetRestores = 0; - int failedAssetRestores = 0; - int successfulItemRestores = 0; - - HashSet loadedNodes = new HashSet(); List folderCandidates = InventoryArchiveUtils.FindFolderByPath( @@ -124,16 +154,11 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver // Possibly provide an option later on to automatically create this folder if it does not exist m_log.ErrorFormat("[INVENTORY ARCHIVER]: Inventory path {0} does not exist", m_invPath); - return loadedNodes; + return m_loadedNodes; } - InventoryFolderBase rootDestinationFolder = folderCandidates[0]; + m_rootDestinationFolder = folderCandidates[0]; archive = new TarArchiveReader(m_loadStream); - - // In order to load identically named folders, we need to keep track of the folders that we have already - // resolved - Dictionary resolvedFolders = new Dictionary(); - byte[] data; TarArchiveReader.TarEntryType entryType; @@ -142,45 +167,14 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver if (filePath == ArchiveConstants.CONTROL_FILE_PATH) { LoadControlFile(filePath, data); - } + } else if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH)) { - if (LoadAsset(filePath, data)) - successfulAssetRestores++; - else - failedAssetRestores++; - - if ((successfulAssetRestores) % 50 == 0) - m_log.DebugFormat( - "[INVENTORY ARCHIVER]: Loaded {0} assets...", - successfulAssetRestores); + LoadAssetFile(filePath, data); } else if (filePath.StartsWith(ArchiveConstants.INVENTORY_PATH)) { - filePath = filePath.Substring(ArchiveConstants.INVENTORY_PATH.Length); - - // Trim off the file portion if we aren't already dealing with a directory path - if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY != entryType) - filePath = filePath.Remove(filePath.LastIndexOf("/") + 1); - - InventoryFolderBase foundFolder - = ReplicateArchivePathToUserInventory( - filePath, rootDestinationFolder, resolvedFolders, loadedNodes); - - if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY != entryType) - { - InventoryItemBase item = LoadItem(data, foundFolder); - - if (item != null) - { - successfulItemRestores++; - - // If we aren't loading the folder containing the item then well need to update the - // viewer separately for that item. - if (!loadedNodes.Contains(foundFolder)) - loadedNodes.Add(item); - } - } + LoadInventoryFile(filePath, entryType, data); } } @@ -188,10 +182,10 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver m_log.DebugFormat( "[INVENTORY ARCHIVER]: Successfully loaded {0} assets with {1} failures", - successfulAssetRestores, failedAssetRestores); - m_log.InfoFormat("[INVENTORY ARCHIVER]: Successfully loaded {0} items", successfulItemRestores); + m_successfulAssetRestores, m_failedAssetRestores); + m_log.InfoFormat("[INVENTORY ARCHIVER]: Successfully loaded {0} items", m_successfulItemRestores); - return loadedNodes; + return m_loadedNodes; } finally { @@ -400,9 +394,11 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver UUID ospResolvedId = OspResolver.ResolveOspa(item.CreatorId, m_scene.UserAccountService); if (UUID.Zero != ospResolvedId) // The user exists in this grid { +// m_log.DebugFormat("[INVENTORY ARCHIVER]: Found creator {0} via OSPA resolution", ospResolvedId); + item.CreatorIdAsUuid = ospResolvedId; - // XXX: For now, don't preserve the OSPA in the creator id (which actually gets persisted to the + // Don't preserve the OSPA in the creator id (which actually gets persisted to the // database). Instead, replace with the UUID that we found. item.CreatorId = ospResolvedId.ToString(); @@ -410,7 +406,8 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver } else if (item.CreatorData == null || item.CreatorData == String.Empty) { - item.CreatorIdAsUuid = m_userInfo.PrincipalID; + item.CreatorId = m_userInfo.PrincipalID.ToString(); + item.CreatorIdAsUuid = new UUID(item.CreatorId); } item.Owner = m_userInfo.PrincipalID; @@ -418,6 +415,13 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver // Reset folder ID to the one in which we want to load it item.Folder = loadFolder.ID; + // Record the creator id for the item's asset so that we can use it later, if necessary, when the asset + // is loaded. + // FIXME: This relies on the items coming before the assets in the TAR file. Need to create stronger + // checks for this, and maybe even an external tool for creating OARs which enforces this, rather than + // relying on native tar tools. + m_creatorIdForAssetId[item.AssetID] = item.CreatorIdAsUuid; + m_scene.AddInventoryItem(item); return item; @@ -446,18 +450,38 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver } string extension = filename.Substring(i); - string uuid = filename.Remove(filename.Length - extension.Length); + string rawUuid = filename.Remove(filename.Length - extension.Length); + UUID assetId = new UUID(rawUuid); if (ArchiveConstants.EXTENSION_TO_ASSET_TYPE.ContainsKey(extension)) { 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.WarnFormat("[INVENTORY ARCHIVER]: Importing {0} byte asset {1} with unknown type", data.Length, assetId); + } + else if (assetType == (sbyte)AssetType.Object) + { + if (m_creatorIdForAssetId.ContainsKey(assetId)) + { + string xmlData = Utils.BytesToString(data); + SceneObjectGroup sog = SceneObjectSerializer.FromOriginalXmlFormat(xmlData); + foreach (SceneObjectPart sop in sog.Parts) + { + if (sop.CreatorData == null || sop.CreatorData == "") + { + sop.CreatorID = m_creatorIdForAssetId[assetId]; + } + } + + data = Utils.StringToBytes(SceneObjectSerializer.ToOriginalXmlFormat(sog)); + } + } //m_log.DebugFormat("[INVENTORY ARCHIVER]: Importing asset {0}, type {1}", uuid, assetType); - AssetBase asset = new AssetBase(new UUID(uuid), "RandomName", assetType, UUID.Zero.ToString()); + AssetBase asset = new AssetBase(assetId, "From IAR", assetType, UUID.Zero.ToString()); asset.Data = data; m_scene.AssetService.Store(asset); @@ -495,7 +519,88 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver majorVersion, MAX_MAJOR_VERSION)); } - m_log.InfoFormat("[INVENTORY ARCHIVER]: Loading IAR with version {0}", version); + m_controlFileLoaded = true; + m_log.InfoFormat("[INVENTORY ARCHIVER]: Loading IAR with version {0}", version); } + + /// + /// Load inventory file + /// + /// + /// + /// + protected void LoadInventoryFile(string path, TarArchiveReader.TarEntryType entryType, byte[] data) + { + if (!m_controlFileLoaded) + throw new Exception( + string.Format( + "The IAR you are trying to load does not list {0} before {1}. Aborting load", + ArchiveConstants.CONTROL_FILE_PATH, ArchiveConstants.INVENTORY_PATH)); + + if (m_assetsLoaded) + throw new Exception( + string.Format( + "The IAR you are trying to load does not list all {0} before {1}. Aborting load", + ArchiveConstants.INVENTORY_PATH, ArchiveConstants.ASSETS_PATH)); + + path = path.Substring(ArchiveConstants.INVENTORY_PATH.Length); + + // Trim off the file portion if we aren't already dealing with a directory path + if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY != entryType) + path = path.Remove(path.LastIndexOf("/") + 1); + + InventoryFolderBase foundFolder + = ReplicateArchivePathToUserInventory( + path, m_rootDestinationFolder, m_resolvedFolders, m_loadedNodes); + + if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY != entryType) + { + InventoryItemBase item = LoadItem(data, foundFolder); + + if (item != null) + { + m_successfulItemRestores++; + + // If we aren't loading the folder containing the item then well need to update the + // viewer separately for that item. + if (!m_loadedNodes.Contains(foundFolder)) + m_loadedNodes.Add(item); + } + } + + m_inventoryNodesLoaded = true; + } + + /// + /// Load asset file + /// + /// + /// + protected void LoadAssetFile(string path, byte[] data) + { + if (!m_controlFileLoaded) + throw new Exception( + string.Format( + "The IAR you are trying to load does not list {0} before {1}. Aborting load", + ArchiveConstants.CONTROL_FILE_PATH, ArchiveConstants.ASSETS_PATH)); + + if (!m_inventoryNodesLoaded) + throw new Exception( + string.Format( + "The IAR you are trying to load does not list all {0} before {1}. Aborting load", + ArchiveConstants.INVENTORY_PATH, ArchiveConstants.ASSETS_PATH)); + + if (LoadAsset(path, data)) + m_successfulAssetRestores++; + else + m_failedAssetRestores++; + + if ((m_successfulAssetRestores) % 50 == 0) + m_log.DebugFormat( + "[INVENTORY ARCHIVER]: Loaded {0} assets...", + m_successfulAssetRestores); + + m_assetsLoaded = true; + } } } \ No newline at end of file diff --git a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiverModule.cs b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiverModule.cs index b1c2a3c683..613f0ed148 100644 --- a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiverModule.cs +++ b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiverModule.cs @@ -109,9 +109,9 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver scene.AddCommand( this, "load iar", - "load iar [--merge] []", + "load iar [-m|--merge] []", "Load user inventory archive (IAR).", - "--merge is an option which merges the loaded IAR with existing inventory folders where possible, rather than always creating new ones" + "-m|--merge is an option which merges the loaded IAR with existing inventory folders where possible, rather than always creating new ones" + " is user's first name." + Environment.NewLine + " is user's last name." + Environment.NewLine + " is the path inside the user's inventory where the IAR should be loaded." + Environment.NewLine @@ -128,6 +128,8 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver + " is the user's last name." + Environment.NewLine + " is the path inside the user's inventory for the folder/item to be saved." + Environment.NewLine + "-p|--profile= adds the url of the profile service to the saved user information." + Environment.NewLine + + "-c|--creators preserves information about foreign creators." + Environment.NewLine + + "-v|--verbose extra debug messages." + Environment.NewLine + " is the filesystem path at which to save the IAR." + string.Format(" If this is not given then the filename {0} in the current directory is used", DEFAULT_INV_BACKUP_FILENAME), HandleSaveInvConsoleCommand); @@ -179,7 +181,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver catch (EntryPointNotFoundException e) { m_log.ErrorFormat( - "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + "[INVENTORY ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); m_log.Error(e); @@ -219,7 +221,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver catch (EntryPointNotFoundException e) { m_log.ErrorFormat( - "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + "[INVENTORY ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); m_log.Error(e); @@ -267,7 +269,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver catch (EntryPointNotFoundException e) { m_log.ErrorFormat( - "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + "[INVENTORY ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); m_log.Error(e); @@ -315,7 +317,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver catch (EntryPointNotFoundException e) { m_log.ErrorFormat( - "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + "[INVENTORY ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); m_log.Error(e); @@ -356,7 +358,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver if (mainParams.Count < 6) { m_log.Error( - "[INVENTORY ARCHIVER]: usage is load iar [--merge] []"); + "[INVENTORY ARCHIVER]: usage is load iar [-m|--merge] []"); return; } @@ -394,6 +396,8 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver OptionSet ops = new OptionSet(); //ops.Add("v|version=", delegate(string v) { options["version"] = v; }); ops.Add("p|profile=", delegate(string v) { options["profile"] = v; }); + ops.Add("v|verbose", delegate(string v) { options["verbose"] = v; }); + ops.Add("c|creators", delegate(string v) { options["creators"] = v; }); List mainParams = ops.Parse(cmdparams); diff --git a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/Tests/InventoryArchiveTestCase.cs b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/Tests/InventoryArchiveTestCase.cs new file mode 100644 index 0000000000..e5127a0118 --- /dev/null +++ b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/Tests/InventoryArchiveTestCase.cs @@ -0,0 +1,155 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Threading; +using NUnit.Framework; +using OpenMetaverse; +using OpenSim.Data; +using OpenSim.Framework; +using OpenSim.Framework.Serialization; +using OpenSim.Framework.Serialization.External; +using OpenSim.Framework.Communications; +using OpenSim.Region.CoreModules.Avatar.Inventory.Archiver; +using OpenSim.Region.CoreModules.World.Serialiser; +using OpenSim.Region.Framework.Scenes; +using OpenSim.Region.Framework.Scenes.Serialization; +using OpenSim.Services.Interfaces; +using OpenSim.Tests.Common; +using OpenSim.Tests.Common.Mock; +using OpenSim.Tests.Common.Setup; + +namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests +{ + [TestFixture] + public class InventoryArchiveTestCase + { + protected ManualResetEvent mre = new ManualResetEvent(false); + + /// + /// A raw array of bytes that we'll use to create an IAR memory stream suitable for isolated use in each test. + /// + protected byte[] m_iarStreamBytes; + + /// + /// Stream of data representing a common IAR for load tests. + /// + protected MemoryStream m_iarStream; + + protected UserAccount m_uaMT + = new UserAccount { + PrincipalID = UUID.Parse("00000000-0000-0000-0000-000000000555"), + FirstName = "Mr", + LastName = "Tiddles" }; + protected UserAccount m_uaLL1 + = new UserAccount { + PrincipalID = UUID.Parse("00000000-0000-0000-0000-000000000666"), + FirstName = "Lord", + LastName = "Lucan" }; + protected UserAccount m_uaLL2 + = new UserAccount { + PrincipalID = UUID.Parse("00000000-0000-0000-0000-000000000777"), + FirstName = "Lord", + LastName = "Lucan" }; + protected string m_item1Name = "Ray Gun Item"; + + [SetUp] + public virtual void SetUp() + { + m_iarStream = new MemoryStream(m_iarStreamBytes); + } + + [TestFixtureSetUp] + public void FixtureSetup() + { + ConstructDefaultIarBytesForTestLoad(); + } + + protected void ConstructDefaultIarBytesForTestLoad() + { +// log4net.Config.XmlConfigurator.Configure(); + + InventoryArchiverModule archiverModule = new InventoryArchiverModule(); + Scene scene = SceneSetupHelpers.SetupScene("Inventory"); + SceneSetupHelpers.SetupSceneModules(scene, archiverModule); + + UserProfileTestUtils.CreateUserWithInventory(scene, m_uaLL1, "hampshire"); + + MemoryStream archiveWriteStream = new MemoryStream(); + + // Create asset + SceneObjectGroup object1; + SceneObjectPart part1; + { + string partName = "Ray Gun Object"; + 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 + InventoryItemBase item1 = new InventoryItemBase(); + item1.Name = m_item1Name; + item1.ID = UUID.Parse("00000000-0000-0000-0000-000000000020"); + item1.AssetID = asset1.FullID; + item1.GroupID = UUID.Random(); + item1.CreatorIdAsUuid = m_uaLL1.PrincipalID; + item1.Owner = m_uaLL1.PrincipalID; + item1.Folder = scene.InventoryService.GetRootFolder(m_uaLL1.PrincipalID).ID; + scene.AddInventoryItem(item1); + + archiverModule.ArchiveInventory( + Guid.NewGuid(), m_uaLL1.FirstName, m_uaLL1.LastName, m_item1Name, "hampshire", archiveWriteStream); + + m_iarStreamBytes = archiveWriteStream.ToArray(); + } + + protected void SaveCompleted( + Guid id, bool succeeded, UserAccount userInfo, string invPath, Stream saveStream, + Exception reportedException) + { + mre.Set(); + } + } +} \ No newline at end of file diff --git a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/Tests/InventoryArchiverTests.cs b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/Tests/InventoryArchiverTests.cs index 76d0b85774..7f156f8904 100644 --- a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/Tests/InventoryArchiverTests.cs +++ b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/Tests/InventoryArchiverTests.cs @@ -31,7 +31,6 @@ using System.IO; using System.Reflection; using System.Threading; using NUnit.Framework; -using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenSim.Data; using OpenSim.Framework; @@ -50,182 +49,21 @@ using OpenSim.Tests.Common.Setup; namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests { [TestFixture] - public class InventoryArchiverTests - { - protected ManualResetEvent mre = new ManualResetEvent(false); - - /// - /// Stream of data representing a common IAR that can be reused in load tests. - /// - protected MemoryStream m_iarStream; - - protected UserAccount m_ua1 - = new UserAccount { - PrincipalID = UUID.Parse("00000000-0000-0000-0000-000000000555"), - FirstName = "Mr", - LastName = "Tiddles" }; - protected UserAccount m_ua2 - = new UserAccount { - PrincipalID = UUID.Parse("00000000-0000-0000-0000-000000000666"), - FirstName = "Lord", - LastName = "Lucan" }; - string m_item1Name = "b.lsl"; - - private void SaveCompleted( - Guid id, bool succeeded, UserAccount userInfo, string invPath, Stream saveStream, - Exception reportedException) - { - mre.Set(); - } - + public class InventoryArchiverTests : InventoryArchiveTestCase + { + protected TestScene m_scene; + protected InventoryArchiverModule m_archiverModule; + [SetUp] - public void Init() + public override void SetUp() { - ConstructDefaultIarForTestLoad(); - } - - protected void ConstructDefaultIarForTestLoad() - { - string archiveItemName = InventoryArchiveWriteRequest.CreateArchiveItemName(m_item1Name, UUID.Random()); - - MemoryStream archiveWriteStream = new MemoryStream(); - TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream); - - InventoryItemBase item1 = new InventoryItemBase(); - item1.Name = m_item1Name; - item1.AssetID = UUID.Random(); - item1.GroupID = UUID.Random(); - //item1.CreatorId = OspResolver.MakeOspa(m_ua2.FirstName, m_ua2.LastName); - //item1.CreatorId = userUuid.ToString(); - item1.CreatorId = m_ua2.PrincipalID.ToString(); - item1.Owner = UUID.Zero; - - Scene scene = SceneSetupHelpers.SetupScene("Inventory"); - UserProfileTestUtils.CreateUserWithInventory(scene, m_ua2, "hampshire"); - - string item1FileName - = string.Format("{0}{1}", ArchiveConstants.INVENTORY_PATH, archiveItemName); - tar.WriteFile(item1FileName, UserInventoryItemSerializer.Serialize(item1, new Dictionary(), scene.UserAccountService)); - tar.Close(); - m_iarStream = new MemoryStream(archiveWriteStream.ToArray()); - } - - /// - /// Test saving an inventory path to a V0.1 OpenSim Inventory Archive - /// (subject to change since there is no fixed format yet). - /// - [Test] - public void TestSavePathToIarV0_1() - { - TestHelper.InMethod(); -// log4net.Config.XmlConfigurator.Configure(); - - InventoryArchiverModule archiverModule = new InventoryArchiverModule(); - - Scene scene = SceneSetupHelpers.SetupScene("Inventory"); - SceneSetupHelpers.SetupSceneModules(scene, archiverModule); - - // Create user - string userFirstName = "Jock"; - string userLastName = "Stirrup"; - string userPassword = "troll"; - UUID userId = UUID.Parse("00000000-0000-0000-0000-000000000020"); - UserProfileTestUtils.CreateUserWithInventory(scene, userFirstName, userLastName, userId, userPassword); + base.SetUp(); - // Create asset - SceneObjectGroup object1; - SceneObjectPart part1; - { - string partName = "My Little Dog Object"; - UUID ownerId = UUID.Parse("00000000-0000-0000-0000-000000000040"); - PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere(); - Vector3 groupPosition = new Vector3(10, 20, 30); - Quaternion rotationOffset = new Quaternion(20, 30, 40, 50); - Vector3 offsetPosition = new Vector3(5, 10, 15); + SerialiserModule serialiserModule = new SerialiserModule(); + m_archiverModule = new InventoryArchiverModule(); - 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 = "My Little Dog"; - item1.AssetID = asset1.FullID; - item1.ID = item1Id; - InventoryFolderBase objsFolder - = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, userId, "Objects")[0]; - item1.Folder = objsFolder.ID; - scene.AddInventoryItem(item1); - - MemoryStream archiveWriteStream = new MemoryStream(); - archiverModule.OnInventoryArchiveSaved += SaveCompleted; - - // Test saving a particular path - mre.Reset(); - archiverModule.ArchiveInventory( - Guid.NewGuid(), userFirstName, userLastName, "Objects", userPassword, archiveWriteStream); - mre.WaitOne(60000, false); - - byte[] archive = archiveWriteStream.ToArray(); - MemoryStream archiveReadStream = new MemoryStream(archive); - TarArchiveReader tar = new TarArchiveReader(archiveReadStream); - - //bool gotControlFile = false; - bool gotObject1File = false; - //bool gotObject2File = false; - string expectedObject1FileName = InventoryArchiveWriteRequest.CreateArchiveItemName(item1); - string expectedObject1FilePath = string.Format( - "{0}{1}{2}", - ArchiveConstants.INVENTORY_PATH, - InventoryArchiveWriteRequest.CreateArchiveFolderName(objsFolder), - expectedObject1FileName); - - string filePath; - TarArchiveReader.TarEntryType tarEntryType; - -// Console.WriteLine("Reading archive"); - - while (tar.ReadEntry(out filePath, out tarEntryType) != null) - { -// Console.WriteLine("Got {0}", filePath); - -// if (ArchiveConstants.CONTROL_FILE_PATH == filePath) -// { -// gotControlFile = true; -// } - - if (filePath.StartsWith(ArchiveConstants.INVENTORY_PATH) && filePath.EndsWith(".xml")) - { -// string fileName = filePath.Remove(0, "Objects/".Length); -// -// if (fileName.StartsWith(part1.Name)) -// { - Assert.That(expectedObject1FilePath, Is.EqualTo(filePath)); - gotObject1File = true; -// } -// else if (fileName.StartsWith(part2.Name)) -// { -// Assert.That(fileName, Is.EqualTo(expectedObject2FileName)); -// gotObject2File = true; -// } - } - } - -// Assert.That(gotControlFile, Is.True, "No control file in archive"); - Assert.That(gotObject1File, Is.True, "No item1 file in archive"); -// Assert.That(gotObject2File, Is.True, "No object2 file in archive"); - - // TODO: Test presence of more files and contents of files. + m_scene = SceneSetupHelpers.SetupScene("Inventory"); + SceneSetupHelpers.SetupSceneModules(m_scene, serialiserModule, m_archiverModule); } /// @@ -238,17 +76,12 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests TestHelper.InMethod(); // log4net.Config.XmlConfigurator.Configure(); - InventoryArchiverModule archiverModule = new InventoryArchiverModule(); - - Scene scene = SceneSetupHelpers.SetupScene("Inventory"); - SceneSetupHelpers.SetupSceneModules(scene, archiverModule); - // Create user string userFirstName = "Jock"; string userLastName = "Stirrup"; string userPassword = "troll"; UUID userId = UUID.Parse("00000000-0000-0000-0000-000000000020"); - UserProfileTestUtils.CreateUserWithInventory(scene, userFirstName, userLastName, userId, userPassword); + UserProfileTestUtils.CreateUserWithInventory(m_scene, userFirstName, userLastName, userId, userPassword); // Create asset SceneObjectGroup object1; @@ -267,12 +100,12 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests part1.Name = partName; object1 = new SceneObjectGroup(part1); - scene.AddNewSceneObject(object1, false); + m_scene.AddNewSceneObject(object1, false); } UUID asset1Id = UUID.Parse("00000000-0000-0000-0000-000000000060"); AssetBase asset1 = AssetHelpers.CreateAsset(asset1Id, object1); - scene.AssetService.Store(asset1); + m_scene.AssetService.Store(asset1); // Create item UUID item1Id = UUID.Parse("00000000-0000-0000-0000-000000000080"); @@ -282,15 +115,15 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests item1.AssetID = asset1.FullID; item1.ID = item1Id; InventoryFolderBase objsFolder - = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, userId, "Objects")[0]; + = InventoryArchiveUtils.FindFolderByPath(m_scene.InventoryService, userId, "Objects")[0]; item1.Folder = objsFolder.ID; - scene.AddInventoryItem(item1); + m_scene.AddInventoryItem(item1); MemoryStream archiveWriteStream = new MemoryStream(); - archiverModule.OnInventoryArchiveSaved += SaveCompleted; + m_archiverModule.OnInventoryArchiveSaved += SaveCompleted; mre.Reset(); - archiverModule.ArchiveInventory( + m_archiverModule.ArchiveInventory( Guid.NewGuid(), userFirstName, userLastName, "Objects/" + item1Name, userPassword, archiveWriteStream); mre.WaitOne(60000, false); @@ -346,474 +179,99 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests } /// - /// Test that things work when the load path specified starts with a slash - /// + /// Test case where a creator account exists for the creator UUID embedded in item metadata and serialized + /// objects. + /// [Test] - public void TestLoadIarPathStartsWithSlash() + public void TestLoadIarCreatorAccountPresent() { TestHelper.InMethod(); // log4net.Config.XmlConfigurator.Configure(); - - SerialiserModule serialiserModule = new SerialiserModule(); - InventoryArchiverModule archiverModule = new InventoryArchiverModule(); - Scene scene = SceneSetupHelpers.SetupScene("inventory"); - SceneSetupHelpers.SetupSceneModules(scene, serialiserModule, archiverModule); - - UserProfileTestUtils.CreateUserWithInventory(scene, m_ua1, "password"); - archiverModule.DearchiveInventory(m_ua1.FirstName, m_ua1.LastName, "/Objects", "password", m_iarStream); + UserProfileTestUtils.CreateUserWithInventory(m_scene, m_uaLL1, "meowfood"); + + m_archiverModule.DearchiveInventory(m_uaLL1.FirstName, m_uaLL1.LastName, "/", "meowfood", m_iarStream); InventoryItemBase foundItem1 - = InventoryArchiveUtils.FindItemByPath( - scene.InventoryService, m_ua1.PrincipalID, "/Objects/" + m_item1Name); - - Assert.That(foundItem1, Is.Not.Null, "Didn't find loaded item 1 in TestLoadIarFolderStartsWithSlash()"); - } - - /// - /// Test loading a V0.1 OpenSim Inventory Archive (subject to change since there is no fixed format yet) where - /// an account exists with the creator name. - /// - /// - /// This test also does some deeper probing of loading into nested inventory structures - [Test] - public void TestLoadIarV0_1ExistingUsers() - { - TestHelper.InMethod(); - //log4net.Config.XmlConfigurator.Configure(); - - SerialiserModule serialiserModule = new SerialiserModule(); - InventoryArchiverModule archiverModule = new InventoryArchiverModule(); - - // Annoyingly, we have to set up a scene even though inventory loading has nothing to do with a scene - Scene scene = SceneSetupHelpers.SetupScene("inventory"); - - SceneSetupHelpers.SetupSceneModules(scene, serialiserModule, archiverModule); + = InventoryArchiveUtils.FindItemByPath(m_scene.InventoryService, m_uaLL1.PrincipalID, m_item1Name); - UserProfileTestUtils.CreateUserWithInventory(scene, m_ua1, "meowfood"); - UserProfileTestUtils.CreateUserWithInventory(scene, m_ua2, "hampshire"); - - archiverModule.DearchiveInventory(m_ua1.FirstName, m_ua1.LastName, "/", "meowfood", m_iarStream); - - InventoryItemBase foundItem1 - = InventoryArchiveUtils.FindItemByPath(scene.InventoryService, m_ua1.PrincipalID, m_item1Name); - - Assert.That(foundItem1, Is.Not.Null, "Didn't find loaded item 1"); - -// We have to disable this check since loaded items that did find users via OSPA resolution are now only storing the -// UUID, not the OSPA itself. -// Assert.That( -// foundItem1.CreatorId, Is.EqualTo(item1.CreatorId), -// "Loaded item non-uuid creator doesn't match original"); Assert.That( - foundItem1.CreatorId, Is.EqualTo(m_ua2.PrincipalID.ToString()), - "Loaded item non-uuid creator doesn't match original"); - + foundItem1.CreatorId, Is.EqualTo(m_uaLL1.PrincipalID.ToString()), + "Loaded item non-uuid creator doesn't match original"); Assert.That( - foundItem1.CreatorIdAsUuid, Is.EqualTo(m_ua2.PrincipalID), + foundItem1.CreatorIdAsUuid, Is.EqualTo(m_uaLL1.PrincipalID), "Loaded item uuid creator doesn't match original"); - Assert.That(foundItem1.Owner, Is.EqualTo(m_ua1.PrincipalID), + Assert.That(foundItem1.Owner, Is.EqualTo(m_uaLL1.PrincipalID), "Loaded item owner doesn't match inventory reciever"); - - // Now try loading to a root child folder - UserInventoryTestUtils.CreateInventoryFolder(scene.InventoryService, m_ua1.PrincipalID, "xA"); - MemoryStream archiveReadStream = new MemoryStream(m_iarStream.ToArray()); - archiverModule.DearchiveInventory(m_ua1.FirstName, m_ua1.LastName, "xA", "meowfood", archiveReadStream); - - InventoryItemBase foundItem2 - = InventoryArchiveUtils.FindItemByPath(scene.InventoryService, m_ua1.PrincipalID, "xA/" + m_item1Name); - Assert.That(foundItem2, Is.Not.Null, "Didn't find loaded item 2"); - - // Now try loading to a more deeply nested folder - UserInventoryTestUtils.CreateInventoryFolder(scene.InventoryService, m_ua1.PrincipalID, "xB/xC"); - archiveReadStream = new MemoryStream(archiveReadStream.ToArray()); - archiverModule.DearchiveInventory(m_ua1.FirstName, m_ua1.LastName, "xB/xC", "meowfood", archiveReadStream); - - InventoryItemBase foundItem3 - = InventoryArchiveUtils.FindItemByPath(scene.InventoryService, m_ua1.PrincipalID, "xB/xC/" + m_item1Name); - Assert.That(foundItem3, Is.Not.Null, "Didn't find loaded item 3"); + + AssetBase asset1 = m_scene.AssetService.Get(foundItem1.AssetID.ToString()); + string xmlData = Utils.BytesToString(asset1.Data); + SceneObjectGroup sog1 = SceneObjectSerializer.FromOriginalXmlFormat(xmlData); + + Assert.That(sog1.RootPart.CreatorID, Is.EqualTo(m_uaLL1.PrincipalID)); } - + + /// + /// Test loading a V0.1 OpenSim Inventory Archive (subject to change since there is no fixed format yet) where + /// an account exists with the same name as the creator, though not the same id. + /// [Test] - public void TestIarV0_1WithEscapedChars() + public void TestLoadIarV0_1SameNameCreator() { 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(); - - Scene scene = SceneSetupHelpers.SetupScene("Inventory"); - SceneSetupHelpers.SetupSceneModules(scene, archiverModule); - - // Create user - string userFirstName = "Jock"; - string userLastName = "Stirrup"; - UUID userId = UUID.Parse("00000000-0000-0000-0000-000000000020"); - UserProfileTestUtils.CreateUserWithInventory(scene, userFirstName, userLastName, userId, "meowfood"); + UserProfileTestUtils.CreateUserWithInventory(m_scene, m_uaMT, "meowfood"); + UserProfileTestUtils.CreateUserWithInventory(m_scene, m_uaLL2, "hampshire"); - // 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")[0]; - item1.Folder = objsFolder.ID; - scene.AddInventoryItem(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); - + m_archiverModule.DearchiveInventory(m_uaMT.FirstName, m_uaMT.LastName, "/", "meowfood", m_iarStream); 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"); + = InventoryArchiveUtils.FindItemByPath(m_scene.InventoryService, m_uaMT.PrincipalID, m_item1Name); + Assert.That( - foundItem1.Name, Is.EqualTo(itemName), - "Loaded item name doesn't match saved name"); + foundItem1.CreatorId, Is.EqualTo(m_uaLL2.PrincipalID.ToString()), + "Loaded item non-uuid creator doesn't match original"); + Assert.That( + foundItem1.CreatorIdAsUuid, Is.EqualTo(m_uaLL2.PrincipalID), + "Loaded item uuid creator doesn't match original"); + Assert.That(foundItem1.Owner, Is.EqualTo(m_uaMT.PrincipalID), + "Loaded item owner doesn't match inventory reciever"); + + AssetBase asset1 = m_scene.AssetService.Get(foundItem1.AssetID.ToString()); + string xmlData = Utils.BytesToString(asset1.Data); + SceneObjectGroup sog1 = SceneObjectSerializer.FromOriginalXmlFormat(xmlData); + + Assert.That(sog1.RootPart.CreatorID, Is.EqualTo(m_uaLL2.PrincipalID)); } /// /// 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 + /// the creator or an account with the creator's name does not exist within the system. /// - /// - /// This may possibly one day get overtaken by the as yet incomplete temporary profiles feature - /// (as tested in the a later commented out test) - /// This test is currently disabled [Test] - public void TestLoadIarV0_1AbsentUsers() + public void TestLoadIarV0_1AbsentCreator() { TestHelper.InMethod(); - //log4net.Config.XmlConfigurator.Configure(); +// log4net.Config.XmlConfigurator.Configure(); - string userFirstName = "Charlie"; - string userLastName = "Chan"; - UUID userUuid = UUID.Parse("00000000-0000-0000-0000-000000000999"); - string userItemCreatorFirstName = "Bat"; - string userItemCreatorLastName = "Man"; - //UUID userItemCreatorUuid = UUID.Parse("00000000-0000-0000-0000-000000008888"); - - string itemName = "b.lsl"; - string archiveItemName = InventoryArchiveWriteRequest.CreateArchiveItemName(itemName, UUID.Random()); - - MemoryStream archiveWriteStream = new MemoryStream(); - TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream); - - InventoryItemBase item1 = new InventoryItemBase(); - item1.Name = itemName; - item1.AssetID = UUID.Random(); - item1.GroupID = UUID.Random(); - item1.CreatorId = OspResolver.MakeOspa(userItemCreatorFirstName, userItemCreatorLastName); - //item1.CreatorId = userUuid.ToString(); - //item1.CreatorId = "00000000-0000-0000-0000-000000000444"; - item1.Owner = UUID.Zero; - - string item1FileName - = string.Format("{0}{1}", ArchiveConstants.INVENTORY_PATH, archiveItemName); - tar.WriteFile(item1FileName, UserInventoryItemSerializer.Serialize(item1, new Dictionary(), null)); - tar.Close(); - - MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray()); - SerialiserModule serialiserModule = new SerialiserModule(); - InventoryArchiverModule archiverModule = new InventoryArchiverModule(); - - // Annoyingly, we have to set up a scene even though inventory loading has nothing to do with a scene - Scene scene = SceneSetupHelpers.SetupScene("inventory"); - - SceneSetupHelpers.SetupSceneModules(scene, serialiserModule, archiverModule); - UserProfileTestUtils.CreateUserWithInventory(scene, userFirstName, userLastName, userUuid, "meowfood"); - - archiverModule.DearchiveInventory(userFirstName, userLastName, "/", "meowfood", archiveReadStream); + UserProfileTestUtils.CreateUserWithInventory(m_scene, m_uaMT, "password"); + m_archiverModule.DearchiveInventory(m_uaMT.FirstName, m_uaMT.LastName, "/", "password", m_iarStream); InventoryItemBase foundItem1 - = InventoryArchiveUtils.FindItemByPath(scene.InventoryService, userUuid, itemName); + = InventoryArchiveUtils.FindItemByPath(m_scene.InventoryService, m_uaMT.PrincipalID, m_item1Name); 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.CreatorIdAsUuid, Is.EqualTo(userUuid), + foundItem1.CreatorId, Is.EqualTo(m_uaMT.PrincipalID.ToString()), + "Loaded item non-uuid creator doesn't match that of the loading user"); + Assert.That( + foundItem1.CreatorIdAsUuid, Is.EqualTo(m_uaMT.PrincipalID), "Loaded item uuid creator doesn't match that of the loading user"); - } - - /// - /// Test loading a V0.1 OpenSim Inventory Archive (subject to change since there is no fixed format yet) where - /// no account exists with the creator name - /// - /// Disabled since temporary profiles have not yet been implemented. - /// - //[Test] - //public void TestLoadIarV0_1TempProfiles() - //{ - // TestHelper.InMethod(); - // //log4net.Config.XmlConfigurator.Configure(); + AssetBase asset1 = m_scene.AssetService.Get(foundItem1.AssetID.ToString()); + string xmlData = Utils.BytesToString(asset1.Data); + SceneObjectGroup sog1 = SceneObjectSerializer.FromOriginalXmlFormat(xmlData); - // string userFirstName = "Dennis"; - // string userLastName = "Menace"; - // UUID userUuid = UUID.Parse("00000000-0000-0000-0000-000000000aaa"); - // string user2FirstName = "Walter"; - // string user2LastName = "Mitty"; - - // string itemName = "b.lsl"; - // string archiveItemName = InventoryArchiveWriteRequest.CreateArchiveItemName(itemName, UUID.Random()); - - // MemoryStream archiveWriteStream = new MemoryStream(); - // TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream); - - // InventoryItemBase item1 = new InventoryItemBase(); - // item1.Name = itemName; - // item1.AssetID = UUID.Random(); - // item1.GroupID = UUID.Random(); - // item1.CreatorId = OspResolver.MakeOspa(user2FirstName, user2LastName); - // item1.Owner = UUID.Zero; - - // string item1FileName - // = string.Format("{0}{1}", ArchiveConstants.INVENTORY_PATH, archiveItemName); - // tar.WriteFile(item1FileName, UserInventoryItemSerializer.Serialize(item1)); - // tar.Close(); - - // MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray()); - // SerialiserModule serialiserModule = new SerialiserModule(); - // InventoryArchiverModule archiverModule = new InventoryArchiverModule(); - - // // Annoyingly, we have to set up a scene even though inventory loading has nothing to do with a scene - // Scene scene = SceneSetupHelpers.SetupScene(); - // IUserAdminService userAdminService = scene.CommsManager.UserAdminService; - - // SceneSetupHelpers.SetupSceneModules(scene, serialiserModule, archiverModule); - // userAdminService.AddUser( - // userFirstName, userLastName, "meowfood", String.Empty, 1000, 1000, userUuid); - - // archiverModule.DearchiveInventory(userFirstName, userLastName, "/", "troll", archiveReadStream); - - // // Check that a suitable temporary user profile has been created. - // UserProfileData user2Profile - // = scene.CommsManager.UserService.GetUserProfile( - // OspResolver.HashName(user2FirstName + " " + user2LastName)); - // Assert.That(user2Profile, Is.Not.Null); - // Assert.That(user2Profile.FirstName == user2FirstName); - // Assert.That(user2Profile.SurName == user2LastName); - - // CachedUserInfo userInfo - // = scene.CommsManager.UserProfileCacheService.GetUserDetails(userFirstName, userLastName); - // userInfo.OnInventoryReceived += InventoryReceived; - - // lock (this) - // { - // userInfo.FetchInventory(); - // Monitor.Wait(this, 60000); - // } - - // InventoryItemBase foundItem = userInfo.RootFolder.FindItemByPath(itemName); - - // Assert.That(foundItem.CreatorId, Is.EqualTo(item1.CreatorId)); - // Assert.That( - // foundItem.CreatorIdAsUuid, Is.EqualTo(OspResolver.HashName(user2FirstName + " " + user2LastName))); - // Assert.That(foundItem.Owner, Is.EqualTo(userUuid)); - - // Console.WriteLine("### Successfully completed {0} ###", MethodBase.GetCurrentMethod()); - //} - - /// - /// Test replication of an archive path to the user's inventory. - /// - [Test] - public void TestNewIarPath() - { - TestHelper.InMethod(); -// log4net.Config.XmlConfigurator.Configure(); - - Scene scene = SceneSetupHelpers.SetupScene("inventory"); - UserAccount ua1 = UserProfileTestUtils.CreateUserWithInventory(scene); - - Dictionary foldersCreated = new Dictionary(); - HashSet nodesLoaded = new HashSet(); - - string folder1Name = "1"; - string folder2aName = "2a"; - string folder2bName = "2b"; - - string folder1ArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder1Name, UUID.Random()); - string folder2aArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder2aName, UUID.Random()); - string folder2bArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder2bName, UUID.Random()); - - string iarPath1 = string.Join("", new string[] { folder1ArchiveName, folder2aArchiveName }); - string iarPath2 = string.Join("", new string[] { folder1ArchiveName, folder2bArchiveName }); - - { - // Test replication of path1 - new InventoryArchiveReadRequest(scene, ua1, null, (Stream)null, false) - .ReplicateArchivePathToUserInventory( - iarPath1, scene.InventoryService.GetRootFolder(ua1.PrincipalID), - foldersCreated, nodesLoaded); - - List folder1Candidates - = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, ua1.PrincipalID, folder1Name); - Assert.That(folder1Candidates.Count, Is.EqualTo(1)); - - InventoryFolderBase folder1 = folder1Candidates[0]; - List folder2aCandidates - = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, folder1, folder2aName); - Assert.That(folder2aCandidates.Count, Is.EqualTo(1)); - } - - { - // Test replication of path2 - new InventoryArchiveReadRequest(scene, ua1, null, (Stream)null, false) - .ReplicateArchivePathToUserInventory( - iarPath2, scene.InventoryService.GetRootFolder(ua1.PrincipalID), - foldersCreated, nodesLoaded); - - List folder1Candidates - = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, ua1.PrincipalID, folder1Name); - Assert.That(folder1Candidates.Count, Is.EqualTo(1)); - - InventoryFolderBase folder1 = folder1Candidates[0]; - - List folder2aCandidates - = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, folder1, folder2aName); - Assert.That(folder2aCandidates.Count, Is.EqualTo(1)); - - List folder2bCandidates - = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, folder1, folder2bName); - Assert.That(folder2bCandidates.Count, Is.EqualTo(1)); - } - } - - /// - /// Test replication of a partly existing archive path to the user's inventory. This should create - /// a duplicate path without the merge option. - /// - [Test] - public void TestPartExistingIarPath() - { - TestHelper.InMethod(); - //log4net.Config.XmlConfigurator.Configure(); - - Scene scene = SceneSetupHelpers.SetupScene("inventory"); - UserAccount ua1 = UserProfileTestUtils.CreateUserWithInventory(scene); - - string folder1ExistingName = "a"; - string folder2Name = "b"; - - InventoryFolderBase folder1 - = UserInventoryTestUtils.CreateInventoryFolder( - scene.InventoryService, ua1.PrincipalID, folder1ExistingName); - - string folder1ArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder1ExistingName, UUID.Random()); - string folder2ArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder2Name, UUID.Random()); - - string itemArchivePath = string.Join("", new string[] { folder1ArchiveName, folder2ArchiveName }); - - new InventoryArchiveReadRequest(scene, ua1, null, (Stream)null, false) - .ReplicateArchivePathToUserInventory( - itemArchivePath, scene.InventoryService.GetRootFolder(ua1.PrincipalID), - new Dictionary(), new HashSet()); - - List folder1PostCandidates - = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, ua1.PrincipalID, folder1ExistingName); - Assert.That(folder1PostCandidates.Count, Is.EqualTo(2)); - - // FIXME: Temporarily, we're going to do something messy to make sure we pick up the created folder. - InventoryFolderBase folder1Post = null; - foreach (InventoryFolderBase folder in folder1PostCandidates) - { - if (folder.ID != folder1.ID) - { - folder1Post = folder; - break; - } - } -// Assert.That(folder1Post.ID, Is.EqualTo(folder1.ID)); - - List folder2PostCandidates - = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, folder1Post, "b"); - Assert.That(folder2PostCandidates.Count, Is.EqualTo(1)); - } - - /// - /// Test replication of a partly existing archive path to the user's inventory. This should create - /// a merged path. - /// - [Test] - public void TestMergeIarPath() - { - TestHelper.InMethod(); -// log4net.Config.XmlConfigurator.Configure(); - - Scene scene = SceneSetupHelpers.SetupScene("inventory"); - UserAccount ua1 = UserProfileTestUtils.CreateUserWithInventory(scene); - - string folder1ExistingName = "a"; - string folder2Name = "b"; - - InventoryFolderBase folder1 - = UserInventoryTestUtils.CreateInventoryFolder( - scene.InventoryService, ua1.PrincipalID, folder1ExistingName); - - string folder1ArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder1ExistingName, UUID.Random()); - string folder2ArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder2Name, UUID.Random()); - - string itemArchivePath = string.Join("", new string[] { folder1ArchiveName, folder2ArchiveName }); - - new InventoryArchiveReadRequest(scene, ua1, folder1ExistingName, (Stream)null, true) - .ReplicateArchivePathToUserInventory( - itemArchivePath, scene.InventoryService.GetRootFolder(ua1.PrincipalID), - new Dictionary(), new HashSet()); - - List folder1PostCandidates - = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, ua1.PrincipalID, folder1ExistingName); - Assert.That(folder1PostCandidates.Count, Is.EqualTo(1)); - Assert.That(folder1PostCandidates[0].ID, Is.EqualTo(folder1.ID)); - - List folder2PostCandidates - = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, folder1PostCandidates[0], "b"); - Assert.That(folder2PostCandidates.Count, Is.EqualTo(1)); + Assert.That(sog1.RootPart.CreatorID, Is.EqualTo(m_uaMT.PrincipalID)); } } } \ No newline at end of file diff --git a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/Tests/PathTests.cs b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/Tests/PathTests.cs new file mode 100644 index 0000000000..0e8f647dbc --- /dev/null +++ b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/Tests/PathTests.cs @@ -0,0 +1,478 @@ +/* + * 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.IO; +using System.Reflection; +using System.Threading; +using NUnit.Framework; +using OpenMetaverse; +using OpenSim.Data; +using OpenSim.Framework; +using OpenSim.Framework.Serialization; +using OpenSim.Framework.Serialization.External; +using OpenSim.Framework.Communications; +using OpenSim.Region.CoreModules.Avatar.Inventory.Archiver; +using OpenSim.Region.CoreModules.World.Serialiser; +using OpenSim.Region.Framework.Scenes; +using OpenSim.Region.Framework.Scenes.Serialization; +using OpenSim.Services.Interfaces; +using OpenSim.Tests.Common; +using OpenSim.Tests.Common.Mock; +using OpenSim.Tests.Common.Setup; + +namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests +{ + [TestFixture] + public class PathTests : InventoryArchiveTestCase + { + /// + /// Test saving an inventory path to a V0.1 OpenSim Inventory Archive + /// (subject to change since there is no fixed format yet). + /// + [Test] + public void TestSavePathToIarV0_1() + { + TestHelper.InMethod(); +// log4net.Config.XmlConfigurator.Configure(); + + InventoryArchiverModule archiverModule = new InventoryArchiverModule(); + + Scene scene = SceneSetupHelpers.SetupScene("Inventory"); + SceneSetupHelpers.SetupSceneModules(scene, archiverModule); + + // Create user + string userFirstName = "Jock"; + string userLastName = "Stirrup"; + string userPassword = "troll"; + UUID userId = UUID.Parse("00000000-0000-0000-0000-000000000020"); + UserProfileTestUtils.CreateUserWithInventory(scene, userFirstName, userLastName, userId, userPassword); + + // Create asset + SceneObjectGroup object1; + SceneObjectPart part1; + { + string partName = "My Little Dog Object"; + UUID ownerId = UUID.Parse("00000000-0000-0000-0000-000000000040"); + PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere(); + Vector3 groupPosition = new Vector3(10, 20, 30); + Quaternion rotationOffset = new Quaternion(20, 30, 40, 50); + Vector3 offsetPosition = new Vector3(5, 10, 15); + + part1 = new SceneObjectPart(ownerId, shape, groupPosition, rotationOffset, offsetPosition); + part1.Name = partName; + + object1 = new SceneObjectGroup(part1); + 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 = "My Little Dog"; + item1.AssetID = asset1.FullID; + item1.ID = item1Id; + InventoryFolderBase objsFolder + = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, userId, "Objects")[0]; + item1.Folder = objsFolder.ID; + scene.AddInventoryItem(item1); + + MemoryStream archiveWriteStream = new MemoryStream(); + archiverModule.OnInventoryArchiveSaved += SaveCompleted; + + // Test saving a particular path + mre.Reset(); + archiverModule.ArchiveInventory( + Guid.NewGuid(), userFirstName, userLastName, "Objects", userPassword, archiveWriteStream); + mre.WaitOne(60000, false); + + byte[] archive = archiveWriteStream.ToArray(); + MemoryStream archiveReadStream = new MemoryStream(archive); + TarArchiveReader tar = new TarArchiveReader(archiveReadStream); + + //bool gotControlFile = false; + bool gotObject1File = false; + //bool gotObject2File = false; + string expectedObject1FileName = InventoryArchiveWriteRequest.CreateArchiveItemName(item1); + string expectedObject1FilePath = string.Format( + "{0}{1}{2}", + ArchiveConstants.INVENTORY_PATH, + InventoryArchiveWriteRequest.CreateArchiveFolderName(objsFolder), + expectedObject1FileName); + + string filePath; + TarArchiveReader.TarEntryType tarEntryType; + +// Console.WriteLine("Reading archive"); + + while (tar.ReadEntry(out filePath, out tarEntryType) != null) + { +// Console.WriteLine("Got {0}", filePath); + +// if (ArchiveConstants.CONTROL_FILE_PATH == filePath) +// { +// gotControlFile = true; +// } + + if (filePath.StartsWith(ArchiveConstants.INVENTORY_PATH) && filePath.EndsWith(".xml")) + { +// string fileName = filePath.Remove(0, "Objects/".Length); +// +// if (fileName.StartsWith(part1.Name)) +// { + Assert.That(expectedObject1FilePath, Is.EqualTo(filePath)); + gotObject1File = true; +// } +// else if (fileName.StartsWith(part2.Name)) +// { +// Assert.That(fileName, Is.EqualTo(expectedObject2FileName)); +// gotObject2File = true; +// } + } + } + +// Assert.That(gotControlFile, Is.True, "No control file in archive"); + Assert.That(gotObject1File, Is.True, "No item1 file in archive"); +// Assert.That(gotObject2File, Is.True, "No object2 file in archive"); + + // TODO: Test presence of more files and contents of files. + } + + /// + /// Test loading an IAR to various different inventory paths. + /// + [Test] + public void TestLoadIarToInventoryPaths() + { + TestHelper.InMethod(); +// log4net.Config.XmlConfigurator.Configure(); + + SerialiserModule serialiserModule = new SerialiserModule(); + InventoryArchiverModule archiverModule = new InventoryArchiverModule(); + + // Annoyingly, we have to set up a scene even though inventory loading has nothing to do with a scene + Scene scene = SceneSetupHelpers.SetupScene("inventory"); + + SceneSetupHelpers.SetupSceneModules(scene, serialiserModule, archiverModule); + + UserProfileTestUtils.CreateUserWithInventory(scene, m_uaMT, "meowfood"); + UserProfileTestUtils.CreateUserWithInventory(scene, m_uaLL1, "hampshire"); + + archiverModule.DearchiveInventory(m_uaMT.FirstName, m_uaMT.LastName, "/", "meowfood", m_iarStream); + InventoryItemBase foundItem1 + = InventoryArchiveUtils.FindItemByPath(scene.InventoryService, m_uaMT.PrincipalID, m_item1Name); + + Assert.That(foundItem1, Is.Not.Null, "Didn't find loaded item 1"); + + // Now try loading to a root child folder + UserInventoryTestUtils.CreateInventoryFolder(scene.InventoryService, m_uaMT.PrincipalID, "xA"); + MemoryStream archiveReadStream = new MemoryStream(m_iarStream.ToArray()); + archiverModule.DearchiveInventory(m_uaMT.FirstName, m_uaMT.LastName, "xA", "meowfood", archiveReadStream); + + InventoryItemBase foundItem2 + = InventoryArchiveUtils.FindItemByPath(scene.InventoryService, m_uaMT.PrincipalID, "xA/" + m_item1Name); + Assert.That(foundItem2, Is.Not.Null, "Didn't find loaded item 2"); + + // Now try loading to a more deeply nested folder + UserInventoryTestUtils.CreateInventoryFolder(scene.InventoryService, m_uaMT.PrincipalID, "xB/xC"); + archiveReadStream = new MemoryStream(archiveReadStream.ToArray()); + archiverModule.DearchiveInventory(m_uaMT.FirstName, m_uaMT.LastName, "xB/xC", "meowfood", archiveReadStream); + + InventoryItemBase foundItem3 + = InventoryArchiveUtils.FindItemByPath(scene.InventoryService, m_uaMT.PrincipalID, "xB/xC/" + m_item1Name); + Assert.That(foundItem3, Is.Not.Null, "Didn't find loaded item 3"); + } + + /// + /// Test that things work when the load path specified starts with a slash + /// + [Test] + public void TestLoadIarPathStartsWithSlash() + { + TestHelper.InMethod(); +// log4net.Config.XmlConfigurator.Configure(); + + SerialiserModule serialiserModule = new SerialiserModule(); + InventoryArchiverModule archiverModule = new InventoryArchiverModule(); + Scene scene = SceneSetupHelpers.SetupScene("inventory"); + SceneSetupHelpers.SetupSceneModules(scene, serialiserModule, archiverModule); + + UserProfileTestUtils.CreateUserWithInventory(scene, m_uaMT, "password"); + archiverModule.DearchiveInventory(m_uaMT.FirstName, m_uaMT.LastName, "/Objects", "password", m_iarStream); + + InventoryItemBase foundItem1 + = InventoryArchiveUtils.FindItemByPath( + scene.InventoryService, m_uaMT.PrincipalID, "/Objects/" + m_item1Name); + + Assert.That(foundItem1, Is.Not.Null, "Didn't find loaded item 1 in TestLoadIarFolderStartsWithSlash()"); + } + + [Test] + public void TestLoadIarPathWithEscapedChars() + { + 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(); + + Scene scene = SceneSetupHelpers.SetupScene("Inventory"); + SceneSetupHelpers.SetupSceneModules(scene, archiverModule); + + // Create user + string userFirstName = "Jock"; + string userLastName = "Stirrup"; + UUID userId = UUID.Parse("00000000-0000-0000-0000-000000000020"); + UserProfileTestUtils.CreateUserWithInventory(scene, userFirstName, userLastName, userId, "meowfood"); + + // 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")[0]; + item1.Folder = objsFolder.ID; + scene.AddInventoryItem(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"); + } + + /// + /// Test replication of an archive path to the user's inventory. + /// + [Test] + public void TestNewIarPath() + { + TestHelper.InMethod(); +// log4net.Config.XmlConfigurator.Configure(); + + Scene scene = SceneSetupHelpers.SetupScene("inventory"); + UserAccount ua1 = UserProfileTestUtils.CreateUserWithInventory(scene); + + Dictionary foldersCreated = new Dictionary(); + HashSet nodesLoaded = new HashSet(); + + string folder1Name = "1"; + string folder2aName = "2a"; + string folder2bName = "2b"; + + string folder1ArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder1Name, UUID.Random()); + string folder2aArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder2aName, UUID.Random()); + string folder2bArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder2bName, UUID.Random()); + + string iarPath1 = string.Join("", new string[] { folder1ArchiveName, folder2aArchiveName }); + string iarPath2 = string.Join("", new string[] { folder1ArchiveName, folder2bArchiveName }); + + { + // Test replication of path1 + new InventoryArchiveReadRequest(scene, ua1, null, (Stream)null, false) + .ReplicateArchivePathToUserInventory( + iarPath1, scene.InventoryService.GetRootFolder(ua1.PrincipalID), + foldersCreated, nodesLoaded); + + List folder1Candidates + = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, ua1.PrincipalID, folder1Name); + Assert.That(folder1Candidates.Count, Is.EqualTo(1)); + + InventoryFolderBase folder1 = folder1Candidates[0]; + List folder2aCandidates + = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, folder1, folder2aName); + Assert.That(folder2aCandidates.Count, Is.EqualTo(1)); + } + + { + // Test replication of path2 + new InventoryArchiveReadRequest(scene, ua1, null, (Stream)null, false) + .ReplicateArchivePathToUserInventory( + iarPath2, scene.InventoryService.GetRootFolder(ua1.PrincipalID), + foldersCreated, nodesLoaded); + + List folder1Candidates + = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, ua1.PrincipalID, folder1Name); + Assert.That(folder1Candidates.Count, Is.EqualTo(1)); + + InventoryFolderBase folder1 = folder1Candidates[0]; + + List folder2aCandidates + = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, folder1, folder2aName); + Assert.That(folder2aCandidates.Count, Is.EqualTo(1)); + + List folder2bCandidates + = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, folder1, folder2bName); + Assert.That(folder2bCandidates.Count, Is.EqualTo(1)); + } + } + + /// + /// Test replication of a partly existing archive path to the user's inventory. This should create + /// a duplicate path without the merge option. + /// + [Test] + public void TestPartExistingIarPath() + { + TestHelper.InMethod(); + //log4net.Config.XmlConfigurator.Configure(); + + Scene scene = SceneSetupHelpers.SetupScene("inventory"); + UserAccount ua1 = UserProfileTestUtils.CreateUserWithInventory(scene); + + string folder1ExistingName = "a"; + string folder2Name = "b"; + + InventoryFolderBase folder1 + = UserInventoryTestUtils.CreateInventoryFolder( + scene.InventoryService, ua1.PrincipalID, folder1ExistingName); + + string folder1ArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder1ExistingName, UUID.Random()); + string folder2ArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder2Name, UUID.Random()); + + string itemArchivePath = string.Join("", new string[] { folder1ArchiveName, folder2ArchiveName }); + + new InventoryArchiveReadRequest(scene, ua1, null, (Stream)null, false) + .ReplicateArchivePathToUserInventory( + itemArchivePath, scene.InventoryService.GetRootFolder(ua1.PrincipalID), + new Dictionary(), new HashSet()); + + List folder1PostCandidates + = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, ua1.PrincipalID, folder1ExistingName); + Assert.That(folder1PostCandidates.Count, Is.EqualTo(2)); + + // FIXME: Temporarily, we're going to do something messy to make sure we pick up the created folder. + InventoryFolderBase folder1Post = null; + foreach (InventoryFolderBase folder in folder1PostCandidates) + { + if (folder.ID != folder1.ID) + { + folder1Post = folder; + break; + } + } +// Assert.That(folder1Post.ID, Is.EqualTo(folder1.ID)); + + List folder2PostCandidates + = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, folder1Post, "b"); + Assert.That(folder2PostCandidates.Count, Is.EqualTo(1)); + } + + /// + /// Test replication of a partly existing archive path to the user's inventory. This should create + /// a merged path. + /// + [Test] + public void TestMergeIarPath() + { + TestHelper.InMethod(); +// log4net.Config.XmlConfigurator.Configure(); + + Scene scene = SceneSetupHelpers.SetupScene("inventory"); + UserAccount ua1 = UserProfileTestUtils.CreateUserWithInventory(scene); + + string folder1ExistingName = "a"; + string folder2Name = "b"; + + InventoryFolderBase folder1 + = UserInventoryTestUtils.CreateInventoryFolder( + scene.InventoryService, ua1.PrincipalID, folder1ExistingName); + + string folder1ArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder1ExistingName, UUID.Random()); + string folder2ArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder2Name, UUID.Random()); + + string itemArchivePath = string.Join("", new string[] { folder1ArchiveName, folder2ArchiveName }); + + new InventoryArchiveReadRequest(scene, ua1, folder1ExistingName, (Stream)null, true) + .ReplicateArchivePathToUserInventory( + itemArchivePath, scene.InventoryService.GetRootFolder(ua1.PrincipalID), + new Dictionary(), new HashSet()); + + List folder1PostCandidates + = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, ua1.PrincipalID, folder1ExistingName); + Assert.That(folder1PostCandidates.Count, Is.EqualTo(1)); + Assert.That(folder1PostCandidates[0].ID, Is.EqualTo(folder1.ID)); + + List folder2PostCandidates + = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, folder1PostCandidates[0], "b"); + Assert.That(folder2PostCandidates.Count, Is.EqualTo(1)); + } + } +} \ No newline at end of file diff --git a/OpenSim/Region/CoreModules/Framework/EntityTransfer/EntityTransferModule.cs b/OpenSim/Region/CoreModules/Framework/EntityTransfer/EntityTransferModule.cs index 9e1d414861..138556fc93 100644 --- a/OpenSim/Region/CoreModules/Framework/EntityTransfer/EntityTransferModule.cs +++ b/OpenSim/Region/CoreModules/Framework/EntityTransfer/EntityTransferModule.cs @@ -244,7 +244,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer } catch (Exception e) { - m_log.WarnFormat("[ENTITY TRANSFER MODULE]: Exception on teleport: {0}\n{1}", e.Message, e.StackTrace); + m_log.WarnFormat("[ENTITY TRANSFER MODULE]: Exception on teleport: {0} {1}", e.Message, e.StackTrace); sp.ControllingClient.SendTeleportFailed("Internal error"); } } @@ -285,9 +285,10 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer return; } - if (!m_aScene.SimulationService.QueryAccess(finalDestination, sp.ControllingClient.AgentId, Vector3.Zero)) + string reason; + if (!m_aScene.SimulationService.QueryAccess(finalDestination, sp.ControllingClient.AgentId, Vector3.Zero, out reason)) { - sp.ControllingClient.SendTeleportFailed("The destination region has refused access"); + sp.ControllingClient.SendTeleportFailed("Teleport failed: " + reason); return; } @@ -318,14 +319,12 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer agentCircuit.Id0 = currentAgentCircuit.Id0; } - if (NeedsNewAgent(oldRegionX, newRegionX, oldRegionY, newRegionY)) + if (NeedsNewAgent(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY)) { // brand new agent, let's create a new caps seed agentCircuit.CapsPath = CapsUtil.GetRandomCapsObjectPath(); } - string reason = String.Empty; - // Let's create an agent there if one doesn't exist yet. bool logout = false; if (!CreateAgent(sp, reg, finalDestination, agentCircuit, teleportFlags, out reason, out logout)) @@ -338,7 +337,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer // OK, it got this agent. Let's close some child agents sp.CloseChildAgents(newRegionX, newRegionY); IClientIPEndpoint ipepClient; - if (NeedsNewAgent(oldRegionX, newRegionX, oldRegionY, newRegionY)) + if (NeedsNewAgent(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY)) { //sp.ControllingClient.SendTeleportProgress(teleportFlags, "Creating agent..."); #region IP Translation for NAT @@ -401,6 +400,10 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer if (!UpdateAgent(reg, finalDestination, agent)) { // Region doesn't take it + m_log.WarnFormat( + "[ENTITY TRANSFER MODULE]: UpdateAgent failed on teleport of {0} to {1}. Returning avatar to source region.", + sp.Name, finalDestination.RegionName); + Fail(sp, finalDestination); return; } @@ -427,16 +430,18 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer // that the client contacted the destination before we send the attachments and close things here. if (!WaitForCallback(sp.UUID)) { - Fail(sp, finalDestination); + m_log.WarnFormat( + "[ENTITY TRANSFER MODULE]: Teleport of {0} to {1} failed due to no callback from destination region. Returning avatar to source region.", + sp.Name, finalDestination.RegionName); + + Fail(sp, finalDestination); return; } - // CrossAttachmentsIntoNewRegion is a synchronous call. We shouldn't need to wait after it CrossAttachmentsIntoNewRegion(finalDestination, sp, true); // Well, this is it. The agent is over there. - KillEntity(sp.Scene, sp.LocalId); // May need to logout or other cleanup @@ -449,7 +454,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer // Finally, let's close this previously-known-as-root agent, when the jump is outside the view zone - if (NeedsClosing(oldRegionX, newRegionX, oldRegionY, newRegionY, reg)) + if (NeedsClosing(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY, reg)) { Thread.Sleep(5000); sp.Close(); @@ -523,14 +528,14 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer return region; } - protected virtual bool NeedsNewAgent(uint oldRegionX, uint newRegionX, uint oldRegionY, uint newRegionY) + protected virtual bool NeedsNewAgent(float drawdist, uint oldRegionX, uint newRegionX, uint oldRegionY, uint newRegionY) { - return Util.IsOutsideView(oldRegionX, newRegionX, oldRegionY, newRegionY); + return Util.IsOutsideView(drawdist, oldRegionX, newRegionX, oldRegionY, newRegionY); } - protected virtual bool NeedsClosing(uint oldRegionX, uint newRegionX, uint oldRegionY, uint newRegionY, GridRegion reg) + protected virtual bool NeedsClosing(float drawdist, uint oldRegionX, uint newRegionX, uint oldRegionY, uint newRegionY, GridRegion reg) { - return Util.IsOutsideView(oldRegionX, newRegionX, oldRegionY, newRegionY); + return Util.IsOutsideView(drawdist, oldRegionX, newRegionX, oldRegionY, newRegionY); } protected virtual bool IsOutsideRegion(Scene s, Vector3 pos) @@ -797,7 +802,8 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer GridRegion neighbourRegion = scene.GridService.GetRegionByPosition(scene.RegionInfo.ScopeID, (int)x, (int)y); - if (!scene.SimulationService.QueryAccess(neighbourRegion, agent.ControllingClient.AgentId, newpos)) + string reason; + if (!scene.SimulationService.QueryAccess(neighbourRegion, agent.ControllingClient.AgentId, newpos, out reason)) { agent.ControllingClient.SendAlertMessage("Cannot region cross into banned parcel"); if (r == null) @@ -1006,7 +1012,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer /// public void EnableChildAgent(ScenePresence sp, GridRegion region) { - m_log.DebugFormat("[ENTITY TRANSFER]: Enabling child agent in new neighour {0}", region.RegionName); + m_log.DebugFormat("[ENTITY TRANSFER]: Enabling child agent in new neighbour {0}", region.RegionName); AgentCircuitData currentAgentCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode); AgentCircuitData agent = sp.ControllingClient.RequestClientInfo(); @@ -1072,7 +1078,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer if (m_regionInfo != null) { - neighbours = RequestNeighbours(sp.Scene, m_regionInfo.RegionLocX, m_regionInfo.RegionLocY); + neighbours = RequestNeighbours(sp, m_regionInfo.RegionLocX, m_regionInfo.RegionLocY); } else { @@ -1298,8 +1304,9 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer /// /// /// - protected List RequestNeighbours(Scene pScene, uint pRegionLocX, uint pRegionLocY) + protected List RequestNeighbours(ScenePresence avatar, uint pRegionLocX, uint pRegionLocY) { + Scene pScene = avatar.Scene; RegionInfo m_regionInfo = pScene.RegionInfo; Border[] northBorders = pScene.NorthBorders.ToArray(); @@ -1307,10 +1314,24 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer Border[] eastBorders = pScene.EastBorders.ToArray(); Border[] westBorders = pScene.WestBorders.ToArray(); - // Legacy one region. Provided for simplicity while testing the all inclusive method in the else statement. + // Leaving this as a "megaregions" computation vs "non-megaregions" computation; it isn't + // clear what should be done with a "far view" given that megaregions already extended the + // view to include everything in the megaregion if (northBorders.Length <= 1 && southBorders.Length <= 1 && eastBorders.Length <= 1 && westBorders.Length <= 1) { - return pScene.GridService.GetNeighbours(m_regionInfo.ScopeID, m_regionInfo.RegionID); + int dd = avatar.DrawDistance < Constants.RegionSize ? (int)Constants.RegionSize : (int)avatar.DrawDistance; + + int startX = (int)pRegionLocX * (int)Constants.RegionSize - dd + (int)(Constants.RegionSize/2); + int startY = (int)pRegionLocY * (int)Constants.RegionSize - dd + (int)(Constants.RegionSize/2); + + int endX = (int)pRegionLocX * (int)Constants.RegionSize + dd + (int)(Constants.RegionSize/2); + int endY = (int)pRegionLocY * (int)Constants.RegionSize + dd + (int)(Constants.RegionSize/2); + + List neighbours = + avatar.Scene.GridService.GetRegionRange(m_regionInfo.ScopeID, startX, endX, startY, endY); + + neighbours.RemoveAll(delegate(GridRegion r) { return r.RegionID == m_regionInfo.RegionID; }); + return neighbours; } else { diff --git a/OpenSim/Region/CoreModules/Framework/EntityTransfer/HGEntityTransferModule.cs b/OpenSim/Region/CoreModules/Framework/EntityTransfer/HGEntityTransferModule.cs index c75bc0a1bf..5a80100693 100644 --- a/OpenSim/Region/CoreModules/Framework/EntityTransfer/HGEntityTransferModule.cs +++ b/OpenSim/Region/CoreModules/Framework/EntityTransfer/HGEntityTransferModule.cs @@ -130,9 +130,9 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer return region; } - protected override bool NeedsClosing(uint oldRegionX, uint newRegionX, uint oldRegionY, uint newRegionY, GridRegion reg) + protected override bool NeedsClosing(float drawdist, uint oldRegionX, uint newRegionX, uint oldRegionY, uint newRegionY, GridRegion reg) { - if (base.NeedsClosing(oldRegionX, newRegionX, oldRegionY, newRegionY, reg)) + if (base.NeedsClosing(drawdist, oldRegionX, newRegionX, oldRegionY, newRegionY, reg)) return true; int flags = m_aScene.GridService.GetRegionFlags(m_aScene.RegionInfo.ScopeID, reg.RegionID); diff --git a/OpenSim/Region/CoreModules/Framework/InventoryAccess/HGInventoryAccessModule.cs b/OpenSim/Region/CoreModules/Framework/InventoryAccess/HGInventoryAccessModule.cs index 34b811428d..4565d103ff 100644 --- a/OpenSim/Region/CoreModules/Framework/InventoryAccess/HGInventoryAccessModule.cs +++ b/OpenSim/Region/CoreModules/Framework/InventoryAccess/HGInventoryAccessModule.cs @@ -55,6 +55,7 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess } private string m_ProfileServerURI; + private bool m_OutboundPermission; // private bool m_Initialized = false; @@ -78,7 +79,10 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess IConfig thisModuleConfig = source.Configs["HGInventoryAccessModule"]; if (thisModuleConfig != null) + { m_ProfileServerURI = thisModuleConfig.GetString("ProfileServerURI", string.Empty); + m_OutboundPermission = thisModuleConfig.GetBoolean("OutboundPermission", true); + } else m_log.Warn("[HG INVENTORY ACCESS MODULE]: HGInventoryAccessModule configs not found. ProfileServerURI not set!"); } @@ -103,7 +107,7 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess public void UploadInventoryItem(UUID avatarID, UUID assetID, string name, int userlevel) { string userAssetServer = string.Empty; - if (IsForeignUser(avatarID, out userAssetServer)) + if (IsForeignUser(avatarID, out userAssetServer) && m_OutboundPermission) { Util.FireAndForget(delegate { m_assMapper.Post(assetID, avatarID, userAssetServer); }); } @@ -197,7 +201,7 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess if (IsForeignUser(sender, out userAssetServer)) m_assMapper.Get(item.AssetID, sender, userAssetServer); - if (IsForeignUser(receiver, out userAssetServer)) + if (IsForeignUser(receiver, out userAssetServer) && m_OutboundPermission) m_assMapper.Post(item.AssetID, receiver, userAssetServer); } diff --git a/OpenSim/Region/CoreModules/Framework/InventoryAccess/InventoryAccessModule.cs b/OpenSim/Region/CoreModules/Framework/InventoryAccess/InventoryAccessModule.cs index 0163060eb9..108c9a0edc 100644 --- a/OpenSim/Region/CoreModules/Framework/InventoryAccess/InventoryAccessModule.cs +++ b/OpenSim/Region/CoreModules/Framework/InventoryAccess/InventoryAccessModule.cs @@ -149,6 +149,9 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId); item = m_Scene.InventoryService.GetItem(item); + if (item.Owner != remoteClient.AgentId) + return UUID.Zero; + if (item != null) { if ((InventoryType)item.InvType == InventoryType.Notecard) @@ -604,6 +607,7 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess { m_log.Debug("[InventoryAccessModule]: Inventory object has UUID.Zero! Position 1"); } + item.Owner = remoteClient.AgentId; AssetBase rezAsset = m_Scene.AssetService.Get(item.AssetID.ToString()); diff --git a/OpenSim/Region/CoreModules/LightShare/LightShareModule.cs b/OpenSim/Region/CoreModules/LightShare/LightShareModule.cs index 88f392dcdb..2de8d7a29b 100644 --- a/OpenSim/Region/CoreModules/LightShare/LightShareModule.cs +++ b/OpenSim/Region/CoreModules/LightShare/LightShareModule.cs @@ -75,7 +75,7 @@ namespace OpenSim.Region.CoreModules.World.LightShare m_scene = scene; m_scene.RegisterModuleInterface(this); m_scene.EventManager.OnPluginConsole += EventManager_OnPluginConsole; - + // ini file settings try { @@ -148,7 +148,7 @@ namespace OpenSim.Region.CoreModules.World.LightShare public void SendProfileToClient(ScenePresence presence) { IClientAPI client = presence.ControllingClient; - if (m_enableWindlight) + if (m_enableWindlight && m_scene.RegionInfo.WindlightSettings.valid) { if (presence.IsChildAgent == false) { @@ -165,7 +165,7 @@ namespace OpenSim.Region.CoreModules.World.LightShare public void SendProfileToClient(ScenePresence presence, RegionLightShareData wl) { IClientAPI client = presence.ControllingClient; - if (m_enableWindlight) + if (m_enableWindlight && m_scene.RegionInfo.WindlightSettings.valid) { if (presence.IsChildAgent == false) { @@ -229,7 +229,7 @@ namespace OpenSim.Region.CoreModules.World.LightShare { Command wlload = new Command("load", CommandIntentions.COMMAND_NON_HAZARDOUS, HandleLoad, "Load windlight profile from the database and broadcast"); Command wlenable = new Command("enable", CommandIntentions.COMMAND_NON_HAZARDOUS, HandleEnable, "Enable the windlight plugin"); - Command wldisable = new Command("disable", CommandIntentions.COMMAND_NON_HAZARDOUS, HandleDisable, "Enable the windlight plugin"); + Command wldisable = new Command("disable", CommandIntentions.COMMAND_NON_HAZARDOUS, HandleDisable, "Disable the windlight plugin"); m_commander.RegisterCommand("load", wlload); m_commander.RegisterCommand("enable", wlenable); diff --git a/OpenSim/Region/CoreModules/Resources/CoreModulePlugin.addin.xml b/OpenSim/Region/CoreModules/Resources/CoreModulePlugin.addin.xml index 43de2abd15..a9d247a2b8 100644 --- a/OpenSim/Region/CoreModules/Resources/CoreModulePlugin.addin.xml +++ b/OpenSim/Region/CoreModules/Resources/CoreModulePlugin.addin.xml @@ -47,7 +47,6 @@ - diff --git a/OpenSim/Region/CoreModules/Scripting/LSLHttp/UrlModule.cs b/OpenSim/Region/CoreModules/Scripting/LSLHttp/UrlModule.cs index 66eb7473a0..bdbd0c2305 100644 --- a/OpenSim/Region/CoreModules/Scripting/LSLHttp/UrlModule.cs +++ b/OpenSim/Region/CoreModules/Scripting/LSLHttp/UrlModule.cs @@ -77,7 +77,7 @@ namespace OpenSim.Region.CoreModules.Scripting.LSLHttp new Dictionary(); - private int m_TotalUrls = 1000; + private int m_TotalUrls = 5000; private IHttpServer m_HttpServer = null; diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Authorization/RemoteAuthorizationServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Authorization/RemoteAuthorizationServiceConnector.cs index 01a2615dc0..66994facff 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Authorization/RemoteAuthorizationServiceConnector.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Authorization/RemoteAuthorizationServiceConnector.cs @@ -139,7 +139,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Authorization if (scene != null) { - UserAccount account = scene.UserAccountService.GetUserAccount(UUID.Zero, userID); + UserAccount account = scene.UserAccountService.GetUserAccount(UUID.Zero, new UUID(userID)); isAuthorized = IsAuthorizedForRegion(userID, account.FirstName, account.LastName, account.Email, scene.RegionInfo.RegionName, regionID, out message); } diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/LocalGridServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/LocalGridServiceConnector.cs index 023a44c601..3c36799050 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/LocalGridServiceConnector.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/LocalGridServiceConnector.cs @@ -247,13 +247,17 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid public void NeighboursCommand(string module, string[] cmdparams) { + System.Text.StringBuilder caps = new System.Text.StringBuilder(); + foreach (KeyValuePair kvp in m_LocalCache) { - m_log.InfoFormat("*** Neighbours of {0} {1} ***", kvp.Key, kvp.Value.RegionName); + caps.AppendFormat("*** Neighbours of {0} ({1}) ***\n", kvp.Value.RegionName, kvp.Key); List regions = kvp.Value.GetNeighbours(); foreach (GridRegion r in regions) - m_log.InfoFormat(" {0} @ {1}={2}", r.RegionName, r.RegionLocX / Constants.RegionSize, r.RegionLocY / Constants.RegionSize); + caps.AppendFormat(" {0} @ {1}-{2}\n", r.RegionName, r.RegionLocX / Constants.RegionSize, r.RegionLocY / Constants.RegionSize); } + + MainConsole.Instance.Output(caps.ToString()); } } diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/Tests/GridConnectorsTests.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/Tests/GridConnectorsTests.cs index ebfba2b83a..7128d2b295 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/Tests/GridConnectorsTests.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/Tests/GridConnectorsTests.cs @@ -32,7 +32,6 @@ using System.Reflection; using System.Threading; using log4net.Config; using NUnit.Framework; -using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenSim.Framework; using Nini.Config; diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/HGInventoryBroker.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/HGInventoryBroker.cs index 39410b561b..3f63db371f 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/HGInventoryBroker.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/HGInventoryBroker.cs @@ -200,6 +200,11 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory return; } } + else + { + m_log.DebugFormat("[HG INVENTORY CONNECTOR]: User {0} does not have InventoryServerURI. OH NOES!", userID); + return; + } } } } diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/RemoteInventoryServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/RemoteInventoryServiceConnector.cs deleted file mode 100644 index 9213132866..0000000000 --- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/RemoteInventoryServiceConnector.cs +++ /dev/null @@ -1,362 +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 log4net; -using System; -using System.Collections.Generic; -using System.Reflection; -using Nini.Config; -using OpenSim.Framework; -using OpenSim.Framework.Statistics; -using OpenSim.Services.Connectors; -using OpenSim.Region.Framework.Interfaces; -using OpenSim.Region.Framework.Scenes; -using OpenSim.Services.Interfaces; -using OpenMetaverse; - -namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory -{ - public class RemoteInventoryServicesConnector : BaseInventoryConnector, ISharedRegionModule, IInventoryService - { - private static readonly ILog m_log = - LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private bool m_Enabled = false; - private bool m_Initialized = false; - private Scene m_Scene; - private InventoryServicesConnector m_RemoteConnector; - - private IUserManagement m_UserManager; - private IUserManagement UserManager - { - get - { - if (m_UserManager == null) - { - m_UserManager = m_Scene.RequestModuleInterface(); - } - return m_UserManager; - } - } - - - public Type ReplaceableInterface - { - get { return null; } - } - - public string Name - { - get { return "RemoteInventoryServicesConnector"; } - } - - public RemoteInventoryServicesConnector() - { - } - - public RemoteInventoryServicesConnector(IConfigSource source) - { - Init(source); - } - - protected override void Init(IConfigSource source) - { - m_RemoteConnector = new InventoryServicesConnector(source); - base.Init(source); - } - - #region ISharedRegionModule - - public void Initialise(IConfigSource source) - { - IConfig moduleConfig = source.Configs["Modules"]; - if (moduleConfig != null) - { - string name = moduleConfig.GetString("InventoryServices", ""); - if (name == Name) - { - Init(source); - m_Enabled = true; - - m_log.Info("[INVENTORY CONNECTOR]: Remote inventory enabled"); - } - } - } - - public void PostInitialise() - { - } - - public void Close() - { - } - - public void AddRegion(Scene scene) - { -// m_Scene = scene; - //m_log.Debug("[XXXX] Adding scene " + m_Scene.RegionInfo.RegionName); - - if (!m_Enabled) - return; - - if (!m_Initialized) - { - m_Initialized = true; - } - - scene.RegisterModuleInterface(this); - m_cache.AddRegion(scene); - - if (m_Scene == null) - m_Scene = scene; - } - - public void RemoveRegion(Scene scene) - { - if (!m_Enabled) - return; - - m_cache.RemoveRegion(scene); - } - - public void RegionLoaded(Scene scene) - { - if (!m_Enabled) - return; - - m_log.InfoFormat("[INVENTORY CONNECTOR]: Enabled remote inventory for region {0}", scene.RegionInfo.RegionName); - - } - - #endregion ISharedRegionModule - - #region IInventoryService - - public override bool CreateUserInventory(UUID user) - { - return false; - } - - public override List GetInventorySkeleton(UUID userId) - { - return new List(); - } - - public override InventoryCollection GetUserInventory(UUID userID) - { - return null; - } - - public override void GetUserInventory(UUID userID, InventoryReceiptCallback callback) - { - UUID sessionID = GetSessionID(userID); - try - { - m_RemoteConnector.GetUserInventory(userID.ToString(), sessionID, callback); - } - catch (Exception e) - { - if (StatsManager.SimExtraStats != null) - StatsManager.SimExtraStats.AddInventoryServiceRetrievalFailure(); - - m_log.ErrorFormat("[INVENTORY CONNECTOR]: Request inventory operation failed, {0} {1}", - e.Source, e.Message); - } - - } - - // inherited. See base class - // public InventoryFolderBase GetFolderForType(UUID userID, AssetType type) - - public override Dictionary GetSystemFolders(UUID userID) - { - UUID sessionID = GetSessionID(userID); - return m_RemoteConnector.GetSystemFolders(userID.ToString(), sessionID); - } - - public override InventoryCollection GetFolderContent(UUID userID, UUID folderID) - { - UUID sessionID = GetSessionID(userID); - try - { - InventoryCollection invCol = m_RemoteConnector.GetFolderContent(userID.ToString(), folderID, sessionID); - foreach (InventoryItemBase item in invCol.Items) - UserManager.AddUser(item.CreatorIdAsUuid, item.CreatorData); - return invCol; - } - catch (Exception e) - { - m_log.ErrorFormat("[INVENTORY CONNECTOR]: GetFolderContent operation failed, {0} {1}", - e.Source, e.Message); - } - InventoryCollection nullCollection = new InventoryCollection(); - nullCollection.Folders = new List(); - nullCollection.Items = new List(); - nullCollection.UserID = userID; - return nullCollection; - } - - public override List GetFolderItems(UUID userID, UUID folderID) - { - UUID sessionID = GetSessionID(userID); - return m_RemoteConnector.GetFolderItems(userID.ToString(), folderID, sessionID); - } - - public override bool AddFolder(InventoryFolderBase folder) - { - if (folder == null) - return false; - - UUID sessionID = GetSessionID(folder.Owner); - return m_RemoteConnector.AddFolder(folder.Owner.ToString(), folder, sessionID); - } - - public override bool UpdateFolder(InventoryFolderBase folder) - { - if (folder == null) - return false; - - UUID sessionID = GetSessionID(folder.Owner); - return m_RemoteConnector.UpdateFolder(folder.Owner.ToString(), folder, sessionID); - } - - public override bool MoveFolder(InventoryFolderBase folder) - { - if (folder == null) - return false; - - UUID sessionID = GetSessionID(folder.Owner); - return m_RemoteConnector.MoveFolder(folder.Owner.ToString(), folder, sessionID); - } - - public override bool DeleteFolders(UUID ownerID, List folderIDs) - { - if (folderIDs == null) - return false; - if (folderIDs.Count == 0) - return false; - - UUID sessionID = GetSessionID(ownerID); - return m_RemoteConnector.DeleteFolders(ownerID.ToString(), folderIDs, sessionID); - } - - - public override bool PurgeFolder(InventoryFolderBase folder) - { - if (folder == null) - return false; - - UUID sessionID = GetSessionID(folder.Owner); - return m_RemoteConnector.PurgeFolder(folder.Owner.ToString(), folder, sessionID); - } - - // public bool AddItem(InventoryItemBase item) inherited - // Uses AddItemPlain - - protected override bool AddItemPlain(InventoryItemBase item) - { - if (item == null) - return false; - - UUID sessionID = GetSessionID(item.Owner); - return m_RemoteConnector.AddItem(item.Owner.ToString(), item, sessionID); - } - - public override bool UpdateItem(InventoryItemBase item) - { - if (item == null) - return false; - - UUID sessionID = GetSessionID(item.Owner); - return m_RemoteConnector.UpdateItem(item.Owner.ToString(), item, sessionID); - } - - public override bool MoveItems(UUID ownerID, List items) - { - if (items == null) - return false; - - UUID sessionID = GetSessionID(ownerID); - return m_RemoteConnector.MoveItems(ownerID.ToString(), items, sessionID); - } - - - public override bool DeleteItems(UUID ownerID, List itemIDs) - { - if (itemIDs == null) - return false; - if (itemIDs.Count == 0) - return true; - - UUID sessionID = GetSessionID(ownerID); - return m_RemoteConnector.DeleteItems(ownerID.ToString(), itemIDs, sessionID); - } - - public override InventoryItemBase GetItem(InventoryItemBase item) - { - if (item == null) - return null; - - UUID sessionID = GetSessionID(item.Owner); - return m_RemoteConnector.QueryItem(item.Owner.ToString(), item, sessionID); - } - - public override InventoryFolderBase GetFolder(InventoryFolderBase folder) - { - if (folder == null) - return null; - - UUID sessionID = GetSessionID(folder.Owner); - return m_RemoteConnector.QueryFolder(folder.Owner.ToString(), folder, sessionID); - } - - public override bool HasInventoryForUser(UUID userID) - { - return false; - } - - public override List GetActiveGestures(UUID userId) - { - return new List(); - } - - public override int GetAssetPermissions(UUID userID, UUID assetID) - { - UUID sessionID = GetSessionID(userID); - return m_RemoteConnector.GetAssetPermissions(userID.ToString(), assetID, sessionID); - } - - - #endregion - - private UUID GetSessionID(UUID userID) - { - return UUID.Zero; - } - - } -} diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/Tests/PresenceConnectorsTests.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/Tests/PresenceConnectorsTests.cs index ef910f4c26..e471f756d0 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/Tests/PresenceConnectorsTests.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/Tests/PresenceConnectorsTests.cs @@ -32,7 +32,6 @@ using System.Reflection; using System.Threading; using log4net.Config; using NUnit.Framework; -using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenSim.Framework; using Nini.Config; diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Simulation/LocalSimulationConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Simulation/LocalSimulationConnector.cs index 971a56f979..41dbffb329 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Simulation/LocalSimulationConnector.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Simulation/LocalSimulationConnector.cs @@ -225,17 +225,17 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation if (destination == null) return false; + // We limit the number of messages sent for a position change to just one per + // simulator so when we receive the update we need to hand it to each of the + // scenes; scenes each check to see if the is a scene presence for the avatar + // note that we really don't need the GridRegion for this call foreach (Scene s in m_sceneList) { - if (s.RegionInfo.RegionHandle == destination.RegionHandle) - { - //m_log.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate"); - s.IncomingChildAgentDataUpdate(cAgentData); - return true; - } + //m_log.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate"); + s.IncomingChildAgentDataUpdate(cAgentData); } //m_log.Debug("[LOCAL COMMS]: region not found for ChildAgentUpdate"); - return false; + return true; } public bool RetrieveAgent(GridRegion destination, UUID id, out IAgentData agent) @@ -257,15 +257,16 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation return false; } - public bool QueryAccess(GridRegion destination, UUID id, Vector3 position) + public bool QueryAccess(GridRegion destination, UUID id, Vector3 position, out string reason) { + reason = "Communications failure"; if (destination == null) return false; foreach (Scene s in m_sceneList) { if (s.RegionInfo.RegionID == destination.RegionID) - return s.QueryAccess(id, position); + return s.QueryAccess(id, position, out reason); } return false; } diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Simulation/RemoteSimulationConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Simulation/RemoteSimulationConnector.cs index e8a662910b..97833f3a9b 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Simulation/RemoteSimulationConnector.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Simulation/RemoteSimulationConnector.cs @@ -192,15 +192,10 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation return false; // Try local first - if (m_localBackend.UpdateAgent(destination, cAgentData)) - return true; - - // else do the remote thing - if (!m_localBackend.IsLocalRegion(destination.RegionHandle)) - return m_remoteConnector.UpdateAgent(destination, cAgentData); - - return false; + if (m_localBackend.IsLocalRegion(destination.RegionHandle)) + return m_localBackend.UpdateAgent(destination, cAgentData); + return m_remoteConnector.UpdateAgent(destination, cAgentData); } public bool UpdateAgent(GridRegion destination, AgentPosition cAgentData) @@ -209,15 +204,10 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation return false; // Try local first - if (m_localBackend.UpdateAgent(destination, cAgentData)) - return true; - - // else do the remote thing - if (!m_localBackend.IsLocalRegion(destination.RegionHandle)) - return m_remoteConnector.UpdateAgent(destination, cAgentData); - - return false; + if (m_localBackend.IsLocalRegion(destination.RegionHandle)) + return m_localBackend.UpdateAgent(destination, cAgentData); + return m_remoteConnector.UpdateAgent(destination, cAgentData); } public bool RetrieveAgent(GridRegion destination, UUID id, out IAgentData agent) @@ -239,18 +229,19 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation } - public bool QueryAccess(GridRegion destination, UUID id, Vector3 position) + public bool QueryAccess(GridRegion destination, UUID id, Vector3 position, out string reason) { + reason = "Communications failure"; if (destination == null) return false; // Try local first - if (m_localBackend.QueryAccess(destination, id, position)) + if (m_localBackend.QueryAccess(destination, id, position, out reason)) return true; // else do the remote thing if (!m_localBackend.IsLocalRegion(destination.RegionHandle)) - return m_remoteConnector.QueryAccess(destination, id, position); + return m_remoteConnector.QueryAccess(destination, id, position, out reason); return false; diff --git a/OpenSim/Region/CoreModules/World/Archiver/Tests/ArchiverTests.cs b/OpenSim/Region/CoreModules/World/Archiver/Tests/ArchiverTests.cs index 04b6e3d3f9..e2760a2065 100644 --- a/OpenSim/Region/CoreModules/World/Archiver/Tests/ArchiverTests.cs +++ b/OpenSim/Region/CoreModules/World/Archiver/Tests/ArchiverTests.cs @@ -32,7 +32,6 @@ using System.Reflection; using System.Threading; using log4net.Config; using NUnit.Framework; -using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenMetaverse.Assets; using OpenSim.Framework; diff --git a/OpenSim/Region/CoreModules/World/Estate/EstateManagementCommands.cs b/OpenSim/Region/CoreModules/World/Estate/EstateManagementCommands.cs new file mode 100644 index 0000000000..f6d1a826c7 --- /dev/null +++ b/OpenSim/Region/CoreModules/World/Estate/EstateManagementCommands.cs @@ -0,0 +1,224 @@ +/* + * 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.IO; +using System.Reflection; +using System.Security; +using System.Text; +using log4net; +using Nini.Config; +using OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Framework.Console; +using OpenSim.Region.CoreModules.Framework.InterfaceCommander; +using OpenSim.Region.Framework.Interfaces; +using OpenSim.Region.Framework.Scenes; + +namespace OpenSim.Region.CoreModules.World.Estate +{ + /// + /// Estate management console commands. + /// + public class EstateManagementCommands + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + protected EstateManagementModule m_module; + + protected Commander m_commander = new Commander("estate"); + + public EstateManagementCommands(EstateManagementModule module) + { + m_module = module; + } + + public void Initialise() + { + m_log.DebugFormat("[ESTATE MODULE]: Setting up estate commands for region {0}", m_module.Scene.RegionInfo.RegionName); + + m_module.Scene.AddCommand(m_module, "set terrain texture", + "set terrain texture [] []", + "Sets the terrain to , if or are specified, it will only " + + "set it on regions with a matching coordinate. Specify -1 in or to wildcard" + + " that coordinate.", + consoleSetTerrainTexture); + + m_module.Scene.AddCommand(m_module, "set terrain heights", + "set terrain heights [] []", + "Sets the terrain texture heights on corner # to /, if or are specified, it will only " + + "set it on regions with a matching coordinate. Specify -1 in or to wildcard" + + " that coordinate. Corner # SW = 0, NW = 1, SE = 2, NE = 3.", + consoleSetTerrainHeights); + + Command showCommand + = new Command("show", CommandIntentions.COMMAND_STATISTICAL, ShowEstatesCommand, "Shows all estates on the simulator."); + + m_commander.RegisterCommand("show", showCommand); + + m_module.Scene.RegisterModuleCommander(m_commander); + + m_module.Scene.EventManager.OnPluginConsole += EventManagerOnPluginConsole; + } + + public void Close() + { + m_module.Scene.EventManager.OnPluginConsole -= EventManagerOnPluginConsole; + m_module.Scene.UnregisterModuleCommander(m_commander.Name); + } + + /// + /// Processes commandline input. Do not call directly. + /// + /// Commandline arguments + protected void EventManagerOnPluginConsole(string[] args) + { + if (args[0] == "estate") + { + if (args.Length == 1) + { + m_commander.ProcessConsoleCommand("help", new string[0]); + return; + } + + string[] tmpArgs = new string[args.Length - 2]; + int i; + for (i = 2; i < args.Length; i++) + tmpArgs[i - 2] = args[i]; + + m_commander.ProcessConsoleCommand(args[1], tmpArgs); + } + } + + protected void consoleSetTerrainTexture(string module, string[] args) + { + string num = args[3]; + string uuid = args[4]; + int x = (args.Length > 5 ? int.Parse(args[5]) : -1); + int y = (args.Length > 6 ? int.Parse(args[6]) : -1); + + if (x == -1 || m_module.Scene.RegionInfo.RegionLocX == x) + { + if (y == -1 || m_module.Scene.RegionInfo.RegionLocY == y) + { + int corner = int.Parse(num); + UUID texture = UUID.Parse(uuid); + + m_log.Debug("[ESTATEMODULE]: Setting terrain textures for " + m_module.Scene.RegionInfo.RegionName + + string.Format(" (C#{0} = {1})", corner, texture)); + + switch (corner) + { + case 0: + m_module.Scene.RegionInfo.RegionSettings.TerrainTexture1 = texture; + break; + case 1: + m_module.Scene.RegionInfo.RegionSettings.TerrainTexture2 = texture; + break; + case 2: + m_module.Scene.RegionInfo.RegionSettings.TerrainTexture3 = texture; + break; + case 3: + m_module.Scene.RegionInfo.RegionSettings.TerrainTexture4 = texture; + break; + } + + m_module.Scene.RegionInfo.RegionSettings.Save(); + m_module.TriggerRegionInfoChange(); + m_module.sendRegionInfoPacketToAll(); + } + } + } + + protected void consoleSetTerrainHeights(string module, string[] args) + { + string num = args[3]; + string min = args[4]; + string max = args[5]; + int x = (args.Length > 6 ? int.Parse(args[6]) : -1); + int y = (args.Length > 7 ? int.Parse(args[7]) : -1); + + if (x == -1 || m_module.Scene.RegionInfo.RegionLocX == x) + { + if (y == -1 || m_module.Scene.RegionInfo.RegionLocY == y) + { + int corner = int.Parse(num); + float lowValue = float.Parse(min, Culture.NumberFormatInfo); + float highValue = float.Parse(max, Culture.NumberFormatInfo); + + m_log.Debug("[ESTATEMODULE]: Setting terrain heights " + m_module.Scene.RegionInfo.RegionName + + string.Format(" (C{0}, {1}-{2}", corner, lowValue, highValue)); + + switch (corner) + { + case 0: + m_module.Scene.RegionInfo.RegionSettings.Elevation1SW = lowValue; + m_module.Scene.RegionInfo.RegionSettings.Elevation2SW = highValue; + break; + case 1: + m_module.Scene.RegionInfo.RegionSettings.Elevation1NW = lowValue; + m_module.Scene.RegionInfo.RegionSettings.Elevation2NW = highValue; + break; + case 2: + m_module.Scene.RegionInfo.RegionSettings.Elevation1SE = lowValue; + m_module.Scene.RegionInfo.RegionSettings.Elevation2SE = highValue; + break; + case 3: + m_module.Scene.RegionInfo.RegionSettings.Elevation1NE = lowValue; + m_module.Scene.RegionInfo.RegionSettings.Elevation2NE = highValue; + break; + } + + m_module.Scene.RegionInfo.RegionSettings.Save(); + m_module.TriggerRegionInfoChange(); + m_module.sendRegionHandshakeToAll(); + } + } + } + + protected void ShowEstatesCommand(Object[] args) + { + StringBuilder report = new StringBuilder(); + RegionInfo ri = m_module.Scene.RegionInfo; + EstateSettings es = ri.EstateSettings; + + report.AppendFormat("Estate information for region {0}\n", ri.RegionName); + report.AppendFormat( + "{0,-20} {1,-7} {2,-20}\n", + "Estate Name", + "ID", + "Owner"); + + report.AppendFormat( + "{0,-20} {1,-7} {2,-20}\n", + es.EstateName, es.EstateID, m_module.UserManager.GetUserName(es.EstateOwner)); + + MainConsole.Instance.Output(report.ToString()); + } + } +} \ No newline at end of file diff --git a/OpenSim/Region/CoreModules/World/Estate/EstateManagementModule.cs b/OpenSim/Region/CoreModules/World/Estate/EstateManagementModule.cs index 36538429c9..c146b724df 100644 --- a/OpenSim/Region/CoreModules/World/Estate/EstateManagementModule.cs +++ b/OpenSim/Region/CoreModules/World/Estate/EstateManagementModule.cs @@ -24,6 +24,7 @@ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ + using System; using System.Collections.Generic; using System.IO; @@ -31,6 +32,7 @@ using System.Reflection; using System.Security; using System.Timers; using log4net; +using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; @@ -39,14 +41,18 @@ using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules.World.Estate { - public class EstateManagementModule : IEstateModule + [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "EstateManagementModule")] + public class EstateManagementModule : IEstateModule, INonSharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private delegate void LookupUUIDS(List uuidLst); - private Scene m_scene; private Timer m_regionChangeTimer = new Timer(); + public Scene Scene { get; private set; } + public IUserManagement UserManager { get; private set; } + + protected EstateManagementCommands m_commands; private EstateTerrainXferHandler TerrainUploader; @@ -60,89 +66,89 @@ namespace OpenSim.Region.CoreModules.World.Estate { uint sun = 0; - if (!m_scene.RegionInfo.EstateSettings.UseGlobalTime) - sun=(uint)(m_scene.RegionInfo.EstateSettings.SunPosition*1024.0) + 0x1800; + if (!Scene.RegionInfo.EstateSettings.UseGlobalTime) + sun = (uint)(Scene.RegionInfo.EstateSettings.SunPosition * 1024.0) + 0x1800; UUID estateOwner; - estateOwner = m_scene.RegionInfo.EstateSettings.EstateOwner; + estateOwner = Scene.RegionInfo.EstateSettings.EstateOwner; - if (m_scene.Permissions.IsGod(remote_client.AgentId)) + if (Scene.Permissions.IsGod(remote_client.AgentId)) estateOwner = remote_client.AgentId; remote_client.SendDetailedEstateData(invoice, - m_scene.RegionInfo.EstateSettings.EstateName, - m_scene.RegionInfo.EstateSettings.EstateID, - m_scene.RegionInfo.EstateSettings.ParentEstateID, + Scene.RegionInfo.EstateSettings.EstateName, + Scene.RegionInfo.EstateSettings.EstateID, + Scene.RegionInfo.EstateSettings.ParentEstateID, GetEstateFlags(), sun, - m_scene.RegionInfo.RegionSettings.Covenant, - m_scene.RegionInfo.EstateSettings.AbuseEmail, + Scene.RegionInfo.RegionSettings.Covenant, + Scene.RegionInfo.EstateSettings.AbuseEmail, estateOwner); remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.EstateManagers, - m_scene.RegionInfo.EstateSettings.EstateManagers, - m_scene.RegionInfo.EstateSettings.EstateID); + Scene.RegionInfo.EstateSettings.EstateManagers, + Scene.RegionInfo.EstateSettings.EstateID); remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AccessOptions, - m_scene.RegionInfo.EstateSettings.EstateAccess, - m_scene.RegionInfo.EstateSettings.EstateID); + Scene.RegionInfo.EstateSettings.EstateAccess, + Scene.RegionInfo.EstateSettings.EstateID); remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AllowedGroups, - m_scene.RegionInfo.EstateSettings.EstateGroups, - m_scene.RegionInfo.EstateSettings.EstateID); + Scene.RegionInfo.EstateSettings.EstateGroups, + Scene.RegionInfo.EstateSettings.EstateID); remote_client.SendBannedUserList(invoice, - m_scene.RegionInfo.EstateSettings.EstateBans, - m_scene.RegionInfo.EstateSettings.EstateID); + Scene.RegionInfo.EstateSettings.EstateBans, + Scene.RegionInfo.EstateSettings.EstateID); } private void estateSetRegionInfoHandler(bool blockTerraform, bool noFly, bool allowDamage, bool blockLandResell, int maxAgents, float objectBonusFactor, int matureLevel, bool restrictPushObject, bool allowParcelChanges) { if (blockTerraform) - m_scene.RegionInfo.RegionSettings.BlockTerraform = true; + Scene.RegionInfo.RegionSettings.BlockTerraform = true; else - m_scene.RegionInfo.RegionSettings.BlockTerraform = false; + Scene.RegionInfo.RegionSettings.BlockTerraform = false; if (noFly) - m_scene.RegionInfo.RegionSettings.BlockFly = true; + Scene.RegionInfo.RegionSettings.BlockFly = true; else - m_scene.RegionInfo.RegionSettings.BlockFly = false; + Scene.RegionInfo.RegionSettings.BlockFly = false; if (allowDamage) - m_scene.RegionInfo.RegionSettings.AllowDamage = true; + Scene.RegionInfo.RegionSettings.AllowDamage = true; else - m_scene.RegionInfo.RegionSettings.AllowDamage = false; + Scene.RegionInfo.RegionSettings.AllowDamage = false; if (blockLandResell) - m_scene.RegionInfo.RegionSettings.AllowLandResell = false; + Scene.RegionInfo.RegionSettings.AllowLandResell = false; else - m_scene.RegionInfo.RegionSettings.AllowLandResell = true; + Scene.RegionInfo.RegionSettings.AllowLandResell = true; - m_scene.RegionInfo.RegionSettings.AgentLimit = (byte) maxAgents; + Scene.RegionInfo.RegionSettings.AgentLimit = (byte) maxAgents; - m_scene.RegionInfo.RegionSettings.ObjectBonus = objectBonusFactor; + Scene.RegionInfo.RegionSettings.ObjectBonus = objectBonusFactor; if (matureLevel <= 13) - m_scene.RegionInfo.RegionSettings.Maturity = 0; + Scene.RegionInfo.RegionSettings.Maturity = 0; else if (matureLevel <= 21) - m_scene.RegionInfo.RegionSettings.Maturity = 1; + Scene.RegionInfo.RegionSettings.Maturity = 1; else - m_scene.RegionInfo.RegionSettings.Maturity = 2; + Scene.RegionInfo.RegionSettings.Maturity = 2; if (restrictPushObject) - m_scene.RegionInfo.RegionSettings.RestrictPushing = true; + Scene.RegionInfo.RegionSettings.RestrictPushing = true; else - m_scene.RegionInfo.RegionSettings.RestrictPushing = false; + Scene.RegionInfo.RegionSettings.RestrictPushing = false; if (allowParcelChanges) - m_scene.RegionInfo.RegionSettings.AllowLandJoinDivide = true; + Scene.RegionInfo.RegionSettings.AllowLandJoinDivide = true; else - m_scene.RegionInfo.RegionSettings.AllowLandJoinDivide = false; + Scene.RegionInfo.RegionSettings.AllowLandJoinDivide = false; - m_scene.RegionInfo.RegionSettings.Save(); + Scene.RegionInfo.RegionSettings.Save(); TriggerRegionInfoChange(); sendRegionInfoPacketToAll(); @@ -156,19 +162,19 @@ namespace OpenSim.Region.CoreModules.World.Estate switch (corner) { case 0: - m_scene.RegionInfo.RegionSettings.TerrainTexture1 = texture; + Scene.RegionInfo.RegionSettings.TerrainTexture1 = texture; break; case 1: - m_scene.RegionInfo.RegionSettings.TerrainTexture2 = texture; + Scene.RegionInfo.RegionSettings.TerrainTexture2 = texture; break; case 2: - m_scene.RegionInfo.RegionSettings.TerrainTexture3 = texture; + Scene.RegionInfo.RegionSettings.TerrainTexture3 = texture; break; case 3: - m_scene.RegionInfo.RegionSettings.TerrainTexture4 = texture; + Scene.RegionInfo.RegionSettings.TerrainTexture4 = texture; break; } - m_scene.RegionInfo.RegionSettings.Save(); + Scene.RegionInfo.RegionSettings.Save(); TriggerRegionInfoChange(); sendRegionInfoPacketToAll(); } @@ -178,23 +184,23 @@ namespace OpenSim.Region.CoreModules.World.Estate switch (corner) { case 0: - m_scene.RegionInfo.RegionSettings.Elevation1SW = lowValue; - m_scene.RegionInfo.RegionSettings.Elevation2SW = highValue; + Scene.RegionInfo.RegionSettings.Elevation1SW = lowValue; + Scene.RegionInfo.RegionSettings.Elevation2SW = highValue; break; case 1: - m_scene.RegionInfo.RegionSettings.Elevation1NW = lowValue; - m_scene.RegionInfo.RegionSettings.Elevation2NW = highValue; + Scene.RegionInfo.RegionSettings.Elevation1NW = lowValue; + Scene.RegionInfo.RegionSettings.Elevation2NW = highValue; break; case 2: - m_scene.RegionInfo.RegionSettings.Elevation1SE = lowValue; - m_scene.RegionInfo.RegionSettings.Elevation2SE = highValue; + Scene.RegionInfo.RegionSettings.Elevation1SE = lowValue; + Scene.RegionInfo.RegionSettings.Elevation2SE = highValue; break; case 3: - m_scene.RegionInfo.RegionSettings.Elevation1NE = lowValue; - m_scene.RegionInfo.RegionSettings.Elevation2NE = highValue; + Scene.RegionInfo.RegionSettings.Elevation1NE = lowValue; + Scene.RegionInfo.RegionSettings.Elevation2NE = highValue; break; } - m_scene.RegionInfo.RegionSettings.Save(); + Scene.RegionInfo.RegionSettings.Save(); TriggerRegionInfoChange(); sendRegionInfoPacketToAll(); } @@ -210,30 +216,30 @@ namespace OpenSim.Region.CoreModules.World.Estate bool UseGlobal, bool EstateFixedSun, float EstateSunHour) { // Water Height - m_scene.RegionInfo.RegionSettings.WaterHeight = WaterHeight; + Scene.RegionInfo.RegionSettings.WaterHeight = WaterHeight; // Terraforming limits - m_scene.RegionInfo.RegionSettings.TerrainRaiseLimit = TerrainRaiseLimit; - m_scene.RegionInfo.RegionSettings.TerrainLowerLimit = TerrainLowerLimit; + Scene.RegionInfo.RegionSettings.TerrainRaiseLimit = TerrainRaiseLimit; + Scene.RegionInfo.RegionSettings.TerrainLowerLimit = TerrainLowerLimit; // Time of day / fixed sun - m_scene.RegionInfo.RegionSettings.UseEstateSun = UseEstateSun; - m_scene.RegionInfo.RegionSettings.FixedSun = UseFixedSun; - m_scene.RegionInfo.RegionSettings.SunPosition = SunHour; + Scene.RegionInfo.RegionSettings.UseEstateSun = UseEstateSun; + Scene.RegionInfo.RegionSettings.FixedSun = UseFixedSun; + Scene.RegionInfo.RegionSettings.SunPosition = SunHour; - m_scene.TriggerEstateSunUpdate(); + Scene.TriggerEstateSunUpdate(); //m_log.Debug("[ESTATE]: UFS: " + UseFixedSun.ToString()); //m_log.Debug("[ESTATE]: SunHour: " + SunHour.ToString()); sendRegionInfoPacketToAll(); - m_scene.RegionInfo.RegionSettings.Save(); + Scene.RegionInfo.RegionSettings.Save(); TriggerRegionInfoChange(); } private void handleEstateRestartSimRequest(IClientAPI remoteClient, int timeInSeconds) { - IRestartModule restartModule = m_scene.RequestModuleInterface(); + IRestartModule restartModule = Scene.RequestModuleInterface(); if (restartModule != null) { List times = new List(); @@ -254,8 +260,8 @@ namespace OpenSim.Region.CoreModules.World.Estate private void handleChangeEstateCovenantRequest(IClientAPI remoteClient, UUID estateCovenantID) { - m_scene.RegionInfo.RegionSettings.Covenant = estateCovenantID; - m_scene.RegionInfo.RegionSettings.Save(); + Scene.RegionInfo.RegionSettings.Covenant = estateCovenantID; + Scene.RegionInfo.RegionSettings.Save(); TriggerRegionInfoChange(); } @@ -263,17 +269,17 @@ namespace OpenSim.Region.CoreModules.World.Estate { // EstateAccessDelta handles Estate Managers, Sim Access, Sim Banlist, allowed Groups.. etc. - if (user == m_scene.RegionInfo.EstateSettings.EstateOwner) + if (user == Scene.RegionInfo.EstateSettings.EstateOwner) return; // never process EO if ((estateAccessType & 4) != 0) // User add { - if (m_scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, false) || m_scene.Permissions.BypassPermissions()) + if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true) || Scene.Permissions.BypassPermissions()) { - m_scene.RegionInfo.EstateSettings.AddEstateUser(user); - m_scene.RegionInfo.EstateSettings.Save(); + Scene.RegionInfo.EstateSettings.AddEstateUser(user); + Scene.RegionInfo.EstateSettings.Save(); TriggerEstateInfoChange(); - remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AccessOptions, m_scene.RegionInfo.EstateSettings.EstateAccess, m_scene.RegionInfo.EstateSettings.EstateID); + remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AccessOptions, Scene.RegionInfo.EstateSettings.EstateAccess, Scene.RegionInfo.EstateSettings.EstateID); } else { @@ -283,13 +289,13 @@ namespace OpenSim.Region.CoreModules.World.Estate } if ((estateAccessType & 8) != 0) // User remove { - if (m_scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, false) || m_scene.Permissions.BypassPermissions()) + if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true) || Scene.Permissions.BypassPermissions()) { - m_scene.RegionInfo.EstateSettings.RemoveEstateUser(user); - m_scene.RegionInfo.EstateSettings.Save(); + Scene.RegionInfo.EstateSettings.RemoveEstateUser(user); + Scene.RegionInfo.EstateSettings.Save(); TriggerEstateInfoChange(); - remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AccessOptions, m_scene.RegionInfo.EstateSettings.EstateAccess, m_scene.RegionInfo.EstateSettings.EstateID); + remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AccessOptions, Scene.RegionInfo.EstateSettings.EstateAccess, Scene.RegionInfo.EstateSettings.EstateID); } else { @@ -298,12 +304,12 @@ namespace OpenSim.Region.CoreModules.World.Estate } if ((estateAccessType & 16) != 0) // Group add { - if (m_scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, false) || m_scene.Permissions.BypassPermissions()) + if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true) || Scene.Permissions.BypassPermissions()) { - m_scene.RegionInfo.EstateSettings.AddEstateGroup(user); - m_scene.RegionInfo.EstateSettings.Save(); + Scene.RegionInfo.EstateSettings.AddEstateGroup(user); + Scene.RegionInfo.EstateSettings.Save(); TriggerEstateInfoChange(); - remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AllowedGroups, m_scene.RegionInfo.EstateSettings.EstateGroups, m_scene.RegionInfo.EstateSettings.EstateID); + remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AllowedGroups, Scene.RegionInfo.EstateSettings.EstateGroups, Scene.RegionInfo.EstateSettings.EstateID); } else { @@ -312,13 +318,13 @@ namespace OpenSim.Region.CoreModules.World.Estate } if ((estateAccessType & 32) != 0) // Group remove { - if (m_scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, false) || m_scene.Permissions.BypassPermissions()) + if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true) || Scene.Permissions.BypassPermissions()) { - m_scene.RegionInfo.EstateSettings.RemoveEstateGroup(user); - m_scene.RegionInfo.EstateSettings.Save(); + Scene.RegionInfo.EstateSettings.RemoveEstateGroup(user); + Scene.RegionInfo.EstateSettings.Save(); TriggerEstateInfoChange(); - remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AllowedGroups, m_scene.RegionInfo.EstateSettings.EstateGroups, m_scene.RegionInfo.EstateSettings.EstateID); + remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AllowedGroups, Scene.RegionInfo.EstateSettings.EstateGroups, Scene.RegionInfo.EstateSettings.EstateID); } else { @@ -327,9 +333,9 @@ namespace OpenSim.Region.CoreModules.World.Estate } if ((estateAccessType & 64) != 0) // Ban add { - if (m_scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, false) || m_scene.Permissions.BypassPermissions()) + if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, false) || Scene.Permissions.BypassPermissions()) { - EstateBan[] banlistcheck = m_scene.RegionInfo.EstateSettings.EstateBans; + EstateBan[] banlistcheck = Scene.RegionInfo.EstateSettings.EstateBans; bool alreadyInList = false; @@ -348,20 +354,20 @@ namespace OpenSim.Region.CoreModules.World.Estate EstateBan item = new EstateBan(); item.BannedUserID = user; - item.EstateID = m_scene.RegionInfo.EstateSettings.EstateID; + item.EstateID = Scene.RegionInfo.EstateSettings.EstateID; item.BannedHostAddress = "0.0.0.0"; item.BannedHostIPMask = "0.0.0.0"; - m_scene.RegionInfo.EstateSettings.AddBan(item); - m_scene.RegionInfo.EstateSettings.Save(); + Scene.RegionInfo.EstateSettings.AddBan(item); + Scene.RegionInfo.EstateSettings.Save(); TriggerEstateInfoChange(); - ScenePresence s = m_scene.GetScenePresence(user); + ScenePresence s = Scene.GetScenePresence(user); if (s != null) { if (!s.IsChildAgent) { - if (!m_scene.TeleportClientHome(user, s.ControllingClient)) + if (!Scene.TeleportClientHome(user, s.ControllingClient)) { s.ControllingClient.Kick("Your access to the region was revoked and TP home failed - you have been logged out."); s.ControllingClient.Close(); @@ -374,8 +380,8 @@ namespace OpenSim.Region.CoreModules.World.Estate { remote_client.SendAlertMessage("User is already on the region ban list"); } - //m_scene.RegionInfo.regionBanlist.Add(Manager(user); - remote_client.SendBannedUserList(invoice, m_scene.RegionInfo.EstateSettings.EstateBans, m_scene.RegionInfo.EstateSettings.EstateID); + //Scene.RegionInfo.regionBanlist.Add(Manager(user); + remote_client.SendBannedUserList(invoice, Scene.RegionInfo.EstateSettings.EstateBans, Scene.RegionInfo.EstateSettings.EstateID); } else { @@ -384,9 +390,9 @@ namespace OpenSim.Region.CoreModules.World.Estate } if ((estateAccessType & 128) != 0) // Ban remove { - if (m_scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, false) || m_scene.Permissions.BypassPermissions()) + if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, false) || Scene.Permissions.BypassPermissions()) { - EstateBan[] banlistcheck = m_scene.RegionInfo.EstateSettings.EstateBans; + EstateBan[] banlistcheck = Scene.RegionInfo.EstateSettings.EstateBans; bool alreadyInList = false; EstateBan listitem = null; @@ -399,20 +405,21 @@ namespace OpenSim.Region.CoreModules.World.Estate listitem = banlistcheck[i]; break; } - } + if (alreadyInList && listitem != null) { - m_scene.RegionInfo.EstateSettings.RemoveBan(listitem.BannedUserID); - m_scene.RegionInfo.EstateSettings.Save(); + Scene.RegionInfo.EstateSettings.RemoveBan(listitem.BannedUserID); + Scene.RegionInfo.EstateSettings.Save(); TriggerEstateInfoChange(); } else { remote_client.SendAlertMessage("User is not on the region ban list"); } - //m_scene.RegionInfo.regionBanlist.Add(Manager(user); - remote_client.SendBannedUserList(invoice, m_scene.RegionInfo.EstateSettings.EstateBans, m_scene.RegionInfo.EstateSettings.EstateID); + + //Scene.RegionInfo.regionBanlist.Add(Manager(user); + remote_client.SendBannedUserList(invoice, Scene.RegionInfo.EstateSettings.EstateBans, Scene.RegionInfo.EstateSettings.EstateID); } else { @@ -421,12 +428,12 @@ namespace OpenSim.Region.CoreModules.World.Estate } if ((estateAccessType & 256) != 0) // Manager add { - if (m_scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true) || m_scene.Permissions.BypassPermissions()) + if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true) || Scene.Permissions.BypassPermissions()) { - m_scene.RegionInfo.EstateSettings.AddEstateManager(user); - m_scene.RegionInfo.EstateSettings.Save(); + Scene.RegionInfo.EstateSettings.AddEstateManager(user); + Scene.RegionInfo.EstateSettings.Save(); TriggerEstateInfoChange(); - remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.EstateManagers, m_scene.RegionInfo.EstateSettings.EstateManagers, m_scene.RegionInfo.EstateSettings.EstateID); + remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.EstateManagers, Scene.RegionInfo.EstateSettings.EstateManagers, Scene.RegionInfo.EstateSettings.EstateID); } else { @@ -435,13 +442,13 @@ namespace OpenSim.Region.CoreModules.World.Estate } if ((estateAccessType & 512) != 0) // Manager remove { - if (m_scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true) || m_scene.Permissions.BypassPermissions()) + if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true) || Scene.Permissions.BypassPermissions()) { - m_scene.RegionInfo.EstateSettings.RemoveEstateManager(user); - m_scene.RegionInfo.EstateSettings.Save(); + Scene.RegionInfo.EstateSettings.RemoveEstateManager(user); + Scene.RegionInfo.EstateSettings.Save(); TriggerEstateInfoChange(); - remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.EstateManagers, m_scene.RegionInfo.EstateSettings.EstateManagers, m_scene.RegionInfo.EstateSettings.EstateID); + remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.EstateManagers, Scene.RegionInfo.EstateSettings.EstateManagers, Scene.RegionInfo.EstateSettings.EstateID); } else { @@ -453,7 +460,7 @@ namespace OpenSim.Region.CoreModules.World.Estate private void SendSimulatorBlueBoxMessage( IClientAPI remote_client, UUID invoice, UUID senderID, UUID sessionID, string senderName, string message) { - IDialogModule dm = m_scene.RequestModuleInterface(); + IDialogModule dm = Scene.RequestModuleInterface(); if (dm != null) dm.SendNotificationToUsersInRegion(senderID, senderName, message); @@ -468,38 +475,38 @@ namespace OpenSim.Region.CoreModules.World.Estate private void handleEstateDebugRegionRequest(IClientAPI remote_client, UUID invoice, UUID senderID, bool scripted, bool collisionEvents, bool physics) { if (physics) - m_scene.RegionInfo.RegionSettings.DisablePhysics = true; + Scene.RegionInfo.RegionSettings.DisablePhysics = true; else - m_scene.RegionInfo.RegionSettings.DisablePhysics = false; + Scene.RegionInfo.RegionSettings.DisablePhysics = false; if (scripted) - m_scene.RegionInfo.RegionSettings.DisableScripts = true; + Scene.RegionInfo.RegionSettings.DisableScripts = true; else - m_scene.RegionInfo.RegionSettings.DisableScripts = false; + Scene.RegionInfo.RegionSettings.DisableScripts = false; if (collisionEvents) - m_scene.RegionInfo.RegionSettings.DisableCollisions = true; + Scene.RegionInfo.RegionSettings.DisableCollisions = true; else - m_scene.RegionInfo.RegionSettings.DisableCollisions = false; + Scene.RegionInfo.RegionSettings.DisableCollisions = false; - m_scene.RegionInfo.RegionSettings.Save(); + Scene.RegionInfo.RegionSettings.Save(); TriggerRegionInfoChange(); - m_scene.SetSceneCoreDebug(scripted, collisionEvents, physics); + Scene.SetSceneCoreDebug(scripted, collisionEvents, physics); } private void handleEstateTeleportOneUserHomeRequest(IClientAPI remover_client, UUID invoice, UUID senderID, UUID prey) { - if (!m_scene.Permissions.CanIssueEstateCommand(remover_client.AgentId, false)) + if (!Scene.Permissions.CanIssueEstateCommand(remover_client.AgentId, false)) return; if (prey != UUID.Zero) { - ScenePresence s = m_scene.GetScenePresence(prey); + ScenePresence s = Scene.GetScenePresence(prey); if (s != null) { - if (!m_scene.TeleportClientHome(prey, s.ControllingClient)) + if (!Scene.TeleportClientHome(prey, s.ControllingClient)) { s.ControllingClient.Kick("You were teleported home by the region owner, but the TP failed - you have been logged out."); s.ControllingClient.Close(); @@ -510,19 +517,19 @@ namespace OpenSim.Region.CoreModules.World.Estate private void handleEstateTeleportAllUsersHomeRequest(IClientAPI remover_client, UUID invoice, UUID senderID) { - if (!m_scene.Permissions.CanIssueEstateCommand(remover_client.AgentId, false)) + if (!Scene.Permissions.CanIssueEstateCommand(remover_client.AgentId, false)) return; - m_scene.ForEachScenePresence(delegate(ScenePresence sp) + Scene.ForEachScenePresence(delegate(ScenePresence sp) { if (sp.UUID != senderID) { - ScenePresence p = m_scene.GetScenePresence(sp.UUID); + ScenePresence p = Scene.GetScenePresence(sp.UUID); // make sure they are still there, we could be working down a long list // Also make sure they are actually in the region if (p != null && !p.IsChildAgent) { - if (!m_scene.TeleportClientHome(p.UUID, p.ControllingClient)) + if (!Scene.TeleportClientHome(p.UUID, p.ControllingClient)) { p.ControllingClient.Kick("You were teleported home by the region owner, but the TP failed - you have been logged out."); p.ControllingClient.Close(); @@ -531,6 +538,7 @@ namespace OpenSim.Region.CoreModules.World.Estate } }); } + private void AbortTerrainXferHandler(IClientAPI remoteClient, ulong XferID) { if (TerrainUploader != null) @@ -561,11 +569,11 @@ namespace OpenSim.Region.CoreModules.World.Estate TerrainUploader = null; } remoteClient.SendAlertMessage("Terrain Upload Complete. Loading...."); - ITerrainModule terr = m_scene.RequestModuleInterface(); + ITerrainModule terr = Scene.RequestModuleInterface(); if (terr != null) { - m_log.Warn("[CLIENT]: Got Request to Send Terrain in region " + m_scene.RegionInfo.RegionName); + m_log.Warn("[CLIENT]: Got Request to Send Terrain in region " + Scene.RegionInfo.RegionName); try { @@ -611,7 +619,6 @@ namespace OpenSim.Region.CoreModules.World.Estate private void handleUploadTerrain(IClientAPI remote_client, string clientFileName) { - if (TerrainUploader == null) { @@ -629,16 +636,16 @@ namespace OpenSim.Region.CoreModules.World.Estate { remote_client.SendAlertMessage("Another Terrain Upload is in progress. Please wait your turn!"); } - } + private void handleTerrainRequest(IClientAPI remote_client, string clientFileName) { // Save terrain here - ITerrainModule terr = m_scene.RequestModuleInterface(); + ITerrainModule terr = Scene.RequestModuleInterface(); if (terr != null) { - m_log.Warn("[CLIENT]: Got Request to Send Terrain in region " + m_scene.RegionInfo.RegionName); + m_log.Warn("[CLIENT]: Got Request to Send Terrain in region " + Scene.RegionInfo.RegionName); if (File.Exists(Util.dataDir() + "/terrain.raw")) { File.Delete(Util.dataDir() + "/terrain.raw"); @@ -649,7 +656,7 @@ namespace OpenSim.Region.CoreModules.World.Estate byte[] bdata = new byte[input.Length]; input.Read(bdata, 0, (int)input.Length); remote_client.SendAlertMessage("Terrain file written, starting download..."); - m_scene.XferManager.AddNewFile("terrain.raw", bdata); + Scene.XferManager.AddNewFile("terrain.raw", bdata); // Tell client about it m_log.Warn("[CLIENT]: Sending Terrain to " + remote_client.Name); remote_client.SendInitiateDownload("terrain.raw", clientFileName); @@ -659,35 +666,35 @@ namespace OpenSim.Region.CoreModules.World.Estate private void HandleRegionInfoRequest(IClientAPI remote_client) { RegionInfoForEstateMenuArgs args = new RegionInfoForEstateMenuArgs(); - args.billableFactor = m_scene.RegionInfo.EstateSettings.BillableFactor; - args.estateID = m_scene.RegionInfo.EstateSettings.EstateID; - args.maxAgents = (byte)m_scene.RegionInfo.RegionSettings.AgentLimit; - args.objectBonusFactor = (float)m_scene.RegionInfo.RegionSettings.ObjectBonus; - args.parentEstateID = m_scene.RegionInfo.EstateSettings.ParentEstateID; - args.pricePerMeter = m_scene.RegionInfo.EstateSettings.PricePerMeter; - args.redirectGridX = m_scene.RegionInfo.EstateSettings.RedirectGridX; - args.redirectGridY = m_scene.RegionInfo.EstateSettings.RedirectGridY; + args.billableFactor = Scene.RegionInfo.EstateSettings.BillableFactor; + args.estateID = Scene.RegionInfo.EstateSettings.EstateID; + args.maxAgents = (byte)Scene.RegionInfo.RegionSettings.AgentLimit; + args.objectBonusFactor = (float)Scene.RegionInfo.RegionSettings.ObjectBonus; + args.parentEstateID = Scene.RegionInfo.EstateSettings.ParentEstateID; + args.pricePerMeter = Scene.RegionInfo.EstateSettings.PricePerMeter; + args.redirectGridX = Scene.RegionInfo.EstateSettings.RedirectGridX; + args.redirectGridY = Scene.RegionInfo.EstateSettings.RedirectGridY; args.regionFlags = GetRegionFlags(); - args.simAccess = m_scene.RegionInfo.AccessLevel; - args.sunHour = (float)m_scene.RegionInfo.RegionSettings.SunPosition; - args.terrainLowerLimit = (float)m_scene.RegionInfo.RegionSettings.TerrainLowerLimit; - args.terrainRaiseLimit = (float)m_scene.RegionInfo.RegionSettings.TerrainRaiseLimit; - args.useEstateSun = m_scene.RegionInfo.RegionSettings.UseEstateSun; - args.waterHeight = (float)m_scene.RegionInfo.RegionSettings.WaterHeight; - args.simName = m_scene.RegionInfo.RegionName; - args.regionType = m_scene.RegionInfo.RegionType; + args.simAccess = Scene.RegionInfo.AccessLevel; + args.sunHour = (float)Scene.RegionInfo.RegionSettings.SunPosition; + args.terrainLowerLimit = (float)Scene.RegionInfo.RegionSettings.TerrainLowerLimit; + args.terrainRaiseLimit = (float)Scene.RegionInfo.RegionSettings.TerrainRaiseLimit; + args.useEstateSun = Scene.RegionInfo.RegionSettings.UseEstateSun; + args.waterHeight = (float)Scene.RegionInfo.RegionSettings.WaterHeight; + args.simName = Scene.RegionInfo.RegionName; + args.regionType = Scene.RegionInfo.RegionType; remote_client.SendRegionInfoToEstateMenu(args); } private void HandleEstateCovenantRequest(IClientAPI remote_client) { - remote_client.SendEstateCovenantInformation(m_scene.RegionInfo.RegionSettings.Covenant); + remote_client.SendEstateCovenantInformation(Scene.RegionInfo.RegionSettings.Covenant); } private void HandleLandStatRequest(int parcelID, uint reportType, uint requestFlags, string filter, IClientAPI remoteClient) { - if (!m_scene.Permissions.CanIssueEstateCommand(remoteClient.AgentId, false)) + if (!Scene.Permissions.CanIssueEstateCommand(remoteClient.AgentId, false)) return; Dictionary SceneData = new Dictionary(); @@ -695,11 +702,11 @@ namespace OpenSim.Region.CoreModules.World.Estate if (reportType == 1) { - SceneData = m_scene.PhysicsScene.GetTopColliders(); + SceneData = Scene.PhysicsScene.GetTopColliders(); } else if (reportType == 0) { - SceneData = m_scene.SceneGraph.GetTopScripts(); + SceneData = Scene.SceneGraph.GetTopScripts(); } List SceneReport = new List(); @@ -707,7 +714,7 @@ namespace OpenSim.Region.CoreModules.World.Estate { foreach (uint obj in SceneData.Keys) { - SceneObjectPart prt = m_scene.GetSceneObjectPart(obj); + SceneObjectPart prt = Scene.GetSceneObjectPart(obj); if (prt != null) { if (prt.ParentGroup != null) @@ -777,9 +784,9 @@ namespace OpenSim.Region.CoreModules.World.Estate for (int i = 0; i < uuidarr.Length; i++) { - // string lookupname = m_scene.CommsManager.UUIDNameRequestString(uuidarr[i]); + // string lookupname = Scene.CommsManager.UUIDNameRequestString(uuidarr[i]); - IUserManagement userManager = m_scene.RequestModuleInterface(); + IUserManagement userManager = Scene.RequestModuleInterface(); if (userManager != null) userManager.GetUserName(uuidarr[i]); @@ -794,7 +801,7 @@ namespace OpenSim.Region.CoreModules.World.Estate public void sendRegionInfoPacketToAll() { - m_scene.ForEachScenePresence(delegate(ScenePresence sp) + Scene.ForEachScenePresence(delegate(ScenePresence sp) { if (!sp.IsChildAgent) HandleRegionInfoRequest(sp.ControllingClient); @@ -805,99 +812,99 @@ namespace OpenSim.Region.CoreModules.World.Estate { RegionHandshakeArgs args = new RegionHandshakeArgs(); - args.isEstateManager = m_scene.RegionInfo.EstateSettings.IsEstateManager(remoteClient.AgentId); - if (m_scene.RegionInfo.EstateSettings.EstateOwner != UUID.Zero && m_scene.RegionInfo.EstateSettings.EstateOwner == remoteClient.AgentId) + args.isEstateManager = Scene.RegionInfo.EstateSettings.IsEstateManager(remoteClient.AgentId); + if (Scene.RegionInfo.EstateSettings.EstateOwner != UUID.Zero && Scene.RegionInfo.EstateSettings.EstateOwner == remoteClient.AgentId) args.isEstateManager = true; - args.billableFactor = m_scene.RegionInfo.EstateSettings.BillableFactor; - args.terrainStartHeight0 = (float)m_scene.RegionInfo.RegionSettings.Elevation1SW; - args.terrainHeightRange0 = (float)m_scene.RegionInfo.RegionSettings.Elevation2SW; - args.terrainStartHeight1 = (float)m_scene.RegionInfo.RegionSettings.Elevation1NW; - args.terrainHeightRange1 = (float)m_scene.RegionInfo.RegionSettings.Elevation2NW; - args.terrainStartHeight2 = (float)m_scene.RegionInfo.RegionSettings.Elevation1SE; - args.terrainHeightRange2 = (float)m_scene.RegionInfo.RegionSettings.Elevation2SE; - args.terrainStartHeight3 = (float)m_scene.RegionInfo.RegionSettings.Elevation1NE; - args.terrainHeightRange3 = (float)m_scene.RegionInfo.RegionSettings.Elevation2NE; - args.simAccess = m_scene.RegionInfo.AccessLevel; - args.waterHeight = (float)m_scene.RegionInfo.RegionSettings.WaterHeight; + args.billableFactor = Scene.RegionInfo.EstateSettings.BillableFactor; + args.terrainStartHeight0 = (float)Scene.RegionInfo.RegionSettings.Elevation1SW; + args.terrainHeightRange0 = (float)Scene.RegionInfo.RegionSettings.Elevation2SW; + args.terrainStartHeight1 = (float)Scene.RegionInfo.RegionSettings.Elevation1NW; + args.terrainHeightRange1 = (float)Scene.RegionInfo.RegionSettings.Elevation2NW; + args.terrainStartHeight2 = (float)Scene.RegionInfo.RegionSettings.Elevation1SE; + args.terrainHeightRange2 = (float)Scene.RegionInfo.RegionSettings.Elevation2SE; + args.terrainStartHeight3 = (float)Scene.RegionInfo.RegionSettings.Elevation1NE; + args.terrainHeightRange3 = (float)Scene.RegionInfo.RegionSettings.Elevation2NE; + args.simAccess = Scene.RegionInfo.AccessLevel; + args.waterHeight = (float)Scene.RegionInfo.RegionSettings.WaterHeight; args.regionFlags = GetRegionFlags(); - args.regionName = m_scene.RegionInfo.RegionName; - args.SimOwner = m_scene.RegionInfo.EstateSettings.EstateOwner; + args.regionName = Scene.RegionInfo.RegionName; + args.SimOwner = Scene.RegionInfo.EstateSettings.EstateOwner; args.terrainBase0 = UUID.Zero; args.terrainBase1 = UUID.Zero; args.terrainBase2 = UUID.Zero; args.terrainBase3 = UUID.Zero; - args.terrainDetail0 = m_scene.RegionInfo.RegionSettings.TerrainTexture1; - args.terrainDetail1 = m_scene.RegionInfo.RegionSettings.TerrainTexture2; - args.terrainDetail2 = m_scene.RegionInfo.RegionSettings.TerrainTexture3; - args.terrainDetail3 = m_scene.RegionInfo.RegionSettings.TerrainTexture4; + args.terrainDetail0 = Scene.RegionInfo.RegionSettings.TerrainTexture1; + args.terrainDetail1 = Scene.RegionInfo.RegionSettings.TerrainTexture2; + args.terrainDetail2 = Scene.RegionInfo.RegionSettings.TerrainTexture3; + args.terrainDetail3 = Scene.RegionInfo.RegionSettings.TerrainTexture4; - remoteClient.SendRegionHandshake(m_scene.RegionInfo,args); + remoteClient.SendRegionHandshake(Scene.RegionInfo,args); } public void sendRegionHandshakeToAll() { - m_scene.ForEachClient(sendRegionHandshake); + Scene.ForEachClient(sendRegionHandshake); } public void handleEstateChangeInfo(IClientAPI remoteClient, UUID invoice, UUID senderID, UInt32 parms1, UInt32 parms2) { if (parms2 == 0) { - m_scene.RegionInfo.EstateSettings.UseGlobalTime = true; - m_scene.RegionInfo.EstateSettings.SunPosition = 0.0; + Scene.RegionInfo.EstateSettings.UseGlobalTime = true; + Scene.RegionInfo.EstateSettings.SunPosition = 0.0; } else { - m_scene.RegionInfo.EstateSettings.UseGlobalTime = false; - m_scene.RegionInfo.EstateSettings.SunPosition = (parms2 - 0x1800)/1024.0; + Scene.RegionInfo.EstateSettings.UseGlobalTime = false; + Scene.RegionInfo.EstateSettings.SunPosition = (parms2 - 0x1800)/1024.0; } if ((parms1 & 0x00000010) != 0) - m_scene.RegionInfo.EstateSettings.FixedSun = true; + Scene.RegionInfo.EstateSettings.FixedSun = true; else - m_scene.RegionInfo.EstateSettings.FixedSun = false; + Scene.RegionInfo.EstateSettings.FixedSun = false; if ((parms1 & 0x00008000) != 0) - m_scene.RegionInfo.EstateSettings.PublicAccess = true; + Scene.RegionInfo.EstateSettings.PublicAccess = true; else - m_scene.RegionInfo.EstateSettings.PublicAccess = false; + Scene.RegionInfo.EstateSettings.PublicAccess = false; if ((parms1 & 0x10000000) != 0) - m_scene.RegionInfo.EstateSettings.AllowVoice = true; + Scene.RegionInfo.EstateSettings.AllowVoice = true; else - m_scene.RegionInfo.EstateSettings.AllowVoice = false; + Scene.RegionInfo.EstateSettings.AllowVoice = false; if ((parms1 & 0x00100000) != 0) - m_scene.RegionInfo.EstateSettings.AllowDirectTeleport = true; + Scene.RegionInfo.EstateSettings.AllowDirectTeleport = true; else - m_scene.RegionInfo.EstateSettings.AllowDirectTeleport = false; + Scene.RegionInfo.EstateSettings.AllowDirectTeleport = false; if ((parms1 & 0x00800000) != 0) - m_scene.RegionInfo.EstateSettings.DenyAnonymous = true; + Scene.RegionInfo.EstateSettings.DenyAnonymous = true; else - m_scene.RegionInfo.EstateSettings.DenyAnonymous = false; + Scene.RegionInfo.EstateSettings.DenyAnonymous = false; if ((parms1 & 0x01000000) != 0) - m_scene.RegionInfo.EstateSettings.DenyIdentified = true; + Scene.RegionInfo.EstateSettings.DenyIdentified = true; else - m_scene.RegionInfo.EstateSettings.DenyIdentified = false; + Scene.RegionInfo.EstateSettings.DenyIdentified = false; if ((parms1 & 0x02000000) != 0) - m_scene.RegionInfo.EstateSettings.DenyTransacted = true; + Scene.RegionInfo.EstateSettings.DenyTransacted = true; else - m_scene.RegionInfo.EstateSettings.DenyTransacted = false; + Scene.RegionInfo.EstateSettings.DenyTransacted = false; if ((parms1 & 0x40000000) != 0) - m_scene.RegionInfo.EstateSettings.DenyMinors = true; + Scene.RegionInfo.EstateSettings.DenyMinors = true; else - m_scene.RegionInfo.EstateSettings.DenyMinors = false; + Scene.RegionInfo.EstateSettings.DenyMinors = false; - m_scene.RegionInfo.EstateSettings.Save(); + Scene.RegionInfo.EstateSettings.Save(); TriggerEstateInfoChange(); - m_scene.TriggerEstateSunUpdate(); + Scene.TriggerEstateSunUpdate(); sendDetailedEstateData(remoteClient, invoice); } @@ -905,140 +912,42 @@ namespace OpenSim.Region.CoreModules.World.Estate #endregion #region IRegionModule Members + + public string Name { get { return "EstateManagementModule"; } } + + public Type ReplaceableInterface { get { return null; } } - public void Initialise(Scene scene, IConfigSource source) + public void Initialise(IConfigSource source) {} + + public void AddRegion(Scene scene) { - m_scene = scene; - m_scene.RegisterModuleInterface(this); - m_scene.EventManager.OnNewClient += EventManager_OnNewClient; - m_scene.EventManager.OnRequestChangeWaterHeight += changeWaterHeight; m_regionChangeTimer.AutoReset = false; m_regionChangeTimer.Interval = 2000; m_regionChangeTimer.Elapsed += RaiseRegionInfoChange; - m_scene.AddCommand(this, "set terrain texture", - "set terrain texture [] []", - "Sets the terrain to , if or are specified, it will only " + - "set it on regions with a matching coordinate. Specify -1 in or to wildcard" + - " that coordinate.", - consoleSetTerrainTexture); - - m_scene.AddCommand(this, "set terrain heights", - "set terrain heights [] []", - "Sets the terrain texture heights on corner # to /, if or are specified, it will only " + - "set it on regions with a matching coordinate. Specify -1 in or to wildcard" + - " that coordinate. Corner # SW = 0, NW = 1, SE = 2, NE = 3.", - consoleSetTerrainHeights); + Scene = scene; + Scene.RegisterModuleInterface(this); + Scene.EventManager.OnNewClient += EventManager_OnNewClient; + Scene.EventManager.OnRequestChangeWaterHeight += changeWaterHeight; + + m_commands = new EstateManagementCommands(this); + m_commands.Initialise(); } - - #region Console Commands - - public void consoleSetTerrainTexture(string module, string[] args) - { - string num = args[3]; - string uuid = args[4]; - int x = (args.Length > 5 ? int.Parse(args[5]) : -1); - int y = (args.Length > 6 ? int.Parse(args[6]) : -1); - - if (x == -1 || m_scene.RegionInfo.RegionLocX == x) - { - if (y == -1 || m_scene.RegionInfo.RegionLocY == y) - { - int corner = int.Parse(num); - UUID texture = UUID.Parse(uuid); - - m_log.Debug("[ESTATEMODULE] Setting terrain textures for " + m_scene.RegionInfo.RegionName + - string.Format(" (C#{0} = {1})", corner, texture)); - - switch (corner) - { - case 0: - m_scene.RegionInfo.RegionSettings.TerrainTexture1 = texture; - break; - case 1: - m_scene.RegionInfo.RegionSettings.TerrainTexture2 = texture; - break; - case 2: - m_scene.RegionInfo.RegionSettings.TerrainTexture3 = texture; - break; - case 3: - m_scene.RegionInfo.RegionSettings.TerrainTexture4 = texture; - break; - } - m_scene.RegionInfo.RegionSettings.Save(); - TriggerRegionInfoChange(); - sendRegionInfoPacketToAll(); - - } - } - } - - public void consoleSetTerrainHeights(string module, string[] args) - { - string num = args[3]; - string min = args[4]; - string max = args[5]; - int x = (args.Length > 6 ? int.Parse(args[6]) : -1); - int y = (args.Length > 7 ? int.Parse(args[7]) : -1); - - if (x == -1 || m_scene.RegionInfo.RegionLocX == x) - { - if (y == -1 || m_scene.RegionInfo.RegionLocY == y) - { - int corner = int.Parse(num); - float lowValue = float.Parse(min, Culture.NumberFormatInfo); - float highValue = float.Parse(max, Culture.NumberFormatInfo); - - m_log.Debug("[ESTATEMODULE] Setting terrain heights " + m_scene.RegionInfo.RegionName + - string.Format(" (C{0}, {1}-{2}", corner, lowValue, highValue)); - - switch (corner) - { - case 0: - m_scene.RegionInfo.RegionSettings.Elevation1SW = lowValue; - m_scene.RegionInfo.RegionSettings.Elevation2SW = highValue; - break; - case 1: - m_scene.RegionInfo.RegionSettings.Elevation1NW = lowValue; - m_scene.RegionInfo.RegionSettings.Elevation2NW = highValue; - break; - case 2: - m_scene.RegionInfo.RegionSettings.Elevation1SE = lowValue; - m_scene.RegionInfo.RegionSettings.Elevation2SE = highValue; - break; - case 3: - m_scene.RegionInfo.RegionSettings.Elevation1NE = lowValue; - m_scene.RegionInfo.RegionSettings.Elevation2NE = highValue; - break; - } - m_scene.RegionInfo.RegionSettings.Save(); - TriggerRegionInfoChange(); - sendRegionHandshakeToAll(); - } - } - } - - #endregion - - public void PostInitialise() + + public void RemoveRegion(Scene scene) {} + + public void RegionLoaded(Scene scene) { // Sets up the sun module based no the saved Estate and Region Settings // DO NOT REMOVE or the sun will stop working - m_scene.TriggerEstateSunUpdate(); + scene.TriggerEstateSunUpdate(); + + UserManager = scene.RequestModuleInterface(); } - public void Close() + public void Close() { - } - - public string Name - { - get { return "EstateManagementModule"; } - } - - public bool IsSharedModule - { - get { return false; } + m_commands.Close(); } #endregion @@ -1048,14 +957,14 @@ namespace OpenSim.Region.CoreModules.World.Estate public void changeWaterHeight(float height) { setRegionTerrainSettings(height, - (float)m_scene.RegionInfo.RegionSettings.TerrainRaiseLimit, - (float)m_scene.RegionInfo.RegionSettings.TerrainLowerLimit, - m_scene.RegionInfo.RegionSettings.UseEstateSun, - m_scene.RegionInfo.RegionSettings.FixedSun, - (float)m_scene.RegionInfo.RegionSettings.SunPosition, - m_scene.RegionInfo.EstateSettings.UseGlobalTime, - m_scene.RegionInfo.EstateSettings.FixedSun, - (float)m_scene.RegionInfo.EstateSettings.SunPosition); + (float)Scene.RegionInfo.RegionSettings.TerrainRaiseLimit, + (float)Scene.RegionInfo.RegionSettings.TerrainLowerLimit, + Scene.RegionInfo.RegionSettings.UseEstateSun, + Scene.RegionInfo.RegionSettings.FixedSun, + (float)Scene.RegionInfo.RegionSettings.SunPosition, + Scene.RegionInfo.EstateSettings.UseGlobalTime, + Scene.RegionInfo.EstateSettings.FixedSun, + (float)Scene.RegionInfo.EstateSettings.SunPosition); sendRegionInfoPacketToAll(); } @@ -1095,33 +1004,42 @@ namespace OpenSim.Region.CoreModules.World.Estate // Fully implemented // - if (m_scene.RegionInfo.RegionSettings.AllowDamage) + if (Scene.RegionInfo.RegionSettings.AllowDamage) flags |= RegionFlags.AllowDamage; - if (m_scene.RegionInfo.RegionSettings.BlockTerraform) + if (Scene.RegionInfo.RegionSettings.BlockTerraform) flags |= RegionFlags.BlockTerraform; - if (!m_scene.RegionInfo.RegionSettings.AllowLandResell) + if (!Scene.RegionInfo.RegionSettings.AllowLandResell) flags |= RegionFlags.BlockLandResell; - if (m_scene.RegionInfo.RegionSettings.DisableCollisions) + if (Scene.RegionInfo.RegionSettings.DisableCollisions) flags |= RegionFlags.SkipCollisions; - if (m_scene.RegionInfo.RegionSettings.DisableScripts) + if (Scene.RegionInfo.RegionSettings.DisableScripts) flags |= RegionFlags.SkipScripts; - if (m_scene.RegionInfo.RegionSettings.DisablePhysics) + if (Scene.RegionInfo.RegionSettings.DisablePhysics) flags |= RegionFlags.SkipPhysics; - if (m_scene.RegionInfo.RegionSettings.BlockFly) + if (Scene.RegionInfo.RegionSettings.BlockFly) flags |= RegionFlags.NoFly; - if (m_scene.RegionInfo.RegionSettings.RestrictPushing) + if (Scene.RegionInfo.RegionSettings.RestrictPushing) flags |= RegionFlags.RestrictPushObject; - if (m_scene.RegionInfo.RegionSettings.AllowLandJoinDivide) + if (Scene.RegionInfo.RegionSettings.AllowLandJoinDivide) flags |= RegionFlags.AllowParcelChanges; - if (m_scene.RegionInfo.RegionSettings.BlockShowInSearch) + if (Scene.RegionInfo.RegionSettings.BlockShowInSearch) flags |= RegionFlags.BlockParcelSearch; - if (m_scene.RegionInfo.RegionSettings.FixedSun) + if (Scene.RegionInfo.RegionSettings.FixedSun) flags |= RegionFlags.SunFixed; - if (m_scene.RegionInfo.RegionSettings.Sandbox) + if (Scene.RegionInfo.RegionSettings.Sandbox) flags |= RegionFlags.Sandbox; - if (m_scene.RegionInfo.EstateSettings.AllowVoice) + if (Scene.RegionInfo.EstateSettings.AllowVoice) flags |= RegionFlags.AllowVoice; + if (Scene.RegionInfo.EstateSettings.AllowLandmark) + flags |= RegionFlags.AllowLandmark; + if (Scene.RegionInfo.EstateSettings.AllowSetHome) + flags |= RegionFlags.AllowSetHome; + if (Scene.RegionInfo.EstateSettings.BlockDwell) + flags |= RegionFlags.BlockDwell; + if (Scene.RegionInfo.EstateSettings.ResetHomeOnTeleport) + flags |= RegionFlags.ResetHomeOnTeleport; + // Fudge these to always on, so the menu options activate // @@ -1142,32 +1060,38 @@ namespace OpenSim.Region.CoreModules.World.Estate { RegionFlags flags = RegionFlags.None; - if (m_scene.RegionInfo.EstateSettings.FixedSun) + if (Scene.RegionInfo.EstateSettings.FixedSun) flags |= RegionFlags.SunFixed; - if (m_scene.RegionInfo.EstateSettings.PublicAccess) + if (Scene.RegionInfo.EstateSettings.PublicAccess) flags |= (RegionFlags.PublicAllowed | RegionFlags.ExternallyVisible); - if (m_scene.RegionInfo.EstateSettings.AllowVoice) + if (Scene.RegionInfo.EstateSettings.AllowVoice) flags |= RegionFlags.AllowVoice; - if (m_scene.RegionInfo.EstateSettings.AllowDirectTeleport) + if (Scene.RegionInfo.EstateSettings.AllowDirectTeleport) flags |= RegionFlags.AllowDirectTeleport; - if (m_scene.RegionInfo.EstateSettings.DenyAnonymous) + if (Scene.RegionInfo.EstateSettings.DenyAnonymous) flags |= RegionFlags.DenyAnonymous; - if (m_scene.RegionInfo.EstateSettings.DenyIdentified) + if (Scene.RegionInfo.EstateSettings.DenyIdentified) flags |= RegionFlags.DenyIdentified; - if (m_scene.RegionInfo.EstateSettings.DenyTransacted) + if (Scene.RegionInfo.EstateSettings.DenyTransacted) flags |= RegionFlags.DenyTransacted; - if (m_scene.RegionInfo.EstateSettings.AbuseEmailToEstateOwner) + if (Scene.RegionInfo.EstateSettings.AbuseEmailToEstateOwner) flags |= RegionFlags.AbuseEmailToEstateOwner; - if (m_scene.RegionInfo.EstateSettings.BlockDwell) + if (Scene.RegionInfo.EstateSettings.BlockDwell) flags |= RegionFlags.BlockDwell; - if (m_scene.RegionInfo.EstateSettings.EstateSkipScripts) + if (Scene.RegionInfo.EstateSettings.EstateSkipScripts) flags |= RegionFlags.EstateSkipScripts; - if (m_scene.RegionInfo.EstateSettings.ResetHomeOnTeleport) + if (Scene.RegionInfo.EstateSettings.ResetHomeOnTeleport) flags |= RegionFlags.ResetHomeOnTeleport; - if (m_scene.RegionInfo.EstateSettings.TaxFree) + if (Scene.RegionInfo.EstateSettings.TaxFree) flags |= RegionFlags.TaxFree; - if (m_scene.RegionInfo.EstateSettings.DenyMinors) + if (Scene.RegionInfo.EstateSettings.AllowLandmark) + flags |= RegionFlags.AllowLandmark; + if (Scene.RegionInfo.EstateSettings.AllowParcelChanges) + flags |= RegionFlags.AllowParcelChanges; + if (Scene.RegionInfo.EstateSettings.AllowSetHome) + flags |= RegionFlags.AllowSetHome; + if (Scene.RegionInfo.EstateSettings.DenyMinors) flags |= (RegionFlags)(1 << 30); return (uint)flags; @@ -1175,17 +1099,17 @@ namespace OpenSim.Region.CoreModules.World.Estate public bool IsManager(UUID avatarID) { - if (avatarID == m_scene.RegionInfo.EstateSettings.EstateOwner) + if (avatarID == Scene.RegionInfo.EstateSettings.EstateOwner) return true; - List ems = new List(m_scene.RegionInfo.EstateSettings.EstateManagers); + List ems = new List(Scene.RegionInfo.EstateSettings.EstateManagers); if (ems.Contains(avatarID)) return true; return false; } - protected void TriggerRegionInfoChange() + public void TriggerRegionInfoChange() { m_regionChangeTimer.Stop(); m_regionChangeTimer.Start(); @@ -1196,23 +1120,23 @@ namespace OpenSim.Region.CoreModules.World.Estate ChangeDelegate change = OnRegionInfoChange; if (change != null) - change(m_scene.RegionInfo.RegionID); + change(Scene.RegionInfo.RegionID); } - protected void TriggerEstateInfoChange() + public void TriggerEstateInfoChange() { ChangeDelegate change = OnEstateInfoChange; if (change != null) - change(m_scene.RegionInfo.RegionID); + change(Scene.RegionInfo.RegionID); } - protected void TriggerEstateMessage(UUID fromID, string fromName, string message) + public void TriggerEstateMessage(UUID fromID, string fromName, string message) { MessageDelegate onmessage = OnEstateMessage; if (onmessage != null) - onmessage(m_scene.RegionInfo.RegionID, fromID, fromName, message); + onmessage(Scene.RegionInfo.RegionID, fromID, fromName, message); } } } diff --git a/OpenSim/Region/CoreModules/World/Land/LandManagementModule.cs b/OpenSim/Region/CoreModules/World/Land/LandManagementModule.cs index b671aeca0a..ad75ea5fe6 100644 --- a/OpenSim/Region/CoreModules/World/Land/LandManagementModule.cs +++ b/OpenSim/Region/CoreModules/World/Land/LandManagementModule.cs @@ -163,13 +163,6 @@ namespace OpenSim.Region.CoreModules.World.Land m_scene.UnregisterModuleCommander(m_commander.Name); } -// private bool OnVerifyUserConnection(ScenePresence scenePresence, out string reason) -// { -// ILandObject nearestParcel = m_scene.GetNearestAllowedParcel(scenePresence.UUID, scenePresence.AbsolutePosition.X, scenePresence.AbsolutePosition.Y); -// reason = "You are not allowed to enter this sim."; -// return nearestParcel != null; -// } - /// /// Processes commandline input. Do not call directly. /// @@ -364,31 +357,7 @@ namespace OpenSim.Region.CoreModules.World.Land } if (parcelAvatarIsEntering != null) - { - if (avatar.AbsolutePosition.Z < LandChannel.BAN_LINE_SAFETY_HIEGHT) - { - if (parcelAvatarIsEntering.IsEitherBannedOrRestricted(avatar.UUID)) - { - SendYouAreBannedNotice(avatar); - ForceAvatarToPosition(avatar, avatar.lastKnownAllowedPosition); - //ForceAvatarToPosition(avatar, m_scene.GetNearestAllowedPosition(avatar)); - } - else if (parcelAvatarIsEntering.IsRestrictedFromLand(avatar.UUID)) - { - SendYouAreRestrictedNotice(avatar); - ForceAvatarToPosition(avatar, avatar.lastKnownAllowedPosition); - //ForceAvatarToPosition(avatar, m_scene.GetNearestAllowedPosition(avatar)); - } - else - { - avatar.sentMessageAboutRestrictedParcelFlyingDown = true; - } - } - else - { - avatar.sentMessageAboutRestrictedParcelFlyingDown = true; - } - } + EnforceBans(parcelAvatarIsEntering, avatar); } } @@ -460,32 +429,7 @@ namespace OpenSim.Region.CoreModules.World.Land SendOutNearestBanLine(remote_client); ILandObject parcel = GetLandObject(clientAvatar.AbsolutePosition.X, clientAvatar.AbsolutePosition.Y); if (parcel != null) - { - if (clientAvatar.AbsolutePosition.Z < LandChannel.BAN_LINE_SAFETY_HIEGHT && - clientAvatar.sentMessageAboutRestrictedParcelFlyingDown) - { - EventManagerOnAvatarEnteringNewParcel(clientAvatar, parcel.LandData.LocalID, - m_scene.RegionInfo.RegionID); - //They are going under the safety line! - if (!parcel.IsBannedFromLand(clientAvatar.UUID)) - { - clientAvatar.sentMessageAboutRestrictedParcelFlyingDown = false; - } - } - else if (clientAvatar.AbsolutePosition.Z < LandChannel.BAN_LINE_SAFETY_HIEGHT && - parcel.IsBannedFromLand(clientAvatar.UUID)) - { - // SendYouAreBannedNotice(clientAvatar); - //ForceAvatarToPosition(clientAvatar, m_scene.GetNearestAllowedPosition(clientAvatar)); - ForceAvatarToPosition(clientAvatar, clientAvatar.lastKnownAllowedPosition); - } - else if (parcel.IsRestrictedFromLand(clientAvatar.UUID)) - { - // SendYouAreRestrictedNotice(clientAvatar); - //ForceAvatarToPosition(clientAvatar, m_scene.GetNearestAllowedPosition(clientAvatar)); - ForceAvatarToPosition(clientAvatar, clientAvatar.lastKnownAllowedPosition); - } - } + EnforceBans(parcel, clientAvatar); } } @@ -2005,5 +1949,27 @@ namespace OpenSim.Region.CoreModules.World.Land MainConsole.Instance.Output(report.ToString()); } + + public void EnforceBans(ILandObject land, ScenePresence avatar) + { + if (avatar.AbsolutePosition.Z > LandChannel.BAN_LINE_SAFETY_HIEGHT) + return; + + if (land.IsEitherBannedOrRestricted(avatar.UUID)) + { + if (land.ContainsPoint(Convert.ToInt32(avatar.lastKnownAllowedPosition.X), Convert.ToInt32(avatar.lastKnownAllowedPosition.Y))) + { + Vector3? pos = m_scene.GetNearestAllowedPosition(avatar); + if (pos == null) + m_scene.TeleportClientHome(avatar.UUID, avatar.ControllingClient); + else + ForceAvatarToPosition(avatar, (Vector3)pos); + } + else + { + ForceAvatarToPosition(avatar, avatar.lastKnownAllowedPosition); + } + } + } } } diff --git a/OpenSim/Region/CoreModules/World/LegacyMap/TexturedMapTileRenderer.cs b/OpenSim/Region/CoreModules/World/LegacyMap/TexturedMapTileRenderer.cs index 071314ac9a..aa14054cf5 100644 --- a/OpenSim/Region/CoreModules/World/LegacyMap/TexturedMapTileRenderer.cs +++ b/OpenSim/Region/CoreModules/World/LegacyMap/TexturedMapTileRenderer.cs @@ -188,17 +188,17 @@ namespace OpenSim.Region.CoreModules.World.LegacyMap } catch (DllNotFoundException) { - m_log.ErrorFormat("[TexturedMapTileRenderer]: OpenJpeg is not installed correctly on this system. Asset Data is emtpy for {0}", id); + m_log.ErrorFormat("[TexturedMapTileRenderer]: OpenJpeg is not installed correctly on this system. Asset Data is empty for {0}", id); } catch (IndexOutOfRangeException) { - m_log.ErrorFormat("[TexturedMapTileRenderer]: OpenJpeg was unable to encode this. Asset Data is emtpy for {0}", id); + m_log.ErrorFormat("[TexturedMapTileRenderer]: OpenJpeg was unable to encode this. Asset Data is empty for {0}", id); } catch (Exception) { - m_log.ErrorFormat("[TexturedMapTileRenderer]: OpenJpeg was unable to encode this. Asset Data is emtpy for {0}", id); + m_log.ErrorFormat("[TexturedMapTileRenderer]: OpenJpeg was unable to encode this. Asset Data is empty for {0}", id); } return null; diff --git a/OpenSim/Region/CoreModules/World/Media/Moap/MoapModule.cs b/OpenSim/Region/CoreModules/World/Media/Moap/MoapModule.cs index 7c5d044347..898ca4a4c3 100644 --- a/OpenSim/Region/CoreModules/World/Media/Moap/MoapModule.cs +++ b/OpenSim/Region/CoreModules/World/Media/Moap/MoapModule.cs @@ -50,7 +50,7 @@ using Caps = OpenSim.Framework.Capabilities.Caps; using OSDArray = OpenMetaverse.StructuredData.OSDArray; using OSDMap = OpenMetaverse.StructuredData.OSDMap; -namespace OpenSim.Region.CoreModules.Media.Moap +namespace OpenSim.Region.CoreModules.World.Media.Moap { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MoapModule")] public class MoapModule : INonSharedRegionModule, IMoapModule @@ -225,24 +225,62 @@ namespace OpenSim.Region.CoreModules.Media.Moap return me; } + /// + /// Set the media entry on the face of the given part. + /// + /// /param> + /// + /// If null, then the media entry is cleared. public void SetMediaEntry(SceneObjectPart part, int face, MediaEntry me) { +// m_log.DebugFormat("[MOAP]: SetMediaEntry for {0}, face {1}", part.Name, face); + CheckFaceParam(part, face); if (null == part.Shape.Media) - part.Shape.Media = new PrimitiveBaseShape.MediaList(new MediaEntry[part.GetNumberOfSides()]); - + { + if (me == null) + return; + else + part.Shape.Media = new PrimitiveBaseShape.MediaList(new MediaEntry[part.GetNumberOfSides()]); + } + lock (part.Shape.Media) - part.Shape.Media[face] = me; + part.Shape.Media[face] = me; UpdateMediaUrl(part, UUID.Zero); + + SetPartMediaFlags(part, face, me != null); + part.ScheduleFullUpdate(); part.TriggerScriptChangedEvent(Changed.MEDIA); } + /// + /// Clear the media entry from the face of the given part. + /// + /// + /// public void ClearMediaEntry(SceneObjectPart part, int face) { - SetMediaEntry(part, face, null); + SetMediaEntry(part, face, null); + } + + /// + /// Set the media flags on the texture face of the given part. + /// + /// + /// The fact that we need a separate function to do what should be a simple one line operation is BUTT UGLY. + /// + /// + /// + /// + protected void SetPartMediaFlags(SceneObjectPart part, int face, bool flag) + { + Primitive.TextureEntry te = part.Shape.Textures; + Primitive.TextureEntryFace teFace = te.CreateFace((uint)face); + teFace.MediaFlags = flag; + part.Shape.Textures = te; } /// @@ -333,7 +371,7 @@ namespace OpenSim.Region.CoreModules.Media.Moap } // m_log.DebugFormat("[MOAP]: Received {0} media entries for prim {1}", omu.FaceMedia.Length, primId); - +// // for (int i = 0; i < omu.FaceMedia.Length; i++) // { // MediaEntry me = omu.FaceMedia[i]; @@ -368,10 +406,7 @@ namespace OpenSim.Region.CoreModules.Media.Moap // FIXME: Race condition here since some other texture entry manipulator may overwrite/get // overwritten. Unfortunately, PrimitiveBaseShape does not allow us to change texture entry // directly. - Primitive.TextureEntry te = part.Shape.Textures; - Primitive.TextureEntryFace face = te.CreateFace((uint)i); - face.MediaFlags = true; - part.Shape.Textures = te; + SetPartMediaFlags(part, i, true); // m_log.DebugFormat( // "[MOAP]: Media flags for face {0} is {1}", // i, part.Shape.Textures.FaceTextures[i].MediaFlags); @@ -380,6 +415,8 @@ namespace OpenSim.Region.CoreModules.Media.Moap } else { +// m_log.DebugFormat("[MOAP]: Setting existing media list for {0}", part.Name); + // We need to go through the media textures one at a time to make sure that we have permission // to change them @@ -401,8 +438,7 @@ namespace OpenSim.Region.CoreModules.Media.Moap if (null == media[i]) continue; - Primitive.TextureEntryFace face = te.CreateFace((uint)i); - face.MediaFlags = true; + SetPartMediaFlags(part, i, true); // m_log.DebugFormat( // "[MOAP]: Media flags for face {0} is {1}", diff --git a/OpenSim/Region/CoreModules/World/Media/Moap/Tests/MoapTests.cs b/OpenSim/Region/CoreModules/World/Media/Moap/Tests/MoapTests.cs new file mode 100644 index 0000000000..5b85830f5f --- /dev/null +++ b/OpenSim/Region/CoreModules/World/Media/Moap/Tests/MoapTests.cs @@ -0,0 +1,102 @@ +/* + * 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.IO; +using System.Reflection; +using System.Threading; +using log4net.Config; +using NUnit.Framework; +using OpenMetaverse; +using OpenMetaverse.Assets; +using OpenSim.Framework; +using OpenSim.Region.CoreModules.World.Media.Moap; +using OpenSim.Region.Framework.Scenes; +using OpenSim.Region.Framework.Scenes.Serialization; +using OpenSim.Tests.Common; +using OpenSim.Tests.Common.Mock; +using OpenSim.Tests.Common.Setup; + +namespace OpenSim.Region.CoreModules.World.Media.Moap.Tests +{ + [TestFixture] + public class MoapTests + { + protected TestScene m_scene; + protected MoapModule m_module; + + [SetUp] + public void SetUp() + { + m_module = new MoapModule(); + m_scene = SceneSetupHelpers.SetupScene(); + SceneSetupHelpers.SetupSceneModules(m_scene, m_module); + } + + [Test] + public void TestClearMediaUrl() + { + TestHelper.InMethod(); +// log4net.Config.XmlConfigurator.Configure(); + + SceneObjectPart part = SceneSetupHelpers.AddSceneObject(m_scene); + MediaEntry me = new MediaEntry(); + + m_module.SetMediaEntry(part, 1, me); + m_module.ClearMediaEntry(part, 1); + + Assert.That(part.Shape.Media[1], Is.EqualTo(null)); + + // Although we've cleared one face, other faces may still be present. So we need to check for an + // update media url version + Assert.That(part.MediaUrl, Is.EqualTo("x-mv:0000000001/" + UUID.Zero)); + + // By changing media flag to false, the face texture once again becomes identical to the DefaultTexture. + // Therefore, when libOMV reserializes it, it disappears and we are left with no face texture in this slot. + // Not at all confusing, eh? + Assert.That(part.Shape.Textures.FaceTextures[1], Is.Null); + } + + [Test] + public void TestSetMediaUrl() + { + TestHelper.InMethod(); + + string homeUrl = "opensimulator.org"; + + SceneObjectPart part = SceneSetupHelpers.AddSceneObject(m_scene); + MediaEntry me = new MediaEntry() { HomeURL = homeUrl }; + + m_module.SetMediaEntry(part, 1, me); + + Assert.That(part.Shape.Media[1].HomeURL, Is.EqualTo(homeUrl)); + Assert.That(part.MediaUrl, Is.EqualTo("x-mv:0000000000/" + UUID.Zero)); + Assert.That(part.Shape.Textures.FaceTextures[1].MediaFlags, Is.True); + } + } +} \ No newline at end of file diff --git a/OpenSim/Region/CoreModules/World/Permissions/PermissionsModule.cs b/OpenSim/Region/CoreModules/World/Permissions/PermissionsModule.cs index f9b2384588..a098ff6078 100644 --- a/OpenSim/Region/CoreModules/World/Permissions/PermissionsModule.cs +++ b/OpenSim/Region/CoreModules/World/Permissions/PermissionsModule.cs @@ -642,7 +642,7 @@ namespace OpenSim.Region.CoreModules.World.Permissions /// implemented by callers. /// /// - /// + /// This is a scene object group UUID /// /// protected bool GenericObjectPermission(UUID currentUser, UUID objId, bool denyOnLocked) @@ -1896,7 +1896,7 @@ namespace OpenSim.Region.CoreModules.World.Permissions // "[PERMISSIONS]: Checking CanControlPrimMedia for {0} on {1} face {2} with control permissions {3}", // agentID, primID, face, me.ControlPermissions); - return GenericPrimMediaPermission(part, agentID, me.ControlPermissions); + return GenericObjectPermission(agentID, part.ParentGroup.UUID, true); } private bool CanInteractWithPrimMedia(UUID agentID, UUID primID, int face) diff --git a/OpenSim/Region/CoreModules/World/Serialiser/Tests/SerialiserTests.cs b/OpenSim/Region/CoreModules/World/Serialiser/Tests/SerialiserTests.cs index f10e848f68..dafaa0c107 100644 --- a/OpenSim/Region/CoreModules/World/Serialiser/Tests/SerialiserTests.cs +++ b/OpenSim/Region/CoreModules/World/Serialiser/Tests/SerialiserTests.cs @@ -30,7 +30,6 @@ using System.IO; using System.Xml; using log4net.Config; using NUnit.Framework; -using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; diff --git a/OpenSim/Region/CoreModules/World/WorldMap/MapSearchModule.cs b/OpenSim/Region/CoreModules/World/WorldMap/MapSearchModule.cs index 334dcb0f47..282e4f18fa 100644 --- a/OpenSim/Region/CoreModules/World/WorldMap/MapSearchModule.cs +++ b/OpenSim/Region/CoreModules/World/WorldMap/MapSearchModule.cs @@ -113,7 +113,7 @@ namespace OpenSim.Region.CoreModules.World.WorldMap data = new MapBlockData(); data.Agents = 0; data.Access = info.Access; - data.MapImageId = info.TerrainImage; + data.MapImageId = UUID.Zero; // could use info.TerrainImage but it seems to break viewer2 data.Name = info.RegionName; data.RegionFlags = 0; // TODO not used? data.WaterHeight = 0; // not used diff --git a/OpenSim/Region/CoreModules/World/WorldMap/WorldMapModule.cs b/OpenSim/Region/CoreModules/World/WorldMap/WorldMapModule.cs index e0f36a2081..b05aef818a 100644 --- a/OpenSim/Region/CoreModules/World/WorldMap/WorldMapModule.cs +++ b/OpenSim/Region/CoreModules/World/WorldMap/WorldMapModule.cs @@ -764,10 +764,11 @@ namespace OpenSim.Region.CoreModules.World.WorldMap if (!responseMap.ContainsKey(itemtype.ToString())) // remote sim doesnt have the stated region handle { - if (!m_blacklistedregions.ContainsKey(regionhandle)) + m_log.DebugFormat("[WORLD MAP]: Remote sim does not have the stated region. Blacklisting."); + lock (m_blacklistedregions) { - m_log.DebugFormat("[WORLD MAP]: Remote sim does not have the stated region. Blacklisting."); - m_blacklistedregions.Add(regionhandle, Environment.TickCount); + if (!m_blacklistedregions.ContainsKey(regionhandle)) + m_blacklistedregions.Add(regionhandle, Environment.TickCount); } } @@ -1055,7 +1056,7 @@ namespace OpenSim.Region.CoreModules.World.WorldMap } else { - OSDArray responsearr = new OSDArray(m_scene.GetRootAgentCount()); + OSDArray responsearr = new OSDArray(); // Don't preallocate. MT (m_scene.GetRootAgentCount()); m_scene.ForEachScenePresence(delegate(ScenePresence sp) { OSDMap responsemapdata = new OSDMap(); diff --git a/OpenSim/Region/Framework/Interfaces/IEstateModule.cs b/OpenSim/Region/Framework/Interfaces/IEstateModule.cs index c850f7fd81..72e79ed497 100644 --- a/OpenSim/Region/Framework/Interfaces/IEstateModule.cs +++ b/OpenSim/Region/Framework/Interfaces/IEstateModule.cs @@ -32,7 +32,7 @@ namespace OpenSim.Region.Framework.Interfaces public delegate void ChangeDelegate(UUID regionID); public delegate void MessageDelegate(UUID regionID, UUID fromID, string fromName, string message); - public interface IEstateModule : IRegionModule + public interface IEstateModule { event ChangeDelegate OnRegionInfoChange; event ChangeDelegate OnEstateInfoChange; @@ -45,5 +45,7 @@ namespace OpenSim.Region.Framework.Interfaces /// Tell all clients about the current state of the region (terrain textures, water height, etc.). /// void sendRegionHandshakeToAll(); + void TriggerEstateInfoChange(); + void TriggerRegionInfoChange(); } } diff --git a/OpenSim/Region/Framework/Interfaces/ISceneViewer.cs b/OpenSim/Region/Framework/Interfaces/ISceneViewer.cs index 7251d57f69..2397f223b3 100644 --- a/OpenSim/Region/Framework/Interfaces/ISceneViewer.cs +++ b/OpenSim/Region/Framework/Interfaces/ISceneViewer.cs @@ -36,5 +36,6 @@ namespace OpenSim.Region.Framework.Interfaces void Close(); void QueuePartForUpdate(SceneObjectPart part); void SendPrimUpdates(); + int GetPendingObjectsCount(); } } diff --git a/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs b/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs index 9a93a2600d..bc892e0dce 100644 --- a/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs +++ b/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs @@ -303,6 +303,8 @@ namespace OpenSim.Region.Framework.Scenes // Passing something to another avatar or a an object will already InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId); item = InventoryService.GetItem(item); + if (item.Owner != remoteClient.AgentId) + return; if (item != null) { @@ -1227,6 +1229,10 @@ namespace OpenSim.Region.Framework.Scenes if ((part.OwnerID != destPart.OwnerID) && ((srcTaskItem.CurrentPermissions & (uint)PermissionMask.Transfer) == 0)) return; + bool overrideNoMod = false; + if ((part.GetEffectiveObjectFlags() & (uint)PrimFlags.AllowInventoryDrop) != 0) + overrideNoMod = true; + if (part.OwnerID != destPart.OwnerID && (part.GetEffectiveObjectFlags() & (uint)PrimFlags.AllowInventoryDrop) == 0) { // object cannot copy items to an object owned by a different owner @@ -1236,7 +1242,7 @@ namespace OpenSim.Region.Framework.Scenes } // must have both move and modify permission to put an item in an object - if ((part.OwnerMask & ((uint)PermissionMask.Move | (uint)PermissionMask.Modify)) == 0) + if (((part.OwnerMask & (uint)PermissionMask.Modify) == 0) && (!overrideNoMod)) { return; } diff --git a/OpenSim/Region/Framework/Scenes/Scene.cs b/OpenSim/Region/Framework/Scenes/Scene.cs index 2424194ad5..e5c0f38864 100644 --- a/OpenSim/Region/Framework/Scenes/Scene.cs +++ b/OpenSim/Region/Framework/Scenes/Scene.cs @@ -64,6 +64,8 @@ namespace OpenSim.Region.Framework.Scenes #region Fields + public bool EmergencyMonitoring = false; + public SynchronizeSceneHandler SynchronizeScene; public SimStatsReporter StatsReporter; public List NorthBorders = new List(); @@ -81,6 +83,13 @@ namespace OpenSim.Region.Framework.Scenes public bool m_useFlySlow; public bool m_usePreJump; public bool m_seeIntoRegionFromNeighbor; + + protected float m_defaultDrawDistance = 255.0f; + public float DefaultDrawDistance + { + get { return m_defaultDrawDistance; } + } + // TODO: need to figure out how allow client agents but deny // root agents when ACL denies access to root agent public bool m_strictAccessControl = true; @@ -129,7 +138,16 @@ namespace OpenSim.Region.Framework.Scenes protected ICapabilitiesModule m_capsModule; // Central Update Loop protected int m_fps = 10; - protected uint m_frame; + + /// + /// Current scene frame number + /// + public uint Frame + { + get; + protected set; + } + protected float m_timespan = 0.089f; protected DateTime m_lastupdate = DateTime.UtcNow; @@ -638,6 +656,8 @@ namespace OpenSim.Region.Framework.Scenes // IConfig startupConfig = m_config.Configs["Startup"]; + m_defaultDrawDistance = startupConfig.GetFloat("DefaultDrawDistance",m_defaultDrawDistance); + //Animation states m_useFlySlow = startupConfig.GetBoolean("enableflyslow", false); // TODO: Change default to true once the feature is supported @@ -1209,7 +1229,8 @@ namespace OpenSim.Region.Framework.Scenes try { - Update(); + while (!shuttingdown) + Update(); } catch (ThreadAbortException) { @@ -1223,190 +1244,180 @@ namespace OpenSim.Region.Framework.Scenes Watchdog.RemoveThread(); } - /// - /// Performs per-frame updates on the scene, this should be the central scene loop - /// public override void Update() - { - float physicsFPS; - int maintc; + { + TimeSpan SinceLastFrame = DateTime.UtcNow - m_lastupdate; + float physicsFPS = 0f; - while (!shuttingdown) + int maintc = Util.EnvironmentTickCount(); + int tmpFrameMS = maintc; + tempOnRezMS = eventMS = backupMS = terrainMS = landMS = 0; + + // Increment the frame counter + ++Frame; + + try { - TimeSpan SinceLastFrame = DateTime.UtcNow - m_lastupdate; - physicsFPS = 0f; + // Check if any objects have reached their targets + CheckAtTargets(); - maintc = Util.EnvironmentTickCount(); - int tmpFrameMS = maintc; - tempOnRezMS = eventMS = backupMS = terrainMS = landMS = 0; + // Update SceneObjectGroups that have scheduled themselves for updates + // Objects queue their updates onto all scene presences + if (Frame % m_update_objects == 0) + m_sceneGraph.UpdateObjectGroups(); - // Increment the frame counter - ++m_frame; + // Run through all ScenePresences looking for updates + // Presence updates and queued object updates for each presence are sent to clients + if (Frame % m_update_presences == 0) + m_sceneGraph.UpdatePresences(); - try + // Coarse locations relate to positions of green dots on the mini-map (on a SecondLife client) + if (Frame % m_update_coarse_locations == 0) { - // Check if any objects have reached their targets - CheckAtTargets(); - - // Update SceneObjectGroups that have scheduled themselves for updates - // Objects queue their updates onto all scene presences - if (m_frame % m_update_objects == 0) - m_sceneGraph.UpdateObjectGroups(); - - // Run through all ScenePresences looking for updates - // Presence updates and queued object updates for each presence are sent to clients - if (m_frame % m_update_presences == 0) - m_sceneGraph.UpdatePresences(); - - // Coarse locations relate to positions of green dots on the mini-map (on a SecondLife client) - if (m_frame % m_update_coarse_locations == 0) + List coarseLocations; + List avatarUUIDs; + SceneGraph.GetCoarseLocations(out coarseLocations, out avatarUUIDs, 60); + // Send coarse locations to clients + ForEachScenePresence(delegate(ScenePresence presence) { - List coarseLocations; - List avatarUUIDs; - SceneGraph.GetCoarseLocations(out coarseLocations, out avatarUUIDs, 60); - // Send coarse locations to clients - ForEachScenePresence(delegate(ScenePresence presence) - { - presence.SendCoarseLocations(coarseLocations, avatarUUIDs); - }); + presence.SendCoarseLocations(coarseLocations, avatarUUIDs); + }); + } + + int tmpPhysicsMS2 = Util.EnvironmentTickCount(); + if ((Frame % m_update_physics == 0) && m_physics_enabled) + m_sceneGraph.UpdatePreparePhysics(); + physicsMS2 = Util.EnvironmentTickCountSubtract(tmpPhysicsMS2); + + // Apply any pending avatar force input to the avatar's velocity + if (Frame % m_update_entitymovement == 0) + m_sceneGraph.UpdateScenePresenceMovement(); + + // Perform the main physics update. This will do the actual work of moving objects and avatars according to their + // velocity + int tmpPhysicsMS = Util.EnvironmentTickCount(); + if (Frame % m_update_physics == 0) + { + if (m_physics_enabled) + physicsFPS = m_sceneGraph.UpdatePhysics(Math.Max(SinceLastFrame.TotalSeconds, m_timespan)); + if (SynchronizeScene != null) + SynchronizeScene(this); + } + physicsMS = Util.EnvironmentTickCountSubtract(tmpPhysicsMS); + + // Delete temp-on-rez stuff + if (Frame % 1000 == 0 && !m_cleaningTemps) + { + int tmpTempOnRezMS = Util.EnvironmentTickCount(); + m_cleaningTemps = true; + Util.FireAndForget(delegate { CleanTempObjects(); m_cleaningTemps = false; }); + tempOnRezMS = Util.EnvironmentTickCountSubtract(tmpTempOnRezMS); + } + + if (RegionStatus != RegionStatus.SlaveScene) + { + if (Frame % m_update_events == 0) + { + int evMS = Util.EnvironmentTickCount(); + UpdateEvents(); + eventMS = Util.EnvironmentTickCountSubtract(evMS); ; } - int tmpPhysicsMS2 = Util.EnvironmentTickCount(); - if ((m_frame % m_update_physics == 0) && m_physics_enabled) - m_sceneGraph.UpdatePreparePhysics(); - physicsMS2 = Util.EnvironmentTickCountSubtract(tmpPhysicsMS2); - - // Apply any pending avatar force input to the avatar's velocity - if (m_frame % m_update_entitymovement == 0) - m_sceneGraph.UpdateScenePresenceMovement(); - - // Perform the main physics update. This will do the actual work of moving objects and avatars according to their - // velocity - int tmpPhysicsMS = Util.EnvironmentTickCount(); - if (m_frame % m_update_physics == 0) + if (Frame % m_update_backup == 0) { - if (m_physics_enabled) - physicsFPS = m_sceneGraph.UpdatePhysics(Math.Max(SinceLastFrame.TotalSeconds, m_timespan)); - if (SynchronizeScene != null) - SynchronizeScene(this); - } - physicsMS = Util.EnvironmentTickCountSubtract(tmpPhysicsMS); - - // Delete temp-on-rez stuff - if (m_frame % 1000 == 0 && !m_cleaningTemps) - { - int tmpTempOnRezMS = Util.EnvironmentTickCount(); - m_cleaningTemps = true; - Util.FireAndForget(delegate { CleanTempObjects(); m_cleaningTemps = false; }); - tempOnRezMS = Util.EnvironmentTickCountSubtract(tmpTempOnRezMS); + int backMS = Util.EnvironmentTickCount(); + UpdateStorageBackup(); + backupMS = Util.EnvironmentTickCountSubtract(backMS); } - if (RegionStatus != RegionStatus.SlaveScene) + if (Frame % m_update_terrain == 0) { - if (m_frame % m_update_events == 0) - { - int evMS = Util.EnvironmentTickCount(); - UpdateEvents(); - eventMS = Util.EnvironmentTickCountSubtract(evMS); ; - } - - if (m_frame % m_update_backup == 0) - { - int backMS = Util.EnvironmentTickCount(); - UpdateStorageBackup(); - backupMS = Util.EnvironmentTickCountSubtract(backMS); - } - - if (m_frame % m_update_terrain == 0) - { - int terMS = Util.EnvironmentTickCount(); - UpdateTerrain(); - terrainMS = Util.EnvironmentTickCountSubtract(terMS); - } - - if (m_frame % m_update_land == 0) - { - int ldMS = Util.EnvironmentTickCount(); - UpdateLand(); - landMS = Util.EnvironmentTickCountSubtract(ldMS); - } - - frameMS = Util.EnvironmentTickCountSubtract(tmpFrameMS); - otherMS = tempOnRezMS + eventMS + backupMS + terrainMS + landMS; - lastCompletedFrame = Util.EnvironmentTickCount(); - - // if (m_frame%m_update_avatars == 0) - // UpdateInWorldTime(); - StatsReporter.AddPhysicsFPS(physicsFPS); - StatsReporter.AddTimeDilation(TimeDilation); - StatsReporter.AddFPS(1); - StatsReporter.SetRootAgents(m_sceneGraph.GetRootAgentCount()); - StatsReporter.SetChildAgents(m_sceneGraph.GetChildAgentCount()); - StatsReporter.SetObjects(m_sceneGraph.GetTotalObjectsCount()); - StatsReporter.SetActiveObjects(m_sceneGraph.GetActiveObjectsCount()); - StatsReporter.addFrameMS(frameMS); - StatsReporter.addPhysicsMS(physicsMS + physicsMS2); - StatsReporter.addOtherMS(otherMS); - StatsReporter.SetActiveScripts(m_sceneGraph.GetActiveScriptsCount()); - StatsReporter.addScriptLines(m_sceneGraph.GetScriptLPS()); + int terMS = Util.EnvironmentTickCount(); + UpdateTerrain(); + terrainMS = Util.EnvironmentTickCountSubtract(terMS); } - if (LoginsDisabled && m_frame == 20) + if (Frame % m_update_land == 0) { - // In 99.9% of cases it is a bad idea to manually force garbage collection. However, - // this is a rare case where we know we have just went through a long cycle of heap - // allocations, and there is no more work to be done until someone logs in - GC.Collect(); + int ldMS = Util.EnvironmentTickCount(); + UpdateLand(); + landMS = Util.EnvironmentTickCountSubtract(ldMS); + } - IConfig startupConfig = m_config.Configs["Startup"]; - if (startupConfig == null || !startupConfig.GetBoolean("StartDisabled", false)) - { - m_log.DebugFormat("[REGION]: Enabling logins for {0}", RegionInfo.RegionName); - LoginsDisabled = false; - m_sceneGridService.InformNeighborsThatRegionisUp(RequestModuleInterface(), RegionInfo); - } + frameMS = Util.EnvironmentTickCountSubtract(tmpFrameMS); + otherMS = tempOnRezMS + eventMS + backupMS + terrainMS + landMS; + lastCompletedFrame = Util.EnvironmentTickCount(); + + // if (Frame%m_update_avatars == 0) + // UpdateInWorldTime(); + StatsReporter.AddPhysicsFPS(physicsFPS); + StatsReporter.AddTimeDilation(TimeDilation); + StatsReporter.AddFPS(1); + StatsReporter.SetRootAgents(m_sceneGraph.GetRootAgentCount()); + StatsReporter.SetChildAgents(m_sceneGraph.GetChildAgentCount()); + StatsReporter.SetObjects(m_sceneGraph.GetTotalObjectsCount()); + StatsReporter.SetActiveObjects(m_sceneGraph.GetActiveObjectsCount()); + StatsReporter.addFrameMS(frameMS); + StatsReporter.addPhysicsMS(physicsMS + physicsMS2); + StatsReporter.addOtherMS(otherMS); + StatsReporter.SetActiveScripts(m_sceneGraph.GetActiveScriptsCount()); + StatsReporter.addScriptLines(m_sceneGraph.GetScriptLPS()); + } + + if (LoginsDisabled && Frame == 20) + { + // In 99.9% of cases it is a bad idea to manually force garbage collection. However, + // this is a rare case where we know we have just went through a long cycle of heap + // allocations, and there is no more work to be done until someone logs in + GC.Collect(); + + IConfig startupConfig = m_config.Configs["Startup"]; + if (startupConfig == null || !startupConfig.GetBoolean("StartDisabled", false)) + { + m_log.DebugFormat("[REGION]: Enabling logins for {0}", RegionInfo.RegionName); + LoginsDisabled = false; + m_sceneGridService.InformNeighborsThatRegionisUp(RequestModuleInterface(), RegionInfo); } } - catch (NotImplementedException) - { - throw; - } - catch (AccessViolationException e) - { - m_log.Error("[REGION]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName); - } - //catch (NullReferenceException e) - //{ - // m_log.Error("[REGION]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName); - //} - catch (InvalidOperationException e) - { - m_log.Error("[REGION]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName); - } - catch (Exception e) - { - m_log.Error("[REGION]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName); - } - finally - { - m_lastupdate = DateTime.UtcNow; - } - - maintc = Util.EnvironmentTickCountSubtract(maintc); - maintc = (int)(m_timespan * 1000) - maintc; - - if (maintc > 0) - Thread.Sleep(maintc); - - // Tell the watchdog that this thread is still alive - Watchdog.UpdateThread(); - - m_lastUpdate = Util.EnvironmentTickCount(); - m_firstHeartbeat = false; } - } + catch (NotImplementedException) + { + throw; + } + catch (AccessViolationException e) + { + m_log.Error("[REGION]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName); + } + //catch (NullReferenceException e) + //{ + // m_log.Error("[REGION]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName); + //} + catch (InvalidOperationException e) + { + m_log.Error("[REGION]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName); + } + catch (Exception e) + { + m_log.Error("[REGION]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName); + } + finally + { + m_lastupdate = DateTime.UtcNow; + } - + maintc = Util.EnvironmentTickCountSubtract(maintc); + maintc = (int)(m_timespan * 1000) - maintc; + + + m_lastUpdate = Util.EnvironmentTickCount(); + m_firstHeartbeat = false; + + if (maintc > 0) + Thread.Sleep(maintc); + + // Tell the watchdog that this thread is still alive + Watchdog.UpdateThread(); + } public void AddGroupTarget(SceneObjectGroup grp) { @@ -3125,7 +3136,9 @@ namespace OpenSim.Region.Framework.Scenes (childagentYN ? "child" : "root"), agentID, RegionInfo.RegionName); m_sceneGraph.removeUserCount(!childagentYN); - CapsModule.RemoveCapsHandler(agentID); + + if (CapsModule != null) + CapsModule.RemoveCapsHandler(agentID); // REFACTORING PROBLEM -- well not really a problem, but just to point out that whatever // this method is doing is HORRIBLE!!! @@ -3329,7 +3342,7 @@ namespace OpenSim.Region.Framework.Scenes // TeleportFlags.ViaLandmark | TeleportFlags.ViaLocation | TeleportFlags.ViaLandmark | TeleportFlags.Default - Regular Teleport // Don't disable this log message - it's too helpful - m_log.InfoFormat( + m_log.DebugFormat( "[CONNECTION BEGIN]: Region {0} told of incoming {1} agent {2} {3} {4} (circuit code {5}, teleportflags {6})", RegionInfo.RegionName, (agent.child ? "child" : "root"), agent.firstname, agent.lastname, agent.AgentID, agent.circuitcode, teleportFlags); @@ -3403,8 +3416,11 @@ namespace OpenSim.Region.Framework.Scenes RegionInfo.RegionName, (agent.child ? "child" : "root"), agent.firstname, agent.lastname, agent.AgentID, agent.circuitcode); - CapsModule.NewUserConnection(agent); - CapsModule.AddCapsHandler(agent.AgentID); + if (CapsModule != null) + { + CapsModule.NewUserConnection(agent); + CapsModule.AddCapsHandler(agent.AgentID); + } } else { @@ -3419,7 +3435,9 @@ namespace OpenSim.Region.Framework.Scenes agent.AgentID, RegionInfo.RegionName); sp.AdjustKnownSeeds(); - CapsModule.NewUserConnection(agent); + + if (CapsModule != null) + CapsModule.NewUserConnection(agent); } } @@ -3506,6 +3524,8 @@ namespace OpenSim.Region.Framework.Scenes private bool TestLandRestrictions(UUID agentID, out string reason, ref float posX, ref float posY) { reason = String.Empty; + if (Permissions.IsGod(agentID)) + return true; ILandObject land = LandChannel.GetLandObject(posX, posY); if (land == null) @@ -3931,15 +3951,15 @@ namespace OpenSim.Region.Framework.Scenes public void RequestTeleportLocation(IClientAPI remoteClient, string regionName, Vector3 position, Vector3 lookat, uint teleportFlags) { - GridRegion regionInfo = GridService.GetRegionByName(UUID.Zero, regionName); - if (regionInfo == null) + List regions = GridService.GetRegionsByName(RegionInfo.ScopeID, regionName, 1); + if (regions == null || regions.Count == 0) { // can't find the region: Tell viewer and abort remoteClient.SendTeleportFailed("The region '" + regionName + "' could not be found."); return; } - RequestTeleportLocation(remoteClient, regionInfo.RegionHandle, position, lookat, teleportFlags); + RequestTeleportLocation(remoteClient, regions[0].RegionHandle, position, lookat, teleportFlags); } /// @@ -5143,9 +5163,15 @@ namespace OpenSim.Region.Framework.Scenes // from logging into the region, teleporting into the region // or corssing the broder walking, but will NOT prevent // child agent creation, thereby emulating the SL behavior. - public bool QueryAccess(UUID agentID, Vector3 position) + public bool QueryAccess(UUID agentID, Vector3 position, out string reason) { - string reason; + reason = "You are banned from the region"; + + if (Permissions.IsGod(agentID)) + { + reason = String.Empty; + return true; + } if (!AuthorizeUser(agentID, out reason)) { @@ -5176,6 +5202,8 @@ namespace OpenSim.Region.Framework.Scenes if (banned || restricted) return false; } + + reason = String.Empty; return true; } } diff --git a/OpenSim/Region/Framework/Scenes/SceneCommunicationService.cs b/OpenSim/Region/Framework/Scenes/SceneCommunicationService.cs index c8af4c38e3..19cb0c16ba 100644 --- a/OpenSim/Region/Framework/Scenes/SceneCommunicationService.cs +++ b/OpenSim/Region/Framework/Scenes/SceneCommunicationService.cs @@ -189,7 +189,8 @@ namespace OpenSim.Region.Framework.Scenes } } - public delegate void SendChildAgentDataUpdateDelegate(AgentPosition cAgentData, UUID scopeID, ulong regionHandle); + public delegate void SendChildAgentDataUpdateDelegate(AgentPosition cAgentData, UUID scopeID, GridRegion dest); + /// /// This informs all neighboring regions about the settings of it's child agent. @@ -198,31 +199,17 @@ namespace OpenSim.Region.Framework.Scenes /// This contains information, such as, Draw Distance, Camera location, Current Position, Current throttle settings, etc. /// /// - private void SendChildAgentDataUpdateAsync(AgentPosition cAgentData, UUID scopeID, ulong regionHandle) + private void SendChildAgentDataUpdateAsync(AgentPosition cAgentData, UUID scopeID, GridRegion dest) { //m_log.Info("[INTERGRID]: Informing neighbors about my agent in " + m_regionInfo.RegionName); try { - //m_commsProvider.InterRegion.ChildAgentUpdate(regionHandle, cAgentData); - uint x = 0, y = 0; - Utils.LongToUInts(regionHandle, out x, out y); - GridRegion destination = m_scene.GridService.GetRegionByPosition(UUID.Zero, (int)x, (int)y); - m_scene.SimulationService.UpdateAgent(destination, cAgentData); + m_scene.SimulationService.UpdateAgent(dest, cAgentData); } catch { // Ignore; we did our best } - - //if (regionAccepted) - //{ - // //m_log.Info("[INTERGRID]: Completed sending a neighbor an update about my agent"); - //} - //else - //{ - // //m_log.Info("[INTERGRID]: Failed sending a neighbor an update about my agent"); - //} - } private void SendChildAgentDataUpdateCompleted(IAsyncResult iar) @@ -236,14 +223,28 @@ namespace OpenSim.Region.Framework.Scenes // This assumes that we know what our neighbors are. try { + uint x = 0, y = 0; + List simulatorList = new List(); foreach (ulong regionHandle in presence.KnownChildRegionHandles) { if (regionHandle != m_regionInfo.RegionHandle) { - SendChildAgentDataUpdateDelegate d = SendChildAgentDataUpdateAsync; - d.BeginInvoke(cAgentData, m_regionInfo.ScopeID, regionHandle, - SendChildAgentDataUpdateCompleted, - d); + // we only want to send one update to each simulator; the simulator will + // hand it off to the regions where a child agent exists, this does assume + // that the region position is cached or performance will degrade + Utils.LongToUInts(regionHandle, out x, out y); + GridRegion dest = m_scene.GridService.GetRegionByPosition(UUID.Zero, (int)x, (int)y); + if (! simulatorList.Contains(dest.ServerURI)) + { + // we havent seen this simulator before, add it to the list + // and send it an update + simulatorList.Add(dest.ServerURI); + + SendChildAgentDataUpdateDelegate d = SendChildAgentDataUpdateAsync; + d.BeginInvoke(cAgentData, m_regionInfo.ScopeID, dest, + SendChildAgentDataUpdateCompleted, + d); + } } } } diff --git a/OpenSim/Region/Framework/Scenes/SceneGraph.cs b/OpenSim/Region/Framework/Scenes/SceneGraph.cs index 92fe2ab697..e8cf4f4f96 100644 --- a/OpenSim/Region/Framework/Scenes/SceneGraph.cs +++ b/OpenSim/Region/Framework/Scenes/SceneGraph.cs @@ -218,9 +218,10 @@ namespace OpenSim.Region.Framework.Scenes for (int i = 0; i < Math.Min(presences.Count, maxLocations); ++i) { ScenePresence sp = presences[i]; + // If this presence is a child agent, we don't want its coarse locations if (sp.IsChildAgent) - return; + continue; if (sp.ParentID != 0) { diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs b/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs index 6496a251e4..9b9f2806aa 100644 --- a/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs +++ b/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs @@ -2093,8 +2093,9 @@ namespace OpenSim.Region.Framework.Scenes public void GetProperties(IClientAPI client) { + //Viewer wants date in microseconds so multiply it by 1,000,000. client.SendObjectPropertiesReply( - m_fromUserInventoryItemID, (ulong)_creationDate, _creatorID, UUID.Zero, UUID.Zero, + m_fromUserInventoryItemID, (ulong)_creationDate*(ulong)1e6, _creatorID, UUID.Zero, UUID.Zero, _groupID, (short)InventorySerial, _lastOwnerID, UUID, _ownerID, ParentGroup.RootPart.TouchName, new byte[0], ParentGroup.RootPart.SitName, Name, Description, ParentGroup.RootPart._ownerMask, ParentGroup.RootPart._nextOwnerMask, ParentGroup.RootPart._groupMask, ParentGroup.RootPart._everyoneMask, @@ -2141,7 +2142,7 @@ namespace OpenSim.Region.Framework.Scenes { Quaternion newRot; - if (this.LinkNum < 2) //KF Single or root prim + if (this.LinkNum == 0 || this.LinkNum == 1) { newRot = RotationOffset; } diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs b/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs index 7e59b10037..854f1dc996 100644 --- a/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs +++ b/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs @@ -1287,9 +1287,13 @@ namespace OpenSim.Region.Framework.Scenes public Dictionary GetScriptStates(bool oldIDs) { + Dictionary ret = new Dictionary(); + + if (m_part.ParentGroup.Scene == null) // Group not in a scene + return ret; + IScriptModule[] engines = m_part.ParentGroup.Scene.RequestModuleInterfaces(); - - Dictionary ret = new Dictionary(); + if (engines == null) // No engine at all return ret; diff --git a/OpenSim/Region/Framework/Scenes/ScenePresence.cs b/OpenSim/Region/Framework/Scenes/ScenePresence.cs index b87275cbb5..3a5b05de8e 100644 --- a/OpenSim/Region/Framework/Scenes/ScenePresence.cs +++ b/OpenSim/Region/Framework/Scenes/ScenePresence.cs @@ -123,7 +123,6 @@ namespace OpenSim.Region.Framework.Scenes private SceneObjectGroup proxyObjectGroup; //private SceneObjectPart proxyObjectPart = null; public Vector3 lastKnownAllowedPosition; - public bool sentMessageAboutRestrictedParcelFlyingDown; public Vector4 CollisionPlane = Vector4.UnitW; private Vector3 m_avInitialPos; // used to calculate unscripted sit rotation @@ -691,7 +690,7 @@ namespace OpenSim.Region.Framework.Scenes Utils.LongToUInts(handle, out x, out y); x = x / Constants.RegionSize; y = y / Constants.RegionSize; - if (Util.IsOutsideView(x, Scene.RegionInfo.RegionLocX, y, Scene.RegionInfo.RegionLocY)) + if (Util.IsOutsideView(DrawDistance, x, Scene.RegionInfo.RegionLocX, y, Scene.RegionInfo.RegionLocY)) { old.Add(handle); } @@ -765,6 +764,7 @@ namespace OpenSim.Region.Framework.Scenes private ScenePresence(IClientAPI client, Scene world, RegionInfo reginfo) : this() { + m_DrawDistance = world.DefaultDrawDistance; m_rootRegionHandle = reginfo.RegionHandle; m_controllingClient = client; m_firstname = m_controllingClient.FirstName; @@ -1311,7 +1311,9 @@ namespace OpenSim.Region.Framework.Scenes if (m_agentTransfer != null) m_agentTransfer.EnableChildAgents(this); else - m_log.DebugFormat("[SCENE PRESENCE]: Unable to create child agents in neighbours, because AgentTransferModule is not active"); + m_log.DebugFormat( + "[SCENE PRESENCE]: Unable to create child agents in neighbours, because AgentTransferModule is not active for region {0}", + m_scene.RegionInfo.RegionName); IFriendsModule friendsModule = m_scene.RequestModuleInterface(); if (friendsModule != null) @@ -1428,7 +1430,11 @@ namespace OpenSim.Region.Framework.Scenes m_CameraUpAxis = agentData.CameraUpAxis; // The Agent's Draw distance setting - m_DrawDistance = agentData.Far; + // When we get to the point of re-computing neighbors everytime this + // changes, then start using the agent's drawdistance rather than the + // region's draw distance. + // m_DrawDistance = agentData.Far; + m_DrawDistance = Scene.DefaultDrawDistance; // Check if Client has camera in 'follow cam' or 'build' mode. Vector3 camdif = (Vector3.One * m_bodyRot - Vector3.One * CameraRotation); @@ -2853,7 +2859,7 @@ namespace OpenSim.Region.Framework.Scenes // If we are using the the cached appearance then send it out to everyone if (cachedappearance) { - m_log.InfoFormat("[SCENEPRESENCE]: baked textures are in the cache for {0}", Name); + m_log.DebugFormat("[SCENEPRESENCE]: baked textures are in the cache for {0}", Name); // If the avatars baked textures are all in the cache, then we have a // complete appearance... send it out, if not, then we'll send it when @@ -3070,8 +3076,11 @@ namespace OpenSim.Region.Framework.Scenes #region Border Crossing Methods /// - /// Checks to see if the avatar is in range of a border and calls CrossToNewRegion + /// Starts the process of moving an avatar into another region if they are crossing the border. /// + /// + /// Also removes the avatar from the physical scene if transit has started. + /// protected void CheckForBorderCrossing() { if (IsChildAgent) @@ -3139,7 +3148,6 @@ namespace OpenSim.Region.Framework.Scenes neighbor = HaveNeighbor(Cardinals.N, ref fix); } - // Makes sure avatar does not end up outside region if (neighbor <= 0) { @@ -3194,6 +3202,13 @@ namespace OpenSim.Region.Framework.Scenes } else { + // We must remove the agent from the physical scene if it has been placed in transit. If we don't, + // then this method continues to be called from ScenePresence.Update() until the handover of the client between + // regions is completed. Since this handover can take more than 1000ms (due to the 1000ms + // event queue polling response from the server), this results in the avatar pausing on the border + // for the handover period. + RemoveFromPhysicalScene(); + // This constant has been inferred from experimentation // I'm not sure what this value should be, so I tried a few values. timeStep = 0.04f; @@ -3205,6 +3220,15 @@ namespace OpenSim.Region.Framework.Scenes } } + /// + /// Checks whether this region has a neighbour in the given direction. + /// + /// + /// + /// + /// An integer which represents a compass point. N == 1, going clockwise until we reach NW == 8. + /// Returns a positive integer if there is a region in that direction, a negative integer if not. + /// protected int HaveNeighbor(Cardinals car, ref int[] fix) { uint neighbourx = m_regionInfo.RegionLocX; @@ -3311,7 +3335,7 @@ namespace OpenSim.Region.Framework.Scenes //m_log.Debug("---> x: " + x + "; newx:" + newRegionX + "; Abs:" + (int)Math.Abs((int)(x - newRegionX))); //m_log.Debug("---> y: " + y + "; newy:" + newRegionY + "; Abs:" + (int)Math.Abs((int)(y - newRegionY))); - if (Util.IsOutsideView(x, newRegionX, y, newRegionY)) + if (Util.IsOutsideView(DrawDistance, x, newRegionX, y, newRegionY)) { byebyeRegions.Add(handle); } @@ -3387,7 +3411,12 @@ namespace OpenSim.Region.Framework.Scenes Vector3 offset = new Vector3(shiftx, shifty, 0f); - m_DrawDistance = cAgentData.Far; + // When we get to the point of re-computing neighbors everytime this + // changes, then start using the agent's drawdistance rather than the + // region's draw distance. + // m_DrawDistance = cAgentData.Far; + m_DrawDistance = Scene.DefaultDrawDistance; + if (cAgentData.Position != new Vector3(-1f, -1f, -1f)) // UGH!! m_pos = cAgentData.Position + offset; @@ -3538,7 +3567,11 @@ namespace OpenSim.Region.Framework.Scenes m_CameraLeftAxis = cAgent.LeftAxis; m_CameraUpAxis = cAgent.UpAxis; - m_DrawDistance = cAgent.Far; + // When we get to the point of re-computing neighbors everytime this + // changes, then start using the agent's drawdistance rather than the + // region's draw distance. + // m_DrawDistance = cAgent.Far; + m_DrawDistance = Scene.DefaultDrawDistance; if ((cAgent.Throttles != null) && cAgent.Throttles.Length > 0) ControllingClient.SetChildAgentThrottle(cAgent.Throttles); diff --git a/OpenSim/Region/Framework/Scenes/SceneViewer.cs b/OpenSim/Region/Framework/Scenes/SceneViewer.cs index 40a73a9d4c..1f4ec9656c 100644 --- a/OpenSim/Region/Framework/Scenes/SceneViewer.cs +++ b/OpenSim/Region/Framework/Scenes/SceneViewer.cs @@ -205,6 +205,14 @@ namespace OpenSim.Region.Framework.Scenes Reset(); } + public int GetPendingObjectsCount() + { + if (m_pendingObjects != null) + return m_pendingObjects.Count; + + return 0; + } + public class ScenePartUpdate { public UUID FullID; diff --git a/OpenSim/Region/Framework/Scenes/Tests/AttachmentTests.cs b/OpenSim/Region/Framework/Scenes/Tests/AttachmentTests.cs new file mode 100644 index 0000000000..855b5894b6 --- /dev/null +++ b/OpenSim/Region/Framework/Scenes/Tests/AttachmentTests.cs @@ -0,0 +1,173 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Text; +using System.Threading; +using System.Timers; +using Timer=System.Timers.Timer; +using Nini.Config; +using NUnit.Framework; +using OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Framework.Communications; +using OpenSim.Region.Framework.Scenes; +using OpenSim.Region.Framework.Interfaces; +using OpenSim.Region.CoreModules.World.Serialiser; +using OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation; +using OpenSim.Tests.Common; +using OpenSim.Tests.Common.Mock; +using OpenSim.Tests.Common.Setup; + +namespace OpenSim.Region.Framework.Scenes.Tests +{ + /// + /// Attachment tests + /// + [TestFixture] + public class AttachmentTests + { + public Scene scene, scene2; + public UUID agent1; + public static Random random; + public ulong region1, region2; + public AgentCircuitData acd1; + public SceneObjectGroup sog1, sog2, sog3; + + [TestFixtureSetUp] + public void Init() + { + TestHelper.InMethod(); + + scene = SceneSetupHelpers.SetupScene("Neighbour x", UUID.Random(), 1000, 1000); + scene2 = SceneSetupHelpers.SetupScene("Neighbour x+1", UUID.Random(), 1001, 1000); + + ISharedRegionModule interregionComms = new LocalSimulationConnectorModule(); + interregionComms.Initialise(new IniConfigSource()); + interregionComms.PostInitialise(); + SceneSetupHelpers.SetupSceneModules(scene, new IniConfigSource(), interregionComms); + SceneSetupHelpers.SetupSceneModules(scene2, new IniConfigSource(), interregionComms); + + agent1 = UUID.Random(); + random = new Random(); + sog1 = NewSOG(UUID.Random(), scene, agent1); + sog2 = NewSOG(UUID.Random(), scene, agent1); + sog3 = NewSOG(UUID.Random(), scene, agent1); + + //ulong neighbourHandle = Utils.UIntsToLong((uint)(neighbourx * Constants.RegionSize), (uint)(neighboury * Constants.RegionSize)); + region1 = scene.RegionInfo.RegionHandle; + region2 = scene2.RegionInfo.RegionHandle; + + SceneSetupHelpers.AddRootAgent(scene, agent1); + } + + [Test] + public void T030_TestAddAttachments() + { + TestHelper.InMethod(); + + ScenePresence presence = scene.GetScenePresence(agent1); + + presence.AddAttachment(sog1); + presence.AddAttachment(sog2); + presence.AddAttachment(sog3); + + Assert.That(presence.HasAttachments(), Is.True); + Assert.That(presence.ValidateAttachments(), Is.True); + } + + [Test] + public void T031_RemoveAttachments() + { + TestHelper.InMethod(); + + ScenePresence presence = scene.GetScenePresence(agent1); + presence.RemoveAttachment(sog1); + presence.RemoveAttachment(sog2); + presence.RemoveAttachment(sog3); + Assert.That(presence.HasAttachments(), Is.False); + } + + // I'm commenting this test because scene setup NEEDS InventoryService to + // be non-null + //[Test] + public void T032_CrossAttachments() + { + TestHelper.InMethod(); + + ScenePresence presence = scene.GetScenePresence(agent1); + ScenePresence presence2 = scene2.GetScenePresence(agent1); + presence2.AddAttachment(sog1); + presence2.AddAttachment(sog2); + + ISharedRegionModule serialiser = new SerialiserModule(); + SceneSetupHelpers.SetupSceneModules(scene, new IniConfigSource(), serialiser); + SceneSetupHelpers.SetupSceneModules(scene2, new IniConfigSource(), serialiser); + + Assert.That(presence.HasAttachments(), Is.False, "Presence has attachments before cross"); + + //Assert.That(presence2.CrossAttachmentsIntoNewRegion(region1, true), Is.True, "Cross was not successful"); + Assert.That(presence2.HasAttachments(), Is.False, "Presence2 objects were not deleted"); + Assert.That(presence.HasAttachments(), Is.True, "Presence has not received new objects"); + } + + private SceneObjectGroup NewSOG(UUID uuid, Scene scene, UUID agent) + { + SceneObjectPart sop = new SceneObjectPart(); + sop.Name = RandomName(); + sop.Description = RandomName(); + sop.Text = RandomName(); + sop.SitName = RandomName(); + sop.TouchName = RandomName(); + sop.UUID = uuid; + sop.Shape = PrimitiveBaseShape.Default; + sop.Shape.State = 1; + sop.OwnerID = agent; + + SceneObjectGroup sog = new SceneObjectGroup(sop); + sog.SetScene(scene); + + return sog; + } + + private static string RandomName() + { + StringBuilder name = new StringBuilder(); + int size = random.Next(5,12); + char ch; + for (int i = 0; i < size; i++) + { + ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))) ; + name.Append(ch); + } + + return name.ToString(); + } + } +} \ No newline at end of file diff --git a/OpenSim/Region/Framework/Scenes/Tests/EntityManagerTests.cs b/OpenSim/Region/Framework/Scenes/Tests/EntityManagerTests.cs index b3c3e22af6..667b74ea95 100644 --- a/OpenSim/Region/Framework/Scenes/Tests/EntityManagerTests.cs +++ b/OpenSim/Region/Framework/Scenes/Tests/EntityManagerTests.cs @@ -32,7 +32,6 @@ using System.Text; using System.Collections.Generic; using Nini.Config; using NUnit.Framework; -using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; diff --git a/OpenSim/Region/Framework/Scenes/Tests/SceneGraphTests.cs b/OpenSim/Region/Framework/Scenes/Tests/SceneGraphTests.cs index 9244bc3461..ca635d708d 100644 --- a/OpenSim/Region/Framework/Scenes/Tests/SceneGraphTests.cs +++ b/OpenSim/Region/Framework/Scenes/Tests/SceneGraphTests.cs @@ -28,7 +28,6 @@ using System; using System.Reflection; using NUnit.Framework; -using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; diff --git a/OpenSim/Region/Framework/Scenes/Tests/SceneObjectBasicTests.cs b/OpenSim/Region/Framework/Scenes/Tests/SceneObjectBasicTests.cs index 4969b09149..a6a95ef885 100644 --- a/OpenSim/Region/Framework/Scenes/Tests/SceneObjectBasicTests.cs +++ b/OpenSim/Region/Framework/Scenes/Tests/SceneObjectBasicTests.cs @@ -28,7 +28,6 @@ using System; using System.Reflection; using NUnit.Framework; -using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; diff --git a/OpenSim/Region/Framework/Scenes/Tests/SceneObjectDeRezTests.cs b/OpenSim/Region/Framework/Scenes/Tests/SceneObjectDeRezTests.cs index 39116b6615..0d260266ef 100644 --- a/OpenSim/Region/Framework/Scenes/Tests/SceneObjectDeRezTests.cs +++ b/OpenSim/Region/Framework/Scenes/Tests/SceneObjectDeRezTests.cs @@ -30,7 +30,6 @@ using System.Collections.Generic; using System.Reflection; using Nini.Config; using NUnit.Framework; -using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; diff --git a/OpenSim/Region/Framework/Scenes/Tests/SceneObjectLinkingTests.cs b/OpenSim/Region/Framework/Scenes/Tests/SceneObjectLinkingTests.cs index b84298f2fa..bdfcd1dc29 100644 --- a/OpenSim/Region/Framework/Scenes/Tests/SceneObjectLinkingTests.cs +++ b/OpenSim/Region/Framework/Scenes/Tests/SceneObjectLinkingTests.cs @@ -29,7 +29,6 @@ using System; using System.Collections.Generic; using System.Reflection; using NUnit.Framework; -using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; diff --git a/OpenSim/Region/Framework/Scenes/Tests/SceneObjectUserGroupTests.cs b/OpenSim/Region/Framework/Scenes/Tests/SceneObjectUserGroupTests.cs index c78038f7a7..8876a435b6 100644 --- a/OpenSim/Region/Framework/Scenes/Tests/SceneObjectUserGroupTests.cs +++ b/OpenSim/Region/Framework/Scenes/Tests/SceneObjectUserGroupTests.cs @@ -30,7 +30,6 @@ using System.Collections.Generic; using System.Reflection; using Nini.Config; using NUnit.Framework; -using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; diff --git a/OpenSim/Region/Framework/Scenes/Tests/ScenePresenceTests.cs b/OpenSim/Region/Framework/Scenes/Tests/ScenePresenceTests.cs index ef52363611..efb757fa6c 100644 --- a/OpenSim/Region/Framework/Scenes/Tests/ScenePresenceTests.cs +++ b/OpenSim/Region/Framework/Scenes/Tests/ScenePresenceTests.cs @@ -34,12 +34,12 @@ using System.Timers; using Timer=System.Timers.Timer; using Nini.Config; using NUnit.Framework; -using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Interfaces; +using OpenSim.Region.CoreModules.Framework.EntityTransfer; using OpenSim.Region.CoreModules.World.Serialiser; using OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation; using OpenSim.Tests.Common; @@ -116,9 +116,6 @@ namespace OpenSim.Region.Framework.Scenes.Tests agent.ChildrenCapSeeds = new Dictionary(); agent.child = true; - if (scene.PresenceService == null) - Console.WriteLine("Presence Service is null"); - scene.PresenceService.LoginAgent(agent.AgentID.ToString(), agent.SessionID, agent.SecureSessionID); string reason; @@ -175,25 +172,6 @@ namespace OpenSim.Region.Framework.Scenes.Tests Assert.That(neighbours.Count, Is.EqualTo(2)); } - - public void fixNullPresence() - { - string firstName = "testfirstname"; - - AgentCircuitData agent = new AgentCircuitData(); - agent.AgentID = agent1; - agent.firstname = firstName; - agent.lastname = "testlastname"; - agent.SessionID = UUID.Zero; - agent.SecureSessionID = UUID.Zero; - agent.circuitcode = 123; - agent.BaseFolder = UUID.Zero; - agent.InventoryFolder = UUID.Zero; - agent.startpos = Vector3.Zero; - agent.CapsPath = GetRandomCapsObjectPath(); - - acd1 = agent; - } [Test] public void T013_TestRemoveNeighbourRegion() @@ -211,24 +189,36 @@ namespace OpenSim.Region.Framework.Scenes.Tests CompleteAvatarMovement */ } - - // I'm commenting this test, because this is not supposed to happen here - //[Test] - public void T020_TestMakeRootAgent() + + /// + /// Test that if a root agent logs into a region, a child agent is also established in the neighbouring region + /// + /// + /// Please note that unlike the other tests here, this doesn't rely on structures + /// + [Test] + public void TestChildAgentEstablished() { TestHelper.InMethod(); - - ScenePresence presence = scene.GetScenePresence(agent1); - Assert.That(presence.IsChildAgent, Is.False, "Starts out as a root agent"); - - presence.MakeChildAgent(); - Assert.That(presence.IsChildAgent, Is.True, "Did not change to child agent after MakeChildAgent"); - - // Accepts 0 but rejects Constants.RegionSize - Vector3 pos = new Vector3(0,unchecked(Constants.RegionSize-1),0); - presence.MakeRootAgent(pos,true); - Assert.That(presence.IsChildAgent, Is.False, "Did not go back to root agent"); - Assert.That(presence.AbsolutePosition, Is.EqualTo(pos), "Position is not the same one entered"); +// log4net.Config.XmlConfigurator.Configure(); + + UUID agent1Id = UUID.Parse("00000000-0000-0000-0000-000000000001"); + + TestScene myScene1 = SceneSetupHelpers.SetupScene("Neighbour y", UUID.Random(), 1000, 1000); + TestScene myScene2 = SceneSetupHelpers.SetupScene("Neighbour y + 1", UUID.Random(), 1001, 1000); + + IConfigSource configSource = new IniConfigSource(); + configSource.AddConfig("Modules").Set("EntityTransferModule", "BasicEntityTransferModule"); + EntityTransferModule etm = new EntityTransferModule(); + + SceneSetupHelpers.SetupSceneModules(myScene1, configSource, etm); + + SceneSetupHelpers.AddRootAgent(myScene1, agent1Id); + ScenePresence childPresence = myScene2.GetScenePresence(agent1); + + // TODO: Need to do a fair amount of work to allow synchronous establishment of child agents +// Assert.That(childPresence, Is.Not.Null); +// Assert.That(childPresence.IsChildAgent, Is.True); } // I'm commenting this test because it does not represent @@ -333,63 +323,26 @@ namespace OpenSim.Region.Framework.Scenes.Tests Assert.That(presence2.IsChildAgent, Is.True, "Did not return from region as expected."); Assert.That(presence.IsChildAgent, Is.False, "Presence was not made root in old region again."); } - - [Test] - public void T030_TestAddAttachments() + + public void fixNullPresence() { - TestHelper.InMethod(); + string firstName = "testfirstname"; - ScenePresence presence = scene.GetScenePresence(agent1); + AgentCircuitData agent = new AgentCircuitData(); + agent.AgentID = agent1; + agent.firstname = firstName; + agent.lastname = "testlastname"; + agent.SessionID = UUID.Zero; + agent.SecureSessionID = UUID.Zero; + agent.circuitcode = 123; + agent.BaseFolder = UUID.Zero; + agent.InventoryFolder = UUID.Zero; + agent.startpos = Vector3.Zero; + agent.CapsPath = GetRandomCapsObjectPath(); - presence.AddAttachment(sog1); - presence.AddAttachment(sog2); - presence.AddAttachment(sog3); - - Assert.That(presence.HasAttachments(), Is.True); - Assert.That(presence.ValidateAttachments(), Is.True); + acd1 = agent; } - - [Test] - public void T031_RemoveAttachments() - { - TestHelper.InMethod(); - - ScenePresence presence = scene.GetScenePresence(agent1); - presence.RemoveAttachment(sog1); - presence.RemoveAttachment(sog2); - presence.RemoveAttachment(sog3); - Assert.That(presence.HasAttachments(), Is.False); - } - - // I'm commenting this test because scene setup NEEDS InventoryService to - // be non-null - //[Test] - public void T032_CrossAttachments() - { - TestHelper.InMethod(); - - ScenePresence presence = scene.GetScenePresence(agent1); - ScenePresence presence2 = scene2.GetScenePresence(agent1); - presence2.AddAttachment(sog1); - presence2.AddAttachment(sog2); - - ISharedRegionModule serialiser = new SerialiserModule(); - SceneSetupHelpers.SetupSceneModules(scene, new IniConfigSource(), serialiser); - SceneSetupHelpers.SetupSceneModules(scene2, new IniConfigSource(), serialiser); - - Assert.That(presence.HasAttachments(), Is.False, "Presence has attachments before cross"); - - //Assert.That(presence2.CrossAttachmentsIntoNewRegion(region1, true), Is.True, "Cross was not successful"); - Assert.That(presence2.HasAttachments(), Is.False, "Presence2 objects were not deleted"); - Assert.That(presence.HasAttachments(), Is.True, "Presence has not received new objects"); - } - - [TearDown] - public void TearDown() - { - if (MainServer.Instance != null) MainServer.Instance.Stop(); - } - + public static string GetRandomCapsObjectPath() { UUID caps = UUID.Random(); diff --git a/OpenSim/Region/Framework/Scenes/Tests/SceneTests.cs b/OpenSim/Region/Framework/Scenes/Tests/SceneTests.cs new file mode 100644 index 0000000000..abcce66e23 --- /dev/null +++ b/OpenSim/Region/Framework/Scenes/Tests/SceneTests.cs @@ -0,0 +1,70 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Text; +using System.Threading; +using System.Timers; +using Timer=System.Timers.Timer; +using Nini.Config; +using NUnit.Framework; +using OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Framework.Communications; +using OpenSim.Region.Framework.Scenes; +using OpenSim.Region.Framework.Interfaces; +using OpenSim.Region.CoreModules.World.Serialiser; +using OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation; +using OpenSim.Tests.Common; +using OpenSim.Tests.Common.Mock; +using OpenSim.Tests.Common.Setup; + +namespace OpenSim.Region.Framework.Scenes.Tests +{ + /// + /// Scene presence tests + /// + [TestFixture] + public class SceneTests + { + /// + /// Very basic scene update test. Should become more elaborate with time. + /// + [Test] + public void TestUpdateScene() + { + TestHelper.InMethod(); + + Scene scene = SceneSetupHelpers.SetupScene(); + scene.Update(); + + Assert.That(scene.Frame, Is.EqualTo(1)); + } + } +} \ No newline at end of file diff --git a/OpenSim/Region/Framework/Scenes/Tests/StandaloneTeleportTests.cs b/OpenSim/Region/Framework/Scenes/Tests/StandaloneTeleportTests.cs index cafe48afdd..8588f7f599 100644 --- a/OpenSim/Region/Framework/Scenes/Tests/StandaloneTeleportTests.cs +++ b/OpenSim/Region/Framework/Scenes/Tests/StandaloneTeleportTests.cs @@ -29,7 +29,6 @@ using System; using System.Reflection; using Nini.Config; using NUnit.Framework; -using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; diff --git a/OpenSim/Region/Framework/Scenes/Tests/TaskInventoryTests.cs b/OpenSim/Region/Framework/Scenes/Tests/TaskInventoryTests.cs index fe59d4f031..8138bcc19a 100644 --- a/OpenSim/Region/Framework/Scenes/Tests/TaskInventoryTests.cs +++ b/OpenSim/Region/Framework/Scenes/Tests/TaskInventoryTests.cs @@ -34,7 +34,6 @@ using System.Timers; using Timer=System.Timers.Timer; using Nini.Config; using NUnit.Framework; -using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenMetaverse.Assets; using OpenSim.Framework; diff --git a/OpenSim/Region/Framework/Scenes/Tests/UuidGathererTests.cs b/OpenSim/Region/Framework/Scenes/Tests/UuidGathererTests.cs index 5e6124b4f9..6b70865533 100644 --- a/OpenSim/Region/Framework/Scenes/Tests/UuidGathererTests.cs +++ b/OpenSim/Region/Framework/Scenes/Tests/UuidGathererTests.cs @@ -28,7 +28,6 @@ using System.Collections.Generic; using System.Text; using NUnit.Framework; -using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; diff --git a/OpenSim/Region/OptionalModules/Agent/UDP/Linden/LindenUDPInfoModule.cs b/OpenSim/Region/OptionalModules/Agent/UDP/Linden/LindenUDPInfoModule.cs index 87d067c961..6a24cc1092 100644 --- a/OpenSim/Region/OptionalModules/Agent/UDP/Linden/LindenUDPInfoModule.cs +++ b/OpenSim/Region/OptionalModules/Agent/UDP/Linden/LindenUDPInfoModule.cs @@ -51,7 +51,7 @@ namespace OpenSim.Region.CoreModules.UDP.Linden [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "LindenUDPInfoModule")] public class LindenUDPInfoModule : ISharedRegionModule { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); +// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected Dictionary m_scenes = new Dictionary(); @@ -95,7 +95,15 @@ namespace OpenSim.Region.CoreModules.UDP.Linden "Show throttle settings for each client and for the server overall", "Without the 'full' option, only root agents are shown." + " With the 'full' option child agents are also shown.", - ShowThrottlesReport); + ShowThrottlesReport); + + scene.AddCommand( + this, "emergency-monitoring", + "Go on/off emergency monitoring mode", + "Go on/off emergency monitoring mode", + "Go on/off emergency monitoring mode", + EmergencyMonitoring); + } public void RemoveRegion(Scene scene) @@ -120,7 +128,25 @@ namespace OpenSim.Region.CoreModules.UDP.Linden { MainConsole.Instance.Output(GetThrottlesReport(cmd)); } - + + protected void EmergencyMonitoring(string module, string[] cmd) + { + bool mode = true; + if (cmd.Length == 1 || (cmd.Length > 1 && cmd[1] == "on")) + { + mode = true; + MainConsole.Instance.Output("Emergency Monitoring ON"); + } + else + { + mode = false; + MainConsole.Instance.Output("Emergency Monitoring OFF"); + } + + foreach (Scene s in m_scenes.Values) + s.EmergencyMonitoring = mode; + } + protected string GetColumnEntry(string entry, int maxLength, int columnPadding) { return string.Format( @@ -154,24 +180,26 @@ namespace OpenSim.Region.CoreModules.UDP.Linden report.Append(GetColumnEntry("Type", maxTypeLength, columnPadding)); report.AppendFormat( - "{0,7} {1,7} {2,9} {3,8} {4,7} {5,7} {6,7} {7,7} {8,9} {9,7} {10,7}\n", + "{0,7} {1,7} {2,7} {3,9} {4,7} {5,7} {6,7} {7,7} {8,7} {9,8} {10,7} {11,7}\n", "Pkts", "Pkts", + "Pkts", "Bytes", - "Pkts", - "Pkts", - "Pkts", - "Pkts", - "Pkts", - "Pkts", - "Pkts", - "Pkts"); + "Q Pkts", + "Q Pkts", + "Q Pkts", + "Q Pkts", + "Q Pkts", + "Q Pkts", + "Q Pkts", + "Q Pkts"); report.AppendFormat("{0,-" + totalInfoFieldsLength + "}", ""); report.AppendFormat( - "{0,7} {1,7} {2,9} {3,8} {4,7} {5,7} {6,7} {7,7} {8,9} {9,7} {10,7}\n", - "Out", + "{0,7} {1,7} {2,7} {3,9} {4,7} {5,7} {6,7} {7,7} {8,7} {9,8} {10,7} {11,7}\n", "In", + "Out", + "Resent", "Unacked", "Resend", "Land", @@ -333,7 +361,7 @@ namespace OpenSim.Region.CoreModules.UDP.Linden ThrottleRates throttleRates = udpServer.ThrottleRates; report.AppendFormat( "{0,7} {1,8} {2,7} {3,7} {4,7} {5,7} {6,9} {7,7}", - "n/a", + (throttleRates.Total * 8) / 1000, (throttleRates.ResendLimit * 8) / 1000, (throttleRates.LandLimit * 8) / 1000, (throttleRates.WindLimit * 8) / 1000, diff --git a/OpenSim/Region/OptionalModules/Avatar/Voice/FreeSwitchVoice/FreeSwitchVoiceModule.cs b/OpenSim/Region/OptionalModules/Avatar/Voice/FreeSwitchVoice/FreeSwitchVoiceModule.cs index d75e25d353..7deb32f47c 100644 --- a/OpenSim/Region/OptionalModules/Avatar/Voice/FreeSwitchVoice/FreeSwitchVoiceModule.cs +++ b/OpenSim/Region/OptionalModules/Avatar/Voice/FreeSwitchVoice/FreeSwitchVoiceModule.cs @@ -92,7 +92,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice private static string m_freeSwitchUrlResetPassword; private uint m_freeSwitchServicePort; private string m_openSimWellKnownHTTPAddress; - private string m_freeSwitchContext; +// private string m_freeSwitchContext; private readonly Dictionary m_UUIDName = new Dictionary(); private Dictionary m_ParcelAddress = new Dictionary(); @@ -144,7 +144,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice m_freeSwitchDefaultWellKnownIP = map["DefaultWellKnownIP"].AsString(); m_freeSwitchDefaultTimeout = map["DefaultTimeout"].AsInteger(); m_freeSwitchUrlResetPassword = String.Empty; - m_freeSwitchContext = map["Context"].AsString(); +// m_freeSwitchContext = map["Context"].AsString(); if (String.IsNullOrEmpty(m_freeSwitchRealm) || String.IsNullOrEmpty(m_freeSwitchAPIPrefix)) @@ -662,7 +662,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice resp.Append(""); response["str_response_string"] = resp.ToString(); - Regex normalizeEndLines = new Regex(@"\r\n", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.Multiline); +// Regex normalizeEndLines = new Regex(@"\r\n", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.Multiline); //m_log.DebugFormat("[FREESWITCH]: {0}", normalizeEndLines.Replace((string)response["str_response_string"],"")); return response; @@ -670,10 +670,10 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice public Hashtable FreeSwitchSLVoiceSigninHTTPHandler(Hashtable request) { -// m_log.Debug("[FreeSwitchVoice] FreeSwitchSLVoiceSigninHTTPHandler called"); - string requestbody = (string)request["body"]; - string uri = (string)request["uri"]; - string contenttype = (string)request["content-type"]; + //m_log.Debug("[FreeSwitchVoice] FreeSwitchSLVoiceSigninHTTPHandler called"); +// string requestbody = (string)request["body"]; +// string uri = (string)request["uri"]; +// string contenttype = (string)request["content-type"]; Hashtable requestBody = ParseRequestBody((string)request["body"]); diff --git a/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/IGroupsServicesConnector.cs b/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/IGroupsServicesConnector.cs index 5c779debc5..6d2607541e 100644 --- a/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/IGroupsServicesConnector.cs +++ b/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/IGroupsServicesConnector.cs @@ -63,7 +63,26 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups void SetAgentActiveGroupRole(UUID RequestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID); void SetAgentGroupInfo(UUID RequestingAgentID, UUID AgentID, UUID GroupID, bool AcceptNotices, bool ListInProfile); + /// + /// Get information about a specific group to which the user belongs. + /// + /// The agent requesting the information. + /// The agent requested. + /// The group requested. + /// + /// If the user is a member of the group then the data structure is returned. If not, then null is returned. + /// GroupMembershipData GetAgentGroupMembership(UUID RequestingAgentID, UUID AgentID, UUID GroupID); + + /// + /// Get information about the groups to which a user belongs. + /// + /// The agent requesting the information. + /// The agent requested. + /// + /// Information about the groups to which the user belongs. If the user belongs to no groups then an empty + /// list is returned. + /// List GetAgentGroupMemberships(UUID RequestingAgentID, UUID AgentID); void AddGroupNotice(UUID RequestingAgentID, UUID groupID, UUID noticeID, string fromName, string subject, string message, byte[] binaryBucket); diff --git a/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/SimianGroupsServicesConnectorModule.cs b/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/SimianGroupsServicesConnectorModule.cs index 0d265f2501..02751eafa7 100644 --- a/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/SimianGroupsServicesConnectorModule.cs +++ b/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/SimianGroupsServicesConnectorModule.cs @@ -704,7 +704,6 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups } } - return findings; } @@ -712,54 +711,55 @@ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); - GroupMembershipData data = new GroupMembershipData(); - - /////////////////////////////// - // Agent Specific Information: - // - OSDMap UserActiveGroup; - if (SimianGetGenericEntry(agentID, "Group", "ActiveGroup", out UserActiveGroup)) - { - data.Active = UserActiveGroup["GroupID"].AsUUID().Equals(groupID); - } + GroupMembershipData data = null; +// bool foundData = false; OSDMap UserGroupMemberInfo; if (SimianGetGenericEntry(agentID, "GroupMember", groupID.ToString(), out UserGroupMemberInfo)) { + data = new GroupMembershipData(); data.AcceptNotices = UserGroupMemberInfo["AcceptNotices"].AsBoolean(); data.Contribution = UserGroupMemberInfo["Contribution"].AsInteger(); data.ListInProfile = UserGroupMemberInfo["ListInProfile"].AsBoolean(); - data.ActiveRole = UserGroupMemberInfo["SelectedRoleID"].AsUUID(); + data.ActiveRole = UserGroupMemberInfo["SelectedRoleID"].AsUUID(); + + /////////////////////////////// + // Agent Specific Information: + // + OSDMap UserActiveGroup; + if (SimianGetGenericEntry(agentID, "Group", "ActiveGroup", out UserActiveGroup)) + { + data.Active = UserActiveGroup["GroupID"].AsUUID().Equals(groupID); + } /////////////////////////////// // Role Specific Information: // - OSDMap GroupRoleInfo; if (SimianGetGenericEntry(groupID, "GroupRole", data.ActiveRole.ToString(), out GroupRoleInfo)) { data.GroupTitle = GroupRoleInfo["Title"].AsString(); data.GroupPowers = GroupRoleInfo["Powers"].AsULong(); - } - } - - /////////////////////////////// - // Group Specific Information: - // - OSDMap GroupInfo; - string GroupName; - if (SimianGetFirstGenericEntry(groupID, "Group", out GroupName, out GroupInfo)) - { - data.GroupID = groupID; - data.AllowPublish = GroupInfo["AllowPublish"].AsBoolean(); - data.Charter = GroupInfo["Charter"].AsString(); - data.FounderID = GroupInfo["FounderID"].AsUUID(); - data.GroupName = GroupName; - data.GroupPicture = GroupInfo["InsigniaID"].AsUUID(); - data.MaturePublish = GroupInfo["MaturePublish"].AsBoolean(); - data.MembershipFee = GroupInfo["MembershipFee"].AsInteger(); - data.OpenEnrollment = GroupInfo["OpenEnrollment"].AsBoolean(); - data.ShowInList = GroupInfo["ShowInList"].AsBoolean(); + } + + /////////////////////////////// + // Group Specific Information: + // + OSDMap GroupInfo; + string GroupName; + if (SimianGetFirstGenericEntry(groupID, "Group", out GroupName, out GroupInfo)) + { + data.GroupID = groupID; + data.AllowPublish = GroupInfo["AllowPublish"].AsBoolean(); + data.Charter = GroupInfo["Charter"].AsString(); + data.FounderID = GroupInfo["FounderID"].AsUUID(); + data.GroupName = GroupName; + data.GroupPicture = GroupInfo["InsigniaID"].AsUUID(); + data.MaturePublish = GroupInfo["MaturePublish"].AsBoolean(); + data.MembershipFee = GroupInfo["MembershipFee"].AsInteger(); + data.OpenEnrollment = GroupInfo["OpenEnrollment"].AsBoolean(); + data.ShowInList = GroupInfo["ShowInList"].AsBoolean(); + } } return data; diff --git a/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/Tests/GroupsModuleTests.cs b/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/Tests/GroupsModuleTests.cs index bc55b04743..6de97b7269 100644 --- a/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/Tests/GroupsModuleTests.cs +++ b/OpenSim/Region/OptionalModules/Avatar/XmlRpcGroups/Tests/GroupsModuleTests.cs @@ -29,7 +29,6 @@ using System; using System.Reflection; using Nini.Config; using NUnit.Framework; -using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; diff --git a/OpenSim/Region/OptionalModules/World/MoneyModule/SampleMoneyModule.cs b/OpenSim/Region/OptionalModules/World/MoneyModule/SampleMoneyModule.cs index b84a34d288..d469548236 100644 --- a/OpenSim/Region/OptionalModules/World/MoneyModule/SampleMoneyModule.cs +++ b/OpenSim/Region/OptionalModules/World/MoneyModule/SampleMoneyModule.cs @@ -838,6 +838,10 @@ namespace OpenSim.Region.OptionalModules.World.MoneyModule if (module != null) module.BuyObject(remoteClient, categoryID, localID, saleType, salePrice); } + + public void MoveMoney(UUID fromAgentID, UUID toAgentID, int amount, string text) + { + } } public enum TransactionType : int diff --git a/OpenSim/Region/OptionalModules/World/WorldView/WorldViewModule.cs b/OpenSim/Region/OptionalModules/World/WorldView/WorldViewModule.cs index d4b7020542..cee8851c3a 100644 --- a/OpenSim/Region/OptionalModules/World/WorldView/WorldViewModule.cs +++ b/OpenSim/Region/OptionalModules/World/WorldView/WorldViewModule.cs @@ -71,6 +71,9 @@ namespace OpenSim.Region.OptionalModules.World.WorldView public void RegionLoaded(Scene scene) { + if (!m_Enabled) + return; + m_Generator = scene.RequestModuleInterface(); if (m_Generator == null) { diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/CM_Api.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/CM_Api.cs new file mode 100644 index 0000000000..489c1c6e21 --- /dev/null +++ b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/CM_Api.cs @@ -0,0 +1,118 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Reflection; +using System.Collections; +using System.Collections.Generic; +using System.Runtime.Remoting.Lifetime; +using OpenMetaverse; +using Nini.Config; +using OpenSim; +using OpenSim.Framework; +using OpenSim.Region.CoreModules.World.LightShare; +using OpenSim.Region.Framework.Interfaces; +using OpenSim.Region.Framework.Scenes; +using OpenSim.Region.ScriptEngine.Shared; +using OpenSim.Region.ScriptEngine.Shared.Api.Plugins; +using OpenSim.Region.ScriptEngine.Shared.ScriptBase; +using OpenSim.Region.ScriptEngine.Interfaces; +using OpenSim.Region.ScriptEngine.Shared.Api.Interfaces; +using OpenSim.Services.Interfaces; + +using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat; +using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger; +using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; +using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list; +using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion; +using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; +using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3; + +namespace OpenSim.Region.ScriptEngine.Shared.Api +{ + [Serializable] + public class CM_Api : MarshalByRefObject, ICM_Api, IScriptApi + { + internal IScriptEngine m_ScriptEngine; + internal SceneObjectPart m_host; + internal uint m_localID; + internal UUID m_itemID; + internal bool m_CMFunctionsEnabled = false; + + public void Initialize(IScriptEngine ScriptEngine, SceneObjectPart host, uint localID, UUID itemID) + { + m_ScriptEngine = ScriptEngine; + m_host = host; + m_localID = localID; + m_itemID = itemID; + + if (m_ScriptEngine.Config.GetBoolean("AllowCareminsterFunctions", false)) + m_CMFunctionsEnabled = true; + } + + public override Object InitializeLifetimeService() + { + ILease lease = (ILease)base.InitializeLifetimeService(); + + if (lease.CurrentState == LeaseState.Initial) + { + lease.InitialLeaseTime = TimeSpan.FromMinutes(0); + // lease.RenewOnCallTime = TimeSpan.FromSeconds(10.0); + // lease.SponsorshipTimeout = TimeSpan.FromMinutes(1.0); + } + return lease; + } + + public Scene World + { + get { return m_ScriptEngine.World; } + } + + public string cmDetectedCountry(int number) + { + m_host.AddScriptLPS(1); + DetectParams detectedParams = m_ScriptEngine.GetDetectParams(m_itemID, number); + if (detectedParams == null) + return String.Empty; + return detectedParams.Country; + } + + public string cmGetAgentCountry(LSL_Key key) + { + if (!World.Permissions.IsGod(m_host.OwnerID)) + return String.Empty; + + UUID uuid; + + if (!UUID.TryParse(key, out uuid)) + return String.Empty; + + UserAccount account = World.UserAccountService.GetUserAccount(World.RegionInfo.ScopeID, uuid); + return account.UserCountry; + } + } +} diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs index 59e905e7ab..559523b86b 100644 --- a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs +++ b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs @@ -1920,15 +1920,14 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api if (part == null || part.ParentGroup == null || part.ParentGroup.IsDeleted) return; - UUID textureID=new UUID(); + UUID textureID = new UUID(); - if (!UUID.TryParse(texture, out textureID)) - { - textureID=InventoryKey(texture, (int)AssetType.Texture); - } - - if (textureID == UUID.Zero) - return; + textureID = InventoryKey(texture, (int)AssetType.Texture); + if (textureID == UUID.Zero) + { + if (!UUID.TryParse(texture, out textureID)) + return; + } Primitive.TextureEntry tex = part.Shape.Textures; @@ -3346,12 +3345,19 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api msg.ParentEstateID = World.RegionInfo.EstateSettings.EstateID; msg.Position = new Vector3(m_host.AbsolutePosition); msg.RegionID = World.RegionInfo.RegionID.Guid; - msg.binaryBucket = Util.StringToBytes256(m_host.OwnerID.ToString()); + msg.binaryBucket + = Util.StringToBytes256( + "{0}/{1}/{2}/{3}", + World.RegionInfo.RegionName, + (int)Math.Floor(m_host.AbsolutePosition.X), + (int)Math.Floor(m_host.AbsolutePosition.Y), + (int)Math.Floor(m_host.AbsolutePosition.Z)); if (m_TransferModule != null) { m_TransferModule.SendInstantMessage(msg, delegate(bool success) {}); } + ScriptSleep(2000); } @@ -4195,7 +4201,8 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api if (!found) { llSay(0, String.Format("Could not find object '{0}'", inventory)); - throw new Exception(String.Format("The inventory object '{0}' could not be found", inventory)); + return; +// throw new Exception(String.Format("The inventory object '{0}' could not be found", inventory)); } // check if destination is an object @@ -4479,7 +4486,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api if (presence != null) { // agent must not be a god - if (presence.GodLevel >= 200) return; + if (presence.UserLevel >= 200) return; // agent must be over the owners land if (m_host.OwnerID == World.LandChannel.GetLandObject( @@ -6860,6 +6867,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api } // copy the first script found with this inventory name + TaskInventoryItem scriptItem = null; m_host.TaskInventory.LockItemsForRead(true); foreach (KeyValuePair inv in m_host.TaskInventory) { @@ -6870,6 +6878,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api { found = true; srcId = inv.Key; + scriptItem = inv.Value; break; } } @@ -6882,8 +6891,18 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api return; } - // the rest of the permission checks are done in RezScript, so check the pin there as well - World.RezScript(srcId, m_host, destId, pin, running, start_param); + SceneObjectPart dest = World.GetSceneObjectPart(destId); + if (dest != null) + { + if ((scriptItem.BasePermissions & (uint)PermissionMask.Transfer) != 0 || dest.ParentGroup.RootPart.OwnerID == m_host.ParentGroup.RootPart.OwnerID) + { + // the rest of the permission checks are done in RezScript, so check the pin there as well + World.RezScript(srcId, m_host, destId, pin, running, start_param); + + if ((scriptItem.BasePermissions & (uint)PermissionMask.Copy) == 0) + m_host.Inventory.RemoveInventoryItem(srcId); + } + } // this will cause the delay even if the script pin or permissions were wrong - seems ok ScriptSleep(3000); } diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/OSSL_Api.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/OSSL_Api.cs index cf059b3afa..39e1a27a94 100644 --- a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/OSSL_Api.cs +++ b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/OSSL_Api.cs @@ -690,10 +690,11 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api // CheckThreatLevel(ThreatLevel.High, "osTeleportAgent"); - TeleportAgent(agent, regionName, position, lookat); + TeleportAgent(agent, regionName, position, lookat, false); } - private void TeleportAgent(string agent, string regionName, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat) + private void TeleportAgent(string agent, string regionName, + LSL_Types.Vector3 position, LSL_Types.Vector3 lookat, bool relaxRestrictions) { m_host.AddScriptLPS(1); UUID agentId = new UUID(); @@ -702,21 +703,13 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api ScenePresence presence = World.GetScenePresence(agentId); if (presence != null) { - // agent must be over owners land to avoid abuse - if (m_host.OwnerID + // For osTeleportAgent, agent must be over owners land to avoid abuse + // For osTeleportOwner, this restriction isn't necessary + if (relaxRestrictions || + m_host.OwnerID == World.LandChannel.GetLandObject( presence.AbsolutePosition.X, presence.AbsolutePosition.Y).LandData.OwnerID) { - // Check for hostname, attempt to make a HG link, - // and convert the regionName to the target region - if (regionName.Contains(".") && regionName.Contains(":")) - { -// List regions = World.GridService.GetRegionsByName(World.RegionInfo.ScopeID, regionName, 1); - string[] parts = regionName.Split(new char[] { ':' }); - if (parts.Length > 2) - regionName = parts[0] + ':' + parts[1] + "/ " + parts[2]; - regionName = "http://" + regionName; - } World.RequestTeleportLocation(presence.ControllingClient, regionName, new Vector3((float)position.x, (float)position.y, (float)position.z), new Vector3((float)lookat.x, (float)lookat.y, (float)lookat.z), (uint)TPFlags.ViaLocation); @@ -733,10 +726,11 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api // CheckThreatLevel(ThreatLevel.High, "osTeleportAgent"); - TeleportAgent(agent, regionX, regionY, position, lookat); + TeleportAgent(agent, regionX, regionY, position, lookat, false); } - private void TeleportAgent(string agent, int regionX, int regionY, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat) + private void TeleportAgent(string agent, int regionX, int regionY, + LSL_Types.Vector3 position, LSL_Types.Vector3 lookat, bool relaxRestrictions) { ulong regionHandle = Util.UIntsToLong(((uint)regionX * (uint)Constants.RegionSize), ((uint)regionY * (uint)Constants.RegionSize)); @@ -747,8 +741,10 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api ScenePresence presence = World.GetScenePresence(agentId); if (presence != null) { - // agent must be over owners land to avoid abuse - if (m_host.OwnerID + // For osTeleportAgent, agent must be over owners land to avoid abuse + // For osTeleportOwner, this restriction isn't necessary + if (relaxRestrictions || + m_host.OwnerID == World.LandChannel.GetLandObject( presence.AbsolutePosition.X, presence.AbsolutePosition.Y).LandData.OwnerID) { @@ -771,7 +767,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api // Threat level None because this is what can already be done with the World Map in the viewer CheckThreatLevel(ThreatLevel.None, "osTeleportOwner"); - TeleportAgent(m_host.OwnerID.ToString(), regionName, position, lookat); + TeleportAgent(m_host.OwnerID.ToString(), regionName, position, lookat, true); } public void osTeleportOwner(LSL_Types.Vector3 position, LSL_Types.Vector3 lookat) @@ -783,7 +779,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api { CheckThreatLevel(ThreatLevel.None, "osTeleportOwner"); - TeleportAgent(m_host.OwnerID.ToString(), regionX, regionY, position, lookat); + TeleportAgent(m_host.OwnerID.ToString(), regionX, regionY, position, lookat, true); } // Functions that get information from the agent itself. diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Interface/ICM_Api.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Interface/ICM_Api.cs new file mode 100644 index 0000000000..ab215f304f --- /dev/null +++ b/OpenSim/Region/ScriptEngine/Shared/Api/Interface/ICM_Api.cs @@ -0,0 +1,46 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System.Collections; +using OpenSim.Region.ScriptEngine.Interfaces; + +using key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; +using rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion; +using vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3; +using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list; +using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; +using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger; +using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat; + +namespace OpenSim.Region.ScriptEngine.Shared.Api.Interfaces +{ + public interface ICM_Api + { + string cmDetectedCountry(int num); + string cmGetAgentCountry(key key); + } +} diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/CM_Stub.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/CM_Stub.cs new file mode 100644 index 0000000000..4132dfa312 --- /dev/null +++ b/OpenSim/Region/ScriptEngine/Shared/Api/Runtime/CM_Stub.cs @@ -0,0 +1,71 @@ +/* + * 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.Runtime.Remoting.Lifetime; +using System.Threading; +using System.Reflection; +using System.Collections; +using System.Collections.Generic; +using OpenSim.Framework; +using OpenSim.Region.Framework.Interfaces; +using OpenSim.Region.ScriptEngine.Interfaces; +using OpenSim.Region.ScriptEngine.Shared.Api.Interfaces; +using integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger; +using vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3; +using rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion; +using key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; +using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list; +using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; +using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat; +using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger; + +namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase +{ + public partial class ScriptBaseClass : MarshalByRefObject + { + public ICM_Api m_CM_Functions; + + public void ApiTypeCM(IScriptApi api) + { + if (!(api is ICM_Api)) + return; + + m_CM_Functions = (ICM_Api)api; + } + + public string cmDetectedCountry(int num) + { + return m_CM_Functions.cmDetectedCountry(num); + } + + public string cmGetAgentCountry(key key) + { + return m_CM_Functions.cmGetAgentCountry(key); + } + } +} diff --git a/OpenSim/Server/Handlers/Grid/GridServerPostHandler.cs b/OpenSim/Server/Handlers/Grid/GridServerPostHandler.cs index 913c6c9b3a..edc05612db 100644 --- a/OpenSim/Server/Handlers/Grid/GridServerPostHandler.cs +++ b/OpenSim/Server/Handlers/Grid/GridServerPostHandler.cs @@ -115,15 +115,15 @@ namespace OpenSim.Server.Handlers.Grid case "get_region_flags": return GetRegionFlags(request); } + m_log.DebugFormat("[GRID HANDLER]: unknown method {0} request {1}", method.Length, method); } catch (Exception e) { - m_log.DebugFormat("[GRID HANDLER]: Exception {0}", e); + m_log.ErrorFormat("[GRID HANDLER]: Exception {0} {1}", e.Message, e.StackTrace); } return FailureResult(); - } #region Method-specific handlers diff --git a/OpenSim/Server/Handlers/Simulation/AgentHandlers.cs b/OpenSim/Server/Handlers/Simulation/AgentHandlers.cs index b33b0d5847..616aef3390 100644 --- a/OpenSim/Server/Handlers/Simulation/AgentHandlers.cs +++ b/OpenSim/Server/Handlers/Simulation/AgentHandlers.cs @@ -205,6 +205,11 @@ namespace OpenSim.Server.Handlers.Simulation // We're behind a proxy Hashtable headers = (Hashtable)request["headers"]; + + //// DEBUG + //foreach (object o in headers.Keys) + // m_log.DebugFormat("XXX {0} = {1}", o.ToString(), (headers[o] == null? "null" : headers[o].ToString())); + string xff = "X-Forwarded-For"; if (headers.ContainsKey(xff.ToLower())) xff = xff.ToLower(); @@ -341,10 +346,17 @@ namespace OpenSim.Server.Handlers.Simulation GridRegion destination = new GridRegion(); destination.RegionID = regionID; - bool result = m_SimulationService.QueryAccess(destination, id, position); + string reason; + bool result = m_SimulationService.QueryAccess(destination, id, position, out reason); responsedata["int_response_code"] = HttpStatusCode.OK; - responsedata["str_response_string"] = result.ToString(); + + OSDMap resp = new OSDMap(2); + + resp["success"] = OSD.FromBoolean(result); + resp["reason"] = OSD.FromString(reason); + + responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp); } protected virtual void DoAgentGet(Hashtable request, Hashtable responsedata, UUID id, UUID regionID) diff --git a/OpenSim/Services/AssetService/AssetService.cs b/OpenSim/Services/AssetService/AssetService.cs index 81ef225ca1..c29bce8136 100644 --- a/OpenSim/Services/AssetService/AssetService.cs +++ b/OpenSim/Services/AssetService/AssetService.cs @@ -93,7 +93,7 @@ namespace OpenSim.Services.AssetService if (!UUID.TryParse(id, out assetID)) { - m_log.WarnFormat("[ASSET SERVICE]: Could not parse requested sset id {0}", id); + m_log.WarnFormat("[ASSET SERVICE]: Could not parse requested asset id {0}", id); return null; } diff --git a/OpenSim/Services/Connectors/Inventory/HGInventoryServiceConnector.cs b/OpenSim/Services/Connectors/Inventory/HGInventoryServiceConnector.cs deleted file mode 100644 index 9878855355..0000000000 --- a/OpenSim/Services/Connectors/Inventory/HGInventoryServiceConnector.cs +++ /dev/null @@ -1,335 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using log4net; -using Nini.Config; -using System; -using System.Collections.Generic; -using System.Reflection; -using OpenSim.Framework; -using OpenSim.Services.Interfaces; -using OpenMetaverse; - -namespace OpenSim.Services.Connectors.Inventory -{ - public class HGInventoryServiceConnector : ISessionAuthInventoryService - { - private static readonly ILog m_log = - LogManager.GetLogger( - MethodBase.GetCurrentMethod().DeclaringType); - - private Dictionary m_connectors = new Dictionary(); - - public HGInventoryServiceConnector(IConfigSource source) - { - IConfig moduleConfig = source.Configs["Modules"]; - if (moduleConfig != null) - { - - IConfig inventoryConfig = source.Configs["InventoryService"]; - if (inventoryConfig == null) - { - m_log.Error("[HG INVENTORY SERVICE]: InventoryService missing from OpenSim.ini"); - return; - } - - m_log.Info("[HG INVENTORY SERVICE]: HG inventory service enabled"); - } - } - - private bool StringToUrlAndUserID(string id, out string url, out string userID) - { - url = String.Empty; - userID = String.Empty; - - Uri assetUri; - - if (Uri.TryCreate(id, UriKind.Absolute, out assetUri) && - assetUri.Scheme == Uri.UriSchemeHttp) - { - url = "http://" + assetUri.Authority; - userID = assetUri.LocalPath.Trim(new char[] { '/' }); - return true; - } - - return false; - } - private ISessionAuthInventoryService GetConnector(string url) - { - InventoryServicesConnector connector = null; - lock (m_connectors) - { - if (m_connectors.ContainsKey(url)) - { - connector = m_connectors[url]; - } - else - { - // We're instantiating this class explicitly, but this won't - // work in general, because the remote grid may be running - // an inventory server that has a different protocol. - // Eventually we will want a piece of protocol asking - // the remote server about its kind. Definitely cool thing to do! - connector = new InventoryServicesConnector(url); - m_connectors.Add(url, connector); - } - } - return connector; - } - - public string Host - { - get { return string.Empty; } - } - - public void GetUserInventory(string id, UUID sessionID, InventoryReceiptCallback callback) - { - m_log.Debug("[HGInventory]: GetUserInventory " + id); - string url = string.Empty; - string userID = string.Empty; - - if (StringToUrlAndUserID(id, out url, out userID)) - { - ISessionAuthInventoryService connector = GetConnector(url); - connector.GetUserInventory(userID, sessionID, callback); - } - - } - - /// - /// Gets the user folder for the given folder-type - /// - /// - /// - /// - public Dictionary GetSystemFolders(string id, UUID sessionID) - { - m_log.Debug("[HGInventory]: GetSystemFolders " + id); - string url = string.Empty; - string userID = string.Empty; - - if (StringToUrlAndUserID(id, out url, out userID)) - { - ISessionAuthInventoryService connector = GetConnector(url); - return connector.GetSystemFolders(userID, sessionID); - } - - return new Dictionary(); - } - - /// - /// Gets everything (folders and items) inside a folder - /// - /// - /// - /// - public InventoryCollection GetFolderContent(string id, UUID folderID, UUID sessionID) - { - m_log.Debug("[HGInventory]: GetFolderContent " + id); - string url = string.Empty; - string userID = string.Empty; - - if (StringToUrlAndUserID(id, out url, out userID)) - { - ISessionAuthInventoryService connector = GetConnector(url); - return connector.GetFolderContent(userID, folderID, sessionID); - } - - return null; - } - - public bool AddFolder(string id, InventoryFolderBase folder, UUID sessionID) - { - string url = string.Empty; - string userID = string.Empty; - - if (StringToUrlAndUserID(id, out url, out userID)) - { - ISessionAuthInventoryService connector = GetConnector(url); - return connector.AddFolder(userID, folder, sessionID); - } - return false; - } - - public bool UpdateFolder(string id, InventoryFolderBase folder, UUID sessionID) - { - string url = string.Empty; - string userID = string.Empty; - - if (StringToUrlAndUserID(id, out url, out userID)) - { - ISessionAuthInventoryService connector = GetConnector(url); - return connector.UpdateFolder(userID, folder, sessionID); - } - return false; - } - - public bool MoveFolder(string id, InventoryFolderBase folder, UUID sessionID) - { - string url = string.Empty; - string userID = string.Empty; - - if (StringToUrlAndUserID(id, out url, out userID)) - { - ISessionAuthInventoryService connector = GetConnector(url); - return connector.MoveFolder(userID, folder, sessionID); - } - return false; - } - - public bool DeleteFolders(string id, List folders, UUID sessionID) - { - string url = string.Empty; - string userID = string.Empty; - - if (StringToUrlAndUserID(id, out url, out userID)) - { - ISessionAuthInventoryService connector = GetConnector(url); - return connector.DeleteFolders(userID, folders, sessionID); - } - return false; - } - - public bool PurgeFolder(string id, InventoryFolderBase folder, UUID sessionID) - { - string url = string.Empty; - string userID = string.Empty; - - if (StringToUrlAndUserID(id, out url, out userID)) - { - ISessionAuthInventoryService connector = GetConnector(url); - return connector.PurgeFolder(userID, folder, sessionID); - } - return false; - } - - public List GetFolderItems(string id, UUID folderID, UUID sessionID) - { - string url = string.Empty; - string userID = string.Empty; - - if (StringToUrlAndUserID(id, out url, out userID)) - { - ISessionAuthInventoryService connector = GetConnector(url); - return connector.GetFolderItems(userID, folderID, sessionID); - } - return new List(); - } - - public bool AddItem(string id, InventoryItemBase item, UUID sessionID) - { - string url = string.Empty; - string userID = string.Empty; - - if (StringToUrlAndUserID(id, out url, out userID)) - { - ISessionAuthInventoryService connector = GetConnector(url); - return connector.AddItem(userID, item, sessionID); - } - return false; - } - - public bool UpdateItem(string id, InventoryItemBase item, UUID sessionID) - { - string url = string.Empty; - string userID = string.Empty; - - if (StringToUrlAndUserID(id, out url, out userID)) - { - ISessionAuthInventoryService connector = GetConnector(url); - return connector.UpdateItem(userID, item, sessionID); - } - return false; - } - - public bool MoveItems(string id, List items, UUID sessionID) - { - string url = string.Empty; - string userID = string.Empty; - - if (StringToUrlAndUserID(id, out url, out userID)) - { - ISessionAuthInventoryService connector = GetConnector(url); - return connector.MoveItems(userID, items, sessionID); - } - return false; - } - - public bool DeleteItems(string id, List itemIDs, UUID sessionID) - { - string url = string.Empty; - string userID = string.Empty; - - if (StringToUrlAndUserID(id, out url, out userID)) - { - ISessionAuthInventoryService connector = GetConnector(url); - return connector.DeleteItems(userID, itemIDs, sessionID); - } - return false; - } - - public InventoryItemBase QueryItem(string id, InventoryItemBase item, UUID sessionID) - { - string url = string.Empty; - string userID = string.Empty; - - if (StringToUrlAndUserID(id, out url, out userID)) - { - //m_log.DebugFormat("[HGInventory CONNECTOR]: calling {0}", url); - ISessionAuthInventoryService connector = GetConnector(url); - return connector.QueryItem(userID, item, sessionID); - } - return null; - } - - public InventoryFolderBase QueryFolder(string id, InventoryFolderBase folder, UUID sessionID) - { - string url = string.Empty; - string userID = string.Empty; - - if (StringToUrlAndUserID(id, out url, out userID)) - { - ISessionAuthInventoryService connector = GetConnector(url); - return connector.QueryFolder(userID, folder, sessionID); - } - return null; - } - - public int GetAssetPermissions(string id, UUID assetID, UUID sessionID) - { - string url = string.Empty; - string userID = string.Empty; - - if (StringToUrlAndUserID(id, out url, out userID)) - { - ISessionAuthInventoryService connector = GetConnector(url); - return connector.GetAssetPermissions(userID, assetID, sessionID); - } - return 0; - } - } -} diff --git a/OpenSim/Services/Connectors/Inventory/ISessionAuthInventoryService.cs b/OpenSim/Services/Connectors/Inventory/ISessionAuthInventoryService.cs deleted file mode 100644 index da8c7e2e61..0000000000 --- a/OpenSim/Services/Connectors/Inventory/ISessionAuthInventoryService.cs +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System.Collections.Generic; -using OpenSim.Framework; -using OpenSim.Services.Interfaces; -using OpenMetaverse; - -namespace OpenSim.Services.Connectors -{ - /// - /// Defines all operations to access a remote inventory service - /// using session authentication as a form of security. - /// - public interface ISessionAuthInventoryService - { - string Host - { - get; - } - - /// - /// Request the inventory for a user. This is an asynchronous operation that will call the callback when the - /// inventory has been received - /// - /// - /// - void GetUserInventory(string userID, UUID session_id, InventoryReceiptCallback callback); - - /// - /// Gets the user folder for the given folder-type - /// - /// - /// - /// - Dictionary GetSystemFolders(string userID, UUID session_id); - - /// - /// Gets everything (folders and items) inside a folder - /// - /// - /// - /// - InventoryCollection GetFolderContent(string userID, UUID folderID, UUID session_id); - - /// - /// Add a new folder to the user's inventory - /// - /// - /// true if the folder was successfully added - bool AddFolder(string userID, InventoryFolderBase folder, UUID session_id); - - /// - /// Update a folder in the user's inventory - /// - /// - /// true if the folder was successfully updated - bool UpdateFolder(string userID, InventoryFolderBase folder, UUID session_id); - - /// - /// Move an inventory folder to a new location - /// - /// A folder containing the details of the new location - /// true if the folder was successfully moved - bool MoveFolder(string userID, InventoryFolderBase folder, UUID session_id); - - /// - /// Delete a list of inventory folders (from trash) - /// - bool DeleteFolders(string userID, List folders, UUID session_id); - - /// - /// Purge an inventory folder of all its items and subfolders. - /// - /// - /// true if the folder was successfully purged - bool PurgeFolder(string userID, InventoryFolderBase folder, UUID session_id); - - /// - /// Get items from a folder. - /// - /// - /// true if the folder was successfully purged - List GetFolderItems(string userID, UUID folderID, UUID session_id); - - /// - /// Add a new item to the user's inventory - /// - /// - /// true if the item was successfully added - bool AddItem(string userID, InventoryItemBase item, UUID session_id); - - /// - /// Update an item in the user's inventory - /// - /// - /// true if the item was successfully updated - bool UpdateItem(string userID, InventoryItemBase item, UUID session_id); - - bool MoveItems(string userID, List items, UUID session_id); - - /// - /// Delete an item from the user's inventory - /// - /// - /// true if the item was successfully deleted - bool DeleteItems(string userID, List itemIDs, UUID session_id); - - InventoryItemBase QueryItem(string userID, InventoryItemBase item, UUID session_id); - - InventoryFolderBase QueryFolder(string userID, InventoryFolderBase item, UUID session_id); - - int GetAssetPermissions(string userID, UUID assetID, UUID session_id); - - } -} diff --git a/OpenSim/Services/Connectors/Inventory/InventoryServiceConnector.cs b/OpenSim/Services/Connectors/Inventory/InventoryServiceConnector.cs deleted file mode 100644 index f86b453665..0000000000 --- a/OpenSim/Services/Connectors/Inventory/InventoryServiceConnector.cs +++ /dev/null @@ -1,582 +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 log4net; -using System; -using System.Collections.Generic; -using System.IO; -using System.Reflection; -using Nini.Config; -using OpenSim.Framework; -using OpenSim.Framework.Servers.HttpServer; -using OpenSim.Services.Interfaces; -using OpenMetaverse; - -namespace OpenSim.Services.Connectors -{ - public class InventoryServicesConnector : ISessionAuthInventoryService - { - private static readonly ILog m_log = - LogManager.GetLogger( - MethodBase.GetCurrentMethod().DeclaringType); - - private string m_ServerURI = String.Empty; - - private Dictionary m_RequestingInventory = new Dictionary(); - private Dictionary m_RequestTime = new Dictionary(); - - public InventoryServicesConnector() - { - } - - public InventoryServicesConnector(string serverURI) - { - m_ServerURI = serverURI.TrimEnd('/'); - } - - public InventoryServicesConnector(IConfigSource source) - { - Initialise(source); - } - - public virtual void Initialise(IConfigSource source) - { - IConfig inventoryConfig = source.Configs["InventoryService"]; - if (inventoryConfig == null) - { - m_log.Error("[INVENTORY CONNECTOR]: InventoryService missing from OpenSim.ini"); - throw new Exception("InventoryService missing from OpenSim.ini"); - } - - string serviceURI = inventoryConfig.GetString("InventoryServerURI", - String.Empty); - - if (serviceURI == String.Empty) - { - m_log.Error("[INVENTORY CONNECTOR]: No Server URI named in section InventoryService"); - throw new Exception("Unable to proceed. Please make sure your ini files in config-include are updated according to .example's"); - } - m_ServerURI = serviceURI.TrimEnd('/'); - } - - #region ISessionAuthInventoryService - - public string Host - { - get { return m_ServerURI; } - } - - /// - /// Caller must catch eventual Exceptions. - /// - /// - /// - /// - public void GetUserInventory(string userIDStr, UUID sessionID, InventoryReceiptCallback callback) - { - UUID userID = UUID.Zero; - if (UUID.TryParse(userIDStr, out userID)) - { - lock (m_RequestingInventory) - { - // *HACK ALERT* - - // If an inventory request times out, it blocks any further requests from the - // same user, even after a relog. This is bad, and makes me sad. - - // Really, we should detect a timeout and report a failure to the callback, - // BUT in my testing i found that it's hard to detect a timeout.. sometimes, - // a partial response is recieved, and sometimes a null response. - - // So, for now, add a timer of ten seconds (which is the request timeout). - - // This should basically have the same effect. - - lock (m_RequestTime) - { - if (m_RequestTime.ContainsKey(userID)) - { - TimeSpan interval = DateTime.Now - m_RequestTime[userID]; - if (interval.TotalSeconds > 10) - { - m_RequestTime.Remove(userID); - if (m_RequestingInventory.ContainsKey(userID)) - { - m_RequestingInventory.Remove(userID); - } - } - } - if (!m_RequestingInventory.ContainsKey(userID)) - { - m_RequestTime.Add(userID, DateTime.Now); - m_RequestingInventory.Add(userID, callback); - } - else - { - m_log.ErrorFormat("[INVENTORY CONNECTOR]: GetUserInventory - ignoring repeated request for user {0}", userID); - return; - } - } - } - - m_log.InfoFormat( - "[INVENTORY CONNECTOR]: Requesting inventory from {0}/GetInventory/ for user {1}", - m_ServerURI, userID); - - RestSessionObjectPosterResponse requester - = new RestSessionObjectPosterResponse(); - requester.ResponseCallback = InventoryResponse; - - requester.BeginPostObject(m_ServerURI + "/GetInventory/", userID.Guid, sessionID.ToString(), userID.ToString()); - } - } - - /// - /// Gets the user folder for the given folder-type - /// - /// - /// - /// - public Dictionary GetSystemFolders(string userID, UUID sessionID) - { - List folders = null; - Dictionary dFolders = new Dictionary(); - try - { - folders = SynchronousRestSessionObjectPoster>.BeginPostObject( - "POST", m_ServerURI + "/SystemFolders/", new Guid(userID), sessionID.ToString(), userID.ToString()); - - foreach (InventoryFolderBase f in folders) - dFolders[(AssetType)f.Type] = f; - - return dFolders; - } - catch (Exception e) - { - // Maybe we're talking to an old inventory server. Try this other thing. - m_log.ErrorFormat("[INVENTORY CONNECTOR]: GetSystemFolders operation failed, {0} {1} (old sever?). Trying GetInventory.", - e.Source, e.Message); - - try - { - InventoryCollection inventory = SynchronousRestSessionObjectPoster.BeginPostObject( - "POST", m_ServerURI + "/GetInventory/", new Guid(userID), sessionID.ToString(), userID.ToString()); - folders = inventory.Folders; - } - catch (Exception ex) - { - m_log.ErrorFormat("[INVENTORY CONNECTOR]: GetInventory operation also failed, {0} {1}. Giving up.", - e.Source, ex.Message); - } - - if ((folders != null) && (folders.Count > 0)) - { - m_log.DebugFormat("[INVENTORY CONNECTOR]: Received entire inventory ({0} folders) for user {1}", - folders.Count, userID); - foreach (InventoryFolderBase f in folders) - { - if ((f.Type != (short)AssetType.Folder) && (f.Type != (short)AssetType.Unknown)) - dFolders[(AssetType)f.Type] = f; - } - - UUID rootFolderID = dFolders[AssetType.Animation].ParentID; - InventoryFolderBase rootFolder = new InventoryFolderBase(rootFolderID, new UUID(userID)); - rootFolder = QueryFolder(userID, rootFolder, sessionID); - dFolders[AssetType.Folder] = rootFolder; - m_log.DebugFormat("[INVENTORY CONNECTOR]: {0} system folders for user {1}", dFolders.Count, userID); - return dFolders; - } - } - - return new Dictionary(); - } - - /// - /// Gets everything (folders and items) inside a folder - /// - /// - /// - /// - public InventoryCollection GetFolderContent(string userID, UUID folderID, UUID sessionID) - { - try - { - // normal case - return SynchronousRestSessionObjectPoster.BeginPostObject( - "POST", m_ServerURI + "/GetFolderContent/", folderID.Guid, sessionID.ToString(), userID.ToString()); - } - catch (TimeoutException e) - { - m_log.ErrorFormat( - "[INVENTORY CONNECTOR]: GetFolderContent operation to {0} for {1} timed out {2} {3}.", - m_ServerURI, folderID, e.Source, e.Message); - } - catch (Exception e) - { - m_log.ErrorFormat("[INVENTORY CONNECTOR]: GetFolderContent operation failed for {0}, {1} {2} (old server?).", - folderID, e.Source, e.Message); - } - - InventoryCollection nullCollection = new InventoryCollection(); - nullCollection.Folders = new List(); - nullCollection.Items = new List(); - nullCollection.UserID = new UUID(userID); - return nullCollection; - } - - public bool AddFolder(string userID, InventoryFolderBase folder, UUID sessionID) - { - try - { - return SynchronousRestSessionObjectPoster.BeginPostObject( - "POST", m_ServerURI + "/NewFolder/", folder, sessionID.ToString(), folder.Owner.ToString()); - } - catch (Exception e) - { - m_log.ErrorFormat("[INVENTORY CONNECTOR]: Add new inventory folder operation failed for {0} {1}, {2} {3}", - folder.Name, folder.ID, e.Source, e.Message); - } - - return false; - } - - public bool UpdateFolder(string userID, InventoryFolderBase folder, UUID sessionID) - { - try - { - return SynchronousRestSessionObjectPoster.BeginPostObject( - "POST", m_ServerURI + "/UpdateFolder/", folder, sessionID.ToString(), folder.Owner.ToString()); - } - catch (Exception e) - { - m_log.ErrorFormat("[INVENTORY CONNECTOR]: Update inventory folder operation failed for {0} {1}, {2} {3}", - folder.Name, folder.ID, e.Source, e.Message); - } - - return false; - } - - public bool DeleteFolders(string userID, List folderIDs, UUID sessionID) - { - try - { - List guids = new List(); - foreach (UUID u in folderIDs) - guids.Add(u.Guid); - return SynchronousRestSessionObjectPoster, bool>.BeginPostObject( - "POST", m_ServerURI + "/DeleteFolders/", guids, sessionID.ToString(), userID); - } - catch (Exception e) - { - m_log.ErrorFormat("[INVENTORY CONNECTOR]: Delete inventory folders operation failed, {0} {1}", - e.Source, e.Message); - } - - return false; - } - - public bool MoveFolder(string userID, InventoryFolderBase folder, UUID sessionID) - { - try - { - return SynchronousRestSessionObjectPoster.BeginPostObject( - "POST", m_ServerURI + "/MoveFolder/", folder, sessionID.ToString(), folder.Owner.ToString()); - } - catch (Exception e) - { - m_log.ErrorFormat("[INVENTORY CONNECTOR]: Move inventory folder operation failed for {0} {1}, {2} {3}", - folder.Name, folder.ID, e.Source, e.Message); - } - - return false; - } - - public bool PurgeFolder(string userID, InventoryFolderBase folder, UUID sessionID) - { - try - { - return SynchronousRestSessionObjectPoster.BeginPostObject( - "POST", m_ServerURI + "/PurgeFolder/", folder, sessionID.ToString(), folder.Owner.ToString()); - } - catch (Exception e) - { - m_log.ErrorFormat("[INVENTORY CONNECTOR]: Purge inventory folder operation failed for {0} {1}, {2} {3}", - folder.Name, folder.ID, e.Source, e.Message); - } - - return false; - } - - public List GetFolderItems(string userID, UUID folderID, UUID sessionID) - { - try - { - InventoryFolderBase folder = new InventoryFolderBase(folderID, new UUID(userID)); - return SynchronousRestSessionObjectPoster>.BeginPostObject( - "POST", m_ServerURI + "/GetItems/", folder, sessionID.ToString(), userID); - } - catch (Exception e) - { - m_log.ErrorFormat("[INVENTORY CONNECTOR]: Get folder items operation failed for folder {0}, {1} {2}", - folderID, e.Source, e.Message); - } - - return null; - } - - public bool AddItem(string userID, InventoryItemBase item, UUID sessionID) - { - try - { - return SynchronousRestSessionObjectPoster.BeginPostObject( - "POST", m_ServerURI + "/NewItem/", item, sessionID.ToString(), item.Owner.ToString()); - } - catch (Exception e) - { - m_log.ErrorFormat("[INVENTORY CONNECTOR]: Add new inventory item operation failed for {0} {1}, {2} {3}", - item.Name, item.ID, e.Source, e.Message); - } - - return false; - } - - public bool UpdateItem(string userID, InventoryItemBase item, UUID sessionID) - { - try - { - return SynchronousRestSessionObjectPoster.BeginPostObject( - "POST", m_ServerURI + "/NewItem/", item, sessionID.ToString(), item.Owner.ToString()); - } - catch (Exception e) - { - m_log.ErrorFormat("[INVENTORY CONNECTOR]: Update new inventory item operation failed for {0} {1}, {2} {3}", - item.Name, item.ID, e.Source, e.Message); - } - - return false; - } - - /** - * MoveItems Async group - */ - - delegate void MoveItemsDelegate(string userID, List items, UUID sessionID); - - private void MoveItemsAsync(string userID, List items, UUID sessionID) - { - if (items == null) - { - m_log.WarnFormat("[INVENTORY CONNECTOR]: request to move items got a null list."); - return; - } - - try - { - //SynchronousRestSessionObjectPoster, bool>.BeginPostObject( - // "POST", m_ServerURI + "/MoveItems/", items, sessionID.ToString(), userID.ToString()); - - //// Success - //return; - string uri = m_ServerURI + "/inventory/" + userID; - if (SynchronousRestObjectRequester. - MakeRequest, bool>("PUT", uri, items)) - m_log.DebugFormat("[INVENTORY CONNECTOR]: move {0} items poster succeeded {1}", items.Count, uri); - else - m_log.DebugFormat("[INVENTORY CONNECTOR]: move {0} items poster failed {1}", items.Count, uri); ; - - return; - - } - catch (Exception e) - { - m_log.ErrorFormat("[INVENTORY CONNECTOR]: Move inventory items operation failed, {0} {1} (old server?). Trying slow way.", - e.Source, e.Message); - } - - } - - private void MoveItemsCompleted(IAsyncResult iar) - { - MoveItemsDelegate d = (MoveItemsDelegate)iar.AsyncState; - d.EndInvoke(iar); - } - - public bool MoveItems(string userID, List items, UUID sessionID) - { - MoveItemsDelegate d = MoveItemsAsync; - d.BeginInvoke(userID, items, sessionID, MoveItemsCompleted, d); - return true; - } - - public bool DeleteItems(string userID, List items, UUID sessionID) - { - try - { - List guids = new List(); - foreach (UUID u in items) - guids.Add(u.Guid); - return SynchronousRestSessionObjectPoster, bool>.BeginPostObject( - "POST", m_ServerURI + "/DeleteItem/", guids, sessionID.ToString(), userID); - } - catch (Exception e) - { - m_log.ErrorFormat("[INVENTORY CONNECTOR]: Delete inventory items operation failed, {0} {1}", - e.Source, e.Message); - } - - return false; - } - - public InventoryItemBase QueryItem(string userID, InventoryItemBase item, UUID sessionID) - { - try - { - return SynchronousRestSessionObjectPoster.BeginPostObject( - "POST", m_ServerURI + "/QueryItem/", item, sessionID.ToString(), item.Owner.ToString()); - } - catch (Exception e) - { - m_log.ErrorFormat("[INVENTORY CONNECTOR]: Query inventory item operation failed, {0} {1}", - e.Source, e.Message); - } - - return null; - } - - public InventoryFolderBase QueryFolder(string userID, InventoryFolderBase folder, UUID sessionID) - { - try - { - return SynchronousRestSessionObjectPoster.BeginPostObject( - "POST", m_ServerURI + "/QueryFolder/", folder, sessionID.ToString(), userID); - } - catch (Exception e) - { - m_log.ErrorFormat("[INVENTORY CONNECTOR]: Query inventory folder operation failed, {0} {1}", - e.Source, e.Message); - } - - return null; - } - - public int GetAssetPermissions(string userID, UUID assetID, UUID sessionID) - { - try - { - InventoryItemBase item = new InventoryItemBase(); - item.Owner = new UUID(userID); - item.AssetID = assetID; - return SynchronousRestSessionObjectPoster.BeginPostObject( - "POST", m_ServerURI + "/AssetPermissions/", item, sessionID.ToString(), userID); - } - catch (Exception e) - { - m_log.ErrorFormat("[INVENTORY CONNECTOR]: AssetPermissions operation failed, {0} {1}", - e.Source, e.Message); - } - - return 0; - } - - #endregion - - /// - /// Callback used by the inventory server GetInventory request - /// - /// - private void InventoryResponse(InventoryCollection response) - { - UUID userID = response.UserID; - InventoryReceiptCallback callback = null; - lock (m_RequestingInventory) - { - if (m_RequestingInventory.ContainsKey(userID)) - { - callback = m_RequestingInventory[userID]; - m_RequestingInventory.Remove(userID); - lock (m_RequestTime) - { - if (m_RequestTime.ContainsKey(userID)) - { - m_RequestTime.Remove(userID); - } - } - } - else - { - m_log.WarnFormat( - "[INVENTORY CONNECTOR]: " + - "Received inventory response for {0} for which we do not have a record of requesting!", - userID); - return; - } - } - - m_log.InfoFormat("[INVENTORY CONNECTOR]: " + - "Received inventory response for user {0} containing {1} folders and {2} items", - userID, response.Folders.Count, response.Items.Count); - - InventoryFolderImpl rootFolder = null; - - ICollection folders = new List(); - ICollection items = new List(); - - foreach (InventoryFolderBase folder in response.Folders) - { - if (folder.ParentID == UUID.Zero) - { - rootFolder = new InventoryFolderImpl(folder); - folders.Add(rootFolder); - - break; - } - } - - if (rootFolder != null) - { - foreach (InventoryFolderBase folder in response.Folders) - { - if (folder.ID != rootFolder.ID) - { - folders.Add(new InventoryFolderImpl(folder)); - } - } - - foreach (InventoryItemBase item in response.Items) - { - items.Add(item); - } - } - else - { - m_log.ErrorFormat("[INVENTORY CONNECTOR]: Did not get back an inventory containing a root folder for user {0}", userID); - } - - callback(folders, items); - } - } -} diff --git a/OpenSim/Services/Connectors/Inventory/QuickAndDirtyInventoryServiceConnector.cs b/OpenSim/Services/Connectors/Inventory/QuickAndDirtyInventoryServiceConnector.cs deleted file mode 100644 index a7aa1382c4..0000000000 --- a/OpenSim/Services/Connectors/Inventory/QuickAndDirtyInventoryServiceConnector.cs +++ /dev/null @@ -1,196 +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 log4net; -using System; -using System.Collections.Generic; -using System.IO; -using System.Reflection; -using Nini.Config; -using OpenSim.Framework; -using OpenSim.Framework.Servers.HttpServer; -using OpenSim.Services.Interfaces; -using OpenMetaverse; - -namespace OpenSim.Services.Connectors -{ - /// - /// This connector is temporary. It's used by the user server, before that server is refactored. - /// - public class QuickAndDirtyInventoryServiceConnector : IInventoryService - { -// private static readonly ILog m_log = -// LogManager.GetLogger( -// MethodBase.GetCurrentMethod().DeclaringType); - - private string m_ServerURI = String.Empty; - - //private Dictionary m_RequestingInventory = new Dictionary(); - - public QuickAndDirtyInventoryServiceConnector() - { - } - - public QuickAndDirtyInventoryServiceConnector(string serverURI) - { - m_ServerURI = serverURI.TrimEnd('/'); - } - - /// - /// - /// - /// - /// - public bool CreateUserInventory(UUID userId) - { - return SynchronousRestObjectPoster.BeginPostObject( - "POST", m_ServerURI + "CreateInventory/", userId.Guid); - } - - /// - /// - /// - /// - /// - public List GetInventorySkeleton(UUID userId) - { - return SynchronousRestObjectPoster.BeginPostObject>( - "POST", m_ServerURI + "RootFolders/", userId.Guid); - } - - /// - /// Returns a list of all the active gestures in a user's inventory. - /// - /// - /// The of the user - /// - /// - /// A flat list of the gesture items. - /// - public List GetActiveGestures(UUID userId) - { - return SynchronousRestObjectPoster.BeginPostObject>( - "POST", m_ServerURI + "ActiveGestures/", userId.Guid); - } - - public InventoryCollection GetUserInventory(UUID userID) - { - return null; - } - - public void GetUserInventory(UUID userID, InventoryReceiptCallback callback) - { - } - - public InventoryFolderBase GetFolderForType(UUID userID, AssetType type) - { - return null; - } - - public InventoryCollection GetFolderContent(UUID userID, UUID folderID) - { - return null; - } - - public List 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 folderIDs) - { - 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 ownerID, List items) - { - return false; - } - - public bool DeleteItems(UUID owner, List itemIDs) - { - 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) - { - return null; - } - - public int GetAssetPermissions(UUID userID, UUID assetID) - { - return 0; - } - - } -} diff --git a/OpenSim/Services/Connectors/SimianGrid/SimianGridMaptileModule.cs b/OpenSim/Services/Connectors/SimianGrid/SimianGridMaptileModule.cs new file mode 100644 index 0000000000..93fdae38c1 --- /dev/null +++ b/OpenSim/Services/Connectors/SimianGrid/SimianGridMaptileModule.cs @@ -0,0 +1,262 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Net; +using System.IO; +using System.Timers; +using System.Drawing; +using System.Drawing.Imaging; + +using log4net; +using Mono.Addins; +using Nini.Config; +using OpenSim.Framework; +using OpenSim.Region.Framework.Interfaces; +using OpenSim.Region.Framework.Scenes; +using OpenMetaverse; +using OpenMetaverse.StructuredData; + +namespace OpenSim.Region.OptionalModules.Simian +{ + /// + /// + /// + /// + + [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "SimianGridMaptile")] + public class SimianGridMaptile : ISharedRegionModule + { + private static readonly ILog m_log = + LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private bool m_enabled = false; + private string m_serverUrl = String.Empty; + private Dictionary m_scenes = new Dictionary(); + + private int m_refreshtime = 0; + private int m_lastrefresh = 0; + private System.Timers.Timer m_refreshTimer = new System.Timers.Timer(); + + #region ISharedRegionModule + + public Type ReplaceableInterface { get { return null; } } + public string Name { get { return "SimianGridMaptile"; } } + public void RegionLoaded(Scene scene) { } + public void Close() { } + + /// + /// + /// + public void Initialise(IConfigSource source) + { + IConfig config = source.Configs["SimianGridMaptiles"]; + if (config == null) + return; + + if (! config.GetBoolean("Enabled", false)) + return; + + m_serverUrl = config.GetString("MaptileURL"); + if (String.IsNullOrEmpty(m_serverUrl)) + return; + + int refreshseconds = Convert.ToInt32(config.GetString("RefreshTime")); + if (refreshseconds <= 0) + return; + + m_refreshtime = refreshseconds * 1000; // convert from seconds to ms + m_log.InfoFormat("[SIMIAN MAPTILE] enabled with refresh timeout {0} and URL {1}", + m_refreshtime,m_serverUrl); + + m_enabled = true; + } + + /// + /// + /// + public void PostInitialise() + { + if (m_enabled) + { + m_refreshTimer.Enabled = true; + m_refreshTimer.AutoReset = true; + m_refreshTimer.Interval = 5 * 60 * 1000; // every 5 minutes + m_refreshTimer.Elapsed += new ElapsedEventHandler(HandleMaptileRefresh); + } + } + + + /// + /// + /// + public void AddRegion(Scene scene) + { + if (! m_enabled) + return; + + // Every shared region module has to maintain an indepedent list of + // currently running regions + lock (m_scenes) + m_scenes[scene.RegionInfo.RegionID] = scene; + } + + /// + /// + /// + public void RemoveRegion(Scene scene) + { + if (! m_enabled) + return; + + lock (m_scenes) + m_scenes.Remove(scene.RegionInfo.RegionID); + } + + #endregion ISharedRegionModule + + /// + /// + /// + private void HandleMaptileRefresh(object sender, EventArgs ea) + { + // this approach is a bit convoluted becase we want to wait for the + // first upload to happen on startup but after all the objects are + // loaded and initialized + if (m_lastrefresh > 0 && Util.EnvironmentTickCountSubtract(m_lastrefresh) < m_refreshtime) + return; + + m_log.DebugFormat("[SIMIAN MAPTILE] map refresh fired"); + lock (m_scenes) + { + foreach (IScene scene in m_scenes.Values) + { + try + { + UploadMapTile(scene); + } + catch (Exception ex) + { + m_log.WarnFormat("[SIMIAN MAPTILE] something bad happened {0}",ex.Message); + } + } + } + + m_lastrefresh = Util.EnvironmentTickCount(); + } + + /// + /// + /// + private void UploadMapTile(IScene scene) + { + m_log.DebugFormat("[SIMIAN MAPTILE]: upload maptile for {0}",scene.RegionInfo.RegionName); + + // Create a PNG map tile and upload it to the AddMapTile API + byte[] pngData = Utils.EmptyBytes; + IMapImageGenerator tileGenerator = scene.RequestModuleInterface(); + if (tileGenerator == null) + { + m_log.Warn("[SIMIAN MAPTILE]: Cannot upload PNG map tile without an ImageGenerator"); + return; + } + + using (Image mapTile = tileGenerator.CreateMapTile()) + { + using (MemoryStream stream = new MemoryStream()) + { + mapTile.Save(stream, ImageFormat.Png); + pngData = stream.ToArray(); + } + } + + List postParameters = new List() + { + new MultipartForm.Parameter("X", scene.RegionInfo.RegionLocX.ToString()), + new MultipartForm.Parameter("Y", scene.RegionInfo.RegionLocY.ToString()), + new MultipartForm.File("Tile", "tile.png", "image/png", pngData) + }; + + string errorMessage = null; + int tickstart = Util.EnvironmentTickCount(); + + // Make the remote storage request + try + { + HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(m_serverUrl); + request.Timeout = 20000; + request.ReadWriteTimeout = 5000; + + using (HttpWebResponse response = MultipartForm.Post(request, postParameters)) + { + using (Stream responseStream = response.GetResponseStream()) + { + string responseStr = responseStream.GetStreamString(); + OSD responseOSD = OSDParser.Deserialize(responseStr); + if (responseOSD.Type == OSDType.Map) + { + OSDMap responseMap = (OSDMap)responseOSD; + if (responseMap["Success"].AsBoolean()) + return; + + errorMessage = "Upload failed: " + responseMap["Message"].AsString(); + } + else + { + errorMessage = "Response format was invalid:\n" + responseStr; + } + } + } + } + catch (WebException we) + { + errorMessage = we.Message; + if (we.Status == WebExceptionStatus.ProtocolError) + { + HttpWebResponse webResponse = (HttpWebResponse)we.Response; + errorMessage = String.Format("[{0}] {1}", + webResponse.StatusCode,webResponse.StatusDescription); + } + } + catch (Exception ex) + { + errorMessage = ex.Message; + } + finally + { + // This just dumps a warning for any operation that takes more than 100 ms + int tickdiff = Util.EnvironmentTickCountSubtract(tickstart); + m_log.DebugFormat("[SIMIAN MAPTILE]: map tile uploaded in {0}ms",tickdiff); + } + + m_log.WarnFormat("[SIMIAN MAPTILE]: Failed to store {0} byte tile for {1}: {2}", + pngData.Length, scene.RegionInfo.RegionName, errorMessage); + } + } +} \ No newline at end of file diff --git a/OpenSim/Services/Connectors/Simulation/SimulationServiceConnector.cs b/OpenSim/Services/Connectors/Simulation/SimulationServiceConnector.cs index 2c8277ff40..1c31402af6 100644 --- a/OpenSim/Services/Connectors/Simulation/SimulationServiceConnector.cs +++ b/OpenSim/Services/Connectors/Simulation/SimulationServiceConnector.cs @@ -48,6 +48,9 @@ namespace OpenSim.Services.Connectors.Simulation { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + // we use this dictionary to track the pending updateagent requests, maps URI --> position update + private Dictionary m_updateAgentQueue = new Dictionary(); + //private GridRegion m_Region; public SimulationServiceConnector() @@ -76,9 +79,6 @@ namespace OpenSim.Services.Connectors.Simulation return "agent/"; } - /// - /// - /// public bool CreateAgent(GridRegion destination, AgentCircuitData aCircuit, uint flags, out string reason) { // m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: CreateAgent start"); @@ -106,6 +106,9 @@ namespace OpenSim.Services.Connectors.Simulation if (result["Success"].AsBoolean()) return true; + m_log.WarnFormat( + "[REMOTE SIMULATION CONNECTOR]: Failed to create agent {0} {1} at remote simulator {1}", + aCircuit.firstname, aCircuit.lastname, destination.RegionName); reason = result["Message"] != null ? result["Message"].AsString() : "error"; return false; } @@ -133,10 +136,56 @@ namespace OpenSim.Services.Connectors.Simulation /// public bool UpdateAgent(GridRegion destination, AgentPosition data) { - // we need a better throttle for these - // return false; + // The basic idea of this code is that the first thread that needs to + // send an update for a specific avatar becomes the worker for any subsequent + // requests until there are no more outstanding requests. Further, only send the most + // recent update; this *should* never be needed but some requests get + // slowed down and once that happens the problem with service end point + // limits kicks in and nothing proceeds + string uri = destination.ServerURI + AgentPath() + data.AgentID + "/"; + lock (m_updateAgentQueue) + { + if (m_updateAgentQueue.ContainsKey(uri)) + { + // Another thread is already handling + // updates for this simulator, just update + // the position and return, overwrites are + // not a problem since we only care about the + // last update anyway + m_updateAgentQueue[uri] = data; + return true; + } + + // Otherwise update the reference and start processing + m_updateAgentQueue[uri] = data; + } - return UpdateAgent(destination, (IAgentData)data); + AgentPosition pos = null; + while (true) + { + lock (m_updateAgentQueue) + { + // save the position + AgentPosition lastpos = pos; + + pos = m_updateAgentQueue[uri]; + + // this is true if no one put a new + // update in the map since the last + // one we processed, if thats the + // case then we are done + if (pos == lastpos) + { + m_updateAgentQueue.Remove(uri); + return true; + } + } + + UpdateAgent(destination,(IAgentData)pos); + } + + // unreachable +// return true; } /// @@ -207,8 +256,10 @@ namespace OpenSim.Services.Connectors.Simulation /// /// - public bool QueryAccess(GridRegion destination, UUID id, Vector3 position) + public bool QueryAccess(GridRegion destination, UUID id, Vector3 position, out string reason) { + reason = "Failed to contact destination"; + // m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: QueryAccess start, position={0}", position); IPEndPoint ext = destination.ExternalEndPoint; @@ -223,7 +274,11 @@ namespace OpenSim.Services.Connectors.Simulation try { OSDMap result = WebUtil.ServiceOSDRequest(uri, request, "QUERYACCESS", 10000); - bool success = result["Success"].AsBoolean(); + bool success = result["success"].AsBoolean(); + reason = result["reason"].AsString(); + + //m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: QueryAccess to {0} returned {1}", uri, success); + if (!success) { if (result.ContainsKey("Message")) @@ -234,8 +289,21 @@ namespace OpenSim.Services.Connectors.Simulation m_log.Info("[REMOTE SIMULATION CONNECTOR]: The above web util error was caused by a TP to a sim that doesn't support QUERYACCESS and can be ignored"); return true; } + + reason = result["Message"]; } + else + { + reason = "Communications failure"; + } + + return false; } + + OSDMap resp = (OSDMap)result["_Result"]; + success = resp["success"].AsBoolean(); + reason = resp["reason"].AsString(); + return success; } catch (Exception e) diff --git a/OpenSim/Services/GridService/GridService.cs b/OpenSim/Services/GridService/GridService.cs index 125c2be8cf..985d77b02d 100644 --- a/OpenSim/Services/GridService/GridService.cs +++ b/OpenSim/Services/GridService/GridService.cs @@ -271,6 +271,7 @@ namespace OpenSim.Services.GridService { List rinfos = new List(); RegionData region = m_Database.Get(regionID, scopeID); + if (region != null) { // Not really? Maybe? @@ -278,15 +279,24 @@ namespace OpenSim.Services.GridService region.posX + (int)Constants.RegionSize + 1, region.posY + (int)Constants.RegionSize + 1, scopeID); foreach (RegionData rdata in rdatas) + { if (rdata.RegionID != regionID) { int flags = Convert.ToInt32(rdata.Data["flags"]); if ((flags & (int)Data.RegionFlags.Hyperlink) == 0) // no hyperlinks as neighbours rinfos.Add(RegionData2RegionInfo(rdata)); } + } + m_log.DebugFormat("[GRID SERVICE]: region {0} has {1} neighbours", region.RegionName, rinfos.Count); } - m_log.DebugFormat("[GRID SERVICE]: region {0} has {1} neighours", region.RegionName, rinfos.Count); + else + { + m_log.WarnFormat( + "[GRID SERVICE]: GetNeighbours() called for scope {0}, region {1} but no such region found", + scopeID, regionID); + } + return rinfos; } diff --git a/OpenSim/Services/GridService/HypergridLinker.cs b/OpenSim/Services/GridService/HypergridLinker.cs index c02c81306f..a4aa44d581 100644 --- a/OpenSim/Services/GridService/HypergridLinker.cs +++ b/OpenSim/Services/GridService/HypergridLinker.cs @@ -121,7 +121,7 @@ namespace OpenSim.Services.GridService m_Check4096 = gridConfig.GetBoolean("Check4096", true); - m_MapTileDirectory = gridConfig.GetString("MapTileDirectory", string.Empty); + m_MapTileDirectory = gridConfig.GetString("MapTileDirectory", "maptiles"); m_GatekeeperConnector = new GatekeeperServiceConnector(m_AssetService); @@ -180,44 +180,18 @@ namespace OpenSim.Services.GridService public GridRegion TryLinkRegionToCoords(UUID scopeID, string mapName, int xloc, int yloc, UUID ownerID, out string reason) { reason = string.Empty; - string host = "127.0.0.1"; - string portstr; - string regionName = ""; uint port = 0; - string[] parts = mapName.Split(new char[] { ':' }); - if (parts.Length >= 1) + string[] parts = mapName.Split(new char[] {':'}); + string regionName = String.Empty; + if (parts.Length > 1) { - host = parts[0]; + regionName = mapName.Substring(parts[0].Length + 1); + regionName = regionName.Trim(new char[] {'"'}); } - if (parts.Length >= 2) - { - portstr = parts[1]; - //m_log.Debug("-- port = " + portstr); - if (!UInt32.TryParse(portstr, out port)) - regionName = parts[1]; - } - // always take the last one - if (parts.Length >= 3) - { - regionName = parts[2]; - } - - //// Sanity check. - //try - //{ - // Util.GetHostFromDNS(host); - //} - //catch - //{ - // reason = "Malformed hostname"; - // return null; - //} - GridRegion regInfo; - bool success = TryCreateLink(scopeID, xloc, yloc, regionName, port, host, ownerID, out regInfo, out reason); - if (success) + if (TryCreateLink(scopeID, xloc, yloc, regionName, 0, null, parts[0], ownerID, out regInfo, out reason)) { - regInfo.RegionName = mapName; + regInfo.RegionName = mapName; return regInfo; } @@ -313,9 +287,9 @@ namespace OpenSim.Services.GridService regInfo.RegionID = regionID; - if ( externalName == string.Empty ) + if (externalName == string.Empty) regInfo.RegionName = regInfo.ServerURI; - else + else regInfo.RegionName = externalName; m_log.Debug("[HYPERGRID LINKER]: naming linked region " + regInfo.RegionName); diff --git a/OpenSim/Services/HypergridService/UserAgentService.cs b/OpenSim/Services/HypergridService/UserAgentService.cs index 12dda48164..09e785fd39 100644 --- a/OpenSim/Services/HypergridService/UserAgentService.cs +++ b/OpenSim/Services/HypergridService/UserAgentService.cs @@ -253,7 +253,7 @@ namespace OpenSim.Services.HypergridService TravelingAgentInfo travel = m_TravelingAgents[sessionID]; - return travel.GridExternalName == thisGridExternalName; + return travel.GridExternalName.ToLower() == thisGridExternalName.ToLower(); } public bool VerifyClient(UUID sessionID, string reportedIP) diff --git a/OpenSim/Services/Interfaces/ISimulationService.cs b/OpenSim/Services/Interfaces/ISimulationService.cs index f08e1c0449..f2184fc816 100644 --- a/OpenSim/Services/Interfaces/ISimulationService.cs +++ b/OpenSim/Services/Interfaces/ISimulationService.cs @@ -40,6 +40,13 @@ namespace OpenSim.Services.Interfaces #region Agents + /// + /// Ask the simulator hosting the destination to create an agent on that region. + /// + /// + /// + /// + /// Reason message in the event of a failure. bool CreateAgent(GridRegion destination, AgentCircuitData aCircuit, uint flags, out string reason); /// @@ -60,7 +67,7 @@ namespace OpenSim.Services.Interfaces bool RetrieveAgent(GridRegion destination, UUID id, out IAgentData agent); - bool QueryAccess(GridRegion destination, UUID id, Vector3 position); + bool QueryAccess(GridRegion destination, UUID id, Vector3 position, out string reason); /// /// Message from receiving region to departing region, telling it got contacted by the client. diff --git a/OpenSim/Tests/Common/DoubleToleranceConstraint.cs b/OpenSim/Tests/Common/DoubleToleranceConstraint.cs index c397a6230b..b2f20571ae 100644 --- a/OpenSim/Tests/Common/DoubleToleranceConstraint.cs +++ b/OpenSim/Tests/Common/DoubleToleranceConstraint.cs @@ -27,6 +27,7 @@ using System; using NUnit.Framework; +using NUnit.Framework.Constraints; namespace OpenSim.Tests.Common { diff --git a/OpenSim/Tests/Common/Mock/TestClient.cs b/OpenSim/Tests/Common/Mock/TestClient.cs index 147571bfa4..7b7d66e9f4 100644 --- a/OpenSim/Tests/Common/Mock/TestClient.cs +++ b/OpenSim/Tests/Common/Mock/TestClient.cs @@ -560,8 +560,11 @@ namespace OpenSim.Tests.Common.Mock agentData.lastname = m_lastName; ICapabilitiesModule capsModule = m_scene.RequestModuleInterface(); - agentData.CapsPath = capsModule.GetCapsPath(m_agentId); - agentData.ChildrenCapSeeds = new Dictionary(capsModule.GetChildrenSeeds(m_agentId)); + if (capsModule != null) + { + agentData.CapsPath = capsModule.GetCapsPath(m_agentId); + agentData.ChildrenCapSeeds = new Dictionary(capsModule.GetChildrenSeeds(m_agentId)); + } return agentData; } diff --git a/OpenSim/Tests/Common/Setup/AssetHelpers.cs b/OpenSim/Tests/Common/Setup/AssetHelpers.cs index 8647cfed51..ff4423f7ab 100644 --- a/OpenSim/Tests/Common/Setup/AssetHelpers.cs +++ b/OpenSim/Tests/Common/Setup/AssetHelpers.cs @@ -68,7 +68,7 @@ namespace OpenSim.Tests.Common return CreateAsset( assetUuid, AssetType.Object, - Encoding.ASCII.GetBytes(SceneObjectSerializer.ToXml2Format(sog)), + Encoding.ASCII.GetBytes(SceneObjectSerializer.ToOriginalXmlFormat(sog)), sog.OwnerID); } diff --git a/OpenSim/Tests/Common/Setup/SceneSetupHelpers.cs b/OpenSim/Tests/Common/Setup/SceneSetupHelpers.cs index 8b1649635c..aa4b285981 100644 --- a/OpenSim/Tests/Common/Setup/SceneSetupHelpers.cs +++ b/OpenSim/Tests/Common/Setup/SceneSetupHelpers.cs @@ -57,21 +57,12 @@ namespace OpenSim.Tests.Common.Setup /// public class SceneSetupHelpers { - // These static variables in order to allow regions to be linked by shared modules and same - // CommunicationsManager. - private static ISharedRegionModule m_assetService = null; -// private static ISharedRegionModule m_authenticationService = null; - private static ISharedRegionModule m_inventoryService = null; - private static ISharedRegionModule m_gridService = null; - private static ISharedRegionModule m_userAccountService = null; - private static ISharedRegionModule m_presenceService = null; - /// /// Set up a test scene /// - /// + /// /// Automatically starts service threads, as would the normal runtime. - /// + /// /// public static TestScene SetupScene() { @@ -86,24 +77,9 @@ namespace OpenSim.Tests.Common.Setup /// public static TestScene SetupScene(String realServices) { - return SetupScene( - "Unit test region", UUID.Random(), 1000, 1000, realServices); + return SetupScene("Unit test region", UUID.Random(), 1000, 1000, realServices); } - // REFACTORING PROBLEM. No idea what the difference is with the previous one - ///// - ///// Set up a test scene - ///// - ///// - ///// Starts real inventory and asset services, as opposed to mock ones, if true - ///// This should be the same if simulating two scenes within a standalone - ///// - //public static TestScene SetupScene(String realServices) - //{ - // return SetupScene( - // "Unit test region", UUID.Random(), 1000, 1000, ""); - //} - /// /// Set up a test scene /// @@ -115,7 +91,7 @@ namespace OpenSim.Tests.Common.Setup /// public static TestScene SetupScene(string name, UUID id, uint x, uint y) { - return SetupScene(name, id, x, y,""); + return SetupScene(name, id, x, y, ""); } /// @@ -132,24 +108,11 @@ namespace OpenSim.Tests.Common.Setup public static TestScene SetupScene( string name, UUID id, uint x, uint y, String realServices) { - bool newScene = false; - Console.WriteLine("Setting up test scene {0}", name); - // REFACTORING PROBLEM! - //// If cm is the same as our last commsManager used, this means the tester wants to link - //// regions. In this case, don't use the sameshared region modules and dont initialize them again. - //// Also, no need to start another MainServer and MainConsole instance. - //if (cm == null || cm != commsManager) - //{ - // System.Console.WriteLine("Starting a brand new scene"); - // newScene = true; - MainConsole.Instance = new MockConsole("TEST PROMPT"); - // MainServer.Instance = new BaseHttpServer(980); - // commsManager = cm; - //} - // We must set up a console otherwise setup of some modules may fail + MainConsole.Instance = new MockConsole("TEST PROMPT"); + RegionInfo regInfo = new RegionInfo(x, y, new IPEndPoint(IPAddress.Loopback, 9000), "127.0.0.1"); regInfo.RegionName = name; regInfo.RegionID = id; @@ -164,55 +127,26 @@ namespace OpenSim.Tests.Common.Setup TestScene testScene = new TestScene( regInfo, acm, scs, simDataService, estateDataService, null, false, false, false, configSource, null); - INonSharedRegionModule capsModule = new CapabilitiesModule(); - capsModule.Initialise(new IniConfigSource()); - testScene.AddRegionModule(capsModule.Name, capsModule); - capsModule.AddRegion(testScene); - IRegionModule godsModule = new GodsModule(); godsModule.Initialise(testScene, new IniConfigSource()); testScene.AddModule(godsModule.Name, godsModule); realServices = realServices.ToLower(); - // IConfigSource config = new IniConfigSource(); - // If we have a brand new scene, need to initialize shared region modules - if ((m_assetService == null && m_inventoryService == null) || newScene) - { - if (realServices.Contains("asset")) - StartAssetService(testScene, true); - else - StartAssetService(testScene, false); + LocalAssetServicesConnector assetService = StartAssetService(testScene, realServices.Contains("asset")); - // For now, always started a 'real' authentication service - StartAuthenticationService(testScene, true); + // For now, always started a 'real' authentication service + StartAuthenticationService(testScene, true); - if (realServices.Contains("inventory")) - StartInventoryService(testScene, true); - else - StartInventoryService(testScene, false); + LocalInventoryServicesConnector inventoryService = StartInventoryService(testScene, realServices.Contains("inventory")); + StartGridService(testScene, true); + LocalUserAccountServicesConnector userAccountService = StartUserAccountService(testScene); + LocalPresenceServicesConnector presenceService = StartPresenceService(testScene); - StartGridService(testScene, true); - StartUserAccountService(testScene); - StartPresenceService(testScene); - } - // If not, make sure the shared module gets references to this new scene - else - { - m_assetService.AddRegion(testScene); - m_assetService.RegionLoaded(testScene); - m_inventoryService.AddRegion(testScene); - m_inventoryService.RegionLoaded(testScene); - m_userAccountService.AddRegion(testScene); - m_userAccountService.RegionLoaded(testScene); - m_presenceService.AddRegion(testScene); - m_presenceService.RegionLoaded(testScene); - - } - - m_inventoryService.PostInitialise(); - m_assetService.PostInitialise(); - m_userAccountService.PostInitialise(); - m_presenceService.PostInitialise(); + inventoryService.PostInitialise(); + assetService.PostInitialise(); + userAccountService.PostInitialise(); + presenceService.PostInitialise(); + testScene.RegionInfo.EstateSettings.EstateOwner = UUID.Random(); testScene.SetModuleInterfaces(); @@ -224,24 +158,15 @@ namespace OpenSim.Tests.Common.Setup testScene.PhysicsScene = physicsPluginManager.GetPhysicsScene("basicphysics", "ZeroMesher", new IniConfigSource(), "test"); - // It's really not a good idea to use static variables as they carry over between tests, leading to - // problems that are extremely hard to debug. Really, these static fields need to be eliminated - - // tests using multiple regions that need to share modules need to find another solution. - m_assetService = null; - m_inventoryService = null; - m_gridService = null; - m_userAccountService = null; - m_presenceService = null; - testScene.RegionInfo.EstateSettings = new EstateSettings(); testScene.LoginsDisabled = false; return testScene; } - private static void StartAssetService(Scene testScene, bool real) + private static LocalAssetServicesConnector StartAssetService(Scene testScene, bool real) { - ISharedRegionModule assetService = new LocalAssetServicesConnector(); + LocalAssetServicesConnector assetService = new LocalAssetServicesConnector(); IConfigSource config = new IniConfigSource(); config.AddConfig("Modules"); config.AddConfig("AssetService"); @@ -255,7 +180,8 @@ namespace OpenSim.Tests.Common.Setup assetService.AddRegion(testScene); assetService.RegionLoaded(testScene); testScene.AddRegionModule(assetService.Name, assetService); - m_assetService = assetService; + + return assetService; } private static void StartAuthenticationService(Scene testScene, bool real) @@ -279,9 +205,9 @@ namespace OpenSim.Tests.Common.Setup //m_authenticationService = service; } - private static void StartInventoryService(Scene testScene, bool real) + private static LocalInventoryServicesConnector StartInventoryService(Scene testScene, bool real) { - ISharedRegionModule inventoryService = new LocalInventoryServicesConnector(); + LocalInventoryServicesConnector inventoryService = new LocalInventoryServicesConnector(); IConfigSource config = new IniConfigSource(); config.AddConfig("Modules"); config.AddConfig("InventoryService"); @@ -301,10 +227,11 @@ namespace OpenSim.Tests.Common.Setup inventoryService.AddRegion(testScene); inventoryService.RegionLoaded(testScene); testScene.AddRegionModule(inventoryService.Name, inventoryService); - m_inventoryService = inventoryService; + + return inventoryService; } - private static void StartGridService(Scene testScene, bool real) + private static LocalGridServicesConnector StartGridService(Scene testScene, bool real) { IConfigSource config = new IniConfigSource(); config.AddConfig("Modules"); @@ -313,24 +240,25 @@ namespace OpenSim.Tests.Common.Setup config.Configs["GridService"].Set("StorageProvider", "OpenSim.Data.Null.dll:NullRegionData"); if (real) config.Configs["GridService"].Set("LocalServiceModule", "OpenSim.Services.GridService.dll:GridService"); - if (m_gridService == null) - { - ISharedRegionModule gridService = new LocalGridServicesConnector(); - gridService.Initialise(config); - m_gridService = gridService; - } + + LocalGridServicesConnector gridService = new LocalGridServicesConnector(); + gridService.Initialise(config); + //else // config.Configs["GridService"].Set("LocalServiceModule", "OpenSim.Tests.Common.dll:TestGridService"); - m_gridService.AddRegion(testScene); - m_gridService.RegionLoaded(testScene); + gridService.AddRegion(testScene); + gridService.RegionLoaded(testScene); //testScene.AddRegionModule(m_gridService.Name, m_gridService); + + return gridService; } /// /// Start a user account service /// /// - private static void StartUserAccountService(Scene testScene) + /// + private static LocalUserAccountServicesConnector StartUserAccountService(Scene testScene) { IConfigSource config = new IniConfigSource(); config.AddConfig("Modules"); @@ -340,23 +268,21 @@ namespace OpenSim.Tests.Common.Setup config.Configs["UserAccountService"].Set( "LocalServiceModule", "OpenSim.Services.UserAccountService.dll:UserAccountService"); - if (m_userAccountService == null) - { - ISharedRegionModule userAccountService = new LocalUserAccountServicesConnector(); - userAccountService.Initialise(config); - m_userAccountService = userAccountService; - } + LocalUserAccountServicesConnector userAccountService = new LocalUserAccountServicesConnector(); + userAccountService.Initialise(config); - m_userAccountService.AddRegion(testScene); - m_userAccountService.RegionLoaded(testScene); - testScene.AddRegionModule(m_userAccountService.Name, m_userAccountService); + userAccountService.AddRegion(testScene); + userAccountService.RegionLoaded(testScene); + testScene.AddRegionModule(userAccountService.Name, userAccountService); + + return userAccountService; } /// /// Start a presence service /// /// - private static void StartPresenceService(Scene testScene) + private static LocalPresenceServicesConnector StartPresenceService(Scene testScene) { IConfigSource config = new IniConfigSource(); config.AddConfig("Modules"); @@ -366,16 +292,14 @@ namespace OpenSim.Tests.Common.Setup config.Configs["PresenceService"].Set( "LocalServiceModule", "OpenSim.Services.PresenceService.dll:PresenceService"); - if (m_presenceService == null) - { - ISharedRegionModule presenceService = new LocalPresenceServicesConnector(); - presenceService.Initialise(config); - m_presenceService = presenceService; - } + LocalPresenceServicesConnector presenceService = new LocalPresenceServicesConnector(); + presenceService.Initialise(config); - m_presenceService.AddRegion(testScene); - m_presenceService.RegionLoaded(testScene); - testScene.AddRegionModule(m_presenceService.Name, m_presenceService); + presenceService.AddRegion(testScene); + presenceService.RegionLoaded(testScene); + testScene.AddRegionModule(presenceService.Name, presenceService); + + return presenceService; } /// @@ -472,7 +396,7 @@ namespace OpenSim.Tests.Common.Setup /// /// Add a root agent. /// - /// + /// /// This function /// /// 1) Tells the scene that an agent is coming. Normally, the login service (local if standalone, from the @@ -483,7 +407,7 @@ namespace OpenSim.Tests.Common.Setup /// /// This function performs actions equivalent with notifying the scene that an agent is /// coming and then actually connecting the agent to the scene. The one step missed out is the very first - /// + /// /// /// /// @@ -504,12 +428,10 @@ namespace OpenSim.Tests.Common.Setup TestClient client = new TestClient(agentData, scene); scene.AddNewClient(client); - // Stage 3: Invoke agent crossing, which converts the child agent into a root agent (with appearance, - // inventory, etc.) - //scene.AgentCrossing(agentData.AgentID, new Vector3(90, 90, 90), false); OBSOLETE - + // Stage 3: Complete the entrance into the region. This converts the child agent into a root agent. ScenePresence scp = scene.GetScenePresence(agentData.AgentID); - scp.MakeRootAgent(new Vector3(90, 90, 90), true); + scp.CompleteMovement(client); + //scp.MakeRootAgent(new Vector3(90, 90, 90), true); return client; } @@ -543,24 +465,5 @@ namespace OpenSim.Tests.Common.Setup return part; } - - /// - /// Delete a scene object asynchronously - /// - /// - /// - /// - /// - /// - public static void DeleteSceneObjectAsync( - TestScene scene, SceneObjectPart part, DeRezAction action, UUID destinationId, IClientAPI client) - { - // Turn off the timer on the async sog deleter - we'll crank it by hand within a unit test - AsyncSceneObjectGroupDeleter sogd = scene.SceneObjectGroupDeleter; - sogd.Enabled = false; - - scene.DeRezObjects(client, new List() { part.LocalId }, UUID.Zero, action, destinationId); - sogd.InventoryDeQueueAndDelete(); - } } } diff --git a/OpenSim/Tests/Common/TestHelper.cs b/OpenSim/Tests/Common/TestHelper.cs index 9d530635f3..1722e59864 100644 --- a/OpenSim/Tests/Common/TestHelper.cs +++ b/OpenSim/Tests/Common/TestHelper.cs @@ -27,11 +27,10 @@ using System; using System.Diagnostics; +using NUnit.Framework; namespace OpenSim.Tests.Common { - public delegate void TestDelegate(); - public class TestHelper { public static bool AssertThisDelegateCausesArgumentException(TestDelegate d) diff --git a/OpenSim/Tests/Common/VectorToleranceConstraint.cs b/OpenSim/Tests/Common/VectorToleranceConstraint.cs index 118cc707f8..2fa20edec9 100644 --- a/OpenSim/Tests/Common/VectorToleranceConstraint.cs +++ b/OpenSim/Tests/Common/VectorToleranceConstraint.cs @@ -28,6 +28,7 @@ using System; using OpenMetaverse; using NUnit.Framework; +using NUnit.Framework.Constraints; namespace OpenSim.Tests.Common { diff --git a/TESTING.txt b/TESTING.txt index e0a7748e6f..54fc976e95 100644 --- a/TESTING.txt +++ b/TESTING.txt @@ -2,23 +2,14 @@ == Running Tests == -On Linux: +On Linux you will need to have NUnit installed (http://www.nunit.org). +This is commonly available in distribution package repositories. + +When this is installed, run the command > nant test -This will print out to the console the test state. - -On Windows: Please see the TESTING ON WINDOWS section below. - - -Also, every checkin will run tests that are kicked off by bamboo. -Results are posted here: http://www.opensimulator.org:8085/ as well as -to #opensim-dev IRC channel. - -== Writing Tests == - -Tests are written to run under NUnit. For more information on NUnit -please see: http://www.nunit.org/index.php +Please see the TESTING ON WINDOWS section below for Windows instructions. == Adding Tests == @@ -32,70 +23,15 @@ that if you are writing tests they end up in a "Tests" sub-directory of the directory where the code you are testing resides. If you have added a new test assembly that hasn't existed before you -must list it in both ".nant/local.include" and ".nant/bamboo.build" +must list it in both ".nant/local.include" for it to be accessible to Linux users and to the continuous integration system. - -=== The Gory Details === -The following is the original document which started off this -document. It should probably be better integrated with the new info. - -==UPDATE== - -The text immediately following is an update to the testing documentation. The -update is written on 2008.08.30 and is copied from an email to the opensim-dev -mailing list[1]. The information below the update, beginning with the section -titled TESTING, is still relevant, so please read this document in its -entirety. - -Mike Mazur - -[1] https://lists.berlios.de/pipermail/opensim-dev/2008-August/002695.html - -""" -The tests are contained in certain DLLs. At the time of writing, these DLLs -have tests in them: - -OpenSim.Region.ScriptEngine.Common.Tests.dll -OpenSim.Region.ScriptEngine.Shared.CodeTools.Tests.dll -OpenSim.Region.ScriptEngine.Shared.Tests.dll -OpenSim.Framework.Tests.dll OpenSim.Region.CoreModules.dll -OpenSim.Region.Physics.OdePlugin.dll[2] - -The console command used to run the tests is `nunit-console` (or -`nunit-console2` on some systems). This command takes a listing of DLLs to -inspect for tests. - -Currently Bamboo's[3] build file (.nant/bamboo.build) lists only those DLLs -for nunit-console to use. However it would be equally correct to simply pass -in all DLLs in bin/; those without tests are just skipped. - -The nunit-console command generates a file TestResults.txt by default. This is -an XML file containing a listing of all DLLs inspected, tests executed, -successes, failures, etc. If nunit-console is passed in all DLLs in bin/, this -file bloats with lots of entries like this: - - - - - - - - -Therefore it makes more sense to me to specify the DLLs when running -nunit-console. - -[2] Note that OpenSim.Region.Physics.OdePlugin.dll is in bin/Physics/ and -needs to be first copied to bin/ before nunit-console is executed. -[3] http://opensimulator.org:8085/ -""" - ==TESTING ON WINDOWS== To use nunit testing on opensim code, you have a variety of methods. The easiast methods involve using IDE capabilities to test code. Using -VS2005/2008 I recommend using the testing capabilities of Resarper(commercial) +VS2005/2008 I recommend using the testing capabilities of Resharper(commercial) or TestDriven.Net(free). Both will recognize nunit tests within your application and allow you to test them individually, or all at once, etc. You will also be able to step into debug mode into a test through these add-ins @@ -133,6 +69,3 @@ Example nunit-console2 OpenSim.Framework.Tests.dll (on linux) nunit-console OpenSim.Framework.Tests.dll (on windows) - -For more information on testing contact the autor of this testing readme: Daedius Moskvitch ( daedius @@@@ daedius com) - diff --git a/bin/HttpServer_OpenSim.dll b/bin/HttpServer_OpenSim.dll index d7503a0915..95ea5dd7ff 100644 Binary files a/bin/HttpServer_OpenSim.dll and b/bin/HttpServer_OpenSim.dll differ diff --git a/bin/HttpServer_OpenSim.pdb b/bin/HttpServer_OpenSim.pdb index 4151588c66..b6b77f75eb 100644 Binary files a/bin/HttpServer_OpenSim.pdb and b/bin/HttpServer_OpenSim.pdb differ diff --git a/bin/MySql.Data.dll b/bin/MySql.Data.dll index c28c618f23..992aa5621c 100644 Binary files a/bin/MySql.Data.dll and b/bin/MySql.Data.dll differ diff --git a/bin/OpenSim.ini.example b/bin/OpenSim.ini.example index 7245bee2e3..5bac56e66a 100644 --- a/bin/OpenSim.ini.example +++ b/bin/OpenSim.ini.example @@ -306,6 +306,9 @@ [ODEPhysicsSettings] ;# {mesh_sculpted_prim} {[Startup]physics:OpenDynamicsEngine} {Mesh sculpties so they collide as they look?} {true false} true ;; Do we want to mesh sculpted prim to collide like they look? + ;; If you are seeing sculpt texture decode problems + ;; (messages such as "Decoded image with unhandled number of components: 0 shortly followed by a physcs exception") + ;; then you might want to try setting this to false. ; mesh_sculpted_prim = true ;# {use_NINJA_physics_joints} {[Startup]physics:OpenDynamicsEngine} {Use jointed (NINJA) physics?} {true false} false diff --git a/bin/OpenSimDefaults.ini b/bin/OpenSimDefaults.ini index c7e550b34e..0337c77663 100644 --- a/bin/OpenSimDefaults.ini +++ b/bin/OpenSimDefaults.ini @@ -94,6 +94,13 @@ ; Warning! Don't use this with regions that have existing content!, This will likely break them CombineContiguousRegions = false + ; Extend the region's draw distance; 255m is the default which includes + ; one neighbor on each side of the current region, 767m would go three + ; neighbors on each side for a total of 49 regions in view. Warning, unless + ; all the regions have the same drawdistance, you will end up with strange + ; effects because the agents that get closed may be inconsistent. + ; DefaultDrawDistance = 255.0 + ; If you have only one region in an instance, or to avoid the many bugs ; that you can trigger in modules by restarting a region, set this to ; true to make the entire instance exit instead of restarting the region. diff --git a/bin/Robust.HG.ini.example b/bin/Robust.HG.ini.example index 9adf1ac5ff..f12a1434ef 100644 --- a/bin/Robust.HG.ini.example +++ b/bin/Robust.HG.ini.example @@ -72,7 +72,7 @@ ServiceConnectors = "8003/OpenSim.Server.Handlers.dll:AssetServiceConnector,8003 AssetService = "OpenSim.Services.AssetService.dll:AssetService" ;; Directory for map tile images of linked regions - ; MapTileDirectory = "./" + ; MapTileDirectory = "./maptiles" ;; Next, we can specify properties of regions, including default and fallback regions ;; The syntax is: Region_ = "" diff --git a/bin/assets/TexturesAssetSet/TexturesAssetSet.xml b/bin/assets/TexturesAssetSet/TexturesAssetSet.xml index 5484ee237f..3af9c994d1 100644 --- a/bin/assets/TexturesAssetSet/TexturesAssetSet.xml +++ b/bin/assets/TexturesAssetSet/TexturesAssetSet.xml @@ -413,6 +413,15 @@ + + + +
+ + + + +
diff --git a/bin/config-include/GridCommon.ini.example b/bin/config-include/GridCommon.ini.example index 761e5eb1dd..4dc0e53342 100644 --- a/bin/config-include/GridCommon.ini.example +++ b/bin/config-include/GridCommon.ini.example @@ -43,7 +43,7 @@ ;AllowHypergridMapSearch = true ;; Directory for map tile images of linked regions - ; MapTileDirectory = "./" + ; MapTileDirectory = "./maptiles" [AvatarService] ; @@ -88,6 +88,10 @@ ; accessible from other grids ; ProfileServerURI = "http://mygridserver.com:8002/user" + ;; If you want to protect your assets from being copied by foreign visitors + ;; uncomment the next line. You may want to do this on sims that have licensed content. + ; OutboundPermission = False + [Modules] ;; Choose 0 or 1 cache modules, and the corresponding config file, if it exists. diff --git a/bin/config-include/HyperSimianGrid.ini b/bin/config-include/HyperSimianGrid.ini index 0b011168d8..89d6be79e3 100644 --- a/bin/config-include/HyperSimianGrid.ini +++ b/bin/config-include/HyperSimianGrid.ini @@ -82,3 +82,14 @@ [Profiles] Module = "SimianProfiles" + +[HGInventoryAccessModule] + ; + ; === HG ONLY === + ; Change this to your profile server + ; accessible from other grids + ; + ProfileServerURI = "http://mygridserver.com:8002/user" + ;; If you want to protect your assets from being copied by foreign visitors + ;; uncomment the next line. You may want to do this on sims that have licensed content. + ; OutboundPermission = False diff --git a/bin/config-include/StandaloneCommon.ini.example b/bin/config-include/StandaloneCommon.ini.example index 4956bc34fa..816e9a6f10 100644 --- a/bin/config-include/StandaloneCommon.ini.example +++ b/bin/config-include/StandaloneCommon.ini.example @@ -33,6 +33,10 @@ [HGInventoryAccessModule] ProfileServerURI = "http://127.0.0.1:9000/profiles" + ;; If you want to protect your assets from being copied by foreign visitors + ;; uncomment the next line. You may want to do this on sims that have licensed content. + ; OutboundPermission = False + [Modules] ;; Choose 0 or 1 cache modules, and the corresponding config file, if it exists. @@ -66,7 +70,7 @@ ; Check4096 = true ;; Directory for map tile images of remote regions - ; MapTileDirectory = "./" + ; MapTileDirectory = "./maptiles" ;; Next, we can specify properties of regions, including default and fallback regions ;; The syntax is: Region_ = "" diff --git a/bin/libsqlite3.so.0 b/bin/libsqlite3.so.0 new file mode 100755 index 0000000000..0512d8a3c0 Binary files /dev/null and b/bin/libsqlite3.so.0 differ diff --git a/bin/libsqlite3.txt b/bin/libsqlite3.txt new file mode 100644 index 0000000000..8ef66bdf06 --- /dev/null +++ b/bin/libsqlite3.txt @@ -0,0 +1 @@ +libsqlite version: 3.7.5 diff --git a/bin/nunit.framework.dll b/bin/nunit.framework.dll index d68d9f20c5..875e098420 100644 Binary files a/bin/nunit.framework.dll and b/bin/nunit.framework.dll differ diff --git a/bin/sqlite-3.6.21.so b/bin/sqlite-3.6.21.so deleted file mode 100644 index 2a8f38ba23..0000000000 Binary files a/bin/sqlite-3.6.21.so and /dev/null differ diff --git a/bin/sqlite3.dll b/bin/sqlite3.dll index 558a015a7f..f29dc625fa 100755 Binary files a/bin/sqlite3.dll and b/bin/sqlite3.dll differ diff --git a/prebuild.xml b/prebuild.xml index bf6c1cc1da..fc94e75ad5 100644 --- a/prebuild.xml +++ b/prebuild.xml @@ -2959,6 +2959,7 @@ +