diff --git a/CONTRIBUTORS.txt b/CONTRIBUTORS.txt index e1de751496..b1c34525a1 100644 --- a/CONTRIBUTORS.txt +++ b/CONTRIBUTORS.txt @@ -146,6 +146,7 @@ what it is today. * Stefan_Boom / stoehr * Strawberry Fride * Talun +* TechplexEngineer (Blake Bourque) * TBG Renfold * tglion * tlaukkan/Tommil (Tommi S. E. Laukkanen, Bubble Cloud) diff --git a/OpenSim/Capabilities/LLSDEnvironmentSettings.cs b/OpenSim/Capabilities/LLSDEnvironmentSettings.cs new file mode 100644 index 0000000000..39019af22c --- /dev/null +++ b/OpenSim/Capabilities/LLSDEnvironmentSettings.cs @@ -0,0 +1,68 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using OpenMetaverse; + +namespace OpenSim.Framework.Capabilities +{ + [OSDMap] + public class LLSDEnvironmentRequest + { + public UUID messageID; + public UUID regionID; + } + + [OSDMap] + public class LLSDEnvironmentSetResponse + { + public UUID regionID; + public UUID messageID; + public Boolean success; + public String fail_reason; + } + + public class EnvironmentSettings + { + /// + /// generates a empty llsd settings response for viewer + /// + /// the message UUID + /// the region UUID + public static string EmptySettings(UUID messageID, UUID regionID) + { + OSDArray arr = new OSDArray(); + LLSDEnvironmentRequest msg = new LLSDEnvironmentRequest(); + msg.messageID = messageID; + msg.regionID = regionID; + arr.Array.Add(msg); + return LLSDHelpers.SerialiseLLSDReply(arr); + } + } + +} diff --git a/OpenSim/Data/MSSQL/MSSQLSimulationData.cs b/OpenSim/Data/MSSQL/MSSQLSimulationData.cs index d9dfe864ec..3f29f5b36d 100644 --- a/OpenSim/Data/MSSQL/MSSQLSimulationData.cs +++ b/OpenSim/Data/MSSQL/MSSQLSimulationData.cs @@ -1181,6 +1181,72 @@ VALUES // } #endregion } + + #region Environment Settings + public string LoadRegionEnvironmentSettings(UUID regionUUID) + { + string sql = "select * from [regionenvironment] where region_id = @region_id"; + using (SqlConnection conn = new SqlConnection(m_connectionString)) + using (SqlCommand cmd = new SqlCommand(sql, conn)) + { + cmd.Parameters.Add(_Database.CreateParameter("@region_id", regionUUID)); + conn.Open(); + using (SqlDataReader result = cmd.ExecuteReader()) + { + if (!result.Read()) + { + return String.Empty; + } + else + { + return Convert.ToString(result["llsd_settings"]); + } + } + } + } + + public void StoreRegionEnvironmentSettings(UUID regionUUID, string settings) + { + { + string sql = "DELETE FROM [regionenvironment] WHERE region_id = @region_id"; + using (SqlConnection conn = new SqlConnection(m_connectionString)) + + using (SqlCommand cmd = new SqlCommand(sql, conn)) + { + cmd.Parameters.Add(_Database.CreateParameter("@region_id", regionUUID)); + conn.Open(); + cmd.ExecuteNonQuery(); + } + + sql = "INSERT INTO [regionenvironment] (region_id, llsd_settings) VALUES (@region_id, @llsd_settings)"; + + using (SqlConnection conn = new SqlConnection(m_connectionString)) + + using (SqlCommand cmd = new SqlCommand(sql, conn)) + { + cmd.Parameters.Add(_Database.CreateParameter("@region_id", regionUUID)); + cmd.Parameters.Add(_Database.CreateParameter("@llsd_settings", settings)); + + conn.Open(); + cmd.ExecuteNonQuery(); + } + } + } + + public void RemoveRegionEnvironmentSettings(UUID regionUUID) + { + string sql = "delete from [regionenvironment] where region_id = @region_id"; + using (SqlConnection conn = new SqlConnection(m_connectionString)) + using (SqlCommand cmd = new SqlCommand(sql, conn)) + { + cmd.Parameters.Add(_Database.CreateParameter("@region_id", regionUUID)); + + conn.Open(); + cmd.ExecuteNonQuery(); + } + } + #endregion + /// /// Loads the settings of a region. /// diff --git a/OpenSim/Data/MSSQL/Resources/RegionStore.migrations b/OpenSim/Data/MSSQL/Resources/RegionStore.migrations index d6a3be9282..350e548a0a 100644 --- a/OpenSim/Data/MSSQL/Resources/RegionStore.migrations +++ b/OpenSim/Data/MSSQL/Resources/RegionStore.migrations @@ -1134,3 +1134,17 @@ ALTER TABLE landaccesslist ADD Expires integer NOT NULL DEFAULT 0; COMMIT +:VERSION 37 #---------------- Environment Settings + +BEGIN TRANSACTION + +CREATE TABLE [dbo].[regionenvironment]( + [region_id] [uniqueidentifier] NOT NULL, + [llsd_settings] [varchar](max) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, + PRIMARY KEY CLUSTERED +( + [region_id] ASC +)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY] +) ON [PRIMARY] + +COMMIT diff --git a/OpenSim/Data/MySQL/MySQLSimulationData.cs b/OpenSim/Data/MySQL/MySQLSimulationData.cs index 9467124bc1..faf749f325 100644 --- a/OpenSim/Data/MySQL/MySQLSimulationData.cs +++ b/OpenSim/Data/MySQL/MySQLSimulationData.cs @@ -994,6 +994,68 @@ namespace OpenSim.Data.MySQL } } + #region RegionEnvironmentSettings + public string LoadRegionEnvironmentSettings(UUID regionUUID) + { + using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) + { + dbcon.Open(); + + string command = "select * from `regionenvironment` where region_id = ?region_id"; + + using (MySqlCommand cmd = new MySqlCommand(command)) + { + cmd.Connection = dbcon; + + cmd.Parameters.AddWithValue("?region_id", regionUUID.ToString()); + + IDataReader result = ExecuteReader(cmd); + if (!result.Read()) + { + return String.Empty; + } + else + { + return Convert.ToString(result["llsd_settings"]); + } + } + } + } + + public void StoreRegionEnvironmentSettings(UUID regionUUID, string settings) + { + using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) + { + dbcon.Open(); + + using (MySqlCommand cmd = dbcon.CreateCommand()) + { + cmd.CommandText = "REPLACE INTO `regionenvironment` (`region_id`, `llsd_settings`) VALUES (?region_id, ?llsd_settings)"; + + cmd.Parameters.AddWithValue("region_id", regionUUID); + cmd.Parameters.AddWithValue("llsd_settings", settings); + + ExecuteNonQuery(cmd); + } + } + } + + public void RemoveRegionEnvironmentSettings(UUID regionUUID) + { + using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) + { + dbcon.Open(); + + using (MySqlCommand cmd = dbcon.CreateCommand()) + { + cmd.CommandText = "delete from `regionenvironment` where region_id = ?region_id"; + cmd.Parameters.AddWithValue("?region_id", regionUUID.ToString()); + ExecuteNonQuery(cmd); + } + } + } + #endregion + public virtual void StoreRegionSettings(RegionSettings rs) { lock (m_dbLock) diff --git a/OpenSim/Data/MySQL/Resources/RegionStore.migrations b/OpenSim/Data/MySQL/Resources/RegionStore.migrations index ef99ef8d7c..db0d0ec399 100644 --- a/OpenSim/Data/MySQL/Resources/RegionStore.migrations +++ b/OpenSim/Data/MySQL/Resources/RegionStore.migrations @@ -883,3 +883,15 @@ ALTER TABLE `regionsettings` MODIFY COLUMN `TelehubObject` VARCHAR(36) NOT NULL COMMIT; +:VERSION 44 #--------------------- Environment Settings + +BEGIN; + +CREATE TABLE `regionenvironment` ( + `region_id` varchar(36) NOT NULL, + `llsd_settings` TEXT NOT NULL, + PRIMARY KEY (`region_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +COMMIT; + diff --git a/OpenSim/Data/Null/NullSimulationData.cs b/OpenSim/Data/Null/NullSimulationData.cs index b7889767da..8f2314ff1f 100644 --- a/OpenSim/Data/Null/NullSimulationData.cs +++ b/OpenSim/Data/Null/NullSimulationData.cs @@ -76,9 +76,27 @@ namespace OpenSim.Data.Null //This connector doesn't support the windlight module yet } + #region Environment Settings + public string LoadRegionEnvironmentSettings(UUID regionUUID) + { + //This connector doesn't support the Environment module yet + return string.Empty; + } + + public void StoreRegionEnvironmentSettings(UUID regionUUID, string settings) + { + //This connector doesn't support the Environment module yet + } + + public void RemoveRegionEnvironmentSettings(UUID regionUUID) + { + //This connector doesn't support the Environment module yet + } + #endregion + public RegionSettings LoadRegionSettings(UUID regionUUID) - { - RegionSettings rs = new RegionSettings(); + { + RegionSettings rs = new RegionSettings(); rs.RegionUUID = regionUUID; return rs; } diff --git a/OpenSim/Data/SQLite/Resources/RegionStore.migrations b/OpenSim/Data/SQLite/Resources/RegionStore.migrations index 1ceddf98a1..e872977634 100644 --- a/OpenSim/Data/SQLite/Resources/RegionStore.migrations +++ b/OpenSim/Data/SQLite/Resources/RegionStore.migrations @@ -564,3 +564,14 @@ COMMIT; BEGIN; ALTER TABLE `regionsettings` ADD COLUMN `parcel_tile_ID` char(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000'; COMMIT; + +:VERSION 26 + +BEGIN; + +CREATE TABLE `regionenvironment` ( + `region_id` varchar(36) NOT NULL DEFAULT '000000-0000-0000-0000-000000000000' PRIMARY KEY, + `llsd_settings` TEXT NOT NULL +); + +COMMIT; diff --git a/OpenSim/Data/SQLite/SQLiteSimulationData.cs b/OpenSim/Data/SQLite/SQLiteSimulationData.cs index 7e7c08a74f..f40e86644c 100644 --- a/OpenSim/Data/SQLite/SQLiteSimulationData.cs +++ b/OpenSim/Data/SQLite/SQLiteSimulationData.cs @@ -61,6 +61,7 @@ namespace OpenSim.Data.SQLite private const string regionbanListSelect = "select * from regionban"; private const string regionSettingsSelect = "select * from regionsettings"; private const string regionWindlightSelect = "select * from regionwindlight"; + private const string regionEnvironmentSelect = "select * from regionenvironment"; private const string regionSpawnPointsSelect = "select * from spawn_points"; private DataSet ds; @@ -72,6 +73,7 @@ namespace OpenSim.Data.SQLite private SqliteDataAdapter landAccessListDa; private SqliteDataAdapter regionSettingsDa; private SqliteDataAdapter regionWindlightDa; + private SqliteDataAdapter regionEnvironmentDa; private SqliteDataAdapter regionSpawnPointsDa; private SqliteConnection m_conn; @@ -146,6 +148,9 @@ namespace OpenSim.Data.SQLite SqliteCommand regionWindlightSelectCmd = new SqliteCommand(regionWindlightSelect, m_conn); regionWindlightDa = new SqliteDataAdapter(regionWindlightSelectCmd); + SqliteCommand regionEnvironmentSelectCmd = new SqliteCommand(regionEnvironmentSelect, m_conn); + regionEnvironmentDa = new SqliteDataAdapter(regionEnvironmentSelectCmd); + SqliteCommand regionSpawnPointsSelectCmd = new SqliteCommand(regionSpawnPointsSelect, m_conn); regionSpawnPointsDa = new SqliteDataAdapter(regionSpawnPointsSelectCmd); @@ -179,6 +184,9 @@ namespace OpenSim.Data.SQLite ds.Tables.Add(createRegionWindlightTable()); setupRegionWindlightCommands(regionWindlightDa, m_conn); + ds.Tables.Add(createRegionEnvironmentTable()); + setupRegionEnvironmentCommands(regionEnvironmentDa, m_conn); + ds.Tables.Add(createRegionSpawnPointsTable()); setupRegionSpawnPointsCommands(regionSpawnPointsDa, m_conn); @@ -258,6 +266,15 @@ namespace OpenSim.Data.SQLite m_log.ErrorFormat("[SQLITE REGION DB]: Caught fill error on regionwindlight table :{0}", e.Message); } + try + { + regionEnvironmentDa.Fill(ds.Tables["regionenvironment"]); + } + catch (Exception e) + { + m_log.ErrorFormat("[SQLITE REGION DB]: Caught fill error on regionenvironment table :{0}", e.Message); + } + try { regionSpawnPointsDa.Fill(ds.Tables["spawn_points"]); @@ -278,12 +295,13 @@ namespace OpenSim.Data.SQLite CreateDataSetMapping(landAccessListDa, "landaccesslist"); CreateDataSetMapping(regionSettingsDa, "regionsettings"); CreateDataSetMapping(regionWindlightDa, "regionwindlight"); + CreateDataSetMapping(regionEnvironmentDa, "regionenvironment"); CreateDataSetMapping(regionSpawnPointsDa, "spawn_points"); } } catch (Exception e) { - m_log.ErrorFormat("[SQLITE REGION DB]: ", e); + m_log.ErrorFormat("[SQLITE REGION DB]: {0} - {1}", e.Message, e.StackTrace); Environment.Exit(23); } return; @@ -341,6 +359,11 @@ namespace OpenSim.Data.SQLite regionWindlightDa.Dispose(); regionWindlightDa = null; } + if (regionEnvironmentDa != null) + { + regionEnvironmentDa.Dispose(); + regionEnvironmentDa = null; + } if (regionSpawnPointsDa != null) { regionSpawnPointsDa.Dispose(); @@ -474,6 +497,63 @@ namespace OpenSim.Data.SQLite } } + #region Region Environment Settings + public string LoadRegionEnvironmentSettings(UUID regionUUID) + { + lock (ds) + { + DataTable environmentTable = ds.Tables["regionenvironment"]; + DataRow row = environmentTable.Rows.Find(regionUUID.ToString()); + if (row == null) + { + return String.Empty; + } + + return (String)row["llsd_settings"]; + } + } + + public void StoreRegionEnvironmentSettings(UUID regionUUID, string settings) + { + lock (ds) + { + DataTable environmentTable = ds.Tables["regionenvironment"]; + DataRow row = environmentTable.Rows.Find(regionUUID.ToString()); + + if (row == null) + { + row = environmentTable.NewRow(); + row["region_id"] = regionUUID.ToString(); + row["llsd_settings"] = settings; + environmentTable.Rows.Add(row); + } + else + { + row["llsd_settings"] = settings; + } + + regionEnvironmentDa.Update(ds, "regionenvironment"); + } + } + + public void RemoveRegionEnvironmentSettings(UUID regionUUID) + { + lock (ds) + { + DataTable environmentTable = ds.Tables["regionenvironment"]; + DataRow row = environmentTable.Rows.Find(regionUUID.ToString()); + + if (row != null) + { + row.Delete(); + } + + regionEnvironmentDa.Update(ds, "regionenvironment"); + } + } + + #endregion + public RegionSettings LoadRegionSettings(UUID regionUUID) { lock (ds) @@ -1430,6 +1510,17 @@ namespace OpenSim.Data.SQLite return regionwindlight; } + private static DataTable createRegionEnvironmentTable() + { + DataTable regionEnvironment = new DataTable("regionenvironment"); + createCol(regionEnvironment, "region_id", typeof(String)); + createCol(regionEnvironment, "llsd_settings", typeof(String)); + + regionEnvironment.PrimaryKey = new DataColumn[] { regionEnvironment.Columns["region_id"] }; + + return regionEnvironment; + } + private static DataTable createRegionSpawnPointsTable() { DataTable spawn_points = new DataTable("spawn_points"); @@ -2691,6 +2782,14 @@ namespace OpenSim.Data.SQLite da.UpdateCommand.Connection = conn; } + private void setupRegionEnvironmentCommands(SqliteDataAdapter da, SqliteConnection conn) + { + da.InsertCommand = createInsertCommand("regionenvironment", ds.Tables["regionenvironment"]); + da.InsertCommand.Connection = conn; + da.UpdateCommand = createUpdateCommand("regionenvironment", "region_id=:region_id", ds.Tables["regionenvironment"]); + da.UpdateCommand.Connection = conn; + } + private void setupRegionSpawnPointsCommands(SqliteDataAdapter da, SqliteConnection conn) { da.InsertCommand = createInsertCommand("spawn_points", ds.Tables["spawn_points"]); diff --git a/OpenSim/Framework/Console/ConsoleDisplayList.cs b/OpenSim/Framework/Console/ConsoleDisplayList.cs new file mode 100644 index 0000000000..68855091d4 --- /dev/null +++ b/OpenSim/Framework/Console/ConsoleDisplayList.cs @@ -0,0 +1,112 @@ +/* + * 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.Linq; +using System.Text; + +namespace OpenSim.Framework.Console +{ + /// + /// Used to generated a formatted table for the console. + /// + /// + /// Currently subject to change. If you use this, be prepared to change your code when this class changes. + /// + public class ConsoleDisplayList + { + /// + /// The default divider between key and value for a list item. + /// + public const string DefaultKeyValueDivider = " : "; + + /// + /// The divider used between key and value for a list item. + /// + public string KeyValueDivider { get; set; } + + /// + /// Table rows + /// + public List> Rows { get; private set; } + + /// + /// Number of spaces to indent the list. + /// + public int Indent { get; set; } + + public ConsoleDisplayList() + { + Rows = new List>(); + KeyValueDivider = DefaultKeyValueDivider; + } + + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + AddToStringBuilder(sb); + return sb.ToString(); + } + + public void AddToStringBuilder(StringBuilder sb) + { + string formatString = GetFormatString(); +// System.Console.WriteLine("FORMAT STRING [{0}]", formatString); + + // rows + foreach (KeyValuePair row in Rows) + sb.AppendFormat(formatString, row.Key, row.Value); + } + + /// + /// Gets the format string for the table. + /// + private string GetFormatString() + { + StringBuilder formatSb = new StringBuilder(); + + int longestKey = -1; + + foreach (KeyValuePair row in Rows) + if (row.Key.Length > longestKey) + longestKey = row.Key.Length; + + formatSb.Append(' ', Indent); + + // Can only do left formatting for now + formatSb.AppendFormat("{{0,-{0}}}{1}{{1}}\n", longestKey, KeyValueDivider); + + return formatSb.ToString(); + } + + public void AddRow(object key, object value) + { + Rows.Add(new KeyValuePair(key.ToString(), value.ToString())); + } + } +} \ No newline at end of file diff --git a/OpenSim/Framework/Console/ConsoleTable.cs b/OpenSim/Framework/Console/ConsoleDisplayTable.cs similarity index 86% rename from OpenSim/Framework/Console/ConsoleTable.cs rename to OpenSim/Framework/Console/ConsoleDisplayTable.cs index be3025be7f..e9d1628b1d 100644 --- a/OpenSim/Framework/Console/ConsoleTable.cs +++ b/OpenSim/Framework/Console/ConsoleDisplayTable.cs @@ -38,7 +38,7 @@ namespace OpenSim.Framework.Console /// /// Currently subject to change. If you use this, be prepared to change your code when this class changes. /// - public class ConsoleTable + public class ConsoleDisplayTable { /// /// Default number of spaces between table columns. @@ -48,12 +48,12 @@ namespace OpenSim.Framework.Console /// /// Table columns. /// - public List Columns { get; private set; } + public List Columns { get; private set; } /// /// Table rows /// - public List Rows { get; private set; } + public List Rows { get; private set; } /// /// Number of spaces to indent the table. @@ -65,11 +65,11 @@ namespace OpenSim.Framework.Console /// public int TableSpacing { get; set; } - public ConsoleTable() + public ConsoleDisplayTable() { TableSpacing = DefaultTableSpacing; - Columns = new List(); - Rows = new List(); + Columns = new List(); + Rows = new List(); } public override string ToString() @@ -88,7 +88,7 @@ namespace OpenSim.Framework.Console sb.AppendFormat(formatString, Columns.ConvertAll(c => c.Header).ToArray()); // rows - foreach (ConsoleTableRow row in Rows) + foreach (ConsoleDisplayTableRow row in Rows) sb.AppendFormat(formatString, row.Cells.ToArray()); } @@ -115,23 +115,23 @@ namespace OpenSim.Framework.Console } } - public struct ConsoleTableColumn + public struct ConsoleDisplayTableColumn { public string Header { get; set; } public int Width { get; set; } - public ConsoleTableColumn(string header, int width) : this() + public ConsoleDisplayTableColumn(string header, int width) : this() { Header = header; Width = width; } } - public struct ConsoleTableRow + public struct ConsoleDisplayTableRow { public List Cells { get; private set; } - public ConsoleTableRow(List cells) : this() + public ConsoleDisplayTableRow(List cells) : this() { Cells = cells; } diff --git a/OpenSim/Framework/Servers/HttpServer/OSHttpStatusCodes.cs b/OpenSim/Framework/Servers/HttpServer/OSHttpStatusCodes.cs index 5625227340..a736c8b753 100644 --- a/OpenSim/Framework/Servers/HttpServer/OSHttpStatusCodes.cs +++ b/OpenSim/Framework/Servers/HttpServer/OSHttpStatusCodes.cs @@ -28,143 +28,252 @@ namespace OpenSim.Framework.Servers.HttpServer { /// - /// HTTP status codes (almost) as defined by W3C in - /// http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html + /// HTTP status codes (almost) as defined by W3C in http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html and IETF in http://tools.ietf.org/html/rfc6585 /// - public enum OSHttpStatusCode: int + public enum OSHttpStatusCode : int { - // 1xx Informational status codes providing a provisional - // response. - // 100 Tells client that to keep on going sending its request - InfoContinue = 100, - // 101 Server understands request, proposes to switch to different - // application level protocol - InfoSwitchingProtocols = 101, + #region 1xx Informational status codes providing a provisional response. + /// + /// 100 Tells client that to keep on going sending its request + /// + InfoContinue = 100, - // 2xx Success codes - // 200 Request successful - SuccessOk = 200, - // 201 Request successful, new resource created - SuccessOkCreated = 201, - // 202 Request accepted, processing still on-going - SuccessOkAccepted = 202, - // 203 Request successful, meta information not authoritative - SuccessOkNonAuthoritativeInformation = 203, - // 204 Request successful, nothing to return in the body - SuccessOkNoContent = 204, - // 205 Request successful, reset displayed content - SuccessOkResetContent = 205, - // 206 Request successful, partial content returned - SuccessOkPartialContent = 206, + /// + /// 101 Server understands request, proposes to switch to different application level protocol + /// + InfoSwitchingProtocols = 101, - // 3xx Redirect code: user agent needs to go somewhere else - // 300 Redirect: different presentation forms available, take - // a pick - RedirectMultipleChoices = 300, - // 301 Redirect: requested resource has moved and now lives - // somewhere else - RedirectMovedPermanently = 301, - // 302 Redirect: Resource temporarily somewhere else, location - // might change - RedirectFound = 302, - // 303 Redirect: See other as result of a POST - RedirectSeeOther = 303, - // 304 Redirect: Resource still the same as before - RedirectNotModified = 304, - // 305 Redirect: Resource must be accessed via proxy provided - // in location field - RedirectUseProxy = 305, - // 307 Redirect: Resource temporarily somewhere else, location - // might change - RedirectMovedTemporarily = 307, + #endregion - // 4xx Client error: the client borked the request - // 400 Client error: bad request, server does not grok what - // the client wants - ClientErrorBadRequest = 400, - // 401 Client error: the client is not authorized, response - // provides WWW-Authenticate header field with a challenge - ClientErrorUnauthorized = 401, - // 402 Client error: Payment required (reserved for future use) - ClientErrorPaymentRequired = 402, - // 403 Client error: Server understood request, will not - // deliver, do not try again. - ClientErrorForbidden = 403, - // 404 Client error: Server cannot find anything matching the - // client request. - ClientErrorNotFound = 404, - // 405 Client error: The method specified by the client in the - // request is not allowed for the resource requested - ClientErrorMethodNotAllowed = 405, - // 406 Client error: Server cannot generate suitable response - // for the resource and content characteristics requested by - // the client - ClientErrorNotAcceptable = 406, - // 407 Client error: Similar to 401, Server requests that - // client authenticate itself with the proxy first - ClientErrorProxyAuthRequired = 407, - // 408 Client error: Server got impatient with client and - // decided to give up waiting for the client's request to - // arrive - ClientErrorRequestTimeout = 408, - // 409 Client error: Server could not fulfill the request for - // a resource as there is a conflict with the current state of - // the resource but thinks client can do something about this - ClientErrorConflict = 409, - // 410 Client error: The resource has moved somewhere else, - // but server has no clue where. - ClientErrorGone = 410, - // 411 Client error: The server is picky again and insists on - // having a content-length header field in the request - ClientErrorLengthRequired = 411, - // 412 Client error: one or more preconditions supplied in the - // client's request is false - ClientErrorPreconditionFailed = 412, - // 413 Client error: For fear of reflux, the server refuses to - // swallow that much data. - ClientErrorRequestEntityToLarge = 413, - // 414 Client error: The server considers the Request-URI to - // be indecently long and refuses to even look at it. - ClientErrorRequestURITooLong = 414, - // 415 Client error: The server has no clue about the media - // type requested by the client (contrary to popular belief it - // is not a warez server) - ClientErrorUnsupportedMediaType = 415, - // 416 Client error: The requested range cannot be delivered - // by the server. + #region 2xx Success codes + + /// + /// 200 Request successful + /// + SuccessOk = 200, + + /// + /// 201 Request successful, new resource created + /// + SuccessOkCreated = 201, + + /// + /// 202 Request accepted, processing still on-going + /// + SuccessOkAccepted = 202, + + /// + /// 203 Request successful, meta information not authoritative + /// + SuccessOkNonAuthoritativeInformation = 203, + + /// + /// 204 Request successful, nothing to return in the body + /// + SuccessOkNoContent = 204, + + /// + /// 205 Request successful, reset displayed content + /// + SuccessOkResetContent = 205, + + /// + /// 206 Request successful, partial content returned + /// + SuccessOkPartialContent = 206, + + #endregion + + #region 3xx Redirect code: user agent needs to go somewhere else + + /// + /// 300 Redirect: different presentation forms available, take a pick + /// + RedirectMultipleChoices = 300, + + /// + /// 301 Redirect: requested resource has moved and now lives somewhere else + /// + RedirectMovedPermanently = 301, + + /// + /// 302 Redirect: Resource temporarily somewhere else, location might change + /// + RedirectFound = 302, + + /// + /// 303 Redirect: See other as result of a POST + /// + RedirectSeeOther = 303, + + /// + /// 304 Redirect: Resource still the same as before + /// + RedirectNotModified = 304, + + /// + /// 305 Redirect: Resource must be accessed via proxy provided in location field + /// + RedirectUseProxy = 305, + + /// + /// 307 Redirect: Resource temporarily somewhere else, location might change + /// + RedirectMovedTemporarily = 307, + + #endregion + + #region 4xx Client error: the client borked the request + + /// + /// 400 Client error: bad request, server does not grok what the client wants + /// + ClientErrorBadRequest = 400, + + /// + /// 401 Client error: the client is not authorized, response provides WWW-Authenticate header field with a challenge + /// + ClientErrorUnauthorized = 401, + + /// + /// 402 Client error: Payment required (reserved for future use) + /// + ClientErrorPaymentRequired = 402, + + /// + /// 403 Client error: Server understood request, will not deliver, do not try again. + ClientErrorForbidden = 403, + + /// + /// 404 Client error: Server cannot find anything matching the client request. + /// + ClientErrorNotFound = 404, + + /// + /// 405 Client error: The method specified by the client in the request is not allowed for the resource requested + /// + ClientErrorMethodNotAllowed = 405, + + /// + /// 406 Client error: Server cannot generate suitable response for the resource and content characteristics requested by the client + /// + ClientErrorNotAcceptable = 406, + + /// + /// 407 Client error: Similar to 401, Server requests that client authenticate itself with the proxy first + /// + ClientErrorProxyAuthRequired = 407, + + /// + /// 408 Client error: Server got impatient with client and decided to give up waiting for the client's request to arrive + /// + ClientErrorRequestTimeout = 408, + + /// + /// 409 Client error: Server could not fulfill the request for a resource as there is a conflict with the current state of the resource but thinks client can do something about this + /// + ClientErrorConflict = 409, + + /// + /// 410 Client error: The resource has moved somewhere else, but server has no clue where. + /// + ClientErrorGone = 410, + + /// + /// 411 Client error: The server is picky again and insists on having a content-length header field in the request + /// + ClientErrorLengthRequired = 411, + + /// + /// 412 Client error: one or more preconditions supplied in the client's request is false + /// + ClientErrorPreconditionFailed = 412, + + /// + /// 413 Client error: For fear of reflux, the server refuses to swallow that much data. + /// + ClientErrorRequestEntityToLarge = 413, + + /// + /// 414 Client error: The server considers the Request-URI to be indecently long and refuses to even look at it. + /// + ClientErrorRequestURITooLong = 414, + + /// + /// 415 Client error: The server has no clue about the media type requested by the client (contrary to popular belief it is not a warez server) + /// + ClientErrorUnsupportedMediaType = 415, + + /// + /// 416 Client error: The requested range cannot be delivered by the server. + /// ClientErrorRequestRangeNotSatisfiable = 416, - // 417 Client error: The expectations of the client as - // expressed in one or more Expect header fields cannot be met - // by the server, the server is awfully sorry about this. - ClientErrorExpectationFailed = 417, - // 499 Client error: Wildcard error. - ClientErrorJoker = 499, - // 5xx Server errors (rare) - // 500 Server error: something really strange and unexpected - // happened - ServerErrorInternalError = 500, - // 501 Server error: The server does not do the functionality - // required to carry out the client request. not at - // all. certainly not before breakfast. but also not after - // breakfast. - ServerErrorNotImplemented = 501, - // 502 Server error: While acting as a proxy or a gateway, the - // server got ditched by the upstream server and as a - // consequence regretfully cannot fulfill the client's request - ServerErrorBadGateway = 502, - // 503 Server error: Due to unforseen circumstances the server - // cannot currently deliver the service requested. Retry-After - // header might indicate when to try again. - ServerErrorServiceUnavailable = 503, - // 504 Server error: The server blames the upstream server - // for not being able to deliver the service requested and - // claims that the upstream server is too slow delivering the - // goods. - ServerErrorGatewayTimeout = 504, - // 505 Server error: The server does not support the HTTP - // version conveyed in the client's request. - ServerErrorHttpVersionNotSupported = 505, + /// + /// 417 Client error: The expectations of the client as expressed in one or more Expect header fields cannot be met by the server, the server is awfully sorry about this. + /// + ClientErrorExpectationFailed = 417, + + /// + /// 428 Client error :The 428 status code indicates that the origin server requires the request to be conditional. + /// + ClientErrorPreconditionRequired = 428, + + /// + /// 429 Client error: The 429 status code indicates that the user has sent too many requests in a given amount of time ("rate limiting"). + /// + ClientErrorTooManyRequests = 429, + + /// + /// 431 Client error: The 431 status code indicates that the server is unwilling to process the request because its header fields are too large. The request MAY be resubmitted after reducing the size of the request header fields. + /// + ClientErrorRequestHeaderFieldsTooLarge = 431, + + /// + /// 499 Client error: Wildcard error. + /// + ClientErrorJoker = 499, + + #endregion + + #region 5xx Server errors (rare) + + /// + /// 500 Server error: something really strange and unexpected happened + /// + ServerErrorInternalError = 500, + + /// + /// 501 Server error: The server does not do the functionality required to carry out the client request. not at all. certainly not before breakfast. but also not after breakfast. + /// + ServerErrorNotImplemented = 501, + + /// + /// 502 Server error: While acting as a proxy or a gateway, the server got ditched by the upstream server and as a consequence regretfully cannot fulfill the client's request + /// + ServerErrorBadGateway = 502, + + /// + /// 503 Server error: Due to unforseen circumstances the server cannot currently deliver the service requested. Retry-After header might indicate when to try again. + /// + ServerErrorServiceUnavailable = 503, + + /// + /// 504 Server error: The server blames the upstream server for not being able to deliver the service requested and claims that the upstream server is too slow delivering the goods. + /// + ServerErrorGatewayTimeout = 504, + + /// + /// 505 Server error: The server does not support the HTTP version conveyed in the client's request. + /// + ServerErrorHttpVersionNotSupported = 505, + + /// + /// 511 Server error: The 511 status code indicates that the client needs to authenticate to gain network access. + /// + ServerErrorNetworkAuthenticationRequired = 511, + + #endregion } } diff --git a/OpenSim/Region/CoreModules/Avatar/Attachments/AttachmentsModule.cs b/OpenSim/Region/CoreModules/Avatar/Attachments/AttachmentsModule.cs index 2bfe190268..7a914812bf 100644 --- a/OpenSim/Region/CoreModules/Avatar/Attachments/AttachmentsModule.cs +++ b/OpenSim/Region/CoreModules/Avatar/Attachments/AttachmentsModule.cs @@ -50,7 +50,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Attachments private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Scene m_scene; - private IDialogModule m_dialogModule; + private IInventoryAccessModule m_invAccessModule; /// /// Are attachments enabled? @@ -72,7 +72,6 @@ namespace OpenSim.Region.CoreModules.Avatar.Attachments public void AddRegion(Scene scene) { m_scene = scene; - m_dialogModule = m_scene.RequestModuleInterface(); m_scene.RegisterModuleInterface(this); if (Enabled) @@ -89,7 +88,10 @@ namespace OpenSim.Region.CoreModules.Avatar.Attachments m_scene.EventManager.OnNewClient -= SubscribeToClientEvents; } - public void RegionLoaded(Scene scene) {} + public void RegionLoaded(Scene scene) + { + m_invAccessModule = m_scene.RequestModuleInterface(); + } public void Close() { @@ -629,6 +631,9 @@ namespace OpenSim.Region.CoreModules.Avatar.Attachments /// The user inventory item created that holds the attachment. private InventoryItemBase AddSceneObjectAsNewAttachmentInInv(IScenePresence sp, SceneObjectGroup grp) { + if (m_invAccessModule == null) + return null; + // m_log.DebugFormat( // "[ATTACHMENTS MODULE]: Called AddSceneObjectAsAttachment for object {0} {1} for {2}", // grp.Name, grp.LocalId, remoteClient.Name); @@ -702,16 +707,6 @@ namespace OpenSim.Region.CoreModules.Avatar.Attachments // sets itemID so client can show item as 'attached' in inventory grp.FromItemID = item.ID; - if (m_scene.AddInventoryItem(item)) - { - sp.ControllingClient.SendInventoryItemCreateUpdate(item, 0); - } - else - { - if (m_dialogModule != null) - m_dialogModule.SendAlertToUser(sp.ControllingClient, "Operation failed"); - } - return item; } @@ -760,76 +755,75 @@ namespace OpenSim.Region.CoreModules.Avatar.Attachments protected SceneObjectGroup RezSingleAttachmentFromInventoryInternal( IScenePresence sp, UUID itemID, UUID assetID, uint attachmentPt, XmlDocument doc) { - IInventoryAccessModule invAccess = m_scene.RequestModuleInterface(); - if (invAccess != null) + if (m_invAccessModule == null) + return null; + + lock (sp.AttachmentsSyncLock) { - lock (sp.AttachmentsSyncLock) + SceneObjectGroup objatt; + + if (itemID != UUID.Zero) + objatt = m_invAccessModule.RezObject(sp.ControllingClient, + itemID, Vector3.Zero, Vector3.Zero, UUID.Zero, (byte)1, true, + false, false, sp.UUID, true); + else + objatt = m_invAccessModule.RezObject(sp.ControllingClient, + null, assetID, Vector3.Zero, Vector3.Zero, UUID.Zero, (byte)1, true, + false, false, sp.UUID, true); + + // m_log.DebugFormat( + // "[ATTACHMENTS MODULE]: Retrieved single object {0} for attachment to {1} on point {2}", + // objatt.Name, remoteClient.Name, AttachmentPt); + + if (objatt != null) { - SceneObjectGroup objatt; - - if (itemID != UUID.Zero) - objatt = invAccess.RezObject(sp.ControllingClient, - itemID, Vector3.Zero, Vector3.Zero, UUID.Zero, (byte)1, true, - false, false, sp.UUID, true); - else - objatt = invAccess.RezObject(sp.ControllingClient, - null, assetID, Vector3.Zero, Vector3.Zero, UUID.Zero, (byte)1, true, - false, false, sp.UUID, true); - - // m_log.DebugFormat( - // "[ATTACHMENTS MODULE]: Retrieved single object {0} for attachment to {1} on point {2}", - // objatt.Name, remoteClient.Name, AttachmentPt); - - if (objatt != null) - { - // HasGroupChanged is being set from within RezObject. Ideally it would be set by the caller. - objatt.HasGroupChanged = false; - bool tainted = false; - if (attachmentPt != 0 && attachmentPt != objatt.AttachmentPoint) - tainted = true; - - // This will throw if the attachment fails - try - { - AttachObject(sp, objatt, attachmentPt, false); - } - catch (Exception e) - { - m_log.ErrorFormat( - "[ATTACHMENTS MODULE]: Failed to attach {0} {1} for {2}, exception {3}{4}", - objatt.Name, objatt.UUID, sp.Name, e.Message, e.StackTrace); - - // Make sure the object doesn't stick around and bail - sp.RemoveAttachment(objatt); - m_scene.DeleteSceneObject(objatt, false); - return null; - } - - if (tainted) - objatt.HasGroupChanged = true; - - if (doc != null) - { - objatt.LoadScriptState(doc); - objatt.ResetOwnerChangeFlag(); - } + // HasGroupChanged is being set from within RezObject. Ideally it would be set by the caller. + objatt.HasGroupChanged = false; + bool tainted = false; + if (attachmentPt != 0 && attachmentPt != objatt.AttachmentPoint) + tainted = true; - // Fire after attach, so we don't get messy perms dialogs - // 4 == AttachedRez - objatt.CreateScriptInstances(0, true, m_scene.DefaultScriptEngine, 4); - objatt.ResumeScripts(); - - // Do this last so that event listeners have access to all the effects of the attachment - m_scene.EventManager.TriggerOnAttach(objatt.LocalId, itemID, sp.UUID); - - return objatt; - } - else + // This will throw if the attachment fails + try { - m_log.WarnFormat( - "[ATTACHMENTS MODULE]: Could not retrieve item {0} for attaching to avatar {1} at point {2}", - itemID, sp.Name, attachmentPt); + AttachObject(sp, objatt, attachmentPt, false); } + catch (Exception e) + { + m_log.ErrorFormat( + "[ATTACHMENTS MODULE]: Failed to attach {0} {1} for {2}, exception {3}{4}", + objatt.Name, objatt.UUID, sp.Name, e.Message, e.StackTrace); + + // Make sure the object doesn't stick around and bail + sp.RemoveAttachment(objatt); + m_scene.DeleteSceneObject(objatt, false); + return null; + } + + if (doc != null) + { + objatt.LoadScriptState(doc); + objatt.ResetOwnerChangeFlag(); + } + + if (tainted) + objatt.HasGroupChanged = true; + + // Fire after attach, so we don't get messy perms dialogs + // 4 == AttachedRez + objatt.CreateScriptInstances(0, true, m_scene.DefaultScriptEngine, 4); + objatt.ResumeScripts(); + + // Do this last so that event listeners have access to all the effects of the attachment + m_scene.EventManager.TriggerOnAttach(objatt.LocalId, itemID, sp.UUID); + + return objatt; + } + else + { + m_log.WarnFormat( + "[ATTACHMENTS MODULE]: Could not retrieve item {0} for attaching to avatar {1} at point {2}", + itemID, sp.Name, attachmentPt); } } diff --git a/OpenSim/Region/CoreModules/Avatar/Attachments/Tests/AttachmentsModuleTests.cs b/OpenSim/Region/CoreModules/Avatar/Attachments/Tests/AttachmentsModuleTests.cs index 42d07fd2d6..5e89eec25d 100644 --- a/OpenSim/Region/CoreModules/Avatar/Attachments/Tests/AttachmentsModuleTests.cs +++ b/OpenSim/Region/CoreModules/Avatar/Attachments/Tests/AttachmentsModuleTests.cs @@ -99,12 +99,12 @@ namespace OpenSim.Region.CoreModules.Avatar.Attachments.Tests public void TestAddAttachmentFromGround() { TestHelpers.InMethod(); -// log4net.Config.XmlConfigurator.Configure(); +// TestHelpers.EnableLogging(); AddPresence(); string attName = "att"; - SceneObjectGroup so = SceneHelpers.AddSceneObject(scene, attName).ParentGroup; + SceneObjectGroup so = SceneHelpers.AddSceneObject(scene, attName, m_presence.UUID).ParentGroup; m_attMod.AttachObject(m_presence, so, (uint)AttachmentPoint.Chest, false); @@ -123,6 +123,15 @@ namespace OpenSim.Region.CoreModules.Avatar.Attachments.Tests Assert.That( m_presence.Appearance.GetAttachpoint(attSo.FromItemID), Is.EqualTo((int)AttachmentPoint.Chest)); + + InventoryItemBase attachmentItem = scene.InventoryService.GetItem(new InventoryItemBase(attSo.FromItemID)); + Assert.That(attachmentItem, Is.Not.Null); + Assert.That(attachmentItem.Name, Is.EqualTo(attName)); + + InventoryFolderBase targetFolder = scene.InventoryService.GetFolderForType(m_presence.UUID, AssetType.Object); + Assert.That(attachmentItem.Folder, Is.EqualTo(targetFolder.ID)); + +// TestHelpers.DisableLogging(); } [Test] diff --git a/OpenSim/Region/CoreModules/Avatar/Friends/HGFriendsModule.cs b/OpenSim/Region/CoreModules/Avatar/Friends/HGFriendsModule.cs index 3728b85a16..06f27e23df 100644 --- a/OpenSim/Region/CoreModules/Avatar/Friends/HGFriendsModule.cs +++ b/OpenSim/Region/CoreModules/Avatar/Friends/HGFriendsModule.cs @@ -415,12 +415,13 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends protected override void StoreBackwards(UUID friendID, UUID agentID) { - Boolean agentIsLocal = true; - Boolean friendIsLocal = true; + bool agentIsLocal = true; +// bool friendIsLocal = true; + if (UserManagementModule != null) { agentIsLocal = UserManagementModule.IsLocalGridUser(agentID); - friendIsLocal = UserManagementModule.IsLocalGridUser(friendID); +// friendIsLocal = UserManagementModule.IsLocalGridUser(friendID); } // Is the requester a local user? @@ -507,7 +508,11 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends { friendUUI = finfo.Friend; theFriendUUID = friendUUI; - UUID utmp = UUID.Zero; String url = String.Empty; String first = String.Empty, last = String.Empty, tmp = String.Empty; + UUID utmp = UUID.Zero; + string url = String.Empty; + string first = String.Empty; + string last = String.Empty; + // If it's confirming the friendship, we already have the full UUI with the secret if (Util.ParseUniversalUserIdentifier(theFriendUUID, out utmp, out url, out first, out last, out secret)) { diff --git a/OpenSim/Region/CoreModules/Framework/EntityTransfer/EntityTransferModule.cs b/OpenSim/Region/CoreModules/Framework/EntityTransfer/EntityTransferModule.cs index f9e2b2f05b..5d9d67f560 100644 --- a/OpenSim/Region/CoreModules/Framework/EntityTransfer/EntityTransferModule.cs +++ b/OpenSim/Region/CoreModules/Framework/EntityTransfer/EntityTransferModule.cs @@ -46,7 +46,30 @@ using Nini.Config; namespace OpenSim.Region.CoreModules.Framework.EntityTransfer { - public class EntityTransferModule : ISharedRegionModule, IEntityTransferModule + /// + /// The possible states that an agent can be in when its being transferred between regions. + /// + /// + /// This is a state machine. + /// + /// [Entry] => Preparing + /// Preparing => { Transferring || CleaningUp || [Exit] } + /// Transferring => { ReceivedAtDestination || CleaningUp } + /// ReceivedAtDestination => CleaningUp + /// CleaningUp => [Exit] + /// + /// In other words, agents normally travel throwing Preparing => Transferring => ReceivedAtDestination => CleaningUp + /// However, any state can transition to CleaningUp if the teleport has failed. + /// + enum AgentTransferState + { + Preparing, // The agent is being prepared for transfer + Transferring, // The agent is in the process of being transferred to a destination + ReceivedAtDestination, // The destination has notified us that the agent has been successfully received + CleaningUp // The agent is being changed to child/removed after a transfer + } + + public class EntityTransferModule : INonSharedRegionModule, IEntityTransferModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); @@ -65,12 +88,16 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer public bool EnableWaitForCallbackFromTeleportDest { get; set; } protected bool m_Enabled = false; - protected Scene m_aScene; - protected List m_Scenes = new List(); - protected List m_agentsInTransit; + + protected Scene m_scene; + + private Dictionary m_agentsInTransit; + private ExpiringCache> m_bannedRegions = new ExpiringCache>(); + private IEventQueue m_eqModule; + #region ISharedRegionModule public Type ReplaceableInterface @@ -116,7 +143,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer MaxTransferDistance = DefaultMaxTransferDistance; } - m_agentsInTransit = new List(); + m_agentsInTransit = new Dictionary(); m_Enabled = true; } @@ -129,10 +156,8 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer if (!m_Enabled) return; - if (m_aScene == null) - m_aScene = scene; + m_scene = scene; - m_Scenes.Add(scene); scene.RegisterModuleInterface(this); scene.EventManager.OnNewClient += OnNewClient; } @@ -143,26 +168,16 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer client.OnTeleportLandmarkRequest += RequestTeleportLandmark; } - public virtual void Close() - { - if (!m_Enabled) - return; - } + public virtual void Close() {} - public virtual void RemoveRegion(Scene scene) - { - if (!m_Enabled) - return; - if (scene == m_aScene) - m_aScene = null; - - m_Scenes.Remove(scene); - } + public virtual void RemoveRegion(Scene scene) {} public virtual void RegionLoaded(Scene scene) { if (!m_Enabled) return; + + m_eqModule = m_scene.RequestModuleInterface(); } #endregion @@ -230,6 +245,15 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer "[ENTITY TRANSFER MODULE]: Teleport for {0} to {1} within {2}", sp.Name, position, sp.Scene.RegionInfo.RegionName); + if (!SetInTransit(sp.UUID)) + { + m_log.DebugFormat( + "[ENTITY TRANSFER MODULE]: Ignoring within region teleport request of {0} {1} to {2} - agent is already in transit.", + sp.Name, sp.UUID, position); + + return; + } + // Teleport within the same region if (IsOutsideRegion(sp.Scene, position) || position.Z < 0) { @@ -258,6 +282,8 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer position.Z = newPosZ; } + UpdateInTransit(sp.UUID, AgentTransferState.Transferring); + sp.ControllingClient.SendTeleportStart(teleportFlags); sp.ControllingClient.SendLocalTeleport(position, lookAt, teleportFlags); @@ -265,10 +291,15 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer sp.Velocity = Vector3.Zero; sp.Teleport(position); + UpdateInTransit(sp.UUID, AgentTransferState.ReceivedAtDestination); + foreach (SceneObjectGroup grp in sp.GetAttachments()) { sp.Scene.EventManager.TriggerOnScriptChangedEvent(grp.LocalId, (uint)Changed.TELEPORT); } + + UpdateInTransit(sp.UUID, AgentTransferState.CleaningUp); + ResetFromTransit(sp.UUID); } /// @@ -286,7 +317,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer { uint x = 0, y = 0; Utils.LongToUInts(regionHandle, out x, out y); - GridRegion reg = m_aScene.GridService.GetRegionByPosition(sp.Scene.RegionInfo.ScopeID, (int)x, (int)y); + GridRegion reg = m_scene.GridService.GetRegionByPosition(sp.Scene.RegionInfo.ScopeID, (int)x, (int)y); if (reg != null) { @@ -366,6 +397,30 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer ScenePresence sp, GridRegion reg, GridRegion finalDestination, Vector3 position, Vector3 lookAt, uint teleportFlags) { + // Record that this agent is in transit so that we can prevent simultaneous requests and do later detection + // of whether the destination region completes the teleport. + if (!SetInTransit(sp.UUID)) + { + m_log.DebugFormat( + "[ENTITY TRANSFER MODULE]: Ignoring teleport request of {0} {1} to {2} ({3}) {4}/{5} - agent is already in transit.", + sp.Name, sp.UUID, reg.ServerURI, finalDestination.ServerURI, finalDestination.RegionName, position); + + return; + } + + if (reg == null || finalDestination == null) + { + sp.ControllingClient.SendTeleportFailed("Unable to locate destination"); + ResetFromTransit(sp.UUID); + + return; + } + + m_log.DebugFormat( + "[ENTITY TRANSFER MODULE]: Teleporting {0} {1} from {2} to {3} ({4}) {5}/{6}", + sp.Name, sp.UUID, sp.Scene.RegionInfo.RegionName, + reg.ServerURI, finalDestination.ServerURI, finalDestination.RegionName, position); + RegionInfo sourceRegion = sp.Scene.RegionInfo; if (!IsWithinMaxTeleportDistance(sourceRegion, finalDestination)) @@ -377,31 +432,11 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer sourceRegion.RegionName, sourceRegion.RegionLocX, sourceRegion.RegionLocY, MaxTransferDistance)); - return; - } - - IEventQueue eq = sp.Scene.RequestModuleInterface(); - - if (reg == null || finalDestination == null) - { - sp.ControllingClient.SendTeleportFailed("Unable to locate destination"); - return; - } - - if (!SetInTransit(sp.UUID)) // Avie is already on the way. Caller shouldn't do this. - { - m_log.DebugFormat( - "[ENTITY TRANSFER MODULE]: Ignoring teleport request of {0} {1} to {2} ({3}) {4}/{5} - agent is already in transit.", - sp.Name, sp.UUID, reg.ServerURI, finalDestination.ServerURI, finalDestination.RegionName, position); + ResetFromTransit(sp.UUID); return; } - m_log.DebugFormat( - "[ENTITY TRANSFER MODULE]: Teleporting {0} {1} from {2} to {3} ({4}) {5}/{6}", - sp.Name, sp.UUID, sp.Scene.RegionInfo.RegionName, - reg.ServerURI, finalDestination.ServerURI, finalDestination.RegionName, position); - uint newRegionX = (uint)(reg.RegionHandle >> 40); uint newRegionY = (((uint)(reg.RegionHandle)) >> 8); uint oldRegionX = (uint)(sp.Scene.RegionInfo.RegionHandle >> 40); @@ -415,15 +450,16 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer IPEndPoint endPoint = finalDestination.ExternalEndPoint; if (endPoint != null && endPoint.Address != null) { - // Fixing a bug where teleporting while sitting results in the avatar ending up removed from - // both regions - if (sp.ParentID != (uint)0) - sp.StandUp(); + sp.ControllingClient.SendTeleportFailed("Remote Region appears to be down"); + ResetFromTransit(sp.UUID); - if (!sp.ValidateAttachments()) - m_log.DebugFormat( - "[ENTITY TRANSFER MODULE]: Failed validation of all attachments for teleport of {0} from {1} to {2}. Continuing.", - sp.Name, sp.Scene.RegionInfo.RegionName, finalDestination.RegionName); + return; + } + + if (!sp.ValidateAttachments()) + m_log.DebugFormat( + "[ENTITY TRANSFER MODULE]: Failed validation of all attachments for teleport of {0} from {1} to {2}. Continuing.", + sp.Name, sp.Scene.RegionInfo.RegionName, finalDestination.RegionName); // if (!sp.ValidateAttachments()) // { @@ -431,212 +467,219 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer // return; // } - string reason; - string version; - if (!m_aScene.SimulationService.QueryAccess( - finalDestination, sp.ControllingClient.AgentId, Vector3.Zero, out version, out reason)) - { - sp.ControllingClient.SendTeleportFailed(reason); - ResetFromTransit(sp.UUID); - - m_log.DebugFormat( - "[ENTITY TRANSFER MODULE]: {0} was stopped from teleporting from {1} to {2} because {3}", - sp.Name, sp.Scene.RegionInfo.RegionName, finalDestination.RegionName, reason); - - return; - } - - m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Destination is running version {0}", version); - - sp.ControllingClient.SendTeleportStart(teleportFlags); - - // the avatar.Close below will clear the child region list. We need this below for (possibly) - // closing the child agents, so save it here (we need a copy as it is Clear()-ed). - //List childRegions = avatar.KnownRegionHandles; - // Compared to ScenePresence.CrossToNewRegion(), there's no obvious code to handle a teleport - // failure at this point (unlike a border crossing failure). So perhaps this can never fail - // once we reach here... - //avatar.Scene.RemoveCapsHandler(avatar.UUID); - - string capsPath = String.Empty; - - AgentCircuitData currentAgentCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode); - AgentCircuitData agentCircuit = sp.ControllingClient.RequestClientInfo(); - agentCircuit.startpos = position; - agentCircuit.child = true; - agentCircuit.Appearance = sp.Appearance; - if (currentAgentCircuit != null) - { - agentCircuit.ServiceURLs = currentAgentCircuit.ServiceURLs; - agentCircuit.IPAddress = currentAgentCircuit.IPAddress; - agentCircuit.Viewer = currentAgentCircuit.Viewer; - agentCircuit.Channel = currentAgentCircuit.Channel; - agentCircuit.Mac = currentAgentCircuit.Mac; - agentCircuit.Id0 = currentAgentCircuit.Id0; - } - - if (NeedsNewAgent(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY)) - { - // brand new agent, let's create a new caps seed - agentCircuit.CapsPath = CapsUtil.GetRandomCapsObjectPath(); - } - - // 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)) - { - sp.ControllingClient.SendTeleportFailed(String.Format("Teleport refused: {0}", reason)); - ResetFromTransit(sp.UUID); - - m_log.DebugFormat( - "[ENTITY TRANSFER MODULE]: Teleport of {0} from {1} to {2} was refused because {3}", - sp.Name, sp.Scene.RegionInfo.RegionName, finalDestination.RegionName, reason); - - return; - } - - // OK, it got this agent. Let's close some child agents - sp.CloseChildAgents(newRegionX, newRegionY); - - IClientIPEndpoint ipepClient; - if (NeedsNewAgent(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY)) - { - //sp.ControllingClient.SendTeleportProgress(teleportFlags, "Creating agent..."); - #region IP Translation for NAT - // Uses ipepClient above - if (sp.ClientView.TryGet(out ipepClient)) - { - endPoint.Address = NetworkUtil.GetIPFor(ipepClient.EndPoint, endPoint.Address); - } - #endregion - capsPath = finalDestination.ServerURI + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath); - - if (eq != null) - { - eq.EnableSimulator(destinationHandle, endPoint, sp.UUID); - - // ES makes the client send a UseCircuitCode message to the destination, - // which triggers a bunch of things there. - // So let's wait - Thread.Sleep(200); - - eq.EstablishAgentCommunication(sp.UUID, endPoint, capsPath); - - } - else - { - sp.ControllingClient.InformClientOfNeighbour(destinationHandle, endPoint); - } - } - else - { - agentCircuit.CapsPath = sp.Scene.CapsModule.GetChildSeed(sp.UUID, reg.RegionHandle); - capsPath = finalDestination.ServerURI + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath); - } - - // Let's send a full update of the agent. This is a synchronous call. - AgentData agent = new AgentData(); - sp.CopyTo(agent); - agent.Position = position; - SetCallbackURL(agent, sp.Scene.RegionInfo); - - //sp.ControllingClient.SendTeleportProgress(teleportFlags, "Updating agent..."); - - if (!UpdateAgent(reg, finalDestination, agent)) - { - // Region doesn't take it - m_log.WarnFormat( - "[ENTITY TRANSFER MODULE]: UpdateAgent failed on teleport of {0} to {1} from {2}. Returning avatar to source region.", - sp.Name, finalDestination.RegionName, sp.Scene.RegionInfo.RegionName); - - Fail(sp, finalDestination, logout); - return; - } - - sp.ControllingClient.SendTeleportProgress(teleportFlags | (uint)TeleportFlags.DisableCancel, "sending_dest"); + string reason; + string version; + if (!m_scene.SimulationService.QueryAccess( + finalDestination, sp.ControllingClient.AgentId, Vector3.Zero, out version, out reason)) + { + sp.ControllingClient.SendTeleportFailed(reason); + ResetFromTransit(sp.UUID); m_log.DebugFormat( - "[ENTITY TRANSFER MODULE]: Sending new CAPS seed url {0} from {1} to {2}", - capsPath, sp.Scene.RegionInfo.RegionName, sp.Name); + "[ENTITY TRANSFER MODULE]: {0} was stopped from teleporting from {1} to {2} because {3}", + sp.Name, sp.Scene.RegionInfo.RegionName, finalDestination.RegionName, reason); - if (eq != null) + return; + } + + m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Destination is running version {0}", version); + + // Fixing a bug where teleporting while sitting results in the avatar ending up removed from + // both regions + if (sp.ParentID != (uint)0) + sp.StandUp(); + + sp.ControllingClient.SendTeleportStart(teleportFlags); + + // the avatar.Close below will clear the child region list. We need this below for (possibly) + // closing the child agents, so save it here (we need a copy as it is Clear()-ed). + //List childRegions = avatar.KnownRegionHandles; + // Compared to ScenePresence.CrossToNewRegion(), there's no obvious code to handle a teleport + // failure at this point (unlike a border crossing failure). So perhaps this can never fail + // once we reach here... + //avatar.Scene.RemoveCapsHandler(avatar.UUID); + + string capsPath = String.Empty; + + AgentCircuitData currentAgentCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode); + AgentCircuitData agentCircuit = sp.ControllingClient.RequestClientInfo(); + agentCircuit.startpos = position; + agentCircuit.child = true; + agentCircuit.Appearance = sp.Appearance; + if (currentAgentCircuit != null) + { + agentCircuit.ServiceURLs = currentAgentCircuit.ServiceURLs; + agentCircuit.IPAddress = currentAgentCircuit.IPAddress; + agentCircuit.Viewer = currentAgentCircuit.Viewer; + agentCircuit.Channel = currentAgentCircuit.Channel; + agentCircuit.Mac = currentAgentCircuit.Mac; + agentCircuit.Id0 = currentAgentCircuit.Id0; + } + + if (NeedsNewAgent(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY)) + { + // brand new agent, let's create a new caps seed + agentCircuit.CapsPath = CapsUtil.GetRandomCapsObjectPath(); + } + + // 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)) + { + sp.ControllingClient.SendTeleportFailed(String.Format("Teleport refused: {0}", reason)); + ResetFromTransit(sp.UUID); + + m_log.DebugFormat( + "[ENTITY TRANSFER MODULE]: Teleport of {0} from {1} to {2} was refused because {3}", + sp.Name, sp.Scene.RegionInfo.RegionName, finalDestination.RegionName, reason); + + return; + } + + // Past this point we have to attempt clean up if the teleport fails, so update transfer state. + UpdateInTransit(sp.UUID, AgentTransferState.Transferring); + + // OK, it got this agent. Let's close some child agents + sp.CloseChildAgents(newRegionX, newRegionY); + + IClientIPEndpoint ipepClient; + if (NeedsNewAgent(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY)) + { + //sp.ControllingClient.SendTeleportProgress(teleportFlags, "Creating agent..."); + #region IP Translation for NAT + // Uses ipepClient above + if (sp.ClientView.TryGet(out ipepClient)) { - eq.TeleportFinishEvent(destinationHandle, 13, endPoint, - 0, teleportFlags, capsPath, sp.UUID); + endPoint.Address = NetworkUtil.GetIPFor(ipepClient.EndPoint, endPoint.Address); + } + #endregion + capsPath = finalDestination.ServerURI + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath); + + if (m_eqModule != null) + { + m_eqModule.EnableSimulator(destinationHandle, endPoint, sp.UUID); + + // ES makes the client send a UseCircuitCode message to the destination, + // which triggers a bunch of things there. + // So let's wait + Thread.Sleep(200); + + m_eqModule.EstablishAgentCommunication(sp.UUID, endPoint, capsPath); + } else { - sp.ControllingClient.SendRegionTeleport(destinationHandle, 13, endPoint, 4, - teleportFlags, capsPath); - } - - // Let's set this to true tentatively. This does not trigger OnChildAgent - sp.IsChildAgent = true; - - // TeleportFinish makes the client send CompleteMovementIntoRegion (at the destination), which - // trigers a whole shebang of things there, including MakeRoot. So let's wait for confirmation - // that the client contacted the destination before we close things here. - if (EnableWaitForCallbackFromTeleportDest && !WaitForCallback(sp.UUID)) - { - m_log.WarnFormat( - "[ENTITY TRANSFER MODULE]: Teleport of {0} to {1} from {2} failed due to no callback from destination region. Returning avatar to source region.", - sp.Name, finalDestination.RegionName, sp.Scene.RegionInfo.RegionName); - - Fail(sp, finalDestination, logout); - return; - } - - // For backwards compatibility - if (version == "Unknown" || version == string.Empty) - { - // CrossAttachmentsIntoNewRegion is a synchronous call. We shouldn't need to wait after it - m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Old simulator, sending attachments one by one..."); - CrossAttachmentsIntoNewRegion(finalDestination, sp, true); - } - - // May need to logout or other cleanup - AgentHasMovedAway(sp, logout); - - // Well, this is it. The agent is over there. - KillEntity(sp.Scene, sp.LocalId); - - // Now let's make it officially a child agent - sp.MakeChildAgent(); - -// sp.Scene.CleanDroppedAttachments(); - - // Finally, let's close this previously-known-as-root agent, when the jump is outside the view zone - - if (NeedsClosing(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY, reg)) - { - // We need to delay here because Imprudence viewers, unlike v1 or v3, have a short (<200ms, <500ms) delay before - // they regard the new region as the current region after receiving the AgentMovementComplete - // response. If close is sent before then, it will cause the viewer to quit instead. - // However, if this delay is longer, then a viewer can teleport back to this region and experience - // a failure because the old ScenePresence has not yet been cleaned up. - Thread.Sleep(2000); - - sp.Close(); - sp.Scene.IncomingCloseAgent(sp.UUID); - } - else - { - // now we have a child agent in this region. - sp.Reset(); - } - - // REFACTORING PROBLEM. Well, not a problem, but this method is HORRIBLE! - if (sp.Scene.NeedSceneCacheClear(sp.UUID)) - { - m_log.DebugFormat( - "[ENTITY TRANSFER MODULE]: User {0} is going to another region, profile cache removed", - sp.UUID); + sp.ControllingClient.InformClientOfNeighbour(destinationHandle, endPoint); } } else { - sp.ControllingClient.SendTeleportFailed("Remote Region appears to be down"); + agentCircuit.CapsPath = sp.Scene.CapsModule.GetChildSeed(sp.UUID, reg.RegionHandle); + capsPath = finalDestination.ServerURI + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath); } + + // Let's send a full update of the agent. This is a synchronous call. + AgentData agent = new AgentData(); + sp.CopyTo(agent); + agent.Position = position; + SetCallbackURL(agent, sp.Scene.RegionInfo); + + //sp.ControllingClient.SendTeleportProgress(teleportFlags, "Updating agent..."); + + if (!UpdateAgent(reg, finalDestination, agent)) + { + // Region doesn't take it + m_log.WarnFormat( + "[ENTITY TRANSFER MODULE]: UpdateAgent failed on teleport of {0} to {1} from {2}. Returning avatar to source region.", + sp.Name, finalDestination.RegionName, sp.Scene.RegionInfo.RegionName); + + Fail(sp, finalDestination, logout); + return; + } + + sp.ControllingClient.SendTeleportProgress(teleportFlags | (uint)TeleportFlags.DisableCancel, "sending_dest"); + + m_log.DebugFormat( + "[ENTITY TRANSFER MODULE]: Sending new CAPS seed url {0} from {1} to {2}", + capsPath, sp.Scene.RegionInfo.RegionName, sp.Name); + + if (m_eqModule != null) + { + m_eqModule.TeleportFinishEvent(destinationHandle, 13, endPoint, 0, teleportFlags, capsPath, sp.UUID); + } + else + { + sp.ControllingClient.SendRegionTeleport(destinationHandle, 13, endPoint, 4, + teleportFlags, capsPath); + } + + // Let's set this to true tentatively. This does not trigger OnChildAgent + sp.IsChildAgent = true; + + // TeleportFinish makes the client send CompleteMovementIntoRegion (at the destination), which + // trigers a whole shebang of things there, including MakeRoot. So let's wait for confirmation + // that the client contacted the destination before we close things here. + if (EnableWaitForCallbackFromTeleportDest && !WaitForCallback(sp.UUID)) + { + m_log.WarnFormat( + "[ENTITY TRANSFER MODULE]: Teleport of {0} to {1} from {2} failed due to no callback from destination region. Returning avatar to source region.", + sp.Name, finalDestination.RegionName, sp.Scene.RegionInfo.RegionName); + + Fail(sp, finalDestination, logout); + return; + } + + UpdateInTransit(sp.UUID, AgentTransferState.CleaningUp); + + // For backwards compatibility + if (version == "Unknown" || version == string.Empty) + { + // CrossAttachmentsIntoNewRegion is a synchronous call. We shouldn't need to wait after it + m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Old simulator, sending attachments one by one..."); + CrossAttachmentsIntoNewRegion(finalDestination, sp, true); + } + + // May need to logout or other cleanup + AgentHasMovedAway(sp, logout); + + // Well, this is it. The agent is over there. + KillEntity(sp.Scene, sp.LocalId); + + // Now let's make it officially a child agent + sp.MakeChildAgent(); + +// sp.Scene.CleanDroppedAttachments(); + + // Finally, let's close this previously-known-as-root agent, when the jump is outside the view zone + + if (NeedsClosing(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY, reg)) + { + // We need to delay here because Imprudence viewers, unlike v1 or v3, have a short (<200ms, <500ms) delay before + // they regard the new region as the current region after receiving the AgentMovementComplete + // response. If close is sent before then, it will cause the viewer to quit instead. + // + // This sleep can be increased if necessary. However, whilst it's active, + // an agent cannot teleport back to this region if it has teleported away. + Thread.Sleep(2000); + + sp.Close(); + sp.Scene.IncomingCloseAgent(sp.UUID); + } + else + { + // now we have a child agent in this region. + sp.Reset(); + } + + // REFACTORING PROBLEM. Well, not a problem, but this method is HORRIBLE! + if (sp.Scene.NeedSceneCacheClear(sp.UUID)) + { + m_log.DebugFormat( + "[ENTITY TRANSFER MODULE]: User {0} is going to another region, profile cache removed", + sp.UUID); + } + + ResetFromTransit(sp.UUID); } protected virtual void Fail(ScenePresence sp, GridRegion finalDestination, bool logout) @@ -652,7 +695,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer EnableChildAgents(sp); // Finally, kill the agent we just created at the destination. - m_aScene.SimulationService.CloseAgent(finalDestination, sp.UUID); + m_scene.SimulationService.CloseAgent(finalDestination, sp.UUID); sp.Scene.EventManager.TriggerTeleportFail(sp.ControllingClient, logout); } @@ -660,7 +703,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer protected virtual bool CreateAgent(ScenePresence sp, GridRegion reg, GridRegion finalDestination, AgentCircuitData agentCircuit, uint teleportFlags, out string reason, out bool logout) { logout = false; - bool success = m_aScene.SimulationService.CreateAgent(finalDestination, agentCircuit, teleportFlags, out reason); + bool success = m_scene.SimulationService.CreateAgent(finalDestination, agentCircuit, teleportFlags, out reason); if (success) sp.Scene.EventManager.TriggerTeleportStart(sp.ControllingClient, reg, finalDestination, teleportFlags, logout); @@ -670,7 +713,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer protected virtual bool UpdateAgent(GridRegion reg, GridRegion finalDestination, AgentData agent) { - return m_aScene.SimulationService.UpdateAgent(finalDestination, agent); + return m_scene.SimulationService.UpdateAgent(finalDestination, agent); } protected virtual void SetCallbackURL(AgentData agent, RegionInfo region) @@ -722,7 +765,6 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer return false; } - #endregion #region Landmark Teleport @@ -734,7 +776,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer /// public virtual void RequestTeleportLandmark(IClientAPI remoteClient, AssetLandmark lm) { - GridRegion info = m_aScene.GridService.GetRegionByUUID(UUID.Zero, lm.RegionID); + GridRegion info = m_scene.GridService.GetRegionByUUID(UUID.Zero, lm.RegionID); if (info == null) { @@ -760,8 +802,8 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer m_log.DebugFormat( "[ENTITY TRANSFER MODULE]: Request to teleport {0} {1} home", client.Name, client.AgentId); - //OpenSim.Services.Interfaces.PresenceInfo pinfo = m_aScene.PresenceService.GetAgent(client.SessionId); - GridUserInfo uinfo = m_aScene.GridUserService.GetGridUserInfo(client.AgentId.ToString()); + //OpenSim.Services.Interfaces.PresenceInfo pinfo = m_scene.PresenceService.GetAgent(client.SessionId); + GridUserInfo uinfo = m_scene.GridUserService.GetGridUserInfo(client.AgentId.ToString()); if (uinfo != null) { @@ -771,7 +813,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer client.SendTeleportFailed("You don't have a home position set."); return false; } - GridRegion regionInfo = m_aScene.GridService.GetRegionByUUID(UUID.Zero, uinfo.HomeRegionID); + GridRegion regionInfo = m_scene.GridService.GetRegionByUUID(UUID.Zero, uinfo.HomeRegionID); if (regionInfo == null) { // can't find the Home region: Tell viewer and abort @@ -1016,107 +1058,123 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer ScenePresence agent, Vector3 pos, uint neighbourx, uint neighboury, GridRegion neighbourRegion, bool isFlying, string version) { + if (neighbourRegion == null) + return agent; + try { + SetInTransit(agent.UUID); + ulong neighbourHandle = Utils.UIntsToLong((uint)(neighbourx * Constants.RegionSize), (uint)(neighboury * Constants.RegionSize)); - m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Crossing agent {0} {1} to {2}-{3} running version {4}", agent.Firstname, agent.Lastname, neighbourx, neighboury, version); + m_log.DebugFormat( + "[ENTITY TRANSFER MODULE]: Crossing agent {0} {1} to {2}-{3} running version {4}", + agent.Firstname, agent.Lastname, neighbourx, neighboury, version); Scene m_scene = agent.Scene; - - if (neighbourRegion != null) + + if (!agent.ValidateAttachments()) + m_log.DebugFormat( + "[ENTITY TRANSFER MODULE]: Failed validation of all attachments for region crossing of {0} from {1} to {2}. Continuing.", + agent.Name, agent.Scene.RegionInfo.RegionName, neighbourRegion.RegionName); + + pos = pos + agent.Velocity; + Vector3 vel2 = new Vector3(agent.Velocity.X, agent.Velocity.Y, 0); + + agent.RemoveFromPhysicalScene(); + + AgentData cAgent = new AgentData(); + agent.CopyTo(cAgent); + cAgent.Position = pos; + if (isFlying) + cAgent.ControlFlags |= (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY; + + // We don't need the callback anymnore + cAgent.CallbackURI = String.Empty; + + // Beyond this point, extra cleanup is needed beyond removing transit state + UpdateInTransit(agent.UUID, AgentTransferState.Transferring); + + if (!m_scene.SimulationService.UpdateAgent(neighbourRegion, cAgent)) { - if (!agent.ValidateAttachments()) - m_log.DebugFormat( - "[ENTITY TRANSFER MODULE]: Failed validation of all attachments for region crossing of {0} from {1} to {2}. Continuing.", - agent.Name, agent.Scene.RegionInfo.RegionName, neighbourRegion.RegionName); + // region doesn't take it + UpdateInTransit(agent.UUID, AgentTransferState.CleaningUp); - pos = pos + agent.Velocity; - Vector3 vel2 = new Vector3(agent.Velocity.X, agent.Velocity.Y, 0); - - agent.RemoveFromPhysicalScene(); - SetInTransit(agent.UUID); - - AgentData cAgent = new AgentData(); - agent.CopyTo(cAgent); - cAgent.Position = pos; - if (isFlying) - cAgent.ControlFlags |= (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY; - - // We don't need the callback anymnore - cAgent.CallbackURI = String.Empty; - - if (!m_scene.SimulationService.UpdateAgent(neighbourRegion, cAgent)) - { - // region doesn't take it - ReInstantiateScripts(agent); - agent.AddToPhysicalScene(isFlying); - ResetFromTransit(agent.UUID); - return agent; - } - - //AgentCircuitData circuitdata = m_controllingClient.RequestClientInfo(); - agent.ControllingClient.RequestClientInfo(); - - //m_log.Debug("BEFORE CROSS"); - //Scene.DumpChildrenSeeds(UUID); - //DumpKnownRegions(); - string agentcaps; - if (!agent.KnownRegions.TryGetValue(neighbourRegion.RegionHandle, out agentcaps)) - { - m_log.ErrorFormat("[ENTITY TRANSFER MODULE]: No ENTITY TRANSFER MODULE information for region handle {0}, exiting CrossToNewRegion.", - neighbourRegion.RegionHandle); - return agent; - } - // No turning back - agent.IsChildAgent = true; - - string capsPath = neighbourRegion.ServerURI + CapsUtil.GetCapsSeedPath(agentcaps); - - m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Sending new CAPS seed url {0} to client {1}", capsPath, agent.UUID); - - IEventQueue eq = agent.Scene.RequestModuleInterface(); - if (eq != null) - { - eq.CrossRegion(neighbourHandle, pos, vel2 /* agent.Velocity */, neighbourRegion.ExternalEndPoint, - capsPath, agent.UUID, agent.ControllingClient.SessionId); - } - else - { - agent.ControllingClient.CrossRegion(neighbourHandle, pos, agent.Velocity, neighbourRegion.ExternalEndPoint, - capsPath); - } - - // SUCCESS! - agent.MakeChildAgent(); + ReInstantiateScripts(agent); + agent.AddToPhysicalScene(isFlying); ResetFromTransit(agent.UUID); - // now we have a child agent in this region. Request all interesting data about other (root) agents - agent.SendOtherAgentsAvatarDataToMe(); - agent.SendOtherAgentsAppearanceToMe(); + return agent; + } - // Backwards compatibility. Best effort - if (version == "Unknown" || version == string.Empty) - { - m_log.DebugFormat("[ENTITY TRANSFER MODULE]: neighbor with old version, passing attachments one by one..."); - Thread.Sleep(3000); // wait a little now that we're not waiting for the callback - CrossAttachmentsIntoNewRegion(neighbourRegion, agent, true); - } + //AgentCircuitData circuitdata = m_controllingClient.RequestClientInfo(); + agent.ControllingClient.RequestClientInfo(); + //m_log.Debug("BEFORE CROSS"); + //Scene.DumpChildrenSeeds(UUID); + //DumpKnownRegions(); + string agentcaps; + if (!agent.KnownRegions.TryGetValue(neighbourRegion.RegionHandle, out agentcaps)) + { + m_log.ErrorFormat("[ENTITY TRANSFER MODULE]: No ENTITY TRANSFER MODULE information for region handle {0}, exiting CrossToNewRegion.", + neighbourRegion.RegionHandle); + return agent; + } + // No turning back + agent.IsChildAgent = true; - // Next, let's close the child agent connections that are too far away. - agent.CloseChildAgents(neighbourx, neighboury); - - AgentHasMovedAway(agent, false); - - // the user may change their profile information in other region, - // so the userinfo in UserProfileCache is not reliable any more, delete it - // REFACTORING PROBLEM. Well, not a problem, but this method is HORRIBLE! - if (agent.Scene.NeedSceneCacheClear(agent.UUID)) - { - m_log.DebugFormat( - "[ENTITY TRANSFER MODULE]: User {0} is going to another region", agent.UUID); - } + string capsPath = neighbourRegion.ServerURI + CapsUtil.GetCapsSeedPath(agentcaps); + + m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Sending new CAPS seed url {0} to client {1}", capsPath, agent.UUID); + + if (m_eqModule != null) + { + m_eqModule.CrossRegion( + neighbourHandle, pos, vel2 /* agent.Velocity */, neighbourRegion.ExternalEndPoint, + capsPath, agent.UUID, agent.ControllingClient.SessionId); + } + else + { + agent.ControllingClient.CrossRegion(neighbourHandle, pos, agent.Velocity, neighbourRegion.ExternalEndPoint, + capsPath); + } + + // SUCCESS! + UpdateInTransit(agent.UUID, AgentTransferState.ReceivedAtDestination); + + // Unlike a teleport, here we do not wait for the destination region to confirm the receipt. + UpdateInTransit(agent.UUID, AgentTransferState.CleaningUp); + + agent.MakeChildAgent(); + + // FIXME: Possibly this should occur lower down after other commands to close other agents, + // but not sure yet what the side effects would be. + ResetFromTransit(agent.UUID); + + // now we have a child agent in this region. Request all interesting data about other (root) agents + agent.SendOtherAgentsAvatarDataToMe(); + agent.SendOtherAgentsAppearanceToMe(); + + // Backwards compatibility. Best effort + if (version == "Unknown" || version == string.Empty) + { + m_log.DebugFormat("[ENTITY TRANSFER MODULE]: neighbor with old version, passing attachments one by one..."); + Thread.Sleep(3000); // wait a little now that we're not waiting for the callback + CrossAttachmentsIntoNewRegion(neighbourRegion, agent, true); + } + + // Next, let's close the child agent connections that are too far away. + agent.CloseChildAgents(neighbourx, neighboury); + + AgentHasMovedAway(agent, false); + + // the user may change their profile information in other region, + // so the userinfo in UserProfileCache is not reliable any more, delete it + // REFACTORING PROBLEM. Well, not a problem, but this method is HORRIBLE! + if (agent.Scene.NeedSceneCacheClear(agent.UUID)) + { + m_log.DebugFormat( + "[ENTITY TRANSFER MODULE]: User {0} is going to another region", agent.UUID); } //m_log.Debug("AFTER CROSS"); @@ -1128,11 +1186,13 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer m_log.ErrorFormat( "[ENTITY TRANSFER MODULE]: Problem crossing user {0} to new region {1} from {2}. Exception {3}{4}", agent.Name, neighbourRegion.RegionName, agent.Scene.RegionInfo.RegionName, e.Message, e.StackTrace); + + // TODO: Might be worth attempting other restoration here such as reinstantiation of scripts, etc. } return agent; } - + private void CrossAgentToNewRegionCompleted(IAsyncResult iar) { CrossAgentToNewRegionDelegate icon = (CrossAgentToNewRegionDelegate)iar.AsyncState; @@ -1431,8 +1491,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer if (regionAccepted && newAgent) { - IEventQueue eq = sp.Scene.RequestModuleInterface(); - if (eq != null) + if (m_eqModule != null) { #region IP Translation for NAT IClientIPEndpoint ipepClient; @@ -1446,8 +1505,8 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer "and EstablishAgentCommunication with seed cap {4}", scene.RegionInfo.RegionName, sp.Name, reg.RegionName, reg.RegionHandle, capsPath); - eq.EnableSimulator(reg.RegionHandle, endPoint, sp.UUID); - eq.EstablishAgentCommunication(sp.UUID, endPoint, capsPath); + m_eqModule.EnableSimulator(reg.RegionHandle, endPoint, sp.UUID); + m_eqModule.EstablishAgentCommunication(sp.UUID, endPoint, capsPath); } else { @@ -1573,8 +1632,37 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer #region Agent Arrived public void AgentArrivedAtDestination(UUID id) { - m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Agent {0} released", id); - ResetFromTransit(id); + lock (m_agentsInTransit) + { + if (!m_agentsInTransit.ContainsKey(id)) + { + m_log.WarnFormat( + "[ENTITY TRANSFER MODULE]: Region {0} received notification of arrival in destination scene of agent {1} but no teleport request is active", + m_scene.RegionInfo.RegionName, id); + + return; + } + + AgentTransferState currentState = m_agentsInTransit[id]; + + if (currentState == AgentTransferState.ReceivedAtDestination) + { + // An anomoly but don't make this an outright failure - destination region could be overzealous in sending notification. + m_log.WarnFormat( + "[ENTITY TRANSFER MODULE]: Region {0} received notification of arrival in destination scene of agent {1} but notification has already previously been received", + m_scene.RegionInfo.RegionName, id); + } + else if (currentState != AgentTransferState.Transferring) + { + m_log.ErrorFormat( + "[ENTITY TRANSFER MODULE]: Region {0} received notification of arrival in destination scene of agent {1} but agent is in transfer state {2}", + m_scene.RegionInfo.RegionName, id, currentState); + + return; + } + + m_agentsInTransit[id] = AgentTransferState.ReceivedAtDestination; + } } #endregion @@ -1845,8 +1933,8 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer //// And the new channel... //if (m_interregionCommsOut != null) // successYN = m_interregionCommsOut.SendCreateObject(newRegionHandle, grp, true); - if (m_aScene.SimulationService != null) - successYN = m_aScene.SimulationService.CreateObject(destination, newPosition, grp, true); + if (m_scene.SimulationService != null) + successYN = m_scene.SimulationService.CreateObject(destination, newPosition, grp, true); if (successYN) { @@ -1925,10 +2013,29 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer #region Misc - protected bool WaitForCallback(UUID id) + private bool WaitForCallback(UUID id) { + lock (m_agentsInTransit) + { + if (!IsInTransit(id)) + throw new Exception( + string.Format( + "Asked to wait for destination callback for agent with ID {0} but it is not in transit")); + + AgentTransferState currentState = m_agentsInTransit[id]; + + if (currentState != AgentTransferState.Transferring && currentState != AgentTransferState.ReceivedAtDestination) + throw new Exception( + string.Format( + "Asked to wait for destination callback for agent with ID {0} but it is in state {1}", + currentState)); + } + int count = 200; - while (m_agentsInTransit.Contains(id) && count-- > 0) + + // There should be no race condition here since no other code should be removing the agent transfer or + // changing the state to another other than Transferring => ReceivedAtDestination. + while (m_agentsInTransit[id] != AgentTransferState.ReceivedAtDestination && count-- > 0) { // m_log.Debug(" >>> Waiting... " + count); Thread.Sleep(100); @@ -1938,17 +2045,17 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer } /// - /// Set that an agent is in the process of being teleported. + /// Set that an agent is in transit. /// /// The ID of the agent being teleported /// true if the agent was not already in transit, false if it was - protected bool SetInTransit(UUID id) + private bool SetInTransit(UUID id) { lock (m_agentsInTransit) { - if (!m_agentsInTransit.Contains(id)) + if (!m_agentsInTransit.ContainsKey(id)) { - m_agentsInTransit.Add(id); + m_agentsInTransit[id] = AgentTransferState.Preparing; return true; } } @@ -1957,34 +2064,87 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer } /// - /// Show whether the given agent is being teleported. - /// - /// true if the agent is in the process of being teleported, false otherwise. - /// The agent ID - protected bool IsInTransit(UUID id) - { - lock (m_agentsInTransit) - return m_agentsInTransit.Contains(id); - } - - /// - /// Set that an agent is no longer being teleported. + /// Updates the state of an agent that is already in transit. /// + /// + /// /// - /// - /// true if the agent was flagged as being teleported when this method was called, false otherwise - /// - protected bool ResetFromTransit(UUID id) + /// Illegal transitions will throw an Exception + private void UpdateInTransit(UUID id, AgentTransferState newState) { lock (m_agentsInTransit) { - if (m_agentsInTransit.Contains(id)) + // Illegal to try and update an agent that's not actually in transit. + if (!m_agentsInTransit.ContainsKey(id)) + throw new Exception(string.Format("Agent with ID {0} is not registered as in transit", id)); + + AgentTransferState oldState = m_agentsInTransit[id]; + + bool transitionOkay = false; + + if (newState == AgentTransferState.CleaningUp && oldState != AgentTransferState.CleaningUp) + transitionOkay = true; + else if (newState == AgentTransferState.Transferring && oldState == AgentTransferState.Preparing) + transitionOkay = true; + else if (newState == AgentTransferState.ReceivedAtDestination && oldState == AgentTransferState.Transferring) + transitionOkay = true; + + if (transitionOkay) + m_agentsInTransit[id] = newState; + else + throw new Exception( + string.Format( + "Agent with ID {0} is not allowed to move from old transit state {1} to new state {2}", + id, oldState, newState)); + } + } + + public bool IsInTransit(UUID id) + { + lock (m_agentsInTransit) + return m_agentsInTransit.ContainsKey(id); + } + + /// + /// Removes an agent from the transit state machine. + /// + /// + /// true if the agent was flagged as being teleported when this method was called, false otherwise + private bool ResetFromTransit(UUID id) + { + lock (m_agentsInTransit) + { + if (m_agentsInTransit.ContainsKey(id)) { + AgentTransferState state = m_agentsInTransit[id]; + + if (state == AgentTransferState.Transferring || state == AgentTransferState.ReceivedAtDestination) + { + // FIXME: For now, we allow exit from any state since a thrown exception in teleport is now guranteed + // to be handled properly - ResetFromTransit() could be invoked at any step along the process + m_log.WarnFormat( + "[ENTITY TRANSFER MODULE]: Agent with ID should not exit directly from state {1}, should go to {2} state first", + state, AgentTransferState.CleaningUp); + +// throw new Exception( +// "Agent with ID {0} cannot exit directly from state {1}, it must go to {2} state first", +// state, AgentTransferState.CleaningUp); + } + m_agentsInTransit.Remove(id); + + m_log.DebugFormat( + "[ENTITY TRANSFER MODULE]: Agent {0} cleared from transit in {1}", + id, m_scene.RegionInfo.RegionName); + return true; } } + m_log.WarnFormat( + "[ENTITY TRANSFER MODULE]: Agent {0} requested to clear from transit in {1} but was already cleared.", + id, m_scene.RegionInfo.RegionName); + return false; } @@ -2015,4 +2175,4 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer #endregion } -} \ No newline at end of file +} diff --git a/OpenSim/Region/CoreModules/Framework/EntityTransfer/HGEntityTransferModule.cs b/OpenSim/Region/CoreModules/Framework/EntityTransfer/HGEntityTransferModule.cs index 6e27299ef0..44ea2b1996 100644 --- a/OpenSim/Region/CoreModules/Framework/EntityTransfer/HGEntityTransferModule.cs +++ b/OpenSim/Region/CoreModules/Framework/EntityTransfer/HGEntityTransferModule.cs @@ -45,11 +45,11 @@ using Nini.Config; namespace OpenSim.Region.CoreModules.Framework.EntityTransfer { - public class HGEntityTransferModule : EntityTransferModule, ISharedRegionModule, IEntityTransferModule, IUserAgentVerificationModule + public class HGEntityTransferModule + : EntityTransferModule, INonSharedRegionModule, IEntityTransferModule, IUserAgentVerificationModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - private bool m_Initialized = false; private int m_levelHGTeleport = 0; private GatekeeperServiceConnector m_GatekeeperConnector; @@ -64,6 +64,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer public override void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; + if (moduleConfig != null) { string name = moduleConfig.GetString("EntityTransferModule", ""); @@ -82,10 +83,9 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer public override void AddRegion(Scene scene) { base.AddRegion(scene); + if (m_Enabled) - { scene.RegisterModuleInterface(this); - } } protected override void OnNewClient(IClientAPI client) @@ -98,24 +98,18 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer public override void RegionLoaded(Scene scene) { base.RegionLoaded(scene); + if (m_Enabled) - if (!m_Initialized) - { - m_GatekeeperConnector = new GatekeeperServiceConnector(scene.AssetService); - m_Initialized = true; - - } - + m_GatekeeperConnector = new GatekeeperServiceConnector(scene.AssetService); } + public override void RemoveRegion(Scene scene) { base.AddRegion(scene); - if (m_Enabled) - { - scene.UnregisterModuleInterface(this); - } - } + if (m_Enabled) + scene.UnregisterModuleInterface(this); + } #endregion @@ -123,8 +117,9 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer protected override GridRegion GetFinalDestination(GridRegion region) { - int flags = m_aScene.GridService.GetRegionFlags(m_aScene.RegionInfo.ScopeID, region.RegionID); + int flags = m_scene.GridService.GetRegionFlags(m_scene.RegionInfo.ScopeID, region.RegionID); m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: region {0} flags: {1}", region.RegionID, flags); + if ((flags & (int)OpenSim.Data.RegionFlags.Hyperlink) != 0) { m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Destination region {0} is hyperlink", region.RegionID); @@ -135,6 +130,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer m_log.WarnFormat("[HG ENTITY TRANSFER MODULE]: GetHyperlinkRegion to Gatekeeper {0} failed", region.ServerURI); return real_destination; } + return region; } @@ -143,7 +139,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer if (base.NeedsClosing(drawdist, oldRegionX, newRegionX, oldRegionY, newRegionY, reg)) return true; - int flags = m_aScene.GridService.GetRegionFlags(m_aScene.RegionInfo.ScopeID, reg.RegionID); + int flags = m_scene.GridService.GetRegionFlags(m_scene.RegionInfo.ScopeID, reg.RegionID); if (flags == -1 /* no region in DB */ || (flags & (int)OpenSim.Data.RegionFlags.Hyperlink) != 0) return true; @@ -156,7 +152,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer if (logout) { // Log them out of this grid - m_aScene.PresenceService.LogoutAgent(sp.ControllingClient.SessionId); + m_scene.PresenceService.LogoutAgent(sp.ControllingClient.SessionId); } } @@ -165,7 +161,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: CreateAgent {0} {1}", reg.ServerURI, finalDestination.ServerURI); reason = string.Empty; logout = false; - int flags = m_aScene.GridService.GetRegionFlags(m_aScene.RegionInfo.ScopeID, reg.RegionID); + int flags = m_scene.GridService.GetRegionFlags(m_scene.RegionInfo.ScopeID, reg.RegionID); if (flags == -1 /* no region in DB */ || (flags & (int)OpenSim.Data.RegionFlags.Hyperlink) != 0) { // this user is going to another grid @@ -210,7 +206,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer "[ENTITY TRANSFER MODULE]: Request to teleport {0} {1} home", client.Name, client.AgentId); // Let's find out if this is a foreign user or a local user - IUserManagement uMan = m_aScene.RequestModuleInterface(); + IUserManagement uMan = m_scene.RequestModuleInterface(); if (uMan != null && uMan.IsLocalGridUser(id)) { // local grid user @@ -265,19 +261,21 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer { m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Teleporting agent via landmark to {0} region {1} position {2}", (lm.Gatekeeper == string.Empty) ? "local" : lm.Gatekeeper, lm.RegionID, lm.Position); + if (lm.Gatekeeper == string.Empty) { base.RequestTeleportLandmark(remoteClient, lm); return; } - GridRegion info = m_aScene.GridService.GetRegionByUUID(UUID.Zero, lm.RegionID); + GridRegion info = m_scene.GridService.GetRegionByUUID(UUID.Zero, lm.RegionID); // Local region? if (info != null) { ((Scene)(remoteClient.Scene)).RequestTeleportLocation(remoteClient, info.RegionHandle, lm.Position, Vector3.Zero, (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaLandmark)); + return; } else @@ -288,6 +286,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer GridRegion gatekeeper = new GridRegion(); gatekeeper.ServerURI = lm.Gatekeeper; GridRegion finalDestination = gConn.GetHyperlinkRegion(gatekeeper, new UUID(lm.RegionID)); + if (finalDestination != null) { ScenePresence sp = scene.GetScenePresence(remoteClient.AgentId); @@ -317,8 +316,12 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer IUserAgentService security = new UserAgentServiceConnector(url); return security.VerifyClient(aCircuit.SessionID, token); } - else - m_log.DebugFormat("[HG ENTITY TRANSFER MODULE]: Agent {0} {1} does not have a HomeURI OH NO!", aCircuit.firstname, aCircuit.lastname); + else + { + m_log.DebugFormat( + "[HG ENTITY TRANSFER MODULE]: Agent {0} {1} does not have a HomeURI OH NO!", + aCircuit.firstname, aCircuit.lastname); + } return false; } @@ -335,8 +338,8 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer } // Let's find out if this is a foreign user or a local user - IUserManagement uMan = m_aScene.RequestModuleInterface(); - UserAccount account = m_aScene.UserAccountService.GetUserAccount(m_aScene.RegionInfo.ScopeID, obj.AgentId); + IUserManagement uMan = m_scene.RequestModuleInterface(); +// UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, obj.AgentId); if (uMan != null && uMan.IsLocalGridUser(obj.AgentId)) { // local grid user @@ -359,7 +362,6 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer #endregion - private GridRegion MakeRegion(AgentCircuitData aCircuit) { GridRegion region = new GridRegion(); @@ -376,6 +378,5 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer region.InternalEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("0.0.0.0"), (int)0); return region; } - } -} +} \ No newline at end of file diff --git a/OpenSim/Region/CoreModules/Framework/InventoryAccess/HGInventoryAccessModule.cs b/OpenSim/Region/CoreModules/Framework/InventoryAccess/HGInventoryAccessModule.cs index a71584a91b..cf72b58832 100644 --- a/OpenSim/Region/CoreModules/Framework/InventoryAccess/HGInventoryAccessModule.cs +++ b/OpenSim/Region/CoreModules/Framework/InventoryAccess/HGInventoryAccessModule.cs @@ -364,8 +364,7 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess { m_log.DebugFormat("[HG INVENTORY ACCESS MODULE]: Changing root inventory for user {0}", client.Name); InventoryCollection content = m_Scene.InventoryService.GetFolderContent(client.AgentId, root.ID); - List fids = new List(); - List iids = new List(); + List keep = new List(); foreach (InventoryFolderBase f in content.Folders) @@ -395,4 +394,4 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess #endregion } -} +} \ No newline at end of file diff --git a/OpenSim/Region/CoreModules/Framework/InventoryAccess/InventoryAccessModule.cs b/OpenSim/Region/CoreModules/Framework/InventoryAccess/InventoryAccessModule.cs index ee9961f831..31820e0fa5 100644 --- a/OpenSim/Region/CoreModules/Framework/InventoryAccess/InventoryAccessModule.cs +++ b/OpenSim/Region/CoreModules/Framework/InventoryAccess/InventoryAccessModule.cs @@ -175,7 +175,7 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess sbyte assetType, byte wearableType, uint nextOwnerMask, int creationDate) { - m_log.DebugFormat("[AGENT INVENTORY]: Received request to create inventory item {0} in folder {1}", name, folderID); + m_log.DebugFormat("[INVENTORY ACCESS MODULE]: Received request to create inventory item {0} in folder {1}", name, folderID); if (!m_Scene.Permissions.CanCreateUserInventory(invType, remoteClient.AgentId)) return; @@ -210,7 +210,7 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess else { m_log.ErrorFormat( - "ScenePresence for agent uuid {0} unexpectedly not found in CreateNewInventoryItem", + "[INVENTORY ACCESS MODULE]: ScenePresence for agent uuid {0} unexpectedly not found in CreateNewInventoryItem", remoteClient.AgentId); } } @@ -288,16 +288,19 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess else { m_log.ErrorFormat( - "[AGENT INVENTORY]: Could not find item {0} for caps inventory update", + "[INVENTORY ACCESS MODULE]: Could not find item {0} for caps inventory update", itemID); } return UUID.Zero; } - public virtual UUID CopyToInventory(DeRezAction action, UUID folderID, - List objectGroups, IClientAPI remoteClient) + public virtual List CopyToInventory( + DeRezAction action, UUID folderID, + List objectGroups, IClientAPI remoteClient, bool asAttachment) { + List copiedItems = new List(); + Dictionary> bundlesToCopy = new Dictionary>(); if (CoalesceMultipleObjectsToInventory) @@ -324,16 +327,16 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess } } - // This is method scoped and will be returned. It will be the - // last created asset id - UUID assetID = UUID.Zero; +// m_log.DebugFormat( +// "[INVENTORY ACCESS MODULE]: Copying {0} object bundles to folder {1} action {2} for {3}", +// bundlesToCopy.Count, folderID, action, remoteClient.Name); // Each iteration is really a separate asset being created, // with distinct destinations as well. foreach (List bundle in bundlesToCopy.Values) - assetID = CopyBundleToInventory(action, folderID, bundle, remoteClient); + copiedItems.Add(CopyBundleToInventory(action, folderID, bundle, remoteClient, asAttachment)); - return assetID; + return copiedItems; } /// @@ -344,12 +347,13 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess /// /// /// - /// - protected UUID CopyBundleToInventory( - DeRezAction action, UUID folderID, List objlist, IClientAPI remoteClient) + /// Should be true if the bundle is being copied as an attachment. This prevents + /// attempted serialization of any script state which would abort any operating scripts. + /// The inventory item created by the copy + protected InventoryItemBase CopyBundleToInventory( + DeRezAction action, UUID folderID, List objlist, IClientAPI remoteClient, + bool asAttachment) { - UUID assetID = UUID.Zero; - CoalescedSceneObjects coa = new CoalescedSceneObjects(UUID.Zero); Dictionary originalPositions = new Dictionary(); @@ -401,18 +405,27 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess string itemXml; + // If we're being called from a script, then trying to serialize that same script's state will not complete + // in any reasonable time period. Therefore, we'll avoid it. The worst that can happen is that if + // the client/server crashes rather than logging out normally, the attachment's scripts will resume + // without state on relog. Arguably, this is what we want anyway. if (objlist.Count > 1) - itemXml = CoalescedSceneObjectsSerializer.ToXml(coa); + itemXml = CoalescedSceneObjectsSerializer.ToXml(coa, !asAttachment); else - itemXml = SceneObjectSerializer.ToOriginalXmlFormat(objlist[0]); + itemXml = SceneObjectSerializer.ToOriginalXmlFormat(objlist[0], !asAttachment); // Restore the position of each group now that it has been stored to inventory. foreach (SceneObjectGroup objectGroup in objlist) objectGroup.AbsolutePosition = originalPositions[objectGroup.UUID]; InventoryItemBase item = CreateItemForObject(action, remoteClient, objlist[0], folderID); + +// m_log.DebugFormat( +// "[INVENTORY ACCESS MODULE]: Created item is {0}", +// item != null ? item.ID.ToString() : "NULL"); + if (item == null) - return UUID.Zero; + return null; // Can't know creator is the same, so null it in inventory if (objlist.Count > 1) @@ -422,7 +435,8 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess } else { - item.CreatorId = objlist[0].RootPart.CreatorID.ToString(); + item.CreatorId = objlist[0].RootPart.CreatorID.ToString(); + item.CreatorData = objlist[0].RootPart.CreatorData; item.SaleType = objlist[0].RootPart.ObjectSaleType; item.SalePrice = objlist[0].RootPart.SalePrice; } @@ -435,8 +449,7 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess objlist[0].OwnerID.ToString()); m_Scene.AssetService.Store(asset); - item.AssetID = asset.FullID; - assetID = asset.FullID; + item.AssetID = asset.FullID; if (DeRezAction.SaveToExistingUserInventoryItem == action) { @@ -469,9 +482,9 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess // This is a hook to do some per-asset post-processing for subclasses that need that if (remoteClient != null) - ExportAsset(remoteClient.AgentId, assetID); + ExportAsset(remoteClient.AgentId, asset.FullID); - return assetID; + return item; } protected virtual void ExportAsset(UUID agentID, UUID assetID) @@ -617,7 +630,7 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess if (null == item) { m_log.DebugFormat( - "[AGENT INVENTORY]: Object {0} {1} scheduled for save to inventory has already been deleted.", + "[INVENTORY ACCESS MODULE]: Object {0} {1} scheduled for save to inventory has already been deleted.", so.Name, so.UUID); return null; @@ -668,7 +681,6 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess { // Catch all. Use lost & found // - folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.LostAndFoundFolder); } } @@ -718,7 +730,6 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess if (item == null) { - return null; } @@ -748,7 +759,7 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess else { m_log.WarnFormat( - "[InventoryAccessModule]: Could not find asset {0} for {1} in RezObject()", + "[INVENTORY ACCESS MODULE]: Could not find asset {0} for {1} in RezObject()", assetID, remoteClient.Name); } @@ -859,7 +870,7 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess SceneObjectPart rootPart = group.RootPart; // m_log.DebugFormat( -// "[InventoryAccessModule]: Preparing to rez {0} {1} {2} ownermask={3:X} nextownermask={4:X} groupmask={5:X} everyonemask={6:X} for {7}", +// "[INVENTORY ACCESS MODULE]: Preparing to rez {0} {1} {2} ownermask={3:X} nextownermask={4:X} groupmask={5:X} everyonemask={6:X} for {7}", // group.Name, group.LocalId, group.UUID, // group.RootPart.OwnerMask, group.RootPart.NextOwnerMask, group.RootPart.GroupMask, group.RootPart.EveryoneMask, // remoteClient.Name); @@ -867,7 +878,7 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess // Vector3 storedPosition = group.AbsolutePosition; if (group.UUID == UUID.Zero) { - m_log.Debug("[InventoryAccessModule]: Object has UUID.Zero! Position 3"); + m_log.Debug("[INVENTORY ACCESS MODULE]: Object has UUID.Zero! Position 3"); } foreach (SceneObjectPart part in group.Parts) @@ -928,7 +939,7 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess } // m_log.DebugFormat( -// "[InventoryAccessModule]: Rezzed {0} {1} {2} ownermask={3:X} nextownermask={4:X} groupmask={5:X} everyonemask={6:X} for {7}", +// "[INVENTORY ACCESS MODULE]: Rezzed {0} {1} {2} ownermask={3:X} nextownermask={4:X} groupmask={5:X} everyonemask={6:X} for {7}", // group.Name, group.LocalId, group.UUID, // group.RootPart.OwnerMask, group.RootPart.NextOwnerMask, group.RootPart.GroupMask, group.RootPart.EveryoneMask, // remoteClient.Name); @@ -1023,8 +1034,9 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess so.FromFolderID = item.Folder; -// Console.WriteLine("rootPart.OwnedID {0}, item.Owner {1}, item.CurrentPermissions {2:X}", -// rootPart.OwnerID, item.Owner, item.CurrentPermissions); +// m_log.DebugFormat( +// "[INVENTORY ACCESS MODULE]: rootPart.OwnedID {0}, item.Owner {1}, item.CurrentPermissions {2:X}", +// rootPart.OwnerID, item.Owner, item.CurrentPermissions); if ((rootPart.OwnerID != item.Owner) || (item.CurrentPermissions & 16) != 0 || @@ -1160,7 +1172,7 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess if (assetRequestItem.AssetID != requestID) { m_log.WarnFormat( - "[CLIENT]: {0} requested asset {1} from item {2} but this does not match item's asset {3}", + "[INVENTORY ACCESS MODULE]: {0} requested asset {1} from item {2} but this does not match item's asset {3}", Name, requestID, itemID, assetRequestItem.AssetID); return false; diff --git a/OpenSim/Region/CoreModules/LightShare/EnvironmentModule.cs b/OpenSim/Region/CoreModules/LightShare/EnvironmentModule.cs new file mode 100644 index 0000000000..1526886d7a --- /dev/null +++ b/OpenSim/Region/CoreModules/LightShare/EnvironmentModule.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.Reflection; +using OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Framework.Capabilities; +using OpenSim.Framework.Servers.HttpServer; +using OpenSim.Region.Framework.Interfaces; +using OpenSim.Region.Framework.Scenes; +using log4net; +using Nini.Config; +using Mono.Addins; + +using Caps = OpenSim.Framework.Capabilities.Caps; + + +namespace OpenSim.Region.CoreModules.World.LightShare +{ + [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "EnvironmentModule")] + + public class EnvironmentModule : INonSharedRegionModule, IEnvironmentModule + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + private Scene m_scene = null; + private UUID regionID = UUID.Zero; + private static bool Enabled = false; + + private static readonly string capsName = "EnvironmentSettings"; + private static readonly string capsBase = "/CAPS/0020/"; + + private LLSDEnvironmentSetResponse setResponse = null; + + #region INonSharedRegionModule + public void Initialise(IConfigSource source) + { + IConfig config = source.Configs["ClientStack.LindenCaps"]; + + if (null == config) + return; + + if (config.GetString("Cap_EnvironmentSettings", String.Empty) != "localhost") + { + m_log.InfoFormat("[{0}]: Module is disabled.", Name); + return; + } + + Enabled = true; + + m_log.InfoFormat("[{0}]: Module is enabled.", Name); + } + + public void Close() + { + } + + public string Name + { + get { return "EnvironmentModule"; } + } + + public Type ReplaceableInterface + { + get { return null; } + } + + public void AddRegion(Scene scene) + { + if (!Enabled) + return; + + scene.RegisterModuleInterface(this); + m_scene = scene; + regionID = scene.RegionInfo.RegionID; + } + + public void RegionLoaded(Scene scene) + { + if (!Enabled) + return; + + setResponse = new LLSDEnvironmentSetResponse(); + scene.EventManager.OnRegisterCaps += OnRegisterCaps; + } + + public void RemoveRegion(Scene scene) + { + if (Enabled) + return; + + scene.EventManager.OnRegisterCaps -= OnRegisterCaps; + m_scene = null; + } + #endregion + + #region IEnvironmentModule + public void ResetEnvironmentSettings(UUID regionUUID) + { + if (!Enabled) + return; + + m_scene.SimulationDataService.RemoveRegionEnvironmentSettings(regionUUID); + } + #endregion + + #region Events + private void OnRegisterCaps(UUID agentID, Caps caps) + { +// m_log.DebugFormat("[{0}]: Register capability for agentID {1} in region {2}", +// Name, agentID, caps.RegionName); + + string capsPath = capsBase + UUID.Random(); + + // Get handler + caps.RegisterHandler( + capsName, + new RestStreamHandler( + "GET", + capsPath, + (request, path, param, httpRequest, httpResponse) + => GetEnvironmentSettings(request, path, param, agentID, caps), + capsName, + agentID.ToString())); + + // Set handler + caps.HttpListener.AddStreamHandler( + new RestStreamHandler( + "POST", + capsPath, + (request, path, param, httpRequest, httpResponse) + => SetEnvironmentSettings(request, path, param, agentID, caps), + capsName, + agentID.ToString())); + } + #endregion + + private string GetEnvironmentSettings(string request, string path, string param, + UUID agentID, Caps caps) + { +// m_log.DebugFormat("[{0}]: Environment GET handle for agentID {1} in region {2}", +// Name, agentID, caps.RegionName); + + string env = String.Empty; + + try + { + env = m_scene.SimulationDataService.LoadRegionEnvironmentSettings(regionID); + } + catch (Exception e) + { + m_log.ErrorFormat("[{0}]: Unable to load environment settings for region {1}, Exception: {2} - {3}", + Name, caps.RegionName, e.Message, e.StackTrace); + } + + if (String.IsNullOrEmpty(env)) + env = EnvironmentSettings.EmptySettings(UUID.Zero, regionID); + + return env; + } + + private string SetEnvironmentSettings(string request, string path, string param, + UUID agentID, Caps caps) + { + +// m_log.DebugFormat("[{0}]: Environment SET handle from agentID {1} in region {2}", +// Name, agentID, caps.RegionName); + + setResponse.regionID = regionID; + setResponse.success = false; + + if (!m_scene.Permissions.CanIssueEstateCommand(agentID, false)) + { + setResponse.fail_reason = "Insufficient estate permissions, settings has not been saved."; + return LLSDHelpers.SerialiseLLSDReply(setResponse); + } + + try + { + m_scene.SimulationDataService.StoreRegionEnvironmentSettings(regionID, request); + setResponse.success = true; + + m_log.InfoFormat("[{0}]: New Environment settings has been saved from agentID {1} in region {2}", + Name, agentID, caps.RegionName); + } + catch (Exception e) + { + m_log.ErrorFormat("[{0}]: Environment settings has not been saved for region {1}, Exception: {2} - {3}", + Name, caps.RegionName, e.Message, e.StackTrace); + + setResponse.success = false; + setResponse.fail_reason = String.Format("Environment Set for region {0} has failed, settings has not been saved.", caps.RegionName); + } + + return LLSDHelpers.SerialiseLLSDReply(setResponse); + } + } +} + diff --git a/OpenSim/Region/CoreModules/Scripting/LSLHttp/UrlModule.cs b/OpenSim/Region/CoreModules/Scripting/LSLHttp/UrlModule.cs index 199dd1110e..1865ab8bc0 100644 --- a/OpenSim/Region/CoreModules/Scripting/LSLHttp/UrlModule.cs +++ b/OpenSim/Region/CoreModules/Scripting/LSLHttp/UrlModule.cs @@ -85,6 +85,10 @@ namespace OpenSim.Region.CoreModules.Scripting.LSLHttp private IHttpServer m_HttpsServer = null; private string m_ExternalHostNameForLSL = ""; + public string ExternalHostNameForLSL + { + get { return m_ExternalHostNameForLSL; } + } public Type ReplaceableInterface { diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Hypergrid/HypergridServiceInConnectorModule.cs b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Hypergrid/HypergridServiceInConnectorModule.cs index 8df1c7b49c..a7dd0dd4dd 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsIn/Hypergrid/HypergridServiceInConnectorModule.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsIn/Hypergrid/HypergridServiceInConnectorModule.cs @@ -122,7 +122,8 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsIn.Hypergrid ISimulationService simService = scene.RequestModuleInterface(); IFriendsSimConnector friendsConn = scene.RequestModuleInterface(); Object[] args = new Object[] { m_Config }; - IFriendsService friendsService = ServerUtils.LoadPlugin(m_LocalServiceDll, args); +// IFriendsService friendsService = ServerUtils.LoadPlugin(m_LocalServiceDll, args) + ServerUtils.LoadPlugin(m_LocalServiceDll, args); m_HypergridHandler = new GatekeeperServiceInConnector(m_Config, MainServer.Instance, simService); diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Asset/HGAssetBroker.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Asset/HGAssetBroker.cs index 8395f8321d..008465fcc9 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Asset/HGAssetBroker.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Asset/HGAssetBroker.cs @@ -149,7 +149,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset m_aScene = scene; - scene.RegisterModuleInterface(this); + m_aScene.RegisterModuleInterface(this); } public void RemoveRegion(Scene scene) diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Simulation/LocalSimulationConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Simulation/LocalSimulationConnector.cs index de089f3ab5..008992e4b9 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Simulation/LocalSimulationConnector.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Simulation/LocalSimulationConnector.cs @@ -26,6 +26,7 @@ */ using System; using System.Collections.Generic; +using System.Linq; using System.Reflection; using log4net; using Nini.Config; @@ -41,22 +42,20 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation public class LocalSimulationConnectorModule : ISharedRegionModule, ISimulationService { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - // Version of this service + + /// + /// Version of this service + /// private const string m_Version = "SIMULATION/0.1"; - private List m_sceneList = new List(); - - private IEntityTransferModule m_AgentTransferModule; - protected IEntityTransferModule AgentTransferModule - { - get - { - if (m_AgentTransferModule == null) - m_AgentTransferModule = m_sceneList[0].RequestModuleInterface(); - return m_AgentTransferModule; - } - } + /// + /// Map region ID to scene. + /// + private Dictionary m_scenes = new Dictionary(); + /// + /// Is this module enabled? + /// private bool m_ModuleEnabled = false; #region IRegionModule @@ -129,12 +128,14 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation /// public void RemoveScene(Scene scene) { - lock (m_sceneList) + lock (m_scenes) { - if (m_sceneList.Contains(scene)) - { - m_sceneList.Remove(scene); - } + if (m_scenes.ContainsKey(scene.RegionInfo.RegionID)) + m_scenes.Remove(scene.RegionInfo.RegionID); + else + m_log.WarnFormat( + "[LOCAL SIMULATION CONNECTOR]: Tried to remove region {0} but it was not present", + scene.RegionInfo.RegionName); } } @@ -144,13 +145,14 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation /// public void Init(Scene scene) { - if (!m_sceneList.Contains(scene)) + lock (m_scenes) { - lock (m_sceneList) - { - m_sceneList.Add(scene); - } - + if (!m_scenes.ContainsKey(scene.RegionInfo.RegionID)) + m_scenes[scene.RegionInfo.RegionID] = scene; + else + m_log.WarnFormat( + "[LOCAL SIMULATION CONNECTOR]: Tried to add region {0} but it is already present", + scene.RegionInfo.RegionName); } } @@ -158,15 +160,24 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation #region ISimulation - public IScene GetScene(ulong regionhandle) + public IScene GetScene(UUID regionId) { - foreach (Scene s in m_sceneList) + if (m_scenes.ContainsKey(regionId)) { - if (s.RegionInfo.RegionHandle == regionhandle) - return s; + return m_scenes[regionId]; + } + else + { + // FIXME: This was pre-existing behaviour but possibly not a good idea, since it hides an error rather + // than making it obvious and fixable. Need to see if the error message comes up in practice. + Scene s = m_scenes.Values.ToArray()[0]; + + m_log.ErrorFormat( + "[LOCAL SIMULATION CONNECTOR]: Region with id {0} not found. Returning {1} {2} instead", + regionId, s.RegionInfo.RegionName, s.RegionInfo.RegionID); + + return s; } - // ? weird. should not happen - return m_sceneList[0]; } public ISimulationService GetInnerService() @@ -187,13 +198,10 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation return false; } - foreach (Scene s in m_sceneList) + if (m_scenes.ContainsKey(destination.RegionID)) { - if (s.RegionInfo.RegionHandle == destination.RegionHandle) - { // m_log.DebugFormat("[LOCAL SIMULATION CONNECTOR]: Found region {0} to send SendCreateChildAgent", destination.RegionName); - return s.NewUserConnection(aCircuit, teleportFlags, out reason); - } + return m_scenes[destination.RegionID].NewUserConnection(aCircuit, teleportFlags, out reason); } reason = "Did not find region " + destination.RegionName; @@ -205,17 +213,13 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation if (destination == null) return false; - foreach (Scene s in m_sceneList) + if (m_scenes.ContainsKey(destination.RegionID)) { - if (s.RegionInfo.RegionHandle == destination.RegionHandle) - { // m_log.DebugFormat( // "[LOCAL SIMULATION CONNECTOR]: Found region {0} {1} to send AgentUpdate", // s.RegionInfo.RegionName, destination.RegionHandle); - s.IncomingChildAgentDataUpdate(cAgentData); - return true; - } + return m_scenes[destination.RegionID].IncomingChildAgentDataUpdate(cAgentData); } // m_log.DebugFormat("[LOCAL COMMS]: Did not find region {0} for ChildAgentUpdate", regionHandle); @@ -231,11 +235,12 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation // 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) + foreach (Scene s in m_scenes.Values) { //m_log.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate"); s.IncomingChildAgentDataUpdate(cAgentData); } + //m_log.Debug("[LOCAL COMMS]: region not found for ChildAgentUpdate"); return true; } @@ -247,14 +252,15 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation if (destination == null) return false; - foreach (Scene s in m_sceneList) + if (m_scenes.ContainsKey(destination.RegionID)) { - if (s.RegionInfo.RegionHandle == destination.RegionHandle) - { - //m_log.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate"); - return s.IncomingRetrieveRootAgent(id, out agent); - } +// m_log.DebugFormat( +// "[LOCAL SIMULATION CONNECTOR]: Found region {0} {1} to send AgentUpdate", +// s.RegionInfo.RegionName, destination.RegionHandle); + + return m_scenes[destination.RegionID].IncomingRetrieveRootAgent(id, out agent); } + //m_log.Debug("[LOCAL COMMS]: region not found for ChildAgentUpdate"); return false; } @@ -266,59 +272,49 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation if (destination == null) return false; - foreach (Scene s in m_sceneList) + if (m_scenes.ContainsKey(destination.RegionID)) { - if (s.RegionInfo.RegionID == destination.RegionID) - return s.QueryAccess(id, position, out reason); +// m_log.DebugFormat( +// "[LOCAL SIMULATION CONNECTOR]: Found region {0} {1} to send AgentUpdate", +// s.RegionInfo.RegionName, destination.RegionHandle); + + return m_scenes[destination.RegionID].QueryAccess(id, position, out reason); } + + //m_log.Debug("[LOCAL COMMS]: region not found for QueryAccess"); return false; } - public bool ReleaseAgent(UUID origin, UUID id, string uri) + public bool ReleaseAgent(UUID originId, UUID agentId, string uri) { - foreach (Scene s in m_sceneList) + if (m_scenes.ContainsKey(originId)) { - if (s.RegionInfo.RegionID == origin) - { -// m_log.Debug("[LOCAL COMMS]: Found region to SendReleaseAgent"); - AgentTransferModule.AgentArrivedAtDestination(id); - return true; -// return s.IncomingReleaseAgent(id); - } +// m_log.DebugFormat( +// "[LOCAL SIMULATION CONNECTOR]: Found region {0} {1} to send AgentUpdate", +// s.RegionInfo.RegionName, destination.RegionHandle); + + m_scenes[originId].EntityTransferModule.AgentArrivedAtDestination(agentId); + return true; } + //m_log.Debug("[LOCAL COMMS]: region not found in SendReleaseAgent " + origin); return false; } + public bool CloseChildAgent(GridRegion destination, UUID id) + { + return CloseAgent(destination, id); + } + public bool CloseAgent(GridRegion destination, UUID id) { if (destination == null) return false; - foreach (Scene s in m_sceneList) + if (m_scenes.ContainsKey(destination.RegionID)) { - if (s.RegionInfo.RegionID == destination.RegionID) - { - //m_log.Debug("[LOCAL COMMS]: Found region to SendCloseAgent"); - return s.IncomingCloseAgent(id); - } - } - //m_log.Debug("[LOCAL COMMS]: region not found in SendCloseAgent"); - return false; - } - - public bool CloseChildAgent(GridRegion destination, UUID id) - { - if (destination == null) - return false; - - foreach (Scene s in m_sceneList) - { - if (s.RegionInfo.RegionID == destination.RegionID) - { - //m_log.Debug("[LOCAL COMMS]: Found region to SendCloseAgent"); - return s.IncomingCloseChildAgent(id); - } + Util.FireAndForget(delegate { m_scenes[destination.RegionID].IncomingCloseAgent(id); }); + return true; } //m_log.Debug("[LOCAL COMMS]: region not found in SendCloseAgent"); return false; @@ -333,25 +329,28 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation if (destination == null) return false; - foreach (Scene s in m_sceneList) + if (m_scenes.ContainsKey(destination.RegionID)) { - if (s.RegionInfo.RegionHandle == destination.RegionHandle) +// m_log.DebugFormat( +// "[LOCAL SIMULATION CONNECTOR]: Found region {0} {1} to send AgentUpdate", +// s.RegionInfo.RegionName, destination.RegionHandle); + + Scene s = m_scenes[destination.RegionID]; + + if (isLocalCall) { - //m_log.Debug("[LOCAL COMMS]: Found region to SendCreateObject"); - if (isLocalCall) - { - // We need to make a local copy of the object - ISceneObject sogClone = sog.CloneForNewScene(); - sogClone.SetState(sog.GetStateSnapshot(), s); - return s.IncomingCreateObject(newPosition, sogClone); - } - else - { - // Use the object as it came through the wire - return s.IncomingCreateObject(newPosition, sog); - } + // We need to make a local copy of the object + ISceneObject sogClone = sog.CloneForNewScene(); + sogClone.SetState(sog.GetStateSnapshot(), s); + return s.IncomingCreateObject(newPosition, sogClone); + } + else + { + // Use the object as it came through the wire + return s.IncomingCreateObject(newPosition, sog); } } + return false; } @@ -360,13 +359,15 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation if (destination == null) return false; - foreach (Scene s in m_sceneList) + if (m_scenes.ContainsKey(destination.RegionID)) { - if (s.RegionInfo.RegionHandle == destination.RegionHandle) - { - return s.IncomingCreateObject(userID, itemID); - } +// m_log.DebugFormat( +// "[LOCAL SIMULATION CONNECTOR]: Found region {0} {1} to send AgentUpdate", +// s.RegionInfo.RegionName, destination.RegionHandle); + + return m_scenes[destination.RegionID].IncomingCreateObject(userID, itemID); } + return false; } @@ -377,18 +378,16 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation public bool IsLocalRegion(ulong regionhandle) { - foreach (Scene s in m_sceneList) + foreach (Scene s in m_scenes.Values) if (s.RegionInfo.RegionHandle == regionhandle) return true; + return false; } public bool IsLocalRegion(UUID id) { - foreach (Scene s in m_sceneList) - if (s.RegionInfo.RegionID == id) - return true; - return false; + return m_scenes.ContainsKey(id); } #endregion diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Simulation/RemoteSimulationConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Simulation/RemoteSimulationConnector.cs index 4b70692e78..d395413b85 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Simulation/RemoteSimulationConnector.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Simulation/RemoteSimulationConnector.cs @@ -151,9 +151,9 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation #region IInterregionComms - public IScene GetScene(ulong handle) + public IScene GetScene(UUID regionId) { - return m_localBackend.GetScene(handle); + return m_localBackend.GetScene(regionId); } public ISimulationService GetInnerService() @@ -226,13 +226,13 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation return m_remoteConnector.RetrieveAgent(destination, id, out agent); return false; - } public bool QueryAccess(GridRegion destination, UUID id, Vector3 position, out string version, out string reason) { reason = "Communications failure"; version = "Unknown"; + if (destination == null) return false; @@ -245,7 +245,6 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation return m_remoteConnector.QueryAccess(destination, id, position, out version, out reason); return false; - } public bool ReleaseAgent(UUID origin, UUID id, string uri) diff --git a/OpenSim/Region/CoreModules/World/Archiver/ArchiveWriteRequestPreparation.cs b/OpenSim/Region/CoreModules/World/Archiver/ArchiveWriteRequestPreparation.cs index 504f09ba5b..4edaaca594 100644 --- a/OpenSim/Region/CoreModules/World/Archiver/ArchiveWriteRequestPreparation.cs +++ b/OpenSim/Region/CoreModules/World/Archiver/ArchiveWriteRequestPreparation.cs @@ -428,9 +428,9 @@ namespace OpenSim.Region.CoreModules.World.Archiver s = sw.ToString(); } - if (m_scene != null) - Console.WriteLine( - "[ARCHIVE WRITE REQUEST PREPARATION]: Control file for {0} is: {1}", m_scene.RegionInfo.RegionName, s); +// if (m_scene != null) +// Console.WriteLine( +// "[ARCHIVE WRITE REQUEST PREPARATION]: Control file for {0} is: {1}", m_scene.RegionInfo.RegionName, s); return s; } diff --git a/OpenSim/Region/CoreModules/World/Region/RegionCommandsModule.cs b/OpenSim/Region/CoreModules/World/Region/RegionCommandsModule.cs new file mode 100644 index 0000000000..2838e0c356 --- /dev/null +++ b/OpenSim/Region/CoreModules/World/Region/RegionCommandsModule.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.Reflection; +using System.Text; +using System.Text.RegularExpressions; +using log4net; +using Mono.Addins; +using NDesk.Options; +using Nini.Config; +using OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Framework.Console; +using OpenSim.Framework.Statistics; +using OpenSim.Region.Framework.Interfaces; +using OpenSim.Region.Framework.Scenes; + +namespace OpenSim.Region.CoreModules.World.Objects.Commands +{ + /// + /// A module that holds commands for manipulating objects in the scene. + /// + [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "RegionCommandsModule")] + public class RegionCommandsModule : INonSharedRegionModule + { + private Scene m_scene; + private ICommandConsole m_console; + + public string Name { get { return "Region Commands Module"; } } + + public Type ReplaceableInterface { get { return null; } } + + public void Initialise(IConfigSource source) + { +// m_log.DebugFormat("[REGION COMMANDS MODULE]: INITIALIZED MODULE"); + } + + public void PostInitialise() + { +// m_log.DebugFormat("[REGION COMMANDS MODULE]: POST INITIALIZED MODULE"); + } + + public void Close() + { +// m_log.DebugFormat("[REGION COMMANDS MODULE]: CLOSED MODULE"); + } + + public void AddRegion(Scene scene) + { +// m_log.DebugFormat("[REGION COMMANDS MODULE]: REGION {0} ADDED", scene.RegionInfo.RegionName); + + m_scene = scene; + m_console = MainConsole.Instance; + + m_console.Commands.AddCommand( + "Regions", false, "show scene", + "show scene", + "Show live scene information for the currently selected region.", HandleShowScene); + } + + public void RemoveRegion(Scene scene) + { +// m_log.DebugFormat("[REGION COMMANDS MODULE]: REGION {0} REMOVED", scene.RegionInfo.RegionName); + } + + public void RegionLoaded(Scene scene) + { +// m_log.DebugFormat("[REGION COMMANDS MODULE]: REGION {0} LOADED", scene.RegionInfo.RegionName); + } + + private void HandleShowScene(string module, string[] cmd) + { + if (!(MainConsole.Instance.ConsoleScene == null || MainConsole.Instance.ConsoleScene == m_scene)) + return; + + SimStatsReporter r = m_scene.StatsReporter; + float[] stats = r.LastReportedSimStats; + + float timeDilation = stats[0]; + float simFps = stats[1]; + float physicsFps = stats[2]; + float agentUpdates = stats[3]; + float rootAgents = stats[4]; + float childAgents = stats[5]; + float totalPrims = stats[6]; + float activePrims = stats[7]; + float totalFrameTime = stats[8]; +// float netFrameTime = stats.StatsBlock[9].StatValue; // Ignored - not used by OpenSimulator + float physicsFrameTime = stats[10]; + float otherFrameTime = stats[11]; +// float imageFrameTime = stats.StatsBlock[12].StatValue; // Ignored + float inPacketsPerSecond = stats[13]; + float outPacketsPerSecond = stats[14]; + float unackedBytes = stats[15]; +// float agentFrameTime = stats.StatsBlock[16].StatValue; // Not really used + float pendingDownloads = stats[17]; + float pendingUploads = stats[18]; + float activeScripts = stats[19]; + float scriptLinesPerSecond = stats[20]; + + StringBuilder sb = new StringBuilder(); + sb.AppendFormat("Scene statistics for {0}\n", m_scene.RegionInfo.RegionName); + + ConsoleDisplayList dispList = new ConsoleDisplayList(); + dispList.AddRow("Time Dilation", timeDilation); + dispList.AddRow("Sim FPS", simFps); + dispList.AddRow("Physics FPS", physicsFps); + dispList.AddRow("Avatars", rootAgents); + dispList.AddRow("Child agents", childAgents); + dispList.AddRow("Total prims", totalPrims); + dispList.AddRow("Scripts", activeScripts); + dispList.AddRow("Script lines processed per second", scriptLinesPerSecond); + dispList.AddRow("Physics enabled prims", activePrims); + dispList.AddRow("Total frame time", totalFrameTime); + dispList.AddRow("Physics frame time", physicsFrameTime); + dispList.AddRow("Other frame time", otherFrameTime); + dispList.AddRow("Agent Updates per second", agentUpdates); + dispList.AddRow("Packets processed from clients per second", inPacketsPerSecond); + dispList.AddRow("Packets sent to clients per second", outPacketsPerSecond); + dispList.AddRow("Bytes unacknowledged by clients", unackedBytes); + dispList.AddRow("Pending asset downloads to clients", pendingDownloads); + dispList.AddRow("Pending asset uploads from clients", pendingUploads); + + dispList.AddToStringBuilder(sb); + + MainConsole.Instance.Output(sb.ToString()); + } + } +} \ No newline at end of file diff --git a/OpenSim/Region/CoreModules/World/Terrain/FileLoaders/TIFF.cs b/OpenSim/Region/CoreModules/World/Terrain/FileLoaders/TIFF.cs index 5d2f8937b4..b416b82a17 100644 --- a/OpenSim/Region/CoreModules/World/Terrain/FileLoaders/TIFF.cs +++ b/OpenSim/Region/CoreModules/World/Terrain/FileLoaders/TIFF.cs @@ -59,7 +59,7 @@ namespace OpenSim.Region.CoreModules.World.Terrain.FileLoaders } //Returns true if this extension is supported for terrain save-tile - public bool SupportsTileSave() + public override bool SupportsTileSave() { return false; } diff --git a/OpenSim/Region/CoreModules/World/Terrain/FileLoaders/Terragen.cs b/OpenSim/Region/CoreModules/World/Terrain/FileLoaders/Terragen.cs index 1ebf91654c..71c71e6cd5 100644 --- a/OpenSim/Region/CoreModules/World/Terrain/FileLoaders/Terragen.cs +++ b/OpenSim/Region/CoreModules/World/Terrain/FileLoaders/Terragen.cs @@ -65,7 +65,7 @@ namespace OpenSim.Region.CoreModules.World.Terrain.FileLoaders bool eof = false; int fileXPoints = 0; - int fileYPoints = 0; +// int fileYPoints = 0; // Terragen file while (eof == false) @@ -75,7 +75,7 @@ namespace OpenSim.Region.CoreModules.World.Terrain.FileLoaders { case "SIZE": fileXPoints = bs.ReadInt16() + 1; - fileYPoints = fileXPoints; +// fileYPoints = fileXPoints; bs.ReadInt16(); break; case "XPTS": @@ -83,7 +83,8 @@ namespace OpenSim.Region.CoreModules.World.Terrain.FileLoaders bs.ReadInt16(); break; case "YPTS": - fileYPoints = bs.ReadInt16(); +// fileYPoints = bs.ReadInt16(); + bs.ReadInt16(); bs.ReadInt16(); break; case "ALTW": @@ -164,10 +165,8 @@ namespace OpenSim.Region.CoreModules.World.Terrain.FileLoaders bool eof = false; if (Encoding.ASCII.GetString(bs.ReadBytes(16)) == "TERRAGENTERRAIN ") { - - int fileWidth = w; - int fileHeight = h; - +// int fileWidth = w; +// int fileHeight = h; // Terragen file while (eof == false) @@ -176,17 +175,22 @@ namespace OpenSim.Region.CoreModules.World.Terrain.FileLoaders switch (tmp) { case "SIZE": - int sztmp = bs.ReadInt16() + 1; - fileWidth = sztmp; - fileHeight = sztmp; +// int sztmp = bs.ReadInt16() + 1; +// fileWidth = sztmp; +// fileHeight = sztmp; + bs.ReadInt16(); + bs.ReadInt16(); + bs.ReadInt16(); bs.ReadInt16(); break; case "XPTS": - fileWidth = bs.ReadInt16(); +// fileWidth = bs.ReadInt16(); + bs.ReadInt16(); bs.ReadInt16(); break; case "YPTS": - fileHeight = bs.ReadInt16(); +// fileHeight = bs.ReadInt16(); + bs.ReadInt16(); bs.ReadInt16(); break; case "ALTW": diff --git a/OpenSim/Region/Framework/Interfaces/IEntityInventory.cs b/OpenSim/Region/Framework/Interfaces/IEntityInventory.cs index 8732ec0fc5..c605fc1f87 100644 --- a/OpenSim/Region/Framework/Interfaces/IEntityInventory.cs +++ b/OpenSim/Region/Framework/Interfaces/IEntityInventory.cs @@ -165,6 +165,19 @@ namespace OpenSim.Region.Framework.Interfaces /// List GetInventoryItems(); + /// + /// Gets an inventory item by name + /// + /// + /// This method returns the first inventory item that matches the given name. In SL this is all you need + /// since each item in a prim inventory must have a unique name. + /// + /// + /// + /// The inventory item. Null if no such item was found. + /// + TaskInventoryItem GetInventoryItem(string name); + /// /// Get inventory items by name. /// diff --git a/OpenSim/Region/Framework/Interfaces/IEntityTransferModule.cs b/OpenSim/Region/Framework/Interfaces/IEntityTransferModule.cs index 9cd27f9ac8..5bc8e51759 100644 --- a/OpenSim/Region/Framework/Interfaces/IEntityTransferModule.cs +++ b/OpenSim/Region/Framework/Interfaces/IEntityTransferModule.cs @@ -57,6 +57,13 @@ namespace OpenSim.Region.Framework.Interfaces void DoTeleport(ScenePresence sp, GridRegion reg, GridRegion finalDestination, Vector3 position, Vector3 lookAt, uint teleportFlags); + /// + /// Show whether the given agent is being teleported. + /// + /// The agent ID + /// true if the agent is in the process of being teleported, false otherwise. + bool IsInTransit(UUID id); + bool Cross(ScenePresence agent, bool isFlying); void AgentArrivedAtDestination(UUID agent); diff --git a/OpenSim/Region/Framework/Interfaces/IEnvironmentModule.cs b/OpenSim/Region/Framework/Interfaces/IEnvironmentModule.cs new file mode 100644 index 0000000000..7a7b78202d --- /dev/null +++ b/OpenSim/Region/Framework/Interfaces/IEnvironmentModule.cs @@ -0,0 +1,36 @@ +/* + * 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 OpenMetaverse; + +namespace OpenSim.Region.Framework.Interfaces +{ + public interface IEnvironmentModule + { + void ResetEnvironmentSettings(UUID regionUUID); + } +} diff --git a/OpenSim/Region/Framework/Interfaces/IInventoryAccessModule.cs b/OpenSim/Region/Framework/Interfaces/IInventoryAccessModule.cs index 1904011b17..3576e35798 100644 --- a/OpenSim/Region/Framework/Interfaces/IInventoryAccessModule.cs +++ b/OpenSim/Region/Framework/Interfaces/IInventoryAccessModule.cs @@ -49,11 +49,15 @@ namespace OpenSim.Region.Framework.Interfaces /// /// /// + /// + /// Should be true if the object(s) are begin taken as attachments. False otherwise. + /// /// - /// Returns the UUID of the newly created item asset (not the item itself). - /// FIXME: This is not very useful. It would be far more useful to return a list of items instead. + /// A list of the items created. If there was more than one object and objects are not being coaleseced in + /// inventory, then the order of items is in the same order as the input objects. /// - UUID CopyToInventory(DeRezAction action, UUID folderID, List objectGroups, IClientAPI remoteClient); + List CopyToInventory( + DeRezAction action, UUID folderID, List objectGroups, IClientAPI remoteClient, bool asAttachment); /// /// Rez an object into the scene from the user's inventory diff --git a/OpenSim/Region/Framework/Interfaces/ISimulationDataService.cs b/OpenSim/Region/Framework/Interfaces/ISimulationDataService.cs index 5295a72976..0fcafcc515 100644 --- a/OpenSim/Region/Framework/Interfaces/ISimulationDataService.cs +++ b/OpenSim/Region/Framework/Interfaces/ISimulationDataService.cs @@ -95,5 +95,26 @@ namespace OpenSim.Region.Framework.Interfaces RegionLightShareData LoadRegionWindlightSettings(UUID regionUUID); void StoreRegionWindlightSettings(RegionLightShareData wl); void RemoveRegionWindlightSettings(UUID regionID); + + /// + /// Load Environment settings from region storage + /// + /// the region UUID + /// LLSD string for viewer + string LoadRegionEnvironmentSettings(UUID regionUUID); + + /// + /// Store Environment settings into region storage + /// + /// the region UUID + /// LLSD string from viewer + void StoreRegionEnvironmentSettings(UUID regionUUID, string settings); + + /// + /// Delete Environment settings from region storage + /// + /// the region UUID + void RemoveRegionEnvironmentSettings(UUID regionUUID); + } } diff --git a/OpenSim/Region/Framework/Interfaces/ISimulationDataStore.cs b/OpenSim/Region/Framework/Interfaces/ISimulationDataStore.cs index 615f3770d1..e424976226 100644 --- a/OpenSim/Region/Framework/Interfaces/ISimulationDataStore.cs +++ b/OpenSim/Region/Framework/Interfaces/ISimulationDataStore.cs @@ -107,6 +107,26 @@ namespace OpenSim.Region.Framework.Interfaces void StoreRegionWindlightSettings(RegionLightShareData wl); void RemoveRegionWindlightSettings(UUID regionID); + /// + /// Load Environment settings from region storage + /// + /// the region UUID + /// LLSD string for viewer + string LoadRegionEnvironmentSettings(UUID regionUUID); + + /// + /// Store Environment settings into region storage + /// + /// the region UUID + /// LLSD string from viewer + void StoreRegionEnvironmentSettings(UUID regionUUID, string settings); + + /// + /// Delete Environment settings from region storage + /// + /// the region UUID + void RemoveRegionEnvironmentSettings(UUID regionUUID); + void Shutdown(); } } diff --git a/OpenSim/Region/Framework/Interfaces/IUrlModule.cs b/OpenSim/Region/Framework/Interfaces/IUrlModule.cs index 1b911666e4..457444cd83 100644 --- a/OpenSim/Region/Framework/Interfaces/IUrlModule.cs +++ b/OpenSim/Region/Framework/Interfaces/IUrlModule.cs @@ -34,6 +34,7 @@ namespace OpenSim.Region.Framework.Interfaces { public interface IUrlModule { + string ExternalHostNameForLSL { get; } UUID RequestURL(IScriptModule engine, SceneObjectPart host, UUID itemID); UUID RequestSecureURL(IScriptModule engine, SceneObjectPart host, UUID itemID); void ReleaseURL(string url); diff --git a/OpenSim/Region/Framework/Scenes/AsyncSceneObjectGroupDeleter.cs b/OpenSim/Region/Framework/Scenes/AsyncSceneObjectGroupDeleter.cs index 834464b2c8..f555b49f58 100644 --- a/OpenSim/Region/Framework/Scenes/AsyncSceneObjectGroupDeleter.cs +++ b/OpenSim/Region/Framework/Scenes/AsyncSceneObjectGroupDeleter.cs @@ -155,7 +155,7 @@ namespace OpenSim.Region.Framework.Scenes { IInventoryAccessModule invAccess = m_scene.RequestModuleInterface(); if (invAccess != null) - invAccess.CopyToInventory(x.action, x.folderID, x.objectGroups, x.remoteClient); + invAccess.CopyToInventory(x.action, x.folderID, x.objectGroups, x.remoteClient, false); if (x.permissionToDelete) { diff --git a/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs b/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs index 942c625850..270b01bc74 100644 --- a/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs +++ b/OpenSim/Region/Framework/Scenes/Scene.Inventory.cs @@ -954,8 +954,8 @@ namespace OpenSim.Region.Framework.Scenes sbyte invType, sbyte type, UUID olditemID) { // m_log.DebugFormat( -// "[AGENT INVENTORY]: Received request from {0} to create inventory item link {1} in folder {2} pointing to {3}", -// remoteClient.Name, name, folderID, olditemID); +// "[AGENT INVENTORY]: Received request from {0} to create inventory item link {1} in folder {2} pointing to {3}, assetType {4}, inventoryType {5}", +// remoteClient.Name, name, folderID, olditemID, (AssetType)type, (InventoryType)invType); if (!Permissions.CanCreateUserInventory(invType, remoteClient.AgentId)) return; @@ -988,10 +988,10 @@ namespace OpenSim.Region.Framework.Scenes asset.Type = type; asset.Name = name; asset.Description = description; - + CreateNewInventoryItem( - remoteClient, remoteClient.AgentId.ToString(), string.Empty, folderID, name, 0, callbackID, asset, invType, - (uint)PermissionMask.All, (uint)PermissionMask.All, (uint)PermissionMask.All, + remoteClient, remoteClient.AgentId.ToString(), string.Empty, folderID, name, 0, callbackID, asset, invType, + (uint)PermissionMask.All, (uint)PermissionMask.All, (uint)PermissionMask.All, (uint)PermissionMask.All, (uint)PermissionMask.All, Util.UnixTimeSinceEpoch()); } else diff --git a/OpenSim/Region/Framework/Scenes/Scene.cs b/OpenSim/Region/Framework/Scenes/Scene.cs index e3bd527d25..32c726266f 100644 --- a/OpenSim/Region/Framework/Scenes/Scene.cs +++ b/OpenSim/Region/Framework/Scenes/Scene.cs @@ -77,7 +77,12 @@ namespace OpenSim.Region.Framework.Scenes public bool DebugUpdates { get; private set; } public SynchronizeSceneHandler SynchronizeScene; - public SimStatsReporter StatsReporter; + + /// + /// Statistical information for this scene. + /// + public SimStatsReporter StatsReporter { get; private set; } + public List NorthBorders = new List(); public List EastBorders = new List(); public List SouthBorders = new List(); @@ -164,7 +169,6 @@ namespace OpenSim.Region.Framework.Scenes protected IConfigSource m_config; protected IRegionSerialiserModule m_serialiser; protected IDialogModule m_dialogModule; - protected IEntityTransferModule m_teleportModule; protected ICapabilitiesModule m_capsModule; protected IGroupsModule m_groupsModule; @@ -515,6 +519,7 @@ namespace OpenSim.Region.Framework.Scenes } public IAttachmentsModule AttachmentsModule { get; set; } + public IEntityTransferModule EntityTransferModule { get; private set; } public IAvatarFactoryModule AvatarFactory { @@ -952,8 +957,8 @@ namespace OpenSim.Region.Framework.Scenes List old = new List(); old.Add(otherRegion.RegionHandle); agent.DropOldNeighbours(old); - if (m_teleportModule != null && agent.PresenceType != PresenceType.Npc) - m_teleportModule.EnableChildAgent(agent, otherRegion); + if (EntityTransferModule != null && agent.PresenceType != PresenceType.Npc) + EntityTransferModule.EnableChildAgent(agent, otherRegion); }); } catch (NullReferenceException) @@ -1060,13 +1065,13 @@ namespace OpenSim.Region.Framework.Scenes } } + m_log.Error("[REGION]: Closing"); + Close(); + if (PhysicsScene != null) { PhysicsScene.Dispose(); - } - - m_log.Error("[REGION]: Closing"); - Close(); + } m_log.Error("[REGION]: Firing Region Restart Message"); @@ -1090,8 +1095,8 @@ namespace OpenSim.Region.Framework.Scenes { ForEachRootScenePresence(delegate(ScenePresence agent) { - if (m_teleportModule != null && agent.PresenceType != PresenceType.Npc) - m_teleportModule.EnableChildAgent(agent, r); + if (EntityTransferModule != null && agent.PresenceType != PresenceType.Npc) + EntityTransferModule.EnableChildAgent(agent, r); }); } catch (NullReferenceException) @@ -1281,7 +1286,7 @@ namespace OpenSim.Region.Framework.Scenes m_serialiser = RequestModuleInterface(); m_dialogModule = RequestModuleInterface(); m_capsModule = RequestModuleInterface(); - m_teleportModule = RequestModuleInterface(); + EntityTransferModule = RequestModuleInterface(); m_groupsModule = RequestModuleInterface(); } @@ -2380,8 +2385,8 @@ namespace OpenSim.Region.Framework.Scenes return; } - if (m_teleportModule != null) - m_teleportModule.Cross(grp, attemptedPosition, silent); + if (EntityTransferModule != null) + EntityTransferModule.Cross(grp, attemptedPosition, silent); } public Border GetCrossedBorder(Vector3 position, Cardinals gridline) @@ -3225,8 +3230,10 @@ namespace OpenSim.Region.Framework.Scenes /// The IClientAPI for the client public virtual bool TeleportClientHome(UUID agentId, IClientAPI client) { - if (m_teleportModule != null) - return m_teleportModule.TeleportHome(agentId, client); + if (EntityTransferModule != null) + { + EntityTransferModule.TeleportHome(agentId, client); + } else { m_log.DebugFormat("[SCENE]: Unable to teleport user home: no AgentTransferModule is active"); @@ -4332,8 +4339,10 @@ namespace OpenSim.Region.Framework.Scenes position.Y -= shifty; } - if (m_teleportModule != null) - m_teleportModule.Teleport(sp, regionHandle, position, lookAt, teleportFlags); + if (EntityTransferModule != null) + { + EntityTransferModule.Teleport(sp, regionHandle, position, lookAt, teleportFlags); + } else { m_log.DebugFormat("[SCENE]: Unable to perform teleports: no AgentTransferModule is active"); @@ -4344,8 +4353,10 @@ namespace OpenSim.Region.Framework.Scenes public bool CrossAgentToNewRegion(ScenePresence agent, bool isFlying) { - if (m_teleportModule != null) - return m_teleportModule.Cross(agent, isFlying); + if (EntityTransferModule != null) + { + return EntityTransferModule.Cross(agent, isFlying); + } else { m_log.DebugFormat("[SCENE]: Unable to cross agent to neighbouring region, because there is no AgentTransferModule"); @@ -5493,16 +5504,36 @@ Environment.Exit(1); throw new Exception(error); } - // This method is called across the simulation connector to - // determine if a given agent is allowed in this region - // AS A ROOT AGENT. Returning false here will prevent them - // 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. + /// + /// This method is called across the simulation connector to + /// determine if a given agent is allowed in this region + /// AS A ROOT AGENT + /// + /// + /// Returning false here will prevent them + /// 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, out string reason) { reason = "You are banned from the region"; + if (EntityTransferModule.IsInTransit(agentID)) + { + reason = "Agent is still in transit from this region"; + + m_log.WarnFormat( + "[SCENE]: Denying agent {0} entry into {1} since region still has them registered as in transit", + agentID, RegionInfo.RegionName); + + return false; + } + if (Permissions.IsGod(agentID)) { reason = String.Empty; diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs b/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs index 141cf66486..f5b98256cf 100644 --- a/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs +++ b/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs @@ -759,14 +759,22 @@ namespace OpenSim.Region.Framework.Scenes return item; } - /// - /// Get inventory items by name. - /// - /// - /// - /// A list of inventory items with that name. - /// If no inventory item has that name then an empty list is returned. - /// + public TaskInventoryItem GetInventoryItem(string name) + { + m_items.LockItemsForRead(true); + foreach (TaskInventoryItem item in m_items.Values) + { + if (item.Name == name) + { + return item; + m_items.LockItemsForRead(false); + } + } + m_items.LockItemsForRead(false); + + return null; + } + public List GetInventoryItems(string name) { List items = new List(); @@ -1236,10 +1244,10 @@ namespace OpenSim.Region.Framework.Scenes if ((item.CurrentPermissions & ((uint)PermissionMask.Modify >> 13)) == 0) item.CurrentPermissions &= ~(uint)PermissionMask.Modify; } - item.OwnerChanged = true; item.CurrentPermissions &= item.NextPermissions; item.BasePermissions &= item.NextPermissions; item.EveryonePermissions &= item.NextPermissions; + item.OwnerChanged = true; item.PermsMask = 0; item.PermsGranter = UUID.Zero; } @@ -1432,4 +1440,4 @@ namespace OpenSim.Region.Framework.Scenes } } } -} \ No newline at end of file +} diff --git a/OpenSim/Region/Framework/Scenes/Serialization/CoalescedSceneObjectsSerializer.cs b/OpenSim/Region/Framework/Scenes/Serialization/CoalescedSceneObjectsSerializer.cs index 55455cc434..a4f730d375 100644 --- a/OpenSim/Region/Framework/Scenes/Serialization/CoalescedSceneObjectsSerializer.cs +++ b/OpenSim/Region/Framework/Scenes/Serialization/CoalescedSceneObjectsSerializer.cs @@ -47,14 +47,30 @@ namespace OpenSim.Region.Framework.Scenes.Serialization /// public class CoalescedSceneObjectsSerializer { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// /// Serialize coalesced objects to Xml /// /// + /// + /// If true then serialize script states. This will halt any running scripts + /// /// public static string ToXml(CoalescedSceneObjects coa) + { + return ToXml(coa, true); + } + + /// + /// Serialize coalesced objects to Xml + /// + /// + /// + /// If true then serialize script states. This will halt any running scripts + /// + /// + public static string ToXml(CoalescedSceneObjects coa, bool doScriptStates) { using (StringWriter sw = new StringWriter()) { @@ -91,7 +107,7 @@ namespace OpenSim.Region.Framework.Scenes.Serialization writer.WriteAttributeString("offsety", offsets[i].Y.ToString()); writer.WriteAttributeString("offsetz", offsets[i].Z.ToString()); - SceneObjectSerializer.ToOriginalXmlFormat(obj, writer, true); + SceneObjectSerializer.ToOriginalXmlFormat(obj, writer, doScriptStates); writer.WriteEndElement(); // SceneObjectGroup } diff --git a/OpenSim/Region/Framework/Scenes/Tests/ScenePresenceTeleportTests.cs b/OpenSim/Region/Framework/Scenes/Tests/ScenePresenceTeleportTests.cs index 41bff7f92e..ccfe4ff218 100644 --- a/OpenSim/Region/Framework/Scenes/Tests/ScenePresenceTeleportTests.cs +++ b/OpenSim/Region/Framework/Scenes/Tests/ScenePresenceTeleportTests.cs @@ -110,12 +110,13 @@ namespace OpenSim.Region.Framework.Scenes.Tests UUID userId = TestHelpers.ParseTail(0x1); - EntityTransferModule etm = new EntityTransferModule(); + EntityTransferModule etmA = new EntityTransferModule(); + EntityTransferModule etmB = new EntityTransferModule(); LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule(); IConfigSource config = new IniConfigSource(); IConfig modulesConfig = config.AddConfig("Modules"); - modulesConfig.Set("EntityTransferModule", etm.Name); + modulesConfig.Set("EntityTransferModule", etmA.Name); modulesConfig.Set("SimulationServices", lscm.Name); IConfig entityTransferConfig = config.AddConfig("EntityTransfer"); @@ -127,7 +128,9 @@ namespace OpenSim.Region.Framework.Scenes.Tests TestScene sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000); TestScene sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1002, 1000); - SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, etm, lscm); + SceneHelpers.SetupSceneModules(sceneA, config, etmA); + SceneHelpers.SetupSceneModules(sceneB, config, etmB); + SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm); Vector3 teleportPosition = new Vector3(10, 11, 12); Vector3 teleportLookAt = new Vector3(20, 21, 22); @@ -174,12 +177,14 @@ namespace OpenSim.Region.Framework.Scenes.Tests UUID userId = TestHelpers.ParseTail(0x1); Vector3 preTeleportPosition = new Vector3(30, 31, 32); - EntityTransferModule etm = new EntityTransferModule(); + EntityTransferModule etmA = new EntityTransferModule(); + EntityTransferModule etmB = new EntityTransferModule(); + LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule(); IConfigSource config = new IniConfigSource(); config.AddConfig("Modules"); - config.Configs["Modules"].Set("EntityTransferModule", etm.Name); + config.Configs["Modules"].Set("EntityTransferModule", etmA.Name); config.Configs["Modules"].Set("SimulationServices", lscm.Name); config.AddConfig("EntityTransfer"); @@ -195,13 +200,15 @@ namespace OpenSim.Region.Framework.Scenes.Tests TestScene sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000); TestScene sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1002, 1000); + SceneHelpers.SetupSceneModules(sceneA, config, etmA ); + // We need to set up the permisions module on scene B so that our later use of agent limit to deny // QueryAccess won't succeed anyway because administrators are always allowed in and the default // IsAdministrator if no permissions module is present is true. - SceneHelpers.SetupSceneModules(sceneB, config, new object[] { new PermissionsModule() }); + SceneHelpers.SetupSceneModules(sceneB, config, new object[] { new PermissionsModule(), etmB }); // Shared scene modules - SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, etm, lscm); + SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm); Vector3 teleportPosition = new Vector3(10, 11, 12); Vector3 teleportLookAt = new Vector3(20, 21, 22); @@ -249,12 +256,13 @@ namespace OpenSim.Region.Framework.Scenes.Tests UUID userId = TestHelpers.ParseTail(0x1); Vector3 preTeleportPosition = new Vector3(30, 31, 32); - EntityTransferModule etm = new EntityTransferModule(); + EntityTransferModule etmA = new EntityTransferModule(); + EntityTransferModule etmB = new EntityTransferModule(); LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule(); IConfigSource config = new IniConfigSource(); config.AddConfig("Modules"); - config.Configs["Modules"].Set("EntityTransferModule", etm.Name); + config.Configs["Modules"].Set("EntityTransferModule", etmA.Name); config.Configs["Modules"].Set("SimulationServices", lscm.Name); config.AddConfig("EntityTransfer"); @@ -267,8 +275,11 @@ namespace OpenSim.Region.Framework.Scenes.Tests TestScene sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000); TestScene sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1002, 1000); + SceneHelpers.SetupSceneModules(sceneA, config, etmA); + SceneHelpers.SetupSceneModules(sceneB, config, etmB); + // Shared scene modules - SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, etm, lscm); + SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm); Vector3 teleportPosition = new Vector3(10, 11, 12); Vector3 teleportLookAt = new Vector3(20, 21, 22); @@ -312,12 +323,13 @@ namespace OpenSim.Region.Framework.Scenes.Tests UUID userId = TestHelpers.ParseTail(0x1); - EntityTransferModule etm = new EntityTransferModule(); + EntityTransferModule etmA = new EntityTransferModule(); + EntityTransferModule etmB = new EntityTransferModule(); LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule(); IConfigSource config = new IniConfigSource(); IConfig modulesConfig = config.AddConfig("Modules"); - modulesConfig.Set("EntityTransferModule", etm.Name); + modulesConfig.Set("EntityTransferModule", etmA.Name); modulesConfig.Set("SimulationServices", lscm.Name); IConfig entityTransferConfig = config.AddConfig("EntityTransfer"); @@ -329,9 +341,9 @@ namespace OpenSim.Region.Framework.Scenes.Tests TestScene sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000); TestScene sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1001, 1000); - SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, etm, lscm); - SceneHelpers.SetupSceneModules(sceneA, new CapabilitiesModule()); - SceneHelpers.SetupSceneModules(sceneB, new CapabilitiesModule()); + SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm); + SceneHelpers.SetupSceneModules(sceneA, config, new CapabilitiesModule(), etmA); + SceneHelpers.SetupSceneModules(sceneB, config, new CapabilitiesModule(), etmB); Vector3 teleportPosition = new Vector3(10, 11, 12); Vector3 teleportLookAt = new Vector3(20, 21, 22); diff --git a/OpenSim/Region/OptionalModules/Avatar/Attachments/AttachmentsCommandModule.cs b/OpenSim/Region/OptionalModules/Avatar/Attachments/AttachmentsCommandModule.cs index a95514c642..1b9e3ace5c 100644 --- a/OpenSim/Region/OptionalModules/Avatar/Attachments/AttachmentsCommandModule.cs +++ b/OpenSim/Region/OptionalModules/Avatar/Attachments/AttachmentsCommandModule.cs @@ -145,12 +145,12 @@ namespace OpenSim.Region.OptionalModules.Avatar.Attachments { sb.AppendFormat("Attachments for {0}\n", sp.Name); - ConsoleTable ct = new ConsoleTable() { Indent = 2 }; - ct.Columns.Add(new ConsoleTableColumn("Attachment Name", 36)); - ct.Columns.Add(new ConsoleTableColumn("Local ID", 10)); - ct.Columns.Add(new ConsoleTableColumn("Item ID", 36)); - ct.Columns.Add(new ConsoleTableColumn("Attach Point", 14)); - ct.Columns.Add(new ConsoleTableColumn("Position", 15)); + ConsoleDisplayTable ct = new ConsoleDisplayTable() { Indent = 2 }; + ct.Columns.Add(new ConsoleDisplayTableColumn("Attachment Name", 36)); + ct.Columns.Add(new ConsoleDisplayTableColumn("Local ID", 10)); + ct.Columns.Add(new ConsoleDisplayTableColumn("Item ID", 36)); + ct.Columns.Add(new ConsoleDisplayTableColumn("Attach Point", 14)); + ct.Columns.Add(new ConsoleDisplayTableColumn("Position", 15)); // sb.AppendFormat( // " {0,-36} {1,-10} {2,-36} {3,-14} {4,-15}\n", @@ -176,7 +176,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Attachments // attachmentObject.Name, attachmentObject.LocalId, attachmentObject.FromItemID, // (AttachmentPoint)attachmentObject.AttachmentPoint, attachmentObject.RootPart.AttachedPos); ct.Rows.Add( - new ConsoleTableRow( + new ConsoleDisplayTableRow( new List() { attachmentObject.Name, diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs index 0cc3e8c52a..03f4108862 100644 --- a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs +++ b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs @@ -354,51 +354,14 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api protected UUID InventoryKey(string name, int type) { - m_host.AddScriptLPS(1); - m_host.TaskInventory.LockItemsForRead(true); - - foreach (KeyValuePair inv in m_host.TaskInventory) - { - if (inv.Value.Name == name) - { - m_host.TaskInventory.LockItemsForRead(false); - - if (inv.Value.Type != type) - { - return UUID.Zero; - } + TaskInventoryItem item = m_host.Inventory.GetInventoryItem(name); - return inv.Value.AssetID; - } - } - - m_host.TaskInventory.LockItemsForRead(false); - return UUID.Zero; + if (item != null && item.Type == type) + return item.AssetID; + else + return UUID.Zero; } - protected UUID InventoryKey(string name) - { - m_host.AddScriptLPS(1); - - - m_host.TaskInventory.LockItemsForRead(true); - - foreach (KeyValuePair inv in m_host.TaskInventory) - { - if (inv.Value.Name == name) - { - m_host.TaskInventory.LockItemsForRead(false); - return inv.Value.AssetID; - } - } - - m_host.TaskInventory.LockItemsForRead(false); - - - return UUID.Zero; - } - - /// /// accepts a valid UUID, -or- a name of an inventory item. /// Returns a valid UUID or UUID.Zero if key invalid and item not found @@ -408,19 +371,22 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api /// protected UUID KeyOrName(string k) { - UUID key = UUID.Zero; + UUID key; // if we can parse the string as a key, use it. - if (UUID.TryParse(k, out key)) - { - return key; - } // else try to locate the name in inventory of object. found returns key, - // not found returns UUID.Zero which will translate to the default particle texture - else + // not found returns UUID.Zero + if (!UUID.TryParse(k, out key)) { - return InventoryKey(k); + TaskInventoryItem item = m_host.Inventory.GetInventoryItem(k); + + if (item != null) + key = item.AssetID; + else + key = UUID.Zero; } + + return key; } // convert a LSL_Rotation to a Quaternion @@ -1897,14 +1863,15 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api return rgb; } + if (face >= 0 && face < GetNumberOfSides(part)) { texcolor = tex.GetFace((uint)face).RGBA; rgb.x = texcolor.R; rgb.y = texcolor.G; rgb.z = texcolor.B; + return rgb; - } else { @@ -3598,17 +3565,12 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api if ((m_item.PermsMask & ScriptBaseClass.PERMISSION_TRIGGER_ANIMATION) != 0) { - UUID animID = new UUID(); - - if (!UUID.TryParse(anim, out animID)) - { - animID = InventoryKey(anim); - } - ScenePresence presence = World.GetScenePresence(m_item.PermsGranter); if (presence != null) { + UUID animID = KeyOrName(anim); + if (animID == UUID.Zero) presence.Animator.RemoveAnimation(anim); else @@ -3737,9 +3699,32 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api } ScenePresence presence = World.GetScenePresence(agentID); - if (presence != null) { + // If permissions are being requested from an NPC and were not implicitly granted above then + // auto grant all reuqested permissions if the script is owned by the NPC or the NPCs owner + INPCModule npcModule = World.RequestModuleInterface(); + if (npcModule != null && npcModule.IsNPC(agentID, World)) + { + if (agentID == m_host.ParentGroup.OwnerID || npcModule.GetOwner(agentID) == m_host.ParentGroup.OwnerID) + { + lock (m_host.TaskInventory) + { + m_host.TaskInventory[m_item.ItemID].PermsGranter = agentID; + m_host.TaskInventory[m_item.ItemID].PermsMask = perm; + } + + m_ScriptEngine.PostScriptEvent( + m_item.ItemID, + new EventParams( + "run_time_permissions", new Object[] { new LSL_Integer(perm) }, new DetectParams[0])); + } + + // it is an NPC, exit even if the permissions werent granted above, they are not going to answer + // the question! + return; + } + string ownerName = resolveName(m_host.ParentGroup.RootPart.OwnerID); if (ownerName == String.Empty) ownerName = "(hippos)"; @@ -3762,10 +3747,9 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api } // Requested agent is not in range, refuse perms - m_ScriptEngine.PostScriptEvent(m_item.ItemID, new EventParams( - "run_time_permissions", new Object[] { - new LSL_Integer(0) }, - new DetectParams[0])); + m_ScriptEngine.PostScriptEvent( + m_item.ItemID, + new EventParams("run_time_permissions", new Object[] { new LSL_Integer(0) }, new DetectParams[0])); } void handleScriptAnswer(IClientAPI client, UUID taskID, UUID itemID, int answer) @@ -9456,7 +9440,8 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api public LSL_String llGetSimulatorHostname() { m_host.AddScriptLPS(1); - return System.Environment.MachineName; + IUrlModule UrlModule = World.RequestModuleInterface(); + return UrlModule.ExternalHostNameForLSL; } // @@ -9811,7 +9796,8 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api GridRegion info; - if (m_ScriptEngine.World.RegionInfo.RegionName == simulator) + if (m_ScriptEngine.World.RegionInfo.RegionName == simulator) //Det data for this simulator? + info = new GridRegion(m_ScriptEngine.World.RegionInfo); else info = m_ScriptEngine.World.GridService.GetRegionByName(m_ScriptEngine.World.RegionInfo.ScopeID, simulator); @@ -9824,10 +9810,25 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api ScriptSleep(1000); return UUID.Zero.ToString(); } - reply = new LSL_Vector( - info.RegionLocX, - info.RegionLocY, - 0).ToString(); + if (m_ScriptEngine.World.RegionInfo.RegionName != simulator) + { + //Hypergrid Region co-ordinates + uint rx = 0, ry = 0; + Utils.LongToUInts(Convert.ToUInt64(info.RegionSecret), out rx, out ry); + + reply = new LSL_Vector( + rx, + ry, + 0).ToString(); + } + else + { + //Local-cooridnates + reply = new LSL_Vector( + info.RegionLocX, + info.RegionLocY, + 0).ToString(); + } break; case ScriptBaseClass.DATA_SIM_STATUS: if (info != null) diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/OSSL_Api.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/OSSL_Api.cs index 51ace1ab4b..8237b608be 100644 --- a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/OSSL_Api.cs +++ b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/OSSL_Api.cs @@ -960,21 +960,25 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api UUID avatarID = (UUID)avatar; m_host.AddScriptLPS(1); + + // FIXME: What we really want to do here is factor out the similar code in llStopAnimation() to a common + // method (though see that doesn't do the is animation check, which is probably a bug) and have both + // these functions call that common code. However, this does mean navigating the brain-dead requirement + // of calling InitLSL() if (World.Entities.ContainsKey(avatarID) && World.Entities[avatarID] is ScenePresence) { ScenePresence target = (ScenePresence)World.Entities[avatarID]; if (target != null) { - UUID animID = UUID.Zero; - m_host.TaskInventory.LockItemsForRead(true); - foreach (KeyValuePair inv in m_host.TaskInventory) + UUID animID; + + if (!UUID.TryParse(animation, out animID)) { - if (inv.Value.Name == animation) - { - if (inv.Value.Type == (int)AssetType.Animation) - animID = inv.Value.AssetID; - continue; - } + TaskInventoryItem item = m_host.Inventory.GetInventoryItem(animation); + if (item != null && item.Type == (int)AssetType.Animation) + animID = item.AssetID; + else + animID = UUID.Zero; } m_host.TaskInventory.LockItemsForRead(false); diff --git a/OpenSim/Server/Handlers/Simulation/AgentHandlers.cs b/OpenSim/Server/Handlers/Simulation/AgentHandlers.cs index 8f6fa52cfd..d772c391ac 100644 --- a/OpenSim/Server/Handlers/Simulation/AgentHandlers.cs +++ b/OpenSim/Server/Handlers/Simulation/AgentHandlers.cs @@ -149,13 +149,16 @@ namespace OpenSim.Server.Handlers.Simulation responsedata["int_response_code"] = HttpStatusCode.OK; - OSDMap resp = new OSDMap(2); + OSDMap resp = new OSDMap(3); resp["success"] = OSD.FromBoolean(result); resp["reason"] = OSD.FromString(reason); resp["version"] = OSD.FromString(version); - responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp); + // We must preserve defaults here, otherwise a false "success" will not be put into the JSON map! + responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp, true); + +// Console.WriteLine("str_response_string [{0}]", responsedata["str_response_string"]); } protected virtual void DoAgentGet(Hashtable request, Hashtable responsedata, UUID id, UUID regionID) @@ -569,7 +572,7 @@ namespace OpenSim.Server.Handlers.Simulation AgentData agent = new AgentData(); try { - agent.Unpack(args, m_SimulationService.GetScene(destination.RegionHandle)); + agent.Unpack(args, m_SimulationService.GetScene(destination.RegionID)); } catch (Exception ex) { @@ -589,7 +592,7 @@ namespace OpenSim.Server.Handlers.Simulation AgentPosition agent = new AgentPosition(); try { - agent.Unpack(args, m_SimulationService.GetScene(destination.RegionHandle)); + agent.Unpack(args, m_SimulationService.GetScene(destination.RegionID)); } catch (Exception ex) { diff --git a/OpenSim/Server/Handlers/Simulation/ObjectHandlers.cs b/OpenSim/Server/Handlers/Simulation/ObjectHandlers.cs index f0d8f69827..a4d03ba891 100644 --- a/OpenSim/Server/Handlers/Simulation/ObjectHandlers.cs +++ b/OpenSim/Server/Handlers/Simulation/ObjectHandlers.cs @@ -161,7 +161,7 @@ namespace OpenSim.Server.Handlers.Simulation if (args.ContainsKey("extra") && args["extra"] != null) extraStr = args["extra"].AsString(); - IScene s = m_SimulationService.GetScene(destination.RegionHandle); + IScene s = m_SimulationService.GetScene(destination.RegionID); ISceneObject sog = null; try { diff --git a/OpenSim/Services/Connectors/Simulation/SimulationDataService.cs b/OpenSim/Services/Connectors/Simulation/SimulationDataService.cs index ccef50b473..c9cbbfa500 100644 --- a/OpenSim/Services/Connectors/Simulation/SimulationDataService.cs +++ b/OpenSim/Services/Connectors/Simulation/SimulationDataService.cs @@ -148,5 +148,21 @@ namespace OpenSim.Services.Connectors { m_database.RemoveRegionWindlightSettings(regionID); } + + public string LoadRegionEnvironmentSettings(UUID regionUUID) + { + return m_database.LoadRegionEnvironmentSettings(regionUUID); + } + + public void StoreRegionEnvironmentSettings(UUID regionUUID, string settings) + { + m_database.StoreRegionEnvironmentSettings(regionUUID, settings); + } + + public void RemoveRegionEnvironmentSettings(UUID regionUUID) + { + m_database.RemoveRegionEnvironmentSettings(regionUUID); + } + } } diff --git a/OpenSim/Services/Connectors/Simulation/SimulationServiceConnector.cs b/OpenSim/Services/Connectors/Simulation/SimulationServiceConnector.cs index 5037543024..cd9338660b 100644 --- a/OpenSim/Services/Connectors/Simulation/SimulationServiceConnector.cs +++ b/OpenSim/Services/Connectors/Simulation/SimulationServiceConnector.cs @@ -62,7 +62,7 @@ namespace OpenSim.Services.Connectors.Simulation //m_Region = region; } - public IScene GetScene(ulong regionHandle) + public IScene GetScene(UUID regionId) { return null; } @@ -320,29 +320,40 @@ namespace OpenSim.Services.Connectors.Simulation { OSDMap data = (OSDMap)result["_Result"]; + // FIXME: If there is a _Result map then it's the success key here that indicates the true success + // or failure, not the sibling result node. + success = data["success"]; + reason = data["reason"].AsString(); if (data["version"] != null && data["version"].AsString() != string.Empty) version = data["version"].AsString(); - m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: QueryAccess to {0} returned {1} version {2} ({3})", uri, success, version, data["version"].AsString()); + m_log.DebugFormat( + "[REMOTE SIMULATION CONNECTOR]: QueryAccess to {0} returned {1}, reason {2}, version {3} ({4})", + uri, success, reason, version, data["version"].AsString()); } if (!success) { - if (result.ContainsKey("Message")) + // If we don't check this then OpenSimulator 0.7.3.1 and some period before will never see the + // actual failure message + if (!result.ContainsKey("_Result")) { - string message = result["Message"].AsString(); - if (message == "Service request failed: [MethodNotAllowed] MethodNotAllowed") // Old style region + if (result.ContainsKey("Message")) { - 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; + string message = result["Message"].AsString(); + if (message == "Service request failed: [MethodNotAllowed] MethodNotAllowed") // Old style region + { + 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"; } - - reason = result["Message"]; - } - else - { - reason = "Communications failure"; } return false; @@ -356,7 +367,7 @@ namespace OpenSim.Services.Connectors.Simulation } catch (Exception e) { - m_log.WarnFormat("[REMOTE SIMULATION CONNECTOR] QueryAcess failed with exception; {0}",e.ToString()); + m_log.WarnFormat("[REMOTE SIMULATION CONNECTOR] QueryAcesss failed with exception; {0}",e.ToString()); } return false; diff --git a/OpenSim/Services/GridService/GridService.cs b/OpenSim/Services/GridService/GridService.cs index 3dc87bc5d5..8a60ca5467 100644 --- a/OpenSim/Services/GridService/GridService.cs +++ b/OpenSim/Services/GridService/GridService.cs @@ -509,19 +509,21 @@ namespace OpenSim.Services.GridService return; } - MainConsole.Instance.Output("Region Name Region UUID"); - MainConsole.Instance.Output("Location URI"); - MainConsole.Instance.Output("Owner ID Flags"); - MainConsole.Instance.Output("-------------------------------------------------------------------------------"); foreach (RegionData r in regions) { OpenSim.Data.RegionFlags flags = (OpenSim.Data.RegionFlags)Convert.ToInt32(r.Data["flags"]); - MainConsole.Instance.Output(String.Format("{0,-20} {1}\n{2,-20} {3}\n{4,-39} {5}\n\n", - r.RegionName, r.RegionID, - String.Format("{0},{1}", r.posX / Constants.RegionSize, r.posY / Constants.RegionSize), - r.Data["serverURI"], - r.Data["owner_uuid"], flags)); + + ConsoleDisplayList dispList = new ConsoleDisplayList(); + dispList.AddRow("Region Name", r.RegionName); + dispList.AddRow("Region ID", r.RegionID); + dispList.AddRow("Location", string.Format("{0},{1}", r.coordX, r.coordY)); + dispList.AddRow("URI", r.Data["serverURI"]); + dispList.AddRow("Owner ID", r.Data["owner_uuid"]); + dispList.AddRow("Flags", flags); + + MainConsole.Instance.Output(dispList.ToString()); } + return; } diff --git a/OpenSim/Services/Interfaces/ISimulationService.cs b/OpenSim/Services/Interfaces/ISimulationService.cs index 7940256ab5..d9f242bcd6 100644 --- a/OpenSim/Services/Interfaces/ISimulationService.cs +++ b/OpenSim/Services/Interfaces/ISimulationService.cs @@ -35,7 +35,17 @@ namespace OpenSim.Services.Interfaces { public interface ISimulationService { - IScene GetScene(ulong regionHandle); + /// + /// Retrieve the scene with the given region ID. + /// + /// + /// Region identifier. + /// + /// + /// The scene. + /// + IScene GetScene(UUID regionId); + ISimulationService GetInnerService(); #region Agents diff --git a/OpenSim/Services/InventoryService/XInventoryService.cs b/OpenSim/Services/InventoryService/XInventoryService.cs index eed88bd391..3355428cf4 100644 --- a/OpenSim/Services/InventoryService/XInventoryService.cs +++ b/OpenSim/Services/InventoryService/XInventoryService.cs @@ -302,7 +302,8 @@ namespace OpenSim.Services.InventoryService public virtual bool AddFolder(InventoryFolderBase folder) { - //m_log.DebugFormat("[XINVENTORY]: Add folder {0} type {1} in parent {2}", folder.Name, folder.Type, folder.ParentID); +// m_log.DebugFormat("[XINVENTORY]: Add folder {0} type {1} in parent {2}", folder.Name, folder.Type, folder.ParentID); + InventoryFolderBase check = GetFolder(folder); if (check != null) return false; @@ -327,27 +328,36 @@ namespace OpenSim.Services.InventoryService public virtual bool UpdateFolder(InventoryFolderBase folder) { - //m_log.DebugFormat("[XINVENTORY]: Update folder {0} {1} ({2})", folder.Name, folder.Type, folder.ID); +// m_log.DebugFormat("[XINVENTORY]: Update folder {0} {1} ({2})", folder.Name, folder.Type, folder.ID); + XInventoryFolder xFolder = ConvertFromOpenSim(folder); InventoryFolderBase check = GetFolder(folder); + if (check == null) return AddFolder(folder); - if (check.Type != -1 || xFolder.type != -1) + if ((check.Type != (short)AssetType.Unknown || xFolder.type != (short)AssetType.Unknown) + && (check.Type != (short)AssetType.OutfitFolder || xFolder.type != (short)AssetType.OutfitFolder)) { if (xFolder.version < check.Version) { - //m_log.DebugFormat("[XINVENTORY]: {0} < {1} can't do", xFolder.version, check.Version); +// m_log.DebugFormat("[XINVENTORY]: {0} < {1} can't do", xFolder.version, check.Version); return false; } + check.Version = (ushort)xFolder.version; xFolder = ConvertFromOpenSim(check); - //m_log.DebugFormat("[XINVENTORY]: Storing {0} {1} {2}", xFolder.folderName, xFolder.version, xFolder.type); + +// m_log.DebugFormat( +// "[XINVENTORY]: Storing version only update to system folder {0} {1} {2}", +// xFolder.folderName, xFolder.version, xFolder.type); + return m_Database.StoreFolder(xFolder); } if (xFolder.version < check.Version) xFolder.version = check.Version; + xFolder.folderID = check.ID; return m_Database.StoreFolder(xFolder); @@ -433,7 +443,6 @@ namespace OpenSim.Services.InventoryService public virtual bool UpdateItem(InventoryItemBase item) { -// throw new Exception("urrgh"); if (!m_AllowDelete) if (item.AssetType == (sbyte)AssetType.Link || item.AssetType == (sbyte)AssetType.LinkFolder) return false; diff --git a/OpenSim/Tests/Common/Helpers/SceneHelpers.cs b/OpenSim/Tests/Common/Helpers/SceneHelpers.cs index 59829d994f..239afc0aee 100644 --- a/OpenSim/Tests/Common/Helpers/SceneHelpers.cs +++ b/OpenSim/Tests/Common/Helpers/SceneHelpers.cs @@ -566,7 +566,7 @@ namespace OpenSim.Tests.Common /// public static SceneObjectPart AddSceneObject(Scene scene) { - return AddSceneObject(scene, "Test Object"); + return AddSceneObject(scene, "Test Object", UUID.Zero); } /// @@ -574,10 +574,11 @@ namespace OpenSim.Tests.Common /// /// /// + /// /// - public static SceneObjectPart AddSceneObject(Scene scene, string name) + public static SceneObjectPart AddSceneObject(Scene scene, string name, UUID ownerId) { - SceneObjectPart part = CreateSceneObjectPart(name, UUID.Random(), UUID.Zero); + SceneObjectPart part = CreateSceneObjectPart(name, UUID.Random(), ownerId); //part.UpdatePrimFlags(false, false, true); //part.ObjectFlags |= (uint)PrimFlags.Phantom; diff --git a/OpenSim/Tests/Common/Mock/MockRegionDataPlugin.cs b/OpenSim/Tests/Common/Mock/MockRegionDataPlugin.cs index 579d41ca03..1845eb94f3 100644 --- a/OpenSim/Tests/Common/Mock/MockRegionDataPlugin.cs +++ b/OpenSim/Tests/Common/Mock/MockRegionDataPlugin.cs @@ -112,6 +112,21 @@ namespace OpenSim.Data.Null { m_store.StoreRegionWindlightSettings(wl); } + + public string LoadRegionEnvironmentSettings(UUID regionUUID) + { + return m_store.LoadRegionEnvironmentSettings(regionUUID); + } + + public void StoreRegionEnvironmentSettings(UUID regionUUID, string settings) + { + m_store.StoreRegionEnvironmentSettings(regionUUID, settings); + } + + public void RemoveRegionEnvironmentSettings(UUID regionUUID) + { + m_store.RemoveRegionEnvironmentSettings(regionUUID); + } } /// @@ -158,7 +173,25 @@ namespace OpenSim.Data.Null { //This connector doesn't support the windlight module yet } - + + #region Environment Settings + public string LoadRegionEnvironmentSettings(UUID regionUUID) + { + //This connector doesn't support the Environment module yet + return string.Empty; + } + + public void StoreRegionEnvironmentSettings(UUID regionUUID, string settings) + { + //This connector doesn't support the Environment module yet + } + + public void RemoveRegionEnvironmentSettings(UUID regionUUID) + { + //This connector doesn't support the Environment module yet + } + #endregion + public RegionSettings LoadRegionSettings(UUID regionUUID) { RegionSettings rs = null; diff --git a/bin/OpenSimDefaults.ini b/bin/OpenSimDefaults.ini index ea83f91e08..6718ccac33 100644 --- a/bin/OpenSimDefaults.ini +++ b/bin/OpenSimDefaults.ini @@ -534,7 +534,7 @@ ; silly vanity "Facelights" dead. Sorry, head mounted miner's lamps ; will also be affected. ; - ;DisableFacelights = "false(1815) + ;DisableFacelights = false [ClientStack.LindenCaps] ;; Long list of capabilities taken from @@ -549,6 +549,7 @@ Cap_CopyInventoryFromNotecard = "localhost" Cap_DispatchRegionInfo = "" Cap_EstateChangeInfo = "" + Cap_EnvironmentSettings = "localhost" Cap_EventQueueGet = "localhost" Cap_FetchInventory = "" Cap_ObjectMedia = "localhost"