Merged with main AND partial implementation of teleport based load balancing. Did not intend to combine the merge with these changes.

dsg
Dan Lake 2010-08-16 10:23:50 -07:00
commit 8f8ef75034
172 changed files with 4214 additions and 2430 deletions

View File

@ -95,6 +95,7 @@ what it is today.
* Mic Bowman * Mic Bowman
* Michelle Argus * Michelle Argus
* Michael Cortez (The Flotsam Project, http://osflotsam.org/) * Michael Cortez (The Flotsam Project, http://osflotsam.org/)
* Micheil Merlin
* Mike Osias (IBM) * Mike Osias (IBM)
* Mike Pitman (IBM) * Mike Pitman (IBM)
* mikkopa/_someone - RealXtend * mikkopa/_someone - RealXtend

View File

@ -1043,11 +1043,6 @@ namespace OpenSim.Client.MXP.ClientStack
// Minimap function, not used. // Minimap function, not used.
} }
public void AttachObject(uint localID, Quaternion rotation, byte attachPoint, UUID ownerID)
{
// Need to translate to MXP somehow
}
public void SetChildAgentThrottle(byte[] throttle) public void SetChildAgentThrottle(byte[] throttle)
{ {
// Need to translate to MXP somehow // Need to translate to MXP somehow
@ -1719,5 +1714,9 @@ namespace OpenSim.Client.MXP.ClientStack
public void SendTextBoxRequest(string message, int chatChannel, string objectname, string ownerFirstName, string ownerLastName, UUID objectId) public void SendTextBoxRequest(string message, int chatChannel, string objectname, string ownerFirstName, string ownerLastName, UUID objectId)
{ {
} }
public void StopFlying(ISceneEntity presence)
{
}
} }
} }

View File

@ -601,11 +601,6 @@ namespace OpenSim.Client.Sirikata.ClientStack
throw new System.NotImplementedException(); throw new System.NotImplementedException();
} }
public void AttachObject(uint localID, Quaternion rotation, byte attachPoint, UUID ownerID)
{
throw new System.NotImplementedException();
}
public void SetChildAgentThrottle(byte[] throttle) public void SetChildAgentThrottle(byte[] throttle)
{ {
throw new System.NotImplementedException(); throw new System.NotImplementedException();
@ -1207,6 +1202,10 @@ namespace OpenSim.Client.Sirikata.ClientStack
{ {
} }
public void StopFlying(ISceneEntity presence)
{
}
#endregion #endregion
} }
} }

View File

@ -607,11 +607,6 @@ namespace OpenSim.Client.VWoHTTP.ClientStack
throw new System.NotImplementedException(); throw new System.NotImplementedException();
} }
public void AttachObject(uint localID, Quaternion rotation, byte attachPoint, UUID ownerID)
{
throw new System.NotImplementedException();
}
public void SetChildAgentThrottle(byte[] throttle) public void SetChildAgentThrottle(byte[] throttle)
{ {
throw new System.NotImplementedException(); throw new System.NotImplementedException();
@ -1222,5 +1217,9 @@ namespace OpenSim.Client.VWoHTTP.ClientStack
public void SendTextBoxRequest(string message, int chatChannel, string objectname, string ownerFirstName, string ownerLastName, UUID objectId) public void SendTextBoxRequest(string message, int chatChannel, string objectname, string ownerFirstName, string ownerLastName, UUID objectId)
{ {
} }
public void StopFlying(ISceneEntity presence)
{
}
} }
} }

View File

@ -29,6 +29,7 @@ using Nini.Config;
using log4net; using log4net;
using System.Reflection; using System.Reflection;
using System; using System;
using System.IO;
using System.Xml; using System.Xml;
using System.Collections.Generic; using System.Collections.Generic;
using OpenSim.Server.Base; using OpenSim.Server.Base;
@ -73,9 +74,18 @@ namespace OpenSim.ConsoleClient
Requester.MakeRequest("http://"+m_Host+":"+m_Port.ToString()+"/StartSession/", String.Format("USER={0}&PASS={1}", m_User, m_Pass), LoginReply); Requester.MakeRequest("http://"+m_Host+":"+m_Port.ToString()+"/StartSession/", String.Format("USER={0}&PASS={1}", m_User, m_Pass), LoginReply);
int res = m_Server.Run(); string pidFile = serverConfig.GetString("PIDFile", String.Empty);
Environment.Exit(res); while (m_Server.Running)
{
System.Threading.Thread.Sleep(500);
// MainConsole.Instance.Prompt();
}
if (pidFile != String.Empty)
File.Delete(pidFile);
Environment.Exit(0);
return 0; return 0;
} }
@ -83,13 +93,14 @@ namespace OpenSim.ConsoleClient
private static void SendCommand(string module, string[] cmd) private static void SendCommand(string module, string[] cmd)
{ {
string sendCmd = ""; string sendCmd = "";
if (cmd.Length > 1) string[] cmdlist = new string[cmd.Length - 1];
{
sendCmd = cmd[0]; sendCmd = cmd[0];
Array.Copy(cmd, 1, cmd, 0, cmd.Length-1); if (cmd.Length > 1)
Array.Resize(ref cmd, cmd.Length-1); {
sendCmd += "\"" + String.Join("\" \"", cmd) + "\""; Array.Copy(cmd, 1, cmdlist, 0, cmd.Length - 1);
sendCmd += " \"" + String.Join("\" \"", cmdlist) + "\"";
} }
Requester.MakeRequest("http://"+m_Host+":"+m_Port.ToString()+"/SessionCommand/", String.Format("ID={0}&COMMAND={1}", m_SessionID, sendCmd), CommandReply); Requester.MakeRequest("http://"+m_Host+":"+m_Port.ToString()+"/SessionCommand/", String.Format("ID={0}&COMMAND={1}", m_SessionID, sendCmd), CommandReply);
@ -183,16 +194,27 @@ namespace OpenSim.ConsoleClient
while (lines.Count > 100) while (lines.Count > 100)
lines.RemoveAt(0); lines.RemoveAt(0);
string prompt = String.Empty;
foreach (string l in lines) foreach (string l in lines)
{ {
string[] parts = l.Split(new char[] {':'}, 3); string[] parts = l.Split(new char[] {':'}, 3);
if (parts.Length != 3) if (parts.Length != 3)
continue; continue;
if (parts[2].StartsWith("+++") || parts[2].StartsWith("-++"))
prompt = parts[2];
else
MainConsole.Instance.Output(parts[2].Trim(), parts[1]); MainConsole.Instance.Output(parts[2].Trim(), parts[1]);
} }
Requester.MakeRequest(requestUrl, requestData, ReadResponses); Requester.MakeRequest(requestUrl, requestData, ReadResponses);
if (prompt.StartsWith("+++"))
MainConsole.Instance.ReadLine(prompt.Substring(3), true, true);
else if (prompt.StartsWith("-++"))
SendCommand(String.Empty, new string[] { MainConsole.Instance.ReadLine(prompt.Substring(3), false, true) });
} }
public static void CommandReply(string requestUrl, string requestData, string replyData) public static void CommandReply(string requestUrl, string requestData, string replyData)

View File

@ -51,7 +51,7 @@ namespace OpenSim.Data
public int inventoryNextPermissions; public int inventoryNextPermissions;
public int inventoryCurrentPermissions; public int inventoryCurrentPermissions;
public int invType; public int invType;
public UUID creatorID; public string creatorID;
public int inventoryBasePermissions; public int inventoryBasePermissions;
public int inventoryEveryOnePermissions; public int inventoryEveryOnePermissions;
public int salePrice; public int salePrice;

View File

@ -67,7 +67,6 @@ namespace OpenSim.Data
/// really want is the assembly of your database class. /// really want is the assembly of your database class.
/// ///
/// </summary> /// </summary>
public class Migration public class Migration
{ {
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
@ -173,8 +172,6 @@ namespace OpenSim.Data
ExecuteScript(_conn, script); ExecuteScript(_conn, script);
} }
public void Update() public void Update()
{ {
InitMigrationsTable(); InitMigrationsTable();
@ -186,8 +183,8 @@ namespace OpenSim.Data
return; return;
// to prevent people from killing long migrations. // to prevent people from killing long migrations.
m_log.InfoFormat("[MIGRATIONS] Upgrading {0} to latest revision {1}.", _type, migrations.Keys[migrations.Count - 1]); m_log.InfoFormat("[MIGRATIONS]: Upgrading {0} to latest revision {1}.", _type, migrations.Keys[migrations.Count - 1]);
m_log.Info("[MIGRATIONS] NOTE: this may take a while, don't interupt this process!"); m_log.Info("[MIGRATIONS]: NOTE - this may take a while, don't interrupt this process!");
foreach (KeyValuePair<int, string[]> kvp in migrations) foreach (KeyValuePair<int, string[]> kvp in migrations)
{ {
@ -206,7 +203,7 @@ namespace OpenSim.Data
} }
catch (Exception e) catch (Exception e)
{ {
m_log.DebugFormat("[MIGRATIONS] Cmd was {0}", e.Message.Replace("\n", " ")); m_log.DebugFormat("[MIGRATIONS]: Cmd was {0}", e.Message.Replace("\n", " "));
m_log.Debug("[MIGRATIONS]: An error has occurred in the migration. This may mean you could see errors trying to run OpenSim. If you see database related errors, you will need to fix the issue manually. Continuing."); m_log.Debug("[MIGRATIONS]: An error has occurred in the migration. This may mean you could see errors trying to run OpenSim. If you see database related errors, you will need to fix the issue manually. Continuing.");
ExecuteScript("ROLLBACK;"); ExecuteScript("ROLLBACK;");
} }

View File

@ -64,11 +64,19 @@ namespace OpenSim.Data.MySQL
public bool StoreFolder(XInventoryFolder folder) public bool StoreFolder(XInventoryFolder folder)
{ {
if (folder.folderName.Length > 64)
folder.folderName = folder.folderName.Substring(0, 64);
return m_Folders.Store(folder); return m_Folders.Store(folder);
} }
public bool StoreItem(XInventoryItem item) public bool StoreItem(XInventoryItem item)
{ {
if (item.inventoryName.Length > 64)
item.inventoryName = item.inventoryName.Substring(0, 64);
if (item.inventoryDescription.Length > 128)
item.inventoryDescription = item.inventoryDescription.Substring(0, 128);
return m_Items.Store(item); return m_Items.Store(item);
} }

View File

@ -73,5 +73,5 @@ ALTER TABLE assets ADD COLUMN asset_flags INTEGER NOT NULL DEFAULT 0;
:VERSION 8 :VERSION 8
ALTER TABLE assets ADD COLUMN CreatorID varchar(36) NOT NULL DEFAULT ''; ALTER TABLE assets ADD COLUMN CreatorID varchar(128) NOT NULL DEFAULT '';

View File

@ -91,3 +91,11 @@ update inventoryitems set creatorID = '00000000-0000-0000-0000-000000000000' whe
alter table inventoryitems modify column creatorID varchar(36) not NULL default '00000000-0000-0000-0000-000000000000'; alter table inventoryitems modify column creatorID varchar(36) not NULL default '00000000-0000-0000-0000-000000000000';
COMMIT; COMMIT;
:VERSION 5 # ------------
BEGIN;
alter table inventoryitems modify column creatorID varchar(128) not NULL default '00000000-0000-0000-0000-000000000000';
COMMIT;

View File

@ -717,9 +717,86 @@ ALTER TABLE regionsettings ADD COLUMN loaded_creation_datetime int unsigned NOT
COMMIT; COMMIT;
:VERSION 32
BEGIN;
CREATE TABLE `regionwindlight` (
`region_id` varchar(36) NOT NULL DEFAULT '000000-0000-0000-0000-000000000000',
`water_color_r` float(9,6) unsigned NOT NULL DEFAULT '4.000000',
`water_color_g` float(9,6) unsigned NOT NULL DEFAULT '38.000000',
`water_color_b` float(9,6) unsigned NOT NULL DEFAULT '64.000000',
`water_fog_density_exponent` float(3,1) unsigned NOT NULL DEFAULT '4.0',
`underwater_fog_modifier` float(3,2) unsigned NOT NULL DEFAULT '0.25',
`reflection_wavelet_scale_1` float(3,1) unsigned NOT NULL DEFAULT '2.0',
`reflection_wavelet_scale_2` float(3,1) unsigned NOT NULL DEFAULT '2.0',
`reflection_wavelet_scale_3` float(3,1) unsigned NOT NULL DEFAULT '2.0',
`fresnel_scale` float(3,2) unsigned NOT NULL DEFAULT '0.40',
`fresnel_offset` float(3,2) unsigned NOT NULL DEFAULT '0.50',
`refract_scale_above` float(3,2) unsigned NOT NULL DEFAULT '0.03',
`refract_scale_below` float(3,2) unsigned NOT NULL DEFAULT '0.20',
`blur_multiplier` float(4,3) unsigned NOT NULL DEFAULT '0.040',
`big_wave_direction_x` float(3,2) NOT NULL DEFAULT '1.05',
`big_wave_direction_y` float(3,2) NOT NULL DEFAULT '-0.42',
`little_wave_direction_x` float(3,2) NOT NULL DEFAULT '1.11',
`little_wave_direction_y` float(3,2) NOT NULL DEFAULT '-1.16',
`normal_map_texture` varchar(36) NOT NULL DEFAULT '822ded49-9a6c-f61c-cb89-6df54f42cdf4',
`horizon_r` float(3,2) unsigned NOT NULL DEFAULT '0.25',
`horizon_g` float(3,2) unsigned NOT NULL DEFAULT '0.25',
`horizon_b` float(3,2) unsigned NOT NULL DEFAULT '0.32',
`horizon_i` float(3,2) unsigned NOT NULL DEFAULT '0.32',
`haze_horizon` float(3,2) unsigned NOT NULL DEFAULT '0.19',
`blue_density_r` float(3,2) unsigned NOT NULL DEFAULT '0.12',
`blue_density_g` float(3,2) unsigned NOT NULL DEFAULT '0.22',
`blue_density_b` float(3,2) unsigned NOT NULL DEFAULT '0.38',
`blue_density_i` float(3,2) unsigned NOT NULL DEFAULT '0.38',
`haze_density` float(3,2) unsigned NOT NULL DEFAULT '0.70',
`density_multiplier` float(3,2) unsigned NOT NULL DEFAULT '0.18',
`distance_multiplier` float(4,1) unsigned NOT NULL DEFAULT '0.8',
`max_altitude` int(4) unsigned NOT NULL DEFAULT '1605',
`sun_moon_color_r` float(3,2) unsigned NOT NULL DEFAULT '0.24',
`sun_moon_color_g` float(3,2) unsigned NOT NULL DEFAULT '0.26',
`sun_moon_color_b` float(3,2) unsigned NOT NULL DEFAULT '0.30',
`sun_moon_color_i` float(3,2) unsigned NOT NULL DEFAULT '0.30',
`sun_moon_position` float(4,3) unsigned NOT NULL DEFAULT '0.317',
`ambient_r` float(3,2) unsigned NOT NULL DEFAULT '0.35',
`ambient_g` float(3,2) unsigned NOT NULL DEFAULT '0.35',
`ambient_b` float(3,2) unsigned NOT NULL DEFAULT '0.35',
`ambient_i` float(3,2) unsigned NOT NULL DEFAULT '0.35',
`east_angle` float(3,2) unsigned NOT NULL DEFAULT '0.00',
`sun_glow_focus` float(3,2) unsigned NOT NULL DEFAULT '0.10',
`sun_glow_size` float(3,2) unsigned NOT NULL DEFAULT '1.75',
`scene_gamma` float(4,2) unsigned NOT NULL DEFAULT '1.00',
`star_brightness` float(3,2) unsigned NOT NULL DEFAULT '0.00',
`cloud_color_r` float(3,2) unsigned NOT NULL DEFAULT '0.41',
`cloud_color_g` float(3,2) unsigned NOT NULL DEFAULT '0.41',
`cloud_color_b` float(3,2) unsigned NOT NULL DEFAULT '0.41',
`cloud_color_i` float(3,2) unsigned NOT NULL DEFAULT '0.41',
`cloud_x` float(3,2) unsigned NOT NULL DEFAULT '1.00',
`cloud_y` float(3,2) unsigned NOT NULL DEFAULT '0.53',
`cloud_density` float(3,2) unsigned NOT NULL DEFAULT '1.00',
`cloud_coverage` float(3,2) unsigned NOT NULL DEFAULT '0.27',
`cloud_scale` float(3,2) unsigned NOT NULL DEFAULT '0.42',
`cloud_detail_x` float(3,2) unsigned NOT NULL DEFAULT '1.00',
`cloud_detail_y` float(3,2) unsigned NOT NULL DEFAULT '0.53',
`cloud_detail_density` float(3,2) unsigned NOT NULL DEFAULT '0.12',
`cloud_scroll_x` float(3,2) unsigned NOT NULL DEFAULT '0.20',
`cloud_scroll_x_lock` tinyint(1) unsigned NOT NULL DEFAULT '0',
`cloud_scroll_y` float(3,2) unsigned NOT NULL DEFAULT '0.01',
`cloud_scroll_y_lock` tinyint(1) unsigned NOT NULL DEFAULT '0',
`draw_classic_clouds` tinyint(1) unsigned NOT NULL DEFAULT '1',
PRIMARY KEY (`region_id`)
);
:VERSION 33 #--------------------- :VERSION 33 #---------------------
BEGIN; BEGIN;
ALTER TABLE regionsettings ADD map_tile_ID CHAR(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000'; ALTER TABLE regionsettings ADD map_tile_ID CHAR(36) NOT NULL DEFAULT '00000000-0000-0000-0000-000000000000';
COMMIT; COMMIT;
:VERSION 34 #---------------------
BEGIN;
ALTER TABLE `regionwindlight` CHANGE COLUMN `cloud_scroll_x` `cloud_scroll_x` FLOAT(4,2) NOT NULL DEFAULT '0.20' AFTER `cloud_detail_density`, CHANGE COLUMN `cloud_scroll_y` `cloud_scroll_y` FLOAT(4,2) NOT NULL DEFAULT '0.01' AFTER `cloud_scroll_x_lock`;
COMMIT;

View File

@ -76,6 +76,5 @@ namespace OpenSim.Data.Null
return false; return false;
} }
} }
} }

View File

@ -88,7 +88,7 @@ namespace OpenSim.Data.Null
m_DataByUUID[data.PrincipalID] = data; m_DataByUUID[data.PrincipalID] = data;
m_DataByName[data.FirstName + " " + data.LastName] = data; m_DataByName[data.FirstName + " " + data.LastName] = data;
if (data.Data.ContainsKey("Email") && data.Data["Email"] != string.Empty) if (data.Data.ContainsKey("Email") && data.Data["Email"] != null && data.Data["Email"] != string.Empty)
m_DataByEmail[data.Data["Email"]] = data; m_DataByEmail[data.Data["Email"]] = data;
return true; return true;

View File

@ -3,19 +3,10 @@
<Import assembly="OpenSim.Data.dll" /> <Import assembly="OpenSim.Data.dll" />
<Import assembly="OpenSim.Framework.dll" /> <Import assembly="OpenSim.Framework.dll" />
</Runtime> </Runtime>
<ExtensionPoint path = "/OpenSim/GridData">
<ExtensionNode name="Plugin" type="OpenSim.Framework.PluginExtensionNode" objectType="OpenSim.Data.IGridDataPlugin" />
</ExtensionPoint>
<ExtensionPoint path = "/OpenSim/LogData">
<ExtensionNode name="Plugin" type="OpenSim.Framework.PluginExtensionNode" objectType="OpenSim.Data.ILogDataPlugin" />
</ExtensionPoint>
<ExtensionPoint path = "/OpenSim/AssetData"> <ExtensionPoint path = "/OpenSim/AssetData">
<ExtensionNode name="Plugin" type="OpenSim.Framework.PluginExtensionNode" objectType="OpenSim.Data.IAssetDataPlugin" /> <ExtensionNode name="Plugin" type="OpenSim.Framework.PluginExtensionNode" objectType="OpenSim.Data.IAssetDataPlugin" />
</ExtensionPoint> </ExtensionPoint>
<ExtensionPoint path = "/OpenSim/InventoryData"> <ExtensionPoint path = "/OpenSim/InventoryData">
<ExtensionNode name="Plugin" type="OpenSim.Framework.PluginExtensionNode" objectType="OpenSim.Data.IInventoryDataPlugin" /> <ExtensionNode name="Plugin" type="OpenSim.Framework.PluginExtensionNode" objectType="OpenSim.Data.IInventoryDataPlugin" />
</ExtensionPoint> </ExtensionPoint>
<ExtensionPoint path = "/OpenSim/UserData">
<ExtensionNode name="Plugin" type="OpenSim.Framework.PluginExtensionNode" objectType="OpenSim.Data.IUserDataPlugin" />
</ExtensionPoint>
</Addin> </Addin>

View File

@ -1,38 +0,0 @@
BEGIN TRANSACTION;
CREATE TABLE inventoryfolders(
folderName varchar(255),
type integer,
version integer,
folderID varchar(255) primary key,
agentID varchar(255) not null default '00000000-0000-0000-0000-000000000000',
parentFolderID varchar(255) not null default '00000000-0000-0000-0000-000000000000');
CREATE TABLE inventoryitems(
assetID varchar(255),
assetType integer,
inventoryName varchar(255),
inventoryDescription varchar(255),
inventoryNextPermissions integer,
inventoryCurrentPermissions integer,
invType integer,
creatorID varchar(255),
inventoryBasePermissions integer,
inventoryEveryOnePermissions integer,
salePrice integer default 99,
saleType integer default 0,
creationDate integer default 2000,
groupID varchar(255) default '00000000-0000-0000-0000-000000000000',
groupOwned integer default 0,
flags integer default 0,
inventoryID varchar(255) primary key,
parentFolderID varchar(255) not null default '00000000-0000-0000-0000-000000000000',
avatarID varchar(255) not null default '00000000-0000-0000-0000-000000000000',
inventoryGroupPermissions integer not null default 0);
create index inventoryfolders_agentid on inventoryfolders(agentID);
create index inventoryfolders_parentid on inventoryfolders(parentFolderID);
create index inventoryitems_parentfolderid on inventoryitems(parentFolderID);
create index inventoryitems_avatarid on inventoryitems(avatarID);
COMMIT;

View File

@ -1,8 +0,0 @@
ATTACH 'inventoryStore.db' AS old;
BEGIN TRANSACTION;
INSERT INTO inventoryfolders (folderName, type, version, folderID, agentID, parentFolderID) SELECT `name` AS folderName, `type` AS type, `version` AS version, `UUID` AS folderID, `agentID` AS agentID, `parentID` AS parentFolderID from old.inventoryfolders;
INSERT INTO inventoryitems (assetID, assetType, inventoryName, inventoryDescription, inventoryNextPermissions, inventoryCurrentPermissions, invType, creatorID, inventoryBasePermissions, inventoryEveryOnePermissions, salePrice, saleType, creationDate, groupID, groupOwned, flags, inventoryID, parentFolderID, avatarID, inventoryGroupPermissions) SELECT `assetID`, `assetType` AS assetType, `inventoryName` AS inventoryName, `inventoryDescription` AS inventoryDescription, `inventoryNextPermissions` AS inventoryNextPermissions, `inventoryCurrentPermissions` AS inventoryCurrentPermissions, `invType` AS invType, `creatorsID` AS creatorID, `inventoryBasePermissions` AS inventoryBasePermissions, `inventoryEveryOnePermissions` AS inventoryEveryOnePermissions, `salePrice` AS salePrice, `saleType` AS saleType, `creationDate` AS creationDate, `groupID` AS groupID, `groupOwned` AS groupOwned, `flags` AS flags, `UUID` AS inventoryID, `parentFolderID` AS parentFolderID, `avatarID` AS avatarID, `inventoryGroupPermissions` AS inventoryGroupPermissions FROM old.inventoryitems;
COMMIT;

View File

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

View File

@ -55,7 +55,7 @@ CREATE TABLE assets(
Local, Local,
Temporary, Temporary,
asset_flags INTEGER NOT NULL DEFAULT 0, asset_flags INTEGER NOT NULL DEFAULT 0,
CreatorID varchar(36) default '', CreatorID varchar(128) default '',
Data); Data);
INSERT INTO assets(UUID,Name,Description,Type,Local,Temporary,Data) INSERT INTO assets(UUID,Name,Description,Type,Local,Temporary,Data)
@ -64,3 +64,4 @@ DROP TABLE assets_backup;
COMMIT; COMMIT;

View File

@ -1,4 +1,4 @@
:VERSION 1 :VERSION 1
BEGIN TRANSACTION; BEGIN TRANSACTION;
@ -219,59 +219,6 @@ COMMIT;
BEGIN TRANSACTION; BEGIN TRANSACTION;
CREATE TABLE estate_groups (
EstateID int(10) NOT NULL,
uuid char(36) NOT NULL
);
CREATE TABLE estate_managers (
EstateID int(10) NOT NULL,
uuid char(36) NOT NULL
);
CREATE TABLE estate_map (
RegionID char(36) NOT NULL default '00000000-0000-0000-0000-000000000000',
EstateID int(11) NOT NULL
);
CREATE TABLE estate_settings (
EstateID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
EstateName varchar(64) default NULL,
AbuseEmailToEstateOwner tinyint(4) NOT NULL,
DenyAnonymous tinyint(4) NOT NULL,
ResetHomeOnTeleport tinyint(4) NOT NULL,
FixedSun tinyint(4) NOT NULL,
DenyTransacted tinyint(4) NOT NULL,
BlockDwell tinyint(4) NOT NULL,
DenyIdentified tinyint(4) NOT NULL,
AllowVoice tinyint(4) NOT NULL,
UseGlobalTime tinyint(4) NOT NULL,
PricePerMeter int(11) NOT NULL,
TaxFree tinyint(4) NOT NULL,
AllowDirectTeleport tinyint(4) NOT NULL,
RedirectGridX int(11) NOT NULL,
RedirectGridY int(11) NOT NULL,
ParentEstateID int(10) NOT NULL,
SunPosition double NOT NULL,
EstateSkipScripts tinyint(4) NOT NULL,
BillableFactor float NOT NULL,
PublicAccess tinyint(4) NOT NULL
);
insert into estate_settings (EstateID,EstateName,AbuseEmailToEstateOwner,DenyAnonymous,ResetHomeOnTeleport,FixedSun,DenyTransacted,BlockDwell,DenyIdentified,AllowVoice,UseGlobalTime,PricePerMeter,TaxFree,AllowDirectTeleport,RedirectGridX,RedirectGridY,ParentEstateID,SunPosition,PublicAccess,EstateSkipScripts,BillableFactor) values ( 99, '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
delete from estate_settings;
CREATE TABLE estate_users (
EstateID int(10) NOT NULL,
uuid char(36) NOT NULL
);
CREATE TABLE estateban (
EstateID int(10) NOT NULL,
bannedUUID varchar(36) NOT NULL,
bannedIp varchar(16) NOT NULL,
bannedIpHostMask varchar(16) NOT NULL,
bannedNameMask varchar(64) default NULL
);
drop table regionsettings; drop table regionsettings;
CREATE TABLE regionsettings ( CREATE TABLE regionsettings (
regionUUID char(36) NOT NULL, regionUUID char(36) NOT NULL,
@ -307,7 +254,7 @@ CREATE TABLE regionsettings (
fixed_sun int(11) NOT NULL, fixed_sun int(11) NOT NULL,
sun_position float NOT NULL, sun_position float NOT NULL,
covenant char(36) default NULL, covenant char(36) default NULL,
Sandbox tinyint(4) NOT NULL, sandbox tinyint(4) NOT NULL,
PRIMARY KEY (regionUUID) PRIMARY KEY (regionUUID)
); );

View File

@ -0,0 +1,51 @@
:VERSION 1
BEGIN TRANSACTION;
CREATE TABLE inventoryfolders(
folderName varchar(64),
type integer,
version integer,
folderID varchar(36) primary key,
agentID varchar(36) not null default '00000000-0000-0000-0000-000000000000',
parentFolderID varchar(36) not null default '00000000-0000-0000-0000-000000000000');
CREATE TABLE inventoryitems(
assetID varchar(36),
assetType integer,
inventoryName varchar(64),
inventoryDescription varchar(128),
inventoryNextPermissions integer,
inventoryCurrentPermissions integer,
invType integer,
creatorID varchar(128),
inventoryBasePermissions integer,
inventoryEveryOnePermissions integer,
salePrice integer default 99,
saleType integer default 0,
creationDate integer default 2000,
groupID varchar(36) default '00000000-0000-0000-0000-000000000000',
groupOwned integer default 0,
flags integer default 0,
inventoryID varchar(36) primary key,
parentFolderID varchar(36) not null default '00000000-0000-0000-0000-000000000000',
avatarID varchar(36) not null default '00000000-0000-0000-0000-000000000000',
inventoryGroupPermissions integer not null default 0);
create index inventoryfolders_agentid on inventoryfolders(agentID);
create index inventoryfolders_parentid on inventoryfolders(parentFolderID);
create index inventoryitems_parentfolderid on inventoryitems(parentFolderID);
create index inventoryitems_avatarid on inventoryitems(avatarID);
COMMIT;
:VERSION 2
ATTACH 'inventoryStore.db' AS old;
BEGIN TRANSACTION;
INSERT INTO inventoryfolders (folderName, type, version, folderID, agentID, parentFolderID) SELECT `name` AS folderName, `type` AS type, `version` AS version, `UUID` AS folderID, `agentID` AS agentID, `parentID` AS parentFolderID from old.inventoryfolders;
INSERT INTO inventoryitems (assetID, assetType, inventoryName, inventoryDescription, inventoryNextPermissions, inventoryCurrentPermissions, invType, creatorID, inventoryBasePermissions, inventoryEveryOnePermissions, salePrice, saleType, creationDate, groupID, groupOwned, flags, inventoryID, parentFolderID, avatarID, inventoryGroupPermissions) SELECT `assetID`, `assetType` AS assetType, `inventoryName` AS inventoryName, `inventoryDescription` AS inventoryDescription, `inventoryNextPermissions` AS inventoryNextPermissions, `inventoryCurrentPermissions` AS inventoryCurrentPermissions, `invType` AS invType, `creatorsID` AS creatorID, `inventoryBasePermissions` AS inventoryBasePermissions, `inventoryEveryOnePermissions` AS inventoryEveryOnePermissions, `salePrice` AS salePrice, `saleType` AS saleType, `creationDate` AS creationDate, `groupID` AS groupID, `groupOwned` AS groupOwned, `flags` AS flags, `UUID` AS inventoryID, `parentFolderID` AS parentFolderID, `avatarID` AS avatarID, `inventoryGroupPermissions` AS inventoryGroupPermissions FROM old.inventoryitems;
COMMIT;

View File

@ -328,7 +328,7 @@ namespace OpenSim.Data.SQLite
public EstateSettings LoadEstateSettings(int estateID) public EstateSettings LoadEstateSettings(int estateID)
{ {
string sql = "select estate_settings."+String.Join(",estate_settings.", FieldList)+" from estate_settings where estate_settings.EstateID :EstateID"; string sql = "select estate_settings."+String.Join(",estate_settings.", FieldList)+" from estate_settings where estate_settings.EstateID = :EstateID";
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
@ -342,7 +342,7 @@ namespace OpenSim.Data.SQLite
{ {
List<int> result = new List<int>(); List<int> result = new List<int>();
string sql = "select EstateID from estate_settings where estate_settings.EstateName :EstateName"; string sql = "select EstateID from estate_settings where estate_settings.EstateName = :EstateName";
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();

View File

@ -93,7 +93,7 @@ namespace OpenSim.Data.SQLite
ds = new DataSet("Region"); ds = new DataSet("Region");
m_log.Info("[REGION DB]: Sqlite - connecting: " + connectionString); m_log.Info("[SQLITE REGION DB]: Sqlite - connecting: " + connectionString);
m_conn = new SqliteConnection(m_connectionString); m_conn = new SqliteConnection(m_connectionString);
m_conn.Open(); m_conn.Open();
@ -156,7 +156,7 @@ namespace OpenSim.Data.SQLite
} }
catch (Exception) catch (Exception)
{ {
m_log.Info("[REGION DB]: Caught fill error on prims table"); m_log.Info("[SQLITE REGION DB]: Caught fill error on prims table");
} }
try try
@ -165,7 +165,16 @@ namespace OpenSim.Data.SQLite
} }
catch (Exception) catch (Exception)
{ {
m_log.Info("[REGION DB]: Caught fill error on primshapes table"); m_log.Info("[SQLITE REGION DB]: Caught fill error on primshapes table");
}
try
{
itemsDa.Fill(ds.Tables["primitems"]);
}
catch (Exception)
{
m_log.Info("[SQLITE REGION DB]: Caught fill error on primitems table");
} }
try try
@ -174,7 +183,7 @@ namespace OpenSim.Data.SQLite
} }
catch (Exception) catch (Exception)
{ {
m_log.Info("[REGION DB]: Caught fill error on terrain table"); m_log.Info("[SQLITE REGION DB]: Caught fill error on terrain table");
} }
try try
@ -183,7 +192,7 @@ namespace OpenSim.Data.SQLite
} }
catch (Exception) catch (Exception)
{ {
m_log.Info("[REGION DB]: Caught fill error on land table"); m_log.Info("[SQLITE REGION DB]: Caught fill error on land table");
} }
try try
@ -192,7 +201,7 @@ namespace OpenSim.Data.SQLite
} }
catch (Exception) catch (Exception)
{ {
m_log.Info("[REGION DB]: Caught fill error on landaccesslist table"); m_log.Info("[SQLITE REGION DB]: Caught fill error on landaccesslist table");
} }
try try
@ -201,7 +210,7 @@ namespace OpenSim.Data.SQLite
} }
catch (Exception) catch (Exception)
{ {
m_log.Info("[REGION DB]: Caught fill error on regionsettings table"); m_log.Info("[SQLITE REGION DB]: Caught fill error on regionsettings table");
} }
// We have to create a data set mapping for every table, otherwise the IDataAdaptor.Update() will not populate rows with values! // We have to create a data set mapping for every table, otherwise the IDataAdaptor.Update() will not populate rows with values!
@ -434,7 +443,7 @@ namespace OpenSim.Data.SQLite
lock (ds) lock (ds)
{ {
DataRow[] primsForRegion = prims.Select(byRegion); DataRow[] primsForRegion = prims.Select(byRegion);
m_log.Info("[REGION DB]: Loaded " + primsForRegion.Length + " prims for region: " + regionUUID); // m_log.Info("[SQLITE REGION DB]: Loaded " + primsForRegion.Length + " prims for region: " + regionUUID);
// First, create all groups // First, create all groups
foreach (DataRow primRow in primsForRegion) foreach (DataRow primRow in primsForRegion)
@ -456,8 +465,8 @@ namespace OpenSim.Data.SQLite
} }
else else
{ {
m_log.Info( m_log.Warn(
"[REGION DB]: No shape found for prim in storage, so setting default box shape"); "[SQLITE REGION DB]: No shape found for prim in storage, so setting default box shape");
prim.Shape = PrimitiveBaseShape.Default; prim.Shape = PrimitiveBaseShape.Default;
} }
@ -469,11 +478,11 @@ namespace OpenSim.Data.SQLite
} }
catch (Exception e) catch (Exception e)
{ {
m_log.Error("[REGION DB]: Failed create prim object in new group, exception and data follows"); m_log.Error("[SQLITE REGION DB]: Failed create prim object in new group, exception and data follows");
m_log.Info("[REGION DB]: " + e.ToString()); m_log.Error("[SQLITE REGION DB]: ", e);
foreach (DataColumn col in prims.Columns) foreach (DataColumn col in prims.Columns)
{ {
m_log.Info("[REGION DB]: Col: " + col.ColumnName + " => " + primRow[col]); m_log.Error("[SQLITE REGION DB]: Col: " + col.ColumnName + " => " + primRow[col]);
} }
} }
} }
@ -498,7 +507,7 @@ namespace OpenSim.Data.SQLite
else else
{ {
m_log.Warn( m_log.Warn(
"[REGION DB]: No shape found for prim in storage, so setting default box shape"); "[SQLITE REGION DB]: No shape found for prim in storage, so setting default box shape");
prim.Shape = PrimitiveBaseShape.Default; prim.Shape = PrimitiveBaseShape.Default;
} }
@ -508,11 +517,11 @@ namespace OpenSim.Data.SQLite
} }
catch (Exception e) catch (Exception e)
{ {
m_log.Error("[REGION DB]: Failed create prim object in group, exception and data follows"); m_log.Error("[SQLITE REGION DB]: Failed create prim object in group, exception and data follows");
m_log.Info("[REGION DB]: " + e.ToString()); m_log.Error("[SQLITE REGION DB]: ", e);
foreach (DataColumn col in prims.Columns) foreach (DataColumn col in prims.Columns)
{ {
m_log.Info("[REGION DB]: Col: " + col.ColumnName + " => " + primRow[col]); m_log.Error("[SQLITE REGION DB]: Col: " + col.ColumnName + " => " + primRow[col]);
} }
} }
} }
@ -526,19 +535,22 @@ namespace OpenSim.Data.SQLite
/// <param name="prim">the prim</param> /// <param name="prim">the prim</param>
private void LoadItems(SceneObjectPart prim) private void LoadItems(SceneObjectPart prim)
{ {
//m_log.DebugFormat("[DATASTORE]: Loading inventory for {0}, {1}", prim.Name, prim.UUID); // m_log.DebugFormat("[SQLITE REGION DB]: Loading inventory for {0} {1}", prim.Name, prim.UUID);
DataTable dbItems = ds.Tables["primitems"]; DataTable dbItems = ds.Tables["primitems"];
String sql = String.Format("primID = '{0}'", prim.UUID.ToString()); String sql = String.Format("primID = '{0}'", prim.UUID.ToString());
DataRow[] dbItemRows = dbItems.Select(sql); DataRow[] dbItemRows = dbItems.Select(sql);
IList<TaskInventoryItem> inventory = new List<TaskInventoryItem>(); IList<TaskInventoryItem> inventory = new List<TaskInventoryItem>();
// m_log.DebugFormat(
// "[SQLITE REGION DB]: Found {0} items for {1} {2}", dbItemRows.Length, prim.Name, prim.UUID);
foreach (DataRow row in dbItemRows) foreach (DataRow row in dbItemRows)
{ {
TaskInventoryItem item = buildItem(row); TaskInventoryItem item = buildItem(row);
inventory.Add(item); inventory.Add(item);
//m_log.DebugFormat("[DATASTORE]: Restored item {0}, {1}", item.Name, item.ItemID); // m_log.DebugFormat("[SQLITE REGION DB]: Restored item {0} {1}", item.Name, item.ItemID);
} }
prim.Inventory.RestoreInventoryItems(inventory); prim.Inventory.RestoreInventoryItems(inventory);
@ -574,7 +586,7 @@ namespace OpenSim.Data.SQLite
// the following is an work around for .NET. The perf // the following is an work around for .NET. The perf
// issues associated with it aren't as bad as you think. // issues associated with it aren't as bad as you think.
m_log.Info("[REGION DB]: Storing terrain revision r" + revision.ToString()); m_log.Debug("[SQLITE REGION DB]: Storing terrain revision r" + revision.ToString());
String sql = "insert into terrain(RegionUUID, Revision, Heightfield)" + String sql = "insert into terrain(RegionUUID, Revision, Heightfield)" +
" values(:RegionUUID, :Revision, :Heightfield)"; " values(:RegionUUID, :Revision, :Heightfield)";
@ -630,11 +642,11 @@ namespace OpenSim.Data.SQLite
} }
else else
{ {
m_log.Info("[REGION DB]: No terrain found for region"); m_log.Warn("[SQLITE REGION DB]: No terrain found for region");
return null; return null;
} }
m_log.Info("[REGION DB]: Loaded terrain revision r" + rev.ToString()); m_log.Debug("[SQLITE REGION DB]: Loaded terrain revision r" + rev.ToString());
} }
} }
return terret; return terret;
@ -1417,7 +1429,7 @@ namespace OpenSim.Data.SQLite
} }
catch (InvalidCastException) catch (InvalidCastException)
{ {
m_log.ErrorFormat("[PARCEL]: unable to get parcel telehub settings for {1}", newData.Name); m_log.ErrorFormat("[SQLITE REGION DB]: unable to get parcel telehub settings for {1}", newData.Name);
newData.UserLocation = Vector3.Zero; newData.UserLocation = Vector3.Zero;
newData.UserLookAt = Vector3.Zero; newData.UserLookAt = Vector3.Zero;
} }
@ -1926,7 +1938,7 @@ namespace OpenSim.Data.SQLite
/// <param name="items"></param> /// <param name="items"></param>
public void StorePrimInventory(UUID primID, ICollection<TaskInventoryItem> items) public void StorePrimInventory(UUID primID, ICollection<TaskInventoryItem> items)
{ {
//m_log.InfoFormat("[REGION DB]: Entered StorePrimInventory with prim ID {0}", primID); // m_log.DebugFormat("[SQLITE REGION DB]: Entered StorePrimInventory with prim ID {0}", primID);
DataTable dbItems = ds.Tables["primitems"]; DataTable dbItems = ds.Tables["primitems"];

View File

@ -66,11 +66,19 @@ namespace OpenSim.Data.SQLite
public bool StoreFolder(XInventoryFolder folder) public bool StoreFolder(XInventoryFolder folder)
{ {
if (folder.folderName.Length > 64)
folder.folderName = folder.folderName.Substring(0, 64);
return m_Folders.Store(folder); return m_Folders.Store(folder);
} }
public bool StoreItem(XInventoryItem item) public bool StoreItem(XInventoryItem item)
{ {
if (item.inventoryName.Length > 64)
item.inventoryName = item.inventoryName.Substring(0, 64);
if (item.inventoryDescription.Length > 128)
item.inventoryDescription = item.inventoryDescription.Substring(0, 128);
return m_Items.Store(item); return m_Items.Store(item);
} }

View File

@ -328,7 +328,7 @@ namespace OpenSim.Data.SQLiteLegacy
public EstateSettings LoadEstateSettings(int estateID) public EstateSettings LoadEstateSettings(int estateID)
{ {
string sql = "select estate_settings."+String.Join(",estate_settings.", FieldList)+" from estate_settings where estate_settings.EstateID :EstateID"; string sql = "select estate_settings."+String.Join(",estate_settings.", FieldList)+" from estate_settings where estate_settings.EstateID = :EstateID";
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
@ -342,7 +342,7 @@ namespace OpenSim.Data.SQLiteLegacy
{ {
List<int> result = new List<int>(); List<int> result = new List<int>();
string sql = "select EstateID from estate_settings where estate_settings.EstateName :EstateName"; string sql = "select EstateID from estate_settings where estate_settings.EstateName = :EstateName";
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand(); SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();

View File

@ -781,7 +781,7 @@ namespace OpenSim.Data.Tests
// Ownership changes when you drop an object into an object // Ownership changes when you drop an object into an object
// owned by someone else // owned by someone else
Assert.That(t.OwnerID,Is.EqualTo(sog.RootPart.OwnerID), "Assert.That(t.OwnerID,Is.EqualTo(sog.RootPart.OwnerID))"); Assert.That(t.OwnerID,Is.EqualTo(sog.RootPart.OwnerID), "Assert.That(t.OwnerID,Is.EqualTo(sog.RootPart.OwnerID))");
Assert.That(t.CurrentPermissions, Is.EqualTo(curperm | 8), "Assert.That(t.CurrentPermissions, Is.EqualTo(curperm | 8))"); // Assert.That(t.CurrentPermissions, Is.EqualTo(curperm | 16), "Assert.That(t.CurrentPermissions, Is.EqualTo(curperm | 8))");
Assert.That(t.ParentID,Is.EqualTo(sog.RootPart.FolderID), "Assert.That(t.ParentID,Is.EqualTo(sog.RootPart.FolderID))"); Assert.That(t.ParentID,Is.EqualTo(sog.RootPart.FolderID), "Assert.That(t.ParentID,Is.EqualTo(sog.RootPart.FolderID))");
Assert.That(t.ParentPartID,Is.EqualTo(sog.RootPart.UUID), "Assert.That(t.ParentPartID,Is.EqualTo(sog.RootPart.UUID))"); Assert.That(t.ParentPartID,Is.EqualTo(sog.RootPart.UUID), "Assert.That(t.ParentPartID,Is.EqualTo(sog.RootPart.UUID))");
} }

View File

@ -21,4 +21,4 @@
[TestConnections] [TestConnections]
MySqlConnection="Server=localhost;Port=3306;Database=opensim-nunit;User ID=opensim-nunit;Password=opensim-nunit;" MySqlConnection="Server=localhost;Port=3306;Database=opensim-nunit;User ID=opensim-nunit;Password=opensim-nunit;"
SqlConnection="Server=.\SQL2008;Database=opensim-nunit;Trusted_Connection=True;" SqlConnection="Server=.\SQL2008;Database=opensim-nunit;Trusted_Connection=True;"
SqliteConnection="" SqliteConnection="URI=file:opensim-nunit.db,version=3"

View File

@ -814,7 +814,7 @@ namespace OpenSim.Framework.Capabilities
if (mm != null) if (mm != null)
{ {
if (!mm.UploadCovered(client)) if (!mm.UploadCovered(client, mm.UploadCharge))
{ {
if (client != null) if (client != null)
client.SendAgentAlertMessage("Unable to upload asset. Insufficient funds.", false); client.SendAgentAlertMessage("Unable to upload asset. Insufficient funds.", false);

View File

@ -265,6 +265,46 @@ namespace OpenSim.Framework
} }
} }
public class ControllerData
{
public UUID ItemID;
public uint IgnoreControls;
public uint EventControls;
public ControllerData(UUID item, uint ignore, uint ev)
{
ItemID = item;
IgnoreControls = ignore;
EventControls = ev;
}
public ControllerData(OSDMap args)
{
UnpackUpdateMessage(args);
}
public OSDMap PackUpdateMessage()
{
OSDMap controldata = new OSDMap();
controldata["item"] = OSD.FromUUID(ItemID);
controldata["ignore"] = OSD.FromInteger(IgnoreControls);
controldata["event"] = OSD.FromInteger(EventControls);
return controldata;
}
public void UnpackUpdateMessage(OSDMap args)
{
if (args["item"] != null)
ItemID = args["item"].AsUUID();
if (args["ignore"] != null)
IgnoreControls = (uint)args["ignore"].AsInteger();
if (args["event"] != null)
EventControls = (uint)args["event"].AsInteger();
}
}
public class AgentData : IAgentData public class AgentData : IAgentData
{ {
private UUID m_id; private UUID m_id;
@ -313,6 +353,9 @@ namespace OpenSim.Framework
public UUID[] Wearables; public UUID[] Wearables;
public AttachmentData[] Attachments; public AttachmentData[] Attachments;
// Scripted
public ControllerData[] Controllers;
public string CallbackURI; public string CallbackURI;
public virtual OSDMap Pack() public virtual OSDMap Pack()
@ -403,6 +446,14 @@ namespace OpenSim.Framework
args["attachments"] = attachs; args["attachments"] = attachs;
} }
if ((Controllers != null) && (Controllers.Length > 0))
{
OSDArray controls = new OSDArray(Controllers.Length);
foreach (ControllerData ctl in Controllers)
controls.Add(ctl.PackUpdateMessage());
args["controllers"] = controls;
}
if ((CallbackURI != null) && (!CallbackURI.Equals(""))) if ((CallbackURI != null) && (!CallbackURI.Equals("")))
args["callback_uri"] = OSD.FromString(CallbackURI); args["callback_uri"] = OSD.FromString(CallbackURI);
@ -559,6 +610,20 @@ namespace OpenSim.Framework
} }
} }
if ((args["controllers"] != null) && (args["controllers"]).Type == OSDType.Array)
{
OSDArray controls = (OSDArray)(args["controllers"]);
Controllers = new ControllerData[controls.Count];
int i = 0;
foreach (OSD o in controls)
{
if (o.Type == OSDType.Map)
{
Controllers[i++] = new ControllerData((OSDMap)o);
}
}
}
if (args["callback_uri"] != null) if (args["callback_uri"] != null)
CallbackURI = args["callback_uri"].AsString(); CallbackURI = args["callback_uri"].AsString();
} }

