From 5c7acd0d4d4d4cf1eceb27dadabc051611a9be33 Mon Sep 17 00:00:00 2001 From: Revolution Date: Sun, 14 Feb 2010 19:32:08 -0600 Subject: Fixes a bug in the previous patch. Signed-off-by: Melanie --- OpenSim/Region/Framework/Scenes/ScenePresence.cs | 31 ++++++++++-------------- 1 file changed, 13 insertions(+), 18 deletions(-) diff --git a/OpenSim/Region/Framework/Scenes/ScenePresence.cs b/OpenSim/Region/Framework/Scenes/ScenePresence.cs index 675fb69..7cdea05 100644 --- a/OpenSim/Region/Framework/Scenes/ScenePresence.cs +++ b/OpenSim/Region/Framework/Scenes/ScenePresence.cs @@ -1226,14 +1226,6 @@ namespace OpenSim.Region.Framework.Scenes } else { - if (m_pos.X < 0) - m_pos.X = 128; - if (m_pos.Y < 0) - m_pos.Y = 128; - if (m_pos.X > Scene.WestBorders[0].BorderLine.X) - m_pos.X = 128; - if (m_pos.Y > Scene.NorthBorders[0].BorderLine.Y) - m_pos.Y = 128; m_LastFinitePos = m_pos; } @@ -2799,16 +2791,19 @@ namespace OpenSim.Region.Framework.Scenes { if (!needsTransit) { - Vector3 pos = AbsolutePosition; - if (AbsolutePosition.X < 0) - pos.X += Velocity.Y; - else if (AbsolutePosition.X > Constants.RegionSize) - pos.X -= Velocity.Y; - if (AbsolutePosition.Y < 0) - pos.Y += Velocity.Y; - else if (AbsolutePosition.Y > Constants.RegionSize) - pos.Y -= Velocity.Y; - AbsolutePosition = pos; + if (m_requestedSitTargetUUID == UUID.Zero) + { + Vector3 pos = AbsolutePosition; + if (AbsolutePosition.X < 0) + pos.X += Velocity.X; + else if (AbsolutePosition.X > Constants.RegionSize) + pos.X -= Velocity.X; + if (AbsolutePosition.Y < 0) + pos.Y += Velocity.Y; + else if (AbsolutePosition.Y > Constants.RegionSize) + pos.Y -= Velocity.Y; + AbsolutePosition = pos; + } } } else if (neighbor > 0) -- cgit v1.1 From af265e001d3bf043590e480cd6574a14193f6de0 Mon Sep 17 00:00:00 2001 From: Jeff Ames Date: Mon, 15 Feb 2010 19:15:03 +0900 Subject: Formatting cleanup. --- OpenSim/Framework/AvatarAppearance.cs | 4 +- OpenSim/Framework/Console/LocalConsole.cs | 14 +- OpenSim/Framework/Console/RemoteConsole.cs | 4 +- OpenSim/Region/Application/OpenSim.cs | 7 +- .../Region/ClientStack/LindenUDP/LLClientView.cs | 2 +- .../Region/CoreModules/Asset/CenomeAssetCache.cs | 2 +- .../Asset/LocalAssetServiceConnector.cs | 2 +- .../CoreModules/World/Access/AccessModule.cs | 2 +- .../World/Archiver/Tests/ArchiverTests.cs | 24 +-- .../Framework/Interfaces/IDynamicTextureManager.cs | 2 +- .../Framework/Interfaces/IEntityInventory.cs | 2 +- OpenSim/Region/Framework/Interfaces/IWorldComm.cs | 8 +- OpenSim/Region/Framework/Scenes/EventManager.cs | 172 ++++++++++----------- OpenSim/Region/Framework/Scenes/Scene.cs | 2 +- OpenSim/Region/Framework/Scenes/SceneGraph.cs | 2 +- OpenSim/Region/Framework/Scenes/SceneObjectPart.cs | 2 +- .../Framework/Scenes/SceneObjectPartInventory.cs | 6 +- OpenSim/Region/Framework/Scenes/ScenePresence.cs | 8 +- OpenSim/Region/Physics/OdePlugin/ODEDynamics.cs | 50 +++--- .../Shared/Api/Implementation/LSL_Api.cs | 64 ++++---- OpenSim/Region/ScriptEngine/XEngine/XEngine.cs | 2 +- .../Handlers/Inventory/XInventoryInConnector.cs | 2 +- OpenSim/Services/AssetService/AssetService.cs | 4 +- .../Connectors/Asset/AssetServiceConnector.cs | 2 +- 24 files changed, 193 insertions(+), 196 deletions(-) diff --git a/OpenSim/Framework/AvatarAppearance.cs b/OpenSim/Framework/AvatarAppearance.cs index b2c4d8e..a2a5c84 100644 --- a/OpenSim/Framework/AvatarAppearance.cs +++ b/OpenSim/Framework/AvatarAppearance.cs @@ -69,7 +69,7 @@ namespace OpenSim.Framework private static UUID HAIR_ASSET = new UUID("d342e6c0-b9d2-11dc-95ff-0800200c9a66"); private static UUID HAIR_ITEM = new UUID("d342e6c1-b9d2-11dc-95ff-0800200c9a66"); - public readonly static int VISUALPARAM_COUNT = 218; + public readonly static int VISUALPARAM_COUNT = 218; protected UUID m_owner; @@ -361,7 +361,7 @@ namespace OpenSim.Framework // This sets Visual Params with *less* weirder values then default. Instead of a ugly alien, it looks like a fat scientist SetDefaultParams(m_visualparams); SetDefaultWearables(); - m_texture = GetDefaultTexture(); + m_texture = GetDefaultTexture(); } public AvatarAppearance(UUID avatarID, AvatarWearable[] wearables, byte[] visualParams) diff --git a/OpenSim/Framework/Console/LocalConsole.cs b/OpenSim/Framework/Console/LocalConsole.cs index b7e191b..be936b6 100644 --- a/OpenSim/Framework/Console/LocalConsole.cs +++ b/OpenSim/Framework/Console/LocalConsole.cs @@ -38,7 +38,7 @@ namespace OpenSim.Framework.Console { /// /// A console that uses cursor control and color - /// + /// public class LocalConsole : CommandConsole { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); @@ -100,8 +100,8 @@ namespace OpenSim.Framework.Console private int SetCursorTop(int top) { // From at least mono 2.4.2.3, window resizing can give mono an invalid row and column values. If we try - // to set a cursor row position with a currently invalid column, mono will throw an exception. - // Therefore, we need to make sure that the column position is valid first. + // to set a cursor row position with a currently invalid column, mono will throw an exception. + // Therefore, we need to make sure that the column position is valid first. int left = System.Console.CursorLeft; if (left < 0) @@ -129,12 +129,12 @@ namespace OpenSim.Framework.Console /// /// /// The new cursor column. - /// + /// private int SetCursorLeft(int left) { // From at least mono 2.4.2.3, window resizing can give mono an invalid row and column values. If we try - // to set a cursor column position with a currently invalid row, mono will throw an exception. - // Therefore, we need to make sure that the row position is valid first. + // to set a cursor column position with a currently invalid row, mono will throw an exception. + // Therefore, we need to make sure that the row position is valid first. int top = System.Console.CursorTop; if (top < 0) @@ -183,7 +183,7 @@ namespace OpenSim.Framework.Console System.Console.Write("{0}", prompt); SetCursorTop(new_y); - SetCursorLeft(new_x); + SetCursorLeft(new_x); } } diff --git a/OpenSim/Framework/Console/RemoteConsole.cs b/OpenSim/Framework/Console/RemoteConsole.cs index 9fdd1b8..6f8348d 100644 --- a/OpenSim/Framework/Console/RemoteConsole.cs +++ b/OpenSim/Framework/Console/RemoteConsole.cs @@ -302,9 +302,9 @@ namespace OpenSim.Framework.Console if (!UUID.TryParse(post["ID"].ToString(), out id)) return reply; - lock(m_Connections) + lock (m_Connections) { - if(!m_Connections.ContainsKey(id)) + if (!m_Connections.ContainsKey(id)) return reply; } diff --git a/OpenSim/Region/Application/OpenSim.cs b/OpenSim/Region/Application/OpenSim.cs index a86a831..96eceb0 100755 --- a/OpenSim/Region/Application/OpenSim.cs +++ b/OpenSim/Region/Application/OpenSim.cs @@ -367,7 +367,6 @@ namespace OpenSim m_console.Commands.AddCommand("hypergrid", false, "unlink-region", "unlink-region or : ", "Unlink a hypergrid region", RunCommand); - } public override void ShutdownSpecific() @@ -433,7 +432,7 @@ namespace OpenSim // kick client... if (alert != null) presence.ControllingClient.Kick(alert); - else + else presence.ControllingClient.Kick("\nThe OpenSim manager kicked you out.\n"); // ...and close on our side @@ -640,7 +639,6 @@ namespace OpenSim } } - /// /// Load, Unload, and list Region modules in use /// @@ -972,7 +970,6 @@ namespace OpenSim scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY, scene.RegionInfo.InternalEndPoint.Port)); - }); break; @@ -1097,7 +1094,7 @@ namespace OpenSim } else { - MainConsole.Instance.Output(string.Format("A user with the name {0} {1} already exists!", firstName, lastName)); + MainConsole.Instance.Output(string.Format("A user with the name {0} {1} already exists!", firstName, lastName)); } } diff --git a/OpenSim/Region/ClientStack/LindenUDP/LLClientView.cs b/OpenSim/Region/ClientStack/LindenUDP/LLClientView.cs index 9fe61a7..6cc0bd2 100644 --- a/OpenSim/Region/ClientStack/LindenUDP/LLClientView.cs +++ b/OpenSim/Region/ClientStack/LindenUDP/LLClientView.cs @@ -5216,7 +5216,7 @@ namespace OpenSim.Region.ClientStack.LindenUDP args.Type = ChatTypeEnum.Shout; args.Position = new Vector3(); args.Scene = Scene; - args.Sender = this; + args.Sender = this; ChatMessage handlerChatFromClient2 = OnChatFromClient; if (handlerChatFromClient2 != null) handlerChatFromClient2(this, args); diff --git a/OpenSim/Region/CoreModules/Asset/CenomeAssetCache.cs b/OpenSim/Region/CoreModules/Asset/CenomeAssetCache.cs index 1903eb9..b1b7b27 100644 --- a/OpenSim/Region/CoreModules/Asset/CenomeAssetCache.cs +++ b/OpenSim/Region/CoreModules/Asset/CenomeAssetCache.cs @@ -330,7 +330,7 @@ namespace OpenSim.Region.CoreModules.Asset //m_log.DebugFormat("[XXX] name = {0} (this module's name: {1}", name, Name); if (name != Name) - return; + return; long maxSize = DefaultMaxSize; int maxCount = DefaultMaxCount; diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Asset/LocalAssetServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Asset/LocalAssetServiceConnector.cs index 2f21e6d..50348da 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Asset/LocalAssetServiceConnector.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Asset/LocalAssetServiceConnector.cs @@ -224,7 +224,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset m_Cache.Cache(a); // if (null == a) -// m_log.WarnFormat("[LOCAL ASSET SERVICES CONNECTOR]: Could not asynchronously find asset with id {0}", id); +// m_log.WarnFormat("[LOCAL ASSET SERVICES CONNECTOR]: Could not asynchronously find asset with id {0}", id); Util.FireAndForget(delegate { handler(assetID, s, a); }); }); diff --git a/OpenSim/Region/CoreModules/World/Access/AccessModule.cs b/OpenSim/Region/CoreModules/World/Access/AccessModule.cs index 73f7ae3..e4fe352 100644 --- a/OpenSim/Region/CoreModules/World/Access/AccessModule.cs +++ b/OpenSim/Region/CoreModules/World/Access/AccessModule.cs @@ -109,7 +109,7 @@ namespace OpenSim.Region.CoreModules.World { foreach (Scene s in m_SceneList) { - if(!ProcessCommand(s, cmd)) + if (!ProcessCommand(s, cmd)) break; } } diff --git a/OpenSim/Region/CoreModules/World/Archiver/Tests/ArchiverTests.cs b/OpenSim/Region/CoreModules/World/Archiver/Tests/ArchiverTests.cs index c3e57f0..e77a23b 100644 --- a/OpenSim/Region/CoreModules/World/Archiver/Tests/ArchiverTests.cs +++ b/OpenSim/Region/CoreModules/World/Archiver/Tests/ArchiverTests.cs @@ -99,7 +99,7 @@ namespace OpenSim.Region.CoreModules.World.Archiver.Tests Quaternion rotationOffset = new Quaternion(20, 30, 40, 50); Vector3 offsetPosition = new Vector3(5, 10, 15); - return new SceneObjectPart(ownerId, shape, groupPosition, rotationOffset, offsetPosition) { Name = partName }; + return new SceneObjectPart(ownerId, shape, groupPosition, rotationOffset, offsetPosition) { Name = partName }; } protected SceneObjectPart CreateSceneObjectPart2() @@ -112,7 +112,7 @@ namespace OpenSim.Region.CoreModules.World.Archiver.Tests Vector3 offsetPosition = new Vector3(20, 25, 30); return new SceneObjectPart(ownerId, shape, groupPosition, rotationOffset, offsetPosition) { Name = partName }; - } + } /// /// Test saving a V0.2 OpenSim Region Archive. @@ -231,7 +231,7 @@ namespace OpenSim.Region.CoreModules.World.Archiver.Tests foreach (string name in names) { if (name.EndsWith(".Resources.test-sound.wav")) - soundDataResourceName = name; + soundDataResourceName = name; } Assert.That(soundDataResourceName, Is.Not.Null); @@ -259,7 +259,7 @@ namespace OpenSim.Region.CoreModules.World.Archiver.Tests = new TaskInventoryItem { AssetID = soundUuid, ItemID = soundItemUuid, Name = soundItemName }; part1.Inventory.AddInventoryItem(item1, true); } - } + } m_scene.AddNewSceneObject(object1, false); @@ -306,15 +306,15 @@ namespace OpenSim.Region.CoreModules.World.Archiver.Tests /// Test loading the region settings of a V0.2 OpenSim Region Archive. /// [Test] - public void TestLoadOarV0_2RegionSettings() + public void TestLoadOarV0_2RegionSettings() { TestHelper.InMethod(); - //log4net.Config.XmlConfigurator.Configure(); + //log4net.Config.XmlConfigurator.Configure(); MemoryStream archiveWriteStream = new MemoryStream(); TarArchiveWriter tar = new TarArchiveWriter(archiveWriteStream); - tar.WriteDir(ArchiveConstants.TERRAINS_PATH); + tar.WriteDir(ArchiveConstants.TERRAINS_PATH); tar.WriteFile(ArchiveConstants.CONTROL_FILE_PATH, ArchiveWriteRequestExecution.Create0p2ControlFile()); RegionSettings rs = new RegionSettings(); @@ -329,11 +329,11 @@ namespace OpenSim.Region.CoreModules.World.Archiver.Tests rs.DisablePhysics = true; rs.DisableScripts = true; rs.Elevation1NW = 15.9; - rs.Elevation1NE = 45.3; + rs.Elevation1NE = 45.3; rs.Elevation1SE = 49; rs.Elevation1SW = 1.9; rs.Elevation2NW = 4.5; - rs.Elevation2NE = 19.2; + rs.Elevation2NE = 19.2; rs.Elevation2SE = 9.2; rs.Elevation2SW = 2.1; rs.FixedSun = true; @@ -411,7 +411,7 @@ namespace OpenSim.Region.CoreModules.World.Archiver.Tests // Quaternion part2RotationOffset = new Quaternion(60, 70, 80, 90); // Vector3 part2OffsetPosition = new Vector3(20, 25, 30); - SceneObjectPart part2 = CreateSceneObjectPart2(); + SceneObjectPart part2 = CreateSceneObjectPart2(); // Create an oar file that we can use for the merge { @@ -420,9 +420,9 @@ namespace OpenSim.Region.CoreModules.World.Archiver.Tests TerrainModule terrainModule = new TerrainModule(); Scene scene = SceneSetupHelpers.SetupScene(); - SceneSetupHelpers.SetupSceneModules(scene, archiverModule, serialiserModule, terrainModule); + SceneSetupHelpers.SetupSceneModules(scene, archiverModule, serialiserModule, terrainModule); - m_scene.AddNewSceneObject(new SceneObjectGroup(part2), false); + m_scene.AddNewSceneObject(new SceneObjectGroup(part2), false); // Write out this scene scene.EventManager.OnOarFileSaved += SaveCompleted; diff --git a/OpenSim/Region/Framework/Interfaces/IDynamicTextureManager.cs b/OpenSim/Region/Framework/Interfaces/IDynamicTextureManager.cs index c289cdb..8954513 100644 --- a/OpenSim/Region/Framework/Interfaces/IDynamicTextureManager.cs +++ b/OpenSim/Region/Framework/Interfaces/IDynamicTextureManager.cs @@ -65,7 +65,7 @@ namespace OpenSim.Region.Framework.Interfaces /// The UUID of the texture updater, not the texture UUID. If you need the texture UUID then you will need /// to obtain it directly from the SceneObjectPart. For instance, if ALL_SIDES is set then this texture /// can be obtained as SceneObjectPart.Shape.Textures.DefaultTexture.TextureID - /// + /// UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data, string extraParams, int updateTimer, bool SetBlending, byte AlphaValue); diff --git a/OpenSim/Region/Framework/Interfaces/IEntityInventory.cs b/OpenSim/Region/Framework/Interfaces/IEntityInventory.cs index fa9bf19..f58904f 100644 --- a/OpenSim/Region/Framework/Interfaces/IEntityInventory.cs +++ b/OpenSim/Region/Framework/Interfaces/IEntityInventory.cs @@ -150,7 +150,7 @@ namespace OpenSim.Region.Framework.Interfaces /// /// A list of inventory items with that name. /// If no inventory item has that name then an empty list is returned. - /// + /// IList GetInventoryItems(string name); /// diff --git a/OpenSim/Region/Framework/Interfaces/IWorldComm.cs b/OpenSim/Region/Framework/Interfaces/IWorldComm.cs index 948b9dc..8da99a0 100644 --- a/OpenSim/Region/Framework/Interfaces/IWorldComm.cs +++ b/OpenSim/Region/Framework/Interfaces/IWorldComm.cs @@ -62,7 +62,7 @@ namespace OpenSim.Region.Framework.Interfaces /// name to filter on /// key to filter on (user given, could be totally faked) /// msg to filter on - /// number of the scripts handle + /// number of the scripts handle int Listen(uint LocalID, UUID itemID, UUID hostID, int channel, string name, UUID id, string msg); /// @@ -77,19 +77,19 @@ namespace OpenSim.Region.Framework.Interfaces /// channel to sent on /// name of sender (object or avatar) /// key of sender (object or avatar) - /// msg to sent + /// msg to sent void DeliverMessage(ChatTypeEnum type, int channel, string name, UUID id, string msg); /// /// Are there any listen events ready to be dispatched? /// - /// boolean indication + /// boolean indication bool HasMessages(); /// /// Pop the first availlable listen event from the queue /// - /// ListenerInfo with filter filled in + /// ListenerInfo with filter filled in IWorldCommListenerInfo GetNextMessage(); void ListenControl(UUID itemID, int handle, int active); diff --git a/OpenSim/Region/Framework/Scenes/EventManager.cs b/OpenSim/Region/Framework/Scenes/EventManager.cs index 9f74b2a..57e1c37 100644 --- a/OpenSim/Region/Framework/Scenes/EventManager.cs +++ b/OpenSim/Region/Framework/Scenes/EventManager.cs @@ -209,7 +209,7 @@ namespace OpenSim.Region.Framework.Scenes /// Triggered when an object or attachment enters a scene /// public event OnIncomingSceneObjectDelegate OnIncomingSceneObject; - public delegate void OnIncomingSceneObjectDelegate(SceneObjectGroup so); + public delegate void OnIncomingSceneObjectDelegate(SceneObjectGroup so); public delegate void NewInventoryItemUploadComplete(UUID avatarID, UUID assetID, string name, int userlevel); @@ -413,7 +413,7 @@ namespace OpenSim.Region.Framework.Scenes } } } - } + } public void TriggerGetScriptRunning(IClientAPI controllingClient, UUID objectID, UUID itemID) { @@ -433,7 +433,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerOnScriptChangedEvent(uint localID, uint change) @@ -454,7 +454,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerOnClientMovement(ScenePresence avatar) @@ -475,7 +475,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerPermissionError(UUID user, string reason) @@ -496,7 +496,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerOnPluginConsole(string[] args) @@ -517,7 +517,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerOnFrame() @@ -538,11 +538,11 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerOnNewClient(IClientAPI client) - { + { OnNewClientDelegate handlerNewClient = OnNewClient; if (handlerNewClient != null) { @@ -559,10 +559,10 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } if (client is IClientCore) - { + { OnClientConnectCoreDelegate handlerClientConnect = OnClientConnect; if (handlerClientConnect != null) { @@ -579,7 +579,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } } @@ -601,11 +601,11 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerOnRemovePresence(UUID agentId) - { + { OnRemovePresenceDelegate handlerRemovePresence = OnRemovePresence; if (handlerRemovePresence != null) { @@ -622,11 +622,11 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerOnBackup(IRegionDataStore dstore) - { + { OnBackupDelegate handlerOnAttach = OnBackup; if (handlerOnAttach != null) { @@ -643,7 +643,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerParcelPrimCountUpdate() @@ -664,7 +664,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerMoneyTransfer(Object sender, MoneyTransferArgs args) @@ -685,7 +685,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerTerrainTick() @@ -706,7 +706,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerParcelPrimCountAdd(SceneObjectGroup obj) @@ -727,7 +727,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerObjectBeingRemovedFromScene(SceneObjectGroup obj) @@ -748,11 +748,11 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerShutdown() - { + { OnShutdownDelegate handlerShutdown = OnShutdown; if (handlerShutdown != null) { @@ -769,11 +769,11 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerObjectGrab(uint localID, uint originalID, Vector3 offsetPos, IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs) - { + { ObjectGrabDelegate handlerObjectGrab = OnObjectGrab; if (handlerObjectGrab != null) { @@ -790,11 +790,11 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerObjectGrabbing(uint localID, uint originalID, Vector3 offsetPos, IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs) - { + { ObjectGrabDelegate handlerObjectGrabbing = OnObjectGrabbing; if (handlerObjectGrabbing != null) { @@ -811,11 +811,11 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerObjectDeGrab(uint localID, uint originalID, IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs) - { + { ObjectDeGrabDelegate handlerObjectDeGrab = OnObjectDeGrab; if (handlerObjectDeGrab != null) { @@ -832,11 +832,11 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerScriptReset(uint localID, UUID itemID) - { + { ScriptResetDelegate handlerScriptReset = OnScriptReset; if (handlerScriptReset != null) { @@ -853,11 +853,11 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerRezScript(uint localID, UUID itemID, string script, int startParam, bool postOnRez, string engine, int stateSource) - { + { NewRezScript handlerRezScript = OnRezScript; if (handlerRezScript != null) { @@ -874,7 +874,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerStartScript(uint localID, UUID itemID) @@ -895,7 +895,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerStopScript(uint localID, UUID itemID) @@ -916,11 +916,11 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerRemoveScript(uint localID, UUID itemID) - { + { RemoveScript handlerRemoveScript = OnRemoveScript; if (handlerRemoveScript != null) { @@ -937,7 +937,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public bool TriggerGroupMove(UUID groupID, Vector3 delta) @@ -1036,7 +1036,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerLandObjectAdded(ILandObject newParcel) @@ -1057,7 +1057,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerLandObjectRemoved(UUID globalID) @@ -1078,7 +1078,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerLandObjectUpdated(uint localParcelID, ILandObject newParcel) @@ -1104,7 +1104,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerIncomingInstantMessage(GridInstantMessage message) @@ -1125,7 +1125,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerUnhandledInstantMessage(GridInstantMessage message) @@ -1146,7 +1146,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerClientClosed(UUID ClientID, Scene scene) @@ -1167,7 +1167,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerOnMakeChildAgent(ScenePresence presence) @@ -1188,7 +1188,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerOnMakeRootAgent(ScenePresence presence) @@ -1209,7 +1209,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerOnIncomingSceneObject(SceneObjectGroup so) @@ -1229,12 +1229,12 @@ namespace OpenSim.Region.Framework.Scenes "[EVENT MANAGER]: Delegate for TriggerOnIncomingSceneObject failed - continuing. {0} {1}", e.Message, e.StackTrace); } - } + } } } public void TriggerOnRegisterCaps(UUID agentID, Caps caps) - { + { RegisterCapsEvent handlerRegisterCaps = OnRegisterCaps; if (handlerRegisterCaps != null) { @@ -1251,7 +1251,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerOnDeregisterCaps(UUID agentID, Caps caps) @@ -1272,7 +1272,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerOnNewInventoryItemUploadComplete(UUID agentID, UUID AssetID, String AssetName, int userlevel) @@ -1293,7 +1293,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerLandBuy(Object sender, LandBuyArgs args) @@ -1314,7 +1314,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerValidateLandBuy(Object sender, LandBuyArgs args) @@ -1335,11 +1335,11 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerAtTargetEvent(uint localID, uint handle, Vector3 targetpos, Vector3 currentpos) - { + { ScriptAtTargetEvent handlerScriptAtTargetEvent = OnScriptAtTargetEvent; if (handlerScriptAtTargetEvent != null) { @@ -1356,7 +1356,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerNotAtTargetEvent(uint localID) @@ -1377,11 +1377,11 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerAtRotTargetEvent(uint localID, uint handle, Quaternion targetrot, Quaternion currentrot) - { + { ScriptAtRotTargetEvent handlerScriptAtRotTargetEvent = OnScriptAtRotTargetEvent; if (handlerScriptAtRotTargetEvent != null) { @@ -1398,7 +1398,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerNotAtRotTargetEvent(uint localID) @@ -1419,7 +1419,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerRequestChangeWaterHeight(float height) @@ -1440,7 +1440,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerAvatarKill(uint KillerObjectLocalID, ScenePresence DeadAvatar) @@ -1461,7 +1461,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerSignificantClientMovement(IClientAPI client) @@ -1482,7 +1482,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerOnChatFromWorld(Object sender, OSChatMessage chat) @@ -1503,7 +1503,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerOnChatFromClient(Object sender, OSChatMessage chat) @@ -1524,7 +1524,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerOnChatBroadcast(Object sender, OSChatMessage chat) @@ -1545,7 +1545,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } internal void TriggerControlEvent(uint p, UUID scriptUUID, UUID avatarID, uint held, uint _changed) @@ -1566,7 +1566,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerNoticeNoLandDataFromStorage() @@ -1587,7 +1587,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerIncomingLandDataFromStorage(List landData) @@ -1608,7 +1608,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerSetAllowForcefulBan(bool allow) @@ -1629,7 +1629,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerRequestParcelPrimCountUpdate() @@ -1650,7 +1650,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerParcelPrimCountTainted() @@ -1671,7 +1671,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } // this lets us keep track of nasty script events like timer, etc. @@ -1710,7 +1710,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public float GetCurrentTimeAsSunLindenHour() @@ -1737,7 +1737,7 @@ namespace OpenSim.Region.Framework.Scenes } public void TriggerOarFileLoaded(Guid requestId, string message) - { + { OarFileLoaded handlerOarFileLoaded = OnOarFileLoaded; if (handlerOarFileLoaded != null) { @@ -1754,7 +1754,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerOarFileSaved(Guid requestId, string message) @@ -1775,7 +1775,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerEmptyScriptCompileQueue(int numScriptsFailed, string message) @@ -1796,7 +1796,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerScriptCollidingStart(uint localId, ColliderArgs colliders) @@ -1817,7 +1817,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerScriptColliding(uint localId, ColliderArgs colliders) @@ -1838,7 +1838,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerScriptCollidingEnd(uint localId, ColliderArgs colliders) @@ -1859,7 +1859,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerScriptLandCollidingStart(uint localId, ColliderArgs colliders) @@ -1880,7 +1880,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerScriptLandColliding(uint localId, ColliderArgs colliders) @@ -1901,7 +1901,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerScriptLandCollidingEnd(uint localId, ColliderArgs colliders) @@ -1922,11 +1922,11 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerSetRootAgentScene(UUID agentID, Scene scene) - { + { OnSetRootAgentSceneDelegate handlerSetRootAgentScene = OnSetRootAgentScene; if (handlerSetRootAgentScene != null) { @@ -1943,7 +1943,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } public void TriggerOnRegionUp(GridRegion otherRegion) @@ -1964,7 +1964,7 @@ namespace OpenSim.Region.Framework.Scenes e.Message, e.StackTrace); } } - } + } } } } \ No newline at end of file diff --git a/OpenSim/Region/Framework/Scenes/Scene.cs b/OpenSim/Region/Framework/Scenes/Scene.cs index c7fb32a..41fd1e1 100644 --- a/OpenSim/Region/Framework/Scenes/Scene.cs +++ b/OpenSim/Region/Framework/Scenes/Scene.cs @@ -2541,7 +2541,7 @@ namespace OpenSim.Region.Framework.Scenes AttachObject( sp.ControllingClient, grp.LocalId, (uint)0, grp.GroupRotation, grp.AbsolutePosition, false); RootPrim.RemFlag(PrimFlags.TemporaryOnRez); - grp.SendGroupFullUpdate(); + grp.SendGroupFullUpdate(); } else { diff --git a/OpenSim/Region/Framework/Scenes/SceneGraph.cs b/OpenSim/Region/Framework/Scenes/SceneGraph.cs index 2b13181..321cc45 100644 --- a/OpenSim/Region/Framework/Scenes/SceneGraph.cs +++ b/OpenSim/Region/Framework/Scenes/SceneGraph.cs @@ -642,7 +642,7 @@ namespace OpenSim.Region.Framework.Scenes // it get cleaned up // group.RootPart.RemFlag(PrimFlags.TemporaryOnRez); - group.HasGroupChanged = false; + group.HasGroupChanged = false; } else { diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs b/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs index d339208..5c283bc 100644 --- a/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs +++ b/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs @@ -4531,7 +4531,7 @@ namespace OpenSim.Region.Framework.Scenes else { // m_log.DebugFormat( -// "[SCENE OBJECT PART]: Scheduling part {0} {1} for full update in aggregateScriptEvents()", Name, LocalId); +// "[SCENE OBJECT PART]: Scheduling part {0} {1} for full update in aggregateScriptEvents()", Name, LocalId); ScheduleFullUpdate(); } } diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs b/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs index 298ede9..a555eae 100644 --- a/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs +++ b/OpenSim/Region/Framework/Scenes/SceneObjectPartInventory.cs @@ -314,7 +314,7 @@ namespace OpenSim.Region.Framework.Scenes } ); } - } + } private void RestoreSavedScriptState(UUID oldID, UUID newID) { @@ -579,7 +579,7 @@ namespace OpenSim.Region.Framework.Scenes m_items.TryGetValue(itemId, out item); return item; - } + } /// /// Get inventory items by name. @@ -588,7 +588,7 @@ namespace OpenSim.Region.Framework.Scenes /// /// A list of inventory items with that name. /// If no inventory item has that name then an empty list is returned. - /// + /// public IList GetInventoryItems(string name) { IList items = new List(); diff --git a/OpenSim/Region/Framework/Scenes/ScenePresence.cs b/OpenSim/Region/Framework/Scenes/ScenePresence.cs index 7cdea05..4973663 100644 --- a/OpenSim/Region/Framework/Scenes/ScenePresence.cs +++ b/OpenSim/Region/Framework/Scenes/ScenePresence.cs @@ -227,7 +227,7 @@ namespace OpenSim.Region.Framework.Scenes // Agent's Draw distance. protected float m_DrawDistance; - protected AvatarAppearance m_appearance; + protected AvatarAppearance m_appearance; // neighbouring regions we have enabled a child agent in // holds the seed cap for the child agent in that region @@ -648,7 +648,7 @@ namespace OpenSim.Region.Framework.Scenes #region Constructor(s) public ScenePresence() - { + { m_sendCourseLocationsMethod = SendCoarseLocationsDefault; CreateSceneViewer(); m_animator = new ScenePresenceAnimator(this); @@ -3265,7 +3265,7 @@ namespace OpenSim.Region.Framework.Scenes m_physicsActor.OnCollisionUpdate += PhysicsCollisionUpdate; m_physicsActor.OnOutOfBounds += OutOfBoundsCall; // Called for PhysicsActors when there's something wrong m_physicsActor.SubscribeEvents(500); - m_physicsActor.LocalID = LocalId; + m_physicsActor.LocalID = LocalId; } private void OutOfBoundsCall(Vector3 pos) @@ -3357,7 +3357,7 @@ namespace OpenSim.Region.Framework.Scenes } if (m_health <= 0) m_scene.EventManager.TriggerAvatarKill(killerObj, this); - } + } } public void setHealthWithUpdate(float health) diff --git a/OpenSim/Region/Physics/OdePlugin/ODEDynamics.cs b/OpenSim/Region/Physics/OdePlugin/ODEDynamics.cs index 6ae0c8a..9beeabb 100644 --- a/OpenSim/Region/Physics/OdePlugin/ODEDynamics.cs +++ b/OpenSim/Region/Physics/OdePlugin/ODEDynamics.cs @@ -72,23 +72,23 @@ namespace OpenSim.Region.Physics.OdePlugin // Vehicle properties - private Vehicle m_type = Vehicle.TYPE_NONE; // If a 'VEHICLE', and what kind - // private Quaternion m_referenceFrame = Quaternion.Identity; // Axis modifier - private VehicleFlag m_flags = (VehicleFlag) 0; // Boolean settings: - // HOVER_TERRAIN_ONLY - // HOVER_GLOBAL_HEIGHT - // NO_DEFLECTION_UP - // HOVER_WATER_ONLY - // HOVER_UP_ONLY - // LIMIT_MOTOR_UP - // LIMIT_ROLL_ONLY + private Vehicle m_type = Vehicle.TYPE_NONE; // If a 'VEHICLE', and what kind + // private Quaternion m_referenceFrame = Quaternion.Identity; // Axis modifier + private VehicleFlag m_flags = (VehicleFlag) 0; // Boolean settings: + // HOVER_TERRAIN_ONLY + // HOVER_GLOBAL_HEIGHT + // NO_DEFLECTION_UP + // HOVER_WATER_ONLY + // HOVER_UP_ONLY + // LIMIT_MOTOR_UP + // LIMIT_ROLL_ONLY private VehicleFlag m_Hoverflags = (VehicleFlag)0; private Vector3 m_BlockingEndPoint = Vector3.Zero; private Quaternion m_RollreferenceFrame = Quaternion.Identity; // Linear properties - private Vector3 m_linearMotorDirection = Vector3.Zero; // velocity requested by LSL, decayed by time - private Vector3 m_linearMotorDirectionLASTSET = Vector3.Zero; // velocity requested by LSL - private Vector3 m_dir = Vector3.Zero; // velocity applied to body + private Vector3 m_linearMotorDirection = Vector3.Zero; // velocity requested by LSL, decayed by time + private Vector3 m_linearMotorDirectionLASTSET = Vector3.Zero; // velocity requested by LSL + private Vector3 m_dir = Vector3.Zero; // velocity applied to body private Vector3 m_linearFrictionTimescale = Vector3.Zero; private float m_linearMotorDecayTimescale = 0; private float m_linearMotorTimescale = 0; @@ -98,14 +98,14 @@ namespace OpenSim.Region.Physics.OdePlugin // private Vector3 m_linearMotorOffset = Vector3.Zero; //Angular properties - private Vector3 m_angularMotorDirection = Vector3.Zero; // angular velocity requested by LSL motor - private int m_angularMotorApply = 0; // application frame counter - private Vector3 m_angularMotorVelocity = Vector3.Zero; // current angular motor velocity - private float m_angularMotorTimescale = 0; // motor angular velocity ramp up rate - private float m_angularMotorDecayTimescale = 0; // motor angular velocity decay rate - private Vector3 m_angularFrictionTimescale = Vector3.Zero; // body angular velocity decay rate - private Vector3 m_lastAngularVelocity = Vector3.Zero; // what was last applied to body - // private Vector3 m_lastVertAttractor = Vector3.Zero; // what VA was last applied to body + private Vector3 m_angularMotorDirection = Vector3.Zero; // angular velocity requested by LSL motor + private int m_angularMotorApply = 0; // application frame counter + private Vector3 m_angularMotorVelocity = Vector3.Zero; // current angular motor velocity + private float m_angularMotorTimescale = 0; // motor angular velocity ramp up rate + private float m_angularMotorDecayTimescale = 0; // motor angular velocity decay rate + private Vector3 m_angularFrictionTimescale = Vector3.Zero; // body angular velocity decay rate + private Vector3 m_lastAngularVelocity = Vector3.Zero; // what was last applied to body + // private Vector3 m_lastVertAttractor = Vector3.Zero; // what VA was last applied to body //Deflection properties // private float m_angularDeflectionEfficiency = 0; @@ -123,14 +123,14 @@ namespace OpenSim.Region.Physics.OdePlugin // private float m_VhoverEfficiency = 0f; private float m_VhoverTimescale = 0f; private float m_VhoverTargetHeight = -1.0f; // if <0 then no hover, else its the current target height - private float m_VehicleBuoyancy = 0f; //KF: m_VehicleBuoyancy is set by VEHICLE_BUOYANCY for a vehicle. + private float m_VehicleBuoyancy = 0f; //KF: m_VehicleBuoyancy is set by VEHICLE_BUOYANCY for a vehicle. // Modifies gravity. Slider between -1 (double-gravity) and 1 (full anti-gravity) // KF: So far I have found no good method to combine a script-requested .Z velocity and gravity. // Therefore only m_VehicleBuoyancy=1 (0g) will use the script-requested .Z velocity. - //Attractor properties - private float m_verticalAttractionEfficiency = 1.0f; // damped - private float m_verticalAttractionTimescale = 500f; // Timescale > 300 means no vert attractor. + //Attractor properties + private float m_verticalAttractionEfficiency = 1.0f; // damped + private float m_verticalAttractionTimescale = 500f; // Timescale > 300 means no vert attractor. internal void ProcessFloatVehicleParam(Vehicle pParam, float pValue) { diff --git a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs index eab4754..aa876ec 100644 --- a/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs +++ b/OpenSim/Region/ScriptEngine/Shared/Api/Implementation/LSL_Api.cs @@ -8192,38 +8192,38 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api { m_host.AddScriptLPS(1); if (m_ScriptEngine.Config.GetBoolean("AllowGodFunctions", false)) - { - if (World.Permissions.CanRunConsoleCommand(m_host.OwnerID)) - { - lock (m_host.TaskInventory) - { - foreach (KeyValuePair inv in m_host.TaskInventory) - { - if (inv.Value.Name == item) - { - switch (mask) - { - case 0: - inv.Value.BasePermissions = (uint)value; - break; - case 1: - inv.Value.CurrentPermissions = (uint)value; - break; - case 2: - inv.Value.GroupPermissions = (uint)value; - break; - case 3: - inv.Value.EveryonePermissions = (uint)value; - break; - case 4: - inv.Value.NextPermissions = (uint)value; - break; - } - } - } - } - } - } + { + if (World.Permissions.CanRunConsoleCommand(m_host.OwnerID)) + { + lock (m_host.TaskInventory) + { + foreach (KeyValuePair inv in m_host.TaskInventory) + { + if (inv.Value.Name == item) + { + switch (mask) + { + case 0: + inv.Value.BasePermissions = (uint)value; + break; + case 1: + inv.Value.CurrentPermissions = (uint)value; + break; + case 2: + inv.Value.GroupPermissions = (uint)value; + break; + case 3: + inv.Value.EveryonePermissions = (uint)value; + break; + case 4: + inv.Value.NextPermissions = (uint)value; + break; + } + } + } + } + } + } } public LSL_String llGetInventoryCreator(string item) diff --git a/OpenSim/Region/ScriptEngine/XEngine/XEngine.cs b/OpenSim/Region/ScriptEngine/XEngine/XEngine.cs index c552b92..98e77c0 100644 --- a/OpenSim/Region/ScriptEngine/XEngine/XEngine.cs +++ b/OpenSim/Region/ScriptEngine/XEngine/XEngine.cs @@ -841,7 +841,7 @@ namespace OpenSim.Region.ScriptEngine.XEngine ObjectRemoved handlerObjectRemoved = OnObjectRemoved; if (handlerObjectRemoved != null) { - SceneObjectPart part = m_Scene.GetSceneObjectPart(localID); + SceneObjectPart part = m_Scene.GetSceneObjectPart(localID); handlerObjectRemoved(part.UUID); } diff --git a/OpenSim/Server/Handlers/Inventory/XInventoryInConnector.cs b/OpenSim/Server/Handlers/Inventory/XInventoryInConnector.cs index c7d5ff1..03d4d7a 100644 --- a/OpenSim/Server/Handlers/Inventory/XInventoryInConnector.cs +++ b/OpenSim/Server/Handlers/Inventory/XInventoryInConnector.cs @@ -197,7 +197,7 @@ namespace OpenSim.Server.Handlers.Asset if (!request.ContainsKey("PRINCIPAL")) return FailureResult(); - if(m_InventoryService.CreateUserInventory(new UUID(request["PRINCIPAL"].ToString()))) + if (m_InventoryService.CreateUserInventory(new UUID(request["PRINCIPAL"].ToString()))) result["RESULT"] = "True"; else result["RESULT"] = "False"; diff --git a/OpenSim/Services/AssetService/AssetService.cs b/OpenSim/Services/AssetService/AssetService.cs index a91b632..b9723a8 100644 --- a/OpenSim/Services/AssetService/AssetService.cs +++ b/OpenSim/Services/AssetService/AssetService.cs @@ -81,12 +81,12 @@ namespace OpenSim.Services.AssetService } public AssetBase Get(string id) - { + { UUID assetID; if (!UUID.TryParse(id, out assetID)) { - m_log.WarnFormat("[ASSET SERVICE]: Could not parse requested sset id {0}", id); + m_log.WarnFormat("[ASSET SERVICE]: Could not parse requested sset id {0}", id); return null; } diff --git a/OpenSim/Services/Connectors/Asset/AssetServiceConnector.cs b/OpenSim/Services/Connectors/Asset/AssetServiceConnector.cs index 6d442b7..8e311d7 100644 --- a/OpenSim/Services/Connectors/Asset/AssetServiceConnector.cs +++ b/OpenSim/Services/Connectors/Asset/AssetServiceConnector.cs @@ -93,7 +93,7 @@ namespace OpenSim.Services.Connectors } public AssetBase Get(string id) - { + { string uri = m_ServerURI + "/assets/" + id; AssetBase asset = null; -- cgit v1.1 From 052f2b3e275b60777c51ca0274f33abce869c55d Mon Sep 17 00:00:00 2001 From: Justin Clark-Casey (justincc) Date: Tue, 16 Feb 2010 14:36:08 +0000 Subject: minor: Make SOG.DelinkFromGroup() return the newly delinked scene object instead of void --- OpenSim/Region/Framework/Scenes/SceneBase.cs | 2 +- .../Region/Framework/Scenes/SceneObjectGroup.cs | 35 +++++++++++++++------- 2 files changed, 26 insertions(+), 11 deletions(-) diff --git a/OpenSim/Region/Framework/Scenes/SceneBase.cs b/OpenSim/Region/Framework/Scenes/SceneBase.cs index 1547f9a..5e798c0 100644 --- a/OpenSim/Region/Framework/Scenes/SceneBase.cs +++ b/OpenSim/Region/Framework/Scenes/SceneBase.cs @@ -262,7 +262,7 @@ namespace OpenSim.Region.Framework.Scenes /// Returns a new unallocated local ID /// /// A brand new local ID - protected internal uint AllocateLocalId() + public uint AllocateLocalId() { uint myID; diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs b/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs index af46659..94e64e4 100644 --- a/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs +++ b/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs @@ -509,7 +509,7 @@ namespace OpenSim.Region.Framework.Scenes if (m_rootPart.Shape.PCode != 9 || m_rootPart.Shape.State == 0) m_rootPart.ParentID = 0; - if (m_rootPart.LocalId==0) + if (m_rootPart.LocalId == 0) m_rootPart.LocalId = m_scene.AllocateLocalId(); // No need to lock here since the object isn't yet in a scene @@ -1468,6 +1468,9 @@ namespace OpenSim.Region.Framework.Scenes /// internal void SendPartFullUpdate(IClientAPI remoteClient, SceneObjectPart part, uint clientFlags) { +// m_log.DebugFormat( +// "[SOG]: Sendinging part full update to {0} for {1} {2}", remoteClient.Name, part.Name, part.LocalId); + if (m_rootPart.UUID == part.UUID) { if (IsAttachment) @@ -2284,7 +2287,6 @@ namespace OpenSim.Region.Framework.Scenes AttachToBackup(); - // Here's the deal, this is ABSOLUTELY CRITICAL so the physics scene gets the update about the // position of linkset prims. IF YOU CHANGE THIS, YOU MUST TEST colliding with just linked and // unmoved prims! @@ -2299,9 +2301,10 @@ namespace OpenSim.Region.Framework.Scenes /// an independent SceneObjectGroup. /// /// - public void DelinkFromGroup(uint partID) + /// The object group of the newly delinked prim. Null if part could not be found + public SceneObjectGroup DelinkFromGroup(uint partID) { - DelinkFromGroup(partID, true); + return DelinkFromGroup(partID, true); } /// @@ -2310,28 +2313,39 @@ namespace OpenSim.Region.Framework.Scenes /// /// /// - public void DelinkFromGroup(uint partID, bool sendEvents) + /// The object group of the newly delinked prim. Null if part could not be found + public SceneObjectGroup DelinkFromGroup(uint partID, bool sendEvents) { SceneObjectPart linkPart = GetChildPart(partID); if (linkPart != null) { - DelinkFromGroup(linkPart, sendEvents); + return DelinkFromGroup(linkPart, sendEvents); } else { - m_log.InfoFormat("[SCENE OBJECT GROUP]: " + + m_log.WarnFormat("[SCENE OBJECT GROUP]: " + "DelinkFromGroup(): Child prim {0} not found in object {1}, {2}", partID, LocalId, UUID); + + return null; } } - public void DelinkFromGroup(SceneObjectPart linkPart, bool sendEvents) + /// + /// Delink the given prim from this group. The delinked prim is established as + /// an independent SceneObjectGroup. + /// + /// + /// + /// The object group of the newly delinked prim. + public SceneObjectGroup DelinkFromGroup(SceneObjectPart linkPart, bool sendEvents) { - linkPart.ClearUndoState(); // m_log.DebugFormat( // "[SCENE OBJECT GROUP]: Delinking part {0}, {1} from group with root part {2}, {3}", // linkPart.Name, linkPart.UUID, RootPart.Name, RootPart.UUID); + + linkPart.ClearUndoState(); Quaternion worldRot = linkPart.GetWorldRotation(); @@ -2384,6 +2398,8 @@ namespace OpenSim.Region.Framework.Scenes //HasGroupChanged = true; //ScheduleGroupForFullUpdate(); + + return objectGroup; } /// @@ -2422,7 +2438,6 @@ namespace OpenSim.Region.Framework.Scenes part.LinkNum = linkNum; - part.OffsetPosition = part.GroupPosition - AbsolutePosition; Quaternion rootRotation = m_rootPart.RotationOffset; -- cgit v1.1 From 4355bcc417b5271bec4955ecab355b216cdea64d Mon Sep 17 00:00:00 2001 From: Justin Clark-Casey (justincc) Date: Tue, 16 Feb 2010 19:31:49 +0000 Subject: Disable Data.BasicRegioNTest.T016_RandomSogWithSceneParts() temporarily since it's making the tests fail but the cause is not obvious (wrapped up in layers of reflection) --- OpenSim/Data/Tests/BasicRegionTest.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OpenSim/Data/Tests/BasicRegionTest.cs b/OpenSim/Data/Tests/BasicRegionTest.cs index 676c6ba..dfbf522 100644 --- a/OpenSim/Data/Tests/BasicRegionTest.cs +++ b/OpenSim/Data/Tests/BasicRegionTest.cs @@ -524,7 +524,7 @@ namespace OpenSim.Data.Tests } } - [Test] + //[Test] public void T016_RandomSogWithSceneParts() { PropertyScrambler scrambler = -- cgit v1.1 From 95a31c9b6f0ca4308bc74fb0da5572885823451f Mon Sep 17 00:00:00 2001 From: Justin Clark-Casey (justincc) Date: Wed, 17 Feb 2010 20:57:29 +0000 Subject: minor: fix error inserting field in log message --- .../ServiceConnectorsOut/Inventory/LocalInventoryServiceConnector.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/LocalInventoryServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/LocalInventoryServiceConnector.cs index 3883dc6..191e859 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/LocalInventoryServiceConnector.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/LocalInventoryServiceConnector.cs @@ -317,7 +317,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory item = m_InventoryService.GetItem(item); if (null == item) - m_log.ErrorFormat("[LOCAL INVENTORY SERVICES CONNECTOR]: Could not find item with id {0}"); + m_log.ErrorFormat("[LOCAL INVENTORY SERVICES CONNECTOR]: Could not find item with id {0}", item.ID); return item; } -- cgit v1.1 From 10f94a3c335dec8902b45bf16b8a8beb7f0e8ea8 Mon Sep 17 00:00:00 2001 From: Justin Clark-Casey (justincc) Date: Wed, 17 Feb 2010 21:13:31 +0000 Subject: remove old commented out switch statement in LLClientView since this has successfully been split into separate methods for quite some time now --- .../Region/ClientStack/LindenUDP/LLClientView.cs | 4849 +------------------- 1 file changed, 3 insertions(+), 4846 deletions(-) diff --git a/OpenSim/Region/ClientStack/LindenUDP/LLClientView.cs b/OpenSim/Region/ClientStack/LindenUDP/LLClientView.cs index 6cc0bd2..0b90b55 100644 --- a/OpenSim/Region/ClientStack/LindenUDP/LLClientView.cs +++ b/OpenSim/Region/ClientStack/LindenUDP/LLClientView.cs @@ -11025,4855 +11025,12 @@ namespace OpenSim.Region.ClientStack.LindenUDP /// OpenMetaverse.packet public void ProcessInPacket(Packet Pack) { - - if (ProcessPacketMethod(Pack)) - { - PacketPool.Instance.ReturnPacket(Pack); - return; - } - - // Main packet processing conditional - switch (Pack.Type) - { - #region CommentedOut - /* - #region Scene/Avatar - - - case PacketType.AvatarPropertiesRequest: - AvatarPropertiesRequestPacket avatarProperties = (AvatarPropertiesRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (avatarProperties.AgentData.SessionID != SessionId || - avatarProperties.AgentData.AgentID != AgentId) - break; - } - #endregion - - RequestAvatarProperties handlerRequestAvatarProperties = OnRequestAvatarProperties; - if (handlerRequestAvatarProperties != null) - { - handlerRequestAvatarProperties(this, avatarProperties.AgentData.AvatarID); - } - - break; - - case PacketType.ChatFromViewer: - ChatFromViewerPacket inchatpack = (ChatFromViewerPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (inchatpack.AgentData.SessionID != SessionId || - inchatpack.AgentData.AgentID != AgentId) - break; - } - #endregion - - string fromName = String.Empty; //ClientAvatar.firstname + " " + ClientAvatar.lastname; - byte[] message = inchatpack.ChatData.Message; - byte type = inchatpack.ChatData.Type; - Vector3 fromPos = new Vector3(); // ClientAvatar.Pos; - // UUID fromAgentID = AgentId; - - int channel = inchatpack.ChatData.Channel; - - if (OnChatFromClient != null) - { - OSChatMessage args = new OSChatMessage(); - args.Channel = channel; - args.From = fromName; - args.Message = Utils.BytesToString(message); - args.Type = (ChatTypeEnum)type; - args.Position = fromPos; - - args.Scene = Scene; - args.Sender = this; - args.SenderUUID = this.AgentId; - - ChatMessage handlerChatFromClient = OnChatFromClient; - if (handlerChatFromClient != null) - handlerChatFromClient(this, args); - } - break; - - case PacketType.AvatarPropertiesUpdate: - AvatarPropertiesUpdatePacket avatarProps = (AvatarPropertiesUpdatePacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (avatarProps.AgentData.SessionID != SessionId || - avatarProps.AgentData.AgentID != AgentId) - break; - } - #endregion - - UpdateAvatarProperties handlerUpdateAvatarProperties = OnUpdateAvatarProperties; - if (handlerUpdateAvatarProperties != null) - { - AvatarPropertiesUpdatePacket.PropertiesDataBlock Properties = avatarProps.PropertiesData; - UserProfileData UserProfile = new UserProfileData(); - UserProfile.ID = AgentId; - UserProfile.AboutText = Utils.BytesToString(Properties.AboutText); - UserProfile.FirstLifeAboutText = Utils.BytesToString(Properties.FLAboutText); - UserProfile.FirstLifeImage = Properties.FLImageID; - UserProfile.Image = Properties.ImageID; - UserProfile.ProfileUrl = Utils.BytesToString(Properties.ProfileURL); - - handlerUpdateAvatarProperties(this, UserProfile); - } - break; - - case PacketType.ScriptDialogReply: - ScriptDialogReplyPacket rdialog = (ScriptDialogReplyPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (rdialog.AgentData.SessionID != SessionId || - rdialog.AgentData.AgentID != AgentId) - break; - } - #endregion - - int ch = rdialog.Data.ChatChannel; - byte[] msg = rdialog.Data.ButtonLabel; - if (OnChatFromClient != null) - { - OSChatMessage args = new OSChatMessage(); - args.Channel = ch; - args.From = String.Empty; - args.Message = Utils.BytesToString(msg); - args.Type = ChatTypeEnum.Shout; - args.Position = new Vector3(); - args.Scene = Scene; - args.Sender = this; - ChatMessage handlerChatFromClient2 = OnChatFromClient; - if (handlerChatFromClient2 != null) - handlerChatFromClient2(this, args); - } - - break; - - case PacketType.ImprovedInstantMessage: - ImprovedInstantMessagePacket msgpack = (ImprovedInstantMessagePacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (msgpack.AgentData.SessionID != SessionId || - msgpack.AgentData.AgentID != AgentId) - break; - } - #endregion - - string IMfromName = Util.FieldToString(msgpack.MessageBlock.FromAgentName); - string IMmessage = Utils.BytesToString(msgpack.MessageBlock.Message); - ImprovedInstantMessage handlerInstantMessage = OnInstantMessage; - - if (handlerInstantMessage != null) - { - GridInstantMessage im = new GridInstantMessage(Scene, - msgpack.AgentData.AgentID, - IMfromName, - msgpack.MessageBlock.ToAgentID, - msgpack.MessageBlock.Dialog, - msgpack.MessageBlock.FromGroup, - IMmessage, - msgpack.MessageBlock.ID, - msgpack.MessageBlock.Offline != 0 ? true : false, - msgpack.MessageBlock.Position, - msgpack.MessageBlock.BinaryBucket); - - handlerInstantMessage(this, im); - } - break; - - case PacketType.AcceptFriendship: - AcceptFriendshipPacket afriendpack = (AcceptFriendshipPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (afriendpack.AgentData.SessionID != SessionId || - afriendpack.AgentData.AgentID != AgentId) - break; - } - #endregion - - // My guess is this is the folder to stick the calling card into - List callingCardFolders = new List(); - - UUID agentID = afriendpack.AgentData.AgentID; - UUID transactionID = afriendpack.TransactionBlock.TransactionID; - - for (int fi = 0; fi < afriendpack.FolderData.Length; fi++) - { - callingCardFolders.Add(afriendpack.FolderData[fi].FolderID); - } - - FriendActionDelegate handlerApproveFriendRequest = OnApproveFriendRequest; - if (handlerApproveFriendRequest != null) - { - handlerApproveFriendRequest(this, agentID, transactionID, callingCardFolders); - } - break; - - case PacketType.DeclineFriendship: - DeclineFriendshipPacket dfriendpack = (DeclineFriendshipPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (dfriendpack.AgentData.SessionID != SessionId || - dfriendpack.AgentData.AgentID != AgentId) - break; - } - #endregion - - if (OnDenyFriendRequest != null) - { - OnDenyFriendRequest(this, - dfriendpack.AgentData.AgentID, - dfriendpack.TransactionBlock.TransactionID, - null); - } - break; - - case PacketType.TerminateFriendship: - TerminateFriendshipPacket tfriendpack = (TerminateFriendshipPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (tfriendpack.AgentData.SessionID != SessionId || - tfriendpack.AgentData.AgentID != AgentId) - break; - } - #endregion - - UUID listOwnerAgentID = tfriendpack.AgentData.AgentID; - UUID exFriendID = tfriendpack.ExBlock.OtherID; - - FriendshipTermination handlerTerminateFriendship = OnTerminateFriendship; - if (handlerTerminateFriendship != null) - { - handlerTerminateFriendship(this, listOwnerAgentID, exFriendID); - } - break; - - case PacketType.RezObject: - RezObjectPacket rezPacket = (RezObjectPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (rezPacket.AgentData.SessionID != SessionId || - rezPacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - RezObject handlerRezObject = OnRezObject; - if (handlerRezObject != null) - { - handlerRezObject(this, rezPacket.InventoryData.ItemID, rezPacket.RezData.RayEnd, - rezPacket.RezData.RayStart, rezPacket.RezData.RayTargetID, - rezPacket.RezData.BypassRaycast, rezPacket.RezData.RayEndIsIntersection, - rezPacket.RezData.RezSelected, rezPacket.RezData.RemoveItem, - rezPacket.RezData.FromTaskID); - } - break; - - case PacketType.DeRezObject: - DeRezObjectPacket DeRezPacket = (DeRezObjectPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (DeRezPacket.AgentData.SessionID != SessionId || - DeRezPacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - DeRezObject handlerDeRezObject = OnDeRezObject; - if (handlerDeRezObject != null) - { - List deRezIDs = new List(); - - foreach (DeRezObjectPacket.ObjectDataBlock data in - DeRezPacket.ObjectData) - { - deRezIDs.Add(data.ObjectLocalID); - } - // It just so happens that the values on the DeRezAction enumerator match the Destination - // values given by a Second Life client - handlerDeRezObject(this, deRezIDs, - DeRezPacket.AgentBlock.GroupID, - (DeRezAction)DeRezPacket.AgentBlock.Destination, - DeRezPacket.AgentBlock.DestinationID); - - } - break; - - case PacketType.ModifyLand: - ModifyLandPacket modify = (ModifyLandPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (modify.AgentData.SessionID != SessionId || - modify.AgentData.AgentID != AgentId) - break; - } - - #endregion - //m_log.Info("[LAND]: LAND:" + modify.ToString()); - if (modify.ParcelData.Length > 0) - { - if (OnModifyTerrain != null) - { - for (int i = 0; i < modify.ParcelData.Length; i++) - { - ModifyTerrain handlerModifyTerrain = OnModifyTerrain; - if (handlerModifyTerrain != null) - { - handlerModifyTerrain(AgentId, modify.ModifyBlock.Height, modify.ModifyBlock.Seconds, - modify.ModifyBlock.BrushSize, - modify.ModifyBlock.Action, modify.ParcelData[i].North, - modify.ParcelData[i].West, modify.ParcelData[i].South, - modify.ParcelData[i].East, AgentId); - } - } - } - } - - break; - - case PacketType.RegionHandshakeReply: - - Action handlerRegionHandShakeReply = OnRegionHandShakeReply; - if (handlerRegionHandShakeReply != null) - { - handlerRegionHandShakeReply(this); - } - - break; - - case PacketType.AgentWearablesRequest: - GenericCall2 handlerRequestWearables = OnRequestWearables; - - if (handlerRequestWearables != null) - { - handlerRequestWearables(); - } - - Action handlerRequestAvatarsData = OnRequestAvatarsData; - - if (handlerRequestAvatarsData != null) - { - handlerRequestAvatarsData(this); - } - - break; - - case PacketType.AgentSetAppearance: - AgentSetAppearancePacket appear = (AgentSetAppearancePacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (appear.AgentData.SessionID != SessionId || - appear.AgentData.AgentID != AgentId) - break; - } - #endregion - - SetAppearance handlerSetAppearance = OnSetAppearance; - if (handlerSetAppearance != null) - { - // Temporarily protect ourselves from the mantis #951 failure. - // However, we could do this for several other handlers where a failure isn't terminal - // for the client session anyway, in order to protect ourselves against bad code in plugins - try - { - byte[] visualparams = new byte[appear.VisualParam.Length]; - for (int i = 0; i < appear.VisualParam.Length; i++) - visualparams[i] = appear.VisualParam[i].ParamValue; - - Primitive.TextureEntry te = null; - if (appear.ObjectData.TextureEntry.Length > 1) - te = new Primitive.TextureEntry(appear.ObjectData.TextureEntry, 0, appear.ObjectData.TextureEntry.Length); - - handlerSetAppearance(te, visualparams); - } - catch (Exception e) - { - m_log.ErrorFormat( - "[CLIENT VIEW]: AgentSetApperance packet handler threw an exception, {0}", - e); - } - } - - break; - - case PacketType.AgentIsNowWearing: - if (OnAvatarNowWearing != null) - { - AgentIsNowWearingPacket nowWearing = (AgentIsNowWearingPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (nowWearing.AgentData.SessionID != SessionId || - nowWearing.AgentData.AgentID != AgentId) - break; - } - #endregion - - AvatarWearingArgs wearingArgs = new AvatarWearingArgs(); - for (int i = 0; i < nowWearing.WearableData.Length; i++) - { - AvatarWearingArgs.Wearable wearable = - new AvatarWearingArgs.Wearable(nowWearing.WearableData[i].ItemID, - nowWearing.WearableData[i].WearableType); - wearingArgs.NowWearing.Add(wearable); - } - - AvatarNowWearing handlerAvatarNowWearing = OnAvatarNowWearing; - if (handlerAvatarNowWearing != null) - { - handlerAvatarNowWearing(this, wearingArgs); - } - } - break; - - case PacketType.RezSingleAttachmentFromInv: - RezSingleAttachmentFromInv handlerRezSingleAttachment = OnRezSingleAttachmentFromInv; - if (handlerRezSingleAttachment != null) - { - RezSingleAttachmentFromInvPacket rez = (RezSingleAttachmentFromInvPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (rez.AgentData.SessionID != SessionId || - rez.AgentData.AgentID != AgentId) - break; - } - #endregion - - handlerRezSingleAttachment(this, rez.ObjectData.ItemID, - rez.ObjectData.AttachmentPt); - } - - break; - - case PacketType.RezMultipleAttachmentsFromInv: - RezMultipleAttachmentsFromInv handlerRezMultipleAttachments = OnRezMultipleAttachmentsFromInv; - if (handlerRezMultipleAttachments != null) - { - RezMultipleAttachmentsFromInvPacket rez = (RezMultipleAttachmentsFromInvPacket)Pack; - handlerRezMultipleAttachments(this, rez.HeaderData, - rez.ObjectData); - } - - break; - - case PacketType.DetachAttachmentIntoInv: - UUIDNameRequest handlerDetachAttachmentIntoInv = OnDetachAttachmentIntoInv; - if (handlerDetachAttachmentIntoInv != null) - { - DetachAttachmentIntoInvPacket detachtoInv = (DetachAttachmentIntoInvPacket)Pack; - - #region Packet Session and User Check - // UNSUPPORTED ON THIS PACKET - #endregion - - UUID itemID = detachtoInv.ObjectData.ItemID; - // UUID ATTACH_agentID = detachtoInv.ObjectData.AgentID; - - handlerDetachAttachmentIntoInv(itemID, this); - } - break; - - case PacketType.ObjectAttach: - if (OnObjectAttach != null) - { - ObjectAttachPacket att = (ObjectAttachPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (att.AgentData.SessionID != SessionId || - att.AgentData.AgentID != AgentId) - break; - } - #endregion - - ObjectAttach handlerObjectAttach = OnObjectAttach; - - if (handlerObjectAttach != null) - { - if (att.ObjectData.Length > 0) - { - handlerObjectAttach(this, att.ObjectData[0].ObjectLocalID, att.AgentData.AttachmentPoint, att.ObjectData[0].Rotation, false); - } - } - } - break; - - case PacketType.ObjectDetach: - ObjectDetachPacket dett = (ObjectDetachPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (dett.AgentData.SessionID != SessionId || - dett.AgentData.AgentID != AgentId) - break; - } - #endregion - - for (int j = 0; j < dett.ObjectData.Length; j++) - { - uint obj = dett.ObjectData[j].ObjectLocalID; - ObjectDeselect handlerObjectDetach = OnObjectDetach; - if (handlerObjectDetach != null) - { - handlerObjectDetach(obj, this); - } - - } - break; - - case PacketType.ObjectDrop: - ObjectDropPacket dropp = (ObjectDropPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (dropp.AgentData.SessionID != SessionId || - dropp.AgentData.AgentID != AgentId) - break; - } - #endregion - - for (int j = 0; j < dropp.ObjectData.Length; j++) - { - uint obj = dropp.ObjectData[j].ObjectLocalID; - ObjectDrop handlerObjectDrop = OnObjectDrop; - if (handlerObjectDrop != null) - { - handlerObjectDrop(obj, this); - } - } - break; - - case PacketType.SetAlwaysRun: - SetAlwaysRunPacket run = (SetAlwaysRunPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (run.AgentData.SessionID != SessionId || - run.AgentData.AgentID != AgentId) - break; - } - #endregion - - SetAlwaysRun handlerSetAlwaysRun = OnSetAlwaysRun; - if (handlerSetAlwaysRun != null) - handlerSetAlwaysRun(this, run.AgentData.AlwaysRun); - - break; - - case PacketType.CompleteAgentMovement: - GenericCall2 handlerCompleteMovementToRegion = OnCompleteMovementToRegion; - if (handlerCompleteMovementToRegion != null) - { - handlerCompleteMovementToRegion(); - } - handlerCompleteMovementToRegion = null; - - break; - - case PacketType.AgentAnimation: - AgentAnimationPacket AgentAni = (AgentAnimationPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (AgentAni.AgentData.SessionID != SessionId || - AgentAni.AgentData.AgentID != AgentId) - break; - } - #endregion - - StartAnim handlerStartAnim = null; - StopAnim handlerStopAnim = null; - - for (int i = 0; i < AgentAni.AnimationList.Length; i++) - { - if (AgentAni.AnimationList[i].StartAnim) - { - handlerStartAnim = OnStartAnim; - if (handlerStartAnim != null) - { - handlerStartAnim(this, AgentAni.AnimationList[i].AnimID); - } - } - else - { - handlerStopAnim = OnStopAnim; - if (handlerStopAnim != null) - { - handlerStopAnim(this, AgentAni.AnimationList[i].AnimID); - } - } - } - break; - - case PacketType.AgentRequestSit: - if (OnAgentRequestSit != null) - { - AgentRequestSitPacket agentRequestSit = (AgentRequestSitPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (agentRequestSit.AgentData.SessionID != SessionId || - agentRequestSit.AgentData.AgentID != AgentId) - break; - } - #endregion - - AgentRequestSit handlerAgentRequestSit = OnAgentRequestSit; - if (handlerAgentRequestSit != null) - handlerAgentRequestSit(this, agentRequestSit.AgentData.AgentID, - agentRequestSit.TargetObject.TargetID, agentRequestSit.TargetObject.Offset); - } - break; - - case PacketType.AgentSit: - if (OnAgentSit != null) - { - AgentSitPacket agentSit = (AgentSitPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (agentSit.AgentData.SessionID != SessionId || - agentSit.AgentData.AgentID != AgentId) - break; - } - #endregion - - AgentSit handlerAgentSit = OnAgentSit; - if (handlerAgentSit != null) - { - OnAgentSit(this, agentSit.AgentData.AgentID); - } - } - break; - - case PacketType.SoundTrigger: - SoundTriggerPacket soundTriggerPacket = (SoundTriggerPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - // UNSUPPORTED ON THIS PACKET - } - #endregion - - SoundTrigger handlerSoundTrigger = OnSoundTrigger; - if (handlerSoundTrigger != null) - { - handlerSoundTrigger(soundTriggerPacket.SoundData.SoundID, soundTriggerPacket.SoundData.OwnerID, - soundTriggerPacket.SoundData.ObjectID, soundTriggerPacket.SoundData.ParentID, - soundTriggerPacket.SoundData.Gain, soundTriggerPacket.SoundData.Position, - soundTriggerPacket.SoundData.Handle); - - } - break; - - case PacketType.AvatarPickerRequest: - AvatarPickerRequestPacket avRequestQuery = (AvatarPickerRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (avRequestQuery.AgentData.SessionID != SessionId || - avRequestQuery.AgentData.AgentID != AgentId) - break; - } - #endregion - - AvatarPickerRequestPacket.AgentDataBlock Requestdata = avRequestQuery.AgentData; - AvatarPickerRequestPacket.DataBlock querydata = avRequestQuery.Data; - //m_log.Debug("Agent Sends:" + Utils.BytesToString(querydata.Name)); - - AvatarPickerRequest handlerAvatarPickerRequest = OnAvatarPickerRequest; - if (handlerAvatarPickerRequest != null) - { - handlerAvatarPickerRequest(this, Requestdata.AgentID, Requestdata.QueryID, - Utils.BytesToString(querydata.Name)); - } - break; - - case PacketType.AgentDataUpdateRequest: - AgentDataUpdateRequestPacket avRequestDataUpdatePacket = (AgentDataUpdateRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (avRequestDataUpdatePacket.AgentData.SessionID != SessionId || - avRequestDataUpdatePacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - FetchInventory handlerAgentDataUpdateRequest = OnAgentDataUpdateRequest; - - if (handlerAgentDataUpdateRequest != null) - { - handlerAgentDataUpdateRequest(this, avRequestDataUpdatePacket.AgentData.AgentID, avRequestDataUpdatePacket.AgentData.SessionID); - } - - break; - - case PacketType.UserInfoRequest: - UserInfoRequest handlerUserInfoRequest = OnUserInfoRequest; - if (handlerUserInfoRequest != null) - { - handlerUserInfoRequest(this); - } - else - { - SendUserInfoReply(false, true, ""); - } - break; - - case PacketType.UpdateUserInfo: - UpdateUserInfoPacket updateUserInfo = (UpdateUserInfoPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (updateUserInfo.AgentData.SessionID != SessionId || - updateUserInfo.AgentData.AgentID != AgentId) - break; - } - #endregion - - UpdateUserInfo handlerUpdateUserInfo = OnUpdateUserInfo; - if (handlerUpdateUserInfo != null) - { - bool visible = true; - string DirectoryVisibility = - Utils.BytesToString(updateUserInfo.UserData.DirectoryVisibility); - if (DirectoryVisibility == "hidden") - visible = false; - - handlerUpdateUserInfo( - updateUserInfo.UserData.IMViaEMail, - visible, this); - } - break; - - case PacketType.SetStartLocationRequest: - SetStartLocationRequestPacket avSetStartLocationRequestPacket = (SetStartLocationRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (avSetStartLocationRequestPacket.AgentData.SessionID != SessionId || - avSetStartLocationRequestPacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - if (avSetStartLocationRequestPacket.AgentData.AgentID == AgentId && avSetStartLocationRequestPacket.AgentData.SessionID == SessionId) - { - TeleportLocationRequest handlerSetStartLocationRequest = OnSetStartLocationRequest; - if (handlerSetStartLocationRequest != null) - { - handlerSetStartLocationRequest(this, 0, avSetStartLocationRequestPacket.StartLocationData.LocationPos, - avSetStartLocationRequestPacket.StartLocationData.LocationLookAt, - avSetStartLocationRequestPacket.StartLocationData.LocationID); - } - } - break; - - case PacketType.AgentThrottle: - AgentThrottlePacket atpack = (AgentThrottlePacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (atpack.AgentData.SessionID != SessionId || - atpack.AgentData.AgentID != AgentId) - break; - } - #endregion - - m_udpClient.SetThrottles(atpack.Throttle.Throttles); - break; - - case PacketType.AgentPause: - m_udpClient.IsPaused = true; - break; - - case PacketType.AgentResume: - m_udpClient.IsPaused = false; - SendStartPingCheck(m_udpClient.CurrentPingSequence++); - - break; - - case PacketType.ForceScriptControlRelease: - ForceReleaseControls handlerForceReleaseControls = OnForceReleaseControls; - if (handlerForceReleaseControls != null) - { - handlerForceReleaseControls(this, AgentId); - } - break; - - #endregion - - - //#region Objects/m_sceneObjects - - case PacketType.ObjectLink: - ObjectLinkPacket link = (ObjectLinkPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (link.AgentData.SessionID != SessionId || - link.AgentData.AgentID != AgentId) - break; - } - #endregion - - uint parentprimid = 0; - List childrenprims = new List(); - if (link.ObjectData.Length > 1) - { - parentprimid = link.ObjectData[0].ObjectLocalID; - - for (int i = 1; i < link.ObjectData.Length; i++) - { - childrenprims.Add(link.ObjectData[i].ObjectLocalID); - } - } - LinkObjects handlerLinkObjects = OnLinkObjects; - if (handlerLinkObjects != null) - { - handlerLinkObjects(this, parentprimid, childrenprims); - } - break; - - case PacketType.ObjectDelink: - ObjectDelinkPacket delink = (ObjectDelinkPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (delink.AgentData.SessionID != SessionId || - delink.AgentData.AgentID != AgentId) - break; - } - #endregion - - // It appears the prim at index 0 is not always the root prim (for - // instance, when one prim of a link set has been edited independently - // of the others). Therefore, we'll pass all the ids onto the delink - // method for it to decide which is the root. - List prims = new List(); - for (int i = 0; i < delink.ObjectData.Length; i++) - { - prims.Add(delink.ObjectData[i].ObjectLocalID); - } - DelinkObjects handlerDelinkObjects = OnDelinkObjects; - if (handlerDelinkObjects != null) - { - handlerDelinkObjects(prims); - } - - break; - - case PacketType.ObjectAdd: - if (OnAddPrim != null) - { - ObjectAddPacket addPacket = (ObjectAddPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (addPacket.AgentData.SessionID != SessionId || - addPacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - PrimitiveBaseShape shape = GetShapeFromAddPacket(addPacket); - // m_log.Info("[REZData]: " + addPacket.ToString()); - //BypassRaycast: 1 - //RayStart: <69.79469, 158.2652, 98.40343> - //RayEnd: <61.97724, 141.995, 92.58341> - //RayTargetID: 00000000-0000-0000-0000-000000000000 - - //Check to see if adding the prim is allowed; useful for any module wanting to restrict the - //object from rezing initially - - AddNewPrim handlerAddPrim = OnAddPrim; - if (handlerAddPrim != null) - handlerAddPrim(AgentId, ActiveGroupId, addPacket.ObjectData.RayEnd, addPacket.ObjectData.Rotation, shape, addPacket.ObjectData.BypassRaycast, addPacket.ObjectData.RayStart, addPacket.ObjectData.RayTargetID, addPacket.ObjectData.RayEndIsIntersection); - } - break; - - case PacketType.ObjectShape: - ObjectShapePacket shapePacket = (ObjectShapePacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (shapePacket.AgentData.SessionID != SessionId || - shapePacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - UpdateShape handlerUpdatePrimShape = null; - for (int i = 0; i < shapePacket.ObjectData.Length; i++) - { - handlerUpdatePrimShape = OnUpdatePrimShape; - if (handlerUpdatePrimShape != null) - { - UpdateShapeArgs shapeData = new UpdateShapeArgs(); - shapeData.ObjectLocalID = shapePacket.ObjectData[i].ObjectLocalID; - shapeData.PathBegin = shapePacket.ObjectData[i].PathBegin; - shapeData.PathCurve = shapePacket.ObjectData[i].PathCurve; - shapeData.PathEnd = shapePacket.ObjectData[i].PathEnd; - shapeData.PathRadiusOffset = shapePacket.ObjectData[i].PathRadiusOffset; - shapeData.PathRevolutions = shapePacket.ObjectData[i].PathRevolutions; - shapeData.PathScaleX = shapePacket.ObjectData[i].PathScaleX; - shapeData.PathScaleY = shapePacket.ObjectData[i].PathScaleY; - shapeData.PathShearX = shapePacket.ObjectData[i].PathShearX; - shapeData.PathShearY = shapePacket.ObjectData[i].PathShearY; - shapeData.PathSkew = shapePacket.ObjectData[i].PathSkew; - shapeData.PathTaperX = shapePacket.ObjectData[i].PathTaperX; - shapeData.PathTaperY = shapePacket.ObjectData[i].PathTaperY; - shapeData.PathTwist = shapePacket.ObjectData[i].PathTwist; - shapeData.PathTwistBegin = shapePacket.ObjectData[i].PathTwistBegin; - shapeData.ProfileBegin = shapePacket.ObjectData[i].ProfileBegin; - shapeData.ProfileCurve = shapePacket.ObjectData[i].ProfileCurve; - shapeData.ProfileEnd = shapePacket.ObjectData[i].ProfileEnd; - shapeData.ProfileHollow = shapePacket.ObjectData[i].ProfileHollow; - - handlerUpdatePrimShape(m_agentId, shapePacket.ObjectData[i].ObjectLocalID, - shapeData); - } - } - break; - - case PacketType.ObjectExtraParams: - ObjectExtraParamsPacket extraPar = (ObjectExtraParamsPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (extraPar.AgentData.SessionID != SessionId || - extraPar.AgentData.AgentID != AgentId) - break; - } - #endregion - - ObjectExtraParams handlerUpdateExtraParams = OnUpdateExtraParams; - if (handlerUpdateExtraParams != null) - { - for (int i = 0; i < extraPar.ObjectData.Length; i++) - { - handlerUpdateExtraParams(m_agentId, extraPar.ObjectData[i].ObjectLocalID, - extraPar.ObjectData[i].ParamType, - extraPar.ObjectData[i].ParamInUse, extraPar.ObjectData[i].ParamData); - } - } - break; - - case PacketType.ObjectDuplicate: - ObjectDuplicatePacket dupe = (ObjectDuplicatePacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (dupe.AgentData.SessionID != SessionId || - dupe.AgentData.AgentID != AgentId) - break; - } - #endregion - - ObjectDuplicatePacket.AgentDataBlock AgentandGroupData = dupe.AgentData; - - ObjectDuplicate handlerObjectDuplicate = null; - - for (int i = 0; i < dupe.ObjectData.Length; i++) - { - handlerObjectDuplicate = OnObjectDuplicate; - if (handlerObjectDuplicate != null) - { - handlerObjectDuplicate(dupe.ObjectData[i].ObjectLocalID, dupe.SharedData.Offset, - dupe.SharedData.DuplicateFlags, AgentandGroupData.AgentID, - AgentandGroupData.GroupID); - } - } - - break; - - case PacketType.RequestMultipleObjects: - RequestMultipleObjectsPacket incomingRequest = (RequestMultipleObjectsPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (incomingRequest.AgentData.SessionID != SessionId || - incomingRequest.AgentData.AgentID != AgentId) - break; - } - #endregion - - ObjectRequest handlerObjectRequest = null; - - for (int i = 0; i < incomingRequest.ObjectData.Length; i++) - { - handlerObjectRequest = OnObjectRequest; - if (handlerObjectRequest != null) - { - handlerObjectRequest(incomingRequest.ObjectData[i].ID, this); - } - } - break; - - case PacketType.ObjectSelect: - ObjectSelectPacket incomingselect = (ObjectSelectPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (incomingselect.AgentData.SessionID != SessionId || - incomingselect.AgentData.AgentID != AgentId) - break; - } - #endregion - - ObjectSelect handlerObjectSelect = null; - - for (int i = 0; i < incomingselect.ObjectData.Length; i++) - { - handlerObjectSelect = OnObjectSelect; - if (handlerObjectSelect != null) - { - handlerObjectSelect(incomingselect.ObjectData[i].ObjectLocalID, this); - } - } - break; - - case PacketType.ObjectDeselect: - ObjectDeselectPacket incomingdeselect = (ObjectDeselectPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (incomingdeselect.AgentData.SessionID != SessionId || - incomingdeselect.AgentData.AgentID != AgentId) - break; - } - #endregion - - ObjectDeselect handlerObjectDeselect = null; - - for (int i = 0; i < incomingdeselect.ObjectData.Length; i++) - { - handlerObjectDeselect = OnObjectDeselect; - if (handlerObjectDeselect != null) - { - OnObjectDeselect(incomingdeselect.ObjectData[i].ObjectLocalID, this); - } - } - break; - - case PacketType.ObjectPosition: - // DEPRECATED: but till libsecondlife removes it, people will use it - ObjectPositionPacket position = (ObjectPositionPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (position.AgentData.SessionID != SessionId || - position.AgentData.AgentID != AgentId) - break; - } - #endregion - - - for (int i = 0; i < position.ObjectData.Length; i++) - { - UpdateVector handlerUpdateVector = OnUpdatePrimGroupPosition; - if (handlerUpdateVector != null) - handlerUpdateVector(position.ObjectData[i].ObjectLocalID, position.ObjectData[i].Position, this); - } - - break; - - case PacketType.ObjectScale: - // DEPRECATED: but till libsecondlife removes it, people will use it - ObjectScalePacket scale = (ObjectScalePacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (scale.AgentData.SessionID != SessionId || - scale.AgentData.AgentID != AgentId) - break; - } - #endregion - - for (int i = 0; i < scale.ObjectData.Length; i++) - { - UpdateVector handlerUpdatePrimGroupScale = OnUpdatePrimGroupScale; - if (handlerUpdatePrimGroupScale != null) - handlerUpdatePrimGroupScale(scale.ObjectData[i].ObjectLocalID, scale.ObjectData[i].Scale, this); - } - - break; - - case PacketType.ObjectRotation: - // DEPRECATED: but till libsecondlife removes it, people will use it - ObjectRotationPacket rotation = (ObjectRotationPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (rotation.AgentData.SessionID != SessionId || - rotation.AgentData.AgentID != AgentId) - break; - } - #endregion - - for (int i = 0; i < rotation.ObjectData.Length; i++) - { - UpdatePrimRotation handlerUpdatePrimRotation = OnUpdatePrimGroupRotation; - if (handlerUpdatePrimRotation != null) - handlerUpdatePrimRotation(rotation.ObjectData[i].ObjectLocalID, rotation.ObjectData[i].Rotation, this); - } - - break; - - case PacketType.ObjectFlagUpdate: - ObjectFlagUpdatePacket flags = (ObjectFlagUpdatePacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (flags.AgentData.SessionID != SessionId || - flags.AgentData.AgentID != AgentId) - break; - } - #endregion - - UpdatePrimFlags handlerUpdatePrimFlags = OnUpdatePrimFlags; - - if (handlerUpdatePrimFlags != null) - { - byte[] data = Pack.ToBytes(); - // 46,47,48 are special positions within the packet - // This may change so perhaps we need a better way - // of storing this (OMV.FlagUpdatePacket.UsePhysics,etc?) - bool UsePhysics = (data[46] != 0) ? true : false; - bool IsTemporary = (data[47] != 0) ? true : false; - bool IsPhantom = (data[48] != 0) ? true : false; - handlerUpdatePrimFlags(flags.AgentData.ObjectLocalID, UsePhysics, IsTemporary, IsPhantom, this); - } - break; - case PacketType.ObjectImage: - ObjectImagePacket imagePack = (ObjectImagePacket)Pack; - - UpdatePrimTexture handlerUpdatePrimTexture = null; - for (int i = 0; i < imagePack.ObjectData.Length; i++) - { - handlerUpdatePrimTexture = OnUpdatePrimTexture; - if (handlerUpdatePrimTexture != null) - { - handlerUpdatePrimTexture(imagePack.ObjectData[i].ObjectLocalID, - imagePack.ObjectData[i].TextureEntry, this); - } - } - break; - - case PacketType.ObjectGrab: - ObjectGrabPacket grab = (ObjectGrabPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (grab.AgentData.SessionID != SessionId || - grab.AgentData.AgentID != AgentId) - break; - } - #endregion - - GrabObject handlerGrabObject = OnGrabObject; - - if (handlerGrabObject != null) - { - List touchArgs = new List(); - if ((grab.SurfaceInfo != null) && (grab.SurfaceInfo.Length > 0)) - { - foreach (ObjectGrabPacket.SurfaceInfoBlock surfaceInfo in grab.SurfaceInfo) - { - SurfaceTouchEventArgs arg = new SurfaceTouchEventArgs(); - arg.Binormal = surfaceInfo.Binormal; - arg.FaceIndex = surfaceInfo.FaceIndex; - arg.Normal = surfaceInfo.Normal; - arg.Position = surfaceInfo.Position; - arg.STCoord = surfaceInfo.STCoord; - arg.UVCoord = surfaceInfo.UVCoord; - touchArgs.Add(arg); - } - } - handlerGrabObject(grab.ObjectData.LocalID, grab.ObjectData.GrabOffset, this, touchArgs); - } - break; - - case PacketType.ObjectGrabUpdate: - ObjectGrabUpdatePacket grabUpdate = (ObjectGrabUpdatePacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (grabUpdate.AgentData.SessionID != SessionId || - grabUpdate.AgentData.AgentID != AgentId) - break; - } - #endregion - - MoveObject handlerGrabUpdate = OnGrabUpdate; - - if (handlerGrabUpdate != null) - { - List touchArgs = new List(); - if ((grabUpdate.SurfaceInfo != null) && (grabUpdate.SurfaceInfo.Length > 0)) - { - foreach (ObjectGrabUpdatePacket.SurfaceInfoBlock surfaceInfo in grabUpdate.SurfaceInfo) - { - SurfaceTouchEventArgs arg = new SurfaceTouchEventArgs(); - arg.Binormal = surfaceInfo.Binormal; - arg.FaceIndex = surfaceInfo.FaceIndex; - arg.Normal = surfaceInfo.Normal; - arg.Position = surfaceInfo.Position; - arg.STCoord = surfaceInfo.STCoord; - arg.UVCoord = surfaceInfo.UVCoord; - touchArgs.Add(arg); - } - } - handlerGrabUpdate(grabUpdate.ObjectData.ObjectID, grabUpdate.ObjectData.GrabOffsetInitial, - grabUpdate.ObjectData.GrabPosition, this, touchArgs); - } - break; - - case PacketType.ObjectDeGrab: - ObjectDeGrabPacket deGrab = (ObjectDeGrabPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (deGrab.AgentData.SessionID != SessionId || - deGrab.AgentData.AgentID != AgentId) - break; - } - #endregion - - DeGrabObject handlerDeGrabObject = OnDeGrabObject; - if (handlerDeGrabObject != null) - { - List touchArgs = new List(); - if ((deGrab.SurfaceInfo != null) && (deGrab.SurfaceInfo.Length > 0)) - { - foreach (ObjectDeGrabPacket.SurfaceInfoBlock surfaceInfo in deGrab.SurfaceInfo) - { - SurfaceTouchEventArgs arg = new SurfaceTouchEventArgs(); - arg.Binormal = surfaceInfo.Binormal; - arg.FaceIndex = surfaceInfo.FaceIndex; - arg.Normal = surfaceInfo.Normal; - arg.Position = surfaceInfo.Position; - arg.STCoord = surfaceInfo.STCoord; - arg.UVCoord = surfaceInfo.UVCoord; - touchArgs.Add(arg); - } - } - handlerDeGrabObject(deGrab.ObjectData.LocalID, this, touchArgs); - } - break; - - case PacketType.ObjectSpinStart: - //m_log.Warn("[CLIENT]: unhandled ObjectSpinStart packet"); - ObjectSpinStartPacket spinStart = (ObjectSpinStartPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (spinStart.AgentData.SessionID != SessionId || - spinStart.AgentData.AgentID != AgentId) - break; - } - #endregion - - SpinStart handlerSpinStart = OnSpinStart; - if (handlerSpinStart != null) - { - handlerSpinStart(spinStart.ObjectData.ObjectID, this); - } - break; - case PacketType.ObjectSpinUpdate: - //m_log.Warn("[CLIENT]: unhandled ObjectSpinUpdate packet"); - ObjectSpinUpdatePacket spinUpdate = (ObjectSpinUpdatePacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (spinUpdate.AgentData.SessionID != SessionId || - spinUpdate.AgentData.AgentID != AgentId) - break; - } - #endregion - - Vector3 axis; - float angle; - spinUpdate.ObjectData.Rotation.GetAxisAngle(out axis, out angle); - //m_log.Warn("[CLIENT]: ObjectSpinUpdate packet rot axis:" + axis + " angle:" + angle); - - SpinObject handlerSpinUpdate = OnSpinUpdate; - if (handlerSpinUpdate != null) - { - handlerSpinUpdate(spinUpdate.ObjectData.ObjectID, spinUpdate.ObjectData.Rotation, this); - } - break; - - - case PacketType.ObjectSpinStop: - //m_log.Warn("[CLIENT]: unhandled ObjectSpinStop packet"); - ObjectSpinStopPacket spinStop = (ObjectSpinStopPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (spinStop.AgentData.SessionID != SessionId || - spinStop.AgentData.AgentID != AgentId) - break; - } - #endregion - - SpinStop handlerSpinStop = OnSpinStop; - if (handlerSpinStop != null) - { - handlerSpinStop(spinStop.ObjectData.ObjectID, this); - } - break; - - case PacketType.ObjectDescription: - ObjectDescriptionPacket objDes = (ObjectDescriptionPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (objDes.AgentData.SessionID != SessionId || - objDes.AgentData.AgentID != AgentId) - break; - } - #endregion - - GenericCall7 handlerObjectDescription = null; - - for (int i = 0; i < objDes.ObjectData.Length; i++) - { - handlerObjectDescription = OnObjectDescription; - if (handlerObjectDescription != null) - { - handlerObjectDescription(this, objDes.ObjectData[i].LocalID, - Util.FieldToString(objDes.ObjectData[i].Description)); - } - } - break; - - case PacketType.ObjectName: - ObjectNamePacket objName = (ObjectNamePacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (objName.AgentData.SessionID != SessionId || - objName.AgentData.AgentID != AgentId) - break; - } - #endregion - - GenericCall7 handlerObjectName = null; - for (int i = 0; i < objName.ObjectData.Length; i++) - { - handlerObjectName = OnObjectName; - if (handlerObjectName != null) - { - handlerObjectName(this, objName.ObjectData[i].LocalID, - Util.FieldToString(objName.ObjectData[i].Name)); - } - } - break; - - case PacketType.ObjectPermissions: - if (OnObjectPermissions != null) - { - ObjectPermissionsPacket newobjPerms = (ObjectPermissionsPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (newobjPerms.AgentData.SessionID != SessionId || - newobjPerms.AgentData.AgentID != AgentId) - break; - } - #endregion - - UUID AgentID = newobjPerms.AgentData.AgentID; - UUID SessionID = newobjPerms.AgentData.SessionID; - - ObjectPermissions handlerObjectPermissions = null; - - for (int i = 0; i < newobjPerms.ObjectData.Length; i++) - { - ObjectPermissionsPacket.ObjectDataBlock permChanges = newobjPerms.ObjectData[i]; - - byte field = permChanges.Field; - uint localID = permChanges.ObjectLocalID; - uint mask = permChanges.Mask; - byte set = permChanges.Set; - - handlerObjectPermissions = OnObjectPermissions; - - if (handlerObjectPermissions != null) - handlerObjectPermissions(this, AgentID, SessionID, field, localID, mask, set); - } - } - - // Here's our data, - // PermField contains the field the info goes into - // PermField determines which mask we're changing - // - // chmask is the mask of the change - // setTF is whether we're adding it or taking it away - // - // objLocalID is the localID of the object. - - // Unfortunately, we have to pass the event the packet because objData is an array - // That means multiple object perms may be updated in a single packet. - - break; - - case PacketType.Undo: - UndoPacket undoitem = (UndoPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (undoitem.AgentData.SessionID != SessionId || - undoitem.AgentData.AgentID != AgentId) - break; - } - #endregion - - if (undoitem.ObjectData.Length > 0) - { - for (int i = 0; i < undoitem.ObjectData.Length; i++) - { - UUID objiD = undoitem.ObjectData[i].ObjectID; - AgentSit handlerOnUndo = OnUndo; - if (handlerOnUndo != null) - { - handlerOnUndo(this, objiD); - } - - } - } - break; - - case PacketType.ObjectDuplicateOnRay: - ObjectDuplicateOnRayPacket dupeOnRay = (ObjectDuplicateOnRayPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (dupeOnRay.AgentData.SessionID != SessionId || - dupeOnRay.AgentData.AgentID != AgentId) - break; - } - #endregion - - ObjectDuplicateOnRay handlerObjectDuplicateOnRay = null; - - for (int i = 0; i < dupeOnRay.ObjectData.Length; i++) - { - handlerObjectDuplicateOnRay = OnObjectDuplicateOnRay; - if (handlerObjectDuplicateOnRay != null) - { - handlerObjectDuplicateOnRay(dupeOnRay.ObjectData[i].ObjectLocalID, dupeOnRay.AgentData.DuplicateFlags, - dupeOnRay.AgentData.AgentID, dupeOnRay.AgentData.GroupID, dupeOnRay.AgentData.RayTargetID, dupeOnRay.AgentData.RayEnd, - dupeOnRay.AgentData.RayStart, dupeOnRay.AgentData.BypassRaycast, dupeOnRay.AgentData.RayEndIsIntersection, - dupeOnRay.AgentData.CopyCenters, dupeOnRay.AgentData.CopyRotates); - } - } - - break; - - case PacketType.RequestObjectPropertiesFamily: - //This powers the little tooltip that appears when you move your mouse over an object - RequestObjectPropertiesFamilyPacket packToolTip = (RequestObjectPropertiesFamilyPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (packToolTip.AgentData.SessionID != SessionId || - packToolTip.AgentData.AgentID != AgentId) - break; - } - #endregion - - RequestObjectPropertiesFamilyPacket.ObjectDataBlock packObjBlock = packToolTip.ObjectData; - - RequestObjectPropertiesFamily handlerRequestObjectPropertiesFamily = OnRequestObjectPropertiesFamily; - - if (handlerRequestObjectPropertiesFamily != null) - { - handlerRequestObjectPropertiesFamily(this, m_agentId, packObjBlock.RequestFlags, - packObjBlock.ObjectID); - } - - break; - - case PacketType.ObjectIncludeInSearch: - //This lets us set objects to appear in search (stuff like DataSnapshot, etc) - ObjectIncludeInSearchPacket packInSearch = (ObjectIncludeInSearchPacket)Pack; - ObjectIncludeInSearch handlerObjectIncludeInSearch = null; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (packInSearch.AgentData.SessionID != SessionId || - packInSearch.AgentData.AgentID != AgentId) - break; - } - #endregion - - foreach (ObjectIncludeInSearchPacket.ObjectDataBlock objData in packInSearch.ObjectData) - { - bool inSearch = objData.IncludeInSearch; - uint localID = objData.ObjectLocalID; - - handlerObjectIncludeInSearch = OnObjectIncludeInSearch; - - if (handlerObjectIncludeInSearch != null) - { - handlerObjectIncludeInSearch(this, inSearch, localID); - } - } - break; - - case PacketType.ScriptAnswerYes: - ScriptAnswerYesPacket scriptAnswer = (ScriptAnswerYesPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (scriptAnswer.AgentData.SessionID != SessionId || - scriptAnswer.AgentData.AgentID != AgentId) - break; - } - #endregion - - ScriptAnswer handlerScriptAnswer = OnScriptAnswer; - if (handlerScriptAnswer != null) - { - handlerScriptAnswer(this, scriptAnswer.Data.TaskID, scriptAnswer.Data.ItemID, scriptAnswer.Data.Questions); - } - break; - - case PacketType.ObjectClickAction: - ObjectClickActionPacket ocpacket = (ObjectClickActionPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (ocpacket.AgentData.SessionID != SessionId || - ocpacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - GenericCall7 handlerObjectClickAction = OnObjectClickAction; - if (handlerObjectClickAction != null) - { - foreach (ObjectClickActionPacket.ObjectDataBlock odata in ocpacket.ObjectData) - { - byte action = odata.ClickAction; - uint localID = odata.ObjectLocalID; - handlerObjectClickAction(this, localID, action.ToString()); - } - } - break; - - case PacketType.ObjectMaterial: - ObjectMaterialPacket ompacket = (ObjectMaterialPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (ompacket.AgentData.SessionID != SessionId || - ompacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - GenericCall7 handlerObjectMaterial = OnObjectMaterial; - if (handlerObjectMaterial != null) - { - foreach (ObjectMaterialPacket.ObjectDataBlock odata in ompacket.ObjectData) - { - byte material = odata.Material; - uint localID = odata.ObjectLocalID; - handlerObjectMaterial(this, localID, material.ToString()); - } - } - break; - - //#endregion - - //#region Inventory/Asset/Other related packets - - case PacketType.RequestImage: - RequestImagePacket imageRequest = (RequestImagePacket)Pack; - //m_log.Debug("image request: " + Pack.ToString()); - - #region Packet Session and User Check - if (m_checkPackets) - { - if (imageRequest.AgentData.SessionID != SessionId || - imageRequest.AgentData.AgentID != AgentId) - break; - } - #endregion - - //handlerTextureRequest = null; - for (int i = 0; i < imageRequest.RequestImage.Length; i++) - { - if (OnRequestTexture != null) - { - TextureRequestArgs args = new TextureRequestArgs(); - - RequestImagePacket.RequestImageBlock block = imageRequest.RequestImage[i]; - - args.RequestedAssetID = block.Image; - args.DiscardLevel = block.DiscardLevel; - args.PacketNumber = block.Packet; - args.Priority = block.DownloadPriority; - args.requestSequence = imageRequest.Header.Sequence; - - // NOTE: This is not a built in part of the LLUDP protocol, but we double the - // priority of avatar textures to get avatars rezzing in faster than the - // surrounding scene - if ((ImageType)block.Type == ImageType.Baked) - args.Priority *= 2.0f; - - //handlerTextureRequest = OnRequestTexture; - - //if (handlerTextureRequest != null) - //OnRequestTexture(this, args); - - // in the end, we null this, so we have to check if it's null - if (m_imageManager != null) - { - m_imageManager.EnqueueReq(args); - } - } - } - break; - - case PacketType.TransferRequest: - //m_log.Debug("ClientView.ProcessPackets.cs:ProcessInPacket() - Got transfer request"); - - TransferRequestPacket transfer = (TransferRequestPacket)Pack; - //m_log.Debug("Transfer Request: " + transfer.ToString()); - // Validate inventory transfers - // Has to be done here, because AssetCache can't do it - // - UUID taskID = UUID.Zero; - if (transfer.TransferInfo.SourceType == 3) - { - taskID = new UUID(transfer.TransferInfo.Params, 48); - UUID itemID = new UUID(transfer.TransferInfo.Params, 64); - UUID requestID = new UUID(transfer.TransferInfo.Params, 80); - if (!(((Scene)m_scene).Permissions.BypassPermissions())) - { - if (taskID != UUID.Zero) // Prim - { - SceneObjectPart part = ((Scene)m_scene).GetSceneObjectPart(taskID); - if (part == null) - break; - - if (part.OwnerID != AgentId) - break; - - if ((part.OwnerMask & (uint)PermissionMask.Modify) == 0) - break; - - TaskInventoryItem ti = part.Inventory.GetInventoryItem(itemID); - if (ti == null) - break; - - if (ti.OwnerID != AgentId) - break; - - if ((ti.CurrentPermissions & ((uint)PermissionMask.Modify | (uint)PermissionMask.Copy | (uint)PermissionMask.Transfer)) != ((uint)PermissionMask.Modify | (uint)PermissionMask.Copy | (uint)PermissionMask.Transfer)) - break; - - if (ti.AssetID != requestID) - break; - } - else // Agent - { - IInventoryService invService = m_scene.RequestModuleInterface(); - InventoryItemBase assetRequestItem = new InventoryItemBase(itemID, AgentId); - assetRequestItem = invService.GetItem(assetRequestItem); - if (assetRequestItem == null) - { - assetRequestItem = ((Scene)m_scene).CommsManager.UserProfileCacheService.LibraryRoot.FindItem(itemID); - if (assetRequestItem == null) - return; - } - - // At this point, we need to apply perms - // only to notecards and scripts. All - // other asset types are always available - // - if (assetRequestItem.AssetType == 10) - { - if (!((Scene)m_scene).Permissions.CanViewScript(itemID, UUID.Zero, AgentId)) - { - SendAgentAlertMessage("Insufficient permissions to view script", false); - break; - } - } - else if (assetRequestItem.AssetType == 7) - { - if (!((Scene)m_scene).Permissions.CanViewNotecard(itemID, UUID.Zero, AgentId)) - { - SendAgentAlertMessage("Insufficient permissions to view notecard", false); - break; - } - } - - if (assetRequestItem.AssetID != requestID) - break; - } - } - } - - //m_assetCache.AddAssetRequest(this, transfer); - - MakeAssetRequest(transfer, taskID); - - // RequestAsset = OnRequestAsset; - // if (RequestAsset != null) - // { - // RequestAsset(this, transfer); - // } - - break; - - case PacketType.AssetUploadRequest: - AssetUploadRequestPacket request = (AssetUploadRequestPacket)Pack; - - - // m_log.Debug("upload request " + request.ToString()); - // m_log.Debug("upload request was for assetid: " + request.AssetBlock.TransactionID.Combine(this.SecureSessionId).ToString()); - UUID temp = UUID.Combine(request.AssetBlock.TransactionID, SecureSessionId); - - UDPAssetUploadRequest handlerAssetUploadRequest = OnAssetUploadRequest; - - if (handlerAssetUploadRequest != null) - { - handlerAssetUploadRequest(this, temp, - request.AssetBlock.TransactionID, request.AssetBlock.Type, - request.AssetBlock.AssetData, request.AssetBlock.StoreLocal, - request.AssetBlock.Tempfile); - } - break; - - case PacketType.RequestXfer: - RequestXferPacket xferReq = (RequestXferPacket)Pack; - - RequestXfer handlerRequestXfer = OnRequestXfer; - - if (handlerRequestXfer != null) - { - handlerRequestXfer(this, xferReq.XferID.ID, Util.FieldToString(xferReq.XferID.Filename)); - } - break; - - case PacketType.SendXferPacket: - SendXferPacketPacket xferRec = (SendXferPacketPacket)Pack; - - XferReceive handlerXferReceive = OnXferReceive; - if (handlerXferReceive != null) - { - handlerXferReceive(this, xferRec.XferID.ID, xferRec.XferID.Packet, xferRec.DataPacket.Data); - } - break; - - case PacketType.ConfirmXferPacket: - ConfirmXferPacketPacket confirmXfer = (ConfirmXferPacketPacket)Pack; - - ConfirmXfer handlerConfirmXfer = OnConfirmXfer; - if (handlerConfirmXfer != null) - { - handlerConfirmXfer(this, confirmXfer.XferID.ID, confirmXfer.XferID.Packet); - } - break; - - case PacketType.AbortXfer: - AbortXferPacket abortXfer = (AbortXferPacket)Pack; - AbortXfer handlerAbortXfer = OnAbortXfer; - if (handlerAbortXfer != null) - { - handlerAbortXfer(this, abortXfer.XferID.ID); - } - - break; - - case PacketType.CreateInventoryFolder: - CreateInventoryFolderPacket invFolder = (CreateInventoryFolderPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (invFolder.AgentData.SessionID != SessionId || - invFolder.AgentData.AgentID != AgentId) - break; - } - #endregion - - CreateInventoryFolder handlerCreateInventoryFolder = OnCreateNewInventoryFolder; - if (handlerCreateInventoryFolder != null) - { - handlerCreateInventoryFolder(this, invFolder.FolderData.FolderID, - (ushort)invFolder.FolderData.Type, - Util.FieldToString(invFolder.FolderData.Name), - invFolder.FolderData.ParentID); - } - break; - - case PacketType.UpdateInventoryFolder: - if (OnUpdateInventoryFolder != null) - { - UpdateInventoryFolderPacket invFolderx = (UpdateInventoryFolderPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (invFolderx.AgentData.SessionID != SessionId || - invFolderx.AgentData.AgentID != AgentId) - break; - } - #endregion - - UpdateInventoryFolder handlerUpdateInventoryFolder = null; - - for (int i = 0; i < invFolderx.FolderData.Length; i++) - { - handlerUpdateInventoryFolder = OnUpdateInventoryFolder; - if (handlerUpdateInventoryFolder != null) - { - OnUpdateInventoryFolder(this, invFolderx.FolderData[i].FolderID, - (ushort)invFolderx.FolderData[i].Type, - Util.FieldToString(invFolderx.FolderData[i].Name), - invFolderx.FolderData[i].ParentID); - } - } - } - break; - - case PacketType.MoveInventoryFolder: - if (OnMoveInventoryFolder != null) - { - MoveInventoryFolderPacket invFoldery = (MoveInventoryFolderPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (invFoldery.AgentData.SessionID != SessionId || - invFoldery.AgentData.AgentID != AgentId) - break; - } - #endregion - - MoveInventoryFolder handlerMoveInventoryFolder = null; - - for (int i = 0; i < invFoldery.InventoryData.Length; i++) - { - handlerMoveInventoryFolder = OnMoveInventoryFolder; - if (handlerMoveInventoryFolder != null) - { - OnMoveInventoryFolder(this, invFoldery.InventoryData[i].FolderID, - invFoldery.InventoryData[i].ParentID); - } - } - } - break; - - case PacketType.CreateInventoryItem: - CreateInventoryItemPacket createItem = (CreateInventoryItemPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (createItem.AgentData.SessionID != SessionId || - createItem.AgentData.AgentID != AgentId) - break; - } - #endregion - - CreateNewInventoryItem handlerCreateNewInventoryItem = OnCreateNewInventoryItem; - if (handlerCreateNewInventoryItem != null) - { - handlerCreateNewInventoryItem(this, createItem.InventoryBlock.TransactionID, - createItem.InventoryBlock.FolderID, - createItem.InventoryBlock.CallbackID, - Util.FieldToString(createItem.InventoryBlock.Description), - Util.FieldToString(createItem.InventoryBlock.Name), - createItem.InventoryBlock.InvType, - createItem.InventoryBlock.Type, - createItem.InventoryBlock.WearableType, - createItem.InventoryBlock.NextOwnerMask, - Util.UnixTimeSinceEpoch()); - } - break; - - case PacketType.FetchInventory: - if (OnFetchInventory != null) - { - FetchInventoryPacket FetchInventoryx = (FetchInventoryPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (FetchInventoryx.AgentData.SessionID != SessionId || - FetchInventoryx.AgentData.AgentID != AgentId) - break; - } - #endregion - - FetchInventory handlerFetchInventory = null; - - for (int i = 0; i < FetchInventoryx.InventoryData.Length; i++) - { - handlerFetchInventory = OnFetchInventory; - - if (handlerFetchInventory != null) - { - OnFetchInventory(this, FetchInventoryx.InventoryData[i].ItemID, - FetchInventoryx.InventoryData[i].OwnerID); - } - } - } - break; - - case PacketType.FetchInventoryDescendents: - FetchInventoryDescendentsPacket Fetch = (FetchInventoryDescendentsPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (Fetch.AgentData.SessionID != SessionId || - Fetch.AgentData.AgentID != AgentId) - break; - } - #endregion - - FetchInventoryDescendents handlerFetchInventoryDescendents = OnFetchInventoryDescendents; - if (handlerFetchInventoryDescendents != null) - { - handlerFetchInventoryDescendents(this, Fetch.InventoryData.FolderID, Fetch.InventoryData.OwnerID, - Fetch.InventoryData.FetchFolders, Fetch.InventoryData.FetchItems, - Fetch.InventoryData.SortOrder); - } - break; - - case PacketType.PurgeInventoryDescendents: - PurgeInventoryDescendentsPacket Purge = (PurgeInventoryDescendentsPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (Purge.AgentData.SessionID != SessionId || - Purge.AgentData.AgentID != AgentId) - break; - } - #endregion - - PurgeInventoryDescendents handlerPurgeInventoryDescendents = OnPurgeInventoryDescendents; - if (handlerPurgeInventoryDescendents != null) - { - handlerPurgeInventoryDescendents(this, Purge.InventoryData.FolderID); - } - break; - - case PacketType.UpdateInventoryItem: - UpdateInventoryItemPacket inventoryItemUpdate = (UpdateInventoryItemPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (inventoryItemUpdate.AgentData.SessionID != SessionId || - inventoryItemUpdate.AgentData.AgentID != AgentId) - break; - } - #endregion - - if (OnUpdateInventoryItem != null) - { - UpdateInventoryItem handlerUpdateInventoryItem = null; - for (int i = 0; i < inventoryItemUpdate.InventoryData.Length; i++) - { - handlerUpdateInventoryItem = OnUpdateInventoryItem; - - if (handlerUpdateInventoryItem != null) - { - InventoryItemBase itemUpd = new InventoryItemBase(); - itemUpd.ID = inventoryItemUpdate.InventoryData[i].ItemID; - itemUpd.Name = Util.FieldToString(inventoryItemUpdate.InventoryData[i].Name); - itemUpd.Description = Util.FieldToString(inventoryItemUpdate.InventoryData[i].Description); - itemUpd.GroupID = inventoryItemUpdate.InventoryData[i].GroupID; - itemUpd.GroupOwned = inventoryItemUpdate.InventoryData[i].GroupOwned; - itemUpd.GroupPermissions = inventoryItemUpdate.InventoryData[i].GroupMask; - itemUpd.NextPermissions = inventoryItemUpdate.InventoryData[i].NextOwnerMask; - itemUpd.EveryOnePermissions = inventoryItemUpdate.InventoryData[i].EveryoneMask; - itemUpd.CreationDate = inventoryItemUpdate.InventoryData[i].CreationDate; - itemUpd.Folder = inventoryItemUpdate.InventoryData[i].FolderID; - itemUpd.InvType = inventoryItemUpdate.InventoryData[i].InvType; - itemUpd.SalePrice = inventoryItemUpdate.InventoryData[i].SalePrice; - itemUpd.SaleType = inventoryItemUpdate.InventoryData[i].SaleType; - itemUpd.Flags = inventoryItemUpdate.InventoryData[i].Flags; - - OnUpdateInventoryItem(this, inventoryItemUpdate.InventoryData[i].TransactionID, - inventoryItemUpdate.InventoryData[i].ItemID, - itemUpd); - } - } - } - break; - - case PacketType.CopyInventoryItem: - CopyInventoryItemPacket copyitem = (CopyInventoryItemPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (copyitem.AgentData.SessionID != SessionId || - copyitem.AgentData.AgentID != AgentId) - break; - } - #endregion - - CopyInventoryItem handlerCopyInventoryItem = null; - if (OnCopyInventoryItem != null) - { - foreach (CopyInventoryItemPacket.InventoryDataBlock datablock in copyitem.InventoryData) - { - handlerCopyInventoryItem = OnCopyInventoryItem; - if (handlerCopyInventoryItem != null) - { - handlerCopyInventoryItem(this, datablock.CallbackID, datablock.OldAgentID, - datablock.OldItemID, datablock.NewFolderID, - Util.FieldToString(datablock.NewName)); - } - } - } - break; - - case PacketType.MoveInventoryItem: - MoveInventoryItemPacket moveitem = (MoveInventoryItemPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (moveitem.AgentData.SessionID != SessionId || - moveitem.AgentData.AgentID != AgentId) - break; - } - #endregion - - if (OnMoveInventoryItem != null) - { - MoveInventoryItem handlerMoveInventoryItem = null; - InventoryItemBase itm = null; - List items = new List(); - foreach (MoveInventoryItemPacket.InventoryDataBlock datablock in moveitem.InventoryData) - { - itm = new InventoryItemBase(datablock.ItemID, AgentId); - itm.Folder = datablock.FolderID; - itm.Name = Util.FieldToString(datablock.NewName); - // weird, comes out as empty string - //m_log.DebugFormat("[XXX] new name: {0}", itm.Name); - items.Add(itm); - } - handlerMoveInventoryItem = OnMoveInventoryItem; - if (handlerMoveInventoryItem != null) - { - handlerMoveInventoryItem(this, items); - } - } - break; - - case PacketType.RemoveInventoryItem: - RemoveInventoryItemPacket removeItem = (RemoveInventoryItemPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (removeItem.AgentData.SessionID != SessionId || - removeItem.AgentData.AgentID != AgentId) - break; - } - #endregion - - if (OnRemoveInventoryItem != null) - { - RemoveInventoryItem handlerRemoveInventoryItem = null; - List uuids = new List(); - foreach (RemoveInventoryItemPacket.InventoryDataBlock datablock in removeItem.InventoryData) - { - uuids.Add(datablock.ItemID); - } - handlerRemoveInventoryItem = OnRemoveInventoryItem; - if (handlerRemoveInventoryItem != null) - { - handlerRemoveInventoryItem(this, uuids); - } - - } - break; - - case PacketType.RemoveInventoryFolder: - RemoveInventoryFolderPacket removeFolder = (RemoveInventoryFolderPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (removeFolder.AgentData.SessionID != SessionId || - removeFolder.AgentData.AgentID != AgentId) - break; - } - #endregion - - if (OnRemoveInventoryFolder != null) - { - RemoveInventoryFolder handlerRemoveInventoryFolder = null; - List uuids = new List(); - foreach (RemoveInventoryFolderPacket.FolderDataBlock datablock in removeFolder.FolderData) - { - uuids.Add(datablock.FolderID); - } - handlerRemoveInventoryFolder = OnRemoveInventoryFolder; - if (handlerRemoveInventoryFolder != null) - { - handlerRemoveInventoryFolder(this, uuids); - } - } - break; - - case PacketType.RemoveInventoryObjects: - RemoveInventoryObjectsPacket removeObject = (RemoveInventoryObjectsPacket)Pack; - #region Packet Session and User Check - if (m_checkPackets) - { - if (removeObject.AgentData.SessionID != SessionId || - removeObject.AgentData.AgentID != AgentId) - break; - } - #endregion - if (OnRemoveInventoryFolder != null) - { - RemoveInventoryFolder handlerRemoveInventoryFolder = null; - List uuids = new List(); - foreach (RemoveInventoryObjectsPacket.FolderDataBlock datablock in removeObject.FolderData) - { - uuids.Add(datablock.FolderID); - } - handlerRemoveInventoryFolder = OnRemoveInventoryFolder; - if (handlerRemoveInventoryFolder != null) - { - handlerRemoveInventoryFolder(this, uuids); - } - } - - if (OnRemoveInventoryItem != null) - { - RemoveInventoryItem handlerRemoveInventoryItem = null; - List uuids = new List(); - foreach (RemoveInventoryObjectsPacket.ItemDataBlock datablock in removeObject.ItemData) - { - uuids.Add(datablock.ItemID); - } - handlerRemoveInventoryItem = OnRemoveInventoryItem; - if (handlerRemoveInventoryItem != null) - { - handlerRemoveInventoryItem(this, uuids); - } - } - break; - - case PacketType.RequestTaskInventory: - RequestTaskInventoryPacket requesttask = (RequestTaskInventoryPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (requesttask.AgentData.SessionID != SessionId || - requesttask.AgentData.AgentID != AgentId) - break; - } - #endregion - - RequestTaskInventory handlerRequestTaskInventory = OnRequestTaskInventory; - if (handlerRequestTaskInventory != null) - { - handlerRequestTaskInventory(this, requesttask.InventoryData.LocalID); - } - break; - - case PacketType.UpdateTaskInventory: - UpdateTaskInventoryPacket updatetask = (UpdateTaskInventoryPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (updatetask.AgentData.SessionID != SessionId || - updatetask.AgentData.AgentID != AgentId) - break; - } - #endregion - - if (OnUpdateTaskInventory != null) - { - if (updatetask.UpdateData.Key == 0) - { - UpdateTaskInventory handlerUpdateTaskInventory = OnUpdateTaskInventory; - if (handlerUpdateTaskInventory != null) - { - TaskInventoryItem newTaskItem = new TaskInventoryItem(); - newTaskItem.ItemID = updatetask.InventoryData.ItemID; - newTaskItem.ParentID = updatetask.InventoryData.FolderID; - newTaskItem.CreatorID = updatetask.InventoryData.CreatorID; - newTaskItem.OwnerID = updatetask.InventoryData.OwnerID; - newTaskItem.GroupID = updatetask.InventoryData.GroupID; - newTaskItem.BasePermissions = updatetask.InventoryData.BaseMask; - newTaskItem.CurrentPermissions = updatetask.InventoryData.OwnerMask; - newTaskItem.GroupPermissions = updatetask.InventoryData.GroupMask; - newTaskItem.EveryonePermissions = updatetask.InventoryData.EveryoneMask; - newTaskItem.NextPermissions = updatetask.InventoryData.NextOwnerMask; - //newTaskItem.GroupOwned=updatetask.InventoryData.GroupOwned; - newTaskItem.Type = updatetask.InventoryData.Type; - newTaskItem.InvType = updatetask.InventoryData.InvType; - newTaskItem.Flags = updatetask.InventoryData.Flags; - //newTaskItem.SaleType=updatetask.InventoryData.SaleType; - //newTaskItem.SalePrice=updatetask.InventoryData.SalePrice;; - newTaskItem.Name = Util.FieldToString(updatetask.InventoryData.Name); - newTaskItem.Description = Util.FieldToString(updatetask.InventoryData.Description); - newTaskItem.CreationDate = (uint)updatetask.InventoryData.CreationDate; - handlerUpdateTaskInventory(this, updatetask.InventoryData.TransactionID, - newTaskItem, updatetask.UpdateData.LocalID); - } - } - } - - break; - - case PacketType.RemoveTaskInventory: - - RemoveTaskInventoryPacket removeTask = (RemoveTaskInventoryPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (removeTask.AgentData.SessionID != SessionId || - removeTask.AgentData.AgentID != AgentId) - break; - } - #endregion - - RemoveTaskInventory handlerRemoveTaskItem = OnRemoveTaskItem; - - if (handlerRemoveTaskItem != null) - { - handlerRemoveTaskItem(this, removeTask.InventoryData.ItemID, removeTask.InventoryData.LocalID); - } - - break; - - case PacketType.MoveTaskInventory: - - MoveTaskInventoryPacket moveTaskInventoryPacket = (MoveTaskInventoryPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (moveTaskInventoryPacket.AgentData.SessionID != SessionId || - moveTaskInventoryPacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - MoveTaskInventory handlerMoveTaskItem = OnMoveTaskItem; - - if (handlerMoveTaskItem != null) - { - handlerMoveTaskItem( - this, moveTaskInventoryPacket.AgentData.FolderID, - moveTaskInventoryPacket.InventoryData.LocalID, - moveTaskInventoryPacket.InventoryData.ItemID); - } - - break; - - case PacketType.RezScript: - //m_log.Debug(Pack.ToString()); - RezScriptPacket rezScriptx = (RezScriptPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (rezScriptx.AgentData.SessionID != SessionId || - rezScriptx.AgentData.AgentID != AgentId) - break; - } - #endregion - - RezScript handlerRezScript = OnRezScript; - InventoryItemBase item = new InventoryItemBase(); - item.ID = rezScriptx.InventoryBlock.ItemID; - item.Folder = rezScriptx.InventoryBlock.FolderID; - item.CreatorId = rezScriptx.InventoryBlock.CreatorID.ToString(); - item.Owner = rezScriptx.InventoryBlock.OwnerID; - item.BasePermissions = rezScriptx.InventoryBlock.BaseMask; - item.CurrentPermissions = rezScriptx.InventoryBlock.OwnerMask; - item.EveryOnePermissions = rezScriptx.InventoryBlock.EveryoneMask; - item.NextPermissions = rezScriptx.InventoryBlock.NextOwnerMask; - item.GroupPermissions = rezScriptx.InventoryBlock.GroupMask; - item.GroupOwned = rezScriptx.InventoryBlock.GroupOwned; - item.GroupID = rezScriptx.InventoryBlock.GroupID; - item.AssetType = rezScriptx.InventoryBlock.Type; - item.InvType = rezScriptx.InventoryBlock.InvType; - item.Flags = rezScriptx.InventoryBlock.Flags; - item.SaleType = rezScriptx.InventoryBlock.SaleType; - item.SalePrice = rezScriptx.InventoryBlock.SalePrice; - item.Name = Util.FieldToString(rezScriptx.InventoryBlock.Name); - item.Description = Util.FieldToString(rezScriptx.InventoryBlock.Description); - item.CreationDate = rezScriptx.InventoryBlock.CreationDate; - - if (handlerRezScript != null) - { - handlerRezScript(this, item, rezScriptx.InventoryBlock.TransactionID, rezScriptx.UpdateBlock.ObjectLocalID); - } - break; - - case PacketType.MapLayerRequest: - RequestMapLayer(); - break; - case PacketType.MapBlockRequest: - MapBlockRequestPacket MapRequest = (MapBlockRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (MapRequest.AgentData.SessionID != SessionId || - MapRequest.AgentData.AgentID != AgentId) - break; - } - #endregion - - RequestMapBlocks handlerRequestMapBlocks = OnRequestMapBlocks; - if (handlerRequestMapBlocks != null) - { - handlerRequestMapBlocks(this, MapRequest.PositionData.MinX, MapRequest.PositionData.MinY, - MapRequest.PositionData.MaxX, MapRequest.PositionData.MaxY, MapRequest.AgentData.Flags); - } - break; - case PacketType.MapNameRequest: - MapNameRequestPacket map = (MapNameRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (map.AgentData.SessionID != SessionId || - map.AgentData.AgentID != AgentId) - break; - } - #endregion - - string mapName = Util.UTF8.GetString(map.NameData.Name, 0, - map.NameData.Name.Length - 1); - RequestMapName handlerMapNameRequest = OnMapNameRequest; - if (handlerMapNameRequest != null) - { - handlerMapNameRequest(this, mapName); - } - break; - - case PacketType.TeleportLandmarkRequest: - TeleportLandmarkRequestPacket tpReq = (TeleportLandmarkRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (tpReq.Info.SessionID != SessionId || - tpReq.Info.AgentID != AgentId) - break; - } - #endregion - - UUID lmid = tpReq.Info.LandmarkID; - AssetLandmark lm; - if (lmid != UUID.Zero) - { - //AssetBase lma = m_assetCache.GetAsset(lmid, false); - AssetBase lma = m_assetService.Get(lmid.ToString()); - - if (lma == null) - { - // Failed to find landmark - TeleportCancelPacket tpCancel = (TeleportCancelPacket)PacketPool.Instance.GetPacket(PacketType.TeleportCancel); - tpCancel.Info.SessionID = tpReq.Info.SessionID; - tpCancel.Info.AgentID = tpReq.Info.AgentID; - OutPacket(tpCancel, ThrottleOutPacketType.Task); - } - - try - { - lm = new AssetLandmark(lma); - } - catch (NullReferenceException) - { - // asset not found generates null ref inside the assetlandmark constructor. - TeleportCancelPacket tpCancel = (TeleportCancelPacket)PacketPool.Instance.GetPacket(PacketType.TeleportCancel); - tpCancel.Info.SessionID = tpReq.Info.SessionID; - tpCancel.Info.AgentID = tpReq.Info.AgentID; - OutPacket(tpCancel, ThrottleOutPacketType.Task); - break; - } - } - else - { - // Teleport home request - UUIDNameRequest handlerTeleportHomeRequest = OnTeleportHomeRequest; - if (handlerTeleportHomeRequest != null) - { - handlerTeleportHomeRequest(AgentId, this); - } - break; - } - - TeleportLandmarkRequest handlerTeleportLandmarkRequest = OnTeleportLandmarkRequest; - if (handlerTeleportLandmarkRequest != null) - { - handlerTeleportLandmarkRequest(this, lm.RegionID, lm.Position); - } - else - { - //no event handler so cancel request - - - TeleportCancelPacket tpCancel = (TeleportCancelPacket)PacketPool.Instance.GetPacket(PacketType.TeleportCancel); - tpCancel.Info.AgentID = tpReq.Info.AgentID; - tpCancel.Info.SessionID = tpReq.Info.SessionID; - OutPacket(tpCancel, ThrottleOutPacketType.Task); - - } - break; - - case PacketType.TeleportLocationRequest: - TeleportLocationRequestPacket tpLocReq = (TeleportLocationRequestPacket)Pack; - // m_log.Debug(tpLocReq.ToString()); - - #region Packet Session and User Check - if (m_checkPackets) - { - if (tpLocReq.AgentData.SessionID != SessionId || - tpLocReq.AgentData.AgentID != AgentId) - break; - } - #endregion - - TeleportLocationRequest handlerTeleportLocationRequest = OnTeleportLocationRequest; - if (handlerTeleportLocationRequest != null) - { - handlerTeleportLocationRequest(this, tpLocReq.Info.RegionHandle, tpLocReq.Info.Position, - tpLocReq.Info.LookAt, 16); - } - else - { - //no event handler so cancel request - TeleportCancelPacket tpCancel = (TeleportCancelPacket)PacketPool.Instance.GetPacket(PacketType.TeleportCancel); - tpCancel.Info.SessionID = tpLocReq.AgentData.SessionID; - tpCancel.Info.AgentID = tpLocReq.AgentData.AgentID; - OutPacket(tpCancel, ThrottleOutPacketType.Task); - } - break; - - //#endregion - - case PacketType.UUIDNameRequest: - UUIDNameRequestPacket incoming = (UUIDNameRequestPacket)Pack; - - foreach (UUIDNameRequestPacket.UUIDNameBlockBlock UUIDBlock in incoming.UUIDNameBlock) - { - UUIDNameRequest handlerNameRequest = OnNameFromUUIDRequest; - if (handlerNameRequest != null) - { - handlerNameRequest(UUIDBlock.ID, this); - } - } - break; - - //#region Parcel related packets - - - case PacketType.RegionHandleRequest: - RegionHandleRequestPacket rhrPack = (RegionHandleRequestPacket)Pack; - - RegionHandleRequest handlerRegionHandleRequest = OnRegionHandleRequest; - if (handlerRegionHandleRequest != null) - { - handlerRegionHandleRequest(this, rhrPack.RequestBlock.RegionID); - } - break; - - case PacketType.ParcelInfoRequest: - ParcelInfoRequestPacket pirPack = (ParcelInfoRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (pirPack.AgentData.SessionID != SessionId || - pirPack.AgentData.AgentID != AgentId) - break; - } - #endregion - - ParcelInfoRequest handlerParcelInfoRequest = OnParcelInfoRequest; - if (handlerParcelInfoRequest != null) - { - handlerParcelInfoRequest(this, pirPack.Data.ParcelID); - } - break; - - case PacketType.ParcelAccessListRequest: - ParcelAccessListRequestPacket requestPacket = (ParcelAccessListRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (requestPacket.AgentData.SessionID != SessionId || - requestPacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - ParcelAccessListRequest handlerParcelAccessListRequest = OnParcelAccessListRequest; - - if (handlerParcelAccessListRequest != null) - { - handlerParcelAccessListRequest(requestPacket.AgentData.AgentID, requestPacket.AgentData.SessionID, - requestPacket.Data.Flags, requestPacket.Data.SequenceID, - requestPacket.Data.LocalID, this); - } - break; - - case PacketType.ParcelAccessListUpdate: - ParcelAccessListUpdatePacket updatePacket = (ParcelAccessListUpdatePacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (updatePacket.AgentData.SessionID != SessionId || - updatePacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - List entries = new List(); - foreach (ParcelAccessListUpdatePacket.ListBlock block in updatePacket.List) - { - ParcelManager.ParcelAccessEntry entry = new ParcelManager.ParcelAccessEntry(); - entry.AgentID = block.ID; - entry.Flags = (AccessList)block.Flags; - entry.Time = new DateTime(); - entries.Add(entry); - } - - ParcelAccessListUpdateRequest handlerParcelAccessListUpdateRequest = OnParcelAccessListUpdateRequest; - if (handlerParcelAccessListUpdateRequest != null) - { - handlerParcelAccessListUpdateRequest(updatePacket.AgentData.AgentID, - updatePacket.AgentData.SessionID, updatePacket.Data.Flags, - updatePacket.Data.LocalID, entries, this); - } - break; - - case PacketType.ParcelPropertiesRequest: - - ParcelPropertiesRequestPacket propertiesRequest = (ParcelPropertiesRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (propertiesRequest.AgentData.SessionID != SessionId || - propertiesRequest.AgentData.AgentID != AgentId) - break; - } - #endregion - - ParcelPropertiesRequest handlerParcelPropertiesRequest = OnParcelPropertiesRequest; - if (handlerParcelPropertiesRequest != null) - { - handlerParcelPropertiesRequest((int)Math.Round(propertiesRequest.ParcelData.West), - (int)Math.Round(propertiesRequest.ParcelData.South), - (int)Math.Round(propertiesRequest.ParcelData.East), - (int)Math.Round(propertiesRequest.ParcelData.North), - propertiesRequest.ParcelData.SequenceID, - propertiesRequest.ParcelData.SnapSelection, this); - } - break; - - case PacketType.ParcelDivide: - ParcelDividePacket landDivide = (ParcelDividePacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (landDivide.AgentData.SessionID != SessionId || - landDivide.AgentData.AgentID != AgentId) - break; - } - #endregion - - ParcelDivideRequest handlerParcelDivideRequest = OnParcelDivideRequest; - if (handlerParcelDivideRequest != null) - { - handlerParcelDivideRequest((int)Math.Round(landDivide.ParcelData.West), - (int)Math.Round(landDivide.ParcelData.South), - (int)Math.Round(landDivide.ParcelData.East), - (int)Math.Round(landDivide.ParcelData.North), this); - } - break; - - case PacketType.ParcelJoin: - ParcelJoinPacket landJoin = (ParcelJoinPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (landJoin.AgentData.SessionID != SessionId || - landJoin.AgentData.AgentID != AgentId) - break; - } - #endregion - - ParcelJoinRequest handlerParcelJoinRequest = OnParcelJoinRequest; - - if (handlerParcelJoinRequest != null) - { - handlerParcelJoinRequest((int)Math.Round(landJoin.ParcelData.West), - (int)Math.Round(landJoin.ParcelData.South), - (int)Math.Round(landJoin.ParcelData.East), - (int)Math.Round(landJoin.ParcelData.North), this); - } - break; - - case PacketType.ParcelPropertiesUpdate: - ParcelPropertiesUpdatePacket parcelPropertiesPacket = (ParcelPropertiesUpdatePacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (parcelPropertiesPacket.AgentData.SessionID != SessionId || - parcelPropertiesPacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - ParcelPropertiesUpdateRequest handlerParcelPropertiesUpdateRequest = OnParcelPropertiesUpdateRequest; - - if (handlerParcelPropertiesUpdateRequest != null) - { - LandUpdateArgs args = new LandUpdateArgs(); - - args.AuthBuyerID = parcelPropertiesPacket.ParcelData.AuthBuyerID; - args.Category = (ParcelCategory)parcelPropertiesPacket.ParcelData.Category; - args.Desc = Utils.BytesToString(parcelPropertiesPacket.ParcelData.Desc); - args.GroupID = parcelPropertiesPacket.ParcelData.GroupID; - args.LandingType = parcelPropertiesPacket.ParcelData.LandingType; - args.MediaAutoScale = parcelPropertiesPacket.ParcelData.MediaAutoScale; - args.MediaID = parcelPropertiesPacket.ParcelData.MediaID; - args.MediaURL = Utils.BytesToString(parcelPropertiesPacket.ParcelData.MediaURL); - args.MusicURL = Utils.BytesToString(parcelPropertiesPacket.ParcelData.MusicURL); - args.Name = Utils.BytesToString(parcelPropertiesPacket.ParcelData.Name); - args.ParcelFlags = parcelPropertiesPacket.ParcelData.ParcelFlags; - args.PassHours = parcelPropertiesPacket.ParcelData.PassHours; - args.PassPrice = parcelPropertiesPacket.ParcelData.PassPrice; - args.SalePrice = parcelPropertiesPacket.ParcelData.SalePrice; - args.SnapshotID = parcelPropertiesPacket.ParcelData.SnapshotID; - args.UserLocation = parcelPropertiesPacket.ParcelData.UserLocation; - args.UserLookAt = parcelPropertiesPacket.ParcelData.UserLookAt; - handlerParcelPropertiesUpdateRequest(args, parcelPropertiesPacket.ParcelData.LocalID, this); - } - break; - - case PacketType.ParcelSelectObjects: - ParcelSelectObjectsPacket selectPacket = (ParcelSelectObjectsPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (selectPacket.AgentData.SessionID != SessionId || - selectPacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - List returnIDs = new List(); - - foreach (ParcelSelectObjectsPacket.ReturnIDsBlock rb in - selectPacket.ReturnIDs) - { - returnIDs.Add(rb.ReturnID); - } - - ParcelSelectObjects handlerParcelSelectObjects = OnParcelSelectObjects; - - if (handlerParcelSelectObjects != null) - { - handlerParcelSelectObjects(selectPacket.ParcelData.LocalID, - Convert.ToInt32(selectPacket.ParcelData.ReturnType), returnIDs, this); - } - break; - - case PacketType.ParcelObjectOwnersRequest: - //m_log.Debug(Pack.ToString()); - ParcelObjectOwnersRequestPacket reqPacket = (ParcelObjectOwnersRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (reqPacket.AgentData.SessionID != SessionId || - reqPacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - ParcelObjectOwnerRequest handlerParcelObjectOwnerRequest = OnParcelObjectOwnerRequest; - - if (handlerParcelObjectOwnerRequest != null) - { - handlerParcelObjectOwnerRequest(reqPacket.ParcelData.LocalID, this); - } - break; - - case PacketType.ParcelGodForceOwner: - ParcelGodForceOwnerPacket godForceOwnerPacket = (ParcelGodForceOwnerPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (godForceOwnerPacket.AgentData.SessionID != SessionId || - godForceOwnerPacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - ParcelGodForceOwner handlerParcelGodForceOwner = OnParcelGodForceOwner; - if (handlerParcelGodForceOwner != null) - { - handlerParcelGodForceOwner(godForceOwnerPacket.Data.LocalID, godForceOwnerPacket.Data.OwnerID, this); - } - break; - - case PacketType.ParcelRelease: - ParcelReleasePacket releasePacket = (ParcelReleasePacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (releasePacket.AgentData.SessionID != SessionId || - releasePacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - ParcelAbandonRequest handlerParcelAbandonRequest = OnParcelAbandonRequest; - if (handlerParcelAbandonRequest != null) - { - handlerParcelAbandonRequest(releasePacket.Data.LocalID, this); - } - break; - - case PacketType.ParcelReclaim: - ParcelReclaimPacket reclaimPacket = (ParcelReclaimPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (reclaimPacket.AgentData.SessionID != SessionId || - reclaimPacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - ParcelReclaim handlerParcelReclaim = OnParcelReclaim; - if (handlerParcelReclaim != null) - { - handlerParcelReclaim(reclaimPacket.Data.LocalID, this); - } - break; - - case PacketType.ParcelReturnObjects: - - - ParcelReturnObjectsPacket parcelReturnObjects = (ParcelReturnObjectsPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (parcelReturnObjects.AgentData.SessionID != SessionId || - parcelReturnObjects.AgentData.AgentID != AgentId) - break; - } - #endregion - - UUID[] puserselectedOwnerIDs = new UUID[parcelReturnObjects.OwnerIDs.Length]; - for (int parceliterator = 0; parceliterator < parcelReturnObjects.OwnerIDs.Length; parceliterator++) - puserselectedOwnerIDs[parceliterator] = parcelReturnObjects.OwnerIDs[parceliterator].OwnerID; - - UUID[] puserselectedTaskIDs = new UUID[parcelReturnObjects.TaskIDs.Length]; - - for (int parceliterator = 0; parceliterator < parcelReturnObjects.TaskIDs.Length; parceliterator++) - puserselectedTaskIDs[parceliterator] = parcelReturnObjects.TaskIDs[parceliterator].TaskID; - - ParcelReturnObjectsRequest handlerParcelReturnObjectsRequest = OnParcelReturnObjectsRequest; - if (handlerParcelReturnObjectsRequest != null) - { - handlerParcelReturnObjectsRequest(parcelReturnObjects.ParcelData.LocalID, parcelReturnObjects.ParcelData.ReturnType, puserselectedOwnerIDs, puserselectedTaskIDs, this); - - } - break; - - case PacketType.ParcelSetOtherCleanTime: - ParcelSetOtherCleanTimePacket parcelSetOtherCleanTimePacket = (ParcelSetOtherCleanTimePacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (parcelSetOtherCleanTimePacket.AgentData.SessionID != SessionId || - parcelSetOtherCleanTimePacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - ParcelSetOtherCleanTime handlerParcelSetOtherCleanTime = OnParcelSetOtherCleanTime; - if (handlerParcelSetOtherCleanTime != null) - { - handlerParcelSetOtherCleanTime(this, - parcelSetOtherCleanTimePacket.ParcelData.LocalID, - parcelSetOtherCleanTimePacket.ParcelData.OtherCleanTime); - } - break; - - case PacketType.LandStatRequest: - LandStatRequestPacket lsrp = (LandStatRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (lsrp.AgentData.SessionID != SessionId || - lsrp.AgentData.AgentID != AgentId) - break; - } - #endregion - - GodLandStatRequest handlerLandStatRequest = OnLandStatRequest; - if (handlerLandStatRequest != null) - { - handlerLandStatRequest(lsrp.RequestData.ParcelLocalID, lsrp.RequestData.ReportType, lsrp.RequestData.RequestFlags, Utils.BytesToString(lsrp.RequestData.Filter), this); - } - break; - - case PacketType.ParcelDwellRequest: - ParcelDwellRequestPacket dwellrq = - (ParcelDwellRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (dwellrq.AgentData.SessionID != SessionId || - dwellrq.AgentData.AgentID != AgentId) - break; - } - #endregion - - ParcelDwellRequest handlerParcelDwellRequest = OnParcelDwellRequest; - if (handlerParcelDwellRequest != null) - { - handlerParcelDwellRequest(dwellrq.Data.LocalID, this); - } - break; - - //#endregion - - //#region Estate Packets - - case PacketType.EstateOwnerMessage: - EstateOwnerMessagePacket messagePacket = (EstateOwnerMessagePacket)Pack; - //m_log.Debug(messagePacket.ToString()); - - #region Packet Session and User Check - if (m_checkPackets) - { - if (messagePacket.AgentData.SessionID != SessionId || - messagePacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - switch (Utils.BytesToString(messagePacket.MethodData.Method)) - { - case "getinfo": - if (((Scene)m_scene).Permissions.CanIssueEstateCommand(AgentId, false)) - { - OnDetailedEstateDataRequest(this, messagePacket.MethodData.Invoice); - } - break; - case "setregioninfo": - if (((Scene)m_scene).Permissions.CanIssueEstateCommand(AgentId, false)) - { - OnSetEstateFlagsRequest(convertParamStringToBool(messagePacket.ParamList[0].Parameter), convertParamStringToBool(messagePacket.ParamList[1].Parameter), - convertParamStringToBool(messagePacket.ParamList[2].Parameter), !convertParamStringToBool(messagePacket.ParamList[3].Parameter), - Convert.ToInt16(Convert.ToDecimal(Utils.BytesToString(messagePacket.ParamList[4].Parameter), Culture.NumberFormatInfo)), - (float)Convert.ToDecimal(Utils.BytesToString(messagePacket.ParamList[5].Parameter), Culture.NumberFormatInfo), - Convert.ToInt16(Utils.BytesToString(messagePacket.ParamList[6].Parameter)), - convertParamStringToBool(messagePacket.ParamList[7].Parameter), convertParamStringToBool(messagePacket.ParamList[8].Parameter)); - } - break; - // case "texturebase": - // if (((Scene)m_scene).Permissions.CanIssueEstateCommand(AgentId, false)) - // { - // foreach (EstateOwnerMessagePacket.ParamListBlock block in messagePacket.ParamList) - // { - // string s = Utils.BytesToString(block.Parameter); - // string[] splitField = s.Split(' '); - // if (splitField.Length == 2) - // { - // UUID tempUUID = new UUID(splitField[1]); - // OnSetEstateTerrainBaseTexture(this, Convert.ToInt16(splitField[0]), tempUUID); - // } - // } - // } - // break; - case "texturedetail": - if (((Scene)m_scene).Permissions.CanIssueEstateCommand(AgentId, false)) - { - foreach (EstateOwnerMessagePacket.ParamListBlock block in messagePacket.ParamList) - { - string s = Utils.BytesToString(block.Parameter); - string[] splitField = s.Split(' '); - if (splitField.Length == 2) - { - Int16 corner = Convert.ToInt16(splitField[0]); - UUID textureUUID = new UUID(splitField[1]); - - OnSetEstateTerrainDetailTexture(this, corner, textureUUID); - } - } - } - - break; - case "textureheights": - if (((Scene)m_scene).Permissions.CanIssueEstateCommand(AgentId, false)) - { - foreach (EstateOwnerMessagePacket.ParamListBlock block in messagePacket.ParamList) - { - string s = Utils.BytesToString(block.Parameter); - string[] splitField = s.Split(' '); - if (splitField.Length == 3) - { - Int16 corner = Convert.ToInt16(splitField[0]); - float lowValue = (float)Convert.ToDecimal(splitField[1], Culture.NumberFormatInfo); - float highValue = (float)Convert.ToDecimal(splitField[2], Culture.NumberFormatInfo); - - OnSetEstateTerrainTextureHeights(this, corner, lowValue, highValue); - } - } - } - break; - case "texturecommit": - OnCommitEstateTerrainTextureRequest(this); - break; - case "setregionterrain": - if (((Scene)m_scene).Permissions.CanIssueEstateCommand(AgentId, false)) - { - if (messagePacket.ParamList.Length != 9) - { - m_log.Error("EstateOwnerMessage: SetRegionTerrain method has a ParamList of invalid length"); - } - else - { - try - { - string tmp = Utils.BytesToString(messagePacket.ParamList[0].Parameter); - if (!tmp.Contains(".")) tmp += ".00"; - float WaterHeight = (float)Convert.ToDecimal(tmp, Culture.NumberFormatInfo); - tmp = Utils.BytesToString(messagePacket.ParamList[1].Parameter); - if (!tmp.Contains(".")) tmp += ".00"; - float TerrainRaiseLimit = (float)Convert.ToDecimal(tmp, Culture.NumberFormatInfo); - tmp = Utils.BytesToString(messagePacket.ParamList[2].Parameter); - if (!tmp.Contains(".")) tmp += ".00"; - float TerrainLowerLimit = (float)Convert.ToDecimal(tmp, Culture.NumberFormatInfo); - bool UseEstateSun = convertParamStringToBool(messagePacket.ParamList[3].Parameter); - bool UseFixedSun = convertParamStringToBool(messagePacket.ParamList[4].Parameter); - float SunHour = (float)Convert.ToDecimal(Utils.BytesToString(messagePacket.ParamList[5].Parameter), Culture.NumberFormatInfo); - bool UseGlobal = convertParamStringToBool(messagePacket.ParamList[6].Parameter); - bool EstateFixedSun = convertParamStringToBool(messagePacket.ParamList[7].Parameter); - float EstateSunHour = (float)Convert.ToDecimal(Utils.BytesToString(messagePacket.ParamList[8].Parameter), Culture.NumberFormatInfo); - - OnSetRegionTerrainSettings(WaterHeight, TerrainRaiseLimit, TerrainLowerLimit, UseEstateSun, UseFixedSun, SunHour, UseGlobal, EstateFixedSun, EstateSunHour); - - } - catch (Exception ex) - { - m_log.Error("EstateOwnerMessage: Exception while setting terrain settings: \n" + messagePacket + "\n" + ex); - } - } - } - - break; - case "restart": - if (((Scene)m_scene).Permissions.CanIssueEstateCommand(AgentId, false)) - { - // There's only 1 block in the estateResetSim.. and that's the number of seconds till restart. - foreach (EstateOwnerMessagePacket.ParamListBlock block in messagePacket.ParamList) - { - float timeSeconds; - Utils.TryParseSingle(Utils.BytesToString(block.Parameter), out timeSeconds); - timeSeconds = (int)timeSeconds; - OnEstateRestartSimRequest(this, (int)timeSeconds); - - } - } - break; - case "estatechangecovenantid": - if (((Scene)m_scene).Permissions.CanIssueEstateCommand(AgentId, false)) - { - foreach (EstateOwnerMessagePacket.ParamListBlock block in messagePacket.ParamList) - { - UUID newCovenantID = new UUID(Utils.BytesToString(block.Parameter)); - OnEstateChangeCovenantRequest(this, newCovenantID); - } - } - break; - case "estateaccessdelta": // Estate access delta manages the banlist and allow list too. - if (((Scene)m_scene).Permissions.CanIssueEstateCommand(AgentId, false)) - { - int estateAccessType = Convert.ToInt16(Utils.BytesToString(messagePacket.ParamList[1].Parameter)); - OnUpdateEstateAccessDeltaRequest(this, messagePacket.MethodData.Invoice, estateAccessType, new UUID(Utils.BytesToString(messagePacket.ParamList[2].Parameter))); - - } - break; - case "simulatormessage": - if (((Scene)m_scene).Permissions.CanIssueEstateCommand(AgentId, false)) - { - UUID invoice = messagePacket.MethodData.Invoice; - UUID SenderID = new UUID(Utils.BytesToString(messagePacket.ParamList[2].Parameter)); - string SenderName = Utils.BytesToString(messagePacket.ParamList[3].Parameter); - string Message = Utils.BytesToString(messagePacket.ParamList[4].Parameter); - UUID sessionID = messagePacket.AgentData.SessionID; - OnSimulatorBlueBoxMessageRequest(this, invoice, SenderID, sessionID, SenderName, Message); - } - break; - case "instantmessage": - if (((Scene)m_scene).Permissions.CanIssueEstateCommand(AgentId, false)) - { - if (messagePacket.ParamList.Length < 5) - break; - UUID invoice = messagePacket.MethodData.Invoice; - UUID SenderID = new UUID(Utils.BytesToString(messagePacket.ParamList[2].Parameter)); - string SenderName = Utils.BytesToString(messagePacket.ParamList[3].Parameter); - string Message = Utils.BytesToString(messagePacket.ParamList[4].Parameter); - UUID sessionID = messagePacket.AgentData.SessionID; - OnEstateBlueBoxMessageRequest(this, invoice, SenderID, sessionID, SenderName, Message); - } - break; - case "setregiondebug": - if (((Scene)m_scene).Permissions.CanIssueEstateCommand(AgentId, false)) - { - UUID invoice = messagePacket.MethodData.Invoice; - UUID SenderID = messagePacket.AgentData.AgentID; - bool scripted = convertParamStringToBool(messagePacket.ParamList[0].Parameter); - bool collisionEvents = convertParamStringToBool(messagePacket.ParamList[1].Parameter); - bool physics = convertParamStringToBool(messagePacket.ParamList[2].Parameter); - - OnEstateDebugRegionRequest(this, invoice, SenderID, scripted, collisionEvents, physics); - } - break; - case "teleporthomeuser": - if (((Scene)m_scene).Permissions.CanIssueEstateCommand(AgentId, false)) - { - UUID invoice = messagePacket.MethodData.Invoice; - UUID SenderID = messagePacket.AgentData.AgentID; - UUID Prey; - - UUID.TryParse(Utils.BytesToString(messagePacket.ParamList[1].Parameter), out Prey); - - OnEstateTeleportOneUserHomeRequest(this, invoice, SenderID, Prey); - } - break; - case "teleporthomeallusers": - if (((Scene)m_scene).Permissions.CanIssueEstateCommand(AgentId, false)) - { - UUID invoice = messagePacket.MethodData.Invoice; - UUID SenderID = messagePacket.AgentData.AgentID; - OnEstateTeleportAllUsersHomeRequest(this, invoice, SenderID); - } - break; - case "colliders": - handlerLandStatRequest = OnLandStatRequest; - if (handlerLandStatRequest != null) - { - handlerLandStatRequest(0, 1, 0, "", this); - } - break; - case "scripts": - handlerLandStatRequest = OnLandStatRequest; - if (handlerLandStatRequest != null) - { - handlerLandStatRequest(0, 0, 0, "", this); - } - break; - case "terrain": - if (((Scene)m_scene).Permissions.CanIssueEstateCommand(AgentId, false)) - { - if (messagePacket.ParamList.Length > 0) - { - if (Utils.BytesToString(messagePacket.ParamList[0].Parameter) == "bake") - { - BakeTerrain handlerBakeTerrain = OnBakeTerrain; - if (handlerBakeTerrain != null) - { - handlerBakeTerrain(this); - } - } - if (Utils.BytesToString(messagePacket.ParamList[0].Parameter) == "download filename") - { - if (messagePacket.ParamList.Length > 1) - { - RequestTerrain handlerRequestTerrain = OnRequestTerrain; - if (handlerRequestTerrain != null) - { - handlerRequestTerrain(this, Utils.BytesToString(messagePacket.ParamList[1].Parameter)); - } - } - } - if (Utils.BytesToString(messagePacket.ParamList[0].Parameter) == "upload filename") - { - if (messagePacket.ParamList.Length > 1) - { - RequestTerrain handlerUploadTerrain = OnUploadTerrain; - if (handlerUploadTerrain != null) - { - handlerUploadTerrain(this, Utils.BytesToString(messagePacket.ParamList[1].Parameter)); - } - } - } - - } - - - } - break; - - case "estatechangeinfo": - if (((Scene)m_scene).Permissions.CanIssueEstateCommand(AgentId, false)) - { - UUID invoice = messagePacket.MethodData.Invoice; - UUID SenderID = messagePacket.AgentData.AgentID; - UInt32 param1 = Convert.ToUInt32(Utils.BytesToString(messagePacket.ParamList[1].Parameter)); - UInt32 param2 = Convert.ToUInt32(Utils.BytesToString(messagePacket.ParamList[2].Parameter)); - - EstateChangeInfo handlerEstateChangeInfo = OnEstateChangeInfo; - if (handlerEstateChangeInfo != null) - { - handlerEstateChangeInfo(this, invoice, SenderID, param1, param2); - } - } - break; - - default: - m_log.Error("EstateOwnerMessage: Unknown method requested\n" + messagePacket); - break; - } - - //int parcelID, uint reportType, uint requestflags, string filter - - //lsrp.RequestData.ParcelLocalID; - //lsrp.RequestData.ReportType; // 1 = colliders, 0 = scripts - //lsrp.RequestData.RequestFlags; - //lsrp.RequestData.Filter; - - break; - - case PacketType.RequestRegionInfo: - RequestRegionInfoPacket.AgentDataBlock mPacket = ((RequestRegionInfoPacket)Pack).AgentData; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (mPacket.SessionID != SessionId || - mPacket.AgentID != AgentId) - break; - } - #endregion - - RegionInfoRequest handlerRegionInfoRequest = OnRegionInfoRequest; - if (handlerRegionInfoRequest != null) - { - handlerRegionInfoRequest(this); - } - break; - - case PacketType.EstateCovenantRequest: - - //EstateCovenantRequestPacket.AgentDataBlock epack = - // ((EstateCovenantRequestPacket)Pack).AgentData; - - EstateCovenantRequest handlerEstateCovenantRequest = OnEstateCovenantRequest; - if (handlerEstateCovenantRequest != null) - { - handlerEstateCovenantRequest(this); - } - break; - - //#endregion - - //#region GodPackets - - case PacketType.RequestGodlikePowers: - RequestGodlikePowersPacket rglpPack = (RequestGodlikePowersPacket)Pack; - RequestGodlikePowersPacket.RequestBlockBlock rblock = rglpPack.RequestBlock; - UUID token = rblock.Token; - - RequestGodlikePowersPacket.AgentDataBlock ablock = rglpPack.AgentData; - - RequestGodlikePowers handlerReqGodlikePowers = OnRequestGodlikePowers; - - if (handlerReqGodlikePowers != null) - { - handlerReqGodlikePowers(ablock.AgentID, ablock.SessionID, token, rblock.Godlike, this); - } - - break; - - case PacketType.GodKickUser: - GodKickUserPacket gkupack = (GodKickUserPacket)Pack; - - if (gkupack.UserInfo.GodSessionID == SessionId && AgentId == gkupack.UserInfo.GodID) - { - GodKickUser handlerGodKickUser = OnGodKickUser; - if (handlerGodKickUser != null) - { - handlerGodKickUser(gkupack.UserInfo.GodID, gkupack.UserInfo.GodSessionID, - gkupack.UserInfo.AgentID, gkupack.UserInfo.KickFlags, gkupack.UserInfo.Reason,gkupack.UserInfo); - } - } - else - { - SendAgentAlertMessage("Kick request denied", false); - } - //KickUserPacket kupack = new KickUserPacket(); - //KickUserPacket.UserInfoBlock kupackib = kupack.UserInfo; - - //kupack.UserInfo.AgentID = gkupack.UserInfo.AgentID; - //kupack.UserInfo.SessionID = gkupack.UserInfo.GodSessionID; - - //kupack.TargetBlock.TargetIP = (uint)0; - //kupack.TargetBlock.TargetPort = (ushort)0; - //kupack.UserInfo.Reason = gkupack.UserInfo.Reason; - - //OutPacket(kupack, ThrottleOutPacketType.Task); - break; - - //#endregion - - //#region Economy/Transaction Packets - - case PacketType.MoneyBalanceRequest: - MoneyBalanceRequestPacket moneybalancerequestpacket = (MoneyBalanceRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (moneybalancerequestpacket.AgentData.SessionID != SessionId || - moneybalancerequestpacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - MoneyBalanceRequest handlerMoneyBalanceRequest = OnMoneyBalanceRequest; - - if (handlerMoneyBalanceRequest != null) - { - handlerMoneyBalanceRequest(this, moneybalancerequestpacket.AgentData.AgentID, moneybalancerequestpacket.AgentData.SessionID, moneybalancerequestpacket.MoneyData.TransactionID); - } - - break; - - case PacketType.EconomyDataRequest: - - - EconomyDataRequest handlerEconomoyDataRequest = OnEconomyDataRequest; - if (handlerEconomoyDataRequest != null) - { - handlerEconomoyDataRequest(AgentId); - } - break; - - case PacketType.RequestPayPrice: - RequestPayPricePacket requestPayPricePacket = (RequestPayPricePacket)Pack; - - RequestPayPrice handlerRequestPayPrice = OnRequestPayPrice; - if (handlerRequestPayPrice != null) - { - handlerRequestPayPrice(this, requestPayPricePacket.ObjectData.ObjectID); - } - break; - - case PacketType.ObjectSaleInfo: - ObjectSaleInfoPacket objectSaleInfoPacket = (ObjectSaleInfoPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (objectSaleInfoPacket.AgentData.SessionID != SessionId || - objectSaleInfoPacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - ObjectSaleInfo handlerObjectSaleInfo = OnObjectSaleInfo; - if (handlerObjectSaleInfo != null) - { - foreach (ObjectSaleInfoPacket.ObjectDataBlock d - in objectSaleInfoPacket.ObjectData) - { - handlerObjectSaleInfo(this, - objectSaleInfoPacket.AgentData.AgentID, - objectSaleInfoPacket.AgentData.SessionID, - d.LocalID, - d.SaleType, - d.SalePrice); - } - } - break; - - case PacketType.ObjectBuy: - ObjectBuyPacket objectBuyPacket = (ObjectBuyPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (objectBuyPacket.AgentData.SessionID != SessionId || - objectBuyPacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - ObjectBuy handlerObjectBuy = OnObjectBuy; - - if (handlerObjectBuy != null) - { - foreach (ObjectBuyPacket.ObjectDataBlock d - in objectBuyPacket.ObjectData) - { - handlerObjectBuy(this, - objectBuyPacket.AgentData.AgentID, - objectBuyPacket.AgentData.SessionID, - objectBuyPacket.AgentData.GroupID, - objectBuyPacket.AgentData.CategoryID, - d.ObjectLocalID, - d.SaleType, - d.SalePrice); - } - } - break; - - //#endregion - - //#region Script Packets - - case PacketType.GetScriptRunning: - GetScriptRunningPacket scriptRunning = (GetScriptRunningPacket)Pack; - - GetScriptRunning handlerGetScriptRunning = OnGetScriptRunning; - if (handlerGetScriptRunning != null) - { - handlerGetScriptRunning(this, scriptRunning.Script.ObjectID, scriptRunning.Script.ItemID); - } - break; - - case PacketType.SetScriptRunning: - SetScriptRunningPacket setScriptRunning = (SetScriptRunningPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (setScriptRunning.AgentData.SessionID != SessionId || - setScriptRunning.AgentData.AgentID != AgentId) - break; - } - #endregion - - SetScriptRunning handlerSetScriptRunning = OnSetScriptRunning; - if (handlerSetScriptRunning != null) - { - handlerSetScriptRunning(this, setScriptRunning.Script.ObjectID, setScriptRunning.Script.ItemID, setScriptRunning.Script.Running); - } - break; - - case PacketType.ScriptReset: - ScriptResetPacket scriptResetPacket = (ScriptResetPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (scriptResetPacket.AgentData.SessionID != SessionId || - scriptResetPacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - ScriptReset handlerScriptReset = OnScriptReset; - if (handlerScriptReset != null) - { - handlerScriptReset(this, scriptResetPacket.Script.ObjectID, scriptResetPacket.Script.ItemID); - } - break; - - //#endregion - - //#region Gesture Managment - - case PacketType.ActivateGestures: - ActivateGesturesPacket activateGesturePacket = (ActivateGesturesPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (activateGesturePacket.AgentData.SessionID != SessionId || - activateGesturePacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - ActivateGesture handlerActivateGesture = OnActivateGesture; - if (handlerActivateGesture != null) - { - handlerActivateGesture(this, - activateGesturePacket.Data[0].AssetID, - activateGesturePacket.Data[0].ItemID); - } - else m_log.Error("Null pointer for activateGesture"); - - break; - - case PacketType.DeactivateGestures: - DeactivateGesturesPacket deactivateGesturePacket = (DeactivateGesturesPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (deactivateGesturePacket.AgentData.SessionID != SessionId || - deactivateGesturePacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - DeactivateGesture handlerDeactivateGesture = OnDeactivateGesture; - if (handlerDeactivateGesture != null) - { - handlerDeactivateGesture(this, deactivateGesturePacket.Data[0].ItemID); - } - break; - case PacketType.ObjectOwner: - ObjectOwnerPacket objectOwnerPacket = (ObjectOwnerPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (objectOwnerPacket.AgentData.SessionID != SessionId || - objectOwnerPacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - List localIDs = new List(); - - foreach (ObjectOwnerPacket.ObjectDataBlock d in objectOwnerPacket.ObjectData) - localIDs.Add(d.ObjectLocalID); - - ObjectOwner handlerObjectOwner = OnObjectOwner; - if (handlerObjectOwner != null) - { - handlerObjectOwner(this, objectOwnerPacket.HeaderData.OwnerID, objectOwnerPacket.HeaderData.GroupID, localIDs); - } - break; - - //#endregion - - case PacketType.AgentFOV: - AgentFOVPacket fovPacket = (AgentFOVPacket)Pack; - - if (fovPacket.FOVBlock.GenCounter > m_agentFOVCounter) - { - m_agentFOVCounter = fovPacket.FOVBlock.GenCounter; - AgentFOV handlerAgentFOV = OnAgentFOV; - if (handlerAgentFOV != null) - { - handlerAgentFOV(this, fovPacket.FOVBlock.VerticalAngle); - } - } - break; - - //#region unimplemented handlers - - case PacketType.ViewerStats: - // TODO: handle this packet - //m_log.Warn("[CLIENT]: unhandled ViewerStats packet"); - break; - - case PacketType.MapItemRequest: - MapItemRequestPacket mirpk = (MapItemRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (mirpk.AgentData.SessionID != SessionId || - mirpk.AgentData.AgentID != AgentId) - break; - } - #endregion - - //m_log.Debug(mirpk.ToString()); - MapItemRequest handlerMapItemRequest = OnMapItemRequest; - if (handlerMapItemRequest != null) - { - handlerMapItemRequest(this, mirpk.AgentData.Flags, mirpk.AgentData.EstateID, - mirpk.AgentData.Godlike, mirpk.RequestData.ItemType, - mirpk.RequestData.RegionHandle); - - } - break; - - case PacketType.TransferAbort: - // TODO: handle this packet - //m_log.Warn("[CLIENT]: unhandled TransferAbort packet"); - break; - - case PacketType.MuteListRequest: - MuteListRequestPacket muteListRequest = - (MuteListRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (muteListRequest.AgentData.SessionID != SessionId || - muteListRequest.AgentData.AgentID != AgentId) - break; - } - #endregion - - MuteListRequest handlerMuteListRequest = OnMuteListRequest; - if (handlerMuteListRequest != null) - { - handlerMuteListRequest(this, muteListRequest.MuteData.MuteCRC); - } - else - { - SendUseCachedMuteList(); - } - break; - - case PacketType.UseCircuitCode: - // Don't display this one, we handle it at a lower level - break; - - case PacketType.AgentHeightWidth: - // TODO: handle this packet - //m_log.Warn("[CLIENT]: unhandled AgentHeightWidth packet"); - break; - - case PacketType.InventoryDescendents: - // TODO: handle this packet - //m_log.Warn("[CLIENT]: unhandled InventoryDescent packet"); - - break; - - case PacketType.DirPlacesQuery: - DirPlacesQueryPacket dirPlacesQueryPacket = (DirPlacesQueryPacket)Pack; - //m_log.Debug(dirPlacesQueryPacket.ToString()); - - #region Packet Session and User Check - if (m_checkPackets) - { - if (dirPlacesQueryPacket.AgentData.SessionID != SessionId || - dirPlacesQueryPacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - DirPlacesQuery handlerDirPlacesQuery = OnDirPlacesQuery; - if (handlerDirPlacesQuery != null) - { - handlerDirPlacesQuery(this, - dirPlacesQueryPacket.QueryData.QueryID, - Utils.BytesToString( - dirPlacesQueryPacket.QueryData.QueryText), - (int)dirPlacesQueryPacket.QueryData.QueryFlags, - (int)dirPlacesQueryPacket.QueryData.Category, - Utils.BytesToString( - dirPlacesQueryPacket.QueryData.SimName), - dirPlacesQueryPacket.QueryData.QueryStart); - } - break; - - case PacketType.DirFindQuery: - DirFindQueryPacket dirFindQueryPacket = (DirFindQueryPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (dirFindQueryPacket.AgentData.SessionID != SessionId || - dirFindQueryPacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - DirFindQuery handlerDirFindQuery = OnDirFindQuery; - if (handlerDirFindQuery != null) - { - handlerDirFindQuery(this, - dirFindQueryPacket.QueryData.QueryID, - Utils.BytesToString( - dirFindQueryPacket.QueryData.QueryText), - dirFindQueryPacket.QueryData.QueryFlags, - dirFindQueryPacket.QueryData.QueryStart); - } - break; - - case PacketType.DirLandQuery: - DirLandQueryPacket dirLandQueryPacket = (DirLandQueryPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (dirLandQueryPacket.AgentData.SessionID != SessionId || - dirLandQueryPacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - DirLandQuery handlerDirLandQuery = OnDirLandQuery; - if (handlerDirLandQuery != null) - { - handlerDirLandQuery(this, - dirLandQueryPacket.QueryData.QueryID, - dirLandQueryPacket.QueryData.QueryFlags, - dirLandQueryPacket.QueryData.SearchType, - dirLandQueryPacket.QueryData.Price, - dirLandQueryPacket.QueryData.Area, - dirLandQueryPacket.QueryData.QueryStart); - } - break; - - case PacketType.DirPopularQuery: - DirPopularQueryPacket dirPopularQueryPacket = (DirPopularQueryPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (dirPopularQueryPacket.AgentData.SessionID != SessionId || - dirPopularQueryPacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - DirPopularQuery handlerDirPopularQuery = OnDirPopularQuery; - if (handlerDirPopularQuery != null) - { - handlerDirPopularQuery(this, - dirPopularQueryPacket.QueryData.QueryID, - dirPopularQueryPacket.QueryData.QueryFlags); - } - break; - - case PacketType.DirClassifiedQuery: - DirClassifiedQueryPacket dirClassifiedQueryPacket = (DirClassifiedQueryPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (dirClassifiedQueryPacket.AgentData.SessionID != SessionId || - dirClassifiedQueryPacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - DirClassifiedQuery handlerDirClassifiedQuery = OnDirClassifiedQuery; - if (handlerDirClassifiedQuery != null) - { - handlerDirClassifiedQuery(this, - dirClassifiedQueryPacket.QueryData.QueryID, - Utils.BytesToString( - dirClassifiedQueryPacket.QueryData.QueryText), - dirClassifiedQueryPacket.QueryData.QueryFlags, - dirClassifiedQueryPacket.QueryData.Category, - dirClassifiedQueryPacket.QueryData.QueryStart); - } - break; - - case PacketType.EventInfoRequest: - EventInfoRequestPacket eventInfoRequestPacket = (EventInfoRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (eventInfoRequestPacket.AgentData.SessionID != SessionId || - eventInfoRequestPacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - if (OnEventInfoRequest != null) - { - OnEventInfoRequest(this, eventInfoRequestPacket.EventData.EventID); - } - break; - - //#region Calling Card - - case PacketType.OfferCallingCard: - OfferCallingCardPacket offerCallingCardPacket = (OfferCallingCardPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (offerCallingCardPacket.AgentData.SessionID != SessionId || - offerCallingCardPacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - if (OnOfferCallingCard != null) - { - OnOfferCallingCard(this, - offerCallingCardPacket.AgentBlock.DestID, - offerCallingCardPacket.AgentBlock.TransactionID); - } - break; - - case PacketType.AcceptCallingCard: - AcceptCallingCardPacket acceptCallingCardPacket = (AcceptCallingCardPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (acceptCallingCardPacket.AgentData.SessionID != SessionId || - acceptCallingCardPacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - // according to http://wiki.secondlife.com/wiki/AcceptCallingCard FolderData should - // contain exactly one entry - if (OnAcceptCallingCard != null && acceptCallingCardPacket.FolderData.Length > 0) - { - OnAcceptCallingCard(this, - acceptCallingCardPacket.TransactionBlock.TransactionID, - acceptCallingCardPacket.FolderData[0].FolderID); - } - break; - - case PacketType.DeclineCallingCard: - DeclineCallingCardPacket declineCallingCardPacket = (DeclineCallingCardPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (declineCallingCardPacket.AgentData.SessionID != SessionId || - declineCallingCardPacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - if (OnDeclineCallingCard != null) - { - OnDeclineCallingCard(this, - declineCallingCardPacket.TransactionBlock.TransactionID); - } - break; - //#endregion - - //#region Groups - case PacketType.ActivateGroup: - ActivateGroupPacket activateGroupPacket = (ActivateGroupPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (activateGroupPacket.AgentData.SessionID != SessionId || - activateGroupPacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - if (m_GroupsModule != null) - { - m_GroupsModule.ActivateGroup(this, activateGroupPacket.AgentData.GroupID); - m_GroupsModule.SendAgentGroupDataUpdate(this); - } - break; - - - case PacketType.GroupTitlesRequest: - GroupTitlesRequestPacket groupTitlesRequest = - (GroupTitlesRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (groupTitlesRequest.AgentData.SessionID != SessionId || - groupTitlesRequest.AgentData.AgentID != AgentId) - break; - } - #endregion - - if (m_GroupsModule != null) - { - GroupTitlesReplyPacket groupTitlesReply = (GroupTitlesReplyPacket)PacketPool.Instance.GetPacket(PacketType.GroupTitlesReply); - - groupTitlesReply.AgentData = - new GroupTitlesReplyPacket.AgentDataBlock(); - - groupTitlesReply.AgentData.AgentID = AgentId; - groupTitlesReply.AgentData.GroupID = - groupTitlesRequest.AgentData.GroupID; - - groupTitlesReply.AgentData.RequestID = - groupTitlesRequest.AgentData.RequestID; - - List titles = - m_GroupsModule.GroupTitlesRequest(this, - groupTitlesRequest.AgentData.GroupID); - - groupTitlesReply.GroupData = - new GroupTitlesReplyPacket.GroupDataBlock[titles.Count]; - - int i = 0; - foreach (GroupTitlesData d in titles) - { - groupTitlesReply.GroupData[i] = - new GroupTitlesReplyPacket.GroupDataBlock(); - - groupTitlesReply.GroupData[i].Title = - Util.StringToBytes256(d.Name); - groupTitlesReply.GroupData[i].RoleID = - d.UUID; - groupTitlesReply.GroupData[i].Selected = - d.Selected; - i++; - } - - OutPacket(groupTitlesReply, ThrottleOutPacketType.Task); - } - break; - - case PacketType.GroupProfileRequest: - GroupProfileRequestPacket groupProfileRequest = - (GroupProfileRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (groupProfileRequest.AgentData.SessionID != SessionId || - groupProfileRequest.AgentData.AgentID != AgentId) - break; - } - #endregion - - if (m_GroupsModule != null) - { - GroupProfileReplyPacket groupProfileReply = (GroupProfileReplyPacket)PacketPool.Instance.GetPacket(PacketType.GroupProfileReply); - - groupProfileReply.AgentData = new GroupProfileReplyPacket.AgentDataBlock(); - groupProfileReply.GroupData = new GroupProfileReplyPacket.GroupDataBlock(); - groupProfileReply.AgentData.AgentID = AgentId; - - GroupProfileData d = m_GroupsModule.GroupProfileRequest(this, - groupProfileRequest.GroupData.GroupID); - - groupProfileReply.GroupData.GroupID = d.GroupID; - groupProfileReply.GroupData.Name = Util.StringToBytes256(d.Name); - groupProfileReply.GroupData.Charter = Util.StringToBytes1024(d.Charter); - groupProfileReply.GroupData.ShowInList = d.ShowInList; - groupProfileReply.GroupData.MemberTitle = Util.StringToBytes256(d.MemberTitle); - groupProfileReply.GroupData.PowersMask = d.PowersMask; - groupProfileReply.GroupData.InsigniaID = d.InsigniaID; - groupProfileReply.GroupData.FounderID = d.FounderID; - groupProfileReply.GroupData.MembershipFee = d.MembershipFee; - groupProfileReply.GroupData.OpenEnrollment = d.OpenEnrollment; - groupProfileReply.GroupData.Money = d.Money; - groupProfileReply.GroupData.GroupMembershipCount = d.GroupMembershipCount; - groupProfileReply.GroupData.GroupRolesCount = d.GroupRolesCount; - groupProfileReply.GroupData.AllowPublish = d.AllowPublish; - groupProfileReply.GroupData.MaturePublish = d.MaturePublish; - groupProfileReply.GroupData.OwnerRole = d.OwnerRole; - - OutPacket(groupProfileReply, ThrottleOutPacketType.Task); - } - break; - - case PacketType.GroupMembersRequest: - GroupMembersRequestPacket groupMembersRequestPacket = - (GroupMembersRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (groupMembersRequestPacket.AgentData.SessionID != SessionId || - groupMembersRequestPacket.AgentData.AgentID != AgentId) - break; - } - #endregion - - if (m_GroupsModule != null) - { - List members = - m_GroupsModule.GroupMembersRequest(this, groupMembersRequestPacket.GroupData.GroupID); - - int memberCount = members.Count; - - while (true) - { - int blockCount = members.Count; - if (blockCount > 40) - blockCount = 40; - - GroupMembersReplyPacket groupMembersReply = (GroupMembersReplyPacket)PacketPool.Instance.GetPacket(PacketType.GroupMembersReply); - - groupMembersReply.AgentData = - new GroupMembersReplyPacket.AgentDataBlock(); - groupMembersReply.GroupData = - new GroupMembersReplyPacket.GroupDataBlock(); - groupMembersReply.MemberData = - new GroupMembersReplyPacket.MemberDataBlock[ - blockCount]; - - groupMembersReply.AgentData.AgentID = AgentId; - groupMembersReply.GroupData.GroupID = - groupMembersRequestPacket.GroupData.GroupID; - groupMembersReply.GroupData.RequestID = - groupMembersRequestPacket.GroupData.RequestID; - groupMembersReply.GroupData.MemberCount = memberCount; - - for (int i = 0; i < blockCount; i++) - { - GroupMembersData m = members[0]; - members.RemoveAt(0); - - groupMembersReply.MemberData[i] = - new GroupMembersReplyPacket.MemberDataBlock(); - groupMembersReply.MemberData[i].AgentID = - m.AgentID; - groupMembersReply.MemberData[i].Contribution = - m.Contribution; - groupMembersReply.MemberData[i].OnlineStatus = - Util.StringToBytes256(m.OnlineStatus); - groupMembersReply.MemberData[i].AgentPowers = - m.AgentPowers; - groupMembersReply.MemberData[i].Title = - Util.StringToBytes256(m.Title); - groupMembersReply.MemberData[i].IsOwner = - m.IsOwner; - } - OutPacket(groupMembersReply, ThrottleOutPacketType.Task); - if (members.Count == 0) - break; - } - } - break; - - case PacketType.GroupRoleDataRequest: - GroupRoleDataRequestPacket groupRolesRequest = - (GroupRoleDataRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (groupRolesRequest.AgentData.SessionID != SessionId || - groupRolesRequest.AgentData.AgentID != AgentId) - break; - } - #endregion - - if (m_GroupsModule != null) - { - GroupRoleDataReplyPacket groupRolesReply = (GroupRoleDataReplyPacket)PacketPool.Instance.GetPacket(PacketType.GroupRoleDataReply); - - groupRolesReply.AgentData = - new GroupRoleDataReplyPacket.AgentDataBlock(); - - groupRolesReply.AgentData.AgentID = AgentId; - - groupRolesReply.GroupData = - new GroupRoleDataReplyPacket.GroupDataBlock(); - - groupRolesReply.GroupData.GroupID = - groupRolesRequest.GroupData.GroupID; - - groupRolesReply.GroupData.RequestID = - groupRolesRequest.GroupData.RequestID; - - List titles = - m_GroupsModule.GroupRoleDataRequest(this, - groupRolesRequest.GroupData.GroupID); - - groupRolesReply.GroupData.RoleCount = - titles.Count; - - groupRolesReply.RoleData = - new GroupRoleDataReplyPacket.RoleDataBlock[titles.Count]; - - int i = 0; - foreach (GroupRolesData d in titles) - { - groupRolesReply.RoleData[i] = - new GroupRoleDataReplyPacket.RoleDataBlock(); - - groupRolesReply.RoleData[i].RoleID = - d.RoleID; - groupRolesReply.RoleData[i].Name = - Util.StringToBytes256(d.Name); - groupRolesReply.RoleData[i].Title = - Util.StringToBytes256(d.Title); - groupRolesReply.RoleData[i].Description = - Util.StringToBytes1024(d.Description); - groupRolesReply.RoleData[i].Powers = - d.Powers; - groupRolesReply.RoleData[i].Members = - (uint)d.Members; - - i++; - } - - OutPacket(groupRolesReply, ThrottleOutPacketType.Task); - } - break; - - case PacketType.GroupRoleMembersRequest: - GroupRoleMembersRequestPacket groupRoleMembersRequest = - (GroupRoleMembersRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (groupRoleMembersRequest.AgentData.SessionID != SessionId || - groupRoleMembersRequest.AgentData.AgentID != AgentId) - break; - } - #endregion - - if (m_GroupsModule != null) - { - List mappings = - m_GroupsModule.GroupRoleMembersRequest(this, - groupRoleMembersRequest.GroupData.GroupID); - - int mappingsCount = mappings.Count; - - while (mappings.Count > 0) - { - int pairs = mappings.Count; - if (pairs > 32) - pairs = 32; - - GroupRoleMembersReplyPacket groupRoleMembersReply = (GroupRoleMembersReplyPacket)PacketPool.Instance.GetPacket(PacketType.GroupRoleMembersReply); - groupRoleMembersReply.AgentData = - new GroupRoleMembersReplyPacket.AgentDataBlock(); - groupRoleMembersReply.AgentData.AgentID = - AgentId; - groupRoleMembersReply.AgentData.GroupID = - groupRoleMembersRequest.GroupData.GroupID; - groupRoleMembersReply.AgentData.RequestID = - groupRoleMembersRequest.GroupData.RequestID; - - groupRoleMembersReply.AgentData.TotalPairs = - (uint)mappingsCount; - - groupRoleMembersReply.MemberData = - new GroupRoleMembersReplyPacket.MemberDataBlock[pairs]; - - for (int i = 0; i < pairs; i++) - { - GroupRoleMembersData d = mappings[0]; - mappings.RemoveAt(0); - - groupRoleMembersReply.MemberData[i] = - new GroupRoleMembersReplyPacket.MemberDataBlock(); - - groupRoleMembersReply.MemberData[i].RoleID = - d.RoleID; - groupRoleMembersReply.MemberData[i].MemberID = - d.MemberID; - } - - OutPacket(groupRoleMembersReply, ThrottleOutPacketType.Task); - } - } - break; - - case PacketType.CreateGroupRequest: - CreateGroupRequestPacket createGroupRequest = - (CreateGroupRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (createGroupRequest.AgentData.SessionID != SessionId || - createGroupRequest.AgentData.AgentID != AgentId) - break; - } - #endregion - - if (m_GroupsModule != null) - { - m_GroupsModule.CreateGroup(this, - Utils.BytesToString(createGroupRequest.GroupData.Name), - Utils.BytesToString(createGroupRequest.GroupData.Charter), - createGroupRequest.GroupData.ShowInList, - createGroupRequest.GroupData.InsigniaID, - createGroupRequest.GroupData.MembershipFee, - createGroupRequest.GroupData.OpenEnrollment, - createGroupRequest.GroupData.AllowPublish, - createGroupRequest.GroupData.MaturePublish); - } - break; - - case PacketType.UpdateGroupInfo: - UpdateGroupInfoPacket updateGroupInfo = - (UpdateGroupInfoPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (updateGroupInfo.AgentData.SessionID != SessionId || - updateGroupInfo.AgentData.AgentID != AgentId) - break; - } - #endregion - - if (m_GroupsModule != null) - { - m_GroupsModule.UpdateGroupInfo(this, - updateGroupInfo.GroupData.GroupID, - Utils.BytesToString(updateGroupInfo.GroupData.Charter), - updateGroupInfo.GroupData.ShowInList, - updateGroupInfo.GroupData.InsigniaID, - updateGroupInfo.GroupData.MembershipFee, - updateGroupInfo.GroupData.OpenEnrollment, - updateGroupInfo.GroupData.AllowPublish, - updateGroupInfo.GroupData.MaturePublish); - } - - break; - - case PacketType.SetGroupAcceptNotices: - SetGroupAcceptNoticesPacket setGroupAcceptNotices = - (SetGroupAcceptNoticesPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (setGroupAcceptNotices.AgentData.SessionID != SessionId || - setGroupAcceptNotices.AgentData.AgentID != AgentId) - break; - } - #endregion - - if (m_GroupsModule != null) - { - m_GroupsModule.SetGroupAcceptNotices(this, - setGroupAcceptNotices.Data.GroupID, - setGroupAcceptNotices.Data.AcceptNotices, - setGroupAcceptNotices.NewData.ListInProfile); - } - - break; - - case PacketType.GroupTitleUpdate: - GroupTitleUpdatePacket groupTitleUpdate = - (GroupTitleUpdatePacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (groupTitleUpdate.AgentData.SessionID != SessionId || - groupTitleUpdate.AgentData.AgentID != AgentId) - break; - } - #endregion - - if (m_GroupsModule != null) - { - m_GroupsModule.GroupTitleUpdate(this, - groupTitleUpdate.AgentData.GroupID, - groupTitleUpdate.AgentData.TitleRoleID); - } - - break; - - - case PacketType.ParcelDeedToGroup: - ParcelDeedToGroupPacket parcelDeedToGroup = (ParcelDeedToGroupPacket)Pack; - if (m_GroupsModule != null) - { - ParcelDeedToGroup handlerParcelDeedToGroup = OnParcelDeedToGroup; - if (handlerParcelDeedToGroup != null) - { - handlerParcelDeedToGroup(parcelDeedToGroup.Data.LocalID, parcelDeedToGroup.Data.GroupID, this); - - } - } - - break; - - - case PacketType.GroupNoticesListRequest: - GroupNoticesListRequestPacket groupNoticesListRequest = - (GroupNoticesListRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (groupNoticesListRequest.AgentData.SessionID != SessionId || - groupNoticesListRequest.AgentData.AgentID != AgentId) - break; - } - #endregion - - if (m_GroupsModule != null) - { - GroupNoticeData[] gn = - m_GroupsModule.GroupNoticesListRequest(this, - groupNoticesListRequest.Data.GroupID); - - GroupNoticesListReplyPacket groupNoticesListReply = (GroupNoticesListReplyPacket)PacketPool.Instance.GetPacket(PacketType.GroupNoticesListReply); - groupNoticesListReply.AgentData = - new GroupNoticesListReplyPacket.AgentDataBlock(); - groupNoticesListReply.AgentData.AgentID = AgentId; - groupNoticesListReply.AgentData.GroupID = groupNoticesListRequest.Data.GroupID; - - groupNoticesListReply.Data = new GroupNoticesListReplyPacket.DataBlock[gn.Length]; - - int i = 0; - foreach (GroupNoticeData g in gn) - { - groupNoticesListReply.Data[i] = new GroupNoticesListReplyPacket.DataBlock(); - groupNoticesListReply.Data[i].NoticeID = - g.NoticeID; - groupNoticesListReply.Data[i].Timestamp = - g.Timestamp; - groupNoticesListReply.Data[i].FromName = - Util.StringToBytes256(g.FromName); - groupNoticesListReply.Data[i].Subject = - Util.StringToBytes256(g.Subject); - groupNoticesListReply.Data[i].HasAttachment = - g.HasAttachment; - groupNoticesListReply.Data[i].AssetType = - g.AssetType; - i++; - } - - OutPacket(groupNoticesListReply, ThrottleOutPacketType.Task); - } - - break; - - case PacketType.GroupNoticeRequest: - GroupNoticeRequestPacket groupNoticeRequest = - (GroupNoticeRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (groupNoticeRequest.AgentData.SessionID != SessionId || - groupNoticeRequest.AgentData.AgentID != AgentId) - break; - } - #endregion - - if (m_GroupsModule != null) - { - m_GroupsModule.GroupNoticeRequest(this, - groupNoticeRequest.Data.GroupNoticeID); - } - break; - - case PacketType.GroupRoleUpdate: - GroupRoleUpdatePacket groupRoleUpdate = - (GroupRoleUpdatePacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (groupRoleUpdate.AgentData.SessionID != SessionId || - groupRoleUpdate.AgentData.AgentID != AgentId) - break; - } - #endregion - - if (m_GroupsModule != null) - { - foreach (GroupRoleUpdatePacket.RoleDataBlock d in - groupRoleUpdate.RoleData) - { - m_GroupsModule.GroupRoleUpdate(this, - groupRoleUpdate.AgentData.GroupID, - d.RoleID, - Utils.BytesToString(d.Name), - Utils.BytesToString(d.Description), - Utils.BytesToString(d.Title), - d.Powers, - d.UpdateType); - } - m_GroupsModule.NotifyChange(groupRoleUpdate.AgentData.GroupID); - } - break; - - case PacketType.GroupRoleChanges: - GroupRoleChangesPacket groupRoleChanges = - (GroupRoleChangesPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (groupRoleChanges.AgentData.SessionID != SessionId || - groupRoleChanges.AgentData.AgentID != AgentId) - break; - } - #endregion - - if (m_GroupsModule != null) - { - foreach (GroupRoleChangesPacket.RoleChangeBlock d in - groupRoleChanges.RoleChange) - { - m_GroupsModule.GroupRoleChanges(this, - groupRoleChanges.AgentData.GroupID, - d.RoleID, - d.MemberID, - d.Change); - } - m_GroupsModule.NotifyChange(groupRoleChanges.AgentData.GroupID); - } - break; - - case PacketType.JoinGroupRequest: - JoinGroupRequestPacket joinGroupRequest = - (JoinGroupRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (joinGroupRequest.AgentData.SessionID != SessionId || - joinGroupRequest.AgentData.AgentID != AgentId) - break; - } - #endregion - - if (m_GroupsModule != null) - { - m_GroupsModule.JoinGroupRequest(this, - joinGroupRequest.GroupData.GroupID); - } - break; - - case PacketType.LeaveGroupRequest: - LeaveGroupRequestPacket leaveGroupRequest = - (LeaveGroupRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (leaveGroupRequest.AgentData.SessionID != SessionId || - leaveGroupRequest.AgentData.AgentID != AgentId) - break; - } - #endregion - - if (m_GroupsModule != null) - { - m_GroupsModule.LeaveGroupRequest(this, - leaveGroupRequest.GroupData.GroupID); - } - break; - - case PacketType.EjectGroupMemberRequest: - EjectGroupMemberRequestPacket ejectGroupMemberRequest = - (EjectGroupMemberRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (ejectGroupMemberRequest.AgentData.SessionID != SessionId || - ejectGroupMemberRequest.AgentData.AgentID != AgentId) - break; - } - #endregion - - if (m_GroupsModule != null) - { - foreach (EjectGroupMemberRequestPacket.EjectDataBlock e - in ejectGroupMemberRequest.EjectData) - { - m_GroupsModule.EjectGroupMemberRequest(this, - ejectGroupMemberRequest.GroupData.GroupID, - e.EjecteeID); - } - } - break; - - case PacketType.InviteGroupRequest: - InviteGroupRequestPacket inviteGroupRequest = - (InviteGroupRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (inviteGroupRequest.AgentData.SessionID != SessionId || - inviteGroupRequest.AgentData.AgentID != AgentId) - break; - } - #endregion - - if (m_GroupsModule != null) - { - foreach (InviteGroupRequestPacket.InviteDataBlock b in - inviteGroupRequest.InviteData) - { - m_GroupsModule.InviteGroupRequest(this, - inviteGroupRequest.GroupData.GroupID, - b.InviteeID, - b.RoleID); - } - } - break; - - //#endregion - - case PacketType.StartLure: - StartLurePacket startLureRequest = (StartLurePacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (startLureRequest.AgentData.SessionID != SessionId || - startLureRequest.AgentData.AgentID != AgentId) - break; - } - #endregion - - StartLure handlerStartLure = OnStartLure; - if (handlerStartLure != null) - handlerStartLure(startLureRequest.Info.LureType, - Utils.BytesToString( - startLureRequest.Info.Message), - startLureRequest.TargetData[0].TargetID, - this); - break; - - case PacketType.TeleportLureRequest: - TeleportLureRequestPacket teleportLureRequest = - (TeleportLureRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (teleportLureRequest.Info.SessionID != SessionId || - teleportLureRequest.Info.AgentID != AgentId) - break; - } - #endregion - - TeleportLureRequest handlerTeleportLureRequest = OnTeleportLureRequest; - if (handlerTeleportLureRequest != null) - handlerTeleportLureRequest( - teleportLureRequest.Info.LureID, - teleportLureRequest.Info.TeleportFlags, - this); - break; - - case PacketType.ClassifiedInfoRequest: - ClassifiedInfoRequestPacket classifiedInfoRequest = - (ClassifiedInfoRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (classifiedInfoRequest.AgentData.SessionID != SessionId || - classifiedInfoRequest.AgentData.AgentID != AgentId) - break; - } - #endregion - - ClassifiedInfoRequest handlerClassifiedInfoRequest = OnClassifiedInfoRequest; - if (handlerClassifiedInfoRequest != null) - handlerClassifiedInfoRequest( - classifiedInfoRequest.Data.ClassifiedID, - this); - break; - - case PacketType.ClassifiedInfoUpdate: - ClassifiedInfoUpdatePacket classifiedInfoUpdate = - (ClassifiedInfoUpdatePacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (classifiedInfoUpdate.AgentData.SessionID != SessionId || - classifiedInfoUpdate.AgentData.AgentID != AgentId) - break; - } - #endregion - - ClassifiedInfoUpdate handlerClassifiedInfoUpdate = OnClassifiedInfoUpdate; - if (handlerClassifiedInfoUpdate != null) - handlerClassifiedInfoUpdate( - classifiedInfoUpdate.Data.ClassifiedID, - classifiedInfoUpdate.Data.Category, - Utils.BytesToString( - classifiedInfoUpdate.Data.Name), - Utils.BytesToString( - classifiedInfoUpdate.Data.Desc), - classifiedInfoUpdate.Data.ParcelID, - classifiedInfoUpdate.Data.ParentEstate, - classifiedInfoUpdate.Data.SnapshotID, - new Vector3( - classifiedInfoUpdate.Data.PosGlobal), - classifiedInfoUpdate.Data.ClassifiedFlags, - classifiedInfoUpdate.Data.PriceForListing, - this); - break; - - case PacketType.ClassifiedDelete: - ClassifiedDeletePacket classifiedDelete = - (ClassifiedDeletePacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (classifiedDelete.AgentData.SessionID != SessionId || - classifiedDelete.AgentData.AgentID != AgentId) - break; - } - #endregion - - ClassifiedDelete handlerClassifiedDelete = OnClassifiedDelete; - if (handlerClassifiedDelete != null) - handlerClassifiedDelete( - classifiedDelete.Data.ClassifiedID, - this); - break; - - case PacketType.ClassifiedGodDelete: - ClassifiedGodDeletePacket classifiedGodDelete = - (ClassifiedGodDeletePacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (classifiedGodDelete.AgentData.SessionID != SessionId || - classifiedGodDelete.AgentData.AgentID != AgentId) - break; - } - #endregion - - ClassifiedDelete handlerClassifiedGodDelete = OnClassifiedGodDelete; - if (handlerClassifiedGodDelete != null) - handlerClassifiedGodDelete( - classifiedGodDelete.Data.ClassifiedID, - this); - break; - - case PacketType.EventGodDelete: - EventGodDeletePacket eventGodDelete = - (EventGodDeletePacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (eventGodDelete.AgentData.SessionID != SessionId || - eventGodDelete.AgentData.AgentID != AgentId) - break; - } - #endregion - - EventGodDelete handlerEventGodDelete = OnEventGodDelete; - if (handlerEventGodDelete != null) - handlerEventGodDelete( - eventGodDelete.EventData.EventID, - eventGodDelete.QueryData.QueryID, - Utils.BytesToString( - eventGodDelete.QueryData.QueryText), - eventGodDelete.QueryData.QueryFlags, - eventGodDelete.QueryData.QueryStart, - this); - break; - - case PacketType.EventNotificationAddRequest: - EventNotificationAddRequestPacket eventNotificationAdd = - (EventNotificationAddRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (eventNotificationAdd.AgentData.SessionID != SessionId || - eventNotificationAdd.AgentData.AgentID != AgentId) - break; - } - #endregion - - EventNotificationAddRequest handlerEventNotificationAddRequest = OnEventNotificationAddRequest; - if (handlerEventNotificationAddRequest != null) - handlerEventNotificationAddRequest( - eventNotificationAdd.EventData.EventID, this); - break; - - case PacketType.EventNotificationRemoveRequest: - EventNotificationRemoveRequestPacket eventNotificationRemove = - (EventNotificationRemoveRequestPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (eventNotificationRemove.AgentData.SessionID != SessionId || - eventNotificationRemove.AgentData.AgentID != AgentId) - break; - } - #endregion - - EventNotificationRemoveRequest handlerEventNotificationRemoveRequest = OnEventNotificationRemoveRequest; - if (handlerEventNotificationRemoveRequest != null) - handlerEventNotificationRemoveRequest( - eventNotificationRemove.EventData.EventID, this); - break; - - case PacketType.RetrieveInstantMessages: - RetrieveInstantMessagesPacket rimpInstantMessagePack = (RetrieveInstantMessagesPacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (rimpInstantMessagePack.AgentData.SessionID != SessionId || - rimpInstantMessagePack.AgentData.AgentID != AgentId) - break; - } - #endregion - - RetrieveInstantMessages handlerRetrieveInstantMessages = OnRetrieveInstantMessages; - if (handlerRetrieveInstantMessages != null) - handlerRetrieveInstantMessages(this); - break; - - case PacketType.PickDelete: - PickDeletePacket pickDelete = - (PickDeletePacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (pickDelete.AgentData.SessionID != SessionId || - pickDelete.AgentData.AgentID != AgentId) - break; - } - #endregion - - PickDelete handlerPickDelete = OnPickDelete; - if (handlerPickDelete != null) - handlerPickDelete(this, pickDelete.Data.PickID); - break; - - case PacketType.PickGodDelete: - PickGodDeletePacket pickGodDelete = - (PickGodDeletePacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (pickGodDelete.AgentData.SessionID != SessionId || - pickGodDelete.AgentData.AgentID != AgentId) - break; - } - #endregion - - PickGodDelete handlerPickGodDelete = OnPickGodDelete; - if (handlerPickGodDelete != null) - handlerPickGodDelete(this, - pickGodDelete.AgentData.AgentID, - pickGodDelete.Data.PickID, - pickGodDelete.Data.QueryID); - break; - - case PacketType.PickInfoUpdate: - PickInfoUpdatePacket pickInfoUpdate = - (PickInfoUpdatePacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (pickInfoUpdate.AgentData.SessionID != SessionId || - pickInfoUpdate.AgentData.AgentID != AgentId) - break; - } - #endregion - - PickInfoUpdate handlerPickInfoUpdate = OnPickInfoUpdate; - if (handlerPickInfoUpdate != null) - handlerPickInfoUpdate(this, - pickInfoUpdate.Data.PickID, - pickInfoUpdate.Data.CreatorID, - pickInfoUpdate.Data.TopPick, - Utils.BytesToString(pickInfoUpdate.Data.Name), - Utils.BytesToString(pickInfoUpdate.Data.Desc), - pickInfoUpdate.Data.SnapshotID, - pickInfoUpdate.Data.SortOrder, - pickInfoUpdate.Data.Enabled); - break; - - case PacketType.AvatarNotesUpdate: - AvatarNotesUpdatePacket avatarNotesUpdate = - (AvatarNotesUpdatePacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (avatarNotesUpdate.AgentData.SessionID != SessionId || - avatarNotesUpdate.AgentData.AgentID != AgentId) - break; - } - #endregion - - AvatarNotesUpdate handlerAvatarNotesUpdate = OnAvatarNotesUpdate; - if (handlerAvatarNotesUpdate != null) - handlerAvatarNotesUpdate(this, - avatarNotesUpdate.Data.TargetID, - Utils.BytesToString(avatarNotesUpdate.Data.Notes)); - break; - - case PacketType.AvatarInterestsUpdate: - AvatarInterestsUpdatePacket avatarInterestUpdate = - (AvatarInterestsUpdatePacket)Pack; - - #region Packet Session and User Check - if (m_checkPackets) - { - if (avatarInterestUpdate.AgentData.SessionID != SessionId || - avatarInterestUpdate.AgentData.AgentID != AgentId) - break; - } - #endregion - - AvatarInterestUpdate handlerAvatarInterestUpdate = OnAvatarInterestUpdate; - if (handlerAvatarInterestUpdate != null) - handlerAvatarInterestUpdate(this, - avatarInterestUpdate.PropertiesData.WantToMask, - Utils.BytesToString(avatarInterestUpdate.PropertiesData.WantToText), - avatarInterestUpdate.PropertiesData.SkillsMask, - Utils.BytesToString(avatarInterestUpdate.PropertiesData.SkillsText), - Utils.BytesToString(avatarInterestUpdate.PropertiesData.LanguagesText)); - break; - - case PacketType.GrantUserRights: - GrantUserRightsPacket GrantUserRights = - (GrantUserRightsPacket)Pack; - #region Packet Session and User Check - if (m_checkPackets) - { - if (GrantUserRights.AgentData.SessionID != SessionId || - GrantUserRights.AgentData.AgentID != AgentId) - break; - } - #endregion - GrantUserFriendRights GrantUserRightsHandler = OnGrantUserRights; - if (GrantUserRightsHandler != null) - GrantUserRightsHandler(this, - GrantUserRights.AgentData.AgentID, - GrantUserRights.Rights[0].AgentRelated, - GrantUserRights.Rights[0].RelatedRights); - break; - - case PacketType.PlacesQuery: - PlacesQueryPacket placesQueryPacket = - (PlacesQueryPacket)Pack; - - PlacesQuery handlerPlacesQuery = OnPlacesQuery; - - if (handlerPlacesQuery != null) - handlerPlacesQuery(placesQueryPacket.AgentData.QueryID, - placesQueryPacket.TransactionData.TransactionID, - Utils.BytesToString( - placesQueryPacket.QueryData.QueryText), - placesQueryPacket.QueryData.QueryFlags, - (byte)placesQueryPacket.QueryData.Category, - Utils.BytesToString( - placesQueryPacket.QueryData.SimName), - this); - break; - */ - #endregion - default: - m_log.Warn("[CLIENT]: unhandled packet " + Pack); - break; + if (!ProcessPacketMethod(Pack)) + { + m_log.Warn("[CLIENT]: unhandled packet " + Pack); } PacketPool.Instance.ReturnPacket(Pack); - } private static PrimitiveBaseShape GetShapeFromAddPacket(ObjectAddPacket addPacket) -- cgit v1.1 From c62a6adb2b234fcbe99e352f4bd2af0cbf683a99 Mon Sep 17 00:00:00 2001 From: dahlia Date: Wed, 17 Feb 2010 19:56:30 -0800 Subject: change "SYSTEMIP" to "localhost" in the create region console command prompt --- OpenSim/Framework/RegionInfo.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/OpenSim/Framework/RegionInfo.cs b/OpenSim/Framework/RegionInfo.cs index 88b62e0..ee5dd37 100644 --- a/OpenSim/Framework/RegionInfo.cs +++ b/OpenSim/Framework/RegionInfo.cs @@ -474,15 +474,15 @@ namespace OpenSim.Framework if (config.Contains("ExternalHostName")) { - externalName = config.GetString("ExternalHostName", "SYSTEMIP"); + externalName = config.GetString("ExternalHostName", "localhost"); } else { - externalName = MainConsole.Instance.CmdPrompt("External host name", "SYSTEMIP"); + externalName = MainConsole.Instance.CmdPrompt("External host name", "localhost"); config.Set("ExternalHostName", externalName); } - if (externalName == "SYSTEMIP") + if (externalName == "localhost") m_externalHostName = Util.GetLocalHost().ToString(); else m_externalHostName = externalName; @@ -788,7 +788,7 @@ namespace OpenSim.Framework m_allow_alternate_ports = (bool) configuration_result; break; case "external_host_name": - if ((string) configuration_result != "SYSTEMIP") + if ((string) configuration_result != "localhost") { m_externalHostName = (string) configuration_result; } -- cgit v1.1 From 92f8f3e9d278455aca1e36e40c58ac529069bdef Mon Sep 17 00:00:00 2001 From: Melanie Date: Thu, 18 Feb 2010 03:31:06 +0000 Subject: Revert "change "SYSTEMIP" to "localhost" in the create region console command prompt" after speaking to Dahlia This reverts commit c62a6adb2b234fcbe99e352f4bd2af0cbf683a99. --- OpenSim/Framework/RegionInfo.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/OpenSim/Framework/RegionInfo.cs b/OpenSim/Framework/RegionInfo.cs index ee5dd37..88b62e0 100644 --- a/OpenSim/Framework/RegionInfo.cs +++ b/OpenSim/Framework/RegionInfo.cs @@ -474,15 +474,15 @@ namespace OpenSim.Framework if (config.Contains("ExternalHostName")) { - externalName = config.GetString("ExternalHostName", "localhost"); + externalName = config.GetString("ExternalHostName", "SYSTEMIP"); } else { - externalName = MainConsole.Instance.CmdPrompt("External host name", "localhost"); + externalName = MainConsole.Instance.CmdPrompt("External host name", "SYSTEMIP"); config.Set("ExternalHostName", externalName); } - if (externalName == "localhost") + if (externalName == "SYSTEMIP") m_externalHostName = Util.GetLocalHost().ToString(); else m_externalHostName = externalName; @@ -788,7 +788,7 @@ namespace OpenSim.Framework m_allow_alternate_ports = (bool) configuration_result; break; case "external_host_name": - if ((string) configuration_result != "localhost") + if ((string) configuration_result != "SYSTEMIP") { m_externalHostName = (string) configuration_result; } -- cgit v1.1 From 842b68eeff7571d3c82415c65065bec3c95f34ea Mon Sep 17 00:00:00 2001 From: Melanie Date: Thu, 18 Feb 2010 04:19:33 +0000 Subject: Change handling of the SYSTEMIP constant to be more sane. This will now choose the first network interface IP address, or the loopback interface if no external interfaces are found. It will log the IP address used as [NETWORK]: Using x.x.x.x for SYSTEMIP. --- OpenSim/Framework/RegionInfo.cs | 1 - OpenSim/Framework/Util.cs | 18 ++++++++++++------ OpenSim/Region/Application/OpenSim.cs | 2 ++ 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/OpenSim/Framework/RegionInfo.cs b/OpenSim/Framework/RegionInfo.cs index 88b62e0..baef32a 100644 --- a/OpenSim/Framework/RegionInfo.cs +++ b/OpenSim/Framework/RegionInfo.cs @@ -487,7 +487,6 @@ namespace OpenSim.Framework else m_externalHostName = externalName; - // Master avatar cruft // string masterAvatarUUID; diff --git a/OpenSim/Framework/Util.cs b/OpenSim/Framework/Util.cs index 7215086..48435cb 100644 --- a/OpenSim/Framework/Util.cs +++ b/OpenSim/Framework/Util.cs @@ -589,11 +589,17 @@ namespace OpenSim.Framework public static IPAddress GetLocalHost() { - string dnsAddress = "localhost"; + IPAddress[] iplist = GetLocalHosts(); - IPAddress[] hosts = Dns.GetHostEntry(dnsAddress).AddressList; + if (iplist.Length == 0) // No accessible external interfaces + { + IPAddress[] loopback = Dns.GetHostAddresses("localhost"); + IPAddress localhost = loopback[0]; - foreach (IPAddress host in hosts) + return localhost; + } + + foreach (IPAddress host in iplist) { if (!IPAddress.IsLoopback(host) && host.AddressFamily == AddressFamily.InterNetwork) { @@ -601,15 +607,15 @@ namespace OpenSim.Framework } } - if (hosts.Length > 0) + if (iplist.Length > 0) { - foreach (IPAddress host in hosts) + foreach (IPAddress host in iplist) { if (host.AddressFamily == AddressFamily.InterNetwork) return host; } // Well all else failed... - return hosts[0]; + return iplist[0]; } return null; diff --git a/OpenSim/Region/Application/OpenSim.cs b/OpenSim/Region/Application/OpenSim.cs index 96eceb0..05e283e 100755 --- a/OpenSim/Region/Application/OpenSim.cs +++ b/OpenSim/Region/Application/OpenSim.cs @@ -190,6 +190,8 @@ namespace OpenSim PrintFileToConsole("startuplogo.txt"); + m_log.InfoFormat("[NETWORK]: Using {0} as SYSTEMIP", Util.GetLocalHost().ToString()); + // For now, start at the 'root' level by default if (m_sceneManager.Scenes.Count == 1) // If there is only one region, select it ChangeSelectedRegion("region", -- cgit v1.1 From 214b1351fbd7287a70e465a4dd83668b1d2c7044 Mon Sep 17 00:00:00 2001 From: Justin Clark-Casey (justincc) Date: Fri, 19 Feb 2010 21:18:03 +0000 Subject: minor: Make FlotsamAssetCache default loglevel 0 to match that given in bin/config-include/FlotsamCache.ini.example --- OpenSim/Region/ClientStack/LindenUDP/LLClientView.cs | 4 ++-- OpenSim/Region/CoreModules/Asset/FlotsamAssetCache.cs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/OpenSim/Region/ClientStack/LindenUDP/LLClientView.cs b/OpenSim/Region/ClientStack/LindenUDP/LLClientView.cs index 0b90b55..2ca2657 100644 --- a/OpenSim/Region/ClientStack/LindenUDP/LLClientView.cs +++ b/OpenSim/Region/ClientStack/LindenUDP/LLClientView.cs @@ -11025,10 +11025,10 @@ namespace OpenSim.Region.ClientStack.LindenUDP /// OpenMetaverse.packet public void ProcessInPacket(Packet Pack) { +// m_log.DebugFormat("[CLIENT]: Packet IN {0}", Pack); + if (!ProcessPacketMethod(Pack)) - { m_log.Warn("[CLIENT]: unhandled packet " + Pack); - } PacketPool.Instance.ReturnPacket(Pack); } diff --git a/OpenSim/Region/CoreModules/Asset/FlotsamAssetCache.cs b/OpenSim/Region/CoreModules/Asset/FlotsamAssetCache.cs index 9216e0b..967c0a1 100644 --- a/OpenSim/Region/CoreModules/Asset/FlotsamAssetCache.cs +++ b/OpenSim/Region/CoreModules/Asset/FlotsamAssetCache.cs @@ -69,7 +69,7 @@ namespace Flotsam.RegionModules.AssetCache private readonly List m_InvalidChars = new List(); - private int m_LogLevel = 1; + private int m_LogLevel = 0; private ulong m_HitRateDisplay = 1; // How often to display hit statistics, given in requests private static ulong m_Requests; @@ -156,7 +156,7 @@ namespace Flotsam.RegionModules.AssetCache m_WaitOnInprogressTimeout = assetConfig.GetInt("WaitOnInprogressTimeout", 3000); #endif - m_LogLevel = assetConfig.GetInt("LogLevel", 1); + m_LogLevel = assetConfig.GetInt("LogLevel", 0); m_HitRateDisplay = (ulong)assetConfig.GetInt("HitRateDisplay", 1000); m_FileExpiration = TimeSpan.FromHours(assetConfig.GetDouble("FileCacheTimeout", m_DefaultFileExpiration)); -- cgit v1.1 From c767a7901cbdb1f2fe786f1a1632c09606af9c6c Mon Sep 17 00:00:00 2001 From: Justin Clark-Casey (justincc) Date: Fri, 19 Feb 2010 22:30:46 +0000 Subject: forestall bug reports about the Command error: System.EntryPointNotFoundException: CreateZStream save/load oar/iar issue by telling the user what the likely problem is --- .../Inventory/Archiver/InventoryArchiverModule.cs | 66 ++++++++++++++++++++-- .../World/Archiver/ArchiveReadRequest.cs | 14 ++++- .../Archiver/ArchiveWriteRequestPreparation.cs | 14 ++++- 3 files changed, 86 insertions(+), 8 deletions(-) diff --git a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiverModule.cs b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiverModule.cs index ecd60bd..ac3e199 100644 --- a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiverModule.cs +++ b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiverModule.cs @@ -131,7 +131,20 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver { if (CheckPresence(userInfo.UserProfile.ID)) { - new InventoryArchiveWriteRequest(id, this, m_aScene, userInfo, invPath, saveStream).Execute(); + try + { + new InventoryArchiveWriteRequest(id, this, m_aScene, userInfo, invPath, saveStream).Execute(); + } + catch (EntryPointNotFoundException e) + { + m_log.ErrorFormat( + "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); + m_log.Error(e); + + return false; + } + return true; } else @@ -156,7 +169,20 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver { if (CheckPresence(userInfo.UserProfile.ID)) { - new InventoryArchiveWriteRequest(id, this, m_aScene, userInfo, invPath, savePath).Execute(); + try + { + new InventoryArchiveWriteRequest(id, this, m_aScene, userInfo, invPath, savePath).Execute(); + } + catch (EntryPointNotFoundException e) + { + m_log.ErrorFormat( + "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); + m_log.Error(e); + + return false; + } + return true; } else @@ -181,8 +207,22 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver { if (CheckPresence(userInfo.UserProfile.ID)) { - InventoryArchiveReadRequest request = - new InventoryArchiveReadRequest(m_aScene, userInfo, invPath, loadStream); + InventoryArchiveReadRequest request; + + try + { + request = new InventoryArchiveReadRequest(m_aScene, userInfo, invPath, loadStream); + } + catch (EntryPointNotFoundException e) + { + m_log.ErrorFormat( + "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); + m_log.Error(e); + + return false; + } + UpdateClientWithLoadedNodes(userInfo, request.Execute()); return true; @@ -209,8 +249,22 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver { if (CheckPresence(userInfo.UserProfile.ID)) { - InventoryArchiveReadRequest request = - new InventoryArchiveReadRequest(m_aScene, userInfo, invPath, loadPath); + InventoryArchiveReadRequest request; + + try + { + request = new InventoryArchiveReadRequest(m_aScene, userInfo, invPath, loadPath); + } + catch (EntryPointNotFoundException e) + { + m_log.ErrorFormat( + "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); + m_log.Error(e); + + return false; + } + UpdateClientWithLoadedNodes(userInfo, request.Execute()); return true; diff --git a/OpenSim/Region/CoreModules/World/Archiver/ArchiveReadRequest.cs b/OpenSim/Region/CoreModules/World/Archiver/ArchiveReadRequest.cs index 8ed1913..ad58f40 100644 --- a/OpenSim/Region/CoreModules/World/Archiver/ArchiveReadRequest.cs +++ b/OpenSim/Region/CoreModules/World/Archiver/ArchiveReadRequest.cs @@ -73,7 +73,19 @@ namespace OpenSim.Region.CoreModules.World.Archiver public ArchiveReadRequest(Scene scene, string loadPath, bool merge, Guid requestId) { m_scene = scene; - m_loadStream = new GZipStream(GetStream(loadPath), CompressionMode.Decompress); + + try + { + m_loadStream = new GZipStream(GetStream(loadPath), CompressionMode.Decompress); + } + catch (EntryPointNotFoundException e) + { + m_log.ErrorFormat( + "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); + m_log.Error(e); + } + m_errorMessage = String.Empty; m_merge = merge; m_requestId = requestId; diff --git a/OpenSim/Region/CoreModules/World/Archiver/ArchiveWriteRequestPreparation.cs b/OpenSim/Region/CoreModules/World/Archiver/ArchiveWriteRequestPreparation.cs index 71bfe57..b61b341 100644 --- a/OpenSim/Region/CoreModules/World/Archiver/ArchiveWriteRequestPreparation.cs +++ b/OpenSim/Region/CoreModules/World/Archiver/ArchiveWriteRequestPreparation.cs @@ -65,7 +65,19 @@ namespace OpenSim.Region.CoreModules.World.Archiver public ArchiveWriteRequestPreparation(Scene scene, string savePath, Guid requestId) { m_scene = scene; - m_saveStream = new GZipStream(new FileStream(savePath, FileMode.Create), CompressionMode.Compress); + + try + { + m_saveStream = new GZipStream(new FileStream(savePath, FileMode.Create), CompressionMode.Compress); + } + catch (EntryPointNotFoundException e) + { + m_log.ErrorFormat( + "[ARCHIVER]: Mismatch between Mono and zlib1g library version when trying to create compression stream." + + "If you've manually installed Mono, have you appropriately updated zlib1g as well?"); + m_log.Error(e); + } + m_requestId = requestId; } -- cgit v1.1 From 8294fbd069aaec81121c8563cf29d89030066717 Mon Sep 17 00:00:00 2001 From: Justin Clark-Casey (justincc) Date: Fri, 19 Feb 2010 22:31:53 +0000 Subject: minor: remove mono compiler warning --- OpenSim/Region/CoreModules/Avatar/Combat/CombatModule.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OpenSim/Region/CoreModules/Avatar/Combat/CombatModule.cs b/OpenSim/Region/CoreModules/Avatar/Combat/CombatModule.cs index 4069991..1a6cd6c 100644 --- a/OpenSim/Region/CoreModules/Avatar/Combat/CombatModule.cs +++ b/OpenSim/Region/CoreModules/Avatar/Combat/CombatModule.cs @@ -159,7 +159,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Combat.CombatModule avatar.Invulnerable = true; } } - catch (Exception ex) + catch (Exception) { } } -- cgit v1.1 From 68b494b2cc54cfdd8fa8a0736332046de3887d6f Mon Sep 17 00:00:00 2001 From: Justin Clark-Casey (justincc) Date: Fri, 19 Feb 2010 22:44:33 +0000 Subject: Apply http://opensimulator.org/mantis/view.php?id=4495 Adds IsChildAgent property to IAvatar in MRM. Thanks ziah --- CONTRIBUTORS.txt | 1 + .../OptionalModules/Scripting/Minimodule/Interfaces/IAvatar.cs | 3 +++ OpenSim/Region/OptionalModules/Scripting/Minimodule/SPAvatar.cs | 5 +++++ 3 files changed, 9 insertions(+) diff --git a/CONTRIBUTORS.txt b/CONTRIBUTORS.txt index 13c05ef..5b4959a 100644 --- a/CONTRIBUTORS.txt +++ b/CONTRIBUTORS.txt @@ -128,6 +128,7 @@ what it is today. * YZh * Zackary Geers aka Kunnis Basiat * Zha Ewry +* ziah = LSL Devs = diff --git a/OpenSim/Region/OptionalModules/Scripting/Minimodule/Interfaces/IAvatar.cs b/OpenSim/Region/OptionalModules/Scripting/Minimodule/Interfaces/IAvatar.cs index 03c1e95..3d49732 100644 --- a/OpenSim/Region/OptionalModules/Scripting/Minimodule/Interfaces/IAvatar.cs +++ b/OpenSim/Region/OptionalModules/Scripting/Minimodule/Interfaces/IAvatar.cs @@ -34,6 +34,9 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule { public interface IAvatar : IEntity { + + bool IsChildAgent { get; } + //// /// Array of worn attachments, empty but not null, if no attachments are worn /// diff --git a/OpenSim/Region/OptionalModules/Scripting/Minimodule/SPAvatar.cs b/OpenSim/Region/OptionalModules/Scripting/Minimodule/SPAvatar.cs index 4427426..0786bd9 100644 --- a/OpenSim/Region/OptionalModules/Scripting/Minimodule/SPAvatar.cs +++ b/OpenSim/Region/OptionalModules/Scripting/Minimodule/SPAvatar.cs @@ -70,6 +70,11 @@ namespace OpenSim.Region.OptionalModules.Scripting.Minimodule set { GetSP().TeleportWithMomentum(value); } } + public bool IsChildAgent + { + get { return GetSP().IsChildAgent; } + } + #region IAvatar implementation public IAvatarAttachment[] Attachments { -- cgit v1.1 From d1f2fae3481ea502630eaf2c4d1cdb776b165c05 Mon Sep 17 00:00:00 2001 From: Jeff Ames Date: Sat, 20 Feb 2010 11:01:50 +0900 Subject: Formatting cleanup. --- .../Voice/FreeSwitchVoice/FreeSwitchVoiceModule.cs | 123 +++++++++------------ .../SvnSerialiser/SvnBackupModule.cs | 10 +- 2 files changed, 59 insertions(+), 74 deletions(-) diff --git a/OpenSim/Region/OptionalModules/Avatar/Voice/FreeSwitchVoice/FreeSwitchVoiceModule.cs b/OpenSim/Region/OptionalModules/Avatar/Voice/FreeSwitchVoice/FreeSwitchVoiceModule.cs index b04b076..35819a6 100644 --- a/OpenSim/Region/OptionalModules/Avatar/Voice/FreeSwitchVoice/FreeSwitchVoiceModule.cs +++ b/OpenSim/Region/OptionalModules/Avatar/Voice/FreeSwitchVoice/FreeSwitchVoiceModule.cs @@ -50,7 +50,6 @@ using OpenSim.Region.Framework.Scenes; using Caps = OpenSim.Framework.Capabilities.Caps; using System.Text.RegularExpressions; - namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice { public class FreeSwitchVoiceModule : IRegionModule, IVoiceModule @@ -76,7 +75,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice // SLVoice client will do a GET on this prefix private static string m_freeSwitchAPIPrefix; - // We need to return some information to SLVoice + // We need to return some information to SLVoice // figured those out via curl // http://vd1.vivox.com/api2/viv_get_prelogin.php // @@ -102,9 +101,9 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice private readonly Dictionary m_UUIDName = new Dictionary(); private Dictionary m_ParcelAddress = new Dictionary(); - + private Scene m_scene; - + private IConfig m_config; @@ -136,9 +135,9 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice m_freeSwitchServerUser = m_config.GetString("freeswitch_server_user", String.Empty); m_freeSwitchServerPass = m_config.GetString("freeswitch_server_pass", String.Empty); m_freeSwitchAPIPrefix = m_config.GetString("freeswitch_api_prefix", String.Empty); - + // XXX: get IP address of HTTP server. (This can be this OpenSim server or another, or could be a dedicated grid service or may live on the freeswitch server) - + string serviceIP = m_config.GetString("freeswitch_service_server", String.Empty); int servicePort = m_config.GetInt("freeswitch_service_port", 80); IPAddress serviceIPAddress = IPAddress.Parse(serviceIP); @@ -156,7 +155,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice // m_freeSwitchSubscribeRetry = m_config.GetInt("freeswitch_subscribe_retry", 120); m_freeSwitchUrlResetPassword = m_config.GetString("freeswitch_password_reset_url", String.Empty); m_freeSwitchContext = m_config.GetString("freeswitch_context", "default"); - + if (String.IsNullOrEmpty(m_freeSwitchServerUser) || String.IsNullOrEmpty(m_freeSwitchServerPass) || String.IsNullOrEmpty(m_freeSwitchRealm) || @@ -182,9 +181,9 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice { MainServer.Instance.AddHTTPHandler(String.Format("{0}/viv_get_prelogin.php", m_freeSwitchAPIPrefix), FreeSwitchSLVoiceGetPreloginHTTPHandler); - + // RestStreamHandler h = new - // RestStreamHandler("GET", + // RestStreamHandler("GET", // String.Format("{0}/viv_get_prelogin.php", m_freeSwitchAPIPrefix), FreeSwitchSLVoiceGetPreloginHTTPHandler); // MainServer.Instance.AddStreamHandler(h); @@ -202,13 +201,9 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice MainServer.Instance.AddHTTPHandler(String.Format("{0}/viv_buddy.php", m_freeSwitchAPIPrefix), FreeSwitchSLVoiceBuddyHTTPHandler); } - - - - m_log.InfoFormat("[FreeSwitchVoice] using FreeSwitch server {0}", m_freeSwitchRealm); - + m_FreeSwitchDirectory = new FreeSwitchDirectory(); m_FreeSwitchDialplan = new FreeSwitchDialplan(); @@ -225,7 +220,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice } } - if (m_pluginEnabled) + if (m_pluginEnabled) { // we need to capture scene in an anonymous method // here as we need it later in the callbacks @@ -233,8 +228,6 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice { OnRegisterCaps(scene, agentID, caps); }; - - try { @@ -254,16 +247,15 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice m_log.Error("[FreeSwitchVoice]: Certificate validation handler change not supported. You may get ssl certificate validation errors teleporting from your region to some SSL regions."); } } - } } - + public void PostInitialise() { if (m_pluginEnabled) { m_log.Info("[FreeSwitchVoice] registering IVoiceModule with the scene"); - + // register the voice interface for this module, so the script engine can call us m_scene.RegisterModuleInterface(this); } @@ -282,15 +274,15 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice { get { return true; } } - + // // implementation of IVoiceModule, called by osSetParcelSIPAddress script function // public void setLandSIPAddress(string SIPAddress,UUID GlobalID) { - m_log.DebugFormat("[FreeSwitchVoice]: setLandSIPAddress parcel id {0}: setting sip address {1}", + m_log.DebugFormat("[FreeSwitchVoice]: setLandSIPAddress parcel id {0}: setting sip address {1}", GlobalID, SIPAddress); - + lock (m_ParcelAddress) { if (m_ParcelAddress.ContainsKey(GlobalID.ToString())) @@ -303,18 +295,18 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice } } } - + // // OnRegisterCaps is invoked via the scene.EventManager // everytime OpenSim hands out capabilities to a client // (login, region crossing). We contribute two capabilities to // the set of capabilities handed back to the client: // ProvisionVoiceAccountRequest and ParcelVoiceInfoRequest. - // + // // ProvisionVoiceAccountRequest allows the client to obtain // the voice account credentials for the avatar it is // controlling (e.g., user name, password, etc). - // + // // ParcelVoiceInfoRequest is invoked whenever the client // changes from one region or parcel to another. // @@ -371,7 +363,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice { System.Threading.Thread.Sleep(2000); avatar = scene.GetScenePresence(agentID); - + if (avatar == null) return "undef"; } @@ -407,8 +399,8 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice // new LLSDVoiceAccountResponse(agentname, password, m_freeSwitchRealm, "http://etsvc02.hursley.ibm.com/api"); LLSDVoiceAccountResponse voiceAccountResponse = new LLSDVoiceAccountResponse(agentname, password, m_freeSwitchRealm, - String.Format("http://{0}:{1}{2}/", m_openSimWellKnownHTTPAddress, - m_freeSwitchServicePort, m_freeSwitchAPIPrefix)); + String.Format("http://{0}:{1}{2}/", m_openSimWellKnownHTTPAddress, + m_freeSwitchServicePort, m_freeSwitchAPIPrefix)); string r = LLSDHelpers.SerialiseLLSDReply(voiceAccountResponse); @@ -442,7 +434,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice string avatarName = avatar.Name; // - check whether we have a region channel in our cache - // - if not: + // - if not: // create it and cache it // - send it to the client // - send channel_uri: as "sip:regionID@m_sipDomain" @@ -451,12 +443,10 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice LLSDParcelVoiceInfoResponse parcelVoiceInfo; string channelUri; - if (null == scene.LandChannel) + if (null == scene.LandChannel) throw new Exception(String.Format("region \"{0}\": avatar \"{1}\": land data not yet available", scene.RegionInfo.RegionName, avatarName)); - - // get channel_uri: check first whether estate // settings allow voice, then whether parcel allows // voice, if all do retrieve or obtain the parcel @@ -493,22 +483,21 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice parcelVoiceInfo = new LLSDParcelVoiceInfoResponse(scene.RegionInfo.RegionName, land.LocalID, creds); string r = LLSDHelpers.SerialiseLLSDReply(parcelVoiceInfo); - m_log.DebugFormat("[FreeSwitchVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": {4}", + m_log.DebugFormat("[FreeSwitchVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": {4}", scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName, r); return r; } catch (Exception e) { - m_log.ErrorFormat("[FreeSwitchVoice][PARCELVOICE]: region \"{0}\": avatar \"{1}\": {2}, retry later", + m_log.ErrorFormat("[FreeSwitchVoice][PARCELVOICE]: region \"{0}\": avatar \"{1}\": {2}, retry later", scene.RegionInfo.RegionName, avatarName, e.Message); - m_log.DebugFormat("[FreeSwitchVoice][PARCELVOICE]: region \"{0}\": avatar \"{1}\": {2} failed", + m_log.DebugFormat("[FreeSwitchVoice][PARCELVOICE]: region \"{0}\": avatar \"{1}\": {2} failed", scene.RegionInfo.RegionName, avatarName, e.ToString()); return "undef"; } } - /// /// Callback for a client request for ChatSessionRequest /// @@ -550,7 +539,6 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice string fwdresponsestr = ""; int fwdresponsecode = 200; string fwdresponsecontenttype = "text/xml"; - HttpWebRequest forwardreq = (HttpWebRequest)WebRequest.Create(forwardaddress); forwardreq.Method = method; @@ -577,7 +565,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice response["content_type"] = fwdresponsecontenttype; response["str_response_string"] = fwdresponsestr; response["int_response_code"] = fwdresponsecode; - + return response; } @@ -585,11 +573,11 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice public Hashtable FreeSwitchSLVoiceGetPreloginHTTPHandler(Hashtable request) { m_log.Debug("[FreeSwitchVoice] FreeSwitchSLVoiceGetPreloginHTTPHandler called"); - + Hashtable response = new Hashtable(); response["content_type"] = "text/xml"; response["keepalive"] = false; - + response["str_response_string"] = String.Format( "\r\n" + "\r\n"+ @@ -607,9 +595,9 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice "", m_freeSwitchRealm, m_freeSwitchSIPProxy, m_freeSwitchAttemptUseSTUN, m_freeSwitchEchoServer, m_freeSwitchEchoPort, - m_freeSwitchDefaultWellKnownIP, m_freeSwitchDefaultTimeout, + m_freeSwitchDefaultWellKnownIP, m_freeSwitchDefaultTimeout, m_freeSwitchUrlResetPassword, ""); - + response["int_response_code"] = 200; m_log.DebugFormat("[FreeSwitchVoice] FreeSwitchSLVoiceGetPreloginHTTPHandler return {0}",response["str_response_string"]); @@ -624,7 +612,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice response["content-type"] = "text/xml"; Hashtable requestBody = parseRequestBody((string)request["body"]); - + if (!requestBody.ContainsKey("auth_token")) return response; @@ -632,7 +620,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice //string[] auth_tokenvals = auth_token.Split(':'); //string username = auth_tokenvals[0]; int strcount = 0; - + string[] ids = new string[strcount]; int iter = -1; @@ -648,7 +636,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice } StringBuilder resp = new StringBuilder(); resp.Append(""); - + resp.Append(string.Format(@" OK lib_session @@ -678,7 +666,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice ", ids[i],i,m_freeSwitchRealm,dt)); } - + resp.Append(""); response["str_response_string"] = resp.ToString(); @@ -694,7 +682,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice string requestbody = (string)request["body"]; string uri = (string)request["uri"]; string contenttype = (string)request["content-type"]; - + Hashtable requestBody = parseRequestBody((string)request["body"]); //string pwd = (string) requestBody["pwd"]; @@ -712,7 +700,6 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice pos++; if (s == userid) break; - } } } @@ -735,7 +722,7 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice ", userid, pos, avatarName); - + response["int_response_code"] = 200; return response; /* @@ -752,13 +739,13 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice public Hashtable FreeSwitchConfigHTTPHandler(Hashtable request) { m_log.DebugFormat("[FreeSwitchVoice] FreeSwitchConfigHTTPHandler called with {0}", (string)request["body"]); - + Hashtable response = new Hashtable(); response["str_response_string"] = string.Empty; // all the params come as NVPs in the request body Hashtable requestBody = parseRequestBody((string) request["body"]); - // is this a dialplan or directory request + // is this a dialplan or directory request string section = (string) requestBody["section"]; if (section == "directory") @@ -767,40 +754,39 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice response = m_FreeSwitchDialplan.HandleDialplanRequest(m_freeSwitchContext, m_freeSwitchRealm, requestBody); else m_log.WarnFormat("[FreeSwitchVoice]: section was {0}", section); - - // XXX: re-generate dialplan: + + // XXX: re-generate dialplan: // - conf == region UUID // - conf number = region port // -> TODO Initialise(): keep track of regions via events - // re-generate accounts for all avatars + // re-generate accounts for all avatars // -> TODO Initialise(): keep track of avatars via events Regex normalizeEndLines = new Regex(@"\r\n", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.Multiline); m_log.DebugFormat("[FreeSwitchVoice] FreeSwitchConfigHTTPHandler return {0}",normalizeEndLines.Replace(((string)response["str_response_string"]), "")); return response; } - + public Hashtable parseRequestBody(string body) { Hashtable bodyParams = new Hashtable(); // split string string [] nvps = body.Split(new Char [] {'&'}); - foreach (string s in nvps) { - + foreach (string s in nvps) + { if (s.Trim() != "") { string [] nvp = s.Split(new Char [] {'='}); bodyParams.Add(HttpUtility.UrlDecode(nvp[0]), HttpUtility.UrlDecode(nvp[1])); } } - + return bodyParams; } private string ChannelUri(Scene scene, LandData land) { - string channelUri = null; string landUUID; @@ -808,12 +794,12 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice // Create parcel voice channel. If no parcel exists, then the voice channel ID is the same // as the directory ID. Otherwise, it reflects the parcel's ID. - + lock (m_ParcelAddress) { if (m_ParcelAddress.ContainsKey(land.GlobalID.ToString())) { - m_log.DebugFormat("[FreeSwitchVoice]: parcel id {0}: using sip address {1}", + m_log.DebugFormat("[FreeSwitchVoice]: parcel id {0}: using sip address {1}", land.GlobalID, m_ParcelAddress[land.GlobalID.ToString()]); return m_ParcelAddress[land.GlobalID.ToString()]; } @@ -823,22 +809,22 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice { landName = String.Format("{0}:{1}", scene.RegionInfo.RegionName, land.Name); landUUID = land.GlobalID.ToString(); - m_log.DebugFormat("[FreeSwitchVoice]: Region:Parcel \"{0}\": parcel id {1}: using channel name {2}", + m_log.DebugFormat("[FreeSwitchVoice]: Region:Parcel \"{0}\": parcel id {1}: using channel name {2}", landName, land.LocalID, landUUID); } else { landName = String.Format("{0}:{1}", scene.RegionInfo.RegionName, scene.RegionInfo.RegionName); landUUID = scene.RegionInfo.RegionID.ToString(); - m_log.DebugFormat("[FreeSwitchVoice]: Region:Parcel \"{0}\": parcel id {1}: using channel name {2}", + m_log.DebugFormat("[FreeSwitchVoice]: Region:Parcel \"{0}\": parcel id {1}: using channel name {2}", landName, land.LocalID, landUUID); } System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); - + // slvoice handles the sip address differently if it begins with confctl, hiding it from the user in the friends list. however it also disables // the personal speech indicators as well unless some siren14-3d codec magic happens. we dont have siren143d so we'll settle for the personal speech indicator. channelUri = String.Format("sip:conf-{0}@{1}", "x" + Convert.ToBase64String(encoding.GetBytes(landUUID)), m_freeSwitchRealm); - + lock (m_ParcelAddress) { if (!m_ParcelAddress.ContainsKey(land.GlobalID.ToString())) @@ -849,14 +835,13 @@ namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice return channelUri; } - + private static bool CustomCertificateValidation(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error) { - return true; - } } + public class MonoCert : ICertificatePolicy { #region ICertificatePolicy Members diff --git a/OpenSim/Region/OptionalModules/SvnSerialiser/SvnBackupModule.cs b/OpenSim/Region/OptionalModules/SvnSerialiser/SvnBackupModule.cs index 3490a8b..ccdea14 100644 --- a/OpenSim/Region/OptionalModules/SvnSerialiser/SvnBackupModule.cs +++ b/OpenSim/Region/OptionalModules/SvnSerialiser/SvnBackupModule.cs @@ -121,19 +121,19 @@ namespace OpenSim.Region.Modules.SvnSerialiser { serialiser.LoadPrimsFromXml2( scene, - m_svndir + Slash.DirectorySeparatorChar + scene.RegionInfo.RegionID + m_svndir + Slash.DirectorySeparatorChar + scene.RegionInfo.RegionID + Slash.DirectorySeparatorChar + "objects.xml"); - + scene.RequestModuleInterface().LoadFromFile( - m_svndir + Slash.DirectorySeparatorChar + scene.RegionInfo.RegionID + m_svndir + Slash.DirectorySeparatorChar + scene.RegionInfo.RegionID + Slash.DirectorySeparatorChar + "heightmap.r32"); - + m_log.Info("[SVNBACKUP]: Region load successful (" + scene.RegionInfo.RegionName + ")."); } else { m_log.ErrorFormat( - "[SVNBACKUP]: Region load of {0} failed - no serialisation module available", + "[SVNBACKUP]: Region load of {0} failed - no serialisation module available", scene.RegionInfo.RegionName); } } -- cgit v1.1 From 0ab6aac05255078a9d190f6623b2d86d5253d955 Mon Sep 17 00:00:00 2001 From: Diva Canto Date: Sat, 20 Feb 2010 17:52:38 -0800 Subject: Added UserAccountData and auth to the SQLite connector. Compiles, runs, but access to these tables doesn't work. --- OpenSim/Data/SQLite/Resources/001_AuthStore.sql | 18 ++ OpenSim/Data/SQLite/Resources/001_UserAccount.sql | 17 ++ OpenSim/Data/SQLite/Resources/002_AuthStore.sql | 5 + OpenSim/Data/SQLite/Resources/002_UserAccount.sql | 5 + OpenSim/Data/SQLite/SQLiteAuthenticationData.cs | 214 ++++++++++++++++++++++ OpenSim/Data/SQLite/SQLiteFramework.cs | 11 +- OpenSim/Data/SQLite/SQLiteGenericTableHandler.cs | 15 +- OpenSim/Data/SQLite/SQLiteUserAccountData.cs | 81 ++++++++ OpenSim/Services/Base/ServiceBase.cs | 5 +- bin/config-include/Standalone.ini | 8 +- bin/config-include/StandaloneHypergrid.ini | 8 +- 11 files changed, 372 insertions(+), 15 deletions(-) create mode 100644 OpenSim/Data/SQLite/Resources/001_AuthStore.sql create mode 100644 OpenSim/Data/SQLite/Resources/001_UserAccount.sql create mode 100644 OpenSim/Data/SQLite/Resources/002_AuthStore.sql create mode 100644 OpenSim/Data/SQLite/Resources/002_UserAccount.sql create mode 100644 OpenSim/Data/SQLite/SQLiteAuthenticationData.cs create mode 100644 OpenSim/Data/SQLite/SQLiteUserAccountData.cs diff --git a/OpenSim/Data/SQLite/Resources/001_AuthStore.sql b/OpenSim/Data/SQLite/Resources/001_AuthStore.sql new file mode 100644 index 0000000..468567d --- /dev/null +++ b/OpenSim/Data/SQLite/Resources/001_AuthStore.sql @@ -0,0 +1,18 @@ +BEGIN TRANSACTION; + +CREATE TABLE auth ( + UUID char(36) NOT NULL, + passwordHash char(32) NOT NULL default '', + passwordSalt char(32) NOT NULL default '', + webLoginKey varchar(255) NOT NULL default '', + accountType VARCHAR(32) NOT NULL DEFAULT 'UserAccount', + PRIMARY KEY (`UUID`) +); + +CREATE TABLE tokens ( + UUID char(36) NOT NULL, + token varchar(255) NOT NULL, + validity datetime NOT NULL +); + +COMMIT; diff --git a/OpenSim/Data/SQLite/Resources/001_UserAccount.sql b/OpenSim/Data/SQLite/Resources/001_UserAccount.sql new file mode 100644 index 0000000..f9bf24c --- /dev/null +++ b/OpenSim/Data/SQLite/Resources/001_UserAccount.sql @@ -0,0 +1,17 @@ +BEGIN TRANSACTION; + +-- useraccounts table +CREATE TABLE UserAccounts ( + PrincipalID CHAR(36) NOT NULL, + ScopeID CHAR(36) NOT NULL, + FirstName VARCHAR(64) NOT NULL, + LastName VARCHAR(64) NOT NULL, + Email VARCHAR(64), + ServiceURLs TEXT, + Created INT(11), + UserLevel integer NOT NULL DEFAULT 0, + UserFlags integer NOT NULL DEFAULT 0, + UserTitle varchar(64) NOT NULL DEFAULT '' +); + +COMMIT; \ No newline at end of file diff --git a/OpenSim/Data/SQLite/Resources/002_AuthStore.sql b/OpenSim/Data/SQLite/Resources/002_AuthStore.sql new file mode 100644 index 0000000..3237b68 --- /dev/null +++ b/OpenSim/Data/SQLite/Resources/002_AuthStore.sql @@ -0,0 +1,5 @@ +BEGIN TRANSACTION; + +INSERT INTO auth (UUID, passwordHash, passwordSalt, webLoginKey) SELECT `UUID` AS UUID, `passwordHash` AS passwordHash, `passwordSalt` AS passwordSalt, `webLoginKey` AS webLoginKey FROM users; + +COMMIT; diff --git a/OpenSim/Data/SQLite/Resources/002_UserAccount.sql b/OpenSim/Data/SQLite/Resources/002_UserAccount.sql new file mode 100644 index 0000000..c0b3d7b --- /dev/null +++ b/OpenSim/Data/SQLite/Resources/002_UserAccount.sql @@ -0,0 +1,5 @@ +BEGIN TRANSACTION; + +INSERT INTO UserAccounts (PrincipalID, ScopeID, FirstName, LastName, Email, ServiceURLs, Created) SELECT `UUID` AS PrincipalID, '00000000-0000-0000-0000-000000000000' AS ScopeID, username AS FirstName, lastname AS LastName, email as Email, CONCAT('AssetServerURI=', userAssetURI, ' InventoryServerURI=', userInventoryURI, ' GatewayURI= HomeURI=') AS ServiceURLs, created as Created FROM users; + +COMMIT; diff --git a/OpenSim/Data/SQLite/SQLiteAuthenticationData.cs b/OpenSim/Data/SQLite/SQLiteAuthenticationData.cs new file mode 100644 index 0000000..271ed47 --- /dev/null +++ b/OpenSim/Data/SQLite/SQLiteAuthenticationData.cs @@ -0,0 +1,214 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using OpenMetaverse; +using OpenSim.Framework; +using Mono.Data.SqliteClient; + +namespace OpenSim.Data.SQLite +{ + public class SQLiteAuthenticationData : SQLiteFramework, IAuthenticationData + { + private string m_Realm; + private List m_ColumnNames; + private int m_LastExpire; + private string m_connectionString; + + private static bool m_initialized = false; + + public SQLiteAuthenticationData(string connectionString, string realm) + : base(connectionString) + { + m_Realm = realm; + m_connectionString = connectionString; + + if (!m_initialized) + { + using (SqliteConnection dbcon = new SqliteConnection(m_connectionString)) + { + dbcon.Open(); + Migration m = new Migration(dbcon, GetType().Assembly, "AuthStore"); + m.Update(); + } + m_initialized = true; + } + } + + public AuthenticationData Get(UUID principalID) + { + AuthenticationData ret = new AuthenticationData(); + ret.Data = new Dictionary(); + + using (SqliteConnection dbcon = new SqliteConnection(m_connectionString)) + { + dbcon.Open(); + SqliteCommand cmd = new SqliteCommand("select * from `" + m_Realm + "` where UUID = '" + principalID.ToString() + "'", dbcon); + + IDataReader result = cmd.ExecuteReader(); + + if (result.Read()) + { + ret.PrincipalID = principalID; + + if (m_ColumnNames == null) + { + m_ColumnNames = new List(); + + DataTable schemaTable = result.GetSchemaTable(); + foreach (DataRow row in schemaTable.Rows) + m_ColumnNames.Add(row["ColumnName"].ToString()); + } + + foreach (string s in m_ColumnNames) + { + if (s == "UUID") + continue; + + ret.Data[s] = result[s].ToString(); + } + + return ret; + } + else + { + return null; + } + } + } + + public bool Store(AuthenticationData data) + { + if (data.Data.ContainsKey("UUID")) + data.Data.Remove("UUID"); + + string[] fields = new List(data.Data.Keys).ToArray(); + string[] values = new string[data.Data.Count]; + int i = 0; + foreach (object o in data.Data.Values) + values[i++] = o.ToString(); + + SqliteCommand cmd = new SqliteCommand(); + + string update = "update `"+m_Realm+"` set "; + bool first = true; + foreach (string field in fields) + { + if (!first) + update += ", "; + update += "`" + field + "` = " + data.Data[field]; + + first = false; + + } + + update += " where UUID = '" + data.PrincipalID.ToString() + "'"; + + cmd.CommandText = update; + + if (ExecuteNonQuery(cmd) < 1) + { + string insert = "insert into `" + m_Realm + "` (`UUID`, `" + + String.Join("`, `", fields) + + "`) values ('" + data.PrincipalID.ToString() + "', " + String.Join(", '", values) + "')"; + + cmd.CommandText = insert; + + if (ExecuteNonQuery(cmd) < 1) + { + cmd.Dispose(); + return false; + } + } + + cmd.Dispose(); + + return true; + } + + public bool SetDataItem(UUID principalID, string item, string value) + { + SqliteCommand cmd = new SqliteCommand("update `" + m_Realm + + "` set `" + item + "` = " + value + " where UUID = '" + principalID.ToString() + "'"); + + if (ExecuteNonQuery(cmd) > 0) + return true; + + return false; + } + + public bool SetToken(UUID principalID, string token, int lifetime) + { + if (System.Environment.TickCount - m_LastExpire > 30000) + DoExpire(); + + SqliteCommand cmd = new SqliteCommand("insert into tokens (UUID, token, validity) values ('" + principalID.ToString() + + "', '" + token + "', datetime('now, 'localtime', '+" + lifetime.ToString() + " minutes'))"); + + if (ExecuteNonQuery(cmd) > 0) + { + cmd.Dispose(); + return true; + } + + cmd.Dispose(); + return false; + } + + public bool CheckToken(UUID principalID, string token, int lifetime) + { + if (System.Environment.TickCount - m_LastExpire > 30000) + DoExpire(); + + SqliteCommand cmd = new SqliteCommand("update tokens set validity = datetime('now, 'localtime', '+" + lifetime.ToString() + + " minutes') where UUID = '" + principalID.ToString() + "' and token = '" + token + "' and validity > datetime('now', 'localtime')"); + + if (ExecuteNonQuery(cmd) > 0) + { + cmd.Dispose(); + return true; + } + + cmd.Dispose(); + + return false; + } + + private void DoExpire() + { + SqliteCommand cmd = new SqliteCommand("delete from tokens where validity < datetime('now, 'localtime')"); + ExecuteNonQuery(cmd); + + cmd.Dispose(); + + m_LastExpire = System.Environment.TickCount; + } + } +} diff --git a/OpenSim/Data/SQLite/SQLiteFramework.cs b/OpenSim/Data/SQLite/SQLiteFramework.cs index 12b2750..d745c92 100644 --- a/OpenSim/Data/SQLite/SQLiteFramework.cs +++ b/OpenSim/Data/SQLite/SQLiteFramework.cs @@ -40,12 +40,17 @@ namespace OpenSim.Data.SQLite /// public class SQLiteFramework { - protected SqliteConnection m_Connection; + protected static SqliteConnection m_Connection; + private bool m_initialized; protected SQLiteFramework(string connectionString) { - m_Connection = new SqliteConnection(connectionString); - m_Connection.Open(); + if (!m_initialized) + { + m_Connection = new SqliteConnection(connectionString); + m_Connection.Open(); + m_initialized = true; + } } ////////////////////////////////////////////////////////////// diff --git a/OpenSim/Data/SQLite/SQLiteGenericTableHandler.cs b/OpenSim/Data/SQLite/SQLiteGenericTableHandler.cs index 8e91693..d29efa0 100644 --- a/OpenSim/Data/SQLite/SQLiteGenericTableHandler.cs +++ b/OpenSim/Data/SQLite/SQLiteGenericTableHandler.cs @@ -48,16 +48,23 @@ namespace OpenSim.Data.SQLite protected string m_Realm; protected FieldInfo m_DataField = null; + private static bool m_initialized; + public SQLiteGenericTableHandler(string connectionString, string realm, string storeName) : base(connectionString) { m_Realm = realm; - if (storeName != String.Empty) + + if (!m_initialized) { - Assembly assem = GetType().Assembly; + if (storeName != String.Empty) + { + Assembly assem = GetType().Assembly; - Migration m = new Migration(m_Connection, assem, storeName); - m.Update(); + Migration m = new Migration(m_Connection, assem, storeName); + m.Update(); + } + m_initialized = true; } Type t = typeof(T); diff --git a/OpenSim/Data/SQLite/SQLiteUserAccountData.cs b/OpenSim/Data/SQLite/SQLiteUserAccountData.cs new file mode 100644 index 0000000..50e8c23 --- /dev/null +++ b/OpenSim/Data/SQLite/SQLiteUserAccountData.cs @@ -0,0 +1,81 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using OpenMetaverse; +using OpenSim.Framework; +using Mono.Data.SqliteClient; + +namespace OpenSim.Data.SQLite +{ + public class SQLiteUserAccountData : SQLiteGenericTableHandler, IUserAccountData + { + public SQLiteUserAccountData(string connectionString, string realm) + : base(connectionString, realm, "UserAccount") + { + } + + public UserAccountData[] GetUsers(UUID scopeID, string query) + { + string[] words = query.Split(new char[] {' '}); + + for (int i = 0 ; i < words.Length ; i++) + { + if (words[i].Length < 3) + { + if (i != words.Length - 1) + Array.Copy(words, i + 1, words, i, words.Length - i - 1); + Array.Resize(ref words, words.Length - 1); + } + } + + if (words.Length == 0) + return new UserAccountData[0]; + + if (words.Length > 2) + return new UserAccountData[0]; + + SqliteCommand cmd = new SqliteCommand(); + + if (words.Length == 1) + { + cmd.CommandText = String.Format("select * from {0} where ScopeID='{1}' or ScopeID='00000000-0000-0000-0000-000000000000') and (FirstName like '{2}%' or LastName like '{2}%')", + m_Realm, scopeID.ToString(), words[0]); + } + else + { + cmd.CommandText = String.Format("select * from {0} where (ScopeID='{1}' or ScopeID='00000000-0000-0000-0000-000000000000') and (FirstName like '{2}%' or LastName like '{3}%')", + m_Realm, scopeID.ToString(), words[0], words[1]); + } + + return DoQuery(cmd); + } + } +} diff --git a/OpenSim/Services/Base/ServiceBase.cs b/OpenSim/Services/Base/ServiceBase.cs index 6bbe978..8e24d85 100644 --- a/OpenSim/Services/Base/ServiceBase.cs +++ b/OpenSim/Services/Base/ServiceBase.cs @@ -64,7 +64,7 @@ namespace OpenSim.Services.Base foreach (Type pluginType in pluginAssembly.GetTypes()) { if (pluginType.IsPublic) - { + { if (className != String.Empty && pluginType.ToString() != pluginType.Namespace + "." + className) @@ -84,8 +84,9 @@ namespace OpenSim.Services.Base return null; } - catch (Exception) + catch (Exception e) { + Console.WriteLine("XXX Exception " + e.StackTrace); return null; } } diff --git a/bin/config-include/Standalone.ini b/bin/config-include/Standalone.ini index bd90df4..b9a9462 100644 --- a/bin/config-include/Standalone.ini +++ b/bin/config-include/Standalone.ini @@ -4,9 +4,6 @@ ;; which you can copy and change. ;; -[Includes] - Include-Common = "config-include/StandaloneCommon.ini" - [Modules] AssetServices = "LocalAssetServicesConnector" InventoryServices = "LocalInventoryServicesConnector" @@ -72,3 +69,8 @@ AvatarService = "OpenSim.Services.AvatarService.dll:AvatarService" WelcomeMessage = "Welcome, Avatar!" + + +;; This should always be the very last thing on this file +[Includes] + Include-Common = "config-include/StandaloneCommon.ini" diff --git a/bin/config-include/StandaloneHypergrid.ini b/bin/config-include/StandaloneHypergrid.ini index a4fa5be..9ad6d1c 100644 --- a/bin/config-include/StandaloneHypergrid.ini +++ b/bin/config-include/StandaloneHypergrid.ini @@ -3,9 +3,6 @@ ;; All optional settings are in StandaloneCommon.ini.example, ;; which you can copy and change. ;; - -[Includes] - Include-Common = "config-include/StandaloneCommon.ini" [Modules] AssetServices = "HGAssetBroker" @@ -112,3 +109,8 @@ [HGInventoryService] ; For the InventoryServiceInConnector LocalServiceModule = "OpenSim.Services.InventoryService.dll:HGInventoryService" + + +;; This should always be the very last thing on this file +[Includes] + Include-Common = "config-include/StandaloneCommon.ini" -- cgit v1.1 From df59d098b319367394bdeb898d7fd7dacd7104ec Mon Sep 17 00:00:00 2001 From: Diva Canto Date: Sat, 20 Feb 2010 20:13:38 -0800 Subject: SQLite connector better, but access to tables still doesn't work. --- OpenSim/Data/SQLite/SQLiteAuthenticationData.cs | 61 +++++++++++++++++----- OpenSim/Data/SQLite/SQLiteFramework.cs | 13 ++--- OpenSim/Data/SQLite/SQLiteGenericTableHandler.cs | 16 +++--- .../AuthenticationServiceBase.cs | 13 +++-- 4 files changed, 71 insertions(+), 32 deletions(-) diff --git a/OpenSim/Data/SQLite/SQLiteAuthenticationData.cs b/OpenSim/Data/SQLite/SQLiteAuthenticationData.cs index 271ed47..7dab6bf 100644 --- a/OpenSim/Data/SQLite/SQLiteAuthenticationData.cs +++ b/OpenSim/Data/SQLite/SQLiteAuthenticationData.cs @@ -52,12 +52,16 @@ namespace OpenSim.Data.SQLite if (!m_initialized) { + m_Connection = new SqliteConnection(connectionString); + m_Connection.Open(); + using (SqliteConnection dbcon = new SqliteConnection(m_connectionString)) { dbcon.Open(); Migration m = new Migration(dbcon, GetType().Assembly, "AuthStore"); m.Update(); } + m_initialized = true; } } @@ -105,7 +109,7 @@ namespace OpenSim.Data.SQLite } public bool Store(AuthenticationData data) - { + { if (data.Data.ContainsKey("UUID")) data.Data.Remove("UUID"); @@ -117,31 +121,60 @@ namespace OpenSim.Data.SQLite SqliteCommand cmd = new SqliteCommand(); - string update = "update `"+m_Realm+"` set "; - bool first = true; - foreach (string field in fields) + if (Get(data.PrincipalID) != null) { - if (!first) - update += ", "; - update += "`" + field + "` = " + data.Data[field]; - first = false; - } + string update = "update `" + m_Realm + "` set "; + bool first = true; + foreach (string field in fields) + { + if (!first) + update += ", "; + update += "`" + field + "` = '" + data.Data[field] + "'"; - update += " where UUID = '" + data.PrincipalID.ToString() + "'"; + first = false; - cmd.CommandText = update; + } + + update += " where UUID = '" + data.PrincipalID.ToString() + "'"; + + cmd.CommandText = update; + Console.WriteLine("XXX " + cmd.CommandText); + try + { + if (ExecuteNonQuery(cmd) < 1) + { + cmd.Dispose(); + return false; + } + } + catch + { + cmd.Dispose(); + return false; + } + } - if (ExecuteNonQuery(cmd) < 1) + else { string insert = "insert into `" + m_Realm + "` (`UUID`, `" + String.Join("`, `", fields) + - "`) values ('" + data.PrincipalID.ToString() + "', " + String.Join(", '", values) + "')"; + "`) values ('" + data.PrincipalID.ToString() + "', '" + String.Join("', '", values) + "')"; cmd.CommandText = insert; - if (ExecuteNonQuery(cmd) < 1) + Console.WriteLine("XXX " + cmd.CommandText); + + try + { + if (ExecuteNonQuery(cmd) < 1) + { + cmd.Dispose(); + return false; + } + } + catch { cmd.Dispose(); return false; diff --git a/OpenSim/Data/SQLite/SQLiteFramework.cs b/OpenSim/Data/SQLite/SQLiteFramework.cs index d745c92..2a8a022 100644 --- a/OpenSim/Data/SQLite/SQLiteFramework.cs +++ b/OpenSim/Data/SQLite/SQLiteFramework.cs @@ -40,17 +40,12 @@ namespace OpenSim.Data.SQLite /// public class SQLiteFramework { - protected static SqliteConnection m_Connection; - private bool m_initialized; + protected SqliteConnection m_Connection; protected SQLiteFramework(string connectionString) { - if (!m_initialized) - { - m_Connection = new SqliteConnection(connectionString); - m_Connection.Open(); - m_initialized = true; - } + //m_Connection = new SqliteConnection(connectionString); + //m_Connection.Open(); } ////////////////////////////////////////////////////////////// @@ -63,6 +58,7 @@ namespace OpenSim.Data.SQLite lock (m_Connection) { cmd.Connection = m_Connection; + Console.WriteLine("XXX " + cmd.CommandText); return cmd.ExecuteNonQuery(); } @@ -75,6 +71,7 @@ namespace OpenSim.Data.SQLite newConnection.Open(); cmd.Connection = newConnection; + Console.WriteLine("XXX " + cmd.CommandText); return cmd.ExecuteReader(); } diff --git a/OpenSim/Data/SQLite/SQLiteGenericTableHandler.cs b/OpenSim/Data/SQLite/SQLiteGenericTableHandler.cs index d29efa0..98943a0 100644 --- a/OpenSim/Data/SQLite/SQLiteGenericTableHandler.cs +++ b/OpenSim/Data/SQLite/SQLiteGenericTableHandler.cs @@ -57,6 +57,9 @@ namespace OpenSim.Data.SQLite if (!m_initialized) { + m_Connection = new SqliteConnection(connectionString); + m_Connection.Open(); + if (storeName != String.Empty) { Assembly assem = GetType().Assembly; @@ -64,6 +67,7 @@ namespace OpenSim.Data.SQLite Migration m = new Migration(m_Connection, assem, storeName); m.Update(); } + m_initialized = true; } @@ -117,7 +121,7 @@ namespace OpenSim.Data.SQLite for (int i = 0 ; i < fields.Length ; i++) { cmd.Parameters.Add(new SqliteParameter(":" + fields[i], keys[i])); - terms.Add("`" + fields[i] + "` = :" + fields[i]); + terms.Add("`" + fields[i] + "`='" + keys[i] + "'"); } string where = String.Join(" and ", terms.ToArray()); @@ -215,8 +219,8 @@ namespace OpenSim.Data.SQLite foreach (FieldInfo fi in m_Fields.Values) { names.Add(fi.Name); - values.Add(":" + fi.Name); - cmd.Parameters.Add(new SqliteParameter(":" + fi.Name, fi.GetValue(row).ToString())); + values.Add(fi.GetValue(row).ToString()); + cmd.Parameters.Add(new SqliteParameter(fi.Name, fi.GetValue(row).ToString())); } if (m_DataField != null) @@ -227,12 +231,12 @@ namespace OpenSim.Data.SQLite foreach (KeyValuePair kvp in data) { names.Add(kvp.Key); - values.Add(":" + kvp.Key); - cmd.Parameters.Add(new SqliteParameter(":" + kvp.Key, kvp.Value)); + values.Add(kvp.Value); + cmd.Parameters.Add(new SqliteParameter(kvp.Key, kvp.Value)); } } - query = String.Format("replace into {0} (`", m_Realm) + String.Join("`,`", names.ToArray()) + "`) values (" + String.Join(",", values.ToArray()) + ")"; + query = String.Format("replace into {0} (`", m_Realm) + String.Join("`,`", names.ToArray()) + "`) values ('" + String.Join("', '", values.ToArray()) + "')"; cmd.CommandText = query; diff --git a/OpenSim/Services/AuthenticationService/AuthenticationServiceBase.cs b/OpenSim/Services/AuthenticationService/AuthenticationServiceBase.cs index f6dd085..9af61a9 100644 --- a/OpenSim/Services/AuthenticationService/AuthenticationServiceBase.cs +++ b/OpenSim/Services/AuthenticationService/AuthenticationServiceBase.cs @@ -106,12 +106,17 @@ namespace OpenSim.Services.AuthenticationService string passwordSalt = Util.Md5Hash(UUID.Random().ToString()); string md5PasswdHash = Util.Md5Hash(Util.Md5Hash(password) + ":" + passwordSalt); - AuthenticationData auth = new AuthenticationData(); - auth.PrincipalID = principalID; - auth.Data = new System.Collections.Generic.Dictionary(); + AuthenticationData auth = m_Database.Get(principalID); + if (auth == null) + { + auth = new AuthenticationData(); + auth.PrincipalID = principalID; + auth.Data = new System.Collections.Generic.Dictionary(); + auth.Data["accountType"] = "UserAccount"; + auth.Data["webLoginKey"] = UUID.Zero.ToString(); + } auth.Data["passwordHash"] = md5PasswdHash; auth.Data["passwordSalt"] = passwordSalt; - auth.Data["webLoginKey"] = UUID.Zero.ToString(); if (!m_Database.Store(auth)) { m_log.DebugFormat("[AUTHENTICATION DB]: Failed to store authentication data"); -- cgit v1.1 From 611eeb583c2e8c7a750201bc10c535410e74330f Mon Sep 17 00:00:00 2001 From: Diva Canto Date: Sat, 20 Feb 2010 20:59:04 -0800 Subject: Reverted SQLite/SQLiteGenericTableHandler to what it was + singleton. --- OpenSim/Data/SQLite/SQLiteGenericTableHandler.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/OpenSim/Data/SQLite/SQLiteGenericTableHandler.cs b/OpenSim/Data/SQLite/SQLiteGenericTableHandler.cs index 98943a0..e7e158d 100644 --- a/OpenSim/Data/SQLite/SQLiteGenericTableHandler.cs +++ b/OpenSim/Data/SQLite/SQLiteGenericTableHandler.cs @@ -121,7 +121,7 @@ namespace OpenSim.Data.SQLite for (int i = 0 ; i < fields.Length ; i++) { cmd.Parameters.Add(new SqliteParameter(":" + fields[i], keys[i])); - terms.Add("`" + fields[i] + "`='" + keys[i] + "'"); + terms.Add("`" + fields[i] + "` = :" + fields[i]); } string where = String.Join(" and ", terms.ToArray()); @@ -219,8 +219,8 @@ namespace OpenSim.Data.SQLite foreach (FieldInfo fi in m_Fields.Values) { names.Add(fi.Name); - values.Add(fi.GetValue(row).ToString()); - cmd.Parameters.Add(new SqliteParameter(fi.Name, fi.GetValue(row).ToString())); + values.Add(":" + fi.Name); + cmd.Parameters.Add(new SqliteParameter(":" + fi.Name, fi.GetValue(row).ToString())); } if (m_DataField != null) @@ -231,12 +231,12 @@ namespace OpenSim.Data.SQLite foreach (KeyValuePair kvp in data) { names.Add(kvp.Key); - values.Add(kvp.Value); - cmd.Parameters.Add(new SqliteParameter(kvp.Key, kvp.Value)); + values.Add(":" + kvp.Key); + cmd.Parameters.Add(new SqliteParameter(":" + kvp.Key, kvp.Value)); } } - query = String.Format("replace into {0} (`", m_Realm) + String.Join("`,`", names.ToArray()) + "`) values ('" + String.Join("', '", values.ToArray()) + "')"; + query = String.Format("replace into {0} (`", m_Realm) + String.Join("`,`", names.ToArray()) + "`) values (" + String.Join(",", values.ToArray()) + ")"; cmd.CommandText = query; -- cgit v1.1 From d761d1624b28a9ab3b006b3a3a94f4b805550f8c Mon Sep 17 00:00:00 2001 From: Melanie Date: Sun, 21 Feb 2010 04:20:22 +0000 Subject: Fix SQLite locking and make it more fascist for now --- OpenSim/Data/SQLite/SQLiteFramework.cs | 36 +++++++++++++++++++++------------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/OpenSim/Data/SQLite/SQLiteFramework.cs b/OpenSim/Data/SQLite/SQLiteFramework.cs index 2a8a022..96764f3 100644 --- a/OpenSim/Data/SQLite/SQLiteFramework.cs +++ b/OpenSim/Data/SQLite/SQLiteFramework.cs @@ -40,12 +40,10 @@ namespace OpenSim.Data.SQLite /// public class SQLiteFramework { - protected SqliteConnection m_Connection; + protected Object m_lockObject = new Object(); protected SQLiteFramework(string connectionString) { - //m_Connection = new SqliteConnection(connectionString); - //m_Connection.Open(); } ////////////////////////////////////////////////////////////// @@ -55,9 +53,13 @@ namespace OpenSim.Data.SQLite // protected int ExecuteNonQuery(SqliteCommand cmd) { - lock (m_Connection) + lock (m_lockObject) { - cmd.Connection = m_Connection; + SqliteConnection newConnection = + (SqliteConnection)((ICloneable)m_Connection).Clone(); + newConnection.Open(); + + cmd.Connection = newConnection; Console.WriteLine("XXX " + cmd.CommandText); return cmd.ExecuteNonQuery(); @@ -66,20 +68,26 @@ namespace OpenSim.Data.SQLite protected IDataReader ExecuteReader(SqliteCommand cmd) { - SqliteConnection newConnection = - (SqliteConnection)((ICloneable)m_Connection).Clone(); - newConnection.Open(); + lock (m_lockObject) + { + SqliteConnection newConnection = + (SqliteConnection)((ICloneable)m_Connection).Clone(); + newConnection.Open(); - cmd.Connection = newConnection; - Console.WriteLine("XXX " + cmd.CommandText); - return cmd.ExecuteReader(); + cmd.Connection = newConnection; + Console.WriteLine("XXX " + cmd.CommandText); + return cmd.ExecuteReader(); + } } protected void CloseReaderCommand(SqliteCommand cmd) { - cmd.Connection.Close(); - cmd.Connection.Dispose(); - cmd.Dispose(); + lock (m_lockObject) + { + cmd.Connection.Close(); + cmd.Connection.Dispose(); + cmd.Dispose(); + } } } } -- cgit v1.1 From 56fb7821ad021879d005da5ba65901c29c10de7f Mon Sep 17 00:00:00 2001 From: Diva Canto Date: Sat, 20 Feb 2010 21:24:18 -0800 Subject: Restored mising m_Connection. --- OpenSim/Data/SQLite/SQLiteAuthenticationData.cs | 10 ++++++---- OpenSim/Data/SQLite/SQLiteFramework.cs | 1 + 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/OpenSim/Data/SQLite/SQLiteAuthenticationData.cs b/OpenSim/Data/SQLite/SQLiteAuthenticationData.cs index 7dab6bf..d71c7eb 100644 --- a/OpenSim/Data/SQLite/SQLiteAuthenticationData.cs +++ b/OpenSim/Data/SQLite/SQLiteAuthenticationData.cs @@ -57,8 +57,8 @@ namespace OpenSim.Data.SQLite using (SqliteConnection dbcon = new SqliteConnection(m_connectionString)) { - dbcon.Open(); - Migration m = new Migration(dbcon, GetType().Assembly, "AuthStore"); + //dbcon.Open(); + Migration m = new Migration(m_Connection, GetType().Assembly, "AuthStore"); m.Update(); } @@ -149,8 +149,9 @@ namespace OpenSim.Data.SQLite return false; } } - catch + catch (Exception e) { + Console.WriteLine(e.ToString()); cmd.Dispose(); return false; } @@ -174,8 +175,9 @@ namespace OpenSim.Data.SQLite return false; } } - catch + catch (Exception e) { + Console.WriteLine(e.ToString()); cmd.Dispose(); return false; } diff --git a/OpenSim/Data/SQLite/SQLiteFramework.cs b/OpenSim/Data/SQLite/SQLiteFramework.cs index 96764f3..54b104b 100644 --- a/OpenSim/Data/SQLite/SQLiteFramework.cs +++ b/OpenSim/Data/SQLite/SQLiteFramework.cs @@ -42,6 +42,7 @@ namespace OpenSim.Data.SQLite { protected Object m_lockObject = new Object(); + protected static SqliteConnection m_Connection; protected SQLiteFramework(string connectionString) { } -- cgit v1.1 From 8a4947f8c75a2dbcd8c13dbff9ad2eff52711f0e Mon Sep 17 00:00:00 2001 From: Diva Canto Date: Sun, 21 Feb 2010 08:47:24 -0800 Subject: SQLite connector for UserAccounts and Auth works. Yey! --- OpenSim/Data/SQLite/SQLiteAuthenticationData.cs | 69 ++++++++++++++---------- OpenSim/Data/SQLite/SQLiteFramework.cs | 31 +++++------ OpenSim/Data/SQLite/SQLiteGenericTableHandler.cs | 16 ++++-- OpenSim/Data/SQLite/SQLiteXInventoryData.cs | 6 +-- 4 files changed, 69 insertions(+), 53 deletions(-) diff --git a/OpenSim/Data/SQLite/SQLiteAuthenticationData.cs b/OpenSim/Data/SQLite/SQLiteAuthenticationData.cs index d71c7eb..84ce775 100644 --- a/OpenSim/Data/SQLite/SQLiteAuthenticationData.cs +++ b/OpenSim/Data/SQLite/SQLiteAuthenticationData.cs @@ -42,6 +42,7 @@ namespace OpenSim.Data.SQLite private int m_LastExpire; private string m_connectionString; + protected static SqliteConnection m_Connection; private static bool m_initialized = false; public SQLiteAuthenticationData(string connectionString, string realm) @@ -55,11 +56,12 @@ namespace OpenSim.Data.SQLite m_Connection = new SqliteConnection(connectionString); m_Connection.Open(); - using (SqliteConnection dbcon = new SqliteConnection(m_connectionString)) + using (SqliteConnection dbcon = (SqliteConnection)((ICloneable)m_Connection).Clone()) { - //dbcon.Open(); - Migration m = new Migration(m_Connection, GetType().Assembly, "AuthStore"); + dbcon.Open(); + Migration m = new Migration(dbcon, GetType().Assembly, "AuthStore"); m.Update(); + dbcon.Close(); } m_initialized = true; @@ -71,13 +73,13 @@ namespace OpenSim.Data.SQLite AuthenticationData ret = new AuthenticationData(); ret.Data = new Dictionary(); - using (SqliteConnection dbcon = new SqliteConnection(m_connectionString)) - { - dbcon.Open(); - SqliteCommand cmd = new SqliteCommand("select * from `" + m_Realm + "` where UUID = '" + principalID.ToString() + "'", dbcon); + SqliteCommand cmd = new SqliteCommand("select * from `" + m_Realm + "` where UUID = :PrincipalID"); + cmd.Parameters.Add(new SqliteParameter(":PrincipalID", principalID.ToString())); - IDataReader result = cmd.ExecuteReader(); + IDataReader result = ExecuteReader(cmd, m_Connection); + try + { if (result.Read()) { ret.PrincipalID = principalID; @@ -106,6 +108,15 @@ namespace OpenSim.Data.SQLite return null; } } + catch + { + } + finally + { + CloseCommand(cmd); + } + + return null; } public bool Store(AuthenticationData data) @@ -131,28 +142,28 @@ namespace OpenSim.Data.SQLite { if (!first) update += ", "; - update += "`" + field + "` = '" + data.Data[field] + "'"; + update += "`" + field + "` = :" + field; + cmd.Parameters.Add(new SqliteParameter(":" + field, data.Data[field])); first = false; - } - update += " where UUID = '" + data.PrincipalID.ToString() + "'"; + update += " where UUID = :UUID"; + cmd.Parameters.Add(new SqliteParameter(":UUID", data.PrincipalID.ToString())); cmd.CommandText = update; - Console.WriteLine("XXX " + cmd.CommandText); try { - if (ExecuteNonQuery(cmd) < 1) + if (ExecuteNonQuery(cmd, m_Connection) < 1) { - cmd.Dispose(); + CloseCommand(cmd); return false; } } catch (Exception e) { Console.WriteLine(e.ToString()); - cmd.Dispose(); + CloseCommand(cmd); return false; } } @@ -161,29 +172,31 @@ namespace OpenSim.Data.SQLite { string insert = "insert into `" + m_Realm + "` (`UUID`, `" + String.Join("`, `", fields) + - "`) values ('" + data.PrincipalID.ToString() + "', '" + String.Join("', '", values) + "')"; + "`) values (:UUID, :" + String.Join(", :", fields) + ")"; - cmd.CommandText = insert; + cmd.Parameters.Add(new SqliteParameter(":UUID", data.PrincipalID.ToString())); + foreach (string field in fields) + cmd.Parameters.Add(new SqliteParameter(":" + field, data.Data[field])); - Console.WriteLine("XXX " + cmd.CommandText); + cmd.CommandText = insert; try { - if (ExecuteNonQuery(cmd) < 1) + if (ExecuteNonQuery(cmd, m_Connection) < 1) { - cmd.Dispose(); + CloseCommand(cmd); return false; } } catch (Exception e) { Console.WriteLine(e.ToString()); - cmd.Dispose(); + CloseCommand(cmd); return false; } } - cmd.Dispose(); + CloseCommand(cmd); return true; } @@ -193,7 +206,7 @@ namespace OpenSim.Data.SQLite SqliteCommand cmd = new SqliteCommand("update `" + m_Realm + "` set `" + item + "` = " + value + " where UUID = '" + principalID.ToString() + "'"); - if (ExecuteNonQuery(cmd) > 0) + if (ExecuteNonQuery(cmd, m_Connection) > 0) return true; return false; @@ -205,9 +218,9 @@ namespace OpenSim.Data.SQLite DoExpire(); SqliteCommand cmd = new SqliteCommand("insert into tokens (UUID, token, validity) values ('" + principalID.ToString() + - "', '" + token + "', datetime('now, 'localtime', '+" + lifetime.ToString() + " minutes'))"); + "', '" + token + "', datetime('now', 'localtime', '+" + lifetime.ToString() + " minutes'))"); - if (ExecuteNonQuery(cmd) > 0) + if (ExecuteNonQuery(cmd, m_Connection) > 0) { cmd.Dispose(); return true; @@ -225,7 +238,7 @@ namespace OpenSim.Data.SQLite SqliteCommand cmd = new SqliteCommand("update tokens set validity = datetime('now, 'localtime', '+" + lifetime.ToString() + " minutes') where UUID = '" + principalID.ToString() + "' and token = '" + token + "' and validity > datetime('now', 'localtime')"); - if (ExecuteNonQuery(cmd) > 0) + if (ExecuteNonQuery(cmd, m_Connection) > 0) { cmd.Dispose(); return true; @@ -238,8 +251,8 @@ namespace OpenSim.Data.SQLite private void DoExpire() { - SqliteCommand cmd = new SqliteCommand("delete from tokens where validity < datetime('now, 'localtime')"); - ExecuteNonQuery(cmd); + SqliteCommand cmd = new SqliteCommand("delete from tokens where validity < datetime('now', 'localtime')"); + ExecuteNonQuery(cmd, m_Connection); cmd.Dispose(); diff --git a/OpenSim/Data/SQLite/SQLiteFramework.cs b/OpenSim/Data/SQLite/SQLiteFramework.cs index 54b104b..20b5085 100644 --- a/OpenSim/Data/SQLite/SQLiteFramework.cs +++ b/OpenSim/Data/SQLite/SQLiteFramework.cs @@ -42,7 +42,6 @@ namespace OpenSim.Data.SQLite { protected Object m_lockObject = new Object(); - protected static SqliteConnection m_Connection; protected SQLiteFramework(string connectionString) { } @@ -52,43 +51,41 @@ namespace OpenSim.Data.SQLite // All non queries are funneled through one connection // to increase performance a little // - protected int ExecuteNonQuery(SqliteCommand cmd) + protected int ExecuteNonQuery(SqliteCommand cmd, SqliteConnection connection) { - lock (m_lockObject) + lock (connection) { SqliteConnection newConnection = - (SqliteConnection)((ICloneable)m_Connection).Clone(); + (SqliteConnection)((ICloneable)connection).Clone(); newConnection.Open(); cmd.Connection = newConnection; - Console.WriteLine("XXX " + cmd.CommandText); + //Console.WriteLine("XXX " + cmd.CommandText); return cmd.ExecuteNonQuery(); } } - - protected IDataReader ExecuteReader(SqliteCommand cmd) + + protected IDataReader ExecuteReader(SqliteCommand cmd, SqliteConnection connection) { - lock (m_lockObject) + lock (connection) { SqliteConnection newConnection = - (SqliteConnection)((ICloneable)m_Connection).Clone(); + (SqliteConnection)((ICloneable)connection).Clone(); newConnection.Open(); cmd.Connection = newConnection; - Console.WriteLine("XXX " + cmd.CommandText); + //Console.WriteLine("XXX " + cmd.CommandText); + return cmd.ExecuteReader(); } } - protected void CloseReaderCommand(SqliteCommand cmd) + protected void CloseCommand(SqliteCommand cmd) { - lock (m_lockObject) - { - cmd.Connection.Close(); - cmd.Connection.Dispose(); - cmd.Dispose(); - } + cmd.Connection.Close(); + cmd.Connection.Dispose(); + cmd.Dispose(); } } } diff --git a/OpenSim/Data/SQLite/SQLiteGenericTableHandler.cs b/OpenSim/Data/SQLite/SQLiteGenericTableHandler.cs index e7e158d..b39bb19 100644 --- a/OpenSim/Data/SQLite/SQLiteGenericTableHandler.cs +++ b/OpenSim/Data/SQLite/SQLiteGenericTableHandler.cs @@ -48,6 +48,7 @@ namespace OpenSim.Data.SQLite protected string m_Realm; protected FieldInfo m_DataField = null; + protected static SqliteConnection m_Connection; private static bool m_initialized; public SQLiteGenericTableHandler(string connectionString, @@ -63,9 +64,14 @@ namespace OpenSim.Data.SQLite if (storeName != String.Empty) { Assembly assem = GetType().Assembly; + SqliteConnection newConnection = + (SqliteConnection)((ICloneable)m_Connection).Clone(); + newConnection.Open(); - Migration m = new Migration(m_Connection, assem, storeName); + Migration m = new Migration(newConnection, assem, storeName); m.Update(); + newConnection.Close(); + newConnection.Dispose(); } m_initialized = true; @@ -136,7 +142,7 @@ namespace OpenSim.Data.SQLite protected T[] DoQuery(SqliteCommand cmd) { - IDataReader reader = ExecuteReader(cmd); + IDataReader reader = ExecuteReader(cmd, m_Connection); if (reader == null) return new T[0]; @@ -191,7 +197,7 @@ namespace OpenSim.Data.SQLite result.Add(row); } - CloseReaderCommand(cmd); + CloseCommand(cmd); return result.ToArray(); } @@ -240,7 +246,7 @@ namespace OpenSim.Data.SQLite cmd.CommandText = query; - if (ExecuteNonQuery(cmd) > 0) + if (ExecuteNonQuery(cmd, m_Connection) > 0) return true; return false; @@ -253,7 +259,7 @@ namespace OpenSim.Data.SQLite cmd.CommandText = String.Format("delete from {0} where `{1}` = :{1}", m_Realm, field); cmd.Parameters.Add(new SqliteParameter(field, val)); - if (ExecuteNonQuery(cmd) > 0) + if (ExecuteNonQuery(cmd, m_Connection) > 0) return true; return false; diff --git a/OpenSim/Data/SQLite/SQLiteXInventoryData.cs b/OpenSim/Data/SQLite/SQLiteXInventoryData.cs index 5c93f88..a66e0c6 100644 --- a/OpenSim/Data/SQLite/SQLiteXInventoryData.cs +++ b/OpenSim/Data/SQLite/SQLiteXInventoryData.cs @@ -115,7 +115,7 @@ namespace OpenSim.Data.SQLite cmd.Parameters.Add(new SqliteParameter(":ParentFolderID", newParent)); cmd.Parameters.Add(new SqliteParameter(":InventoryID", id)); - return ExecuteNonQuery(cmd) == 0 ? false : true; + return ExecuteNonQuery(cmd, m_Connection) == 0 ? false : true; } public XInventoryItem[] GetActiveGestures(UUID principalID) @@ -137,7 +137,7 @@ namespace OpenSim.Data.SQLite cmd.Parameters.Add(new SqliteParameter(":PrincipalID", principalID.ToString())); cmd.Parameters.Add(new SqliteParameter(":AssetID", assetID.ToString())); - IDataReader reader = ExecuteReader(cmd); + IDataReader reader = ExecuteReader(cmd, m_Connection); int perms = 0; @@ -147,7 +147,7 @@ namespace OpenSim.Data.SQLite } reader.Close(); - CloseReaderCommand(cmd); + CloseCommand(cmd); return perms; } -- cgit v1.1 From 552e9e8c7832f41f5a53666d9c3ece62f57be4ba Mon Sep 17 00:00:00 2001 From: Diva Canto Date: Sun, 21 Feb 2010 09:09:35 -0800 Subject: * Added SQlite connector for AvatarData. Tested -- works. * Small bug fix in debug message * Set default standalone configs to use SQLite across the board --- OpenSim/Data/SQLite/Resources/001_Avatar.sql | 9 +++ OpenSim/Data/SQLite/SQLiteAvatarData.cs | 74 ++++++++++++++++++++++ .../Inventory/LocalInventoryServiceConnector.cs | 2 +- bin/config-include/Standalone.ini | 6 +- bin/config-include/StandaloneHypergrid.ini | 6 +- 5 files changed, 90 insertions(+), 7 deletions(-) create mode 100644 OpenSim/Data/SQLite/Resources/001_Avatar.sql create mode 100644 OpenSim/Data/SQLite/SQLiteAvatarData.cs diff --git a/OpenSim/Data/SQLite/Resources/001_Avatar.sql b/OpenSim/Data/SQLite/Resources/001_Avatar.sql new file mode 100644 index 0000000..7ec906b --- /dev/null +++ b/OpenSim/Data/SQLite/Resources/001_Avatar.sql @@ -0,0 +1,9 @@ +BEGIN TRANSACTION; + +CREATE TABLE Avatars ( + PrincipalID CHAR(36) NOT NULL, + Name VARCHAR(32) NOT NULL, + Value VARCHAR(255) NOT NULL DEFAULT '', + PRIMARY KEY(PrincipalID, Name)); + +COMMIT; diff --git a/OpenSim/Data/SQLite/SQLiteAvatarData.cs b/OpenSim/Data/SQLite/SQLiteAvatarData.cs new file mode 100644 index 0000000..d0b82de --- /dev/null +++ b/OpenSim/Data/SQLite/SQLiteAvatarData.cs @@ -0,0 +1,74 @@ +/* + * Copyright (c) Contributors, http://opensimulator.org/ + * See CONTRIBUTORS.TXT for a full list of copyright holders. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the OpenSimulator Project nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections.Generic; +using System.Data; +using System.Reflection; +using System.Threading; +using log4net; +using OpenMetaverse; +using OpenSim.Framework; +using Mono.Data.SqliteClient; + +namespace OpenSim.Data.SQLite +{ + /// + /// A MySQL Interface for the Grid Server + /// + public class SQLiteAvatarData : SQLiteGenericTableHandler, + IAvatarData + { + private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + + public SQLiteAvatarData(string connectionString, string realm) : + base(connectionString, realm, "Avatar") + { + } + + public bool Delete(UUID principalID, string name) + { + SqliteCommand cmd = new SqliteCommand(); + + cmd.CommandText = String.Format("delete from {0} where `PrincipalID` = :PrincipalID and `Name` = :Name", m_Realm); + cmd.Parameters.Add(":PrincipalID", principalID.ToString()); + cmd.Parameters.Add(":Name", name); + + try + { + if (ExecuteNonQuery(cmd, m_Connection) > 0) + return true; + + return false; + } + finally + { + CloseCommand(cmd); + } + } + } +} diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/LocalInventoryServiceConnector.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/LocalInventoryServiceConnector.cs index 54e62e2..e97d21f 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/LocalInventoryServiceConnector.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Inventory/LocalInventoryServiceConnector.cs @@ -314,7 +314,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory item = m_InventoryService.GetItem(item); if (null == item) - m_log.ErrorFormat("[LOCAL INVENTORY SERVICES CONNECTOR]: Could not find item with id {0}"); + m_log.ErrorFormat("[LOCAL INVENTORY SERVICES CONNECTOR]: Could not find item with id {0}", item.ID); return item; } diff --git a/bin/config-include/Standalone.ini b/bin/config-include/Standalone.ini index b9a9462..06333d8 100644 --- a/bin/config-include/Standalone.ini +++ b/bin/config-include/Standalone.ini @@ -32,14 +32,14 @@ [AvatarService] LocalServiceModule = "OpenSim.Services.AvatarService.dll:AvatarService" - StorageProvider = "OpenSim.Data.Null.dll" + ConnectionString = "URI=file:avatars.db,version=3" [AuthorizationService] LocalServiceModule = "OpenSim.Services.AuthorizationService.dll:AuthorizationService" [AuthenticationService] LocalServiceModule = "OpenSim.Services.AuthenticationService.dll:PasswordAuthenticationService" - StorageProvider = "OpenSim.Data.Null.dll" + ConnectionString = "URI=file:auth.db,version=3" [GridService] LocalServiceModule = "OpenSim.Services.GridService.dll:GridService" @@ -52,7 +52,7 @@ [UserAccountService] LocalServiceModule = "OpenSim.Services.UserAccountService.dll:UserAccountService" - StorageProvider = "OpenSim.Data.Null.dll" + ConnectionString = "URI=file:userprofiles.db,version=3" ;; These are for creating new accounts AuthenticationService = "OpenSim.Services.AuthenticationService.dll:PasswordAuthenticationService" PresenceService = "OpenSim.Services.PresenceService.dll:PresenceService" diff --git a/bin/config-include/StandaloneHypergrid.ini b/bin/config-include/StandaloneHypergrid.ini index 9ad6d1c..04a2356 100644 --- a/bin/config-include/StandaloneHypergrid.ini +++ b/bin/config-include/StandaloneHypergrid.ini @@ -42,7 +42,7 @@ [AvatarService] LocalServiceModule = "OpenSim.Services.AvatarService.dll:AvatarService" - StorageProvider = "OpenSim.Data.Null.dll" + ConnectionString = "URI=file:avatars.db,version=3" [LibraryService] LocalServiceModule = "OpenSim.Services.InventoryService.dll:LibraryService" @@ -54,7 +54,7 @@ [AuthenticationService] LocalServiceModule = "OpenSim.Services.AuthenticationService.dll:PasswordAuthenticationService" - StorageProvider = "OpenSim.Data.Null.dll" + ConnectionString = "URI=file:auth.db,version=3" [GridService] ; LocalGridServicesConnector needs this @@ -70,7 +70,7 @@ [UserAccountService] LocalServiceModule = "OpenSim.Services.UserAccountService.dll:UserAccountService" - StorageProvider = "OpenSim.Data.Null.dll" + ConnectionString = "URI=file:userprofiles.db,version=3" ;; These are for creating new accounts by the service AuthenticationService = "OpenSim.Services.AuthenticationService.dll:PasswordAuthenticationService" PresenceService = "OpenSim.Services.PresenceService.dll:PresenceService" -- cgit v1.1 From bd5a4dab0c06bf7faf05df5be7a1c93c5e025724 Mon Sep 17 00:00:00 2001 From: Diva Canto Date: Sun, 21 Feb 2010 09:39:12 -0800 Subject: Bug fixes on field names in order to make data import work from old users table to new UserAccounts table. --- OpenSim/Data/SQLite/Resources/002_UserAccount.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OpenSim/Data/SQLite/Resources/002_UserAccount.sql b/OpenSim/Data/SQLite/Resources/002_UserAccount.sql index c0b3d7b..c7a6293 100644 --- a/OpenSim/Data/SQLite/Resources/002_UserAccount.sql +++ b/OpenSim/Data/SQLite/Resources/002_UserAccount.sql @@ -1,5 +1,5 @@ BEGIN TRANSACTION; -INSERT INTO UserAccounts (PrincipalID, ScopeID, FirstName, LastName, Email, ServiceURLs, Created) SELECT `UUID` AS PrincipalID, '00000000-0000-0000-0000-000000000000' AS ScopeID, username AS FirstName, lastname AS LastName, email as Email, CONCAT('AssetServerURI=', userAssetURI, ' InventoryServerURI=', userInventoryURI, ' GatewayURI= HomeURI=') AS ServiceURLs, created as Created FROM users; +INSERT INTO UserAccounts (PrincipalID, ScopeID, FirstName, LastName, Email, ServiceURLs, Created) SELECT `UUID` AS PrincipalID, '00000000-0000-0000-0000-000000000000' AS ScopeID, username AS FirstName, surname AS LastName, '' as Email, '' AS ServiceURLs, created as Created FROM users; COMMIT; -- cgit v1.1 From bb171717ceaef37b022a135209c2e0bf031d21f9 Mon Sep 17 00:00:00 2001 From: Diva Canto Date: Sun, 21 Feb 2010 15:38:52 -0800 Subject: Deleted obsolete files in the Data layer. Compiles. --- OpenSim/Data/DataPluginFactory.cs | 155 --- OpenSim/Data/GridDataBase.cs | 52 - OpenSim/Data/IGridData.cs | 134 --- OpenSim/Data/ILogData.cs | 87 -- OpenSim/Data/IRegionProfileService.cs | 100 -- OpenSim/Data/IUserData.cs | 209 ---- OpenSim/Data/MSSQL/MSSQLGridData.cs | 587 --------- OpenSim/Data/MSSQL/MSSQLLogData.cs | 146 --- OpenSim/Data/MSSQL/MSSQLUserData.cs | 1214 ------------------- OpenSim/Data/MySQL/MySQLGridData.cs | 422 ------- OpenSim/Data/MySQL/MySQLLogData.cs | 166 --- OpenSim/Data/MySQL/MySQLManager.cs | 1248 ------------------- OpenSim/Data/MySQL/MySQLSuperManager.cs | 52 - OpenSim/Data/MySQL/MySQLUserData.cs | 766 ------------ OpenSim/Data/MySQL/Tests/MySQLAssetTest.cs | 22 +- OpenSim/Data/MySQL/Tests/MySQLEstateTest.cs | 54 +- OpenSim/Data/MySQL/Tests/MySQLGridTest.cs | 94 -- OpenSim/Data/MySQL/Tests/MySQLInventoryTest.cs | 30 +- OpenSim/Data/MySQL/Tests/MySQLRegionTest.cs | 53 +- OpenSim/Data/MySQL/Tests/MySQLUserTest.cs | 85 -- OpenSim/Data/RegionProfileData.cs | 337 ------ OpenSim/Data/RegionProfileServiceProxy.cs | 119 -- OpenSim/Data/ReservationData.cs | 48 - OpenSim/Data/SQLite/SQLiteGridData.cs | 286 ----- OpenSim/Data/SQLite/SQLiteManager.cs | 225 ---- OpenSim/Data/SQLite/SQLiteUserData.cs | 1262 -------------------- OpenSim/Data/SQLite/Tests/SQLiteUserTest.cs | 64 - OpenSim/Data/Tests/BasicGridTest.cs | 173 --- OpenSim/Data/Tests/BasicUserTest.cs | 703 ----------- OpenSim/Data/UserDataBase.cs | 91 -- .../Communications/TemporaryUserProfilePlugin.cs | 104 -- OpenSim/Tests/Common/Mock/TestUserDataPlugin.cs | 216 ---- 32 files changed, 103 insertions(+), 9201 deletions(-) delete mode 100644 OpenSim/Data/DataPluginFactory.cs delete mode 100644 OpenSim/Data/GridDataBase.cs delete mode 100644 OpenSim/Data/IGridData.cs delete mode 100644 OpenSim/Data/ILogData.cs delete mode 100644 OpenSim/Data/IRegionProfileService.cs delete mode 100644 OpenSim/Data/IUserData.cs delete mode 100644 OpenSim/Data/MSSQL/MSSQLGridData.cs delete mode 100644 OpenSim/Data/MSSQL/MSSQLLogData.cs delete mode 100644 OpenSim/Data/MSSQL/MSSQLUserData.cs delete mode 100644 OpenSim/Data/MySQL/MySQLGridData.cs delete mode 100644 OpenSim/Data/MySQL/MySQLLogData.cs delete mode 100644 OpenSim/Data/MySQL/MySQLManager.cs delete mode 100644 OpenSim/Data/MySQL/MySQLSuperManager.cs delete mode 100644 OpenSim/Data/MySQL/MySQLUserData.cs delete mode 100644 OpenSim/Data/MySQL/Tests/MySQLGridTest.cs delete mode 100644 OpenSim/Data/MySQL/Tests/MySQLUserTest.cs delete mode 100644 OpenSim/Data/RegionProfileData.cs delete mode 100644 OpenSim/Data/RegionProfileServiceProxy.cs delete mode 100644 OpenSim/Data/ReservationData.cs delete mode 100644 OpenSim/Data/SQLite/SQLiteGridData.cs delete mode 100644 OpenSim/Data/SQLite/SQLiteManager.cs delete mode 100644 OpenSim/Data/SQLite/SQLiteUserData.cs delete mode 100644 OpenSim/Data/SQLite/Tests/SQLiteUserTest.cs delete mode 100644 OpenSim/Data/Tests/BasicGridTest.cs delete mode 100644 OpenSim/Data/Tests/BasicUserTest.cs delete mode 100644 OpenSim/Data/UserDataBase.cs delete mode 100644 OpenSim/Framework/Communications/TemporaryUserProfilePlugin.cs delete mode 100644 OpenSim/Tests/Common/Mock/TestUserDataPlugin.cs diff --git a/OpenSim/Data/DataPluginFactory.cs b/OpenSim/Data/DataPluginFactory.cs deleted file mode 100644 index 841f71e..0000000 --- a/OpenSim/Data/DataPluginFactory.cs +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using OpenSim.Framework; - -namespace OpenSim.Data -{ - /// - /// A static class containing methods for obtaining handles to database - /// storage objects. - /// - public static class DataPluginFactory - { - /// - /// Based on , returns the appropriate - /// PluginInitialiserBase instance in and - /// extension point path in . - /// - /// - /// The DB connection string used when creating a new - /// PluginInitialiserBase, returned in . - /// - /// - /// A reference to a PluginInitialiserBase object in which the proper - /// initialiser will be returned. - /// - /// - /// A string in which the proper extension point path will be returned. - /// - /// - /// The type of data plugin requested. - /// - /// - /// Thrown if is not one of the expected data - /// interfaces. - /// - private static void PluginLoaderParamFactory(string connect, out PluginInitialiserBase init, out string path) where T : IPlugin - { - Type type = typeof(T); - - if (type == typeof(IInventoryDataPlugin)) - { - init = new InventoryDataInitialiser(connect); - path = "/OpenSim/InventoryData"; - } - else if (type == typeof(IUserDataPlugin)) - { - init = new UserDataInitialiser(connect); - path = "/OpenSim/UserData"; - } - else if (type == typeof(IGridDataPlugin)) - { - init = new GridDataInitialiser(connect); - path = "/OpenSim/GridData"; - } - else if (type == typeof(ILogDataPlugin)) - { - init = new LogDataInitialiser(connect); - path = "/OpenSim/LogData"; - } - else if (type == typeof(IAssetDataPlugin)) - { - init = new AssetDataInitialiser(connect); - path = "/OpenSim/AssetData"; - } - else - { - // We don't support this data plugin. - throw new NotImplementedException(String.Format("The type '{0}' is not a valid data plugin.", type)); - } - } - - /// - /// Returns a list of new data plugins. - /// Plugins will be requested in the order they were added. - /// - /// - /// The filename of the inventory server plugin DLL. - /// - /// - /// The connection string for the storage backend. - /// - /// - /// The type of data plugin requested. - /// - /// - /// A list of all loaded plugins matching . - /// - public static List LoadDataPlugins(string provider, string connect) where T : IPlugin - { - PluginInitialiserBase pluginInitialiser; - string extensionPointPath; - - PluginLoaderParamFactory(connect, out pluginInitialiser, out extensionPointPath); - - using (PluginLoader loader = new PluginLoader(pluginInitialiser)) - { - // loader will try to load all providers (MySQL, MSSQL, etc) - // unless it is constrainted to the correct "Provider" entry in the addin.xml - loader.Add(extensionPointPath, new PluginProviderFilter(provider)); - loader.Load(); - - return loader.Plugins; - } - } - - /// - /// Returns a new data plugin instance if - /// only one was loaded, otherwise returns null (default(T)). - /// - /// - /// The filename of the inventory server plugin DLL. - /// - /// - /// The connection string for the storage backend. - /// - /// - /// The type of data plugin requested. - /// - /// - /// A list of all loaded plugins matching . - /// - public static T LoadDataPlugin(string provider, string connect) where T : IPlugin - { - List plugins = LoadDataPlugins(provider, connect); - return (plugins.Count == 1) ? plugins[0] : default(T); - } - } -} diff --git a/OpenSim/Data/GridDataBase.cs b/OpenSim/Data/GridDataBase.cs deleted file mode 100644 index a03488b..0000000 --- a/OpenSim/Data/GridDataBase.cs +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System.Collections.Generic; -using OpenMetaverse; - -namespace OpenSim.Data -{ - public abstract class GridDataBase : IGridDataPlugin - { - public abstract RegionProfileData GetProfileByHandle(ulong regionHandle); - public abstract RegionProfileData GetProfileByUUID(UUID UUID); - public abstract RegionProfileData GetProfileByString(string regionName); - public abstract RegionProfileData[] GetProfilesInRange(uint Xmin, uint Ymin, uint Xmax, uint Ymax); - public abstract List GetRegionsByName(string namePrefix, uint maxNum); - public abstract bool AuthenticateSim(UUID UUID, ulong regionHandle, string simrecvkey); - public abstract DataResponse StoreProfile(RegionProfileData profile); - public abstract ReservationData GetReservationAtPoint(uint x, uint y); - public abstract DataResponse DeleteProfile(string uuid); - - public abstract void Initialise(); - public abstract void Initialise(string connect); - public abstract void Dispose(); - - public abstract string Name { get; } - public abstract string Version { get; } - } -} diff --git a/OpenSim/Data/IGridData.cs b/OpenSim/Data/IGridData.cs deleted file mode 100644 index 8bd3811..0000000 --- a/OpenSim/Data/IGridData.cs +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System.Collections.Generic; -using OpenMetaverse; -using OpenSim.Framework; - -namespace OpenSim.Data -{ - public enum DataResponse - { - RESPONSE_OK, - RESPONSE_AUTHREQUIRED, - RESPONSE_INVALIDCREDENTIALS, - RESPONSE_ERROR - } - - /// - /// A standard grid interface - /// - public interface IGridDataPlugin : IPlugin - { - /// - /// Initialises the interface - /// - void Initialise(string connect); - - /// - /// Returns a sim profile from a regionHandle - /// - /// A 64bit Region Handle - /// A simprofile - RegionProfileData GetProfileByHandle(ulong regionHandle); - - /// - /// Returns a sim profile from a UUID - /// - /// A 128bit UUID - /// A sim profile - RegionProfileData GetProfileByUUID(UUID UUID); - - /// - /// Returns a sim profile from a string match - /// - /// A string for a partial region name match - /// A sim profile - RegionProfileData GetProfileByString(string regionName); - - /// - /// Returns all profiles within the specified range - /// - /// Minimum sim coordinate (X) - /// Minimum sim coordinate (Y) - /// Maximum sim coordinate (X) - /// Maximum sim coordinate (Y) - /// An array containing all the sim profiles in the specified range - RegionProfileData[] GetProfilesInRange(uint Xmin, uint Ymin, uint Xmax, uint Ymax); - - /// - /// Returns up to maxNum profiles of regions that have a name starting with namePrefix - /// - /// The name to match against - /// Maximum number of profiles to return - /// A list of sim profiles - List GetRegionsByName(string namePrefix, uint maxNum); - - /// - /// Authenticates a sim by use of its recv key. - /// WARNING: Insecure - /// - /// The UUID sent by the sim - /// The regionhandle sent by the sim - /// The receiving key sent by the sim - /// Whether the sim has been authenticated - bool AuthenticateSim(UUID UUID, ulong regionHandle, string simrecvkey); - - /// - /// Adds or updates a profile in the database - /// - /// The profile to add - /// RESPONSE_OK if successful, error if not. - DataResponse StoreProfile(RegionProfileData profile); - - /// - /// Remove a profile from the database - /// - /// ID of profile to remove - /// - DataResponse DeleteProfile(string UUID); - - /// - /// Function not used???? - /// - /// - /// - /// - ReservationData GetReservationAtPoint(uint x, uint y); - } - - public class GridDataInitialiser : PluginInitialiserBase - { - private string connect; - public GridDataInitialiser (string s) { connect = s; } - public override void Initialise (IPlugin plugin) - { - IGridDataPlugin p = plugin as IGridDataPlugin; - p.Initialise (connect); - } - } -} diff --git a/OpenSim/Data/ILogData.cs b/OpenSim/Data/ILogData.cs deleted file mode 100644 index 97ca1cc..0000000 --- a/OpenSim/Data/ILogData.cs +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using OpenSim.Framework; - -namespace OpenSim.Data -{ - /// - /// The severity of an individual log message - /// - public enum LogSeverity : int - { - /// - /// Critical: systems failure - /// - CRITICAL = 1, - /// - /// Major: warning prior to systems failure - /// - MAJOR = 2, - /// - /// Medium: an individual non-critical task failed - /// - MEDIUM = 3, - /// - /// Low: Informational warning - /// - LOW = 4, - /// - /// Info: Information - /// - INFO = 5, - /// - /// Verbose: Debug Information - /// - VERBOSE = 6 - } - - /// - /// An interface to a LogData storage system - /// - public interface ILogDataPlugin : IPlugin - { - void saveLog(string serverDaemon, string target, string methodCall, string arguments, int priority, - string logMessage); - - /// - /// Initialises the interface - /// - void Initialise(string connect); - } - - public class LogDataInitialiser : PluginInitialiserBase - { - private string connect; - public LogDataInitialiser (string s) { connect = s; } - public override void Initialise (IPlugin plugin) - { - ILogDataPlugin p = plugin as ILogDataPlugin; - p.Initialise (connect); - } - } -} diff --git a/OpenSim/Data/IRegionProfileService.cs b/OpenSim/Data/IRegionProfileService.cs deleted file mode 100644 index b3acc52..0000000 --- a/OpenSim/Data/IRegionProfileService.cs +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.Text; -using OpenMetaverse; - -namespace OpenSim.Data -{ - public interface IRegionProfileService - { - /// - /// Returns a region by argument - /// - /// A UUID key of the region to return - /// A SimProfileData for the region - RegionProfileData GetRegion(UUID uuid); - - /// - /// Returns a region by argument - /// - /// A regionHandle of the region to return - /// A SimProfileData for the region - RegionProfileData GetRegion(ulong handle); - - /// - /// Returns a region by argument - /// - /// A partial regionName of the region to return - /// A SimProfileData for the region - RegionProfileData GetRegion(string regionName); - - List GetRegions(uint xmin, uint ymin, uint xmax, uint ymax); - List GetRegions(string name, int maxNum); - DataResponse AddUpdateRegion(RegionProfileData sim, RegionProfileData existingSim); - DataResponse DeleteRegion(string uuid); - } - - public interface IRegionProfileRouter - { - /// - /// Request sim profile information from a grid server, by Region UUID - /// - /// The region UUID to look for - /// - /// - /// - /// The sim profile. Null if there was a request failure - /// This method should be statics - RegionProfileData RequestSimProfileData(UUID regionId, Uri gridserverUrl, - string gridserverSendkey, string gridserverRecvkey); - - /// - /// Request sim profile information from a grid server, by Region Handle - /// - /// the region handle to look for - /// - /// - /// - /// The sim profile. Null if there was a request failure - RegionProfileData RequestSimProfileData(ulong regionHandle, Uri gridserverUrl, - string gridserverSendkey, string gridserverRecvkey); - - /// - /// Request sim profile information from a grid server, by Region Name - /// - /// the region name to look for - /// - /// - /// - /// The sim profile. Null if there was a request failure - RegionProfileData RequestSimProfileData(string regionName, Uri gridserverUrl, - string gridserverSendkey, string gridserverRecvkey); - } -} diff --git a/OpenSim/Data/IUserData.cs b/OpenSim/Data/IUserData.cs deleted file mode 100644 index e9a1e81..0000000 --- a/OpenSim/Data/IUserData.cs +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using OpenMetaverse; -using OpenSim.Framework; - -namespace OpenSim.Data -{ - /// - /// An interface for connecting to user storage servers. - /// - public interface IUserDataPlugin : IPlugin - { - /// - /// Returns a user profile from a database via their UUID - /// - /// The user's UUID - /// The user data profile. Returns null if no user is found - UserProfileData GetUserByUUID(UUID user); - - /// - /// Returns a users profile by searching their username parts - /// - /// Account firstname - /// Account lastname - /// The user data profile. Null if no user is found - UserProfileData GetUserByName(string fname, string lname); - - /// - /// Get a user from a given uri. - /// - /// - /// The user data profile. Null if no user is found. - UserProfileData GetUserByUri(Uri uri); - - /// - /// Returns a list of UUIDs firstnames and lastnames that match string query entered into the avatar picker. - /// - /// ID associated with the user's query. This must match what the client sent - /// The filtered contents of the search box when the user hit search. - /// A list of user details. If there are no results than either an empty list or null - List GeneratePickerResults(UUID queryID, string query); - - /// - /// Returns the current agent for a user searching by it's UUID - /// - /// The users UUID - /// The current agent session. Null if no session was found - UserAgentData GetAgentByUUID(UUID user); - - /// - /// Returns the current session agent for a user searching by username - /// - /// The users account name - /// The current agent session - UserAgentData GetAgentByName(string name); - - /// - /// Returns the current session agent for a user searching by username parts - /// - /// The users first account name - /// The users account surname - /// The current agent session - UserAgentData GetAgentByName(string fname, string lname); - - /// - /// Stores new web-login key for user during web page login - /// - /// - void StoreWebLoginKey(UUID agentID, UUID webLoginKey); - - /// - /// Adds a new User profile to the database - /// - /// UserProfile to add - void AddNewUserProfile(UserProfileData user); - - /// - /// Adds a temporary user profile. A temporary userprofile is one that should exist only for the lifetime of - /// the process. - /// - /// - void AddTemporaryUserProfile(UserProfileData userProfile); - - /// - /// Updates an existing user profile - /// - /// UserProfile to update - bool UpdateUserProfile(UserProfileData user); - - /// - /// Adds a new agent to the database - /// - /// The agent to add - void AddNewUserAgent(UserAgentData agent); - - /// - /// Adds a new friend to the database for XUser - /// - /// The agent that who's friends list is being added to - /// The agent that being added to the friends list of the friends list owner - /// A uint bit vector for set perms that the friend being added has; 0 = none, 1=This friend can see when they sign on, 2 = map, 4 edit objects - void AddNewUserFriend(UUID friendlistowner, UUID friend, uint perms); - - /// - /// Delete friend on friendlistowner's friendlist. - /// - /// The agent that who's friends list is being updated - /// The Ex-friend agent - void RemoveUserFriend(UUID friendlistowner, UUID friend); - - /// - /// Update permissions for friend on friendlistowner's friendlist. - /// - /// The agent that who's friends list is being updated - /// The agent that is getting or loosing permissions - /// A uint bit vector for set perms that the friend being added has; 0 = none, 1=This friend can see when they sign on, 2 = map, 4 edit objects - void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms); - - /// - /// Returns a list of FriendsListItems that describe the friends and permissions in the friend relationship for UUID friendslistowner - /// - /// The agent that we're retreiving the friends Data. - /// The user's friends. If there are no results than either an empty list or null - List GetUserFriendList(UUID friendlistowner); - - /// - /// Returns a list of - /// A of , mapping the s to s. - /// - Dictionary GetFriendRegionInfos(List uuids); - - /// - /// Attempts to move currency units between accounts (NOT RELIABLE / TRUSTWORTHY. DONT TRY RUN YOUR OWN CURRENCY EXCHANGE WITH REAL VALUES) - /// - /// The account to transfer from - /// The account to transfer to - /// The amount to transfer - /// Successful? - bool MoneyTransferRequest(UUID from, UUID to, uint amount); - - /// - /// Attempts to move inventory between accounts, if inventory is copyable it will be copied into the target account. - /// - /// User to transfer from - /// User to transfer to - /// Specified inventory item - /// Successful? - bool InventoryTransferRequest(UUID from, UUID to, UUID inventory); - - /// - /// Initialises the plugin (artificial constructor) - /// - void Initialise(string connect); - - /// - /// Gets the user appearance - /// - AvatarAppearance GetUserAppearance(UUID user); - - void UpdateUserAppearance(UUID user, AvatarAppearance appearance); - - void ResetAttachments(UUID userID); - - void LogoutUsers(UUID regionID); - } - - public class UserDataInitialiser : PluginInitialiserBase - { - private string connect; - public UserDataInitialiser (string s) { connect = s; } - public override void Initialise (IPlugin plugin) - { - IUserDataPlugin p = plugin as IUserDataPlugin; - p.Initialise (connect); - } - } -} diff --git a/OpenSim/Data/MSSQL/MSSQLGridData.cs b/OpenSim/Data/MSSQL/MSSQLGridData.cs deleted file mode 100644 index 8a3d332..0000000 --- a/OpenSim/Data/MSSQL/MSSQLGridData.cs +++ /dev/null @@ -1,587 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.SqlClient; -using System.Reflection; -using log4net; -using OpenMetaverse; -using OpenSim.Framework; - -namespace OpenSim.Data.MSSQL -{ - /// - /// A grid data interface for MSSQL Server - /// - public class MSSQLGridData : GridDataBase - { - private const string _migrationStore = "GridStore"; - - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - /// - /// Database manager - /// - private MSSQLManager database; - - private string m_regionsTableName = "regions"; - - #region IPlugin Members - - // [Obsolete("Cannot be default-initialized!")] - override public void Initialise() - { - m_log.Info("[GRID DB]: " + Name + " cannot be default-initialized!"); - throw new PluginNotInitialisedException(Name); - } - - /// - /// Initialises the Grid Interface - /// - /// connect string - /// use mssql_connection.ini - override public void Initialise(string connectionString) - { - if (!string.IsNullOrEmpty(connectionString)) - { - database = new MSSQLManager(connectionString); - } - else - { - // TODO: make the connect string actually do something - IniFile iniFile = new IniFile("mssql_connection.ini"); - - string settingDataSource = iniFile.ParseFileReadValue("data_source"); - string settingInitialCatalog = iniFile.ParseFileReadValue("initial_catalog"); - string settingPersistSecurityInfo = iniFile.ParseFileReadValue("persist_security_info"); - string settingUserId = iniFile.ParseFileReadValue("user_id"); - string settingPassword = iniFile.ParseFileReadValue("password"); - - m_regionsTableName = iniFile.ParseFileReadValue("regionstablename"); - if (m_regionsTableName == null) - { - m_regionsTableName = "regions"; - } - - database = - new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId, - settingPassword); - } - - //New migrations check of store - database.CheckMigration(_migrationStore); - } - - /// - /// Shuts down the grid interface - /// - override public void Dispose() - { - database = null; - } - - /// - /// The name of this DB provider. - /// - /// A string containing the storage system name - override public string Name - { - get { return "MSSQL OpenGridData"; } - } - - /// - /// Database provider version. - /// - /// A string containing the storage system version - override public string Version - { - get { return "0.1"; } - } - - #endregion - - #region Public override GridDataBase methods - - /// - /// Returns a list of regions within the specified ranges - /// - /// minimum X coordinate - /// minimum Y coordinate - /// maximum X coordinate - /// maximum Y coordinate - /// null - /// always return null - override public RegionProfileData[] GetProfilesInRange(uint xmin, uint ymin, uint xmax, uint ymax) - { - using (AutoClosingSqlCommand command = database.Query("SELECT * FROM regions WHERE locX >= @xmin AND locX <= @xmax AND locY >= @ymin AND locY <= @ymax")) - { - command.Parameters.Add(database.CreateParameter("xmin", xmin)); - command.Parameters.Add(database.CreateParameter("ymin", ymin)); - command.Parameters.Add(database.CreateParameter("xmax", xmax)); - command.Parameters.Add(database.CreateParameter("ymax", ymax)); - - List rows = new List(); - - using (SqlDataReader reader = command.ExecuteReader()) - { - while (reader.Read()) - { - rows.Add(ReadSimRow(reader)); - } - } - - if (rows.Count > 0) - { - return rows.ToArray(); - } - } - m_log.Info("[GRID DB] : Found no regions within range."); - return null; - } - - - /// - /// Returns up to maxNum profiles of regions that have a name starting with namePrefix - /// - /// The name to match against - /// Maximum number of profiles to return - /// A list of sim profiles - override public List GetRegionsByName (string namePrefix, uint maxNum) - { - using (AutoClosingSqlCommand command = database.Query("SELECT * FROM regions WHERE regionName LIKE @name")) - { - command.Parameters.Add(database.CreateParameter("name", namePrefix + "%")); - - List rows = new List(); - - using (SqlDataReader reader = command.ExecuteReader()) - { - while (rows.Count < maxNum && reader.Read()) - { - rows.Add(ReadSimRow(reader)); - } - } - - return rows; - } - } - - /// - /// Returns a sim profile from its location - /// - /// Region location handle - /// Sim profile - override public RegionProfileData GetProfileByHandle(ulong handle) - { - using (AutoClosingSqlCommand command = database.Query("SELECT * FROM " + m_regionsTableName + " WHERE regionHandle = @handle")) - { - command.Parameters.Add(database.CreateParameter("handle", handle)); - - using (SqlDataReader reader = command.ExecuteReader()) - { - if (reader.Read()) - { - return ReadSimRow(reader); - } - } - } - m_log.InfoFormat("[GRID DB] : No region found with handle : {0}", handle); - return null; - } - - /// - /// Returns a sim profile from its UUID - /// - /// The region UUID - /// The sim profile - override public RegionProfileData GetProfileByUUID(UUID uuid) - { - using (AutoClosingSqlCommand command = database.Query("SELECT * FROM " + m_regionsTableName + " WHERE uuid = @uuid")) - { - command.Parameters.Add(database.CreateParameter("uuid", uuid)); - - using (SqlDataReader reader = command.ExecuteReader()) - { - if (reader.Read()) - { - return ReadSimRow(reader); - } - } - } - m_log.InfoFormat("[GRID DB] : No region found with UUID : {0}", uuid); - return null; - } - - /// - /// Returns a sim profile from it's Region name string - /// - /// The region name search query - /// The sim profile - override public RegionProfileData GetProfileByString(string regionName) - { - if (regionName.Length > 2) - { - using (AutoClosingSqlCommand command = database.Query("SELECT top 1 * FROM " + m_regionsTableName + " WHERE regionName like @regionName order by regionName")) - { - command.Parameters.Add(database.CreateParameter("regionName", regionName + "%")); - - using (SqlDataReader reader = command.ExecuteReader()) - { - if (reader.Read()) - { - return ReadSimRow(reader); - } - } - } - m_log.InfoFormat("[GRID DB] : No region found with regionName : {0}", regionName); - return null; - } - - m_log.Error("[GRID DB]: Searched for a Region Name shorter then 3 characters"); - return null; - } - - /// - /// Adds a new specified region to the database - /// - /// The profile to add - /// A dataresponse enum indicating success - override public DataResponse StoreProfile(RegionProfileData profile) - { - if (GetProfileByUUID(profile.UUID) == null) - { - if (InsertRegionRow(profile)) - { - return DataResponse.RESPONSE_OK; - } - } - else - { - if (UpdateRegionRow(profile)) - { - return DataResponse.RESPONSE_OK; - } - } - - return DataResponse.RESPONSE_ERROR; - } - - /// - /// Deletes a sim profile from the database - /// - /// the sim UUID - /// Successful? - //public DataResponse DeleteProfile(RegionProfileData profile) - override public DataResponse DeleteProfile(string uuid) - { - using (AutoClosingSqlCommand command = database.Query("DELETE FROM regions WHERE uuid = @uuid;")) - { - command.Parameters.Add(database.CreateParameter("uuid", uuid)); - try - { - command.ExecuteNonQuery(); - return DataResponse.RESPONSE_OK; - } - catch (Exception e) - { - m_log.DebugFormat("[GRID DB] : Error deleting region info, error is : {0}", e.Message); - return DataResponse.RESPONSE_ERROR; - } - } - } - - #endregion - - #region Methods that are not used or deprecated (still needed because of base class) - - /// - /// DEPRECATED. Attempts to authenticate a region by comparing a shared secret. - /// - /// The UUID of the challenger - /// The attempted regionHandle of the challenger - /// The secret - /// Whether the secret and regionhandle match the database entry for UUID - override public bool AuthenticateSim(UUID uuid, ulong handle, string authkey) - { - bool throwHissyFit = false; // Should be true by 1.0 - - if (throwHissyFit) - throw new Exception("CRYPTOWEAK AUTHENTICATE: Refusing to authenticate due to replay potential."); - - RegionProfileData data = GetProfileByUUID(uuid); - - return (handle == data.regionHandle && authkey == data.regionSecret); - } - - /// - /// NOT YET FUNCTIONAL. Provides a cryptographic authentication of a region - /// - /// This requires a security audit. - /// - /// - /// - /// - /// - public bool AuthenticateSim(UUID uuid, ulong handle, string authhash, string challenge) - { - // SHA512Managed HashProvider = new SHA512Managed(); - // Encoding TextProvider = new UTF8Encoding(); - - // byte[] stream = TextProvider.GetBytes(uuid.ToString() + ":" + handle.ToString() + ":" + challenge); - // byte[] hash = HashProvider.ComputeHash(stream); - return false; - } - - /// - /// NOT IMPLEMENTED - /// WHEN IS THIS GONNA BE IMPLEMENTED. - /// - /// - /// - /// null - override public ReservationData GetReservationAtPoint(uint x, uint y) - { - return null; - } - - #endregion - - #region private methods - - /// - /// Reads a region row from a database reader - /// - /// An active database reader - /// A region profile - private static RegionProfileData ReadSimRow(IDataRecord reader) - { - RegionProfileData retval = new RegionProfileData(); - - // Region Main gotta-have-or-we-return-null parts - UInt64 tmp64; - if (!UInt64.TryParse(reader["regionHandle"].ToString(), out tmp64)) - { - return null; - } - - retval.regionHandle = tmp64; - -// UUID tmp_uuid; -// if (!UUID.TryParse((string)reader["uuid"], out tmp_uuid)) -// { -// return null; -// } - - retval.UUID = new UUID((Guid)reader["uuid"]); // tmp_uuid; - - // non-critical parts - retval.regionName = reader["regionName"].ToString(); - retval.originUUID = new UUID((Guid)reader["originUUID"]); - - // Secrets - retval.regionRecvKey = reader["regionRecvKey"].ToString(); - retval.regionSecret = reader["regionSecret"].ToString(); - retval.regionSendKey = reader["regionSendKey"].ToString(); - - // Region Server - retval.regionDataURI = reader["regionDataURI"].ToString(); - retval.regionOnline = false; // Needs to be pinged before this can be set. - retval.serverIP = reader["serverIP"].ToString(); - retval.serverPort = Convert.ToUInt32(reader["serverPort"]); - retval.serverURI = reader["serverURI"].ToString(); - retval.httpPort = Convert.ToUInt32(reader["serverHttpPort"].ToString()); - retval.remotingPort = Convert.ToUInt32(reader["serverRemotingPort"].ToString()); - - // Location - retval.regionLocX = Convert.ToUInt32(reader["locX"].ToString()); - retval.regionLocY = Convert.ToUInt32(reader["locY"].ToString()); - retval.regionLocZ = Convert.ToUInt32(reader["locZ"].ToString()); - - // Neighbours - 0 = No Override - retval.regionEastOverrideHandle = Convert.ToUInt64(reader["eastOverrideHandle"].ToString()); - retval.regionWestOverrideHandle = Convert.ToUInt64(reader["westOverrideHandle"].ToString()); - retval.regionSouthOverrideHandle = Convert.ToUInt64(reader["southOverrideHandle"].ToString()); - retval.regionNorthOverrideHandle = Convert.ToUInt64(reader["northOverrideHandle"].ToString()); - - // Assets - retval.regionAssetURI = reader["regionAssetURI"].ToString(); - retval.regionAssetRecvKey = reader["regionAssetRecvKey"].ToString(); - retval.regionAssetSendKey = reader["regionAssetSendKey"].ToString(); - - // Userserver - retval.regionUserURI = reader["regionUserURI"].ToString(); - retval.regionUserRecvKey = reader["regionUserRecvKey"].ToString(); - retval.regionUserSendKey = reader["regionUserSendKey"].ToString(); - - // World Map Addition - retval.regionMapTextureID = new UUID((Guid)reader["regionMapTexture"]); - retval.owner_uuid = new UUID((Guid)reader["owner_uuid"]); - retval.maturity = Convert.ToUInt32(reader["access"]); - return retval; - } - - /// - /// Update the specified region in the database - /// - /// The profile to update - /// success ? - private bool UpdateRegionRow(RegionProfileData profile) - { - bool returnval = false; - - //Insert new region - string sql = - "UPDATE " + m_regionsTableName + @" SET - [regionHandle]=@regionHandle, [regionName]=@regionName, - [regionRecvKey]=@regionRecvKey, [regionSecret]=@regionSecret, [regionSendKey]=@regionSendKey, - [regionDataURI]=@regionDataURI, [serverIP]=@serverIP, [serverPort]=@serverPort, [serverURI]=@serverURI, - [locX]=@locX, [locY]=@locY, [locZ]=@locZ, [eastOverrideHandle]=@eastOverrideHandle, - [westOverrideHandle]=@westOverrideHandle, [southOverrideHandle]=@southOverrideHandle, - [northOverrideHandle]=@northOverrideHandle, [regionAssetURI]=@regionAssetURI, - [regionAssetRecvKey]=@regionAssetRecvKey, [regionAssetSendKey]=@regionAssetSendKey, - [regionUserURI]=@regionUserURI, [regionUserRecvKey]=@regionUserRecvKey, [regionUserSendKey]=@regionUserSendKey, - [regionMapTexture]=@regionMapTexture, [serverHttpPort]=@serverHttpPort, - [serverRemotingPort]=@serverRemotingPort, [owner_uuid]=@owner_uuid , [originUUID]=@originUUID - where [uuid]=@uuid"; - - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("regionHandle", profile.regionHandle)); - command.Parameters.Add(database.CreateParameter("regionName", profile.regionName)); - command.Parameters.Add(database.CreateParameter("uuid", profile.UUID)); - command.Parameters.Add(database.CreateParameter("regionRecvKey", profile.regionRecvKey)); - command.Parameters.Add(database.CreateParameter("regionSecret", profile.regionSecret)); - command.Parameters.Add(database.CreateParameter("regionSendKey", profile.regionSendKey)); - command.Parameters.Add(database.CreateParameter("regionDataURI", profile.regionDataURI)); - command.Parameters.Add(database.CreateParameter("serverIP", profile.serverIP)); - command.Parameters.Add(database.CreateParameter("serverPort", profile.serverPort)); - command.Parameters.Add(database.CreateParameter("serverURI", profile.serverURI)); - command.Parameters.Add(database.CreateParameter("locX", profile.regionLocX)); - command.Parameters.Add(database.CreateParameter("locY", profile.regionLocY)); - command.Parameters.Add(database.CreateParameter("locZ", profile.regionLocZ)); - command.Parameters.Add(database.CreateParameter("eastOverrideHandle", profile.regionEastOverrideHandle)); - command.Parameters.Add(database.CreateParameter("westOverrideHandle", profile.regionWestOverrideHandle)); - command.Parameters.Add(database.CreateParameter("northOverrideHandle", profile.regionNorthOverrideHandle)); - command.Parameters.Add(database.CreateParameter("southOverrideHandle", profile.regionSouthOverrideHandle)); - command.Parameters.Add(database.CreateParameter("regionAssetURI", profile.regionAssetURI)); - command.Parameters.Add(database.CreateParameter("regionAssetRecvKey", profile.regionAssetRecvKey)); - command.Parameters.Add(database.CreateParameter("regionAssetSendKey", profile.regionAssetSendKey)); - command.Parameters.Add(database.CreateParameter("regionUserURI", profile.regionUserURI)); - command.Parameters.Add(database.CreateParameter("regionUserRecvKey", profile.regionUserRecvKey)); - command.Parameters.Add(database.CreateParameter("regionUserSendKey", profile.regionUserSendKey)); - command.Parameters.Add(database.CreateParameter("regionMapTexture", profile.regionMapTextureID)); - command.Parameters.Add(database.CreateParameter("serverHttpPort", profile.httpPort)); - command.Parameters.Add(database.CreateParameter("serverRemotingPort", profile.remotingPort)); - command.Parameters.Add(database.CreateParameter("owner_uuid", profile.owner_uuid)); - command.Parameters.Add(database.CreateParameter("originUUID", profile.originUUID)); - - try - { - command.ExecuteNonQuery(); - returnval = true; - } - catch (Exception e) - { - m_log.Error("[GRID DB] : Error updating region, error: " + e.Message); - } - } - - return returnval; - } - - /// - /// Creates a new region in the database - /// - /// The region profile to insert - /// Successful? - private bool InsertRegionRow(RegionProfileData profile) - { - bool returnval = false; - - //Insert new region - string sql = - "INSERT INTO " + m_regionsTableName + @" ([regionHandle], [regionName], [uuid], [regionRecvKey], [regionSecret], [regionSendKey], [regionDataURI], - [serverIP], [serverPort], [serverURI], [locX], [locY], [locZ], [eastOverrideHandle], [westOverrideHandle], - [southOverrideHandle], [northOverrideHandle], [regionAssetURI], [regionAssetRecvKey], [regionAssetSendKey], - [regionUserURI], [regionUserRecvKey], [regionUserSendKey], [regionMapTexture], [serverHttpPort], - [serverRemotingPort], [owner_uuid], [originUUID], [access]) - VALUES (@regionHandle, @regionName, @uuid, @regionRecvKey, @regionSecret, @regionSendKey, @regionDataURI, - @serverIP, @serverPort, @serverURI, @locX, @locY, @locZ, @eastOverrideHandle, @westOverrideHandle, - @southOverrideHandle, @northOverrideHandle, @regionAssetURI, @regionAssetRecvKey, @regionAssetSendKey, - @regionUserURI, @regionUserRecvKey, @regionUserSendKey, @regionMapTexture, @serverHttpPort, @serverRemotingPort, @owner_uuid, @originUUID, @access);"; - - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("regionHandle", profile.regionHandle)); - command.Parameters.Add(database.CreateParameter("regionName", profile.regionName)); - command.Parameters.Add(database.CreateParameter("uuid", profile.UUID)); - command.Parameters.Add(database.CreateParameter("regionRecvKey", profile.regionRecvKey)); - command.Parameters.Add(database.CreateParameter("regionSecret", profile.regionSecret)); - command.Parameters.Add(database.CreateParameter("regionSendKey", profile.regionSendKey)); - command.Parameters.Add(database.CreateParameter("regionDataURI", profile.regionDataURI)); - command.Parameters.Add(database.CreateParameter("serverIP", profile.serverIP)); - command.Parameters.Add(database.CreateParameter("serverPort", profile.serverPort)); - command.Parameters.Add(database.CreateParameter("serverURI", profile.serverURI)); - command.Parameters.Add(database.CreateParameter("locX", profile.regionLocX)); - command.Parameters.Add(database.CreateParameter("locY", profile.regionLocY)); - command.Parameters.Add(database.CreateParameter("locZ", profile.regionLocZ)); - command.Parameters.Add(database.CreateParameter("eastOverrideHandle", profile.regionEastOverrideHandle)); - command.Parameters.Add(database.CreateParameter("westOverrideHandle", profile.regionWestOverrideHandle)); - command.Parameters.Add(database.CreateParameter("northOverrideHandle", profile.regionNorthOverrideHandle)); - command.Parameters.Add(database.CreateParameter("southOverrideHandle", profile.regionSouthOverrideHandle)); - command.Parameters.Add(database.CreateParameter("regionAssetURI", profile.regionAssetURI)); - command.Parameters.Add(database.CreateParameter("regionAssetRecvKey", profile.regionAssetRecvKey)); - command.Parameters.Add(database.CreateParameter("regionAssetSendKey", profile.regionAssetSendKey)); - command.Parameters.Add(database.CreateParameter("regionUserURI", profile.regionUserURI)); - command.Parameters.Add(database.CreateParameter("regionUserRecvKey", profile.regionUserRecvKey)); - command.Parameters.Add(database.CreateParameter("regionUserSendKey", profile.regionUserSendKey)); - command.Parameters.Add(database.CreateParameter("regionMapTexture", profile.regionMapTextureID)); - command.Parameters.Add(database.CreateParameter("serverHttpPort", profile.httpPort)); - command.Parameters.Add(database.CreateParameter("serverRemotingPort", profile.remotingPort)); - command.Parameters.Add(database.CreateParameter("owner_uuid", profile.owner_uuid)); - command.Parameters.Add(database.CreateParameter("originUUID", profile.originUUID)); - command.Parameters.Add(database.CreateParameter("access", profile.maturity)); - - try - { - command.ExecuteNonQuery(); - returnval = true; - } - catch (Exception e) - { - m_log.Error("[GRID DB] : Error inserting region, error: " + e.Message); - } - } - - return returnval; - } - - #endregion - } -} diff --git a/OpenSim/Data/MSSQL/MSSQLLogData.cs b/OpenSim/Data/MSSQL/MSSQLLogData.cs deleted file mode 100644 index 72c50e6..0000000 --- a/OpenSim/Data/MSSQL/MSSQLLogData.cs +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Reflection; -using log4net; -using OpenSim.Framework; - -namespace OpenSim.Data.MSSQL -{ - /// - /// An interface to the log database for MSSQL - /// - internal class MSSQLLogData : ILogDataPlugin - { - private const string _migrationStore = "LogStore"; - - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - /// - /// The database manager - /// - public MSSQLManager database; - - [Obsolete("Cannot be default-initialized!")] - public void Initialise() - { - m_log.Info("[LOG DB]: " + Name + " cannot be default-initialized!"); - throw new PluginNotInitialisedException (Name); - } - - /// - /// Artificial constructor called when the plugin is loaded - /// - public void Initialise(string connect) - { - if (!string.IsNullOrEmpty(connect)) - { - database = new MSSQLManager(connect); - } - else - { - // TODO: do something with the connect string - IniFile gridDataMSSqlFile = new IniFile("mssql_connection.ini"); - string settingDataSource = gridDataMSSqlFile.ParseFileReadValue("data_source"); - string settingInitialCatalog = gridDataMSSqlFile.ParseFileReadValue("initial_catalog"); - string settingPersistSecurityInfo = gridDataMSSqlFile.ParseFileReadValue("persist_security_info"); - string settingUserId = gridDataMSSqlFile.ParseFileReadValue("user_id"); - string settingPassword = gridDataMSSqlFile.ParseFileReadValue("password"); - - database = - new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId, - settingPassword); - } - - //Updating mechanisme - database.CheckMigration(_migrationStore); - } - - /// - /// Saves a log item to the database - /// - /// The daemon triggering the event - /// The target of the action (region / agent UUID, etc) - /// The method call where the problem occured - /// The arguments passed to the method - /// How critical is this? - /// The message to log - public void saveLog(string serverDaemon, string target, string methodCall, string arguments, int priority, - string logMessage) - { - string sql = "INSERT INTO logs ([target], [server], [method], [arguments], [priority], [message]) VALUES "; - sql += "(@target, @server, @method, @arguments, @priority, @message);"; - - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("server", serverDaemon)); - command.Parameters.Add(database.CreateParameter("target",target)); - command.Parameters.Add(database.CreateParameter("method", methodCall)); - command.Parameters.Add(database.CreateParameter("arguments", arguments)); - command.Parameters.Add(database.CreateParameter("priority", priority.ToString())); - command.Parameters.Add(database.CreateParameter("message", logMessage)); - - try - { - command.ExecuteNonQuery(); - } - catch (Exception e) - { - //Are we not in a loop here - m_log.Error("[LOG DB] Error logging : " + e.Message); - } - } - } - - /// - /// Returns the name of this DB provider - /// - /// A string containing the DB provider name - public string Name - { - get { return "MSSQL Logdata Interface"; } - } - - /// - /// Closes the database provider - /// - public void Dispose() - { - database = null; - } - - /// - /// Returns the version of this DB provider - /// - /// A string containing the provider version - public string Version - { - get { return "0.1"; } - } - } -} diff --git a/OpenSim/Data/MSSQL/MSSQLUserData.cs b/OpenSim/Data/MSSQL/MSSQLUserData.cs deleted file mode 100644 index 3ef1053..0000000 --- a/OpenSim/Data/MSSQL/MSSQLUserData.cs +++ /dev/null @@ -1,1214 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; -using System.Data.SqlClient; -using System.Reflection; -using log4net; -using OpenMetaverse; -using OpenSim.Framework; - -namespace OpenSim.Data.MSSQL -{ - /// - /// A database interface class to a user profile storage system - /// - public class MSSQLUserData : UserDataBase - { - private const string _migrationStore = "UserStore"; - - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - /// - /// Database manager for MSSQL - /// - public MSSQLManager database; - - private const string m_agentsTableName = "agents"; - private const string m_usersTableName = "users"; - private const string m_userFriendsTableName = "userfriends"; - - // [Obsolete("Cannot be default-initialized!")] - override public void Initialise() - { - m_log.Info("[MSSQLUserData]: " + Name + " cannot be default-initialized!"); - throw new PluginNotInitialisedException(Name); - } - - /// - /// Loads and initialises the MSSQL storage plugin - /// - /// connectionstring - /// use mssql_connection.ini - override public void Initialise(string connect) - { - if (!string.IsNullOrEmpty(connect)) - { - database = new MSSQLManager(connect); - } - else - { - IniFile iniFile = new IniFile("mssql_connection.ini"); - - string settingDataSource = iniFile.ParseFileReadValue("data_source"); - string settingInitialCatalog = iniFile.ParseFileReadValue("initial_catalog"); - string settingPersistSecurityInfo = iniFile.ParseFileReadValue("persist_security_info"); - string settingUserId = iniFile.ParseFileReadValue("user_id"); - string settingPassword = iniFile.ParseFileReadValue("password"); - - database = new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId, settingPassword); - } - - //Check migration on DB - database.CheckMigration(_migrationStore); - } - - /// - /// Releases unmanaged and - optionally - managed resources - /// - override public void Dispose() { } - - #region User table methods - - /// - /// Searches the database for a specified user profile by name components - /// - /// The first part of the account name - /// The second part of the account name - /// A user profile - override public UserProfileData GetUserByName(string user, string last) - { - string sql = string.Format(@"SELECT * FROM {0} - WHERE username = @first AND lastname = @second", m_usersTableName); - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("first", user)); - command.Parameters.Add(database.CreateParameter("second", last)); - try - { - using (SqlDataReader reader = command.ExecuteReader()) - { - return ReadUserRow(reader); - } - } - catch (Exception e) - { - m_log.ErrorFormat("[USER DB] Error getting user profile for {0} {1}: {2}", user, last, e.Message); - return null; - } - } - } - - /// - /// See IUserDataPlugin - /// - /// - /// - override public UserProfileData GetUserByUUID(UUID uuid) - { - string sql = string.Format("SELECT * FROM {0} WHERE UUID = @uuid", m_usersTableName); - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("uuid", uuid)); - try - { - using (SqlDataReader reader = command.ExecuteReader()) - { - return ReadUserRow(reader); - } - } - catch (Exception e) - { - m_log.ErrorFormat("[USER DB] Error getting user profile by UUID {0}, error: {1}", uuid, e.Message); - return null; - } - } - } - - - /// - /// Creates a new users profile - /// - /// The user profile to create - override public void AddNewUserProfile(UserProfileData user) - { - try - { - InsertUserRow(user.ID, user.FirstName, user.SurName, user.Email, user.PasswordHash, user.PasswordSalt, - user.HomeRegion, user.HomeLocation.X, user.HomeLocation.Y, - user.HomeLocation.Z, - user.HomeLookAt.X, user.HomeLookAt.Y, user.HomeLookAt.Z, user.Created, - user.LastLogin, user.UserInventoryURI, user.UserAssetURI, - user.CanDoMask, user.WantDoMask, - user.AboutText, user.FirstLifeAboutText, user.Image, - user.FirstLifeImage, user.WebLoginKey, user.HomeRegionID, - user.GodLevel, user.UserFlags, user.CustomType, user.Partner); - } - catch (Exception e) - { - m_log.ErrorFormat("[USER DB] Error adding new profile, error: {0}", e.Message); - } - } - - /// - /// update a user profile - /// - /// the profile to update - /// - override public bool UpdateUserProfile(UserProfileData user) - { - string sql = string.Format(@"UPDATE {0} - SET UUID = @uuid, - username = @username, - lastname = @lastname, - email = @email, - passwordHash = @passwordHash, - passwordSalt = @passwordSalt, - homeRegion = @homeRegion, - homeLocationX = @homeLocationX, - homeLocationY = @homeLocationY, - homeLocationZ = @homeLocationZ, - homeLookAtX = @homeLookAtX, - homeLookAtY = @homeLookAtY, - homeLookAtZ = @homeLookAtZ, - created = @created, - lastLogin = @lastLogin, - userInventoryURI = @userInventoryURI, - userAssetURI = @userAssetURI, - profileCanDoMask = @profileCanDoMask, - profileWantDoMask = @profileWantDoMask, - profileAboutText = @profileAboutText, - profileFirstText = @profileFirstText, - profileImage = @profileImage, - profileFirstImage = @profileFirstImage, - webLoginKey = @webLoginKey, - homeRegionID = @homeRegionID, - userFlags = @userFlags, - godLevel = @godLevel, - customType = @customType, - partner = @partner WHERE UUID = @keyUUUID;",m_usersTableName); - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("uuid", user.ID)); - command.Parameters.Add(database.CreateParameter("username", user.FirstName)); - command.Parameters.Add(database.CreateParameter("lastname", user.SurName)); - command.Parameters.Add(database.CreateParameter("email", user.Email)); - command.Parameters.Add(database.CreateParameter("passwordHash", user.PasswordHash)); - command.Parameters.Add(database.CreateParameter("passwordSalt", user.PasswordSalt)); - command.Parameters.Add(database.CreateParameter("homeRegion", user.HomeRegion)); - command.Parameters.Add(database.CreateParameter("homeLocationX", user.HomeLocation.X)); - command.Parameters.Add(database.CreateParameter("homeLocationY", user.HomeLocation.Y)); - command.Parameters.Add(database.CreateParameter("homeLocationZ", user.HomeLocation.Z)); - command.Parameters.Add(database.CreateParameter("homeLookAtX", user.HomeLookAt.X)); - command.Parameters.Add(database.CreateParameter("homeLookAtY", user.HomeLookAt.Y)); - command.Parameters.Add(database.CreateParameter("homeLookAtZ", user.HomeLookAt.Z)); - command.Parameters.Add(database.CreateParameter("created", user.Created)); - command.Parameters.Add(database.CreateParameter("lastLogin", user.LastLogin)); - command.Parameters.Add(database.CreateParameter("userInventoryURI", user.UserInventoryURI)); - command.Parameters.Add(database.CreateParameter("userAssetURI", user.UserAssetURI)); - command.Parameters.Add(database.CreateParameter("profileCanDoMask", user.CanDoMask)); - command.Parameters.Add(database.CreateParameter("profileWantDoMask", user.WantDoMask)); - command.Parameters.Add(database.CreateParameter("profileAboutText", user.AboutText)); - command.Parameters.Add(database.CreateParameter("profileFirstText", user.FirstLifeAboutText)); - command.Parameters.Add(database.CreateParameter("profileImage", user.Image)); - command.Parameters.Add(database.CreateParameter("profileFirstImage", user.FirstLifeImage)); - command.Parameters.Add(database.CreateParameter("webLoginKey", user.WebLoginKey)); - command.Parameters.Add(database.CreateParameter("homeRegionID", user.HomeRegionID)); - command.Parameters.Add(database.CreateParameter("userFlags", user.UserFlags)); - command.Parameters.Add(database.CreateParameter("godLevel", user.GodLevel)); - command.Parameters.Add(database.CreateParameter("customType", user.CustomType)); - command.Parameters.Add(database.CreateParameter("partner", user.Partner)); - command.Parameters.Add(database.CreateParameter("keyUUUID", user.ID)); - - try - { - int affected = command.ExecuteNonQuery(); - return (affected != 0); - } - catch (Exception e) - { - m_log.ErrorFormat("[USER DB] Error updating profile, error: {0}", e.Message); - } - } - return false; - } - - #endregion - - #region Agent table methods - - /// - /// Returns a user session searching by name - /// - /// The account name - /// The users session - override public UserAgentData GetAgentByName(string name) - { - return GetAgentByName(name.Split(' ')[0], name.Split(' ')[1]); - } - - /// - /// Returns a user session by account name - /// - /// First part of the users account name - /// Second part of the users account name - /// The users session - override public UserAgentData GetAgentByName(string user, string last) - { - UserProfileData profile = GetUserByName(user, last); - return GetAgentByUUID(profile.ID); - } - - /// - /// Returns an agent session by account UUID - /// - /// The accounts UUID - /// The users session - override public UserAgentData GetAgentByUUID(UUID uuid) - { - string sql = string.Format("SELECT * FROM {0} WHERE UUID = @uuid", m_agentsTableName); - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("uuid", uuid)); - try - { - using (SqlDataReader reader = command.ExecuteReader()) - { - return readAgentRow(reader); - } - } - catch (Exception e) - { - m_log.ErrorFormat("[USER DB] Error updating agentdata by UUID, error: {0}", e.Message); - return null; - } - } - } - - /// - /// Creates a new agent - /// - /// The agent to create - override public void AddNewUserAgent(UserAgentData agent) - { - try - { - InsertUpdateAgentRow(agent); - } - catch (Exception e) - { - m_log.ErrorFormat("[USER DB] Error adding new agentdata, error: {0}", e.Message); - } - } - - #endregion - - #region User Friends List Data - - /// - /// Add a new friend in the friendlist - /// - /// UUID of the friendlist owner - /// Friend's UUID - /// Permission flag - override public void AddNewUserFriend(UUID friendlistowner, UUID friend, uint perms) - { - int dtvalue = Util.UnixTimeSinceEpoch(); - string sql = string.Format(@"INSERT INTO {0} - (ownerID,friendID,friendPerms,datetimestamp) - VALUES - (@ownerID,@friendID,@friendPerms,@datetimestamp)", m_userFriendsTableName); - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("ownerID", friendlistowner)); - command.Parameters.Add(database.CreateParameter("friendID", friend)); - command.Parameters.Add(database.CreateParameter("friendPerms", perms)); - command.Parameters.Add(database.CreateParameter("datetimestamp", dtvalue)); - command.ExecuteNonQuery(); - - try - { - sql = string.Format(@"INSERT INTO {0} - (ownerID,friendID,friendPerms,datetimestamp) - VALUES - (@friendID,@ownerID,@friendPerms,@datetimestamp)", m_userFriendsTableName); - command.CommandText = sql; - command.ExecuteNonQuery(); - } - catch (Exception e) - { - m_log.ErrorFormat("[USER DB] Error adding new userfriend, error: {0}", e.Message); - return; - } - } - } - - /// - /// Remove an friend from the friendlist - /// - /// UUID of the friendlist owner - /// UUID of the not-so-friendly user to remove from the list - override public void RemoveUserFriend(UUID friendlistowner, UUID friend) - { - string sql = string.Format(@"DELETE from {0} - WHERE ownerID = @ownerID - AND friendID = @friendID", m_userFriendsTableName); - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("@ownerID", friendlistowner)); - command.Parameters.Add(database.CreateParameter("@friendID", friend)); - command.ExecuteNonQuery(); - sql = string.Format(@"DELETE from {0} - WHERE ownerID = @friendID - AND friendID = @ownerID", m_userFriendsTableName); - command.CommandText = sql; - try - { - command.ExecuteNonQuery(); - } - catch (Exception e) - { - m_log.ErrorFormat("[USER DB] Error removing userfriend, error: {0}", e.Message); - } - } - } - - /// - /// Update friendlist permission flag for a friend - /// - /// UUID of the friendlist owner - /// UUID of the friend - /// new permission flag - override public void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms) - { - string sql = string.Format(@"UPDATE {0} SET friendPerms = @friendPerms - WHERE ownerID = @ownerID - AND friendID = @friendID", m_userFriendsTableName); - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("@ownerID", friendlistowner)); - command.Parameters.Add(database.CreateParameter("@friendID", friend)); - command.Parameters.Add(database.CreateParameter("@friendPerms", perms)); - - try - { - command.ExecuteNonQuery(); - } - catch (Exception e) - { - m_log.ErrorFormat("[USER DB] Error updating userfriend, error: {0}", e.Message); - } - } - } - - /// - /// Get (fetch?) the user's friendlist - /// - /// UUID of the friendlist owner - /// Friendlist list - override public List GetUserFriendList(UUID friendlistowner) - { - List friendList = new List(); - - //Left Join userfriends to itself - string sql = string.Format(@"SELECT a.ownerID, a.friendID, a.friendPerms, b.friendPerms AS ownerperms - FROM {0} as a, {0} as b - WHERE a.ownerID = @ownerID - AND b.ownerID = a.friendID - AND b.friendID = a.ownerID", m_userFriendsTableName); - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("@ownerID", friendlistowner)); - try - { - using (SqlDataReader reader = command.ExecuteReader()) - { - while (reader.Read()) - { - FriendListItem fli = new FriendListItem(); - fli.FriendListOwner = new UUID((Guid)reader["ownerID"]); - fli.Friend = new UUID((Guid)reader["friendID"]); - fli.FriendPerms = (uint)Convert.ToInt32(reader["friendPerms"]); - - // This is not a real column in the database table, it's a joined column from the opposite record - fli.FriendListOwnerPerms = (uint)Convert.ToInt32(reader["ownerperms"]); - friendList.Add(fli); - } - } - } - catch (Exception e) - { - m_log.ErrorFormat("[USER DB] Error updating userfriend, error: {0}", e.Message); - } - } - return friendList; - } - - override public Dictionary GetFriendRegionInfos (List uuids) - { - Dictionary infos = new Dictionary(); - try - { - foreach (UUID uuid in uuids) - { - string sql = string.Format(@"SELECT agentOnline,currentHandle - FROM {0} WHERE UUID = @uuid", m_agentsTableName); - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("@uuid", uuid)); - using (SqlDataReader reader = command.ExecuteReader()) - { - while (reader.Read()) - { - FriendRegionInfo fri = new FriendRegionInfo(); - fri.isOnline = (byte)reader["agentOnline"] != 0; - fri.regionHandle = Convert.ToUInt64(reader["currentHandle"].ToString()); - - infos[uuid] = fri; - } - } - } - } - } - catch (Exception e) - { - m_log.Warn("[MSSQL]: Got exception on trying to find friends regions:", e); - } - - return infos; - } - #endregion - - #region Money functions (not used) - - /// - /// Performs a money transfer request between two accounts - /// - /// The senders account ID - /// The receivers account ID - /// The amount to transfer - /// false - override public bool MoneyTransferRequest(UUID from, UUID to, uint amount) - { - return false; - } - - /// - /// Performs an inventory transfer request between two accounts - /// - /// TODO: Move to inventory server - /// The senders account ID - /// The receivers account ID - /// The item to transfer - /// false - override public bool InventoryTransferRequest(UUID from, UUID to, UUID item) - { - return false; - } - - #endregion - - #region Appearance methods - - /// - /// Gets the user appearance. - /// - /// The user. - /// - override public AvatarAppearance GetUserAppearance(UUID user) - { - try - { - AvatarAppearance appearance = new AvatarAppearance(); - string sql = "SELECT * FROM avatarappearance WHERE owner = @UUID"; - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("@UUID", user)); - using (SqlDataReader reader = command.ExecuteReader()) - { - if (reader.Read()) - appearance = readUserAppearance(reader); - else - { - m_log.WarnFormat("[USER DB] No appearance found for user {0}", user.ToString()); - return null; - } - - } - } - - appearance.SetAttachments(GetUserAttachments(user)); - - return appearance; - } - catch (Exception e) - { - m_log.ErrorFormat("[USER DB] Error updating userfriend, error: {0}", e.Message); - } - return null; - } - - /// - /// Update a user appearence into database - /// - /// the used UUID - /// the appearence - override public void UpdateUserAppearance(UUID user, AvatarAppearance appearance) - { - string sql = @"DELETE FROM avatarappearance WHERE owner=@owner; - INSERT INTO avatarappearance - (owner, serial, visual_params, texture, avatar_height, - body_item, body_asset, skin_item, skin_asset, hair_item, - hair_asset, eyes_item, eyes_asset, shirt_item, shirt_asset, - pants_item, pants_asset, shoes_item, shoes_asset, socks_item, - socks_asset, jacket_item, jacket_asset, gloves_item, gloves_asset, - undershirt_item, undershirt_asset, underpants_item, underpants_asset, - skirt_item, skirt_asset) - VALUES - (@owner, @serial, @visual_params, @texture, @avatar_height, - @body_item, @body_asset, @skin_item, @skin_asset, @hair_item, - @hair_asset, @eyes_item, @eyes_asset, @shirt_item, @shirt_asset, - @pants_item, @pants_asset, @shoes_item, @shoes_asset, @socks_item, - @socks_asset, @jacket_item, @jacket_asset, @gloves_item, @gloves_asset, - @undershirt_item, @undershirt_asset, @underpants_item, @underpants_asset, - @skirt_item, @skirt_asset)"; - - using (AutoClosingSqlCommand cmd = database.Query(sql)) - { - cmd.Parameters.Add(database.CreateParameter("@owner", appearance.Owner)); - cmd.Parameters.Add(database.CreateParameter("@serial", appearance.Serial)); - cmd.Parameters.Add(database.CreateParameter("@visual_params", appearance.VisualParams)); - cmd.Parameters.Add(database.CreateParameter("@texture", appearance.Texture.GetBytes())); - cmd.Parameters.Add(database.CreateParameter("@avatar_height", appearance.AvatarHeight)); - cmd.Parameters.Add(database.CreateParameter("@body_item", appearance.BodyItem)); - cmd.Parameters.Add(database.CreateParameter("@body_asset", appearance.BodyAsset)); - cmd.Parameters.Add(database.CreateParameter("@skin_item", appearance.SkinItem)); - cmd.Parameters.Add(database.CreateParameter("@skin_asset", appearance.SkinAsset)); - cmd.Parameters.Add(database.CreateParameter("@hair_item", appearance.HairItem)); - cmd.Parameters.Add(database.CreateParameter("@hair_asset", appearance.HairAsset)); - cmd.Parameters.Add(database.CreateParameter("@eyes_item", appearance.EyesItem)); - cmd.Parameters.Add(database.CreateParameter("@eyes_asset", appearance.EyesAsset)); - cmd.Parameters.Add(database.CreateParameter("@shirt_item", appearance.ShirtItem)); - cmd.Parameters.Add(database.CreateParameter("@shirt_asset", appearance.ShirtAsset)); - cmd.Parameters.Add(database.CreateParameter("@pants_item", appearance.PantsItem)); - cmd.Parameters.Add(database.CreateParameter("@pants_asset", appearance.PantsAsset)); - cmd.Parameters.Add(database.CreateParameter("@shoes_item", appearance.ShoesItem)); - cmd.Parameters.Add(database.CreateParameter("@shoes_asset", appearance.ShoesAsset)); - cmd.Parameters.Add(database.CreateParameter("@socks_item", appearance.SocksItem)); - cmd.Parameters.Add(database.CreateParameter("@socks_asset", appearance.SocksAsset)); - cmd.Parameters.Add(database.CreateParameter("@jacket_item", appearance.JacketItem)); - cmd.Parameters.Add(database.CreateParameter("@jacket_asset", appearance.JacketAsset)); - cmd.Parameters.Add(database.CreateParameter("@gloves_item", appearance.GlovesItem)); - cmd.Parameters.Add(database.CreateParameter("@gloves_asset", appearance.GlovesAsset)); - cmd.Parameters.Add(database.CreateParameter("@undershirt_item", appearance.UnderShirtItem)); - cmd.Parameters.Add(database.CreateParameter("@undershirt_asset", appearance.UnderShirtAsset)); - cmd.Parameters.Add(database.CreateParameter("@underpants_item", appearance.UnderPantsItem)); - cmd.Parameters.Add(database.CreateParameter("@underpants_asset", appearance.UnderPantsAsset)); - cmd.Parameters.Add(database.CreateParameter("@skirt_item", appearance.SkirtItem)); - cmd.Parameters.Add(database.CreateParameter("@skirt_asset", appearance.SkirtAsset)); - - try - { - cmd.ExecuteNonQuery(); - } - catch (Exception e) - { - m_log.ErrorFormat("[USER DB] Error updating user appearance, error: {0}", e.Message); - } - } - UpdateUserAttachments(user, appearance.GetAttachments()); - } - - #endregion - - #region Attachment methods - - /// - /// Gets all attachment of a agent. - /// - /// agent ID. - /// - public Hashtable GetUserAttachments(UUID agentID) - { - Hashtable returnTable = new Hashtable(); - string sql = "select attachpoint, item, asset from avatarattachments where UUID = @uuid"; - using (AutoClosingSqlCommand command = database.Query(sql, database.CreateParameter("@uuid", agentID))) - { - using (SqlDataReader reader = command.ExecuteReader()) - { - while (reader.Read()) - { - int attachpoint = Convert.ToInt32(reader["attachpoint"]); - if (returnTable.ContainsKey(attachpoint)) - continue; - Hashtable item = new Hashtable(); - item.Add("item", reader["item"].ToString()); - item.Add("asset", reader["asset"].ToString()); - - returnTable.Add(attachpoint, item); - } - } - } - return returnTable; - } - - /// - /// Updates all attachments of the agent. - /// - /// agentID. - /// data with all items on attachmentpoints - public void UpdateUserAttachments(UUID agentID, Hashtable data) - { - string sql = "DELETE FROM avatarattachments WHERE UUID = @uuid"; - - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("uuid", agentID)); - command.ExecuteNonQuery(); - } - if (data == null) - return; - - sql = @"INSERT INTO avatarattachments (UUID, attachpoint, item, asset) - VALUES (@uuid, @attachpoint, @item, @asset)"; - - using (AutoClosingSqlCommand command = database.Query(sql)) - { - bool firstTime = true; - foreach (DictionaryEntry e in data) - { - int attachpoint = Convert.ToInt32(e.Key); - - Hashtable item = (Hashtable)e.Value; - - if (firstTime) - { - command.Parameters.Add(database.CreateParameter("@uuid", agentID)); - command.Parameters.Add(database.CreateParameter("@attachpoint", attachpoint)); - command.Parameters.Add(database.CreateParameter("@item", new UUID(item["item"].ToString()))); - command.Parameters.Add(database.CreateParameter("@asset", new UUID(item["asset"].ToString()))); - firstTime = false; - } - command.Parameters["@uuid"].Value = agentID.Guid; //.ToString(); - command.Parameters["@attachpoint"].Value = attachpoint; - command.Parameters["@item"].Value = new Guid(item["item"].ToString()); - command.Parameters["@asset"].Value = new Guid(item["asset"].ToString()); - - try - { - command.ExecuteNonQuery(); - } - catch (Exception ex) - { - m_log.DebugFormat("[USER DB] : Error adding user attachment. {0}", ex.Message); - } - } - } - } - - /// - /// Resets all attachments of a agent in the database. - /// - /// agentID. - override public void ResetAttachments(UUID agentID) - { - string sql = "UPDATE avatarattachments SET asset = '00000000-0000-0000-0000-000000000000' WHERE UUID = @uuid"; - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("uuid", agentID)); - command.ExecuteNonQuery(); - } - } - - override public void LogoutUsers(UUID regionID) - { - } - - #endregion - - #region Other public methods - - /// - /// - /// - /// - /// - /// - override public List GeneratePickerResults(UUID queryID, string query) - { - List returnlist = new List(); - string[] querysplit = query.Split(' '); - if (querysplit.Length == 2) - { - try - { - string sql = string.Format(@"SELECT UUID,username,lastname FROM {0} - WHERE username LIKE @first AND lastname LIKE @second", m_usersTableName); - using (AutoClosingSqlCommand command = database.Query(sql)) - { - //Add wildcard to the search - command.Parameters.Add(database.CreateParameter("first", querysplit[0] + "%")); - command.Parameters.Add(database.CreateParameter("second", querysplit[1] + "%")); - using (SqlDataReader reader = command.ExecuteReader()) - { - while (reader.Read()) - { - AvatarPickerAvatar user = new AvatarPickerAvatar(); - user.AvatarID = new UUID((Guid)reader["UUID"]); - user.firstName = (string)reader["username"]; - user.lastName = (string)reader["lastname"]; - returnlist.Add(user); - } - } - } - } - catch (Exception e) - { - m_log.Error(e.ToString()); - } - } - else if (querysplit.Length == 1) - { - try - { - string sql = string.Format(@"SELECT UUID,username,lastname FROM {0} - WHERE username LIKE @first OR lastname LIKE @first", m_usersTableName); - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("first", querysplit[0] + "%")); - - using (SqlDataReader reader = command.ExecuteReader()) - { - while (reader.Read()) - { - AvatarPickerAvatar user = new AvatarPickerAvatar(); - user.AvatarID = new UUID((Guid)reader["UUID"]); - user.firstName = (string)reader["username"]; - user.lastName = (string)reader["lastname"]; - returnlist.Add(user); - } - } - } - } - catch (Exception e) - { - m_log.Error(e.ToString()); - } - } - return returnlist; - } - - /// - /// Store a weblogin key - /// - /// The agent UUID - /// the WebLogin Key - /// unused ? - override public void StoreWebLoginKey(UUID AgentID, UUID WebLoginKey) - { - UserProfileData user = GetUserByUUID(AgentID); - user.WebLoginKey = WebLoginKey; - UpdateUserProfile(user); - } - - /// - /// Database provider name - /// - /// Provider name - override public string Name - { - get { return "MSSQL Userdata Interface"; } - } - - /// - /// Database provider version - /// - /// provider version - override public string Version - { - get { return database.getVersion(); } - } - - #endregion - - #region Private functions - - /// - /// Reads a one item from an SQL result - /// - /// The SQL Result - /// the item read - private static AvatarAppearance readUserAppearance(SqlDataReader reader) - { - try - { - AvatarAppearance appearance = new AvatarAppearance(); - - appearance.Owner = new UUID((Guid)reader["owner"]); - appearance.Serial = Convert.ToInt32(reader["serial"]); - appearance.VisualParams = (byte[])reader["visual_params"]; - appearance.Texture = new Primitive.TextureEntry((byte[])reader["texture"], 0, ((byte[])reader["texture"]).Length); - appearance.AvatarHeight = (float)Convert.ToDouble(reader["avatar_height"]); - appearance.BodyItem = new UUID((Guid)reader["body_item"]); - appearance.BodyAsset = new UUID((Guid)reader["body_asset"]); - appearance.SkinItem = new UUID((Guid)reader["skin_item"]); - appearance.SkinAsset = new UUID((Guid)reader["skin_asset"]); - appearance.HairItem = new UUID((Guid)reader["hair_item"]); - appearance.HairAsset = new UUID((Guid)reader["hair_asset"]); - appearance.EyesItem = new UUID((Guid)reader["eyes_item"]); - appearance.EyesAsset = new UUID((Guid)reader["eyes_asset"]); - appearance.ShirtItem = new UUID((Guid)reader["shirt_item"]); - appearance.ShirtAsset = new UUID((Guid)reader["shirt_asset"]); - appearance.PantsItem = new UUID((Guid)reader["pants_item"]); - appearance.PantsAsset = new UUID((Guid)reader["pants_asset"]); - appearance.ShoesItem = new UUID((Guid)reader["shoes_item"]); - appearance.ShoesAsset = new UUID((Guid)reader["shoes_asset"]); - appearance.SocksItem = new UUID((Guid)reader["socks_item"]); - appearance.SocksAsset = new UUID((Guid)reader["socks_asset"]); - appearance.JacketItem = new UUID((Guid)reader["jacket_item"]); - appearance.JacketAsset = new UUID((Guid)reader["jacket_asset"]); - appearance.GlovesItem = new UUID((Guid)reader["gloves_item"]); - appearance.GlovesAsset = new UUID((Guid)reader["gloves_asset"]); - appearance.UnderShirtItem = new UUID((Guid)reader["undershirt_item"]); - appearance.UnderShirtAsset = new UUID((Guid)reader["undershirt_asset"]); - appearance.UnderPantsItem = new UUID((Guid)reader["underpants_item"]); - appearance.UnderPantsAsset = new UUID((Guid)reader["underpants_asset"]); - appearance.SkirtItem = new UUID((Guid)reader["skirt_item"]); - appearance.SkirtAsset = new UUID((Guid)reader["skirt_asset"]); - - return appearance; - } - catch (SqlException e) - { - m_log.Error(e.ToString()); - } - - return null; - } - - /// - /// Insert/Update a agent row in the DB. - /// - /// agentdata. - private void InsertUpdateAgentRow(UserAgentData agentdata) - { - string sql = @" - -IF EXISTS (SELECT * FROM agents WHERE UUID = @UUID) - BEGIN - UPDATE agents SET UUID = @UUID, sessionID = @sessionID, secureSessionID = @secureSessionID, agentIP = @agentIP, agentPort = @agentPort, agentOnline = @agentOnline, loginTime = @loginTime, logoutTime = @logoutTime, currentRegion = @currentRegion, currentHandle = @currentHandle, currentPos = @currentPos - WHERE UUID = @UUID - END -ELSE - BEGIN - INSERT INTO - agents (UUID, sessionID, secureSessionID, agentIP, agentPort, agentOnline, loginTime, logoutTime, currentRegion, currentHandle, currentPos) VALUES - (@UUID, @sessionID, @secureSessionID, @agentIP, @agentPort, @agentOnline, @loginTime, @logoutTime, @currentRegion, @currentHandle, @currentPos) - END -"; - - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("@UUID", agentdata.ProfileID)); - command.Parameters.Add(database.CreateParameter("@sessionID", agentdata.SessionID)); - command.Parameters.Add(database.CreateParameter("@secureSessionID", agentdata.SecureSessionID)); - command.Parameters.Add(database.CreateParameter("@agentIP", agentdata.AgentIP)); - command.Parameters.Add(database.CreateParameter("@agentPort", agentdata.AgentPort)); - command.Parameters.Add(database.CreateParameter("@agentOnline", agentdata.AgentOnline)); - command.Parameters.Add(database.CreateParameter("@loginTime", agentdata.LoginTime)); - command.Parameters.Add(database.CreateParameter("@logoutTime", agentdata.LogoutTime)); - command.Parameters.Add(database.CreateParameter("@currentRegion", agentdata.Region)); - command.Parameters.Add(database.CreateParameter("@currentHandle", agentdata.Handle)); - command.Parameters.Add(database.CreateParameter("@currentPos", "<" + ((int)agentdata.Position.X) + "," + ((int)agentdata.Position.Y) + "," + ((int)agentdata.Position.Z) + ">")); - - command.Transaction = command.Connection.BeginTransaction(IsolationLevel.Serializable); - try - { - if (command.ExecuteNonQuery() > 0) - { - command.Transaction.Commit(); - return; - } - - command.Transaction.Rollback(); - return; - } - catch (Exception e) - { - command.Transaction.Rollback(); - m_log.Error(e.ToString()); - return; - } - } - - } - - /// - /// Reads an agent row from a database reader - /// - /// An active database reader - /// A user session agent - private UserAgentData readAgentRow(SqlDataReader reader) - { - UserAgentData retval = new UserAgentData(); - - if (reader.Read()) - { - // Agent IDs - retval.ProfileID = new UUID((Guid)reader["UUID"]); - retval.SessionID = new UUID((Guid)reader["sessionID"]); - retval.SecureSessionID = new UUID((Guid)reader["secureSessionID"]); - - // Agent Who? - retval.AgentIP = (string)reader["agentIP"]; - retval.AgentPort = Convert.ToUInt32(reader["agentPort"].ToString()); - retval.AgentOnline = Convert.ToInt32(reader["agentOnline"].ToString()) != 0; - - // Login/Logout times (UNIX Epoch) - retval.LoginTime = Convert.ToInt32(reader["loginTime"].ToString()); - retval.LogoutTime = Convert.ToInt32(reader["logoutTime"].ToString()); - - // Current position - retval.Region = new UUID((Guid)reader["currentRegion"]); - retval.Handle = Convert.ToUInt64(reader["currentHandle"].ToString()); - Vector3 tmp_v; - Vector3.TryParse((string)reader["currentPos"], out tmp_v); - retval.Position = tmp_v; - - } - else - { - return null; - } - return retval; - } - - /// - /// Creates a new user and inserts it into the database - /// - /// User ID - /// First part of the login - /// Second part of the login - /// Email of person - /// A salted hash of the users password - /// The salt used for the password hash - /// A regionHandle of the users home region - /// Home region position vector - /// Home region position vector - /// Home region position vector - /// Home region 'look at' vector - /// Home region 'look at' vector - /// Home region 'look at' vector - /// Account created (unix timestamp) - /// Last login (unix timestamp) - /// Users inventory URI - /// Users asset URI - /// I can do mask - /// I want to do mask - /// Profile text - /// Firstlife text - /// UUID for profile image - /// UUID for firstlife image - /// web login key - /// homeregion UUID - /// has the user godlevel - /// unknown - /// unknown - /// UUID of partner - /// Success? - private void InsertUserRow(UUID uuid, string username, string lastname, string email, string passwordHash, - string passwordSalt, UInt64 homeRegion, float homeLocX, float homeLocY, float homeLocZ, - float homeLookAtX, float homeLookAtY, float homeLookAtZ, int created, int lastlogin, - string inventoryURI, string assetURI, uint canDoMask, uint wantDoMask, - string aboutText, string firstText, - UUID profileImage, UUID firstImage, UUID webLoginKey, UUID homeRegionID, - int godLevel, int userFlags, string customType, UUID partnerID) - { - string sql = string.Format(@"INSERT INTO {0} - ([UUID], [username], [lastname], [email], [passwordHash], [passwordSalt], - [homeRegion], [homeLocationX], [homeLocationY], [homeLocationZ], [homeLookAtX], - [homeLookAtY], [homeLookAtZ], [created], [lastLogin], [userInventoryURI], - [userAssetURI], [profileCanDoMask], [profileWantDoMask], [profileAboutText], - [profileFirstText], [profileImage], [profileFirstImage], [webLoginKey], - [homeRegionID], [userFlags], [godLevel], [customType], [partner]) - VALUES - (@UUID, @username, @lastname, @email, @passwordHash, @passwordSalt, - @homeRegion, @homeLocationX, @homeLocationY, @homeLocationZ, @homeLookAtX, - @homeLookAtY, @homeLookAtZ, @created, @lastLogin, @userInventoryURI, - @userAssetURI, @profileCanDoMask, @profileWantDoMask, @profileAboutText, - @profileFirstText, @profileImage, @profileFirstImage, @webLoginKey, - @homeRegionID, @userFlags, @godLevel, @customType, @partner)", m_usersTableName); - - try - { - using (AutoClosingSqlCommand command = database.Query(sql)) - { - command.Parameters.Add(database.CreateParameter("UUID", uuid)); - command.Parameters.Add(database.CreateParameter("username", username)); - command.Parameters.Add(database.CreateParameter("lastname", lastname)); - command.Parameters.Add(database.CreateParameter("email", email)); - command.Parameters.Add(database.CreateParameter("passwordHash", passwordHash)); - command.Parameters.Add(database.CreateParameter("passwordSalt", passwordSalt)); - command.Parameters.Add(database.CreateParameter("homeRegion", homeRegion)); - command.Parameters.Add(database.CreateParameter("homeLocationX", homeLocX)); - command.Parameters.Add(database.CreateParameter("homeLocationY", homeLocY)); - command.Parameters.Add(database.CreateParameter("homeLocationZ", homeLocZ)); - command.Parameters.Add(database.CreateParameter("homeLookAtX", homeLookAtX)); - command.Parameters.Add(database.CreateParameter("homeLookAtY", homeLookAtY)); - command.Parameters.Add(database.CreateParameter("homeLookAtZ", homeLookAtZ)); - command.Parameters.Add(database.CreateParameter("created", created)); - command.Parameters.Add(database.CreateParameter("lastLogin", lastlogin)); - command.Parameters.Add(database.CreateParameter("userInventoryURI", inventoryURI)); - command.Parameters.Add(database.CreateParameter("userAssetURI", assetURI)); - command.Parameters.Add(database.CreateParameter("profileCanDoMask", canDoMask)); - command.Parameters.Add(database.CreateParameter("profileWantDoMask", wantDoMask)); - command.Parameters.Add(database.CreateParameter("profileAboutText", aboutText)); - command.Parameters.Add(database.CreateParameter("profileFirstText", firstText)); - command.Parameters.Add(database.CreateParameter("profileImage", profileImage)); - command.Parameters.Add(database.CreateParameter("profileFirstImage", firstImage)); - command.Parameters.Add(database.CreateParameter("webLoginKey", webLoginKey)); - command.Parameters.Add(database.CreateParameter("homeRegionID", homeRegionID)); - command.Parameters.Add(database.CreateParameter("userFlags", userFlags)); - command.Parameters.Add(database.CreateParameter("godLevel", godLevel)); - command.Parameters.Add(database.CreateParameter("customType", customType)); - command.Parameters.Add(database.CreateParameter("partner", partnerID)); - - command.ExecuteNonQuery(); - return; - } - } - catch (Exception e) - { - m_log.Error(e.ToString()); - return; - } - } - - /// - /// Reads a user profile from an active data reader - /// - /// An active database reader - /// A user profile - private static UserProfileData ReadUserRow(SqlDataReader reader) - { - UserProfileData retval = new UserProfileData(); - - if (reader.Read()) - { - retval.ID = new UUID((Guid)reader["UUID"]); - retval.FirstName = (string)reader["username"]; - retval.SurName = (string)reader["lastname"]; - if (reader.IsDBNull(reader.GetOrdinal("email"))) - retval.Email = ""; - else - retval.Email = (string)reader["email"]; - - retval.PasswordHash = (string)reader["passwordHash"]; - retval.PasswordSalt = (string)reader["passwordSalt"]; - - retval.HomeRegion = Convert.ToUInt64(reader["homeRegion"].ToString()); - retval.HomeLocation = new Vector3( - Convert.ToSingle(reader["homeLocationX"].ToString()), - Convert.ToSingle(reader["homeLocationY"].ToString()), - Convert.ToSingle(reader["homeLocationZ"].ToString())); - retval.HomeLookAt = new Vector3( - Convert.ToSingle(reader["homeLookAtX"].ToString()), - Convert.ToSingle(reader["homeLookAtY"].ToString()), - Convert.ToSingle(reader["homeLookAtZ"].ToString())); - - if (reader.IsDBNull(reader.GetOrdinal("homeRegionID"))) - retval.HomeRegionID = UUID.Zero; - else - retval.HomeRegionID = new UUID((Guid)reader["homeRegionID"]); - - retval.Created = Convert.ToInt32(reader["created"].ToString()); - retval.LastLogin = Convert.ToInt32(reader["lastLogin"].ToString()); - - if (reader.IsDBNull(reader.GetOrdinal("userInventoryURI"))) - retval.UserInventoryURI = ""; - else - retval.UserInventoryURI = (string)reader["userInventoryURI"]; - - if (reader.IsDBNull(reader.GetOrdinal("userAssetURI"))) - retval.UserAssetURI = ""; - else - retval.UserAssetURI = (string)reader["userAssetURI"]; - - retval.CanDoMask = Convert.ToUInt32(reader["profileCanDoMask"].ToString()); - retval.WantDoMask = Convert.ToUInt32(reader["profileWantDoMask"].ToString()); - - - if (reader.IsDBNull(reader.GetOrdinal("profileAboutText"))) - retval.AboutText = ""; - else - retval.AboutText = (string)reader["profileAboutText"]; - - if (reader.IsDBNull(reader.GetOrdinal("profileFirstText"))) - retval.FirstLifeAboutText = ""; - else - retval.FirstLifeAboutText = (string)reader["profileFirstText"]; - - if (reader.IsDBNull(reader.GetOrdinal("profileImage"))) - retval.Image = UUID.Zero; - else - retval.Image = new UUID((Guid)reader["profileImage"]); - - if (reader.IsDBNull(reader.GetOrdinal("profileFirstImage"))) - retval.Image = UUID.Zero; - else - retval.FirstLifeImage = new UUID((Guid)reader["profileFirstImage"]); - - if (reader.IsDBNull(reader.GetOrdinal("webLoginKey"))) - retval.WebLoginKey = UUID.Zero; - else - retval.WebLoginKey = new UUID((Guid)reader["webLoginKey"]); - - retval.UserFlags = Convert.ToInt32(reader["userFlags"].ToString()); - retval.GodLevel = Convert.ToInt32(reader["godLevel"].ToString()); - if (reader.IsDBNull(reader.GetOrdinal("customType"))) - retval.CustomType = ""; - else - retval.CustomType = reader["customType"].ToString(); - - if (reader.IsDBNull(reader.GetOrdinal("partner"))) - retval.Partner = UUID.Zero; - else - retval.Partner = new UUID((Guid)reader["partner"]); - } - else - { - return null; - } - return retval; - } - #endregion - } - -} diff --git a/OpenSim/Data/MySQL/MySQLGridData.cs b/OpenSim/Data/MySQL/MySQLGridData.cs deleted file mode 100644 index f4e7b85..0000000 --- a/OpenSim/Data/MySQL/MySQLGridData.cs +++ /dev/null @@ -1,422 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.Data; -using System.Reflection; -using System.Threading; -using log4net; -using MySql.Data.MySqlClient; -using OpenMetaverse; -using OpenSim.Framework; - -namespace OpenSim.Data.MySQL -{ - /// - /// A MySQL Interface for the Grid Server - /// - public class MySQLGridData : GridDataBase - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private MySQLManager m_database; - private object m_dbLock = new object(); - private string m_connectionString; - - override public void Initialise() - { - m_log.Info("[MySQLGridData]: " + Name + " cannot be default-initialized!"); - throw new PluginNotInitialisedException (Name); - } - - /// - /// Initialises Grid interface - /// - /// - /// Loads and initialises the MySQL storage plugin - /// Warns and uses the obsolete mysql_connection.ini if connect string is empty. - /// Check for migration - /// - /// - /// - /// connect string. - override public void Initialise(string connect) - { - m_connectionString = connect; - m_database = new MySQLManager(connect); - - // This actually does the roll forward assembly stuff - Assembly assem = GetType().Assembly; - - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - Migration m = new Migration(dbcon, assem, "GridStore"); - m.Update(); - } - } - - /// - /// Shuts down the grid interface - /// - override public void Dispose() - { - } - - /// - /// Returns the plugin name - /// - /// Plugin name - override public string Name - { - get { return "MySql OpenGridData"; } - } - - /// - /// Returns the plugin version - /// - /// Plugin version - override public string Version - { - get { return "0.1"; } - } - - /// - /// Returns all the specified region profiles within coordates -- coordinates are inclusive - /// - /// Minimum X coordinate - /// Minimum Y coordinate - /// Maximum X coordinate - /// Maximum Y coordinate - /// Array of sim profiles - override public RegionProfileData[] GetProfilesInRange(uint xmin, uint ymin, uint xmax, uint ymax) - { - try - { - Dictionary param = new Dictionary(); - param["?xmin"] = xmin.ToString(); - param["?ymin"] = ymin.ToString(); - param["?xmax"] = xmax.ToString(); - param["?ymax"] = ymax.ToString(); - - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - using (IDbCommand result = m_database.Query(dbcon, - "SELECT * FROM regions WHERE locX >= ?xmin AND locX <= ?xmax AND locY >= ?ymin AND locY <= ?ymax", - param)) - { - using (IDataReader reader = result.ExecuteReader()) - { - RegionProfileData row; - - List rows = new List(); - - while ((row = m_database.readSimRow(reader)) != null) - rows.Add(row); - - return rows.ToArray(); - } - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return null; - } - } - - /// - /// Returns up to maxNum profiles of regions that have a name starting with namePrefix - /// - /// The name to match against - /// Maximum number of profiles to return - /// A list of sim profiles - override public List GetRegionsByName(string namePrefix, uint maxNum) - { - try - { - Dictionary param = new Dictionary(); - param["?name"] = namePrefix + "%"; - - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - using (IDbCommand result = m_database.Query(dbcon, - "SELECT * FROM regions WHERE regionName LIKE ?name", - param)) - { - using (IDataReader reader = result.ExecuteReader()) - { - RegionProfileData row; - - List rows = new List(); - - while (rows.Count < maxNum && (row = m_database.readSimRow(reader)) != null) - rows.Add(row); - - return rows; - } - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return null; - } - } - - /// - /// Returns a sim profile from it's location - /// - /// Region location handle - /// Sim profile - override public RegionProfileData GetProfileByHandle(ulong handle) - { - try - { - Dictionary param = new Dictionary(); - param["?handle"] = handle.ToString(); - - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - using (IDbCommand result = m_database.Query(dbcon, "SELECT * FROM regions WHERE regionHandle = ?handle", param)) - { - using (IDataReader reader = result.ExecuteReader()) - { - RegionProfileData row = m_database.readSimRow(reader); - return row; - } - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return null; - } - } - - /// - /// Returns a sim profile from it's UUID - /// - /// The region UUID - /// The sim profile - override public RegionProfileData GetProfileByUUID(UUID uuid) - { - try - { - Dictionary param = new Dictionary(); - param["?uuid"] = uuid.ToString(); - - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - using (IDbCommand result = m_database.Query(dbcon, "SELECT * FROM regions WHERE uuid = ?uuid", param)) - { - using (IDataReader reader = result.ExecuteReader()) - { - RegionProfileData row = m_database.readSimRow(reader); - return row; - } - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return null; - } - } - - /// - /// Returns a sim profile from it's Region name string - /// - /// The sim profile - override public RegionProfileData GetProfileByString(string regionName) - { - if (regionName.Length > 2) - { - try - { - Dictionary param = new Dictionary(); - // Add % because this is a like query. - param["?regionName"] = regionName + "%"; - - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - // Order by statement will return shorter matches first. Only returns one record or no record. - using (IDbCommand result = m_database.Query(dbcon, - "SELECT * FROM regions WHERE regionName like ?regionName order by LENGTH(regionName) asc LIMIT 1", - param)) - { - using (IDataReader reader = result.ExecuteReader()) - { - RegionProfileData row = m_database.readSimRow(reader); - return row; - } - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return null; - } - } - - m_log.Error("[GRID DB]: Searched for a Region Name shorter then 3 characters"); - return null; - } - - /// - /// Adds a new profile to the database - /// - /// The profile to add - /// Successful? - override public DataResponse StoreProfile(RegionProfileData profile) - { - try - { - if (m_database.insertRegion(profile)) - return DataResponse.RESPONSE_OK; - else - return DataResponse.RESPONSE_ERROR; - } - catch - { - return DataResponse.RESPONSE_ERROR; - } - } - - /// - /// Deletes a sim profile from the database - /// - /// the sim UUID - /// Successful? - //public DataResponse DeleteProfile(RegionProfileData profile) - override public DataResponse DeleteProfile(string uuid) - { - try - { - if (m_database.deleteRegion(uuid)) - return DataResponse.RESPONSE_OK; - else - return DataResponse.RESPONSE_ERROR; - } - catch - { - return DataResponse.RESPONSE_ERROR; - } - } - - /// - /// DEPRECATED. Attempts to authenticate a region by comparing a shared secret. - /// - /// The UUID of the challenger - /// The attempted regionHandle of the challenger - /// The secret - /// Whether the secret and regionhandle match the database entry for UUID - override public bool AuthenticateSim(UUID uuid, ulong handle, string authkey) - { - bool throwHissyFit = false; // Should be true by 1.0 - - if (throwHissyFit) - throw new Exception("CRYPTOWEAK AUTHENTICATE: Refusing to authenticate due to replay potential."); - - RegionProfileData data = GetProfileByUUID(uuid); - - return (handle == data.regionHandle && authkey == data.regionSecret); - } - - /// - /// NOT YET FUNCTIONAL. Provides a cryptographic authentication of a region - /// - /// This requires a security audit. - /// - /// - /// - /// - /// - public bool AuthenticateSim(UUID uuid, ulong handle, string authhash, string challenge) - { - // SHA512Managed HashProvider = new SHA512Managed(); - // Encoding TextProvider = new UTF8Encoding(); - - // byte[] stream = TextProvider.GetBytes(uuid.ToString() + ":" + handle.ToString() + ":" + challenge); - // byte[] hash = HashProvider.ComputeHash(stream); - - return false; - } - - /// - /// Adds a location reservation - /// - /// x coordinate - /// y coordinate - /// - override public ReservationData GetReservationAtPoint(uint x, uint y) - { - try - { - Dictionary param = new Dictionary(); - param["?x"] = x.ToString(); - param["?y"] = y.ToString(); - - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - using (IDbCommand result = m_database.Query(dbcon, - "SELECT * FROM reservations WHERE resXMin <= ?x AND resXMax >= ?x AND resYMin <= ?y AND resYMax >= ?y", - param)) - { - using (IDataReader reader = result.ExecuteReader()) - { - ReservationData row = m_database.readReservationRow(reader); - return row; - } - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return null; - } - } - } -} diff --git a/OpenSim/Data/MySQL/MySQLLogData.cs b/OpenSim/Data/MySQL/MySQLLogData.cs deleted file mode 100644 index 304883c..0000000 --- a/OpenSim/Data/MySQL/MySQLLogData.cs +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -using System; -using System.Collections.Generic; -using System.Reflection; -using log4net; -using OpenSim.Framework; - -namespace OpenSim.Data.MySQL -{ - /// - /// An interface to the log database for MySQL - /// - internal class MySQLLogData : ILogDataPlugin - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - /// - /// The database manager - /// - public MySQLManager database; - - public void Initialise() - { - m_log.Info("[MySQLLogData]: " + Name + " cannot be default-initialized!"); - throw new PluginNotInitialisedException (Name); - } - - /// - /// Artificial constructor called when the plugin is loaded - /// Uses the obsolete mysql_connection.ini if connect string is empty. - /// - /// connect string - public void Initialise(string connect) - { - if (connect != String.Empty) - { - database = new MySQLManager(connect); - } - else - { - m_log.Warn("Using deprecated mysql_connection.ini. Please update database_connect in GridServer_Config.xml and we'll use that instead"); - - IniFile GridDataMySqlFile = new IniFile("mysql_connection.ini"); - string settingHostname = GridDataMySqlFile.ParseFileReadValue("hostname"); - string settingDatabase = GridDataMySqlFile.ParseFileReadValue("database"); - string settingUsername = GridDataMySqlFile.ParseFileReadValue("username"); - string settingPassword = GridDataMySqlFile.ParseFileReadValue("password"); - string settingPooling = GridDataMySqlFile.ParseFileReadValue("pooling"); - string settingPort = GridDataMySqlFile.ParseFileReadValue("port"); - - database = new MySQLManager(settingHostname, settingDatabase, settingUsername, settingPassword, - settingPooling, settingPort); - } - - // This actually does the roll forward assembly stuff - Assembly assem = GetType().Assembly; - - using (MySql.Data.MySqlClient.MySqlConnection dbcon = new MySql.Data.MySqlClient.MySqlConnection(connect)) - { - dbcon.Open(); - - Migration m = new Migration(dbcon, assem, "LogStore"); - - // TODO: After rev 6000, remove this. People should have - // been rolled onto the new migration code by then. - TestTables(m); - - m.Update(); - } - } - - /// - /// - private void TestTables(Migration m) - { - // under migrations, bail - if (m.Version > 0) - return; - - Dictionary tableList = new Dictionary(); - tableList["logs"] = null; - database.GetTableVersion(tableList); - - // migrations will handle it - if (tableList["logs"] == null) - return; - - // we have the table, so pretend like we did the first migration in the past - if (m.Version == 0) - m.Version = 1; - } - - /// - /// Saves a log item to the database - /// - /// The daemon triggering the event - /// The target of the action (region / agent UUID, etc) - /// The method call where the problem occured - /// The arguments passed to the method - /// How critical is this? - /// The message to log - public void saveLog(string serverDaemon, string target, string methodCall, string arguments, int priority, - string logMessage) - { - try - { - database.insertLogRow(serverDaemon, target, methodCall, arguments, priority, logMessage); - } - catch - { - } - } - - /// - /// Returns the name of this DB provider - /// - /// A string containing the DB provider name - public string Name - { - get { return "MySQL Logdata Interface";} - } - - /// - /// Closes the database provider - /// - /// do nothing - public void Dispose() - { - // Do nothing. - } - - /// - /// Returns the version of this DB provider - /// - /// A string containing the provider version - public string Version - { - get { return "0.1"; } - } - } -} diff --git a/OpenSim/Data/MySQL/MySQLManager.cs b/OpenSim/Data/MySQL/MySQLManager.cs deleted file mode 100644 index ace2027..0000000 --- a/OpenSim/Data/MySQL/MySQLManager.cs +++ /dev/null @@ -1,1248 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; -using System.IO; -using System.Reflection; -using log4net; -using MySql.Data.MySqlClient; -using OpenMetaverse; -using OpenSim.Framework; - -namespace OpenSim.Data.MySQL -{ - /// - /// A MySQL Database manager - /// - public class MySQLManager - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - /// - /// Connection string for ADO.net - /// - private string connectionString; - - private object m_dbLock = new object(); - - private const string m_waitTimeoutSelect = "select @@wait_timeout"; - - /// - /// Wait timeout for our connection in ticks. - /// - private long m_waitTimeout; - - /// - /// Make our storage of the timeout this amount smaller than it actually is, to give us a margin on long - /// running database operations. - /// - private long m_waitTimeoutLeeway = 60 * TimeSpan.TicksPerSecond; - - /// - /// Holds the last tick time that the connection was used. - /// - private long m_lastConnectionUse; - - /// - /// Initialises and creates a new MySQL connection and maintains it. - /// - /// The MySQL server being connected to - /// The name of the MySQL database being used - /// The username logging into the database - /// The password for the user logging in - /// Whether to use connection pooling or not, can be one of the following: 'yes', 'true', 'no' or 'false', if unsure use 'false'. - /// The MySQL server port - public MySQLManager(string hostname, string database, string username, string password, string cpooling, - string port) - { - string s = "Server=" + hostname + ";Port=" + port + ";Database=" + database + ";User ID=" + - username + ";Password=" + password + ";Pooling=" + cpooling + ";"; - - Initialise(s); - } - - /// - /// Initialises and creates a new MySQL connection and maintains it. - /// - /// connectionString - public MySQLManager(String connect) - { - Initialise(connect); - } - - /// - /// Initialises and creates a new MySQL connection and maintains it. - /// - /// connectionString - public void Initialise(String connect) - { - try - { - connectionString = connect; - //dbcon = new MySqlConnection(connectionString); - - try - { - //dbcon.Open(); - } - catch(Exception e) - { - throw new Exception("Connection error while using connection string ["+connectionString+"]", e); - } - - m_log.Info("[MYSQL]: Connection established"); - GetWaitTimeout(); - } - catch (Exception e) - { - throw new Exception("Error initialising MySql Database: " + e.ToString()); - } - } - - /// - /// Get the wait_timeout value for our connection - /// - protected void GetWaitTimeout() - { - using (MySqlConnection dbcon = new MySqlConnection(connectionString)) - { - dbcon.Open(); - - using (MySqlCommand cmd = new MySqlCommand(m_waitTimeoutSelect, dbcon)) - { - using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow)) - { - if (dbReader.Read()) - { - m_waitTimeout - = Convert.ToInt32(dbReader["@@wait_timeout"]) * TimeSpan.TicksPerSecond + m_waitTimeoutLeeway; - } - } - } - } - - m_lastConnectionUse = DateTime.Now.Ticks; - - m_log.DebugFormat( - "[REGION DB]: Connection wait timeout {0} seconds", m_waitTimeout / TimeSpan.TicksPerSecond); - } - - public string ConnectionString - { - get { return connectionString; } - } - - /// - /// Returns the version of this DB provider - /// - /// A string containing the DB provider - public string getVersion() - { - Module module = GetType().Module; - // string dllName = module.Assembly.ManifestModule.Name; - Version dllVersion = module.Assembly.GetName().Version; - - return - string.Format("{0}.{1}.{2}.{3}", dllVersion.Major, dllVersion.Minor, dllVersion.Build, - dllVersion.Revision); - } - - /// - /// Extract a named string resource from the embedded resources - /// - /// name of embedded resource - /// string contained within the embedded resource - private string getResourceString(string name) - { - Assembly assem = GetType().Assembly; - string[] names = assem.GetManifestResourceNames(); - - foreach (string s in names) - { - if (s.EndsWith(name)) - { - using (Stream resource = assem.GetManifestResourceStream(s)) - { - using (StreamReader resourceReader = new StreamReader(resource)) - { - string resourceString = resourceReader.ReadToEnd(); - return resourceString; - } - } - } - } - throw new Exception(string.Format("Resource '{0}' was not found", name)); - } - - /// - /// Execute a SQL statement stored in a resource, as a string - /// - /// name of embedded resource - public void ExecuteResourceSql(string name) - { - using (MySqlConnection dbcon = new MySqlConnection(connectionString)) - { - dbcon.Open(); - - MySqlCommand cmd = new MySqlCommand(getResourceString(name), dbcon); - cmd.ExecuteNonQuery(); - } - } - - /// - /// Execute a MySqlCommand - /// - /// sql string to execute - public void ExecuteSql(string sql) - { - using (MySqlConnection dbcon = new MySqlConnection(connectionString)) - { - dbcon.Open(); - - MySqlCommand cmd = new MySqlCommand(sql, dbcon); - cmd.ExecuteNonQuery(); - } - } - - public void ExecuteParameterizedSql(string sql, Dictionary parameters) - { - using (MySqlConnection dbcon = new MySqlConnection(connectionString)) - { - dbcon.Open(); - - MySqlCommand cmd = (MySqlCommand)dbcon.CreateCommand(); - cmd.CommandText = sql; - foreach (KeyValuePair param in parameters) - { - cmd.Parameters.AddWithValue(param.Key, param.Value); - } - cmd.ExecuteNonQuery(); - } - } - - /// - /// Given a list of tables, return the version of the tables, as seen in the database - /// - /// - public void GetTableVersion(Dictionary tableList) - { - lock (m_dbLock) - { - using (MySqlConnection dbcon = new MySqlConnection(connectionString)) - { - dbcon.Open(); - - using (MySqlCommand tablesCmd = new MySqlCommand( - "SELECT TABLE_NAME, TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=?dbname", dbcon)) - { - tablesCmd.Parameters.AddWithValue("?dbname", dbcon.Database); - - using (MySqlDataReader tables = tablesCmd.ExecuteReader()) - { - while (tables.Read()) - { - try - { - string tableName = (string)tables["TABLE_NAME"]; - string comment = (string)tables["TABLE_COMMENT"]; - if (tableList.ContainsKey(tableName)) - { - tableList[tableName] = comment; - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - } - } - } - } - } - } - } - - // TODO: at some time this code should be cleaned up - - /// - /// Runs a query with protection against SQL Injection by using parameterised input. - /// - /// Database connection - /// The SQL string - replace any variables such as WHERE x = "y" with WHERE x = @y - /// The parameters - index so that @y is indexed as 'y' - /// A MySQL DB Command - public IDbCommand Query(MySqlConnection dbcon, string sql, Dictionary parameters) - { - try - { - MySqlCommand dbcommand = (MySqlCommand)dbcon.CreateCommand(); - dbcommand.CommandText = sql; - foreach (KeyValuePair param in parameters) - { - dbcommand.Parameters.AddWithValue(param.Key, param.Value); - } - - return (IDbCommand)dbcommand; - } - catch (Exception e) - { - // Return null if it fails. - m_log.Error("Failed during Query generation: " + e.Message, e); - return null; - } - } - - /// - /// Reads a region row from a database reader - /// - /// An active database reader - /// A region profile - public RegionProfileData readSimRow(IDataReader reader) - { - RegionProfileData retval = new RegionProfileData(); - - if (reader.Read()) - { - // Region Main gotta-have-or-we-return-null parts - UInt64 tmp64; - if (!UInt64.TryParse(reader["regionHandle"].ToString(), out tmp64)) - { - return null; - } - else - { - retval.regionHandle = tmp64; - } - UUID tmp_uuid; - if (!UUID.TryParse((string)reader["uuid"], out tmp_uuid)) - { - return null; - } - else - { - retval.UUID = tmp_uuid; - } - - // non-critical parts - retval.regionName = (string)reader["regionName"]; - retval.originUUID = new UUID((string) reader["originUUID"]); - - // Secrets - retval.regionRecvKey = (string) reader["regionRecvKey"]; - retval.regionSecret = (string) reader["regionSecret"]; - retval.regionSendKey = (string) reader["regionSendKey"]; - - // Region Server - retval.regionDataURI = (string) reader["regionDataURI"]; - retval.regionOnline = false; // Needs to be pinged before this can be set. - retval.serverIP = (string) reader["serverIP"]; - retval.serverPort = (uint) reader["serverPort"]; - retval.serverURI = (string) reader["serverURI"]; - retval.httpPort = Convert.ToUInt32(reader["serverHttpPort"].ToString()); - retval.remotingPort = Convert.ToUInt32(reader["serverRemotingPort"].ToString()); - - // Location - retval.regionLocX = Convert.ToUInt32(reader["locX"].ToString()); - retval.regionLocY = Convert.ToUInt32(reader["locY"].ToString()); - retval.regionLocZ = Convert.ToUInt32(reader["locZ"].ToString()); - - // Neighbours - 0 = No Override - retval.regionEastOverrideHandle = Convert.ToUInt64(reader["eastOverrideHandle"].ToString()); - retval.regionWestOverrideHandle = Convert.ToUInt64(reader["westOverrideHandle"].ToString()); - retval.regionSouthOverrideHandle = Convert.ToUInt64(reader["southOverrideHandle"].ToString()); - retval.regionNorthOverrideHandle = Convert.ToUInt64(reader["northOverrideHandle"].ToString()); - - // Assets - retval.regionAssetURI = (string) reader["regionAssetURI"]; - retval.regionAssetRecvKey = (string) reader["regionAssetRecvKey"]; - retval.regionAssetSendKey = (string) reader["regionAssetSendKey"]; - - // Userserver - retval.regionUserURI = (string) reader["regionUserURI"]; - retval.regionUserRecvKey = (string) reader["regionUserRecvKey"]; - retval.regionUserSendKey = (string) reader["regionUserSendKey"]; - - // World Map Addition - UUID.TryParse((string)reader["regionMapTexture"], out retval.regionMapTextureID); - UUID.TryParse((string)reader["owner_uuid"], out retval.owner_uuid); - retval.maturity = Convert.ToUInt32(reader["access"]); - } - else - { - return null; - } - return retval; - } - - /// - /// Reads a reservation row from a database reader - /// - /// An active database reader - /// A reservation data object - public ReservationData readReservationRow(IDataReader reader) - { - ReservationData retval = new ReservationData(); - if (reader.Read()) - { - retval.gridRecvKey = (string) reader["gridRecvKey"]; - retval.gridSendKey = (string) reader["gridSendKey"]; - retval.reservationCompany = (string) reader["resCompany"]; - retval.reservationMaxX = Convert.ToInt32(reader["resXMax"].ToString()); - retval.reservationMaxY = Convert.ToInt32(reader["resYMax"].ToString()); - retval.reservationMinX = Convert.ToInt32(reader["resXMin"].ToString()); - retval.reservationMinY = Convert.ToInt32(reader["resYMin"].ToString()); - retval.reservationName = (string) reader["resName"]; - retval.status = Convert.ToInt32(reader["status"].ToString()) == 1; - UUID tmp; - UUID.TryParse((string) reader["userUUID"], out tmp); - retval.userUUID = tmp; - } - else - { - return null; - } - return retval; - } - - /// - /// Reads an agent row from a database reader - /// - /// An active database reader - /// A user session agent - public UserAgentData readAgentRow(IDataReader reader) - { - UserAgentData retval = new UserAgentData(); - - if (reader.Read()) - { - // Agent IDs - UUID tmp; - if (!UUID.TryParse((string)reader["UUID"], out tmp)) - return null; - retval.ProfileID = tmp; - - UUID.TryParse((string) reader["sessionID"], out tmp); - retval.SessionID = tmp; - - UUID.TryParse((string)reader["secureSessionID"], out tmp); - retval.SecureSessionID = tmp; - - // Agent Who? - retval.AgentIP = (string) reader["agentIP"]; - retval.AgentPort = Convert.ToUInt32(reader["agentPort"].ToString()); - retval.AgentOnline = Convert.ToBoolean(Convert.ToInt16(reader["agentOnline"].ToString())); - - // Login/Logout times (UNIX Epoch) - retval.LoginTime = Convert.ToInt32(reader["loginTime"].ToString()); - retval.LogoutTime = Convert.ToInt32(reader["logoutTime"].ToString()); - - // Current position - retval.Region = new UUID((string)reader["currentRegion"]); - retval.Handle = Convert.ToUInt64(reader["currentHandle"].ToString()); - Vector3 tmp_v; - Vector3.TryParse((string) reader["currentPos"], out tmp_v); - retval.Position = tmp_v; - Vector3.TryParse((string)reader["currentLookAt"], out tmp_v); - retval.LookAt = tmp_v; - } - else - { - return null; - } - return retval; - } - - /// - /// Reads a user profile from an active data reader - /// - /// An active database reader - /// A user profile - public UserProfileData readUserRow(IDataReader reader) - { - UserProfileData retval = new UserProfileData(); - - if (reader.Read()) - { - UUID id; - if (!UUID.TryParse((string)reader["UUID"], out id)) - return null; - - retval.ID = id; - retval.FirstName = (string) reader["username"]; - retval.SurName = (string) reader["lastname"]; - retval.Email = (reader.IsDBNull(reader.GetOrdinal("email"))) ? "" : (string) reader["email"]; - - retval.PasswordHash = (string) reader["passwordHash"]; - retval.PasswordSalt = (string) reader["passwordSalt"]; - - retval.HomeRegion = Convert.ToUInt64(reader["homeRegion"].ToString()); - retval.HomeLocation = new Vector3( - Convert.ToSingle(reader["homeLocationX"].ToString()), - Convert.ToSingle(reader["homeLocationY"].ToString()), - Convert.ToSingle(reader["homeLocationZ"].ToString())); - retval.HomeLookAt = new Vector3( - Convert.ToSingle(reader["homeLookAtX"].ToString()), - Convert.ToSingle(reader["homeLookAtY"].ToString()), - Convert.ToSingle(reader["homeLookAtZ"].ToString())); - - UUID regionID = UUID.Zero; - UUID.TryParse(reader["homeRegionID"].ToString(), out regionID); // it's ok if it doesn't work; just use UUID.Zero - retval.HomeRegionID = regionID; - - retval.Created = Convert.ToInt32(reader["created"].ToString()); - retval.LastLogin = Convert.ToInt32(reader["lastLogin"].ToString()); - - retval.UserInventoryURI = (string) reader["userInventoryURI"]; - retval.UserAssetURI = (string) reader["userAssetURI"]; - - retval.CanDoMask = Convert.ToUInt32(reader["profileCanDoMask"].ToString()); - retval.WantDoMask = Convert.ToUInt32(reader["profileWantDoMask"].ToString()); - - if (reader.IsDBNull(reader.GetOrdinal("profileAboutText"))) - retval.AboutText = ""; - else - retval.AboutText = (string) reader["profileAboutText"]; - - if (reader.IsDBNull(reader.GetOrdinal("profileFirstText"))) - retval.FirstLifeAboutText = ""; - else - retval.FirstLifeAboutText = (string)reader["profileFirstText"]; - - if (reader.IsDBNull(reader.GetOrdinal("profileImage"))) - retval.Image = UUID.Zero; - else { - UUID tmp; - UUID.TryParse((string)reader["profileImage"], out tmp); - retval.Image = tmp; - } - - if (reader.IsDBNull(reader.GetOrdinal("profileFirstImage"))) - retval.FirstLifeImage = UUID.Zero; - else { - UUID tmp; - UUID.TryParse((string)reader["profileFirstImage"], out tmp); - retval.FirstLifeImage = tmp; - } - - if (reader.IsDBNull(reader.GetOrdinal("webLoginKey"))) - { - retval.WebLoginKey = UUID.Zero; - } - else - { - UUID tmp; - UUID.TryParse((string)reader["webLoginKey"], out tmp); - retval.WebLoginKey = tmp; - } - - retval.UserFlags = Convert.ToInt32(reader["userFlags"].ToString()); - retval.GodLevel = Convert.ToInt32(reader["godLevel"].ToString()); - if (reader.IsDBNull(reader.GetOrdinal("customType"))) - retval.CustomType = ""; - else - retval.CustomType = reader["customType"].ToString(); - - if (reader.IsDBNull(reader.GetOrdinal("partner"))) - { - retval.Partner = UUID.Zero; - } - else - { - UUID tmp; - UUID.TryParse((string)reader["partner"], out tmp); - retval.Partner = tmp; - } - } - else - { - return null; - } - return retval; - } - - /// - /// Reads an avatar appearence from an active data reader - /// - /// An active database reader - /// An avatar appearence - public AvatarAppearance readAppearanceRow(IDataReader reader) - { - AvatarAppearance appearance = null; - if (reader.Read()) - { - appearance = new AvatarAppearance(); - appearance.Owner = new UUID((string)reader["owner"]); - appearance.Serial = Convert.ToInt32(reader["serial"]); - appearance.VisualParams = (byte[])reader["visual_params"]; - appearance.Texture = new Primitive.TextureEntry((byte[])reader["texture"], 0, ((byte[])reader["texture"]).Length); - appearance.AvatarHeight = (float)Convert.ToDouble(reader["avatar_height"]); - appearance.BodyItem = new UUID((string)reader["body_item"]); - appearance.BodyAsset = new UUID((string)reader["body_asset"]); - appearance.SkinItem = new UUID((string)reader["skin_item"]); - appearance.SkinAsset = new UUID((string)reader["skin_asset"]); - appearance.HairItem = new UUID((string)reader["hair_item"]); - appearance.HairAsset = new UUID((string)reader["hair_asset"]); - appearance.EyesItem = new UUID((string)reader["eyes_item"]); - appearance.EyesAsset = new UUID((string)reader["eyes_asset"]); - appearance.ShirtItem = new UUID((string)reader["shirt_item"]); - appearance.ShirtAsset = new UUID((string)reader["shirt_asset"]); - appearance.PantsItem = new UUID((string)reader["pants_item"]); - appearance.PantsAsset = new UUID((string)reader["pants_asset"]); - appearance.ShoesItem = new UUID((string)reader["shoes_item"]); - appearance.ShoesAsset = new UUID((string)reader["shoes_asset"]); - appearance.SocksItem = new UUID((string)reader["socks_item"]); - appearance.SocksAsset = new UUID((string)reader["socks_asset"]); - appearance.JacketItem = new UUID((string)reader["jacket_item"]); - appearance.JacketAsset = new UUID((string)reader["jacket_asset"]); - appearance.GlovesItem = new UUID((string)reader["gloves_item"]); - appearance.GlovesAsset = new UUID((string)reader["gloves_asset"]); - appearance.UnderShirtItem = new UUID((string)reader["undershirt_item"]); - appearance.UnderShirtAsset = new UUID((string)reader["undershirt_asset"]); - appearance.UnderPantsItem = new UUID((string)reader["underpants_item"]); - appearance.UnderPantsAsset = new UUID((string)reader["underpants_asset"]); - appearance.SkirtItem = new UUID((string)reader["skirt_item"]); - appearance.SkirtAsset = new UUID((string)reader["skirt_asset"]); - } - return appearance; - } - - // Read attachment list from data reader - public Hashtable readAttachments(IDataReader r) - { - Hashtable ret = new Hashtable(); - - while (r.Read()) - { - int attachpoint = Convert.ToInt32(r["attachpoint"]); - if (ret.ContainsKey(attachpoint)) - continue; - Hashtable item = new Hashtable(); - item.Add("item", r["item"].ToString()); - item.Add("asset", r["asset"].ToString()); - - ret.Add(attachpoint, item); - } - - return ret; - } - - /// - /// Inserts a new row into the log database - /// - /// The daemon which triggered this event - /// Who were we operating on when this occured (region UUID, user UUID, etc) - /// The method call where the problem occured - /// The arguments passed to the method - /// How critical is this? - /// Extra message info - /// Saved successfully? - public bool insertLogRow(string serverDaemon, string target, string methodCall, string arguments, int priority, - string logMessage) - { - string sql = "INSERT INTO logs (`target`, `server`, `method`, `arguments`, `priority`, `message`) VALUES "; - sql += "(?target, ?server, ?method, ?arguments, ?priority, ?message)"; - - Dictionary parameters = new Dictionary(); - parameters["?server"] = serverDaemon; - parameters["?target"] = target; - parameters["?method"] = methodCall; - parameters["?arguments"] = arguments; - parameters["?priority"] = priority.ToString(); - parameters["?message"] = logMessage; - - bool returnval = false; - - try - { - using (MySqlConnection dbcon = new MySqlConnection(connectionString)) - { - dbcon.Open(); - - IDbCommand result = Query(dbcon, sql, parameters); - - if (result.ExecuteNonQuery() == 1) - returnval = true; - - result.Dispose(); - } - } - catch (Exception e) - { - m_log.Error(e.ToString()); - return false; - } - - return returnval; - } - - /// - /// Creates a new user and inserts it into the database - /// - /// User ID - /// First part of the login - /// Second part of the login - /// A salted hash of the users password - /// The salt used for the password hash - /// A regionHandle of the users home region - /// The UUID of the user's home region - /// Home region position vector - /// Home region position vector - /// Home region position vector - /// Home region 'look at' vector - /// Home region 'look at' vector - /// Home region 'look at' vector - /// Account created (unix timestamp) - /// Last login (unix timestamp) - /// Users inventory URI - /// Users asset URI - /// I can do mask - /// I want to do mask - /// Profile text - /// Firstlife text - /// UUID for profile image - /// UUID for firstlife image - /// Ignored - /// Success? - public bool insertUserRow(UUID uuid, string username, string lastname, string email, string passwordHash, - string passwordSalt, UInt64 homeRegion, UUID homeRegionID, float homeLocX, float homeLocY, float homeLocZ, - float homeLookAtX, float homeLookAtY, float homeLookAtZ, int created, int lastlogin, - string inventoryURI, string assetURI, uint canDoMask, uint wantDoMask, - string aboutText, string firstText, - UUID profileImage, UUID firstImage, UUID webLoginKey, int userFlags, int godLevel, string customType, UUID partner) - { - m_log.Debug("[MySQLManager]: Creating profile for \"" + username + " " + lastname + "\" (" + uuid + ")"); - string sql = - "INSERT INTO users (`UUID`, `username`, `lastname`, `email`, `passwordHash`, `passwordSalt`, `homeRegion`, `homeRegionID`, "; - sql += - "`homeLocationX`, `homeLocationY`, `homeLocationZ`, `homeLookAtX`, `homeLookAtY`, `homeLookAtZ`, `created`, "; - sql += - "`lastLogin`, `userInventoryURI`, `userAssetURI`, `profileCanDoMask`, `profileWantDoMask`, `profileAboutText`, "; - sql += "`profileFirstText`, `profileImage`, `profileFirstImage`, `webLoginKey`, `userFlags`, `godLevel`, `customType`, `partner`) VALUES "; - - sql += "(?UUID, ?username, ?lastname, ?email, ?passwordHash, ?passwordSalt, ?homeRegion, ?homeRegionID, "; - sql += - "?homeLocationX, ?homeLocationY, ?homeLocationZ, ?homeLookAtX, ?homeLookAtY, ?homeLookAtZ, ?created, "; - sql += - "?lastLogin, ?userInventoryURI, ?userAssetURI, ?profileCanDoMask, ?profileWantDoMask, ?profileAboutText, "; - sql += "?profileFirstText, ?profileImage, ?profileFirstImage, ?webLoginKey, ?userFlags, ?godLevel, ?customType, ?partner)"; - - Dictionary parameters = new Dictionary(); - parameters["?UUID"] = uuid.ToString(); - parameters["?username"] = username; - parameters["?lastname"] = lastname; - parameters["?email"] = email; - parameters["?passwordHash"] = passwordHash; - parameters["?passwordSalt"] = passwordSalt; - parameters["?homeRegion"] = homeRegion; - parameters["?homeRegionID"] = homeRegionID.ToString(); - parameters["?homeLocationX"] = homeLocX; - parameters["?homeLocationY"] = homeLocY; - parameters["?homeLocationZ"] = homeLocZ; - parameters["?homeLookAtX"] = homeLookAtX; - parameters["?homeLookAtY"] = homeLookAtY; - parameters["?homeLookAtZ"] = homeLookAtZ; - parameters["?created"] = created; - parameters["?lastLogin"] = lastlogin; - parameters["?userInventoryURI"] = inventoryURI; - parameters["?userAssetURI"] = assetURI; - parameters["?profileCanDoMask"] = canDoMask; - parameters["?profileWantDoMask"] = wantDoMask; - parameters["?profileAboutText"] = aboutText; - parameters["?profileFirstText"] = firstText; - parameters["?profileImage"] = profileImage.ToString(); - parameters["?profileFirstImage"] = firstImage.ToString(); - parameters["?webLoginKey"] = webLoginKey.ToString(); - parameters["?userFlags"] = userFlags; - parameters["?godLevel"] = godLevel; - parameters["?customType"] = customType == null ? "" : customType; - parameters["?partner"] = partner.ToString(); - bool returnval = false; - - try - { - using (MySqlConnection dbcon = new MySqlConnection(connectionString)) - { - dbcon.Open(); - - IDbCommand result = Query(dbcon, sql, parameters); - - if (result.ExecuteNonQuery() == 1) - returnval = true; - - result.Dispose(); - } - } - catch (Exception e) - { - m_log.Error(e.ToString()); - return false; - } - - //m_log.Debug("[MySQLManager]: Fetch user retval == " + returnval.ToString()); - return returnval; - } - - /// - /// Update user data into the database where User ID = uuid - /// - /// User ID - /// First part of the login - /// Second part of the login - /// A salted hash of the users password - /// The salt used for the password hash - /// A regionHandle of the users home region - /// Home region position vector - /// Home region position vector - /// Home region position vector - /// Home region 'look at' vector - /// Home region 'look at' vector - /// Home region 'look at' vector - /// Account created (unix timestamp) - /// Last login (unix timestamp) - /// Users inventory URI - /// Users asset URI - /// I can do mask - /// I want to do mask - /// Profile text - /// Firstlife text - /// UUID for profile image - /// UUID for firstlife image - /// UUID for weblogin Key - /// Success? - public bool updateUserRow(UUID uuid, string username, string lastname, string email, string passwordHash, - string passwordSalt, UInt64 homeRegion, UUID homeRegionID, float homeLocX, float homeLocY, float homeLocZ, - float homeLookAtX, float homeLookAtY, float homeLookAtZ, int created, int lastlogin, - string inventoryURI, string assetURI, uint canDoMask, uint wantDoMask, - string aboutText, string firstText, - UUID profileImage, UUID firstImage, UUID webLoginKey, int userFlags, int godLevel, string customType, UUID partner) - { - string sql = "UPDATE users SET `username` = ?username , `lastname` = ?lastname, `email` = ?email "; - sql += ", `passwordHash` = ?passwordHash , `passwordSalt` = ?passwordSalt , "; - sql += "`homeRegion` = ?homeRegion , `homeRegionID` = ?homeRegionID, `homeLocationX` = ?homeLocationX , "; - sql += "`homeLocationY` = ?homeLocationY , `homeLocationZ` = ?homeLocationZ , "; - sql += "`homeLookAtX` = ?homeLookAtX , `homeLookAtY` = ?homeLookAtY , "; - sql += "`homeLookAtZ` = ?homeLookAtZ , `created` = ?created , `lastLogin` = ?lastLogin , "; - sql += "`userInventoryURI` = ?userInventoryURI , `userAssetURI` = ?userAssetURI , "; - sql += "`profileCanDoMask` = ?profileCanDoMask , `profileWantDoMask` = ?profileWantDoMask , "; - sql += "`profileAboutText` = ?profileAboutText , `profileFirstText` = ?profileFirstText, "; - sql += "`profileImage` = ?profileImage , `profileFirstImage` = ?profileFirstImage , "; - sql += "`userFlags` = ?userFlags , `godLevel` = ?godLevel , "; - sql += "`customType` = ?customType , `partner` = ?partner , "; - sql += "`webLoginKey` = ?webLoginKey WHERE UUID = ?UUID"; - - Dictionary parameters = new Dictionary(); - parameters["?UUID"] = uuid.ToString(); - parameters["?username"] = username; - parameters["?lastname"] = lastname; - parameters["?email"] = email; - parameters["?passwordHash"] = passwordHash; - parameters["?passwordSalt"] = passwordSalt; - parameters["?homeRegion"] = homeRegion; - parameters["?homeRegionID"] = homeRegionID.ToString(); - parameters["?homeLocationX"] = homeLocX; - parameters["?homeLocationY"] = homeLocY; - parameters["?homeLocationZ"] = homeLocZ; - parameters["?homeLookAtX"] = homeLookAtX; - parameters["?homeLookAtY"] = homeLookAtY; - parameters["?homeLookAtZ"] = homeLookAtZ; - parameters["?created"] = created; - parameters["?lastLogin"] = lastlogin; - parameters["?userInventoryURI"] = inventoryURI; - parameters["?userAssetURI"] = assetURI; - parameters["?profileCanDoMask"] = canDoMask; - parameters["?profileWantDoMask"] = wantDoMask; - parameters["?profileAboutText"] = aboutText; - parameters["?profileFirstText"] = firstText; - parameters["?profileImage"] = profileImage.ToString(); - parameters["?profileFirstImage"] = firstImage.ToString(); - parameters["?webLoginKey"] = webLoginKey.ToString(); - parameters["?userFlags"] = userFlags; - parameters["?godLevel"] = godLevel; - parameters["?customType"] = customType == null ? "" : customType; - parameters["?partner"] = partner.ToString(); - - bool returnval = false; - try - { - using (MySqlConnection dbcon = new MySqlConnection(connectionString)) - { - dbcon.Open(); - - IDbCommand result = Query(dbcon, sql, parameters); - - if (result.ExecuteNonQuery() == 1) - returnval = true; - - result.Dispose(); - } - } - catch (Exception e) - { - m_log.Error(e.ToString()); - return false; - } - - //m_log.Debug("[MySQLManager]: update user retval == " + returnval.ToString()); - return returnval; - } - - /// - /// Inserts a new region into the database - /// - /// The region to insert - /// Success? - public bool insertRegion(RegionProfileData regiondata) - { - bool GRID_ONLY_UPDATE_NECESSARY_DATA = false; - - string sql = String.Empty; - if (GRID_ONLY_UPDATE_NECESSARY_DATA) - { - sql += "INSERT INTO "; - } - else - { - sql += "REPLACE INTO "; - } - - sql += "regions (regionHandle, regionName, uuid, regionRecvKey, regionSecret, regionSendKey, regionDataURI, "; - sql += - "serverIP, serverPort, serverURI, locX, locY, locZ, eastOverrideHandle, westOverrideHandle, southOverrideHandle, northOverrideHandle, regionAssetURI, regionAssetRecvKey, "; - - // part of an initial brutish effort to provide accurate information (as per the xml region spec) - // wrt the ownership of a given region - // the (very bad) assumption is that this value is being read and handled inconsistently or - // not at all. Current strategy is to put the code in place to support the validity of this information - // and to roll forward debugging any issues from that point - // - // this particular section of the mod attempts to implement the commit of a supplied value - // server for the UUID of the region's owner (master avatar). It consists of the addition of the column and value to the relevant sql, - // as well as the related parameterization - sql += - "regionAssetSendKey, regionUserURI, regionUserRecvKey, regionUserSendKey, regionMapTexture, serverHttpPort, serverRemotingPort, owner_uuid, originUUID, access) VALUES "; - - sql += "(?regionHandle, ?regionName, ?uuid, ?regionRecvKey, ?regionSecret, ?regionSendKey, ?regionDataURI, "; - sql += - "?serverIP, ?serverPort, ?serverURI, ?locX, ?locY, ?locZ, ?eastOverrideHandle, ?westOverrideHandle, ?southOverrideHandle, ?northOverrideHandle, ?regionAssetURI, ?regionAssetRecvKey, "; - sql += - "?regionAssetSendKey, ?regionUserURI, ?regionUserRecvKey, ?regionUserSendKey, ?regionMapTexture, ?serverHttpPort, ?serverRemotingPort, ?owner_uuid, ?originUUID, ?access)"; - - if (GRID_ONLY_UPDATE_NECESSARY_DATA) - { - sql += "ON DUPLICATE KEY UPDATE serverIP = ?serverIP, serverPort = ?serverPort, serverURI = ?serverURI, owner_uuid - ?owner_uuid;"; - } - else - { - sql += ";"; - } - - Dictionary parameters = new Dictionary(); - - parameters["?regionHandle"] = regiondata.regionHandle.ToString(); - parameters["?regionName"] = regiondata.regionName.ToString(); - parameters["?uuid"] = regiondata.UUID.ToString(); - parameters["?regionRecvKey"] = regiondata.regionRecvKey.ToString(); - parameters["?regionSecret"] = regiondata.regionSecret.ToString(); - parameters["?regionSendKey"] = regiondata.regionSendKey.ToString(); - parameters["?regionDataURI"] = regiondata.regionDataURI.ToString(); - parameters["?serverIP"] = regiondata.serverIP.ToString(); - parameters["?serverPort"] = regiondata.serverPort.ToString(); - parameters["?serverURI"] = regiondata.serverURI.ToString(); - parameters["?locX"] = regiondata.regionLocX.ToString(); - parameters["?locY"] = regiondata.regionLocY.ToString(); - parameters["?locZ"] = regiondata.regionLocZ.ToString(); - parameters["?eastOverrideHandle"] = regiondata.regionEastOverrideHandle.ToString(); - parameters["?westOverrideHandle"] = regiondata.regionWestOverrideHandle.ToString(); - parameters["?northOverrideHandle"] = regiondata.regionNorthOverrideHandle.ToString(); - parameters["?southOverrideHandle"] = regiondata.regionSouthOverrideHandle.ToString(); - parameters["?regionAssetURI"] = regiondata.regionAssetURI.ToString(); - parameters["?regionAssetRecvKey"] = regiondata.regionAssetRecvKey.ToString(); - parameters["?regionAssetSendKey"] = regiondata.regionAssetSendKey.ToString(); - parameters["?regionUserURI"] = regiondata.regionUserURI.ToString(); - parameters["?regionUserRecvKey"] = regiondata.regionUserRecvKey.ToString(); - parameters["?regionUserSendKey"] = regiondata.regionUserSendKey.ToString(); - parameters["?regionMapTexture"] = regiondata.regionMapTextureID.ToString(); - parameters["?serverHttpPort"] = regiondata.httpPort.ToString(); - parameters["?serverRemotingPort"] = regiondata.remotingPort.ToString(); - parameters["?owner_uuid"] = regiondata.owner_uuid.ToString(); - parameters["?originUUID"] = regiondata.originUUID.ToString(); - parameters["?access"] = regiondata.maturity.ToString(); - - bool returnval = false; - - try - { - using (MySqlConnection dbcon = new MySqlConnection(connectionString)) - { - dbcon.Open(); - - IDbCommand result = Query(dbcon, sql, parameters); - - // int x; - // if ((x = result.ExecuteNonQuery()) > 0) - // { - // returnval = true; - // } - if (result.ExecuteNonQuery() > 0) - { - returnval = true; - } - result.Dispose(); - } - } - catch (Exception e) - { - m_log.Error(e.ToString()); - return false; - } - - return returnval; - } - - /// - /// Delete a region from the database - /// - /// The region to delete - /// Success? - //public bool deleteRegion(RegionProfileData regiondata) - public bool deleteRegion(string uuid) - { - bool returnval = false; - - string sql = "DELETE FROM regions WHERE uuid = ?uuid;"; - - Dictionary parameters = new Dictionary(); - - try - { - parameters["?uuid"] = uuid; - - using (MySqlConnection dbcon = new MySqlConnection(connectionString)) - { - dbcon.Open(); - - IDbCommand result = Query(dbcon, sql, parameters); - - // int x; - // if ((x = result.ExecuteNonQuery()) > 0) - // { - // returnval = true; - // } - if (result.ExecuteNonQuery() > 0) - { - returnval = true; - } - result.Dispose(); - } - } - catch (Exception e) - { - m_log.Error(e.ToString()); - return false; - } - - return returnval; - } - - /// - /// Creates a new agent and inserts it into the database - /// - /// The agent data to be inserted - /// Success? - public bool insertAgentRow(UserAgentData agentdata) - { - string sql = String.Empty; - sql += "REPLACE INTO "; - sql += "agents (UUID, sessionID, secureSessionID, agentIP, agentPort, agentOnline, loginTime, logoutTime, currentRegion, currentHandle, currentPos, currentLookAt) VALUES "; - sql += "(?UUID, ?sessionID, ?secureSessionID, ?agentIP, ?agentPort, ?agentOnline, ?loginTime, ?logoutTime, ?currentRegion, ?currentHandle, ?currentPos, ?currentLookAt);"; - Dictionary parameters = new Dictionary(); - - parameters["?UUID"] = agentdata.ProfileID.ToString(); - parameters["?sessionID"] = agentdata.SessionID.ToString(); - parameters["?secureSessionID"] = agentdata.SecureSessionID.ToString(); - parameters["?agentIP"] = agentdata.AgentIP.ToString(); - parameters["?agentPort"] = agentdata.AgentPort.ToString(); - parameters["?agentOnline"] = (agentdata.AgentOnline == true) ? "1" : "0"; - parameters["?loginTime"] = agentdata.LoginTime.ToString(); - parameters["?logoutTime"] = agentdata.LogoutTime.ToString(); - parameters["?currentRegion"] = agentdata.Region.ToString(); - parameters["?currentHandle"] = agentdata.Handle.ToString(); - parameters["?currentPos"] = "<" + (agentdata.Position.X).ToString().Replace(",", ".") + "," + (agentdata.Position.Y).ToString().Replace(",", ".") + "," + (agentdata.Position.Z).ToString().Replace(",", ".") + ">"; - parameters["?currentLookAt"] = "<" + (agentdata.LookAt.X).ToString().Replace(",", ".") + "," + (agentdata.LookAt.Y).ToString().Replace(",", ".") + "," + (agentdata.LookAt.Z).ToString().Replace(",", ".") + ">"; - - bool returnval = false; - - try - { - using (MySqlConnection dbcon = new MySqlConnection(connectionString)) - { - dbcon.Open(); - - IDbCommand result = Query(dbcon, sql, parameters); - - // int x; - // if ((x = result.ExecuteNonQuery()) > 0) - // { - // returnval = true; - // } - if (result.ExecuteNonQuery() > 0) - { - returnval = true; - } - result.Dispose(); - } - } - catch (Exception e) - { - m_log.Error(e.ToString()); - return false; - } - - return returnval; - } - - /// - /// Create (or replace if existing) an avatar appearence - /// - /// - /// Succes? - public bool insertAppearanceRow(AvatarAppearance appearance) - { - string sql = String.Empty; - sql += "REPLACE INTO "; - sql += "avatarappearance (owner, serial, visual_params, texture, avatar_height, "; - sql += "body_item, body_asset, skin_item, skin_asset, hair_item, hair_asset, eyes_item, eyes_asset, "; - sql += "shirt_item, shirt_asset, pants_item, pants_asset, shoes_item, shoes_asset, socks_item, socks_asset, "; - sql += "jacket_item, jacket_asset, gloves_item, gloves_asset, undershirt_item, undershirt_asset, underpants_item, underpants_asset, "; - sql += "skirt_item, skirt_asset) values ("; - sql += "?owner, ?serial, ?visual_params, ?texture, ?avatar_height, "; - sql += "?body_item, ?body_asset, ?skin_item, ?skin_asset, ?hair_item, ?hair_asset, ?eyes_item, ?eyes_asset, "; - sql += "?shirt_item, ?shirt_asset, ?pants_item, ?pants_asset, ?shoes_item, ?shoes_asset, ?socks_item, ?socks_asset, "; - sql += "?jacket_item, ?jacket_asset, ?gloves_item, ?gloves_asset, ?undershirt_item, ?undershirt_asset, ?underpants_item, ?underpants_asset, "; - sql += "?skirt_item, ?skirt_asset)"; - - bool returnval = false; - - // we want to send in byte data, which means we can't just pass down strings - try - { - using (MySqlConnection dbcon = new MySqlConnection(connectionString)) - { - dbcon.Open(); - - using (MySqlCommand cmd = (MySqlCommand)dbcon.CreateCommand()) - { - cmd.CommandText = sql; - cmd.Parameters.AddWithValue("?owner", appearance.Owner.ToString()); - cmd.Parameters.AddWithValue("?serial", appearance.Serial); - cmd.Parameters.AddWithValue("?visual_params", appearance.VisualParams); - cmd.Parameters.AddWithValue("?texture", appearance.Texture.GetBytes()); - cmd.Parameters.AddWithValue("?avatar_height", appearance.AvatarHeight); - cmd.Parameters.AddWithValue("?body_item", appearance.BodyItem.ToString()); - cmd.Parameters.AddWithValue("?body_asset", appearance.BodyAsset.ToString()); - cmd.Parameters.AddWithValue("?skin_item", appearance.SkinItem.ToString()); - cmd.Parameters.AddWithValue("?skin_asset", appearance.SkinAsset.ToString()); - cmd.Parameters.AddWithValue("?hair_item", appearance.HairItem.ToString()); - cmd.Parameters.AddWithValue("?hair_asset", appearance.HairAsset.ToString()); - cmd.Parameters.AddWithValue("?eyes_item", appearance.EyesItem.ToString()); - cmd.Parameters.AddWithValue("?eyes_asset", appearance.EyesAsset.ToString()); - cmd.Parameters.AddWithValue("?shirt_item", appearance.ShirtItem.ToString()); - cmd.Parameters.AddWithValue("?shirt_asset", appearance.ShirtAsset.ToString()); - cmd.Parameters.AddWithValue("?pants_item", appearance.PantsItem.ToString()); - cmd.Parameters.AddWithValue("?pants_asset", appearance.PantsAsset.ToString()); - cmd.Parameters.AddWithValue("?shoes_item", appearance.ShoesItem.ToString()); - cmd.Parameters.AddWithValue("?shoes_asset", appearance.ShoesAsset.ToString()); - cmd.Parameters.AddWithValue("?socks_item", appearance.SocksItem.ToString()); - cmd.Parameters.AddWithValue("?socks_asset", appearance.SocksAsset.ToString()); - cmd.Parameters.AddWithValue("?jacket_item", appearance.JacketItem.ToString()); - cmd.Parameters.AddWithValue("?jacket_asset", appearance.JacketAsset.ToString()); - cmd.Parameters.AddWithValue("?gloves_item", appearance.GlovesItem.ToString()); - cmd.Parameters.AddWithValue("?gloves_asset", appearance.GlovesAsset.ToString()); - cmd.Parameters.AddWithValue("?undershirt_item", appearance.UnderShirtItem.ToString()); - cmd.Parameters.AddWithValue("?undershirt_asset", appearance.UnderShirtAsset.ToString()); - cmd.Parameters.AddWithValue("?underpants_item", appearance.UnderPantsItem.ToString()); - cmd.Parameters.AddWithValue("?underpants_asset", appearance.UnderPantsAsset.ToString()); - cmd.Parameters.AddWithValue("?skirt_item", appearance.SkirtItem.ToString()); - cmd.Parameters.AddWithValue("?skirt_asset", appearance.SkirtAsset.ToString()); - - if (cmd.ExecuteNonQuery() > 0) - returnval = true; - } - } - } - catch (Exception e) - { - m_log.Error(e.ToString()); - return false; - } - - return returnval; - - } - - public void writeAttachments(UUID agentID, Hashtable data) - { - string sql = "delete from avatarattachments where UUID = ?uuid"; - - using (MySqlConnection dbcon = new MySqlConnection(connectionString)) - { - dbcon.Open(); - - MySqlCommand cmd = (MySqlCommand)dbcon.CreateCommand(); - cmd.CommandText = sql; - cmd.Parameters.AddWithValue("?uuid", agentID.ToString()); - - cmd.ExecuteNonQuery(); - - if (data == null) - return; - - sql = "insert into avatarattachments (UUID, attachpoint, item, asset) values (?uuid, ?attachpoint, ?item, ?asset)"; - - cmd = (MySqlCommand)dbcon.CreateCommand(); - cmd.CommandText = sql; - - foreach (DictionaryEntry e in data) - { - int attachpoint = Convert.ToInt32(e.Key); - - Hashtable item = (Hashtable)e.Value; - - cmd.Parameters.Clear(); - cmd.Parameters.AddWithValue("?uuid", agentID.ToString()); - cmd.Parameters.AddWithValue("?attachpoint", attachpoint); - cmd.Parameters.AddWithValue("?item", item["item"]); - cmd.Parameters.AddWithValue("?asset", item["asset"]); - - cmd.ExecuteNonQuery(); - } - } - } - } -} diff --git a/OpenSim/Data/MySQL/MySQLSuperManager.cs b/OpenSim/Data/MySQL/MySQLSuperManager.cs deleted file mode 100644 index c579432..0000000 --- a/OpenSim/Data/MySQL/MySQLSuperManager.cs +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System.Threading; - -namespace OpenSim.Data.MySQL -{ - public class MySQLSuperManager - { - public bool Locked; - private readonly Mutex m_lock = new Mutex(false); - public MySQLManager Manager; - public string Running; - - public void GetLock() - { - Locked = true; - m_lock.WaitOne(); - } - - public void Release() - { - m_lock.ReleaseMutex(); - Locked = false; - } - - } -} diff --git a/OpenSim/Data/MySQL/MySQLUserData.cs b/OpenSim/Data/MySQL/MySQLUserData.cs deleted file mode 100644 index 0a9d2e3..0000000 --- a/OpenSim/Data/MySQL/MySQLUserData.cs +++ /dev/null @@ -1,766 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Data; -using System.Reflection; -using System.Text.RegularExpressions; -using System.Threading; -using log4net; -using MySql.Data.MySqlClient; -using OpenMetaverse; -using OpenSim.Framework; - -namespace OpenSim.Data.MySQL -{ - /// - /// A database interface class to a user profile storage system - /// - public class MySQLUserData : UserDataBase - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private MySQLManager m_database; - private string m_connectionString; - private object m_dbLock = new object(); - - public int m_maxConnections = 10; - public int m_lastConnect; - - private string m_agentsTableName = "agents"; - private string m_usersTableName = "users"; - private string m_userFriendsTableName = "userfriends"; - private string m_appearanceTableName = "avatarappearance"; - private string m_attachmentsTableName = "avatarattachments"; - - public override void Initialise() - { - m_log.Info("[MySQLUserData]: " + Name + " cannot be default-initialized!"); - throw new PluginNotInitialisedException(Name); - } - - /// - /// Initialise User Interface - /// Loads and initialises the MySQL storage plugin - /// Warns and uses the obsolete mysql_connection.ini if connect string is empty. - /// Checks for migration - /// - /// connect string. - public override void Initialise(string connect) - { - m_connectionString = connect; - m_database = new MySQLManager(connect); - - // This actually does the roll forward assembly stuff - Assembly assem = GetType().Assembly; - - using (MySql.Data.MySqlClient.MySqlConnection dbcon = new MySql.Data.MySqlClient.MySqlConnection(m_connectionString)) - { - dbcon.Open(); - Migration m = new Migration(dbcon, assem, "UserStore"); - m.Update(); - } - } - - public override void Dispose() - { - } - - // see IUserDataPlugin - public override UserProfileData GetUserByName(string user, string last) - { - try - { - Dictionary param = new Dictionary(); - param["?first"] = user; - param["?second"] = last; - - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - using (IDbCommand result = m_database.Query(dbcon, - "SELECT * FROM " + m_usersTableName + " WHERE username = ?first AND lastname = ?second", param)) - { - using (IDataReader reader = result.ExecuteReader()) - { - UserProfileData row = m_database.readUserRow(reader); - return row; - } - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return null; - } - } - - #region User Friends List Data - - public override void AddNewUserFriend(UUID friendlistowner, UUID friend, uint perms) - { - int dtvalue = Util.UnixTimeSinceEpoch(); - - Dictionary param = new Dictionary(); - param["?ownerID"] = friendlistowner.ToString(); - param["?friendID"] = friend.ToString(); - param["?friendPerms"] = perms.ToString(); - param["?datetimestamp"] = dtvalue.ToString(); - - try - { - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - using (IDbCommand adder = m_database.Query(dbcon, - "INSERT INTO `" + m_userFriendsTableName + "` " + - "(`ownerID`,`friendID`,`friendPerms`,`datetimestamp`) " + - "VALUES " + - "(?ownerID,?friendID,?friendPerms,?datetimestamp)", - param)) - { - adder.ExecuteNonQuery(); - } - - using (IDbCommand adder = m_database.Query(dbcon, - "INSERT INTO `" + m_userFriendsTableName + "` " + - "(`ownerID`,`friendID`,`friendPerms`,`datetimestamp`) " + - "VALUES " + - "(?friendID,?ownerID,?friendPerms,?datetimestamp)", - param)) - { - adder.ExecuteNonQuery(); - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return; - } - } - - public override void RemoveUserFriend(UUID friendlistowner, UUID friend) - { - Dictionary param = new Dictionary(); - param["?ownerID"] = friendlistowner.ToString(); - param["?friendID"] = friend.ToString(); - - try - { - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - using (IDbCommand updater = m_database.Query(dbcon, - "delete from " + m_userFriendsTableName + " where ownerID = ?ownerID and friendID = ?friendID", - param)) - { - updater.ExecuteNonQuery(); - } - - using (IDbCommand updater = m_database.Query(dbcon, - "delete from " + m_userFriendsTableName + " where ownerID = ?friendID and friendID = ?ownerID", - param)) - { - updater.ExecuteNonQuery(); - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return; - } - } - - public override void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms) - { - Dictionary param = new Dictionary(); - param["?ownerID"] = friendlistowner.ToString(); - param["?friendID"] = friend.ToString(); - param["?friendPerms"] = perms.ToString(); - - try - { - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - using (IDbCommand updater = m_database.Query(dbcon, - "update " + m_userFriendsTableName + - " SET friendPerms = ?friendPerms " + - "where ownerID = ?ownerID and friendID = ?friendID", - param)) - { - updater.ExecuteNonQuery(); - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return; - } - } - - public override List GetUserFriendList(UUID friendlistowner) - { - List Lfli = new List(); - - Dictionary param = new Dictionary(); - param["?ownerID"] = friendlistowner.ToString(); - - try - { - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - //Left Join userfriends to itself - using (IDbCommand result = m_database.Query(dbcon, - "select a.ownerID,a.friendID,a.friendPerms,b.friendPerms as ownerperms from " + - m_userFriendsTableName + " as a, " + m_userFriendsTableName + " as b" + - " where a.ownerID = ?ownerID and b.ownerID = a.friendID and b.friendID = a.ownerID", - param)) - { - using (IDataReader reader = result.ExecuteReader()) - { - while (reader.Read()) - { - FriendListItem fli = new FriendListItem(); - fli.FriendListOwner = new UUID((string)reader["ownerID"]); - fli.Friend = new UUID((string)reader["friendID"]); - fli.FriendPerms = (uint)Convert.ToInt32(reader["friendPerms"]); - - // This is not a real column in the database table, it's a joined column from the opposite record - fli.FriendListOwnerPerms = (uint)Convert.ToInt32(reader["ownerperms"]); - - Lfli.Add(fli); - } - } - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return Lfli; - } - - return Lfli; - } - - override public Dictionary GetFriendRegionInfos (List uuids) - { - Dictionary infos = new Dictionary(); - - try - { - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - foreach (UUID uuid in uuids) - { - Dictionary param = new Dictionary(); - param["?uuid"] = uuid.ToString(); - - using (IDbCommand result = m_database.Query(dbcon, "select agentOnline,currentHandle from " + m_agentsTableName + - " where UUID = ?uuid", param)) - { - using (IDataReader reader = result.ExecuteReader()) - { - while (reader.Read()) - { - FriendRegionInfo fri = new FriendRegionInfo(); - fri.isOnline = (sbyte)reader["agentOnline"] != 0; - fri.regionHandle = (ulong)reader["currentHandle"]; - - infos[uuid] = fri; - } - } - } - } - } - } - catch (Exception e) - { - m_log.Warn("[MYSQL]: Got exception on trying to find friends regions:", e); - m_log.Error(e.Message, e); - } - - return infos; - } - - #endregion - - public override List GeneratePickerResults(UUID queryID, string query) - { - List returnlist = new List(); - - Regex objAlphaNumericPattern = new Regex("[^a-zA-Z0-9]"); - - string[] querysplit; - querysplit = query.Split(' '); - if (querysplit.Length > 1 && querysplit[1].Trim() != String.Empty) - { - Dictionary param = new Dictionary(); - param["?first"] = objAlphaNumericPattern.Replace(querysplit[0], String.Empty) + "%"; - param["?second"] = objAlphaNumericPattern.Replace(querysplit[1], String.Empty) + "%"; - - try - { - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - using (IDbCommand result = m_database.Query(dbcon, - "SELECT UUID,username,lastname FROM " + m_usersTableName + - " WHERE username like ?first AND lastname like ?second LIMIT 100", - param)) - { - using (IDataReader reader = result.ExecuteReader()) - { - while (reader.Read()) - { - AvatarPickerAvatar user = new AvatarPickerAvatar(); - user.AvatarID = new UUID((string)reader["UUID"]); - user.firstName = (string)reader["username"]; - user.lastName = (string)reader["lastname"]; - returnlist.Add(user); - } - } - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return returnlist; - } - } - else - { - try - { - Dictionary param = new Dictionary(); - param["?first"] = objAlphaNumericPattern.Replace(querysplit[0], String.Empty) + "%"; - - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - using (IDbCommand result = m_database.Query(dbcon, - "SELECT UUID,username,lastname FROM " + m_usersTableName + - " WHERE username like ?first OR lastname like ?first LIMIT 100", - param)) - { - using (IDataReader reader = result.ExecuteReader()) - { - while (reader.Read()) - { - AvatarPickerAvatar user = new AvatarPickerAvatar(); - user.AvatarID = new UUID((string)reader["UUID"]); - user.firstName = (string)reader["username"]; - user.lastName = (string)reader["lastname"]; - returnlist.Add(user); - } - } - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return returnlist; - } - } - return returnlist; - } - - /// - /// See IUserDataPlugin - /// - /// User UUID - /// User profile data - public override UserProfileData GetUserByUUID(UUID uuid) - { - try - { - Dictionary param = new Dictionary(); - param["?uuid"] = uuid.ToString(); - - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - using (IDbCommand result = m_database.Query(dbcon, "SELECT * FROM " + m_usersTableName + " WHERE UUID = ?uuid", param)) - { - using (IDataReader reader = result.ExecuteReader()) - { - UserProfileData row = m_database.readUserRow(reader); - return row; - } - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return null; - } - } - - /// - /// Returns a user session searching by name - /// - /// The account name : "Username Lastname" - /// The users session - public override UserAgentData GetAgentByName(string name) - { - return GetAgentByName(name.Split(' ')[0], name.Split(' ')[1]); - } - - /// - /// Returns a user session by account name - /// - /// First part of the users account name - /// Second part of the users account name - /// The users session - public override UserAgentData GetAgentByName(string user, string last) - { - UserProfileData profile = GetUserByName(user, last); - return GetAgentByUUID(profile.ID); - } - - /// - /// - /// - /// - /// is it still used ? - public override void StoreWebLoginKey(UUID AgentID, UUID WebLoginKey) - { - Dictionary param = new Dictionary(); - param["?UUID"] = AgentID.ToString(); - param["?webLoginKey"] = WebLoginKey.ToString(); - - try - { - m_database.ExecuteParameterizedSql( - "update " + m_usersTableName + " SET webLoginKey = ?webLoginKey " + - "where UUID = ?UUID", - param); - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return; - } - } - - /// - /// Returns an agent session by account UUID - /// - /// The accounts UUID - /// The users session - public override UserAgentData GetAgentByUUID(UUID uuid) - { - try - { - Dictionary param = new Dictionary(); - param["?uuid"] = uuid.ToString(); - - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - using (IDbCommand result = m_database.Query(dbcon, "SELECT * FROM " + m_agentsTableName + " WHERE UUID = ?uuid", param)) - { - using (IDataReader reader = result.ExecuteReader()) - { - UserAgentData row = m_database.readAgentRow(reader); - return row; - } - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return null; - } - } - - /// - /// Creates a new users profile - /// - /// The user profile to create - public override void AddNewUserProfile(UserProfileData user) - { - UUID zero = UUID.Zero; - if (user.ID == zero) - { - return; - } - - try - { - m_database.insertUserRow( - user.ID, user.FirstName, user.SurName, user.Email, user.PasswordHash, user.PasswordSalt, - user.HomeRegion, user.HomeRegionID, user.HomeLocation.X, user.HomeLocation.Y, - user.HomeLocation.Z, - user.HomeLookAt.X, user.HomeLookAt.Y, user.HomeLookAt.Z, user.Created, - user.LastLogin, user.UserInventoryURI, user.UserAssetURI, - user.CanDoMask, user.WantDoMask, - user.AboutText, user.FirstLifeAboutText, user.Image, - user.FirstLifeImage, user.WebLoginKey, user.UserFlags, user.GodLevel, user.CustomType, user.Partner); - } - catch (Exception e) - { - m_log.Error(e.Message, e); - } - } - - /// - /// Creates a new agent - /// - /// The agent to create - public override void AddNewUserAgent(UserAgentData agent) - { - UUID zero = UUID.Zero; - if (agent.ProfileID == zero || agent.SessionID == zero) - return; - - try - { - m_database.insertAgentRow(agent); - } - catch (Exception e) - { - m_log.Error(e.Message, e); - } - } - - /// - /// Updates a user profile stored in the DB - /// - /// The profile data to use to update the DB - public override bool UpdateUserProfile(UserProfileData user) - { - try - { - m_database.updateUserRow( - user.ID, user.FirstName, user.SurName, user.Email, user.PasswordHash, user.PasswordSalt, - user.HomeRegion, user.HomeRegionID, user.HomeLocation.X, user.HomeLocation.Y, - user.HomeLocation.Z, user.HomeLookAt.X, - user.HomeLookAt.Y, user.HomeLookAt.Z, user.Created, user.LastLogin, - user.UserInventoryURI, - user.UserAssetURI, user.CanDoMask, user.WantDoMask, user.AboutText, - user.FirstLifeAboutText, user.Image, user.FirstLifeImage, user.WebLoginKey, - user.UserFlags, user.GodLevel, user.CustomType, user.Partner); - - return true; - } - catch - { - return false; - } - } - - /// - /// Performs a money transfer request between two accounts - /// - /// The senders account ID - /// The receivers account ID - /// The amount to transfer - /// Success? - public override bool MoneyTransferRequest(UUID from, UUID to, uint amount) - { - return false; - } - - /// - /// Performs an inventory transfer request between two accounts - /// - /// TODO: Move to inventory server - /// The senders account ID - /// The receivers account ID - /// The item to transfer - /// Success? - public override bool InventoryTransferRequest(UUID from, UUID to, UUID item) - { - return false; - } - - public override AvatarAppearance GetUserAppearance(UUID user) - { - try - { - Dictionary param = new Dictionary(); - param["?owner"] = user.ToString(); - - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - using (IDbCommand result = m_database.Query(dbcon, "SELECT * FROM " + m_appearanceTableName + " WHERE owner = ?owner", param)) - { - using (IDataReader reader = result.ExecuteReader()) - { - AvatarAppearance appearance = m_database.readAppearanceRow(reader); - - if (appearance == null) - { - m_log.WarnFormat("[USER DB] No appearance found for user {0}", user.ToString()); - return null; - } - else - { - appearance.SetAttachments(GetUserAttachments(user)); - return appearance; - } - } - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return null; - } - } - - /// - /// Updates an avatar appearence - /// - /// The user UUID - /// The avatar appearance - // override - public override void UpdateUserAppearance(UUID user, AvatarAppearance appearance) - { - try - { - appearance.Owner = user; - m_database.insertAppearanceRow(appearance); - - UpdateUserAttachments(user, appearance.GetAttachments()); - } - catch (Exception e) - { - m_log.Error(e.Message, e); - } - } - - /// - /// Database provider name - /// - /// Provider name - public override string Name - { - get { return "MySQL Userdata Interface"; } - } - - /// - /// Database provider version - /// - /// provider version - public override string Version - { - get { return "0.1"; } - } - - public Hashtable GetUserAttachments(UUID agentID) - { - Dictionary param = new Dictionary(); - param["?uuid"] = agentID.ToString(); - - try - { - using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) - { - dbcon.Open(); - - using (IDbCommand result = m_database.Query(dbcon, - "SELECT attachpoint, item, asset from " + m_attachmentsTableName + " WHERE UUID = ?uuid", param)) - { - using (IDataReader reader = result.ExecuteReader()) - { - Hashtable ret = m_database.readAttachments(reader); - return ret; - } - } - } - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return null; - } - } - - public void UpdateUserAttachments(UUID agentID, Hashtable data) - { - m_database.writeAttachments(agentID, data); - } - - public override void ResetAttachments(UUID userID) - { - Dictionary param = new Dictionary(); - param["?uuid"] = userID.ToString(); - - m_database.ExecuteParameterizedSql( - "UPDATE " + m_attachmentsTableName + - " SET asset = '00000000-0000-0000-0000-000000000000' WHERE UUID = ?uuid", - param); - } - - public override void LogoutUsers(UUID regionID) - { - Dictionary param = new Dictionary(); - param["?regionID"] = regionID.ToString(); - - try - { - m_database.ExecuteParameterizedSql( - "update " + m_agentsTableName + " SET agentOnline = 0 " + - "where currentRegion = ?regionID", - param); - } - catch (Exception e) - { - m_log.Error(e.Message, e); - return; - } - } - } -} diff --git a/OpenSim/Data/MySQL/Tests/MySQLAssetTest.cs b/OpenSim/Data/MySQL/Tests/MySQLAssetTest.cs index e1d3f81..a46fdf8 100644 --- a/OpenSim/Data/MySQL/Tests/MySQLAssetTest.cs +++ b/OpenSim/Data/MySQL/Tests/MySQLAssetTest.cs @@ -31,6 +31,7 @@ using OpenSim.Data.Tests; using log4net; using System.Reflection; using OpenSim.Tests.Common; +using MySql.Data.MySqlClient; namespace OpenSim.Data.MySQL.Tests { @@ -39,7 +40,7 @@ namespace OpenSim.Data.MySQL.Tests { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public string file; - public MySQLManager database; + private string m_connectionString; public string connect = "Server=localhost;Port=3306;Database=opensim-nunit;User ID=opensim-nunit;Password=opensim-nunit;Pooling=false;"; [TestFixtureSetUp] @@ -52,7 +53,6 @@ namespace OpenSim.Data.MySQL.Tests // tests. try { - database = new MySQLManager(connect); db = new MySQLAssetData(); db.Initialise(connect); } @@ -70,10 +70,22 @@ namespace OpenSim.Data.MySQL.Tests { db.Dispose(); } - if (database != null) + ExecuteSql("drop table migrations"); + ExecuteSql("drop table assets"); + } + + /// + /// Execute a MySqlCommand + /// + /// sql string to execute + private void ExecuteSql(string sql) + { + using (MySqlConnection dbcon = new MySqlConnection(connect)) { - database.ExecuteSql("drop table migrations"); - database.ExecuteSql("drop table assets"); + dbcon.Open(); + + MySqlCommand cmd = new MySqlCommand(sql, dbcon); + cmd.ExecuteNonQuery(); } } } diff --git a/OpenSim/Data/MySQL/Tests/MySQLEstateTest.cs b/OpenSim/Data/MySQL/Tests/MySQLEstateTest.cs index 48486b1..01afcae 100644 --- a/OpenSim/Data/MySQL/Tests/MySQLEstateTest.cs +++ b/OpenSim/Data/MySQL/Tests/MySQLEstateTest.cs @@ -31,6 +31,8 @@ using OpenSim.Data.Tests; using log4net; using System.Reflection; using OpenSim.Tests.Common; +using MySql.Data.MySqlClient; + namespace OpenSim.Data.MySQL.Tests { @@ -39,7 +41,6 @@ namespace OpenSim.Data.MySQL.Tests { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public string file; - public MySQLManager database; public string connect = "Server=localhost;Port=3306;Database=opensim-nunit;User ID=opensim-nunit;Password=opensim-nunit;Pooling=false;"; [TestFixtureSetUp] @@ -52,9 +53,8 @@ namespace OpenSim.Data.MySQL.Tests // tests. try { - database = new MySQLManager(connect); // clear db incase to ensure we are in a clean state - ClearDB(database); + ClearDB(); regionDb = new MySQLDataStore(); regionDb.Initialise(connect); @@ -75,29 +75,41 @@ namespace OpenSim.Data.MySQL.Tests { regionDb.Dispose(); } - ClearDB(database); + ClearDB(); } - private void ClearDB(MySQLManager manager) + private void ClearDB() { // if a new table is added, it has to be dropped here - if (manager != null) + ExecuteSql("drop table if exists migrations"); + ExecuteSql("drop table if exists prims"); + ExecuteSql("drop table if exists primshapes"); + ExecuteSql("drop table if exists primitems"); + ExecuteSql("drop table if exists terrain"); + ExecuteSql("drop table if exists land"); + ExecuteSql("drop table if exists landaccesslist"); + ExecuteSql("drop table if exists regionban"); + ExecuteSql("drop table if exists regionsettings"); + ExecuteSql("drop table if exists estate_managers"); + ExecuteSql("drop table if exists estate_groups"); + ExecuteSql("drop table if exists estate_users"); + ExecuteSql("drop table if exists estateban"); + ExecuteSql("drop table if exists estate_settings"); + ExecuteSql("drop table if exists estate_map"); + } + + /// + /// Execute a MySqlCommand + /// + /// sql string to execute + private void ExecuteSql(string sql) + { + using (MySqlConnection dbcon = new MySqlConnection(connect)) { - manager.ExecuteSql("drop table if exists migrations"); - manager.ExecuteSql("drop table if exists prims"); - manager.ExecuteSql("drop table if exists primshapes"); - manager.ExecuteSql("drop table if exists primitems"); - manager.ExecuteSql("drop table if exists terrain"); - manager.ExecuteSql("drop table if exists land"); - manager.ExecuteSql("drop table if exists landaccesslist"); - manager.ExecuteSql("drop table if exists regionban"); - manager.ExecuteSql("drop table if exists regionsettings"); - manager.ExecuteSql("drop table if exists estate_managers"); - manager.ExecuteSql("drop table if exists estate_groups"); - manager.ExecuteSql("drop table if exists estate_users"); - manager.ExecuteSql("drop table if exists estateban"); - manager.ExecuteSql("drop table if exists estate_settings"); - manager.ExecuteSql("drop table if exists estate_map"); + dbcon.Open(); + + MySqlCommand cmd = new MySqlCommand(sql, dbcon); + cmd.ExecuteNonQuery(); } } } diff --git a/OpenSim/Data/MySQL/Tests/MySQLGridTest.cs b/OpenSim/Data/MySQL/Tests/MySQLGridTest.cs deleted file mode 100644 index 8272316..0000000 --- a/OpenSim/Data/MySQL/Tests/MySQLGridTest.cs +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using NUnit.Framework; -using OpenSim.Data.Tests; -using log4net; -using System.Reflection; -using OpenSim.Tests.Common; -using MySql.Data.MySqlClient; - -namespace OpenSim.Data.MySQL.Tests -{ - [TestFixture, DatabaseTest] - public class MySQLGridTest : BasicGridTest - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - public string file; - public MySQLManager database; - public string connect = "Server=localhost;Port=3306;Database=opensim-nunit;User ID=opensim-nunit;Password=opensim-nunit;Pooling=false;"; - - [TestFixtureSetUp] - public void Init() - { - SuperInit(); - // If we manage to connect to the database with the user - // and password above it is our test database, and run - // these tests. If anything goes wrong, ignore these - // tests. - try - { - database = new MySQLManager(connect); - db = new MySQLGridData(); - db.Initialise(connect); - } - catch (Exception e) - { - m_log.Error("Exception {0}", e); - Assert.Ignore(); - } - - // This actually does the roll forward assembly stuff - Assembly assem = GetType().Assembly; - - using (MySqlConnection dbcon = new MySqlConnection(connect)) - { - dbcon.Open(); - Migration m = new Migration(dbcon, assem, "AssetStore"); - m.Update(); - } - } - - [TestFixtureTearDown] - public void Cleanup() - { - m_log.Warn("Cleaning up."); - if (db != null) - { - db.Dispose(); - } - // if a new table is added, it has to be dropped here - if (database != null) - { - database.ExecuteSql("drop table migrations"); - database.ExecuteSql("drop table regions"); - } - } - } -} diff --git a/OpenSim/Data/MySQL/Tests/MySQLInventoryTest.cs b/OpenSim/Data/MySQL/Tests/MySQLInventoryTest.cs index a3a32dc..4575493 100644 --- a/OpenSim/Data/MySQL/Tests/MySQLInventoryTest.cs +++ b/OpenSim/Data/MySQL/Tests/MySQLInventoryTest.cs @@ -31,6 +31,8 @@ using OpenSim.Data.Tests; using log4net; using System.Reflection; using OpenSim.Tests.Common; +using MySql.Data.MySqlClient; + namespace OpenSim.Data.MySQL.Tests { @@ -39,7 +41,6 @@ namespace OpenSim.Data.MySQL.Tests { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public string file; - public MySQLManager database; public string connect = "Server=localhost;Port=3306;Database=opensim-nunit;User ID=opensim-nunit;Password=opensim-nunit;Pooling=false;"; [TestFixtureSetUp] @@ -52,7 +53,6 @@ namespace OpenSim.Data.MySQL.Tests // tests. try { - database = new MySQLManager(connect); DropTables(); db = new MySQLInventoryData(); db.Initialise(connect); @@ -71,17 +71,29 @@ namespace OpenSim.Data.MySQL.Tests { db.Dispose(); } - if (database != null) - { - DropTables(); - } + DropTables(); } private void DropTables() { - database.ExecuteSql("drop table IF EXISTS inventoryitems"); - database.ExecuteSql("drop table IF EXISTS inventoryfolders"); - database.ExecuteSql("drop table IF EXISTS migrations"); + ExecuteSql("drop table IF EXISTS inventoryitems"); + ExecuteSql("drop table IF EXISTS inventoryfolders"); + ExecuteSql("drop table IF EXISTS migrations"); + } + + /// + /// Execute a MySqlCommand + /// + /// sql string to execute + private void ExecuteSql(string sql) + { + using (MySqlConnection dbcon = new MySqlConnection(connect)) + { + dbcon.Open(); + + MySqlCommand cmd = new MySqlCommand(sql, dbcon); + cmd.ExecuteNonQuery(); + } } } } diff --git a/OpenSim/Data/MySQL/Tests/MySQLRegionTest.cs b/OpenSim/Data/MySQL/Tests/MySQLRegionTest.cs index 0dc8b7d..e7e57e4 100644 --- a/OpenSim/Data/MySQL/Tests/MySQLRegionTest.cs +++ b/OpenSim/Data/MySQL/Tests/MySQLRegionTest.cs @@ -31,6 +31,7 @@ using OpenSim.Data.Tests; using log4net; using System.Reflection; using OpenSim.Tests.Common; +using MySql.Data.MySqlClient; namespace OpenSim.Data.MySQL.Tests { @@ -39,7 +40,6 @@ namespace OpenSim.Data.MySQL.Tests { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public string file; - public MySQLManager database; public string connect = "Server=localhost;Port=3306;Database=opensim-nunit;User ID=opensim-nunit;Password=opensim-nunit;Pooling=false;"; [TestFixtureSetUp] @@ -52,9 +52,8 @@ namespace OpenSim.Data.MySQL.Tests // tests. try { - database = new MySQLManager(connect); // this is important in case a previous run ended badly - ClearDB(database); + ClearDB(); db = new MySQLDataStore(); db.Initialise(connect); @@ -73,28 +72,40 @@ namespace OpenSim.Data.MySQL.Tests { db.Dispose(); } - ClearDB(database); + ClearDB(); } - private void ClearDB(MySQLManager manager) + private void ClearDB() { - if (manager != null) + ExecuteSql("drop table if exists migrations"); + ExecuteSql("drop table if exists prims"); + ExecuteSql("drop table if exists primshapes"); + ExecuteSql("drop table if exists primitems"); + ExecuteSql("drop table if exists terrain"); + ExecuteSql("drop table if exists land"); + ExecuteSql("drop table if exists landaccesslist"); + ExecuteSql("drop table if exists regionban"); + ExecuteSql("drop table if exists regionsettings"); + ExecuteSql("drop table if exists estate_managers"); + ExecuteSql("drop table if exists estate_groups"); + ExecuteSql("drop table if exists estate_users"); + ExecuteSql("drop table if exists estateban"); + ExecuteSql("drop table if exists estate_settings"); + ExecuteSql("drop table if exists estate_map"); + } + + /// + /// Execute a MySqlCommand + /// + /// sql string to execute + private void ExecuteSql(string sql) + { + using (MySqlConnection dbcon = new MySqlConnection(connect)) { - manager.ExecuteSql("drop table if exists migrations"); - manager.ExecuteSql("drop table if exists prims"); - manager.ExecuteSql("drop table if exists primshapes"); - manager.ExecuteSql("drop table if exists primitems"); - manager.ExecuteSql("drop table if exists terrain"); - manager.ExecuteSql("drop table if exists land"); - manager.ExecuteSql("drop table if exists landaccesslist"); - manager.ExecuteSql("drop table if exists regionban"); - manager.ExecuteSql("drop table if exists regionsettings"); - manager.ExecuteSql("drop table if exists estate_managers"); - manager.ExecuteSql("drop table if exists estate_groups"); - manager.ExecuteSql("drop table if exists estate_users"); - manager.ExecuteSql("drop table if exists estateban"); - manager.ExecuteSql("drop table if exists estate_settings"); - manager.ExecuteSql("drop table if exists estate_map"); + dbcon.Open(); + + MySqlCommand cmd = new MySqlCommand(sql, dbcon); + cmd.ExecuteNonQuery(); } } } diff --git a/OpenSim/Data/MySQL/Tests/MySQLUserTest.cs b/OpenSim/Data/MySQL/Tests/MySQLUserTest.cs deleted file mode 100644 index cf8139a..0000000 --- a/OpenSim/Data/MySQL/Tests/MySQLUserTest.cs +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using NUnit.Framework; -using OpenSim.Data.Tests; -using log4net; -using System.Reflection; -using OpenSim.Tests.Common; - -namespace OpenSim.Data.MySQL.Tests -{ - [TestFixture, DatabaseTest] - public class MySQLUserTest : BasicUserTest - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - public string file; - public MySQLManager database; - public string connect = "Server=localhost;Port=3306;Database=opensim-nunit;User ID=opensim-nunit;Password=opensim-nunit;Pooling=false;"; - - [TestFixtureSetUp] - public void Init() - { - SuperInit(); - // If we manage to connect to the database with the user - // and password above it is our test database, and run - // these tests. If anything goes wrong, ignore these - // tests. - try - { - database = new MySQLManager(connect); - db = new MySQLUserData(); - db.Initialise(connect); - } - catch (Exception e) - { - m_log.Error("Exception {0}", e); - Assert.Ignore(); - } - } - - [TestFixtureTearDown] - public void Cleanup() - { - if (db != null) - { - db.Dispose(); - } - // if a new table is added, it has to be dropped here - if (database != null) - { - database.ExecuteSql("drop table migrations"); - database.ExecuteSql("drop table users"); - database.ExecuteSql("drop table userfriends"); - database.ExecuteSql("drop table agents"); - database.ExecuteSql("drop table avatarappearance"); - database.ExecuteSql("drop table avatarattachments"); - } - } - } -} diff --git a/OpenSim/Data/RegionProfileData.cs b/OpenSim/Data/RegionProfileData.cs deleted file mode 100644 index 90713d2..0000000 --- a/OpenSim/Data/RegionProfileData.cs +++ /dev/null @@ -1,337 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using Nwc.XmlRpc; -using OpenMetaverse; -using OpenSim.Framework; - -namespace OpenSim.Data -{ - /// - /// A class which contains information known to the grid server about a region - /// - [Serializable] - public class RegionProfileData - { - /// - /// The name of the region - /// - public string regionName = String.Empty; - - /// - /// A 64-bit number combining map position into a (mostly) unique ID - /// - public ulong regionHandle; - - /// - /// OGS/OpenSim Specific ID for a region - /// - public UUID UUID; - - /// - /// Coordinates of the region - /// - public uint regionLocX; - public uint regionLocY; - public uint regionLocZ; // Reserved (round-robin, layers, etc) - - /// - /// Authentication secrets - /// - /// Not very secure, needs improvement. - public string regionSendKey = String.Empty; - public string regionRecvKey = String.Empty; - public string regionSecret = String.Empty; - - /// - /// Whether the region is online - /// - public bool regionOnline; - - /// - /// Information about the server that the region is currently hosted on - /// - public string serverIP = String.Empty; - public uint serverPort; - public string serverURI = String.Empty; - - public uint httpPort; - public uint remotingPort; - public string httpServerURI = String.Empty; - - /// - /// Set of optional overrides. Can be used to create non-eulicidean spaces. - /// - public ulong regionNorthOverrideHandle; - public ulong regionSouthOverrideHandle; - public ulong regionEastOverrideHandle; - public ulong regionWestOverrideHandle; - - /// - /// Optional: URI Location of the region database - /// - /// Used for floating sim pools where the region data is not nessecarily coupled to a specific server - public string regionDataURI = String.Empty; - - /// - /// Region Asset Details - /// - public string regionAssetURI = String.Empty; - - public string regionAssetSendKey = String.Empty; - public string regionAssetRecvKey = String.Empty; - - /// - /// Region Userserver Details - /// - public string regionUserURI = String.Empty; - - public string regionUserSendKey = String.Empty; - public string regionUserRecvKey = String.Empty; - - /// - /// Region Map Texture Asset - /// - public UUID regionMapTextureID = new UUID("00000000-0000-1111-9999-000000000006"); - - /// - /// this particular mod to the file provides support within the spec for RegionProfileData for the - /// owner_uuid for the region - /// - public UUID owner_uuid = UUID.Zero; - - /// - /// OGS/OpenSim Specific original ID for a region after move/split - /// - public UUID originUUID; - - /// - /// The Maturity rating of the region - /// - public uint maturity; - - //Data Wrappers - public string RegionName - { - get { return regionName; } - set { regionName = value; } - } - public ulong RegionHandle - { - get { return regionHandle; } - set { regionHandle = value; } - } - public UUID Uuid - { - get { return UUID; } - set { UUID = value; } - } - public uint RegionLocX - { - get { return regionLocX; } - set { regionLocX = value; } - } - public uint RegionLocY - { - get { return regionLocY; } - set { regionLocY = value; } - } - public uint RegionLocZ - { - get { return regionLocZ; } - set { regionLocZ = value; } - } - public string RegionSendKey - { - get { return regionSendKey; } - set { regionSendKey = value; } - } - public string RegionRecvKey - { - get { return regionRecvKey; } - set { regionRecvKey = value; } - } - public string RegionSecret - { - get { return regionSecret; } - set { regionSecret = value; } - } - public bool RegionOnline - { - get { return regionOnline; } - set { regionOnline = value; } - } - public string ServerIP - { - get { return serverIP; } - set { serverIP = value; } - } - public uint ServerPort - { - get { return serverPort; } - set { serverPort = value; } - } - public string ServerURI - { - get { return serverURI; } - set { serverURI = value; } - } - public uint ServerHttpPort - { - get { return httpPort; } - set { httpPort = value; } - } - public uint ServerRemotingPort - { - get { return remotingPort; } - set { remotingPort = value; } - } - - public ulong NorthOverrideHandle - { - get { return regionNorthOverrideHandle; } - set { regionNorthOverrideHandle = value; } - } - public ulong SouthOverrideHandle - { - get { return regionSouthOverrideHandle; } - set { regionSouthOverrideHandle = value; } - } - public ulong EastOverrideHandle - { - get { return regionEastOverrideHandle; } - set { regionEastOverrideHandle = value; } - } - public ulong WestOverrideHandle - { - get { return regionWestOverrideHandle; } - set { regionWestOverrideHandle = value; } - } - public string RegionDataURI - { - get { return regionDataURI; } - set { regionDataURI = value; } - } - public string RegionAssetURI - { - get { return regionAssetURI; } - set { regionAssetURI = value; } - } - public string RegionAssetSendKey - { - get { return regionAssetSendKey; } - set { regionAssetSendKey = value; } - } - public string RegionAssetRecvKey - { - get { return regionAssetRecvKey; } - set { regionAssetRecvKey = value; } - } - public string RegionUserURI - { - get { return regionUserURI; } - set { regionUserURI = value; } - } - public string RegionUserSendKey - { - get { return regionUserSendKey; } - set { regionUserSendKey = value; } - } - public string RegionUserRecvKey - { - get { return regionUserRecvKey; } - set { regionUserRecvKey = value; } - } - public UUID RegionMapTextureID - { - get { return regionMapTextureID; } - set { regionMapTextureID = value; } - } - public UUID Owner_uuid - { - get { return owner_uuid; } - set { owner_uuid = value; } - } - public UUID OriginUUID - { - get { return originUUID; } - set { originUUID = value; } - } - public uint Maturity - { - get { return maturity; } - set { maturity = value; } - } - - public byte AccessLevel - { - get { return Util.ConvertMaturityToAccessLevel(maturity); } - } - - - public RegionInfo ToRegionInfo() - { - return RegionInfo.Create(UUID, regionName, regionLocX, regionLocY, serverIP, httpPort, serverPort, remotingPort, serverURI); - } - - public static RegionProfileData FromRegionInfo(RegionInfo regionInfo) - { - if (regionInfo == null) - { - return null; - } - - return Create(regionInfo.RegionID, regionInfo.RegionName, regionInfo.RegionLocX, - regionInfo.RegionLocY, regionInfo.ExternalHostName, - (uint) regionInfo.ExternalEndPoint.Port, regionInfo.HttpPort, regionInfo.RemotingPort, - regionInfo.ServerURI, regionInfo.AccessLevel); - } - - public static RegionProfileData Create(UUID regionID, string regionName, uint locX, uint locY, string externalHostName, uint regionPort, uint httpPort, uint remotingPort, string serverUri, byte access) - { - RegionProfileData regionProfile; - regionProfile = new RegionProfileData(); - regionProfile.regionLocX = locX; - regionProfile.regionLocY = locY; - regionProfile.regionHandle = - Utils.UIntsToLong((regionProfile.regionLocX * Constants.RegionSize), - (regionProfile.regionLocY*Constants.RegionSize)); - regionProfile.serverIP = externalHostName; - regionProfile.serverPort = regionPort; - regionProfile.httpPort = httpPort; - regionProfile.remotingPort = remotingPort; - regionProfile.serverURI = serverUri; - regionProfile.httpServerURI = "http://" + externalHostName + ":" + httpPort + "/"; - regionProfile.UUID = regionID; - regionProfile.regionName = regionName; - regionProfile.maturity = access; - return regionProfile; - } - } -} diff --git a/OpenSim/Data/RegionProfileServiceProxy.cs b/OpenSim/Data/RegionProfileServiceProxy.cs deleted file mode 100644 index 20d7df0..0000000 --- a/OpenSim/Data/RegionProfileServiceProxy.cs +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Text; -using Nwc.XmlRpc; -using OpenMetaverse; -using OpenSim.Framework; - -namespace OpenSim.Data -{ - public class RegionProfileServiceProxy : IRegionProfileRouter - { - /// - /// Request sim data based on arbitrary key/value - /// - private RegionProfileData RequestSimData(Uri gridserverUrl, string gridserverSendkey, string keyField, string keyValue) - { - Hashtable requestData = new Hashtable(); - requestData[keyField] = keyValue; - requestData["authkey"] = gridserverSendkey; - ArrayList SendParams = new ArrayList(); - SendParams.Add(requestData); - XmlRpcRequest GridReq = new XmlRpcRequest("simulator_data_request", SendParams); - XmlRpcResponse GridResp = GridReq.Send(gridserverUrl.ToString(), 3000); - - Hashtable responseData = (Hashtable) GridResp.Value; - - RegionProfileData simData = null; - - if (!responseData.ContainsKey("error")) - { - uint locX = Convert.ToUInt32((string)responseData["region_locx"]); - uint locY = Convert.ToUInt32((string)responseData["region_locy"]); - string externalHostName = (string)responseData["sim_ip"]; - uint simPort = Convert.ToUInt32((string)responseData["sim_port"]); - uint httpPort = Convert.ToUInt32((string)responseData["http_port"]); - uint remotingPort = Convert.ToUInt32((string)responseData["remoting_port"]); - string serverUri = (string)responseData["server_uri"]; - UUID regionID = new UUID((string)responseData["region_UUID"]); - string regionName = (string)responseData["region_name"]; - byte access = Convert.ToByte((string)responseData["access"]); - - simData = RegionProfileData.Create(regionID, regionName, locX, locY, externalHostName, simPort, httpPort, remotingPort, serverUri, access); - } - - return simData; - } - - /// - /// Request sim profile information from a grid server, by Region UUID - /// - /// The region UUID to look for - /// - /// - /// - /// The sim profile. Null if there was a request failure - /// This method should be statics - public RegionProfileData RequestSimProfileData(UUID regionId, Uri gridserverUrl, - string gridserverSendkey, string gridserverRecvkey) - { - return RequestSimData(gridserverUrl, gridserverSendkey, "region_UUID", regionId.Guid.ToString()); - } - - /// - /// Request sim profile information from a grid server, by Region Handle - /// - /// the region handle to look for - /// - /// - /// - /// The sim profile. Null if there was a request failure - public RegionProfileData RequestSimProfileData(ulong regionHandle, Uri gridserverUrl, - string gridserverSendkey, string gridserverRecvkey) - { - return RequestSimData(gridserverUrl, gridserverSendkey, "region_handle", regionHandle.ToString()); - } - - /// - /// Request sim profile information from a grid server, by Region Name - /// - /// the region name to look for - /// - /// - /// - /// The sim profile. Null if there was a request failure - public RegionProfileData RequestSimProfileData(string regionName, Uri gridserverUrl, - string gridserverSendkey, string gridserverRecvkey) - { - return RequestSimData(gridserverUrl, gridserverSendkey, "region_name_search", regionName); - } - } -} diff --git a/OpenSim/Data/ReservationData.cs b/OpenSim/Data/ReservationData.cs deleted file mode 100644 index 3956fe6..0000000 --- a/OpenSim/Data/ReservationData.cs +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using OpenMetaverse; - -namespace OpenSim.Data -{ - public class ReservationData - { - public UUID userUUID = UUID.Zero; - public int reservationMinX = 0; - public int reservationMinY = 0; - public int reservationMaxX = 65536; - public int reservationMaxY = 65536; - - public string reservationName = String.Empty; - public string reservationCompany = String.Empty; - public bool status = true; - - public string gridSendKey = String.Empty; - public string gridRecvKey = String.Empty; - } -} diff --git a/OpenSim/Data/SQLite/SQLiteGridData.cs b/OpenSim/Data/SQLite/SQLiteGridData.cs deleted file mode 100644 index 18abb88..0000000 --- a/OpenSim/Data/SQLite/SQLiteGridData.cs +++ /dev/null @@ -1,286 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.Data; -using System.Reflection; -using log4net; -using OpenMetaverse; -using OpenSim.Framework; - -namespace OpenSim.Data.SQLite -{ - /// - /// A Grid Interface to the SQLite database - /// - public class SQLiteGridData : GridDataBase - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - /// - /// SQLite database manager - /// - private SQLiteManager database; - - override public void Initialise() - { - m_log.Info("[SQLite]: " + Name + " cannot be default-initialized!"); - throw new PluginNotInitialisedException (Name); - } - - /// - /// - /// Initialises Inventory interface - /// Loads and initialises a new SQLite connection and maintains it. - /// use default URI if connect string is empty. - /// - /// - /// connect string - override public void Initialise(string connect) - { - database = new SQLiteManager(connect); - } - - /// - /// Shuts down the grid interface - /// - override public void Dispose() - { - database.Close(); - } - - /// - /// Returns the name of this grid interface - /// - /// A string containing the grid interface - override public string Name - { - get { return "SQLite OpenGridData"; } - } - - /// - /// Returns the version of this grid interface - /// - /// A string containing the version - override public string Version - { - get { return "0.1"; } - } - - /// - /// Returns a list of regions within the specified ranges - /// - /// minimum X coordinate - /// minimum Y coordinate - /// maximum X coordinate - /// maximum Y coordinate - /// An array of region profiles - /// NOT IMPLEMENTED ? always return null - override public RegionProfileData[] GetProfilesInRange(uint a, uint b, uint c, uint d) - { - return null; - } - - - /// - /// Returns up to maxNum profiles of regions that have a name starting with namePrefix - /// - /// The name to match against - /// Maximum number of profiles to return - /// A list of sim profiles - override public List GetRegionsByName (string namePrefix, uint maxNum) - { - return null; - } - - /// - /// Returns a sim profile from it's handle - /// - /// Region location handle - /// Sim profile - override public RegionProfileData GetProfileByHandle(ulong handle) - { - Dictionary param = new Dictionary(); - param["handle"] = handle.ToString(); - - IDbCommand result = database.Query("SELECT * FROM regions WHERE handle = @handle", param); - IDataReader reader = result.ExecuteReader(); - - RegionProfileData row = database.getRow(reader); - reader.Close(); - result.Dispose(); - - return row; - } - - /// - /// Returns a sim profile from it's Region name string - /// - /// The region name search query - /// The sim profile - override public RegionProfileData GetProfileByString(string regionName) - { - if (regionName.Length > 2) - { - Dictionary param = new Dictionary(); - // Add % because this is a like query. - param["?regionName"] = regionName + "%"; - // Only returns one record or no record. - IDbCommand result = database.Query("SELECT * FROM regions WHERE regionName like ?regionName LIMIT 1", param); - IDataReader reader = result.ExecuteReader(); - - RegionProfileData row = database.getRow(reader); - reader.Close(); - result.Dispose(); - - return row; - } - else - { - //m_log.Error("[DATABASE]: Searched for a Region Name shorter then 3 characters"); - return null; - } - } - - /// - /// Returns a sim profile from it's UUID - /// - /// The region UUID - /// The sim profile - override public RegionProfileData GetProfileByUUID(UUID uuid) - { - Dictionary param = new Dictionary(); - param["uuid"] = uuid.ToString(); - - IDbCommand result = database.Query("SELECT * FROM regions WHERE uuid = @uuid", param); - IDataReader reader = result.ExecuteReader(); - - RegionProfileData row = database.getRow(reader); - reader.Close(); - result.Dispose(); - - return row; - } - - /// - /// Returns a list of avatar and UUIDs that match the query - /// - /// do nothing yet - public List GeneratePickerResults(UUID queryID, string query) - { - //Do nothing yet - List returnlist = new List(); - return returnlist; - } - - /// - /// Adds a new specified region to the database - /// - /// The profile to add - /// A dataresponse enum indicating success - override public DataResponse StoreProfile(RegionProfileData profile) - { - if (database.insertRow(profile)) - { - return DataResponse.RESPONSE_OK; - } - else - { - return DataResponse.RESPONSE_ERROR; - } - } - - /// - /// Deletes a sim profile from the database - /// - /// the sim UUID - /// Successful? - override public DataResponse DeleteProfile(string uuid) - { - Dictionary param = new Dictionary(); - param["uuid"] = uuid; - - IDbCommand result = database.Query("DELETE FROM regions WHERE uuid = @uuid", param); - if (result.ExecuteNonQuery() > 0) - { - return DataResponse.RESPONSE_OK; - } - return DataResponse.RESPONSE_ERROR; - } - - /// - /// DEPRECATED. Attempts to authenticate a region by comparing a shared secret. - /// - /// The UUID of the challenger - /// The attempted regionHandle of the challenger - /// The secret - /// Whether the secret and regionhandle match the database entry for UUID - override public bool AuthenticateSim(UUID uuid, ulong handle, string authkey) - { - bool throwHissyFit = false; // Should be true by 1.0 - - if (throwHissyFit) - throw new Exception("CRYPTOWEAK AUTHENTICATE: Refusing to authenticate due to replay potential."); - - RegionProfileData data = GetProfileByUUID(uuid); - - return (handle == data.regionHandle && authkey == data.regionSecret); - } - - /// - /// NOT YET FUNCTIONAL. Provides a cryptographic authentication of a region - /// - /// This requires a security audit. - /// - /// - /// - /// - /// - public bool AuthenticateSim(UUID uuid, ulong handle, string authhash, string challenge) - { - // SHA512Managed HashProvider = new SHA512Managed(); - // Encoding TextProvider = new UTF8Encoding(); - - // byte[] stream = TextProvider.GetBytes(uuid.ToString() + ":" + handle.ToString() + ":" + challenge); - // byte[] hash = HashProvider.ComputeHash(stream); - - return false; - } - - /// - /// NOT IMPLEMENTED - /// - /// x coordinate - /// y coordinate - /// always return null - override public ReservationData GetReservationAtPoint(uint x, uint y) - { - return null; - } - } -} diff --git a/OpenSim/Data/SQLite/SQLiteManager.cs b/OpenSim/Data/SQLite/SQLiteManager.cs deleted file mode 100644 index b6d4a1c..0000000 --- a/OpenSim/Data/SQLite/SQLiteManager.cs +++ /dev/null @@ -1,225 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.SQLite; -using System.Reflection; -using log4net; -using OpenMetaverse; - -namespace OpenSim.Data.SQLite -{ - /// - /// SQLite Manager - /// - internal class SQLiteManager : SQLiteUtil - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - private IDbConnection dbcon; - - /// - /// - /// Initialises and creates a new SQLite connection and maintains it. - /// use default URI if connect string is empty. - /// - /// - /// connect string - public SQLiteManager(string connect) - { - try - { - string connectionString = String.Empty; - if (connect != String.Empty) - { - connectionString = connect; - } - else - { - m_log.Warn("[SQLITE] grid db not specified, using default"); - connectionString = "URI=file:GridServerSqlite.db;"; - } - - dbcon = new SQLiteConnection(connectionString); - - dbcon.Open(); - } - catch (Exception e) - { - throw new Exception("Error initialising SQLite Database: " + e.ToString()); - } - } - - /// - /// Shuts down the database connection - /// - public void Close() - { - dbcon.Close(); - dbcon = null; - } - - /// - /// Runs a query with protection against SQL Injection by using parameterised input. - /// - /// The SQL string - replace any variables such as WHERE x = "y" with WHERE x = @y - /// The parameters - index so that @y is indexed as 'y' - /// A SQLite DB Command - public IDbCommand Query(string sql, Dictionary parameters) - { - SQLiteCommand dbcommand = (SQLiteCommand) dbcon.CreateCommand(); - dbcommand.CommandText = sql; - foreach (KeyValuePair param in parameters) - { - SQLiteParameter paramx = new SQLiteParameter(param.Key, param.Value); - dbcommand.Parameters.Add(paramx); - } - - return (IDbCommand) dbcommand; - } - - /// - /// Reads a region row from a database reader - /// - /// An active database reader - /// A region profile - public RegionProfileData getRow(IDataReader reader) - { - RegionProfileData retval = new RegionProfileData(); - - if (reader.Read()) - { - // Region Main - retval.regionHandle = (ulong) reader["regionHandle"]; - retval.regionName = (string) reader["regionName"]; - retval.UUID = new UUID((string) reader["uuid"]); - - // Secrets - retval.regionRecvKey = (string) reader["regionRecvKey"]; - retval.regionSecret = (string) reader["regionSecret"]; - retval.regionSendKey = (string) reader["regionSendKey"]; - - // Region Server - retval.regionDataURI = (string) reader["regionDataURI"]; - retval.regionOnline = false; // Needs to be pinged before this can be set. - retval.serverIP = (string) reader["serverIP"]; - retval.serverPort = (uint) reader["serverPort"]; - retval.serverURI = (string) reader["serverURI"]; - - // Location - retval.regionLocX = (uint) ((int) reader["locX"]); - retval.regionLocY = (uint) ((int) reader["locY"]); - retval.regionLocZ = (uint) ((int) reader["locZ"]); - - // Neighbours - 0 = No Override - retval.regionEastOverrideHandle = (ulong) reader["eastOverrideHandle"]; - retval.regionWestOverrideHandle = (ulong) reader["westOverrideHandle"]; - retval.regionSouthOverrideHandle = (ulong) reader["southOverrideHandle"]; - retval.regionNorthOverrideHandle = (ulong) reader["northOverrideHandle"]; - - // Assets - retval.regionAssetURI = (string) reader["regionAssetURI"]; - retval.regionAssetRecvKey = (string) reader["regionAssetRecvKey"]; - retval.regionAssetSendKey = (string) reader["regionAssetSendKey"]; - - // Userserver - retval.regionUserURI = (string) reader["regionUserURI"]; - retval.regionUserRecvKey = (string) reader["regionUserRecvKey"]; - retval.regionUserSendKey = (string) reader["regionUserSendKey"]; - } - else - { - throw new Exception("No rows to return"); - } - return retval; - } - - /// - /// Inserts a new region into the database - /// - /// The region to insert - /// Success? - public bool insertRow(RegionProfileData profile) - { - string sql = - "REPLACE INTO regions VALUES (regionHandle, regionName, uuid, regionRecvKey, regionSecret, regionSendKey, regionDataURI, "; - sql += - "serverIP, serverPort, serverURI, locX, locY, locZ, eastOverrideHandle, westOverrideHandle, southOverrideHandle, northOverrideHandle, regionAssetURI, regionAssetRecvKey, "; - sql += "regionAssetSendKey, regionUserURI, regionUserRecvKey, regionUserSendKey) VALUES "; - - sql += "(@regionHandle, @regionName, @uuid, @regionRecvKey, @regionSecret, @regionSendKey, @regionDataURI, "; - sql += - "@serverIP, @serverPort, @serverURI, @locX, @locY, @locZ, @eastOverrideHandle, @westOverrideHandle, @southOverrideHandle, @northOverrideHandle, @regionAssetURI, @regionAssetRecvKey, "; - sql += "@regionAssetSendKey, @regionUserURI, @regionUserRecvKey, @regionUserSendKey);"; - - Dictionary parameters = new Dictionary(); - - parameters["regionHandle"] = profile.regionHandle.ToString(); - parameters["regionName"] = profile.regionName; - parameters["uuid"] = profile.UUID.ToString(); - parameters["regionRecvKey"] = profile.regionRecvKey; - parameters["regionSendKey"] = profile.regionSendKey; - parameters["regionDataURI"] = profile.regionDataURI; - parameters["serverIP"] = profile.serverIP; - parameters["serverPort"] = profile.serverPort.ToString(); - parameters["serverURI"] = profile.serverURI; - parameters["locX"] = profile.regionLocX.ToString(); - parameters["locY"] = profile.regionLocY.ToString(); - parameters["locZ"] = profile.regionLocZ.ToString(); - parameters["eastOverrideHandle"] = profile.regionEastOverrideHandle.ToString(); - parameters["westOverrideHandle"] = profile.regionWestOverrideHandle.ToString(); - parameters["northOverrideHandle"] = profile.regionNorthOverrideHandle.ToString(); - parameters["southOverrideHandle"] = profile.regionSouthOverrideHandle.ToString(); - parameters["regionAssetURI"] = profile.regionAssetURI; - parameters["regionAssetRecvKey"] = profile.regionAssetRecvKey; - parameters["regionAssetSendKey"] = profile.regionAssetSendKey; - parameters["regionUserURI"] = profile.regionUserURI; - parameters["regionUserRecvKey"] = profile.regionUserRecvKey; - parameters["regionUserSendKey"] = profile.regionUserSendKey; - - bool returnval = false; - - try - { - IDbCommand result = Query(sql, parameters); - - if (result.ExecuteNonQuery() == 1) - returnval = true; - - result.Dispose(); - } - catch (Exception) - { - return false; - } - - return returnval; - } - } -} diff --git a/OpenSim/Data/SQLite/SQLiteUserData.cs b/OpenSim/Data/SQLite/SQLiteUserData.cs deleted file mode 100644 index caddcf8..0000000 --- a/OpenSim/Data/SQLite/SQLiteUserData.cs +++ /dev/null @@ -1,1262 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.Data; -using System.Reflection; -using log4net; -using Mono.Data.SqliteClient; -using OpenMetaverse; -using OpenSim.Framework; - -namespace OpenSim.Data.SQLite -{ - /// - /// A User storage interface for the SQLite database system - /// - public class SQLiteUserData : UserDataBase - { - private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - /// - /// The database manager - /// - /// - /// Artificial constructor called upon plugin load - /// - private const string SelectUserByUUID = "select * from users where UUID=:UUID"; - private const string SelectUserByName = "select * from users where username=:username and surname=:surname"; - private const string SelectFriendsByUUID = "select a.friendID, a.friendPerms, b.friendPerms from userfriends as a, userfriends as b where a.ownerID=:ownerID and b.ownerID=a.friendID and b.friendID=a.ownerID"; - - private const string userSelect = "select * from users"; - private const string userFriendsSelect = "select a.ownerID as ownerID,a.friendID as friendID,a.friendPerms as friendPerms,b.friendPerms as ownerperms, b.ownerID as fownerID, b.friendID as ffriendID from userfriends as a, userfriends as b"; - private const string userAgentSelect = "select * from useragents"; - private const string AvatarAppearanceSelect = "select * from avatarappearance"; - - private const string AvatarPickerAndSQL = "select * from users where username like :username and surname like :surname"; - private const string AvatarPickerOrSQL = "select * from users where username like :username or surname like :surname"; - - private DataSet ds; - private SqliteDataAdapter da; - private SqliteDataAdapter daf; - private SqliteDataAdapter dua; - private SqliteDataAdapter daa; - SqliteConnection g_conn; - - public override void Initialise() - { - m_log.Info("[SQLiteUserData]: " + Name + " cannot be default-initialized!"); - throw new PluginNotInitialisedException (Name); - } - - /// - /// - /// Initialises User Interface - /// Loads and initialises a new SQLite connection and maintains it. - /// use default URI if connect string string is empty. - /// - /// - /// connect string - override public void Initialise(string connect) - { - // default to something sensible - if (connect == "") - connect = "URI=file:userprofiles.db,version=3"; - - SqliteConnection conn = new SqliteConnection(connect); - - // This sucks, but It doesn't seem to work with the dataset Syncing :P - g_conn = conn; - g_conn.Open(); - - Assembly assem = GetType().Assembly; - Migration m = new Migration(g_conn, assem, "UserStore"); - m.Update(); - - - ds = new DataSet(); - da = new SqliteDataAdapter(new SqliteCommand(userSelect, conn)); - dua = new SqliteDataAdapter(new SqliteCommand(userAgentSelect, conn)); - daf = new SqliteDataAdapter(new SqliteCommand(userFriendsSelect, conn)); - daa = new SqliteDataAdapter(new SqliteCommand(AvatarAppearanceSelect, conn)); - //if (daa == null) m_log.Info("[SQLiteUserData]: daa = null"); - - lock (ds) - { - ds.Tables.Add(createUsersTable()); - ds.Tables.Add(createUserAgentsTable()); - ds.Tables.Add(createUserFriendsTable()); - ds.Tables.Add(createAvatarAppearanceTable()); - - setupUserCommands(da, conn); - da.Fill(ds.Tables["users"]); - - setupAgentCommands(dua, conn); - dua.Fill(ds.Tables["useragents"]); - - setupUserFriendsCommands(daf, conn); - daf.Fill(ds.Tables["userfriends"]); - - setupAvatarAppearanceCommands(daa, conn); - daa.Fill(ds.Tables["avatarappearance"]); - } - - return; - } - - public override void Dispose () - { - if (g_conn != null) - { - g_conn.Close(); - g_conn = null; - } - if (ds != null) - { - ds.Dispose(); - ds = null; - } - if (da != null) - { - da.Dispose(); - da = null; - } - if (daf != null) - { - daf.Dispose(); - daf = null; - } - if (dua != null) - { - dua.Dispose(); - dua = null; - } - if (daa != null) - { - daa.Dispose(); - daa = null; - } - } - - /// - /// see IUserDataPlugin, - /// Get user data profile by UUID - /// - /// User UUID - /// user profile data - override public UserProfileData GetUserByUUID(UUID uuid) - { - lock (ds) - { - DataRow row = ds.Tables["users"].Rows.Find(uuid.ToString()); - if (row != null) - { - UserProfileData user = buildUserProfile(row); - return user; - } - else - { - return null; - } - } - } - - /// - /// see IUserDataPlugin, - /// Get user data profile by name - /// - /// first name - /// last name - /// user profile data - override public UserProfileData GetUserByName(string fname, string lname) - { - string select = "surname = '" + lname + "' and username = '" + fname + "'"; - lock (ds) - { - DataRow[] rows = ds.Tables["users"].Select(select); - if (rows.Length > 0) - { - UserProfileData user = buildUserProfile(rows[0]); - return user; - } - else - { - return null; - } - } - } - - #region User Friends List Data - - private bool ExistsFriend(UUID owner, UUID friend) - { - string FindFriends = "select * from userfriends where (ownerID=:ownerID and friendID=:friendID) or (ownerID=:friendID and friendID=:ownerID)"; - using (SqliteCommand cmd = new SqliteCommand(FindFriends, g_conn)) - { - cmd.Parameters.Add(new SqliteParameter(":ownerID", owner.ToString())); - cmd.Parameters.Add(new SqliteParameter(":friendID", friend.ToString())); - try - { - using (IDataReader reader = cmd.ExecuteReader()) - { - if (reader.Read()) - { - reader.Close(); - return true; - } - else - { - reader.Close(); - return false; - } - } - } - catch (Exception ex) - { - m_log.Error("[USER DB]: Exception getting friends list for user: " + ex.ToString()); - return false; - } - } - } - /// - /// Add a new friend in the friendlist - /// - /// UUID of the friendlist owner - /// UUID of the friend to add - /// permission flag - override public void AddNewUserFriend(UUID friendlistowner, UUID friend, uint perms) - { - if (ExistsFriend(friendlistowner, friend)) - return; - - string InsertFriends = "insert into userfriends(ownerID, friendID, friendPerms) values(:ownerID, :friendID, :perms)"; - using (SqliteCommand cmd = new SqliteCommand(InsertFriends, g_conn)) - { - cmd.Parameters.Add(new SqliteParameter(":ownerID", friendlistowner.ToString())); - cmd.Parameters.Add(new SqliteParameter(":friendID", friend.ToString())); - cmd.Parameters.Add(new SqliteParameter(":perms", perms)); - cmd.ExecuteNonQuery(); - } - using (SqliteCommand cmd = new SqliteCommand(InsertFriends, g_conn)) - { - cmd.Parameters.Add(new SqliteParameter(":ownerID", friend.ToString())); - cmd.Parameters.Add(new SqliteParameter(":friendID", friendlistowner.ToString())); - cmd.Parameters.Add(new SqliteParameter(":perms", perms)); - cmd.ExecuteNonQuery(); - } - } - - /// - /// Remove a user from the friendlist - /// - /// UUID of the friendlist owner - /// UUID of the friend to remove - override public void RemoveUserFriend(UUID friendlistowner, UUID friend) - { - string DeletePerms = "delete from userfriends where (ownerID=:ownerID and friendID=:friendID) or (ownerID=:friendID and friendID=:ownerID)"; - using (SqliteCommand cmd = new SqliteCommand(DeletePerms, g_conn)) - { - cmd.Parameters.Add(new SqliteParameter(":ownerID", friendlistowner.ToString())); - cmd.Parameters.Add(new SqliteParameter(":friendID", friend.ToString())); - cmd.ExecuteNonQuery(); - } - } - - /// - /// Update the friendlist permission - /// - /// UUID of the friendlist owner - /// UUID of the friend to modify - /// updated permission flag - override public void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms) - { - string UpdatePerms = "update userfriends set friendPerms=:perms where ownerID=:ownerID and friendID=:friendID"; - using (SqliteCommand cmd = new SqliteCommand(UpdatePerms, g_conn)) - { - cmd.Parameters.Add(new SqliteParameter(":perms", perms)); - cmd.Parameters.Add(new SqliteParameter(":ownerID", friendlistowner.ToString())); - cmd.Parameters.Add(new SqliteParameter(":friendID", friend.ToString())); - cmd.ExecuteNonQuery(); - } - } - - /// - /// Get (fetch?) the friendlist for a user - /// - /// UUID of the friendlist owner - /// The friendlist list - override public List GetUserFriendList(UUID friendlistowner) - { - List returnlist = new List(); - - using (SqliteCommand cmd = new SqliteCommand(SelectFriendsByUUID, g_conn)) - { - cmd.Parameters.Add(new SqliteParameter(":ownerID", friendlistowner.ToString())); - - try - { - using (IDataReader reader = cmd.ExecuteReader()) - { - while (reader.Read()) - { - FriendListItem user = new FriendListItem(); - user.FriendListOwner = friendlistowner; - user.Friend = new UUID((string)reader[0]); - user.FriendPerms = Convert.ToUInt32(reader[1]); - user.FriendListOwnerPerms = Convert.ToUInt32(reader[2]); - returnlist.Add(user); - } - reader.Close(); - } - } - catch (Exception ex) - { - m_log.Error("[USER DB]: Exception getting friends list for user: " + ex.ToString()); - } - } - - return returnlist; - } - - override public Dictionary GetFriendRegionInfos (List uuids) - { - Dictionary infos = new Dictionary(); - - DataTable agents = ds.Tables["useragents"]; - foreach (UUID uuid in uuids) - { - lock (ds) - { - DataRow row = agents.Rows.Find(uuid.ToString()); - if (row == null) infos[uuid] = null; - else - { - FriendRegionInfo fri = new FriendRegionInfo(); - fri.isOnline = (bool)row["agentOnline"]; - fri.regionHandle = Convert.ToUInt64(row["currentHandle"]); - infos[uuid] = fri; - } - } - } - return infos; - } - - #endregion - - /// - /// - /// - /// - /// - /// - override public List GeneratePickerResults(UUID queryID, string query) - { - List returnlist = new List(); - string[] querysplit; - querysplit = query.Split(' '); - if (querysplit.Length == 2) - { - using (SqliteCommand cmd = new SqliteCommand(AvatarPickerAndSQL, g_conn)) - { - cmd.Parameters.Add(new SqliteParameter(":username", querysplit[0] + "%")); - cmd.Parameters.Add(new SqliteParameter(":surname", querysplit[1] + "%")); - - using (IDataReader reader = cmd.ExecuteReader()) - { - while (reader.Read()) - { - AvatarPickerAvatar user = new AvatarPickerAvatar(); - user.AvatarID = new UUID((string) reader["UUID"]); - user.firstName = (string) reader["username"]; - user.lastName = (string) reader["surname"]; - returnlist.Add(user); - } - reader.Close(); - } - } - } - else if (querysplit.Length == 1) - { - using (SqliteCommand cmd = new SqliteCommand(AvatarPickerOrSQL, g_conn)) - { - cmd.Parameters.Add(new SqliteParameter(":username", querysplit[0] + "%")); - cmd.Parameters.Add(new SqliteParameter(":surname", querysplit[0] + "%")); - - using (IDataReader reader = cmd.ExecuteReader()) - { - while (reader.Read()) - { - AvatarPickerAvatar user = new AvatarPickerAvatar(); - user.AvatarID = new UUID((string) reader["UUID"]); - user.firstName = (string) reader["username"]; - user.lastName = (string) reader["surname"]; - returnlist.Add(user); - } - reader.Close(); - } - } - } - return returnlist; - } - - /// - /// Returns a user by UUID direct - /// - /// The user's account ID - /// A matching user profile - override public UserAgentData GetAgentByUUID(UUID uuid) - { - lock (ds) - { - DataRow row = ds.Tables["useragents"].Rows.Find(uuid.ToString()); - if (row != null) - { - return buildUserAgent(row); - } - else - { - return null; - } - } - } - - /// - /// Returns a session by account name - /// - /// The account name - /// The user's session agent - override public UserAgentData GetAgentByName(string name) - { - return GetAgentByName(name.Split(' ')[0], name.Split(' ')[1]); - } - - /// - /// Returns a session by account name - /// - /// The first part of the user's account name - /// The second part of the user's account name - /// A user agent - override public UserAgentData GetAgentByName(string fname, string lname) - { - UserAgentData agent = null; - - UserProfileData profile = GetUserByName(fname, lname); - if (profile != null) - { - agent = GetAgentByUUID(profile.ID); - } - return agent; - } - - /// - /// DEPRECATED? Store the weblogin key - /// - /// UUID of the user - /// UUID of the weblogin - override public void StoreWebLoginKey(UUID AgentID, UUID WebLoginKey) - { - DataTable users = ds.Tables["users"]; - lock (ds) - { - DataRow row = users.Rows.Find(AgentID.ToString()); - if (row == null) - { - m_log.Warn("[USER DB]: Unable to store new web login key for non-existant user"); - } - else - { - UserProfileData user = GetUserByUUID(AgentID); - user.WebLoginKey = WebLoginKey; - fillUserRow(row, user); - da.Update(ds, "users"); - } - } - } - - private bool ExistsFirstLastName(String fname, String lname) - { - string FindUser = "select * from users where (username=:username and surname=:surname)"; - using (SqliteCommand cmd = new SqliteCommand(FindUser, g_conn)) - { - cmd.Parameters.Add(new SqliteParameter(":username", fname)); - cmd.Parameters.Add(new SqliteParameter(":surname", lname)); - try - { - using (IDataReader reader = cmd.ExecuteReader()) - { - if (reader.Read()) - { - reader.Close(); - return true; - } - else - { - reader.Close(); - return false; - } - } - } - catch (Exception ex) - { - m_log.Error("[USER DB]: Exception searching for user's first and last name: " + ex.ToString()); - return false; - } - } - } - - /// - /// Creates a new user profile - /// - /// The profile to add to the database - override public void AddNewUserProfile(UserProfileData user) - { - DataTable users = ds.Tables["users"]; - UUID zero = UUID.Zero; - if (ExistsFirstLastName(user.FirstName, user.SurName) || user.ID == zero) - return; - - lock (ds) - { - DataRow row = users.Rows.Find(user.ID.ToString()); - if (row == null) - { - row = users.NewRow(); - fillUserRow(row, user); - users.Rows.Add(row); - - m_log.Debug("[USER DB]: Syncing user database: " + ds.Tables["users"].Rows.Count + " users stored"); - - // save changes off to disk - da.Update(ds, "users"); - } - else - { - m_log.WarnFormat("[USER DB]: Ignoring add since user with id {0} already exists", user.ID); - } - } - } - - /// - /// Creates a new user profile - /// - /// The profile to add to the database - /// True on success, false on error - override public bool UpdateUserProfile(UserProfileData user) - { - DataTable users = ds.Tables["users"]; - lock (ds) - { - DataRow row = users.Rows.Find(user.ID.ToString()); - if (row == null) - { - return false; - } - else - { - fillUserRow(row, user); - da.Update(ds, "users"); - } - } - - //AddNewUserProfile(user); - return true; - } - - /// - /// Creates a new user agent - /// - /// The agent to add to the database - override public void AddNewUserAgent(UserAgentData agent) - { - UUID zero = UUID.Zero; - if (agent.SessionID == zero || agent.ProfileID == zero) - return; - - DataTable agents = ds.Tables["useragents"]; - lock (ds) - { - DataRow row = agents.Rows.Find(agent.ProfileID.ToString()); - if (row == null) - { - row = agents.NewRow(); - fillUserAgentRow(row, agent); - agents.Rows.Add(row); - } - else - { - fillUserAgentRow(row, agent); - - } - m_log.Info("[USER DB]: Syncing useragent database: " + ds.Tables["useragents"].Rows.Count + " agents stored"); - // save changes off to disk - dua.Update(ds, "useragents"); - } - } - - /// - /// Transfers money between two user accounts - /// - /// Starting account - /// End account - /// The amount to move - /// Success? - override public bool MoneyTransferRequest(UUID from, UUID to, uint amount) - { - return false; // for consistency with the MySQL impl - } - - /// - /// Transfers inventory between two accounts - /// - /// Move to inventory server - /// Senders account - /// Receivers account - /// Inventory item - /// Success? - override public bool InventoryTransferRequest(UUID from, UUID to, UUID item) - { - return false; //for consistency with the MySQL impl - } - - - /// - /// Appearance. - /// TODO: stubs for now to do in memory appearance. - /// - /// The user UUID - /// Avatar Appearence - override public AvatarAppearance GetUserAppearance(UUID user) - { - m_log.Info("[APPEARANCE] GetUserAppearance " + user.ToString()); - - AvatarAppearance aa = new AvatarAppearance(user); - //try { - aa.Owner = user; - - DataTable aap = ds.Tables["avatarappearance"]; - lock (ds) - { - DataRow row = aap.Rows.Find(Util.ToRawUuidString(user)); - if (row == null) - { - m_log.Info("[APPEARANCE] Could not find appearance for " + user.ToString()); - - //m_log.Debug("[USER DB]: Creating avatarappearance For: " + user.ToString()); - - //row = aap.NewRow(); - //fillAvatarAppearanceRow(row, user, appearance); - //aap.Rows.Add(row); - // m_log.Debug("[USER DB]: Syncing user database: " + ds.Tables["users"].Rows.Count + " users stored"); - // save changes off to disk - //daa.Update(ds, "avatarappearance"); - } - else - { - m_log.InfoFormat("[APPEARANCE] appearance found for {0}", user.ToString()); - - aa.BodyAsset = new UUID((String)row["BodyAsset"]); - aa.BodyItem = new UUID((String)row["BodyItem"]); - aa.SkinItem = new UUID((String)row["SkinItem"]); - aa.SkinAsset = new UUID((String)row["SkinAsset"]); - aa.HairItem = new UUID((String)row["HairItem"]); - aa.HairAsset = new UUID((String)row["HairAsset"]); - aa.EyesItem = new UUID((String)row["EyesItem"]); - aa.EyesAsset = new UUID((String)row["EyesAsset"]); - aa.ShirtItem = new UUID((String)row["ShirtItem"]); - aa.ShirtAsset = new UUID((String)row["ShirtAsset"]); - aa.PantsItem = new UUID((String)row["PantsItem"]); - aa.PantsAsset = new UUID((String)row["PantsAsset"]); - aa.ShoesItem = new UUID((String)row["ShoesItem"]); - aa.ShoesAsset = new UUID((String)row["ShoesAsset"]); - aa.SocksItem = new UUID((String)row["SocksItem"]); - aa.SocksAsset = new UUID((String)row["SocksAsset"]); - aa.JacketItem = new UUID((String)row["JacketItem"]); - aa.JacketAsset = new UUID((String)row["JacketAsset"]); - aa.GlovesItem = new UUID((String)row["GlovesItem"]); - aa.GlovesAsset = new UUID((String)row["GlovesAsset"]); - aa.UnderShirtItem = new UUID((String)row["UnderShirtItem"]); - aa.UnderShirtAsset = new UUID((String)row["UnderShirtAsset"]); - aa.UnderPantsItem = new UUID((String)row["UnderPantsItem"]); - aa.UnderPantsAsset = new UUID((String)row["UnderPantsAsset"]); - aa.SkirtItem = new UUID((String)row["SkirtItem"]); - aa.SkirtAsset = new UUID((String)row["SkirtAsset"]); - - // Ewe Loon - // Used Base64String because for some reason it wont accept using Byte[] (which works in Region date) - - String str = (String)row["Texture"]; - byte[] texture = Convert.FromBase64String(str); - aa.Texture = new Primitive.TextureEntry(texture, 0, texture.Length); - - str = (String)row["VisualParams"]; - byte[] VisualParams = Convert.FromBase64String(str); - aa.VisualParams = VisualParams; - - aa.Serial = Convert.ToInt32(row["Serial"]); - aa.AvatarHeight = Convert.ToSingle(row["AvatarHeight"]); - m_log.InfoFormat("[APPEARANCE] appearance set for {0}", user.ToString()); - } - } - - // m_log.Info("[APPEARANCE] Found appearance for " + user.ToString() + aa.ToString()); - // } catch (KeyNotFoundException) { - // m_log.InfoFormat("[APPEARANCE] No appearance found for {0}", user.ToString()); - // } - return aa; - } - - /// - /// Update a user appearence - /// - /// the user UUID - /// appearence - override public void UpdateUserAppearance(UUID user, AvatarAppearance appearance) - { - appearance.Owner = user; - DataTable aap = ds.Tables["avatarappearance"]; - lock (ds) - { - DataRow row = aap.Rows.Find(Util.ToRawUuidString(user)); - if (row == null) - { - m_log.Debug("[USER DB]: Creating UserAppearance For: " + user.ToString()); - - row = aap.NewRow(); - fillAvatarAppearanceRow(row, user, appearance); - aap.Rows.Add(row); - // m_log.Debug("[USER DB]: Syncing user database: " + ds.Tables["users"].Rows.Count + " users stored"); - // save changes off to disk - daa.Update(ds, "avatarappearance"); - } - else - { - m_log.Debug("[USER DB]: Updating UserAppearance For: " + user.ToString()); - fillAvatarAppearanceRow(row, user, appearance); - daa.Update(ds, "avatarappearance"); - } - } - } - - /// - /// Returns the name of the storage provider - /// - /// Storage provider name - override public string Name - { - get {return "Sqlite Userdata";} - } - - /// - /// Returns the version of the storage provider - /// - /// Storage provider version - override public string Version - { - get {return "0.1";} - } - - /*********************************************************************** - * - * DataTable creation - * - **********************************************************************/ - /*********************************************************************** - * - * Database Definition Functions - * - * This should be db agnostic as we define them in ADO.NET terms - * - **********************************************************************/ - - /// - /// Create the "users" table - /// - /// DataTable - private static DataTable createUsersTable() - { - DataTable users = new DataTable("users"); - - SQLiteUtil.createCol(users, "UUID", typeof (String)); - SQLiteUtil.createCol(users, "username", typeof (String)); - SQLiteUtil.createCol(users, "surname", typeof (String)); - SQLiteUtil.createCol(users, "email", typeof (String)); - SQLiteUtil.createCol(users, "passwordHash", typeof (String)); - SQLiteUtil.createCol(users, "passwordSalt", typeof (String)); - - SQLiteUtil.createCol(users, "homeRegionX", typeof (Int32)); - SQLiteUtil.createCol(users, "homeRegionY", typeof (Int32)); - SQLiteUtil.createCol(users, "homeRegionID", typeof (String)); - SQLiteUtil.createCol(users, "homeLocationX", typeof (Double)); - SQLiteUtil.createCol(users, "homeLocationY", typeof (Double)); - SQLiteUtil.createCol(users, "homeLocationZ", typeof (Double)); - SQLiteUtil.createCol(users, "homeLookAtX", typeof (Double)); - SQLiteUtil.createCol(users, "homeLookAtY", typeof (Double)); - SQLiteUtil.createCol(users, "homeLookAtZ", typeof (Double)); - SQLiteUtil.createCol(users, "created", typeof (Int32)); - SQLiteUtil.createCol(users, "lastLogin", typeof (Int32)); - - //TODO: Please delete this column. It's now a brick - SQLiteUtil.createCol(users, "rootInventoryFolderID", typeof (String)); - - SQLiteUtil.createCol(users, "userInventoryURI", typeof (String)); - SQLiteUtil.createCol(users, "userAssetURI", typeof (String)); - SQLiteUtil.createCol(users, "profileCanDoMask", typeof (Int32)); - SQLiteUtil.createCol(users, "profileWantDoMask", typeof (Int32)); - SQLiteUtil.createCol(users, "profileAboutText", typeof (String)); - SQLiteUtil.createCol(users, "profileFirstText", typeof (String)); - SQLiteUtil.createCol(users, "profileImage", typeof (String)); - SQLiteUtil.createCol(users, "profileFirstImage", typeof (String)); - SQLiteUtil.createCol(users, "webLoginKey", typeof(String)); - SQLiteUtil.createCol(users, "userFlags", typeof (Int32)); - SQLiteUtil.createCol(users, "godLevel", typeof (Int32)); - SQLiteUtil.createCol(users, "customType", typeof (String)); - SQLiteUtil.createCol(users, "partner", typeof (String)); - // Add in contraints - users.PrimaryKey = new DataColumn[] {users.Columns["UUID"]}; - return users; - } - - /// - /// Create the "useragents" table - /// - /// Data Table - private static DataTable createUserAgentsTable() - { - DataTable ua = new DataTable("useragents"); - // this is the UUID of the user - SQLiteUtil.createCol(ua, "UUID", typeof (String)); - SQLiteUtil.createCol(ua, "agentIP", typeof (String)); - SQLiteUtil.createCol(ua, "agentPort", typeof (Int32)); - SQLiteUtil.createCol(ua, "agentOnline", typeof (Boolean)); - SQLiteUtil.createCol(ua, "sessionID", typeof (String)); - SQLiteUtil.createCol(ua, "secureSessionID", typeof (String)); - SQLiteUtil.createCol(ua, "regionID", typeof (String)); - SQLiteUtil.createCol(ua, "loginTime", typeof (Int32)); - SQLiteUtil.createCol(ua, "logoutTime", typeof (Int32)); - SQLiteUtil.createCol(ua, "currentRegion", typeof (String)); - SQLiteUtil.createCol(ua, "currentHandle", typeof (String)); - // vectors - SQLiteUtil.createCol(ua, "currentPosX", typeof (Double)); - SQLiteUtil.createCol(ua, "currentPosY", typeof (Double)); - SQLiteUtil.createCol(ua, "currentPosZ", typeof (Double)); - // constraints - ua.PrimaryKey = new DataColumn[] {ua.Columns["UUID"]}; - - return ua; - } - - /// - /// Create the "userfriends" table - /// - /// Data Table - private static DataTable createUserFriendsTable() - { - DataTable ua = new DataTable("userfriends"); - // table contains user <----> user relationship with perms - SQLiteUtil.createCol(ua, "ownerID", typeof(String)); - SQLiteUtil.createCol(ua, "friendID", typeof(String)); - SQLiteUtil.createCol(ua, "friendPerms", typeof(Int32)); - SQLiteUtil.createCol(ua, "ownerPerms", typeof(Int32)); - SQLiteUtil.createCol(ua, "datetimestamp", typeof(Int32)); - - return ua; - } - - /// - /// Create the "avatarappearance" table - /// - /// Data Table - private static DataTable createAvatarAppearanceTable() - { - DataTable aa = new DataTable("avatarappearance"); - // table contains user appearance items - - SQLiteUtil.createCol(aa, "Owner", typeof(String)); - SQLiteUtil.createCol(aa, "BodyItem", typeof(String)); - SQLiteUtil.createCol(aa, "BodyAsset", typeof(String)); - SQLiteUtil.createCol(aa, "SkinItem", typeof(String)); - SQLiteUtil.createCol(aa, "SkinAsset", typeof(String)); - SQLiteUtil.createCol(aa, "HairItem", typeof(String)); - SQLiteUtil.createCol(aa, "HairAsset", typeof(String)); - SQLiteUtil.createCol(aa, "EyesItem", typeof(String)); - SQLiteUtil.createCol(aa, "EyesAsset", typeof(String)); - SQLiteUtil.createCol(aa, "ShirtItem", typeof(String)); - SQLiteUtil.createCol(aa, "ShirtAsset", typeof(String)); - SQLiteUtil.createCol(aa, "PantsItem", typeof(String)); - SQLiteUtil.createCol(aa, "PantsAsset", typeof(String)); - SQLiteUtil.createCol(aa, "ShoesItem", typeof(String)); - SQLiteUtil.createCol(aa, "ShoesAsset", typeof(String)); - SQLiteUtil.createCol(aa, "SocksItem", typeof(String)); - SQLiteUtil.createCol(aa, "SocksAsset", typeof(String)); - SQLiteUtil.createCol(aa, "JacketItem", typeof(String)); - SQLiteUtil.createCol(aa, "JacketAsset", typeof(String)); - SQLiteUtil.createCol(aa, "GlovesItem", typeof(String)); - SQLiteUtil.createCol(aa, "GlovesAsset", typeof(String)); - SQLiteUtil.createCol(aa, "UnderShirtItem", typeof(String)); - SQLiteUtil.createCol(aa, "UnderShirtAsset", typeof(String)); - SQLiteUtil.createCol(aa, "UnderPantsItem", typeof(String)); - SQLiteUtil.createCol(aa, "UnderPantsAsset", typeof(String)); - SQLiteUtil.createCol(aa, "SkirtItem", typeof(String)); - SQLiteUtil.createCol(aa, "SkirtAsset", typeof(String)); - - // Used Base64String because for some reason it wont accept using Byte[] (which works in Region date) - SQLiteUtil.createCol(aa, "Texture", typeof (String)); - SQLiteUtil.createCol(aa, "VisualParams", typeof (String)); - - SQLiteUtil.createCol(aa, "Serial", typeof(Int32)); - SQLiteUtil.createCol(aa, "AvatarHeight", typeof(Double)); - - aa.PrimaryKey = new DataColumn[] { aa.Columns["Owner"] }; - - return aa; - } - - /*********************************************************************** - * - * Convert between ADO.NET <=> OpenSim Objects - * - * These should be database independant - * - **********************************************************************/ - - /// - /// TODO: this doesn't work yet because something more - /// interesting has to be done to actually get these values - /// back out. Not enough time to figure it out yet. - /// - /// - /// - private static UserProfileData buildUserProfile(DataRow row) - { - UserProfileData user = new UserProfileData(); - UUID tmp; - UUID.TryParse((String)row["UUID"], out tmp); - user.ID = tmp; - user.FirstName = (String) row["username"]; - user.SurName = (String) row["surname"]; - user.Email = (row.IsNull("email")) ? "" : (String) row["email"]; - - user.PasswordHash = (String) row["passwordHash"]; - user.PasswordSalt = (String) row["passwordSalt"]; - - user.HomeRegionX = Convert.ToUInt32(row["homeRegionX"]); - user.HomeRegionY = Convert.ToUInt32(row["homeRegionY"]); - user.HomeLocation = new Vector3( - Convert.ToSingle(row["homeLocationX"]), - Convert.ToSingle(row["homeLocationY"]), - Convert.ToSingle(row["homeLocationZ"]) - ); - user.HomeLookAt = new Vector3( - Convert.ToSingle(row["homeLookAtX"]), - Convert.ToSingle(row["homeLookAtY"]), - Convert.ToSingle(row["homeLookAtZ"]) - ); - - UUID regionID = UUID.Zero; - UUID.TryParse(row["homeRegionID"].ToString(), out regionID); // it's ok if it doesn't work; just use UUID.Zero - user.HomeRegionID = regionID; - - user.Created = Convert.ToInt32(row["created"]); - user.LastLogin = Convert.ToInt32(row["lastLogin"]); - user.UserInventoryURI = (String) row["userInventoryURI"]; - user.UserAssetURI = (String) row["userAssetURI"]; - user.CanDoMask = Convert.ToUInt32(row["profileCanDoMask"]); - user.WantDoMask = Convert.ToUInt32(row["profileWantDoMask"]); - user.AboutText = (String) row["profileAboutText"]; - user.FirstLifeAboutText = (String) row["profileFirstText"]; - UUID.TryParse((String)row["profileImage"], out tmp); - user.Image = tmp; - UUID.TryParse((String)row["profileFirstImage"], out tmp); - user.FirstLifeImage = tmp; - user.WebLoginKey = new UUID((String) row["webLoginKey"]); - user.UserFlags = Convert.ToInt32(row["userFlags"]); - user.GodLevel = Convert.ToInt32(row["godLevel"]); - user.CustomType = row["customType"].ToString(); - user.Partner = new UUID((String) row["partner"]); - - return user; - } - - /// - /// Persist user profile data - /// - /// - /// - private void fillUserRow(DataRow row, UserProfileData user) - { - row["UUID"] = user.ID.ToString(); - row["username"] = user.FirstName; - row["surname"] = user.SurName; - row["email"] = user.Email; - row["passwordHash"] = user.PasswordHash; - row["passwordSalt"] = user.PasswordSalt; - - row["homeRegionX"] = user.HomeRegionX; - row["homeRegionY"] = user.HomeRegionY; - row["homeRegionID"] = user.HomeRegionID.ToString(); - row["homeLocationX"] = user.HomeLocation.X; - row["homeLocationY"] = user.HomeLocation.Y; - row["homeLocationZ"] = user.HomeLocation.Z; - row["homeLookAtX"] = user.HomeLookAt.X; - row["homeLookAtY"] = user.HomeLookAt.Y; - row["homeLookAtZ"] = user.HomeLookAt.Z; - - row["created"] = user.Created; - row["lastLogin"] = user.LastLogin; - //TODO: Get rid of rootInventoryFolderID in a safe way. - row["rootInventoryFolderID"] = UUID.Zero.ToString(); - row["userInventoryURI"] = user.UserInventoryURI; - row["userAssetURI"] = user.UserAssetURI; - row["profileCanDoMask"] = user.CanDoMask; - row["profileWantDoMask"] = user.WantDoMask; - row["profileAboutText"] = user.AboutText; - row["profileFirstText"] = user.FirstLifeAboutText; - row["profileImage"] = user.Image.ToString(); - row["profileFirstImage"] = user.FirstLifeImage.ToString(); - row["webLoginKey"] = user.WebLoginKey.ToString(); - row["userFlags"] = user.UserFlags; - row["godLevel"] = user.GodLevel; - row["customType"] = user.CustomType == null ? "" : user.CustomType; - row["partner"] = user.Partner.ToString(); - - // ADO.NET doesn't handle NULL very well - foreach (DataColumn col in ds.Tables["users"].Columns) - { - if (row[col] == null) - { - row[col] = String.Empty; - } - } - } - - /// - /// - /// - /// - /// - private void fillAvatarAppearanceRow(DataRow row, UUID user, AvatarAppearance appearance) - { - row["Owner"] = Util.ToRawUuidString(user); - row["BodyItem"] = appearance.BodyItem.ToString(); - row["BodyAsset"] = appearance.BodyAsset.ToString(); - row["SkinItem"] = appearance.SkinItem.ToString(); - row["SkinAsset"] = appearance.SkinAsset.ToString(); - row["HairItem"] = appearance.HairItem.ToString(); - row["HairAsset"] = appearance.HairAsset.ToString(); - row["EyesItem"] = appearance.EyesItem.ToString(); - row["EyesAsset"] = appearance.EyesAsset.ToString(); - row["ShirtItem"] = appearance.ShirtItem.ToString(); - row["ShirtAsset"] = appearance.ShirtAsset.ToString(); - row["PantsItem"] = appearance.PantsItem.ToString(); - row["PantsAsset"] = appearance.PantsAsset.ToString(); - row["ShoesItem"] = appearance.ShoesItem.ToString(); - row["ShoesAsset"] = appearance.ShoesAsset.ToString(); - row["SocksItem"] = appearance.SocksItem.ToString(); - row["SocksAsset"] = appearance.SocksAsset.ToString(); - row["JacketItem"] = appearance.JacketItem.ToString(); - row["JacketAsset"] = appearance.JacketAsset.ToString(); - row["GlovesItem"] = appearance.GlovesItem.ToString(); - row["GlovesAsset"] = appearance.GlovesAsset.ToString(); - row["UnderShirtItem"] = appearance.UnderShirtItem.ToString(); - row["UnderShirtAsset"] = appearance.UnderShirtAsset.ToString(); - row["UnderPantsItem"] = appearance.UnderPantsItem.ToString(); - row["UnderPantsAsset"] = appearance.UnderPantsAsset.ToString(); - row["SkirtItem"] = appearance.SkirtItem.ToString(); - row["SkirtAsset"] = appearance.SkirtAsset.ToString(); - - // Used Base64String because for some reason it wont accept using Byte[] (which works in Region date) - row["Texture"] = Convert.ToBase64String(appearance.Texture.GetBytes()); - row["VisualParams"] = Convert.ToBase64String(appearance.VisualParams); - - row["Serial"] = appearance.Serial; - row["AvatarHeight"] = appearance.AvatarHeight; - - // ADO.NET doesn't handle NULL very well - foreach (DataColumn col in ds.Tables["avatarappearance"].Columns) - { - if (row[col] == null) - { - row[col] = String.Empty; - } - } - } - - /// - /// - /// - /// - /// - private static UserAgentData buildUserAgent(DataRow row) - { - UserAgentData ua = new UserAgentData(); - - UUID tmp; - UUID.TryParse((String)row["UUID"], out tmp); - ua.ProfileID = tmp; - ua.AgentIP = (String)row["agentIP"]; - ua.AgentPort = Convert.ToUInt32(row["agentPort"]); - ua.AgentOnline = Convert.ToBoolean(row["agentOnline"]); - ua.SessionID = new UUID((String) row["sessionID"]); - ua.SecureSessionID = new UUID((String) row["secureSessionID"]); - ua.InitialRegion = new UUID((String) row["regionID"]); - ua.LoginTime = Convert.ToInt32(row["loginTime"]); - ua.LogoutTime = Convert.ToInt32(row["logoutTime"]); - ua.Region = new UUID((String) row["currentRegion"]); - ua.Handle = Convert.ToUInt64(row["currentHandle"]); - ua.Position = new Vector3( - Convert.ToSingle(row["currentPosX"]), - Convert.ToSingle(row["currentPosY"]), - Convert.ToSingle(row["currentPosZ"]) - ); - ua.LookAt = new Vector3( - Convert.ToSingle(row["currentLookAtX"]), - Convert.ToSingle(row["currentLookAtY"]), - Convert.ToSingle(row["currentLookAtZ"]) - ); - return ua; - } - - /// - /// - /// - /// - /// - private static void fillUserAgentRow(DataRow row, UserAgentData ua) - { - row["UUID"] = ua.ProfileID.ToString(); - row["agentIP"] = ua.AgentIP; - row["agentPort"] = ua.AgentPort; - row["agentOnline"] = ua.AgentOnline; - row["sessionID"] = ua.SessionID.ToString(); - row["secureSessionID"] = ua.SecureSessionID.ToString(); - row["regionID"] = ua.InitialRegion.ToString(); - row["loginTime"] = ua.LoginTime; - row["logoutTime"] = ua.LogoutTime; - row["currentRegion"] = ua.Region.ToString(); - row["currentHandle"] = ua.Handle.ToString(); - // vectors - row["currentPosX"] = ua.Position.X; - row["currentPosY"] = ua.Position.Y; - row["currentPosZ"] = ua.Position.Z; - row["currentLookAtX"] = ua.LookAt.X; - row["currentLookAtY"] = ua.LookAt.Y; - row["currentLookAtZ"] = ua.LookAt.Z; - } - - /*********************************************************************** - * - * Database Binding functions - * - * These will be db specific due to typing, and minor differences - * in databases. - * - **********************************************************************/ - - /// - /// - /// - /// - /// - private void setupUserCommands(SqliteDataAdapter da, SqliteConnection conn) - { - da.InsertCommand = SQLiteUtil.createInsertCommand("users", ds.Tables["users"]); - da.InsertCommand.Connection = conn; - - da.UpdateCommand = SQLiteUtil.createUpdateCommand("users", "UUID=:UUID", ds.Tables["users"]); - da.UpdateCommand.Connection = conn; - - SqliteCommand delete = new SqliteCommand("delete from users where UUID = :UUID"); - delete.Parameters.Add(SQLiteUtil.createSqliteParameter("UUID", typeof(String))); - delete.Connection = conn; - da.DeleteCommand = delete; - } - - private void setupAgentCommands(SqliteDataAdapter da, SqliteConnection conn) - { - da.InsertCommand = SQLiteUtil.createInsertCommand("useragents", ds.Tables["useragents"]); - da.InsertCommand.Connection = conn; - - da.UpdateCommand = SQLiteUtil.createUpdateCommand("useragents", "UUID=:UUID", ds.Tables["useragents"]); - da.UpdateCommand.Connection = conn; - - SqliteCommand delete = new SqliteCommand("delete from useragents where UUID = :ProfileID"); - delete.Parameters.Add(SQLiteUtil.createSqliteParameter("ProfileID", typeof(String))); - delete.Connection = conn; - da.DeleteCommand = delete; - } - - /// - /// - /// - /// - /// - private void setupUserFriendsCommands(SqliteDataAdapter daf, SqliteConnection conn) - { - daf.InsertCommand = SQLiteUtil.createInsertCommand("userfriends", ds.Tables["userfriends"]); - daf.InsertCommand.Connection = conn; - - daf.UpdateCommand = SQLiteUtil.createUpdateCommand("userfriends", "ownerID=:ownerID and friendID=:friendID", ds.Tables["userfriends"]); - daf.UpdateCommand.Connection = conn; - - SqliteCommand delete = new SqliteCommand("delete from userfriends where ownerID=:ownerID and friendID=:friendID"); - delete.Parameters.Add(SQLiteUtil.createSqliteParameter("ownerID", typeof(String))); - delete.Parameters.Add(SQLiteUtil.createSqliteParameter("friendID", typeof(String))); - delete.Connection = conn; - daf.DeleteCommand = delete; - - } - - /// - /// - /// - /// - /// - private void setupAvatarAppearanceCommands(SqliteDataAdapter daa, SqliteConnection conn) - { - daa.InsertCommand = SQLiteUtil.createInsertCommand("avatarappearance", ds.Tables["avatarappearance"]); - daa.InsertCommand.Connection = conn; - - daa.UpdateCommand = SQLiteUtil.createUpdateCommand("avatarappearance", "Owner=:Owner", ds.Tables["avatarappearance"]); - daa.UpdateCommand.Connection = conn; - - SqliteCommand delete = new SqliteCommand("delete from avatarappearance where Owner=:Owner"); - delete.Parameters.Add(SQLiteUtil.createSqliteParameter("Owner", typeof(String))); - delete.Connection = conn; - daa.DeleteCommand = delete; - } - - - override public void ResetAttachments(UUID userID) - { - } - - override public void LogoutUsers(UUID regionID) - { - } - } -} diff --git a/OpenSim/Data/SQLite/Tests/SQLiteUserTest.cs b/OpenSim/Data/SQLite/Tests/SQLiteUserTest.cs deleted file mode 100644 index c9953c5..0000000 --- a/OpenSim/Data/SQLite/Tests/SQLiteUserTest.cs +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System.IO; -using NUnit.Framework; -using OpenSim.Data.Tests; -using OpenSim.Tests.Common; - -namespace OpenSim.Data.SQLite.Tests -{ - [TestFixture, DatabaseTest] - public class SQLiteUserTest : BasicUserTest - { - public string file; - public string connect; - - [TestFixtureSetUp] - public void Init() - { - // SQLite doesn't work on power or z linux - if (Directory.Exists("/proc/ppc64") || Directory.Exists("/proc/dasd")) - { - Assert.Ignore(); - } - - SuperInit(); - file = Path.GetTempFileName() + ".db"; - connect = "URI=file:" + file + ",version=3"; - db = new SQLiteUserData(); - db.Initialise(connect); - } - - [TestFixtureTearDown] - public void Cleanup() - { - db.Dispose(); - File.Delete(file); - } - } -} diff --git a/OpenSim/Data/Tests/BasicGridTest.cs b/OpenSim/Data/Tests/BasicGridTest.cs deleted file mode 100644 index df6c669..0000000 --- a/OpenSim/Data/Tests/BasicGridTest.cs +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.Text; -using NUnit.Framework; -using NUnit.Framework.SyntaxHelpers; -using OpenMetaverse; - -namespace OpenSim.Data.Tests -{ - public class BasicGridTest - { - public IGridDataPlugin db; - public UUID region1, region2, region3; - public UUID zero = UUID.Zero; - public static Random random = new Random(); - - [TearDown] - public void removeAllRegions() - { - // Clean up all the regions. - List regions = db.GetRegionsByName("", 100); - if (regions != null) - { - foreach (RegionProfileData region in regions) - { - db.DeleteProfile(region.Uuid.ToString()); - } - } - } - - public void SuperInit() - { - OpenSim.Tests.Common.TestLogging.LogToConsole(); - region1 = UUID.Random(); - region2 = UUID.Random(); - region3 = UUID.Random(); - } - - protected RegionProfileData createRegion(UUID regionUUID, string regionName) - { - RegionProfileData reg = new RegionProfileData(); - new PropertyScrambler().Scramble(reg); - reg.Uuid = regionUUID; - reg.RegionName = regionName; - - db.StoreProfile(reg); - - return reg; - } - - [Test] - public void T001_LoadEmpty() - { - Assert.That(db.GetProfileByUUID(region1),Is.Null); - Assert.That(db.GetProfileByUUID(region2),Is.Null); - Assert.That(db.GetProfileByUUID(region3),Is.Null); - Assert.That(db.GetProfileByUUID(zero),Is.Null); - } - - [Test] - public void T011_AddRetrieveCompleteTest() - { - RegionProfileData newreg = createRegion(region2, "||"); - RegionProfileData retreg = db.GetProfileByUUID(region2); - - Assert.That(retreg, Constraints.PropertyCompareConstraint(newreg).IgnoreProperty(x => x.RegionOnline)); - - retreg = db.GetProfileByHandle(newreg.RegionHandle); - Assert.That(retreg.Uuid, Is.EqualTo(region2), "Assert.That(retreg.Uuid, Is.EqualTo(region2))"); - - retreg = db.GetProfileByString(newreg.RegionName); - Assert.That(retreg.Uuid, Is.EqualTo(region2), "Assert.That(retreg.Uuid, Is.EqualTo(region2))"); - - RegionProfileData[] retregs = db.GetProfilesInRange(newreg.RegionLocX,newreg.RegionLocY,newreg.RegionLocX,newreg.RegionLocY); - Assert.That(retregs[0].Uuid, Is.EqualTo(region2), "Assert.That(retregs[0].Uuid, Is.EqualTo(region2))"); - } - - [Test] - public void T012_DeleteProfile() - { - createRegion(region1, "doesn't matter"); - - db.DeleteProfile(region1.ToString()); - RegionProfileData retreg = db.GetProfileByUUID(region1); - Assert.That(retreg,Is.Null); - } - - [Test] - public void T013_UpdateProfile() - { - createRegion(region2, "||"); - - RegionProfileData retreg = db.GetProfileByUUID(region2); - retreg.regionName = "Gotham City"; - - db.StoreProfile(retreg); - - retreg = db.GetProfileByUUID(region2); - Assert.That(retreg.RegionName, Is.EqualTo("Gotham City"), "Assert.That(retreg.RegionName, Is.EqualTo(\"Gotham City\"))"); - } - - [Test] - public void T014_RegionList() - { - createRegion(region2, "Gotham City"); - - RegionProfileData retreg = db.GetProfileByUUID(region2); - retreg.RegionName = "Gotham Town"; - retreg.Uuid = region1; - - db.StoreProfile(retreg); - - retreg = db.GetProfileByUUID(region2); - retreg.RegionName = "Gothan Town"; - retreg.Uuid = region3; - - db.StoreProfile(retreg); - - List listreg = db.GetRegionsByName("Gotham",10); - - Assert.That(listreg.Count,Is.EqualTo(2), "Assert.That(listreg.Count,Is.EqualTo(2))"); - Assert.That(listreg[0].Uuid,Is.Not.EqualTo(listreg[1].Uuid), "Assert.That(listreg[0].Uuid,Is.Not.EqualTo(listreg[1].Uuid))"); - Assert.That(listreg[0].Uuid, Is.EqualTo(region1) | Is.EqualTo(region2), "Assert.That(listreg[0].Uuid, Is.EqualTo(region1) | Is.EqualTo(region2))"); - Assert.That(listreg[1].Uuid, Is.EqualTo(region1) | Is.EqualTo(region2), "Assert.That(listreg[1].Uuid, Is.EqualTo(region1) | Is.EqualTo(region2))"); - } - - [Test] - public void T999_StillNull() - { - Assert.That(db.GetProfileByUUID(zero), Is.Null); - } - - protected static string RandomName() - { - StringBuilder name = new StringBuilder(); - int size = random.Next(5,12); - char ch ; - for (int i=0; i> 8); - homeregy = ((homeregy << 8) >> 8); - - u.ID = id; - u.WebLoginKey = webloginkey; - u.HomeRegionID = homeregion; - u.FirstName = fname; - u.SurName = lname; - u.Email = email; - u.PasswordHash = passhash; - u.PasswordSalt = passsalt; - u.HomeRegionX = homeregx; - u.HomeRegionY = homeregy; - ulong homereg = u.HomeRegion; - u.HomeLocation = homeloc; - u.HomeLookAt = homelookat; - u.Created = created; - u.LastLogin = lastlogin; - u.UserInventoryURI = userinvuri; - u.UserAssetURI = userasseturi; - u.CanDoMask = candomask; - u.WantDoMask = wantdomask; - u.AboutText = abouttext; - u.FirstLifeAboutText = flabouttext; - u.Image = image; - u.FirstLifeImage = firstimage; - u.CurrentAgent = agent; - u.UserFlags = userflags; - u.GodLevel = godlevel; - u.CustomType = customtype; - u.Partner = partner; - - db.AddNewUserProfile(u); - UserProfileData u1a = db.GetUserByUUID(id); - Assert.That(u1a,Is.Not.Null); - Assert.That(id,Is.EqualTo(u1a.ID), "Assert.That(id,Is.EqualTo(u1a.ID))"); - Assert.That(homeregion,Is.EqualTo(u1a.HomeRegionID), "Assert.That(homeregion,Is.EqualTo(u1a.HomeRegionID))"); - Assert.That(webloginkey,Is.EqualTo(u1a.WebLoginKey), "Assert.That(webloginkey,Is.EqualTo(u1a.WebLoginKey))"); - Assert.That(fname,Is.EqualTo(u1a.FirstName), "Assert.That(fname,Is.EqualTo(u1a.FirstName))"); - Assert.That(lname,Is.EqualTo(u1a.SurName), "Assert.That(lname,Is.EqualTo(u1a.SurName))"); - Assert.That(email,Is.EqualTo(u1a.Email), "Assert.That(email,Is.EqualTo(u1a.Email))"); - Assert.That(passhash,Is.EqualTo(u1a.PasswordHash), "Assert.That(passhash,Is.EqualTo(u1a.PasswordHash))"); - Assert.That(passsalt,Is.EqualTo(u1a.PasswordSalt), "Assert.That(passsalt,Is.EqualTo(u1a.PasswordSalt))"); - Assert.That(homeregx,Is.EqualTo(u1a.HomeRegionX), "Assert.That(homeregx,Is.EqualTo(u1a.HomeRegionX))"); - Assert.That(homeregy,Is.EqualTo(u1a.HomeRegionY), "Assert.That(homeregy,Is.EqualTo(u1a.HomeRegionY))"); - Assert.That(homereg,Is.EqualTo(u1a.HomeRegion), "Assert.That(homereg,Is.EqualTo(u1a.HomeRegion))"); - Assert.That(homeloc,Is.EqualTo(u1a.HomeLocation), "Assert.That(homeloc,Is.EqualTo(u1a.HomeLocation))"); - Assert.That(homelookat,Is.EqualTo(u1a.HomeLookAt), "Assert.That(homelookat,Is.EqualTo(u1a.HomeLookAt))"); - Assert.That(created,Is.EqualTo(u1a.Created), "Assert.That(created,Is.EqualTo(u1a.Created))"); - Assert.That(lastlogin,Is.EqualTo(u1a.LastLogin), "Assert.That(lastlogin,Is.EqualTo(u1a.LastLogin))"); - Assert.That(userinvuri,Is.EqualTo(u1a.UserInventoryURI), "Assert.That(userinvuri,Is.EqualTo(u1a.UserInventoryURI))"); - Assert.That(userasseturi,Is.EqualTo(u1a.UserAssetURI), "Assert.That(userasseturi,Is.EqualTo(u1a.UserAssetURI))"); - Assert.That(candomask,Is.EqualTo(u1a.CanDoMask), "Assert.That(candomask,Is.EqualTo(u1a.CanDoMask))"); - Assert.That(wantdomask,Is.EqualTo(u1a.WantDoMask), "Assert.That(wantdomask,Is.EqualTo(u1a.WantDoMask))"); - Assert.That(abouttext,Is.EqualTo(u1a.AboutText), "Assert.That(abouttext,Is.EqualTo(u1a.AboutText))"); - Assert.That(flabouttext,Is.EqualTo(u1a.FirstLifeAboutText), "Assert.That(flabouttext,Is.EqualTo(u1a.FirstLifeAboutText))"); - Assert.That(image,Is.EqualTo(u1a.Image), "Assert.That(image,Is.EqualTo(u1a.Image))"); - Assert.That(firstimage,Is.EqualTo(u1a.FirstLifeImage), "Assert.That(firstimage,Is.EqualTo(u1a.FirstLifeImage))"); - Assert.That(u1a.CurrentAgent,Is.Null); - Assert.That(userflags,Is.EqualTo(u1a.UserFlags), "Assert.That(userflags,Is.EqualTo(u1a.UserFlags))"); - Assert.That(godlevel,Is.EqualTo(u1a.GodLevel), "Assert.That(godlevel,Is.EqualTo(u1a.GodLevel))"); - Assert.That(customtype,Is.EqualTo(u1a.CustomType), "Assert.That(customtype,Is.EqualTo(u1a.CustomType))"); - Assert.That(partner,Is.EqualTo(u1a.Partner), "Assert.That(partner,Is.EqualTo(u1a.Partner))"); - } - - [Test] - public void T016_UserUpdatePersistency() - { - UUID id = user5; - UserProfileData u = db.GetUserByUUID(id); - string fname = RandomName(); - string lname = RandomName(); - string email = RandomName(); - string passhash = RandomName(); - string passsalt = RandomName(); - UUID homeregionid = UUID.Random(); - UUID webloginkey = UUID.Random(); - uint homeregx = (uint) random.Next(); - uint homeregy = (uint) random.Next(); - Vector3 homeloc = new Vector3((float)Math.Round(random.NextDouble(),5),(float)Math.Round(random.NextDouble(),5),(float)Math.Round(random.NextDouble(),5)); - Vector3 homelookat = new Vector3((float)Math.Round(random.NextDouble(),5),(float)Math.Round(random.NextDouble(),5),(float)Math.Round(random.NextDouble(),5)); - int created = random.Next(); - int lastlogin = random.Next(); - string userinvuri = RandomName(); - string userasseturi = RandomName(); - uint candomask = (uint) random.Next(); - uint wantdomask = (uint) random.Next(); - string abouttext = RandomName(); - string flabouttext = RandomName(); - UUID image = UUID.Random(); - UUID firstimage = UUID.Random(); - UserAgentData agent = NewAgent(id,UUID.Random()); - int userflags = random.Next(); - int godlevel = random.Next(); - string customtype = RandomName(); - UUID partner = UUID.Random(); - - //HomeRegionX and HomeRegionY must only use 24 bits - homeregx = ((homeregx << 8) >> 8); - homeregy = ((homeregy << 8) >> 8); - - u.WebLoginKey = webloginkey; - u.HomeRegionID = homeregionid; - u.FirstName = fname; - u.SurName = lname; - u.Email = email; - u.PasswordHash = passhash; - u.PasswordSalt = passsalt; - u.HomeRegionX = homeregx; - u.HomeRegionY = homeregy; - ulong homereg = u.HomeRegion; - u.HomeLocation = homeloc; - u.HomeLookAt = homelookat; - u.Created = created; - u.LastLogin = lastlogin; - u.UserInventoryURI = userinvuri; - u.UserAssetURI = userasseturi; - u.CanDoMask = candomask; - u.WantDoMask = wantdomask; - u.AboutText = abouttext; - u.FirstLifeAboutText = flabouttext; - u.Image = image; - u.FirstLifeImage = firstimage; - u.CurrentAgent = agent; - u.UserFlags = userflags; - u.GodLevel = godlevel; - u.CustomType = customtype; - u.Partner = partner; - - db.UpdateUserProfile(u); - UserProfileData u1a = db.GetUserByUUID(id); - Assert.That(u1a,Is.Not.Null); - Assert.That(id,Is.EqualTo(u1a.ID), "Assert.That(id,Is.EqualTo(u1a.ID))"); - Assert.That(homeregionid,Is.EqualTo(u1a.HomeRegionID), "Assert.That(homeregionid,Is.EqualTo(u1a.HomeRegionID))"); - Assert.That(webloginkey,Is.EqualTo(u1a.WebLoginKey), "Assert.That(webloginkey,Is.EqualTo(u1a.WebLoginKey))"); - Assert.That(fname,Is.EqualTo(u1a.FirstName), "Assert.That(fname,Is.EqualTo(u1a.FirstName))"); - Assert.That(lname,Is.EqualTo(u1a.SurName), "Assert.That(lname,Is.EqualTo(u1a.SurName))"); - Assert.That(email,Is.EqualTo(u1a.Email), "Assert.That(email,Is.EqualTo(u1a.Email))"); - Assert.That(passhash,Is.EqualTo(u1a.PasswordHash), "Assert.That(passhash,Is.EqualTo(u1a.PasswordHash))"); - Assert.That(passsalt,Is.EqualTo(u1a.PasswordSalt), "Assert.That(passsalt,Is.EqualTo(u1a.PasswordSalt))"); - Assert.That(homereg,Is.EqualTo(u1a.HomeRegion), "Assert.That(homereg,Is.EqualTo(u1a.HomeRegion))"); - Assert.That(homeregx,Is.EqualTo(u1a.HomeRegionX), "Assert.That(homeregx,Is.EqualTo(u1a.HomeRegionX))"); - Assert.That(homeregy,Is.EqualTo(u1a.HomeRegionY), "Assert.That(homeregy,Is.EqualTo(u1a.HomeRegionY))"); - Assert.That(homereg,Is.EqualTo(u1a.HomeRegion), "Assert.That(homereg,Is.EqualTo(u1a.HomeRegion))"); - Assert.That(homeloc,Is.EqualTo(u1a.HomeLocation), "Assert.That(homeloc,Is.EqualTo(u1a.HomeLocation))"); - Assert.That(homelookat,Is.EqualTo(u1a.HomeLookAt), "Assert.That(homelookat,Is.EqualTo(u1a.HomeLookAt))"); - Assert.That(created,Is.EqualTo(u1a.Created), "Assert.That(created,Is.EqualTo(u1a.Created))"); - Assert.That(lastlogin,Is.EqualTo(u1a.LastLogin), "Assert.That(lastlogin,Is.EqualTo(u1a.LastLogin))"); - Assert.That(userasseturi,Is.EqualTo(u1a.UserAssetURI), "Assert.That(userasseturi,Is.EqualTo(u1a.UserAssetURI))"); - Assert.That(candomask,Is.EqualTo(u1a.CanDoMask), "Assert.That(candomask,Is.EqualTo(u1a.CanDoMask))"); - Assert.That(wantdomask,Is.EqualTo(u1a.WantDoMask), "Assert.That(wantdomask,Is.EqualTo(u1a.WantDoMask))"); - Assert.That(abouttext,Is.EqualTo(u1a.AboutText), "Assert.That(abouttext,Is.EqualTo(u1a.AboutText))"); - Assert.That(flabouttext,Is.EqualTo(u1a.FirstLifeAboutText), "Assert.That(flabouttext,Is.EqualTo(u1a.FirstLifeAboutText))"); - Assert.That(image,Is.EqualTo(u1a.Image), "Assert.That(image,Is.EqualTo(u1a.Image))"); - Assert.That(firstimage,Is.EqualTo(u1a.FirstLifeImage), "Assert.That(firstimage,Is.EqualTo(u1a.FirstLifeImage))"); - Assert.That(u1a.CurrentAgent,Is.Null); - Assert.That(userflags,Is.EqualTo(u1a.UserFlags), "Assert.That(userflags,Is.EqualTo(u1a.UserFlags))"); - Assert.That(godlevel,Is.EqualTo(u1a.GodLevel), "Assert.That(godlevel,Is.EqualTo(u1a.GodLevel))"); - Assert.That(customtype,Is.EqualTo(u1a.CustomType), "Assert.That(customtype,Is.EqualTo(u1a.CustomType))"); - Assert.That(partner,Is.EqualTo(u1a.Partner), "Assert.That(partner,Is.EqualTo(u1a.Partner))"); - } - - [Test] - public void T017_UserUpdateRandomPersistency() - { - UUID id = user5; - UserProfileData u = db.GetUserByUUID(id); - new PropertyScrambler().DontScramble(x=>x.ID).Scramble(u); - - db.UpdateUserProfile(u); - UserProfileData u1a = db.GetUserByUUID(id); - Assert.That(u1a, Constraints.PropertyCompareConstraint(u) - .IgnoreProperty(x=>x.HomeRegionX) - .IgnoreProperty(x=>x.HomeRegionY) - ); - } - - [Test] - public void T020_CreateAgent() - { - UserAgentData a1 = NewAgent(user1,agent1); - UserAgentData a2 = NewAgent(user2,agent2); - UserAgentData a3 = NewAgent(user3,agent3); - db.AddNewUserAgent(a1); - db.AddNewUserAgent(a2); - db.AddNewUserAgent(a3); - UserAgentData a1a = db.GetAgentByUUID(user1); - UserAgentData a2a = db.GetAgentByUUID(user2); - UserAgentData a3a = db.GetAgentByUUID(user3); - Assert.That(agent1,Is.EqualTo(a1a.SessionID), "Assert.That(agent1,Is.EqualTo(a1a.SessionID))"); - Assert.That(user1,Is.EqualTo(a1a.ProfileID), "Assert.That(user1,Is.EqualTo(a1a.ProfileID))"); - Assert.That(agent2,Is.EqualTo(a2a.SessionID), "Assert.That(agent2,Is.EqualTo(a2a.SessionID))"); - Assert.That(user2,Is.EqualTo(a2a.ProfileID), "Assert.That(user2,Is.EqualTo(a2a.ProfileID))"); - Assert.That(agent3,Is.EqualTo(a3a.SessionID), "Assert.That(agent3,Is.EqualTo(a3a.SessionID))"); - Assert.That(user3,Is.EqualTo(a3a.ProfileID), "Assert.That(user3,Is.EqualTo(a3a.ProfileID))"); - } - - [Test] - public void T021_FetchAgentByName() - { - String name3 = fname3 + " " + lname3; - UserAgentData a2 = db.GetAgentByName(fname2,lname2); - UserAgentData a3 = db.GetAgentByName(name3); - Assert.That(user2,Is.EqualTo(a2.ProfileID), "Assert.That(user2,Is.EqualTo(a2.ProfileID))"); - Assert.That(user3,Is.EqualTo(a3.ProfileID), "Assert.That(user3,Is.EqualTo(a3.ProfileID))"); - } - - [Test] - public void T022_ExceptionalCases() - { - UserAgentData a0 = NewAgent(user4,zero); - UserAgentData a4 = NewAgent(zero,agent4); - db.AddNewUserAgent(a0); - db.AddNewUserAgent(a4); - - Assert.That(db.GetAgentByUUID(user4),Is.Null); - Assert.That(db.GetAgentByUUID(zero),Is.Null); - } - - [Test] - public void T023_AgentPersistency() - { - UUID user = user4; - UUID agent = agent4; - UUID secureagent = UUID.Random(); - string agentip = RandomName(); - uint agentport = (uint)random.Next(); - bool agentonline = (random.NextDouble() > 0.5); - int logintime = random.Next(); - int logouttime = random.Next(); - UUID regionid = UUID.Random(); - ulong regionhandle = (ulong) random.Next(); - Vector3 currentpos = new Vector3((float)Math.Round(random.NextDouble(),5),(float)Math.Round(random.NextDouble(),5),(float)Math.Round(random.NextDouble(),5)); - Vector3 currentlookat = new Vector3((float)Math.Round(random.NextDouble(),5),(float)Math.Round(random.NextDouble(),5),(float)Math.Round(random.NextDouble(),5)); - UUID orgregionid = UUID.Random(); - - UserAgentData a = new UserAgentData(); - a.ProfileID = user; - a.SessionID = agent; - a.SecureSessionID = secureagent; - a.AgentIP = agentip; - a.AgentPort = agentport; - a.AgentOnline = agentonline; - a.LoginTime = logintime; - a.LogoutTime = logouttime; - a.Region = regionid; - a.Handle = regionhandle; - a.Position = currentpos; - a.LookAt = currentlookat; - a.InitialRegion = orgregionid; - - db.AddNewUserAgent(a); - - UserAgentData a1 = db.GetAgentByUUID(user4); - Assert.That(user,Is.EqualTo(a1.ProfileID), "Assert.That(user,Is.EqualTo(a1.ProfileID))"); - Assert.That(agent,Is.EqualTo(a1.SessionID), "Assert.That(agent,Is.EqualTo(a1.SessionID))"); - Assert.That(secureagent,Is.EqualTo(a1.SecureSessionID), "Assert.That(secureagent,Is.EqualTo(a1.SecureSessionID))"); - Assert.That(agentip,Is.EqualTo(a1.AgentIP), "Assert.That(agentip,Is.EqualTo(a1.AgentIP))"); - Assert.That(agentport,Is.EqualTo(a1.AgentPort), "Assert.That(agentport,Is.EqualTo(a1.AgentPort))"); - Assert.That(agentonline,Is.EqualTo(a1.AgentOnline), "Assert.That(agentonline,Is.EqualTo(a1.AgentOnline))"); - Assert.That(logintime,Is.EqualTo(a1.LoginTime), "Assert.That(logintime,Is.EqualTo(a1.LoginTime))"); - Assert.That(logouttime,Is.EqualTo(a1.LogoutTime), "Assert.That(logouttime,Is.EqualTo(a1.LogoutTime))"); - Assert.That(regionid,Is.EqualTo(a1.Region), "Assert.That(regionid,Is.EqualTo(a1.Region))"); - Assert.That(regionhandle,Is.EqualTo(a1.Handle), "Assert.That(regionhandle,Is.EqualTo(a1.Handle))"); - Assert.That(currentpos,Is.EqualTo(a1.Position), "Assert.That(currentpos,Is.EqualTo(a1.Position))"); - Assert.That(currentlookat,Is.EqualTo(a1.LookAt), "Assert.That(currentlookat,Is.EqualTo(a1.LookAt))"); - } - - [Test] - public void T030_CreateFriendList() - { - Dictionary perms = new Dictionary(); - Dictionary friends = new Dictionary(); - uint temp; - int tempu1, tempu2; - db.AddNewUserFriend(user1,user2, 1); - db.AddNewUserFriend(user1,user3, 2); - db.AddNewUserFriend(user1,user2, 4); - List fl1 = db.GetUserFriendList(user1); - Assert.That(fl1.Count,Is.EqualTo(2), "Assert.That(fl1.Count,Is.EqualTo(2))"); - perms.Add(user2,1); - perms.Add(user3,2); - for (int i = 0; i < fl1.Count; i++) - { - Assert.That(user1,Is.EqualTo(fl1[i].FriendListOwner), "Assert.That(user1,Is.EqualTo(fl1[i].FriendListOwner))"); - friends.Add(fl1[i].Friend,1); - temp = perms[fl1[i].Friend]; - Assert.That(temp,Is.EqualTo(fl1[i].FriendPerms), "Assert.That(temp,Is.EqualTo(fl1[i].FriendPerms))"); - } - tempu1 = friends[user2]; - tempu2 = friends[user3]; - Assert.That(1,Is.EqualTo(tempu1) & Is.EqualTo(tempu2), "Assert.That(1,Is.EqualTo(tempu1) & Is.EqualTo(tempu2))"); - } - - [Test] - public void T031_RemoveUserFriend() - // user1 has 2 friends, user2 and user3. - { - List fl1 = db.GetUserFriendList(user1); - List fl2 = db.GetUserFriendList(user2); - - Assert.That(fl1.Count,Is.EqualTo(2), "Assert.That(fl1.Count,Is.EqualTo(2))"); - Assert.That(fl1[0].Friend,Is.EqualTo(user2) | Is.EqualTo(user3), "Assert.That(fl1[0].Friend,Is.EqualTo(user2) | Is.EqualTo(user3))"); - Assert.That(fl2[0].Friend,Is.EqualTo(user1), "Assert.That(fl2[0].Friend,Is.EqualTo(user1))"); - db.RemoveUserFriend(user2, user1); - - fl1 = db.GetUserFriendList(user1); - fl2 = db.GetUserFriendList(user2); - Assert.That(fl1.Count,Is.EqualTo(1), "Assert.That(fl1.Count,Is.EqualTo(1))"); - Assert.That(fl1[0].Friend, Is.EqualTo(user3), "Assert.That(fl1[0].Friend, Is.EqualTo(user3))"); - Assert.That(fl2, Is.Empty); - } - - [Test] - public void T032_UpdateFriendPerms() - // user1 has 1 friend, user3, who has permission 2 in T030. - { - List fl1 = db.GetUserFriendList(user1); - Assert.That(fl1[0].FriendPerms,Is.EqualTo(2), "Assert.That(fl1[0].FriendPerms,Is.EqualTo(2))"); - db.UpdateUserFriendPerms(user1, user3, 4); - - fl1 = db.GetUserFriendList(user1); - Assert.That(fl1[0].FriendPerms,Is.EqualTo(4), "Assert.That(fl1[0].FriendPerms,Is.EqualTo(4))"); - } - - [Test] - public void T040_UserAppearance() - { - AvatarAppearance appear = new AvatarAppearance(); - appear.Owner = user1; - db.UpdateUserAppearance(user1, appear); - AvatarAppearance user1app = db.GetUserAppearance(user1); - Assert.That(user1,Is.EqualTo(user1app.Owner), "Assert.That(user1,Is.EqualTo(user1app.Owner))"); - } - - [Test] - public void T041_UserAppearancePersistency() - { - AvatarAppearance appear = new AvatarAppearance(); - UUID owner = UUID.Random(); - int serial = random.Next(); - byte[] visualp = new byte[218]; - random.NextBytes(visualp); - UUID bodyitem = UUID.Random(); - UUID bodyasset = UUID.Random(); - UUID skinitem = UUID.Random(); - UUID skinasset = UUID.Random(); - UUID hairitem = UUID.Random(); - UUID hairasset = UUID.Random(); - UUID eyesitem = UUID.Random(); - UUID eyesasset = UUID.Random(); - UUID shirtitem = UUID.Random(); - UUID shirtasset = UUID.Random(); - UUID pantsitem = UUID.Random(); - UUID pantsasset = UUID.Random(); - UUID shoesitem = UUID.Random(); - UUID shoesasset = UUID.Random(); - UUID socksitem = UUID.Random(); - UUID socksasset = UUID.Random(); - UUID jacketitem = UUID.Random(); - UUID jacketasset = UUID.Random(); - UUID glovesitem = UUID.Random(); - UUID glovesasset = UUID.Random(); - UUID ushirtitem = UUID.Random(); - UUID ushirtasset = UUID.Random(); - UUID upantsitem = UUID.Random(); - UUID upantsasset = UUID.Random(); - UUID skirtitem = UUID.Random(); - UUID skirtasset = UUID.Random(); - Primitive.TextureEntry texture = AvatarAppearance.GetDefaultTexture(); - float avatarheight = (float) (Math.Round(random.NextDouble(),5)); - - appear.Owner = owner; - appear.Serial = serial; - appear.VisualParams = visualp; - appear.BodyItem = bodyitem; - appear.BodyAsset = bodyasset; - appear.SkinItem = skinitem; - appear.SkinAsset = skinasset; - appear.HairItem = hairitem; - appear.HairAsset = hairasset; - appear.EyesItem = eyesitem; - appear.EyesAsset = eyesasset; - appear.ShirtItem = shirtitem; - appear.ShirtAsset = shirtasset; - appear.PantsItem = pantsitem; - appear.PantsAsset = pantsasset; - appear.ShoesItem = shoesitem; - appear.ShoesAsset = shoesasset; - appear.SocksItem = socksitem; - appear.SocksAsset = socksasset; - appear.JacketItem = jacketitem; - appear.JacketAsset = jacketasset; - appear.GlovesItem = glovesitem; - appear.GlovesAsset = glovesasset; - appear.UnderShirtItem = ushirtitem; - appear.UnderShirtAsset = ushirtasset; - appear.UnderPantsItem = upantsitem; - appear.UnderPantsAsset = upantsasset; - appear.SkirtItem = skirtitem; - appear.SkirtAsset = skirtasset; - appear.Texture = texture; - appear.AvatarHeight = avatarheight; - - db.UpdateUserAppearance(owner, appear); - AvatarAppearance app = db.GetUserAppearance(owner); - - Assert.That(owner,Is.EqualTo(app.Owner), "Assert.That(owner,Is.EqualTo(app.Owner))"); - Assert.That(serial,Is.EqualTo(app.Serial), "Assert.That(serial,Is.EqualTo(app.Serial))"); - Assert.That(visualp,Is.EqualTo(app.VisualParams), "Assert.That(visualp,Is.EqualTo(app.VisualParams))"); - Assert.That(bodyitem,Is.EqualTo(app.BodyItem), "Assert.That(bodyitem,Is.EqualTo(app.BodyItem))"); - Assert.That(bodyasset,Is.EqualTo(app.BodyAsset), "Assert.That(bodyasset,Is.EqualTo(app.BodyAsset))"); - Assert.That(skinitem,Is.EqualTo(app.SkinItem), "Assert.That(skinitem,Is.EqualTo(app.SkinItem))"); - Assert.That(skinasset,Is.EqualTo(app.SkinAsset), "Assert.That(skinasset,Is.EqualTo(app.SkinAsset))"); - Assert.That(hairitem,Is.EqualTo(app.HairItem), "Assert.That(hairitem,Is.EqualTo(app.HairItem))"); - Assert.That(hairasset,Is.EqualTo(app.HairAsset), "Assert.That(hairasset,Is.EqualTo(app.HairAsset))"); - Assert.That(eyesitem,Is.EqualTo(app.EyesItem), "Assert.That(eyesitem,Is.EqualTo(app.EyesItem))"); - Assert.That(eyesasset,Is.EqualTo(app.EyesAsset), "Assert.That(eyesasset,Is.EqualTo(app.EyesAsset))"); - Assert.That(shirtitem,Is.EqualTo(app.ShirtItem), "Assert.That(shirtitem,Is.EqualTo(app.ShirtItem))"); - Assert.That(shirtasset,Is.EqualTo(app.ShirtAsset), "Assert.That(shirtasset,Is.EqualTo(app.ShirtAsset))"); - Assert.That(pantsitem,Is.EqualTo(app.PantsItem), "Assert.That(pantsitem,Is.EqualTo(app.PantsItem))"); - Assert.That(pantsasset,Is.EqualTo(app.PantsAsset), "Assert.That(pantsasset,Is.EqualTo(app.PantsAsset))"); - Assert.That(shoesitem,Is.EqualTo(app.ShoesItem), "Assert.That(shoesitem,Is.EqualTo(app.ShoesItem))"); - Assert.That(shoesasset,Is.EqualTo(app.ShoesAsset), "Assert.That(shoesasset,Is.EqualTo(app.ShoesAsset))"); - Assert.That(socksitem,Is.EqualTo(app.SocksItem), "Assert.That(socksitem,Is.EqualTo(app.SocksItem))"); - Assert.That(socksasset,Is.EqualTo(app.SocksAsset), "Assert.That(socksasset,Is.EqualTo(app.SocksAsset))"); - Assert.That(jacketitem,Is.EqualTo(app.JacketItem), "Assert.That(jacketitem,Is.EqualTo(app.JacketItem))"); - Assert.That(jacketasset,Is.EqualTo(app.JacketAsset), "Assert.That(jacketasset,Is.EqualTo(app.JacketAsset))"); - Assert.That(glovesitem,Is.EqualTo(app.GlovesItem), "Assert.That(glovesitem,Is.EqualTo(app.GlovesItem))"); - Assert.That(glovesasset,Is.EqualTo(app.GlovesAsset), "Assert.That(glovesasset,Is.EqualTo(app.GlovesAsset))"); - Assert.That(ushirtitem,Is.EqualTo(app.UnderShirtItem), "Assert.That(ushirtitem,Is.EqualTo(app.UnderShirtItem))"); - Assert.That(ushirtasset,Is.EqualTo(app.UnderShirtAsset), "Assert.That(ushirtasset,Is.EqualTo(app.UnderShirtAsset))"); - Assert.That(upantsitem,Is.EqualTo(app.UnderPantsItem), "Assert.That(upantsitem,Is.EqualTo(app.UnderPantsItem))"); - Assert.That(upantsasset,Is.EqualTo(app.UnderPantsAsset), "Assert.That(upantsasset,Is.EqualTo(app.UnderPantsAsset))"); - Assert.That(skirtitem,Is.EqualTo(app.SkirtItem), "Assert.That(skirtitem,Is.EqualTo(app.SkirtItem))"); - Assert.That(skirtasset,Is.EqualTo(app.SkirtAsset), "Assert.That(skirtasset,Is.EqualTo(app.SkirtAsset))"); - Assert.That(texture.ToString(),Is.EqualTo(app.Texture.ToString()), "Assert.That(texture.ToString(),Is.EqualTo(app.Texture.ToString()))"); - Assert.That(avatarheight,Is.EqualTo(app.AvatarHeight), "Assert.That(avatarheight,Is.EqualTo(app.AvatarHeight))"); - } - - [Test] - public void T999_StillNull() - { - Assert.That(db.GetUserByUUID(zero), Is.Null); - Assert.That(db.GetAgentByUUID(zero), Is.Null); - } - - public UserProfileData NewUser(UUID id,string fname,string lname) - { - UserProfileData u = new UserProfileData(); - u.ID = id; - u.FirstName = fname; - u.SurName = lname; - u.PasswordHash = "NOTAHASH"; - u.PasswordSalt = "NOTSALT"; - // MUST specify at least these 5 parameters or an exception is raised - - return u; - } - - public UserAgentData NewAgent(UUID user_profile, UUID agent) - { - UserAgentData a = new UserAgentData(); - a.ProfileID = user_profile; - a.SessionID = agent; - a.SecureSessionID = UUID.Random(); - a.AgentIP = RandomName(); - return a; - } - - public static string RandomName() - { - StringBuilder name = new StringBuilder(); - int size = random.Next(5,12); - char ch ; - for (int i=0; i aplist = new Dictionary(); - - public abstract UserProfileData GetUserByUUID(UUID user); - public abstract UserProfileData GetUserByName(string fname, string lname); - public abstract UserAgentData GetAgentByUUID(UUID user); - public abstract UserAgentData GetAgentByName(string name); - public abstract UserAgentData GetAgentByName(string fname, string lname); - public UserProfileData GetUserByUri(Uri uri) { return null; } - public abstract void StoreWebLoginKey(UUID agentID, UUID webLoginKey); - public abstract void AddNewUserProfile(UserProfileData user); - - public virtual void AddTemporaryUserProfile(UserProfileData userProfile) - { - // Deliberately blank - database plugins shouldn't store temporary profiles. - } - - public abstract bool UpdateUserProfile(UserProfileData user); - public abstract void AddNewUserAgent(UserAgentData agent); - public abstract void AddNewUserFriend(UUID friendlistowner, UUID friend, uint perms); - public abstract void RemoveUserFriend(UUID friendlistowner, UUID friend); - public abstract void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms); - public abstract List GetUserFriendList(UUID friendlistowner); - public abstract Dictionary GetFriendRegionInfos (List uuids); - public abstract bool MoneyTransferRequest(UUID from, UUID to, uint amount); - public abstract bool InventoryTransferRequest(UUID from, UUID to, UUID inventory); - public abstract List GeneratePickerResults(UUID queryID, string query); - public abstract AvatarAppearance GetUserAppearance(UUID user); - public abstract void UpdateUserAppearance(UUID user, AvatarAppearance appearance); - // public virtual AvatarAppearance GetUserAppearance(UUID user) { - // AvatarAppearance aa = null; - // try { - // aa = aplist[user]; - // m_log.Info("[APPEARANCE] Found appearance for " + user.ToString() + aa.ToString()); - // } catch (System.Collections.Generic.KeyNotFoundException e) { - // m_log.Info("[APPEARANCE] No appearance found for " + user.ToString()); - // } - // return aa; - // } - // public virtual void UpdateUserAppearance(UUID user, AvatarAppearance appearance) { - // aplist[user] = appearance; - // m_log.Info("[APPEARANCE] Setting appearance for " + user.ToString() + appearance.ToString()); - // } - public abstract void ResetAttachments(UUID userID); - - public abstract void LogoutUsers(UUID regionID); - - public abstract string Version {get;} - public abstract string Name {get;} - public abstract void Initialise(string connect); - public abstract void Initialise(); - public abstract void Dispose(); - } -} diff --git a/OpenSim/Framework/Communications/TemporaryUserProfilePlugin.cs b/OpenSim/Framework/Communications/TemporaryUserProfilePlugin.cs deleted file mode 100644 index 2413055..0000000 --- a/OpenSim/Framework/Communications/TemporaryUserProfilePlugin.cs +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using System.Reflection; -using log4net; -using OpenMetaverse; -using OpenSim.Data; - -namespace OpenSim.Framework.Communications -{ - /// - /// Plugin for managing temporary user profiles. - /// - public class TemporaryUserProfilePlugin : IUserDataPlugin - { - //private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - protected Dictionary m_profiles = new Dictionary(); - - public string Name { get { return "TemporaryUserProfilePlugin"; } } - public string Version { get { return "0.1"; } } - public void Initialise() {} - public void Initialise(string connect) {} - public void Dispose() {} - - public UserProfileData GetUserByUUID(UUID user) - { - //m_log.DebugFormat("[TEMP USER PROFILE]: Received request for {0}", user); - - lock (m_profiles) - { - if (m_profiles.ContainsKey(user)) - return m_profiles[user]; - else - return null; - } - } - - public UserProfileData GetUserByName(string fname, string lname) - { - // We deliberately don't look up a temporary profile by name so that we don't obscure non-temporary - // profiles. - - return null; - } - - public virtual void AddTemporaryUserProfile(UserProfileData userProfile) - { - //m_log.DebugFormat("[TEMP USER PROFILE]: Adding {0} {1}", userProfile.Name, userProfile.ID); - - lock (m_profiles) - { - m_profiles[userProfile.ID] = userProfile; - } - } - - public UserProfileData GetUserByUri(Uri uri) { return null; } - public List GeneratePickerResults(UUID queryID, string query) { return null; } - public UserAgentData GetAgentByUUID(UUID user) { return null; } - public UserAgentData GetAgentByName(string name) { return null; } - public UserAgentData GetAgentByName(string fname, string lname) { return null; } - public void StoreWebLoginKey(UUID agentID, UUID webLoginKey) {} - public void AddNewUserProfile(UserProfileData user) {} - public bool UpdateUserProfile(UserProfileData user) { return false; } - public void AddNewUserAgent(UserAgentData agent) {} - public void AddNewUserFriend(UUID friendlistowner, UUID friend, uint perms) {} - public void RemoveUserFriend(UUID friendlistowner, UUID friend) {} - public void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms) {} - public List GetUserFriendList(UUID friendlistowner) { return null; } - public Dictionary GetFriendRegionInfos(List uuids) { return null; } - public bool MoneyTransferRequest(UUID from, UUID to, uint amount) { return false; } - public bool InventoryTransferRequest(UUID from, UUID to, UUID inventory) { return false; } - public AvatarAppearance GetUserAppearance(UUID user) { return null; } - public void UpdateUserAppearance(UUID user, AvatarAppearance appearance) {} - public void ResetAttachments(UUID userID) {} - public void LogoutUsers(UUID regionID) {} - } -} diff --git a/OpenSim/Tests/Common/Mock/TestUserDataPlugin.cs b/OpenSim/Tests/Common/Mock/TestUserDataPlugin.cs deleted file mode 100644 index 5188cf6..0000000 --- a/OpenSim/Tests/Common/Mock/TestUserDataPlugin.cs +++ /dev/null @@ -1,216 +0,0 @@ -/* - * Copyright (c) Contributors, http://opensimulator.org/ - * See CONTRIBUTORS.TXT for a full list of copyright holders. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the OpenSimulator Project nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -using System; -using System.Collections.Generic; -using OpenMetaverse; -using OpenSim.Framework; -using OpenSim.Data; - -namespace OpenSim.Tests.Common.Mock -{ - /// - /// In memory user data provider. Might be quite useful as a proper user data plugin, though getting mono addins - /// to load any plugins when running unit tests has proven impossible so far. Currently no locking since unit - /// tests are single threaded. - /// - public class TestUserDataPlugin : IUserDataPlugin - { - public string Version { get { return "0"; } } - public string Name { get { return "TestUserDataPlugin"; } } - - /// - /// User profiles keyed by name - /// - private Dictionary m_userProfilesByName = new Dictionary(); - - /// - /// User profiles keyed by uuid - /// - private Dictionary m_userProfilesByUuid = new Dictionary(); - - /// - /// User profiles and their agents - /// - private Dictionary m_agentByProfileUuid = new Dictionary(); - - /// - /// Friends list by uuid - /// - private Dictionary> m_friendsListByUuid = new Dictionary>(); - - public void Initialise() {} - public void Dispose() {} - - public void AddTemporaryUserProfile(UserProfileData userProfile) - { - // Not interested - } - - public void AddNewUserProfile(UserProfileData user) - { - UpdateUserProfile(user); - } - - public UserProfileData GetUserByUUID(UUID user) - { - UserProfileData userProfile = null; - m_userProfilesByUuid.TryGetValue(user, out userProfile); - - return userProfile; - } - - public UserProfileData GetUserByName(string fname, string lname) - { - UserProfileData userProfile = null; - m_userProfilesByName.TryGetValue(fname + " " + lname, out userProfile); - - return userProfile; - } - - public UserProfileData GetUserByUri(Uri uri) { return null; } - - public bool UpdateUserProfile(UserProfileData user) - { - m_userProfilesByUuid[user.ID] = user; - m_userProfilesByName[user.FirstName + " " + user.SurName] = user; - - return true; - } - - public List GeneratePickerResults(UUID queryID, string query) { return null; } - - public UserAgentData GetAgentByUUID(UUID user) - { - UserAgentData userAgent = null; - m_agentByProfileUuid.TryGetValue(user, out userAgent); - - return userAgent; - } - - public UserAgentData GetAgentByName(string name) - { - UserProfileData userProfile = null; - m_userProfilesByName.TryGetValue(name, out userProfile); - UserAgentData userAgent = null; - m_agentByProfileUuid.TryGetValue(userProfile.ID, out userAgent); - - return userAgent; - } - - public UserAgentData GetAgentByName(string fname, string lname) - { - UserProfileData userProfile = GetUserByName(fname,lname); - UserAgentData userAgent = null; - m_agentByProfileUuid.TryGetValue(userProfile.ID, out userAgent); - - return userAgent; - } - - public void StoreWebLoginKey(UUID agentID, UUID webLoginKey) {} - - public void AddNewUserAgent(UserAgentData agent) - { - m_agentByProfileUuid[agent.ProfileID] = agent; - } - public void AddNewUserFriend(UUID friendlistowner, UUID friend, uint perms) - { - FriendListItem newfriend = new FriendListItem(); - newfriend.FriendPerms = perms; - newfriend.Friend = friend; - newfriend.FriendListOwner = friendlistowner; - - if (!m_friendsListByUuid.ContainsKey(friendlistowner)) - { - List friendslist = new List(); - m_friendsListByUuid[friendlistowner] = friendslist; - - } - m_friendsListByUuid[friendlistowner].Add(newfriend); - } - - public void RemoveUserFriend(UUID friendlistowner, UUID friend) - { - if (m_friendsListByUuid.ContainsKey(friendlistowner)) - { - List friendslist = m_friendsListByUuid[friendlistowner]; - foreach (FriendListItem frienditem in friendslist) - { - if (frienditem.Friend == friend) - { - friendslist.Remove(frienditem); - break; - } - } - } - } - - public void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms) - { - if (m_friendsListByUuid.ContainsKey(friendlistowner)) - { - List friendslist = m_friendsListByUuid[friendlistowner]; - foreach (FriendListItem frienditem in friendslist) - { - if (frienditem.Friend == friend) - { - frienditem.FriendPerms = perms; - break; - } - } - } - } - - public List GetUserFriendList(UUID friendlistowner) - { - if (m_friendsListByUuid.ContainsKey(friendlistowner)) - { - return m_friendsListByUuid[friendlistowner]; - } - else - return new List(); - - - } - - public Dictionary GetFriendRegionInfos(List uuids) { return null; } - - public bool MoneyTransferRequest(UUID from, UUID to, uint amount) { return false; } - - public bool InventoryTransferRequest(UUID from, UUID to, UUID inventory) { return false; } - - public void Initialise(string connect) { return; } - - public AvatarAppearance GetUserAppearance(UUID user) { return null; } - - public void UpdateUserAppearance(UUID user, AvatarAppearance appearance) {} - - public void ResetAttachments(UUID userID) {} - - public void LogoutUsers(UUID regionID) {} - } -} -- cgit v1.1 From b92645ac5647d6c12f0ff2af214c6c4ef6e58680 Mon Sep 17 00:00:00 2001 From: Diva Canto Date: Sun, 21 Feb 2010 17:59:00 -0800 Subject: MySQL tests pass, except T016_RandomSogWithSceneParts. Total mystery as to why that test doesn't show in panda. --- OpenSim/Data/Tests/BasicAssetTest.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/OpenSim/Data/Tests/BasicAssetTest.cs b/OpenSim/Data/Tests/BasicAssetTest.cs index 25aed61..967d70d 100644 --- a/OpenSim/Data/Tests/BasicAssetTest.cs +++ b/OpenSim/Data/Tests/BasicAssetTest.cs @@ -73,17 +73,23 @@ namespace OpenSim.Data.Tests a2.Data = asset1; a3.Data = asset1; + a1.Metadata.ContentType = "application/octet-stream"; + a2.Metadata.ContentType = "application/octet-stream"; + a3.Metadata.ContentType = "application/octet-stream"; + PropertyScrambler scrambler = new PropertyScrambler() .DontScramble(x => x.Data) .DontScramble(x => x.ID) .DontScramble(x => x.FullID) .DontScramble(x => x.Metadata.ID) + .DontScramble(x => x.Metadata.ContentType) .DontScramble(x => x.Metadata.FullID); scrambler.Scramble(a1); scrambler.Scramble(a2); scrambler.Scramble(a3); + db.StoreAsset(a1); db.StoreAsset(a2); db.StoreAsset(a3); -- cgit v1.1 From 70de6956ff6a3d833149156b6293122ef734b73d Mon Sep 17 00:00:00 2001 From: Diva Canto Date: Sun, 21 Feb 2010 18:56:44 -0800 Subject: Small bug fixes for making tests work. --- OpenSim/Data/Null/NullPresenceData.cs | 20 +++++++++------ .../Grid/Tests/GridConnectorsTests.cs | 6 ++--- .../Presence/Tests/PresenceConnectorsTests.cs | 2 +- OpenSim/Services/GridService/GridService.cs | 30 ++++++++++++---------- OpenSim/Services/GridService/HypergridLinker.cs | 26 ++++++++++--------- 5 files changed, 46 insertions(+), 38 deletions(-) diff --git a/OpenSim/Data/Null/NullPresenceData.cs b/OpenSim/Data/Null/NullPresenceData.cs index 40700cf..5f78691 100644 --- a/OpenSim/Data/Null/NullPresenceData.cs +++ b/OpenSim/Data/Null/NullPresenceData.cs @@ -43,16 +43,18 @@ namespace OpenSim.Data.Null public NullPresenceData(string connectionString, string realm) { if (Instance == null) + { Instance = this; - //Console.WriteLine("[XXX] NullRegionData constructor"); - // Let's stick in a test presence - PresenceData p = new PresenceData(); - p.SessionID = UUID.Zero; - p.UserID = UUID.Zero.ToString(); - p.Data = new Dictionary(); - p.Data["Online"] = "true"; - m_presenceData.Add(UUID.Zero, p); + //Console.WriteLine("[XXX] NullRegionData constructor"); + // Let's stick in a test presence + PresenceData p = new PresenceData(); + p.SessionID = UUID.Zero; + p.UserID = UUID.Zero.ToString(); + p.Data = new Dictionary(); + p.Data["Online"] = true.ToString(); + m_presenceData.Add(UUID.Zero, p); + } } public bool Store(PresenceData data) @@ -70,7 +72,9 @@ namespace OpenSim.Data.Null return Instance.Get(sessionID); if (m_presenceData.ContainsKey(sessionID)) + { return m_presenceData[sessionID]; + } return null; } diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/Tests/GridConnectorsTests.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/Tests/GridConnectorsTests.cs index 2ca90f8..95d8737 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/Tests/GridConnectorsTests.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Grid/Tests/GridConnectorsTests.cs @@ -56,7 +56,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid.Tests config.AddConfig("GridService"); config.Configs["Modules"].Set("GridServices", "LocalGridServicesConnector"); config.Configs["GridService"].Set("LocalServiceModule", "OpenSim.Services.GridService.dll:GridService"); - config.Configs["GridService"].Set("StorageProvider", "OpenSim.Data.Null.dll:NullRegionData"); + config.Configs["GridService"].Set("StorageProvider", "OpenSim.Data.Null.dll"); m_LocalConnector = new LocalGridServicesConnector(config); } @@ -92,7 +92,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid.Tests r2.HttpPort = 9002; r2.InternalEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("0.0.0.0"), 0); s = new Scene(new RegionInfo()); - s.RegionInfo.RegionID = r1.RegionID; + s.RegionInfo.RegionID = r2.RegionID; m_LocalConnector.AddRegion(s); GridRegion r3 = new GridRegion(); @@ -104,7 +104,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid.Tests r3.HttpPort = 9003; r3.InternalEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("0.0.0.0"), 0); s = new Scene(new RegionInfo()); - s.RegionInfo.RegionID = r1.RegionID; + s.RegionInfo.RegionID = r3.RegionID; m_LocalConnector.AddRegion(s); m_LocalConnector.RegisterRegion(UUID.Zero, r1); diff --git a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/Tests/PresenceConnectorsTests.cs b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/Tests/PresenceConnectorsTests.cs index 9ba1bdc..ca42461 100644 --- a/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/Tests/PresenceConnectorsTests.cs +++ b/OpenSim/Region/CoreModules/ServiceConnectorsOut/Presence/Tests/PresenceConnectorsTests.cs @@ -56,7 +56,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Presence.Tests config.AddConfig("PresenceService"); config.Configs["Modules"].Set("PresenceServices", "LocalPresenceServicesConnector"); config.Configs["PresenceService"].Set("LocalServiceModule", "OpenSim.Services.PresenceService.dll:PresenceService"); - config.Configs["PresenceService"].Set("StorageProvider", "OpenSim.Data.Null.dll:NullPresenceData"); + config.Configs["PresenceService"].Set("StorageProvider", "OpenSim.Data.Null.dll"); m_LocalConnector = new LocalPresenceServicesConnector(config); } diff --git a/OpenSim/Services/GridService/GridService.cs b/OpenSim/Services/GridService/GridService.cs index 4dee7a4..1368e46 100644 --- a/OpenSim/Services/GridService/GridService.cs +++ b/OpenSim/Services/GridService/GridService.cs @@ -82,20 +82,22 @@ namespace OpenSim.Services.GridService { m_RootInstance = this; - MainConsole.Instance.Commands.AddCommand("grid", true, - "show region", - "show region ", - "Show details on a region", - String.Empty, - HandleShowRegion); - - MainConsole.Instance.Commands.AddCommand("grid", true, - "set region flags", - "set region flags ", - "Set database flags for region", - String.Empty, - HandleSetFlags); - + if (MainConsole.Instance != null) + { + MainConsole.Instance.Commands.AddCommand("grid", true, + "show region", + "show region ", + "Show details on a region", + String.Empty, + HandleShowRegion); + + MainConsole.Instance.Commands.AddCommand("grid", true, + "set region flags", + "set region flags ", + "Set database flags for region", + String.Empty, + HandleSetFlags); + } m_HypergridLinker = new HypergridLinker(m_config, this, m_Database); } } diff --git a/OpenSim/Services/GridService/HypergridLinker.cs b/OpenSim/Services/GridService/HypergridLinker.cs index 18d0586..de5df9d 100644 --- a/OpenSim/Services/GridService/HypergridLinker.cs +++ b/OpenSim/Services/GridService/HypergridLinker.cs @@ -113,18 +113,20 @@ namespace OpenSim.Services.GridService m_log.DebugFormat("[HYPERGRID LINKER]: Loaded all services..."); } - - - MainConsole.Instance.Commands.AddCommand("hypergrid", false, "link-region", - "link-region :[:] ", - "Link a hypergrid region", RunCommand); - MainConsole.Instance.Commands.AddCommand("hypergrid", false, "unlink-region", - "unlink-region or : ", - "Unlink a hypergrid region", RunCommand); - MainConsole.Instance.Commands.AddCommand("hypergrid", false, "link-mapping", "link-mapping [ ] ", - "Set local coordinate to map HG regions to", RunCommand); - MainConsole.Instance.Commands.AddCommand("hypergrid", false, "show hyperlinks", "show hyperlinks ", - "List the HG regions", HandleShow); + + if (MainConsole.Instance != null) + { + MainConsole.Instance.Commands.AddCommand("hypergrid", false, "link-region", + "link-region :[:] ", + "Link a hypergrid region", RunCommand); + MainConsole.Instance.Commands.AddCommand("hypergrid", false, "unlink-region", + "unlink-region or : ", + "Unlink a hypergrid region", RunCommand); + MainConsole.Instance.Commands.AddCommand("hypergrid", false, "link-mapping", "link-mapping [ ] ", + "Set local coordinate to map HG regions to", RunCommand); + MainConsole.Instance.Commands.AddCommand("hypergrid", false, "show hyperlinks", "show hyperlinks ", + "List the HG regions", HandleShow); + } } -- cgit v1.1 From 2dea162073dbc8622d47d95f5f0b1ca2c619a22a Mon Sep 17 00:00:00 2001 From: Jeff Ames Date: Mon, 22 Feb 2010 12:25:59 +0900 Subject: Formatting cleanup. --- .../Avatar/Inventory/Archiver/InventoryArchiverModule.cs | 8 ++++---- OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiverModule.cs b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiverModule.cs index ac3e199..a898992 100644 --- a/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiverModule.cs +++ b/OpenSim/Region/CoreModules/Avatar/Inventory/Archiver/InventoryArchiverModule.cs @@ -134,7 +134,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver try { new InventoryArchiveWriteRequest(id, this, m_aScene, userInfo, invPath, saveStream).Execute(); - } + } catch (EntryPointNotFoundException e) { m_log.ErrorFormat( @@ -172,7 +172,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver try { new InventoryArchiveWriteRequest(id, this, m_aScene, userInfo, invPath, savePath).Execute(); - } + } catch (EntryPointNotFoundException e) { m_log.ErrorFormat( @@ -212,7 +212,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver try { request = new InventoryArchiveReadRequest(m_aScene, userInfo, invPath, loadStream); - } + } catch (EntryPointNotFoundException e) { m_log.ErrorFormat( @@ -254,7 +254,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver try { request = new InventoryArchiveReadRequest(m_aScene, userInfo, invPath, loadPath); - } + } catch (EntryPointNotFoundException e) { m_log.ErrorFormat( diff --git a/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs b/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs index 6357192..c5a6171 100644 --- a/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs +++ b/OpenSim/Region/Framework/Scenes/SceneObjectGroup.cs @@ -2351,7 +2351,7 @@ namespace OpenSim.Region.Framework.Scenes /// /// /// - /// The object group of the newly delinked prim. + /// The object group of the newly delinked prim. public SceneObjectGroup DelinkFromGroup(SceneObjectPart linkPart, bool sendEvents) { // m_log.DebugFormat( -- cgit v1.1 From 2e7aa387f7a705079df4b534978c0f134591eea9 Mon Sep 17 00:00:00 2001 From: Diva Canto Date: Sun, 21 Feb 2010 19:11:48 -0800 Subject: One more test running. --- .../World/Archiver/Tests/ArchiverTests.cs | 2 +- .../UserAccountService/UserAccountService.cs | 17 ++++++++------ OpenSim/Tests/Common/Setup/SceneSetupHelpers.cs | 26 ++++++++++++++++++++++ 3 files changed, 37 insertions(+), 8 deletions(-) diff --git a/OpenSim/Region/CoreModules/World/Archiver/Tests/ArchiverTests.cs b/OpenSim/Region/CoreModules/World/Archiver/Tests/ArchiverTests.cs index d986274..18f77fd 100644 --- a/OpenSim/Region/CoreModules/World/Archiver/Tests/ArchiverTests.cs +++ b/OpenSim/Region/CoreModules/World/Archiver/Tests/ArchiverTests.cs @@ -63,7 +63,7 @@ namespace OpenSim.Region.CoreModules.World.Archiver.Tests SerialiserModule serialiserModule = new SerialiserModule(); TerrainModule terrainModule = new TerrainModule(); - m_scene = SceneSetupHelpers.SetupScene("scene1"); + m_scene = SceneSetupHelpers.SetupScene("useraccounts"); SceneSetupHelpers.SetupSceneModules(m_scene, m_archiverModule, serialiserModule, terrainModule); } diff --git a/OpenSim/Services/UserAccountService/UserAccountService.cs b/OpenSim/Services/UserAccountService/UserAccountService.cs index ffb9cca..e498bd5 100644 --- a/OpenSim/Services/UserAccountService/UserAccountService.cs +++ b/OpenSim/Services/UserAccountService/UserAccountService.cs @@ -77,13 +77,16 @@ namespace OpenSim.Services.UserAccountService if (invServiceDll != string.Empty) m_InventoryService = LoadPlugin(invServiceDll, new Object[] { config }); - MainConsole.Instance.Commands.AddCommand("UserService", false, - "create user", - "create user [ [ [ []]]]", - "Create a new user", HandleCreateUser); - MainConsole.Instance.Commands.AddCommand("UserService", false, "reset user password", - "reset user password [ [ []]]", - "Reset a user password", HandleResetUserPassword); + if (MainConsole.Instance != null) + { + MainConsole.Instance.Commands.AddCommand("UserService", false, + "create user", + "create user [ [ [ []]]]", + "Create a new user", HandleCreateUser); + MainConsole.Instance.Commands.AddCommand("UserService", false, "reset user password", + "reset user password [ [ []]]", + "Reset a user password", HandleResetUserPassword); + } } diff --git a/OpenSim/Tests/Common/Setup/SceneSetupHelpers.cs b/OpenSim/Tests/Common/Setup/SceneSetupHelpers.cs index e37e137..9e718f6 100644 --- a/OpenSim/Tests/Common/Setup/SceneSetupHelpers.cs +++ b/OpenSim/Tests/Common/Setup/SceneSetupHelpers.cs @@ -45,6 +45,7 @@ using OpenSim.Region.CoreModules.Avatar.Gods; using OpenSim.Region.CoreModules.ServiceConnectorsOut.Asset; using OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory; using OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid; +using OpenSim.Region.CoreModules.ServiceConnectorsOut.UserAccounts; using OpenSim.Services.Interfaces; using OpenSim.Tests.Common.Mock; @@ -60,6 +61,7 @@ namespace OpenSim.Tests.Common.Setup private static ISharedRegionModule m_assetService = null; private static ISharedRegionModule m_inventoryService = null; private static ISharedRegionModule m_gridService = null; + private static ISharedRegionModule m_userAccountService = null; /// /// Set up a test scene @@ -183,6 +185,8 @@ namespace OpenSim.Tests.Common.Setup StartInventoryService(testScene, false); if (realServices.Contains("grid")) StartGridService(testScene, true); + if (realServices.Contains("useraccounts")) + StartUserAccountService(testScene, true); } // If not, make sure the shared module gets references to this new scene @@ -269,6 +273,28 @@ namespace OpenSim.Tests.Common.Setup //testScene.AddRegionModule(m_gridService.Name, m_gridService); } + private static void StartUserAccountService(Scene testScene, bool real) + { + IConfigSource config = new IniConfigSource(); + config.AddConfig("Modules"); + config.AddConfig("UserAccountService"); + config.Configs["Modules"].Set("UserAccountServices", "LocalUserAccountServicesConnector"); + config.Configs["UserAccountService"].Set("StorageProvider", "OpenSim.Data.Null.dll"); + if (real) + config.Configs["UserAccountService"].Set("LocalServiceModule", "OpenSim.Services.UserAccountService.dll:UserAccountService"); + if (m_userAccountService == null) + { + ISharedRegionModule userAccountService = new LocalUserAccountServicesConnector(); + userAccountService.Initialise(config); + m_userAccountService = userAccountService; + } + //else + // config.Configs["GridService"].Set("LocalServiceModule", "OpenSim.Tests.Common.dll:TestGridService"); + m_userAccountService.AddRegion(testScene); + m_userAccountService.RegionLoaded(testScene); + //testScene.AddRegionModule(m_gridService.Name, m_gridService); + } + /// /// Setup modules for a scene using their default settings. -- cgit v1.1 From 0d85f4f8612ce8c839b8cf75668978e1860ddad3 Mon Sep 17 00:00:00 2001 From: Diva Canto Date: Mon, 22 Feb 2010 09:56:03 -0800 Subject: Deleted duplicate [GridService] section. --- bin/OpenSim.Server.ini.example | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/bin/OpenSim.Server.ini.example b/bin/OpenSim.Server.ini.example index 0535765..54101b0 100644 --- a/bin/OpenSim.Server.ini.example +++ b/bin/OpenSim.Server.ini.example @@ -122,17 +122,3 @@ ServiceConnectors = "8003/OpenSim.Server.Handlers.dll:AssetServiceConnector,8003 LibraryService = "OpenSim.Services.InventoryService.dll:LibraryService" WelcomeMessage = "Welcome, Avatar!" - -; * This is the new style grid service. -; * "Realm" is the table that is used for user lookup. -; * It defaults to "regions", which uses the legacy tables -; * -[GridService] -LocalServiceModule = "OpenSim.Services.GridService.dll:GridService" -StorageProvider = "OpenSim.Data.MySQL.dll:MySqlRegionData" -ConnectionString = "Data Source=localhost;Database=opensim;User ID=opensim;Password=grid;" -Realm = "regions" - -; If true, duplicate region names are allowed on the grid. If false, no duplicate names are allowed -; Default is false -; AllowDuplicateNames = "True" -- cgit v1.1