View File

@ -44,6 +44,7 @@ namespace OpenSim.Framework.Console
{ {
public int last; public int last;
public long lastLineSeen; public long lastLineSeen;
public bool newConnection = true;
} }
// A console that uses REST interfaces // A console that uses REST interfaces
@ -106,8 +107,15 @@ namespace OpenSim.Framework.Console
public override string ReadLine(string p, bool isCommand, bool e) public override string ReadLine(string p, bool isCommand, bool e)
{ {
if (isCommand)
Output("+++"+p);
else
Output("-++"+p);
m_DataEvent.WaitOne(); m_DataEvent.WaitOne();
string cmdinput;
lock (m_InputData) lock (m_InputData)
{ {
if (m_InputData.Count == 0) if (m_InputData.Count == 0)
@ -116,11 +124,13 @@ namespace OpenSim.Framework.Console
return ""; return "";
} }
string cmdinput = m_InputData[0]; cmdinput = m_InputData[0];
m_InputData.RemoveAt(0); m_InputData.RemoveAt(0);
if (m_InputData.Count == 0) if (m_InputData.Count == 0)
m_DataEvent.Reset(); m_DataEvent.Reset();
}
if (isCommand) if (isCommand)
{ {
string[] cmd = Commands.Resolve(Parser.Parse(cmdinput)); string[] cmd = Commands.Resolve(Parser.Parse(cmdinput));
@ -139,7 +149,6 @@ namespace OpenSim.Framework.Console
} }
return cmdinput; return cmdinput;
} }
}
private void DoExpire() private void DoExpire()
{ {
@ -308,7 +317,7 @@ namespace OpenSim.Framework.Console
return reply; return reply;
} }
if (post["COMMAND"] == null || post["COMMAND"].ToString() == String.Empty) if (post["COMMAND"] == null)
return reply; return reply;
lock (m_InputData) lock (m_InputData)
@ -416,6 +425,12 @@ namespace OpenSim.Framework.Console
XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession", XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
""); "");
if (c.newConnection)
{
c.newConnection = false;
Output("+++" + DefaultPrompt);
}
lock (m_Scrollback) lock (m_Scrollback)
{ {
long startLine = m_LineNumber - m_Scrollback.Count; long startLine = m_LineNumber - m_Scrollback.Count;

View File

@ -58,7 +58,7 @@ namespace OpenSim.Framework
RezMultipleAttachmentsFromInvPacket.ObjectDataBlock[] objects); RezMultipleAttachmentsFromInvPacket.ObjectDataBlock[] objects);
public delegate void ObjectAttach( public delegate void ObjectAttach(
IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, Quaternion rot, bool silent); IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, bool silent);
public delegate void ModifyTerrain(UUID user, public delegate void ModifyTerrain(UUID user,
float height, float seconds, byte size, byte action, float north, float west, float south, float east, float height, float seconds, byte size, byte action, float north, float west, float south, float east,
@ -1025,7 +1025,6 @@ namespace OpenSim.Framework
void SendCoarseLocationUpdate(List<UUID> users, List<Vector3> CoarseLocations); void SendCoarseLocationUpdate(List<UUID> users, List<Vector3> CoarseLocations);
void AttachObject(uint localID, Quaternion rotation, byte attachPoint, UUID ownerID);
void SetChildAgentThrottle(byte[] throttle); void SetChildAgentThrottle(byte[] throttle);
void SendAvatarDataImmediate(ISceneEntity avatar); void SendAvatarDataImmediate(ISceneEntity avatar);
@ -1316,5 +1315,7 @@ namespace OpenSim.Framework
void SendChangeUserRights(UUID agentID, UUID friendID, int rights); void SendChangeUserRights(UUID agentID, UUID friendID, int rights);
void SendTextBoxRequest(string message, int chatChannel, string objectname, string ownerFirstName, string ownerLastName, UUID objectId); void SendTextBoxRequest(string message, int chatChannel, string objectname, string ownerFirstName, string ownerLastName, UUID objectId);
void StopFlying(ISceneEntity presence);
} }
} }

View File

@ -35,35 +35,15 @@ namespace OpenSim.Framework
bool ObjectGiveMoney(UUID objectID, UUID fromID, UUID toID, bool ObjectGiveMoney(UUID objectID, UUID fromID, UUID toID,
int amount); int amount);
int GetBalance(IClientAPI client); int GetBalance(UUID agentID);
void ApplyUploadCharge(UUID agentID); bool UploadCovered(IClientAPI client, int amount);
bool UploadCovered(IClientAPI client);
void ApplyGroupCreationCharge(UUID agentID);
bool GroupCreationCovered(IClientAPI client);
bool AmountCovered(IClientAPI client, int amount); bool AmountCovered(IClientAPI client, int amount);
void ApplyCharge(UUID agentID, int amount, string text); void ApplyCharge(UUID agentID, int amount, string text);
void ApplyUploadCharge(UUID agentID, int amount, string text);
EconomyData GetEconomyData(); int UploadCharge { get; }
int GroupCreationCharge { get; }
event ObjectPaid OnObjectPaid; event ObjectPaid OnObjectPaid;
} }
public struct EconomyData
{
public int ObjectCapacity;
public int ObjectCount;
public int PriceEnergyUnit;
public int PriceGroupCreate;
public int PriceObjectClaim;
public float PriceObjectRent;
public float PriceObjectScaleFactor;
public int PriceParcelClaim;
public float PriceParcelClaimFactor;
public int PriceParcelRent;
public int PricePublicObjectDecay;
public int PricePublicObjectDelete;
public int PriceRentLight;
public int PriceUpload;
public int TeleportMinPrice;
}
} }

View File

@ -29,14 +29,15 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net; using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
using System.Reflection;
using System.Xml; using System.Xml;
using System.IO; using System.IO;
using log4net;
using Nini.Config; using Nini.Config;
using OpenMetaverse; using OpenMetaverse;
using OpenMetaverse.StructuredData; using OpenMetaverse.StructuredData;
using OpenSim.Framework.Console; using OpenSim.Framework.Console;
namespace OpenSim.Framework namespace OpenSim.Framework
{ {
public class RegionLightShareData : ICloneable public class RegionLightShareData : ICloneable
@ -97,8 +98,7 @@ namespace OpenSim.Framework
[Serializable] [Serializable]
public class SimpleRegionInfo public class SimpleRegionInfo
{ {
// private static readonly log4net.ILog m_log // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary> /// <summary>
/// The port by which http communication occurs with the region (most noticeably, CAPS communication) /// The port by which http communication occurs with the region (most noticeably, CAPS communication)
@ -327,8 +327,7 @@ namespace OpenSim.Framework
public class RegionInfo public class RegionInfo
{ {
// private static readonly log4net.ILog m_log private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public bool commFailTF = false; public bool commFailTF = false;
public ConfigurationMember configMember; public ConfigurationMember configMember;
@ -772,9 +771,16 @@ namespace OpenSim.Framework
} }
if (externalName == "SYSTEMIP") if (externalName == "SYSTEMIP")
{
m_externalHostName = Util.GetLocalHost().ToString(); m_externalHostName = Util.GetLocalHost().ToString();
m_log.InfoFormat(
"[REGIONINFO]: Resolving SYSTEMIP to {0} for external hostname of region {1}",
m_externalHostName, name);
}
else else
{
m_externalHostName = externalName; m_externalHostName = externalName;
}
m_regionType = config.GetString("RegionType", String.Empty); m_regionType = config.GetString("RegionType", String.Empty);

View File

@ -310,7 +310,7 @@ namespace OpenSim.Framework.Servers.HttpServer
} }
catch (Exception e) catch (Exception e)
{ {
m_log.Error(String.Format("[BASE HTTP SERVER]: OnRequest() failed with {0}", e.Message)); m_log.ErrorFormat("[BASE HTTP SERVER]: OnRequest() failed with {0}{1}", e.Message, e.StackTrace);
} }
} }

View File

@ -73,7 +73,18 @@ namespace OpenSim.Framework.Servers.HttpServer
{ {
if (req.PollServiceArgs.HasEvents(req.RequestID, req.PollServiceArgs.Id)) if (req.PollServiceArgs.HasEvents(req.RequestID, req.PollServiceArgs.Id))
{ {
StreamReader str = new StreamReader(req.Request.Body); StreamReader str;
try
{
str = new StreamReader(req.Request.Body);
}
catch (System.ArgumentException)
{
// Stream was not readable means a child agent
// was closed due to logout, leaving the
// Event Queue request orphaned.
continue;
}
Hashtable responsedata = req.PollServiceArgs.GetEvents(req.RequestID, req.PollServiceArgs.Id, str.ReadToEnd()); Hashtable responsedata = req.PollServiceArgs.GetEvents(req.RequestID, req.PollServiceArgs.Id, str.ReadToEnd());
m_server.DoHTTPGruntWork(responsedata, m_server.DoHTTPGruntWork(responsedata,

View File

@ -29,7 +29,7 @@ namespace OpenSim
{ {
public class VersionInfo public class VersionInfo
{ {
private const string VERSION_NUMBER = "0.7"; private const string VERSION_NUMBER = "0.7.1";
private const Flavour VERSION_FLAVOUR = Flavour.Dev; private const Flavour VERSION_FLAVOUR = Flavour.Dev;
public enum Flavour public enum Flavour

View File

@ -114,7 +114,7 @@ namespace OpenSim.Framework
} }
catch (Exception ex) catch (Exception ex)
{ {
m_log.Warn("GET from URL " + url + " failed: " + ex.Message); m_log.Warn(httpVerb + " on URL " + url + " failed: " + ex.Message);
errorMessage = ex.Message; errorMessage = ex.Message;
} }

View File

@ -194,8 +194,6 @@ namespace OpenSim
PrintFileToConsole("startuplogo.txt"); PrintFileToConsole("startuplogo.txt");
m_log.InfoFormat("[NETWORK]: Using {0} as SYSTEMIP", Util.GetLocalHost().ToString());
// For now, start at the 'root' level by default // For now, start at the 'root' level by default
if (m_sceneManager.Scenes.Count == 1) // If there is only one region, select it if (m_sceneManager.Scenes.Count == 1) // If there is only one region, select it
ChangeSelectedRegion("region", ChangeSelectedRegion("region",

View File

@ -367,13 +367,13 @@ namespace OpenSim
Environment.Exit(1); Environment.Exit(1);
} }
scene.loadAllLandObjectsFromStorage(regionInfo.originRegionID);
scene.EventManager.TriggerParcelPrimCountUpdate();
// We need to do this after we've initialized the // We need to do this after we've initialized the
// scripting engines. // scripting engines.
scene.CreateScriptInstances(); scene.CreateScriptInstances();
scene.loadAllLandObjectsFromStorage(regionInfo.originRegionID);
scene.EventManager.TriggerParcelPrimCountUpdate();
m_sceneManager.Add(scene); m_sceneManager.Add(scene);
if (m_autoCreateClientStack) if (m_autoCreateClientStack)

View File

@ -55,7 +55,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
public IJ2KDecoder J2KDecoder; public IJ2KDecoder J2KDecoder;
public IAssetService AssetService; public IAssetService AssetService;
public UUID AgentID; public UUID AgentID;
public IHyperAssetService HyperAssets; public IInventoryAccessModule InventoryAccessModule;
public OpenJPEG.J2KLayerInfo[] Layers; public OpenJPEG.J2KLayerInfo[] Layers;
public bool IsDecoded; public bool IsDecoded;
public bool HasAsset; public bool HasAsset;
@ -375,14 +375,18 @@ namespace OpenSim.Region.ClientStack.LindenUDP
UUID assetID = UUID.Zero; UUID assetID = UUID.Zero;
if (asset != null) if (asset != null)
assetID = asset.FullID; assetID = asset.FullID;
else if ((HyperAssets != null) && (sender != HyperAssets)) else if ((InventoryAccessModule != null) && (sender != InventoryAccessModule))
{ {
// Try the user's inventory, but only if it's different from the regions' // Unfortunately we need this here, there's no other way.
string userAssets = HyperAssets.GetUserAssetServer(AgentID); // This is due to the fact that textures opened directly from the agent's inventory
if ((userAssets != string.Empty) && (userAssets != HyperAssets.GetSimAssetServer())) // don't have any distinguishing feature. As such, in order to serve those when the
// foreign user is visiting, we need to try again after the first fail to the local
// asset service.
string assetServerURL = string.Empty;
if (InventoryAccessModule.IsForeignUser(AgentID, out assetServerURL))
{ {
m_log.DebugFormat("[J2KIMAGE]: texture {0} not found in local asset storage. Trying user's storage.", id); m_log.DebugFormat("[J2KIMAGE]: texture {0} not found in local asset storage. Trying user's storage.", id);
AssetService.Get(userAssets + "/" + id, HyperAssets, AssetReceived); AssetService.Get(assetServerURL + "/" + id, InventoryAccessModule, AssetReceived);
return; return;
} }
} }

View File

@ -335,6 +335,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP
/// </value> /// </value>
protected HashSet<uint> m_killRecord; protected HashSet<uint> m_killRecord;
// protected HashSet<uint> m_attachmentsSent;
private int m_moneyBalance; private int m_moneyBalance;
private int m_animationSequenceNumber = 1; private int m_animationSequenceNumber = 1;
private bool m_SendLogoutPacketWhenClosing = true; private bool m_SendLogoutPacketWhenClosing = true;
@ -359,7 +361,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP
protected uint m_agentFOVCounter; protected uint m_agentFOVCounter;
protected IAssetService m_assetService; protected IAssetService m_assetService;
private IHyperAssetService m_hyperAssets;
private const bool m_checkPackets = true; private const bool m_checkPackets = true;
private Timer m_propertiesPacketTimer; private Timer m_propertiesPacketTimer;
@ -435,9 +436,9 @@ namespace OpenSim.Region.ClientStack.LindenUDP
m_entityUpdates = new PriorityQueue(m_scene.Entities.Count); m_entityUpdates = new PriorityQueue(m_scene.Entities.Count);
m_fullUpdateDataBlocksBuilder = new List<ObjectUpdatePacket.ObjectDataBlock>(); m_fullUpdateDataBlocksBuilder = new List<ObjectUpdatePacket.ObjectDataBlock>();
m_killRecord = new HashSet<uint>(); m_killRecord = new HashSet<uint>();
// m_attachmentsSent = new HashSet<uint>();
m_assetService = m_scene.RequestModuleInterface<IAssetService>(); m_assetService = m_scene.RequestModuleInterface<IAssetService>();
m_hyperAssets = m_scene.RequestModuleInterface<IHyperAssetService>();
m_GroupsModule = scene.RequestModuleInterface<IGroupsModule>(); m_GroupsModule = scene.RequestModuleInterface<IGroupsModule>();
m_imageManager = new LLImageManager(this, m_assetService, Scene.RequestModuleInterface<IJ2KDecoder>()); m_imageManager = new LLImageManager(this, m_assetService, Scene.RequestModuleInterface<IJ2KDecoder>());
m_channelVersion = Util.StringToBytes256(scene.GetSimulatorVersion()); m_channelVersion = Util.StringToBytes256(scene.GetSimulatorVersion());
@ -3425,6 +3426,9 @@ namespace OpenSim.Region.ClientStack.LindenUDP
objupdate.ObjectData[0] = CreateAvatarUpdateBlock(presence); objupdate.ObjectData[0] = CreateAvatarUpdateBlock(presence);
OutPacket(objupdate, ThrottleOutPacketType.Task); OutPacket(objupdate, ThrottleOutPacketType.Task);
// We need to record the avatar local id since the root prim of an attachment points to this.
// m_attachmentsSent.Add(avatar.LocalId);
} }
public void SendCoarseLocationUpdate(List<UUID> users, List<Vector3> CoarseLocations) public void SendCoarseLocationUpdate(List<UUID> users, List<Vector3> CoarseLocations)
@ -3434,7 +3438,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
CoarseLocationUpdatePacket loc = (CoarseLocationUpdatePacket)PacketPool.Instance.GetPacket(PacketType.CoarseLocationUpdate); CoarseLocationUpdatePacket loc = (CoarseLocationUpdatePacket)PacketPool.Instance.GetPacket(PacketType.CoarseLocationUpdate);
loc.Header.Reliable = false; loc.Header.Reliable = false;
// Each packet can only hold around 62 avatar positions and the client clears the mini-map each time // Each packet can only hold around 60 avatar positions and the client clears the mini-map each time
// a CoarseLocationUpdate packet is received. Oh well. // a CoarseLocationUpdate packet is received. Oh well.
int total = Math.Min(CoarseLocations.Count, (int)MaxCoarseLocations); int total = Math.Min(CoarseLocations.Count, (int)MaxCoarseLocations);
@ -3556,9 +3560,42 @@ namespace OpenSim.Region.ClientStack.LindenUDP
if (!canUseImproved && !canUseCompressed) if (!canUseImproved && !canUseCompressed)
{ {
if (update.Entity is ScenePresence) if (update.Entity is ScenePresence)
{
objectUpdateBlocks.Value.Add(CreateAvatarUpdateBlock((ScenePresence)update.Entity)); objectUpdateBlocks.Value.Add(CreateAvatarUpdateBlock((ScenePresence)update.Entity));
}
else else
{
// if (update.Entity is SceneObjectPart && ((SceneObjectPart)update.Entity).IsAttachment)
// {
// SceneObjectPart sop = (SceneObjectPart)update.Entity;
// string text = sop.Text;
// if (text.IndexOf("\n") >= 0)
// text = text.Remove(text.IndexOf("\n"));
//
// if (m_attachmentsSent.Contains(sop.ParentID))
// {
//// m_log.DebugFormat(
//// "[CLIENT]: Sending full info about attached prim {0} text {1}",
//// sop.LocalId, text);
//
// objectUpdateBlocks.Value.Add(CreatePrimUpdateBlock(sop, this.m_agentId));
//
// m_attachmentsSent.Add(sop.LocalId);
// }
// else
// {
// m_log.DebugFormat(
// "[CLIENT]: Requeueing full update of prim {0} text {1} since we haven't sent its parent {2} yet",
// sop.LocalId, text, sop.ParentID);
//
// m_entityUpdates.Enqueue(double.MaxValue, update, sop.LocalId);
// }
// }
// else
// {
objectUpdateBlocks.Value.Add(CreatePrimUpdateBlock((SceneObjectPart)update.Entity, this.m_agentId)); objectUpdateBlocks.Value.Add(CreatePrimUpdateBlock((SceneObjectPart)update.Entity, this.m_agentId));
// }
}
} }
else if (!canUseImproved) else if (!canUseImproved)
{ {
@ -3655,30 +3692,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP
#endregion Primitive Packet/Data Sending Methods #endregion Primitive Packet/Data Sending Methods
/// <summary>
///
/// </summary>
/// <param name="localID"></param>
/// <param name="rotation"></param>
/// <param name="attachPoint"></param>
public void AttachObject(uint localID, Quaternion rotation, byte attachPoint, UUID ownerID)
{
if (attachPoint > 30 && ownerID != AgentId) // Someone else's HUD
return;
ObjectAttachPacket attach = (ObjectAttachPacket)PacketPool.Instance.GetPacket(PacketType.ObjectAttach);
// TODO: don't create new blocks if recycling an old packet
attach.AgentData.AgentID = AgentId;
attach.AgentData.SessionID = m_sessionId;
attach.AgentData.AttachmentPoint = attachPoint;
attach.ObjectData = new ObjectAttachPacket.ObjectDataBlock[1];
attach.ObjectData[0] = new ObjectAttachPacket.ObjectDataBlock();
attach.ObjectData[0].ObjectLocalID = localID;
attach.ObjectData[0].Rotation = rotation;
attach.Header.Zerocoded = true;
OutPacket(attach, ThrottleOutPacketType.Task);
}
void HandleQueueEmpty(ThrottleOutPacketTypeFlags categories) void HandleQueueEmpty(ThrottleOutPacketTypeFlags categories)
{ {
if ((categories & ThrottleOutPacketTypeFlags.Task) != 0) if ((categories & ThrottleOutPacketTypeFlags.Task) != 0)
@ -5747,7 +5760,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
{ {
if (att.ObjectData.Length > 0) if (att.ObjectData.Length > 0)
{ {
handlerObjectAttach(this, att.ObjectData[0].ObjectLocalID, att.AgentData.AttachmentPoint, att.ObjectData[0].Rotation, false); handlerObjectAttach(this, att.ObjectData[0].ObjectLocalID, att.AgentData.AttachmentPoint, false);
} }
} }
} }
@ -6317,8 +6330,8 @@ namespace OpenSim.Region.ClientStack.LindenUDP
if (handlerObjectDuplicate != null) if (handlerObjectDuplicate != null)
{ {
handlerObjectDuplicate(dupe.ObjectData[i].ObjectLocalID, dupe.SharedData.Offset, handlerObjectDuplicate(dupe.ObjectData[i].ObjectLocalID, dupe.SharedData.Offset,
dupe.SharedData.DuplicateFlags, AgentandGroupData.AgentID, dupe.SharedData.DuplicateFlags, AgentId,
AgentandGroupData.GroupID); m_activeGroupID);
} }
} }
@ -6908,7 +6921,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
if (handlerObjectDuplicateOnRay != null) if (handlerObjectDuplicateOnRay != null)
{ {
handlerObjectDuplicateOnRay(dupeOnRay.ObjectData[i].ObjectLocalID, dupeOnRay.AgentData.DuplicateFlags, handlerObjectDuplicateOnRay(dupeOnRay.ObjectData[i].ObjectLocalID, dupeOnRay.AgentData.DuplicateFlags,
dupeOnRay.AgentData.AgentID, dupeOnRay.AgentData.GroupID, dupeOnRay.AgentData.RayTargetID, dupeOnRay.AgentData.RayEnd, AgentId, m_activeGroupID, dupeOnRay.AgentData.RayTargetID, dupeOnRay.AgentData.RayEnd,
dupeOnRay.AgentData.RayStart, dupeOnRay.AgentData.BypassRaycast, dupeOnRay.AgentData.RayEndIsIntersection, dupeOnRay.AgentData.RayStart, dupeOnRay.AgentData.BypassRaycast, dupeOnRay.AgentData.RayEndIsIntersection,
dupeOnRay.AgentData.CopyCenters, dupeOnRay.AgentData.CopyRotates); dupeOnRay.AgentData.CopyCenters, dupeOnRay.AgentData.CopyRotates);
} }
@ -7210,59 +7223,22 @@ namespace OpenSim.Region.ClientStack.LindenUDP
} }
else // Agent else // Agent
{ {
IInventoryService invService = m_scene.RequestModuleInterface<IInventoryService>(); IInventoryAccessModule invAccess = m_scene.RequestModuleInterface<IInventoryAccessModule>();
InventoryItemBase assetRequestItem = new InventoryItemBase(itemID, AgentId); if (invAccess != null)
assetRequestItem = invService.GetItem(assetRequestItem);
if (assetRequestItem == null)
{ {
ILibraryService lib = m_scene.RequestModuleInterface<ILibraryService>(); if (!invAccess.GetAgentInventoryItem(this, itemID, requestID))
if (lib != null) return false;
assetRequestItem = lib.LibraryRootFolder.FindItem(itemID);
if (assetRequestItem == null)
return true;
}
// At this point, we need to apply perms
// only to notecards and scripts. All
// other asset types are always available
//
if (assetRequestItem.AssetType == (int)AssetType.LSLText)
{
if (!((Scene)m_scene).Permissions.CanViewScript(itemID, UUID.Zero, AgentId))
{
SendAgentAlertMessage("Insufficient permissions to view script", false);
return true;
}
}
else if (assetRequestItem.AssetType == (int)AssetType.Notecard)
{
if (!((Scene)m_scene).Permissions.CanViewNotecard(itemID, UUID.Zero, AgentId))
{
SendAgentAlertMessage("Insufficient permissions to view notecard", false);
return true;
}
} }
else
return false;
if (assetRequestItem.AssetID != requestID)
{
m_log.WarnFormat(
"[CLIENT]: {0} requested asset {1} from item {2} but this does not match item's asset {3}",
Name, requestID, itemID, assetRequestItem.AssetID);
return true;
} }
} }
} }
}
//m_assetCache.AddAssetRequest(this, transfer);
MakeAssetRequest(transfer, taskID); MakeAssetRequest(transfer, taskID);
/* RequestAsset = OnRequestAsset;
if (RequestAsset != null)
{
RequestAsset(this, transfer);
}*/
return true; return true;
} }
@ -11473,15 +11449,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP
else if (transferRequest.TransferInfo.SourceType == (int)SourceType.SimInventoryItem) else if (transferRequest.TransferInfo.SourceType == (int)SourceType.SimInventoryItem)
{ {
requestID = new UUID(transferRequest.TransferInfo.Params, 80); requestID = new UUID(transferRequest.TransferInfo.Params, 80);
//m_log.Debug("[XXX] inventory asset request " + requestID);
//if (taskID == UUID.Zero) // Agent
// if (m_scene is HGScene)
// {
// m_log.Debug("[XXX] hg asset request " + requestID);
// // We may need to fetch the asset from the user's asset server into the local asset server
// HGAssetMapper mapper = ((HGScene)m_scene).AssetMapper;
// mapper.Get(requestID, AgentId);
// }
} }
// m_log.DebugFormat("[CLIENT]: {0} requesting asset {1}", Name, requestID); // m_log.DebugFormat("[CLIENT]: {0} requesting asset {1}", Name, requestID);
@ -11497,49 +11464,25 @@ namespace OpenSim.Region.ClientStack.LindenUDP
/// <param name="asset"></param> /// <param name="asset"></param>
protected void AssetReceived(string id, Object sender, AssetBase asset) protected void AssetReceived(string id, Object sender, AssetBase asset)
{ {
if (asset == null)
return;
TransferRequestPacket transferRequest = (TransferRequestPacket)sender; TransferRequestPacket transferRequest = (TransferRequestPacket)sender;
UUID requestID = UUID.Zero; UUID requestID = UUID.Zero;
byte source = (byte)SourceType.Asset; byte source = (byte)SourceType.Asset;
if ((transferRequest.TransferInfo.SourceType == (int)SourceType.Asset) if (transferRequest.TransferInfo.SourceType == (int)SourceType.Asset)
|| (transferRequest.TransferInfo.SourceType == 2222))
{ {
requestID = new UUID(transferRequest.TransferInfo.Params, 0); requestID = new UUID(transferRequest.TransferInfo.Params, 0);
} }
else if ((transferRequest.TransferInfo.SourceType == (int)SourceType.SimInventoryItem) else if (transferRequest.TransferInfo.SourceType == (int)SourceType.SimInventoryItem)
|| (transferRequest.TransferInfo.SourceType == 3333))
{ {
requestID = new UUID(transferRequest.TransferInfo.Params, 80); requestID = new UUID(transferRequest.TransferInfo.Params, 80);
source = (byte)SourceType.SimInventoryItem; source = (byte)SourceType.SimInventoryItem;
//m_log.Debug("asset request " + requestID); //m_log.Debug("asset request " + requestID);
} }
if (null == asset)
{
if ((m_hyperAssets != null) && (transferRequest.TransferInfo.SourceType < 2000))
{
// Try the user's inventory, but only if it's different from the regions'
string userAssets = m_hyperAssets.GetUserAssetServer(AgentId);
if ((userAssets != string.Empty) && (userAssets != m_hyperAssets.GetSimAssetServer()))
{
m_log.DebugFormat("[CLIENT]: asset {0} not found in local asset storage. Trying user's storage.", id);
if (transferRequest.TransferInfo.SourceType == (int)SourceType.Asset)
transferRequest.TransferInfo.SourceType = 2222; // marker
else if (transferRequest.TransferInfo.SourceType == (int)SourceType.SimInventoryItem)
transferRequest.TransferInfo.SourceType = 3333; // marker
m_assetService.Get(userAssets + "/" + id, transferRequest, AssetReceived);
return;
}
}
//m_log.DebugFormat("[ASSET CACHE]: Asset transfer request for asset which is {0} already known to be missing. Dropping", requestID);
// FIXME: We never tell the client about assets which do not exist when requested by this transfer mechanism, which can't be right.
return;
}
// Scripts cannot be retrieved by direct request // Scripts cannot be retrieved by direct request
if (transferRequest.TransferInfo.SourceType == (int)SourceType.Asset && asset.Type == 10) if (transferRequest.TransferInfo.SourceType == (int)SourceType.Asset && asset.Type == 10)
return; return;
@ -11857,5 +11800,60 @@ namespace OpenSim.Region.ClientStack.LindenUDP
dialog.Buttons = buttons; dialog.Buttons = buttons;
OutPacket(dialog, ThrottleOutPacketType.Task); OutPacket(dialog, ThrottleOutPacketType.Task);
} }
public void StopFlying(ISceneEntity p)
{
if (p is ScenePresence)
{
ScenePresence presence = p as ScenePresence;
// It turns out to get the agent to stop flying, you have to feed it stop flying velocities
// There's no explicit message to send the client to tell it to stop flying.. it relies on the
// velocity, collision plane and avatar height
// Add 1/6 the avatar's height to it's position so it doesn't shoot into the air
// when the avatar stands up
Vector3 pos = presence.AbsolutePosition;
if (presence.Appearance.AvatarHeight != 127.0f)
pos += new Vector3(0f, 0f, (presence.Appearance.AvatarHeight/6f));
else
pos += new Vector3(0f, 0f, (1.56f/6f));
presence.AbsolutePosition = pos;
// attach a suitable collision plane regardless of the actual situation to force the LLClient to land.
// Collision plane below the avatar's position a 6th of the avatar's height is suitable.
// Mind you, that this method doesn't get called if the avatar's velocity magnitude is greater then a
// certain amount.. because the LLClient wouldn't land in that situation anyway.
// why are we still testing for this really old height value default???
if (presence.Appearance.AvatarHeight != 127.0f)
presence.CollisionPlane = new Vector4(0, 0, 0, pos.Z - presence.Appearance.AvatarHeight/6f);
else
presence.CollisionPlane = new Vector4(0, 0, 0, pos.Z - (1.56f/6f));
ImprovedTerseObjectUpdatePacket.ObjectDataBlock block =
CreateImprovedTerseBlock(p, false);
const float TIME_DILATION = 1.0f;
ushort timeDilation = Utils.FloatToUInt16(TIME_DILATION, 0.0f, 1.0f);
ImprovedTerseObjectUpdatePacket packet = new ImprovedTerseObjectUpdatePacket();
packet.RegionData.RegionHandle = m_scene.RegionInfo.RegionHandle;
packet.RegionData.TimeDilation = timeDilation;
packet.ObjectData = new ImprovedTerseObjectUpdatePacket.ObjectDataBlock[1];
packet.ObjectData[0] = block;
OutPacket(packet, ThrottleOutPacketType.Task, true);
}
//ControllingClient.SendAvatarTerseUpdate(new SendAvatarTerseData(m_rootRegionHandle, (ushort)(m_scene.TimeDilation * ushort.MaxValue), LocalId,
// AbsolutePosition, Velocity, Vector3.Zero, m_bodyRot, new Vector4(0,0,1,AbsolutePosition.Z - 0.5f), m_uuid, null, GetUpdatePriority(ControllingClient)));
}
} }
} }

View File

@ -58,8 +58,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP
private C5.IntervalHeap<J2KImage> m_priorityQueue = new C5.IntervalHeap<J2KImage>(10, new J2KImageComparer()); private C5.IntervalHeap<J2KImage> m_priorityQueue = new C5.IntervalHeap<J2KImage>(10, new J2KImageComparer());
private object m_syncRoot = new object(); private object m_syncRoot = new object();
private IHyperAssetService m_hyperAssets;
public LLClientView Client { get { return m_client; } } public LLClientView Client { get { return m_client; } }
public AssetBase MissingImage { get { return m_missingImage; } } public AssetBase MissingImage { get { return m_missingImage; } }
@ -75,7 +73,6 @@ namespace OpenSim.Region.ClientStack.LindenUDP
m_log.Error("[ClientView] - Couldn't set missing image asset, falling back to missing image packet. This is known to crash the client"); m_log.Error("[ClientView] - Couldn't set missing image asset, falling back to missing image packet. This is known to crash the client");
m_j2kDecodeModule = pJ2kDecodeModule; m_j2kDecodeModule = pJ2kDecodeModule;
m_hyperAssets = client.Scene.RequestModuleInterface<IHyperAssetService>();
} }
/// <summary> /// <summary>
@ -149,7 +146,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP
imgrequest.J2KDecoder = m_j2kDecodeModule; imgrequest.J2KDecoder = m_j2kDecodeModule;
imgrequest.AssetService = m_assetCache; imgrequest.AssetService = m_assetCache;
imgrequest.AgentID = m_client.AgentId; imgrequest.AgentID = m_client.AgentId;
imgrequest.HyperAssets = m_hyperAssets; imgrequest.InventoryAccessModule = m_client.Scene.RequestModuleInterface<IInventoryAccessModule>();
imgrequest.DiscardLevel = newRequest.DiscardLevel; imgrequest.DiscardLevel = newRequest.DiscardLevel;
imgrequest.StartPacket = Math.Max(1, newRequest.PacketNumber); imgrequest.StartPacket = Math.Max(1, newRequest.PacketNumber);
imgrequest.Priority = newRequest.Priority; imgrequest.Priority = newRequest.Priority;

View File

@ -892,7 +892,12 @@ namespace OpenSim.Region.ClientStack.LindenUDP
LLUDPClient udpClient = new LLUDPClient(this, m_throttleRates, m_throttle, circuitCode, agentID, remoteEndPoint, m_defaultRTO, m_maxRTO); LLUDPClient udpClient = new LLUDPClient(this, m_throttleRates, m_throttle, circuitCode, agentID, remoteEndPoint, m_defaultRTO, m_maxRTO);
IClientAPI existingClient; IClientAPI existingClient;
if (!m_scene.TryGetClient(agentID, out existingClient)) // REGION SYNC (Load Balancing)
ScenePresence presence;
m_scene.TryGetScenePresence(agentID, out presence);
bool syncedAvatar = (presence != null && presence.IsSyncedAvatar);
if (!m_scene.TryGetClient(agentID, out existingClient) || syncedAvatar)
{ {
// Create the LLClientView // Create the LLClientView
LLClientView client = new LLClientView(remoteEndPoint, m_scene, this, udpClient, sessionInfo, agentID, sessionID, circuitCode); LLClientView client = new LLClientView(remoteEndPoint, m_scene, this, udpClient, sessionInfo, agentID, sessionID, circuitCode);

View File

@ -182,7 +182,13 @@ namespace OpenSim.Region.CoreModules.Agent.AssetTransaction
if (part.Inventory.UpdateInventoryItem(item)) if (part.Inventory.UpdateInventoryItem(item))
{ {
if ((InventoryType)item.InvType == InventoryType.Notecard)
remoteClient.SendAgentAlertMessage("Notecard saved", false); remoteClient.SendAgentAlertMessage("Notecard saved", false);
else if ((InventoryType)item.InvType == InventoryType.LSL)
remoteClient.SendAgentAlertMessage("Script saved", false);
else
remoteClient.SendAgentAlertMessage("Item saved", false);
part.GetProperties(remoteClient); part.GetProperties(remoteClient);
} }
} }

View File

@ -243,7 +243,7 @@ namespace OpenSim.Region.CoreModules.Agent.AssetTransaction
if (mm != null) if (mm != null)
{ {
if (!mm.UploadCovered(remoteClient)) if (!mm.UploadCovered(remoteClient, mm.UploadCharge))
{ {
remoteClient.SendAgentAlertMessage("Unable to upload asset. Insufficient funds.", false); remoteClient.SendAgentAlertMessage("Unable to upload asset. Insufficient funds.", false);
return; return;

View File

@ -1,4 +1,4 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
@ -131,6 +131,12 @@ namespace OpenSim.Region.CoreModules.Avatar.ObjectCaps
if (texture != null) if (texture != null)
{ {
if (texture.Type != (sbyte)AssetType.Texture)
{
httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
httpResponse.Send();
return null;
}
SendTexture(httpRequest, httpResponse, texture); SendTexture(httpRequest, httpResponse, texture);
} }
else else
@ -147,6 +153,12 @@ namespace OpenSim.Region.CoreModules.Avatar.ObjectCaps
if (texture != null) if (texture != null)
{ {
if (texture.Type != (sbyte)AssetType.Texture)
{
httpResponse.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
httpResponse.Send();
return null;
}
SendTexture(httpRequest, httpResponse, texture); SendTexture(httpRequest, httpResponse, texture);
} }
else else
@ -178,7 +190,7 @@ namespace OpenSim.Region.CoreModules.Avatar.ObjectCaps
end = Utils.Clamp(end, 1, texture.Data.Length); end = Utils.Clamp(end, 1, texture.Data.Length);
start = Utils.Clamp(start, 0, end - 1); start = Utils.Clamp(start, 0, end - 1);
m_log.Debug("Serving " + start + " to " + end + " of " + texture.Data.Length + " bytes for texture " + texture.ID); //m_log.Debug("Serving " + start + " to " + end + " of " + texture.Data.Length + " bytes for texture " + texture.ID);
if (end - start < texture.Data.Length) if (end - start < texture.Data.Length)
response.StatusCode = (int)System.Net.HttpStatusCode.PartialContent; response.StatusCode = (int)System.Net.HttpStatusCode.PartialContent;

View File

@ -25,6 +25,7 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Reflection; using System.Reflection;
using log4net; using log4net;
@ -68,10 +69,14 @@ namespace OpenSim.Region.CoreModules.Avatar.Attachments
get { return false; } get { return false; }
} }
public void AttachObject(IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, Quaternion rot, bool silent) // Called by client
//
public void AttachObject(IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, bool silent)
{ {
m_log.Debug("[ATTACHMENTS MODULE]: Invoking AttachObject"); m_log.Debug("[ATTACHMENTS MODULE]: Invoking AttachObject");
try
{
// If we can't take it, we can't attach it! // If we can't take it, we can't attach it!
SceneObjectPart part = m_scene.GetSceneObjectPart(objectLocalID); SceneObjectPart part = m_scene.GetSceneObjectPart(objectLocalID);
if (part == null) if (part == null)
@ -81,7 +86,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Attachments
return; return;
// Calls attach with a Zero position // Calls attach with a Zero position
if (AttachObject(remoteClient, objectLocalID, AttachmentPt, rot, Vector3.Zero, false)) if (AttachObject(remoteClient, part.ParentGroup, AttachmentPt, false))
{ {
m_scene.EventManager.TriggerOnAttach(objectLocalID, part.ParentGroup.GetFromItemID(), remoteClient.AgentId); m_scene.EventManager.TriggerOnAttach(objectLocalID, part.ParentGroup.GetFromItemID(), remoteClient.AgentId);
@ -97,13 +102,16 @@ namespace OpenSim.Region.CoreModules.Avatar.Attachments
} }
} }
} }
catch (Exception e)
{
m_log.DebugFormat("[ATTACHMENTS MODULE]: exception upon Attach Object {0}", e);
}
}
public bool AttachObject( public bool AttachObject(IClientAPI remoteClient, SceneObjectGroup group, uint AttachmentPt, bool silent)
IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, Quaternion rot, Vector3 attachPos, bool silent)
{
SceneObjectGroup group = m_scene.GetGroupByPrim(objectLocalID);
if (group != null)
{ {
Vector3 attachPos = group.AbsolutePosition;
if (m_scene.Permissions.CanTakeObject(group.UUID, remoteClient.AgentId)) if (m_scene.Permissions.CanTakeObject(group.UUID, remoteClient.AgentId))
{ {
// If the attachment point isn't the same as the one previously used // If the attachment point isn't the same as the one previously used
@ -132,19 +140,33 @@ namespace OpenSim.Region.CoreModules.Avatar.Attachments
group.SetAttachmentPoint((byte)AttachmentPt); group.SetAttachmentPoint((byte)AttachmentPt);
group.AbsolutePosition = attachPos; group.AbsolutePosition = attachPos;
// Saves and gets itemID // Remove any previous attachments
UUID itemId; ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
UUID itemID = UUID.Zero;
if (sp != null)
{
foreach(SceneObjectGroup grp in sp.Attachments)
{
if (grp.GetAttachmentPoint() == (byte)AttachmentPt)
{
itemID = grp.GetFromItemID();
break;
}
}
if (itemID != UUID.Zero)
DetachSingleAttachmentToInv(itemID, remoteClient);
}
if (group.GetFromItemID() == UUID.Zero) if (group.GetFromItemID() == UUID.Zero)
{ {
m_scene.attachObjectAssetStore(remoteClient, group, remoteClient.AgentId, out itemId); m_scene.attachObjectAssetStore(remoteClient, group, remoteClient.AgentId, out itemID);
} }
else else
{ {
itemId = group.GetFromItemID(); itemID = group.GetFromItemID();
} }
SetAttachmentInventoryStatus(remoteClient, AttachmentPt, itemId, group); SetAttachmentInventoryStatus(remoteClient, AttachmentPt, itemID, group);
group.AttachToAgent(remoteClient.AgentId, AttachmentPt, attachPos, silent); group.AttachToAgent(remoteClient.AgentId, AttachmentPt, attachPos, silent);
@ -160,12 +182,6 @@ namespace OpenSim.Region.CoreModules.Avatar.Attachments
return false; return false;
} }
}
else
{
m_log.DebugFormat("[ATTACHMENTS MODULE]: AttachObject found no such scene object {0}", objectLocalID);
return false;
}
return true; return true;
} }
@ -229,8 +245,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Attachments
if (AttachmentPt != 0 && AttachmentPt != objatt.GetAttachmentPoint()) if (AttachmentPt != 0 && AttachmentPt != objatt.GetAttachmentPoint())
tainted = true; tainted = true;
AttachObject( AttachObject(remoteClient, objatt, AttachmentPt, false);
remoteClient, objatt.LocalId, AttachmentPt, Quaternion.Identity, objatt.AbsolutePosition, false);
//objatt.ScheduleGroupForFullUpdate(); //objatt.ScheduleGroupForFullUpdate();
if (tainted) if (tainted)
@ -344,7 +359,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Attachments
// Save avatar attachment information // Save avatar attachment information
if (m_scene.AvatarFactory != null) if (m_scene.AvatarFactory != null)
{ {
m_log.Debug("[ATTACHMENTS MODULE]: Saving avatar attachment. AgentID: " + remoteClient.AgentId + ", ItemID: " + itemID); m_log.Debug("[ATTACHMENTS MODULE]: Dettaching from UserID: " + remoteClient.AgentId + ", ItemID: " + itemID);
m_scene.AvatarFactory.UpdateDatabase(remoteClient.AgentId, presence.Appearance); m_scene.AvatarFactory.UpdateDatabase(remoteClient.AgentId, presence.Appearance);
} }
} }

View File

@ -198,7 +198,7 @@ namespace OpenSim.Region.CoreModules.Avatar.AvatarFactory
public void UpdateDatabase(UUID user, AvatarAppearance appearance) public void UpdateDatabase(UUID user, AvatarAppearance appearance)
{ {
//m_log.DebugFormat("[APPEARANCE]: UpdateDatabase"); m_log.DebugFormat("[APPEARANCE]: UpdateDatabase");
AvatarData adata = new AvatarData(appearance); AvatarData adata = new AvatarData(appearance);
m_scene.AvatarService.SetAvatar(user, adata); m_scene.AvatarService.SetAvatar(user, adata);
} }

View File

@ -81,14 +81,14 @@ namespace OpenSim.Region.CoreModules.Avatar.Dialog
{ {
ScenePresence sp = m_scene.GetScenePresence(agentID); ScenePresence sp = m_scene.GetScenePresence(agentID);
if (sp != null && !sp.IsChildAgent) if (sp != null)
sp.ControllingClient.SendAgentAlertMessage(message, modal); sp.ControllingClient.SendAgentAlertMessage(message, modal);
} }
public void SendAlertToUser(string firstName, string lastName, string message, bool modal) public void SendAlertToUser(string firstName, string lastName, string message, bool modal)
{ {
ScenePresence presence = m_scene.GetScenePresence(firstName, lastName); ScenePresence presence = m_scene.GetScenePresence(firstName, lastName);
if (presence != null && !presence.IsChildAgent) if (presence != null)
presence.ControllingClient.SendAgentAlertMessage(message, modal); presence.ControllingClient.SendAgentAlertMessage(message, modal);
} }
@ -96,7 +96,6 @@ namespace OpenSim.Region.CoreModules.Avatar.Dialog
{ {
m_scene.ForEachScenePresence(delegate(ScenePresence presence) m_scene.ForEachScenePresence(delegate(ScenePresence presence)
{ {
if (!presence.IsChildAgent)
presence.ControllingClient.SendAlertMessage(message); presence.ControllingClient.SendAlertMessage(message);
}); });
} }
@ -119,7 +118,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Dialog
} }
ScenePresence sp = m_scene.GetScenePresence(avatarID); ScenePresence sp = m_scene.GetScenePresence(avatarID);
if (sp != null && !sp.IsChildAgent) if (sp != null)
sp.ControllingClient.SendDialog(objectName, objectID, ownerFirstName, ownerLastName, message, textureID, ch, buttonlabels); sp.ControllingClient.SendDialog(objectName, objectID, ownerFirstName, ownerLastName, message, textureID, ch, buttonlabels);
} }
@ -128,7 +127,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Dialog
{ {
ScenePresence sp = m_scene.GetScenePresence(avatarID); ScenePresence sp = m_scene.GetScenePresence(avatarID);
if (sp != null && !sp.IsChildAgent) if (sp != null)
sp.ControllingClient.SendLoadURL(objectName, objectID, ownerID, groupOwned, message, url); sp.ControllingClient.SendLoadURL(objectName, objectID, ownerID, groupOwned, message, url);
} }
@ -149,7 +148,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Dialog
ScenePresence sp = m_scene.GetScenePresence(avatarid); ScenePresence sp = m_scene.GetScenePresence(avatarid);
if (sp != null && !sp.IsChildAgent) if (sp != null)
sp.ControllingClient.SendTextBoxRequest(message, chatChannel, name, ownerFirstName, ownerLastName, objectid); sp.ControllingClient.SendTextBoxRequest(message, chatChannel, name, ownerFirstName, ownerLastName, objectid);
} }

View File

@ -111,10 +111,12 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends
protected IGridService GridService protected IGridService GridService
{ {
get get { return m_Scenes[0].GridService; }
{
return m_Scenes[0].GridService;
} }
public IUserAccountService UserAccountService
{
get { return m_Scenes[0].UserAccountService; }
} }
public IScene Scene public IScene Scene
@ -218,8 +220,8 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends
client.OnGrantUserRights += OnGrantUserRights; client.OnGrantUserRights += OnGrantUserRights;
client.OnLogout += OnLogout; lock (m_Friends)
{
if (m_Friends.ContainsKey(client.AgentId)) if (m_Friends.ContainsKey(client.AgentId))
{ {
m_Friends[client.AgentId].Refcount++; m_Friends[client.AgentId].Refcount++;
@ -234,12 +236,18 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends
newFriends.RegionID = UUID.Zero; newFriends.RegionID = UUID.Zero;
m_Friends.Add(client.AgentId, newFriends); m_Friends.Add(client.AgentId, newFriends);
}
//StatusChange(client.AgentId, true);
} }
private void OnClientClosed(UUID agentID, Scene scene) private void OnClientClosed(UUID agentID, Scene scene)
{ {
ScenePresence sp = scene.GetScenePresence(agentID);
if (sp != null && !sp.IsChildAgent)
// do this for root agents closing out
StatusChange(agentID, false);
lock (m_Friends)
if (m_Friends.ContainsKey(agentID)) if (m_Friends.ContainsKey(agentID))
{ {
if (m_Friends[agentID].Refcount == 1) if (m_Friends[agentID].Refcount == 1)
@ -249,23 +257,18 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends
} }
} }
private void OnLogout(IClientAPI client)
{
StatusChange(client.AgentId, false);
m_Friends.Remove(client.AgentId);
}
private void OnMakeRootAgent(ScenePresence sp) private void OnMakeRootAgent(ScenePresence sp)
{ {
UUID agentID = sp.ControllingClient.AgentId; UUID agentID = sp.ControllingClient.AgentId;
if (m_Friends.ContainsKey(agentID)) if (m_Friends.ContainsKey(agentID))
{ {
if (m_Friends[agentID].RegionID == UUID.Zero && m_Friends[agentID].Friends == null) // This is probably an overkill, but just
{ // to make sure we have the latest and greatest
// friends list -- always pull OnMakeRoot
m_Friends[agentID].Friends = m_Friends[agentID].Friends =
m_FriendsService.GetFriends(agentID); m_FriendsService.GetFriends(agentID);
}
m_Friends[agentID].RegionID = m_Friends[agentID].RegionID =
sp.ControllingClient.Scene.RegionInfo.RegionID; sp.ControllingClient.Scene.RegionInfo.RegionID;
} }
@ -431,20 +434,29 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends
/// <param name="online"></param> /// <param name="online"></param>
private void StatusChange(UUID agentID, bool online) private void StatusChange(UUID agentID, bool online)
{ {
//m_log.DebugFormat("[FRIENDS]: StatusChange {0}", online);
if (m_Friends.ContainsKey(agentID)) if (m_Friends.ContainsKey(agentID))
{ {
//m_log.DebugFormat("[FRIENDS]: # of friends: {0}", m_Friends[agentID].Friends.Length);
List<FriendInfo> friendList = new List<FriendInfo>(); List<FriendInfo> friendList = new List<FriendInfo>();
foreach (FriendInfo fi in m_Friends[agentID].Friends) foreach (FriendInfo fi in m_Friends[agentID].Friends)
{ {
if (((fi.MyFlags & 1) != 0) && (fi.TheirFlags != -1)) if (((fi.MyFlags & 1) != 0) && (fi.TheirFlags != -1))
friendList.Add(fi); friendList.Add(fi);
} }
Util.FireAndForget(delegate
{
foreach (FriendInfo fi in friendList) foreach (FriendInfo fi in friendList)
{ {
//m_log.DebugFormat("[FRIENDS]: Notifying {0}", fi.PrincipalID);
// Notify about this user status // Notify about this user status
StatusNotify(fi, agentID, online); StatusNotify(fi, agentID, online);
} }
});
} }
else
m_log.WarnFormat("[FRIENDS]: {0} not found in cache", agentID);
} }
private void StatusNotify(FriendInfo friend, UUID userID, bool online) private void StatusNotify(FriendInfo friend, UUID userID, bool online)
@ -461,16 +473,26 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends
PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() }); PresenceInfo[] friendSessions = PresenceService.GetAgents(new string[] { friendID.ToString() });
if (friendSessions != null && friendSessions.Length > 0) if (friendSessions != null && friendSessions.Length > 0)
{ {
PresenceInfo friendSession = friendSessions[0]; PresenceInfo friendSession = null;
foreach (PresenceInfo pinfo in friendSessions)
if (pinfo.RegionID != UUID.Zero) // let's guard against sessions-gone-bad
{
friendSession = pinfo;
break;
}
if (friendSession != null) if (friendSession != null)
{ {
GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID); GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
//m_log.DebugFormat("[FRIENDS]: Remote Notify to region {0}", region.RegionName);
m_FriendsSimConnector.StatusNotify(region, userID, friendID, online); m_FriendsSimConnector.StatusNotify(region, userID, friendID, online);
} }
} }
// Friend is not online. Ignore. // Friend is not online. Ignore.
} }
else
m_log.WarnFormat("[FRIENDS]: Error parsing friend ID {0}", friend.Friend);
} }
private void OnInstantMessage(IClientAPI client, GridInstantMessage im) private void OnInstantMessage(IClientAPI client, GridInstantMessage im)
@ -481,7 +503,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends
UUID principalID = new UUID(im.fromAgentID); UUID principalID = new UUID(im.fromAgentID);
UUID friendID = new UUID(im.toAgentID); UUID friendID = new UUID(im.toAgentID);
m_log.DebugFormat("[FRIENDS]: {0} offered friendship to {1}", principalID, friendID); m_log.DebugFormat("[FRIENDS]: {0} ({1}) offered friendship to {2}", principalID, im.fromAgentName, friendID);
// This user wants to be friends with the other user. // This user wants to be friends with the other user.
// Let's add the relation backwards, in case the other is not online // Let's add the relation backwards, in case the other is not online
@ -499,6 +521,9 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends
im.imSessionID = im.fromAgentID; im.imSessionID = im.fromAgentID;
// Try the local sim // Try the local sim
UserAccount account = UserAccountService.GetUserAccount(Scene.RegionInfo.ScopeID, agentID);
im.fromAgentName = (account == null) ? "Unknown" : account.FirstName + " " + account.LastName;
if (LocalFriendshipOffered(friendID, im)) if (LocalFriendshipOffered(friendID, im))
return; return;
@ -518,12 +543,13 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends
private void OnApproveFriendRequest(IClientAPI client, UUID agentID, UUID friendID, List<UUID> callingCardFolders) private void OnApproveFriendRequest(IClientAPI client, UUID agentID, UUID friendID, List<UUID> callingCardFolders)
{ {
m_log.DebugFormat("[FRIENDS]: {0} accepted friendship from {1}", agentID, friendID);
FriendsService.StoreFriend(agentID, friendID.ToString(), 1); FriendsService.StoreFriend(agentID, friendID.ToString(), 1);
FriendsService.StoreFriend(friendID, agentID.ToString(), 1); FriendsService.StoreFriend(friendID, agentID.ToString(), 1);
// update the local cache // update the local cache
m_Friends[agentID].Friends = FriendsService.GetFriends(agentID); m_Friends[agentID].Friends = FriendsService.GetFriends(agentID);
m_log.DebugFormat("[FRIENDS]: {0} accepted friendship from {1}", agentID, friendID);
// //
// Notify the friend // Notify the friend
@ -572,7 +598,10 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends
if (friendSession != null) if (friendSession != null)
{ {
GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID); GridRegion region = GridService.GetRegionByUUID(m_Scenes[0].RegionInfo.ScopeID, friendSession.RegionID);
if (region != null)
m_FriendsSimConnector.FriendshipDenied(region, agentID, client.Name, friendID); m_FriendsSimConnector.FriendshipDenied(region, agentID, client.Name, friendID);
else
m_log.WarnFormat("[FRIENDS]: Could not find region {0} in locating {1}", friendSession.RegionID, friendID);
} }
} }
} }
@ -739,8 +768,15 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends
bool canEditObjectsChanged = ((rights ^ userFlags) & (int)FriendRights.CanModifyObjects) != 0; bool canEditObjectsChanged = ((rights ^ userFlags) & (int)FriendRights.CanModifyObjects) != 0;
if (canEditObjectsChanged) if (canEditObjectsChanged)
friendClient.SendChangeUserRights(userID, friendID, rights); friendClient.SendChangeUserRights(userID, friendID, rights);
} }
// update local cache
//m_Friends[friendID].Friends = m_FriendsService.GetFriends(friendID);
foreach (FriendInfo finfo in m_Friends[friendID].Friends)
if (finfo.Friend == userID.ToString())
finfo.TheirFlags = rights;
return true; return true;
} }
@ -753,7 +789,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends
IClientAPI friendClient = LocateClientObject(friendID); IClientAPI friendClient = LocateClientObject(friendID);
if (friendClient != null) if (friendClient != null)
{ {
//m_log.DebugFormat("[FRIENDS]: Notify {0} that user {1} is {2}", friend.Friend, userID, online); //m_log.DebugFormat("[FRIENDS]: Local Status Notify {0} that user {1} is {2}", friendID, userID, online);
// the friend in this sim as root agent // the friend in this sim as root agent
if (online) if (online)
friendClient.SendAgentOnline(new UUID[] { userID }); friendClient.SendAgentOnline(new UUID[] { userID });

View File

@ -35,6 +35,7 @@ using OpenSim.Framework;
using OpenSim.Server.Base; using OpenSim.Server.Base;
using OpenSim.Framework.Servers.HttpServer; using OpenSim.Framework.Servers.HttpServer;
using FriendInfo = OpenSim.Services.Interfaces.FriendInfo; using FriendInfo = OpenSim.Services.Interfaces.FriendInfo;
using OpenSim.Services.Interfaces;
using OpenMetaverse; using OpenMetaverse;
using log4net; using log4net;
@ -61,7 +62,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends
sr.Close(); sr.Close();
body = body.Trim(); body = body.Trim();
m_log.DebugFormat("[XXX]: query String: {0}", body); //m_log.DebugFormat("[XXX]: query String: {0}", body);
try try
{ {
@ -115,9 +116,15 @@ namespace OpenSim.Region.CoreModules.Avatar.Friends
if (!UUID.TryParse(request["ToID"].ToString(), out toID)) if (!UUID.TryParse(request["ToID"].ToString(), out toID))
return FailureResult(); return FailureResult();
GridInstantMessage im = new GridInstantMessage(m_FriendsModule.Scene, fromID, "", toID, UserAccount account = m_FriendsModule.UserAccountService.GetUserAccount(m_FriendsModule.Scene.RegionInfo.ScopeID, fromID);
string name = (account == null) ? "Unknown" : account.FirstName + " " + account.LastName;
GridInstantMessage im = new GridInstantMessage(m_FriendsModule.Scene, fromID, name, toID,
(byte)InstantMessageDialog.FriendshipOffered, message, false, Vector3.Zero); (byte)InstantMessageDialog.FriendshipOffered, message, false, Vector3.Zero);
// !! HACK
im.imSessionID = im.fromAgentID;
if (m_FriendsModule.LocalFriendshipOffered(toID, im)) if (m_FriendsModule.LocalFriendshipOffered(toID, im))
return SuccessResult(); return SuccessResult();

View File

@ -268,6 +268,8 @@ namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
fromAgentName = (string)requestData["from_agent_name"]; fromAgentName = (string)requestData["from_agent_name"];
message = (string)requestData["message"]; message = (string)requestData["message"];
if (message == null)
message = string.Empty;
// Bytes don't transfer well over XMLRPC, so, we Base64 Encode them. // Bytes don't transfer well over XMLRPC, so, we Base64 Encode them.
string requestData1 = (string)requestData["dialog"]; string requestData1 = (string)requestData["dialog"];

View File

@ -92,37 +92,38 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
/// returned /// returned
/// </returns> /// </returns>
public List<InventoryNodeBase> Execute() public List<InventoryNodeBase> Execute()
{
try
{ {
string filePath = "ERROR"; string filePath = "ERROR";
int successfulAssetRestores = 0; int successfulAssetRestores = 0;
int failedAssetRestores = 0; int failedAssetRestores = 0;
int successfulItemRestores = 0; int successfulItemRestores = 0;
List<InventoryNodeBase> nodesLoaded = new List<InventoryNodeBase>();
//InventoryFolderImpl rootDestinationFolder = m_userInfo.RootFolder.FindFolderByPath(m_invPath); List<InventoryNodeBase> loadedNodes = new List<InventoryNodeBase>();
InventoryFolderBase rootDestinationFolder
List<InventoryFolderBase> folderCandidates
= InventoryArchiveUtils.FindFolderByPath( = InventoryArchiveUtils.FindFolderByPath(
m_scene.InventoryService, m_userInfo.PrincipalID, m_invPath); m_scene.InventoryService, m_userInfo.PrincipalID, m_invPath);
if (null == rootDestinationFolder) if (folderCandidates.Count == 0)
{ {
// Possibly provide an option later on to automatically create this folder if it does not exist // Possibly provide an option later on to automatically create this folder if it does not exist
m_log.ErrorFormat("[INVENTORY ARCHIVER]: Inventory path {0} does not exist", m_invPath); m_log.ErrorFormat("[INVENTORY ARCHIVER]: Inventory path {0} does not exist", m_invPath);
return nodesLoaded; return loadedNodes;
} }
InventoryFolderBase rootDestinationFolder = folderCandidates[0];
archive = new TarArchiveReader(m_loadStream); archive = new TarArchiveReader(m_loadStream);
// In order to load identically named folders, we need to keep track of the folders that we have already // In order to load identically named folders, we need to keep track of the folders that we have already
// created // resolved
Dictionary <string, InventoryFolderBase> foldersCreated = new Dictionary<string, InventoryFolderBase>(); Dictionary <string, InventoryFolderBase> resolvedFolders = new Dictionary<string, InventoryFolderBase>();
byte[] data; byte[] data;
TarArchiveReader.TarEntryType entryType; TarArchiveReader.TarEntryType entryType;
try
{
while ((data = archive.ReadEntry(out filePath, out entryType)) != null) while ((data = archive.ReadEntry(out filePath, out entryType)) != null)
{ {
if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH)) if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH))
@ -139,10 +140,15 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
} }
else if (filePath.StartsWith(ArchiveConstants.INVENTORY_PATH)) else if (filePath.StartsWith(ArchiveConstants.INVENTORY_PATH))
{ {
filePath = filePath.Substring(ArchiveConstants.INVENTORY_PATH.Length);
// Trim off the file portion if we aren't already dealing with a directory path
if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY != entryType)
filePath = filePath.Remove(filePath.LastIndexOf("/") + 1);
InventoryFolderBase foundFolder InventoryFolderBase foundFolder
= ReplicateArchivePathToUserInventory( = ReplicateArchivePathToUserInventory(
filePath, TarArchiveReader.TarEntryType.TYPE_DIRECTORY == entryType, filePath, rootDestinationFolder, resolvedFolders, loadedNodes);
rootDestinationFolder, foldersCreated, nodesLoaded);
if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY != entryType) if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY != entryType)
{ {
@ -155,23 +161,25 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
// If we're loading an item directly into the given destination folder then we need to record // If we're loading an item directly into the given destination folder then we need to record
// it separately from any loaded root folders // it separately from any loaded root folders
if (rootDestinationFolder == foundFolder) if (rootDestinationFolder == foundFolder)
nodesLoaded.Add(item); loadedNodes.Add(item);
} }
} }
} }
} }
}
finally
{
archive.Close(); archive.Close();
}
m_log.DebugFormat( m_log.DebugFormat(
"[INVENTORY ARCHIVER]: Successfully loaded {0} assets with {1} failures", "[INVENTORY ARCHIVER]: Successfully loaded {0} assets with {1} failures",
successfulAssetRestores, failedAssetRestores); successfulAssetRestores, failedAssetRestores);
m_log.InfoFormat("[INVENTORY ARCHIVER]: Successfully loaded {0} items", successfulItemRestores); m_log.InfoFormat("[INVENTORY ARCHIVER]: Successfully loaded {0} items", successfulItemRestores);
return nodesLoaded; return loadedNodes;
}
finally
{
m_loadStream.Close();
}
} }
public void Close() public void Close()
@ -183,81 +191,139 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
/// <summary> /// <summary>
/// Replicate the inventory paths in the archive to the user's inventory as necessary. /// Replicate the inventory paths in the archive to the user's inventory as necessary.
/// </summary> /// </summary>
/// <param name="archivePath">The item archive path to replicate</param> /// <param name="iarPath">The item archive path to replicate</param>
/// <param name="isDir">Is the path we're dealing with a directory?</param>
/// <param name="rootDestinationFolder">The root folder for the inventory load</param> /// <param name="rootDestinationFolder">The root folder for the inventory load</param>
/// <param name="foldersCreated"> /// <param name="resolvedFolders">
/// The folders created so far. This method will add more folders if necessary /// The folders that we have resolved so far for a given archive path.
/// This method will add more folders if necessary
/// </param> /// </param>
/// <param name="nodesLoaded"> /// <param name="loadedNodes">
/// Track the inventory nodes created. This is distinct from the folders created since for a particular folder /// Track the inventory nodes created.
/// chain, only the root node needs to be recorded
/// </param> /// </param>
/// <returns>The last user inventory folder created or found for the archive path</returns> /// <returns>The last user inventory folder created or found for the archive path</returns>
public InventoryFolderBase ReplicateArchivePathToUserInventory( public InventoryFolderBase ReplicateArchivePathToUserInventory(
string archivePath, string iarPath,
bool isDir,
InventoryFolderBase rootDestFolder, InventoryFolderBase rootDestFolder,
Dictionary <string, InventoryFolderBase> foldersCreated, Dictionary <string, InventoryFolderBase> resolvedFolders,
List<InventoryNodeBase> nodesLoaded) List<InventoryNodeBase> loadedNodes)
{ {
archivePath = archivePath.Substring(ArchiveConstants.INVENTORY_PATH.Length); string iarPathExisting = iarPath;
// Remove the file portion if we aren't already dealing with a directory path
if (!isDir)
archivePath = archivePath.Remove(archivePath.LastIndexOf("/") + 1);
string originalArchivePath = archivePath;
// m_log.DebugFormat( // m_log.DebugFormat(
// "[INVENTORY ARCHIVER]: Loading folder {0} {1}", rootDestFolder.Name, rootDestFolder.ID); // "[INVENTORY ARCHIVER]: Loading folder {0} {1}", rootDestFolder.Name, rootDestFolder.ID);
InventoryFolderBase destFolder = ResolveDestinationFolder(rootDestFolder, ref iarPathExisting, resolvedFolders);
// m_log.DebugFormat(
// "[INVENTORY ARCHIVER]: originalArchivePath [{0}], section already loaded [{1}]",
// iarPath, iarPathExisting);
string iarPathToCreate = iarPath.Substring(iarPathExisting.Length);
CreateFoldersForPath(destFolder, iarPathExisting, iarPathToCreate, resolvedFolders, loadedNodes);
return destFolder;
}
/// <summary>
/// Resolve a destination folder
/// </summary>
///
/// We require here a root destination folder (usually the root of the user's inventory) and the archive
/// path. We also pass in a list of previously resolved folders in case we've found this one previously.
///
/// <param name="archivePath">
/// The item archive path to resolve. The portion of the path passed back is that
/// which corresponds to the resolved desintation folder.
/// <param name="rootDestinationFolder">
/// The root folder for the inventory load
/// </param>
/// <param name="resolvedFolders">
/// The folders that we have resolved so far for a given archive path.
/// </param>
/// <returns>
/// The folder in the user's inventory that matches best the archive path given. If no such folder was found
/// then the passed in root destination folder is returned.
/// </returns>
protected InventoryFolderBase ResolveDestinationFolder(
InventoryFolderBase rootDestFolder,
ref string archivePath,
Dictionary <string, InventoryFolderBase> resolvedFolders)
{
// string originalArchivePath = archivePath;
InventoryFolderBase destFolder = null; InventoryFolderBase destFolder = null;
// XXX: Nasty way of dealing with a path that has no directory component
if (archivePath.Length > 0) if (archivePath.Length > 0)
{ {
while (null == destFolder && archivePath.Length > 0) while (null == destFolder && archivePath.Length > 0)
{ {
if (foldersCreated.ContainsKey(archivePath)) // m_log.DebugFormat("[INVENTORY ARCHIVER]: Trying to resolve destination folder {0}", archivePath);
if (resolvedFolders.ContainsKey(archivePath))
{ {
// m_log.DebugFormat( // m_log.DebugFormat(
// "[INVENTORY ARCHIVER]: Found previously created folder from archive path {0}", archivePath); // "[INVENTORY ARCHIVER]: Found previously created folder from archive path {0}", archivePath);
destFolder = foldersCreated[archivePath]; destFolder = resolvedFolders[archivePath];
} }
else else
{ {
// Don't include the last slash // Don't include the last slash so find the penultimate one
int penultimateSlashIndex = archivePath.LastIndexOf("/", archivePath.Length - 2); int penultimateSlashIndex = archivePath.LastIndexOf("/", archivePath.Length - 2);
if (penultimateSlashIndex >= 0) if (penultimateSlashIndex >= 0)
{ {
// Remove the last section of path so that we can see if we've already resolved the parent
archivePath = archivePath.Remove(penultimateSlashIndex + 1); archivePath = archivePath.Remove(penultimateSlashIndex + 1);
} }
else else
{ {
m_log.DebugFormat( // m_log.DebugFormat(
"[INVENTORY ARCHIVER]: Found no previously created folder for archive path {0}", // "[INVENTORY ARCHIVER]: Found no previously created folder for archive path {0}",
originalArchivePath); // originalArchivePath);
archivePath = string.Empty; archivePath = string.Empty;
destFolder = rootDestFolder; destFolder = rootDestFolder;
} }
} }
} }
} }
else
{ if (null == destFolder)
destFolder = rootDestFolder; destFolder = rootDestFolder;
return destFolder;
} }
string archivePathSectionToCreate = originalArchivePath.Substring(archivePath.Length); /// <summary>
string[] rawDirsToCreate /// Create a set of folders for the given path.
= archivePathSectionToCreate.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); /// </summary>
/// <param name="destFolder">
/// The root folder from which the creation will take place.
/// </param>
/// <param name="iarPathExisting">
/// the part of the iar path that already exists
/// </param>
/// <param name="iarPathToReplicate">
/// The path to replicate in the user's inventory from iar
/// </param>
/// <param name="resolvedFolders">
/// The folders that we have resolved so far for a given archive path.
/// </param>
/// <param name="loadedNodes">
/// Track the inventory nodes created.
/// </param>
protected void CreateFoldersForPath(
InventoryFolderBase destFolder,
string iarPathExisting,
string iarPathToReplicate,
Dictionary <string, InventoryFolderBase> resolvedFolders,
List<InventoryNodeBase> loadedNodes)
{
string[] rawDirsToCreate = iarPathToReplicate.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
int i = 0; int i = 0;
while (i < rawDirsToCreate.Length) while (i < rawDirsToCreate.Length)
{ {
m_log.DebugFormat("[INVENTORY ARCHIVER]: Loading archived folder {0}", rawDirsToCreate[i]); // m_log.DebugFormat("[INVENTORY ARCHIVER]: Creating folder {0} from IAR", rawDirsToCreate[i]);
int identicalNameIdentifierIndex int identicalNameIdentifierIndex
= rawDirsToCreate[i].LastIndexOf( = rawDirsToCreate[i].LastIndexOf(
@ -283,63 +349,16 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
(short)AssetType.Unknown, destFolder.ID, 1); (short)AssetType.Unknown, destFolder.ID, 1);
m_scene.InventoryService.AddFolder(destFolder); m_scene.InventoryService.AddFolder(destFolder);
// UUID newFolderId = UUID.Random();
// m_scene.InventoryService.AddFolder(
// m_userInfo.CreateFolder(
// folderName, newFolderId, (ushort)AssetType.Folder, foundFolder.ID);
// m_log.DebugFormat("[INVENTORY ARCHIVER]: Retrieving newly created folder {0}", folderName);
// foundFolder = foundFolder.GetChildFolder(newFolderId);
// m_log.DebugFormat(
// "[INVENTORY ARCHIVER]: Retrieved newly created folder {0} with ID {1}",
// foundFolder.Name, foundFolder.ID);
// Record that we have now created this folder // Record that we have now created this folder
archivePath += rawDirsToCreate[i] + "/"; iarPathExisting += rawDirsToCreate[i] + "/";
m_log.DebugFormat("[INVENTORY ARCHIVER]: Loaded archive path {0}", archivePath); m_log.DebugFormat("[INVENTORY ARCHIVER]: Created folder {0} from IAR", iarPathExisting);
foldersCreated[archivePath] = destFolder; resolvedFolders[iarPathExisting] = destFolder;
if (0 == i) if (0 == i)
nodesLoaded.Add(destFolder); loadedNodes.Add(destFolder);
i++; i++;
} }
return destFolder;
/*
string[] rawFolders = filePath.Split(new char[] { '/' });
// Find the folders that do exist along the path given
int i = 0;
bool noFolder = false;
InventoryFolderImpl foundFolder = rootDestinationFolder;
while (!noFolder && i < rawFolders.Length)
{
InventoryFolderImpl folder = foundFolder.FindFolderByPath(rawFolders[i]);
if (null != folder)
{
m_log.DebugFormat("[INVENTORY ARCHIVER]: Found folder {0}", folder.Name);
foundFolder = folder;
i++;
}
else
{
noFolder = true;
}
}
// Create any folders that did not previously exist
while (i < rawFolders.Length)
{
m_log.DebugFormat("[INVENTORY ARCHIVER]: Creating folder {0}", rawFolders[i]);
UUID newFolderId = UUID.Random();
m_userInfo.CreateFolder(
rawFolders[i++], newFolderId, (ushort)AssetType.Folder, foundFolder.ID);
foundFolder = foundFolder.GetChildFolder(newFolderId);
}
*/
} }
/// <summary> /// <summary>

View File

@ -55,8 +55,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
/// ///
/// This method does not handle paths that contain multiple delimitors /// This method does not handle paths that contain multiple delimitors
/// ///
/// FIXME: We do not yet handle situations where folders have the same name. We could handle this by some /// FIXME: We have no way of distinguishing folders with the same path
/// XPath like expression
/// ///
/// FIXME: Delimitors which occur in names themselves are not currently escapable. /// FIXME: Delimitors which occur in names themselves are not currently escapable.
/// ///
@ -70,14 +69,14 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
/// The path to the required folder. /// The path to the required folder.
/// It this is empty or consists only of the PATH_DELIMTER then this folder itself is returned. /// It this is empty or consists only of the PATH_DELIMTER then this folder itself is returned.
/// </param> /// </param>
/// <returns>null if the folder is not found</returns> /// <returns>An empty list if the folder is not found, otherwise a list of all folders that match the name</returns>
public static InventoryFolderBase FindFolderByPath( public static List<InventoryFolderBase> FindFolderByPath(
IInventoryService inventoryService, UUID userId, string path) IInventoryService inventoryService, UUID userId, string path)
{ {
InventoryFolderBase rootFolder = inventoryService.GetRootFolder(userId); InventoryFolderBase rootFolder = inventoryService.GetRootFolder(userId);
if (null == rootFolder) if (null == rootFolder)
return null; return new List<InventoryFolderBase>();
return FindFolderByPath(inventoryService, rootFolder, path); return FindFolderByPath(inventoryService, rootFolder, path);
} }
@ -88,8 +87,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
/// ///
/// This method does not handle paths that contain multiple delimitors /// This method does not handle paths that contain multiple delimitors
/// ///
/// FIXME: We do not yet handle situations where folders have the same name. We could handle this by some /// FIXME: We have no way of distinguishing folders with the same path.
/// XPath like expression
/// ///
/// FIXME: Delimitors which occur in names themselves are not currently escapable. /// FIXME: Delimitors which occur in names themselves are not currently escapable.
/// ///
@ -103,17 +101,25 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
/// The path to the required folder. /// The path to the required folder.
/// It this is empty or consists only of the PATH_DELIMTER then this folder itself is returned. /// It this is empty or consists only of the PATH_DELIMTER then this folder itself is returned.
/// </param> /// </param>
/// <returns>null if the folder is not found</returns> /// <returns>An empty list if the folder is not found, otherwise a list of all folders that match the name</returns>
public static InventoryFolderBase FindFolderByPath( public static List<InventoryFolderBase> FindFolderByPath(
IInventoryService inventoryService, InventoryFolderBase startFolder, string path) IInventoryService inventoryService, InventoryFolderBase startFolder, string path)
{ {
List<InventoryFolderBase> foundFolders = new List<InventoryFolderBase>();
if (path == string.Empty) if (path == string.Empty)
return startFolder; {
foundFolders.Add(startFolder);
return foundFolders;
}
path = path.Trim(); path = path.Trim();
if (path == PATH_DELIMITER.ToString()) if (path == PATH_DELIMITER.ToString())
return startFolder; {
foundFolders.Add(startFolder);
return foundFolders;
}
string[] components = SplitEscapedPath(path); string[] components = SplitEscapedPath(path);
components[0] = UnescapePath(components[0]); components[0] = UnescapePath(components[0]);
@ -127,14 +133,13 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
if (folder.Name == components[0]) if (folder.Name == components[0])
{ {
if (components.Length > 1) if (components.Length > 1)
return FindFolderByPath(inventoryService, folder, components[1]); foundFolders.AddRange(FindFolderByPath(inventoryService, folder, components[1]));
else else
return folder; foundFolders.Add(folder);
} }
} }
// We didn't find a folder with the right name return foundFolders;
return null;
} }
/// <summary> /// <summary>
@ -201,11 +206,18 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
if (components.Length == 1) if (components.Length == 1)
{ {
// m_log.DebugFormat("FOUND SINGLE COMPONENT [{0}]", components[0]); // m_log.DebugFormat(
// "FOUND SINGLE COMPONENT [{0}]. Looking for this in [{1}] {2}",
// components[0], startFolder.Name, startFolder.ID);
List<InventoryItemBase> items = inventoryService.GetFolderItems(startFolder.Owner, startFolder.ID); List<InventoryItemBase> items = inventoryService.GetFolderItems(startFolder.Owner, startFolder.ID);
// m_log.DebugFormat("[INVENTORY ARCHIVE UTILS]: Found {0} items in FindItemByPath()", items.Count);
foreach (InventoryItemBase item in items) foreach (InventoryItemBase item in items)
{ {
// m_log.DebugFormat("[INVENTORY ARCHIVE UTILS]: Inspecting item {0} {1}", item.Name, item.ID);
if (item.Name == components[0]) if (item.Name == components[0])
return item; return item;
} }

View File

@ -126,15 +126,17 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
// We're almost done. Just need to write out the control file now // We're almost done. Just need to write out the control file now
m_archiveWriter.WriteFile(ArchiveConstants.CONTROL_FILE_PATH, Create0p1ControlFile()); m_archiveWriter.WriteFile(ArchiveConstants.CONTROL_FILE_PATH, Create0p1ControlFile());
m_log.InfoFormat("[ARCHIVER]: Added control file to archive."); m_log.InfoFormat("[ARCHIVER]: Added control file to archive.");
m_archiveWriter.Close(); m_archiveWriter.Close();
} }
catch (Exception e) catch (Exception e)
{ {
m_saveStream.Close();
reportedException = e; reportedException = e;
succeeded = false; succeeded = false;
} }
finally
{
m_saveStream.Close();
}
m_module.TriggerInventoryArchiveSaved( m_module.TriggerInventoryArchiveSaved(
m_id, succeeded, m_userInfo, m_invPath, m_saveStream, reportedException); m_id, succeeded, m_userInfo, m_invPath, m_saveStream, reportedException);
@ -212,6 +214,8 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
/// Execute the inventory write request /// Execute the inventory write request
/// </summary> /// </summary>
public void Execute() public void Execute()
{
try
{ {
InventoryFolderBase inventoryFolder = null; InventoryFolderBase inventoryFolder = null;
InventoryItemBase inventoryItem = null; InventoryItemBase inventoryItem = null;
@ -249,9 +253,10 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
else else
{ {
m_invPath = m_invPath.Remove(m_invPath.LastIndexOf(InventoryFolderImpl.PATH_DELIMITER)); m_invPath = m_invPath.Remove(m_invPath.LastIndexOf(InventoryFolderImpl.PATH_DELIMITER));
inventoryFolder List<InventoryFolderBase> candidateFolders
= InventoryArchiveUtils.FindFolderByPath(m_scene.InventoryService, rootFolder, m_invPath); = InventoryArchiveUtils.FindFolderByPath(m_scene.InventoryService, rootFolder, m_invPath);
//inventoryFolder = m_userInfo.RootFolder.FindFolderByPath(m_invPath); if (candidateFolders.Count > 0)
inventoryFolder = candidateFolders[0];
} }
// The path may point to an item instead // The path may point to an item instead
@ -265,17 +270,13 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
{ {
// We couldn't find the path indicated // We couldn't find the path indicated
string errorMessage = string.Format("Aborted save. Could not find inventory path {0}", m_invPath); string errorMessage = string.Format("Aborted save. Could not find inventory path {0}", m_invPath);
m_log.ErrorFormat("[INVENTORY ARCHIVER]: {0}", errorMessage); Exception e = new InventoryArchiverException(errorMessage);
m_module.TriggerInventoryArchiveSaved( m_module.TriggerInventoryArchiveSaved(m_id, false, m_userInfo, m_invPath, m_saveStream, e);
m_id, false, m_userInfo, m_invPath, m_saveStream, throw e;
new Exception(errorMessage));
return;
} }
m_archiveWriter = new TarArchiveWriter(m_saveStream); m_archiveWriter = new TarArchiveWriter(m_saveStream);
try
{
if (inventoryFolder != null) if (inventoryFolder != null)
{ {
m_log.DebugFormat( m_log.DebugFormat(
@ -296,16 +297,15 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
// Don't put all this profile information into the archive right now. // Don't put all this profile information into the archive right now.
//SaveUsers(); //SaveUsers();
new AssetsRequest(
new AssetsArchiver(m_archiveWriter), m_assetUuids, m_scene.AssetService, ReceivedAllAssets).Execute();
} }
catch (Exception) catch (Exception)
{ {
m_archiveWriter.Close(); m_saveStream.Close();
throw; throw;
} }
new AssetsRequest(
new AssetsArchiver(m_archiveWriter), m_assetUuids,
m_scene.AssetService, ReceivedAllAssets).Execute();
} }
/// <summary> /// <summary>

View File

@ -1,4 +1,4 @@
/* /*
* Copyright (c) Contributors, http://opensimulator.org/ * Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders. * See CONTRIBUTORS.TXT for a full list of copyright holders.
* *
@ -24,14 +24,17 @@
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
using System;
using OpenMetaverse;
namespace OpenSim.Region.Framework.Interfaces using System;
namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
{ {
public interface IHyperAssetService /// <summary>
/// Signals an inventory archiving problem
/// </summary>
public class InventoryArchiverException : Exception
{ {
string GetUserAssetServer(UUID userID); public InventoryArchiverException(string message) : base(message) {}
string GetSimAssetServer(); public InventoryArchiverException(string message, Exception e) : base(message, e) {}
} }
} }

View File

@ -30,11 +30,11 @@ using System.Collections.Generic;
using System.IO; using System.IO;
using System.Reflection; using System.Reflection;
using log4net; using log4net;
using NDesk.Options;
using Nini.Config; using Nini.Config;
using OpenMetaverse; using OpenMetaverse;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Framework.Communications; using OpenSim.Framework.Communications;
using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces; using OpenSim.Services.Interfaces;
@ -92,7 +92,10 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
scene.AddCommand( scene.AddCommand(
this, "load iar", this, "load iar",
"load iar <first> <last> <inventory path> <password> [<IAR path>]", "load iar <first> <last> <inventory path> <password> [<IAR path>]",
//"load iar [--merge] <first> <last> <inventory path> <password> [<IAR path>]",
"Load user inventory archive (IAR).", "Load user inventory archive (IAR).",
//"--merge is an option which merges the loaded IAR with existing inventory folders where possible, rather than always creating new ones"
//+ "<first> is user's first name." + Environment.NewLine
"<first> is user's first name." + Environment.NewLine "<first> is user's first name." + Environment.NewLine
+ "<last> is user's last name." + Environment.NewLine + "<last> is user's last name." + Environment.NewLine
+ "<inventory path> is the path inside the user's inventory where the IAR should be loaded." + Environment.NewLine + "<inventory path> is the path inside the user's inventory where the IAR should be loaded." + Environment.NewLine
@ -134,7 +137,15 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
handlerInventoryArchiveSaved(id, succeeded, userInfo, invPath, saveStream, reportedException); handlerInventoryArchiveSaved(id, succeeded, userInfo, invPath, saveStream, reportedException);
} }
public bool ArchiveInventory(Guid id, string firstName, string lastName, string invPath, string pass, Stream saveStream) public bool ArchiveInventory(
Guid id, string firstName, string lastName, string invPath, string pass, Stream saveStream)
{
return ArchiveInventory(id, firstName, lastName, invPath, pass, saveStream, new Dictionary<string, object>());
}
public bool ArchiveInventory(
Guid id, string firstName, string lastName, string invPath, string pass, Stream saveStream,
Dictionary<string, object> options)
{ {
if (m_scenes.Count > 0) if (m_scenes.Count > 0)
{ {
@ -172,7 +183,9 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
return false; return false;
} }
public bool ArchiveInventory(Guid id, string firstName, string lastName, string invPath, string pass, string savePath) public bool ArchiveInventory(
Guid id, string firstName, string lastName, string invPath, string pass, string savePath,
Dictionary<string, object> options)
{ {
if (m_scenes.Count > 0) if (m_scenes.Count > 0)
{ {
@ -211,6 +224,13 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
} }
public bool DearchiveInventory(string firstName, string lastName, string invPath, string pass, Stream loadStream) public bool DearchiveInventory(string firstName, string lastName, string invPath, string pass, Stream loadStream)
{
return DearchiveInventory(firstName, lastName, invPath, pass, loadStream, new Dictionary<string, object>());
}
public bool DearchiveInventory(
string firstName, string lastName, string invPath, string pass, Stream loadStream,
Dictionary<string, object> options)
{ {
if (m_scenes.Count > 0) if (m_scenes.Count > 0)
{ {
@ -252,7 +272,9 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
return false; return false;
} }
public bool DearchiveInventory(string firstName, string lastName, string invPath, string pass, string loadPath) public bool DearchiveInventory(
string firstName, string lastName, string invPath, string pass, string loadPath,
Dictionary<string, object> options)
{ {
if (m_scenes.Count > 0) if (m_scenes.Count > 0)
{ {
@ -300,36 +322,52 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
/// <param name="cmdparams"></param> /// <param name="cmdparams"></param>
protected void HandleLoadInvConsoleCommand(string module, string[] cmdparams) protected void HandleLoadInvConsoleCommand(string module, string[] cmdparams)
{ {
if (cmdparams.Length < 6) try
{
m_log.Info("[INVENTORY ARCHIVER]: PLEASE NOTE THAT THIS FACILITY IS EXPERIMENTAL. BUG REPORTS WELCOME.");
Dictionary<string, object> options = new Dictionary<string, object>();
OptionSet optionSet = new OptionSet().Add("m|merge", delegate (string v) { options["merge"] = v != null; });
List<string> mainParams = optionSet.Parse(cmdparams);
if (mainParams.Count < 6)
{ {
m_log.Error( m_log.Error(
"[INVENTORY ARCHIVER]: usage is load iar <first name> <last name> <inventory path> <user password> [<load file path>]"); "[INVENTORY ARCHIVER]: usage is load iar <first name> <last name> <inventory path> <user password> [<load file path>]");
return; return;
} }
m_log.Info("[INVENTORY ARCHIVER]: PLEASE NOTE THAT THIS FACILITY IS EXPERIMENTAL. BUG REPORTS WELCOME."); string firstName = mainParams[2];
string lastName = mainParams[3];
string firstName = cmdparams[2]; string invPath = mainParams[4];
string lastName = cmdparams[3]; string pass = mainParams[5];
string invPath = cmdparams[4]; string loadPath = (mainParams.Count > 6 ? mainParams[6] : DEFAULT_INV_BACKUP_FILENAME);
string pass = cmdparams[5];
string loadPath = (cmdparams.Length > 6 ? cmdparams[6] : DEFAULT_INV_BACKUP_FILENAME);
m_log.InfoFormat( m_log.InfoFormat(
"[INVENTORY ARCHIVER]: Loading archive {0} to inventory path {1} for {2} {3}", "[INVENTORY ARCHIVER]: Loading archive {0} to inventory path {1} for {2} {3}",
loadPath, invPath, firstName, lastName); loadPath, invPath, firstName, lastName);
if (DearchiveInventory(firstName, lastName, invPath, pass, loadPath)) if (DearchiveInventory(firstName, lastName, invPath, pass, loadPath, options))
m_log.InfoFormat( m_log.InfoFormat(
"[INVENTORY ARCHIVER]: Loaded archive {0} for {1} {2}", "[INVENTORY ARCHIVER]: Loaded archive {0} for {1} {2}",
loadPath, firstName, lastName); loadPath, firstName, lastName);
} }
catch (InventoryArchiverException e)
{
m_log.ErrorFormat("[INVENTORY ARCHIVER]: {0}", e.Message);
}
}
/// <summary> /// <summary>
/// Save inventory to a file archive /// Save inventory to a file archive
/// </summary> /// </summary>
/// <param name="cmdparams"></param> /// <param name="cmdparams"></param>
protected void HandleSaveInvConsoleCommand(string module, string[] cmdparams) protected void HandleSaveInvConsoleCommand(string module, string[] cmdparams)
{
Guid id = Guid.NewGuid();
try
{ {
if (cmdparams.Length < 6) if (cmdparams.Length < 6)
{ {
@ -350,8 +388,12 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
"[INVENTORY ARCHIVER]: Saving archive {0} using inventory path {1} for {2} {3}", "[INVENTORY ARCHIVER]: Saving archive {0} using inventory path {1} for {2} {3}",
savePath, invPath, firstName, lastName); savePath, invPath, firstName, lastName);
Guid id = Guid.NewGuid(); ArchiveInventory(id, firstName, lastName, invPath, pass, savePath, new Dictionary<string, object>());
ArchiveInventory(id, firstName, lastName, invPath, pass, savePath); }
catch (InventoryArchiverException e)
{
m_log.ErrorFormat("[INVENTORY ARCHIVER]: {0}", e.Message);
}
lock (m_pendingConsoleSaves) lock (m_pendingConsoleSaves)
m_pendingConsoleSaves.Add(id); m_pendingConsoleSaves.Add(id);
@ -390,7 +432,9 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
/// <returns></returns> /// <returns></returns>
protected UserAccount GetUserInfo(string firstName, string lastName, string pass) protected UserAccount GetUserInfo(string firstName, string lastName, string pass)
{ {
UserAccount account = m_aScene.UserAccountService.GetUserAccount(m_aScene.RegionInfo.ScopeID, firstName, lastName); UserAccount account
= m_aScene.UserAccountService.GetUserAccount(m_aScene.RegionInfo.ScopeID, firstName, lastName);
if (null == account) if (null == account)
{ {
m_log.ErrorFormat( m_log.ErrorFormat(

View File

@ -55,14 +55,6 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
{ {
protected ManualResetEvent mre = new ManualResetEvent(false); protected ManualResetEvent mre = new ManualResetEvent(false);
private void InventoryReceived(UUID userId)
{
lock (this)
{
Monitor.PulseAll(this);
}
}
private void SaveCompleted( private void SaveCompleted(
Guid id, bool succeeded, UserAccount userInfo, string invPath, Stream saveStream, Guid id, bool succeeded, UserAccount userInfo, string invPath, Stream saveStream,
Exception reportedException) Exception reportedException)
@ -71,16 +63,14 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
} }
/// <summary> /// <summary>
/// Test saving a V0.1 OpenSim Inventory Archive (subject to change since there is no fixed format yet). /// Test saving an inventory path to a V0.1 OpenSim Inventory Archive
/// (subject to change since there is no fixed format yet).
/// </summary> /// </summary>
// Commenting for now! The mock inventory service needs more beef, at least for [Test]
// GetFolderForType public void TestSavePathToIarV0_1()
// REFACTORING PROBLEM. This needs to be rewritten.
//[Test]
public void TestSaveIarV0_1()
{ {
TestHelper.InMethod(); TestHelper.InMethod();
log4net.Config.XmlConfigurator.Configure(); // log4net.Config.XmlConfigurator.Configure();
InventoryArchiverModule archiverModule = new InventoryArchiverModule(true); InventoryArchiverModule archiverModule = new InventoryArchiverModule(true);
@ -125,7 +115,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
item1.AssetID = asset1.FullID; item1.AssetID = asset1.FullID;
item1.ID = item1Id; item1.ID = item1Id;
InventoryFolderBase objsFolder InventoryFolderBase objsFolder
= InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, userId, "Objects"); = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, userId, "Objects")[0];
item1.Folder = objsFolder.ID; item1.Folder = objsFolder.ID;
scene.AddInventoryItem(userId, item1); scene.AddInventoryItem(userId, item1);
@ -182,6 +172,123 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
} }
} }
// Assert.That(gotControlFile, Is.True, "No control file in archive");
Assert.That(gotObject1File, Is.True, "No item1 file in archive");
// Assert.That(gotObject2File, Is.True, "No object2 file in archive");
// TODO: Test presence of more files and contents of files.
}
/// <summary>
/// Test saving a single inventory item to a V0.1 OpenSim Inventory Archive
/// (subject to change since there is no fixed format yet).
/// </summary>
[Test]
public void TestSaveItemToIarV0_1()
{
TestHelper.InMethod();
// log4net.Config.XmlConfigurator.Configure();
InventoryArchiverModule archiverModule = new InventoryArchiverModule(true);
Scene scene = SceneSetupHelpers.SetupScene("Inventory");
SceneSetupHelpers.SetupSceneModules(scene, archiverModule);
// Create user
string userFirstName = "Jock";
string userLastName = "Stirrup";
string userPassword = "troll";
UUID userId = UUID.Parse("00000000-0000-0000-0000-000000000020");
UserProfileTestUtils.CreateUserWithInventory(scene, userFirstName, userLastName, userId, userPassword);
// Create asset
SceneObjectGroup object1;
SceneObjectPart part1;
{
string partName = "My Little Dog Object";
UUID ownerId = UUID.Parse("00000000-0000-0000-0000-000000000040");
PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere();
Vector3 groupPosition = new Vector3(10, 20, 30);
Quaternion rotationOffset = new Quaternion(20, 30, 40, 50);
Vector3 offsetPosition = new Vector3(5, 10, 15);
part1
= new SceneObjectPart(
ownerId, shape, groupPosition, rotationOffset, offsetPosition);
part1.Name = partName;
object1 = new SceneObjectGroup(part1);
scene.AddNewSceneObject(object1, false);
}
UUID asset1Id = UUID.Parse("00000000-0000-0000-0000-000000000060");
AssetBase asset1 = AssetHelpers.CreateAsset(asset1Id, object1);
scene.AssetService.Store(asset1);
// Create item
UUID item1Id = UUID.Parse("00000000-0000-0000-0000-000000000080");
string item1Name = "My Little Dog";
InventoryItemBase item1 = new InventoryItemBase();
item1.Name = item1Name;
item1.AssetID = asset1.FullID;
item1.ID = item1Id;
InventoryFolderBase objsFolder
= InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, userId, "Objects")[0];
item1.Folder = objsFolder.ID;
scene.AddInventoryItem(userId, item1);
MemoryStream archiveWriteStream = new MemoryStream();
archiverModule.OnInventoryArchiveSaved += SaveCompleted;
mre.Reset();
archiverModule.ArchiveInventory(
Guid.NewGuid(), userFirstName, userLastName, "Objects/" + item1Name, userPassword, archiveWriteStream);
mre.WaitOne(60000, false);
byte[] archive = archiveWriteStream.ToArray();
MemoryStream archiveReadStream = new MemoryStream(archive);
TarArchiveReader tar = new TarArchiveReader(archiveReadStream);
//bool gotControlFile = false;
bool gotObject1File = false;
//bool gotObject2File = false;
string expectedObject1FileName = InventoryArchiveWriteRequest.CreateArchiveItemName(item1);
string expectedObject1FilePath = string.Format(
"{0}{1}",
ArchiveConstants.INVENTORY_PATH,
expectedObject1FileName);
string filePath;
TarArchiveReader.TarEntryType tarEntryType;
// Console.WriteLine("Reading archive");
while (tar.ReadEntry(out filePath, out tarEntryType) != null)
{
Console.WriteLine("Got {0}", filePath);
// if (ArchiveConstants.CONTROL_FILE_PATH == filePath)
// {
// gotControlFile = true;
// }
if (filePath.StartsWith(ArchiveConstants.INVENTORY_PATH) && filePath.EndsWith(".xml"))
{
// string fileName = filePath.Remove(0, "Objects/".Length);
//
// if (fileName.StartsWith(part1.Name))
// {
Assert.That(expectedObject1FilePath, Is.EqualTo(filePath));
gotObject1File = true;
// }
// else if (fileName.StartsWith(part2.Name))
// {
// Assert.That(fileName, Is.EqualTo(expectedObject2FileName));
// gotObject2File = true;
// }
}
}
// Assert.That(gotControlFile, Is.True, "No control file in archive"); // Assert.That(gotControlFile, Is.True, "No control file in archive");
Assert.That(gotObject1File, Is.True, "No item1 file in archive"); Assert.That(gotObject1File, Is.True, "No item1 file in archive");
// Assert.That(gotObject2File, Is.True, "No object2 file in archive"); // Assert.That(gotObject2File, Is.True, "No object2 file in archive");
@ -195,189 +302,175 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
/// </summary> /// </summary>
/// ///
/// This test also does some deeper probing of loading into nested inventory structures /// This test also does some deeper probing of loading into nested inventory structures
/// REFACTORING PROBLEM. This needs to be rewritten. [Test]
// [Test] public void TestLoadIarV0_1ExistingUsers()
// public void TestLoadIarV0_1ExistingUsers() {
// { TestHelper.InMethod();
// TestHelper.InMethod(); //log4net.Config.XmlConfigurator.Configure();
// //log4net.Config.XmlConfigurator.Configure(); string userFirstName = "Mr";
string userLastName = "Tiddles";
UUID userUuid = UUID.Parse("00000000-0000-0000-0000-000000000555");
string userItemCreatorFirstName = "Lord";
string userItemCreatorLastName = "Lucan";
UUID userItemCreatorUuid = UUID.Parse("00000000-0000-0000-0000-000000000666");
// string userFirstName = "Mr"; string item1Name = "b.lsl";
// string userLastName = "Tiddles"; string archiveItemName = InventoryArchiveWriteRequest.CreateArchiveItemName(item1Name, UUID.Random());
// UUID userUuid = UUID.Parse("00000000-0000-0000-0000-000000000555");
// string userItemCreatorFirstName = "Lord";
// string userItemCreatorLastName = "Lucan";
// UUID userItemCreatorUuid = UUID.Parse("00000000-0000-0000-0000-000000000666");
// string item1Name = "b.lsl"; MemoryStream archiveWriteStream = new MemoryStream();
// string archiveItemName = InventoryArchiveWriteRequest.CreateArchiveItemName(item1Name, UUID.Random()); TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream);
// MemoryStream archiveWriteStream = new MemoryStream(); InventoryItemBase item1 = new InventoryItemBase();
// TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream); item1.Name = item1Name;
item1.AssetID = UUID.Random();
item1.GroupID = UUID.Random();
item1.CreatorId = OspResolver.MakeOspa(userItemCreatorFirstName, userItemCreatorLastName);
//item1.CreatorId = userUuid.ToString();
//item1.CreatorId = "00000000-0000-0000-0000-000000000444";
item1.Owner = UUID.Zero;
// InventoryItemBase item1 = new InventoryItemBase(); string item1FileName
// item1.Name = item1Name; = string.Format("{0}{1}", ArchiveConstants.INVENTORY_PATH, archiveItemName);
// item1.AssetID = UUID.Random(); tar.WriteFile(item1FileName, UserInventoryItemSerializer.Serialize(item1));
// item1.GroupID = UUID.Random(); tar.Close();
// item1.CreatorId = OspResolver.MakeOspa(userItemCreatorFirstName, userItemCreatorLastName);
// //item1.CreatorId = userUuid.ToString();
// //item1.CreatorId = "00000000-0000-0000-0000-000000000444";
// item1.Owner = UUID.Zero;
// string item1FileName MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray());
// = string.Format("{0}{1}", ArchiveConstants.INVENTORY_PATH, archiveItemName); SerialiserModule serialiserModule = new SerialiserModule();
// tar.WriteFile(item1FileName, UserInventoryItemSerializer.Serialize(item1)); InventoryArchiverModule archiverModule = new InventoryArchiverModule(true);
// tar.Close();
// MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray()); // Annoyingly, we have to set up a scene even though inventory loading has nothing to do with a scene
// SerialiserModule serialiserModule = new SerialiserModule(); Scene scene = SceneSetupHelpers.SetupScene("inventory");
// InventoryArchiverModule archiverModule = new InventoryArchiverModule(true);
// // Annoyingly, we have to set up a scene even though inventory loading has nothing to do with a scene SceneSetupHelpers.SetupSceneModules(scene, serialiserModule, archiverModule);
// Scene scene = SceneSetupHelpers.SetupScene("inventory");
// IUserAdminService userAdminService = scene.CommsManager.UserAdminService;
// SceneSetupHelpers.SetupSceneModules(scene, serialiserModule, archiverModule); UserProfileTestUtils.CreateUserWithInventory(
// userAdminService.AddUser( scene, userFirstName, userLastName, userUuid, "meowfood");
// userFirstName, userLastName, "meowfood", String.Empty, 1000, 1000, userUuid); UserProfileTestUtils.CreateUserWithInventory(
// userAdminService.AddUser( scene, userItemCreatorFirstName, userItemCreatorLastName, userItemCreatorUuid, "hampshire");
// userItemCreatorFirstName, userItemCreatorLastName, "hampshire",
// String.Empty, 1000, 1000, userItemCreatorUuid);
// archiverModule.DearchiveInventory(userFirstName, userLastName, "/", "meowfood", archiveReadStream); archiverModule.DearchiveInventory(userFirstName, userLastName, "/", "meowfood", archiveReadStream);
// CachedUserInfo userInfo InventoryItemBase foundItem1
// = scene.CommsManager.UserProfileCacheService.GetUserDetails(userFirstName, userLastName); = InventoryArchiveUtils.FindItemByPath(scene.InventoryService, userUuid, item1Name);
// InventoryItemBase foundItem1 Assert.That(foundItem1, Is.Not.Null, "Didn't find loaded item 1");
// = InventoryArchiveUtils.FindItemByPath(scene.InventoryService, userInfo.UserProfile.ID, item1Name);
// Assert.That(foundItem1, Is.Not.Null, "Didn't find loaded item 1"); // We have to disable this check since loaded items that did find users via OSPA resolution are now only storing the
// UUID, not the OSPA itself.
//// We have to disable this check since loaded items that did find users via OSPA resolution are now only storing the
//// UUID, not the OSPA itself.
//// Assert.That(
//// foundItem1.CreatorId, Is.EqualTo(item1.CreatorId),
//// "Loaded item non-uuid creator doesn't match original");
// Assert.That( // Assert.That(
// foundItem1.CreatorId, Is.EqualTo(userItemCreatorUuid.ToString()), // foundItem1.CreatorId, Is.EqualTo(item1.CreatorId),
// "Loaded item non-uuid creator doesn't match original"); // "Loaded item non-uuid creator doesn't match original");
Assert.That(
foundItem1.CreatorId, Is.EqualTo(userItemCreatorUuid.ToString()),
"Loaded item non-uuid creator doesn't match original");
Assert.That(
foundItem1.CreatorIdAsUuid, Is.EqualTo(userItemCreatorUuid),
"Loaded item uuid creator doesn't match original");
Assert.That(foundItem1.Owner, Is.EqualTo(userUuid),
"Loaded item owner doesn't match inventory reciever");
// Now try loading to a root child folder
UserInventoryTestUtils.CreateInventoryFolder(scene.InventoryService, userUuid, "xA");
archiveReadStream = new MemoryStream(archiveReadStream.ToArray());
archiverModule.DearchiveInventory(userFirstName, userLastName, "xA", "meowfood", archiveReadStream);
InventoryItemBase foundItem2
= InventoryArchiveUtils.FindItemByPath(scene.InventoryService, userUuid, "xA/" + item1Name);
Assert.That(foundItem2, Is.Not.Null, "Didn't find loaded item 2");
// Now try loading to a more deeply nested folder
UserInventoryTestUtils.CreateInventoryFolder(scene.InventoryService, userUuid, "xB/xC");
archiveReadStream = new MemoryStream(archiveReadStream.ToArray());
archiverModule.DearchiveInventory(userFirstName, userLastName, "xB/xC", "meowfood", archiveReadStream);
InventoryItemBase foundItem3
= InventoryArchiveUtils.FindItemByPath(scene.InventoryService, userUuid, "xB/xC/" + item1Name);
Assert.That(foundItem3, Is.Not.Null, "Didn't find loaded item 3");
}
[Test]
public void TestIarV0_1WithEscapedChars()
{
TestHelper.InMethod();
// log4net.Config.XmlConfigurator.Configure();
string itemName = "You & you are a mean/man/";
string humanEscapedItemName = @"You & you are a mean\/man\/";
string userPassword = "meowfood";
InventoryArchiverModule archiverModule = new InventoryArchiverModule(true);
Scene scene = SceneSetupHelpers.SetupScene("Inventory");
SceneSetupHelpers.SetupSceneModules(scene, archiverModule);
// Create user
string userFirstName = "Jock";
string userLastName = "Stirrup";
UUID userId = UUID.Parse("00000000-0000-0000-0000-000000000020");
UserProfileTestUtils.CreateUserWithInventory(scene, userFirstName, userLastName, userId, "meowfood");
// Create asset
SceneObjectGroup object1;
SceneObjectPart part1;
{
string partName = "part name";
UUID ownerId = UUID.Parse("00000000-0000-0000-0000-000000000040");
PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere();
Vector3 groupPosition = new Vector3(10, 20, 30);
Quaternion rotationOffset = new Quaternion(20, 30, 40, 50);
Vector3 offsetPosition = new Vector3(5, 10, 15);
part1
= new SceneObjectPart(
ownerId, shape, groupPosition, rotationOffset, offsetPosition);
part1.Name = partName;
object1 = new SceneObjectGroup(part1);
scene.AddNewSceneObject(object1, false);
}
UUID asset1Id = UUID.Parse("00000000-0000-0000-0000-000000000060");
AssetBase asset1 = AssetHelpers.CreateAsset(asset1Id, object1);
scene.AssetService.Store(asset1);
// Create item
UUID item1Id = UUID.Parse("00000000-0000-0000-0000-000000000080");
InventoryItemBase item1 = new InventoryItemBase();
item1.Name = itemName;
item1.AssetID = asset1.FullID;
item1.ID = item1Id;
InventoryFolderBase objsFolder
= InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, userId, "Objects")[0];
item1.Folder = objsFolder.ID;
scene.AddInventoryItem(userId, item1);
MemoryStream archiveWriteStream = new MemoryStream();
archiverModule.OnInventoryArchiveSaved += SaveCompleted;
mre.Reset();
archiverModule.ArchiveInventory(
Guid.NewGuid(), userFirstName, userLastName, "Objects", userPassword, archiveWriteStream);
mre.WaitOne(60000, false);
// LOAD ITEM
MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray());
archiverModule.DearchiveInventory(userFirstName, userLastName, "Scripts", userPassword, archiveReadStream);
InventoryItemBase foundItem1
= InventoryArchiveUtils.FindItemByPath(
scene.InventoryService, userId, "Scripts/Objects/" + humanEscapedItemName);
Assert.That(foundItem1, Is.Not.Null, "Didn't find loaded item 1");
// Assert.That( // Assert.That(
// foundItem1.CreatorIdAsUuid, Is.EqualTo(userItemCreatorUuid), // foundItem1.CreatorId, Is.EqualTo(userUuid),
// "Loaded item uuid creator doesn't match original"); // "Loaded item non-uuid creator doesn't match that of the loading user");
// Assert.That(foundItem1.Owner, Is.EqualTo(userUuid), Assert.That(
// "Loaded item owner doesn't match inventory reciever"); foundItem1.Name, Is.EqualTo(itemName),
"Loaded item name doesn't match saved name");
// // Now try loading to a root child folder }
// UserInventoryTestUtils.CreateInventoryFolder(scene.InventoryService, userInfo.UserProfile.ID, "xA");
// archiveReadStream = new MemoryStream(archiveReadStream.ToArray());
// archiverModule.DearchiveInventory(userFirstName, userLastName, "xA", "meowfood", archiveReadStream);
// InventoryItemBase foundItem2
// = InventoryArchiveUtils.FindItemByPath(scene.InventoryService, userInfo.UserProfile.ID, "xA/" + item1Name);
// Assert.That(foundItem2, Is.Not.Null, "Didn't find loaded item 2");
// // Now try loading to a more deeply nested folder
// UserInventoryTestUtils.CreateInventoryFolder(scene.InventoryService, userInfo.UserProfile.ID, "xB/xC");
// archiveReadStream = new MemoryStream(archiveReadStream.ToArray());
// archiverModule.DearchiveInventory(userFirstName, userLastName, "xB/xC", "meowfood", archiveReadStream);
// InventoryItemBase foundItem3
// = InventoryArchiveUtils.FindItemByPath(scene.InventoryService, userInfo.UserProfile.ID, "xB/xC/" + item1Name);
// Assert.That(foundItem3, Is.Not.Null, "Didn't find loaded item 3");
//}
// REFACTORING PROBLEM. Needs rewrite.
// [Test]
// public void TestIarV0_1WithEscapedChars()
// {
// TestHelper.InMethod();
//// log4net.Config.XmlConfigurator.Configure();
// string itemName = "You & you are a mean/man/";
// string humanEscapedItemName = @"You & you are a mean\/man\/";
// string userPassword = "meowfood";
// InventoryArchiverModule archiverModule = new InventoryArchiverModule(true);
// Scene scene = SceneSetupHelpers.SetupScene("Inventory");
// SceneSetupHelpers.SetupSceneModules(scene, archiverModule);
// CommunicationsManager cm = scene.CommsManager;
// // Create user
// string userFirstName = "Jock";
// string userLastName = "Stirrup";
// UUID userId = UUID.Parse("00000000-0000-0000-0000-000000000020");
// lock (this)
// {
// UserProfileTestUtils.CreateUserWithInventory(
// cm, userFirstName, userLastName, userPassword, userId, InventoryReceived);
// Monitor.Wait(this, 60000);
// }
// // Create asset
// SceneObjectGroup object1;
// SceneObjectPart part1;
// {
// string partName = "part name";
// UUID ownerId = UUID.Parse("00000000-0000-0000-0000-000000000040");
// PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere();
// Vector3 groupPosition = new Vector3(10, 20, 30);
// Quaternion rotationOffset = new Quaternion(20, 30, 40, 50);
// Vector3 offsetPosition = new Vector3(5, 10, 15);
// part1
// = new SceneObjectPart(
// ownerId, shape, groupPosition, rotationOffset, offsetPosition);
// part1.Name = partName;
// object1 = new SceneObjectGroup(part1);
// scene.AddNewSceneObject(object1, false);
// }
// UUID asset1Id = UUID.Parse("00000000-0000-0000-0000-000000000060");
// AssetBase asset1 = AssetHelpers.CreateAsset(asset1Id, object1);
// scene.AssetService.Store(asset1);
// // Create item
// UUID item1Id = UUID.Parse("00000000-0000-0000-0000-000000000080");
// InventoryItemBase item1 = new InventoryItemBase();
// item1.Name = itemName;
// item1.AssetID = asset1.FullID;
// item1.ID = item1Id;
// InventoryFolderBase objsFolder
// = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, userId, "Objects");
// item1.Folder = objsFolder.ID;
// scene.AddInventoryItem(userId, item1);
// MemoryStream archiveWriteStream = new MemoryStream();
// archiverModule.OnInventoryArchiveSaved += SaveCompleted;
// mre.Reset();
// archiverModule.ArchiveInventory(
// Guid.NewGuid(), userFirstName, userLastName, "Objects", userPassword, archiveWriteStream);
// mre.WaitOne(60000, false);
// // LOAD ITEM
// MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray());
// archiverModule.DearchiveInventory(userFirstName, userLastName, "Scripts", userPassword, archiveReadStream);
// InventoryItemBase foundItem1
// = InventoryArchiveUtils.FindItemByPath(
// scene.InventoryService, userId, "Scripts/Objects/" + humanEscapedItemName);
// Assert.That(foundItem1, Is.Not.Null, "Didn't find loaded item 1");
//// Assert.That(
//// foundItem1.CreatorId, Is.EqualTo(userUuid),
//// "Loaded item non-uuid creator doesn't match that of the loading user");
// Assert.That(
// foundItem1.Name, Is.EqualTo(itemName),
// "Loaded item name doesn't match saved name");
// }
/// <summary> /// <summary>
/// Test loading a V0.1 OpenSim Inventory Archive (subject to change since there is no fixed format yet) where /// Test loading a V0.1 OpenSim Inventory Archive (subject to change since there is no fixed format yet) where
@ -386,76 +479,69 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
/// ///
/// This may possibly one day get overtaken by the as yet incomplete temporary profiles feature /// This may possibly one day get overtaken by the as yet incomplete temporary profiles feature
/// (as tested in the a later commented out test) /// (as tested in the a later commented out test)
/// REFACTORING PROBLEM. Needs rewrite. /// This test is currently disabled
// [Test] [Test]
// public void TestLoadIarV0_1AbsentUsers() public void TestLoadIarV0_1AbsentUsers()
// { {
// TestHelper.InMethod(); TestHelper.InMethod();
//log4net.Config.XmlConfigurator.Configure();
// //log4net.Config.XmlConfigurator.Configure(); string userFirstName = "Charlie";
string userLastName = "Chan";
UUID userUuid = UUID.Parse("00000000-0000-0000-0000-000000000999");
string userItemCreatorFirstName = "Bat";
string userItemCreatorLastName = "Man";
//UUID userItemCreatorUuid = UUID.Parse("00000000-0000-0000-0000-000000008888");
// string userFirstName = "Charlie"; string itemName = "b.lsl";
// string userLastName = "Chan"; string archiveItemName = InventoryArchiveWriteRequest.CreateArchiveItemName(itemName, UUID.Random());
// UUID userUuid = UUID.Parse("00000000-0000-0000-0000-000000000999");
// string userItemCreatorFirstName = "Bat";
// string userItemCreatorLastName = "Man";
// //UUID userItemCreatorUuid = UUID.Parse("00000000-0000-0000-0000-000000008888");
// string itemName = "b.lsl"; MemoryStream archiveWriteStream = new MemoryStream();
// string archiveItemName = InventoryArchiveWriteRequest.CreateArchiveItemName(itemName, UUID.Random()); TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream);
// MemoryStream archiveWriteStream = new MemoryStream(); InventoryItemBase item1 = new InventoryItemBase();
// TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream); item1.Name = itemName;
item1.AssetID = UUID.Random();
item1.GroupID = UUID.Random();
item1.CreatorId = OspResolver.MakeOspa(userItemCreatorFirstName, userItemCreatorLastName);
//item1.CreatorId = userUuid.ToString();
//item1.CreatorId = "00000000-0000-0000-0000-000000000444";
item1.Owner = UUID.Zero;
// InventoryItemBase item1 = new InventoryItemBase(); string item1FileName
// item1.Name = itemName; = string.Format("{0}{1}", ArchiveConstants.INVENTORY_PATH, archiveItemName);
// item1.AssetID = UUID.Random(); tar.WriteFile(item1FileName, UserInventoryItemSerializer.Serialize(item1));
// item1.GroupID = UUID.Random(); tar.Close();
// item1.CreatorId = OspResolver.MakeOspa(userItemCreatorFirstName, userItemCreatorLastName);
// //item1.CreatorId = userUuid.ToString();
// //item1.CreatorId = "00000000-0000-0000-0000-000000000444";
// item1.Owner = UUID.Zero;
// string item1FileName MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray());
// = string.Format("{0}{1}", ArchiveConstants.INVENTORY_PATH, archiveItemName); SerialiserModule serialiserModule = new SerialiserModule();
// tar.WriteFile(item1FileName, UserInventoryItemSerializer.Serialize(item1)); InventoryArchiverModule archiverModule = new InventoryArchiverModule(true);
// tar.Close();
// MemoryStream archiveReadStream = new MemoryStream(archiveWriteStream.ToArray()); // Annoyingly, we have to set up a scene even though inventory loading has nothing to do with a scene
// SerialiserModule serialiserModule = new SerialiserModule(); Scene scene = SceneSetupHelpers.SetupScene("inventory");
// InventoryArchiverModule archiverModule = new InventoryArchiverModule(true);
// // Annoyingly, we have to set up a scene even though inventory loading has nothing to do with a scene SceneSetupHelpers.SetupSceneModules(scene, serialiserModule, archiverModule);
// Scene scene = SceneSetupHelpers.SetupScene("inventory"); UserProfileTestUtils.CreateUserWithInventory(scene, userFirstName, userLastName, userUuid, "meowfood");
// IUserAdminService userAdminService = scene.CommsManager.UserAdminService;
// SceneSetupHelpers.SetupSceneModules(scene, serialiserModule, archiverModule); archiverModule.DearchiveInventory(userFirstName, userLastName, "/", "meowfood", archiveReadStream);
// userAdminService.AddUser(
// userFirstName, userLastName, "meowfood", String.Empty, 1000, 1000, userUuid);
// archiverModule.DearchiveInventory(userFirstName, userLastName, "/", "meowfood", archiveReadStream); InventoryItemBase foundItem1
= InventoryArchiveUtils.FindItemByPath(scene.InventoryService, userUuid, itemName);
// CachedUserInfo userInfo Assert.That(foundItem1, Is.Not.Null, "Didn't find loaded item 1");
// = scene.CommsManager.UserProfileCacheService.GetUserDetails(userFirstName, userLastName);
// InventoryItemBase foundItem1
// = InventoryArchiveUtils.FindItemByPath(scene.InventoryService, userInfo.UserProfile.ID, itemName);
// Assert.That(foundItem1, Is.Not.Null, "Didn't find loaded item 1");
//// Assert.That(
//// foundItem1.CreatorId, Is.EqualTo(userUuid),
//// "Loaded item non-uuid creator doesn't match that of the loading user");
// Assert.That( // Assert.That(
// foundItem1.CreatorIdAsUuid, Is.EqualTo(userUuid), // foundItem1.CreatorId, Is.EqualTo(userUuid),
// "Loaded item uuid creator doesn't match that of the loading user"); // "Loaded item non-uuid creator doesn't match that of the loading user");
// } Assert.That(
foundItem1.CreatorIdAsUuid, Is.EqualTo(userUuid),
"Loaded item uuid creator doesn't match that of the loading user");
}
/// <summary> /// <summary>
/// Test loading a V0.1 OpenSim Inventory Archive (subject to change since there is no fixed format yet) where /// Test loading a V0.1 OpenSim Inventory Archive (subject to change since there is no fixed format yet) where
/// no account exists with the creator name /// no account exists with the creator name
/// </summary> /// </summary>
/// Disabled since temporary profiles have not yet been implemented. /// Disabled since temporary profiles have not yet been implemented.
/// REFACTORING PROBLEM. Needs rewrite.
/// ///
//[Test] //[Test]
//public void TestLoadIarV0_1TempProfiles() //public void TestLoadIarV0_1TempProfiles()
@ -534,7 +620,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
/// Test replication of an archive path to the user's inventory. /// Test replication of an archive path to the user's inventory.
/// </summary> /// </summary>
[Test] [Test]
public void TestReplicateArchivePathToUserInventory() public void TestNewIarPath()
{ {
TestHelper.InMethod(); TestHelper.InMethod();
// log4net.Config.XmlConfigurator.Configure(); // log4net.Config.XmlConfigurator.Configure();
@ -545,29 +631,106 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver.Tests
Dictionary <string, InventoryFolderBase> foldersCreated = new Dictionary<string, InventoryFolderBase>(); Dictionary <string, InventoryFolderBase> foldersCreated = new Dictionary<string, InventoryFolderBase>();
List<InventoryNodeBase> nodesLoaded = new List<InventoryNodeBase>(); List<InventoryNodeBase> nodesLoaded = new List<InventoryNodeBase>();
string folder1Name = "a"; string folder1Name = "1";
string folder2Name = "b"; string folder2aName = "2a";
string itemName = "c.lsl"; string folder2bName = "2b";
string folder1ArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder1Name, UUID.Random()); string folder1ArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder1Name, UUID.Random());
string folder2ArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder2Name, UUID.Random()); string folder2aArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder2aName, UUID.Random());
string itemArchiveName = InventoryArchiveWriteRequest.CreateArchiveItemName(itemName, UUID.Random()); string folder2bArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder2bName, UUID.Random());
string itemArchivePath string iarPath1 = string.Join("", new string[] { folder1ArchiveName, folder2aArchiveName });
= string.Format( string iarPath2 = string.Join("", new string[] { folder1ArchiveName, folder2bArchiveName });
"{0}{1}{2}{3}",
ArchiveConstants.INVENTORY_PATH, folder1ArchiveName, folder2ArchiveName, itemArchiveName); {
// Test replication of path1
new InventoryArchiveReadRequest(scene, ua1, null, (Stream)null)
.ReplicateArchivePathToUserInventory(
iarPath1, scene.InventoryService.GetRootFolder(ua1.PrincipalID),
foldersCreated, nodesLoaded);
List<InventoryFolderBase> folder1Candidates
= InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, ua1.PrincipalID, folder1Name);
Assert.That(folder1Candidates.Count, Is.EqualTo(1));
InventoryFolderBase folder1 = folder1Candidates[0];
List<InventoryFolderBase> folder2aCandidates
= InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, folder1, folder2aName);
Assert.That(folder2aCandidates.Count, Is.EqualTo(1));
}
{
// Test replication of path2
new InventoryArchiveReadRequest(scene, ua1, null, (Stream)null)
.ReplicateArchivePathToUserInventory(
iarPath2, scene.InventoryService.GetRootFolder(ua1.PrincipalID),
foldersCreated, nodesLoaded);
List<InventoryFolderBase> folder1Candidates
= InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, ua1.PrincipalID, folder1Name);
Assert.That(folder1Candidates.Count, Is.EqualTo(1));
InventoryFolderBase folder1 = folder1Candidates[0];
List<InventoryFolderBase> folder2aCandidates
= InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, folder1, folder2aName);
Assert.That(folder2aCandidates.Count, Is.EqualTo(1));
List<InventoryFolderBase> folder2bCandidates
= InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, folder1, folder2bName);
Assert.That(folder2bCandidates.Count, Is.EqualTo(1));
}
}
/// <summary>
/// Test replication of a partly existing archive path to the user's inventory. This should create
/// a duplicate path without the merge option.
/// </summary>
[Test]
public void TestPartExistingIarPath()
{
TestHelper.InMethod();
//log4net.Config.XmlConfigurator.Configure();
Scene scene = SceneSetupHelpers.SetupScene("inventory");
UserAccount ua1 = UserProfileTestUtils.CreateUserWithInventory(scene);
string folder1ExistingName = "a";
string folder2Name = "b";
InventoryFolderBase folder1
= UserInventoryTestUtils.CreateInventoryFolder(
scene.InventoryService, ua1.PrincipalID, folder1ExistingName);
string folder1ArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder1ExistingName, UUID.Random());
string folder2ArchiveName = InventoryArchiveWriteRequest.CreateArchiveFolderName(folder2Name, UUID.Random());
string itemArchivePath = string.Join("", new string[] { folder1ArchiveName, folder2ArchiveName });
new InventoryArchiveReadRequest(scene, ua1, null, (Stream)null) new InventoryArchiveReadRequest(scene, ua1, null, (Stream)null)
.ReplicateArchivePathToUserInventory( .ReplicateArchivePathToUserInventory(
itemArchivePath, false, scene.InventoryService.GetRootFolder(ua1.PrincipalID), itemArchivePath, scene.InventoryService.GetRootFolder(ua1.PrincipalID),
foldersCreated, nodesLoaded); new Dictionary<string, InventoryFolderBase>(), new List<InventoryNodeBase>());
InventoryFolderBase folder1 List<InventoryFolderBase> folder1PostCandidates
= InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, ua1.PrincipalID, "a"); = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, ua1.PrincipalID, folder1ExistingName);
Assert.That(folder1, Is.Not.Null, "Could not find folder a"); Assert.That(folder1PostCandidates.Count, Is.EqualTo(2));
InventoryFolderBase folder2 = InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, folder1, "b");
Assert.That(folder2, Is.Not.Null, "Could not find folder b"); // FIXME: Temporarily, we're going to do something messy to make sure we pick up the created folder.
InventoryFolderBase folder1Post = null;
foreach (InventoryFolderBase folder in folder1PostCandidates)
{
if (folder.ID != folder1.ID)
{
folder1Post = folder;
break;
}
}
// Assert.That(folder1Post.ID, Is.EqualTo(folder1.ID));
List<InventoryFolderBase> folder2PostCandidates
= InventoryArchiveUtils.FindFolderByPath(scene.InventoryService, folder1Post, "b");
Assert.That(folder2PostCandidates.Count, Is.EqualTo(1));
} }
} }
} }

View File

@ -145,30 +145,31 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Transfer
{ {
ScenePresence presence = scene.GetScenePresence(agentId); ScenePresence presence = scene.GetScenePresence(agentId);
if (presence != null) if (presence != null)
{
if (!presence.IsChildAgent)
return scene; return scene;
} }
} }
}
return null; return null;
} }
private void OnInstantMessage(IClientAPI client, GridInstantMessage im) private void OnInstantMessage(IClientAPI client, GridInstantMessage im)
{ {
m_log.InfoFormat("OnInstantMessage {0}", im.dialog); m_log.InfoFormat("[INVENTORY TRANSFER]: OnInstantMessage {0}", im.dialog);
Scene scene = FindClientScene(client.AgentId); Scene scene = FindClientScene(client.AgentId);
if (scene == null) // Something seriously wrong here. if (scene == null) // Something seriously wrong here.
return; return;
if (im.dialog == (byte) InstantMessageDialog.InventoryOffered) if (im.dialog == (byte) InstantMessageDialog.InventoryOffered)
{ {
//m_log.DebugFormat("Asset type {0}", ((AssetType)im.binaryBucket[0])); //m_log.DebugFormat("Asset type {0}", ((AssetType)im.binaryBucket[0]));
ScenePresence user = scene.GetScenePresence(new UUID(im.toAgentID)); if (im.binaryBucket.Length < 17) // Invalid
return;
UUID receipientID = new UUID(im.toAgentID);
ScenePresence user = scene.GetScenePresence(receipientID);
UUID copyID; UUID copyID;
// First byte is the asset type // First byte is the asset type
@ -183,7 +184,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Transfer
folderID, new UUID(im.toAgentID)); folderID, new UUID(im.toAgentID));
InventoryFolderBase folderCopy InventoryFolderBase folderCopy
= scene.GiveInventoryFolder(new UUID(im.toAgentID), client.AgentId, folderID, UUID.Zero); = scene.GiveInventoryFolder(receipientID, client.AgentId, folderID, UUID.Zero);
if (folderCopy == null) if (folderCopy == null)
{ {
@ -199,20 +200,22 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Transfer
im.binaryBucket[0] = (byte)AssetType.Folder; im.binaryBucket[0] = (byte)AssetType.Folder;
Array.Copy(copyIDBytes, 0, im.binaryBucket, 1, copyIDBytes.Length); Array.Copy(copyIDBytes, 0, im.binaryBucket, 1, copyIDBytes.Length);
if (user != null && !user.IsChildAgent) if (user != null)
{ {
user.ControllingClient.SendBulkUpdateInventory(folderCopy); user.ControllingClient.SendBulkUpdateInventory(folderCopy);
} }
// HACK!!
im.imSessionID = folderID.Guid;
} }
else else
{ {
// First byte of the array is probably the item type // First byte of the array is probably the item type
// Next 16 bytes are the UUID // Next 16 bytes are the UUID
m_log.Info("OnInstantMessage - giving item");
UUID itemID = new UUID(im.binaryBucket, 1); UUID itemID = new UUID(im.binaryBucket, 1);
m_log.DebugFormat("[AGENT INVENTORY]: Inserting item {0} "+ m_log.DebugFormat("[AGENT INVENTORY]: (giving) Inserting item {0} "+
"into agent {1}'s inventory", "into agent {1}'s inventory",
itemID, new UUID(im.toAgentID)); itemID, new UUID(im.toAgentID));
@ -229,29 +232,32 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Transfer
copyID = itemCopy.ID; copyID = itemCopy.ID;
Array.Copy(copyID.GetBytes(), 0, im.binaryBucket, 1, 16); Array.Copy(copyID.GetBytes(), 0, im.binaryBucket, 1, 16);
if (user != null && !user.IsChildAgent) if (user != null)
{ {
user.ControllingClient.SendBulkUpdateInventory(itemCopy); user.ControllingClient.SendBulkUpdateInventory(itemCopy);
} }
// HACK!!
im.imSessionID = itemID.Guid;
} }
// Send the IM to the recipient. The item is already // Send the IM to the recipient. The item is already
// in their inventory, so it will not be lost if // in their inventory, so it will not be lost if
// they are offline. // they are offline.
// //
if (user != null && !user.IsChildAgent) if (user != null)
{ {
// And notify. Transaction ID is the item ID. We get that
// same ID back on the reply so we know what to act on
//
user.ControllingClient.SendInstantMessage(im); user.ControllingClient.SendInstantMessage(im);
return; return;
} }
else else
{ {
if (m_TransferModule != null) if (m_TransferModule != null)
m_TransferModule.SendInstantMessage(im, delegate(bool success) {}); m_TransferModule.SendInstantMessage(im, delegate(bool success)
{
if (!success)
client.SendAlertMessage("User not online. Inventory has been saved");
});
} }
} }
else if (im.dialog == (byte) InstantMessageDialog.InventoryAccepted) else if (im.dialog == (byte) InstantMessageDialog.InventoryAccepted)
@ -283,9 +289,9 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Transfer
InventoryFolderBase trashFolder = InventoryFolderBase trashFolder =
invService.GetFolderForType(client.AgentId, AssetType.TrashFolder); invService.GetFolderForType(client.AgentId, AssetType.TrashFolder);
UUID inventoryEntityID = new UUID(im.imSessionID); // The inventory item/folder, back from it's trip UUID inventoryID = new UUID(im.imSessionID); // The inventory item/folder, back from it's trip
InventoryItemBase item = new InventoryItemBase(inventoryEntityID, client.AgentId); InventoryItemBase item = new InventoryItemBase(inventoryID, client.AgentId);
item = invService.GetItem(item); item = invService.GetItem(item);
InventoryFolderBase folder = null; InventoryFolderBase folder = null;
@ -301,7 +307,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Transfer
} }
else else
{ {
folder = new InventoryFolderBase(inventoryEntityID, client.AgentId); folder = new InventoryFolderBase(inventoryID, client.AgentId);
folder = invService.GetFolder(folder); folder = invService.GetFolder(folder);
if (folder != null & trashFolder != null) if (folder != null & trashFolder != null)
@ -417,90 +423,18 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Transfer
{ {
// Check if this is ours to handle // Check if this is ours to handle
// //
m_log.Info("OnFridInstantMessage");
if (msg.dialog != (byte) InstantMessageDialog.InventoryOffered)
return;
if (msg.binaryBucket.Length < 17) // Invalid
return;
Scene scene = FindClientScene(new UUID(msg.toAgentID)); Scene scene = FindClientScene(new UUID(msg.toAgentID));
if (scene == null)
return;
// Find agent to deliver to // Find agent to deliver to
// //
ScenePresence user = scene.GetScenePresence(new UUID(msg.toAgentID)); ScenePresence user = scene.GetScenePresence(new UUID(msg.toAgentID));
if (user == null) // Shouldn't happen // Just forward to local handling
{ OnInstantMessage(user.ControllingClient, msg);
m_log.Debug("[INVENTORY TRANSFER] Can't find recipient");
return;
}
//CachedUserInfo userInfo =
// scene.CommsManager.UserProfileCacheService.
// GetUserDetails(user.ControllingClient.AgentId);
//if (userInfo == null)
//{
// m_log.Debug("[INVENTORY TRANSFER] Can't find user info of recipient");
// return;
//}
AssetType assetType = (AssetType)msg.binaryBucket[0];
IInventoryService invService = scene.InventoryService;
if (AssetType.Folder == assetType)
{
UUID folderID = new UUID(msg.binaryBucket, 1);
InventoryFolderBase folder = new InventoryFolderBase();
folder.ID = folderID;
folder.Owner = user.ControllingClient.AgentId;
// Fetch from service
//
folder = invService.GetFolder(folder);
if (folder == null)
{
m_log.Debug("[INVENTORY TRANSFER] Can't find folder to give");
return;
}
user.ControllingClient.SendBulkUpdateInventory(folder);
//// This unelegant, slow kludge is to reload the folders and
//// items. Since a folder give can transfer subfolders and
//// items, this is the easiest way to pull that stuff in
////
//userInfo.DropInventory();
//userInfo.FetchInventory();
// Deliver message
//
user.ControllingClient.SendInstantMessage(msg);
}
else
{
UUID itemID = new UUID(msg.binaryBucket, 1);
InventoryItemBase item = new InventoryItemBase(itemID, user.ControllingClient.AgentId);
// Fetch from service
//
item = invService.GetItem(item);
if (item == null)
{
m_log.Debug("[INVENTORY TRANSFER] Can't find item to give");
return;
}
// Update item to viewer (makes it appear in proper folder)
//
user.ControllingClient.SendBulkUpdateInventory(item);
// Deliver message
//
user.ControllingClient.SendInstantMessage(msg);
}
} }
} }
} }

View File

@ -180,6 +180,9 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
sp.ControllingClient.SendLocalTeleport(position, lookAt, teleportFlags); sp.ControllingClient.SendLocalTeleport(position, lookAt, teleportFlags);
sp.Teleport(position); sp.Teleport(position);
foreach (SceneObjectGroup grp in sp.Attachments)
sp.Scene.EventManager.TriggerOnScriptChangedEvent(grp.LocalId, (uint)Changed.TELEPORT);
} }
else // Another region possibly in another simulator else // Another region possibly in another simulator
{ {
@ -393,7 +396,12 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
agent.Position = position; agent.Position = position;
SetCallbackURL(agent, sp.Scene.RegionInfo); SetCallbackURL(agent, sp.Scene.RegionInfo);
UpdateAgent(reg, finalDestination, agent); if (!UpdateAgent(reg, finalDestination, agent))
{
// Region doesn't take it
Fail(sp, finalDestination);
return;
}
m_log.DebugFormat( m_log.DebugFormat(
"[ENTITY TRANSFER MODULE]: Sending new CAPS seed url {0} to client {1}", capsPath, sp.UUID); "[ENTITY TRANSFER MODULE]: Sending new CAPS seed url {0} to client {1}", capsPath, sp.UUID);
@ -410,23 +418,15 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
teleportFlags, capsPath); 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 // 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 // trigers a whole shebang of things there, including MakeRoot. So let's wait for confirmation
// that the client contacted the destination before we send the attachments and close things here. // that the client contacted the destination before we send the attachments and close things here.
if (!WaitForCallback(sp.UUID)) if (!WaitForCallback(sp.UUID))
{ {
// Client never contacted destination. Let's restore everything back Fail(sp, finalDestination);
sp.ControllingClient.SendTeleportFailed("Problems connecting to destination.");
ResetFromTransit(sp.UUID);
// Yikes! We should just have a ref to scene here.
//sp.Scene.InformClientOfNeighbours(sp);
EnableChildAgents(sp);
// Finally, kill the agent we just created at the destination.
m_aScene.SimulationService.CloseAgent(finalDestination, sp.UUID);
return; return;
} }
@ -436,7 +436,9 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
KillEntity(sp.Scene, sp.LocalId); KillEntity(sp.Scene, sp.LocalId);
// Now let's make it officially a child agent
sp.MakeChildAgent(); sp.MakeChildAgent();
// Finally, let's close this previously-known-as-root agent, when the jump is outside the view zone // Finally, let's close this previously-known-as-root agent, when the jump is outside the view zone
if (NeedsClosing(oldRegionX, newRegionX, oldRegionY, newRegionY, reg)) if (NeedsClosing(oldRegionX, newRegionX, oldRegionY, newRegionY, reg))
@ -464,6 +466,22 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
} }
} }
private void Fail(ScenePresence sp, GridRegion finalDestination)
{
// Client never contacted destination. Let's restore everything back
sp.ControllingClient.SendTeleportFailed("Problems connecting to destination.");
// Fail. Reset it back
sp.IsChildAgent = false;
ResetFromTransit(sp.UUID);
EnableChildAgents(sp);
// Finally, kill the agent we just created at the destination.
m_aScene.SimulationService.CloseAgent(finalDestination, sp.UUID);
}
protected virtual bool CreateAgent(ScenePresence sp, GridRegion reg, GridRegion finalDestination, AgentCircuitData agentCircuit, uint teleportFlags, out string reason) protected virtual bool CreateAgent(ScenePresence sp, GridRegion reg, GridRegion finalDestination, AgentCircuitData agentCircuit, uint teleportFlags, out string reason)
{ {
@ -538,6 +556,9 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
client.SendTeleportFailed("Your home region could not be found."); client.SendTeleportFailed("Your home region could not be found.");
return; return;
} }
m_log.DebugFormat("[ENTITY TRANSFER MODULE]: User's home region is {0} {1} ({2}-{3})",
regionInfo.RegionName, regionInfo.RegionID, regionInfo.RegionLocX / Constants.RegionSize, regionInfo.RegionLocY / Constants.RegionSize);
// a little eekie that this goes back to Scene and with a forced cast, will fix that at some point... // a little eekie that this goes back to Scene and with a forced cast, will fix that at some point...
((Scene)(client.Scene)).RequestTeleportLocation( ((Scene)(client.Scene)).RequestTeleportLocation(
client, regionInfo.RegionHandle, uinfo.HomePosition, uinfo.HomeLookAt, client, regionInfo.RegionHandle, uinfo.HomePosition, uinfo.HomeLookAt,
@ -799,7 +820,12 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
cAgent.CallbackURI = "http://" + m_scene.RegionInfo.ExternalHostName + ":" + m_scene.RegionInfo.HttpPort + cAgent.CallbackURI = "http://" + m_scene.RegionInfo.ExternalHostName + ":" + m_scene.RegionInfo.HttpPort +
"/agent/" + agent.UUID.ToString() + "/" + m_scene.RegionInfo.RegionID.ToString() + "/release/"; "/agent/" + agent.UUID.ToString() + "/" + m_scene.RegionInfo.RegionID.ToString() + "/release/";
m_scene.SimulationService.UpdateAgent(neighbourRegion, cAgent); if (!m_scene.SimulationService.UpdateAgent(neighbourRegion, cAgent))
{
// region doesn't take it
ResetFromTransit(agent.UUID);
return agent;
}
// Next, let's close the child agent connections that are too far away. // Next, let's close the child agent connections that are too far away.
agent.CloseChildAgents(neighbourx, neighboury); agent.CloseChildAgents(neighbourx, neighboury);
@ -854,8 +880,6 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
CrossAttachmentsIntoNewRegion(neighbourRegion, agent, true); CrossAttachmentsIntoNewRegion(neighbourRegion, agent, true);
// m_scene.SendKillObject(m_localId);
// the user may change their profile information in other region, // the user may change their profile information in other region,
// so the userinfo in UserProfileCache is not reliable any more, delete it // so the userinfo in UserProfileCache is not reliable any more, delete it
// REFACTORING PROBLEM. Well, not a problem, but this method is HORRIBLE! // REFACTORING PROBLEM. Well, not a problem, but this method is HORRIBLE!
@ -898,12 +922,40 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
/// </summary> /// </summary>
public void EnableChildAgent(ScenePresence sp, GridRegion region) public void EnableChildAgent(ScenePresence sp, GridRegion region)
{ {
m_log.DebugFormat("[ENTITY TRANSFER]: Enabling child agent in new neighour {0}", region.RegionName);
AgentCircuitData currentAgentCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
AgentCircuitData agent = sp.ControllingClient.RequestClientInfo(); AgentCircuitData agent = sp.ControllingClient.RequestClientInfo();
agent.BaseFolder = UUID.Zero; agent.BaseFolder = UUID.Zero;
agent.InventoryFolder = UUID.Zero; agent.InventoryFolder = UUID.Zero;
agent.startpos = new Vector3(128, 128, 70); agent.startpos = new Vector3(128, 128, 70);
agent.child = true; agent.child = true;
agent.Appearance = sp.Appearance; agent.Appearance = sp.Appearance;
agent.CapsPath = CapsUtil.GetRandomCapsObjectPath();
agent.ChildrenCapSeeds = new Dictionary<ulong, string>(sp.Scene.CapsModule.GetChildrenSeeds(sp.UUID));
m_log.DebugFormat("[XXX] Seeds 1 {0}", agent.ChildrenCapSeeds.Count);
if (!agent.ChildrenCapSeeds.ContainsKey(sp.Scene.RegionInfo.RegionHandle))
agent.ChildrenCapSeeds.Add(sp.Scene.RegionInfo.RegionHandle, sp.ControllingClient.RequestClientInfo().CapsPath);
m_log.DebugFormat("[XXX] Seeds 2 {0}", agent.ChildrenCapSeeds.Count);
sp.AddNeighbourRegion(region.RegionHandle, agent.CapsPath);
foreach (ulong h in agent.ChildrenCapSeeds.Keys)
m_log.DebugFormat("[XXX] --> {0}", h);
m_log.DebugFormat("[XXX] Adding {0}", region.RegionHandle);
agent.ChildrenCapSeeds.Add(region.RegionHandle, agent.CapsPath);
if (sp.Scene.CapsModule != null)
{
sp.Scene.CapsModule.SetChildrenSeed(sp.UUID, agent.ChildrenCapSeeds);
}
if (currentAgentCircuit != null)
{
agent.ServiceURLs = currentAgentCircuit.ServiceURLs;
agent.Viewer = currentAgentCircuit.Viewer;
}
InformClientOfNeighbourDelegate d = InformClientOfNeighbourAsync; InformClientOfNeighbourDelegate d = InformClientOfNeighbourAsync;
d.BeginInvoke(sp, agent, region, region.ExternalEndPoint, true, d.BeginInvoke(sp, agent, region, region.ExternalEndPoint, true,
@ -1111,7 +1163,7 @@ namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
string reason = String.Empty; string reason = String.Empty;
bool regionAccepted = m_scene.SimulationService.CreateAgent(reg, a, 0, out reason); // m_interregionCommsOut.SendCreateChildAgent(reg.RegionHandle, a, 0, out reason); bool regionAccepted = m_scene.SimulationService.CreateAgent(reg, a, (uint)TeleportFlags.Default, out reason);
if (regionAccepted && newAgent) if (regionAccepted && newAgent)
{ {

View File

@ -95,6 +95,10 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
try try
{ {
asset1.ID = url + "/" + asset.ID; asset1.ID = url + "/" + asset.ID;
UUID temp = UUID.Zero;
// TODO: if the creator is local, stick this grid's URL in front
//if (UUID.TryParse(asset.Metadata.CreatorID, out temp))
// asset1.Metadata.CreatorID = ??? + "/" + asset.Metadata.CreatorID;
} }
catch catch
{ {
@ -153,6 +157,8 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
Dictionary<UUID, AssetType> ids = new Dictionary<UUID, AssetType>(); Dictionary<UUID, AssetType> ids = new Dictionary<UUID, AssetType>();
HGUuidGatherer uuidGatherer = new HGUuidGatherer(this, m_scene.AssetService, userAssetURL); HGUuidGatherer uuidGatherer = new HGUuidGatherer(this, m_scene.AssetService, userAssetURL);
uuidGatherer.GatherAssetUuids(asset.FullID, (AssetType)asset.Type, ids); uuidGatherer.GatherAssetUuids(asset.FullID, (AssetType)asset.Type, ids);
if (ids.ContainsKey(assetID))
ids.Remove(assetID);
foreach (UUID uuid in ids.Keys) foreach (UUID uuid in ids.Keys)
FetchAsset(userAssetURL, uuid); FetchAsset(userAssetURL, uuid);

View File

@ -131,6 +131,7 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
return ret; return ret;
} }
// DO NOT OVERRIDE THE BASE METHOD
public virtual UUID DeleteToInventory(DeRezAction action, UUID folderID, public virtual UUID DeleteToInventory(DeRezAction action, UUID folderID,
SceneObjectGroup objectGroup, IClientAPI remoteClient) SceneObjectGroup objectGroup, IClientAPI remoteClient)
{ {
@ -138,6 +139,7 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
if (!assetID.Equals(UUID.Zero)) if (!assetID.Equals(UUID.Zero))
{ {
if (remoteClient != null)
UploadInventoryItem(remoteClient.AgentId, assetID, "", 0); UploadInventoryItem(remoteClient.AgentId, assetID, "", 0);
} }
else else
@ -191,9 +193,7 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
m_assMapper.Post(item.AssetID, receiver, userAssetServer); m_assMapper.Post(item.AssetID, receiver, userAssetServer);
} }
#endregion public override bool IsForeignUser(UUID userID, out string assetServerURL)
public bool IsForeignUser(UUID userID, out string assetServerURL)
{ {
assetServerURL = string.Empty; assetServerURL = string.Empty;
UserAccount account = null; UserAccount account = null;
@ -216,5 +216,18 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
return false; return false;
} }
#endregion
protected override InventoryItemBase GetItem(UUID agentID, UUID itemID)
{
InventoryItemBase item = base.GetItem(agentID, itemID);
string userAssetServer = string.Empty;
if (IsForeignUser(agentID, out userAssetServer))
m_assMapper.Get(item.AssetID, agentID, userAssetServer);
return item;
}
} }
} }

View File

@ -286,22 +286,14 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
{ {
// Deleting someone else's item // Deleting someone else's item
// //
if (remoteClient == null || if (remoteClient == null ||
objectGroup.OwnerID != remoteClient.AgentId) objectGroup.OwnerID != remoteClient.AgentId)
{ {
// Folder skeleton may not be loaded and we
// have to wait for the inventory to find
// the destination folder
//
folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.LostAndFoundFolder); folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.LostAndFoundFolder);
} }
else else
{ {
// Assume inventory skeleton was loaded during login
// and all folders can be found
//
folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.TrashFolder); folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.TrashFolder);
} }
} }
@ -330,9 +322,20 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
} }
} }
// Override and put into where it came from, if it came
// from anywhere in inventory
//
if (action == DeRezAction.Take || action == DeRezAction.TakeCopy)
{
if (objectGroup.RootPart.FromFolderID != UUID.Zero)
{
InventoryFolderBase f = new InventoryFolderBase(objectGroup.RootPart.FromFolderID, userID);
folder = m_Scene.InventoryService.GetFolder(f);
}
}
if (folder == null) // None of the above if (folder == null) // None of the above
{ {
//folder = userInfo.RootFolder.FindFolder(folderID);
folder = new InventoryFolderBase(folderID); folder = new InventoryFolderBase(folderID);
if (folder == null) // Nowhere to put it if (folder == null) // Nowhere to put it
@ -378,12 +381,27 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
if ((nextPerms & (uint)PermissionMask.Modify) == 0) if ((nextPerms & (uint)PermissionMask.Modify) == 0)
perms &= ~(uint)PermissionMask.Modify; perms &= ~(uint)PermissionMask.Modify;
// Make sure all bits but the ones we want are clear
// on take.
// This will be applied to the current perms, so
// it will do what we want.
objectGroup.RootPart.NextOwnerMask &=
((uint)PermissionMask.Copy |
(uint)PermissionMask.Transfer |
(uint)PermissionMask.Modify);
objectGroup.RootPart.NextOwnerMask |=
(uint)PermissionMask.Move;
item.BasePermissions = perms & objectGroup.RootPart.NextOwnerMask; item.BasePermissions = perms & objectGroup.RootPart.NextOwnerMask;
item.CurrentPermissions = item.BasePermissions; item.CurrentPermissions = item.BasePermissions;
item.NextPermissions = objectGroup.RootPart.NextOwnerMask; item.NextPermissions = objectGroup.RootPart.NextOwnerMask;
item.EveryOnePermissions = objectGroup.RootPart.EveryoneMask & objectGroup.RootPart.NextOwnerMask; item.EveryOnePermissions = objectGroup.RootPart.EveryoneMask & objectGroup.RootPart.NextOwnerMask;
item.GroupPermissions = objectGroup.RootPart.GroupMask & objectGroup.RootPart.NextOwnerMask; item.GroupPermissions = objectGroup.RootPart.GroupMask & objectGroup.RootPart.NextOwnerMask;
item.CurrentPermissions |= 8; // Slam!
// Magic number badness. Maybe this deserves an enum.
// bit 4 (16) is the "Slam" bit, it means treat as passed
// and apply next owner perms on rez
item.CurrentPermissions |= 16; // Slam!
} }
else else
{ {
@ -393,7 +411,12 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
item.EveryOnePermissions = objectGroup.RootPart.EveryoneMask; item.EveryOnePermissions = objectGroup.RootPart.EveryoneMask;
item.GroupPermissions = objectGroup.RootPart.GroupMask; item.GroupPermissions = objectGroup.RootPart.GroupMask;
item.CurrentPermissions |= 8; // Slam! item.CurrentPermissions &=
((uint)PermissionMask.Copy |
(uint)PermissionMask.Transfer |
(uint)PermissionMask.Modify |
(uint)PermissionMask.Move |
7); // Preserve folded permissions
} }
// TODO: add the new fields (Flags, Sale info, etc) // TODO: add the new fields (Flags, Sale info, etc)
@ -494,6 +517,14 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
SceneObjectGroup group SceneObjectGroup group
= SceneObjectSerializer.FromOriginalXmlFormat(itemId, xmlData); = SceneObjectSerializer.FromOriginalXmlFormat(itemId, xmlData);
group.RootPart.FromFolderID = item.Folder;
// If it's rezzed in world, select it. Much easier to
// find small items.
//
if (!attachment)
group.RootPart.CreateSelected = true;
if (!m_Scene.Permissions.CanRezObject( if (!m_Scene.Permissions.CanRezObject(
group.Children.Count, remoteClient.AgentId, pos) group.Children.Count, remoteClient.AgentId, pos)
&& !attachment) && !attachment)
@ -566,15 +597,13 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
List<SceneObjectPart> partList = new List<SceneObjectPart>(group.Children.Values); List<SceneObjectPart> partList = new List<SceneObjectPart>(group.Children.Values);
group.SetGroup(remoteClient.ActiveGroupId, remoteClient); group.SetGroup(remoteClient.ActiveGroupId, remoteClient);
if (rootPart.OwnerID != item.Owner) if ((rootPart.OwnerID != item.Owner) || (item.CurrentPermissions & 16) != 0)
{ {
//Need to kill the for sale here //Need to kill the for sale here
rootPart.ObjectSaleType = 0; rootPart.ObjectSaleType = 0;
rootPart.SalePrice = 10; rootPart.SalePrice = 10;
if (m_Scene.Permissions.PropagatePermissions()) if (m_Scene.Permissions.PropagatePermissions())
{
if ((item.CurrentPermissions & 8) != 0)
{ {
foreach (SceneObjectPart part in partList) foreach (SceneObjectPart part in partList)
{ {
@ -582,7 +611,6 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
part.NextOwnerMask = item.NextPermissions; part.NextOwnerMask = item.NextPermissions;
part.GroupMask = 0; // DO NOT propagate here part.GroupMask = 0; // DO NOT propagate here
} }
}
group.ApplyNextOwnerPermissions(); group.ApplyNextOwnerPermissions();
} }
@ -590,19 +618,15 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
foreach (SceneObjectPart part in partList) foreach (SceneObjectPart part in partList)
{ {
if (part.OwnerID != item.Owner) if ((part.OwnerID != item.Owner) || (item.CurrentPermissions & 16) != 0)
{ {
part.LastOwnerID = part.OwnerID; part.LastOwnerID = part.OwnerID;
part.OwnerID = item.Owner; part.OwnerID = item.Owner;
part.Inventory.ChangeInventoryOwner(item.Owner); part.Inventory.ChangeInventoryOwner(item.Owner);
}
else if (((item.CurrentPermissions & 8) != 0) && (!attachment)) // Slam!
{
part.EveryoneMask = item.EveryOnePermissions;
part.NextOwnerMask = item.NextPermissions;
part.GroupMask = 0; // DO NOT propagate here part.GroupMask = 0; // DO NOT propagate here
} }
part.EveryoneMask = item.EveryOnePermissions;
part.NextOwnerMask = item.NextPermissions;
} }
rootPart.TrimPermissions(); rootPart.TrimPermissions();
@ -648,6 +672,57 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
{ {
} }
public virtual bool GetAgentInventoryItem(IClientAPI remoteClient, UUID itemID, UUID requestID)
{
InventoryItemBase assetRequestItem = GetItem(remoteClient.AgentId, itemID);
if (assetRequestItem == null)
{
ILibraryService lib = m_Scene.RequestModuleInterface<ILibraryService>();
if (lib != null)
assetRequestItem = lib.LibraryRootFolder.FindItem(itemID);
if (assetRequestItem == null)
return false;
}
// At this point, we need to apply perms
// only to notecards and scripts. All
// other asset types are always available
//
if (assetRequestItem.AssetType == (int)AssetType.LSLText)
{
if (!m_Scene.Permissions.CanViewScript(itemID, UUID.Zero, remoteClient.AgentId))
{
remoteClient.SendAgentAlertMessage("Insufficient permissions to view script", false);
return false;
}
}
else if (assetRequestItem.AssetType == (int)AssetType.Notecard)
{
if (!m_Scene.Permissions.CanViewNotecard(itemID, UUID.Zero, remoteClient.AgentId))
{
remoteClient.SendAgentAlertMessage("Insufficient permissions to view notecard", false);
return false;
}
}
if (assetRequestItem.AssetID != requestID)
{
m_log.WarnFormat(
"[CLIENT]: {0} requested asset {1} from item {2} but this does not match item's asset {3}",
Name, requestID, itemID, assetRequestItem.AssetID);
return false;
}
return true;
}
public virtual bool IsForeignUser(UUID userID, out string assetServerURL)
{
assetServerURL = string.Empty;
return false;
}
#endregion #endregion
#region Misc #region Misc
@ -670,6 +745,14 @@ namespace OpenSim.Region.CoreModules.Framework.InventoryAccess
return asset; return asset;
} }
protected virtual InventoryItemBase GetItem(UUID agentID, UUID itemID)
{
IInventoryService invService = m_Scene.RequestModuleInterface<IInventoryService>();
InventoryItemBase assetRequestItem = new InventoryItemBase(itemID, agentID);
assetRequestItem = invService.GetItem(assetRequestItem);
return assetRequestItem;
}
#endregion #endregion
} }
} }

View File

@ -372,7 +372,7 @@ namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule
public virtual String Name public virtual String Name
{ {
get { return FirstName + LastName; } get { return FirstName + " " + LastName; }
} }
public bool IsActive public bool IsActive
@ -1200,6 +1200,9 @@ namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule
{ {
throw new System.NotImplementedException(); throw new System.NotImplementedException();
} }
public void StopFlying(ISceneEntity p)
{
}
} }
} }

View File

@ -10,10 +10,12 @@ using OpenMetaverse.Packets;
using OpenMetaverse.StructuredData; using OpenMetaverse.StructuredData;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Framework.Client; using OpenSim.Framework.Client;
using TPFlags = OpenSim.Framework.Constants.TeleportFlags;
using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Serialization; using OpenSim.Region.Framework.Scenes.Serialization;
using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes.Types; using OpenSim.Region.Framework.Scenes.Types;
using log4net; using log4net;
namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule
@ -359,6 +361,15 @@ namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule
RegionSyncAvatar av = new RegionSyncAvatar(m_scene, agentID, first, last, startPos); RegionSyncAvatar av = new RegionSyncAvatar(m_scene, agentID, first, last, startPos);
m_remoteAvatars.Add(agentID, av); m_remoteAvatars.Add(agentID, av);
m_scene.AddNewClient(av); m_scene.AddNewClient(av);
m_scene.TryGetScenePresence(agentID, out sp);
if (sp == null)
{
m_log.ErrorFormat("{0} Could not get newly added scene presence.", LogHeader);
}
else
{
sp.IsSyncedAvatar = true;
}
//RegionSyncMessage.HandlerDebug(LogHeader, msg, String.Format("Added new remote avatar \"{0}\" ({1})", first + " " + last, agentID)); //RegionSyncMessage.HandlerDebug(LogHeader, msg, String.Format("Added new remote avatar \"{0}\" ({1})", first + " " + last, agentID));
RegionSyncMessage.HandleSuccess(LogHeader, msg, String.Format("Added new remote avatar \"{0}\" ({1})", first + " " + last, agentID)); RegionSyncMessage.HandleSuccess(LogHeader, msg, String.Format("Added new remote avatar \"{0}\" ({1})", first + " " + last, agentID));
return; return;
@ -412,6 +423,22 @@ namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule
return; return;
} }
if (presence.IsBalancing && presence.ControllingClient is RegionSyncAvatar)
{
lock (m_syncRoot)
{
if (m_localAvatars.ContainsKey(presence.UUID))
{
}
else
{
m_log.WarnFormat("{0} Received update for balancing avatar not in local avatar list. \"{1}\"", LogHeader, presence.Name);
return;
}
}
}
/** /**
// Update the scene presence from parameters // Update the scene presence from parameters
bool updateAnimations = ((presence.AgentControlFlags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY ) != (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY ) || bool updateAnimations = ((presence.AgentControlFlags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY ) != (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY ) ||
@ -631,6 +658,21 @@ namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule
//m_log.WarnFormat("{0} END of AvatarAppearance handler", LogHeader); //m_log.WarnFormat("{0} END of AvatarAppearance handler", LogHeader);
return; return;
} }
case RegionSyncMessage.MsgType.BalanceClientLoad:
{
// Get the data from message and error check
OSDMap data = DeserializeMessage(msg);
if (data == null)
{
RegionSyncMessage.HandleError(LogHeader, msg, "Could not deserialize JSON data.");
return;
}
int targetLoad = data["endCount"].AsInteger();
string destinationRegion = data["toRegion"].AsString();
RegionSyncMessage.HandleSuccess(LogHeader, msg, String.Format("Balancing load from {0} to {1} via region \"{2}\"", m_localAvatars.Count, targetLoad, destinationRegion));
BalanceClientLoad(targetLoad, destinationRegion);
return;
}
default: default:
{ {
RegionSyncMessage.HandleError(LogHeader, msg, String.Format("{0} Unsupported message type: {1}", LogHeader, ((int)msg.Type).ToString())); RegionSyncMessage.HandleError(LogHeader, msg, String.Format("{0} Unsupported message type: {1}", LogHeader, ((int)msg.Type).ToString()));
@ -685,6 +727,10 @@ namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule
// don't subscribe to events or send back to server // don't subscribe to events or send back to server
if (RemoteAvatars.ContainsKey(client.AgentId)) if (RemoteAvatars.ContainsKey(client.AgentId))
return; return;
// If this client is local, then it must have been added during a teleport due to load balancing.
// Don't subscribe to events or sent to server.
if (LocalAvatars.ContainsKey(client.AgentId))
return;
// Otherwise, it's a real local client connecting so track it locally // Otherwise, it's a real local client connecting so track it locally
lock (m_syncRoot) lock (m_syncRoot)
{ {
@ -708,8 +754,33 @@ namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule
client.OnChatFromClientRaw += HandleChatFromClientRaw; client.OnChatFromClientRaw += HandleChatFromClientRaw;
} }
void RemoveLocalClient(UUID clientID, Scene scene) private void RemoveLocalClient(UUID clientID, Scene scene)
{ {
// If the client closed due to load balancing, the presence will stick around
// and we just move from a local avatar to a remote avatar and give it a new
// RegionSyncAvatar as the client
ScenePresence sp;
m_scene.TryGetScenePresence(clientID, out sp);
if (sp != null && sp.IsBalancing)
{
// Replace the LLClientView with a RegionSyncAvatar
RegionSyncAvatar av = new RegionSyncAvatar(sp.Scene, sp.UUID, sp.Firstname, sp.Lastname, sp.AbsolutePosition);
sp.ControllingClient = av;
lock (m_syncRoot)
{
Dictionary<UUID, IClientAPI> newlocals = new Dictionary<UUID, IClientAPI>(LocalAvatars);
newlocals.Remove(sp.UUID);
m_localAvatars = newlocals;
Dictionary<UUID, RegionSyncAvatar> newremotes = new Dictionary<UUID, RegionSyncAvatar>(RemoteAvatars);
newremotes.Add(sp.UUID, av);
m_remoteAvatars = newremotes;
}
sp.IsBalancing = false;
sp.IsSyncedAvatar = true;
return;
}
lock (m_syncRoot) lock (m_syncRoot)
{ {
// If the client to be removed is a local client, then send a message to the remote scene // If the client to be removed is a local client, then send a message to the remote scene
@ -815,5 +886,71 @@ namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule
//m_log.WarnFormat("{0}: Sent stats: {1},{2},{3}", LogHeader, t, l, r); //m_log.WarnFormat("{0}: Sent stats: {1},{2},{3}", LogHeader, t, l, r);
Send(new RegionSyncMessage(RegionSyncMessage.MsgType.RegionStatus, OSDParser.SerializeJsonString(data))); Send(new RegionSyncMessage(RegionSyncMessage.MsgType.RegionStatus, OSDParser.SerializeJsonString(data)));
} }
// Handles a message from the authoritative sim to balance client load by reducing client count to targetLoad
// by teleporting the extras to destinationRegion
private void BalanceClientLoad(int targetLoad, string destinationRegion)
{
int numberToTransfer = m_localAvatars.Count - targetLoad;
foreach(KeyValuePair<UUID,IClientAPI> kvp in LocalAvatars)
{
// BEGIN HACK FOR DEMO (Never teleport me please! I'll go where I please.)
if (kvp.Value.FirstName == "Dan" && kvp.Value.LastName == "Lake")
continue;
// END HACK FOR DEMO
ScenePresence sp;
m_scene.TryGetScenePresence(kvp.Key, out sp);
if (sp == null)
{
m_log.ErrorFormat("{0} Could not find scene presence {1} to teleport", LogHeader, kvp.Value.Name);
continue;
}
sp.IsBalancing = true;
// Let the auth sim know we are losing responsibility for this client
OSDMap data = new OSDMap(1);
data["agentID"] = OSD.FromUUID(kvp.Key);
Send(new RegionSyncMessage(RegionSyncMessage.MsgType.AvatarTeleportOut, OSDParser.SerializeJsonString(data)));
//kvp.Value.SendTeleportLocationStart();
m_scene.RequestTeleportLocation(kvp.Value, destinationRegion, sp.AbsolutePosition, sp.Lookat, (uint)TPFlags.ViaLocation);
if (--numberToTransfer <= 0)
break;
}
}
// When a client teleports into the region from another client manager, this function is called after
// the ScenePresence's RegionSyncAvatar client has been changed to an LLClientView.
// Here we will subscribe to interesting client events
public void IncomingLoadBalanceConnection(ScenePresence presence)
{
m_log.WarnFormat("{0} IncomingLoadBalanceConnection", LogHeader);
IClientAPI client = presence.ControllingClient;
// Let the auth sim know we just picked up responsibility for this client
OSDMap data = new OSDMap(1);
data["agentID"] = OSD.FromUUID(client.AgentId);
Send(new RegionSyncMessage(RegionSyncMessage.MsgType.AvatarTeleportIn, OSDParser.SerializeJsonString(data)));
lock (m_syncRoot)
{
Dictionary<UUID, IClientAPI> newlocals = new Dictionary<UUID, IClientAPI>(LocalAvatars);
newlocals.Add(client.AgentId, client);
m_localAvatars = newlocals;
Dictionary<UUID, RegionSyncAvatar> newremotes = new Dictionary<UUID, RegionSyncAvatar>(RemoteAvatars);
newremotes.Remove(client.AgentId);
m_remoteAvatars = newremotes;
}
// Register for interesting client events which will be forwarded to auth sim
// These are the raw packet data blocks from the client, intercepted and sent up to the sim
client.OnAgentUpdateRaw += HandleAgentUpdateRaw;
client.OnSetAppearanceRaw += HandleSetAppearanceRaw;
client.OnChatFromClientRaw += HandleChatFromClientRaw;
presence.IsSyncedAvatar = false;
}
} }
} }

View File

@ -106,6 +106,11 @@ namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule
m_client.SendCoarseLocations(); m_client.SendCoarseLocations();
} }
public void IncomingLoadBalanceConnection(ScenePresence presence)
{
m_client.IncomingLoadBalanceConnection(presence);
}
public bool Active public bool Active
{ {
get { return m_active; } get { return m_active; }
@ -228,9 +233,10 @@ namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule
m_log.WarnFormat("[REGION SYNC CLIENT MODULE] Already stopped"); m_log.WarnFormat("[REGION SYNC CLIENT MODULE] Already stopped");
return; return;
} }
m_log.Warn("[REGION SYNC CLIENT MODULE] Stopping synchronization");
m_client.Stop(); m_client.Stop();
m_client = null; m_client = null;
m_log.Warn("[REGION SYNC CLIENT MODULE] Stopping synchronization");
} }
} }

View File

@ -70,6 +70,11 @@ namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule
private Thread m_send_loop; private Thread m_send_loop;
private string m_regionName; private string m_regionName;
public string Name
{
get { return m_regionName; }
}
// A string of the format [REGION SYNC CLIENT VIEW (regionname)] for use in log headers // A string of the format [REGION SYNC CLIENT VIEW (regionname)] for use in log headers
private string LogHeader private string LogHeader
{ {
@ -94,10 +99,8 @@ namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule
public string GetStats() public string GetStats()
{ {
int syncedAvCount; int syncedAvCount = SyncedAvCount; ;
string ret; string ret;
lock (m_syncRoot)
syncedAvCount = m_syncedAvatars.Count;
lock (stats) lock (stats)
{ {
double secondsSinceLastStats = DateTime.Now.Subtract(lastStatTime).TotalSeconds; double secondsSinceLastStats = DateTime.Now.Subtract(lastStatTime).TotalSeconds;
@ -192,9 +195,16 @@ namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule
msgsIn++; msgsIn++;
bytesIn += msg.Length; bytesIn += msg.Length;
} }
try
{
lock (m_syncRoot) lock (m_syncRoot)
HandleMessage(msg); HandleMessage(msg);
} }
catch (Exception e)
{
m_log.ErrorFormat("{0} Exception in HandleMessage({1}) (ReceiveLoop):{2}", LogHeader, msg.Type.ToString(), e.Message);
}
}
} }
catch (Exception e) catch (Exception e)
{ {
@ -374,7 +384,7 @@ namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule
} }
if(!found) if(!found)
{ {
RegionSyncMessage.HandleWarning(LogHeader, msg, String.Format("Received agent update for non-existent avatar with UUID {0}", agentData.AgentID)); RegionSyncMessage.HandleWarning(LogHeader, msg, String.Format("Received agent update for avatar not owned by this client view {0}", agentData.AgentID));
return; return;
} }
@ -571,6 +581,66 @@ namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule
//RegionSyncMessage.HandleSuccess(LogHeader, msg, String.Format("Received stats: {0},{1},{2}", t, l, r)); //RegionSyncMessage.HandleSuccess(LogHeader, msg, String.Format("Received stats: {0},{1},{2}", t, l, r));
return; return;
} }
case RegionSyncMessage.MsgType.AvatarTeleportIn:
{
// Get the data from message and error check
OSDMap data = DeserializeMessage(msg);
if (data == null)
{
RegionSyncMessage.HandleError(LogHeader, msg, "Could not deserialize JSON data.");
return;
}
UUID agentID = data["agentID"].AsUUID();
ScenePresence sp;
m_scene.TryGetScenePresence(agentID, out sp);
if (sp == null)
{
RegionSyncMessage.HandleError(LogHeader, msg, "Presence is not in scene");
return;
}
if (sp.ControllingClient is RegionSyncAvatar)
{
m_syncedAvatars.Add(agentID, (RegionSyncAvatar)sp.ControllingClient);
RegionSyncMessage.HandleSuccess(LogHeader, msg, String.Format("Avatar {0} now owned by region {1}", sp.Name, m_regionName));
return;
}
else
{
RegionSyncMessage.HandleError(LogHeader, msg, "Presence is not a RegionSyncAvatar");
return;
}
}
case RegionSyncMessage.MsgType.AvatarTeleportOut:
{
// Get the data from message and error check
OSDMap data = DeserializeMessage(msg);
if (data == null)
{
RegionSyncMessage.HandleError(LogHeader, msg, "Could not deserialize JSON data.");
return;
}
UUID agentID = data["agentID"].AsUUID();
ScenePresence sp;
m_scene.TryGetScenePresence(agentID, out sp);
if (sp == null)
{
RegionSyncMessage.HandleError(LogHeader, msg, "Presence is not in scene");
return;
}
if (sp.ControllingClient is RegionSyncAvatar)
{
m_syncedAvatars.Remove(agentID);
RegionSyncMessage.HandleSuccess(LogHeader, msg, String.Format("Avatar {0} is no longer owned by region {1}", sp.Name, m_regionName));
return;
}
else
{
RegionSyncMessage.HandleError(LogHeader, msg, "Presence is not a RegionSyncAvatar");
return;
}
}
default: default:
{ {
m_log.WarnFormat("{0} Unable to handle unsupported message type", LogHeader); m_log.WarnFormat("{0} Unable to handle unsupported message type", LogHeader);
@ -635,11 +705,18 @@ namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule
} }
} }
public int SyncedAvCount
{
get
{
lock (m_syncRoot)
return m_syncedAvatars.Count;
}
}
public void ReportStatus() public void ReportStatus()
{ {
int syncedAvCount; int syncedAvCount = SyncedAvCount;
lock (m_syncRoot)
syncedAvCount = m_syncedAvatars.Count;
lock (stats) lock (stats)
{ {
bool localcheck = true; bool localcheck = true;
@ -652,9 +729,16 @@ namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule
if (m_scene.SceneGraph.GetRootAgentCount() - syncedAvCount != lastRemoteCount) if (m_scene.SceneGraph.GetRootAgentCount() - syncedAvCount != lastRemoteCount)
remotecheck = false; remotecheck = false;
m_log.ErrorFormat("{0} Syncing {1,4} remote presences. Remote scene reporting {2,4} locals, {3,4} remotes, {4,4} total ({5},{6},{7})", m_log.ErrorFormat("{0} Syncing {1,4} remote presences. Remote scene reporting {2,4} locals, {3,4} remotes, {4,4} total ({5},{6},{7})",
LogHeader, m_syncedAvatars.Count, lastLocalCount, lastRemoteCount, lastTotalCount, localcheck ? " " : "!", remotecheck ? " " : "!", totalcheck ? " " : "!"); LogHeader, syncedAvCount, lastLocalCount, lastRemoteCount, lastTotalCount, localcheck ? " " : "!", remotecheck ? " " : "!", totalcheck ? " " : "!");
} }
} }
public void BalanceClients(int targetLoad, string destinationRegion)
{
OSDMap data = new OSDMap(2);
data["endCount"] = OSD.FromInteger(targetLoad);
data["toRegion"] = OSD.FromString(destinationRegion);
Send(new RegionSyncMessage(RegionSyncMessage.MsgType.BalanceClientLoad, OSDParser.SerializeJsonString(data)));
}
} }
} }

View File

@ -17,6 +17,7 @@ namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule
//ConnectSyncClient, //ConnectSyncClient,
//DisconnectSyncClient, //DisconnectSyncClient,
// CM -> SIM // CM -> SIM
ActorConnect,
AgentAdd, AgentAdd,
AgentUpdate, AgentUpdate,
AgentRemove, AgentRemove,
@ -26,6 +27,8 @@ namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule
GetAvatars, GetAvatars,
SubscribeAvatars, SubscribeAvatars,
ChatFromClient, ChatFromClient,
AvatarTeleportOut, // An LLClientView (real client) was converted to a RegionSyncAvatar
AvatarTeleportIn, // A RegionSyncAvatar was converted to an LLClientView (real client)
// SIM -> CM // SIM -> CM
Terrain, Terrain,
NewObject, // objects NewObject, // objects
@ -36,6 +39,7 @@ namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule
AnimateAvatar, AnimateAvatar,
AvatarAppearance, AvatarAppearance,
RemovedAvatar, // avatars RemovedAvatar, // avatars
BalanceClientLoad, // Tells CM a client load target and a place to teleport the extras
ChatFromSim, ChatFromSim,
// BIDIR // BIDIR
EchoRequest, EchoRequest,

View File

@ -31,88 +31,49 @@ namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule
private TcpListener m_listener; private TcpListener m_listener;
private Thread m_listenerThread; private Thread m_listenerThread;
// The list of clients and the threads handling IO for each client private DSGClientManagerLoadBalancer m_ClientBalancer;
// The list is read most of the time and only updated when a new client manager
// connects, so we just replace the list when it changes. Iterators on this
// list need to be able to handle if an element is shutting down.
private object m_clientview_lock = new object();
private HashSet<RegionSyncClientView> m_client_views = new HashSet<RegionSyncClientView>();
// Check if any of the client views are in a connected state // Check if any of the client views are in a connected state
public bool Synced public bool Synced
{ {
get get
{ {
return (m_client_views.Count > 0); return (m_ClientBalancer.Count > 0);
}
}
// Add the client view to the list and increment synced client counter
public void AddSyncedClient(RegionSyncClientView rscv)
{
lock (m_clientview_lock)
{
HashSet<RegionSyncClientView> currentlist = m_client_views;
HashSet<RegionSyncClientView> newlist = new HashSet<RegionSyncClientView>(currentlist);
newlist.Add(rscv);
// Threads holding the previous version of the list can keep using it since
// they will not hold it for long and get a new copy next time they need to iterate
m_client_views = newlist;
}
}
// Remove the client view from the list and decrement synced client counter
public void RemoveSyncedClient(RegionSyncClientView rscv)
{
lock (m_clientview_lock)
{
HashSet<RegionSyncClientView> currentlist = m_client_views;
HashSet<RegionSyncClientView> newlist = new HashSet<RegionSyncClientView>(currentlist);
newlist.Remove(rscv);
// Threads holding the previous version of the list can keep using it since
// they will not hold it for long and get a new copy next time they need to iterate
m_client_views = newlist;
} }
} }
public void ReportStats(System.IO.TextWriter tw) public void ReportStats(System.IO.TextWriter tw)
{ {
// We should be able to safely iterate over our reference to the list since
// the only places which change it will replace it with an updated version
HashSet<RegionSyncClientView> cvs = m_client_views;
tw.WriteLine("{0}: [REGION SYNC SERVER] TOTAL LOCAL REMOTE TO_SCENE FROM_SCENE", DateTime.Now.ToLongTimeString()); tw.WriteLine("{0}: [REGION SYNC SERVER] TOTAL LOCAL REMOTE TO_SCENE FROM_SCENE", DateTime.Now.ToLongTimeString());
tw.WriteLine("{0}: [REGION SYNC SERVER] MSGS ( /s ) BYTES ( Mbps ) MSGS ( /s ) BYTES ( Mbps ) QUEUE", DateTime.Now.ToLongTimeString()); tw.WriteLine("{0}: [REGION SYNC SERVER] MSGS ( /s ) BYTES ( Mbps ) MSGS ( /s ) BYTES ( Mbps ) QUEUE", DateTime.Now.ToLongTimeString());
foreach (RegionSyncClientView cv in cvs) m_ClientBalancer.ForEachClientManager(delegate(RegionSyncClientView rscv) {
{ {
tw.WriteLine("{0}: [{1}] {2}", DateTime.Now.ToLongTimeString(), cv.Description, cv.GetStats()); tw.WriteLine("{0}: [{1}] {2}", DateTime.Now.ToLongTimeString(), rscv.Description, rscv.GetStats());
} }
});
tw.Flush(); tw.Flush();
} }
public void ReportStatus() public void ReportStatus()
{ {
lock (m_clientview_lock) int cvcount = m_ClientBalancer.Count;
{ m_log.ErrorFormat("[REGION SYNC SERVER] Connected to {0} remote client managers", cvcount);
m_log.ErrorFormat("[REGION SYNC SERVER] Connected to {0} remote client managers", m_client_views.Count);
m_log.ErrorFormat("[REGION SYNC SERVER] Local scene contains {0} presences", m_scene.SceneGraph.GetRootAgentCount()); m_log.ErrorFormat("[REGION SYNC SERVER] Local scene contains {0} presences", m_scene.SceneGraph.GetRootAgentCount());
foreach (RegionSyncClientView rscv in m_client_views) m_ClientBalancer.ForEachClientManager(delegate(RegionSyncClientView rscv){rscv.ReportStatus();});
{
rscv.ReportStatus();
}
}
} }
#endregion #endregion
// Constructor // Constructor
public RegionSyncServer(Scene scene, string addr, int port) public RegionSyncServer(Scene scene, string addr, int port, int maxClientsPerManager)
{ {
m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//m_log.Warn("[REGION SYNC SERVER] Constructed"); //m_log.Warn("[REGION SYNC SERVER] Constructed");
m_scene = scene; m_scene = scene;
m_addr = IPAddress.Parse(addr); m_addr = IPAddress.Parse(addr);
m_port = port; m_port = port;
m_ClientBalancer = new DSGClientManagerLoadBalancer(maxClientsPerManager, scene);
} }
// Start the server // Start the server
@ -135,14 +96,12 @@ namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule
m_listenerThread.Abort(); m_listenerThread.Abort();
m_listenerThread = null; m_listenerThread = null;
// Stop all existing client views and clear client list m_ClientBalancer.ForEachClientManager(delegate(RegionSyncClientView rscv)
HashSet<RegionSyncClientView> list = new HashSet<RegionSyncClientView>(m_client_views);
foreach (RegionSyncClientView rscv in list)
{ {
// Each client view will clean up after itself // Each client view will clean up after itself
rscv.Shutdown(); rscv.Shutdown();
RemoveSyncedClient(rscv); m_ClientBalancer.RemoveSyncedClient(rscv);
} });
} }
// Listen for connections from a new RegionSyncClient // Listen for connections from a new RegionSyncClient
@ -168,7 +127,7 @@ namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule
// not sent before it is ready to process them. // not sent before it is ready to process them.
RegionSyncClientView rscv = new RegionSyncClientView(++clientCounter, m_scene, tcpclient); RegionSyncClientView rscv = new RegionSyncClientView(++clientCounter, m_scene, tcpclient);
m_log.WarnFormat("[REGION SYNC SERVER] New connection from {0}", rscv.Description); m_log.WarnFormat("[REGION SYNC SERVER] New connection from {0}", rscv.Description);
AddSyncedClient(rscv); m_ClientBalancer.AddSyncedClient(rscv);
} }
} }
catch (SocketException e) catch (SocketException e)
@ -181,26 +140,25 @@ namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule
public void Broadcast(RegionSyncMessage msg) public void Broadcast(RegionSyncMessage msg)
{ {
List<RegionSyncClientView> closed = null; List<RegionSyncClientView> closed = null;
foreach (RegionSyncClientView client in m_client_views) m_ClientBalancer.ForEachClientManager(delegate(RegionSyncClientView rscv)
{ {
// If connected, send the message. // If connected, send the message.
if (client.Connected) if (rscv.Connected)
{ {
client.Send(msg); rscv.Send(msg);
} }
// Else, remove the client view from the list // Else, remove the client view from the list
else else
{ {
if (closed == null) if (closed == null)
closed = new List<RegionSyncClientView>(); closed = new List<RegionSyncClientView>();
closed.Add(client); closed.Add(rscv);
}
} }
});
if (closed != null) if (closed != null)
{ {
foreach (RegionSyncClientView rscv in closed) foreach (RegionSyncClientView rscv in closed)
RemoveSyncedClient(rscv); m_ClientBalancer.RemoveSyncedClient(rscv);
//m_client_views.Remove(rscv);
} }
} }
@ -208,27 +166,31 @@ namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule
public void EnqueuePresenceUpdate(UUID id, byte[] update) public void EnqueuePresenceUpdate(UUID id, byte[] update)
{ {
List<RegionSyncClientView> closed = null; List<RegionSyncClientView> closed = null;
foreach (RegionSyncClientView client in m_client_views) m_ClientBalancer.ForEachClientManager(delegate(RegionSyncClientView rscv)
{ {
// If connected, send the message. // If connected, send the message.
if (client.Connected) if (rscv.Connected)
{ {
client.EnqueuePresenceUpdate(id, update); rscv.EnqueuePresenceUpdate(id, update);
} }
// Else, remove the client view from the list // Else, remove the client view from the list
else else
{ {
if (closed == null) if (closed == null)
closed = new List<RegionSyncClientView>(); closed = new List<RegionSyncClientView>();
closed.Add(client); closed.Add(rscv);
}
} }
});
if (closed != null) if (closed != null)
{ {
foreach (RegionSyncClientView rscv in closed) foreach (RegionSyncClientView rscv in closed)
RemoveSyncedClient(rscv); m_ClientBalancer.RemoveSyncedClient(rscv);
//m_client_views.Remove(rscv); }
} }
public void BalanceClients()
{
m_ClientBalancer.BalanceLoad();
} }
} }
} }

View File

@ -61,6 +61,7 @@ namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule
} }
m_serveraddr = syncConfig.GetString("ServerIPAddress", "127.0.0.1"); m_serveraddr = syncConfig.GetString("ServerIPAddress", "127.0.0.1");
m_serverport = syncConfig.GetInt("ServerPort", 13000); m_serverport = syncConfig.GetInt("ServerPort", 13000);
m_maxClientsPerManager = syncConfig.GetInt("MaxClientsPerManager", 100);
m_scene = scene; m_scene = scene;
m_scene.RegisterModuleInterface<IRegionSyncServerModule>(this); m_scene.RegisterModuleInterface<IRegionSyncServerModule>(this);
@ -92,7 +93,7 @@ namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule
m_log.Warn("[REGION SYNC SERVER MODULE] Starting RegionSyncServer"); m_log.Warn("[REGION SYNC SERVER MODULE] Starting RegionSyncServer");
// Start the server and listen for RegionSyncClients // Start the server and listen for RegionSyncClients
m_server = new RegionSyncServer(m_scene, m_serveraddr, m_serverport); m_server = new RegionSyncServer(m_scene, m_serveraddr, m_serverport, m_maxClientsPerManager);
m_server.Start(); m_server.Start();
m_statsTimer.Elapsed += new System.Timers.ElapsedEventHandler(StatsTimerElapsed); m_statsTimer.Elapsed += new System.Timers.ElapsedEventHandler(StatsTimerElapsed);
m_statsTimer.Start(); m_statsTimer.Start();
@ -228,7 +229,7 @@ namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule
} }
catch (Exception e) catch (Exception e)
{ {
m_log.ErrorFormat("[REGION SYNC SERVER MODULE] Caught exception sending presence updates for {0}", presence.Name); m_log.ErrorFormat("[REGION SYNC SERVER MODULE] Caught exception sending presence updates for {0}: {1}", presence.Name, e.Message);
} }
} }
// Indicate that the current batch of updates has been completed // Indicate that the current batch of updates has been completed
@ -343,6 +344,7 @@ namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule
private bool m_active = true; private bool m_active = true;
private string m_serveraddr; private string m_serveraddr;
private int m_serverport; private int m_serverport;
private int m_maxClientsPerManager;
private Scene m_scene; private Scene m_scene;
//private IClientAPI m_clientAggregator; //private IClientAPI m_clientAggregator;
private ILog m_log; private ILog m_log;
@ -536,7 +538,9 @@ namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule
private void InstallInterfaces() private void InstallInterfaces()
{ {
Command cmdSyncStatus = new Command("status", CommandIntentions.COMMAND_HAZARDOUS, SyncStatus, "Reports current status of the RegionSyncServer."); Command cmdSyncStatus = new Command("status", CommandIntentions.COMMAND_HAZARDOUS, SyncStatus, "Reports current status of the RegionSyncServer.");
Command cmdBalanceClients = new Command("balance", CommandIntentions.COMMAND_HAZARDOUS, BalanceClients, "Balance client load across available client managers.");
m_commander.RegisterCommand("status", cmdSyncStatus); m_commander.RegisterCommand("status", cmdSyncStatus);
m_commander.RegisterCommand("balance", cmdBalanceClients);
lock (m_scene) lock (m_scene)
{ {
@ -576,6 +580,14 @@ namespace OpenSim.Region.CoreModules.RegionSync.RegionSyncModule
else else
m_log.Error("No RegionSyncClients connected"); m_log.Error("No RegionSyncClients connected");
} }
private void BalanceClients(Object[] args)
{
if (Synced)
m_server.BalanceClients();
else
m_log.Error("No RegionSyncClients connected");
}
#endregion #endregion

View File

@ -40,7 +40,7 @@ using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.Scripting.EmailModules namespace OpenSim.Region.CoreModules.Scripting.EmailModules
{ {
public class EmailModule : IEmailModule public class EmailModule : IRegionModule, IEmailModule
{ {
// //
// Log // Log

View File

@ -96,7 +96,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsIn.Inventory
Object[] args = new Object[] { m_Config, MainServer.Instance, "HGInventoryService" }; Object[] args = new Object[] { m_Config, MainServer.Instance, "HGInventoryService" };
ServerUtils.LoadPlugin<IServiceConnector>("OpenSim.Server.Handlers.dll:HGInventoryServiceInConnector", args); ServerUtils.LoadPlugin<IServiceConnector>("OpenSim.Server.Handlers.dll:XInventoryInConnector", args);
} }
} }

View File

@ -123,17 +123,14 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsIn.Neighbour
public GridRegion HelloNeighbour(ulong regionHandle, RegionInfo thisRegion) public GridRegion HelloNeighbour(ulong regionHandle, RegionInfo thisRegion)
{ {
m_log.DebugFormat("[NEIGHBOUR IN CONNECTOR]: HelloNeighbour from {0}, to {1}. Count = {2}",
thisRegion.RegionName, regionHandle, m_Scenes.Count);
foreach (Scene s in m_Scenes) foreach (Scene s in m_Scenes)
{ {
if (s.RegionInfo.RegionHandle == regionHandle) if (s.RegionInfo.RegionHandle == regionHandle)
{ {
m_log.Debug("[NEIGHBOUR IN CONNECTOR]: Found region to SendHelloNeighbour"); //m_log.DebugFormat("[NEIGHBOUR IN CONNECTOR]: HelloNeighbour from {0} to {1}", thisRegion.RegionName, s.RegionInfo.RegionName);
return s.IncomingHelloNeighbour(thisRegion); return s.IncomingHelloNeighbour(thisRegion);
} }
} }
m_log.DebugFormat("[NEIGHBOUR IN CONNECTOR]: region handle {0} not found", regionHandle);
return null; return null;
} }

View File

@ -41,7 +41,7 @@ using OpenMetaverse;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset
{ {
public class HGAssetBroker : public class HGAssetBroker :
ISharedRegionModule, IAssetService, IHyperAssetService ISharedRegionModule, IAssetService
{ {
private static readonly ILog m_log = private static readonly ILog m_log =
LogManager.GetLogger( LogManager.GetLogger(
@ -150,7 +150,6 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset
m_aScene = scene; m_aScene = scene;
scene.RegisterModuleInterface<IAssetService>(this); scene.RegisterModuleInterface<IAssetService>(this);
scene.RegisterModuleInterface<IHyperAssetService>(this);
} }
public void RemoveRegion(Scene scene) public void RemoveRegion(Scene scene)

View File

@ -181,22 +181,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID) public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID)
{ {
if (m_LocalCache.ContainsKey(regionID)) return m_GridService.GetNeighbours(scopeID, regionID);
{
List<GridRegion> neighbours = m_LocalCache[regionID].GetNeighbours();
if (neighbours.Count == 0)
// try the DB
neighbours = m_GridService.GetNeighbours(scopeID, regionID);
return neighbours;
}
else
{
m_log.WarnFormat("[LOCAL GRID CONNECTOR]: GetNeighbours: Requested region {0} is not on this sim", regionID);
return new List<GridRegion>();
}
// Don't go to the DB
//return m_GridService.GetNeighbours(scopeID, regionID);
} }
public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID) public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID)

View File

@ -153,12 +153,9 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
return false; return false;
} }
// Let's override GetNeighbours completely -- never go to the grid server
// Neighbours are/should be cached locally
// For retrieval from the DB, caller should call GetRegionByPosition
public override List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID) public override List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID)
{ {
return m_LocalGridService.GetNeighbours(scopeID, regionID); return base.GetNeighbours(scopeID, regionID);
} }
public override GridRegion GetRegionByUUID(UUID scopeID, UUID regionID) public override GridRegion GetRegionByUUID(UUID scopeID, UUID regionID)

View File

@ -202,9 +202,6 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
} }
} }
} }
// else put a null; it means that the methods should forward to local grid's inventory
m_InventoryURLs.Add(userID, null);
} }
private void DropInventoryServiceURL(UUID userID) private void DropInventoryServiceURL(UUID userID)
@ -223,10 +220,13 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
if (m_InventoryURLs.ContainsKey(userID)) if (m_InventoryURLs.ContainsKey(userID))
return m_InventoryURLs[userID]; return m_InventoryURLs[userID];
else
CacheInventoryServiceURL(userID); CacheInventoryServiceURL(userID);
if (m_InventoryURLs.ContainsKey(userID))
return m_InventoryURLs[userID]; return m_InventoryURLs[userID];
return null; //it means that the methods should forward to local grid's inventory
} }
#endregion #endregion
@ -253,7 +253,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
public InventoryFolderBase GetRootFolder(UUID userID) public InventoryFolderBase GetRootFolder(UUID userID)
{ {
m_log.DebugFormat("[HG INVENTORY CONNECTOR]: GetRootFolder for {0}", userID); //m_log.DebugFormat("[HG INVENTORY CONNECTOR]: GetRootFolder for {0}", userID);
string invURL = GetInventoryServiceURL(userID); string invURL = GetInventoryServiceURL(userID);
@ -267,7 +267,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
public InventoryFolderBase GetFolderForType(UUID userID, AssetType type) public InventoryFolderBase GetFolderForType(UUID userID, AssetType type)
{ {
m_log.DebugFormat("[HG INVENTORY CONNECTOR]: GetFolderForType {0} type {1}", userID, type); //m_log.DebugFormat("[HG INVENTORY CONNECTOR]: GetFolderForType {0} type {1}", userID, type);
string invURL = GetInventoryServiceURL(userID); string invURL = GetInventoryServiceURL(userID);
@ -281,7 +281,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
public InventoryCollection GetFolderContent(UUID userID, UUID folderID) public InventoryCollection GetFolderContent(UUID userID, UUID folderID)
{ {
m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolderContent " + folderID); //m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolderContent " + folderID);
string invURL = GetInventoryServiceURL(userID); string invURL = GetInventoryServiceURL(userID);
@ -296,7 +296,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
public List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID) public List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID)
{ {
m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolderItems " + folderID); //m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolderItems " + folderID);
string invURL = GetInventoryServiceURL(userID); string invURL = GetInventoryServiceURL(userID);
@ -314,7 +314,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
if (folder == null) if (folder == null)
return false; return false;
m_log.Debug("[HG INVENTORY CONNECTOR]: AddFolder " + folder.ID); //m_log.Debug("[HG INVENTORY CONNECTOR]: AddFolder " + folder.ID);
string invURL = GetInventoryServiceURL(folder.Owner); string invURL = GetInventoryServiceURL(folder.Owner);
@ -331,7 +331,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
if (folder == null) if (folder == null)
return false; return false;
m_log.Debug("[HG INVENTORY CONNECTOR]: UpdateFolder " + folder.ID); //m_log.Debug("[HG INVENTORY CONNECTOR]: UpdateFolder " + folder.ID);
string invURL = GetInventoryServiceURL(folder.Owner); string invURL = GetInventoryServiceURL(folder.Owner);
@ -350,7 +350,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
if (folderIDs.Count == 0) if (folderIDs.Count == 0)
return false; return false;
m_log.Debug("[HG INVENTORY CONNECTOR]: DeleteFolders for " + ownerID); //m_log.Debug("[HG INVENTORY CONNECTOR]: DeleteFolders for " + ownerID);
string invURL = GetInventoryServiceURL(ownerID); string invURL = GetInventoryServiceURL(ownerID);
@ -367,7 +367,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
if (folder == null) if (folder == null)
return false; return false;
m_log.Debug("[HG INVENTORY CONNECTOR]: MoveFolder for " + folder.Owner); //m_log.Debug("[HG INVENTORY CONNECTOR]: MoveFolder for " + folder.Owner);
string invURL = GetInventoryServiceURL(folder.Owner); string invURL = GetInventoryServiceURL(folder.Owner);
@ -384,7 +384,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
if (folder == null) if (folder == null)
return false; return false;
m_log.Debug("[HG INVENTORY CONNECTOR]: PurgeFolder for " + folder.Owner); //m_log.Debug("[HG INVENTORY CONNECTOR]: PurgeFolder for " + folder.Owner);
string invURL = GetInventoryServiceURL(folder.Owner); string invURL = GetInventoryServiceURL(folder.Owner);
@ -401,7 +401,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
if (item == null) if (item == null)
return false; return false;
m_log.Debug("[HG INVENTORY CONNECTOR]: AddItem " + item.ID); //m_log.Debug("[HG INVENTORY CONNECTOR]: AddItem " + item.ID);
string invURL = GetInventoryServiceURL(item.Owner); string invURL = GetInventoryServiceURL(item.Owner);
@ -418,7 +418,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
if (item == null) if (item == null)
return false; return false;
m_log.Debug("[HG INVENTORY CONNECTOR]: UpdateItem " + item.ID); //m_log.Debug("[HG INVENTORY CONNECTOR]: UpdateItem " + item.ID);
string invURL = GetInventoryServiceURL(item.Owner); string invURL = GetInventoryServiceURL(item.Owner);
@ -437,7 +437,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
if (items.Count == 0) if (items.Count == 0)
return true; return true;
m_log.Debug("[HG INVENTORY CONNECTOR]: MoveItems for " + ownerID); //m_log.Debug("[HG INVENTORY CONNECTOR]: MoveItems for " + ownerID);
string invURL = GetInventoryServiceURL(ownerID); string invURL = GetInventoryServiceURL(ownerID);
@ -451,15 +451,13 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
public bool DeleteItems(UUID ownerID, List<UUID> itemIDs) public bool DeleteItems(UUID ownerID, List<UUID> itemIDs)
{ {
m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Delete {0} items for user {1}", itemIDs.Count, ownerID); //m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Delete {0} items for user {1}", itemIDs.Count, ownerID);
if (itemIDs == null) if (itemIDs == null)
return false; return false;
if (itemIDs.Count == 0) if (itemIDs.Count == 0)
return true; return true;
m_log.Debug("[HG INVENTORY CONNECTOR]: DeleteItems for " + ownerID);
string invURL = GetInventoryServiceURL(ownerID); string invURL = GetInventoryServiceURL(ownerID);
if (invURL == null) // not there, forward to local inventory connector to resolve if (invURL == null) // not there, forward to local inventory connector to resolve
@ -474,7 +472,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
{ {
if (item == null) if (item == null)
return null; return null;
m_log.Debug("[HG INVENTORY CONNECTOR]: GetItem " + item.ID); //m_log.Debug("[HG INVENTORY CONNECTOR]: GetItem " + item.ID);
string invURL = GetInventoryServiceURL(item.Owner); string invURL = GetInventoryServiceURL(item.Owner);
@ -491,7 +489,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
if (folder == null) if (folder == null)
return null; return null;
m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolder " + folder.ID); //m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolder " + folder.ID);
string invURL = GetInventoryServiceURL(folder.Owner); string invURL = GetInventoryServiceURL(folder.Owner);
@ -515,7 +513,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
public int GetAssetPermissions(UUID userID, UUID assetID) public int GetAssetPermissions(UUID userID, UUID assetID)
{ {
m_log.Debug("[HG INVENTORY CONNECTOR]: GetAssetPermissions " + assetID); //m_log.Debug("[HG INVENTORY CONNECTOR]: GetAssetPermissions " + assetID);
string invURL = GetInventoryServiceURL(userID); string invURL = GetInventoryServiceURL(userID);

View File

@ -121,17 +121,17 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Neighbour
public GridRegion HelloNeighbour(ulong regionHandle, RegionInfo thisRegion) public GridRegion HelloNeighbour(ulong regionHandle, RegionInfo thisRegion)
{ {
m_log.DebugFormat("[NEIGHBOUR CONNECTOR]: HelloNeighbour from {0}, to {1}. Count = {2}", m_log.DebugFormat("[NEIGHBOUR CONNECTOR]: HelloNeighbour from {0}, to {1}.",
thisRegion.RegionName, regionHandle, m_Scenes.Count); thisRegion.RegionName, regionHandle);
foreach (Scene s in m_Scenes) foreach (Scene s in m_Scenes)
{ {
if (s.RegionInfo.RegionHandle == regionHandle) if (s.RegionInfo.RegionHandle == regionHandle)
{ {
m_log.Debug("[NEIGHBOUR CONNECTOR]: Found region to SendHelloNeighbour"); //m_log.Debug("[NEIGHBOUR CONNECTOR]: Found region to SendHelloNeighbour");
return s.IncomingHelloNeighbour(thisRegion); return s.IncomingHelloNeighbour(thisRegion);
} }
} }
m_log.DebugFormat("[NEIGHBOUR CONNECTOR]: region handle {0} not found", regionHandle); //m_log.DebugFormat("[NEIGHBOUR CONNECTOR]: region handle {0} not found", regionHandle);
return null; return null;
} }

View File

@ -188,7 +188,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation
{ {
if (s.RegionInfo.RegionHandle == destination.RegionHandle) if (s.RegionInfo.RegionHandle == destination.RegionHandle)
{ {
m_log.DebugFormat("[LOCAL SIMULATION CONNECTOR]: Found region {0} to send SendCreateChildAgent", destination.RegionName); m_log.WarnFormat("[LOCAL SIMULATION CONNECTOR]: Found region {0} to send SendCreateChildAgent", destination.RegionName);
return s.NewUserConnection(aCircuit, teleportFlags, out reason); return s.NewUserConnection(aCircuit, teleportFlags, out reason);
} }
} }

View File

@ -181,7 +181,6 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation
// else do the remote thing // else do the remote thing
if (!m_localBackend.IsLocalRegion(destination.RegionHandle)) if (!m_localBackend.IsLocalRegion(destination.RegionHandle))
{ {
//m_regionClient.SendUserInformation(regInfo, aCircuit);
return m_remoteConnector.CreateAgent(destination, aCircuit, teleportFlags, out reason); return m_remoteConnector.CreateAgent(destination, aCircuit, teleportFlags, out reason);
} }
return false; return false;

View File

@ -44,10 +44,8 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.UserAccounts
public UserAccountCache() public UserAccountCache()
{ {
// Warning: the size values are a bit fuzzy. What matters
// most for this cache is the count value (128 entries).
m_UUIDCache = new ExpiringCache<UUID, UserAccount>(); m_UUIDCache = new ExpiringCache<UUID, UserAccount>();
m_NameCache = new ExpiringCache<string, UUID>(); // this one is unbound m_NameCache = new ExpiringCache<string, UUID>();
} }
public void Cache(UUID userID, UserAccount account) public void Cache(UUID userID, UserAccount account)

View File

@ -69,7 +69,7 @@ namespace OpenSim.Region.CoreModules.World.Archiver.Tests
SerialiserModule serialiserModule = new SerialiserModule(); SerialiserModule serialiserModule = new SerialiserModule();
TerrainModule terrainModule = new TerrainModule(); TerrainModule terrainModule = new TerrainModule();
m_scene = SceneSetupHelpers.SetupScene("useraccounts"); m_scene = SceneSetupHelpers.SetupScene();
SceneSetupHelpers.SetupSceneModules(m_scene, m_archiverModule, serialiserModule, terrainModule); SceneSetupHelpers.SetupSceneModules(m_scene, m_archiverModule, serialiserModule, terrainModule);
} }

View File

@ -146,7 +146,7 @@ namespace OpenSim.Region.CoreModules.World.Land
else else
{ {
// Normal Calculations // Normal Calculations
return (int)Math.Round(((float)LandData.Area / 65536.0f) * (float)m_scene.objectCapacity * (float)m_scene.RegionInfo.RegionSettings.ObjectBonus); return (int)Math.Round(((float)LandData.Area / 65536.0f) * (float)m_scene.RegionInfo.ObjectCapacity * (float)m_scene.RegionInfo.RegionSettings.ObjectBonus);
} }
} }
public int GetSimulatorMaxPrimCount(ILandObject thisObject) public int GetSimulatorMaxPrimCount(ILandObject thisObject)
@ -158,7 +158,7 @@ namespace OpenSim.Region.CoreModules.World.Land
else else
{ {
//Normal Calculations //Normal Calculations
return m_scene.objectCapacity; return m_scene.RegionInfo.ObjectCapacity;
} }
} }
#endregion #endregion

View File

@ -70,10 +70,8 @@ namespace OpenSim.Region.CoreModules.World.WorldMap
#region IMapImageGenerator Members #region IMapImageGenerator Members
public byte[] WriteJpeg2000Image(string gradientmap) public Bitmap CreateMapTile(string gradientmap)
{ {
byte[] imageData = null;
bool drawPrimVolume = true; bool drawPrimVolume = true;
bool textureTerrain = false; bool textureTerrain = false;
@ -98,8 +96,7 @@ namespace OpenSim.Region.CoreModules.World.WorldMap
} }
terrainRenderer.Initialise(m_scene, m_config); terrainRenderer.Initialise(m_scene, m_config);
using (Bitmap mapbmp = new Bitmap((int)Constants.RegionSize, (int)Constants.RegionSize)) Bitmap mapbmp = new Bitmap((int)Constants.RegionSize, (int)Constants.RegionSize, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
{
//long t = System.Environment.TickCount; //long t = System.Environment.TickCount;
//for (int i = 0; i < 10; ++i) { //for (int i = 0; i < 10; ++i) {
terrainRenderer.TerrainToBitmap(mapbmp); terrainRenderer.TerrainToBitmap(mapbmp);
@ -113,17 +110,22 @@ namespace OpenSim.Region.CoreModules.World.WorldMap
DrawObjectVolume(m_scene, mapbmp); DrawObjectVolume(m_scene, mapbmp);
} }
return mapbmp;
}
public byte[] WriteJpeg2000Image(string gradientmap)
{
try try
{ {
imageData = OpenJPEG.EncodeFromImage(mapbmp, true); using (Bitmap mapbmp = CreateMapTile(gradientmap))
return OpenJPEG.EncodeFromImage(mapbmp, true);
} }
catch (Exception e) // LEGIT: Catching problems caused by OpenJPEG p/invoke catch (Exception e) // LEGIT: Catching problems caused by OpenJPEG p/invoke
{ {
m_log.Error("Failed generating terrain map: " + e); m_log.Error("Failed generating terrain map: " + e);
} }
}
return imageData; return null;
} }
#endregion #endregion

View File

@ -37,6 +37,8 @@ namespace OpenSim.Region.CoreModules.World.WorldMap
{ {
public class ShadedMapTileRenderer : IMapTileTerrainRenderer public class ShadedMapTileRenderer : IMapTileTerrainRenderer
{ {
private static readonly Color WATER_COLOR = Color.FromArgb(29, 71, 95);
private static readonly ILog m_log = private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
@ -221,8 +223,7 @@ namespace OpenSim.Region.CoreModules.World.WorldMap
try try
{ {
Color water = Color.FromArgb((int)heightvalue, (int)heightvalue, 255); mapbmp.SetPixel(x, yr, WATER_COLOR);
mapbmp.SetPixel(x, yr, water);
} }
catch (ArgumentException) catch (ArgumentException)
{ {

View File

@ -136,6 +136,8 @@ namespace OpenSim.Region.CoreModules.World.WorldMap
private static readonly UUID defaultTerrainTexture4 = new UUID("53a2f406-4895-1d13-d541-d2e3b86bc19c"); private static readonly UUID defaultTerrainTexture4 = new UUID("53a2f406-4895-1d13-d541-d2e3b86bc19c");
private static readonly Color defaultColor4 = Color.FromArgb(200, 200, 200); private static readonly Color defaultColor4 = Color.FromArgb(200, 200, 200);
private static readonly Color WATER_COLOR = Color.FromArgb(29, 71, 95);
#endregion #endregion
@ -406,8 +408,7 @@ namespace OpenSim.Region.CoreModules.World.WorldMap
heightvalue = 100f - (heightvalue * 100f) / 19f; // 0 - 19 => 100 - 0 heightvalue = 100f - (heightvalue * 100f) / 19f; // 0 - 19 => 100 - 0
Color water = Color.FromArgb((int)heightvalue, (int)heightvalue, 255); mapbmp.SetPixel(x, yr, WATER_COLOR);
mapbmp.SetPixel(x, yr, water);
} }
} }
} }

View File

@ -805,7 +805,7 @@ namespace OpenSim.Region.CoreModules.World.WorldMap
imgstream = new MemoryStream(); imgstream = new MemoryStream();
// non-async because we know we have the asset immediately. // non-async because we know we have the asset immediately.
AssetBase mapasset = m_scene.AssetService.Get(m_scene.RegionInfo.lastMapUUID.ToString()); AssetBase mapasset = m_scene.AssetService.Get(m_scene.RegionInfo.RegionSettings.TerrainImageID.ToString());
// Decode image to System.Drawing.Image // Decode image to System.Drawing.Image
if (OpenJPEG.DecodeToImage(mapasset.Data, out managedImage, out image)) if (OpenJPEG.DecodeToImage(mapasset.Data, out managedImage, out image))
@ -1002,41 +1002,15 @@ namespace OpenSim.Region.CoreModules.World.WorldMap
public void RegenerateMaptile(byte[] data) public void RegenerateMaptile(byte[] data)
{ {
// Overwrites the local Asset cache with new maptile data
// Assets are single write, this causes the asset server to ignore this update,
// but the local asset cache does not
// this is on purpose! The net result of this is the region always has the most up to date
// map tile while protecting the (grid) asset database from bloat caused by a new asset each
// time a mapimage is generated!
UUID lastMapRegionUUID = m_scene.RegionInfo.RegionSettings.TerrainImageID; UUID lastMapRegionUUID = m_scene.RegionInfo.RegionSettings.TerrainImageID;
int lastMapRefresh = 0;
int twoDays = 172800;
// int RefreshSeconds = twoDays;
try
{
lastMapRefresh = Convert.ToInt32(m_scene.RegionInfo.lastMapRefresh);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
m_log.Debug("[MAPTILE]: STORING MAPTILE IMAGE"); m_log.Debug("[MAPTILE]: STORING MAPTILE IMAGE");
m_scene.RegionInfo.RegionSettings.TerrainImageID = UUID.Random(); m_scene.RegionInfo.RegionSettings.TerrainImageID = UUID.Random();
AssetBase asset = new AssetBase( AssetBase asset = new AssetBase(
m_scene.RegionInfo.RegionSettings.TerrainImageID, m_scene.RegionInfo.RegionSettings.TerrainImageID,
"terrainImage_" + m_scene.RegionInfo.RegionID.ToString() + "_" + lastMapRefresh.ToString(), "terrainImage_" + m_scene.RegionInfo.RegionID.ToString(),
(sbyte)AssetType.Texture, (sbyte)AssetType.Texture,
m_scene.RegionInfo.RegionID.ToString()); m_scene.RegionInfo.RegionID.ToString());
asset.Data = data; asset.Data = data;

View File

@ -73,7 +73,7 @@ namespace OpenSim.Region.DataSnapshot.Providers
client.OnGrabUpdate += delegate(UUID objectID, Vector3 offset, Vector3 grapPos, client.OnGrabUpdate += delegate(UUID objectID, Vector3 offset, Vector3 grapPos,
IClientAPI remoteClient, List<SurfaceTouchEventArgs> surfaceArgs) { this.Stale = true; }; IClientAPI remoteClient, List<SurfaceTouchEventArgs> surfaceArgs) { this.Stale = true; };
client.OnObjectAttach += delegate(IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, client.OnObjectAttach += delegate(IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt,
Quaternion rot, bool silent) { this.Stale = true; }; bool silent) { this.Stale = true; };
client.OnObjectDuplicate += delegate(uint localID, Vector3 offset, uint dupeFlags, UUID AgentID, client.OnObjectDuplicate += delegate(uint localID, Vector3 offset, uint dupeFlags, UUID AgentID,
UUID GroupID) { this.Stale = true; }; UUID GroupID) { this.Stale = true; };
client.OnObjectDuplicateOnRay += delegate(uint localID, uint dupeFlags, UUID AgentID, UUID GroupID, client.OnObjectDuplicateOnRay += delegate(uint localID, uint dupeFlags, UUID AgentID, UUID GroupID,

View File

@ -258,22 +258,17 @@ namespace OpenSim.Region.DataSnapshot
private String GetRegionCategory(Scene scene) private String GetRegionCategory(Scene scene)
{ {
//Boolean choice between: if (scene.RegionInfo.RegionSettings.Maturity == 0)
// "PG" - Mormontown
// "Mature" - Sodom and Gomorrah
if (scene.RegionInfo.RegionSettings.Maturity == 1)
{
return "Mature";
}
else if (scene.RegionInfo.RegionSettings.Maturity == 0)
{
return "PG"; return "PG";
}
else if (scene.RegionInfo.RegionSettings.Maturity == 1)
{ return "Mature";
if (scene.RegionInfo.RegionSettings.Maturity == 2)
return "Adult";
return "Unknown"; return "Unknown";
} }
}
private XmlNode GetGridSnapshotData(XmlDocument factory) private XmlNode GetGridSnapshotData(XmlDocument factory)
{ {

View File

@ -544,10 +544,6 @@ namespace OpenSim.Region.Examples.SimpleModule
{ {
} }
public virtual void AttachObject(uint localID, Quaternion rotation, byte attachPoint, UUID ownerID)
{
}
public virtual void SendDialog(string objectname, UUID objectID, string ownerFirstName, string ownerLastName, string msg, UUID textureID, int ch, string[] buttonlabels) public virtual void SendDialog(string objectname, UUID objectID, string ownerFirstName, string ownerLastName, string msg, UUID textureID, int ch, string[] buttonlabels)
{ {
} }
@ -1163,5 +1159,9 @@ namespace OpenSim.Region.Examples.SimpleModule
public void SendTextBoxRequest(string message, int chatChannel, string objectname, string ownerFirstName, string ownerLastName, UUID objectId) public void SendTextBoxRequest(string message, int chatChannel, string objectname, string ownerFirstName, string ownerLastName, UUID objectId)
{ {
} }
public void StopFlying(ISceneEntity presence)
{
}
} }
} }

View File

@ -44,7 +44,7 @@ namespace OpenSim.Region.Framework.Interfaces
/// <param name="rot"></param> /// <param name="rot"></param>
/// <param name="silent"></param> /// <param name="silent"></param>
void AttachObject( void AttachObject(
IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, Quaternion rot, bool silent); IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, bool silent);
/// <summary> /// <summary>
/// Attach an object to an avatar. /// Attach an object to an avatar.
@ -57,7 +57,7 @@ namespace OpenSim.Region.Framework.Interfaces
/// <param name="silent"></param> /// <param name="silent"></param>
/// <returns>true if the object was successfully attached, false otherwise</returns> /// <returns>true if the object was successfully attached, false otherwise</returns>
bool AttachObject( bool AttachObject(
IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, Quaternion rot, Vector3 attachPos, bool silent); IClientAPI remoteClient, SceneObjectGroup grp, uint AttachmentPt, bool silent);
/// <summary> /// <summary>
/// Rez an attachment from user inventory and change inventory status to match. /// Rez an attachment from user inventory and change inventory status to match.

View File

@ -38,7 +38,7 @@ namespace OpenSim.Region.Framework.Interfaces
public int numLeft; public int numLeft;
} }
public interface IEmailModule : IRegionModule public interface IEmailModule
{ {
void SendEmail(UUID objectID, string address, string subject, string body); void SendEmail(UUID objectID, string address, string subject, string body);
Email GetNextEmail(UUID objectID, string sender, string subject); Email GetNextEmail(UUID objectID, string sender, string subject);

View File

@ -43,5 +43,9 @@ namespace OpenSim.Region.Framework.Interfaces
UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection, UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection,
bool RezSelected, bool RemoveItem, UUID fromTaskID, bool attachment); bool RezSelected, bool RemoveItem, UUID fromTaskID, bool attachment);
void TransferInventoryAssets(InventoryItemBase item, UUID sender, UUID receiver); void TransferInventoryAssets(InventoryItemBase item, UUID sender, UUID receiver);
bool GetAgentInventoryItem(IClientAPI remoteClient, UUID itemID, UUID requestID);
// Must be here because of textures in user's inventory
bool IsForeignUser(UUID userID, out string assetServerURL);
} }
} }

View File

@ -26,6 +26,7 @@
*/ */
using System; using System;
using System.Collections.Generic;
using System.IO; using System.IO;
using OpenSim.Services.Interfaces; using OpenSim.Services.Interfaces;
@ -60,6 +61,20 @@ namespace OpenSim.Region.Framework.Interfaces
/// <returns>true if the first stage of the operation succeeded, false otherwise</returns> /// <returns>true if the first stage of the operation succeeded, false otherwise</returns>
bool DearchiveInventory(string firstName, string lastName, string invPath, string pass, Stream loadStream); bool DearchiveInventory(string firstName, string lastName, string invPath, string pass, Stream loadStream);
/// <summary>
/// Dearchive a user's inventory folder from the given stream
/// </summary>
/// <param name="firstName"></param>
/// <param name="lastName"></param>
/// <param name="invPath">The inventory path in which to place the loaded folders and items</param>
/// <param name="loadStream">The stream from which the inventory archive will be loaded</param>
/// <param name="options">Dearchiving options. At the moment, the only option is ("merge", true). This merges
/// the loaded IAR with existing folders where possible.</param>
/// <returns>true if the first stage of the operation succeeded, false otherwise</returns>
bool DearchiveInventory(
string firstName, string lastName, string invPath, string pass, Stream loadStream,
Dictionary<string, object> options);
/// <summary> /// <summary>
/// Archive a user's inventory folder to the given stream /// Archive a user's inventory folder to the given stream
/// </summary> /// </summary>
@ -70,5 +85,19 @@ namespace OpenSim.Region.Framework.Interfaces
/// <param name="saveStream">The stream to which the inventory archive will be saved</param> /// <param name="saveStream">The stream to which the inventory archive will be saved</param>
/// <returns>true if the first stage of the operation succeeded, false otherwise</returns> /// <returns>true if the first stage of the operation succeeded, false otherwise</returns>
bool ArchiveInventory(Guid id, string firstName, string lastName, string invPath, string pass, Stream saveStream); bool ArchiveInventory(Guid id, string firstName, string lastName, string invPath, string pass, Stream saveStream);
/// <summary>
/// Archive a user's inventory folder to the given stream
/// </summary>
/// <param name="id">ID representing this request. This will later be returned in the save event</param>
/// <param name="firstName"></param>
/// <param name="lastName"></param>
/// <param name="invPath">The inventory path from which the inventory should be saved.</param>
/// <param name="saveStream">The stream to which the inventory archive will be saved</param>
/// <param name="options">Archiving options. Currently, there are none.</param>
/// <returns>true if the first stage of the operation succeeded, false otherwise</returns>
bool ArchiveInventory(
Guid id, string firstName, string lastName, string invPath, string pass, Stream saveStream,
Dictionary<string, object> options);
} }
} }

View File

@ -36,5 +36,6 @@ namespace OpenSim.Region.Framework.Interfaces
bool Active { get; } bool Active { get; }
bool Synced { get; } bool Synced { get; }
void SendCoarseLocations(); void SendCoarseLocations();
void IncomingLoadBalanceConnection(ScenePresence presence);
} }
} }

View File

@ -73,6 +73,7 @@ namespace OpenSim.Region.Framework.Interfaces
public interface IMapImageGenerator public interface IMapImageGenerator
{ {
System.Drawing.Bitmap CreateMapTile(string gradientmap);
byte[] WriteJpeg2000Image(string gradientmap); byte[] WriteJpeg2000Image(string gradientmap);
} }
} }

View File

@ -179,7 +179,7 @@ namespace OpenSim.Region.Framework.Scenes
public event ScriptChangedEvent OnScriptChangedEvent; public event ScriptChangedEvent OnScriptChangedEvent;
public delegate void ScriptChangedEvent(uint localID, uint change); public delegate void ScriptChangedEvent(uint localID, uint change);
public delegate void ScriptControlEvent(uint localID, UUID item, UUID avatarID, uint held, uint changed); public delegate void ScriptControlEvent(UUID item, UUID avatarID, uint held, uint changed);
public event ScriptControlEvent OnScriptControlEvent; public event ScriptControlEvent OnScriptControlEvent;
public delegate void ScriptAtTargetEvent(uint localID, uint handle, Vector3 targetpos, Vector3 atpos); public delegate void ScriptAtTargetEvent(uint localID, uint handle, Vector3 targetpos, Vector3 atpos);
@ -1595,7 +1595,7 @@ namespace OpenSim.Region.Framework.Scenes
} }
} }
internal void TriggerControlEvent(uint p, UUID scriptUUID, UUID avatarID, uint held, uint _changed) internal void TriggerControlEvent(UUID scriptUUID, UUID avatarID, uint held, uint _changed)
{ {
ScriptControlEvent handlerScriptControlEvent = OnScriptControlEvent; ScriptControlEvent handlerScriptControlEvent = OnScriptControlEvent;
if (handlerScriptControlEvent != null) if (handlerScriptControlEvent != null)
@ -1604,7 +1604,7 @@ namespace OpenSim.Region.Framework.Scenes
{ {
try try
{ {
d(p, scriptUUID, avatarID, held, _changed); d(scriptUUID, avatarID, held, _changed);
} }
catch (Exception e) catch (Exception e)
{ {

View File

@ -1,4 +1,4 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using log4net; using log4net;
using Nini.Config; using Nini.Config;
@ -33,6 +33,15 @@ namespace OpenSim.Region.Framework.Scenes
{ {
private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// This is added to the priority of all child prims, to make sure that the root prim update is sent to the
/// viewer before child prim updates.
/// The adjustment is added to child prims and subtracted from root prims, so the gap ends up
/// being double. We do it both ways so that there is a still a priority delta even if the priority is already
/// double.MinValue or double.MaxValue.
/// </summary>
private double m_childPrimAdjustmentFactor = 0.05;
private Scene m_scene; private Scene m_scene;
public Prioritizer(Scene scene) public Prioritizer(Scene scene)
@ -42,21 +51,53 @@ namespace OpenSim.Region.Framework.Scenes
public double GetUpdatePriority(IClientAPI client, ISceneEntity entity) public double GetUpdatePriority(IClientAPI client, ISceneEntity entity)
{ {
double priority = 0;
if (entity == null)
return 100000;
switch (m_scene.UpdatePrioritizationScheme) switch (m_scene.UpdatePrioritizationScheme)
{ {
case UpdatePrioritizationSchemes.Time: case UpdatePrioritizationSchemes.Time:
return GetPriorityByTime(); priority = GetPriorityByTime();
break;
case UpdatePrioritizationSchemes.Distance: case UpdatePrioritizationSchemes.Distance:
return GetPriorityByDistance(client, entity); priority = GetPriorityByDistance(client, entity);
break;
case UpdatePrioritizationSchemes.SimpleAngularDistance: case UpdatePrioritizationSchemes.SimpleAngularDistance:
return GetPriorityByDistance(client, entity); // TODO: Reimplement SimpleAngularDistance priority = GetPriorityByDistance(client, entity); // TODO: Reimplement SimpleAngularDistance
break;
case UpdatePrioritizationSchemes.FrontBack: case UpdatePrioritizationSchemes.FrontBack:
return GetPriorityByFrontBack(client, entity); priority = GetPriorityByFrontBack(client, entity);
break;
case UpdatePrioritizationSchemes.BestAvatarResponsiveness: case UpdatePrioritizationSchemes.BestAvatarResponsiveness:
return GetPriorityByBestAvatarResponsiveness(client, entity); priority = GetPriorityByBestAvatarResponsiveness(client, entity);
break;
default: default:
throw new InvalidOperationException("UpdatePrioritizationScheme not defined."); throw new InvalidOperationException("UpdatePrioritizationScheme not defined.");
break;
} }
// Adjust priority so that root prims are sent to the viewer first. This is especially important for
// attachments acting as huds, since current viewers fail to display hud child prims if their updates
// arrive before the root one.
if (entity is SceneObjectPart)
{
SceneObjectPart sop = ((SceneObjectPart)entity);
if (sop.IsRoot)
{
if (priority >= double.MinValue + m_childPrimAdjustmentFactor)
priority -= m_childPrimAdjustmentFactor;
}
else
{
if (priority <= double.MaxValue - m_childPrimAdjustmentFactor)
priority += m_childPrimAdjustmentFactor;
}
}
return priority;
} }
private double GetPriorityByTime() private double GetPriorityByTime()
@ -173,6 +214,9 @@ namespace OpenSim.Region.Framework.Scenes
PhysicsActor physActor = ((SceneObjectPart)entity).ParentGroup.RootPart.PhysActor; PhysicsActor physActor = ((SceneObjectPart)entity).ParentGroup.RootPart.PhysActor;
if (physActor == null || !physActor.IsPhysical) if (physActor == null || !physActor.IsPhysical)
priority += 100; priority += 100;
if (((SceneObjectPart)entity).ParentGroup.RootPart.IsAttachment)
priority = 1.0;
} }
return priority; return priority;
} }

View File

@ -73,7 +73,7 @@ namespace OpenSim.Region.Framework.Scenes
IMoneyModule money=RequestModuleInterface<IMoneyModule>(); IMoneyModule money=RequestModuleInterface<IMoneyModule>();
if (money != null) if (money != null)
{ {
money.ApplyUploadCharge(agentID); money.ApplyUploadCharge(agentID, money.UploadCharge, "Asset upload");
} }
AddInventoryItem(agentID, item); AddInventoryItem(agentID, item);
@ -203,7 +203,7 @@ namespace OpenSim.Region.Framework.Scenes
// Update item with new asset // Update item with new asset
item.AssetID = asset.FullID; item.AssetID = asset.FullID;
if (group.UpdateInventoryItem(item)) if (group.UpdateInventoryItem(item))
remoteClient.SendAgentAlertMessage("Notecard saved", false); remoteClient.SendAgentAlertMessage("Script saved", false);
part.GetProperties(remoteClient); part.GetProperties(remoteClient);
@ -265,6 +265,10 @@ namespace OpenSim.Region.Framework.Scenes
public void UpdateInventoryItemAsset(IClientAPI remoteClient, UUID transactionID, public void UpdateInventoryItemAsset(IClientAPI remoteClient, UUID transactionID,
UUID itemID, InventoryItemBase itemUpd) UUID itemID, InventoryItemBase itemUpd)
{ {
// This one will let people set next perms on items in agent
// inventory. Rut-Roh. Whatever. Make this secure. Yeah.
//
// Passing something to another avatar or a an object will already
InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId); InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId);
item = InventoryService.GetItem(item); item = InventoryService.GetItem(item);
@ -274,11 +278,9 @@ namespace OpenSim.Region.Framework.Scenes
{ {
item.Name = itemUpd.Name; item.Name = itemUpd.Name;
item.Description = itemUpd.Description; item.Description = itemUpd.Description;
item.NextPermissions = itemUpd.NextPermissions; item.NextPermissions = itemUpd.NextPermissions & item.BasePermissions;
item.CurrentPermissions |= 8; // Slam! item.EveryOnePermissions = itemUpd.EveryOnePermissions & item.BasePermissions;
item.EveryOnePermissions = itemUpd.EveryOnePermissions; item.GroupPermissions = itemUpd.GroupPermissions & item.BasePermissions;
item.GroupPermissions = itemUpd.GroupPermissions;
item.GroupID = itemUpd.GroupID; item.GroupID = itemUpd.GroupID;
item.GroupOwned = itemUpd.GroupOwned; item.GroupOwned = itemUpd.GroupOwned;
item.CreationDate = itemUpd.CreationDate; item.CreationDate = itemUpd.CreationDate;
@ -384,28 +386,103 @@ namespace OpenSim.Region.Framework.Scenes
if (Permissions.PropagatePermissions() && recipient != senderId) if (Permissions.PropagatePermissions() && recipient != senderId)
{ {
// First, make sore base is limited to the next perms // Trying to do this right this time. This is evil. If
itemCopy.BasePermissions = item.BasePermissions & item.NextPermissions; // you believe in Good, go elsewhere. Vampires and other
// By default, current equals base // evil creatores only beyond this point. You have been
itemCopy.CurrentPermissions = itemCopy.BasePermissions; // warned.
// If this is an object, replace current perms // We're going to mask a lot of things by the next perms
// with folded perms // Tweak the next perms to be nicer to our data
//
// In this mask, all the bits we do NOT want to mess
// with are set. These are:
//
// Transfer
// Copy
// Modufy
uint permsMask = ~ ((uint)PermissionMask.Copy |
(uint)PermissionMask.Transfer |
(uint)PermissionMask.Modify);
// Now, reduce the next perms to the mask bits
// relevant to the operation
uint nextPerms = permsMask | (item.NextPermissions &
((uint)PermissionMask.Copy |
(uint)PermissionMask.Transfer |
(uint)PermissionMask.Modify));
// nextPerms now has all bits set, except for the actual
// next permission bits.
// This checks for no mod, no copy, no trans.
// This indicates an error or messed up item. Do it like
// SL and assume trans
if (nextPerms == permsMask)
nextPerms |= (uint)PermissionMask.Transfer;
// Inventory owner perms are the logical AND of the
// folded perms and the root prim perms, however, if
// the root prim is mod, the inventory perms will be
// mod. This happens on "take" and is of little concern
// here, save for preventing escalation
// This hack ensures that items previously permalocked
// get unlocked when they're passed or rezzed
uint basePerms = item.BasePermissions |
(uint)PermissionMask.Move;
uint ownerPerms = item.CurrentPermissions;
// If this is an object, root prim perms may be more
// permissive than folded perms. Use folded perms as
// a mask
if (item.InvType == (int)InventoryType.Object) if (item.InvType == (int)InventoryType.Object)
{ {
itemCopy.CurrentPermissions &= ~(uint)(PermissionMask.Copy | PermissionMask.Modify | PermissionMask.Transfer); // Create a safe mask for the current perms
itemCopy.CurrentPermissions |= (item.CurrentPermissions & 7) << 13; uint foldedPerms = (item.CurrentPermissions & 7) << 13;
foldedPerms |= permsMask;
bool isRootMod = (item.CurrentPermissions &
(uint)PermissionMask.Modify) != 0 ?
true : false;
// Mask the owner perms to the folded perms
ownerPerms &= foldedPerms;
basePerms &= foldedPerms;
// If the root was mod, let the mask reflect that
// We also need to adjust the base here, because
// we should be able to edit in-inventory perms
// for the root prim, if it's mod.
if (isRootMod)
{
ownerPerms |= (uint)PermissionMask.Modify;
basePerms |= (uint)PermissionMask.Modify;
}
} }
// Ensure there is no escalation // These will be applied to the root prim at next rez.
itemCopy.CurrentPermissions &= item.NextPermissions; // The slam bit (bit 3) and folded permission (bits 0-2)
// are preserved due to the above mangling
ownerPerms &= nextPerms;
// Need slam bit on xfer // Mask the base permissions. This is a conservative
itemCopy.CurrentPermissions |= 8; // approach altering only the three main perms
basePerms &= nextPerms;
// Assign to the actual item. Make sure the slam bit is
// set, if it wasn't set before.
itemCopy.BasePermissions = basePerms;
itemCopy.CurrentPermissions = ownerPerms | 16; // Slam
itemCopy.NextPermissions = item.NextPermissions; itemCopy.NextPermissions = item.NextPermissions;
itemCopy.EveryOnePermissions = 0; // This preserves "everyone can move"
itemCopy.EveryOnePermissions = item.EveryOnePermissions &
nextPerms;
// Intentionally killing "share with group" here, as
// the recipient will not have the group this is
// set to
itemCopy.GroupPermissions = 0; itemCopy.GroupPermissions = 0;
} }
else else
@ -897,14 +974,15 @@ namespace OpenSim.Region.Framework.Scenes
if ((part.OwnerID != destAgent) && Permissions.PropagatePermissions()) if ((part.OwnerID != destAgent) && Permissions.PropagatePermissions())
{ {
agentItem.BasePermissions = taskItem.BasePermissions & taskItem.NextPermissions; agentItem.BasePermissions = taskItem.BasePermissions & (taskItem.NextPermissions | (uint)PermissionMask.Move);
if (taskItem.InvType == (int)InventoryType.Object) if (taskItem.InvType == (int)InventoryType.Object)
agentItem.CurrentPermissions = agentItem.BasePermissions & ((taskItem.CurrentPermissions & 7) << 13); agentItem.CurrentPermissions = agentItem.BasePermissions & (((taskItem.CurrentPermissions & 7) << 13) | (taskItem.CurrentPermissions & (uint)PermissionMask.Move));
agentItem.CurrentPermissions = agentItem.BasePermissions ; else
agentItem.CurrentPermissions = agentItem.BasePermissions & taskItem.CurrentPermissions;
agentItem.CurrentPermissions |= 8; agentItem.CurrentPermissions |= 16; // Slam
agentItem.NextPermissions = taskItem.NextPermissions; agentItem.NextPermissions = taskItem.NextPermissions;
agentItem.EveryOnePermissions = taskItem.EveryonePermissions & taskItem.NextPermissions; agentItem.EveryOnePermissions = taskItem.EveryonePermissions & (taskItem.NextPermissions | (uint)PermissionMask.Move);
agentItem.GroupPermissions = taskItem.GroupPermissions & taskItem.NextPermissions; agentItem.GroupPermissions = taskItem.GroupPermissions & taskItem.NextPermissions;
} }
else else
@ -1086,14 +1164,14 @@ namespace OpenSim.Region.Framework.Scenes
if (Permissions.PropagatePermissions()) if (Permissions.PropagatePermissions())
{ {
destTaskItem.CurrentPermissions = srcTaskItem.CurrentPermissions & destTaskItem.CurrentPermissions = srcTaskItem.CurrentPermissions &
srcTaskItem.NextPermissions; (srcTaskItem.NextPermissions | (uint)PermissionMask.Move);
destTaskItem.GroupPermissions = srcTaskItem.GroupPermissions & destTaskItem.GroupPermissions = srcTaskItem.GroupPermissions &
srcTaskItem.NextPermissions; (srcTaskItem.NextPermissions | (uint)PermissionMask.Move);
destTaskItem.EveryonePermissions = srcTaskItem.EveryonePermissions & destTaskItem.EveryonePermissions = srcTaskItem.EveryonePermissions &
srcTaskItem.NextPermissions; (srcTaskItem.NextPermissions | (uint)PermissionMask.Move);
destTaskItem.BasePermissions = srcTaskItem.BasePermissions & destTaskItem.BasePermissions = srcTaskItem.BasePermissions &
srcTaskItem.NextPermissions; (srcTaskItem.NextPermissions | (uint)PermissionMask.Move);
destTaskItem.CurrentPermissions |= 8; // Slam! destTaskItem.CurrentPermissions |= 16; // Slam!
} }
} }
@ -1265,7 +1343,13 @@ namespace OpenSim.Region.Framework.Scenes
} }
if (part.Inventory.UpdateInventoryItem(itemInfo)) if (part.Inventory.UpdateInventoryItem(itemInfo))
{ {
if ((InventoryType)itemInfo.InvType == InventoryType.Notecard)
remoteClient.SendAgentAlertMessage("Notecard saved", false); remoteClient.SendAgentAlertMessage("Notecard saved", false);
else if ((InventoryType)itemInfo.InvType == InventoryType.LSL)
remoteClient.SendAgentAlertMessage("Script saved", false);
else
remoteClient.SendAgentAlertMessage("Item saved", false);
part.GetProperties(remoteClient); part.GetProperties(remoteClient);
} }
} }
@ -1477,7 +1561,7 @@ namespace OpenSim.Region.Framework.Scenes
srcTaskItem.NextPermissions; srcTaskItem.NextPermissions;
destTaskItem.BasePermissions = srcTaskItem.BasePermissions & destTaskItem.BasePermissions = srcTaskItem.BasePermissions &
srcTaskItem.NextPermissions; srcTaskItem.NextPermissions;
destTaskItem.CurrentPermissions |= 8; // Slam! destTaskItem.CurrentPermissions |= 16; // Slam!
} }
} }
@ -1573,6 +1657,17 @@ namespace OpenSim.Region.Framework.Scenes
// for when deleting the object from it // for when deleting the object from it
ForceSceneObjectBackup(grp); ForceSceneObjectBackup(grp);
if (remoteClient == null)
{
// Autoreturn has a null client. Nothing else does. So
// allow only returns
if (action != DeRezAction.Return)
return;
permissionToTakeCopy = false;
}
else
{
if (!Permissions.CanTakeCopyObject(grp.UUID, remoteClient.AgentId)) if (!Permissions.CanTakeCopyObject(grp.UUID, remoteClient.AgentId))
permissionToTakeCopy = false; permissionToTakeCopy = false;
if (!Permissions.CanTakeObject(grp.UUID, remoteClient.AgentId)) if (!Permissions.CanTakeObject(grp.UUID, remoteClient.AgentId))
@ -1580,11 +1675,12 @@ namespace OpenSim.Region.Framework.Scenes
if (!Permissions.CanDeleteObject(grp.UUID, remoteClient.AgentId)) if (!Permissions.CanDeleteObject(grp.UUID, remoteClient.AgentId))
permissionToDelete = false; permissionToDelete = false;
}
} }
// Handle god perms // Handle god perms
if (Permissions.IsGod(remoteClient.AgentId)) if ((remoteClient != null) && Permissions.IsGod(remoteClient.AgentId))
{ {
permissionToTake = true; permissionToTake = true;
permissionToTakeCopy = true; permissionToTakeCopy = true;
@ -1595,7 +1691,7 @@ namespace OpenSim.Region.Framework.Scenes
if (action == DeRezAction.SaveToExistingUserInventoryItem) if (action == DeRezAction.SaveToExistingUserInventoryItem)
permissionToDelete = false; permissionToDelete = false;
// if we want to take a copy,, we also don't want to delete // if we want to take a copy, we also don't want to delete
// Note: after this point, the permissionToTakeCopy flag // Note: after this point, the permissionToTakeCopy flag
// becomes irrelevant. It already includes the permissionToTake // becomes irrelevant. It already includes the permissionToTake
// permission and after excluding no copy items here, we can // permission and after excluding no copy items here, we can
@ -1606,6 +1702,7 @@ namespace OpenSim.Region.Framework.Scenes
if (!permissionToTakeCopy) if (!permissionToTakeCopy)
return; return;
permissionToTake = true;
// Don't delete // Don't delete
permissionToDelete = false; permissionToDelete = false;
} }
@ -1736,7 +1833,11 @@ namespace OpenSim.Region.Framework.Scenes
item.AssetType = asset.Type; item.AssetType = asset.Type;
item.InvType = (int)InventoryType.Object; item.InvType = (int)InventoryType.Object;
item.Folder = UUID.Zero; // Objects folder! InventoryFolderBase folder = InventoryService.GetFolderForType(remoteClient.AgentId, AssetType.Object);
if (folder != null)
item.Folder = folder.ID;
else // oopsies
item.Folder = UUID.Zero;
if ((remoteClient.AgentId != grp.RootPart.OwnerID) && Permissions.PropagatePermissions()) if ((remoteClient.AgentId != grp.RootPart.OwnerID) && Permissions.PropagatePermissions())
{ {
@ -1846,36 +1947,30 @@ namespace OpenSim.Region.Framework.Scenes
group.SetGroup(sourcePart.GroupID, null); group.SetGroup(sourcePart.GroupID, null);
if (rootPart.OwnerID != item.OwnerID) if ((rootPart.OwnerID != item.OwnerID) || (item.CurrentPermissions & 16) != 0)
{ {
if (Permissions.PropagatePermissions()) if (Permissions.PropagatePermissions())
{
if ((item.CurrentPermissions & 8) != 0)
{ {
foreach (SceneObjectPart part in partList) foreach (SceneObjectPart part in partList)
{ {
part.EveryoneMask = item.EveryonePermissions; part.EveryoneMask = item.EveryonePermissions;
part.NextOwnerMask = item.NextPermissions; part.NextOwnerMask = item.NextPermissions;
} }
}
group.ApplyNextOwnerPermissions(); group.ApplyNextOwnerPermissions();
} }
} }
foreach (SceneObjectPart part in partList) foreach (SceneObjectPart part in partList)
{ {
if (part.OwnerID != item.OwnerID) if ((part.OwnerID != item.OwnerID) || (item.CurrentPermissions & 16) != 0)
{ {
part.LastOwnerID = part.OwnerID; part.LastOwnerID = part.OwnerID;
part.OwnerID = item.OwnerID; part.OwnerID = item.OwnerID;
part.Inventory.ChangeInventoryOwner(item.OwnerID); part.Inventory.ChangeInventoryOwner(item.OwnerID);
} }
else if ((item.CurrentPermissions & 8) != 0) // Slam!
{
part.EveryoneMask = item.EveryonePermissions; part.EveryoneMask = item.EveryonePermissions;
part.NextOwnerMask = item.NextPermissions; part.NextOwnerMask = item.NextPermissions;
} }
}
rootPart.TrimPermissions(); rootPart.TrimPermissions();

View File

@ -375,7 +375,7 @@ namespace OpenSim.Region.Framework.Scenes
private int m_update_backup = 200; private int m_update_backup = 200;
private int m_update_terrain = 50; private int m_update_terrain = 50;
private int m_update_land = 1; private int m_update_land = 1;
private int m_update_coarse_locations = 25; private int m_update_coarse_locations = 50;
private int frameMS; private int frameMS;
private int physicsMS2; private int physicsMS2;
@ -505,8 +505,6 @@ namespace OpenSim.Region.Framework.Scenes
set { m_sceneGraph.RestorePresences = value; } set { m_sceneGraph.RestorePresences = value; }
} }
public int objectCapacity = 45000;
#endregion #endregion
#region BinaryStats #region BinaryStats
@ -714,7 +712,7 @@ namespace OpenSim.Region.Framework.Scenes
StatsReporter.OnSendStatsResult += SendSimStatsPackets; StatsReporter.OnSendStatsResult += SendSimStatsPackets;
StatsReporter.OnStatsIncorrect += m_sceneGraph.RecalculateStats; StatsReporter.OnStatsIncorrect += m_sceneGraph.RecalculateStats;
StatsReporter.SetObjectCapacity(objectCapacity); StatsReporter.SetObjectCapacity(RegionInfo.ObjectCapacity);
// Old // Old
/* /*
@ -980,12 +978,6 @@ namespace OpenSim.Region.Framework.Scenes
// Let the grid service module know, so this can be cached // Let the grid service module know, so this can be cached
m_eventManager.TriggerOnRegionUp(otherRegion); m_eventManager.TriggerOnRegionUp(otherRegion);
RegionInfo regInfo = new RegionInfo(xcell, ycell, otherRegion.InternalEndPoint, otherRegion.ExternalHostName);
regInfo.RegionID = otherRegion.RegionID;
regInfo.RegionName = otherRegion.RegionName;
regInfo.ScopeID = otherRegion.ScopeID;
regInfo.ExternalHostName = otherRegion.ExternalHostName;
GridRegion r = new GridRegion(regInfo);
try try
{ {
ForEachScenePresence(delegate(ScenePresence agent) ForEachScenePresence(delegate(ScenePresence agent)
@ -1000,7 +992,7 @@ namespace OpenSim.Region.Framework.Scenes
old.Add(otherRegion.RegionHandle); old.Add(otherRegion.RegionHandle);
agent.DropOldNeighbours(old); agent.DropOldNeighbours(old);
if (m_teleportModule != null) if (m_teleportModule != null)
m_teleportModule.EnableChildAgent(agent, r); m_teleportModule.EnableChildAgent(agent, otherRegion);
} }
} }
); );
@ -1375,6 +1367,8 @@ namespace OpenSim.Region.Framework.Scenes
m_regInfo.EstateSettings.EstateOwner = account.PrincipalID; m_regInfo.EstateSettings.EstateOwner = account.PrincipalID;
m_regInfo.EstateSettings.Save(); m_regInfo.EstateSettings.Save();
} }
else
m_log.ErrorFormat("[SCENE]: Unable to store account. If this simulator is connected to a grid,\n you must create the estate owner account first.");
} }
else else
{ {
@ -1591,6 +1585,7 @@ namespace OpenSim.Region.Framework.Scenes
{ {
m_log.DebugFormat("[REGION]: Enabling logins for {0}", RegionInfo.RegionName); m_log.DebugFormat("[REGION]: Enabling logins for {0}", RegionInfo.RegionName);
LoginsDisabled = false; LoginsDisabled = false;
m_sceneGridService.InformNeighborsThatRegionisUp(RequestModuleInterface<INeighbourService>(), RegionInfo);
} }
} }
} }
@ -1915,6 +1910,8 @@ namespace OpenSim.Region.Framework.Scenes
{ {
RegisterCommsEvents(); RegisterCommsEvents();
m_sceneGridService.SetScene(this);
// These two 'commands' *must be* next to each other or sim rebooting fails. // These two 'commands' *must be* next to each other or sim rebooting fails.
//m_sceneGridService.RegisterRegion(m_interregionCommsOut, RegionInfo); //m_sceneGridService.RegisterRegion(m_interregionCommsOut, RegionInfo);
@ -1925,24 +1922,6 @@ namespace OpenSim.Region.Framework.Scenes
throw new Exception(error); throw new Exception(error);
} }
m_sceneGridService.SetScene(this);
m_sceneGridService.InformNeighborsThatRegionisUp(RequestModuleInterface<INeighbourService>(), RegionInfo);
//Dictionary<string, string> dGridSettings = m_sceneGridService.GetGridSettings();
//if (dGridSettings.ContainsKey("allow_forceful_banlines"))
//{
// if (dGridSettings["allow_forceful_banlines"] != "TRUE")
// {
// m_log.Info("[GRID]: Grid is disabling forceful parcel banlists");
// EventManager.TriggerSetAllowForcefulBan(false);
// }
// else
// {
// m_log.Info("[GRID]: Grid is allowing forceful parcel banlists");
// EventManager.TriggerSetAllowForcefulBan(true);
// }
//}
} }
/// <summary> /// <summary>
@ -2194,6 +2173,32 @@ namespace OpenSim.Region.Framework.Scenes
return sceneObject; return sceneObject;
} }
/// <summary>
/// Add an object into the scene that has come from storage
/// </summary>
///
/// <param name="sceneObject"></param>
/// <param name="attachToBackup">
/// If true, changes to the object will be reflected in its persisted data
/// If false, the persisted data will not be changed even if the object in the scene is changed
/// </param>
/// <param name="alreadyPersisted">
/// If true, we won't persist this object until it changes
/// If false, we'll persist this object immediately
/// </param>
/// <param name="sendClientUpdates">
/// If true, we send updates to the client to tell it about this object
/// If false, we leave it up to the caller to do this
/// </param>
/// <returns>
/// true if the object was added, false if an object with the same uuid was already in the scene
/// </returns>
public bool AddRestoredSceneObject(
SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted, bool sendClientUpdates)
{
return m_sceneGraph.AddRestoredSceneObject(sceneObject, attachToBackup, alreadyPersisted, sendClientUpdates);
}
/// <summary> /// <summary>
/// Add an object into the scene that has come from storage /// Add an object into the scene that has come from storage
/// </summary> /// </summary>
@ -2213,7 +2218,7 @@ namespace OpenSim.Region.Framework.Scenes
public bool AddRestoredSceneObject( public bool AddRestoredSceneObject(
SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted) SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted)
{ {
return m_sceneGraph.AddRestoredSceneObject(sceneObject, attachToBackup, alreadyPersisted); return AddRestoredSceneObject(sceneObject, attachToBackup, alreadyPersisted, true);
} }
/// <summary> /// <summary>
@ -2567,7 +2572,7 @@ namespace OpenSim.Region.Framework.Scenes
/// <summary> /// <summary>
/// Called when objects or attachments cross the border between regions. /// Called when objects or attachments cross the border, or teleport, between regions.
/// </summary> /// </summary>
/// <param name="sog"></param> /// <param name="sog"></param>
/// <returns></returns> /// <returns></returns>
@ -2593,9 +2598,13 @@ namespace OpenSim.Region.Framework.Scenes
newObject.RootPart.ParentGroup.CreateScriptInstances(0, false, DefaultScriptEngine, 1); newObject.RootPart.ParentGroup.CreateScriptInstances(0, false, DefaultScriptEngine, 1);
newObject.ResumeScripts();
// Do this as late as possible so that listeners have full access to the incoming object // Do this as late as possible so that listeners have full access to the incoming object
EventManager.TriggerOnIncomingSceneObject(newObject); EventManager.TriggerOnIncomingSceneObject(newObject);
TriggerChangedTeleport(newObject);
return true; return true;
} }
@ -2651,7 +2660,10 @@ namespace OpenSim.Region.Framework.Scenes
sceneObject.RootPart.AddFlag(PrimFlags.TemporaryOnRez); sceneObject.RootPart.AddFlag(PrimFlags.TemporaryOnRez);
sceneObject.RootPart.AddFlag(PrimFlags.Phantom); sceneObject.RootPart.AddFlag(PrimFlags.Phantom);
AddRestoredSceneObject(sceneObject, false, false);
// Don't sent a full update here because this will cause full updates to be sent twice for
// attachments on region crossings, resulting in viewer glitches.
AddRestoredSceneObject(sceneObject, false, false, false);
// Handle attachment special case // Handle attachment special case
SceneObjectPart RootPrim = sceneObject.RootPart; SceneObjectPart RootPrim = sceneObject.RootPart;
@ -2659,31 +2671,21 @@ namespace OpenSim.Region.Framework.Scenes
// Fix up attachment Parent Local ID // Fix up attachment Parent Local ID
ScenePresence sp = GetScenePresence(sceneObject.OwnerID); ScenePresence sp = GetScenePresence(sceneObject.OwnerID);
//uint parentLocalID = 0;
if (sp != null) if (sp != null)
{ {
//parentLocalID = sp.LocalId;
//sceneObject.RootPart.IsAttachment = true;
//sceneObject.RootPart.SetParentLocalId(parentLocalID);
SceneObjectGroup grp = sceneObject; SceneObjectGroup grp = sceneObject;
//RootPrim.SetParentLocalId(parentLocalID);
m_log.DebugFormat( m_log.DebugFormat(
"[ATTACHMENT]: Received attachment {0}, inworld asset id {1}", grp.GetFromItemID(), grp.UUID); "[ATTACHMENT]: Received attachment {0}, inworld asset id {1}", grp.GetFromItemID(), grp.UUID);
//grp.SetFromAssetID(grp.RootPart.LastOwnerID);
m_log.DebugFormat( m_log.DebugFormat(
"[ATTACHMENT]: Attach to avatar {0} at position {1}", sp.UUID, grp.AbsolutePosition); "[ATTACHMENT]: Attach to avatar {0} at position {1}", sp.UUID, grp.AbsolutePosition);
if (AttachmentsModule != null)
AttachmentsModule.AttachObject(
sp.ControllingClient, grp.LocalId, (uint)0, grp.GroupRotation, grp.AbsolutePosition, false);
RootPrim.RemFlag(PrimFlags.TemporaryOnRez); RootPrim.RemFlag(PrimFlags.TemporaryOnRez);
grp.SendGroupFullUpdate();
if (AttachmentsModule != null)
AttachmentsModule.AttachObject(sp.ControllingClient, grp, 0, false);
} }
else else
{ {
@ -2711,6 +2713,27 @@ namespace OpenSim.Region.Framework.Scenes
return true; return true;
} }
private void TriggerChangedTeleport(SceneObjectGroup sog)
{
ScenePresence sp = GetScenePresence(sog.OwnerID);
if (sp != null)
{
AgentCircuitData aCircuit = m_authenticateHandler.GetAgentCircuitData(sp.UUID);
if (aCircuit != null && (aCircuit.teleportFlags != (uint)TeleportFlags.Default))
{
// This will get your attention
//m_log.Error("[XXX] Triggering ");
// Trigger CHANGED_TELEPORT
sp.Scene.EventManager.TriggerOnScriptChangedEvent(sog.LocalId, (uint)Changed.TELEPORT);
}
}
}
#endregion #endregion
#region Add/Remove Avatar Methods #region Add/Remove Avatar Methods
@ -3544,6 +3567,8 @@ namespace OpenSim.Region.Framework.Scenes
public bool NewUserConnection(AgentCircuitData agent, uint teleportFlags, out string reason) public bool NewUserConnection(AgentCircuitData agent, uint teleportFlags, out string reason)
{ {
TeleportFlags tp = (TeleportFlags)teleportFlags; TeleportFlags tp = (TeleportFlags)teleportFlags;
reason = String.Empty;
//Teleport flags: //Teleport flags:
// //
// TeleportFlags.ViaGodlikeLure - Border Crossing // TeleportFlags.ViaGodlikeLure - Border Crossing
@ -3551,36 +3576,34 @@ namespace OpenSim.Region.Framework.Scenes
// TeleportFlags.TeleportFlags.ViaLure - Teleport request sent by another user // TeleportFlags.TeleportFlags.ViaLure - Teleport request sent by another user
// TeleportFlags.ViaLandmark | TeleportFlags.ViaLocation | TeleportFlags.ViaLandmark | TeleportFlags.Default - Regular Teleport // TeleportFlags.ViaLandmark | TeleportFlags.ViaLocation | TeleportFlags.ViaLandmark | TeleportFlags.Default - Regular Teleport
if (LoginsDisabled)
{
reason = "Logins Disabled";
return false;
}
// Don't disable this log message - it's too helpful // Don't disable this log message - it's too helpful
m_log.InfoFormat( m_log.InfoFormat(
"[CONNECTION BEGIN]: Region {0} told of incoming {1} agent {2} {3} {4} (circuit code {5}, teleportflags {6})", "[CONNECTION BEGIN]: Region {0} told of incoming {1} agent {2} {3} {4} (circuit code {5}, teleportflags {6})",
RegionInfo.RegionName, (agent.child ? "child" : "root"), agent.firstname, agent.lastname, RegionInfo.RegionName, (agent.child ? "child" : "root"), agent.firstname, agent.lastname,
agent.AgentID, agent.circuitcode, teleportFlags); agent.AgentID, agent.circuitcode, teleportFlags);
reason = String.Empty; if (LoginsDisabled)
if (!VerifyUserPresence(agent, out reason)) {
reason = "Logins Disabled";
return false; return false;
}
if (!AuthorizeUser(agent, out reason)) ScenePresence sp = GetScenePresence(agent.AgentID);
return false;
m_log.InfoFormat( if (sp != null && !sp.IsChildAgent)
"[CONNECTION BEGIN]: Region {0} authenticated and authorized incoming {1} agent {2} {3} {4} (circuit code {5})", {
RegionInfo.RegionName, (agent.child ? "child" : "root"), agent.firstname, agent.lastname, // We have a zombie from a crashed session.
agent.AgentID, agent.circuitcode); // Or the same user is trying to be root twice here, won't work.
// Kill it.
CapsModule.NewUserConnection(agent); m_log.DebugFormat("[SCENE]: Zombie scene presence detected for {0} in {1}", agent.AgentID, RegionInfo.RegionName);
sp.ControllingClient.Close();
sp = null;
}
ILandObject land = LandChannel.GetLandObject(agent.startpos.X, agent.startpos.Y); ILandObject land = LandChannel.GetLandObject(agent.startpos.X, agent.startpos.Y);
//On login or border crossing test land permisions //On login test land permisions
if (tp != TeleportFlags.Default) if (tp == TeleportFlags.ViaLogin)
{ {
if (land != null && !TestLandRestrictions(agent, land, out reason)) if (land != null && !TestLandRestrictions(agent, land, out reason))
{ {
@ -3588,8 +3611,40 @@ namespace OpenSim.Region.Framework.Scenes
} }
} }
ScenePresence sp = GetScenePresence(agent.AgentID); if (sp == null) // We don't have an [child] agent here already
if (sp != null) {
try
{
if (!VerifyUserPresence(agent, out reason))
return false;
}
catch (Exception e)
{
m_log.DebugFormat("[CONNECTION BEGIN]: Exception verifying presence {0}", e.Message);
return false;
}
try
{
if (!AuthorizeUser(agent, out reason))
return false;
}
catch (Exception e)
{
m_log.DebugFormat("[CONNECTION BEGIN]: Exception authorizing user {0}", e.Message);
return false;
}
m_log.InfoFormat(
"[CONNECTION BEGIN]: Region {0} authenticated and authorized incoming {1} agent {2} {3} {4} (circuit code {5})",
RegionInfo.RegionName, (agent.child ? "child" : "root"), agent.firstname, agent.lastname,
agent.AgentID, agent.circuitcode);
CapsModule.NewUserConnection(agent);
CapsModule.AddCapsHandler(agent.AgentID);
}
else
{ {
if (sp.IsChildAgent) if (sp.IsChildAgent)
{ {
@ -3598,20 +3653,16 @@ namespace OpenSim.Region.Framework.Scenes
agent.AgentID, RegionInfo.RegionName); agent.AgentID, RegionInfo.RegionName);
sp.AdjustKnownSeeds(); sp.AdjustKnownSeeds();
CapsModule.NewUserConnection(agent);
return true;
}
else
{
// We have a zombie from a crashed session. Kill it.
m_log.DebugFormat("[SCENE]: Zombie scene presence detected for {0} in {1}", agent.AgentID, RegionInfo.RegionName);
sp.ControllingClient.Close();
} }
} }
CapsModule.AddCapsHandler(agent.AgentID);
if (!agent.child) // In all cases, add or update the circuit data with the new agent circuit data and teleport flags
agent.teleportFlags = teleportFlags;
m_authenticateHandler.AddNewCircuit(agent.circuitcode, agent);
if (tp == TeleportFlags.ViaLogin)
{ {
if (TestBorderCross(agent.startpos, Cardinals.E)) if (TestBorderCross(agent.startpos, Cardinals.E))
{ {
@ -3678,9 +3729,6 @@ namespace OpenSim.Region.Framework.Scenes
} }
} }
agent.teleportFlags = teleportFlags;
m_authenticateHandler.AddNewCircuit(agent.circuitcode, agent);
return true; return true;
} }
@ -3772,6 +3820,8 @@ namespace OpenSim.Region.Framework.Scenes
} }
} }
if (m_regInfo.EstateSettings != null)
{
if (m_regInfo.EstateSettings.IsBanned(agent.AgentID)) if (m_regInfo.EstateSettings.IsBanned(agent.AgentID))
{ {
m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user is on the banlist", m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user is on the banlist",
@ -3780,6 +3830,9 @@ namespace OpenSim.Region.Framework.Scenes
RegionInfo.RegionName); RegionInfo.RegionName);
return false; return false;
} }
}
else
m_log.ErrorFormat("[CONNECTION BEGIN]: Estate Settings is null!");
IGroupsModule groupsModule = IGroupsModule groupsModule =
RequestModuleInterface<IGroupsModule>(); RequestModuleInterface<IGroupsModule>();
@ -3791,13 +3844,20 @@ namespace OpenSim.Region.Framework.Scenes
GroupMembershipData[] GroupMembership = GroupMembershipData[] GroupMembership =
groupsModule.GetMembershipData(agent.AgentID); groupsModule.GetMembershipData(agent.AgentID);
if (GroupMembership != null)
{
for (int i = 0; i < GroupMembership.Length; i++) for (int i = 0; i < GroupMembership.Length; i++)
agentGroups.Add(GroupMembership[i].GroupID); agentGroups.Add(GroupMembership[i].GroupID);
} }
else
m_log.ErrorFormat("[CONNECTION BEGIN]: GroupMembership is null!");
}
bool groupAccess = false; bool groupAccess = false;
UUID[] estateGroups = m_regInfo.EstateSettings.EstateGroups; UUID[] estateGroups = m_regInfo.EstateSettings.EstateGroups;
if (estateGroups != null)
{
foreach (UUID group in estateGroups) foreach (UUID group in estateGroups)
{ {
if (agentGroups.Contains(group)) if (agentGroups.Contains(group))
@ -3806,6 +3866,9 @@ namespace OpenSim.Region.Framework.Scenes
break; break;
} }
} }
}
else
m_log.ErrorFormat("[CONNECTION BEGIN]: EstateGroups is null!");
if (!m_regInfo.EstateSettings.PublicAccess && if (!m_regInfo.EstateSettings.PublicAccess &&
!m_regInfo.EstateSettings.HasAccess(agent.AgentID) && !m_regInfo.EstateSettings.HasAccess(agent.AgentID) &&
@ -3957,6 +4020,8 @@ namespace OpenSim.Region.Framework.Scenes
m_log.DebugFormat( m_log.DebugFormat(
"[SCENE]: Incoming child agent update for {0} in {1}", cAgentData.AgentID, RegionInfo.RegionName); "[SCENE]: Incoming child agent update for {0} in {1}", cAgentData.AgentID, RegionInfo.RegionName);
// XPTO: if this agent is not allowed here as root, always return false
// We have to wait until the viewer contacts this region after receiving EAC. // We have to wait until the viewer contacts this region after receiving EAC.
// That calls AddNewClient, which finally creates the ScenePresence // That calls AddNewClient, which finally creates the ScenePresence
ScenePresence childAgentUpdate = WaitGetScenePresence(cAgentData.AgentID); ScenePresence childAgentUpdate = WaitGetScenePresence(cAgentData.AgentID);
@ -4131,7 +4196,9 @@ namespace OpenSim.Region.Framework.Scenes
// bordercross if position is outside of region // bordercross if position is outside of region
if (!result) if (!result)
{
regionHandle = m_regInfo.RegionHandle; regionHandle = m_regInfo.RegionHandle;
}
else else
{ {
// not in this region, undo the shift! // not in this region, undo the shift!
@ -4188,20 +4255,6 @@ namespace OpenSim.Region.Framework.Scenes
#region Other Methods #region Other Methods
public void SetObjectCapacity(int objects)
{
// Region specific config overrides global
//
if (RegionInfo.ObjectCapacity != 0)
objects = RegionInfo.ObjectCapacity;
if (StatsReporter != null)
{
StatsReporter.SetObjectCapacity(objects);
}
objectCapacity = objects;
}
#endregion #endregion
public void HandleObjectPermissionsUpdate(IClientAPI controller, UUID agentID, UUID sessionID, byte field, uint localId, uint mask, byte set) public void HandleObjectPermissionsUpdate(IClientAPI controller, UUID agentID, UUID sessionID, byte field, uint localId, uint mask, byte set)
@ -4806,7 +4859,7 @@ namespace OpenSim.Region.Framework.Scenes
part.NextOwnerMask; part.NextOwnerMask;
item.GroupPermissions = part.GroupMask & item.GroupPermissions = part.GroupMask &
part.NextOwnerMask; part.NextOwnerMask;
item.CurrentPermissions |= 8; // Slam! item.CurrentPermissions |= 16; // Slam!
item.CreationDate = Util.UnixTimeSinceEpoch(); item.CreationDate = Util.UnixTimeSinceEpoch();
if (InventoryService.AddItem(item)) if (InventoryService.AddItem(item))

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