* Rex merge, Framework (some problems in one or two files).

afrisby-3
Adam Frisby 2008-02-25 17:54:58 +00:00
parent 8df0331405
commit 4853884c30
133 changed files with 31412 additions and 26213 deletions

View File

@ -13,7 +13,7 @@
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS AS IS AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY

View File

@ -62,7 +62,7 @@ namespace OpenSim.Framework
public bool child; public bool child;
public LLUUID InventoryFolder; public LLUUID InventoryFolder;
public LLUUID BaseFolder; public LLUUID BaseFolder;
public string CapsPath = ""; public string CapsPath = String.Empty;
public string ClientVersion = "not set"; //rex public string ClientVersion = "not set"; //rex
public string authenticationAddr; public string authenticationAddr;
public string asAddress = ""; public string asAddress = "";
@ -105,7 +105,7 @@ namespace OpenSim.Framework
public bool child; public bool child;
public Guid InventoryFolder; public Guid InventoryFolder;
public Guid BaseFolder; public Guid BaseFolder;
public string CapsPath = ""; public string CapsPath = String.Empty;
public string ClientVersion = "not set"; //rex public string ClientVersion = "not set"; //rex
} }
} }

View File

@ -234,7 +234,7 @@ namespace OpenSim.Framework
public LLUUID CreatorID; public LLUUID CreatorID;
public sbyte InvType; public sbyte InvType;
public sbyte Type; public sbyte Type;
public string Name = ""; public string Name = System.String.Empty;
public string Description; public string Description;
public InventoryItem() public InventoryItem()
@ -245,7 +245,7 @@ namespace OpenSim.Framework
public string ExportString() public string ExportString()
{ {
string typ = "notecard"; string typ = "notecard";
string result = ""; string result = System.String.Empty;
result += "\tinv_object\t0\n\t{\n"; result += "\tinv_object\t0\n\t{\n";
result += "\t\tobj_id\t%s\n"; result += "\t\tobj_id\t%s\n";
result += "\t\tparent_id\t" + ItemID.ToString() + "\n"; result += "\t\tparent_id\t" + ItemID.ToString() + "\n";

View File

@ -1,3 +1,31 @@
/*
* 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 OpenSim 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.Reflection; using System.Reflection;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
@ -10,7 +38,7 @@ using System.Runtime.InteropServices;
[assembly : AssemblyConfiguration("")] [assembly : AssemblyConfiguration("")]
[assembly : AssemblyCompany("")] [assembly : AssemblyCompany("")]
[assembly : AssemblyProduct("OpenSim.FrameWork")] [assembly : AssemblyProduct("OpenSim.FrameWork")]
[assembly : AssemblyCopyright("Copyright © 2007")] [assembly : AssemblyCopyright("Copyright © OpenSimulator.org Developers 2007-2008")]
[assembly : AssemblyTrademark("")] [assembly : AssemblyTrademark("")]
[assembly : AssemblyCulture("")] [assembly : AssemblyCulture("")]

View File

@ -37,8 +37,8 @@ namespace OpenSim.Framework
public LLUUID FullID; public LLUUID FullID;
public sbyte Type; public sbyte Type;
public sbyte InvType; public sbyte InvType;
public string Name = ""; public string Name = String.Empty;
public string Description = ""; public string Description = String.Empty;
public string MediaURL = "";//rex public string MediaURL = "";//rex
public bool Local = false; public bool Local = false;
public bool Temporary = false; public bool Temporary = false;

View File

@ -13,7 +13,7 @@
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS AS IS AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
@ -26,6 +26,9 @@
* *
*/ */
using System;
using OpenSim.Framework.Console;
namespace OpenSim.Framework namespace OpenSim.Framework
{ {
/// <summary> /// <summary>
@ -33,9 +36,9 @@ namespace OpenSim.Framework
/// </summary> /// </summary>
public class AssetConfig public class AssetConfig
{ {
public string DefaultStartupMsg = ""; public string DefaultStartupMsg = String.Empty;
public string DatabaseProvider = ""; public string DatabaseProvider = String.Empty;
public static uint DefaultHttpPort = 8003; public static uint DefaultHttpPort = 8003;
public uint HttpPort = DefaultHttpPort; public uint HttpPort = DefaultHttpPort;

View File

@ -44,6 +44,8 @@ namespace OpenSim.Framework.AssetLoader.Filesystem
{ {
public class AssetLoaderFileSystem : IAssetLoader public class AssetLoaderFileSystem : IAssetLoader
{ {
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
protected AssetBase CreateAsset(string assetIdStr, string name, string path, bool isImage) protected AssetBase CreateAsset(string assetIdStr, string name, string path, bool isImage)
{ {
AssetBase asset = new AssetBase( AssetBase asset = new AssetBase(
@ -53,13 +55,13 @@ namespace OpenSim.Framework.AssetLoader.Filesystem
if (!String.IsNullOrEmpty(path)) if (!String.IsNullOrEmpty(path))
{ {
MainLog.Instance.Verbose("ASSETS", "Loading: [{0}][{1}]", name, path); m_log.InfoFormat("[ASSETS]: Loading: [{0}][{1}]", name, path);
LoadAsset(asset, isImage, path); LoadAsset(asset, isImage, path);
} }
else else
{ {
MainLog.Instance.Verbose("ASSETS", "Instantiated: [{0}]", name); m_log.InfoFormat("[ASSETS]: Instantiated: [{0}]", name);
} }
return asset; return asset;
@ -99,21 +101,19 @@ namespace OpenSim.Framework.AssetLoader.Filesystem
for (int i = 0; i < source.Configs.Count; i++) for (int i = 0; i < source.Configs.Count; i++)
{ {
assetSetPath = source.Configs[i].GetString("file", ""); assetSetPath = source.Configs[i].GetString("file", String.Empty);
LoadXmlAssetSet(Path.Combine(Util.assetsDir(), assetSetPath), assets); LoadXmlAssetSet(Path.Combine(Util.assetsDir(), assetSetPath), assets);
} }
} }
catch (XmlException e) catch (XmlException e)
{ {
MainLog.Instance.Error("ASSETS", "Error loading {0} : {1}", assetSetPath, e); m_log.ErrorFormat("[ASSETS]: Error loading {0} : {1}", assetSetPath, e);
} }
} }
else else
{ {
MainLog.Instance.Error( m_log.Error("[ASSETS]: Asset set control file assets/AssetSets.xml does not exist! No assets loaded.");
"ASSETS",
"Asset set control file assets/AssetSets.xml does not exist! No assets loaded.");
} }
assets.ForEach(action); assets.ForEach(action);
@ -126,7 +126,7 @@ namespace OpenSim.Framework.AssetLoader.Filesystem
/// <param name="assets"></param> /// <param name="assets"></param>
protected void LoadXmlAssetSet(string assetSetPath, List<AssetBase> assets) protected void LoadXmlAssetSet(string assetSetPath, List<AssetBase> assets)
{ {
MainLog.Instance.Verbose("ASSETS", "Loading asset set {0}", assetSetPath); m_log.InfoFormat("[ASSETS]: Loading asset set {0}", assetSetPath);
if (File.Exists(assetSetPath)) if (File.Exists(assetSetPath))
{ {
@ -138,10 +138,10 @@ namespace OpenSim.Framework.AssetLoader.Filesystem
for (int i = 0; i < source.Configs.Count; i++) for (int i = 0; i < source.Configs.Count; i++)
{ {
string assetIdStr = source.Configs[i].GetString("assetID", LLUUID.Random().ToString()); string assetIdStr = source.Configs[i].GetString("assetID", LLUUID.Random().ToString());
string name = source.Configs[i].GetString("name", ""); string name = source.Configs[i].GetString("name", String.Empty);
sbyte type = (sbyte) source.Configs[i].GetInt("assetType", 0); sbyte type = (sbyte) source.Configs[i].GetInt("assetType", 0);
sbyte invType = (sbyte) source.Configs[i].GetInt("inventoryType", 0); sbyte invType = (sbyte) source.Configs[i].GetInt("inventoryType", 0);
string assetPath = Path.Combine(dir, source.Configs[i].GetString("fileName", "")); string assetPath = Path.Combine(dir, source.Configs[i].GetString("fileName", String.Empty));
AssetBase newAsset = CreateAsset(assetIdStr, name, assetPath, false); AssetBase newAsset = CreateAsset(assetIdStr, name, assetPath, false);
@ -152,12 +152,12 @@ namespace OpenSim.Framework.AssetLoader.Filesystem
} }
catch (XmlException e) catch (XmlException e)
{ {
MainLog.Instance.Error("ASSETS", "Error loading {0} : {1}", assetSetPath, e); m_log.ErrorFormat("[ASSETS]: Error loading {0} : {1}", assetSetPath, e);
} }
} }
else else
{ {
MainLog.Instance.Error("ASSETS", "Asset set file {0} does not exist!", assetSetPath); m_log.ErrorFormat("[ASSETS]: Asset set file {0} does not exist!", assetSetPath);
} }
} }
} }

View File

@ -1,3 +1,31 @@
/*
* 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 OpenSim 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 libsecondlife; using libsecondlife;
namespace OpenSim.Framework namespace OpenSim.Framework

View File

@ -64,5 +64,10 @@ namespace OpenSim.Framework
return m_queue.Contains(item); return m_queue.Contains(item);
} }
} }
public int Count()
{
return m_queue.Count;
}
} }
} }

View File

@ -46,5 +46,8 @@ namespace OpenSim.Framework
public Guid AgentID; public Guid AgentID;
public float godlevel; public float godlevel;
public byte[] throttles; public byte[] throttles;
public bool alwaysrun;
public Guid ActiveGroupID;
public uint GroupAccess;
} }
} }

View File

@ -13,7 +13,7 @@
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS AS IS AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
@ -26,6 +26,7 @@
* *
*/ */
using System;
using System.Collections.Generic; using System.Collections.Generic;
using libsecondlife; using libsecondlife;
using libsecondlife.Packets; using libsecondlife.Packets;
@ -36,11 +37,12 @@ namespace OpenSim.Framework
public class ClientManager public class ClientManager
{ {
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private Dictionary<uint, IClientAPI> m_clients; private Dictionary<uint, IClientAPI> m_clients;
public void ForEachClient(ForEachClientDelegate whatToDo) public void ForEachClient(ForEachClientDelegate whatToDo)
{ {
// Wasteful, I know // Wasteful, I know
IClientAPI[] LocalClients = new IClientAPI[0]; IClientAPI[] LocalClients = new IClientAPI[0];
lock (m_clients) lock (m_clients)
@ -57,7 +59,7 @@ namespace OpenSim.Framework
} }
catch (System.Exception e) catch (System.Exception e)
{ {
OpenSim.Framework.Console.MainLog.Instance.Warn("CLIENT", "Unable to do ForEachClient for one of the clients" + "\n Reason: " + e.ToString()); m_log.Warn("[CLIENT]: Unable to do ForEachClient for one of the clients" + "\n Reason: " + e.ToString());
} }
} }
} }
@ -67,21 +69,31 @@ namespace OpenSim.Framework
m_clients = new Dictionary<uint, IClientAPI>(); m_clients = new Dictionary<uint, IClientAPI>();
} }
private void Remove(uint id) public void Remove(uint id)
{ {
m_clients.Remove(id); //m_log.InfoFormat("[CLIENT]: Removing client with code {0}, current count {1}", id, m_clients.Count);
lock (m_clients)
{
m_clients.Remove(id);
}
m_log.InfoFormat("[CLIENT]: Removed client with code {0}, new client count {1}", id, m_clients.Count);
} }
public void Add(uint id, IClientAPI client) public void Add(uint id, IClientAPI client)
{ {
m_clients.Add(id, client); lock (m_clients)
{
m_clients.Add(id, client);
}
} }
public void InPacket(uint circuitCode, Packet packet) public void InPacket(uint circuitCode, Packet packet)
{ {
IClientAPI client; IClientAPI client;
bool tryGetRet = false;
if (m_clients.TryGetValue(circuitCode, out client)) lock (m_clients)
tryGetRet = m_clients.TryGetValue(circuitCode, out client);
if(tryGetRet)
{ {
client.InPacket(packet); client.InPacket(packet);
} }
@ -90,8 +102,10 @@ namespace OpenSim.Framework
public void CloseAllAgents(uint circuitCode) public void CloseAllAgents(uint circuitCode)
{ {
IClientAPI client; IClientAPI client;
bool tryGetRet = false;
if (m_clients.TryGetValue(circuitCode, out client)) lock (m_clients)
tryGetRet = m_clients.TryGetValue(circuitCode, out client);
if (tryGetRet)
{ {
CloseAllCircuits(client.AgentId); CloseAllCircuits(client.AgentId);
} }
@ -107,8 +121,10 @@ namespace OpenSim.Framework
IClientAPI client; IClientAPI client;
try try
{ {
bool tryGetRet = false;
if (m_clients.TryGetValue(circuits[i], out client)) lock (m_clients)
tryGetRet = m_clients.TryGetValue(circuits[i], out client);
if(tryGetRet)
{ {
Remove(client.CircuitCode); Remove(client.CircuitCode);
client.Close(false); client.Close(false);
@ -116,11 +132,9 @@ namespace OpenSim.Framework
} }
catch (System.Exception e) catch (System.Exception e)
{ {
OpenSim.Framework.Console.MainLog.Instance.Error("CLIENT", string.Format("Unable to shutdown circuit for: {0}\n Reason: {1}", agentId, e)); m_log.Error(string.Format("[CLIENT]: Unable to shutdown circuit for: {0}\n Reason: {1}", agentId, e));
} }
} }
} }
private uint[] GetAllCircuits(LLUUID agentId) private uint[] GetAllCircuits(LLUUID agentId)
@ -134,7 +148,6 @@ namespace OpenSim.Framework
m_clients.Values.CopyTo(LocalClients, 0); m_clients.Values.CopyTo(LocalClients, 0);
} }
for (int i = 0; i < LocalClients.Length; i++ ) for (int i = 0; i < LocalClients.Length; i++ )
{ {
if (LocalClients[i].AgentId == agentId) if (LocalClients[i].AgentId == agentId)
@ -160,13 +173,13 @@ namespace OpenSim.Framework
m_clients.Values.CopyTo(LocalClients, 0); m_clients.Values.CopyTo(LocalClients, 0);
} }
for (int i = 0; i < LocalClients.Length; i++) for (int i = 0; i < LocalClients.Length; i++)
{ {
if (LocalClients[i].AgentId != sender.AgentId) if (LocalClients[i].AgentId != sender.AgentId)
{ {
packet.AgentData.AgentID = LocalClients[i].AgentId; packet.AgentData.AgentID = LocalClients[i].AgentId;
packet.AgentData.SessionID = LocalClients[i].SessionId; packet.AgentData.SessionID = LocalClients[i].SessionId;
packet.Header.Reliable = false;
LocalClients[i].OutPacket(packet, ThrottleOutPacketType.Task); LocalClients[i].OutPacket(packet, ThrottleOutPacketType.Task);
} }
@ -175,7 +188,10 @@ namespace OpenSim.Framework
public bool TryGetClient(uint circuitId, out IClientAPI user) public bool TryGetClient(uint circuitId, out IClientAPI user)
{ {
return m_clients.TryGetValue(circuitId, out user); lock (m_clients)
{
return m_clients.TryGetValue(circuitId, out user);
}
} }
} }
} }

View File

@ -13,7 +13,7 @@
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS AS IS AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
@ -32,7 +32,7 @@ namespace OpenSim.Framework.Communications
{ {
public class CAPSService public class CAPSService
{ {
private BaseHttpServer m_server; private readonly BaseHttpServer m_server;
public CAPSService(BaseHttpServer httpServer) public CAPSService(BaseHttpServer httpServer)
{ {
@ -48,7 +48,7 @@ namespace OpenSim.Framework.Communications
public string CapsRequest(string request, string path, string param) public string CapsRequest(string request, string path, string param)
{ {
System.Console.WriteLine("new caps request " + request + " from path " + path); System.Console.WriteLine("new caps request " + request + " from path " + path);
return ""; return System.String.Empty;
} }
} }
} }

View File

@ -25,6 +25,8 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
//moved to a module, left here until the module is found to have no problems
/*
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
@ -35,18 +37,24 @@ using OpenSim.Region.Capabilities;
namespace OpenSim.Framework.Communications.Cache namespace OpenSim.Framework.Communications.Cache
{ {
/// <summary>
/// Manage asset transactions for a single agent.
/// </summary>
public class AgentAssetTransactions public class AgentAssetTransactions
{ {
private static readonly log4net.ILog m_log
= log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Fields // Fields
public List<AssetCapsUploader> CapsUploaders = new List<AssetCapsUploader>(); public List<AssetCapsUploader> CapsUploaders = new List<AssetCapsUploader>();
public List<NoteCardCapsUpdate> NotecardUpdaters = new List<NoteCardCapsUpdate>(); public List<NoteCardCapsUpdate> NotecardUpdaters = new List<NoteCardCapsUpdate>();
public LLUUID UserID; public LLUUID UserID;
public Dictionary<LLUUID, AssetXferUploader> XferUploaders = new Dictionary<LLUUID, AssetXferUploader>(); public Dictionary<LLUUID, AssetXferUploader> XferUploaders = new Dictionary<LLUUID, AssetXferUploader>();
public AssetTransactionManager Manager; public AgentAssetTransactionsManager Manager;
private bool m_dumpAssetsToFile; private bool m_dumpAssetsToFile;
// Methods // Methods
public AgentAssetTransactions(LLUUID agentID, AssetTransactionManager manager, bool dumpAssetsToFile) public AgentAssetTransactions(LLUUID agentID, AgentAssetTransactionsManager manager, bool dumpAssetsToFile)
{ {
UserID = agentID; UserID = agentID;
Manager = manager; Manager = manager;
@ -73,7 +81,11 @@ namespace OpenSim.Framework.Communications.Cache
{ {
AssetXferUploader uploader = new AssetXferUploader(this, m_dumpAssetsToFile); AssetXferUploader uploader = new AssetXferUploader(this, m_dumpAssetsToFile);
XferUploaders.Add(transactionID, uploader); lock (XferUploaders)
{
XferUploaders.Add(transactionID, uploader);
}
return uploader; return uploader;
} }
return null; return null;
@ -81,12 +93,35 @@ namespace OpenSim.Framework.Communications.Cache
public void HandleXfer(ulong xferID, uint packetID, byte[] data) public void HandleXfer(ulong xferID, uint packetID, byte[] data)
{ {
foreach (AssetXferUploader uploader in XferUploaders.Values) AssetXferUploader uploaderFound = null;
lock (XferUploaders)
{ {
if (uploader.XferID == xferID) foreach (AssetXferUploader uploader in XferUploaders.Values)
{ {
uploader.HandleXferPacket(xferID, packetID, data); if (uploader.XferID == xferID)
break; {
if (uploader.HandleXferPacket(xferID, packetID, data))
{
uploaderFound = uploader;
}
break;
}
}
// Remove the uploader once the uploader is complete
//[don't think we can be sure a upload has finished from here, uploads are multi part things]
// [or maybe we can if we do more checking like data lenght checks]
if (uploaderFound != null)
{
// m_log.InfoFormat(
// "[ASSET TRANSACTIONS] Removing asset xfer uploader with transfer id {0}, transaction {1}",
// xferID, uploaderFound.TransactionID);
// XferUploaders.Remove(uploaderFound.TransactionID);
//m_log.InfoFormat("[ASSET TRANSACTIONS] Current uploaders: {0}", XferUploaders.Count);
} }
} }
} }
@ -103,12 +138,35 @@ namespace OpenSim.Framework.Communications.Cache
} }
} }
public void RequestUpdateInventoryItem(IClientAPI remoteClient, LLUUID transactionID,
InventoryItemBase item)
{
if (XferUploaders.ContainsKey(transactionID))
{
XferUploaders[transactionID].RequestUpdateInventoryItem(remoteClient, transactionID, item);
}
}
/// <summary>
/// Get an uploaded asset. If the data is successfully retrieved, the transaction will be removed.
/// </summary>
/// <param name="transactionID"></param>
/// <returns>The asset if the upload has completed, null if it has not.</returns>
public AssetBase GetTransactionAsset(LLUUID transactionID) public AssetBase GetTransactionAsset(LLUUID transactionID)
{ {
if (XferUploaders.ContainsKey(transactionID)) if (XferUploaders.ContainsKey(transactionID))
{ {
return XferUploaders[transactionID].GetAssetData(); AssetXferUploader uploader = XferUploaders[transactionID];
AssetBase asset = uploader.GetAssetData();
lock (XferUploaders)
{
XferUploaders.Remove(transactionID);
}
return asset;
} }
return null; return null;
} }
@ -123,8 +181,8 @@ namespace OpenSim.Framework.Communications.Cache
public LLUUID TransactionID = LLUUID.Zero; public LLUUID TransactionID = LLUUID.Zero;
public bool UploadComplete; public bool UploadComplete;
public ulong XferID; public ulong XferID;
private string m_name = ""; private string m_name = String.Empty;
private string m_description = ""; private string m_description = String.Empty;
private sbyte type = 0; private sbyte type = 0;
private sbyte invType = 0; private sbyte invType = 0;
private uint nextPerm = 0; private uint nextPerm = 0;
@ -140,8 +198,14 @@ namespace OpenSim.Framework.Communications.Cache
m_dumpAssetToFile = dumpAssetToFile; m_dumpAssetToFile = dumpAssetToFile;
} }
// Methods /// <summary>
public void HandleXferPacket(ulong xferID, uint packetID, byte[] data) /// Process transfer data received from the client.
/// </summary>
/// <param name="xferID"></param>
/// <param name="packetID"></param>
/// <param name="data"></param>
/// <returns>True if the transfer is complete, false otherwise or if the xferID was not valid</returns>
public bool HandleXferPacket(ulong xferID, uint packetID, byte[] data)
{ {
if (XferID == xferID) if (XferID == xferID)
{ {
@ -165,11 +229,21 @@ namespace OpenSim.Framework.Communications.Cache
if ((packetID & 0x80000000) != 0) if ((packetID & 0x80000000) != 0)
{ {
SendCompleteMessage(); SendCompleteMessage();
return true;
} }
} }
return false;
} }
public void Initialise(IClientAPI remoteClient, LLUUID assetID, LLUUID transaction, sbyte type, byte[] data, /// <summary>
/// Initialise asset transfer from the client
/// </summary>
/// <param name="xferID"></param>
/// <param name="packetID"></param>
/// <param name="data"></param>
/// <returns>True if the transfer is complete, false otherwise</returns>
public bool Initialise(IClientAPI remoteClient, LLUUID assetID, LLUUID transaction, sbyte type, byte[] data,
bool storeLocal, bool tempFile) bool storeLocal, bool tempFile)
{ {
ourClient = remoteClient; ourClient = remoteClient;
@ -188,14 +262,17 @@ namespace OpenSim.Framework.Communications.Cache
if (Asset.Data.Length > 2) if (Asset.Data.Length > 2)
{ {
SendCompleteMessage(); SendCompleteMessage();
return true;
} }
else else
{ {
ReqestStartXfer(); RequestStartXfer();
} }
return false;
} }
protected void ReqestStartXfer() protected void RequestStartXfer()
{ {
UploadComplete = false; UploadComplete = false;
XferID = Util.GetNextXferID(); XferID = Util.GetNextXferID();
@ -237,6 +314,7 @@ namespace OpenSim.Framework.Communications.Cache
SaveAssetToFile(filename, Asset.Data); SaveAssetToFile(filename, Asset.Data);
} }
} }
///Left this in and commented in case there are unforseen issues ///Left this in and commented in case there are unforseen issues
//private void SaveAssetToFile(string filename, byte[] data) //private void SaveAssetToFile(string filename, byte[] data)
//{ //{
@ -284,6 +362,44 @@ namespace OpenSim.Framework.Communications.Cache
} }
} }
public void RequestUpdateInventoryItem(IClientAPI remoteClient, LLUUID transactionID,
InventoryItemBase item)
{
if (TransactionID == transactionID)
{
CachedUserInfo userInfo =
m_userTransactions.Manager.CommsManager.UserProfileCacheService.GetUserDetails(
remoteClient.AgentId);
if (userInfo != null)
{
LLUUID assetID = LLUUID.Combine(transactionID, remoteClient.SecureSessionId);
AssetBase asset
= m_userTransactions.Manager.CommsManager.AssetCache.GetAsset(
assetID, (item.assetType == (int) AssetType.Texture ? true : false));
if (asset == null)
{
asset = m_userTransactions.GetTransactionAsset(transactionID);
}
if (asset != null && asset.FullID == assetID)
{
asset.Name = item.inventoryName;
asset.Description = item.inventoryDescription;
asset.InvType = (sbyte) item.invType;
asset.Type = (sbyte) item.assetType;
item.assetID = asset.FullID;
m_userTransactions.Manager.CommsManager.AssetCache.AddAsset(Asset);
}
userInfo.UpdateItem(remoteClient.AgentId, item);
}
}
}
private void DoCreateItem() private void DoCreateItem()
{ {
//really need to fix this call, if lbsa71 saw this he would die. //really need to fix this call, if lbsa71 saw this he would die.
@ -302,6 +418,7 @@ namespace OpenSim.Framework.Communications.Cache
item.assetType = type; item.assetType = type;
item.invType = invType; item.invType = invType;
item.parentFolderID = InventFolder; item.parentFolderID = InventFolder;
item.inventoryBasePermissions = 2147483647;
item.inventoryCurrentPermissions = 2147483647; item.inventoryCurrentPermissions = 2147483647;
item.inventoryNextPermissions = nextPerm; item.inventoryNextPermissions = nextPerm;
@ -310,10 +427,6 @@ namespace OpenSim.Framework.Communications.Cache
} }
} }
public void UpdateInventoryItem(LLUUID itemID)
{
}
public AssetBase GetAssetData() public AssetBase GetAssetData()
{ {
if (m_finished) if (m_finished)
@ -331,12 +444,12 @@ namespace OpenSim.Framework.Communications.Cache
// Fields // Fields
private BaseHttpServer httpListener; private BaseHttpServer httpListener;
private LLUUID inventoryItemID; private LLUUID inventoryItemID;
private string m_assetDescription = ""; private string m_assetDescription = String.Empty;
private string m_assetName = ""; private string m_assetName = String.Empty;
private LLUUID m_folderID; private LLUUID m_folderID;
private LLUUID newAssetID; private LLUUID newAssetID;
private bool m_dumpImageToFile; private bool m_dumpImageToFile;
private string uploaderPath = ""; private string uploaderPath = String.Empty;
// Events // Events
public event UpLoadedAsset OnUpLoad; public event UpLoadedAsset OnUpLoad;
@ -367,7 +480,7 @@ namespace OpenSim.Framework.Communications.Cache
public string uploaderCaps(byte[] data, string path, string param) public string uploaderCaps(byte[] data, string path, string param)
{ {
LLUUID inventoryItemID = this.inventoryItemID; LLUUID inventoryItemID = this.inventoryItemID;
string text = ""; string text = String.Empty;
LLSDAssetUploadComplete complete = new LLSDAssetUploadComplete(); LLSDAssetUploadComplete complete = new LLSDAssetUploadComplete();
complete.new_asset = newAssetID.ToString(); complete.new_asset = newAssetID.ToString();
complete.new_inventory_item = inventoryItemID; complete.new_inventory_item = inventoryItemID;
@ -380,7 +493,7 @@ namespace OpenSim.Framework.Communications.Cache
} }
if (OnUpLoad != null) if (OnUpLoad != null)
{ {
OnUpLoad(m_assetName, "description", newAssetID, inventoryItemID, LLUUID.Zero, data, "", ""); OnUpLoad(m_assetName, "description", newAssetID, inventoryItemID, LLUUID.Zero, data, String.Empty, String.Empty);
} }
return text; return text;
} }
@ -391,10 +504,10 @@ namespace OpenSim.Framework.Communications.Cache
// Fields // Fields
private BaseHttpServer httpListener; private BaseHttpServer httpListener;
private LLUUID inventoryItemID; private LLUUID inventoryItemID;
private string m_assetName = ""; private string m_assetName = String.Empty;
private LLUUID newAssetID; private LLUUID newAssetID;
private bool SaveImages = false; private bool SaveImages = false;
private string uploaderPath = ""; private string uploaderPath = String.Empty;
// Events // Events
public event UpLoadedAsset OnUpLoad; public event UpLoadedAsset OnUpLoad;
@ -420,7 +533,7 @@ namespace OpenSim.Framework.Communications.Cache
public string uploaderCaps(byte[] data, string path, string param) public string uploaderCaps(byte[] data, string path, string param)
{ {
LLUUID inventoryItemID = this.inventoryItemID; LLUUID inventoryItemID = this.inventoryItemID;
string text = ""; string text = String.Empty;
LLSDAssetUploadComplete complete = new LLSDAssetUploadComplete(); LLSDAssetUploadComplete complete = new LLSDAssetUploadComplete();
complete.new_asset = newAssetID.ToString(); complete.new_asset = newAssetID.ToString();
complete.new_inventory_item = inventoryItemID; complete.new_inventory_item = inventoryItemID;
@ -433,7 +546,7 @@ namespace OpenSim.Framework.Communications.Cache
} }
if (OnUpLoad != null) if (OnUpLoad != null)
{ {
OnUpLoad(m_assetName, "description", newAssetID, inventoryItemID, LLUUID.Zero, data, "", ""); OnUpLoad(m_assetName, "description", newAssetID, inventoryItemID, LLUUID.Zero, data, String.Empty, String.Empty);
} }
return text; return text;
} }
@ -442,3 +555,4 @@ namespace OpenSim.Framework.Communications.Cache
#endregion #endregion
} }
} }
*/

View File

@ -0,0 +1,206 @@
/*
* 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 OpenSim 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.
*
*/
//moved to a module, left here until the module is found to have no problems
/*
using System;
using System.Collections.Generic;
using libsecondlife;
namespace OpenSim.Framework.Communications.Cache
{
/// <summary>
/// Provider handlers for processing asset transactions originating from the agent. This encompasses
/// clothing creation and update as well as asset uploads.
/// </summary>
public class AgentAssetTransactionsManager
{
private static readonly log4net.ILog m_log
= log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Fields
public CommunicationsManager CommsManager;
/// <summary>
/// Each agent has its own singleton collection of transactions
/// </summary>
private Dictionary<LLUUID, AgentAssetTransactions> AgentTransactions =
new Dictionary<LLUUID, AgentAssetTransactions>();
/// <summary>
/// Should we dump uploaded assets to the filesystem?
/// </summary>
private bool m_dumpAssetsToFile;
public AgentAssetTransactionsManager(CommunicationsManager commsManager, bool dumpAssetsToFile)
{
CommsManager = commsManager;
m_dumpAssetsToFile = dumpAssetsToFile;
}
/// <summary>
/// Get the collection of asset transactions for the given user. If one does not already exist, it
/// is created.
/// </summary>
/// <param name="userID"></param>
/// <returns></returns>
private AgentAssetTransactions GetUserTransactions(LLUUID userID)
{
lock (AgentTransactions)
{
if (!AgentTransactions.ContainsKey(userID))
{
AgentAssetTransactions transactions
= new AgentAssetTransactions(userID, this, m_dumpAssetsToFile);
AgentTransactions.Add(userID, transactions);
}
return AgentTransactions[userID];
}
}
/// <summary>
/// Remove the given agent asset transactions. This should be called when a client is departing
/// from a scene (and hence won't be making any more transactions here).
/// </summary>
/// <param name="userID"></param>
public void RemoveAgentAssetTransactions(LLUUID userID)
{
m_log.DebugFormat("Removing agent asset transactions structure for agent {0}", userID);
lock (AgentTransactions)
{
AgentTransactions.Remove(userID);
}
}
/// <summary>
/// Create an inventory item from data that has been received through a transaction.
///
/// This is called when new clothing or body parts are created. It may also be called in other
/// situations.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="transactionID"></param>
/// <param name="folderID"></param>
/// <param name="callbackID"></param>
/// <param name="description"></param>
/// <param name="name"></param>
/// <param name="invType"></param>
/// <param name="type"></param>
/// <param name="wearableType"></param>
/// <param name="nextOwnerMask"></param>
public void HandleItemCreationFromTransaction(IClientAPI remoteClient, LLUUID transactionID, LLUUID folderID,
uint callbackID, string description, string name, sbyte invType,
sbyte type, byte wearableType, uint nextOwnerMask)
{
m_log.DebugFormat(
"[TRANSACTIONS MANAGER] Called HandleItemCreationFromTransaction with item {0}", name);
AgentAssetTransactions transactions = GetUserTransactions(remoteClient.AgentId);
transactions.RequestCreateInventoryItem(
remoteClient, transactionID, folderID, callbackID, description,
name, invType, type, wearableType, nextOwnerMask);
}
/// <summary>
/// Update an inventory item with data that has been received through a transaction.
///
/// This is called when clothing or body parts are updated (for instance, with new textures or
/// colours). It may also be called in other situations.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="transactionID"></param>
/// <param name="item"></param>
public void HandleItemUpdateFromTransaction(IClientAPI remoteClient, LLUUID transactionID,
InventoryItemBase item)
{
m_log.DebugFormat(
"[TRANSACTIONS MANAGER] Called HandleItemUpdateFromTransaction with item {0}",
item.inventoryName);
AgentAssetTransactions transactions
= CommsManager.TransactionsManager.GetUserTransactions(remoteClient.AgentId);
transactions.RequestUpdateInventoryItem(remoteClient, transactionID, item);
}
/// <summary>
/// Request that a client (agent) begin an asset transfer.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="assetID"></param>
/// <param name="transaction"></param>
/// <param name="type"></param>
/// <param name="data"></param></param>
/// <param name="tempFile"></param>
public void HandleUDPUploadRequest(IClientAPI remoteClient, LLUUID assetID, LLUUID transaction, sbyte type,
byte[] data, bool storeLocal, bool tempFile)
{
// Console.WriteLine("asset upload of " + assetID);
AgentAssetTransactions transactions = GetUserTransactions(remoteClient.AgentId);
AgentAssetTransactions.AssetXferUploader uploader = transactions.RequestXferUploader(transaction);
if (uploader != null)
{
// Upload has already compelted uploading...
if (uploader.Initialise(remoteClient, assetID, transaction, type, data, storeLocal, tempFile))
{
//[commenting out as this removal breaks uploads]
/*lock (transactions.XferUploaders)
{
// XXX Weak ass way of doing this by directly manipulating this public dictionary, purely temporary
transactions.XferUploaders.Remove(uploader.TransactionID);
//m_log.InfoFormat("[ASSET TRANSACTIONS] Current uploaders: {0}", transactions.XferUploaders.Count);
}*/
/* }
}
}
/// <summary>
/// Handle asset transfer data packets received in response to the asset upload request in
/// HandleUDPUploadRequest()
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="xferID"></param>
/// <param name="packetID"></param>
/// <param name="data"></param>
public void HandleXfer(IClientAPI remoteClient, ulong xferID, uint packetID, byte[] data)
{
AgentAssetTransactions transactions = GetUserTransactions(remoteClient.AgentId);
transactions.HandleXfer(xferID, packetID, data);
}
}
}
*/

View File

@ -31,7 +31,9 @@ using System.Collections.Generic;
using System.Threading; using System.Threading;
using libsecondlife; using libsecondlife;
using libsecondlife.Packets; using libsecondlife.Packets;
using OpenSim.Framework.Console; using OpenSim.Framework.Console;
using OpenSim.Framework.Statistics;
namespace OpenSim.Framework.Communications.Cache namespace OpenSim.Framework.Communications.Cache
{ {
@ -39,47 +41,142 @@ namespace OpenSim.Framework.Communications.Cache
/// <summary> /// <summary>
/// Manages local cache of assets and their sending to viewers. /// Manages local cache of assets and their sending to viewers.
///
/// This class actually encapsulates two largely separate mechanisms. One mechanism fetches assets either
/// synchronously or async and passes the data back to the requester. The second mechanism fetches assets and
/// sends packetised data directly back to the client. The only point where they meet is AssetReceived() and
/// AssetNotFound(), which means they do share the same asset and texture caches.
///
/// TODO Assets in this cache are effectively immortal (they are never disposed off through old age).
/// This is not a huge problem at the moment since other memory use usually dwarfs that used by assets
/// but it's something to bear in mind.
/// </summary> /// </summary>
public class AssetCache : IAssetReceiver public class AssetCache : IAssetReceiver
{ {
public Dictionary<LLUUID, AssetInfo> Assets; private static readonly log4net.ILog m_log
public Dictionary<LLUUID, TextureImage> Textures; = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public List<AssetRequest> AssetRequests = new List<AssetRequest>(); //assets ready to be sent to viewers /// <summary>
public List<AssetRequest> TextureRequests = new List<AssetRequest>(); //textures ready to be sent /// The cache of assets. This does not include textures.
/// </summary>
private Dictionary<LLUUID, AssetInfo> Assets;
public Dictionary<LLUUID, AssetRequest> RequestedAssets = new Dictionary<LLUUID, AssetRequest>(); /// <summary>
//Assets requested from the asset server /// The cache of textures.
/// </summary>
private Dictionary<LLUUID, TextureImage> Textures;
public Dictionary<LLUUID, AssetRequest> RequestedTextures = new Dictionary<LLUUID, AssetRequest>(); /// <summary>
//Textures requested from the asset server /// Assets requests which are waiting for asset server data. This includes texture requests
/// </summary>
private Dictionary<LLUUID, AssetRequest> RequestedAssets;
public Dictionary<LLUUID, AssetRequestsList> RequestLists = new Dictionary<LLUUID, AssetRequestsList>(); /// <summary>
/// Asset requests with data which are ready to be sent back to requesters. This includes textures.
/// </summary>
private List<AssetRequest> AssetRequests;
/// <summary>
/// Until the asset request is fulfilled, each asset request is associated with a list of requesters
/// </summary>
private Dictionary<LLUUID, AssetRequestsList> RequestLists;
private readonly IAssetServer m_assetServer; private readonly IAssetServer m_assetServer;
private readonly Thread m_assetCacheThread; private readonly Thread m_assetCacheThread;
private readonly LogBase m_log;
/// <summary> /// <summary>
/// /// Report statistical data.
/// </summary> /// </summary>
public AssetCache(IAssetServer assetServer, LogBase log) public void ShowState()
{ {
log.Verbose("ASSETSTORAGE", "Creating Asset cache"); m_log.InfoFormat("Assets:{0} Textures:{1} AssetRequests:{2} RequestedAssets:{3} RequestLists:{4}",
m_assetServer = assetServer; Assets.Count,
m_assetServer.SetReceiver(this); Textures.Count,
Assets = new Dictionary<LLUUID, AssetInfo>(); AssetRequests.Count,
Textures = new Dictionary<LLUUID, TextureImage>(); RequestedAssets.Count,
m_assetCacheThread = new Thread(new ThreadStart(RunAssetManager)); RequestLists.Count);
m_assetCacheThread.IsBackground = true;
m_assetCacheThread.Start(); int temporaryImages = 0;
int temporaryAssets = 0;
long imageBytes = 0;
long assetBytes = 0;
foreach (TextureImage texture in Textures.Values)
{
if (texture.Temporary)
{
temporaryImages++;
}
imageBytes += texture.Data.GetLongLength(0);
}
foreach (AssetInfo asset in Assets.Values)
{
if (asset.Temporary)
{
temporaryAssets++;
}
assetBytes += asset.Data.GetLongLength(0);
}
m_log.InfoFormat("Temporary Images: {0} Temporary Assets: {1}",
temporaryImages,
temporaryAssets);
m_log.InfoFormat("Image data: {0}kb Asset data: {1}kb",
imageBytes / 1024,
assetBytes / 1024);
m_log = log;
} }
/// <summary> /// <summary>
/// /// Clear the asset cache.
/// </summary>
public void Clear()
{
m_log.Info("[ASSET CACHE]: Clearing Asset cache");
Initialize();
}
/// <summary>
/// Initialize the cache.
/// </summary>
private void Initialize()
{
Assets = new Dictionary<LLUUID, AssetInfo>();
Textures = new Dictionary<LLUUID, TextureImage>();
AssetRequests = new List<AssetRequest>();
RequestedAssets = new Dictionary<LLUUID, AssetRequest>();
RequestLists = new Dictionary<LLUUID, AssetRequestsList>();
}
/// <summary>
/// Constructor. Initialize will need to be called separately.
/// </summary>
/// <param name="assetServer"></param>
public AssetCache(IAssetServer assetServer)
{
m_log.Info("[ASSET CACHE]: Creating Asset cache");
Initialize();
m_assetServer = assetServer;
m_assetServer.SetReceiver(this);
m_assetCacheThread = new Thread(new ThreadStart(RunAssetManager));
m_assetCacheThread.Name = "AssetCacheThread";
m_assetCacheThread.IsBackground = true;
m_assetCacheThread.Start();
OpenSim.Framework.ThreadTracker.Add(m_assetCacheThread);
}
/// <summary>
/// Process the asset queue which holds data which is packeted up and sent
/// directly back to the client.
/// </summary> /// </summary>
public void RunAssetManager() public void RunAssetManager()
{ {
@ -92,7 +189,7 @@ namespace OpenSim.Framework.Communications.Cache
} }
catch (Exception e) catch (Exception e)
{ {
m_log.Error("ASSETCACHE", e.ToString()); m_log.Error("[ASSET CACHE]: " + e.ToString());
} }
} }
} }
@ -100,70 +197,94 @@ namespace OpenSim.Framework.Communications.Cache
/// <summary> /// <summary>
/// Only get an asset if we already have it in the cache. /// Only get an asset if we already have it in the cache.
/// </summary> /// </summary>
/// <param name="assetID"></param></param> /// <param name="assetId"></param></param>
/// <returns></returns> /// <returns></returns>
private AssetBase GetCachedAsset(LLUUID assetID) //private AssetBase GetCachedAsset(LLUUID assetId)
//{
// AssetBase asset = null;
// if (Textures.ContainsKey(assetId))
// {
// asset = Textures[assetId];
// }
// else if (Assets.ContainsKey(assetId))
// {
// asset = Assets[assetId];
// }
// return asset;
//}
private bool TryGetCachedAsset(LLUUID assetId, out AssetBase asset)
{ {
AssetBase asset = null; if (Textures.ContainsKey(assetId))
if (Textures.ContainsKey(assetID))
{ {
asset = Textures[assetID]; asset = Textures[assetId];
return true;
} }
else if (Assets.ContainsKey(assetID)) else if (Assets.ContainsKey(assetId))
{ {
asset = Assets[assetID]; asset = Assets[assetId];
return true;
} }
return asset;
asset = null;
return false;
} }
public void GetAsset(LLUUID assetID, AssetRequestCallback callback) /// <summary>
/// Asynchronously retrieve an asset.
/// </summary>
/// <param name="assetId"></param>
/// <param name="callback">
/// A callback invoked when the asset has either been found or not found.
/// If the asset was found this is called with the asset UUID and the asset data
/// If the asset was not found this is still called with the asset UUID but with a null asset data reference</param>
public void GetAsset(LLUUID assetId, AssetRequestCallback callback, bool isTexture)
{ {
AssetBase asset = null; AssetBase asset;
if (Textures.ContainsKey(assetID))
{
asset = Textures[assetID];
}
else if (Assets.ContainsKey(assetID))
{
asset = Assets[assetID];
}
if (asset != null) if (TryGetCachedAsset(assetId, out asset))
{ {
callback(assetID, asset); callback(assetId, asset);
} }
else else
{ {
NewAssetRequest req = new NewAssetRequest(assetID, callback); #if DEBUG
if (RequestLists.ContainsKey(assetID)) //m_log.DebugFormat("[ASSET CACHE]: Adding request for {0} {1}", isTexture ? "texture" : "asset", assetId);
#endif
NewAssetRequest req = new NewAssetRequest(assetId, callback);
// Make sure we always have a request list to which to add the asset
AssetRequestsList requestList;
lock (RequestLists)
{ {
lock (RequestLists) if (RequestLists.TryGetValue(assetId, out requestList))
{ {
RequestLists[assetID].Requests.Add(req); }
else
{
requestList = new AssetRequestsList(assetId);
RequestLists.Add(assetId, requestList);
} }
} }
else
{ requestList.Requests.Add(req);
AssetRequestsList reqList = new AssetRequestsList(assetID);
reqList.Requests.Add(req); m_assetServer.RequestAsset(assetId, isTexture);
lock (RequestLists)
{
RequestLists.Add(assetID, reqList);
}
}
m_assetServer.RequestAsset(assetID, false);
} }
} }
/// <summary> /// <summary>
/// Get an asset. If the asset isn't in the cache, a request will be made to the persistent store to /// Synchronously retreive an asset. If the asset isn't in the cache, a request will be made to the persistent store to
/// load it into the cache. /// load it into the cache.
/// ///
/// XXX We'll keep polling the cache until we get the asset or we exceed /// XXX We'll keep polling the cache until we get the asset or we exceed
/// the allowed number of polls. This isn't a very good way of doing things since a single thread /// the allowed number of polls. This isn't a very good way of doing things since a single thread
/// is processing inbound packets, so if the asset server is slow, we could block this for up to /// is processing inbound packets, so if the asset server is slow, we could block this for up to
/// the timeout period. What we might want to do is register asynchronous callbacks on asset /// the timeout period. What we might want to do is register asynchronous callbacks on asset
/// receipt in the same manner as the nascent (but not yet active) TextureDownloadModule. Of course, /// receipt in the same manner as the TextureDownloadModule. Of course,
/// a timeout before asset receipt usually isn't fatal, the operation will work on the retry when the /// a timeout before asset receipt usually isn't fatal, the operation will work on the retry when the
/// asset is much more likely to have made it into the cache. /// asset is much more likely to have made it into the cache.
/// </summary> /// </summary>
@ -177,29 +298,31 @@ namespace OpenSim.Framework.Communications.Cache
int pollPeriod = 200; int pollPeriod = 200;
int maxPolls = 15; int maxPolls = 15;
AssetBase asset = GetCachedAsset(assetID); AssetBase asset;
if (asset != null)
if (TryGetCachedAsset(assetID, out asset))
{ {
return asset; return asset;
} }
else
m_assetServer.RequestAsset(assetID, isTexture);
do
{ {
Thread.Sleep(pollPeriod); m_assetServer.RequestAsset(assetID, isTexture);
asset = GetCachedAsset(assetID); do
if (asset != null)
{ {
return asset; Thread.Sleep(pollPeriod);
}
} while (--maxPolls > 0);
MainLog.Instance.Warn( if (TryGetCachedAsset(assetID, out asset))
"ASSETCACHE", "Asset {0} was not received before the retrieval timeout was reached"); {
return asset;
}
} while (--maxPolls > 0);
return null; m_log.WarnFormat("[ASSET CACHE]: {0} {1} was not received before the retrieval timeout was reached",
isTexture ? "texture" : "asset", assetID.ToString());
return null;
}
} }
// rex, new function // rex, new function
@ -220,7 +343,7 @@ namespace OpenSim.Framework.Communications.Cache
/// <param name="asset"></param> /// <param name="asset"></param>
public void AddAsset(AssetBase asset) public void AddAsset(AssetBase asset)
{ {
string temporary = asset.Temporary ? "temporary" : ""; string temporary = asset.Temporary ? "temporary" : String.Empty;
string type = asset.Type == 0 ? "texture" : "asset"; string type = asset.Type == 0 ? "texture" : "asset";
string result = "Ignored"; string result = "Ignored";
@ -235,6 +358,10 @@ namespace OpenSim.Framework.Communications.Cache
{ {
TextureImage textur = new TextureImage(asset); TextureImage textur = new TextureImage(asset);
Textures.Add(textur.FullID, textur); Textures.Add(textur.FullID, textur);
if (StatsManager.SimExtraStats != null)
StatsManager.SimExtraStats.AddTexture(textur);
if (asset.Temporary) if (asset.Temporary)
{ {
result = "Added to cache"; result = "Added to cache";
@ -256,6 +383,10 @@ namespace OpenSim.Framework.Communications.Cache
{ {
AssetInfo assetInf = new AssetInfo(asset); AssetInfo assetInf = new AssetInfo(asset);
Assets.Add(assetInf.FullID, assetInf); Assets.Add(assetInf.FullID, assetInf);
if (StatsManager.SimExtraStats != null)
StatsManager.SimExtraStats.AddAsset(assetInf);
if (asset.Temporary) if (asset.Temporary)
{ {
result = "Added to cache"; result = "Added to cache";
@ -267,8 +398,9 @@ namespace OpenSim.Framework.Communications.Cache
} }
} }
} }
#if DEBUG
m_log.Verbose("ASSETCACHE", "Adding {0} {1} [{2}]: {3}.", temporary, type, asset.FullID, result); //m_log.DebugFormat("[ASSET CACHE]: Adding {0} {1} [{2}]: {3}.", temporary, type, asset.FullID, result);
#endif
} }
// rex, new function for "replace asset" functionality // rex, new function for "replace asset" functionality
@ -372,25 +504,13 @@ namespace OpenSim.Framework.Communications.Cache
} }
public void DeleteAsset(LLUUID assetID) public void DeleteAsset(LLUUID assetID)
{ // See IAssetReceiver
// this.m_assetServer.DeleteAsset(assetID);
//Todo should delete it from memory too
}
public AssetBase CopyAsset(LLUUID assetID)
{
AssetBase asset = GetCachedAsset(assetID);
if (asset == null)
return null;
asset.FullID = LLUUID.Random(); // TODO: check for conflicts
AddAsset(asset);
return asset;
}
public void AssetReceived(AssetBase asset, bool IsTexture) public void AssetReceived(AssetBase asset, bool IsTexture)
{ {
#if DEBUG
m_log.DebugFormat("[ASSET CACHE]: Received {0} [{1}]", IsTexture ? "texture" : "asset", asset.FullID);
#endif
if (asset.FullID != LLUUID.Zero) // if it is set to zero then the asset wasn't found by the server if (asset.FullID != LLUUID.Zero) // if it is set to zero then the asset wasn't found by the server
{ {
//check if it is a texture or not //check if it is a texture or not
@ -400,51 +520,68 @@ namespace OpenSim.Framework.Communications.Cache
if (IsTexture) if (IsTexture)
{ {
//Console.WriteLine("asset received from asset server");
TextureImage image = new TextureImage(asset); TextureImage image = new TextureImage(asset);
if (!Textures.ContainsKey(image.FullID)) if (Textures.ContainsKey(image.FullID))
{
#if DEBUG
//m_log.DebugFormat("[ASSET CACHE]: There's already an texture {0} in memory. Skipping.", asset.FullID);
#endif
}
else
{ {
Textures.Add(image.FullID, image); Textures.Add(image.FullID, image);
if (RequestedTextures.ContainsKey(image.FullID))
if (StatsManager.SimExtraStats != null)
{ {
AssetRequest req = RequestedTextures[image.FullID]; StatsManager.SimExtraStats.AddTexture(image);
req.ImageInfo = image;
req.NumPackets = CalculateNumPackets(image.Data);
RequestedTextures.Remove(image.FullID);
TextureRequests.Add(req);
} }
} }
} }
else else
{ {
AssetInfo assetInf = new AssetInfo(asset); AssetInfo assetInf = new AssetInfo(asset);
if (!Assets.ContainsKey(assetInf.FullID)) if (Assets.ContainsKey(assetInf.FullID))
{
#if DEBUG
//m_log.DebugFormat("[ASSET CACHE]: There's already an asset {0} in memory. Skipping.", asset.FullID);
#endif
}
else
{ {
Assets.Add(assetInf.FullID, assetInf); Assets.Add(assetInf.FullID, assetInf);
if (StatsManager.SimExtraStats != null)
{
StatsManager.SimExtraStats.AddAsset(assetInf);
}
if (RequestedAssets.ContainsKey(assetInf.FullID)) if (RequestedAssets.ContainsKey(assetInf.FullID))
{ {
#if DEBUG
//m_log.DebugFormat("[ASSET CACHE]: Moving {0} from RequestedAssets to AssetRequests", asset.FullID);
#endif
AssetRequest req = RequestedAssets[assetInf.FullID]; AssetRequest req = RequestedAssets[assetInf.FullID];
req.AssetInf = assetInf; req.AssetInf = assetInf;
req.NumPackets = CalculateNumPackets(assetInf.Data); req.NumPackets = CalculateNumPackets(assetInf.Data);
RequestedAssets.Remove(assetInf.FullID); RequestedAssets.Remove(assetInf.FullID);
AssetRequests.Add(req); AssetRequests.Add(req);
} }
} }
} }
// Notify requesters for this asset
if (RequestLists.ContainsKey(asset.FullID)) if (RequestLists.ContainsKey(asset.FullID))
{ {
AssetRequestsList reqList = RequestLists[asset.FullID];
foreach (NewAssetRequest req in reqList.Requests)
{
req.Callback(asset.FullID, asset);
}
lock (RequestLists) lock (RequestLists)
{ {
AssetRequestsList reqList = RequestLists[asset.FullID];
foreach (NewAssetRequest req in reqList.Requests)
{
req.Callback(asset.FullID, asset);
}
RequestLists.Remove(asset.FullID); RequestLists.Remove(asset.FullID);
reqList.Requests.Clear(); reqList.Requests.Clear();
} }
@ -452,23 +589,52 @@ namespace OpenSim.Framework.Communications.Cache
} }
} }
// See IAssetReceiver
public void AssetNotFound(LLUUID assetID) public void AssetNotFound(LLUUID assetID)
{ {
//if (this.RequestedTextures.ContainsKey(assetID)) //m_log.ErrorFormat("[ASSET CACHE]: AssetNotFound for {0}", assetID);
//{
// MainLog.Instance.Warn("ASSET CACHE", "sending image not found for {0}", assetID); // The 'image not found' packet needs to happen, but RequestedTextures is not actually used (should be cleaned up)
// AssetRequest req = this.RequestedTextures[assetID]; // It might also be better to do this in the TextureDownloadModule
// ImageNotInDatabasePacket notFound = new ImageNotInDatabasePacket(); /*
// notFound.ImageID.ID = assetID; *
// req.RequestUser.OutPacket(notFound); AssetRequest req;
// this.RequestedTextures.Remove(assetID);
//} if (RequestedTextures.TryGetValue(assetID, out req))
//else {
//{ m_log.WarnFormat("[ASSET CACHE]: sending image not found for {0}", assetID);
// MainLog.Instance.Error("ASSET CACHE", "Cound not send image not found for {0}", assetID); ImageNotInDatabasePacket notFound = new ImageNotInDatabasePacket();
//} notFound.ImageID.ID = assetID;
req.RequestUser.OutPacket(notFound, ThrottleOutPacketType.Unknown);
RequestedTextures.Remove(assetID);
}
else
{
m_log.ErrorFormat("[ASSET CACHE]: Asset [{0}] not found, but couldn't find any users to send to ", assetID);
}
*/
// Notify requesters for this asset
lock (RequestLists)
{
if (RequestLists.ContainsKey(assetID))
{
AssetRequestsList reqList = RequestLists[assetID];
foreach (NewAssetRequest req in reqList.Requests)
{
req.Callback(assetID, null);
}
RequestLists.Remove(assetID);
}
}
} }
/// <summary>
/// Calculate the number of packets required to send the asset to the client.
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
private int CalculateNumPackets(byte[] data) private int CalculateNumPackets(byte[] data)
{ {
const uint m_maxPacketSize = 600; const uint m_maxPacketSize = 600;
@ -478,17 +644,15 @@ namespace OpenSim.Framework.Communications.Cache
{ {
// over max number of bytes so split up file // over max number of bytes so split up file
long restData = data.LongLength - m_maxPacketSize; long restData = data.LongLength - m_maxPacketSize;
int restPackets = (int) ((restData + m_maxPacketSize - 1)/m_maxPacketSize); int restPackets = (int)((restData + m_maxPacketSize - 1) / m_maxPacketSize);
numPackets += restPackets; numPackets += restPackets;
} }
return numPackets; return numPackets;
} }
#region Assets
/// <summary> /// <summary>
/// /// Make an asset request the result of which will be packeted up and sent directly back to the client.
/// </summary> /// </summary>
/// <param name="userInfo"></param> /// <param name="userInfo"></param>
/// <param name="transferRequest"></param> /// <param name="transferRequest"></param>
@ -543,7 +707,7 @@ namespace OpenSim.Framework.Communications.Cache
} }
/// <summary> /// <summary>
/// /// Process the asset queue which sends packets directly back to the client.
/// </summary> /// </summary>
private void ProcessAssetQueue() private void ProcessAssetQueue()
{ {
@ -559,7 +723,7 @@ namespace OpenSim.Framework.Communications.Cache
AssetRequest req; AssetRequest req;
for (int i = 0; i < num; i++) for (int i = 0; i < num; i++)
{ {
req = (AssetRequest) AssetRequests[i]; req = (AssetRequest)AssetRequests[i];
//Console.WriteLine("sending asset " + req.RequestAssetID); //Console.WriteLine("sending asset " + req.RequestAssetID);
TransferInfoPacket Transfer = new TransferInfoPacket(); TransferInfoPacket Transfer = new TransferInfoPacket();
Transfer.TransferInfo.ChannelType = 2; Transfer.TransferInfo.ChannelType = 2;
@ -569,7 +733,7 @@ namespace OpenSim.Framework.Communications.Cache
{ {
Transfer.TransferInfo.Params = new byte[20]; Transfer.TransferInfo.Params = new byte[20];
Array.Copy(req.RequestAssetID.GetBytes(), 0, Transfer.TransferInfo.Params, 0, 16); Array.Copy(req.RequestAssetID.GetBytes(), 0, Transfer.TransferInfo.Params, 0, 16);
int assType = (int) req.AssetInf.Type; int assType = (int)req.AssetInf.Type;
Array.Copy(Helpers.IntToBytes(assType), 0, Transfer.TransferInfo.Params, 16, 4); Array.Copy(Helpers.IntToBytes(assType), 0, Transfer.TransferInfo.Params, 16, 4);
} }
else if (req.AssetRequestSource == 3) else if (req.AssetRequestSource == 3)
@ -579,7 +743,7 @@ namespace OpenSim.Framework.Communications.Cache
//Array.Copy(req.RequestUser.AgentId.GetBytes(), 0, Transfer.TransferInfo.Params, 0, 16); //Array.Copy(req.RequestUser.AgentId.GetBytes(), 0, Transfer.TransferInfo.Params, 0, 16);
//Array.Copy(req.RequestUser.SessionId.GetBytes(), 0, Transfer.TransferInfo.Params, 16, 16); //Array.Copy(req.RequestUser.SessionId.GetBytes(), 0, Transfer.TransferInfo.Params, 16, 16);
} }
Transfer.TransferInfo.Size = (int) req.AssetInf.Data.Length; Transfer.TransferInfo.Size = (int)req.AssetInf.Data.Length;
Transfer.TransferInfo.TransferID = req.TransferRequestID; Transfer.TransferInfo.TransferID = req.TransferRequestID;
req.RequestUser.OutPacket(Transfer, ThrottleOutPacketType.Asset); req.RequestUser.OutPacket(Transfer, ThrottleOutPacketType.Asset);
@ -597,7 +761,7 @@ namespace OpenSim.Framework.Communications.Cache
{ {
int processedLength = 0; int processedLength = 0;
// libsecondlife hardcodes 1500 as the maximum data chunk size // libsecondlife hardcodes 1500 as the maximum data chunk size
int maxChunkSize = 1500; int maxChunkSize = 1250;
int packetNumber = 0; int packetNumber = 0;
while (processedLength < req.AssetInf.Data.Length) while (processedLength < req.AssetInf.Data.Length)
@ -638,8 +802,6 @@ namespace OpenSim.Framework.Communications.Cache
} }
} }
#endregion
public class AssetRequest public class AssetRequest
{ {
public IClientAPI RequestUser; public IClientAPI RequestUser;
@ -698,7 +860,6 @@ namespace OpenSim.Framework.Communications.Cache
} }
} }
public class AssetRequestsList public class AssetRequestsList
{ {
public LLUUID AssetID; public LLUUID AssetID;

View File

@ -35,6 +35,8 @@ namespace OpenSim.Framework.Communications.Cache
{ {
public class LocalAssetServer : AssetServerBase public class LocalAssetServer : AssetServerBase
{ {
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private IObjectContainer db; private IObjectContainer db;
public LocalAssetServer() public LocalAssetServer()
@ -43,7 +45,7 @@ namespace OpenSim.Framework.Communications.Cache
yapfile = File.Exists(Path.Combine(Util.dataDir(), "regionassets.yap")); yapfile = File.Exists(Path.Combine(Util.dataDir(), "regionassets.yap"));
db = Db4oFactory.OpenFile(Path.Combine(Util.dataDir(), "regionassets.yap")); db = Db4oFactory.OpenFile(Path.Combine(Util.dataDir(), "regionassets.yap"));
MainLog.Instance.Verbose("ASSETS", "Db4 Asset database creation"); m_log.Info("[ASSETS]: Db4 Asset database creation");
if (!yapfile) if (!yapfile)
{ {
@ -67,7 +69,7 @@ namespace OpenSim.Framework.Communications.Cache
if (db != null) if (db != null)
{ {
MainLog.Instance.Verbose("ASSETSERVER", "Closing local asset server database"); m_log.Info("[ASSETSERVER]: Closing local asset server database");
db.Close(); db.Close();
} }
} }
@ -193,7 +195,7 @@ namespace OpenSim.Framework.Communications.Cache
protected virtual void SetUpAssetDatabase() protected virtual void SetUpAssetDatabase()
{ {
MainLog.Instance.Verbose("LOCAL ASSET SERVER", "Setting up asset database"); m_log.Info("[LOCAL ASSET SERVER]: Setting up asset database");
base.LoadDefaultAssets(); base.LoadDefaultAssets();
} }

View File

@ -37,6 +37,9 @@ namespace OpenSim.Framework.Communications.Cache
{ {
public abstract class AssetServerBase : IAssetServer public abstract class AssetServerBase : IAssetServer
{ {
private static readonly log4net.ILog m_log
= log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
protected IAssetReceiver m_receiver; protected IAssetReceiver m_receiver;
protected BlockingQueue<AssetRequest> m_assetRequests; protected BlockingQueue<AssetRequest> m_assetRequests;
protected Thread m_localAssetServerThread; protected Thread m_localAssetServerThread;
@ -70,15 +73,13 @@ namespace OpenSim.Framework.Communications.Cache
if (asset != null) if (asset != null)
{ {
MainLog.Instance.Verbose( //m_log.InfoFormat("[ASSETSERVER]: Asset {0} received from asset server", req.AssetID);
"ASSET", "Asset {0} received from asset server", req.AssetID);
m_receiver.AssetReceived(asset, req.IsTexture); m_receiver.AssetReceived(asset, req.IsTexture);
} }
else else
{ {
MainLog.Instance.Error( m_log.ErrorFormat("[ASSET SERVER]: Asset {0} not found by asset server", req.AssetID);
"ASSET", "Asset {0} not found by asset server", req.AssetID);
m_receiver.AssetNotFound(req.AssetID); m_receiver.AssetNotFound(req.AssetID);
} }
@ -86,22 +87,23 @@ namespace OpenSim.Framework.Communications.Cache
public virtual void LoadDefaultAssets() public virtual void LoadDefaultAssets()
{ {
MainLog.Instance.Verbose("ASSETSERVER", "Setting up asset database"); m_log.Info("[ASSET SERVER]: Setting up asset database");
assetLoader.ForEachDefaultXmlAsset(StoreAsset); assetLoader.ForEachDefaultXmlAsset(StoreAsset);
CommitAssets(); CommitAssets();
} }
public AssetServerBase() public AssetServerBase()
{ {
MainLog.Instance.Verbose("ASSETSERVER", "Starting asset storage system"); m_log.Info("[ASSET SERVER]: Starting asset storage system");
m_assetRequests = new BlockingQueue<AssetRequest>(); m_assetRequests = new BlockingQueue<AssetRequest>();
m_localAssetServerThread = new Thread(RunRequests); m_localAssetServerThread = new Thread(RunRequests);
m_localAssetServerThread.Name = "LocalAssetServerThread";
m_localAssetServerThread.IsBackground = true; m_localAssetServerThread.IsBackground = true;
m_localAssetServerThread.Start(); m_localAssetServerThread.Start();
OpenSim.Framework.ThreadTracker.Add(m_localAssetServerThread);
} }
private void RunRequests() private void RunRequests()
@ -116,11 +118,15 @@ namespace OpenSim.Framework.Communications.Cache
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Error("ASSETSERVER", e.Message); m_log.Error("[ASSET SERVER]: " + e.ToString());
} }
} }
} }
/// <summary>
/// The receiver will be called back with asset data once it comes in.
/// </summary>
/// <param name="receiver"></param>
public void SetReceiver(IAssetReceiver receiver) public void SetReceiver(IAssetReceiver receiver)
{ {
m_receiver = receiver; m_receiver = receiver;
@ -133,7 +139,9 @@ namespace OpenSim.Framework.Communications.Cache
req.IsTexture = isTexture; req.IsTexture = isTexture;
m_assetRequests.Enqueue(req); m_assetRequests.Enqueue(req);
MainLog.Instance.Verbose("ASSET", "Added {0} to request queue", assetID); #if DEBUG
m_log.InfoFormat("[ASSET SERVER]: Added {0} to request queue", assetID);
#endif
} }
public virtual void UpdateAsset(AssetBase asset) public virtual void UpdateAsset(AssetBase asset)

View File

@ -1,109 +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 OpenSim 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 libsecondlife;
namespace OpenSim.Framework.Communications.Cache
{
public class AssetTransactionManager
{
// Fields
public CommunicationsManager CommsManager;
public Dictionary<LLUUID, AgentAssetTransactions> AgentTransactions =
new Dictionary<LLUUID, AgentAssetTransactions>();
private bool m_dumpAssetsToFile;
public AssetTransactionManager(CommunicationsManager commsManager, bool dumpAssetsToFile)
{
CommsManager = commsManager;
m_dumpAssetsToFile = dumpAssetsToFile;
}
// Methods
public AgentAssetTransactions AddUser(LLUUID userID)
{
lock (AgentTransactions)
{
if (!AgentTransactions.ContainsKey(userID))
{
AgentAssetTransactions transactions = new AgentAssetTransactions(userID, this, m_dumpAssetsToFile);
AgentTransactions.Add(userID, transactions);
return transactions;
}
}
return null;
}
public AgentAssetTransactions GetUserTransActions(LLUUID userID)
{
if (AgentTransactions.ContainsKey(userID))
{
return AgentTransactions[userID];
}
return null;
}
public void HandleInventoryFromTransaction(IClientAPI remoteClient, LLUUID transactionID, LLUUID folderID,
uint callbackID, string description, string name, sbyte invType,
sbyte type, byte wearableType, uint nextOwnerMask)
{
AgentAssetTransactions transactions = GetUserTransActions(remoteClient.AgentId);
if (transactions != null)
{
transactions.RequestCreateInventoryItem(remoteClient, transactionID, folderID, callbackID, description,
name, invType, type, wearableType, nextOwnerMask);
}
}
public void HandleUDPUploadRequest(IClientAPI remoteClient, LLUUID assetID, LLUUID transaction, sbyte type,
byte[] data, bool storeLocal, bool tempFile)
{
// Console.WriteLine("asset upload of " + assetID);
AgentAssetTransactions transactions = GetUserTransActions(remoteClient.AgentId);
if (transactions != null)
{
AgentAssetTransactions.AssetXferUploader uploader = transactions.RequestXferUploader(transaction);
if (uploader != null)
{
uploader.Initialise(remoteClient, assetID, transaction, type, data, storeLocal, tempFile);
}
}
}
public void HandleXfer(IClientAPI remoteClient, ulong xferID, uint packetID, byte[] data)
{
AgentAssetTransactions transactions = GetUserTransActions(remoteClient.AgentId);
if (transactions != null)
{
transactions.HandleXfer(xferID, packetID, data);
}
}
}
}

View File

@ -36,6 +36,8 @@ namespace OpenSim.Framework.Communications.Cache
{ {
public class GridAssetClient : AssetServerBase public class GridAssetClient : AssetServerBase
{ {
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private string _assetServerUrl; private string _assetServerUrl;
public GridAssetClient(string serverUrl) public GridAssetClient(string serverUrl)
@ -50,7 +52,9 @@ namespace OpenSim.Framework.Communications.Cache
Stream s = null; Stream s = null;
try try
{ {
MainLog.Instance.Debug("ASSETCACHE", "Querying for {0}", req.AssetID.ToString()); #if DEBUG
//m_log.DebugFormat("[GRID ASSET CLIENT]: Querying for {0}", req.AssetID.ToString());
#endif
RestClient rc = new RestClient(_assetServerUrl); RestClient rc = new RestClient(_assetServerUrl);
rc.AddResourcePath("assets"); rc.AddResourcePath("assets");
@ -70,9 +74,9 @@ namespace OpenSim.Framework.Communications.Cache
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Error("ASSETCACHE", e.Message); m_log.Error("[GRID ASSET CLIENT]: " + e.Message);
MainLog.Instance.Debug("ASSETCACHE", "Getting asset {0}", req.AssetID.ToString()); m_log.DebugFormat("[GRID ASSET CLIENT]: Getting asset {0}", req.AssetID.ToString());
MainLog.Instance.Error("ASSETCACHE", e.StackTrace); m_log.Error("[GRID ASSET CLIENT]: " + e.StackTrace);
} }
return null; return null;
@ -93,17 +97,19 @@ namespace OpenSim.Framework.Communications.Cache
// XmlSerializer xs = new XmlSerializer(typeof(AssetBase)); // XmlSerializer xs = new XmlSerializer(typeof(AssetBase));
// xs.Serialize(s, asset); // xs.Serialize(s, asset);
// RestClient rc = new RestClient(_assetServerUrl); // RestClient rc = new RestClient(_assetServerUrl);
MainLog.Instance.Verbose("ASSET", "Storing asset"); m_log.Info("[GRID ASSET CLIENT]: Storing asset");
//rc.AddResourcePath("assets"); //rc.AddResourcePath("assets");
// rc.RequestMethod = "POST"; // rc.RequestMethod = "POST";
// rc.Request(s); // rc.Request(s);
//MainLog.Instance.Verbose("ASSET", "Stored {0}", rc); //m_log.InfoFormat("[ASSET]: Stored {0}", rc);
MainLog.Instance.Verbose("ASSET", "Sending to " + _assetServerUrl + "/assets/"); m_log.Info("[GRID ASSET CLIENT]: Sending to " + _assetServerUrl + "/assets/");
RestObjectPoster.BeginPostObject<AssetBase>(_assetServerUrl + "/assets/", asset); RestObjectPoster.BeginPostObject<AssetBase>(_assetServerUrl + "/assets/", asset);
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Error("ASSETS", e.Message); m_log.Error("[GRID ASSET CLIENT]: " + e.Message);
} }
} }

View File

@ -13,7 +13,7 @@
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS AS IS AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
@ -26,12 +26,12 @@
* *
*/ */
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Xml; using System.Xml;
using libsecondlife; using libsecondlife;
using Nini.Config; using Nini.Config;
using OpenSim.Framework.Console; using OpenSim.Framework.Console;
namespace OpenSim.Framework.Communications.Cache namespace OpenSim.Framework.Communications.Cache
@ -42,6 +42,8 @@ namespace OpenSim.Framework.Communications.Cache
/// </summary> /// </summary>
public class LibraryRootFolder : InventoryFolderImpl public class LibraryRootFolder : InventoryFolderImpl
{ {
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private LLUUID libOwner = new LLUUID("11111111-1111-0000-0000-000100bba000"); private LLUUID libOwner = new LLUUID("11111111-1111-0000-0000-000100bba000");
/// <summary> /// <summary>
@ -53,7 +55,7 @@ namespace OpenSim.Framework.Communications.Cache
public LibraryRootFolder() public LibraryRootFolder()
{ {
MainLog.Instance.Verbose("LIBRARYINVENTORY", "Loading library inventory"); m_log.Info("[LIBRARY INVENTORY]: Loading library inventory");
agentID = libOwner; agentID = libOwner;
folderID = new LLUUID("00000112-000f-0000-0000-000100bba000"); folderID = new LLUUID("00000112-000f-0000-0000-000100bba000");
@ -138,8 +140,8 @@ namespace OpenSim.Framework.Communications.Cache
/// <param name="assets"></param> /// <param name="assets"></param>
protected void LoadLibraries(string librariesControlPath) protected void LoadLibraries(string librariesControlPath)
{ {
MainLog.Instance.Verbose( m_log.InfoFormat(
"LIBRARYINVENTORY", "Loading libraries control file {0}", librariesControlPath); "[LIBRARY INVENTORY]: Loading libraries control file {0}", librariesControlPath);
LoadFromFile(librariesControlPath, "Libraries control", ReadLibraryFromConfig); LoadFromFile(librariesControlPath, "Libraries control", ReadLibraryFromConfig);
} }
@ -152,13 +154,13 @@ namespace OpenSim.Framework.Communications.Cache
{ {
string foldersPath string foldersPath
= Path.Combine( = Path.Combine(
Util.inventoryDir(), config.GetString("foldersFile", "")); Util.inventoryDir(), config.GetString("foldersFile", System.String.Empty));
LoadFromFile(foldersPath, "Library folders", ReadFolderFromConfig); LoadFromFile(foldersPath, "Library folders", ReadFolderFromConfig);
string itemsPath string itemsPath
= Path.Combine( = Path.Combine(
Util.inventoryDir(), config.GetString("itemsFile", "")); Util.inventoryDir(), config.GetString("itemsFile", System.String.Empty));
LoadFromFile(itemsPath, "Library items", ReadItemFromConfig); LoadFromFile(itemsPath, "Library items", ReadItemFromConfig);
} }
@ -186,14 +188,12 @@ namespace OpenSim.Framework.Communications.Cache
libraryFolders.Add(folderInfo.folderID, folderInfo); libraryFolders.Add(folderInfo.folderID, folderInfo);
parentFolder.SubFolders.Add(folderInfo.folderID, folderInfo); parentFolder.SubFolders.Add(folderInfo.folderID, folderInfo);
// MainLog.Instance.Verbose( // m_log.InfoFormat("[LIBRARY INVENTORY]: Adding folder {0} ({1})", folderInfo.name, folderInfo.folderID);
// "LIBRARYINVENTORY", "Adding folder {0} ({1})", folderInfo.name, folderInfo.folderID);
} }
else else
{ {
MainLog.Instance.Warn( m_log.WarnFormat(
"LIBRARYINVENTORY", "[LIBRARY INVENTORY]: Couldn't add folder {0} ({1}) since parent folder with ID {2} does not exist!",
"Couldn't add folder {0} ({1}) since parent folder with ID {2} does not exist!",
folderInfo.name, folderInfo.folderID, folderInfo.parentID); folderInfo.name, folderInfo.folderID, folderInfo.parentID);
} }
} }
@ -210,8 +210,8 @@ namespace OpenSim.Framework.Communications.Cache
item.inventoryID = new LLUUID(config.GetString("inventoryID", folderID.ToString())); item.inventoryID = new LLUUID(config.GetString("inventoryID", folderID.ToString()));
item.assetID = new LLUUID(config.GetString("assetID", LLUUID.Random().ToString())); item.assetID = new LLUUID(config.GetString("assetID", LLUUID.Random().ToString()));
item.parentFolderID = new LLUUID(config.GetString("folderID", folderID.ToString())); item.parentFolderID = new LLUUID(config.GetString("folderID", folderID.ToString()));
item.inventoryDescription = config.GetString("description", ""); item.inventoryDescription = config.GetString("description", System.String.Empty);
item.inventoryName = config.GetString("name", ""); item.inventoryName = config.GetString("name", System.String.Empty);
item.assetType = config.GetInt("assetType", 0); item.assetType = config.GetInt("assetType", 0);
item.invType = config.GetInt("inventoryType", 0); item.invType = config.GetInt("inventoryType", 0);
item.inventoryCurrentPermissions = (uint)config.GetLong("currentPermissions", 0x7FFFFFFF); item.inventoryCurrentPermissions = (uint)config.GetLong("currentPermissions", 0x7FFFFFFF);
@ -227,9 +227,8 @@ namespace OpenSim.Framework.Communications.Cache
} }
else else
{ {
MainLog.Instance.Warn( m_log.WarnFormat(
"LIBRARYINVENTORY", "[LIBRARY INVENTORY]: Couldn't add item {0} ({1}) since parent folder with ID {2} does not exist!",
"Couldn't add item {0} ({1}) since parent folder with ID {2} does not exist!",
item.inventoryName, item.inventoryID, item.parentFolderID); item.inventoryName, item.inventoryID, item.parentFolderID);
} }
} }
@ -257,14 +256,12 @@ namespace OpenSim.Framework.Communications.Cache
} }
catch (XmlException e) catch (XmlException e)
{ {
MainLog.Instance.Error( m_log.ErrorFormat("[LIBRARY INVENTORY]: Error loading {0} : {1}", path, e);
"LIBRARYINVENTORY", "Error loading {0} : {1}", path, e);
} }
} }
else else
{ {
MainLog.Instance.Error( m_log.ErrorFormat("[LIBRARY INVENTORY]: {0} file {1} does not exist!", fileDescription, path);
"LIBRARYINVENTORY", "{0} file {1} does not exist!", fileDescription, path);
} }
} }

View File

@ -33,6 +33,8 @@ namespace OpenSim.Framework.Communications.Cache
{ {
public class SQLAssetServer : AssetServerBase public class SQLAssetServer : AssetServerBase
{ {
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public SQLAssetServer(string pluginName) public SQLAssetServer(string pluginName)
{ {
AddPlugin(pluginName); AddPlugin(pluginName);
@ -45,7 +47,7 @@ namespace OpenSim.Framework.Communications.Cache
public void AddPlugin(string FileName) public void AddPlugin(string FileName)
{ {
MainLog.Instance.Verbose("SQLAssetServer", "AssetStorage: Attempting to load " + FileName); m_log.Info("[SQLAssetServer]: AssetStorage: Attempting to load " + FileName);
Assembly pluginAssembly = Assembly.LoadFrom(FileName); Assembly pluginAssembly = Assembly.LoadFrom(FileName);
foreach (Type pluginType in pluginAssembly.GetTypes()) foreach (Type pluginType in pluginAssembly.GetTypes())
@ -61,15 +63,14 @@ namespace OpenSim.Framework.Communications.Cache
m_assetProvider = plug; m_assetProvider = plug;
m_assetProvider.Initialise(); m_assetProvider.Initialise();
MainLog.Instance.Verbose("AssetStorage", m_log.Info("[AssetStorage]: " +
"Added " + m_assetProvider.Name + " " + "Added " + m_assetProvider.Name + " " +
m_assetProvider.Version); m_assetProvider.Version);
} }
} }
} }
} }
public override void Close() public override void Close()
{ {
base.Close(); base.Close();

View File

@ -25,6 +25,8 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
using System;
using System.Collections.Generic; using System.Collections.Generic;
using libsecondlife; using libsecondlife;
using OpenSim.Framework.Console; using OpenSim.Framework.Console;
@ -33,6 +35,8 @@ namespace OpenSim.Framework.Communications.Cache
{ {
public class UserProfileCacheService public class UserProfileCacheService
{ {
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Fields // Fields
private readonly CommunicationsManager m_parent; private readonly CommunicationsManager m_parent;
private readonly Dictionary<LLUUID, CachedUserInfo> m_userProfiles = new Dictionary<LLUUID, CachedUserInfo>(); private readonly Dictionary<LLUUID, CachedUserInfo> m_userProfiles = new Dictionary<LLUUID, CachedUserInfo>();
@ -77,7 +81,7 @@ namespace OpenSim.Framework.Communications.Cache
} }
else else
{ {
MainLog.Instance.Error("USERCACHE", "User profile for user {0} not found", userID); m_log.ErrorFormat("[USERCACHE]: User profile for user {0} not found", userID);
} }
} }
} }
@ -293,32 +297,32 @@ namespace OpenSim.Framework.Communications.Cache
} }
else else
{ {
MainLog.Instance.Error( m_log.ErrorFormat("[INVENTORYCACHE]: Could not find root folder for user {0}", remoteClient.Name);
"INVENTORYCACHE", "Could not find root folder for user {0}", remoteClient.Name);
return; return;
} }
} }
else else
{ {
MainLog.Instance.Error( m_log.ErrorFormat("[INVENTORYCACHE]: " +
"INVENTORYCACHE", "Could not find user profile for {0} for folder {1}",
"Could not find user profile for {0} for folder {1}", remoteClient.Name, folderID);
remoteClient.Name, folderID);
return; return;
} }
// If we've reached this point then we couldn't find the folder, even though the client thinks // If we've reached this point then we couldn't find the folder, even though the client thinks
// it exists // it exists
MainLog.Instance.Error( m_log.ErrorFormat("[INVENTORYCACHE]: " +
"INVENTORYCACHE", "Could not find folder {0} for user {1}",
"Could not find folder {0} for user {1}", folderID, remoteClient.Name);
folderID, remoteClient.Name);
} }
public void HandlePurgeInventoryDescendents(IClientAPI remoteClient, LLUUID folderID) public void HandlePurgeInventoryDescendents(IClientAPI remoteClient, LLUUID folderID)
{ {
// m_log.InfoFormat("[INVENTORYCACHE]: Purging folder {0} for {1} uuid {2}",
// folderID, remoteClient.Name, remoteClient.AgentId);
CachedUserInfo userProfile; CachedUserInfo userProfile;
if (m_userProfiles.TryGetValue(remoteClient.AgentId, out userProfile)) if (m_userProfiles.TryGetValue(remoteClient.AgentId, out userProfile))
{ {

View File

@ -57,6 +57,8 @@ namespace OpenSim.Region.Capabilities
public class Caps public class Caps
{ {
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private string m_httpListenerHostName; private string m_httpListenerHostName;
private uint m_httpListenPort; private uint m_httpListenPort;
@ -103,7 +105,7 @@ namespace OpenSim.Region.Capabilities
/// </summary> /// </summary>
public void RegisterHandlers() public void RegisterHandlers()
{ {
MainLog.Instance.Verbose("CAPS", "Registering CAPS handlers"); m_log.Info("[CAPS]: Registering CAPS handlers");
string capsBase = "/CAPS/" + m_capsObjectPath; string capsBase = "/CAPS/" + m_capsObjectPath;
try try
{ {
@ -122,7 +124,7 @@ namespace OpenSim.Region.Capabilities
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Error("CAPS", e.ToString()); m_log.Error("[CAPS]: " + e.ToString());
} }
} }
@ -204,7 +206,7 @@ namespace OpenSim.Region.Capabilities
{ {
Console.WriteLine("texture request " + request); Console.WriteLine("texture request " + request);
// Needs implementing (added to remove compiler warning) // Needs implementing (added to remove compiler warning)
return ""; return String.Empty;
} }
#region EventQueue (Currently not enabled) #region EventQueue (Currently not enabled)
@ -218,7 +220,7 @@ namespace OpenSim.Region.Capabilities
/// <returns></returns> /// <returns></returns>
public string ProcessEventQueue(string request, string path, string param) public string ProcessEventQueue(string request, string path, string param)
{ {
string res = ""; string res = String.Empty;
if (m_capsEventQueue.Count > 0) if (m_capsEventQueue.Count > 0)
{ {
@ -282,7 +284,7 @@ namespace OpenSim.Region.Capabilities
{ {
try try
{ {
// MainLog.Instance.Debug("CAPS", "request: {0}, path: {1}, param: {2}", request, path, param); // m_log.DebugFormat("[CAPS]: request: {0}, path: {1}, param: {2}", request, path, param);
Hashtable hash = (Hashtable) LLSD.LLSDDeserialize(Helpers.StringToField(request)); Hashtable hash = (Hashtable) LLSD.LLSDDeserialize(Helpers.StringToField(request));
LLSDTaskScriptUpdate llsdUpdateRequest = new LLSDTaskScriptUpdate(); LLSDTaskScriptUpdate llsdUpdateRequest = new LLSDTaskScriptUpdate();
@ -310,16 +312,15 @@ namespace OpenSim.Region.Capabilities
uploadResponse.uploader = uploaderURL; uploadResponse.uploader = uploaderURL;
uploadResponse.state = "upload"; uploadResponse.state = "upload";
// MainLog.Instance.Verbose( // m_log.InfoFormat("[CAPS]: " +
// "CAPS", // "ScriptTaskInventory response: {0}",
// "ScriptTaskInventory response: {0}", // LLSDHelpers.SerialiseLLSDReply(uploadResponse)));
// LLSDHelpers.SerialiseLLSDReply(uploadResponse));
return LLSDHelpers.SerialiseLLSDReply(uploadResponse); return LLSDHelpers.SerialiseLLSDReply(uploadResponse);
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Error("CAPS", e.ToString()); m_log.Error("[CAPS]: " + e.ToString());
} }
return null; return null;
@ -356,10 +357,9 @@ namespace OpenSim.Region.Capabilities
uploadResponse.uploader = uploaderURL; uploadResponse.uploader = uploaderURL;
uploadResponse.state = "upload"; uploadResponse.state = "upload";
// MainLog.Instance.Verbose( // m_log.InfoFormat("[CAPS]: " +
// "CAPS", // "NoteCardAgentInventory response: {0}",
// "NoteCardAgentInventory response: {0}", // LLSDHelpers.SerialiseLLSDReply(uploadResponse)));
// LLSDHelpers.SerialiseLLSDReply(uploadResponse));
return LLSDHelpers.SerialiseLLSDReply(uploadResponse); return LLSDHelpers.SerialiseLLSDReply(uploadResponse);
} }
@ -541,18 +541,19 @@ namespace OpenSim.Region.Capabilities
public class AssetUploader public class AssetUploader
{ {
public event UpLoadedAsset OnUpLoad; public event UpLoadedAsset OnUpLoad;
private UpLoadedAsset handler001 = null;
private string uploaderPath = ""; private string uploaderPath = String.Empty;
private LLUUID newAssetID; private LLUUID newAssetID;
private LLUUID inventoryItemID; private LLUUID inventoryItemID;
private LLUUID parentFolder; private LLUUID parentFolder;
private BaseHttpServer httpListener; private BaseHttpServer httpListener;
private bool m_dumpAssetsToFile; private bool m_dumpAssetsToFile;
private string m_assetName = ""; private string m_assetName = String.Empty;
private string m_assetDes = ""; private string m_assetDes = String.Empty;
private string m_invType = ""; private string m_invType = String.Empty;
private string m_assetType = ""; private string m_assetType = String.Empty;
public AssetUploader(string assetName, string description, LLUUID assetID, LLUUID inventoryItem, public AssetUploader(string assetName, string description, LLUUID assetID, LLUUID inventoryItem,
LLUUID parentFolderID, string invType, string assetType, string path, LLUUID parentFolderID, string invType, string assetType, string path,
@ -580,7 +581,7 @@ namespace OpenSim.Region.Capabilities
public string uploaderCaps(byte[] data, string path, string param) public string uploaderCaps(byte[] data, string path, string param)
{ {
LLUUID inv = inventoryItemID; LLUUID inv = inventoryItemID;
string res = ""; string res = String.Empty;
LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete(); LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete();
uploadComplete.new_asset = newAssetID.ToString(); uploadComplete.new_asset = newAssetID.ToString();
uploadComplete.new_inventory_item = inv; uploadComplete.new_inventory_item = inv;
@ -594,10 +595,10 @@ namespace OpenSim.Region.Capabilities
{ {
SaveAssetToFile(m_assetName + ".jp2", data); SaveAssetToFile(m_assetName + ".jp2", data);
} }
handler001 = OnUpLoad;
if (OnUpLoad != null) if (handler001 != null)
{ {
OnUpLoad(m_assetName, m_assetDes, newAssetID, inv, parentFolder, data, m_invType, m_assetType); handler001(m_assetName, m_assetDes, newAssetID, inv, parentFolder, data, m_invType, m_assetType);
} }
return res; return res;
@ -634,7 +635,9 @@ namespace OpenSim.Region.Capabilities
{ {
public event UpdateItem OnUpLoad; public event UpdateItem OnUpLoad;
private string uploaderPath = ""; private UpdateItem handler001 = null;
private string uploaderPath = String.Empty;
private LLUUID inventoryItemID; private LLUUID inventoryItemID;
private BaseHttpServer httpListener; private BaseHttpServer httpListener;
private bool m_dumpAssetToFile; private bool m_dumpAssetToFile;
@ -658,13 +661,13 @@ namespace OpenSim.Region.Capabilities
public string uploaderCaps(byte[] data, string path, string param) public string uploaderCaps(byte[] data, string path, string param)
{ {
LLUUID inv = inventoryItemID; LLUUID inv = inventoryItemID;
string res = ""; string res = String.Empty;
LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete(); LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete();
LLUUID assetID = LLUUID.Zero; LLUUID assetID = LLUUID.Zero;
handler001 = OnUpLoad;
if (OnUpLoad != null) if (handler001 != null)
{ {
assetID = OnUpLoad(inv, data); assetID = handler001(inv, data);
} }
uploadComplete.new_asset = assetID.ToString(); uploadComplete.new_asset = assetID.ToString();
@ -714,7 +717,9 @@ namespace OpenSim.Region.Capabilities
{ {
public event UpdateTaskScript OnUpLoad; public event UpdateTaskScript OnUpLoad;
private string uploaderPath = ""; private UpdateTaskScript handler001 = null;
private string uploaderPath = String.Empty;
private LLUUID inventoryItemID; private LLUUID inventoryItemID;
private LLUUID primID; private LLUUID primID;
private bool isScriptRunning; private bool isScriptRunning;
@ -747,17 +752,17 @@ namespace OpenSim.Region.Capabilities
{ {
try try
{ {
// MainLog.Instance.Verbose( // m_log.InfoFormat("[CAPS]: " +
// "CAPS", // "TaskInventoryScriptUpdater received data: {0}, path: {1}, param: {2}",
// "TaskInventoryScriptUpdater received data: {0}, path: {1}, param: {2}", // data, path, param));
// data, path, param);
string res = ""; string res = String.Empty;
LLSDTaskInventoryUploadComplete uploadComplete = new LLSDTaskInventoryUploadComplete(); LLSDTaskInventoryUploadComplete uploadComplete = new LLSDTaskInventoryUploadComplete();
if (OnUpLoad != null) handler001 = OnUpLoad;
if (handler001 != null)
{ {
OnUpLoad(inventoryItemID, primID, isScriptRunning, data); handler001(inventoryItemID, primID, isScriptRunning, data);
} }
uploadComplete.item_id = inventoryItemID; uploadComplete.item_id = inventoryItemID;
@ -773,13 +778,13 @@ namespace OpenSim.Region.Capabilities
SaveAssetToFile("updatedtaskscript" + Util.RandomClass.Next(1, 1000) + ".dat", data); SaveAssetToFile("updatedtaskscript" + Util.RandomClass.Next(1, 1000) + ".dat", data);
} }
// MainLog.Instance.Verbose("CAPS", "TaskInventoryScriptUpdater.uploaderCaps res: {0}", res); // m_log.InfoFormat("[CAPS]: TaskInventoryScriptUpdater.uploaderCaps res: {0}", res);
return res; return res;
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Error("CAPS", e.ToString()); m_log.Error("[CAPS]: " + e.ToString());
} }
// XXX Maybe this should be some meaningful error packet // XXX Maybe this should be some meaningful error packet

View File

@ -26,15 +26,16 @@
* *
*/ */
using libsecondlife; using libsecondlife;
using System;
namespace OpenSim.Region.Capabilities namespace OpenSim.Region.Capabilities
{ {
[LLSDType("MAP")] [LLSDType("MAP")]
public class LLSDAssetUploadComplete public class LLSDAssetUploadComplete
{ {
public string new_asset = ""; public string new_asset = String.Empty;
public LLUUID new_inventory_item = LLUUID.Zero; public LLUUID new_inventory_item = LLUUID.Zero;
public string state = ""; public string state = String.Empty;
//public bool success = false; //public bool success = false;
public LLSDAssetUploadComplete() public LLSDAssetUploadComplete()

View File

@ -13,7 +13,7 @@
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS AS IS AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
@ -33,11 +33,11 @@ namespace OpenSim.Region.Capabilities
[LLSDMap] [LLSDMap]
public class LLSDAssetUploadRequest public class LLSDAssetUploadRequest
{ {
public string asset_type = ""; public string asset_type = System.String.Empty;
public string description = ""; public string description = System.String.Empty;
public LLUUID folder_id = LLUUID.Zero; public LLUUID folder_id = LLUUID.Zero;
public string inventory_type = ""; public string inventory_type = System.String.Empty;
public string name = ""; public string name = System.String.Empty;
public LLSDAssetUploadRequest() public LLSDAssetUploadRequest()
{ {

View File

@ -13,7 +13,7 @@
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS AS IS AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
@ -31,8 +31,8 @@ namespace OpenSim.Region.Capabilities
[LLSDMap] [LLSDMap]
public class LLSDAssetUploadResponse public class LLSDAssetUploadResponse
{ {
public string uploader = ""; public string uploader = System.String.Empty;
public string state = ""; public string state = System.String.Empty;
public LLSDAssetUploadResponse() public LLSDAssetUploadResponse()
{ {

View File

@ -13,7 +13,7 @@
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS AS IS AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
@ -26,20 +26,22 @@
* *
*/ */
using System;
namespace OpenSim.Region.Capabilities namespace OpenSim.Region.Capabilities
{ {
[LLSDType("MAP")] [LLSDType("MAP")]
public class LLSDCapsDetails public class LLSDCapsDetails
{ {
public string MapLayer = ""; public string MapLayer = String.Empty;
public string NewFileAgentInventory = ""; public string NewFileAgentInventory = String.Empty;
//public string EventQueueGet = ""; //public string EventQueueGet = String.Empty;
// public string RequestTextureDownload = ""; // public string RequestTextureDownload = String.Empty;
// public string ChatSessionRequest = ""; // public string ChatSessionRequest = String.Empty;
public string UpdateNotecardAgentInventory = ""; public string UpdateNotecardAgentInventory = String.Empty;
public string UpdateScriptAgentInventory = ""; public string UpdateScriptAgentInventory = String.Empty;
public string UpdateScriptTaskInventory = ""; public string UpdateScriptTaskInventory = String.Empty;
// public string ParcelVoiceInfoRequest = ""; // public string ParcelVoiceInfoRequest = String.Empty;
public LLSDCapsDetails() public LLSDCapsDetails()
{ {

View File

@ -13,7 +13,7 @@
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS AS IS AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY

View File

@ -13,7 +13,7 @@
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS AS IS AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY

View File

@ -13,7 +13,7 @@
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS AS IS AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY

View File

@ -13,7 +13,7 @@
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS AS IS AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY

View File

@ -13,7 +13,7 @@
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS AS IS AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY

View File

@ -36,6 +36,8 @@ namespace OpenSim.Framework.Communications
{ {
public class CommunicationsManager public class CommunicationsManager
{ {
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
protected IUserService m_userService; protected IUserService m_userService;
public IUserService UserService public IUserService UserService
@ -71,12 +73,12 @@ namespace OpenSim.Framework.Communications
get { return m_userProfileCacheService; } get { return m_userProfileCacheService; }
} }
protected AssetTransactionManager m_transactionsManager; // protected AgentAssetTransactionsManager m_transactionsManager;
public AssetTransactionManager TransactionsManager // public AgentAssetTransactionsManager TransactionsManager
{ // {
get { return m_transactionsManager; } // get { return m_transactionsManager; }
} // }
protected AssetCache m_assetCache; protected AssetCache m_assetCache;
@ -98,7 +100,7 @@ namespace OpenSim.Framework.Communications
m_networkServersInfo = serversInfo; m_networkServersInfo = serversInfo;
m_assetCache = assetCache; m_assetCache = assetCache;
m_userProfileCacheService = new UserProfileCacheService(this); m_userProfileCacheService = new UserProfileCacheService(this);
m_transactionsManager = new AssetTransactionManager(this, dumpAssetsToFile); // m_transactionsManager = new AgentAssetTransactionsManager(this, dumpAssetsToFile);
} }
public void doCreate(string[] cmmdParams) public void doCreate(string[] cmmdParams)
@ -114,11 +116,11 @@ namespace OpenSim.Framework.Communications
if (cmmdParams.Length < 2) if (cmmdParams.Length < 2)
{ {
firstName = MainLog.Instance.CmdPrompt("First name", "Default"); firstName = MainConsole.Instance.CmdPrompt("First name", "Default");
lastName = MainLog.Instance.CmdPrompt("Last name", "User"); lastName = MainConsole.Instance.CmdPrompt("Last name", "User");
password = MainLog.Instance.PasswdPrompt("Password"); password = MainConsole.Instance.PasswdPrompt("Password");
regX = Convert.ToUInt32(MainLog.Instance.CmdPrompt("Start Region X", "1000")); regX = Convert.ToUInt32(MainConsole.Instance.CmdPrompt("Start Region X", "1000"));
regY = Convert.ToUInt32(MainLog.Instance.CmdPrompt("Start Region Y", "1000")); regY = Convert.ToUInt32(MainConsole.Instance.CmdPrompt("Start Region Y", "1000"));
} }
else else
{ {
@ -129,14 +131,30 @@ namespace OpenSim.Framework.Communications
regY = Convert.ToUInt32(cmmdParams[5]); regY = Convert.ToUInt32(cmmdParams[5]);
} }
AddUser(firstName, lastName, password, regX, regY); if (null == m_userService.GetUserProfile(firstName, lastName))
{
AddUser(firstName, lastName, password, regX, regY);
}
else
{
m_log.ErrorFormat("[USERS]: A user with the name {0} {1} already exists!", firstName, lastName);
}
break; break;
} }
} }
/// <summary>
/// Persistently adds a user to OpenSim.
/// </summary>
/// <param name="firstName"></param>
/// <param name="lastName"></param>
/// <param name="password"></param>
/// <param name="regX"></param>
/// <param name="regY"></param>
/// <returns>The UUID of the added user. Returns null if the add was unsuccessful</returns>
public LLUUID AddUser(string firstName, string lastName, string password, uint regX, uint regY) public LLUUID AddUser(string firstName, string lastName, string password, uint regX, uint regY)
{ {
string md5PasswdHash = Util.Md5Hash(Util.Md5Hash(password) + ":" + ""); string md5PasswdHash = Util.Md5Hash(Util.Md5Hash(password) + ":" + String.Empty);
m_userService.AddUserProfile(firstName, lastName, md5PasswdHash, regX, regY); m_userService.AddUserProfile(firstName, lastName, md5PasswdHash, regX, regY);
UserProfileData userProf = UserService.GetUserProfile(firstName, lastName, ""); UserProfileData userProf = UserService.GetUserProfile(firstName, lastName, "");
@ -147,7 +165,7 @@ namespace OpenSim.Framework.Communications
else else
{ {
m_inventoryService.CreateNewUserInventory(userProf.UUID); m_inventoryService.CreateNewUserInventory(userProf.UUID);
System.Console.WriteLine("Created new inventory set for " + firstName + " " + lastName); System.Console.WriteLine("[USERS]: Created new inventory set for " + firstName + " " + lastName);
return userProf.UUID; return userProf.UUID;
} }
} }
@ -163,6 +181,20 @@ namespace OpenSim.Framework.Communications
{ {
m_userService.AddNewUserFriend(friendlistowner, friend, perms); m_userService.AddNewUserFriend(friendlistowner, friend, perms);
} }
/// <summary>
/// Logs off a user and does the appropriate communications
/// </summary>
/// <param name="userid"></param>
/// <param name="regionid"></param>
/// <param name="regionhandle"></param>
/// <param name="posx"></param>
/// <param name="posy"></param>
/// <param name="posz"></param>
public void LogOffUser(LLUUID userid, LLUUID regionid, ulong regionhandle, float posx, float posy, float posz)
{
m_userService.LogOffUser(userid, regionid, regionhandle, posx, posy, posz);
}
/// <summary> /// <summary>
/// Delete friend on friendlistowner's friendlist. /// Delete friend on friendlistowner's friendlist.

View File

@ -32,6 +32,8 @@ namespace OpenSim.Framework.Communications
public interface IInterRegionCommunications public interface IInterRegionCommunications
{ {
string rdebugRegionName { get; set; } string rdebugRegionName { get; set; }
bool Available { get; }
void CheckRegion(string address, uint port);
bool InformRegionOfChildAgent(ulong regionHandle, AgentCircuitData agentData); bool InformRegionOfChildAgent(ulong regionHandle, AgentCircuitData agentData);
bool InformRegionOfPrimCrossing(ulong regionHandle, LLUUID primID, string objData); bool InformRegionOfPrimCrossing(ulong regionHandle, LLUUID primID, string objData);
bool RegionUp(SearializableRegionInfo region, ulong regionhandle); bool RegionUp(SearializableRegionInfo region, ulong regionhandle);
@ -43,6 +45,6 @@ namespace OpenSim.Framework.Communications
bool AcknowledgeAgentCrossed(ulong regionHandle, LLUUID agentId); bool AcknowledgeAgentCrossed(ulong regionHandle, LLUUID agentId);
bool AcknowledgePrimCrossed(ulong regionHandle, LLUUID primID); bool AcknowledgePrimCrossed(ulong regionHandle, LLUUID primID);
void TellRegionToCloseChildConnection(ulong regionHandle, LLUUID agentID); bool TellRegionToCloseChildConnection(ulong regionHandle, LLUUID agentID);
} }
} }

View File

@ -13,7 +13,7 @@
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS AS IS AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
@ -36,20 +36,65 @@ namespace OpenSim.Framework.Communications
public delegate void InventoryItemInfo(LLUUID userID, InventoryItemBase itemInfo); public delegate void InventoryItemInfo(LLUUID userID, InventoryItemBase itemInfo);
/// <summary>
/// Defines all the operations one can perform on a user's inventory.
/// </summary>
public interface IInventoryServices public interface IInventoryServices
{ {
void RequestInventoryForUser(LLUUID userID, InventoryFolderInfo folderCallBack, InventoryItemInfo itemCallBack); void RequestInventoryForUser(LLUUID userID, InventoryFolderInfo folderCallBack, InventoryItemInfo itemCallBack);
/// <summary>
/// Add a new folder to the given user's inventory
/// </summary>
/// <param name="userID"></param>
/// <param name="folder"></param>
void AddNewInventoryFolder(LLUUID userID, InventoryFolderBase folder); void AddNewInventoryFolder(LLUUID userID, InventoryFolderBase folder);
void MoveInventoryFolder(LLUUID userID, InventoryFolderBase folder); void MoveInventoryFolder(LLUUID userID, InventoryFolderBase folder);
/// <summary>
/// Add a new item to the given user's inventory
/// </summary>
/// <param name="userID"></param>
/// <param name="item"></param>
void AddNewInventoryItem(LLUUID userID, InventoryItemBase item); void AddNewInventoryItem(LLUUID userID, InventoryItemBase item);
/// <summary>
/// Delete an item from the given user's inventory
/// </summary>
/// <param name="userID"></param>
/// <param name="item"></param>
void DeleteInventoryItem(LLUUID userID, InventoryItemBase item); void DeleteInventoryItem(LLUUID userID, InventoryItemBase item);
/// <summary>
/// Create a new inventory for the given user
/// </summary>
/// <param name="user"></param>
void CreateNewUserInventory(LLUUID user); void CreateNewUserInventory(LLUUID user);
bool HasInventoryForUser(LLUUID userID);
/// <summary>
/// Retrieve the root inventory folder for the given user.
/// </summary>
/// <param name="userID"></param>
/// <returns>null if no root folder was found</returns>
InventoryFolderBase RequestRootFolder(LLUUID userID);
/// <summary> /// <summary>
/// Returns the root folder plus any folders in root (so down one level in the Inventory folders tree) /// Returns the root folder plus any folders in root (so down one level in the Inventory folders tree)
/// for the given user.
/// </summary> /// </summary>
/// <param name="userID"></param> /// <param name="userID"></param>
/// <returns></returns> /// <returns></returns>
List<InventoryFolderBase> RequestFirstLevelFolders(LLUUID userID); List<InventoryFolderBase> RequestFirstLevelFolders(LLUUID userID);
/// <summary>
/// Returns the named folder in that users inventory, returns null if folder is not found.
/// </summary>
/// <param name="userID"></param>
/// <param name="folderName"></param>
/// <returns></returns>
InventoryFolderBase RequestNamedFolder(LLUUID userID, string folderName);
} }
} }

View File

@ -13,7 +13,7 @@
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS AS IS AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
@ -36,13 +36,12 @@ namespace OpenSim.Framework.Communications
{ {
public abstract class InventoryServiceBase : IInventoryServices public abstract class InventoryServiceBase : IInventoryServices
{ {
protected Dictionary<string, IInventoryData> m_plugins = new Dictionary<string, IInventoryData>(); private static readonly log4net.ILog m_log
//protected IAssetServer m_assetServer; = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public InventoryServiceBase() protected Dictionary<string, IInventoryData> m_plugins = new Dictionary<string, IInventoryData>();
{
//m_assetServer = assetServer; #region Plugin methods
}
/// <summary> /// <summary>
/// Adds a new user server plugin - plugins will be requested in the order they were loaded. /// Adds a new user server plugin - plugins will be requested in the order they were loaded.
@ -52,7 +51,7 @@ namespace OpenSim.Framework.Communications
{ {
if (!String.IsNullOrEmpty(FileName)) if (!String.IsNullOrEmpty(FileName))
{ {
MainLog.Instance.Verbose("AGENTINVENTORY", "Inventorystorage: Attempting to load " + FileName); m_log.Info("[AGENTINVENTORY]: Inventorystorage: Attempting to load " + FileName);
Assembly pluginAssembly = Assembly.LoadFrom(FileName); Assembly pluginAssembly = Assembly.LoadFrom(FileName);
foreach (Type pluginType in pluginAssembly.GetTypes()) foreach (Type pluginType in pluginAssembly.GetTypes())
@ -67,24 +66,25 @@ namespace OpenSim.Framework.Communications
(IInventoryData) Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString())); (IInventoryData) Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString()));
plug.Initialise(); plug.Initialise();
m_plugins.Add(plug.getName(), plug); m_plugins.Add(plug.getName(), plug);
MainLog.Instance.Verbose("AGENTINVENTORY", "Added IInventoryData Interface"); m_log.Info("[AGENTINVENTORY]: Added IInventoryData Interface");
} }
} }
} }
} }
} }
#endregion
#region IInventoryServices methods
// See IInventoryServices
public List<InventoryFolderBase> RequestFirstLevelFolders(Guid rawUserID) public List<InventoryFolderBase> RequestFirstLevelFolders(Guid rawUserID)
{ {
LLUUID userID = new LLUUID(rawUserID); LLUUID userID = new LLUUID(rawUserID);
return RequestFirstLevelFolders(userID); return RequestFirstLevelFolders(userID);
} }
/// <summary> // See IInventoryServices
/// Returns the root folder plus any folders in root (so down one level in the Inventory folders tree)
/// </summary>
/// <param name="userID"></param>
/// <returns></returns>
public List<InventoryFolderBase> RequestFirstLevelFolders(LLUUID userID) public List<InventoryFolderBase> RequestFirstLevelFolders(LLUUID userID)
{ {
List<InventoryFolderBase> inventoryList = new List<InventoryFolderBase>(); List<InventoryFolderBase> inventoryList = new List<InventoryFolderBase>();
@ -95,9 +95,8 @@ namespace OpenSim.Framework.Communications
rootFolder = plugin.Value.getUserRootFolder(userID); rootFolder = plugin.Value.getUserRootFolder(userID);
if (rootFolder != null) if (rootFolder != null)
{ {
MainLog.Instance.Verbose( m_log.Info(
"INVENTORY", "[INVENTORY]: Found root folder for user with ID " + userID + ". Retrieving inventory contents.");
"Found root folder for user with ID " + userID + ". Retrieving inventory contents.");
inventoryList = plugin.Value.getInventoryFolders(rootFolder.folderID); inventoryList = plugin.Value.getInventoryFolders(rootFolder.folderID);
inventoryList.Insert(0, rootFolder); inventoryList.Insert(0, rootFolder);
@ -105,17 +104,13 @@ namespace OpenSim.Framework.Communications
} }
} }
MainLog.Instance.Warn( m_log.Warn(
"INVENTORY", "Could not find a root folder belonging to user with ID " + userID); "[INVENTORY]: Could not find a root folder belonging to user with ID " + userID);
return inventoryList; return inventoryList;
} }
/// <summary> // See IInventoryServices
/// Get the root folder for a user
/// </summary>
/// <param name="userID"></param>
/// <returns>null if no root folder was found</returns>
public InventoryFolderBase RequestUsersRoot(LLUUID userID) public InventoryFolderBase RequestUsersRoot(LLUUID userID)
{ {
foreach (KeyValuePair<string, IInventoryData> plugin in m_plugins) foreach (KeyValuePair<string, IInventoryData> plugin in m_plugins)
@ -125,9 +120,7 @@ namespace OpenSim.Framework.Communications
return null; return null;
} }
/// <summary> // See IInventoryServices
///
/// </summary>
public void MoveInventoryFolder(LLUUID userID, InventoryFolderBase folder) public void MoveInventoryFolder(LLUUID userID, InventoryFolderBase folder)
{ {
foreach (KeyValuePair<string, IInventoryData> plugin in m_plugins) foreach (KeyValuePair<string, IInventoryData> plugin in m_plugins)
@ -136,11 +129,53 @@ namespace OpenSim.Framework.Communications
} }
} }
/// <summary> public virtual bool HasInventoryForUser(LLUUID userID)
/// {
/// </summary> return false;
/// <param name="parentFolderID"></param> }
/// <returns></returns>
// See IInventoryServices
public InventoryFolderBase RequestRootFolder(LLUUID userID)
{
return RequestUsersRoot(userID);
}
// See IInventoryServices
public virtual InventoryFolderBase RequestNamedFolder(LLUUID userID, string folderName)
{
return null;
}
// See IInventoryServices
public void CreateNewUserInventory(LLUUID user)
{
InventoryFolderBase existingRootFolder = RequestUsersRoot(user);
if (null != existingRootFolder)
{
m_log.ErrorFormat("[AGENTINVENTORY]: " +
"Did not create a new inventory for user {0} since they already have "
+ "a root inventory folder with id {1}", user, existingRootFolder);
}
else
{
UsersInventory inven = new UsersInventory();
inven.CreateNewInventorySet(user);
AddNewInventorySet(inven);
}
}
public abstract void RequestInventoryForUser(LLUUID userID, InventoryFolderInfo folderCallBack,
InventoryItemInfo itemCallBack);
public abstract void AddNewInventoryFolder(LLUUID userID, InventoryFolderBase folder);
public abstract void MoveExistingInventoryFolder(InventoryFolderBase folder);
public abstract void AddNewInventoryItem(LLUUID userID, InventoryItemBase item);
public abstract void DeleteInventoryItem(LLUUID userID, InventoryItemBase item);
#endregion
#region Methods used by GridInventoryService
public List<InventoryFolderBase> RequestSubFolders(LLUUID parentFolderID) public List<InventoryFolderBase> RequestSubFolders(LLUUID parentFolderID)
{ {
List<InventoryFolderBase> inventoryList = new List<InventoryFolderBase>(); List<InventoryFolderBase> inventoryList = new List<InventoryFolderBase>();
@ -162,7 +197,9 @@ namespace OpenSim.Framework.Communications
return itemsList; return itemsList;
} }
public void AddFolder(InventoryFolderBase folder) #endregion
protected void AddFolder(InventoryFolderBase folder)
{ {
foreach (KeyValuePair<string, IInventoryData> plugin in m_plugins) foreach (KeyValuePair<string, IInventoryData> plugin in m_plugins)
{ {
@ -170,7 +207,7 @@ namespace OpenSim.Framework.Communications
} }
} }
public void MoveFolder(InventoryFolderBase folder) protected void MoveFolder(InventoryFolderBase folder)
{ {
foreach (KeyValuePair<string, IInventoryData> plugin in m_plugins) foreach (KeyValuePair<string, IInventoryData> plugin in m_plugins)
{ {
@ -178,7 +215,7 @@ namespace OpenSim.Framework.Communications
} }
} }
public void AddItem(InventoryItemBase item) protected void AddItem(InventoryItemBase item)
{ {
foreach (KeyValuePair<string, IInventoryData> plugin in m_plugins) foreach (KeyValuePair<string, IInventoryData> plugin in m_plugins)
{ {
@ -186,7 +223,7 @@ namespace OpenSim.Framework.Communications
} }
} }
public void DeleteItem(InventoryItemBase item) protected void DeleteItem(InventoryItemBase item)
{ {
foreach (KeyValuePair<string, IInventoryData> plugin in m_plugins) foreach (KeyValuePair<string, IInventoryData> plugin in m_plugins)
{ {
@ -194,11 +231,7 @@ namespace OpenSim.Framework.Communications
} }
} }
/// <summary> private void AddNewInventorySet(UsersInventory inventory)
///
/// </summary>
/// <param name="inventory"></param>
public void AddNewInventorySet(UsersInventory inventory)
{ {
foreach (InventoryFolderBase folder in inventory.Folders.Values) foreach (InventoryFolderBase folder in inventory.Folders.Values)
{ {
@ -206,41 +239,15 @@ namespace OpenSim.Framework.Communications
} }
} }
/// <summary> private class UsersInventory
/// Create a new set of inventory folders for the given user.
/// </summary>
/// <param name="user"></param>
public void CreateNewUserInventory(LLUUID user)
{
InventoryFolderBase existingRootFolder = RequestUsersRoot(user);
if (null != existingRootFolder)
{
MainLog.Instance.Error(
"AGENTINVENTORY",
"Did not create a new inventory for user {0} since they already have "
+ "a root inventory folder with id {1}", user, existingRootFolder);
}
else
{
UsersInventory inven = new UsersInventory();
inven.CreateNewInventorySet(user);
AddNewInventorySet(inven);
}
}
public class UsersInventory
{ {
public Dictionary<LLUUID, InventoryFolderBase> Folders = new Dictionary<LLUUID, InventoryFolderBase>(); public Dictionary<LLUUID, InventoryFolderBase> Folders = new Dictionary<LLUUID, InventoryFolderBase>();
public Dictionary<LLUUID, InventoryItemBase> Items = new Dictionary<LLUUID, InventoryItemBase>(); public Dictionary<LLUUID, InventoryItemBase> Items = new Dictionary<LLUUID, InventoryItemBase>();
public UsersInventory()
{
}
public virtual void CreateNewInventorySet(LLUUID user) public virtual void CreateNewInventorySet(LLUUID user)
{ {
InventoryFolderBase folder = new InventoryFolderBase(); InventoryFolderBase folder = new InventoryFolderBase();
folder.parentID = LLUUID.Zero; folder.parentID = LLUUID.Zero;
folder.agentID = user; folder.agentID = user;
folder.folderID = LLUUID.Random(); folder.folderID = LLUUID.Random();
@ -378,13 +385,5 @@ namespace OpenSim.Framework.Communications
Folders.Add(folder.folderID, folder); Folders.Add(folder.folderID, folder);
} }
} }
public abstract void RequestInventoryForUser(LLUUID userID, InventoryFolderInfo folderCallBack,
InventoryItemInfo itemCallBack);
public abstract void AddNewInventoryFolder(LLUUID userID, InventoryFolderBase folder);
public abstract void MoveExistingInventoryFolder(InventoryFolderBase folder);
public abstract void AddNewInventoryItem(LLUUID userID, InventoryItemBase item);
public abstract void DeleteInventoryItem(LLUUID userID, InventoryItemBase item);
} }
} }

View File

@ -13,7 +13,7 @@
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS AS IS AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
@ -42,6 +42,8 @@ namespace OpenSim.Framework.UserManagement
/// </summary> /// </summary>
public class LoginResponse public class LoginResponse
{ {
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private Hashtable loginFlagsHash; private Hashtable loginFlagsHash;
private Hashtable globalTexturesHash; private Hashtable globalTexturesHash;
private Hashtable loginError; private Hashtable loginError;
@ -130,7 +132,7 @@ namespace OpenSim.Framework.UserManagement
defaultXmlRpcResponse = new XmlRpcResponse(); defaultXmlRpcResponse = new XmlRpcResponse();
SetDefaultValues(); SetDefaultValues();
} // LoginServer }
public void SetDefaultValues() public void SetDefaultValues()
{ {
@ -152,8 +154,8 @@ namespace OpenSim.Framework.UserManagement
ErrorMessage = "You have entered an invalid name/password combination. Check Caps/lock."; ErrorMessage = "You have entered an invalid name/password combination. Check Caps/lock.";
ErrorReason = "key"; ErrorReason = "key";
welcomeMessage = "Welcome to OpenSim!"; welcomeMessage = "Welcome to OpenSim!";
seedCapability = ""; seedCapability = String.Empty;
home = "{'region_handle':[r" + (1000*256).ToString() + ",r" + (1000*256).ToString() + "], 'position':[r" + home = "{'region_handle':[r" + (1000*Constants.RegionSize).ToString() + ",r" + (1000*Constants.RegionSize).ToString() + "], 'position':[r" +
userProfile.homepos.X.ToString() + ",r" + userProfile.homepos.Y.ToString() + ",r" + userProfile.homepos.X.ToString() + ",r" + userProfile.homepos.Y.ToString() + ",r" +
userProfile.homepos.Z.ToString() + "], 'look_at':[r" + userProfile.homelookat.X.ToString() + ",r" + userProfile.homepos.Z.ToString() + "], 'look_at':[r" + userProfile.homelookat.X.ToString() + ",r" +
userProfile.homelookat.Y.ToString() + ",r" + userProfile.homelookat.Z.ToString() + "]}"; userProfile.homelookat.Y.ToString() + ",r" + userProfile.homelookat.Z.ToString() + "]}";
@ -183,7 +185,7 @@ namespace OpenSim.Framework.UserManagement
InitialOutfitHash["folder_name"] = "Nightclub Female"; InitialOutfitHash["folder_name"] = "Nightclub Female";
InitialOutfitHash["gender"] = "female"; InitialOutfitHash["gender"] = "female";
initialOutfit.Add(InitialOutfitHash); initialOutfit.Add(InitialOutfitHash);
} // SetDefaultValues }
#region Login Failure Methods #region Login Failure Methods
@ -201,7 +203,7 @@ namespace OpenSim.Framework.UserManagement
loginError["login"] = login; loginError["login"] = login;
xmlRpcResponse.Value = loginError; xmlRpcResponse.Value = loginError;
return (xmlRpcResponse); return (xmlRpcResponse);
} // GenerateResponse }
public LLSD GenerateFailureResponseLLSD(string reason, string message, string login) public LLSD GenerateFailureResponseLLSD(string reason, string message, string login)
{ {
@ -221,7 +223,7 @@ namespace OpenSim.Framework.UserManagement
public XmlRpcResponse CreateFailedResponse() public XmlRpcResponse CreateFailedResponse()
{ {
return (CreateLoginFailedResponse()); return (CreateLoginFailedResponse());
} // CreateErrorConnectingToGridResponse() }
public LLSD CreateFailedResponseLLSD() public LLSD CreateFailedResponseLLSD()
{ {
@ -234,7 +236,7 @@ namespace OpenSim.Framework.UserManagement
(GenerateFailureResponse("key", (GenerateFailureResponse("key",
"Could not authenticate your avatar. Please check your username and password, and check the grid if problems persist.", "Could not authenticate your avatar. Please check your username and password, and check the grid if problems persist.",
"false")); "false"));
} // LoginFailedResponse }
public LLSD CreateLoginFailedResponseLLSD() public LLSD CreateLoginFailedResponseLLSD()
{ {
@ -250,7 +252,7 @@ namespace OpenSim.Framework.UserManagement
(GenerateFailureResponse("presence", (GenerateFailureResponse("presence",
"You appear to be already logged in, if this is not the case please wait for your session to timeout, if this takes longer than a few minutes please contact the grid owner", "You appear to be already logged in, if this is not the case please wait for your session to timeout, if this takes longer than a few minutes please contact the grid owner",
"false")); "false"));
} // CreateAlreadyLoggedInResponse() }
public LLSD CreateAlreadyLoggedInResponseLLSD() public LLSD CreateAlreadyLoggedInResponseLLSD()
{ {
@ -350,8 +352,8 @@ namespace OpenSim.Framework.UserManagement
responseData["home"] = home; responseData["home"] = home;
responseData["look_at"] = lookAt; responseData["look_at"] = lookAt;
responseData["message"] = welcomeMessage; responseData["message"] = welcomeMessage;
responseData["region_x"] = (Int32) RegionX*256; responseData["region_x"] = (Int32)(RegionX * Constants.RegionSize);
responseData["region_y"] = (Int32) RegionY*256; responseData["region_y"] = (Int32)(RegionY * Constants.RegionSize);
responseData["version"] = clientVersion; //rex responseData["version"] = clientVersion; //rex
@ -369,13 +371,11 @@ namespace OpenSim.Framework.UserManagement
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Warn( m_log.Warn("[CLIENT]: LoginResponse: Error creating XML-RPC Response: " + e.Message);
"CLIENT",
"LoginResponse: Error creating XML-RPC Response: " + e.Message
);
return (GenerateFailureResponse("Internal Error", "Error generating Login Response", "false")); return (GenerateFailureResponse("Internal Error", "Error generating Login Response", "false"));
} }
} // ToXmlRpcResponse }
public LLSD ToLLSDResponse() public LLSD ToLLSDResponse()
{ {
@ -454,8 +454,8 @@ namespace OpenSim.Framework.UserManagement
map["home"] = LLSD.FromString(home); map["home"] = LLSD.FromString(home);
map["look_at"] = LLSD.FromString(lookAt); map["look_at"] = LLSD.FromString(lookAt);
map["message"] = LLSD.FromString(welcomeMessage); map["message"] = LLSD.FromString(welcomeMessage);
map["region_x"] = LLSD.FromInteger(RegionX * 256); map["region_x"] = LLSD.FromInteger(RegionX * Constants.RegionSize);
map["region_y"] = LLSD.FromInteger(RegionY * 256); map["region_y"] = LLSD.FromInteger(RegionY * Constants.RegionSize);
map["version"] = LLSD.FromString(clientVersion); //rex map["version"] = LLSD.FromString(clientVersion); //rex
@ -470,10 +470,8 @@ namespace OpenSim.Framework.UserManagement
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Warn( m_log.Warn("[CLIENT]: LoginResponse: Error creating XML-RPC Response: " + e.Message);
"CLIENT",
"LoginResponse: Error creating XML-RPC Response: " + e.Message
);
return GenerateFailureResponseLLSD("Internal Error", "Error generating Login Response", "false"); return GenerateFailureResponseLLSD("Internal Error", "Error generating Login Response", "false");
} }
} }
@ -489,12 +487,12 @@ namespace OpenSim.Framework.UserManagement
{ {
// this.eventCategoriesHash[category] = value; // this.eventCategoriesHash[category] = value;
//TODO //TODO
} // SetEventCategories }
public void AddToUIConfig(string itemName, string item) public void AddToUIConfig(string itemName, string item)
{ {
uiConfigHash[itemName] = item; uiConfigHash[itemName] = item;
} // SetUIConfig }
public void AddClassifiedCategory(Int32 ID, string categoryName) public void AddClassifiedCategory(Int32 ID, string categoryName)
{ {
@ -503,7 +501,7 @@ namespace OpenSim.Framework.UserManagement
hash["category_id"] = ID; hash["category_id"] = ID;
classifiedCategories.Add(hash); classifiedCategories.Add(hash);
// this.classifiedCategoriesHash.Clear(); // this.classifiedCategoriesHash.Clear();
} // SetClassifiedCategory }
#region Properties #region Properties
@ -511,109 +509,109 @@ namespace OpenSim.Framework.UserManagement
{ {
get { return login; } get { return login; }
set { login = value; } set { login = value; }
} // Login }
public string DST public string DST
{ {
get { return dst; } get { return dst; }
set { dst = value; } set { dst = value; }
} // DST }
public string StipendSinceLogin public string StipendSinceLogin
{ {
get { return stipendSinceLogin; } get { return stipendSinceLogin; }
set { stipendSinceLogin = value; } set { stipendSinceLogin = value; }
} // StipendSinceLogin }
public string Gendered public string Gendered
{ {
get { return gendered; } get { return gendered; }
set { gendered = value; } set { gendered = value; }
} // Gendered }
public string EverLoggedIn public string EverLoggedIn
{ {
get { return everLoggedIn; } get { return everLoggedIn; }
set { everLoggedIn = value; } set { everLoggedIn = value; }
} // EverLoggedIn }
public uint SimPort public uint SimPort
{ {
get { return simPort; } get { return simPort; }
set { simPort = value; } set { simPort = value; }
} // SimPort }
public string SimAddress public string SimAddress
{ {
get { return simAddress; } get { return simAddress; }
set { simAddress = value; } set { simAddress = value; }
} // SimAddress }
public LLUUID AgentID public LLUUID AgentID
{ {
get { return agentID; } get { return agentID; }
set { agentID = value; } set { agentID = value; }
} // AgentID }
public LLUUID SessionID public LLUUID SessionID
{ {
get { return sessionID; } get { return sessionID; }
set { sessionID = value; } set { sessionID = value; }
} // SessionID }
public LLUUID SecureSessionID public LLUUID SecureSessionID
{ {
get { return secureSessionID; } get { return secureSessionID; }
set { secureSessionID = value; } set { secureSessionID = value; }
} // SecureSessionID }
public Int32 CircuitCode public Int32 CircuitCode
{ {
get { return circuitCode; } get { return circuitCode; }
set { circuitCode = value; } set { circuitCode = value; }
} // CircuitCode }
public uint RegionX public uint RegionX
{ {
get { return regionX; } get { return regionX; }
set { regionX = value; } set { regionX = value; }
} // RegionX }
public uint RegionY public uint RegionY
{ {
get { return regionY; } get { return regionY; }
set { regionY = value; } set { regionY = value; }
} // RegionY }
public string SunTexture public string SunTexture
{ {
get { return sunTexture; } get { return sunTexture; }
set { sunTexture = value; } set { sunTexture = value; }
} // SunTexture }
public string CloudTexture public string CloudTexture
{ {
get { return cloudTexture; } get { return cloudTexture; }
set { cloudTexture = value; } set { cloudTexture = value; }
} // CloudTexture }
public string MoonTexture public string MoonTexture
{ {
get { return moonTexture; } get { return moonTexture; }
set { moonTexture = value; } set { moonTexture = value; }
} // MoonTexture }
public string Firstname public string Firstname
{ {
get { return firstname; } get { return firstname; }
set { firstname = value; } set { firstname = value; }
} // Firstname }
public string Lastname public string Lastname
{ {
get { return lastname; } get { return lastname; }
set { lastname = value; } set { lastname = value; }
} // Lastname }
public string ClientVersion public string ClientVersion
{ {
@ -631,7 +629,7 @@ namespace OpenSim.Framework.UserManagement
{ {
get { return startLocation; } get { return startLocation; }
set { startLocation = value; } set { startLocation = value; }
} // StartLocation }
public string LookAt public string LookAt
{ {
@ -643,19 +641,19 @@ namespace OpenSim.Framework.UserManagement
{ {
get { return seedCapability; } get { return seedCapability; }
set { seedCapability = value; } set { seedCapability = value; }
} // SeedCapability }
public string ErrorReason public string ErrorReason
{ {
get { return errorReason; } get { return errorReason; }
set { errorReason = value; } set { errorReason = value; }
} // ErrorReason }
public string ErrorMessage public string ErrorMessage
{ {
get { return errorMessage; } get { return errorMessage; }
set { errorMessage = value; } set { errorMessage = value; }
} // ErrorMessage }
public ArrayList InventoryRoot public ArrayList InventoryRoot
{ {

View File

@ -13,7 +13,7 @@
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS AS IS AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
@ -29,6 +29,8 @@
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading; using System.Threading;
using libsecondlife; using libsecondlife;
using libsecondlife.StructuredData; using libsecondlife.StructuredData;
@ -36,11 +38,14 @@ using Nwc.XmlRpc;
using OpenSim.Framework.Communications.Cache; using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Console; using OpenSim.Framework.Console;
using OpenSim.Framework.Statistics;
namespace OpenSim.Framework.UserManagement namespace OpenSim.Framework.UserManagement
{ {
public class LoginService public class LoginService
{ {
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
protected string m_welcomeMessage = "Welcome to OpenSim"; protected string m_welcomeMessage = "Welcome to OpenSim";
protected UserManagerBase m_userManager = null; protected UserManagerBase m_userManager = null;
protected Mutex m_loginMutex = new Mutex(false); protected Mutex m_loginMutex = new Mutex(false);
@ -63,7 +68,7 @@ namespace OpenSim.Framework.UserManagement
if (m_rexMode) if (m_rexMode)
m_rexLoginHandler = new RexLoginHandler(this, m_userManager); m_rexLoginHandler = new RexLoginHandler(this, m_userManager);
if (welcomeMess != "") if (welcomeMess != String.Empty)
{ {
m_welcomeMessage = welcomeMess; m_welcomeMessage = welcomeMess;
} }
@ -80,55 +85,67 @@ namespace OpenSim.Framework.UserManagement
m_loginMutex.WaitOne(); m_loginMutex.WaitOne();
try try
{ {
if (!m_rexMode) //CFK: CustomizeResponse contains sufficient strings to alleviate the need for this.
{ //CKF: m_log.Info("[LOGIN]: Attempting login now...");
//CFK: CustomizeResponse contains sufficient strings to alleviate the need for this. XmlRpcResponse response = new XmlRpcResponse();
//CKF: MainLog.Instance.Verbose("LOGIN", "Attempting login now..."); Hashtable requestData = (Hashtable) request.Params[0];
XmlRpcResponse response = new XmlRpcResponse();
Hashtable requestData = (Hashtable) request.Params[0];
bool GoodXML = (requestData.Contains("first") && requestData.Contains("last") && bool GoodXML = (requestData.Contains("first") && requestData.Contains("last") &&
requestData.Contains("passwd")); (requestData.Contains("passwd") || requestData.Contains("web_login_key")));
bool GoodLogin = false; bool GoodLogin = false;
UserProfileData userProfile; UserProfileData userProfile;
LoginResponse logResponse = new LoginResponse(); LoginResponse logResponse = new LoginResponse();
if (GoodXML) if (GoodXML)
{
string firstname = (string) requestData["first"];
string lastname = (string) requestData["last"];
if( requestData.Contains("version"))
{ {
string firstname = (string) requestData["first"]; string clientversion = (string)requestData["version"];
string lastname = (string) requestData["last"]; m_log.Info("[LOGIN]: Client Version " + clientversion + " for " + firstname + " " + lastname);
string passwd = (string) requestData["passwd"];
userProfile = GetTheUser(firstname, lastname, "");
if (userProfile == null)
{
MainLog.Instance.Verbose(
"LOGIN",
"Could not find a profile for " + firstname + " " + lastname);
return logResponse.CreateLoginFailedResponse();
}
GoodLogin = AuthenticateUser(userProfile, passwd);
} }
else
userProfile = GetTheUser(firstname, lastname);
if (userProfile == null)
{ {
return logResponse.CreateGridErrorResponse(); m_log.Info("[LOGIN]: Could not find a profile for " + firstname + " " + lastname);
}
if (!GoodLogin) if (!GoodLogin)
{ {
return logResponse.CreateLoginFailedResponse(); return logResponse.CreateLoginFailedResponse();
} }
if (requestData.Contains("passwd"))
{
string passwd = (string)requestData["passwd"];
GoodLogin = AuthenticateUser(userProfile, passwd);
}
else if (requestData.Contains("web_login_key"))
{
LLUUID webloginkey = null;
try
{
webloginkey = new LLUUID((string)requestData["web_login_key"]);
}
catch (System.Exception)
{
return logResponse.CreateFailedResponse();
}
GoodLogin = AuthenticateUser(userProfile, webloginkey);
}
else else
{ {
// If we already have a session... return logResponse.CreateFailedResponse();
}
if (userProfile.currentAgent != null && userProfile.currentAgent.agentOnline) }
{ else
userProfile.currentAgent = null; {
m_userManager.CommitAgent(ref userProfile); return logResponse.CreateGridErrorResponse();
}
// Reject the login // Reject the login
return logResponse.CreateAlreadyLoggedInResponse(); return logResponse.CreateAlreadyLoggedInResponse();
@ -204,9 +221,25 @@ namespace OpenSim.Framework.UserManagement
{ {
MainLog.Instance.Verbose("LOGIN", E.ToString()); MainLog.Instance.Verbose("LOGIN", E.ToString());
} }
//} catch (Exception e)
{
m_log.Info("[LOGIN]: " + e.ToString());
return logResponse.CreateDeadRegionResponse();
//return logResponse.ToXmlRpcResponse();
}
CommitAgent(ref userProfile);
// If we reach this point, then the login has successfully logged onto the grid
if (StatsManager.UserStats != null)
StatsManager.UserStats.AddSuccessfulLogin();
return logResponse.ToXmlRpcResponse();
} }
return response; catch (Exception e)
{
m_log.Info("[LOGIN]: " + e.ToString());
}
//}
} }
else else
{ {
@ -241,9 +274,7 @@ namespace OpenSim.Framework.UserManagement
if (map.ContainsKey("first") && map.ContainsKey("last") && map.ContainsKey("passwd")) if (map.ContainsKey("first") && map.ContainsKey("last") && map.ContainsKey("passwd"))
{ {
string firstname = map["first"].AsString(); m_log.Info("[LOGIN]: Could not find a profile for " + firstname + " " + lastname);
string lastname = map["last"].AsString();
string passwd = map["passwd"].AsString();
//REX: Client version //REX: Client version
if (map.ContainsKey("version")) if (map.ContainsKey("version"))
@ -347,7 +378,7 @@ namespace OpenSim.Framework.UserManagement
} }
catch (Exception ex) catch (Exception ex)
{ {
MainLog.Instance.Verbose("LOGIN", ex.ToString()); m_log.Info("[LOGIN]: " + ex.ToString());
return logResponse.CreateFailedResponseLLSD(); return logResponse.CreateFailedResponseLLSD();
} }
} }
@ -364,6 +395,10 @@ namespace OpenSim.Framework.UserManagement
} }
} }
// If we reach this point, then the login has successfully logged onto the grid
if (StatsManager.UserStats != null)
StatsManager.UserStats.AddSuccessfulLogin();
/* /*
/// <summary> /// <summary>
/// Remove agent /// Remove agent
@ -398,10 +433,8 @@ namespace OpenSim.Framework.UserManagement
if (user != null) if (user != null)
{ {
ClearUserAgent(ref user, user.authenticationAddr); m_log.Info("[LOGIN]: " + ex.ToString());
MainLog.Instance.Verbose("REMOVE AGENT", "Success. Agent removed from database. UUID = " + user.UUID); return logResponse.CreateFailedResponseLLSD();
return logResponse.GenerateAgentRemoveSuccessResponse();
} }
} }
@ -434,6 +467,211 @@ namespace OpenSim.Framework.UserManagement
{ {
} }
public Hashtable ProcessHTMLLogin(Hashtable keysvals)
{
// Matches all unspecified characters
// Currently specified,; lowercase letters, upper case letters, numbers, underline
// period, space, parens, and dash.
Regex wfcut = new Regex("[^a-zA-Z0-9_\\.\\$ \\(\\)\\-]");
Hashtable returnactions = new Hashtable();
int statuscode = 200;
string firstname = String.Empty;
string lastname = String.Empty;
string location = String.Empty;
string region =String.Empty;
string grid = String.Empty;
string channel = String.Empty;
string version = String.Empty;
string lang = String.Empty;
string password = String.Empty;
string errormessages = String.Empty;
// the client requires the HTML form field be named 'username'
// however, the data it sends when it loads the first time is 'firstname'
// another one of those little nuances.
if (keysvals.Contains("firstname"))
firstname = wfcut.Replace((string)keysvals["firstname"],String.Empty,99999);
if (keysvals.Contains("username"))
firstname = wfcut.Replace((string)keysvals["username"],String.Empty,99999);
if (keysvals.Contains("lastname"))
lastname = wfcut.Replace((string)keysvals["lastname"],String.Empty,99999);
if (keysvals.Contains("location"))
location = wfcut.Replace((string)keysvals["location"],String.Empty,99999);
if (keysvals.Contains("region"))
region = wfcut.Replace((string)keysvals["region"],String.Empty,99999);
if (keysvals.Contains("grid"))
grid = wfcut.Replace((string)keysvals["grid"],String.Empty,99999);
if (keysvals.Contains("channel"))
channel = wfcut.Replace((string)keysvals["channel"],String.Empty,99999);
if (keysvals.Contains("version"))
version = wfcut.Replace((string)keysvals["version"],String.Empty,99999);
if (keysvals.Contains("lang"))
lang = wfcut.Replace((string)keysvals["lang"],String.Empty,99999);
if (keysvals.Contains("password"))
password = wfcut.Replace((string)keysvals["password"], String.Empty, 99999);
// load our login form.
string loginform = GetLoginForm(firstname,lastname,location,region,grid,channel,version,lang,password,errormessages);
if (keysvals.ContainsKey("show_login_form"))
{
UserProfileData user = GetTheUser(firstname, lastname);
bool goodweblogin = false;
if (user != null)
goodweblogin = AuthenticateUser(user, password);
if (goodweblogin)
{
LLUUID webloginkey = LLUUID.Random();
m_userManager.StoreWebLoginKey(user.UUID, webloginkey);
statuscode = 301;
string redirectURL = "about:blank?redirect-http-hack=" + System.Web.HttpUtility.UrlEncode("secondlife:///app/login?first_name=" + firstname + "&last_name=" +
lastname +
"&location=" + location + "&grid=Other&web_login_key=" + webloginkey.ToString());
//m_log.Info("[WEB]: R:" + redirectURL);
returnactions["int_response_code"] = statuscode;
returnactions["str_redirect_location"] = redirectURL;
returnactions["str_response_string"] = "<HTML><BODY>GoodLogin</BODY></HTML>";
}
else
{
errormessages = "The Username and password supplied did not match our records. Check your caps lock and try again";
loginform = GetLoginForm(firstname, lastname, location, region, grid, channel, version, lang, password, errormessages);
returnactions["int_response_code"] = statuscode;
returnactions["str_response_string"] = loginform;
}
}
else
{
returnactions["int_response_code"] = statuscode;
returnactions["str_response_string"] = loginform;
}
return returnactions;
}
public string GetLoginForm(string firstname, string lastname, string location, string region,
string grid, string channel, string version, string lang,
string password, string errormessages)
{
// inject our values in the form at the markers
string loginform=String.Empty;
string file = Path.Combine(Util.configDir(), "http_loginform.html");
if (!File.Exists(file))
{
loginform = GetDefaultLoginForm();
}
else
{
StreamReader sr = File.OpenText(file);
loginform = sr.ReadToEnd();
sr.Close();
}
loginform = loginform.Replace("[$firstname]", firstname);
loginform = loginform.Replace("[$lastname]", lastname);
loginform = loginform.Replace("[$location]", location);
loginform = loginform.Replace("[$region]", region);
loginform = loginform.Replace("[$grid]", grid);
loginform = loginform.Replace("[$channel]", channel);
loginform = loginform.Replace("[$version]", version);
loginform = loginform.Replace("[$lang]", lang);
loginform = loginform.Replace("[$password]", password);
loginform = loginform.Replace("[$errors]", errormessages);
return loginform;
}
public string GetDefaultLoginForm()
{
string responseString =
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
responseString = responseString + "<html xmlns=\"http://www.w3.org/1999/xhtml\">";
responseString = responseString + "<head>";
responseString = responseString +
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />";
responseString = responseString + "<meta http-equiv=\"cache-control\" content=\"no-cache\">";
responseString = responseString + "<meta http-equiv=\"Pragma\" content=\"no-cache\">";
responseString = responseString + "<title>OpenSim Login</title>";
responseString = responseString + "<body><br />";
responseString = responseString + "<div id=\"login_box\">";
responseString = responseString + "<form action=\"/go.cgi\" method=\"GET\" id=\"login-form\">";
responseString = responseString + "<div id=\"message\">[$errors]</div>";
responseString = responseString + "<fieldset id=\"firstname\">";
responseString = responseString + "<legend>First Name:</legend>";
responseString = responseString + "<input type=\"text\" id=\"firstname_input\" size=\"15\" maxlength=\"100\" name=\"username\" value=\"[$firstname]\" />";
responseString = responseString + "</fieldset>";
responseString = responseString + "<fieldset id=\"lastname\">";
responseString = responseString + "<legend>Last Name:</legend>";
responseString = responseString + "<input type=\"text\" size=\"15\" maxlength=\"100\" name=\"lastname\" value=\"[$lastname]\" />";
responseString = responseString + "</fieldset>";
responseString = responseString + "<fieldset id=\"password\">";
responseString = responseString + "<legend>Password:</legend>";
responseString = responseString + "<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">";
responseString = responseString + "<tr>";
responseString = responseString + "<td colspan=\"2\"><input type=\"password\" size=\"15\" maxlength=\"100\" name=\"password\" value=\"[$password]\" /></td>";
responseString = responseString + "</tr>";
responseString = responseString + "<tr>";
responseString = responseString + "<td valign=\"middle\"><input type=\"checkbox\" name=\"remember_password\" id=\"remember_password\" [$remember_password] style=\"margin-left:0px;\"/></td>";
responseString = responseString + "<td><label for=\"remember_password\">Remember password</label></td>";
responseString = responseString + "</tr>";
responseString = responseString + "</table>";
responseString = responseString + "</fieldset>";
responseString = responseString + "<input type=\"hidden\" name=\"show_login_form\" value=\"FALSE\" />";
responseString = responseString + "<input type=\"hidden\" name=\"method\" value=\"login\" />";
responseString = responseString + "<input type=\"hidden\" id=\"grid\" name=\"grid\" value=\"[$grid]\" />";
responseString = responseString + "<input type=\"hidden\" id=\"region\" name=\"region\" value=\"[$region]\" />";
responseString = responseString + "<input type=\"hidden\" id=\"location\" name=\"location\" value=\"[$location]\" />";
responseString = responseString + "<input type=\"hidden\" id=\"channel\" name=\"channel\" value=\"[$channel]\" />";
responseString = responseString + "<input type=\"hidden\" id=\"version\" name=\"version\" value=\"[$version]\" />";
responseString = responseString + "<input type=\"hidden\" id=\"lang\" name=\"lang\" value=\"[$lang]\" />";
responseString = responseString + "<div id=\"submitbtn\">";
responseString = responseString + "<input class=\"input_over\" type=\"submit\" value=\"Connect\" />";
responseString = responseString + "</div>";
responseString = responseString + "<div id=\"connecting\" style=\"visibility:hidden\"> Connecting...</div>";
responseString = responseString + "<div id=\"helplinks\">";
responseString = responseString + "<a href=\"#join now link\" target=\"_blank\"></a> | ";
responseString = responseString + "<a href=\"#forgot password link\" target=\"_blank\"></a>";
responseString = responseString + "</div>";
responseString = responseString + "<div id=\"channelinfo\"> [$channel] | [$version]=[$lang]</div>";
responseString = responseString + "</form>";
responseString = responseString + "<script language=\"JavaScript\">";
responseString = responseString + "document.getElementById('firstname_input').focus();";
responseString = responseString + "</script>";
responseString = responseString + "</div>";
responseString = responseString + "</div>";
responseString = responseString + "</body>";
responseString = responseString + "</html>";
return responseString;
}
/// <summary> /// <summary>
/// Saves a target agent to the database /// Saves a target agent to the database
/// </summary> /// </summary>
@ -466,14 +704,38 @@ namespace OpenSim.Framework.UserManagement
/// <returns>Authenticated?</returns> /// <returns>Authenticated?</returns>
public virtual bool AuthenticateUser(UserProfileData profile, string password) public virtual bool AuthenticateUser(UserProfileData profile, string password)
{ {
MainLog.Instance.Verbose( bool passwordSuccess = false;
"LOGIN", "Authenticating {0} {1} ({2})", profile.username, profile.surname, profile.UUID); m_log.InfoFormat("[LOGIN]: Authenticating {0} {1} ({2})", profile.username, profile.surname, profile.UUID);
// Web Login method seems to also occasionally send the hashed password itself
// we do this to get our hash in a form that the server password code can consume
// when the web-login-form submits the password in the clear (supposed to be over SSL!)
if (!password.StartsWith("$1$"))
password = "$1$" + Util.Md5Hash(password);
password = password.Remove(0, 3); //remove $1$ password = password.Remove(0, 3); //remove $1$
string s = Util.Md5Hash(password + ":" + profile.passwordSalt); string s = Util.Md5Hash(password + ":" + profile.passwordSalt);
// Testing...
//m_log.Info("[LOGIN]: SubHash:" + s + " userprofile:" + profile.passwordHash);
//m_log.Info("[LOGIN]: userprofile:" + profile.passwordHash + " SubCT:" + password);
return profile.passwordHash.Equals(s.ToString(), StringComparison.InvariantCultureIgnoreCase); passwordSuccess = (profile.passwordHash.Equals(s.ToString(), StringComparison.InvariantCultureIgnoreCase)
|| profile.passwordHash.Equals(password,StringComparison.InvariantCultureIgnoreCase));
return passwordSuccess;
}
public virtual bool AuthenticateUser(UserProfileData profile, LLUUID webloginkey)
{
bool passwordSuccess = false;
m_log.InfoFormat("[LOGIN]: Authenticating {0} {1} ({2})", profile.username, profile.surname, profile.UUID);
// Match web login key unless it's the default weblogin key LLUUID.Zero
passwordSuccess = ((profile.webLoginKey==webloginkey) && profile.webLoginKey != LLUUID.Zero);
return passwordSuccess;
} }
/// <summary> /// <summary>

View File

@ -37,7 +37,7 @@ using System.Runtime.InteropServices;
[assembly : AssemblyConfiguration("")] [assembly : AssemblyConfiguration("")]
[assembly : AssemblyCompany("")] [assembly : AssemblyCompany("")]
[assembly : AssemblyProduct("OpenGrid.Framework.Communications")] [assembly : AssemblyProduct("OpenGrid.Framework.Communications")]
[assembly : AssemblyCopyright("Copyright © 2007")] [assembly : AssemblyCopyright("Copyright © OpenSimulator.org Developers 2007-2008")]
[assembly : AssemblyTrademark("")] [assembly : AssemblyTrademark("")]
[assembly : AssemblyCulture("")] [assembly : AssemblyCulture("")]

View File

@ -56,6 +56,8 @@ namespace OpenSim.Framework.Communications
/// </remarks> /// </remarks>
public class RestClient public class RestClient
{ {
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private string realuri; private string realuri;
#region member variables #region member variables
@ -201,7 +203,7 @@ namespace OpenSim.Framework.Communications
/// <returns>slash '/' if not already present</returns> /// <returns>slash '/' if not already present</returns>
private string slash(string s) private string slash(string s)
{ {
return isSlashed(s) ? "" : "/"; return isSlashed(s) ? String.Empty : "/";
} }
/// <summary> /// <summary>
@ -238,7 +240,7 @@ namespace OpenSim.Framework.Communications
} }
} }
realuri = sb.ToString(); realuri = sb.ToString();
MainLog.Instance.Verbose("REST", "RestURL: {0}", realuri); m_log.InfoFormat("[REST]: RestURL: {0}", realuri);
return new Uri(sb.ToString()); return new Uri(sb.ToString());
} }
@ -374,21 +376,22 @@ namespace OpenSim.Framework.Communications
_asyncException = null; _asyncException = null;
_request.ContentLength = src.Length; _request.ContentLength = src.Length;
MainLog.Instance.Verbose("REST", "Request Length {0}", _request.ContentLength); m_log.InfoFormat("[REST]: Request Length {0}", _request.ContentLength);
MainLog.Instance.Verbose("REST", "Sending Web Request {0}", buildUri()); m_log.InfoFormat("[REST]: Sending Web Request {0}", buildUri());
src.Seek(0, SeekOrigin.Begin); src.Seek(0, SeekOrigin.Begin);
MainLog.Instance.Verbose("REST", "Seek is ok"); m_log.Info("[REST]: Seek is ok");
Stream dst = _request.GetRequestStream(); Stream dst = _request.GetRequestStream();
MainLog.Instance.Verbose("REST", "GetRequestStream is ok"); m_log.Info("[REST]: GetRequestStream is ok");
byte[] buf = new byte[1024]; byte[] buf = new byte[1024];
int length = src.Read(buf, 0, 1024); int length = src.Read(buf, 0, 1024);
MainLog.Instance.Verbose("REST", "First Read is ok"); m_log.Info("[REST]: First Read is ok");
while (length > 0) while (length > 0)
{ {
dst.Write(buf, 0, length); dst.Write(buf, 0, length);
length = src.Read(buf, 0, 1024); length = src.Read(buf, 0, 1024);
} }
_response = (HttpWebResponse) _request.GetResponse(); _response = (HttpWebResponse) _request.GetResponse();
// IAsyncResult responseAsyncResult = _request.BeginGetResponse(new AsyncCallback(ResponseIsReadyDelegate), _request); // IAsyncResult responseAsyncResult = _request.BeginGetResponse(new AsyncCallback(ResponseIsReadyDelegate), _request);

View File

@ -34,6 +34,7 @@ using libsecondlife;
using libsecondlife.StructuredData; using libsecondlife.StructuredData;
using Nwc.XmlRpc; using Nwc.XmlRpc;
using OpenSim.Framework.Console; using OpenSim.Framework.Console;
using OpenSim.Framework.Statistics;
namespace OpenSim.Framework.UserManagement namespace OpenSim.Framework.UserManagement
{ {
@ -42,6 +43,8 @@ namespace OpenSim.Framework.UserManagement
/// </summary> /// </summary>
public abstract class UserManagerBase : IUserService public abstract class UserManagerBase : IUserService
{ {
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public UserConfig _config; public UserConfig _config;
private Dictionary<string, IUserData> _plugins = new Dictionary<string, IUserData>(); private Dictionary<string, IUserData> _plugins = new Dictionary<string, IUserData>();
public bool RexMode = false; // _config is not initiated in local mode public bool RexMode = false; // _config is not initiated in local mode
@ -54,10 +57,10 @@ namespace OpenSim.Framework.UserManagement
{ {
if (!String.IsNullOrEmpty(FileName)) if (!String.IsNullOrEmpty(FileName))
{ {
MainLog.Instance.Verbose("USERSTORAGE", "Attempting to load " + FileName); m_log.Info("[USERSTORAGE]: Attempting to load " + FileName);
Assembly pluginAssembly = Assembly.LoadFrom(FileName); Assembly pluginAssembly = Assembly.LoadFrom(FileName);
MainLog.Instance.Verbose("USERSTORAGE", "Found " + pluginAssembly.GetTypes().Length + " interfaces."); m_log.Info("[USERSTORAGE]: Found " + pluginAssembly.GetTypes().Length + " interfaces.");
foreach (Type pluginType in pluginAssembly.GetTypes()) foreach (Type pluginType in pluginAssembly.GetTypes())
{ {
if (!pluginType.IsAbstract) if (!pluginType.IsAbstract)
@ -79,16 +82,29 @@ namespace OpenSim.Framework.UserManagement
{ {
plug.Initialise(); plug.Initialise();
_plugins.Add(plug.getName(), plug); _plugins.Add(plug.getName(), plug);
MainLog.Instance.Verbose("USERSTORAGE", "Added IUserData Interface"); m_log.Info("[USERSTORAGE]: Added IUserData Interface");
} }
#region Get UserProfile #region Get UserProfile
/// <summary> // see IUserService
/// Loads a user profile from a database by UUID public UserProfileData GetUserProfile(string fname, string lname)
/// </summary> {
/// <param name="uuid">The target UUID</param> foreach (KeyValuePair<string, IUserData> plugin in _plugins)
/// <returns>A user profile. Returns null if no user profile is found.</returns> {
UserProfileData profile = plugin.Value.GetUserByName(fname, lname);
if (profile != null)
{
profile.currentAgent = getUserAgent(profile.UUID);
return profile;
}
}
return null;
}
// see IUserService
public UserProfileData GetUserProfile(LLUUID uuid, string authAddr) public UserProfileData GetUserProfile(LLUUID uuid, string authAddr)
{ {
if (!RexMode) if (!RexMode)
@ -180,8 +196,7 @@ namespace OpenSim.Framework.UserManagement
} }
catch (Exception) catch (Exception)
{ {
MainLog.Instance.Verbose("USERSTORAGE", m_log.Info("[USERSTORAGE]: Unable to generate AgentPickerData via " + plugin.Key + "(" + query + ")");
"Unable to generate AgentPickerData via " + plugin.Key + "(" + query + ")");
return new List<AvatarPickerAvatar>(); return new List<AvatarPickerAvatar>();
} }
} }
@ -262,8 +277,7 @@ namespace OpenSim.Framework.UserManagement
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Verbose("USERSTORAGE", m_log.Info("[USERSTORAGE]: Unable to set user via " + plugin.Key + "(" + e.ToString() + ")");
"Unable to set user via " + plugin.Key + "(" + e.ToString() + ")");
} }
} }
@ -289,8 +303,7 @@ namespace OpenSim.Framework.UserManagement
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Verbose("USERSTORAGE", m_log.Info("[USERSTORAGE]: Unable to find user via " + plugin.Key + "(" + e.ToString() + ")");
"Unable to find user via " + plugin.Key + "(" + e.ToString() + ")");
} }
} }
@ -313,8 +326,7 @@ namespace OpenSim.Framework.UserManagement
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Verbose("USERSTORAGE", m_log.Info("[USERSTORAGE]: Unable to GetUserFriendList via " + plugin.Key + "(" + e.ToString() + ")");
"Unable to GetUserFriendList via " + plugin.Key + "(" + e.ToString() + ")");
} }
} }
@ -322,6 +334,22 @@ namespace OpenSim.Framework.UserManagement
} }
public void StoreWebLoginKey(LLUUID agentID, LLUUID webLoginKey)
{
foreach (KeyValuePair<string, IUserData> plugin in _plugins)
{
try
{
plugin.Value.StoreWebLoginKey(agentID, webLoginKey);
}
catch (Exception e)
{
m_log.Info("[USERSTORAGE]: Unable to Store WebLoginKey via " + plugin.Key + "(" + e.ToString() + ")");
}
}
}
public void AddNewUserFriend(LLUUID friendlistowner, LLUUID friend, uint perms) public void AddNewUserFriend(LLUUID friendlistowner, LLUUID friend, uint perms)
{ {
foreach (KeyValuePair<string, IUserData> plugin in _plugins) foreach (KeyValuePair<string, IUserData> plugin in _plugins)
@ -332,8 +360,7 @@ namespace OpenSim.Framework.UserManagement
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Verbose("USERSTORAGE", m_log.Info("[USERSTORAGE]: Unable to AddNewUserFriend via " + plugin.Key + "(" + e.ToString() + ")");
"Unable to AddNewUserFriend via " + plugin.Key + "(" + e.ToString() + ")");
} }
} }
@ -350,8 +377,7 @@ namespace OpenSim.Framework.UserManagement
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Verbose("USERSTORAGE", m_log.Info("[USERSTORAGE]: Unable to RemoveUserFriend via " + plugin.Key + "(" + e.ToString() + ")");
"Unable to RemoveUserFriend via " + plugin.Key + "(" + e.ToString() + ")");
} }
} }
} }
@ -366,8 +392,7 @@ namespace OpenSim.Framework.UserManagement
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Verbose("USERSTORAGE", m_log.Info("[USERSTORAGE]: Unable to UpdateUserFriendPerms via " + plugin.Key + "(" + e.ToString() + ")");
"Unable to UpdateUserFriendPerms via " + plugin.Key + "(" + e.ToString() + ")");
} }
} }
} }
@ -386,8 +411,7 @@ namespace OpenSim.Framework.UserManagement
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Verbose("USERSTORAGE", m_log.Info("[USERSTORAGE]: Unable to find user via " + plugin.Key + "(" + e.ToString() + ")");
"Unable to find user via " + plugin.Key + "(" + e.ToString() + ")");
} }
} }
@ -443,8 +467,7 @@ namespace OpenSim.Framework.UserManagement
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Verbose("USERSTORAGE", m_log.Info("[USERSTORAGE]: Unable to find user via " + plugin.Key + "(" + e.ToString() + ")");
"Unable to find user via " + plugin.Key + "(" + e.ToString() + ")");
} }
} }
@ -519,6 +542,63 @@ namespace OpenSim.Framework.UserManagement
profile.currentAgent = agent; profile.currentAgent = agent;
} }
/// <summary>
/// Process a user logoff from OpenSim.
/// </summary>
/// <param name="userid"></param>
/// <param name="regionid"></param>
/// <param name="regionhandle"></param>
/// <param name="posx"></param>
/// <param name="posy"></param>
/// <param name="posz"></param>
public void LogOffUser(LLUUID userid, LLUUID regionid, ulong regionhandle, float posx, float posy, float posz)
{
if (StatsManager.UserStats != null)
StatsManager.UserStats.AddLogout();
UserProfileData userProfile;
UserAgentData userAgent;
LLVector3 currentPos = new LLVector3(posx, posy, posz);
userProfile = GetUserProfile(userid);
if (userProfile != null)
{
// This line needs to be in side the above if statement or the UserServer will crash on some logouts.
m_log.Info("[LOGOUT]: " + userProfile.username + " " + userProfile.surname + " from " + regionhandle + "(" + posx + "," + posy + "," + posz + ")");
userAgent = userProfile.currentAgent;
if (userAgent != null)
{
userAgent.agentOnline = false;
userAgent.logoutTime = Util.UnixTimeSinceEpoch();
userAgent.sessionID = LLUUID.Zero;
if (regionid != null)
{
userAgent.currentRegion = regionid;
}
userAgent.currentHandle = regionhandle;
userAgent.currentPos = currentPos;
userProfile.currentAgent = userAgent;
CommitAgent(ref userProfile);
}
else
{
// If currentagent is null, we can't reference it here or the UserServer crashes!
m_log.Info("[LOGOUT]: didn't save logout position: " + userid.ToString());
}
}
else
{
m_log.Warn("[LOGOUT]: Unknown User logged out");
}
}
public void CreateAgent(UserProfileData profile, LLSD request) public void CreateAgent(UserProfileData profile, LLSD request)
{ {
UserAgentData agent = new UserAgentData(); UserAgentData agent = new UserAgentData();
@ -579,7 +659,7 @@ namespace OpenSim.Framework.UserManagement
user.username = firstName; user.username = firstName;
user.surname = lastName; user.surname = lastName;
user.passwordHash = pass; user.passwordHash = pass;
user.passwordSalt = ""; user.passwordSalt = String.Empty;
user.created = Util.UnixTimeSinceEpoch(); user.created = Util.UnixTimeSinceEpoch();
user.homeLookAt = new LLVector3(100, 100, 100); user.homeLookAt = new LLVector3(100, 100, 100);
user.homeRegionX = regX; user.homeRegionX = regX;
@ -594,8 +674,7 @@ namespace OpenSim.Framework.UserManagement
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Verbose("USERSTORAGE", m_log.Info("[USERSTORAGE]: Unable to add user via " + plugin.Key + "(" + e.ToString() + ")");
"Unable to add user via " + plugin.Key + "(" + e.ToString() + ")");
} }
} }

View File

@ -13,7 +13,7 @@
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS AS IS AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
@ -35,11 +35,13 @@ namespace OpenSim.Framework.Configuration.HTTP
{ {
public class HTTPConfiguration : IGenericConfig public class HTTPConfiguration : IGenericConfig
{ {
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private RemoteConfigSettings remoteConfigSettings; private RemoteConfigSettings remoteConfigSettings;
private XmlConfiguration xmlConfig; private XmlConfiguration xmlConfig;
private string configFileName = ""; private string configFileName = System.String.Empty;
public HTTPConfiguration() public HTTPConfiguration()
{ {
@ -81,7 +83,7 @@ namespace OpenSim.Framework.Configuration.HTTP
} }
catch (WebException) catch (WebException)
{ {
MainLog.Instance.Warn("Unable to connect to remote configuration file (" + m_log.Warn("Unable to connect to remote configuration file (" +
remoteConfigSettings.baseConfigURL + configFileName + remoteConfigSettings.baseConfigURL + configFileName +
"). Creating local file instead."); "). Creating local file instead.");
xmlConfig.SetFileName(configFileName); xmlConfig.SetFileName(configFileName);

View File

@ -13,7 +13,7 @@
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS AS IS AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
@ -32,7 +32,7 @@ namespace OpenSim.Framework.Configuration.HTTP
{ {
private ConfigurationMember configMember; private ConfigurationMember configMember;
public string baseConfigURL = ""; public string baseConfigURL = System.String.Empty;
public RemoteConfigSettings(string filename) public RemoteConfigSettings(string filename)
{ {

View File

@ -71,9 +71,9 @@ namespace OpenSim.Framework.Configuration
else else
{ {
createdFile = true; createdFile = true;
rootNode = doc.CreateNode(XmlNodeType.Element, "Root", ""); rootNode = doc.CreateNode(XmlNodeType.Element, "Root", String.Empty);
doc.AppendChild(rootNode); doc.AppendChild(rootNode);
configNode = doc.CreateNode(XmlNodeType.Element, "Config", ""); configNode = doc.CreateNode(XmlNodeType.Element, "Config", String.Empty);
rootNode.AppendChild(configNode); rootNode.AppendChild(configNode);
} }

View File

@ -13,7 +13,7 @@
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS AS IS AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
@ -39,13 +39,15 @@ namespace OpenSim.Framework
{ {
public class ConfigurationMember public class ConfigurationMember
{ {
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public delegate bool ConfigurationOptionResult(string configuration_key, object configuration_result); public delegate bool ConfigurationOptionResult(string configuration_key, object configuration_result);
public delegate void ConfigurationOptionsLoad(); public delegate void ConfigurationOptionsLoad();
private List<ConfigurationOption> configurationOptions = new List<ConfigurationOption>(); private List<ConfigurationOption> configurationOptions = new List<ConfigurationOption>();
private string configurationFilename = ""; private string configurationFilename = String.Empty;
private string configurationDescription = ""; private string configurationDescription = String.Empty;
private XmlNode configurationFromXMLNode = null; private XmlNode configurationFromXMLNode = null;
private ConfigurationOptionsLoad loadFunction; private ConfigurationOptionsLoad loadFunction;
private ConfigurationOptionResult resultFunction; private ConfigurationOptionResult resultFunction;
@ -70,7 +72,7 @@ namespace OpenSim.Framework
public ConfigurationMember(XmlNode configuration_xml, string configuration_description, public ConfigurationMember(XmlNode configuration_xml, string configuration_description,
ConfigurationOptionsLoad load_function, ConfigurationOptionResult result_function, bool use_console_to_prompt_on_error) ConfigurationOptionsLoad load_function, ConfigurationOptionResult result_function, bool use_console_to_prompt_on_error)
{ {
configurationFilename = ""; configurationFilename = String.Empty;
configurationFromXMLNode = configuration_xml; configurationFromXMLNode = configuration_xml;
configurationDescription = configuration_description; configurationDescription = configuration_description;
loadFunction = load_function; loadFunction = load_function;
@ -100,8 +102,8 @@ namespace OpenSim.Framework
private void checkAndAddConfigOption(ConfigurationOption option) private void checkAndAddConfigOption(ConfigurationOption option)
{ {
if ((option.configurationKey != "" && option.configurationQuestion != "") || if ((option.configurationKey != String.Empty && option.configurationQuestion != String.Empty) ||
(option.configurationKey != "" && option.configurationUseDefaultNoPrompt)) (option.configurationKey != String.Empty && option.configurationUseDefaultNoPrompt))
{ {
if (!configurationOptions.Contains(option)) if (!configurationOptions.Contains(option))
{ {
@ -110,7 +112,7 @@ namespace OpenSim.Framework
} }
else else
{ {
MainLog.Instance.Notice( m_log.Info(
"Required fields for adding a configuration option is invalid. Will not add this option (" + "Required fields for adding a configuration option is invalid. Will not add this option (" +
option.configurationKey + ")"); option.configurationKey + ")");
} }
@ -147,50 +149,48 @@ namespace OpenSim.Framework
checkAndAddConfigOption(configOption); checkAndAddConfigOption(configOption);
} }
// TEMP - REMOVE // TEMP - REMOVE
private int cE = 0; private int cE = 0;
public void performConfigurationRetrieve() public void performConfigurationRetrieve()
{ {
if (cE > 1) if (cE > 1)
MainLog.Instance.Error("READING CONFIGURATION COUT: " + cE.ToString()); m_log.Error("READING CONFIGURATION COUT: " + cE.ToString());
configurationPlugin = LoadConfigDll(configurationPluginFilename); configurationPlugin = LoadConfigDll(configurationPluginFilename);
configurationOptions.Clear(); configurationOptions.Clear();
if (loadFunction == null) if (loadFunction == null)
{ {
MainLog.Instance.Error("Load Function for '" + configurationDescription + m_log.Error("Load Function for '" + configurationDescription +
"' is null. Refusing to run configuration."); "' is null. Refusing to run configuration.");
return; return;
} }
if (resultFunction == null) if (resultFunction == null)
{ {
MainLog.Instance.Error("Result Function for '" + configurationDescription + m_log.Error("Result Function for '" + configurationDescription +
"' is null. Refusing to run configuration."); "' is null. Refusing to run configuration.");
return; return;
} }
MainLog.Instance.Verbose("CONFIG", "Calling Configuration Load Function..."); m_log.Info("[CONFIG]: Calling Configuration Load Function...");
loadFunction(); loadFunction();
if (configurationOptions.Count <= 0) if (configurationOptions.Count <= 0)
{ {
MainLog.Instance.Error("CONFIG", m_log.Error("[CONFIG]: No configuration options were specified for '" + configurationOptions +
"No configuration options were specified for '" + configurationOptions + "'. Refusing to continue configuration.");
"'. Refusing to continue configuration.");
return; return;
} }
bool useFile = true; bool useFile = true;
if (configurationPlugin == null) if (configurationPlugin == null)
{ {
MainLog.Instance.Error("CONFIG", "Configuration Plugin NOT LOADED!"); m_log.Error("[CONFIG]: Configuration Plugin NOT LOADED!");
return; return;
} }
if (configurationFilename.Trim() != "") if (configurationFilename.Trim() != String.Empty)
{ {
configurationPlugin.SetFileName(configurationFilename); configurationPlugin.SetFileName(configurationFilename);
try try
@ -200,7 +200,7 @@ namespace OpenSim.Framework
} }
catch (XmlException e) catch (XmlException e)
{ {
MainLog.Instance.Error("Error loading " + configurationFilename + ": " + e.ToString()); m_log.Error("Error loading " + configurationFilename + ": " + e.ToString());
useFile = false; useFile = false;
} }
} }
@ -208,11 +208,11 @@ namespace OpenSim.Framework
{ {
if (configurationFromXMLNode != null) if (configurationFromXMLNode != null)
{ {
MainLog.Instance.Notice("Loading from XML Node, will not save to the file"); m_log.Info("Loading from XML Node, will not save to the file");
configurationPlugin.LoadDataFromString(configurationFromXMLNode.OuterXml); configurationPlugin.LoadDataFromString(configurationFromXMLNode.OuterXml);
} }
MainLog.Instance.Notice("XML Configuration Filename is not valid; will not save to the file."); m_log.Info("XML Configuration Filename is not valid; will not save to the file.");
useFile = false; useFile = false;
} }
@ -220,11 +220,11 @@ namespace OpenSim.Framework
{ {
bool convertSuccess = false; bool convertSuccess = false;
object return_result = null; object return_result = null;
string errorMessage = ""; string errorMessage = String.Empty;
bool ignoreNextFromConfig = false; bool ignoreNextFromConfig = false;
while (convertSuccess == false) while (convertSuccess == false)
{ {
string console_result = ""; string console_result = String.Empty;
string attribute = null; string attribute = null;
if (useFile || configurationFromXMLNode != null) if (useFile || configurationFromXMLNode != null)
{ {
@ -250,18 +250,18 @@ namespace OpenSim.Framework
configOption.shouldIBeAsked(configOption.configurationKey)) || configOption.shouldIBeAsked(configOption.configurationKey)) ||
configOption.shouldIBeAsked == null) configOption.shouldIBeAsked == null)
{ {
if (configurationDescription.Trim() != "") if (configurationDescription.Trim() != String.Empty)
{ {
console_result = console_result =
MainLog.Instance.CmdPrompt( MainConsole.Instance.CmdPrompt(
configurationDescription + ": " + configOption.configurationQuestion, configurationDescription + ": " + configOption.configurationQuestion,
configOption.configurationDefault); configOption.configurationDefault);
} }
else else
{ {
console_result = console_result =
MainLog.Instance.CmdPrompt(configOption.configurationQuestion, MainConsole.Instance.CmdPrompt(configOption.configurationQuestion,
configOption.configurationDefault); configOption.configurationDefault);
} }
} }
else else
@ -431,7 +431,7 @@ namespace OpenSim.Framework
if (!resultFunction(configOption.configurationKey, return_result)) if (!resultFunction(configOption.configurationKey, return_result))
{ {
MainLog.Instance.Notice( m_log.Info(
"The handler for the last configuration option denied that input, please try again."); "The handler for the last configuration option denied that input, please try again.");
convertSuccess = false; convertSuccess = false;
ignoreNextFromConfig = true; ignoreNextFromConfig = true;
@ -441,20 +441,18 @@ namespace OpenSim.Framework
{ {
if (configOption.configurationUseDefaultNoPrompt) if (configOption.configurationUseDefaultNoPrompt)
{ {
MainLog.Instance.Error("CONFIG", m_log.Error(string.Format(
string.Format( "[CONFIG]: [{3}]:[{1}] is not valid default for parameter [{0}].\nThe configuration result must be parsable to {2}.\n",
"[{3}]:[{1}] is not valid default for parameter [{0}].\nThe configuration result must be parsable to {2}.\n", configOption.configurationKey, console_result, errorMessage,
configOption.configurationKey, console_result, errorMessage, configurationFilename));
configurationFilename));
convertSuccess = true; convertSuccess = true;
} }
else else
{ {
MainLog.Instance.Warn("CONFIG", m_log.Warn(string.Format(
string.Format( "[CONFIG]: [{3}]:[{1}] is not a valid value [{0}].\nThe configuration result must be parsable to {2}.\n",
"[{3}]:[{1}] is not a valid value [{0}].\nThe configuration result must be parsable to {2}.\n", configOption.configurationKey, console_result, errorMessage,
configOption.configurationKey, console_result, errorMessage, configurationFilename));
configurationFilename));
ignoreNextFromConfig = true; ignoreNextFromConfig = true;
} }
} }

View File

@ -13,7 +13,7 @@
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS AS IS AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
@ -26,6 +26,8 @@
* *
*/ */
using System;
namespace OpenSim.Framework namespace OpenSim.Framework
{ {
public class ConfigurationOption public class ConfigurationOption
@ -52,9 +54,9 @@ namespace OpenSim.Framework
TYPE_DOUBLE TYPE_DOUBLE
} ; } ;
public string configurationKey = ""; public string configurationKey = String.Empty;
public string configurationQuestion = ""; public string configurationQuestion = String.Empty;
public string configurationDefault = ""; public string configurationDefault = String.Empty;
public ConfigurationTypes configurationType = ConfigurationTypes.TYPE_STRING; public ConfigurationTypes configurationType = ConfigurationTypes.TYPE_STRING;
public bool configurationUseDefaultNoPrompt = false; public bool configurationUseDefaultNoPrompt = false;

View File

@ -36,12 +36,12 @@ using System.Runtime.InteropServices;
[assembly : AssemblyTitle("ServerConsole")] [assembly : AssemblyTitle("ServerConsole")]
[assembly : AssemblyDescription("")] [assembly : AssemblyDescription("")]
[assembly : AssemblyConfiguration("")] [assembly: AssemblyConfiguration("")]
[assembly : AssemblyCompany("")] [assembly: AssemblyCompany("")]
[assembly : AssemblyProduct("ServerConsole")] [assembly : AssemblyProduct("ServerConsole")]
[assembly : AssemblyCopyright("")] [assembly: AssemblyCopyright("")]
[assembly : AssemblyTrademark("")] [assembly: AssemblyTrademark("")]
[assembly : AssemblyCulture("")] [assembly: AssemblyCulture("")]
// This sets the default COM visibility of types in the assembly to invisible. // This sets the default COM visibility of types in the assembly to invisible.
// If you need to expose a type to COM, use [ComVisible(true)] on that type. // If you need to expose a type to COM, use [ComVisible(true)] on that type.

View File

@ -33,49 +33,28 @@ using System.Net;
namespace OpenSim.Framework.Console namespace OpenSim.Framework.Console
{ {
public enum LogPriority : int public class ConsoleBase
{ {
CRITICAL, private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
HIGH,
MEDIUM,
NORMAL,
LOW,
VERBOSE,
EXTRAVERBOSE
}
public class LogBase private readonly object m_syncRoot = new object();
{
private object m_syncRoot = new object();
private StreamWriter Log; public conscmd_callback m_cmdParser;
public conscmd_callback cmdparser; public string m_componentName;
public string componentname;
private bool m_verbose;
public LogBase(string LogFile, string componentname, conscmd_callback cmdparser, bool verbose) public ConsoleBase(string componentname, conscmd_callback cmdparser)
{ {
this.componentname = componentname; m_componentName = componentname;
this.cmdparser = cmdparser; m_cmdParser = cmdparser;
m_verbose = verbose;
System.Console.WriteLine("Creating new local console"); System.Console.WriteLine("Creating new local console");
if (String.IsNullOrEmpty(LogFile)) m_log.Info("[" + m_componentName + "]: Started at " + DateTime.Now.ToString());
{
LogFile = componentname + ".log";
}
System.Console.WriteLine("Logs will be saved to current directory in " + LogFile);
Log = File.AppendText(LogFile);
Log.WriteLine("========================================================================");
Log.WriteLine(componentname + " Started at " + DateTime.Now.ToString());
} }
public void Close() public void Close()
{ {
Log.WriteLine("Shutdown at " + DateTime.Now.ToString()); m_log.Info("[" + m_componentName + "]: Shutdown at " + DateTime.Now.ToString());
Log.Close();
} }
/// <summary> /// <summary>
@ -87,23 +66,22 @@ namespace OpenSim.Framework.Console
/// <returns>an ansii color</returns> /// <returns>an ansii color</returns>
private ConsoleColor DeriveColor(string input) private ConsoleColor DeriveColor(string input)
{ {
int colIdx = (input.ToUpper().GetHashCode()%6) + 9; int colIdx = (input.ToUpper().GetHashCode() % 6) + 9;
return (ConsoleColor) colIdx; return (ConsoleColor) colIdx;
} }
/// <summary> /// <summary>
/// Sends a warning to the current log output /// Sends a warning to the current console output
/// </summary> /// </summary>
/// <param name="format">The message to send</param> /// <param name="format">The message to send</param>
/// <param name="args">WriteLine-style message arguments</param> /// <param name="args">WriteLine-style message arguments</param>
public void Warn(string format, params object[] args) public void Warn(string format, params object[] args)
{ {
WriteNewLine(ConsoleColor.Yellow, format, args); WriteNewLine(ConsoleColor.Yellow, format, args);
return;
} }
/// <summary> /// <summary>
/// Sends a warning to the current log output /// Sends a warning to the current console output
/// </summary> /// </summary>
/// <param name="sender">The module that sent this message</param> /// <param name="sender">The module that sent this message</param>
/// <param name="format">The message to send</param> /// <param name="format">The message to send</param>
@ -112,22 +90,20 @@ namespace OpenSim.Framework.Console
{ {
WritePrefixLine(DeriveColor(sender), sender); WritePrefixLine(DeriveColor(sender), sender);
WriteNewLine(ConsoleColor.Yellow, format, args); WriteNewLine(ConsoleColor.Yellow, format, args);
return;
} }
/// <summary> /// <summary>
/// Sends a notice to the current log output /// Sends a notice to the current console output
/// </summary> /// </summary>
/// <param name="format">The message to send</param> /// <param name="format">The message to send</param>
/// <param name="args">WriteLine-style message arguments</param> /// <param name="args">WriteLine-style message arguments</param>
public void Notice(string format, params object[] args) public void Notice(string format, params object[] args)
{ {
WriteNewLine(ConsoleColor.White, format, args); WriteNewLine(ConsoleColor.White, format, args);
return;
} }
/// <summary> /// <summary>
/// Sends a notice to the current log output /// Sends a notice to the current console output
/// </summary> /// </summary>
/// <param name="sender">The module that sent this message</param> /// <param name="sender">The module that sent this message</param>
/// <param name="format">The message to send</param> /// <param name="format">The message to send</param>
@ -136,22 +112,20 @@ namespace OpenSim.Framework.Console
{ {
WritePrefixLine(DeriveColor(sender), sender); WritePrefixLine(DeriveColor(sender), sender);
WriteNewLine(ConsoleColor.White, format, args); WriteNewLine(ConsoleColor.White, format, args);
return;
} }
/// <summary> /// <summary>
/// Sends an error to the current log output /// Sends an error to the current console output
/// </summary> /// </summary>
/// <param name="format">The message to send</param> /// <param name="format">The message to send</param>
/// <param name="args">WriteLine-style message arguments</param> /// <param name="args">WriteLine-style message arguments</param>
public void Error(string format, params object[] args) public void Error(string format, params object[] args)
{ {
WriteNewLine(ConsoleColor.Red, format, args); WriteNewLine(ConsoleColor.Red, format, args);
return;
} }
/// <summary> /// <summary>
/// Sends an error to the current log output /// Sends an error to the current console output
/// </summary> /// </summary>
/// <param name="sender">The module that sent this message</param> /// <param name="sender">The module that sent this message</param>
/// <param name="format">The message to send</param> /// <param name="format">The message to send</param>
@ -160,38 +134,20 @@ namespace OpenSim.Framework.Console
{ {
WritePrefixLine(DeriveColor(sender), sender); WritePrefixLine(DeriveColor(sender), sender);
Error(format, args); Error(format, args);
return;
} }
/// <summary> /// <summary>
/// Sends an informational message to the current log output /// Sends a status message to the current console output
/// </summary>
/// <param name="sender">The module that sent this message</param>
/// <param name="format">The message to send</param>
/// <param name="args">WriteLine-style message arguments</param>
public void Verbose(string sender, string format, params object[] args)
{
if (m_verbose)
{
WritePrefixLine(DeriveColor(sender), sender);
WriteNewLine(ConsoleColor.Gray, format, args);
return;
}
}
/// <summary>
/// Sends a status message to the current log output
/// </summary> /// </summary>
/// <param name="format">The message to send</param> /// <param name="format">The message to send</param>
/// <param name="args">WriteLine-style message arguments</param> /// <param name="args">WriteLine-style message arguments</param>
public void Status(string format, params object[] args) public void Status(string format, params object[] args)
{ {
WriteNewLine(ConsoleColor.Blue, format, args); WriteNewLine(ConsoleColor.Blue, format, args);
return;
} }
/// <summary> /// <summary>
/// Sends a status message to the current log output /// Sends a status message to the current console output
/// </summary> /// </summary>
/// <param name="sender">The module that sent this message</param> /// <param name="sender">The module that sent this message</param>
/// <param name="format">The message to send</param> /// <param name="format">The message to send</param>
@ -200,14 +156,12 @@ namespace OpenSim.Framework.Console
{ {
WritePrefixLine(DeriveColor(sender), sender); WritePrefixLine(DeriveColor(sender), sender);
WriteNewLine(ConsoleColor.Blue, format, args); WriteNewLine(ConsoleColor.Blue, format, args);
return;
} }
[Conditional("DEBUG")] [Conditional("DEBUG")]
public void Debug(string format, params object[] args) public void Debug(string format, params object[] args)
{ {
WriteNewLine(ConsoleColor.Gray, format, args); WriteNewLine(ConsoleColor.Gray, format, args);
return;
} }
[Conditional("DEBUG")] [Conditional("DEBUG")]
@ -215,98 +169,86 @@ namespace OpenSim.Framework.Console
{ {
WritePrefixLine(DeriveColor(sender), sender); WritePrefixLine(DeriveColor(sender), sender);
WriteNewLine(ConsoleColor.Gray, format, args); WriteNewLine(ConsoleColor.Gray, format, args);
return;
} }
private void WriteNewLine(ConsoleColor color, string format, params object[] args) private void WriteNewLine(ConsoleColor color, string format, params object[] args)
{ {
lock (m_syncRoot) try
{ {
string now = DateTime.Now.ToString("[MM-dd hh:mm:ss] "); lock (m_syncRoot)
Log.Write(now);
try
{ {
Log.WriteLine(format, args); try
Log.Flush(); {
} if (color != ConsoleColor.White)
System.Console.ForegroundColor = color;
catch (FormatException) System.Console.WriteLine(format, args);
{ System.Console.ResetColor();
System.Console.WriteLine(args); }
catch (ArgumentNullException)
{
// Some older systems dont support coloured text.
System.Console.WriteLine(format, args);
}
catch (FormatException)
{
System.Console.WriteLine(args);
}
} }
System.Console.Write(now); }
try catch (ObjectDisposedException)
{ {
if (color != ConsoleColor.White)
System.Console.ForegroundColor = color;
System.Console.WriteLine(format, args);
System.Console.ResetColor();
}
catch (ArgumentNullException)
{
// Some older systems dont support coloured text.
System.Console.WriteLine(format, args);
}
catch (FormatException)
{
// Some older systems dont support coloured text.
System.Console.WriteLine(args);
}
return;
} }
} }
private void WritePrefixLine(ConsoleColor color, string sender) private void WritePrefixLine(ConsoleColor color, string sender)
{ {
lock (m_syncRoot) try
{ {
sender = sender.ToUpper(); lock (m_syncRoot)
Log.WriteLine("[" + sender + "] ");
Log.Flush();
System.Console.Write("[");
try
{ {
System.Console.ForegroundColor = color; sender = sender.ToUpper();
System.Console.Write(sender);
System.Console.ResetColor();
}
catch (ArgumentNullException)
{
// Some older systems dont support coloured text.
System.Console.WriteLine(sender);
}
System.Console.Write("] \t"); System.Console.WriteLine("[" + sender + "] ");
return; System.Console.Write("[");
try
{
System.Console.ForegroundColor = color;
System.Console.Write(sender);
System.Console.ResetColor();
}
catch (ArgumentNullException)
{
// Some older systems dont support coloured text.
System.Console.WriteLine(sender);
}
System.Console.Write("] \t");
}
}
catch (ObjectDisposedException)
{
} }
} }
public string ReadLine() public string ReadLine()
{ {
try try
{ {
string TempStr = System.Console.ReadLine(); return System.Console.ReadLine();
Log.WriteLine(TempStr);
return TempStr;
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Error("Console", "System.Console.ReadLine exception " + e.ToString()); m_log.Error("[Console]: System.Console.ReadLine exception " + e.ToString());
return ""; return String.Empty;
} }
} }
public int Read() public int Read()
{ {
int TempInt = System.Console.Read(); return System.Console.Read();
Log.Write((char) TempInt);
return TempInt;
} }
public IPAddress CmdPromptIPAddress(string prompt, string defaultvalue) public IPAddress CmdPromptIPAddress(string prompt, string defaultvalue)
@ -316,14 +258,14 @@ namespace OpenSim.Framework.Console
while (true) while (true)
{ {
addressStr = MainLog.Instance.CmdPrompt(prompt, defaultvalue); addressStr = CmdPrompt(prompt, defaultvalue);
if (IPAddress.TryParse(addressStr, out address)) if (IPAddress.TryParse(addressStr, out address))
{ {
break; break;
} }
else else
{ {
MainLog.Instance.Error("Illegal address. Please re-enter."); m_log.Error("Illegal address. Please re-enter.");
} }
} }
@ -337,7 +279,7 @@ namespace OpenSim.Framework.Console
while (true) while (true)
{ {
portStr = MainLog.Instance.CmdPrompt(prompt, defaultvalue); portStr = CmdPrompt(prompt, defaultvalue);
if (uint.TryParse(portStr, out port)) if (uint.TryParse(portStr, out port))
{ {
if (port >= IPEndPoint.MinPort && port <= IPEndPoint.MaxPort) if (port >= IPEndPoint.MinPort && port <= IPEndPoint.MaxPort)
@ -346,30 +288,29 @@ namespace OpenSim.Framework.Console
} }
} }
MainLog.Instance.Error("Illegal address. Please re-enter."); m_log.Error("Illegal address. Please re-enter.");
} }
return port; return port;
} }
// Displays a prompt and waits for the user to enter a string, then returns that string // Displays a prompt and waits for the user to enter a string, then returns that string
// Done with no echo and suitable for passwords // (Done with no echo and suitable for passwords - currently disabled)
public string PasswdPrompt(string prompt) public string PasswdPrompt(string prompt)
{ {
// FIXME: Needs to be better abstracted // FIXME: Needs to be better abstracted
Log.WriteLine(prompt); System.Console.WriteLine(String.Format("{0}: ", prompt));
Notice(prompt); //ConsoleColor oldfg = System.Console.ForegroundColor;
ConsoleColor oldfg = System.Console.ForegroundColor; //System.Console.ForegroundColor = System.Console.BackgroundColor;
System.Console.ForegroundColor = System.Console.BackgroundColor;
string temp = System.Console.ReadLine(); string temp = System.Console.ReadLine();
System.Console.ForegroundColor = oldfg; //System.Console.ForegroundColor = oldfg;
return temp; return temp;
} }
// Displays a command prompt and waits for the user to enter a string, then returns that string // Displays a command prompt and waits for the user to enter a string, then returns that string
public string CmdPrompt(string prompt) public string CmdPrompt(string prompt)
{ {
Notice(String.Format("{0}: ", prompt)); System.Console.WriteLine(String.Format("{0}: ", prompt));
return ReadLine(); return ReadLine();
} }
@ -377,7 +318,7 @@ namespace OpenSim.Framework.Console
public string CmdPrompt(string prompt, string defaultresponse) public string CmdPrompt(string prompt, string defaultresponse)
{ {
string temp = CmdPrompt(String.Format("{0} [{1}]", prompt, defaultresponse)); string temp = CmdPrompt(String.Format("{0} [{1}]", prompt, defaultresponse));
if (temp == "") if (temp == String.Empty)
{ {
return defaultresponse; return defaultresponse;
} }
@ -400,7 +341,7 @@ namespace OpenSim.Framework.Console
} }
else else
{ {
Notice("Valid options are " + OptionA + " or " + OptionB); System.Console.WriteLine("Valid options are " + OptionA + " or " + OptionB);
temp = CmdPrompt(prompt, defaultresponse); temp = CmdPrompt(prompt, defaultresponse);
} }
} }
@ -410,23 +351,23 @@ namespace OpenSim.Framework.Console
// Runs a command with a number of parameters // Runs a command with a number of parameters
public Object RunCmd(string Cmd, string[] cmdparams) public Object RunCmd(string Cmd, string[] cmdparams)
{ {
cmdparser.RunCmd(Cmd, cmdparams); m_cmdParser.RunCmd(Cmd, cmdparams);
return null; return null;
} }
// Shows data about something // Shows data about something
public void ShowCommands(string ShowWhat) public void ShowCommands(string ShowWhat)
{ {
cmdparser.Show(ShowWhat); m_cmdParser.Show(ShowWhat);
} }
public void MainLogPrompt() public void Prompt()
{ {
string tempstr = CmdPrompt(componentname + "# "); string tempstr = CmdPrompt(m_componentName + "# ");
MainLogRunCommand(tempstr); RunCommand(tempstr);
} }
public void MainLogRunCommand(string command) public void RunCommand(string command)
{ {
string[] tempstrarray; string[] tempstrarray;
tempstrarray = command.Split(' '); tempstrarray = command.Split(' ');
@ -435,13 +376,14 @@ namespace OpenSim.Framework.Console
Array.Resize<string>(ref tempstrarray, tempstrarray.Length - 1); Array.Resize<string>(ref tempstrarray, tempstrarray.Length - 1);
Array.Reverse(tempstrarray); Array.Reverse(tempstrarray);
string[] cmdparams = (string[]) tempstrarray; string[] cmdparams = (string[]) tempstrarray;
try try
{ {
RunCmd(cmd, cmdparams); RunCmd(cmd, cmdparams);
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Error("Console", "Command failed with exception " + e.ToString()); m_log.ErrorFormat("[Console]: Command [{0}] failed with exception {1}", command, e.ToString());
} }
} }

View File

@ -25,13 +25,14 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
namespace OpenSim.Framework.Console namespace OpenSim.Framework.Console
{ {
public class MainLog public class MainConsole
{ {
private static LogBase instance; private static ConsoleBase instance;
public static LogBase Instance public static ConsoleBase Instance
{ {
get { return instance; } get { return instance; }
set { instance = value; } set { instance = value; }

View File

@ -0,0 +1,115 @@
/*
* 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 OpenSim 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.Text;
using System.Text.RegularExpressions;
using System.Globalization;
using log4net.Core;
using log4net.Layout;
using log4net.Appender;
using log4net.Util;
namespace OpenSim.Framework.Console
{
public class OpenSimAppender : AnsiColorTerminalAppender
{
override protected void Append(LoggingEvent le)
{
try {
string loggingMessage = RenderLoggingEvent(le);
string regex = @"^(?<Front>.*?)\[(?<Category>[^\]]+)\]:?(?<End>.*)";
Regex RE = new Regex(regex, RegexOptions.Multiline);
MatchCollection matches = RE.Matches(loggingMessage);
// Get some direct matches $1 $4 is a
if (matches.Count == 1)
{
System.Console.Write(matches[0].Groups["Front"].Value);
System.Console.Write("[");
WriteColorText(DeriveColor(matches[0].Groups["Category"].Value), matches[0].Groups["Category"].Value);
System.Console.Write("]:");
if (le.Level == Level.Error)
{
WriteColorText(ConsoleColor.Red, matches[0].Groups["End"].Value);
}
else if (le.Level == Level.Warn)
{
WriteColorText(ConsoleColor.Yellow, matches[0].Groups["End"].Value);
}
else
{
System.Console.Write(matches[0].Groups["End"].Value);
}
System.Console.WriteLine();
}
else
{
System.Console.Write(loggingMessage);
}
}
catch (Exception e)
{
System.Console.WriteLine("Couldn't write out log message", e.ToString());
}
}
private void WriteColorText(ConsoleColor color, string sender)
{
try
{
lock (this)
{
try
{
System.Console.ForegroundColor = color;
System.Console.Write(sender);
System.Console.ResetColor();
}
catch (ArgumentNullException)
{
// Some older systems dont support coloured text.
System.Console.WriteLine(sender);
}
}
}
catch (ObjectDisposedException)
{
}
}
private ConsoleColor DeriveColor(string input)
{
int colIdx = (input.ToUpper().GetHashCode() % 6) + 9;
return (ConsoleColor) colIdx;
}
}
}

View File

@ -0,0 +1,39 @@
/*
* 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 OpenSim 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;
namespace OpenSim.Framework
{
public class Constants
{
public const uint RegionSize = 256;
}
}

View File

@ -13,7 +13,7 @@
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS AS IS AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY

View File

@ -37,6 +37,8 @@ namespace OpenSim.Framework.Data.DB4o
/// </summary> /// </summary>
public class DB4oUserData : IUserData public class DB4oUserData : IUserData
{ {
//private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary> /// <summary>
/// The database manager /// The database manager
/// </summary> /// </summary>
@ -144,27 +146,33 @@ namespace OpenSim.Framework.Data.DB4o
return null; return null;
} }
} }
public void StoreWebLoginKey(LLUUID AgentID, LLUUID WebLoginKey)
{
UserProfileData user = GetUserByUUID(AgentID);
user.webLoginKey = WebLoginKey;
UpdateUserProfile(user);
}
#region User Friends List Data #region User Friends List Data
public void AddNewUserFriend(LLUUID friendlistowner, LLUUID friend, uint perms) public void AddNewUserFriend(LLUUID friendlistowner, LLUUID friend, uint perms)
{ {
//MainLog.Instance.Verbose("FRIEND", "Stub AddNewUserFriend called"); //m_log.Info("[FRIEND]: Stub AddNewUserFriend called");
} }
public void RemoveUserFriend(LLUUID friendlistowner, LLUUID friend) public void RemoveUserFriend(LLUUID friendlistowner, LLUUID friend)
{ {
//MainLog.Instance.Verbose("FRIEND", "Stub RemoveUserFriend called"); //m_log.Info("[FRIEND]: Stub RemoveUserFriend called");
} }
public void UpdateUserFriendPerms(LLUUID friendlistowner, LLUUID friend, uint perms) public void UpdateUserFriendPerms(LLUUID friendlistowner, LLUUID friend, uint perms)
{ {
//MainLog.Instance.Verbose("FRIEND", "Stub UpdateUserFriendPerms called"); //m_log.Info("[FRIEND]: Stub UpdateUserFriendPerms called");
} }
public List<FriendListItem> GetUserFriendList(LLUUID friendlistowner) public List<FriendListItem> GetUserFriendList(LLUUID friendlistowner)
{ {
//MainLog.Instance.Verbose("FRIEND", "Stub GetUserFriendList called"); //m_log.Info("[FRIEND]: Stub GetUserFriendList called");
return new List<FriendListItem>(); return new List<FriendListItem>();
} }
@ -172,13 +180,10 @@ namespace OpenSim.Framework.Data.DB4o
public void UpdateUserCurrentRegion(LLUUID avatarid, LLUUID regionuuid) public void UpdateUserCurrentRegion(LLUUID avatarid, LLUUID regionuuid)
{ {
//MainLog.Instance.Verbose("USER", "Stub UpdateUserCUrrentRegion called"); //m_log.Info("[USER]: Stub UpdateUserCUrrentRegion called");
} }
public void LogOffUser(LLUUID avatarid)
{
//MainLog.Instance.Verbose("USER", "Stub LogOffUser called");
}
public List<Framework.AvatarPickerAvatar> GeneratePickerResults(LLUUID queryID, string query) public List<Framework.AvatarPickerAvatar> GeneratePickerResults(LLUUID queryID, string query)
{ {

View File

@ -1,3 +1,31 @@
/*
* 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 OpenSim 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.Reflection; using System.Reflection;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
@ -10,7 +38,7 @@ using System.Runtime.InteropServices;
[assembly : AssemblyConfiguration("")] [assembly : AssemblyConfiguration("")]
[assembly : AssemblyCompany("")] [assembly : AssemblyCompany("")]
[assembly : AssemblyProduct("OpenSim.Framework.Data.DB4o")] [assembly : AssemblyProduct("OpenSim.Framework.Data.DB4o")]
[assembly : AssemblyCopyright("Copyright © 2007")] [assembly : AssemblyCopyright("Copyright © OpenSimulator.org Developers 2007-2008")]
[assembly : AssemblyTrademark("")] [assembly : AssemblyTrademark("")]
[assembly : AssemblyCulture("")] [assembly : AssemblyCulture("")]

View File

@ -13,7 +13,7 @@
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS AS IS AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
@ -37,6 +37,8 @@ namespace OpenSim.Framework.Data.MSSQL
{ {
internal class MSSQLAssetData : IAssetProvider internal class MSSQLAssetData : IAssetProvider
{ {
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private MSSQLManager database; private MSSQLManager database;
#region IAssetProvider Members #region IAssetProvider Members
@ -46,7 +48,7 @@ namespace OpenSim.Framework.Data.MSSQL
// null as the version, indicates that the table didn't exist // null as the version, indicates that the table didn't exist
if (tableName == null) if (tableName == null)
{ {
MainLog.Instance.Notice("ASSETS", "Creating new database tables"); m_log.Info("[ASSETS]: Creating new database tables");
database.ExecuteResourceSql("CreateAssetsTable.sql"); database.ExecuteResourceSql("CreateAssetsTable.sql");
return; return;
} }
@ -168,7 +170,7 @@ namespace OpenSim.Framework.Data.MSSQL
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
} }
} }

View File

@ -38,28 +38,57 @@ namespace OpenSim.Framework.Data.MSSQL
/// <summary> /// <summary>
/// A grid data interface for Microsoft SQL Server /// A grid data interface for Microsoft SQL Server
/// </summary> /// </summary>
public class SqlGridData : IGridData public class MSSQLGridData : IGridData
{ {
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary> /// <summary>
/// Database manager /// Database manager
/// </summary> /// </summary>
private MSSQLManager database; private MSSQLManager database;
private string m_regionsTableName;
/// <summary> /// <summary>
/// Initialises the Grid Interface /// Initialises the Grid Interface
/// </summary> /// </summary>
public void Initialise() public void Initialise()
{ {
IniFile GridDataMySqlFile = new IniFile("mssql_connection.ini"); IniFile iniFile = new IniFile("mssql_connection.ini");
string settingDataSource = GridDataMySqlFile.ParseFileReadValue("data_source");
string settingInitialCatalog = GridDataMySqlFile.ParseFileReadValue("initial_catalog"); string settingDataSource = iniFile.ParseFileReadValue("data_source");
string settingPersistSecurityInfo = GridDataMySqlFile.ParseFileReadValue("persist_security_info"); string settingInitialCatalog = iniFile.ParseFileReadValue("initial_catalog");
string settingUserId = GridDataMySqlFile.ParseFileReadValue("user_id"); string settingPersistSecurityInfo = iniFile.ParseFileReadValue("persist_security_info");
string settingPassword = GridDataMySqlFile.ParseFileReadValue("password"); string settingUserId = iniFile.ParseFileReadValue("user_id");
string settingPassword = iniFile.ParseFileReadValue("password");
m_regionsTableName = iniFile.ParseFileReadValue("regionstablename");
if (m_regionsTableName == null)
{
m_regionsTableName = "regions";
}
database = database =
new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId, new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId,
settingPassword); settingPassword);
TestTables();
}
private void TestTables()
{
IDbCommand cmd = database.Query("SELECT TOP 1 * FROM "+m_regionsTableName, new Dictionary<string, string>());
try
{
cmd.ExecuteNonQuery();
cmd.Dispose();
}
catch (Exception)
{
m_log.Info("[DATASTORE]: MSSQL Database doesn't exist... creating");
database.ExecuteResourceSql("Mssql-regions.sql");
}
} }
/// <summary> /// <summary>
@ -113,7 +142,7 @@ namespace OpenSim.Framework.Data.MSSQL
{ {
Dictionary<string, string> param = new Dictionary<string, string>(); Dictionary<string, string> param = new Dictionary<string, string>();
param["handle"] = handle.ToString(); param["handle"] = handle.ToString();
IDbCommand result = database.Query("SELECT * FROM regions WHERE regionHandle = @handle", param); IDbCommand result = database.Query("SELECT * FROM " + m_regionsTableName + " WHERE regionHandle = @handle", param);
reader = result.ExecuteReader(); reader = result.ExecuteReader();
RegionProfileData row = database.getRegionRow(reader); RegionProfileData row = database.getRegionRow(reader);
@ -132,88 +161,6 @@ namespace OpenSim.Framework.Data.MSSQL
return null; return null;
} }
/// <summary>
/// // Returns a list of avatar and UUIDs that match the query
/// </summary>
public List<AvatarPickerAvatar> GeneratePickerResults(LLUUID queryID, string query)
{
List<AvatarPickerAvatar> returnlist = new List<AvatarPickerAvatar>();
string[] querysplit;
querysplit = query.Split(' ');
if (querysplit.Length == 2)
{
try
{
lock (database)
{
Dictionary<string, string> param = new Dictionary<string, string>();
param["first"] = querysplit[0];
param["second"] = querysplit[1];
IDbCommand result =
database.Query(
"SELECT UUID,username,surname FROM users WHERE username = @first AND lastname = @second",
param);
IDataReader reader = result.ExecuteReader();
while (reader.Read())
{
AvatarPickerAvatar user = new AvatarPickerAvatar();
user.AvatarID = new LLUUID((string) reader["UUID"]);
user.firstName = (string) reader["username"];
user.lastName = (string) reader["surname"];
returnlist.Add(user);
}
reader.Close();
result.Dispose();
}
}
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
return returnlist;
}
}
else if (querysplit.Length == 1)
{
try
{
lock (database)
{
Dictionary<string, string> param = new Dictionary<string, string>();
param["first"] = querysplit[0];
param["second"] = querysplit[1];
IDbCommand result =
database.Query(
"SELECT UUID,username,surname FROM users WHERE username = @first OR lastname = @second",
param);
IDataReader reader = result.ExecuteReader();
while (reader.Read())
{
AvatarPickerAvatar user = new AvatarPickerAvatar();
user.AvatarID = new LLUUID((string) reader["UUID"]);
user.firstName = (string) reader["username"];
user.lastName = (string) reader["surname"];
returnlist.Add(user);
}
reader.Close();
result.Dispose();
}
}
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
return returnlist;
}
}
return returnlist;
}
/// <summary> /// <summary>
/// Returns a sim profile from it's UUID /// Returns a sim profile from it's UUID
@ -224,7 +171,7 @@ namespace OpenSim.Framework.Data.MSSQL
{ {
Dictionary<string, string> param = new Dictionary<string, string>(); Dictionary<string, string> param = new Dictionary<string, string>();
param["uuid"] = uuid.ToString(); param["uuid"] = uuid.ToString();
IDbCommand result = database.Query("SELECT * FROM regions WHERE uuid = @uuid", param); IDbCommand result = database.Query("SELECT * FROM " + m_regionsTableName + " WHERE uuid = @uuid", param);
IDataReader reader = result.ExecuteReader(); IDataReader reader = result.ExecuteReader();
RegionProfileData row = database.getRegionRow(reader); RegionProfileData row = database.getRegionRow(reader);
@ -253,7 +200,7 @@ namespace OpenSim.Framework.Data.MSSQL
System.Console.WriteLine("No regions found. Create new one."); System.Console.WriteLine("No regions found. Create new one.");
} }
if (database.insertRegionRow(profile)) if ( insertRegionRow(profile))
{ {
return DataResponse.RESPONSE_OK; return DataResponse.RESPONSE_OK;
} }
@ -263,6 +210,77 @@ namespace OpenSim.Framework.Data.MSSQL
} }
} }
/// <summary>
/// Creates a new region in the database
/// </summary>
/// <param name="profile">The region profile to insert</param>
/// <returns>Successful?</returns>
public bool insertRegionRow(RegionProfileData profile)
{
//Insert new region
string sql =
"INSERT INTO " + m_regionsTableName + " ([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]) 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);";
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters["regionHandle"] = profile.regionHandle.ToString();
parameters["regionName"] = profile.regionName;
parameters["uuid"] = profile.UUID.ToString();
parameters["regionRecvKey"] = profile.regionRecvKey;
parameters["regionSecret"] = profile.regionSecret;
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;
parameters["regionMapTexture"] = profile.regionMapTextureID.ToString();
parameters["serverHttpPort"] = profile.httpPort.ToString();
parameters["serverRemotingPort"] = profile.remotingPort.ToString();
bool returnval = false;
try
{
IDbCommand result = database.Query(sql, parameters);
if (result.ExecuteNonQuery() == 1)
returnval = true;
result.Dispose();
}
catch (Exception e)
{
m_log.Error("MSSQLManager : " + e.ToString());
}
return returnval;
}
/// <summary> /// <summary>
/// DEPRECIATED. Attempts to authenticate a region by comparing a shared secret. /// DEPRECIATED. Attempts to authenticate a region by comparing a shared secret.
/// </summary> /// </summary>

View File

@ -39,6 +39,8 @@ namespace OpenSim.Framework.Data.MSSQL
/// </summary> /// </summary>
public class MSSQLInventoryData : IInventoryData public class MSSQLInventoryData : IInventoryData
{ {
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary> /// <summary>
/// The database manager /// The database manager
/// </summary> /// </summary>
@ -159,7 +161,7 @@ namespace OpenSim.Framework.Data.MSSQL
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
return null; return null;
} }
} }
@ -198,7 +200,7 @@ namespace OpenSim.Framework.Data.MSSQL
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
return null; return null;
} }
} }
@ -244,7 +246,7 @@ namespace OpenSim.Framework.Data.MSSQL
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
return null; return null;
} }
} }
@ -282,7 +284,7 @@ namespace OpenSim.Framework.Data.MSSQL
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
return null; return null;
} }
} }
@ -315,7 +317,7 @@ namespace OpenSim.Framework.Data.MSSQL
} }
catch (SqlException e) catch (SqlException e)
{ {
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
} }
return null; return null;
@ -352,7 +354,7 @@ namespace OpenSim.Framework.Data.MSSQL
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
} }
return null; return null;
} }
@ -377,7 +379,7 @@ namespace OpenSim.Framework.Data.MSSQL
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
} }
return null; return null;
@ -412,7 +414,7 @@ namespace OpenSim.Framework.Data.MSSQL
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
return null; return null;
} }
} }
@ -452,7 +454,7 @@ namespace OpenSim.Framework.Data.MSSQL
} }
catch (SqlException e) catch (SqlException e)
{ {
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
} }
} }
@ -511,7 +513,7 @@ namespace OpenSim.Framework.Data.MSSQL
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
} }
} }
@ -533,7 +535,7 @@ namespace OpenSim.Framework.Data.MSSQL
catch (SqlException e) catch (SqlException e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
} }
} }
@ -564,7 +566,7 @@ namespace OpenSim.Framework.Data.MSSQL
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
} }
} }
@ -602,7 +604,7 @@ namespace OpenSim.Framework.Data.MSSQL
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
} }
} }
@ -628,7 +630,7 @@ namespace OpenSim.Framework.Data.MSSQL
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
} }
} }
@ -675,7 +677,7 @@ namespace OpenSim.Framework.Data.MSSQL
catch (SqlException e) catch (SqlException e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
} }
} }
@ -695,7 +697,7 @@ namespace OpenSim.Framework.Data.MSSQL
catch (SqlException e) catch (SqlException e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
} }
} }

View File

@ -25,6 +25,9 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *
*/ */
using System.Collections.Generic;
using System.Data;
namespace OpenSim.Framework.Data.MSSQL namespace OpenSim.Framework.Data.MSSQL
{ {
/// <summary> /// <summary>
@ -52,6 +55,18 @@ namespace OpenSim.Framework.Data.MSSQL
database = database =
new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId, new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId,
settingPassword); settingPassword);
IDbCommand cmd = database.Query("select top 1 * from logs", new Dictionary<string, string>());
try
{
cmd.ExecuteNonQuery();
cmd.Dispose();
}
catch
{
database.ExecuteResourceSql("Mssql-logs.sql");
}
} }
/// <summary> /// <summary>

View File

@ -40,8 +40,10 @@ namespace OpenSim.Framework.Data.MSSQL
/// <summary> /// <summary>
/// A management class for the MS SQL Storage Engine /// A management class for the MS SQL Storage Engine
/// </summary> /// </summary>
internal class MSSQLManager public class MSSQLManager
{ {
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary> /// <summary>
/// The database connection object /// The database connection object
/// </summary> /// </summary>
@ -50,22 +52,12 @@ namespace OpenSim.Framework.Data.MSSQL
/// <summary> /// <summary>
/// Connection string for ADO.net /// Connection string for ADO.net
/// </summary> /// </summary>
private string connectionString; private readonly string connectionString;
/// <summary>
/// Initialises and creates a new Sql connection and maintains it.
/// </summary>
/// <param name="hostname">The Sql server being connected to</param>
/// <param name="database">The name of the Sql database being used</param>
/// <param name="username">The username logging into the database</param>
/// <param name="password">The password for the user logging in</param>
/// <param name="cpooling">Whether to use connection pooling or not, can be one of the following: 'yes', 'true', 'no' or 'false', if unsure use 'false'.</param>
public MSSQLManager(string dataSource, string initialCatalog, string persistSecurityInfo, string userId, public MSSQLManager(string dataSource, string initialCatalog, string persistSecurityInfo, string userId,
string password) string password)
{ {
try connectionString = "Data Source=" + dataSource + ";Initial Catalog=" + initialCatalog +
{
connectionString = "Data Source=" + dataSource + ";Initial Catalog=" + initialCatalog +
";Persist Security Info=" + persistSecurityInfo + ";User ID=" + userId + ";Password=" + ";Persist Security Info=" + persistSecurityInfo + ";User ID=" + userId + ";Password=" +
password + ";"; password + ";";
dbcon = new SqlConnection(connectionString); dbcon = new SqlConnection(connectionString);
@ -116,68 +108,45 @@ namespace OpenSim.Framework.Data.MSSQL
return true; return true;
} }
private void InitDB(IDbConnection conn) // createCol(regions, "regionHandle", typeof (ulong));
{ // createCol(regions, "regionName", typeof (String));
string createRegions = defineTable(createRegionsTable()); // createCol(regions, "uuid", typeof (String));
Dictionary<string, string> param = new Dictionary<string, string>();
IDbCommand pcmd = Query(createRegions, param);
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
pcmd.ExecuteNonQuery();
pcmd.Dispose();
ExecuteResourceSql("Mssql-users.sql"); // createCol(regions, "regionRecvKey", typeof (String));
ExecuteResourceSql("Mssql-agents.sql"); // createCol(regions, "regionSecret", typeof (String));
ExecuteResourceSql("Mssql-logs.sql"); // createCol(regions, "regionSendKey", typeof (String));
conn.Close(); // createCol(regions, "regionDataURI", typeof (String));
} // createCol(regions, "serverIP", typeof (String));
// createCol(regions, "serverPort", typeof (String));
private DataTable createRegionsTable() // createCol(regions, "serverURI", typeof (String));
{
DataTable regions = new DataTable("regions");
createCol(regions, "regionHandle", typeof (ulong));
createCol(regions, "regionName", typeof (String));
createCol(regions, "uuid", typeof (String));
createCol(regions, "regionRecvKey", typeof (String));
createCol(regions, "regionSecret", typeof (String));
createCol(regions, "regionSendKey", typeof (String));
createCol(regions, "regionDataURI", typeof (String));
createCol(regions, "serverIP", typeof (String));
createCol(regions, "serverPort", typeof (String));
createCol(regions, "serverURI", typeof (String));
createCol(regions, "locX", typeof (uint)); // createCol(regions, "locX", typeof (uint));
createCol(regions, "locY", typeof (uint)); // createCol(regions, "locY", typeof (uint));
createCol(regions, "locZ", typeof (uint)); // createCol(regions, "locZ", typeof (uint));
createCol(regions, "eastOverrideHandle", typeof (ulong)); // createCol(regions, "eastOverrideHandle", typeof (ulong));
createCol(regions, "westOverrideHandle", typeof (ulong)); // createCol(regions, "westOverrideHandle", typeof (ulong));
createCol(regions, "southOverrideHandle", typeof (ulong)); // createCol(regions, "southOverrideHandle", typeof (ulong));
createCol(regions, "northOverrideHandle", typeof (ulong)); // createCol(regions, "northOverrideHandle", typeof (ulong));
createCol(regions, "regionAssetURI", typeof (String)); // createCol(regions, "regionAssetURI", typeof (String));
createCol(regions, "regionAssetRecvKey", typeof (String)); // createCol(regions, "regionAssetRecvKey", typeof (String));
createCol(regions, "regionAssetSendKey", typeof (String)); // createCol(regions, "regionAssetSendKey", typeof (String));
createCol(regions, "regionUserURI", typeof (String)); // createCol(regions, "regionUserURI", typeof (String));
createCol(regions, "regionUserRecvKey", typeof (String)); // createCol(regions, "regionUserRecvKey", typeof (String));
createCol(regions, "regionUserSendKey", typeof (String)); // createCol(regions, "regionUserSendKey", typeof (String));
createCol(regions, "regionMapTexture", typeof (String)); // createCol(regions, "regionMapTexture", typeof (String));
createCol(regions, "serverHttpPort", typeof (String)); // createCol(regions, "serverHttpPort", typeof (String));
createCol(regions, "serverRemotingPort", typeof (uint)); // createCol(regions, "serverRemotingPort", typeof (uint));
// Add in contraints // // Add in contraints
regions.PrimaryKey = new DataColumn[] {regions.Columns["UUID"]}; // regions.PrimaryKey = new DataColumn[] {regions.Columns["UUID"]};
return regions; // return regions;
} //}
protected static void createCol(DataTable dt, string name, Type type) protected static void createCol(DataTable dt, string name, Type type)
{ {
@ -188,7 +157,7 @@ namespace OpenSim.Framework.Data.MSSQL
protected static string defineTable(DataTable dt) protected static string defineTable(DataTable dt)
{ {
string sql = "create table " + dt.TableName + "("; string sql = "create table " + dt.TableName + "(";
string subsql = ""; string subsql = String.Empty;
foreach (DataColumn col in dt.Columns) foreach (DataColumn col in dt.Columns)
{ {
if (subsql.Length > 0) if (subsql.Length > 0)
@ -213,19 +182,19 @@ namespace OpenSim.Framework.Data.MSSQL
// slightly differently. // slightly differently.
private static string SqlType(Type type) private static string SqlType(Type type)
{ {
if (type == typeof (String)) if (type == typeof(String))
{ {
return "varchar(255)"; return "varchar(255)";
} }
else if (type == typeof (Int32)) else if (type == typeof(Int32))
{ {
return "integer"; return "integer";
} }
else if (type == typeof (Double)) else if (type == typeof(Double))
{ {
return "float"; return "float";
} }
else if (type == typeof (Byte[])) else if (type == typeof(Byte[]))
{ {
return "image"; return "image";
} }
@ -253,7 +222,6 @@ namespace OpenSim.Framework.Data.MSSQL
{ {
try try
{ {
//string connectionString = "Data Source=WRK-OU-738\\SQLEXPRESS;Initial Catalog=rex;Persist Security Info=True;User ID=sa;Password=rex";
// Close the DB connection // Close the DB connection
dbcon.Close(); dbcon.Close();
// Try reopen it // Try reopen it
@ -262,7 +230,7 @@ namespace OpenSim.Framework.Data.MSSQL
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Error("Unable to reconnect to database " + e.ToString()); m_log.Error("Unable to reconnect to database " + e.ToString());
} }
} }
} }
@ -275,14 +243,14 @@ namespace OpenSim.Framework.Data.MSSQL
/// <returns>A Sql DB Command</returns> /// <returns>A Sql DB Command</returns>
public IDbCommand Query(string sql, Dictionary<string, string> parameters) public IDbCommand Query(string sql, Dictionary<string, string> parameters)
{ {
SqlCommand dbcommand = (SqlCommand) dbcon.CreateCommand(); SqlCommand dbcommand = (SqlCommand)dbcon.CreateCommand();
dbcommand.CommandText = sql; dbcommand.CommandText = sql;
foreach (KeyValuePair<string, string> param in parameters) foreach (KeyValuePair<string, string> param in parameters)
{ {
dbcommand.Parameters.AddWithValue(param.Key, param.Value); dbcommand.Parameters.AddWithValue(param.Key, param.Value);
} }
return (IDbCommand) dbcommand; return (IDbCommand)dbcommand;
} }
/// <summary> /// <summary>
@ -298,20 +266,20 @@ namespace OpenSim.Framework.Data.MSSQL
{ {
// Region Main // Region Main
regionprofile.regionHandle = Convert.ToUInt64(reader["regionHandle"]); regionprofile.regionHandle = Convert.ToUInt64(reader["regionHandle"]);
regionprofile.regionName = (string) reader["regionName"]; regionprofile.regionName = (string)reader["regionName"];
regionprofile.UUID = new LLUUID((string) reader["uuid"]); regionprofile.UUID = new LLUUID((string)reader["uuid"]);
// Secrets // Secrets
regionprofile.regionRecvKey = (string) reader["regionRecvKey"]; regionprofile.regionRecvKey = (string)reader["regionRecvKey"];
regionprofile.regionSecret = (string) reader["regionSecret"]; regionprofile.regionSecret = (string)reader["regionSecret"];
regionprofile.regionSendKey = (string) reader["regionSendKey"]; regionprofile.regionSendKey = (string)reader["regionSendKey"];
// Region Server // Region Server
regionprofile.regionDataURI = (string) reader["regionDataURI"]; regionprofile.regionDataURI = (string)reader["regionDataURI"];
regionprofile.regionOnline = false; // Needs to be pinged before this can be set. regionprofile.regionOnline = false; // Needs to be pinged before this can be set.
regionprofile.serverIP = (string) reader["serverIP"]; regionprofile.serverIP = (string)reader["serverIP"];
regionprofile.serverPort = Convert.ToUInt32(reader["serverPort"]); regionprofile.serverPort = Convert.ToUInt32(reader["serverPort"]);
regionprofile.serverURI = (string) reader["serverURI"]; regionprofile.serverURI = (string)reader["serverURI"];
regionprofile.httpPort = Convert.ToUInt32(reader["serverHttpPort"]); regionprofile.httpPort = Convert.ToUInt32(reader["serverHttpPort"]);
regionprofile.remotingPort = Convert.ToUInt32(reader["serverRemotingPort"]); regionprofile.remotingPort = Convert.ToUInt32(reader["serverRemotingPort"]);
@ -328,18 +296,18 @@ namespace OpenSim.Framework.Data.MSSQL
regionprofile.regionNorthOverrideHandle = Convert.ToUInt64(reader["northOverrideHandle"]); regionprofile.regionNorthOverrideHandle = Convert.ToUInt64(reader["northOverrideHandle"]);
// Assets // Assets
regionprofile.regionAssetURI = (string) reader["regionAssetURI"]; regionprofile.regionAssetURI = (string)reader["regionAssetURI"];
regionprofile.regionAssetRecvKey = (string) reader["regionAssetRecvKey"]; regionprofile.regionAssetRecvKey = (string)reader["regionAssetRecvKey"];
regionprofile.regionAssetSendKey = (string) reader["regionAssetSendKey"]; regionprofile.regionAssetSendKey = (string)reader["regionAssetSendKey"];
// Userserver // Userserver
regionprofile.regionUserURI = (string) reader["regionUserURI"]; regionprofile.regionUserURI = (string)reader["regionUserURI"];
regionprofile.regionUserRecvKey = (string) reader["regionUserRecvKey"]; regionprofile.regionUserRecvKey = (string)reader["regionUserRecvKey"];
regionprofile.regionUserSendKey = (string) reader["regionUserSendKey"]; regionprofile.regionUserSendKey = (string)reader["regionUserSendKey"];
// World Map Addition // World Map Addition
string tempRegionMap = reader["regionMapTexture"].ToString(); string tempRegionMap = reader["regionMapTexture"].ToString();
if (tempRegionMap != "") if (tempRegionMap != String.Empty)
{ {
regionprofile.regionMapTextureID = new LLUUID(tempRegionMap); regionprofile.regionMapTextureID = new LLUUID(tempRegionMap);
} }
@ -367,12 +335,12 @@ namespace OpenSim.Framework.Data.MSSQL
if (reader.Read()) if (reader.Read())
{ {
retval.UUID = new LLUUID((string) reader["UUID"]); retval.UUID = new LLUUID((string)reader["UUID"]);
retval.username = (string) reader["username"]; retval.username = (string)reader["username"];
retval.surname = (string) reader["lastname"]; retval.surname = (string)reader["lastname"];
retval.passwordHash = (string) reader["passwordHash"]; retval.passwordHash = (string)reader["passwordHash"];
retval.passwordSalt = (string) reader["passwordSalt"]; retval.passwordSalt = (string)reader["passwordSalt"];
retval.homeRegion = Convert.ToUInt64(reader["homeRegion"].ToString()); retval.homeRegion = Convert.ToUInt64(reader["homeRegion"].ToString());
retval.homeLocation = new LLVector3( retval.homeLocation = new LLVector3(
@ -387,17 +355,17 @@ namespace OpenSim.Framework.Data.MSSQL
retval.created = Convert.ToInt32(reader["created"].ToString()); retval.created = Convert.ToInt32(reader["created"].ToString());
retval.lastLogin = Convert.ToInt32(reader["lastLogin"].ToString()); retval.lastLogin = Convert.ToInt32(reader["lastLogin"].ToString());
retval.userInventoryURI = (string) reader["userInventoryURI"]; retval.userInventoryURI = (string)reader["userInventoryURI"];
retval.userAssetURI = (string) reader["userAssetURI"]; retval.userAssetURI = (string)reader["userAssetURI"];
retval.profileCanDoMask = Convert.ToUInt32(reader["profileCanDoMask"].ToString()); retval.profileCanDoMask = Convert.ToUInt32(reader["profileCanDoMask"].ToString());
retval.profileWantDoMask = Convert.ToUInt32(reader["profileWantDoMask"].ToString()); retval.profileWantDoMask = Convert.ToUInt32(reader["profileWantDoMask"].ToString());
retval.profileAboutText = (string) reader["profileAboutText"]; retval.profileAboutText = (string)reader["profileAboutText"];
retval.profileFirstText = (string) reader["profileFirstText"]; retval.profileFirstText = (string)reader["profileFirstText"];
retval.profileImage = new LLUUID((string) reader["profileImage"]); retval.profileImage = new LLUUID((string)reader["profileImage"]);
retval.profileFirstImage = new LLUUID((string) reader["profileFirstImage"]); retval.profileFirstImage = new LLUUID((string)reader["profileFirstImage"]);
retval.webLoginKey = new LLUUID((string)reader["webLoginKey"]); retval.webLoginKey = new LLUUID((string)reader["webLoginKey"]);
} }
else else
@ -419,12 +387,12 @@ namespace OpenSim.Framework.Data.MSSQL
if (reader.Read()) if (reader.Read())
{ {
// Agent IDs // Agent IDs
retval.UUID = new LLUUID((string) reader["UUID"]); retval.UUID = new LLUUID((string)reader["UUID"]);
retval.sessionID = new LLUUID((string) reader["sessionID"]); retval.sessionID = new LLUUID((string)reader["sessionID"]);
retval.secureSessionID = new LLUUID((string) reader["secureSessionID"]); retval.secureSessionID = new LLUUID((string)reader["secureSessionID"]);
// Agent Who? // Agent Who?
retval.agentIP = (string) reader["agentIP"]; retval.agentIP = (string)reader["agentIP"];
retval.agentPort = Convert.ToUInt32(reader["agentPort"].ToString()); retval.agentPort = Convert.ToUInt32(reader["agentPort"].ToString());
retval.agentOnline = Convert.ToBoolean(reader["agentOnline"].ToString()); retval.agentOnline = Convert.ToBoolean(reader["agentOnline"].ToString());
@ -433,9 +401,9 @@ namespace OpenSim.Framework.Data.MSSQL
retval.logoutTime = Convert.ToInt32(reader["logoutTime"].ToString()); retval.logoutTime = Convert.ToInt32(reader["logoutTime"].ToString());
// Current position // Current position
retval.currentRegion = (string) reader["currentRegion"]; retval.currentRegion = (string)reader["currentRegion"];
retval.currentHandle = Convert.ToUInt64(reader["currentHandle"].ToString()); retval.currentHandle = Convert.ToUInt64(reader["currentHandle"].ToString());
LLVector3.TryParse((string) reader["currentPos"], out retval.currentPos); LLVector3.TryParse((string)reader["currentPos"], out retval.currentPos);
} }
else else
{ {
@ -458,7 +426,7 @@ namespace OpenSim.Framework.Data.MSSQL
asset.FullID = new LLUUID((string) reader["id"]); asset.FullID = new LLUUID((string) reader["id"]);
asset.InvType = Convert.ToSByte(reader["invType"]); asset.InvType = Convert.ToSByte(reader["invType"]);
asset.Local = Convert.ToBoolean(reader["local"]); // ((sbyte)reader["local"]) != 0 ? true : false; asset.Local = Convert.ToBoolean(reader["local"]); // ((sbyte)reader["local"]) != 0 ? true : false;
asset.Name = (string) reader["name"]; asset.Name = (string)reader["name"];
asset.Type = Convert.ToSByte(reader["assetType"]); asset.Type = Convert.ToSByte(reader["assetType"]);
} }
else else
@ -468,76 +436,6 @@ namespace OpenSim.Framework.Data.MSSQL
return asset; return asset;
} }
/// <summary>
/// Creates a new region in the database
/// </summary>
/// <param name="profile">The region profile to insert</param>
/// <returns>Successful?</returns>
public bool insertRegionRow(RegionProfileData profile)
{
//Insert new region
string sql =
"INSERT INTO regions ([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]) 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);";
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters["regionHandle"] = profile.regionHandle.ToString();
parameters["regionName"] = profile.regionName;
parameters["uuid"] = profile.UUID.ToString();
parameters["regionRecvKey"] = profile.regionRecvKey;
parameters["regionSecret"] = profile.regionSecret;
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;
parameters["regionMapTexture"] = profile.regionMapTextureID.ToString();
parameters["serverHttpPort"] = profile.httpPort.ToString();
parameters["serverRemotingPort"] = profile.remotingPort.ToString();
bool returnval = false;
try
{
IDbCommand result = Query(sql, parameters);
if (result.ExecuteNonQuery() == 1)
returnval = true;
result.Dispose();
}
catch (Exception e)
{
MainLog.Instance.Error("MSSQLManager : " + e.ToString());
}
return returnval;
}
/// <summary> /// <summary>
/// Inserts a new row into the log database /// Inserts a new row into the log database
@ -576,101 +474,7 @@ namespace OpenSim.Framework.Data.MSSQL
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
return false;
}
return returnval;
}
/// <summary>
/// Creates a new user and inserts it into the database
/// </summary>
/// <param name="uuid">User ID</param>
/// <param name="username">First part of the login</param>
/// <param name="lastname">Second part of the login</param>
/// <param name="passwordHash">A salted hash of the users password</param>
/// <param name="passwordSalt">The salt used for the password hash</param>
/// <param name="homeRegion">A regionHandle of the users home region</param>
/// <param name="homeLocX">Home region position vector</param>
/// <param name="homeLocY">Home region position vector</param>
/// <param name="homeLocZ">Home region position vector</param>
/// <param name="homeLookAtX">Home region 'look at' vector</param>
/// <param name="homeLookAtY">Home region 'look at' vector</param>
/// <param name="homeLookAtZ">Home region 'look at' vector</param>
/// <param name="created">Account created (unix timestamp)</param>
/// <param name="lastlogin">Last login (unix timestamp)</param>
/// <param name="inventoryURI">Users inventory URI</param>
/// <param name="assetURI">Users asset URI</param>
/// <param name="canDoMask">I can do mask</param>
/// <param name="wantDoMask">I want to do mask</param>
/// <param name="aboutText">Profile text</param>
/// <param name="firstText">Firstlife text</param>
/// <param name="profileImage">UUID for profile image</param>
/// <param name="firstImage">UUID for firstlife image</param>
/// <returns>Success?</returns>
public bool insertUserRow(LLUUID uuid, string username, string lastname, 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,
LLUUID profileImage, LLUUID firstImage, LLUUID webLoginKey)
{
string sql = "INSERT INTO users ";
sql += "([UUID], [username], [lastname], [passwordHash], [passwordSalt], [homeRegion], ";
sql +=
"[homeLocationX], [homeLocationY], [homeLocationZ], [homeLookAtX], [homeLookAtY], [homeLookAtZ], [created], ";
sql +=
"[lastLogin], [userInventoryURI], [userAssetURI], [profileCanDoMask], [profileWantDoMask], [profileAboutText], ";
sql += "[profileFirstText], [profileImage], [profileFirstImage], [webLoginKey]) VALUES ";
sql += "(@UUID, @username, @lastname, @passwordHash, @passwordSalt, @homeRegion, ";
sql +=
"@homeLocationX, @homeLocationY, @homeLocationZ, @homeLookAtX, @homeLookAtY, @homeLookAtZ, @created, ";
sql +=
"@lastLogin, @userInventoryURI, @userAssetURI, @profileCanDoMask, @profileWantDoMask, @profileAboutText, ";
sql += "@profileFirstText, @profileImage, @profileFirstImage, @webLoginKey);";
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters["UUID"] = uuid.ToString();
parameters["username"] = username.ToString();
parameters["lastname"] = lastname.ToString();
parameters["passwordHash"] = passwordHash.ToString();
parameters["passwordSalt"] = passwordSalt.ToString();
parameters["homeRegion"] = homeRegion.ToString();
parameters["homeLocationX"] = homeLocX.ToString();
parameters["homeLocationY"] = homeLocY.ToString();
parameters["homeLocationZ"] = homeLocZ.ToString();
parameters["homeLookAtX"] = homeLookAtX.ToString();
parameters["homeLookAtY"] = homeLookAtY.ToString();
parameters["homeLookAtZ"] = homeLookAtZ.ToString();
parameters["created"] = created.ToString();
parameters["lastLogin"] = lastlogin.ToString();
parameters["userInventoryURI"] = "";
parameters["userAssetURI"] = "";
parameters["profileCanDoMask"] = "0";
parameters["profileWantDoMask"] = "0";
parameters["profileAboutText"] = "";
parameters["profileFirstText"] = "";
parameters["profileImage"] = LLUUID.Zero.ToString();
parameters["profileFirstImage"] = LLUUID.Zero.ToString();
parameters["webLoginKey"] = LLUUID.Random().ToString();
bool returnval = false;
try
{
IDbCommand result = Query(sql, parameters);
if (result.ExecuteNonQuery() == 1)
returnval = true;
result.Dispose();
}
catch (Exception e)
{
MainLog.Instance.Error(e.ToString());
return false; return false;
} }
@ -683,21 +487,14 @@ namespace OpenSim.Framework.Data.MSSQL
/// <param name="name"></param> /// <param name="name"></param>
public void ExecuteResourceSql(string name) public void ExecuteResourceSql(string name)
{ {
try SqlCommand cmd = new SqlCommand(getResourceString(name), (SqlConnection)dbcon);
{ cmd.ExecuteNonQuery();
SqlCommand cmd = new SqlCommand(getResourceString(name), (SqlConnection) dbcon); cmd.Dispose();
cmd.ExecuteNonQuery();
cmd.Dispose();
}
catch (Exception e)
{
MainLog.Instance.Error("Unable to execute query " + e.ToString());
}
} }
public SqlConnection getConnection() public SqlConnection getConnection()
{ {
return (SqlConnection) dbcon; return (SqlConnection)dbcon;
} }
/// <summary> /// <summary>
@ -718,13 +515,13 @@ namespace OpenSim.Framework.Data.MSSQL
{ {
try try
{ {
string tableName = (string) tables["TABLE_NAME"]; string tableName = (string)tables["TABLE_NAME"];
if (tableList.ContainsKey(tableName)) if (tableList.ContainsKey(tableName))
tableList[tableName] = tableName; tableList[tableName] = tableName;
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
} }
} }
tables.Close(); tables.Close();

View File

@ -37,13 +37,19 @@ namespace OpenSim.Framework.Data.MSSQL
/// <summary> /// <summary>
/// A database interface class to a user profile storage system /// A database interface class to a user profile storage system
/// </summary> /// </summary>
internal class MSSQLUserData : IUserData public class MSSQLUserData : IUserData
{ {
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary> /// <summary>
/// Database manager for MySQL /// Database manager for MySQL
/// </summary> /// </summary>
public MSSQLManager database; public MSSQLManager database;
private string m_agentsTableName;
private string m_usersTableName;
private string m_userFriendsTableName;
/// <summary> /// <summary>
/// Loads and initialises the MySQL storage plugin /// Loads and initialises the MySQL storage plugin
/// </summary> /// </summary>
@ -51,18 +57,74 @@ namespace OpenSim.Framework.Data.MSSQL
{ {
// Load from an INI file connection details // Load from an INI file connection details
// TODO: move this to XML? // TODO: move this to XML?
IniFile GridDataMySqlFile = new IniFile("mssql_connection.ini"); IniFile iniFile = new IniFile("mssql_connection.ini");
string settingDataSource = GridDataMySqlFile.ParseFileReadValue("data_source"); string settingDataSource = iniFile.ParseFileReadValue("data_source");
string settingInitialCatalog = GridDataMySqlFile.ParseFileReadValue("initial_catalog"); string settingInitialCatalog = iniFile.ParseFileReadValue("initial_catalog");
string settingPersistSecurityInfo = GridDataMySqlFile.ParseFileReadValue("persist_security_info"); string settingPersistSecurityInfo = iniFile.ParseFileReadValue("persist_security_info");
string settingUserId = GridDataMySqlFile.ParseFileReadValue("user_id"); string settingUserId = iniFile.ParseFileReadValue("user_id");
string settingPassword = GridDataMySqlFile.ParseFileReadValue("password"); string settingPassword = iniFile.ParseFileReadValue("password");
m_usersTableName = iniFile.ParseFileReadValue("userstablename");
if (m_usersTableName == null)
{
m_usersTableName = "users";
}
m_userFriendsTableName = iniFile.ParseFileReadValue("userfriendstablename");
if (m_userFriendsTableName == null)
{
m_userFriendsTableName = "userfriends";
}
m_agentsTableName = iniFile.ParseFileReadValue("agentstablename");
if (m_agentsTableName == null)
{
m_agentsTableName = "agents";
}
database = database =
new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId, new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId,
settingPassword); settingPassword);
TestTables();
} }
private bool TestTables()
{
IDbCommand cmd;
cmd = database.Query("select top 1 * from " + m_usersTableName, new Dictionary<string, string>());
try
{
cmd.ExecuteNonQuery();
}
catch
{
database.ExecuteResourceSql("Mssql-users.sql");
}
cmd = database.Query("select top 1 * from " + m_agentsTableName, new Dictionary<string, string>());
try
{
cmd.ExecuteNonQuery();
}
catch
{
database.ExecuteResourceSql("Mssql-agents.sql");
}
cmd = database.Query("select top 1 * from " + m_userFriendsTableName, new Dictionary<string, string>());
try
{
cmd.ExecuteNonQuery();
}
catch
{
database.ExecuteResourceSql("CreateUserFriendsTable.sql");
}
return true;
}
/// <summary> /// <summary>
/// Searches the database for a specified user profile by name components /// Searches the database for a specified user profile by name components
/// </summary> /// </summary>
@ -80,7 +142,7 @@ namespace OpenSim.Framework.Data.MSSQL
param["second"] = last; param["second"] = last;
IDbCommand result = IDbCommand result =
database.Query("SELECT * FROM users WHERE username = @first AND lastname = @second", param); database.Query("SELECT * FROM " + m_usersTableName + " WHERE username = @first AND lastname = @second", param);
IDataReader reader = result.ExecuteReader(); IDataReader reader = result.ExecuteReader();
UserProfileData row = database.readUserRow(reader); UserProfileData row = database.readUserRow(reader);
@ -94,7 +156,7 @@ namespace OpenSim.Framework.Data.MSSQL
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
return null; return null;
} }
} }
@ -103,36 +165,165 @@ namespace OpenSim.Framework.Data.MSSQL
public void AddNewUserFriend(LLUUID friendlistowner, LLUUID friend, uint perms) public void AddNewUserFriend(LLUUID friendlistowner, LLUUID friend, uint perms)
{ {
MainLog.Instance.Verbose("FRIEND", "Stub AddNewUserFriend called"); int dtvalue = Util.UnixTimeSinceEpoch();
Dictionary<string, string> param = new Dictionary<string, string>();
param["@ownerID"] = friendlistowner.UUID.ToString();
param["@friendID"] = friend.UUID.ToString();
param["@friendPerms"] = perms.ToString();
param["@datetimestamp"] = dtvalue.ToString();
try
{
lock (database)
{
IDbCommand adder =
database.Query(
"INSERT INTO " + m_userFriendsTableName + " " +
"(ownerID,friendID,friendPerms,datetimestamp) " +
"VALUES " +
"(@ownerID,@friendID,@friendPerms,@datetimestamp)",
param);
adder.ExecuteNonQuery();
adder =
database.Query(
"INSERT INTO " + m_userFriendsTableName + " " +
"(ownerID,friendID,friendPerms,datetimestamp) " +
"VALUES " +
"(@friendID,@ownerID,@friendPerms,@datetimestamp)",
param);
adder.ExecuteNonQuery();
}
}
catch (Exception e)
{
database.Reconnect();
m_log.Error(e.ToString());
return;
}
} }
public void RemoveUserFriend(LLUUID friendlistowner, LLUUID friend) public void RemoveUserFriend(LLUUID friendlistowner, LLUUID friend)
{ {
MainLog.Instance.Verbose("FRIEND", "Stub RemoveUserFriend called"); Dictionary<string, string> param = new Dictionary<string, string>();
param["@ownerID"] = friendlistowner.UUID.ToString();
param["@friendID"] = friend.UUID.ToString();
try
{
lock (database)
{
IDbCommand updater =
database.Query(
"delete from " + m_userFriendsTableName + " where ownerID = @ownerID and friendID = @friendID",
param);
updater.ExecuteNonQuery();
updater =
database.Query(
"delete from " + m_userFriendsTableName + " where ownerID = @friendID and friendID = @ownerID",
param);
updater.ExecuteNonQuery();
}
}
catch (Exception e)
{
database.Reconnect();
m_log.Error(e.ToString());
return;
}
} }
public void UpdateUserFriendPerms(LLUUID friendlistowner, LLUUID friend, uint perms) public void UpdateUserFriendPerms(LLUUID friendlistowner, LLUUID friend, uint perms)
{ {
MainLog.Instance.Verbose("FRIEND", "Stub UpdateUserFriendPerms called"); Dictionary<string, string> param = new Dictionary<string, string>();
param["@ownerID"] = friendlistowner.UUID.ToString();
param["@friendID"] = friend.UUID.ToString();
param["@friendPerms"] = perms.ToString();
try
{
lock (database)
{
IDbCommand updater =
database.Query(
"update " + m_userFriendsTableName +
" SET friendPerms = @friendPerms " +
"where ownerID = @ownerID and friendID = @friendID",
param);
updater.ExecuteNonQuery();
}
}
catch (Exception e)
{
database.Reconnect();
m_log.Error(e.ToString());
return;
}
} }
public List<FriendListItem> GetUserFriendList(LLUUID friendlistowner) public List<FriendListItem> GetUserFriendList(LLUUID friendlistowner)
{ {
MainLog.Instance.Verbose("FRIEND", "Stub GetUserFriendList called"); List<FriendListItem> Lfli = new List<FriendListItem>();
return new List<FriendListItem>();
Dictionary<string, string> param = new Dictionary<string, string>();
param["@ownerID"] = friendlistowner.UUID.ToString();
try
{
lock (database)
{
//Left Join userfriends to itself
IDbCommand result =
database.Query(
"select a.ownerID,a.friendID,a.friendPerms,b.friendPerms as ownerperms from " + m_userFriendsTableName + " as a, " + m_userFriendsTableName + " as b" +
" where a.ownerID = @ownerID and b.ownerID = a.friendID and b.friendID = a.ownerID",
param);
IDataReader reader = result.ExecuteReader();
while (reader.Read())
{
FriendListItem fli = new FriendListItem();
fli.FriendListOwner = new LLUUID((string)reader["ownerID"]);
fli.Friend = new LLUUID((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);
}
reader.Close();
result.Dispose();
}
}
catch (Exception e)
{
database.Reconnect();
m_log.Error(e.ToString());
return Lfli;
}
return Lfli;
} }
#endregion #endregion
public void UpdateUserCurrentRegion(LLUUID avatarid, LLUUID regionuuid) public void UpdateUserCurrentRegion(LLUUID avatarid, LLUUID regionuuid)
{ {
MainLog.Instance.Verbose("USER", "Stub UpdateUserCUrrentRegion called"); m_log.Info("[USER]: Stub UpdateUserCUrrentRegion called");
} }
public void LogOffUser(LLUUID avatarid)
{
MainLog.Instance.Verbose("USER", "Stub LogOffUser called");
}
public List<Framework.AvatarPickerAvatar> GeneratePickerResults(LLUUID queryID, string query) public List<Framework.AvatarPickerAvatar> GeneratePickerResults(LLUUID queryID, string query)
{ {
@ -151,7 +342,7 @@ namespace OpenSim.Framework.Data.MSSQL
IDbCommand result = IDbCommand result =
database.Query( database.Query(
"SELECT UUID,username,surname FROM users WHERE username = @first AND lastname = @second", "SELECT UUID,username,lastname FROM " + m_usersTableName + " WHERE username = @first AND lastname = @second",
param); param);
IDataReader reader = result.ExecuteReader(); IDataReader reader = result.ExecuteReader();
@ -159,9 +350,9 @@ namespace OpenSim.Framework.Data.MSSQL
while (reader.Read()) while (reader.Read())
{ {
Framework.AvatarPickerAvatar user = new Framework.AvatarPickerAvatar(); Framework.AvatarPickerAvatar user = new Framework.AvatarPickerAvatar();
user.AvatarID = new LLUUID((string) reader["UUID"]); user.AvatarID = new LLUUID((string)reader["UUID"]);
user.firstName = (string) reader["username"]; user.firstName = (string)reader["username"];
user.lastName = (string) reader["surname"]; user.lastName = (string)reader["lastname"];
returnlist.Add(user); returnlist.Add(user);
} }
reader.Close(); reader.Close();
@ -171,7 +362,7 @@ namespace OpenSim.Framework.Data.MSSQL
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
return returnlist; return returnlist;
} }
} }
@ -183,11 +374,10 @@ namespace OpenSim.Framework.Data.MSSQL
{ {
Dictionary<string, string> param = new Dictionary<string, string>(); Dictionary<string, string> param = new Dictionary<string, string>();
param["first"] = querysplit[0]; param["first"] = querysplit[0];
param["second"] = querysplit[1];
IDbCommand result = IDbCommand result =
database.Query( database.Query(
"SELECT UUID,username,surname FROM users WHERE username = @first OR lastname = @second", "SELECT UUID,username,lastname FROM " + m_usersTableName + " WHERE username = @first OR lastname = @first",
param); param);
IDataReader reader = result.ExecuteReader(); IDataReader reader = result.ExecuteReader();
@ -195,9 +385,9 @@ namespace OpenSim.Framework.Data.MSSQL
while (reader.Read()) while (reader.Read())
{ {
Framework.AvatarPickerAvatar user = new Framework.AvatarPickerAvatar(); Framework.AvatarPickerAvatar user = new Framework.AvatarPickerAvatar();
user.AvatarID = new LLUUID((string) reader["UUID"]); user.AvatarID = new LLUUID((string)reader["UUID"]);
user.firstName = (string) reader["username"]; user.firstName = (string)reader["username"];
user.lastName = (string) reader["surname"]; user.lastName = (string)reader["lastname"];
returnlist.Add(user); returnlist.Add(user);
} }
reader.Close(); reader.Close();
@ -207,7 +397,7 @@ namespace OpenSim.Framework.Data.MSSQL
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
return returnlist; return returnlist;
} }
} }
@ -224,7 +414,7 @@ namespace OpenSim.Framework.Data.MSSQL
Dictionary<string, string> param = new Dictionary<string, string>(); Dictionary<string, string> param = new Dictionary<string, string>();
param["uuid"] = uuid.ToString(); param["uuid"] = uuid.ToString();
IDbCommand result = database.Query("SELECT * FROM users WHERE UUID = @uuid", param); IDbCommand result = database.Query("SELECT * FROM " + m_usersTableName + " WHERE UUID = @uuid", param);
IDataReader reader = result.ExecuteReader(); IDataReader reader = result.ExecuteReader();
UserProfileData row = database.readUserRow(reader); UserProfileData row = database.readUserRow(reader);
@ -238,7 +428,7 @@ namespace OpenSim.Framework.Data.MSSQL
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
return null; return null;
} }
} }
@ -321,7 +511,7 @@ namespace OpenSim.Framework.Data.MSSQL
Dictionary<string, string> param = new Dictionary<string, string>(); Dictionary<string, string> param = new Dictionary<string, string>();
param["uuid"] = uuid.ToString(); param["uuid"] = uuid.ToString();
IDbCommand result = database.Query("SELECT * FROM agents WHERE UUID = @uuid", param); IDbCommand result = database.Query("SELECT * FROM " + m_agentsTableName + " WHERE UUID = @uuid", param);
IDataReader reader = result.ExecuteReader(); IDataReader reader = result.ExecuteReader();
UserAgentData row = database.readAgentRow(reader); UserAgentData row = database.readAgentRow(reader);
@ -335,11 +525,17 @@ namespace OpenSim.Framework.Data.MSSQL
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
return null; return null;
} }
} }
public void StoreWebLoginKey(LLUUID AgentID, LLUUID WebLoginKey)
{
UserProfileData user = GetUserByUUID(AgentID);
user.webLoginKey = WebLoginKey;
UpdateUserProfile(user);
}
/// <summary> /// <summary>
/// Creates a new users profile /// Creates a new users profile
/// </summary> /// </summary>
@ -350,23 +546,116 @@ namespace OpenSim.Framework.Data.MSSQL
{ {
lock (database) lock (database)
{ {
database.insertUserRow(user.UUID, user.username, user.surname, user.passwordHash, user.passwordSalt, InsertUserRow(user.UUID, user.username, user.surname, user.passwordHash, user.passwordSalt,
user.homeRegion, user.homeLocation.X, user.homeLocation.Y, user.homeRegion, user.homeLocation.X, user.homeLocation.Y,
user.homeLocation.Z, user.homeLocation.Z,
user.homeLookAt.X, user.homeLookAt.Y, user.homeLookAt.Z, user.created, user.homeLookAt.X, user.homeLookAt.Y, user.homeLookAt.Z, user.created,
user.lastLogin, user.userInventoryURI, user.userAssetURI, user.lastLogin, user.userInventoryURI, user.userAssetURI,
user.profileCanDoMask, user.profileWantDoMask, user.profileCanDoMask, user.profileWantDoMask,
user.profileAboutText, user.profileFirstText, user.profileImage, user.profileAboutText, user.profileFirstText, user.profileImage,
user.profileFirstImage,user.webLoginKey); user.profileFirstImage, user.webLoginKey);
} }
} }
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
} }
} }
/// <summary>
/// Creates a new user and inserts it into the database
/// </summary>
/// <param name="uuid">User ID</param>
/// <param name="username">First part of the login</param>
/// <param name="lastname">Second part of the login</param>
/// <param name="passwordHash">A salted hash of the users password</param>
/// <param name="passwordSalt">The salt used for the password hash</param>
/// <param name="homeRegion">A regionHandle of the users home region</param>
/// <param name="homeLocX">Home region position vector</param>
/// <param name="homeLocY">Home region position vector</param>
/// <param name="homeLocZ">Home region position vector</param>
/// <param name="homeLookAtX">Home region 'look at' vector</param>
/// <param name="homeLookAtY">Home region 'look at' vector</param>
/// <param name="homeLookAtZ">Home region 'look at' vector</param>
/// <param name="created">Account created (unix timestamp)</param>
/// <param name="lastlogin">Last login (unix timestamp)</param>
/// <param name="inventoryURI">Users inventory URI</param>
/// <param name="assetURI">Users asset URI</param>
/// <param name="canDoMask">I can do mask</param>
/// <param name="wantDoMask">I want to do mask</param>
/// <param name="aboutText">Profile text</param>
/// <param name="firstText">Firstlife text</param>
/// <param name="profileImage">UUID for profile image</param>
/// <param name="firstImage">UUID for firstlife image</param>
/// <returns>Success?</returns>
private bool InsertUserRow(LLUUID uuid, string username, string lastname, 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,
LLUUID profileImage, LLUUID firstImage, LLUUID webLoginKey)
{
string sql = "INSERT INTO "+m_usersTableName;
sql += " ([UUID], [username], [lastname], [passwordHash], [passwordSalt], [homeRegion], ";
sql +=
"[homeLocationX], [homeLocationY], [homeLocationZ], [homeLookAtX], [homeLookAtY], [homeLookAtZ], [created], ";
sql +=
"[lastLogin], [userInventoryURI], [userAssetURI], [profileCanDoMask], [profileWantDoMask], [profileAboutText], ";
sql += "[profileFirstText], [profileImage], [profileFirstImage], [webLoginKey]) VALUES ";
sql += "(@UUID, @username, @lastname, @passwordHash, @passwordSalt, @homeRegion, ";
sql +=
"@homeLocationX, @homeLocationY, @homeLocationZ, @homeLookAtX, @homeLookAtY, @homeLookAtZ, @created, ";
sql +=
"@lastLogin, @userInventoryURI, @userAssetURI, @profileCanDoMask, @profileWantDoMask, @profileAboutText, ";
sql += "@profileFirstText, @profileImage, @profileFirstImage, @webLoginKey);";
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters["UUID"] = uuid.ToString();
parameters["username"] = username.ToString();
parameters["lastname"] = lastname.ToString();
parameters["passwordHash"] = passwordHash.ToString();
parameters["passwordSalt"] = passwordSalt.ToString();
parameters["homeRegion"] = homeRegion.ToString();
parameters["homeLocationX"] = homeLocX.ToString();
parameters["homeLocationY"] = homeLocY.ToString();
parameters["homeLocationZ"] = homeLocZ.ToString();
parameters["homeLookAtX"] = homeLookAtX.ToString();
parameters["homeLookAtY"] = homeLookAtY.ToString();
parameters["homeLookAtZ"] = homeLookAtZ.ToString();
parameters["created"] = created.ToString();
parameters["lastLogin"] = lastlogin.ToString();
parameters["userInventoryURI"] = String.Empty;
parameters["userAssetURI"] = String.Empty;
parameters["profileCanDoMask"] = "0";
parameters["profileWantDoMask"] = "0";
parameters["profileAboutText"] = String.Empty;
parameters["profileFirstText"] = String.Empty;
parameters["profileImage"] = LLUUID.Zero.ToString();
parameters["profileFirstImage"] = LLUUID.Zero.ToString();
parameters["webLoginKey"] = LLUUID.Random().ToString();
bool returnval = false;
try
{
IDbCommand result = database.Query(sql, parameters);
if (result.ExecuteNonQuery() == 1)
returnval = true;
result.Dispose();
}
catch (Exception e)
{
m_log.Error(e.ToString());
return false;
}
return returnval;
}
/// <summary> /// <summary>
/// Creates a new agent /// Creates a new agent
/// </summary> /// </summary>
@ -379,7 +668,7 @@ namespace OpenSim.Framework.Data.MSSQL
public bool UpdateUserProfile(UserProfileData user) public bool UpdateUserProfile(UserProfileData user)
{ {
SqlCommand command = new SqlCommand("UPDATE users set UUID = @uuid, " + SqlCommand command = new SqlCommand("UPDATE " + m_usersTableName + " set UUID = @uuid, " +
"username = @username, " + "username = @username, " +
"lastname = @lastname," + "lastname = @lastname," +
"passwordHash = @passwordHash," + "passwordHash = @passwordHash," +
@ -400,7 +689,8 @@ namespace OpenSim.Framework.Data.MSSQL
"profileAboutText = @profileAboutText," + "profileAboutText = @profileAboutText," +
"profileFirstText = @profileFirstText," + "profileFirstText = @profileFirstText," +
"profileImage = @profileImage," + "profileImage = @profileImage," +
"profileFirstImage = @profileFirstImage where " + "profileFirstImage = @profileFirstImage, " +
"webLoginKey = @webLoginKey where " +
"UUID = @keyUUUID;", database.getConnection()); "UUID = @keyUUUID;", database.getConnection());
SqlParameter param1 = new SqlParameter("@uuid", user.UUID.ToString()); SqlParameter param1 = new SqlParameter("@uuid", user.UUID.ToString());
SqlParameter param2 = new SqlParameter("@username", user.username); SqlParameter param2 = new SqlParameter("@username", user.username);
@ -425,6 +715,7 @@ namespace OpenSim.Framework.Data.MSSQL
SqlParameter param21 = new SqlParameter("@profileImage", LLUUID.Zero.ToString()); SqlParameter param21 = new SqlParameter("@profileImage", LLUUID.Zero.ToString());
SqlParameter param22 = new SqlParameter("@profileFirstImage", LLUUID.Zero.ToString()); SqlParameter param22 = new SqlParameter("@profileFirstImage", LLUUID.Zero.ToString());
SqlParameter param23 = new SqlParameter("@keyUUUID", user.UUID.ToString()); SqlParameter param23 = new SqlParameter("@keyUUUID", user.UUID.ToString());
SqlParameter param24 = new SqlParameter("@webLoginKey", user.webLoginKey.UUID.ToString());
command.Parameters.Add(param1); command.Parameters.Add(param1);
command.Parameters.Add(param2); command.Parameters.Add(param2);
command.Parameters.Add(param3); command.Parameters.Add(param3);
@ -448,6 +739,7 @@ namespace OpenSim.Framework.Data.MSSQL
command.Parameters.Add(param21); command.Parameters.Add(param21);
command.Parameters.Add(param22); command.Parameters.Add(param22);
command.Parameters.Add(param23); command.Parameters.Add(param23);
command.Parameters.Add(param24);
try try
{ {
int affected = command.ExecuteNonQuery(); int affected = command.ExecuteNonQuery();
@ -462,7 +754,7 @@ namespace OpenSim.Framework.Data.MSSQL
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
} }
return false; return false;
} }

View File

@ -1,3 +1,31 @@
/*
* 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 OpenSim 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.Reflection; using System.Reflection;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
@ -10,7 +38,7 @@ using System.Runtime.InteropServices;
[assembly : AssemblyConfiguration("")] [assembly : AssemblyConfiguration("")]
[assembly : AssemblyCompany("")] [assembly : AssemblyCompany("")]
[assembly : AssemblyProduct("OpenSim.Framework.Data.MSSQL")] [assembly : AssemblyProduct("OpenSim.Framework.Data.MSSQL")]
[assembly : AssemblyCopyright("Copyright © 2007")] [assembly : AssemblyCopyright("Copyright © OpenSimulator.org Developers 2007-2008")]
[assembly : AssemblyTrademark("")] [assembly : AssemblyTrademark("")]
[assembly : AssemblyCulture("")] [assembly : AssemblyCulture("")]

View File

@ -0,0 +1,14 @@
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [dbo].[userfriends](
[ownerID] [varchar](50) COLLATE Latin1_General_CI_AS NOT NULL,
[friendID] [varchar](50) COLLATE Latin1_General_CI_AS NOT NULL,
[friendPerms] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[datetimestamp] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
) ON [PRIMARY]
SET ANSI_PADDING OFF

View File

@ -0,0 +1,40 @@
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
SET ANSI_PADDING ON
CREATE TABLE [dbo].[regions](
[regionHandle] [varchar](255) COLLATE Latin1_General_CI_AS NULL,
[regionName] [varchar](255) COLLATE Latin1_General_CI_AS NULL,
[uuid] [varchar](255) COLLATE Latin1_General_CI_AS NOT NULL,
[regionRecvKey] [varchar](255) COLLATE Latin1_General_CI_AS NULL,
[regionSecret] [varchar](255) COLLATE Latin1_General_CI_AS NULL,
[regionSendKey] [varchar](255) COLLATE Latin1_General_CI_AS NULL,
[regionDataURI] [varchar](255) COLLATE Latin1_General_CI_AS NULL,
[serverIP] [varchar](255) COLLATE Latin1_General_CI_AS NULL,
[serverPort] [varchar](255) COLLATE Latin1_General_CI_AS NULL,
[serverURI] [varchar](255) COLLATE Latin1_General_CI_AS NULL,
[locX] [varchar](255) COLLATE Latin1_General_CI_AS NULL,
[locY] [varchar](255) COLLATE Latin1_General_CI_AS NULL,
[locZ] [varchar](255) COLLATE Latin1_General_CI_AS NULL,
[eastOverrideHandle] [varchar](255) COLLATE Latin1_General_CI_AS NULL,
[westOverrideHandle] [varchar](255) COLLATE Latin1_General_CI_AS NULL,
[southOverrideHandle] [varchar](255) COLLATE Latin1_General_CI_AS NULL,
[northOverrideHandle] [varchar](255) COLLATE Latin1_General_CI_AS NULL,
[regionAssetURI] [varchar](255) COLLATE Latin1_General_CI_AS NULL,
[regionAssetRecvKey] [varchar](255) COLLATE Latin1_General_CI_AS NULL,
[regionAssetSendKey] [varchar](255) COLLATE Latin1_General_CI_AS NULL,
[regionUserURI] [varchar](255) COLLATE Latin1_General_CI_AS NULL,
[regionUserRecvKey] [varchar](255) COLLATE Latin1_General_CI_AS NULL,
[regionUserSendKey] [varchar](255) COLLATE Latin1_General_CI_AS NULL,
[regionMapTexture] [varchar](255) COLLATE Latin1_General_CI_AS NULL,
[serverHttpPort] [varchar](255) COLLATE Latin1_General_CI_AS NULL,
[serverRemotingPort] [varchar](255) COLLATE Latin1_General_CI_AS NULL,
PRIMARY KEY CLUSTERED
(
[uuid] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
SET ANSI_PADDING OFF

View File

@ -13,7 +13,7 @@
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS AS IS AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
@ -37,6 +37,8 @@ namespace OpenSim.Framework.Data.MySQL
{ {
internal class MySQLAssetData : IAssetProvider internal class MySQLAssetData : IAssetProvider
{ {
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private MySQLManager _dbConnection; private MySQLManager _dbConnection;
#region IAssetProvider Members #region IAssetProvider Members
@ -46,7 +48,7 @@ namespace OpenSim.Framework.Data.MySQL
// null as the version, indicates that the table didn't exist // null as the version, indicates that the table didn't exist
if (oldVersion == null) if (oldVersion == null)
{ {
MainLog.Instance.Notice("ASSETS", "Creating new database tables"); m_log.Info("[ASSETS]: Creating new database tables");
_dbConnection.ExecuteResourceSql("CreateAssetsTable.sql"); _dbConnection.ExecuteResourceSql("CreateAssetsTable.sql");
return; return;
} }
@ -76,6 +78,7 @@ namespace OpenSim.Framework.Data.MySQL
_dbConnection.Connection); _dbConnection.Connection);
MySqlParameter p = cmd.Parameters.Add("?id", MySqlDbType.Binary, 16); MySqlParameter p = cmd.Parameters.Add("?id", MySqlDbType.Binary, 16);
p.Value = assetID.GetBytes(); p.Value = assetID.GetBytes();
try try
{ {
using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow)) using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
@ -95,9 +98,12 @@ namespace OpenSim.Framework.Data.MySQL
cmd.Dispose(); cmd.Dispose();
} }
} }
catch (Exception) catch (Exception e)
{ {
MainLog.Instance.Warn("ASSETS", "MySql failure fetching asset"); m_log.ErrorFormat(
"[ASSETS]: MySql failure fetching asset {0}" + Environment.NewLine + e.ToString()
+ Environment.NewLine + "Attempting reconnection", assetID);
_dbConnection.Reconnect();
} }
} }
return asset; return asset;
@ -105,26 +111,40 @@ namespace OpenSim.Framework.Data.MySQL
public void CreateAsset(AssetBase asset) public void CreateAsset(AssetBase asset)
{ {
MySqlCommand cmd = lock (_dbConnection)
new MySqlCommand(
"REPLACE INTO assets(id, name, description, assetType, invType, local, temporary, data)" +
"VALUES(?id, ?name, ?description, ?assetType, ?invType, ?local, ?temporary, ?data)",
_dbConnection.Connection);
// need to ensure we dispose
using (cmd)
{ {
MySqlParameter p = cmd.Parameters.Add("?id", MySqlDbType.Binary, 16); MySqlCommand cmd =
p.Value = asset.FullID.GetBytes(); new MySqlCommand(
cmd.Parameters.AddWithValue("?name", asset.Name); "REPLACE INTO assets(id, name, description, assetType, invType, local, temporary, data)" +
cmd.Parameters.AddWithValue("?description", asset.Description); "VALUES(?id, ?name, ?description, ?assetType, ?invType, ?local, ?temporary, ?data)",
cmd.Parameters.AddWithValue("?assetType", asset.Type); _dbConnection.Connection);
cmd.Parameters.AddWithValue("?invType", asset.InvType);
cmd.Parameters.AddWithValue("?local", asset.Local); // need to ensure we dispose
cmd.Parameters.AddWithValue("?temporary", asset.Temporary); try
cmd.Parameters.AddWithValue("?data", asset.Data); {
cmd.ExecuteNonQuery(); using (cmd)
cmd.Dispose(); {
MySqlParameter p = cmd.Parameters.Add("?id", MySqlDbType.Binary, 16);
p.Value = asset.FullID.GetBytes();
cmd.Parameters.AddWithValue("?name", asset.Name);
cmd.Parameters.AddWithValue("?description", asset.Description);
cmd.Parameters.AddWithValue("?assetType", asset.Type);
cmd.Parameters.AddWithValue("?invType", asset.InvType);
cmd.Parameters.AddWithValue("?local", asset.Local);
cmd.Parameters.AddWithValue("?temporary", asset.Temporary);
cmd.Parameters.AddWithValue("?data", asset.Data);
cmd.ExecuteNonQuery();
cmd.Dispose();
}
}
catch (Exception e)
{
m_log.ErrorFormat(
"[ASSETS]: " +
"MySql failure creating asset {0} with name {1}" + Environment.NewLine + e.ToString()
+ Environment.NewLine + "Attempting reconnection", asset.FullID, asset.Name);
_dbConnection.Reconnect();
}
} }
} }

View File

@ -42,8 +42,11 @@ namespace OpenSim.Framework.Data.MySQL
{ {
public class MySQLDataStore : IRegionDataStore public class MySQLDataStore : IRegionDataStore
{ {
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private const string m_primSelect = "select * from prims"; private const string m_primSelect = "select * from prims";
private const string m_shapeSelect = "select * from primshapes"; private const string m_shapeSelect = "select * from primshapes";
private const string m_itemsSelect = "select * from primitems";
private const string m_terrainSelect = "select * from terrain limit 1"; private const string m_terrainSelect = "select * from terrain limit 1";
private const string m_landSelect = "select * from land"; private const string m_landSelect = "select * from land";
private const string m_landAccessListSelect = "select * from landaccesslist"; private const string m_landAccessListSelect = "select * from landaccesslist";
@ -51,16 +54,22 @@ namespace OpenSim.Framework.Data.MySQL
private DataSet m_dataSet; private DataSet m_dataSet;
private MySqlDataAdapter m_primDataAdapter; private MySqlDataAdapter m_primDataAdapter;
private MySqlDataAdapter m_shapeDataAdapter; private MySqlDataAdapter m_shapeDataAdapter;
private MySqlDataAdapter m_itemsDataAdapter;
private MySqlConnection m_connection; private MySqlConnection m_connection;
private MySqlDataAdapter m_terrainDataAdapter; private MySqlDataAdapter m_terrainDataAdapter;
private MySqlDataAdapter m_landDataAdapter; private MySqlDataAdapter m_landDataAdapter;
private MySqlDataAdapter m_landAccessListDataAdapter; private MySqlDataAdapter m_landAccessListDataAdapter;
private DataTable m_primTable; private DataTable m_primTable;
private DataTable m_shapeTable; private DataTable m_shapeTable;
private DataTable m_itemsTable;
private DataTable m_terrainTable; private DataTable m_terrainTable;
private DataTable m_landTable; private DataTable m_landTable;
private DataTable m_landAccessListTable; private DataTable m_landAccessListTable;
// Temporary attribute while this is experimental
private bool persistPrimInventories;
/*********************************************************************** /***********************************************************************
* *
* Public Interface Functions * Public Interface Functions
@ -71,8 +80,9 @@ namespace OpenSim.Framework.Data.MySQL
public void Initialise(string connectionstring, bool persistPrimInventories) public void Initialise(string connectionstring, bool persistPrimInventories)
{ {
m_dataSet = new DataSet(); m_dataSet = new DataSet();
this.persistPrimInventories = persistPrimInventories;
MainLog.Instance.Verbose("DATASTORE", "MySql - connecting: " + connectionstring); m_log.Info("[DATASTORE]: MySql - connecting: " + connectionstring);
m_connection = new MySqlConnection(connectionstring); m_connection = new MySqlConnection(connectionstring);
MySqlCommand primSelectCmd = new MySqlCommand(m_primSelect, m_connection); MySqlCommand primSelectCmd = new MySqlCommand(m_primSelect, m_connection);
@ -81,6 +91,9 @@ namespace OpenSim.Framework.Data.MySQL
MySqlCommand shapeSelectCmd = new MySqlCommand(m_shapeSelect, m_connection); MySqlCommand shapeSelectCmd = new MySqlCommand(m_shapeSelect, m_connection);
m_shapeDataAdapter = new MySqlDataAdapter(shapeSelectCmd); m_shapeDataAdapter = new MySqlDataAdapter(shapeSelectCmd);
MySqlCommand itemsSelectCmd = new MySqlCommand(m_itemsSelect, m_connection);
m_itemsDataAdapter = new MySqlDataAdapter(itemsSelectCmd);
MySqlCommand terrainSelectCmd = new MySqlCommand(m_terrainSelect, m_connection); MySqlCommand terrainSelectCmd = new MySqlCommand(m_terrainSelect, m_connection);
m_terrainDataAdapter = new MySqlDataAdapter(terrainSelectCmd); m_terrainDataAdapter = new MySqlDataAdapter(terrainSelectCmd);
@ -104,6 +117,14 @@ namespace OpenSim.Framework.Data.MySQL
SetupShapeCommands(m_shapeDataAdapter, m_connection); SetupShapeCommands(m_shapeDataAdapter, m_connection);
m_shapeDataAdapter.Fill(m_shapeTable); m_shapeDataAdapter.Fill(m_shapeTable);
if (persistPrimInventories)
{
m_itemsTable = createItemsTable();
m_dataSet.Tables.Add(m_itemsTable);
SetupItemsCommands(m_itemsDataAdapter, m_connection);
m_itemsDataAdapter.Fill(m_itemsTable);
}
m_terrainTable = createTerrainTable(); m_terrainTable = createTerrainTable();
m_dataSet.Tables.Add(m_terrainTable); m_dataSet.Tables.Add(m_terrainTable);
SetupTerrainCommands(m_terrainDataAdapter, m_connection); SetupTerrainCommands(m_terrainDataAdapter, m_connection);
@ -129,12 +150,12 @@ namespace OpenSim.Framework.Data.MySQL
{ {
if ((prim.ObjectFlags & (uint) LLObject.ObjectFlags.Physics) == 0) if ((prim.ObjectFlags & (uint) LLObject.ObjectFlags.Physics) == 0)
{ {
MainLog.Instance.Verbose("DATASTORE", "Adding obj: " + obj.UUID + " to region: " + regionUUID); m_log.Info("[DATASTORE]: Adding obj: " + obj.UUID + " to region: " + regionUUID);
addPrim(prim, obj.UUID, regionUUID); addPrim(prim, obj.UUID, regionUUID);
} }
else else
{ {
// MainLog.Instance.Verbose("DATASTORE", "Ignoring Physical obj: " + obj.UUID + " in region: " + regionUUID); // m_log.Info("[DATASTORE]: Ignoring Physical obj: " + obj.UUID + " in region: " + regionUUID);
} }
} }
} }
@ -144,6 +165,8 @@ namespace OpenSim.Framework.Data.MySQL
public void RemoveObject(LLUUID obj, LLUUID regionUUID) public void RemoveObject(LLUUID obj, LLUUID regionUUID)
{ {
m_log.InfoFormat("[DATASTORE]: Removing obj: {0} from region: {1}", obj.UUID, regionUUID);
DataTable prims = m_primTable; DataTable prims = m_primTable;
DataTable shapes = m_shapeTable; DataTable shapes = m_shapeTable;
@ -153,12 +176,20 @@ namespace OpenSim.Framework.Data.MySQL
DataRow[] primRows = prims.Select(selectExp); DataRow[] primRows = prims.Select(selectExp);
foreach (DataRow row in primRows) foreach (DataRow row in primRows)
{ {
// Remove shapes row
LLUUID uuid = new LLUUID((string) row["UUID"]); LLUUID uuid = new LLUUID((string) row["UUID"]);
DataRow shapeRow = shapes.Rows.Find(Util.ToRawUuidString(uuid)); DataRow shapeRow = shapes.Rows.Find(Util.ToRawUuidString(uuid));
if (shapeRow != null) if (shapeRow != null)
{ {
shapeRow.Delete(); shapeRow.Delete();
} }
if (persistPrimInventories)
{
RemoveItems(uuid);
}
// Remove prim row
row.Delete(); row.Delete();
} }
} }
@ -166,6 +197,24 @@ namespace OpenSim.Framework.Data.MySQL
Commit(); Commit();
} }
/// <summary>
/// Remove all persisted items of the given prim.
/// The caller must acquire the necessrary synchronization locks and commit or rollback changes.
/// </summary>
private void RemoveItems(LLUUID uuid)
{
String sql = String.Format("primID = '{0}'", uuid);
DataRow[] itemRows = m_itemsTable.Select(sql);
foreach (DataRow itemRow in itemRows)
{
itemRow.Delete();
}
}
/// <summary>
/// Load persisted objects from region storage.
/// </summary>
public List<SceneObjectGroup> LoadObjects(LLUUID regionUUID) public List<SceneObjectGroup> LoadObjects(LLUUID regionUUID)
{ {
Dictionary<LLUUID, SceneObjectGroup> createdObjects = new Dictionary<LLUUID, SceneObjectGroup>(); Dictionary<LLUUID, SceneObjectGroup> createdObjects = new Dictionary<LLUUID, SceneObjectGroup>();
@ -181,7 +230,7 @@ namespace OpenSim.Framework.Data.MySQL
lock (m_dataSet) lock (m_dataSet)
{ {
DataRow[] primsForRegion = prims.Select(byRegion, orderByParent); DataRow[] primsForRegion = prims.Select(byRegion, orderByParent);
MainLog.Instance.Verbose("DATASTORE", m_log.Info("[DATASTORE]: " +
"Loaded " + primsForRegion.Length + " prims for region: " + regionUUID); "Loaded " + primsForRegion.Length + " prims for region: " + regionUUID);
foreach (DataRow primRow in primsForRegion) foreach (DataRow primRow in primsForRegion)
@ -190,10 +239,13 @@ namespace OpenSim.Framework.Data.MySQL
{ {
string uuid = (string) primRow["UUID"]; string uuid = (string) primRow["UUID"];
string objID = (string) primRow["SceneGroupID"]; string objID = (string) primRow["SceneGroupID"];
SceneObjectPart prim = buildPrim(primRow);
if (uuid == objID) //is new SceneObjectGroup ? if (uuid == objID) //is new SceneObjectGroup ?
{ {
SceneObjectGroup group = new SceneObjectGroup(); SceneObjectGroup group = new SceneObjectGroup();
SceneObjectPart prim = buildPrim(primRow);
DataRow shapeRow = shapes.Rows.Find(Util.ToRawUuidString(prim.UUID)); DataRow shapeRow = shapes.Rows.Find(Util.ToRawUuidString(prim.UUID));
if (shapeRow != null) if (shapeRow != null)
{ {
@ -201,7 +253,7 @@ namespace OpenSim.Framework.Data.MySQL
} }
else else
{ {
MainLog.Instance.Notice( m_log.Info(
"No shape found for prim in storage, so setting default box shape"); "No shape found for prim in storage, so setting default box shape");
prim.Shape = PrimitiveBaseShape.Default; prim.Shape = PrimitiveBaseShape.Default;
} }
@ -213,7 +265,6 @@ namespace OpenSim.Framework.Data.MySQL
} }
else else
{ {
SceneObjectPart prim = buildPrim(primRow);
DataRow shapeRow = shapes.Rows.Find(Util.ToRawUuidString(prim.UUID)); DataRow shapeRow = shapes.Rows.Find(Util.ToRawUuidString(prim.UUID));
if (shapeRow != null) if (shapeRow != null)
{ {
@ -221,20 +272,25 @@ namespace OpenSim.Framework.Data.MySQL
} }
else else
{ {
MainLog.Instance.Notice( m_log.Info(
"No shape found for prim in storage, so setting default box shape"); "No shape found for prim in storage, so setting default box shape");
prim.Shape = PrimitiveBaseShape.Default; prim.Shape = PrimitiveBaseShape.Default;
} }
createdObjects[new LLUUID(objID)].AddPart(prim); createdObjects[new LLUUID(objID)].AddPart(prim);
} }
if (persistPrimInventories)
{
LoadItems(prim);
}
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Error("DATASTORE", "Failed create prim object, exception and data follows"); m_log.Error("[DATASTORE]: Failed create prim object, exception and data follows");
MainLog.Instance.Verbose("DATASTORE", e.ToString()); m_log.Info("[DATASTORE]: " + e.ToString());
foreach (DataColumn col in prims.Columns) foreach (DataColumn col in prims.Columns)
{ {
MainLog.Instance.Verbose("DATASTORE", "Col: " + col.ColumnName + " => " + primRow[col]); m_log.Info("[DATASTORE]: Col: " + col.ColumnName + " => " + primRow[col]);
} }
} }
} }
@ -242,11 +298,43 @@ namespace OpenSim.Framework.Data.MySQL
return retvals; return retvals;
} }
/// <summary>
/// Load in a prim's persisted inventory.
/// </summary>
/// <param name="prim"></param>
private void LoadItems(SceneObjectPart prim)
{
//m_log.InfoFormat("[DATASTORE]: Loading inventory for {0}, {1}", prim.Name, prim.UUID);
DataTable dbItems = m_itemsTable;
String sql = String.Format("primID = '{0}'", prim.UUID.ToString());
DataRow[] dbItemRows = dbItems.Select(sql);
IList<TaskInventoryItem> inventory = new List<TaskInventoryItem>();
foreach (DataRow row in dbItemRows)
{
TaskInventoryItem item = buildItem(row);
inventory.Add(item);
//m_log.DebugFormat("[DATASTORE]: Restored item {0}, {1}", item.Name, item.ItemID);
}
prim.RestoreInventoryItems(inventory);
// XXX A nasty little hack to recover the folder id for the prim (which is currently stored in
// every item). This data should really be stored in the prim table itself.
if (dbItemRows.Length > 0)
{
prim.FolderID = inventory[0].ParentID;
}
}
public void StoreTerrain(double[,] ter, LLUUID regionID) public void StoreTerrain(double[,] ter, LLUUID regionID)
{ {
int revision = Util.UnixTimeSinceEpoch(); int revision = Util.UnixTimeSinceEpoch();
MainLog.Instance.Verbose("DATASTORE", "Storing terrain revision r" + revision.ToString()); m_log.Info("[DATASTORE]: Storing terrain revision r" + revision.ToString());
DataTable terrain = m_dataSet.Tables["terrain"]; DataTable terrain = m_dataSet.Tables["terrain"];
lock (m_dataSet) lock (m_dataSet)
@ -286,23 +374,24 @@ namespace OpenSim.Framework.Data.MySQL
int rev = 0; int rev = 0;
if (row.Read()) if (row.Read())
{ {
byte[] heightmap = (byte[]) row["Heightfield"]; MemoryStream str = new MemoryStream((byte[]) row["Heightfield"]);
BinaryReader br = new BinaryReader(str);
for (int x = 0; x < 256; x++) for (int x = 0; x < 256; x++)
{ {
for (int y = 0; y < 256; y++) for (int y = 0; y < 256; y++)
{ {
terret[x, y] = BitConverter.ToDouble(heightmap, ((x*256) + y)*8); terret[x, y] = br.ReadDouble();
} }
} }
rev = (int) row["Revision"]; rev = (int) row["Revision"];
} }
else else
{ {
MainLog.Instance.Verbose("DATASTORE", "No terrain found for region"); m_log.Info("[DATASTORE]: No terrain found for region");
return null; return null;
} }
MainLog.Instance.Verbose("DATASTORE", "Loaded terrain revision r" + rev.ToString()); m_log.Info("[DATASTORE]: Loaded terrain revision r" + rev.ToString());
} }
return terret; return terret;
@ -328,8 +417,13 @@ namespace OpenSim.Framework.Data.MySQL
} }
} }
static Random rnd = new Random();
public void StoreLandObject(Land parcel, LLUUID regionUUID) public void StoreLandObject(Land parcel, LLUUID regionUUID)
{ {
// Does the new locking fix it?
m_log.Info("[DATASTORE]: Tedds temp fix: Waiting 3 seconds to avoid others writing to table while we hold a dataset of it. (Someone please fix! :))");
System.Threading.Thread.Sleep(2500 + rnd.Next(0, 1000));
lock (m_dataSet) lock (m_dataSet)
{ {
DataTable land = m_landTable; DataTable land = m_landTable;
@ -361,8 +455,8 @@ namespace OpenSim.Framework.Data.MySQL
fillLandAccessRow(newAccessRow, entry, parcel.landData.globalID); fillLandAccessRow(newAccessRow, entry, parcel.landData.globalID);
landaccesslist.Rows.Add(newAccessRow); landaccesslist.Rows.Add(newAccessRow);
} }
}
}
Commit(); Commit();
} }
@ -408,7 +502,7 @@ namespace OpenSim.Framework.Data.MySQL
foreach (DataColumn column in table.Columns) foreach (DataColumn column in table.Columns)
Debug.Write(column.ColumnName + " = " + Debug.Write(column.ColumnName + " = " +
row[column, DataRowVersion.Original] + ", "); row[column, DataRowVersion.Original] + ", ");
Debug.WriteLine(""); Debug.WriteLine(String.Empty);
} }
//--- Display the current values, if there are any. //--- Display the current values, if there are any.
if (row.HasVersion(DataRowVersion.Current)) if (row.HasVersion(DataRowVersion.Current))
@ -417,9 +511,9 @@ namespace OpenSim.Framework.Data.MySQL
foreach (DataColumn column in table.Columns) foreach (DataColumn column in table.Columns)
Debug.Write(column.ColumnName + " = " + Debug.Write(column.ColumnName + " = " +
row[column, DataRowVersion.Current] + ", "); row[column, DataRowVersion.Current] + ", ");
Debug.WriteLine(""); Debug.WriteLine(String.Empty);
} }
Debug.WriteLine(""); Debug.WriteLine(String.Empty);
} }
} }
} }
@ -437,6 +531,12 @@ namespace OpenSim.Framework.Data.MySQL
m_primDataAdapter.Update(m_primTable); m_primDataAdapter.Update(m_primTable);
m_shapeDataAdapter.Update(m_shapeTable); m_shapeDataAdapter.Update(m_shapeTable);
if (persistPrimInventories)
{
m_itemsDataAdapter.Update(m_itemsTable);
}
m_terrainDataAdapter.Update(m_terrainTable); m_terrainDataAdapter.Update(m_terrainTable);
m_landDataAdapter.Update(m_landTable); m_landDataAdapter.Update(m_landTable);
m_landAccessListDataAdapter.Update(m_landAccessListTable); m_landAccessListDataAdapter.Update(m_landAccessListTable);
@ -445,6 +545,7 @@ namespace OpenSim.Framework.Data.MySQL
} }
} }
public void Shutdown() public void Shutdown()
{ {
Commit(); Commit();
@ -631,6 +732,38 @@ namespace OpenSim.Framework.Data.MySQL
return shapes; return shapes;
} }
private DataTable createItemsTable()
{
DataTable items = new DataTable("primitems");
createCol(items, "itemID", typeof (String));
createCol(items, "primID", typeof (String));
createCol(items, "assetID", typeof (String));
createCol(items, "parentFolderID", typeof (String));
createCol(items, "invType", typeof (Int32));
createCol(items, "assetType", typeof (Int32));
createCol(items, "name", typeof (String));
createCol(items, "description", typeof (String));
createCol(items, "creationDate", typeof (Int64));
createCol(items, "creatorID", typeof (String));
createCol(items, "ownerID", typeof (String));
createCol(items, "lastOwnerID", typeof (String));
createCol(items, "groupID", typeof (String));
createCol(items, "nextPermissions", typeof (Int32));
createCol(items, "currentPermissions", typeof (Int32));
createCol(items, "basePermissions", typeof (Int32));
createCol(items, "everyonePermissions", typeof (Int32));
createCol(items, "groupPermissions", typeof (Int32));
items.PrimaryKey = new DataColumn[] {items.Columns["itemID"]};
return items;
}
/*********************************************************************** /***********************************************************************
* *
* Convert between ADO.NET <=> OpenSim Objects * Convert between ADO.NET <=> OpenSim Objects
@ -728,6 +861,41 @@ namespace OpenSim.Framework.Data.MySQL
return prim; return prim;
} }
/// <summary>
/// Build a prim inventory item from the persisted data.
/// </summary>
/// <param name="row"></param>
/// <returns></returns>
private TaskInventoryItem buildItem(DataRow row)
{
TaskInventoryItem taskItem = new TaskInventoryItem();
taskItem.ItemID = new LLUUID((String)row["itemID"]);
taskItem.ParentPartID = new LLUUID((String)row["primID"]);
taskItem.AssetID = new LLUUID((String)row["assetID"]);
taskItem.ParentID = new LLUUID((String)row["parentFolderID"]);
taskItem.InvType = Convert.ToInt32(row["invType"]);
taskItem.Type = Convert.ToInt32(row["assetType"]);
taskItem.Name = (String)row["name"];
taskItem.Description = (String)row["description"];
taskItem.CreationDate = Convert.ToUInt32(row["creationDate"]);
taskItem.CreatorID = new LLUUID((String)row["creatorID"]);
taskItem.OwnerID = new LLUUID((String)row["ownerID"]);
taskItem.LastOwnerID = new LLUUID((String)row["lastOwnerID"]);
taskItem.GroupID = new LLUUID((String)row["groupID"]);
taskItem.NextOwnerMask = Convert.ToUInt32(row["nextPermissions"]);
taskItem.OwnerMask = Convert.ToUInt32(row["currentPermissions"]);
taskItem.BaseMask = Convert.ToUInt32(row["basePermissions"]);
taskItem.EveryoneMask = Convert.ToUInt32(row["everyonePermissions"]);
taskItem.GroupMask = Convert.ToUInt32(row["groupPermissions"]);
return taskItem;
}
private LandData buildLandData(DataRow row) private LandData buildLandData(DataRow row)
{ {
LandData newData = new LandData(); LandData newData = new LandData();
@ -871,6 +1039,30 @@ namespace OpenSim.Framework.Data.MySQL
} }
} }
private void fillItemRow(DataRow row, TaskInventoryItem taskItem)
{
row["itemID"] = taskItem.ItemID;
row["primID"] = taskItem.ParentPartID;
row["assetID"] = taskItem.AssetID;
row["parentFolderID"] = taskItem.ParentID;
row["invType"] = taskItem.InvType;
row["assetType"] = taskItem.Type;
row["name"] = taskItem.Name;
row["description"] = taskItem.Description;
row["creationDate"] = taskItem.CreationDate;
row["creatorID"] = taskItem.CreatorID;
row["ownerID"] = taskItem.OwnerID;
row["lastOwnerID"] = taskItem.LastOwnerID;
row["groupID"] = taskItem.GroupID;
row["nextPermissions"] = taskItem.NextOwnerMask;
row["currentPermissions"] = taskItem.OwnerMask;
row["basePermissions"] = taskItem.BaseMask;
row["everyonePermissions"] = taskItem.EveryoneMask;
row["groupPermissions"] = taskItem.GroupMask;
}
private void fillLandRow(DataRow row, LandData land, LLUUID regionUUID) private void fillLandRow(DataRow row, LandData land, LLUUID regionUUID)
{ {
row["UUID"] = Util.ToRawUuidString(land.globalID); row["UUID"] = Util.ToRawUuidString(land.globalID);
@ -1019,6 +1211,37 @@ namespace OpenSim.Framework.Data.MySQL
} }
} }
// see IRegionDatastore
public void StorePrimInventory(LLUUID primID, ICollection<TaskInventoryItem> items)
{
if (!persistPrimInventories)
return;
m_log.InfoFormat("[DATASTORE]: Persisting Prim Inventory with prim ID {0}", primID);
// For now, we're just going to crudely remove all the previous inventory items
// no matter whether they have changed or not, and replace them with the current set.
lock (m_dataSet)
{
RemoveItems(primID);
// repalce with current inventory details
foreach (TaskInventoryItem newItem in items)
{
// m_log.InfoFormat(
// "[DATASTORE]: " +
// "Adding item {0}, {1} to prim ID {2}",
// newItem.Name, newItem.ItemID, newItem.ParentPartID);
DataRow newItemRow = m_itemsTable.NewRow();
fillItemRow(newItemRow, newItem);
m_itemsTable.Rows.Add(newItemRow);
}
}
Commit();
}
/*********************************************************************** /***********************************************************************
* *
* SQL Statement Creation Functions * SQL Statement Creation Functions
@ -1067,7 +1290,7 @@ namespace OpenSim.Framework.Data.MySQL
private MySqlCommand createUpdateCommand(string table, string pk, DataTable dt) private MySqlCommand createUpdateCommand(string table, string pk, DataTable dt)
{ {
string sql = "update " + table + " set "; string sql = "update " + table + " set ";
string subsql = ""; string subsql = String.Empty;
foreach (DataColumn col in dt.Columns) foreach (DataColumn col in dt.Columns)
{ {
if (subsql.Length > 0) if (subsql.Length > 0)
@ -1091,11 +1314,10 @@ namespace OpenSim.Framework.Data.MySQL
return cmd; return cmd;
} }
private string defineTable(DataTable dt) private string defineTable(DataTable dt)
{ {
string sql = "create table " + dt.TableName + "("; string sql = "create table " + dt.TableName + "(";
string subsql = ""; string subsql = String.Empty;
foreach (DataColumn col in dt.Columns) foreach (DataColumn col in dt.Columns)
{ {
if (subsql.Length > 0) if (subsql.Length > 0)
@ -1111,6 +1333,9 @@ namespace OpenSim.Framework.Data.MySQL
} }
sql += subsql; sql += subsql;
sql += ")"; sql += ")";
//m_log.InfoFormat("[DATASTORE]: defineTable() sql {0}", sql);
return sql; return sql;
} }
@ -1167,6 +1392,20 @@ namespace OpenSim.Framework.Data.MySQL
da.DeleteCommand = delete; da.DeleteCommand = delete;
} }
private void SetupItemsCommands(MySqlDataAdapter da, MySqlConnection conn)
{
da.InsertCommand = createInsertCommand("primitems", m_itemsTable);
da.InsertCommand.Connection = conn;
da.UpdateCommand = createUpdateCommand("primitems", "itemID = ?itemID", m_itemsTable);
da.UpdateCommand.Connection = conn;
MySqlCommand delete = new MySqlCommand("delete from primitems where itemID = ?itemID");
delete.Parameters.Add(createMySqlParameter("itemID", typeof (String)));
delete.Connection = conn;
da.DeleteCommand = delete;
}
private void SetupTerrainCommands(MySqlDataAdapter da, MySqlConnection conn) private void SetupTerrainCommands(MySqlDataAdapter da, MySqlConnection conn)
{ {
da.InsertCommand = createInsertCommand("terrain", m_dataSet.Tables["terrain"]); da.InsertCommand = createInsertCommand("terrain", m_dataSet.Tables["terrain"]);
@ -1206,64 +1445,84 @@ namespace OpenSim.Framework.Data.MySQL
{ {
string createPrims = defineTable(createPrimTable()); string createPrims = defineTable(createPrimTable());
string createShapes = defineTable(createShapeTable()); string createShapes = defineTable(createShapeTable());
string createItems = defineTable(createItemsTable());
string createTerrain = defineTable(createTerrainTable()); string createTerrain = defineTable(createTerrainTable());
string createLand = defineTable(createLandTable()); string createLand = defineTable(createLandTable());
string createLandAccessList = defineTable(createLandAccessListTable()); string createLandAccessList = defineTable(createLandAccessListTable());
MySqlCommand pcmd = new MySqlCommand(createPrims, conn); MySqlCommand pcmd = new MySqlCommand(createPrims, conn);
MySqlCommand scmd = new MySqlCommand(createShapes, conn); MySqlCommand scmd = new MySqlCommand(createShapes, conn);
MySqlCommand icmd = new MySqlCommand(createItems, conn);
MySqlCommand tcmd = new MySqlCommand(createTerrain, conn); MySqlCommand tcmd = new MySqlCommand(createTerrain, conn);
MySqlCommand lcmd = new MySqlCommand(createLand, conn); MySqlCommand lcmd = new MySqlCommand(createLand, conn);
MySqlCommand lalcmd = new MySqlCommand(createLandAccessList, conn); MySqlCommand lalcmd = new MySqlCommand(createLandAccessList, conn);
if (conn.State != ConnectionState.Open) if (conn.State != ConnectionState.Open)
{ {
conn.Open(); try
{
conn.Open();
}
catch (Exception ex)
{
m_log.Error("[MySql]: Error connecting to MySQL server: " + ex.Message);
m_log.Error("[MySql]: Application is terminating!");
System.Threading.Thread.CurrentThread.Abort();
}
} }
try try
{ {
pcmd.ExecuteNonQuery(); pcmd.ExecuteNonQuery();
} }
catch (MySqlException) catch (MySqlException e)
{ {
MainLog.Instance.Warn("MySql", "Primitives Table Already Exists"); m_log.WarnFormat("[MySql]: Primitives Table Already Exists: {0}", e);
} }
try try
{ {
scmd.ExecuteNonQuery(); scmd.ExecuteNonQuery();
} }
catch (MySqlException) catch (MySqlException e)
{ {
MainLog.Instance.Warn("MySql", "Shapes Table Already Exists"); m_log.WarnFormat("[MySql]: Shapes Table Already Exists: {0}", e);
}
try
{
icmd.ExecuteNonQuery();
}
catch (MySqlException e)
{
m_log.WarnFormat("[MySql]: Items Table Already Exists: {0}", e);
} }
try try
{ {
tcmd.ExecuteNonQuery(); tcmd.ExecuteNonQuery();
} }
catch (MySqlException) catch (MySqlException e)
{ {
MainLog.Instance.Warn("MySql", "Terrain Table Already Exists"); m_log.WarnFormat("[MySql]: Terrain Table Already Exists: {0}", e);
} }
try try
{ {
lcmd.ExecuteNonQuery(); lcmd.ExecuteNonQuery();
} }
catch (MySqlException) catch (MySqlException e)
{ {
MainLog.Instance.Warn("MySql", "Land Table Already Exists"); m_log.WarnFormat("[MySql]: Land Table Already Exists: {0}", e);
} }
try try
{ {
lalcmd.ExecuteNonQuery(); lalcmd.ExecuteNonQuery();
} }
catch (MySqlException) catch (MySqlException e)
{ {
MainLog.Instance.Warn("MySql", "LandAccessList Table Already Exists"); m_log.WarnFormat("[MySql]: LandAccessList Table Already Exists: {0}", e);
} }
conn.Close(); conn.Close();
} }
@ -1274,6 +1533,8 @@ namespace OpenSim.Framework.Data.MySQL
MySqlDataAdapter pDa = new MySqlDataAdapter(primSelectCmd); MySqlDataAdapter pDa = new MySqlDataAdapter(primSelectCmd);
MySqlCommand shapeSelectCmd = new MySqlCommand(m_shapeSelect, conn); MySqlCommand shapeSelectCmd = new MySqlCommand(m_shapeSelect, conn);
MySqlDataAdapter sDa = new MySqlDataAdapter(shapeSelectCmd); MySqlDataAdapter sDa = new MySqlDataAdapter(shapeSelectCmd);
MySqlCommand itemsSelectCmd = new MySqlCommand(m_itemsSelect, conn);
MySqlDataAdapter iDa = new MySqlDataAdapter(itemsSelectCmd);
MySqlCommand terrainSelectCmd = new MySqlCommand(m_terrainSelect, conn); MySqlCommand terrainSelectCmd = new MySqlCommand(m_terrainSelect, conn);
MySqlDataAdapter tDa = new MySqlDataAdapter(terrainSelectCmd); MySqlDataAdapter tDa = new MySqlDataAdapter(terrainSelectCmd);
MySqlCommand landSelectCmd = new MySqlCommand(m_landSelect, conn); MySqlCommand landSelectCmd = new MySqlCommand(m_landSelect, conn);
@ -1286,18 +1547,26 @@ namespace OpenSim.Framework.Data.MySQL
{ {
pDa.Fill(tmpDS, "prims"); pDa.Fill(tmpDS, "prims");
sDa.Fill(tmpDS, "primshapes"); sDa.Fill(tmpDS, "primshapes");
if (persistPrimInventories)
iDa.Fill(tmpDS, "primitems");
tDa.Fill(tmpDS, "terrain"); tDa.Fill(tmpDS, "terrain");
lDa.Fill(tmpDS, "land"); lDa.Fill(tmpDS, "land");
lalDa.Fill(tmpDS, "landaccesslist"); lalDa.Fill(tmpDS, "landaccesslist");
} }
catch (MySqlException) catch (MySqlException)
{ {
MainLog.Instance.Verbose("DATASTORE", "MySql Database doesn't exist... creating"); m_log.Info("[DATASTORE]: MySql Database doesn't exist... creating");
InitDB(conn); InitDB(conn);
} }
pDa.Fill(tmpDS, "prims"); pDa.Fill(tmpDS, "prims");
sDa.Fill(tmpDS, "primshapes"); sDa.Fill(tmpDS, "primshapes");
if (persistPrimInventories)
iDa.Fill(tmpDS, "primitems");
tDa.Fill(tmpDS, "terrain"); tDa.Fill(tmpDS, "terrain");
lDa.Fill(tmpDS, "land"); lDa.Fill(tmpDS, "land");
lalDa.Fill(tmpDS, "landaccesslist"); lalDa.Fill(tmpDS, "landaccesslist");
@ -1306,42 +1575,49 @@ namespace OpenSim.Framework.Data.MySQL
{ {
if (!tmpDS.Tables["prims"].Columns.Contains(col.ColumnName)) if (!tmpDS.Tables["prims"].Columns.Contains(col.ColumnName))
{ {
MainLog.Instance.Verbose("DATASTORE", "Missing required column:" + col.ColumnName); m_log.Info("[DATASTORE]: Missing required column:" + col.ColumnName);
return false; return false;
} }
} }
foreach (DataColumn col in createShapeTable().Columns) foreach (DataColumn col in createShapeTable().Columns)
{ {
if (!tmpDS.Tables["primshapes"].Columns.Contains(col.ColumnName)) if (!tmpDS.Tables["primshapes"].Columns.Contains(col.ColumnName))
{ {
MainLog.Instance.Verbose("DATASTORE", "Missing required column:" + col.ColumnName); m_log.Info("[DATASTORE]: Missing required column:" + col.ColumnName);
return false; return false;
} }
} }
// XXX primitems should probably go here eventually
foreach (DataColumn col in createTerrainTable().Columns) foreach (DataColumn col in createTerrainTable().Columns)
{ {
if (!tmpDS.Tables["terrain"].Columns.Contains(col.ColumnName)) if (!tmpDS.Tables["terrain"].Columns.Contains(col.ColumnName))
{ {
MainLog.Instance.Verbose("DATASTORE", "Missing require column:" + col.ColumnName); m_log.Info("[DATASTORE]: Missing require column:" + col.ColumnName);
return false; return false;
} }
} }
foreach (DataColumn col in createLandTable().Columns) foreach (DataColumn col in createLandTable().Columns)
{ {
if (!tmpDS.Tables["land"].Columns.Contains(col.ColumnName)) if (!tmpDS.Tables["land"].Columns.Contains(col.ColumnName))
{ {
MainLog.Instance.Verbose("DATASTORE", "Missing require column:" + col.ColumnName); m_log.Info("[DATASTORE]: Missing require column:" + col.ColumnName);
return false; return false;
} }
} }
foreach (DataColumn col in createLandAccessListTable().Columns) foreach (DataColumn col in createLandAccessListTable().Columns)
{ {
if (!tmpDS.Tables["landaccesslist"].Columns.Contains(col.ColumnName)) if (!tmpDS.Tables["landaccesslist"].Columns.Contains(col.ColumnName))
{ {
MainLog.Instance.Verbose("DATASTORE", "Missing require column:" + col.ColumnName); m_log.Info("[DATASTORE]: Missing require column:" + col.ColumnName);
return false; return false;
} }
} }
return true; return true;
} }
@ -1395,6 +1671,10 @@ namespace OpenSim.Framework.Data.MySQL
{ {
return "integer"; return "integer";
} }
else if (type == typeof (Int64))
{
return "bigint";
}
else if (type == typeof (Double)) else if (type == typeof (Double))
{ {
return "float"; return "float";

View File

@ -0,0 +1,54 @@
/*
* 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 OpenSim 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.Data.Common;
using MySql.Data.MySqlClient;
//using TribalMedia.Framework.Data;
namespace OpenSim.Framework.Data.MySQL
{
/*
public class MySQLDatabaseMapper : OpenSimDatabaseConnector
{
public MySQLDatabaseMapper(string connectionString)
: base(connectionString)
{
}
public override DbConnection GetNewConnection()
{
MySqlConnection connection = new MySqlConnection(m_connectionString);
return connection;
}
public override string CreateParamName(string fieldName)
{
return "?" + fieldName;
}
}*/
}

View File

@ -42,6 +42,8 @@ namespace OpenSim.Framework.Data.MySQL
/// </summary> /// </summary>
public class MySQLGridData : IGridData public class MySQLGridData : IGridData
{ {
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary> /// <summary>
/// MySQL Database Manager /// MySQL Database Manager
/// </summary> /// </summary>
@ -168,7 +170,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
return null; return null;
} }
} }
@ -200,95 +202,11 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
return null; return null;
} }
} }
/// <summary>
/// // Returns a list of avatar and UUIDs that match the query
/// </summary>
public List<AvatarPickerAvatar> GeneratePickerResults(LLUUID queryID, string query)
{
List<AvatarPickerAvatar> returnlist = new List<AvatarPickerAvatar>();
Regex objAlphaNumericPattern = new Regex("[^a-zA-Z0-9]");
string[] querysplit;
querysplit = query.Split(' ');
if (querysplit.Length == 2)
{
Dictionary<string, string> param = new Dictionary<string, string>();
param["?first"] = objAlphaNumericPattern.Replace(querysplit[0], "") + "%";
param["?second"] = objAlphaNumericPattern.Replace(querysplit[1], "") + "%";
try
{
lock (database)
{
IDbCommand result =
database.Query(
"SELECT UUID,username,surname FROM users WHERE username like ?first AND lastname like ?second LIMIT 100",
param);
IDataReader reader = result.ExecuteReader();
while (reader.Read())
{
AvatarPickerAvatar user = new AvatarPickerAvatar();
user.AvatarID = new LLUUID((string) reader["UUID"]);
user.firstName = (string) reader["username"];
user.lastName = (string) reader["surname"];
returnlist.Add(user);
}
reader.Close();
result.Dispose();
}
}
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
return returnlist;
}
}
else if (querysplit.Length == 1)
{
try
{
lock (database)
{
Dictionary<string, string> param = new Dictionary<string, string>();
param["?first"] = objAlphaNumericPattern.Replace(querysplit[0], "") + "%";
IDbCommand result =
database.Query(
"SELECT UUID,username,surname FROM users WHERE username like ?first OR lastname like ?second",
param);
IDataReader reader = result.ExecuteReader();
while (reader.Read())
{
AvatarPickerAvatar user = new AvatarPickerAvatar();
user.AvatarID = new LLUUID((string) reader["UUID"]);
user.firstName = (string) reader["username"];
user.lastName = (string) reader["surname"];
returnlist.Add(user);
}
reader.Close();
result.Dispose();
}
}
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
return returnlist;
}
}
return returnlist;
}
/// <summary> /// <summary>
/// Returns a sim profile from it's UUID /// Returns a sim profile from it's UUID
/// </summary> /// </summary>
@ -316,7 +234,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
return null; return null;
} }
} }
@ -405,7 +323,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
return null; return null;
} }
} }

View File

@ -38,6 +38,9 @@ namespace OpenSim.Framework.Data.MySQL
/// </summary> /// </summary>
public class MySQLInventoryData : IInventoryData public class MySQLInventoryData : IInventoryData
{ {
private static readonly log4net.ILog m_log
= log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary> /// <summary>
/// The database manager /// The database manager
/// </summary> /// </summary>
@ -104,8 +107,8 @@ namespace OpenSim.Framework.Data.MySQL
tableList["inventoryitems"] = null; tableList["inventoryitems"] = null;
database.GetTableVersion(tableList); database.GetTableVersion(tableList);
MainLog.Instance.Verbose("MYSQL", "Inventory Folder Version: " + tableList["inventoryfolders"]); m_log.Info("[MYSQL]: Inventory Folder Version: " + tableList["inventoryfolders"]);
MainLog.Instance.Verbose("MYSQL", "Inventory Items Version: " + tableList["inventoryitems"]); m_log.Info("[MYSQL]: Inventory Items Version: " + tableList["inventoryitems"]);
UpgradeFoldersTable(tableList["inventoryfolders"]); UpgradeFoldersTable(tableList["inventoryfolders"]);
UpgradeItemsTable(tableList["inventoryitems"]); UpgradeItemsTable(tableList["inventoryitems"]);
@ -170,7 +173,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
return null; return null;
} }
} }
@ -208,7 +211,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
return null; return null;
} }
} }
@ -254,7 +257,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
return null; return null;
} }
} }
@ -292,7 +295,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
return null; return null;
} }
} }
@ -325,7 +328,7 @@ namespace OpenSim.Framework.Data.MySQL
} }
catch (MySqlException e) catch (MySqlException e)
{ {
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
} }
return null; return null;
@ -362,7 +365,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
} }
return null; return null;
} }
@ -387,7 +390,7 @@ namespace OpenSim.Framework.Data.MySQL
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
} }
return null; return null;
@ -421,7 +424,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
return null; return null;
} }
} }
@ -459,7 +462,7 @@ namespace OpenSim.Framework.Data.MySQL
} }
catch (MySqlException e) catch (MySqlException e)
{ {
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
} }
} }
@ -488,7 +491,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (MySqlException e) catch (MySqlException e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
} }
} }
@ -512,11 +515,14 @@ namespace OpenSim.Framework.Data.MySQL
try try
{ {
cmd.ExecuteNonQuery(); lock (database)
{
cmd.ExecuteNonQuery();
}
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
} }
} }
@ -541,14 +547,16 @@ namespace OpenSim.Framework.Data.MySQL
cmd.Parameters.AddWithValue("?folderID", folder.folderID.ToString()); cmd.Parameters.AddWithValue("?folderID", folder.folderID.ToString());
cmd.Parameters.AddWithValue("?parentFolderID", folder.parentID.ToString()); cmd.Parameters.AddWithValue("?parentFolderID", folder.parentID.ToString());
try try
{ {
cmd.ExecuteNonQuery(); lock (database)
{
cmd.ExecuteNonQuery();
}
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
} }
} }
@ -588,12 +596,16 @@ namespace OpenSim.Framework.Data.MySQL
MySqlCommand cmd = MySqlCommand cmd =
new MySqlCommand("DELETE FROM inventoryfolders WHERE folderID=?uuid", database.Connection); new MySqlCommand("DELETE FROM inventoryfolders WHERE folderID=?uuid", database.Connection);
cmd.Parameters.AddWithValue("?uuid", folderID.ToString()); cmd.Parameters.AddWithValue("?uuid", folderID.ToString());
cmd.ExecuteNonQuery();
lock (database)
{
cmd.ExecuteNonQuery();
}
} }
catch (MySqlException e) catch (MySqlException e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
} }
} }
@ -604,12 +616,16 @@ namespace OpenSim.Framework.Data.MySQL
MySqlCommand cmd = MySqlCommand cmd =
new MySqlCommand("DELETE FROM inventoryitems WHERE parentFolderID=?uuid", database.Connection); new MySqlCommand("DELETE FROM inventoryitems WHERE parentFolderID=?uuid", database.Connection);
cmd.Parameters.AddWithValue("?uuid", folderID.ToString()); cmd.Parameters.AddWithValue("?uuid", folderID.ToString());
cmd.ExecuteNonQuery();
lock (database)
{
cmd.ExecuteNonQuery();
}
} }
catch (MySqlException e) catch (MySqlException e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
} }
} }
@ -620,21 +636,18 @@ namespace OpenSim.Framework.Data.MySQL
/// <param name="folderId">Id of folder to delete</param> /// <param name="folderId">Id of folder to delete</param>
public void deleteInventoryFolder(LLUUID folderID) public void deleteInventoryFolder(LLUUID folderID)
{ {
lock (database) List<InventoryFolderBase> subFolders = getFolderHierarchy(folderID);
//Delete all sub-folders
foreach (InventoryFolderBase f in subFolders)
{ {
List<InventoryFolderBase> subFolders = getFolderHierarchy(folderID); deleteOneFolder(f.folderID);
deleteItemsInFolder(f.folderID);
//Delete all sub-folders
foreach (InventoryFolderBase f in subFolders)
{
deleteOneFolder(f.folderID);
deleteItemsInFolder(f.folderID);
}
//Delete the actual row
deleteOneFolder(folderID);
deleteItemsInFolder(folderID);
} }
//Delete the actual row
deleteOneFolder(folderID);
deleteItemsInFolder(folderID);
} }
} }
} }

View File

@ -29,6 +29,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Data; using System.Data;
using System.Data.SqlClient;
using System.IO; using System.IO;
using System.Reflection; using System.Reflection;
using libsecondlife; using libsecondlife;
@ -42,6 +43,8 @@ namespace OpenSim.Framework.Data.MySQL
/// </summary> /// </summary>
internal class MySQLManager internal class MySQLManager
{ {
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary> /// <summary>
/// The database connection object /// The database connection object
/// </summary> /// </summary>
@ -69,9 +72,16 @@ namespace OpenSim.Framework.Data.MySQL
username + ";Password=" + password + ";Pooling=" + cpooling + ";"; username + ";Password=" + password + ";Pooling=" + cpooling + ";";
dbcon = new MySqlConnection(connectionString); dbcon = new MySqlConnection(connectionString);
dbcon.Open(); try
{
dbcon.Open();
}
catch(Exception e)
{
throw new Exception( "Connection error while using connection string ["+connectionString+"]", e );
}
MainLog.Instance.Verbose("MYSQL", "Connection established"); m_log.Info("[MYSQL]: Connection established");
} }
catch (Exception e) catch (Exception e)
{ {
@ -113,7 +123,7 @@ namespace OpenSim.Framework.Data.MySQL
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Error("Unable to reconnect to database " + e.ToString()); m_log.Error("Unable to reconnect to database " + e.ToString());
} }
} }
} }
@ -190,11 +200,13 @@ namespace OpenSim.Framework.Data.MySQL
string tableName = (string) tables["TABLE_NAME"]; string tableName = (string) tables["TABLE_NAME"];
string comment = (string) tables["TABLE_COMMENT"]; string comment = (string) tables["TABLE_COMMENT"];
if (tableList.ContainsKey(tableName)) if (tableList.ContainsKey(tableName))
{
tableList[tableName] = comment; tableList[tableName] = comment;
}
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
} }
} }
tables.Close(); tables.Close();
@ -245,7 +257,7 @@ namespace OpenSim.Framework.Data.MySQL
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Error("Unable to reconnect to database " + e.ToString()); m_log.Error("Unable to reconnect to database " + e.ToString());
} }
// Run the query again // Run the query again
@ -263,7 +275,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e) catch (Exception e)
{ {
// Return null if it fails. // Return null if it fails.
MainLog.Instance.Error("Failed during Query generation: " + e.ToString()); m_log.Error("Failed during Query generation: " + e.ToString());
return null; return null;
} }
} }
@ -324,7 +336,7 @@ namespace OpenSim.Framework.Data.MySQL
// World Map Addition // World Map Addition
string tempRegionMap = reader["regionMapTexture"].ToString(); string tempRegionMap = reader["regionMapTexture"].ToString();
if (tempRegionMap != "") if (tempRegionMap != String.Empty)
{ {
retval.regionMapTextureID = new LLUUID(tempRegionMap); retval.regionMapTextureID = new LLUUID(tempRegionMap);
} }
@ -332,6 +344,23 @@ namespace OpenSim.Framework.Data.MySQL
{ {
retval.regionMapTextureID = LLUUID.Zero; retval.regionMapTextureID = LLUUID.Zero;
} }
// 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 supply a value from the region table to the caller of 'readSimRow()'
// for the UUID of the region's owner (master avatar)
try
{
retval.owner_uuid = new LLUUID((string)reader["owner_uuid"]);
}
catch
{
retval.owner_uuid = LLUUID.Zero;
}
} }
else else
{ {
@ -447,7 +476,15 @@ namespace OpenSim.Framework.Data.MySQL
retval.profileImage = new LLUUID((string) reader["profileImage"]); retval.profileImage = new LLUUID((string) reader["profileImage"]);
retval.profileFirstImage = new LLUUID((string) reader["profileFirstImage"]); retval.profileFirstImage = new LLUUID((string) reader["profileFirstImage"]);
retval.webLoginKey = new LLUUID((string)reader["webLoginKey"]);
if( reader.IsDBNull( reader.GetOrdinal( "webLoginKey" ) ) )
{
retval.webLoginKey = LLUUID.Zero;
}
else
{
retval.webLoginKey = new LLUUID((string)reader["webLoginKey"]);
}
} }
else else
{ {
@ -494,7 +531,7 @@ namespace OpenSim.Framework.Data.MySQL
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
return false; return false;
} }
@ -565,12 +602,12 @@ namespace OpenSim.Framework.Data.MySQL
parameters["?homeLookAtZ"] = homeLookAtZ.ToString(); parameters["?homeLookAtZ"] = homeLookAtZ.ToString();
parameters["?created"] = created.ToString(); parameters["?created"] = created.ToString();
parameters["?lastLogin"] = lastlogin.ToString(); parameters["?lastLogin"] = lastlogin.ToString();
parameters["?userInventoryURI"] = ""; parameters["?userInventoryURI"] = String.Empty;
parameters["?userAssetURI"] = ""; parameters["?userAssetURI"] = String.Empty;
parameters["?profileCanDoMask"] = "0"; parameters["?profileCanDoMask"] = "0";
parameters["?profileWantDoMask"] = "0"; parameters["?profileWantDoMask"] = "0";
parameters["?profileAboutText"] = ""; parameters["?profileAboutText"] = String.Empty;
parameters["?profileFirstText"] = ""; parameters["?profileFirstText"] = String.Empty;
parameters["?profileImage"] = LLUUID.Zero.ToString(); parameters["?profileImage"] = LLUUID.Zero.ToString();
parameters["?profileFirstImage"] = LLUUID.Zero.ToString(); parameters["?profileFirstImage"] = LLUUID.Zero.ToString();
parameters["?webLoginKey"] = LLUUID.Random().ToString(); parameters["?webLoginKey"] = LLUUID.Random().ToString();
@ -588,7 +625,7 @@ namespace OpenSim.Framework.Data.MySQL
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
return false; return false;
} }
@ -605,7 +642,7 @@ namespace OpenSim.Framework.Data.MySQL
{ {
bool GRID_ONLY_UPDATE_NECESSARY_DATA = false; bool GRID_ONLY_UPDATE_NECESSARY_DATA = false;
string sql = ""; string sql = String.Empty;
if (GRID_ONLY_UPDATE_NECESSARY_DATA) if (GRID_ONLY_UPDATE_NECESSARY_DATA)
{ {
sql += "INSERT INTO "; sql += "INSERT INTO ";
@ -618,18 +655,28 @@ namespace OpenSim.Framework.Data.MySQL
sql += "regions (regionHandle, regionName, uuid, regionRecvKey, regionSecret, regionSendKey, regionDataURI, "; sql += "regions (regionHandle, regionName, uuid, regionRecvKey, regionSecret, regionSendKey, regionDataURI, ";
sql += sql +=
"serverIP, serverPort, serverURI, locX, locY, locZ, eastOverrideHandle, westOverrideHandle, southOverrideHandle, northOverrideHandle, regionAssetURI, regionAssetRecvKey, "; "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 += sql +=
"regionAssetSendKey, regionUserURI, regionUserRecvKey, regionUserSendKey, regionMapTexture, serverHttpPort, serverRemotingPort) VALUES "; "regionAssetSendKey, regionUserURI, regionUserRecvKey, regionUserSendKey, regionMapTexture, serverHttpPort, serverRemotingPort, owner_uuid) VALUES ";
sql += "(?regionHandle, ?regionName, ?uuid, ?regionRecvKey, ?regionSecret, ?regionSendKey, ?regionDataURI, "; sql += "(?regionHandle, ?regionName, ?uuid, ?regionRecvKey, ?regionSecret, ?regionSendKey, ?regionDataURI, ";
sql += sql +=
"?serverIP, ?serverPort, ?serverURI, ?locX, ?locY, ?locZ, ?eastOverrideHandle, ?westOverrideHandle, ?southOverrideHandle, ?northOverrideHandle, ?regionAssetURI, ?regionAssetRecvKey, "; "?serverIP, ?serverPort, ?serverURI, ?locX, ?locY, ?locZ, ?eastOverrideHandle, ?westOverrideHandle, ?southOverrideHandle, ?northOverrideHandle, ?regionAssetURI, ?regionAssetRecvKey, ";
sql += sql +=
"?regionAssetSendKey, ?regionUserURI, ?regionUserRecvKey, ?regionUserSendKey, ?regionMapTexture, ?serverHttpPort, ?serverRemotingPort)"; "?regionAssetSendKey, ?regionUserURI, ?regionUserRecvKey, ?regionUserSendKey, ?regionMapTexture, ?serverHttpPort, ?serverRemotingPort, ?owner_uuid)";
if (GRID_ONLY_UPDATE_NECESSARY_DATA) if (GRID_ONLY_UPDATE_NECESSARY_DATA)
{ {
sql += "ON DUPLICATE KEY UPDATE serverIP = ?serverIP, serverPort = ?serverPort, serverURI = ?serverURI;"; sql += "ON DUPLICATE KEY UPDATE serverIP = ?serverIP, serverPort = ?serverPort, serverURI = ?serverURI, owner_uuid - ?owner_uuid;";
} }
else else
{ {
@ -664,6 +711,8 @@ namespace OpenSim.Framework.Data.MySQL
parameters["?regionMapTexture"] = regiondata.regionMapTextureID.ToString(); parameters["?regionMapTexture"] = regiondata.regionMapTextureID.ToString();
parameters["?serverHttpPort"] = regiondata.httpPort.ToString(); parameters["?serverHttpPort"] = regiondata.httpPort.ToString();
parameters["?serverRemotingPort"] = regiondata.remotingPort.ToString(); parameters["?serverRemotingPort"] = regiondata.remotingPort.ToString();
parameters["?owner_uuid"] = regiondata.owner_uuid.ToString();
bool returnval = false; bool returnval = false;
try try
@ -680,7 +729,7 @@ namespace OpenSim.Framework.Data.MySQL
} }
catch (Exception e) catch (Exception e)
{ {
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
return false; return false;
} }

View File

@ -39,25 +39,50 @@ namespace OpenSim.Framework.Data.MySQL
/// </summary> /// </summary>
internal class MySQLUserData : IUserData internal class MySQLUserData : IUserData
{ {
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary> /// <summary>
/// Database manager for MySQL /// Database manager for MySQL
/// </summary> /// </summary>
public MySQLManager database; public MySQLManager database;
private string m_agentsTableName;
private string m_usersTableName;
private string m_userFriendsTableName;
/// <summary> /// <summary>
/// Loads and initialises the MySQL storage plugin /// Loads and initialises the MySQL storage plugin
/// </summary> /// </summary>
public void Initialise() public void Initialise()
{ {
// Load from an INI file connection details // Load from an INI file connection details
// TODO: move this to XML? // TODO: move this to XML? Yes, PLEASE!
IniFile GridDataMySqlFile = new IniFile("mysql_connection.ini");
string settingHostname = GridDataMySqlFile.ParseFileReadValue("hostname"); IniFile iniFile = new IniFile("mysql_connection.ini");
string settingDatabase = GridDataMySqlFile.ParseFileReadValue("database"); string settingHostname = iniFile.ParseFileReadValue("hostname");
string settingUsername = GridDataMySqlFile.ParseFileReadValue("username"); string settingDatabase = iniFile.ParseFileReadValue("database");
string settingPassword = GridDataMySqlFile.ParseFileReadValue("password"); string settingUsername = iniFile.ParseFileReadValue("username");
string settingPooling = GridDataMySqlFile.ParseFileReadValue("pooling"); string settingPassword = iniFile.ParseFileReadValue("password");
string settingPort = GridDataMySqlFile.ParseFileReadValue("port"); string settingPooling = iniFile.ParseFileReadValue("pooling");
string settingPort = iniFile.ParseFileReadValue("port");
m_usersTableName = iniFile.ParseFileReadValue("userstablename");
if( m_usersTableName == null )
{
m_usersTableName = "users";
}
m_userFriendsTableName = iniFile.ParseFileReadValue("userfriendstablename");
if (m_userFriendsTableName == null)
{
m_userFriendsTableName = "userfriends";
}
m_agentsTableName = iniFile.ParseFileReadValue("agentstablename");
if (m_agentsTableName == null)
{
m_agentsTableName = "agents";
}
database = database =
new MySQLManager(settingHostname, settingDatabase, settingUsername, settingPassword, settingPooling, new MySQLManager(settingHostname, settingDatabase, settingUsername, settingPassword, settingPooling,
@ -75,14 +100,14 @@ namespace OpenSim.Framework.Data.MySQL
{ {
Dictionary<string, string> tableList = new Dictionary<string, string>(); Dictionary<string, string> tableList = new Dictionary<string, string>();
tableList["agents"] = null; tableList[m_agentsTableName] = null;
tableList["users"] = null; tableList[m_usersTableName] = null;
tableList["userfriends"] = null; tableList[m_userFriendsTableName] = null;
database.GetTableVersion(tableList); database.GetTableVersion(tableList);
UpgradeAgentsTable(tableList["agents"]); UpgradeAgentsTable(tableList[m_agentsTableName]);
UpgradeUsersTable(tableList["users"]); UpgradeUsersTable(tableList[m_usersTableName]);
UpgradeFriendsTable(tableList["userfriends"]); UpgradeFriendsTable(tableList[m_userFriendsTableName]);
} }
@ -119,7 +144,7 @@ namespace OpenSim.Framework.Data.MySQL
database.ExecuteResourceSql("UpgradeUsersTableToVersion2.sql"); database.ExecuteResourceSql("UpgradeUsersTableToVersion2.sql");
return; return;
} }
//MainLog.Instance.Verbose("DB","DBVers:" + oldVersion); //m_log.Info("[DB]: DBVers:" + oldVersion);
} }
/// <summary> /// <summary>
@ -151,7 +176,7 @@ namespace OpenSim.Framework.Data.MySQL
param["?second"] = last; param["?second"] = last;
IDbCommand result = IDbCommand result =
database.Query("SELECT * FROM users WHERE username = ?first AND lastname = ?second", param); database.Query("SELECT * FROM " + m_usersTableName + " WHERE username = ?first AND lastname = ?second", param);
IDataReader reader = result.ExecuteReader(); IDataReader reader = result.ExecuteReader();
UserProfileData row = database.readUserRow(reader); UserProfileData row = database.readUserRow(reader);
@ -164,7 +189,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
return null; return null;
} }
} }
@ -187,7 +212,7 @@ namespace OpenSim.Framework.Data.MySQL
{ {
IDbCommand adder = IDbCommand adder =
database.Query( database.Query(
"INSERT INTO `userfriends` " + "INSERT INTO `" + m_userFriendsTableName + "` " +
"(`ownerID`,`friendID`,`friendPerms`,`datetimestamp`) " + "(`ownerID`,`friendID`,`friendPerms`,`datetimestamp`) " +
"VALUES " + "VALUES " +
"(?ownerID,?friendID,?friendPerms,?datetimestamp)", "(?ownerID,?friendID,?friendPerms,?datetimestamp)",
@ -196,7 +221,7 @@ namespace OpenSim.Framework.Data.MySQL
adder = adder =
database.Query( database.Query(
"INSERT INTO `userfriends` " + "INSERT INTO `" + m_userFriendsTableName + "` " +
"(`ownerID`,`friendID`,`friendPerms`,`datetimestamp`) " + "(`ownerID`,`friendID`,`friendPerms`,`datetimestamp`) " +
"VALUES " + "VALUES " +
"(?friendID,?ownerID,?friendPerms,?datetimestamp)", "(?friendID,?ownerID,?friendPerms,?datetimestamp)",
@ -208,7 +233,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
return; return;
} }
} }
@ -226,15 +251,13 @@ namespace OpenSim.Framework.Data.MySQL
{ {
IDbCommand updater = IDbCommand updater =
database.Query( database.Query(
"delete from userfriends " + "delete from " + m_userFriendsTableName + " where ownerID = ?ownerID and friendID = ?friendID",
"where ownerID = ?ownerID and friendID = ?friendID",
param); param);
updater.ExecuteNonQuery(); updater.ExecuteNonQuery();
updater = updater =
database.Query( database.Query(
"delete from userfriends " + "delete from " + m_userFriendsTableName + " where ownerID = ?friendID and friendID = ?ownerID",
"where ownerID = ?friendID and friendID = ?ownerID",
param); param);
updater.ExecuteNonQuery(); updater.ExecuteNonQuery();
@ -243,7 +266,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
return; return;
} }
} }
@ -261,8 +284,8 @@ namespace OpenSim.Framework.Data.MySQL
{ {
IDbCommand updater = IDbCommand updater =
database.Query( database.Query(
"update userfriends " + "update " + m_userFriendsTableName +
"SET friendPerms = ?friendPerms " + " SET friendPerms = ?friendPerms " +
"where ownerID = ?ownerID and friendID = ?friendID", "where ownerID = ?ownerID and friendID = ?friendID",
param); param);
updater.ExecuteNonQuery(); updater.ExecuteNonQuery();
@ -272,7 +295,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
return; return;
} }
} }
@ -292,7 +315,7 @@ namespace OpenSim.Framework.Data.MySQL
//Left Join userfriends to itself //Left Join userfriends to itself
IDbCommand result = IDbCommand result =
database.Query( database.Query(
"select a.ownerID,a.friendID,a.friendPerms,b.friendPerms as ownerperms from userfriends as a, userfriends as b" + "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", " where a.ownerID = ?ownerID and b.ownerID = a.friendID and b.friendID = a.ownerID",
param); param);
IDataReader reader = result.ExecuteReader(); IDataReader reader = result.ExecuteReader();
@ -317,7 +340,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
return Lfli; return Lfli;
} }
@ -328,13 +351,9 @@ namespace OpenSim.Framework.Data.MySQL
public void UpdateUserCurrentRegion(LLUUID avatarid, LLUUID regionuuid) public void UpdateUserCurrentRegion(LLUUID avatarid, LLUUID regionuuid)
{ {
MainLog.Instance.Verbose("USER", "Stub UpdateUserCUrrentRegion called"); m_log.Info("[USER]: Stub UpdateUserCUrrentRegion called");
} }
public void LogOffUser(LLUUID avatarid)
{
MainLog.Instance.Verbose("USER", "Stub LogOffUser called");
}
public List<Framework.AvatarPickerAvatar> GeneratePickerResults(LLUUID queryID, string query) public List<Framework.AvatarPickerAvatar> GeneratePickerResults(LLUUID queryID, string query)
{ {
@ -347,15 +366,15 @@ namespace OpenSim.Framework.Data.MySQL
if (querysplit.Length == 2) if (querysplit.Length == 2)
{ {
Dictionary<string, string> param = new Dictionary<string, string>(); Dictionary<string, string> param = new Dictionary<string, string>();
param["?first"] = objAlphaNumericPattern.Replace(querysplit[0], "") + "%"; param["?first"] = objAlphaNumericPattern.Replace(querysplit[0], String.Empty) + "%";
param["?second"] = objAlphaNumericPattern.Replace(querysplit[1], "") + "%"; param["?second"] = objAlphaNumericPattern.Replace(querysplit[1], String.Empty) + "%";
try try
{ {
lock (database) lock (database)
{ {
IDbCommand result = IDbCommand result =
database.Query( database.Query(
"SELECT UUID,username,lastname FROM users WHERE username like ?first AND lastname like ?second LIMIT 100", "SELECT UUID,username,lastname FROM " + m_usersTableName + " WHERE username like ?first AND lastname like ?second LIMIT 100",
param); param);
IDataReader reader = result.ExecuteReader(); IDataReader reader = result.ExecuteReader();
@ -375,7 +394,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
return returnlist; return returnlist;
} }
} }
@ -386,11 +405,11 @@ namespace OpenSim.Framework.Data.MySQL
lock (database) lock (database)
{ {
Dictionary<string, string> param = new Dictionary<string, string>(); Dictionary<string, string> param = new Dictionary<string, string>();
param["?first"] = objAlphaNumericPattern.Replace(querysplit[0], "") + "%"; param["?first"] = objAlphaNumericPattern.Replace(querysplit[0], String.Empty) + "%";
IDbCommand result = IDbCommand result =
database.Query( database.Query(
"SELECT UUID,username,lastname FROM users WHERE username like ?first OR lastname like ?first LIMIT 100", "SELECT UUID,username,lastname FROM " + m_usersTableName + " WHERE username like ?first OR lastname like ?first LIMIT 100",
param); param);
IDataReader reader = result.ExecuteReader(); IDataReader reader = result.ExecuteReader();
@ -410,7 +429,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
return returnlist; return returnlist;
} }
} }
@ -427,7 +446,7 @@ namespace OpenSim.Framework.Data.MySQL
Dictionary<string, string> param = new Dictionary<string, string>(); Dictionary<string, string> param = new Dictionary<string, string>();
param["?uuid"] = uuid.ToString(); param["?uuid"] = uuid.ToString();
IDbCommand result = database.Query("SELECT * FROM users WHERE UUID = ?uuid", param); IDbCommand result = database.Query("SELECT * FROM " + m_usersTableName + " WHERE UUID = ?uuid", param);
IDataReader reader = result.ExecuteReader(); IDataReader reader = result.ExecuteReader();
UserProfileData row = database.readUserRow(reader); UserProfileData row = database.readUserRow(reader);
@ -441,7 +460,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
return null; return null;
} }
} }
@ -499,6 +518,38 @@ namespace OpenSim.Framework.Data.MySQL
{ {
UserProfileData profile = GetUserByName(user, last); UserProfileData profile = GetUserByName(user, last);
return GetAgentByUUID(profile.UUID); return GetAgentByUUID(profile.UUID);
}
public void StoreWebLoginKey(LLUUID AgentID, LLUUID WebLoginKey)
{
Dictionary<string, string> param = new Dictionary<string, string>();
param["?UUID"] = AgentID.UUID.ToString();
param["?webLoginKey"] = WebLoginKey.UUID.ToString();
try
{
lock (database)
{
IDbCommand updater =
database.Query(
"update " + m_usersTableName + " SET webLoginKey = ?webLoginKey " +
"where UUID = ?UUID",
param);
updater.ExecuteNonQuery();
}
}
catch (Exception e)
{
database.Reconnect();
m_log.Error(e.ToString());
return;
}
} }
/// <summary> /// <summary>
@ -515,7 +566,7 @@ namespace OpenSim.Framework.Data.MySQL
Dictionary<string, string> param = new Dictionary<string, string>(); Dictionary<string, string> param = new Dictionary<string, string>();
param["?uuid"] = uuid.ToString(); param["?uuid"] = uuid.ToString();
IDbCommand result = database.Query("SELECT * FROM agents WHERE UUID = ?uuid", param); IDbCommand result = database.Query("SELECT * FROM " + m_agentsTableName + " WHERE UUID = ?uuid", param);
IDataReader reader = result.ExecuteReader(); IDataReader reader = result.ExecuteReader();
UserAgentData row = database.readAgentRow(reader); UserAgentData row = database.readAgentRow(reader);
@ -529,7 +580,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
return null; return null;
} }
} }
@ -557,7 +608,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e) catch (Exception e)
{ {
database.Reconnect(); database.Reconnect();
MainLog.Instance.Error(e.ToString()); m_log.Error(e.ToString());
} }
} }

View File

@ -1,3 +1,31 @@
/*
* 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 OpenSim 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.Reflection; using System.Reflection;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
@ -10,7 +38,7 @@ using System.Runtime.InteropServices;
[assembly : AssemblyConfiguration("")] [assembly : AssemblyConfiguration("")]
[assembly : AssemblyCompany("")] [assembly : AssemblyCompany("")]
[assembly : AssemblyProduct("OpenSim.Framework.Data.MySQL")] [assembly : AssemblyProduct("OpenSim.Framework.Data.MySQL")]
[assembly : AssemblyCopyright("Copyright © 2007")] [assembly : AssemblyCopyright("Copyright © OpenSimulator.org Developers 2007-2008")]
[assembly : AssemblyTrademark("")] [assembly : AssemblyTrademark("")]
[assembly : AssemblyCulture("")] [assembly : AssemblyCulture("")]

View File

@ -0,0 +1,42 @@
--
-- Create schema avatar_appearance
--
CREATE DATABASE IF NOT EXISTS avatar_appearance;
USE avatar_appearance;
DROP TABLE IF EXISTS `avatarappearance`;
CREATE TABLE `avatarappearance` (
`UUID` char(36) NOT NULL,
`Serial` int(10) unsigned NOT NULL,
`WearableItem0` char(36) NOT NULL,
`WearableAsset0` char(36) NOT NULL,
`WearableItem1` char(36) NOT NULL,
`WearableAsset1` char(36) NOT NULL,
`WearableItem2` char(36) NOT NULL,
`WearableAsset2` char(36) NOT NULL,
`WearableItem3` char(36) NOT NULL,
`WearableAsset3` char(36) NOT NULL,
`WearableItem4` char(36) NOT NULL,
`WearableAsset4` char(36) NOT NULL,
`WearableItem5` char(36) NOT NULL,
`WearableAsset5` char(36) NOT NULL,
`WearableItem6` char(36) NOT NULL,
`WearableAsset6` char(36) NOT NULL,
`WearableItem7` char(36) NOT NULL,
`WearableAsset7` char(36) NOT NULL,
`WearableItem8` char(36) NOT NULL,
`WearableAsset8` char(36) NOT NULL,
`WearableItem9` char(36) NOT NULL,
`WearableAsset9` char(36) NOT NULL,
`WearableItem10` char(36) NOT NULL,
`WearableAsset10` char(36) NOT NULL,
`WearableItem11` char(36) NOT NULL,
`WearableAsset11` char(36) NOT NULL,
`WearableItem12` char(36) NOT NULL,
`WearableAsset12` char(36) NOT NULL,
PRIMARY KEY (`UUID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

View File

@ -4,7 +4,7 @@ SET FOREIGN_KEY_CHECKS=0;
-- ---------------------------- -- ----------------------------
CREATE TABLE `userfriends` ( CREATE TABLE `userfriends` (
`ownerID` VARCHAR(37) NOT NULL, `ownerID` VARCHAR(37) NOT NULL,
`friendID` VARCHAR(47) NOT NULL, `friendID` VARCHAR(37) NOT NULL,
`friendPerms` INT NOT NULL, `friendPerms` INT NOT NULL,
`datetimestamp` INT NOT NULL, `datetimestamp` INT NOT NULL,
UNIQUE KEY (`ownerID`, `friendID`) UNIQUE KEY (`ownerID`, `friendID`)

View File

@ -1,3 +1,31 @@
/*
* 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 OpenSim 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.Reflection; using System.Reflection;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
@ -10,7 +38,7 @@ using System.Runtime.InteropServices;
[assembly : AssemblyConfiguration("")] [assembly : AssemblyConfiguration("")]
[assembly : AssemblyCompany("")] [assembly : AssemblyCompany("")]
[assembly : AssemblyProduct("OpenSim.Framework.Data.SQLite")] [assembly : AssemblyProduct("OpenSim.Framework.Data.SQLite")]
[assembly : AssemblyCopyright("Copyright © 2007")] [assembly : AssemblyCopyright("Copyright © OpenSimulator.org Developers 2007-2008")]
[assembly : AssemblyTrademark("")] [assembly : AssemblyTrademark("")]
[assembly : AssemblyCulture("")] [assembly : AssemblyCulture("")]
@ -34,5 +62,5 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Revision and Build Numbers // You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below: // by using the '*' as shown below:
[assembly : AssemblyVersion("0.4.0.0")] [assembly : AssemblyVersion("1.0.0.0")]
[assembly : AssemblyFileVersion("1.0.0.0")] [assembly : AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,13 @@
BEGIN TRANSACTION;
CREATE TABLE assets(
UUID varchar(255) primary key,
Name varchar(255),
Description varchar(255),
Type integer,
InvType integer,
Local integer,
Temporary integer,
Data blob);
COMMIT;

View File

@ -0,0 +1,26 @@
BEGIN TRANSACTION;
CREATE TABLE inventoryitems(
UUID varchar(255) primary key,
assetID varchar(255),
assetType integer,
invType integer,
parentFolderID varchar(255),
avatarID varchar(255),
creatorsID varchar(255),
inventoryName varchar(255),
inventoryDescription varchar(255),
inventoryNextPermissions integer,
inventoryCurrentPermissions integer,
inventoryBasePermissions integer,
inventoryEveryOnePermissions integer);
CREATE TABLE inventoryfolders(
UUID varchar(255) primary key,
name varchar(255),
agentID varchar(255),
parentID varchar(255),
type integer,
version integer);
COMMIT;

View File

@ -0,0 +1,121 @@
BEGIN TRANSACTION;
CREATE TABLE prims(
UUID varchar(255) primary key,
RegionUUID varchar(255),
ParentID integer,
CreationDate integer,
Name varchar(255),
SceneGroupID varchar(255),
Text varchar(255),
Description varchar(255),
SitName varchar(255),
TouchName varchar(255),
CreatorID varchar(255),
OwnerID varchar(255),
GroupID varchar(255),
LastOwnerID varchar(255),
OwnerMask integer,
NextOwnerMask integer,
GroupMask integer,
EveryoneMask integer,
BaseMask integer,
PositionX float,
PositionY float,
PositionZ float,
GroupPositionX float,
GroupPositionY float,
GroupPositionZ float,
VelocityX float,
VelocityY float,
VelocityZ float,
AngularVelocityX float,
AngularVelocityY float,
AngularVelocityZ float,
AccelerationX float,
AccelerationY float,
AccelerationZ float,
RotationX float,
RotationY float,
RotationZ float,
RotationW float,
ObjectFlags integer,
SitTargetOffsetX float NOT NULL default 0,
SitTargetOffsetY float NOT NULL default 0,
SitTargetOffsetZ float NOT NULL default 0,
SitTargetOrientW float NOT NULL default 0,
SitTargetOrientX float NOT NULL default 0,
SitTargetOrientY float NOT NULL default 0,
SitTargetOrientZ float NOT NULL default 0);
CREATE TABLE primshapes(UUID varchar(255) primary key,
Shape integer,
ScaleX float,
ScaleY float,
ScaleZ float,
PCode integer,
PathBegin integer,
PathEnd integer,
PathScaleX integer,
PathScaleY integer,
PathShearX integer,
PathShearY integer,
PathSkew integer,
PathCurve integer,
PathRadiusOffset integer,
PathRevolutions integer,
PathTaperX integer,
PathTaperY integer,
PathTwist integer,
PathTwistBegin integer,
ProfileBegin integer,
ProfileEnd integer,
ProfileCurve integer,
ProfileHollow integer,
Texture blob,
ExtraParams blob);
CREATE TABLE terrain(
RegionUUID varchar(255),
Revision integer,
Heightfield blob);
CREATE TABLE land(
UUID varchar(255) primary key,
RegionUUID varchar(255),
LocalLandID string,
Bitmap blob,
Name varchar(255),
Desc varchar(255),
OwnerUUID varchar(36),
IsGroupOwned string,
Area integer,
AuctionID integer,
Category integer,
ClaimDate integer,
ClaimPrice integer,
GroupUUID varchar(255),
SalePrice integer,
LandStatus integer,
LandFlags string,
LandingType string,
MediaAutoScale string,
MediaTextureUUID varchar(255),
MediaURL varchar(255),
MusicURL varchar(255),
PassHours float,
PassPrice string,
SnapshotUUID varchar(255),
UserLocationX float,
UserLocationY float,
UserLocationZ float,
UserLookAtX float,
UserLookAtY float,
UserLookAtZ float);
CREATE TABLE landaccesslist(
LandUUID varchar(255),
AccessUUID varchar(255),
Flags string);
COMMIT;

View File

@ -0,0 +1,37 @@
BEGIN TRANSACTION;
CREATE TABLE users(
UUID varchar(255) primary key,
username varchar(255),
surname varchar(255),
passwordHash varchar(255),
passwordSalt varchar(255),
homeRegionX integer,
homeRegionY integer,
homeLocationX float,
homeLocationY float,
homeLocationZ float,
homeLookAtX float,
homeLookAtY float,
homeLookAtZ float,
created integer,
lastLogin integer,
rootInventoryFolderID varchar(255),
userInventoryURI varchar(255),
userAssetURI varchar(255),
profileCanDoMask integer,
profileWantDoMask integer,
profileAboutText varchar(255),
profileFirstText varchar(255),
profileImage varchar(255),
profileFirstImage varchar(255),
webLoginKey text default '00000000-0000-0000-0000-000000000000');
CREATE TABLE userfriends(
ownerID varchar(255),
friendID varchar(255),
friendPerms integer,
ownerPerms integer,
datetimestamp integer);
COMMIT;

View File

@ -40,82 +40,97 @@ namespace OpenSim.Framework.Data.SQLite
/// </summary> /// </summary>
public class SQLiteAssetData : SQLiteBase, IAssetProvider public class SQLiteAssetData : SQLiteBase, IAssetProvider
{ {
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary> /// <summary>
/// The database manager /// The database manager
/// </summary> /// </summary>
/// <summary> /// <summary>
/// Artificial constructor called upon plugin load /// Artificial constructor called upon plugin load
/// </summary> /// </summary>
private const string SelectAssetSQL = "select * from assets where UUID=:UUID";
private const string DeleteAssetSQL = "delete from assets where UUID=:UUID";
private const string InsertAssetSQL = "insert into assets(UUID, Name, Description, Type, InvType, Local, Temporary, Data) values(:UUID, :Name, :Description, :Type, :InvType, :Local, :Temporary, :Data)";
private const string UpdateAssetSQL = "update assets set Name=:Name, Description=:Description, Type=:Type, InvType=:InvType, Local=:Local, Temporary=:Temporary, Data=:Data where UUID=:UUID";
private const string assetSelect = "select * from assets"; private const string assetSelect = "select * from assets";
private DataSet ds; private SqliteConnection m_conn;
private SqliteDataAdapter da;
public void Initialise(string dbfile, string dbname) public void Initialise(string dbfile, string dbname)
{ {
SqliteConnection conn = new SqliteConnection("URI=file:" + dbfile + ",version=3"); m_conn = new SqliteConnection("URI=file:" + dbfile + ",version=3");
TestTables(conn); m_conn.Open();
TestTables(m_conn);
ds = new DataSet();
da = new SqliteDataAdapter(new SqliteCommand(assetSelect, conn));
lock (ds)
{
ds.Tables.Add(createAssetsTable());
setupAssetCommands(da, conn);
try
{
da.Fill(ds.Tables["assets"]);
}
catch (Exception e)
{
MainLog.Instance.Verbose("SQLITE", e.ToString());
}
}
return; return;
} }
public AssetBase FetchAsset(LLUUID uuid) public AssetBase FetchAsset(LLUUID uuid)
{ {
AssetBase asset = new AssetBase();
DataRow row = ds.Tables["assets"].Rows.Find(Util.ToRawUuidString(uuid)); using (SqliteCommand cmd = new SqliteCommand(SelectAssetSQL, m_conn))
if (row != null)
{ {
return buildAsset(row); cmd.Parameters.Add(new SqliteParameter(":UUID", Util.ToRawUuidString(uuid)));
} using (IDataReader reader = cmd.ExecuteReader())
else {
{ if (reader.Read())
return null; {
AssetBase asset = buildAsset(reader);
reader.Close();
return asset;
}
else
{
reader.Close();
return null;
}
}
} }
} }
public void CreateAsset(AssetBase asset) public void CreateAsset(AssetBase asset)
{ {
// no difference for now m_log.Info("[SQLITE]: Creating Asset " + Util.ToRawUuidString(asset.FullID));
UpdateAsset(asset); if (ExistsAsset(asset.FullID))
{
m_log.Info("[SQLITE]: Asset exists, updating instead. You should fix the caller for this!");
UpdateAsset(asset);
}
else
{
using (SqliteCommand cmd = new SqliteCommand(InsertAssetSQL, m_conn))
{
cmd.Parameters.Add(new SqliteParameter(":UUID", Util.ToRawUuidString(asset.FullID)));
cmd.Parameters.Add(new SqliteParameter(":Name", asset.Name));
cmd.Parameters.Add(new SqliteParameter(":Description", asset.Description));
cmd.Parameters.Add(new SqliteParameter(":Type", asset.Type));
cmd.Parameters.Add(new SqliteParameter(":InvType", asset.InvType));
cmd.Parameters.Add(new SqliteParameter(":Local", asset.Local));
cmd.Parameters.Add(new SqliteParameter(":Temporary", asset.Temporary));
cmd.Parameters.Add(new SqliteParameter(":Data", asset.Data));
cmd.ExecuteNonQuery();
}
}
} }
public void UpdateAsset(AssetBase asset) public void UpdateAsset(AssetBase asset)
{ {
LogAssetLoad(asset); LogAssetLoad(asset);
DataTable assets = ds.Tables["assets"]; using (SqliteCommand cmd = new SqliteCommand(UpdateAssetSQL, m_conn))
lock (ds)
{ {
DataRow row = assets.Rows.Find(Util.ToRawUuidString(asset.FullID)); cmd.Parameters.Add(new SqliteParameter(":UUID", Util.ToRawUuidString(asset.FullID)));
if (row == null) cmd.Parameters.Add(new SqliteParameter(":Name", asset.Name));
{ cmd.Parameters.Add(new SqliteParameter(":Description", asset.Description));
row = assets.NewRow(); cmd.Parameters.Add(new SqliteParameter(":Type", asset.Type));
fillAssetRow(row, asset); cmd.Parameters.Add(new SqliteParameter(":InvType", asset.InvType));
assets.Rows.Add(row); cmd.Parameters.Add(new SqliteParameter(":Local", asset.Local));
} cmd.Parameters.Add(new SqliteParameter(":Temporary", asset.Temporary));
else cmd.Parameters.Add(new SqliteParameter(":Data", asset.Data));
{
fillAssetRow(row, asset); cmd.ExecuteNonQuery();
}
} }
} }
// rex new function for "replace assets" functionality // rex new function for "replace assets" functionality
@ -141,7 +156,7 @@ namespace OpenSim.Framework.Data.SQLite
string temporary = asset.Temporary ? "Temporary" : "Stored"; string temporary = asset.Temporary ? "Temporary" : "Stored";
string local = asset.Local ? "Local" : "Remote"; string local = asset.Local ? "Local" : "Remote";
MainLog.Instance.Verbose("SQLITE", m_log.Info("[SQLITE]: " +
string.Format("Loaded {6} {5} Asset: [{0}][{3}/{4}] \"{1}\":{2} ({7} bytes)", string.Format("Loaded {6} {5} Asset: [{0}][{3}/{4}] \"{1}\":{2} ({7} bytes)",
asset.FullID, asset.Name, asset.Description, asset.Type, asset.FullID, asset.Name, asset.Description, asset.Type,
asset.InvType, temporary, local, asset.Data.Length)); asset.InvType, temporary, local, asset.Data.Length));
@ -149,8 +164,23 @@ namespace OpenSim.Framework.Data.SQLite
public bool ExistsAsset(LLUUID uuid) public bool ExistsAsset(LLUUID uuid)
{ {
DataRow row = ds.Tables["assets"].Rows.Find(Util.ToRawUuidString(uuid)); using (SqliteCommand cmd = new SqliteCommand(SelectAssetSQL, m_conn))
return (row != null); {
cmd.Parameters.Add(new SqliteParameter(":UUID", Util.ToRawUuidString(uuid)));
using (IDataReader reader = cmd.ExecuteReader())
{
if(reader.Read())
{
reader.Close();
return true;
}
else
{
reader.Close();
return false;
}
}
}
} }
// rex, new function // rex, new function
@ -181,24 +211,22 @@ namespace OpenSim.Framework.Data.SQLite
public void DeleteAsset(LLUUID uuid) public void DeleteAsset(LLUUID uuid)
{ {
lock (ds) using (SqliteCommand cmd = new SqliteCommand(DeleteAssetSQL, m_conn))
{ {
DataRow row = ds.Tables["assets"].Rows.Find(Util.ToRawUuidString(uuid)); cmd.Parameters.Add(new SqliteParameter(":UUID", Util.ToRawUuidString(uuid)));
if (row != null)
{ cmd.ExecuteNonQuery();
row.Delete();
}
} }
} }
public void CommitAssets() // force a sync to the database public void CommitAssets() // force a sync to the database
{ {
MainLog.Instance.Verbose("SQLITE", "Attempting commit"); m_log.Info("[SQLITE]: Attempting commit");
lock (ds) // lock (ds)
{ // {
da.Update(ds, "assets"); // da.Update(ds, "assets");
ds.AcceptChanges(); // ds.AcceptChanges();
} // }
} }
/*********************************************************************** /***********************************************************************
@ -235,7 +263,7 @@ namespace OpenSim.Framework.Data.SQLite
* *
**********************************************************************/ **********************************************************************/
private AssetBase buildAsset(DataRow row) private AssetBase buildAsset(IDataReader row)
{ {
// TODO: this doesn't work yet because something more // TODO: this doesn't work yet because something more
// interesting has to be done to actually get these values // interesting has to be done to actually get these values
@ -308,27 +336,11 @@ namespace OpenSim.Framework.Data.SQLite
* *
**********************************************************************/ **********************************************************************/
private void setupAssetCommands(SqliteDataAdapter da, SqliteConnection conn)
{
da.InsertCommand = createInsertCommand("assets", ds.Tables["assets"]);
da.InsertCommand.Connection = conn;
da.UpdateCommand = createUpdateCommand("assets", "UUID=:UUID", ds.Tables["assets"]);
da.UpdateCommand.Connection = conn;
SqliteCommand delete = new SqliteCommand("delete from assets where UUID = :UUID");
delete.Parameters.Add(createSqliteParameter("UUID", typeof (String)));
delete.Connection = conn;
da.DeleteCommand = delete;
}
private void InitDB(SqliteConnection conn) private void InitDB(SqliteConnection conn)
{ {
string createAssets = defineTable(createAssetsTable()); string createAssets = defineTable(createAssetsTable());
SqliteCommand pcmd = new SqliteCommand(createAssets, conn); SqliteCommand pcmd = new SqliteCommand(createAssets, conn);
conn.Open();
pcmd.ExecuteNonQuery(); pcmd.ExecuteNonQuery();
conn.Close();
} }
private bool TestTables(SqliteConnection conn) private bool TestTables(SqliteConnection conn)
@ -342,7 +354,7 @@ namespace OpenSim.Framework.Data.SQLite
} }
catch (SqliteSyntaxException) catch (SqliteSyntaxException)
{ {
MainLog.Instance.Verbose("SQLITE", "SQLite Database doesn't exist... creating"); m_log.Info("[SQLITE]: SQLite Database doesn't exist... creating");
InitDB(conn); InitDB(conn);
} }
return true; return true;

View File

@ -98,7 +98,7 @@ namespace OpenSim.Framework.Data.SQLite
protected static SqliteCommand createUpdateCommand(string table, string pk, DataTable dt) protected static SqliteCommand createUpdateCommand(string table, string pk, DataTable dt)
{ {
string sql = "update " + table + " set "; string sql = "update " + table + " set ";
string subsql = ""; string subsql = String.Empty;
foreach (DataColumn col in dt.Columns) foreach (DataColumn col in dt.Columns)
{ {
if (subsql.Length > 0) if (subsql.Length > 0)
@ -126,7 +126,7 @@ namespace OpenSim.Framework.Data.SQLite
protected static string defineTable(DataTable dt) protected static string defineTable(DataTable dt)
{ {
string sql = "create table " + dt.TableName + "("; string sql = "create table " + dt.TableName + "(";
string subsql = ""; string subsql = String.Empty;
foreach (DataColumn col in dt.Columns) foreach (DataColumn col in dt.Columns)
{ {
if (subsql.Length > 0) if (subsql.Length > 0)

View File

@ -13,7 +13,7 @@
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS AS IS AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
@ -38,6 +38,8 @@ namespace OpenSim.Framework.Data.SQLite
{ {
public class SQLiteInventoryStore : SQLiteBase, IInventoryData public class SQLiteInventoryStore : SQLiteBase, IInventoryData
{ {
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private const string invItemsSelect = "select * from inventoryitems"; private const string invItemsSelect = "select * from inventoryitems";
private const string invFoldersSelect = "select * from inventoryfolders"; private const string invFoldersSelect = "select * from inventoryfolders";
@ -45,6 +47,11 @@ namespace OpenSim.Framework.Data.SQLite
private SqliteDataAdapter invItemsDa; private SqliteDataAdapter invItemsDa;
private SqliteDataAdapter invFoldersDa; private SqliteDataAdapter invFoldersDa;
/// <summary>
/// used to manage concurrent access tothe sqlite database files. Only one thread may open, read, write at a time.
/// </summary>
private object InventoryLock = new object();
/// <summary> /// <summary>
/// Initialises the interface /// Initialises the interface
/// </summary> /// </summary>
@ -57,7 +64,7 @@ namespace OpenSim.Framework.Data.SQLite
{ {
string connectionString = "URI=file:" + dbfile + ",version=3"; string connectionString = "URI=file:" + dbfile + ",version=3";
MainLog.Instance.Verbose("Inventory", "Sqlite - connecting: " + dbfile); m_log.Info("[Inventory]: Sqlite - connecting: " + dbfile);
SqliteConnection conn = new SqliteConnection(connectionString); SqliteConnection conn = new SqliteConnection(connectionString);
TestTables(conn); TestTables(conn);
@ -74,12 +81,12 @@ namespace OpenSim.Framework.Data.SQLite
ds.Tables.Add(createInventoryFoldersTable()); ds.Tables.Add(createInventoryFoldersTable());
invFoldersDa.Fill(ds.Tables["inventoryfolders"]); invFoldersDa.Fill(ds.Tables["inventoryfolders"]);
setupFoldersCommands(invFoldersDa, conn); setupFoldersCommands(invFoldersDa, conn);
MainLog.Instance.Verbose("DATASTORE", "Populated Intentory Folders Definitions"); m_log.Info("[DATASTORE]: Populated Intentory Folders Definitions");
ds.Tables.Add(createInventoryItemsTable()); ds.Tables.Add(createInventoryItemsTable());
invItemsDa.Fill(ds.Tables["inventoryitems"]); invItemsDa.Fill(ds.Tables["inventoryitems"]);
setupItemsCommands(invItemsDa, conn); setupItemsCommands(invItemsDa, conn);
MainLog.Instance.Verbose("DATASTORE", "Populated Intentory Items Definitions"); m_log.Info("[DATASTORE]: Populated Intentory Items Definitions");
ds.AcceptChanges(); ds.AcceptChanges();
} }
@ -124,58 +131,67 @@ namespace OpenSim.Framework.Data.SQLite
private void addFolder(InventoryFolderBase folder) private void addFolder(InventoryFolderBase folder)
{ {
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"]; lock (InventoryLock)
DataRow inventoryRow = inventoryFolderTable.Rows.Find(Util.ToRawUuidString(folder.folderID));
if (inventoryRow == null)
{ {
inventoryRow = inventoryFolderTable.NewRow(); DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
fillFolderRow(inventoryRow, folder);
inventoryFolderTable.Rows.Add(inventoryRow);
}
else
{
fillFolderRow(inventoryRow, folder);
}
invFoldersDa.Update(ds, "inventoryfolders"); DataRow inventoryRow = inventoryFolderTable.Rows.Find(Util.ToRawUuidString(folder.folderID));
if (inventoryRow == null)
{
inventoryRow = inventoryFolderTable.NewRow();
fillFolderRow(inventoryRow, folder);
inventoryFolderTable.Rows.Add(inventoryRow);
}
else
{
fillFolderRow(inventoryRow, folder);
}
invFoldersDa.Update(ds, "inventoryfolders");
}
} }
private void moveFolder(InventoryFolderBase folder) private void moveFolder(InventoryFolderBase folder)
{ {
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"]; lock (InventoryLock)
DataRow inventoryRow = inventoryFolderTable.Rows.Find(Util.ToRawUuidString(folder.folderID));
if (inventoryRow == null)
{ {
inventoryRow = inventoryFolderTable.NewRow(); DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
fillFolderRow(inventoryRow, folder);
inventoryFolderTable.Rows.Add(inventoryRow);
}
else
{
moveFolderRow(inventoryRow, folder);
}
invFoldersDa.Update(ds, "inventoryfolders"); DataRow inventoryRow = inventoryFolderTable.Rows.Find(Util.ToRawUuidString(folder.folderID));
if (inventoryRow == null)
{
inventoryRow = inventoryFolderTable.NewRow();
fillFolderRow(inventoryRow, folder);
inventoryFolderTable.Rows.Add(inventoryRow);
}
else
{
moveFolderRow(inventoryRow, folder);
}
invFoldersDa.Update(ds, "inventoryfolders");
}
} }
private void addItem(InventoryItemBase item) private void addItem(InventoryItemBase item)
{ {
DataTable inventoryItemTable = ds.Tables["inventoryitems"]; lock (InventoryLock)
{
DataTable inventoryItemTable = ds.Tables["inventoryitems"];
DataRow inventoryRow = inventoryItemTable.Rows.Find(Util.ToRawUuidString(item.inventoryID)); DataRow inventoryRow = inventoryItemTable.Rows.Find(Util.ToRawUuidString(item.inventoryID));
if (inventoryRow == null) if (inventoryRow == null)
{ {
inventoryRow = inventoryItemTable.NewRow(); inventoryRow = inventoryItemTable.NewRow();
fillItemRow(inventoryRow, item); fillItemRow(inventoryRow, item);
inventoryItemTable.Rows.Add(inventoryRow); inventoryItemTable.Rows.Add(inventoryRow);
}
else
{
fillItemRow(inventoryRow, item);
}
invItemsDa.Update(ds, "inventoryitems");
} }
else
{
fillItemRow(inventoryRow, item);
}
invItemsDa.Update(ds, "inventoryitems");
} }
public void Shutdown() public void Shutdown()
@ -222,16 +238,19 @@ namespace OpenSim.Framework.Data.SQLite
/// <returns>A List of InventoryItemBase items</returns> /// <returns>A List of InventoryItemBase items</returns>
public List<InventoryItemBase> getInventoryInFolder(LLUUID folderID) public List<InventoryItemBase> getInventoryInFolder(LLUUID folderID)
{ {
List<InventoryItemBase> retval = new List<InventoryItemBase>(); lock (InventoryLock)
DataTable inventoryItemTable = ds.Tables["inventoryitems"];
string selectExp = "parentFolderID = '" + Util.ToRawUuidString(folderID) + "'";
DataRow[] rows = inventoryItemTable.Select(selectExp);
foreach (DataRow row in rows)
{ {
retval.Add(buildItem(row)); List<InventoryItemBase> retval = new List<InventoryItemBase>();
} DataTable inventoryItemTable = ds.Tables["inventoryitems"];
string selectExp = "parentFolderID = '" + Util.ToRawUuidString(folderID) + "'";
DataRow[] rows = inventoryItemTable.Select(selectExp);
foreach (DataRow row in rows)
{
retval.Add(buildItem(row));
}
return retval; return retval;
}
} }
/// <summary> /// <summary>
@ -247,27 +266,30 @@ namespace OpenSim.Framework.Data.SQLite
// see InventoryItemBase.getUserRootFolder // see InventoryItemBase.getUserRootFolder
public InventoryFolderBase getUserRootFolder(LLUUID user) public InventoryFolderBase getUserRootFolder(LLUUID user)
{ {
List<InventoryFolderBase> folders = new List<InventoryFolderBase>(); lock (InventoryLock)
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
string selectExp = "agentID = '" + Util.ToRawUuidString(user) + "' AND parentID = '" +
Util.ToRawUuidString(LLUUID.Zero) + "'";
DataRow[] rows = inventoryFolderTable.Select(selectExp);
foreach (DataRow row in rows)
{ {
folders.Add(buildFolder(row)); List<InventoryFolderBase> folders = new List<InventoryFolderBase>();
} DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
string selectExp = "agentID = '" + Util.ToRawUuidString(user) + "' AND parentID = '" +
Util.ToRawUuidString(LLUUID.Zero) + "'";
DataRow[] rows = inventoryFolderTable.Select(selectExp);
foreach (DataRow row in rows)
{
folders.Add(buildFolder(row));
}
// There should only ever be one root folder for a user. However, if there's more // There should only ever be one root folder for a user. However, if there's more
// than one we'll simply use the first one rather than failing. It would be even // than one we'll simply use the first one rather than failing. It would be even
// nicer to print some message to this effect, but this feels like it's too low a // nicer to print some message to this effect, but this feels like it's too low a
// to put such a message out, and it's too minor right now to spare the time to // to put such a message out, and it's too minor right now to spare the time to
// suitably refactor. // suitably refactor.
if (folders.Count > 0) if (folders.Count > 0)
{ {
return folders[0]; return folders[0];
} }
return null; return null;
}
} }
/// <summary> /// <summary>
@ -277,12 +299,15 @@ namespace OpenSim.Framework.Data.SQLite
/// <param name="parentID">ID of parent</param> /// <param name="parentID">ID of parent</param>
protected void getInventoryFolders(ref List<InventoryFolderBase> folders, LLUUID parentID) protected void getInventoryFolders(ref List<InventoryFolderBase> folders, LLUUID parentID)
{ {
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"]; lock (InventoryLock)
string selectExp = "parentID = '" + Util.ToRawUuidString(parentID) + "'";
DataRow[] rows = inventoryFolderTable.Select(selectExp);
foreach (DataRow row in rows)
{ {
folders.Add(buildFolder(row)); DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
string selectExp = "parentID = '" + Util.ToRawUuidString(parentID) + "'";
DataRow[] rows = inventoryFolderTable.Select(selectExp);
foreach (DataRow row in rows)
{
folders.Add(buildFolder(row));
}
} }
} }
@ -321,14 +346,17 @@ namespace OpenSim.Framework.Data.SQLite
/// <returns>A class containing item information</returns> /// <returns>A class containing item information</returns>
public InventoryItemBase getInventoryItem(LLUUID item) public InventoryItemBase getInventoryItem(LLUUID item)
{ {
DataRow row = ds.Tables["inventoryitems"].Rows.Find(Util.ToRawUuidString(item)); lock (InventoryLock)
if (row != null)
{ {
return buildItem(row); DataRow row = ds.Tables["inventoryitems"].Rows.Find(Util.ToRawUuidString(item));
} if (row != null)
else {
{ return buildItem(row);
return null; }
else
{
return null;
}
} }
} }
@ -344,15 +372,17 @@ namespace OpenSim.Framework.Data.SQLite
// better to leave multi region at this point. It does mean // better to leave multi region at this point. It does mean
// that you don't get to see system textures why creating // that you don't get to see system textures why creating
// clothes and the like. :( // clothes and the like. :(
lock (InventoryLock)
DataRow row = ds.Tables["inventoryfolders"].Rows.Find(Util.ToRawUuidString(folder));
if (row != null)
{ {
return buildFolder(row); DataRow row = ds.Tables["inventoryfolders"].Rows.Find(Util.ToRawUuidString(folder));
} if (row != null)
else {
{ return buildFolder(row);
return null; }
else
{
return null;
}
} }
} }
@ -380,18 +410,20 @@ namespace OpenSim.Framework.Data.SQLite
/// <param name="item"></param> /// <param name="item"></param>
public void deleteInventoryItem(LLUUID itemID) public void deleteInventoryItem(LLUUID itemID)
{ {
DataTable inventoryItemTable = ds.Tables["inventoryitems"]; lock (InventoryLock)
DataRow inventoryRow = inventoryItemTable.Rows.Find(Util.ToRawUuidString(itemID));
if (inventoryRow != null)
{ {
inventoryRow.Delete(); DataTable inventoryItemTable = ds.Tables["inventoryitems"];
DataRow inventoryRow = inventoryItemTable.Rows.Find(Util.ToRawUuidString(itemID));
if (inventoryRow != null)
{
inventoryRow.Delete();
}
invItemsDa.Update(ds, "inventoryitems");
} }
invItemsDa.Update(ds, "inventoryitems");
} }
/// <summary> /// <summary>
/// Delete all items in the specified folder /// Delete all items in the specified folder
/// </summary> /// </summary>
@ -441,31 +473,34 @@ namespace OpenSim.Framework.Data.SQLite
/// <param name="item"></param> /// <param name="item"></param>
public void deleteInventoryFolder(LLUUID folderID) public void deleteInventoryFolder(LLUUID folderID)
{ {
List<InventoryFolderBase> subFolders = getFolderHierarchy(Util.ToRawUuidString(folderID)); lock (InventoryLock)
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
DataRow inventoryRow;
//Delete all sub-folders
foreach (InventoryFolderBase f in subFolders)
{ {
inventoryRow = inventoryFolderTable.Rows.Find(Util.ToRawUuidString(f.folderID)); List<InventoryFolderBase> subFolders = getFolderHierarchy(Util.ToRawUuidString(folderID));
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
DataRow inventoryRow;
//Delete all sub-folders
foreach (InventoryFolderBase f in subFolders)
{
inventoryRow = inventoryFolderTable.Rows.Find(Util.ToRawUuidString(f.folderID));
if (inventoryRow != null)
{
deleteItemsInFolder(Util.ToRawUuidString(f.folderID));
inventoryRow.Delete();
}
}
//Delete the actual row
inventoryRow = inventoryFolderTable.Rows.Find(Util.ToRawUuidString(folderID));
if (inventoryRow != null) if (inventoryRow != null)
{ {
deleteItemsInFolder(Util.ToRawUuidString(f.folderID)); deleteItemsInFolder(Util.ToRawUuidString(folderID));
inventoryRow.Delete(); inventoryRow.Delete();
} }
}
//Delete the actual row invFoldersDa.Update(ds, "inventoryfolders");
inventoryRow = inventoryFolderTable.Rows.Find(Util.ToRawUuidString(folderID));
if (inventoryRow != null)
{
deleteItemsInFolder(Util.ToRawUuidString(folderID));
inventoryRow.Delete();
} }
invFoldersDa.Update(ds, "inventoryfolders");
} }
/*********************************************************************** /***********************************************************************
@ -515,30 +550,36 @@ namespace OpenSim.Framework.Data.SQLite
private void setupItemsCommands(SqliteDataAdapter da, SqliteConnection conn) private void setupItemsCommands(SqliteDataAdapter da, SqliteConnection conn)
{ {
da.InsertCommand = createInsertCommand("inventoryitems", ds.Tables["inventoryitems"]); lock (InventoryLock)
da.InsertCommand.Connection = conn; {
da.InsertCommand = createInsertCommand("inventoryitems", ds.Tables["inventoryitems"]);
da.InsertCommand.Connection = conn;
da.UpdateCommand = createUpdateCommand("inventoryitems", "UUID=:UUID", ds.Tables["inventoryitems"]); da.UpdateCommand = createUpdateCommand("inventoryitems", "UUID=:UUID", ds.Tables["inventoryitems"]);
da.UpdateCommand.Connection = conn; da.UpdateCommand.Connection = conn;
SqliteCommand delete = new SqliteCommand("delete from inventoryitems where UUID = :UUID"); SqliteCommand delete = new SqliteCommand("delete from inventoryitems where UUID = :UUID");
delete.Parameters.Add(createSqliteParameter("UUID", typeof (String))); delete.Parameters.Add(createSqliteParameter("UUID", typeof(String)));
delete.Connection = conn; delete.Connection = conn;
da.DeleteCommand = delete; da.DeleteCommand = delete;
}
} }
private void setupFoldersCommands(SqliteDataAdapter da, SqliteConnection conn) private void setupFoldersCommands(SqliteDataAdapter da, SqliteConnection conn)
{ {
da.InsertCommand = createInsertCommand("inventoryfolders", ds.Tables["inventoryfolders"]); lock (InventoryLock)
da.InsertCommand.Connection = conn; {
da.InsertCommand = createInsertCommand("inventoryfolders", ds.Tables["inventoryfolders"]);
da.InsertCommand.Connection = conn;
da.UpdateCommand = createUpdateCommand("inventoryfolders", "UUID=:UUID", ds.Tables["inventoryfolders"]); da.UpdateCommand = createUpdateCommand("inventoryfolders", "UUID=:UUID", ds.Tables["inventoryfolders"]);
da.UpdateCommand.Connection = conn; da.UpdateCommand.Connection = conn;
SqliteCommand delete = new SqliteCommand("delete from inventoryfolders where UUID = :UUID"); SqliteCommand delete = new SqliteCommand("delete from inventoryfolders where UUID = :UUID");
delete.Parameters.Add(createSqliteParameter("UUID", typeof (String))); delete.Parameters.Add(createSqliteParameter("UUID", typeof(String)));
delete.Connection = conn; delete.Connection = conn;
da.DeleteCommand = delete; da.DeleteCommand = delete;
}
} }
private InventoryFolderBase buildFolder(DataRow row) private InventoryFolderBase buildFolder(DataRow row)
@ -577,15 +618,18 @@ namespace OpenSim.Framework.Data.SQLite
private void InitDB(SqliteConnection conn) private void InitDB(SqliteConnection conn)
{ {
string createInventoryItems = defineTable(createInventoryItemsTable()); lock (InventoryLock)
string createInventoryFolders = defineTable(createInventoryFoldersTable()); {
string createInventoryItems = defineTable(createInventoryItemsTable());
string createInventoryFolders = defineTable(createInventoryFoldersTable());
SqliteCommand pcmd = new SqliteCommand(createInventoryItems, conn); SqliteCommand pcmd = new SqliteCommand(createInventoryItems, conn);
SqliteCommand scmd = new SqliteCommand(createInventoryFolders, conn); SqliteCommand scmd = new SqliteCommand(createInventoryFolders, conn);
conn.Open(); conn.Open();
pcmd.ExecuteNonQuery(); pcmd.ExecuteNonQuery();
scmd.ExecuteNonQuery(); scmd.ExecuteNonQuery();
conn.Close(); conn.Close();
}
} }
private bool TestTables(SqliteConnection conn) private bool TestTables(SqliteConnection conn)
@ -603,7 +647,7 @@ namespace OpenSim.Framework.Data.SQLite
} }
catch (SqliteSyntaxException) catch (SqliteSyntaxException)
{ {
MainLog.Instance.Verbose("DATASTORE", "SQLite Database doesn't exist... creating"); m_log.Info("[DATASTORE]: SQLite Database doesn't exist... creating");
InitDB(conn); InitDB(conn);
} }
@ -614,7 +658,7 @@ namespace OpenSim.Framework.Data.SQLite
{ {
if (! tmpDS.Tables["inventoryitems"].Columns.Contains(col.ColumnName)) if (! tmpDS.Tables["inventoryitems"].Columns.Contains(col.ColumnName))
{ {
MainLog.Instance.Verbose("DATASTORE", "Missing required column:" + col.ColumnName); m_log.Info("[DATASTORE]: Missing required column:" + col.ColumnName);
return false; return false;
} }
} }
@ -622,7 +666,7 @@ namespace OpenSim.Framework.Data.SQLite
{ {
if (! tmpDS.Tables["inventoryfolders"].Columns.Contains(col.ColumnName)) if (! tmpDS.Tables["inventoryfolders"].Columns.Contains(col.ColumnName))
{ {
MainLog.Instance.Verbose("DATASTORE", "Missing required column:" + col.ColumnName); m_log.Info("[DATASTORE]: Missing required column:" + col.ColumnName);
return false; return false;
} }
} }

View File

@ -37,6 +37,8 @@ namespace OpenSim.Framework.Data.SQLite
{ {
internal class SQLiteManager : SQLiteBase internal class SQLiteManager : SQLiteBase
{ {
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private IDbConnection dbcon; private IDbConnection dbcon;
/// <summary> /// <summary>
@ -101,7 +103,7 @@ namespace OpenSim.Framework.Data.SQLite
} }
catch (SqliteSyntaxException) catch (SqliteSyntaxException)
{ {
MainLog.Instance.Verbose("DATASTORE", "SQLite Database doesn't exist... creating"); m_log.Info("[DATASTORE]: SQLite Database doesn't exist... creating");
InitDB(conn); InitDB(conn);
} }
return true; return true;

File diff suppressed because it is too large Load Diff

View File

@ -39,15 +39,24 @@ namespace OpenSim.Framework.Data.SQLite
/// </summary> /// </summary>
public class SQLiteUserData : SQLiteBase, IUserData public class SQLiteUserData : SQLiteBase, IUserData
{ {
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary> /// <summary>
/// The database manager /// The database manager
/// </summary> /// </summary>
/// <summary> /// <summary>
/// Artificial constructor called upon plugin load /// Artificial constructor called upon plugin load
/// </summary> /// </summary>
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 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 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 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 DataSet ds;
private SqliteDataAdapter da; private SqliteDataAdapter da;
private SqliteDataAdapter daf; private SqliteDataAdapter daf;
@ -60,6 +69,7 @@ namespace OpenSim.Framework.Data.SQLite
// This sucks, but It doesn't seem to work with the dataset Syncing :P // This sucks, but It doesn't seem to work with the dataset Syncing :P
g_conn = conn; g_conn = conn;
g_conn.Open();
ds = new DataSet(); ds = new DataSet();
da = new SqliteDataAdapter(new SqliteCommand(userSelect, conn)); da = new SqliteDataAdapter(new SqliteCommand(userSelect, conn));
@ -81,7 +91,7 @@ namespace OpenSim.Framework.Data.SQLite
} }
catch (SqliteSyntaxException) catch (SqliteSyntaxException)
{ {
MainLog.Instance.Verbose("SQLITE", "userfriends table not found, creating.... "); m_log.Info("[SQLITE]: userfriends table not found, creating.... ");
InitDB(conn); InitDB(conn);
daf.Fill(ds.Tables["userfriends"]); daf.Fill(ds.Tables["userfriends"]);
} }
@ -169,126 +179,77 @@ namespace OpenSim.Framework.Data.SQLite
public void AddNewUserFriend(LLUUID friendlistowner, LLUUID friend, uint perms) public void AddNewUserFriend(LLUUID friendlistowner, LLUUID friend, uint perms)
{ {
//do stuff; string InsertFriends = "insert into userfriends(ownerID, friendID, friendPerms) values(:ownerID, :friendID, :perms)";
MainLog.Instance.Verbose("FRIEND", "Stub AddNewUserFriend called");
DataTable friends = ds.Tables["userfriends"]; using (SqliteCommand cmd = new SqliteCommand(InsertFriends, g_conn))
DataTable ua = ds.Tables["userfriends"];
lock (ds)
{ {
cmd.Parameters.Add(new SqliteParameter(":ownerID", friendlistowner.UUID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":friendID", friend.UUID.ToString()));
DataRow row = friends.NewRow(); cmd.Parameters.Add(new SqliteParameter(":perms", perms));
fillFriendRow(row, friendlistowner.UUID.ToString(),friend.UUID.ToString(),perms); cmd.ExecuteNonQuery();
friends.Rows.Add(row); }
using (SqliteCommand cmd = new SqliteCommand(InsertFriends, g_conn))
row = friends.NewRow(); {
fillFriendRow(row, friend.UUID.ToString(), friendlistowner.UUID.ToString(), perms); cmd.Parameters.Add(new SqliteParameter(":ownerID", friend.UUID.ToString()));
friends.Rows.Add(row); cmd.Parameters.Add(new SqliteParameter(":friendID", friendlistowner.UUID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":perms", perms));
MainLog.Instance.Verbose("SQLITE", cmd.ExecuteNonQuery();
"Adding Friend: " + ds.Tables["userfriends"].Rows.Count + " friends stored");
// save changes off to disk
daf.Update(ds, "userfriends");
} }
} }
public void RemoveUserFriend(LLUUID friendlistowner, LLUUID friend) public void RemoveUserFriend(LLUUID friendlistowner, LLUUID friend)
{ {
DataTable ua = ds.Tables["userfriends"]; string DeletePerms = "delete from friendlist where (ownerID=:ownerID and friendID=:friendID) or (ownerID=:friendID and friendID=:ownerID)";
string select = "`ownerID` ='" + friendlistowner.UUID.ToString() + "' and `friendID` ='" + friend.UUID.ToString() + "'"; using (SqliteCommand cmd = new SqliteCommand(DeletePerms, g_conn))
lock (ds)
{ {
DataRow[] rows = ds.Tables["userfriends"].Select(select); cmd.Parameters.Add(new SqliteParameter(":ownerID", friendlistowner.UUID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":friendID", friend.UUID.ToString()));
if ( rows != null) cmd.ExecuteNonQuery();
{
if (rows.Length > 0)
{
for (int i = 0; i < rows.Length; i++)
{
DataRow row = rows[i];
row.Delete();
}
}
}
} }
select = "`ownerID` ='" + friend.UUID.ToString() + "' and `friendID` ='" + friendlistowner.UUID.ToString() + "'";
lock (ds)
{
DataRow[] rows = ds.Tables["userfriends"].Select(select);
if (rows != null)
{
if (rows.Length > 0)
{
for (int i = 0; i < rows.Length; i++)
{
DataRow row = rows[i];
row.Delete();
}
}
}
}
SqliteCommand deletecommand = new SqliteCommand("delete from userfriends where `ownerID`='" + friendlistowner.UUID.ToString() + "' and `friendID` ='" + friend.UUID.ToString() + "'", g_conn);
g_conn.Open();
deletecommand.ExecuteNonQuery();
deletecommand = new SqliteCommand("delete from userfriends where `ownerID`='" + friend.UUID.ToString() + "' and `friendID` ='" + friendlistowner.UUID.ToString() + "'", g_conn);
deletecommand.ExecuteNonQuery();
g_conn.Close();
MainLog.Instance.Verbose("FRIEND", "Stub RemoveUserFriend called");
} }
public void UpdateUserFriendPerms(LLUUID friendlistowner, LLUUID friend, uint perms) public void UpdateUserFriendPerms(LLUUID friendlistowner, LLUUID friend, uint perms)
{ {
DataTable ua = ds.Tables["userfriends"]; string UpdatePerms = "update friendlist set perms=:perms where ownerID=:ownerID and friendID=:friendID";
string select = "a.ownerID ='" + friendlistowner.UUID.ToString() + "' and b.friendID ='" + friend.UUID.ToString() + "'"; using (SqliteCommand cmd = new SqliteCommand(UpdatePerms, g_conn))
lock (ds)
{ {
DataRow[] rows = ds.Tables["userfriends"].Select(select); cmd.Parameters.Add(new SqliteParameter(":perms", perms));
cmd.Parameters.Add(new SqliteParameter(":ownerID", friendlistowner.UUID.ToString()));
if ( rows != null) cmd.Parameters.Add(new SqliteParameter(":friendID", friend.UUID.ToString()));
{ cmd.ExecuteNonQuery();
if (rows.Length > 0)
{
for (int i = 0; i < rows.Length; i++)
{
FriendListItem user = new FriendListItem();
DataRow row = rows[i];
row["friendPerms"] = Convert.ToInt32(perms);
}
daf.Update(ds, "userfriends");
}
}
} }
MainLog.Instance.Verbose("FRIEND", "Stub UpdateUserFriendPerms called");
} }
public List<FriendListItem> GetUserFriendList(LLUUID friendlistowner) public List<FriendListItem> GetUserFriendList(LLUUID friendlistowner)
{ {
List<FriendListItem> returnlist = new List<FriendListItem>(); List<FriendListItem> returnlist = new List<FriendListItem>();
string select = "ownerID = '" + friendlistowner.UUID.ToString() + "' and fownerID = friendID and ffriendID = ownerID"; using (SqliteCommand cmd = new SqliteCommand(SelectFriendsByUUID, g_conn))
lock (ds)
{ {
DataRow[] rows = ds.Tables["userfriends"].Select(select); cmd.Parameters.Add(new SqliteParameter(":ownerID", friendlistowner.UUID.ToString()));
if (rows.Length > 0) try
{ {
for (int i = 0; i < rows.Length; i++) using (IDataReader reader = cmd.ExecuteReader())
{ {
FriendListItem user = new FriendListItem(); while (reader.Read())
DataRow row = rows[i]; {
user.FriendListOwner = new LLUUID((string)row[0]); FriendListItem user = new FriendListItem();
user.Friend = new LLUUID((string)row[1]); user.FriendListOwner = friendlistowner;
user.FriendPerms = Convert.ToUInt32(row[2]); user.Friend = new LLUUID((string)reader[0]);
user.FriendListOwnerPerms = Convert.ToUInt32(row[3]); user.FriendPerms = Convert.ToUInt32(reader[1]);
returnlist.Add(user); user.FriendListOwnerPerms = Convert.ToUInt32(reader[2]);
returnlist.Add(user);
}
reader.Close();
} }
} }
catch (Exception ex)
{
m_log.Error("[USER]: Exception getting friends list for user: " + ex.ToString());
}
} }
return returnlist; return returnlist;
} }
@ -299,13 +260,9 @@ namespace OpenSim.Framework.Data.SQLite
public void UpdateUserCurrentRegion(LLUUID avatarid, LLUUID regionuuid) public void UpdateUserCurrentRegion(LLUUID avatarid, LLUUID regionuuid)
{ {
MainLog.Instance.Verbose("USER", "Stub UpdateUserCUrrentRegion called"); m_log.Info("[USER]: Stub UpdateUserCUrrentRegion called");
} }
public void LogOffUser(LLUUID avatarid)
{
MainLog.Instance.Verbose("USER", "Stub LogOffUser called");
}
public List<Framework.AvatarPickerAvatar> GeneratePickerResults(LLUUID queryID, string query) public List<Framework.AvatarPickerAvatar> GeneratePickerResults(LLUUID queryID, string query)
{ {
@ -314,41 +271,43 @@ namespace OpenSim.Framework.Data.SQLite
querysplit = query.Split(' '); querysplit = query.Split(' ');
if (querysplit.Length == 2) if (querysplit.Length == 2)
{ {
string select = "username like '" + querysplit[0] + "%' and surname like '" + querysplit[1] + "%'"; using (SqliteCommand cmd = new SqliteCommand(AvatarPickerAndSQL, g_conn))
lock (ds)
{ {
DataRow[] rows = ds.Tables["users"].Select(select); cmd.Parameters.Add(new SqliteParameter(":username", querysplit[0] + "%"));
if (rows.Length > 0) cmd.Parameters.Add(new SqliteParameter(":surname", querysplit[1] + "%"));
using (IDataReader reader = cmd.ExecuteReader())
{ {
for (int i = 0; i < rows.Length; i++) while (reader.Read())
{ {
Framework.AvatarPickerAvatar user = new Framework.AvatarPickerAvatar(); Framework.AvatarPickerAvatar user = new Framework.AvatarPickerAvatar();
DataRow row = rows[i]; user.AvatarID = new LLUUID((string) reader["UUID"]);
user.AvatarID = new LLUUID((string) row["UUID"]); user.firstName = (string) reader["username"];
user.firstName = (string) row["username"]; user.lastName = (string) reader["surname"];
user.lastName = (string) row["surname"];
returnlist.Add(user); returnlist.Add(user);
} }
reader.Close();
} }
} }
} }
else if (querysplit.Length == 1) else if (querysplit.Length == 1)
{ {
string select = "username like '" + querysplit[0] + "%' OR surname like '" + querysplit[0] + "%'"; using (SqliteCommand cmd = new SqliteCommand(AvatarPickerOrSQL, g_conn))
lock (ds)
{ {
DataRow[] rows = ds.Tables["users"].Select(select); cmd.Parameters.Add(new SqliteParameter(":username", querysplit[0] + "%"));
if (rows.Length > 0) cmd.Parameters.Add(new SqliteParameter(":surname", querysplit[0] + "%"));
using (IDataReader reader = cmd.ExecuteReader())
{ {
for (int i = 0; i < rows.Length; i++) while (reader.Read())
{ {
Framework.AvatarPickerAvatar user = new Framework.AvatarPickerAvatar(); Framework.AvatarPickerAvatar user = new Framework.AvatarPickerAvatar();
DataRow row = rows[i]; user.AvatarID = new LLUUID((string) reader["UUID"]);
user.AvatarID = new LLUUID((string) row[0]); user.firstName = (string) reader["username"];
user.firstName = (string) row[1]; user.lastName = (string) reader["surname"];
user.lastName = (string) row[2];
returnlist.Add(user); returnlist.Add(user);
} }
reader.Close();
} }
} }
} }
@ -400,6 +359,29 @@ namespace OpenSim.Framework.Data.SQLite
} }
} }
public void StoreWebLoginKey(LLUUID AgentID, LLUUID WebLoginKey)
{
DataTable users = ds.Tables["users"];
lock (ds)
{
DataRow row = users.Rows.Find(Util.ToRawUuidString(AgentID));
if (row == null)
{
m_log.Warn("[WEBLOGIN]: 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");
}
}
}
/// <summary> /// <summary>
/// Creates a new user profile /// Creates a new user profile
/// </summary> /// </summary>
@ -419,6 +401,7 @@ namespace OpenSim.Framework.Data.SQLite
else else
{ {
fillUserRow(row, user); fillUserRow(row, user);
} }
// This is why we're getting the 'logins never log-off'.. because It isn't clearing the // This is why we're getting the 'logins never log-off'.. because It isn't clearing the
// useragents table once the useragent is null // useragents table once the useragent is null
@ -457,7 +440,7 @@ namespace OpenSim.Framework.Data.SQLite
} }
} }
MainLog.Instance.Verbose("SQLITE", m_log.Info("[SQLITE]: " +
"Syncing user database: " + ds.Tables["users"].Rows.Count + " users stored"); "Syncing user database: " + ds.Tables["users"].Rows.Count + " users stored");
// save changes off to disk // save changes off to disk
da.Update(ds, "users"); da.Update(ds, "users");
@ -677,7 +660,7 @@ namespace OpenSim.Framework.Data.SQLite
{ {
if (row[col] == null) if (row[col] == null)
{ {
row[col] = ""; row[col] = String.Empty;
} }
} }
} }
@ -718,7 +701,7 @@ namespace OpenSim.Framework.Data.SQLite
{ {
if (row[col] == null) if (row[col] == null)
{ {
row[col] = ""; row[col] = String.Empty;
} }
} }
} }
@ -821,7 +804,7 @@ namespace OpenSim.Framework.Data.SQLite
} }
catch (System.Exception) catch (System.Exception)
{ {
MainLog.Instance.Verbose("USERS", "users table already exists"); m_log.Info("[USERS]: users table already exists");
} }
try try
@ -830,7 +813,7 @@ namespace OpenSim.Framework.Data.SQLite
} }
catch (System.Exception) catch (System.Exception)
{ {
MainLog.Instance.Verbose("USERS", "userfriends table already exists"); m_log.Info("[USERS]: userfriends table already exists");
} }
conn.Close(); conn.Close();
@ -853,7 +836,7 @@ namespace OpenSim.Framework.Data.SQLite
} }
catch (SqliteSyntaxException) catch (SqliteSyntaxException)
{ {
MainLog.Instance.Verbose("DATASTORE", "SQLite Database doesn't exist... creating"); m_log.Info("[DATASTORE]: SQLite Database doesn't exist... creating");
InitDB(conn); InitDB(conn);
} }
conn.Open(); conn.Open();

View File

@ -78,9 +78,6 @@ namespace OpenSim.Framework.Data
/// <returns>An array containing all the sim profiles in the specified range</returns> /// <returns>An array containing all the sim profiles in the specified range</returns>
RegionProfileData[] GetProfilesInRange(uint Xmin, uint Ymin, uint Xmax, uint Ymax); RegionProfileData[] GetProfilesInRange(uint Xmin, uint Ymin, uint Xmax, uint Ymax);
List<AvatarPickerAvatar> GeneratePickerResults(LLUUID queryID, string query);
/// <summary> /// <summary>
/// Authenticates a sim by use of its recv key. /// Authenticates a sim by use of its recv key.
/// WARNING: Insecure /// WARNING: Insecure

View File

@ -0,0 +1,68 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim 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.Text;
using libsecondlife;
using TribalMedia.Framework.Data;
namespace OpenSim.Framework.Data
{
public class OpenSimDataReader : BaseDataReader
{
public OpenSimDataReader(IDataReader source) : base(source)
{
}
public LLVector3 GetVector(string s)
{
float x = GetFloat(s + "X");
float y = GetFloat(s + "Y");
float z = GetFloat(s + "Z");
LLVector3 vector = new LLVector3(x, y, z);
return vector;
}
public LLQuaternion GetQuaternion(string s)
{
float x = GetFloat(s + "X");
float y = GetFloat(s + "Y");
float z = GetFloat(s + "Z");
float w = GetFloat(s + "W");
LLQuaternion quaternion = new LLQuaternion(x, y, z, w);
return quaternion;
}
}
}

View File

@ -0,0 +1,78 @@
/*
* 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 OpenSim 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.Data;
using System.Data.Common;
using libsecondlife;
using MySql.Data.MySqlClient;
using TribalMedia.Framework.Data;
namespace OpenSim.Framework.Data
{
public abstract class OpenSimDatabaseConnector : BaseDatabaseConnector
{
public OpenSimDatabaseConnector(string connectionString) : base(connectionString)
{
}
public override object ConvertToDbType(object value)
{
if (value is LLUUID)
{
return ((LLUUID) value).UUID.ToString();
}
return base.ConvertToDbType(value);
}
public override BaseDataReader CreateReader(IDataReader reader)
{
return new OpenSimDataReader(reader);
}
}
public class MySQLDatabaseMapper : OpenSimDatabaseConnector
{
public MySQLDatabaseMapper(string connectionString)
: base(connectionString)
{
}
public override DbConnection GetNewConnection()
{
MySqlConnection connection = new MySqlConnection(m_connectionString);
return connection;
}
public override string CreateParamName(string fieldName)
{
return "?" + fieldName;
}
}
}

View File

@ -0,0 +1,103 @@
/*
* 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 OpenSim 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.Common;
using System.Text;
using libsecondlife;
using TribalMedia.Framework.Data;
namespace OpenSim.Framework.Data
{
public class OpenSimObjectFieldMapper<TObject, TField> : ObjectField<TObject, TField>
{
public OpenSimObjectFieldMapper(BaseTableMapper tableMapper, string fieldName,
ObjectGetAccessor<TObject, TField> rowMapperGetAccessor,
ObjectSetAccessor<TObject, TField> rowMapperSetAccessor)
: base(tableMapper, fieldName, rowMapperGetAccessor, rowMapperSetAccessor)
{
}
public override void ExpandField<TObj>(TObj obj, DbCommand command, List<string> fieldNames)
{
string fieldName = FieldName;
object value = GetParamValue(obj);
if (ValueType == typeof(LLVector3))
{
LLVector3 vector = (LLVector3)value;
RawAddParam(command, fieldNames, fieldName + "X", vector.X);
RawAddParam(command, fieldNames, fieldName + "Y", vector.Y);
RawAddParam(command, fieldNames, fieldName + "Z", vector.Z);
}
else if (ValueType == typeof(LLQuaternion))
{
LLQuaternion quaternion = (LLQuaternion)value;
RawAddParam(command, fieldNames, fieldName + "X", quaternion.X);
RawAddParam(command, fieldNames, fieldName + "Y", quaternion.Y);
RawAddParam(command, fieldNames, fieldName + "Z", quaternion.Z);
RawAddParam(command, fieldNames, fieldName + "W", quaternion.W);
}
else
{
base.ExpandField(obj, command, fieldNames);
}
}
protected override object GetValue(BaseDataReader reader)
{
object value;
OpenSimDataReader osreader = (OpenSimDataReader) reader;
if (ValueType == typeof(LLVector3))
{
value = osreader.GetVector(FieldName);
}
else if (ValueType == typeof(LLQuaternion))
{
value = osreader.GetQuaternion(FieldName);
}
else if (ValueType == typeof(LLUUID))
{
Guid guid = reader.GetGuid(FieldName);
value = new LLUUID(guid);
}
else
{
value = base.GetValue(reader);
}
return value;
}
}
}

View File

@ -0,0 +1,41 @@
/*
* 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 OpenSim 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.Data;
using TribalMedia.Framework.Data;
namespace OpenSim.Framework.Data
{
public abstract class OpenSimTableMapper<TRowMapper, TPrimaryKey> : BaseTableMapper<TRowMapper, TPrimaryKey>
{
public OpenSimTableMapper(BaseDatabaseConnector database, string tableName) : base(database, tableName)
{
}
}
}

View File

@ -0,0 +1,171 @@
/*
* 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 OpenSim 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 OpenSim.Framework;
using TribalMedia.Framework.Data;
using libsecondlife;
namespace OpenSim.Framework.Data
{
public class PrimitiveBaseShapeRowMapper : BaseRowMapper<PrimitiveBaseShape>
{
public Guid SceneObjectPartId;
public PrimitiveBaseShapeRowMapper(BaseSchema schema, PrimitiveBaseShape obj) : base(schema, obj)
{
}
}
public class PrimitiveBaseShapeTableMapper : OpenSimTableMapper<PrimitiveBaseShapeRowMapper, Guid>
{
public PrimitiveBaseShapeTableMapper(BaseDatabaseConnector connection, string tableName)
: base(connection, tableName)
{
BaseSchema<PrimitiveBaseShapeRowMapper> rowMapperSchema = new BaseSchema<PrimitiveBaseShapeRowMapper>(this);
m_schema = rowMapperSchema;
m_keyFieldMapper = rowMapperSchema.AddMapping<Guid>("SceneObjectPartId",
delegate(PrimitiveBaseShapeRowMapper shape) { return shape.SceneObjectPartId; },
delegate(PrimitiveBaseShapeRowMapper shape, Guid value) { shape.SceneObjectPartId = value; });
rowMapperSchema.AddMapping<byte>("PCode",
delegate(PrimitiveBaseShapeRowMapper shape) { return shape.Object.PCode; },
delegate(PrimitiveBaseShapeRowMapper shape, byte value) { shape.Object.PCode = value; });
rowMapperSchema.AddMapping<ushort>("PathBegin",
delegate(PrimitiveBaseShapeRowMapper shape) { return shape.Object.PathBegin; },
delegate(PrimitiveBaseShapeRowMapper shape, ushort value) { shape.Object.PathBegin = value; });
rowMapperSchema.AddMapping<ushort>("PathEnd",
delegate(PrimitiveBaseShapeRowMapper shape) { return shape.Object.PathEnd; },
delegate(PrimitiveBaseShapeRowMapper shape, ushort value) { shape.Object.PathEnd = value; });
rowMapperSchema.AddMapping<byte>("PathScaleX",
delegate(PrimitiveBaseShapeRowMapper shape) { return shape.Object.PathScaleX; },
delegate(PrimitiveBaseShapeRowMapper shape, byte value) { shape.Object.PathScaleX = value; });
rowMapperSchema.AddMapping<byte>("PathScaleY",
delegate(PrimitiveBaseShapeRowMapper shape) { return shape.Object.PathScaleY; },
delegate(PrimitiveBaseShapeRowMapper shape, byte value) { shape.Object.PathScaleY = value; });
rowMapperSchema.AddMapping<byte>("PathShearX",
delegate(PrimitiveBaseShapeRowMapper shape) { return shape.Object.PathShearX; },
delegate(PrimitiveBaseShapeRowMapper shape, byte value) { shape.Object.PathShearX = value; });
rowMapperSchema.AddMapping<byte>("PathShearY",
delegate(PrimitiveBaseShapeRowMapper shape) { return shape.Object.PathShearY; },
delegate(PrimitiveBaseShapeRowMapper shape, byte value) { shape.Object.PathShearY = value; });
rowMapperSchema.AddMapping<ushort>("ProfileBegin",
delegate(PrimitiveBaseShapeRowMapper shape) { return shape.Object.ProfileBegin; },
delegate(PrimitiveBaseShapeRowMapper shape, ushort value) { shape.Object.ProfileBegin = value; });
rowMapperSchema.AddMapping<ushort>("ProfileEnd",
delegate(PrimitiveBaseShapeRowMapper shape) { return shape.Object.ProfileEnd; },
delegate(PrimitiveBaseShapeRowMapper shape, ushort value) { shape.Object.ProfileEnd = value; });
rowMapperSchema.AddMapping<LLVector3>("Scale",
delegate(PrimitiveBaseShapeRowMapper shape) { return shape.Object.Scale; },
delegate(PrimitiveBaseShapeRowMapper shape, LLVector3 value) { shape.Object.Scale = value; });
rowMapperSchema.AddMapping<sbyte>("PathTaperX",
delegate(PrimitiveBaseShapeRowMapper shape) { return shape.Object.PathTaperX; },
delegate(PrimitiveBaseShapeRowMapper shape, sbyte value) { shape.Object.PathTaperX = value; });
rowMapperSchema.AddMapping<sbyte>("PathTaperY",
delegate(PrimitiveBaseShapeRowMapper shape) { return shape.Object.PathTaperY; },
delegate(PrimitiveBaseShapeRowMapper shape, sbyte value) { shape.Object.PathTaperY = value; });
rowMapperSchema.AddMapping<sbyte>("PathTwist",
delegate(PrimitiveBaseShapeRowMapper shape) { return shape.Object.PathTwist; },
delegate(PrimitiveBaseShapeRowMapper shape, sbyte value) { shape.Object.PathTwist = value; });
rowMapperSchema.AddMapping<sbyte>("PathRadiusOffset",
delegate(PrimitiveBaseShapeRowMapper shape) { return shape.Object.PathRadiusOffset; },
delegate(PrimitiveBaseShapeRowMapper shape, sbyte value) { shape.Object.PathRadiusOffset = value; });
rowMapperSchema.AddMapping<byte>("PathRevolutions",
delegate(PrimitiveBaseShapeRowMapper shape) { return shape.Object.PathRevolutions; },
delegate(PrimitiveBaseShapeRowMapper shape, byte value) { shape.Object.PathRevolutions = value; });
rowMapperSchema.AddMapping<sbyte>("PathTwistBegin",
delegate(PrimitiveBaseShapeRowMapper shape) { return shape.Object.PathTwistBegin; },
delegate(PrimitiveBaseShapeRowMapper shape, sbyte value) { shape.Object.PathTwistBegin = value; });
rowMapperSchema.AddMapping<byte>("PathCurve",
delegate(PrimitiveBaseShapeRowMapper shape) { return shape.Object.PathCurve; },
delegate(PrimitiveBaseShapeRowMapper shape, byte value) { shape.Object.PathCurve = value; });
rowMapperSchema.AddMapping<byte>("ProfileCurve",
delegate(PrimitiveBaseShapeRowMapper shape) { return shape.Object.ProfileCurve; },
delegate(PrimitiveBaseShapeRowMapper shape, byte value) { shape.Object.ProfileCurve = value; });
rowMapperSchema.AddMapping<ushort>("ProfileHollow",
delegate(PrimitiveBaseShapeRowMapper shape) { return shape.Object.ProfileHollow; },
delegate(PrimitiveBaseShapeRowMapper shape, ushort value) { shape.Object.ProfileHollow = value; });
rowMapperSchema.AddMapping<byte[]>("TextureEntry",
delegate(PrimitiveBaseShapeRowMapper shape) { return shape.Object.TextureEntry; },
delegate(PrimitiveBaseShapeRowMapper shape, byte[] value) { shape.Object.TextureEntry = value; });
rowMapperSchema.AddMapping<byte[]>("ExtraParams",
delegate(PrimitiveBaseShapeRowMapper shape) { return shape.Object.ExtraParams; },
delegate(PrimitiveBaseShapeRowMapper shape, byte[] value) { shape.Object.ExtraParams = value; });
}
public override PrimitiveBaseShapeRowMapper FromReader(BaseDataReader reader)
{
PrimitiveBaseShape shape = new PrimitiveBaseShape();
PrimitiveBaseShapeRowMapper mapper = new PrimitiveBaseShapeRowMapper(m_schema, shape);
mapper.FillObject( reader );
return mapper;
}
public bool Update(Guid sceneObjectPartId, PrimitiveBaseShape primitiveBaseShape)
{
PrimitiveBaseShapeRowMapper mapper = CreateRowMapper(sceneObjectPartId, primitiveBaseShape);
return Update(sceneObjectPartId, mapper);
}
public bool Add(Guid sceneObjectPartId, PrimitiveBaseShape primitiveBaseShape)
{
PrimitiveBaseShapeRowMapper mapper = CreateRowMapper(sceneObjectPartId, primitiveBaseShape);
return Add(mapper);
}
private PrimitiveBaseShapeRowMapper CreateRowMapper(Guid sceneObjectPartId, PrimitiveBaseShape primitiveBaseShape)
{
PrimitiveBaseShapeRowMapper mapper = new PrimitiveBaseShapeRowMapper( m_schema, primitiveBaseShape );
mapper.SceneObjectPartId = sceneObjectPartId;
return mapper;
}
}
}

View File

@ -1,3 +1,31 @@
/*
* 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 OpenSim 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.Reflection; using System.Reflection;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
@ -10,7 +38,7 @@ using System.Runtime.InteropServices;
[assembly : AssemblyConfiguration("")] [assembly : AssemblyConfiguration("")]
[assembly : AssemblyCompany("")] [assembly : AssemblyCompany("")]
[assembly : AssemblyProduct("OpenSim.Framework.Data")] [assembly : AssemblyProduct("OpenSim.Framework.Data")]
[assembly : AssemblyCopyright("Copyright © 2007")] [assembly : AssemblyCopyright("Copyright © OpenSimulator.org Developers 2007-2008")]
[assembly : AssemblyTrademark("")] [assembly : AssemblyTrademark("")]
[assembly : AssemblyCulture("")] [assembly : AssemblyCulture("")]

View File

@ -41,7 +41,7 @@ namespace OpenSim.Framework.Data
/// <summary> /// <summary>
/// The name of the region /// The name of the region
/// </summary> /// </summary>
public string regionName = ""; public string regionName = String.Empty;
/// <summary> /// <summary>
/// A 64-bit number combining map position into a (mostly) unique ID /// A 64-bit number combining map position into a (mostly) unique ID
@ -65,10 +65,10 @@ namespace OpenSim.Framework.Data
/// Authentication secrets /// Authentication secrets
/// </summary> /// </summary>
/// <remarks>Not very secure, needs improvement.</remarks> /// <remarks>Not very secure, needs improvement.</remarks>
public string regionSendKey = ""; public string regionSendKey = String.Empty;
public string regionRecvKey = ""; public string regionRecvKey = String.Empty;
public string regionSecret = ""; public string regionSecret = String.Empty;
/// <summary> /// <summary>
/// Whether the region is online /// Whether the region is online
@ -78,14 +78,14 @@ namespace OpenSim.Framework.Data
/// <summary> /// <summary>
/// Information about the server that the region is currently hosted on /// Information about the server that the region is currently hosted on
/// </summary> /// </summary>
public string serverIP = ""; public string serverIP = String.Empty;
public uint serverPort; public uint serverPort;
public string serverURI = ""; public string serverURI = String.Empty;
public uint httpPort; public uint httpPort;
public uint remotingPort; public uint remotingPort;
public string httpServerURI = ""; public string httpServerURI = String.Empty;
/// <summary> /// <summary>
/// Set of optional overrides. Can be used to create non-eulicidean spaces. /// Set of optional overrides. Can be used to create non-eulicidean spaces.
@ -100,29 +100,41 @@ namespace OpenSim.Framework.Data
/// Optional: URI Location of the region database /// Optional: URI Location of the region database
/// </summary> /// </summary>
/// <remarks>Used for floating sim pools where the region data is not nessecarily coupled to a specific server</remarks> /// <remarks>Used for floating sim pools where the region data is not nessecarily coupled to a specific server</remarks>
public string regionDataURI = ""; public string regionDataURI = String.Empty;
/// <summary> /// <summary>
/// Region Asset Details /// Region Asset Details
/// </summary> /// </summary>
public string regionAssetURI = ""; public string regionAssetURI = String.Empty;
public string regionAssetSendKey = ""; public string regionAssetSendKey = String.Empty;
public string regionAssetRecvKey = ""; public string regionAssetRecvKey = String.Empty;
/// <summary> /// <summary>
/// Region Userserver Details /// Region Userserver Details
/// </summary> /// </summary>
public string regionUserURI = ""; public string regionUserURI = String.Empty;
public string regionUserSendKey = ""; public string regionUserSendKey = String.Empty;
public string regionUserRecvKey = ""; public string regionUserRecvKey = String.Empty;
/// <summary> /// <summary>
/// Region Map Texture Asset /// Region Map Texture Asset
/// </summary> /// </summary>
public LLUUID regionMapTextureID = new LLUUID("00000000-0000-0000-9999-000000000006"); public LLUUID regionMapTextureID = new LLUUID("00000000-0000-0000-9999-000000000006");
// 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
//
/// <summary>
/// this particular mod to the file provides support within the spec for RegionProfileData for the
/// owner_uuid for the region
/// </summary>
public LLUUID owner_uuid;
/// <summary> /// <summary>
/// Get Sim profile data from grid server when in grid mode /// Get Sim profile data from grid server when in grid mode
/// </summary> /// </summary>
@ -151,7 +163,7 @@ namespace OpenSim.Framework.Data
RegionProfileData simData = new RegionProfileData(); RegionProfileData simData = new RegionProfileData();
simData.regionLocX = Convert.ToUInt32((string) responseData["region_locx"]); simData.regionLocX = Convert.ToUInt32((string) responseData["region_locx"]);
simData.regionLocY = Convert.ToUInt32((string) responseData["region_locy"]); simData.regionLocY = Convert.ToUInt32((string) responseData["region_locy"]);
simData.regionHandle = Helpers.UIntsToLong((simData.regionLocX*256), (simData.regionLocY*256)); simData.regionHandle = Helpers.UIntsToLong((simData.regionLocX * Constants.RegionSize), (simData.regionLocY * Constants.RegionSize));
simData.serverIP = (string) responseData["sim_ip"]; simData.serverIP = (string) responseData["sim_ip"];
simData.serverPort = Convert.ToUInt32((string) responseData["sim_port"]); simData.serverPort = Convert.ToUInt32((string) responseData["sim_port"]);
simData.httpPort = Convert.ToUInt32((string) responseData["http_port"]); simData.httpPort = Convert.ToUInt32((string) responseData["http_port"]);
@ -164,7 +176,15 @@ namespace OpenSim.Framework.Data
return simData; return simData;
} }
public RegionProfileData RequestSimProfileData(ulong region_handle, string gridserver_url, /// <summary>
/// Request sim profile information from a grid server
/// </summary>
/// <param name="region_handle"></param>
/// <param name="gridserver_url"></param>
/// <param name="gridserver_sendkey"></param>
/// <param name="gridserver_recvkey"></param>
/// <returns>The sim profile. Null if there was a request failure</returns>
public static RegionProfileData RequestSimProfileData(ulong region_handle, string gridserver_url,
string gridserver_sendkey, string gridserver_recvkey) string gridserver_sendkey, string gridserver_recvkey)
{ {
Hashtable requestData = new Hashtable(); Hashtable requestData = new Hashtable();
@ -185,7 +205,7 @@ namespace OpenSim.Framework.Data
RegionProfileData simData = new RegionProfileData(); RegionProfileData simData = new RegionProfileData();
simData.regionLocX = Convert.ToUInt32((string) responseData["region_locx"]); simData.regionLocX = Convert.ToUInt32((string) responseData["region_locx"]);
simData.regionLocY = Convert.ToUInt32((string) responseData["region_locy"]); simData.regionLocY = Convert.ToUInt32((string) responseData["region_locy"]);
simData.regionHandle = Helpers.UIntsToLong((simData.regionLocX*256), (simData.regionLocY*256)); simData.regionHandle = Helpers.UIntsToLong((simData.regionLocX * Constants.RegionSize), (simData.regionLocY * Constants.RegionSize));
simData.serverIP = (string) responseData["sim_ip"]; simData.serverIP = (string) responseData["sim_ip"];
simData.serverPort = Convert.ToUInt32((string) responseData["sim_port"]); simData.serverPort = Convert.ToUInt32((string) responseData["sim_port"]);
simData.httpPort = Convert.ToUInt32((string) responseData["http_port"]); simData.httpPort = Convert.ToUInt32((string) responseData["http_port"]);

View File

@ -37,11 +37,11 @@ namespace OpenSim.Framework.Data
public int reservationMaxX = 65536; public int reservationMaxX = 65536;
public int reservationMaxY = 65536; public int reservationMaxY = 65536;
public string reservationName = ""; public string reservationName = System.String.Empty;
public string reservationCompany = ""; public string reservationCompany = System.String.Empty;
public bool status = true; public bool status = true;
public string gridSendKey = ""; public string gridSendKey = System.String.Empty;
public string gridRecvKey = ""; public string gridRecvKey = System.String.Empty;
} }
} }

View File

@ -28,11 +28,14 @@
using System; using System;
using System.IO; using System.IO;
using libsecondlife; using libsecondlife;
using OpenSim.Framework.Console;
namespace OpenSim.Framework namespace OpenSim.Framework
{ {
public class EstateSettings public class EstateSettings
{ {
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Settings to this island //Settings to this island
private float m_billableFactor; private float m_billableFactor;
@ -734,7 +737,7 @@ namespace OpenSim.Framework
} }
else else
{ {
OpenSim.Framework.Console.MainLog.Instance.Error("ESTATESETTINGS", "Unable to locate estate manager : " + avatarID.ToString() + " for removal"); m_log.Error("[ESTATESETTINGS]: Unable to locate estate manager : " + avatarID.ToString() + " for removal");
} }
} }
@ -749,113 +752,113 @@ namespace OpenSim.Framework
{ {
configMember = configMember =
new ConfigurationMember(Path.Combine(Util.configDir(), "estate_settings.xml"), "ESTATE SETTINGS", new ConfigurationMember(Path.Combine(Util.configDir(), "estate_settings.xml"), "ESTATE SETTINGS",
loadConfigurationOptions, handleIncomingConfiguration,true); loadConfigurationOptions, handleIncomingConfiguration, true);
configMember.performConfigurationRetrieve(); configMember.performConfigurationRetrieve();
} }
} }
public void loadConfigurationOptions() public void loadConfigurationOptions()
{ {
configMember.addConfigurationOption("billable_factor", ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, "", configMember.addConfigurationOption("billable_factor", ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, String.Empty,
"0.0", true); "0.0", true);
configMember.addConfigurationOption("estate_id", ConfigurationOption.ConfigurationTypes.TYPE_UINT32, "", "0", configMember.addConfigurationOption("estate_id", ConfigurationOption.ConfigurationTypes.TYPE_UINT32, String.Empty, "0",
true); true);
configMember.addConfigurationOption("parent_estate_id", ConfigurationOption.ConfigurationTypes.TYPE_UINT32, configMember.addConfigurationOption("parent_estate_id", ConfigurationOption.ConfigurationTypes.TYPE_UINT32,
"", "0", true); String.Empty, "0", true);
configMember.addConfigurationOption("max_agents", ConfigurationOption.ConfigurationTypes.TYPE_BYTE, "", "40", configMember.addConfigurationOption("max_agents", ConfigurationOption.ConfigurationTypes.TYPE_BYTE, String.Empty, "40",
true); true);
configMember.addConfigurationOption("object_bonus_factor", ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, configMember.addConfigurationOption("object_bonus_factor", ConfigurationOption.ConfigurationTypes.TYPE_FLOAT,
"", "1.0", true); String.Empty, "1.0", true);
configMember.addConfigurationOption("redirect_grid_x", ConfigurationOption.ConfigurationTypes.TYPE_INT32, "", configMember.addConfigurationOption("redirect_grid_x", ConfigurationOption.ConfigurationTypes.TYPE_INT32, String.Empty,
"0", true); "0", true);
configMember.addConfigurationOption("redirect_grid_y", ConfigurationOption.ConfigurationTypes.TYPE_INT32, "", configMember.addConfigurationOption("redirect_grid_y", ConfigurationOption.ConfigurationTypes.TYPE_INT32, String.Empty,
"0", true); "0", true);
configMember.addConfigurationOption("region_flags", ConfigurationOption.ConfigurationTypes.TYPE_UINT32, "", configMember.addConfigurationOption("region_flags", ConfigurationOption.ConfigurationTypes.TYPE_UINT32, String.Empty,
"0", true); "0", true);
configMember.addConfigurationOption("sim_access", ConfigurationOption.ConfigurationTypes.TYPE_BYTE, "", "21", configMember.addConfigurationOption("sim_access", ConfigurationOption.ConfigurationTypes.TYPE_BYTE, String.Empty, "21",
true); true);
configMember.addConfigurationOption("sun_hour", ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, "", "0", configMember.addConfigurationOption("sun_hour", ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, String.Empty, "0",
true); true);
configMember.addConfigurationOption("terrain_raise_limit", ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, configMember.addConfigurationOption("terrain_raise_limit", ConfigurationOption.ConfigurationTypes.TYPE_FLOAT,
"", "0", true); String.Empty, "0", true);
configMember.addConfigurationOption("terrain_lower_limit", ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, configMember.addConfigurationOption("terrain_lower_limit", ConfigurationOption.ConfigurationTypes.TYPE_FLOAT,
"", "0", true); String.Empty, "0", true);
configMember.addConfigurationOption("use_fixed_sun", ConfigurationOption.ConfigurationTypes.TYPE_BOOLEAN, "", configMember.addConfigurationOption("use_fixed_sun", ConfigurationOption.ConfigurationTypes.TYPE_BOOLEAN, String.Empty,
"false", true); "false", true);
configMember.addConfigurationOption("price_per_meter", ConfigurationOption.ConfigurationTypes.TYPE_UINT32, configMember.addConfigurationOption("price_per_meter", ConfigurationOption.ConfigurationTypes.TYPE_UINT32,
"", "1", true); String.Empty, "1", true);
configMember.addConfigurationOption("region_water_height", configMember.addConfigurationOption("region_water_height",
ConfigurationOption.ConfigurationTypes.TYPE_UINT16, "", "20", true); ConfigurationOption.ConfigurationTypes.TYPE_UINT16, String.Empty, "20", true);
configMember.addConfigurationOption("region_allow_terraform", configMember.addConfigurationOption("region_allow_terraform",
ConfigurationOption.ConfigurationTypes.TYPE_BOOLEAN, "", "true", true); ConfigurationOption.ConfigurationTypes.TYPE_BOOLEAN, String.Empty, "true", true);
configMember.addConfigurationOption("terrain_base_0", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID, "", configMember.addConfigurationOption("terrain_base_0", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID, String.Empty,
"b8d3965a-ad78-bf43-699b-bff8eca6c975", true); "b8d3965a-ad78-bf43-699b-bff8eca6c975", true);
configMember.addConfigurationOption("terrain_base_1", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID, "", configMember.addConfigurationOption("terrain_base_1", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID, String.Empty,
"abb783e6-3e93-26c0-248a-247666855da3", true); "abb783e6-3e93-26c0-248a-247666855da3", true);
configMember.addConfigurationOption("terrain_base_2", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID, "", configMember.addConfigurationOption("terrain_base_2", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID, String.Empty,
"179cdabd-398a-9b6b-1391-4dc333ba321f", true); "179cdabd-398a-9b6b-1391-4dc333ba321f", true);
configMember.addConfigurationOption("terrain_base_3", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID, "", configMember.addConfigurationOption("terrain_base_3", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID, String.Empty,
"beb169c7-11ea-fff2-efe5-0f24dc881df2", true); "beb169c7-11ea-fff2-efe5-0f24dc881df2", true);
configMember.addConfigurationOption("terrain_detail_0", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID, configMember.addConfigurationOption("terrain_detail_0", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID,
"", "00000000-0000-0000-0000-000000000000", true); String.Empty, "00000000-0000-0000-0000-000000000000", true);
configMember.addConfigurationOption("terrain_detail_1", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID, configMember.addConfigurationOption("terrain_detail_1", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID,
"", "00000000-0000-0000-0000-000000000000", true); String.Empty, "00000000-0000-0000-0000-000000000000", true);
configMember.addConfigurationOption("terrain_detail_2", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID, configMember.addConfigurationOption("terrain_detail_2", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID,
"", "00000000-0000-0000-0000-000000000000", true); String.Empty, "00000000-0000-0000-0000-000000000000", true);
configMember.addConfigurationOption("terrain_detail_3", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID, configMember.addConfigurationOption("terrain_detail_3", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID,
"", "00000000-0000-0000-0000-000000000000", true); String.Empty, "00000000-0000-0000-0000-000000000000", true);
configMember.addConfigurationOption("terrain_start_height_0", configMember.addConfigurationOption("terrain_start_height_0",
ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, "", "10.0", true); ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, String.Empty, "10.0", true);
configMember.addConfigurationOption("terrain_start_height_1", configMember.addConfigurationOption("terrain_start_height_1",
ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, "", "10.0", true); ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, String.Empty, "10.0", true);
configMember.addConfigurationOption("terrain_start_height_2", configMember.addConfigurationOption("terrain_start_height_2",
ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, "", "10.0", true); ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, String.Empty, "10.0", true);
configMember.addConfigurationOption("terrain_start_height_3", configMember.addConfigurationOption("terrain_start_height_3",
ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, "", "10.0", true); ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, String.Empty, "10.0", true);
configMember.addConfigurationOption("terrain_height_range_0", configMember.addConfigurationOption("terrain_height_range_0",
ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, "", "60.0", true); ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, String.Empty, "60.0", true);
configMember.addConfigurationOption("terrain_height_range_1", configMember.addConfigurationOption("terrain_height_range_1",
ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, "", "60.0", true); ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, String.Empty, "60.0", true);
configMember.addConfigurationOption("terrain_height_range_2", configMember.addConfigurationOption("terrain_height_range_2",
ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, "", "60.0", true); ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, String.Empty, "60.0", true);
configMember.addConfigurationOption("terrain_height_range_3", configMember.addConfigurationOption("terrain_height_range_3",
ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, "", "60.0", true); ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, String.Empty, "60.0", true);
configMember.addConfigurationOption("terrain_file", configMember.addConfigurationOption("terrain_file",
ConfigurationOption.ConfigurationTypes.TYPE_STRING_NOT_EMPTY, "", ConfigurationOption.ConfigurationTypes.TYPE_STRING_NOT_EMPTY, String.Empty,
"default.r32", true); "default.r32", true);
configMember.addConfigurationOption("terrain_multiplier", ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, configMember.addConfigurationOption("terrain_multiplier", ConfigurationOption.ConfigurationTypes.TYPE_FLOAT,
"", "60.0", true); String.Empty, "60.0", true);
configMember.addConfigurationOption("water_height", ConfigurationOption.ConfigurationTypes.TYPE_DOUBLE, "", configMember.addConfigurationOption("water_height", ConfigurationOption.ConfigurationTypes.TYPE_DOUBLE, String.Empty,
"20.0", true); "20.0", true);
configMember.addConfigurationOption("terrain_image_id", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID, configMember.addConfigurationOption("terrain_image_id", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID,
"", "00000000-0000-0000-0000-000000000000", true); String.Empty, "00000000-0000-0000-0000-000000000000", true);
configMember.addConfigurationOption("estate_manager_0", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID, configMember.addConfigurationOption("estate_manager_0", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID,
"", "00000000-0000-0000-0000-000000000000", true); String.Empty, "00000000-0000-0000-0000-000000000000", true);
configMember.addConfigurationOption("estate_manager_1", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID, configMember.addConfigurationOption("estate_manager_1", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID,
"", "00000000-0000-0000-0000-000000000000", true); String.Empty, "00000000-0000-0000-0000-000000000000", true);
configMember.addConfigurationOption("estate_manager_2", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID, configMember.addConfigurationOption("estate_manager_2", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID,
"", "00000000-0000-0000-0000-000000000000", true); String.Empty, "00000000-0000-0000-0000-000000000000", true);
configMember.addConfigurationOption("estate_manager_3", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID, configMember.addConfigurationOption("estate_manager_3", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID,
"", "00000000-0000-0000-0000-000000000000", true); String.Empty, "00000000-0000-0000-0000-000000000000", true);
configMember.addConfigurationOption("estate_manager_4", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID, configMember.addConfigurationOption("estate_manager_4", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID,
"", "00000000-0000-0000-0000-000000000000", true); String.Empty, "00000000-0000-0000-0000-000000000000", true);
configMember.addConfigurationOption("estate_manager_5", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID, configMember.addConfigurationOption("estate_manager_5", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID,
"", "00000000-0000-0000-0000-000000000000", true); String.Empty, "00000000-0000-0000-0000-000000000000", true);
configMember.addConfigurationOption("estate_manager_6", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID, configMember.addConfigurationOption("estate_manager_6", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID,
"", "00000000-0000-0000-0000-000000000000", true); String.Empty, "00000000-0000-0000-0000-000000000000", true);
configMember.addConfigurationOption("estate_manager_7", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID, configMember.addConfigurationOption("estate_manager_7", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID,
"", "00000000-0000-0000-0000-000000000000", true); String.Empty, "00000000-0000-0000-0000-000000000000", true);
configMember.addConfigurationOption("estate_manager_8", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID, configMember.addConfigurationOption("estate_manager_8", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID,
"", "00000000-0000-0000-0000-000000000000", true); String.Empty, "00000000-0000-0000-0000-000000000000", true);
configMember.addConfigurationOption("estate_manager_9", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID, configMember.addConfigurationOption("estate_manager_9", ConfigurationOption.ConfigurationTypes.TYPE_LLUUID,
"", "00000000-0000-0000-0000-000000000000", true); String.Empty, "00000000-0000-0000-0000-000000000000", true);
} }

View File

@ -13,7 +13,7 @@
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS AS IS AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
@ -26,23 +26,26 @@
* *
*/ */
using System;
using OpenSim.Framework.Console;
namespace OpenSim.Framework namespace OpenSim.Framework
{ {
public class GridConfig public class GridConfig
{ {
public string GridOwner = ""; public string GridOwner = String.Empty;
public string DefaultAssetServer = ""; public string DefaultAssetServer = String.Empty;
public string AssetSendKey = ""; public string AssetSendKey = String.Empty;
public string AssetRecvKey = ""; public string AssetRecvKey = String.Empty;
public string DefaultUserServer = ""; public string DefaultUserServer = String.Empty;
public string UserSendKey = ""; public string UserSendKey = String.Empty;
public string UserRecvKey = ""; public string UserRecvKey = String.Empty;
public string SimSendKey = ""; public string SimSendKey = String.Empty;
public string SimRecvKey = ""; public string SimRecvKey = String.Empty;
public string DatabaseProvider = ""; public string DatabaseProvider = String.Empty;
public static uint DefaultHttpPort = 8001; public static uint DefaultHttpPort = 8001;

View File

@ -13,7 +13,7 @@
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS AS IS AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY

View File

@ -50,7 +50,17 @@ namespace OpenSim.Framework
// could change to delegate? // could change to delegate?
public interface IAssetReceiver public interface IAssetReceiver
{ {
/// <summary>
/// Call back made when a requested asset has been retrieved by an asset server
/// </summary>
/// <param name="asset"></param>
/// <param name="IsTexture"></param>
void AssetReceived(AssetBase asset, bool IsTexture); void AssetReceived(AssetBase asset, bool IsTexture);
/// <summary>
/// Call back made when an asset server could not retrieve a requested asset
/// </summary>
/// <param name="assetID"></param>
void AssetNotFound(LLUUID assetID); void AssetNotFound(LLUUID assetID);
} }

View File

@ -65,7 +65,7 @@ namespace OpenSim.Framework
Task = 4, Task = 4,
Texture = 5, Texture = 5,
Asset = 6, Asset = 6,
Unknown = 7, Unknown = 7, // Also doubles as 'do not throttle'
Back = 8 Back = 8
} }
@ -234,6 +234,11 @@ namespace OpenSim.Framework
uint EveryoneMask, uint GroupMask, uint NextOwnerMask, uint ItemFlags, uint EveryoneMask, uint GroupMask, uint NextOwnerMask, uint ItemFlags,
bool RezSelected, bool RemoveItem, LLUUID fromTaskID ); bool RezSelected, bool RemoveItem, LLUUID fromTaskID );
public delegate void RezSingleAttachmentFromInv(IClientAPI remoteClient, LLUUID itemID, uint AttachmentPt,
uint ItemFlags, uint NextOwnerMask);
public delegate void ObjectAttach(IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, LLQuaternion rot);
public delegate void ModifyTerrain( public delegate void ModifyTerrain(
float height, float seconds, byte size, byte action, float north, float west, float south, float east, float height, float seconds, byte size, byte action, float north, float west, float south, float east,
IClientAPI remoteClient); IClientAPI remoteClient);
@ -380,7 +385,10 @@ namespace OpenSim.Framework
IClientAPI remoteClient, LLUUID folderID, LLUUID itemID, int length, string newName); IClientAPI remoteClient, LLUUID folderID, LLUUID itemID, int length, string newName);
public delegate void RemoveInventoryItem( public delegate void RemoveInventoryItem(
IClientAPI remoteClient, LLUUID itemID); // rex IClientAPI remoteClient, LLUUID itemID);
public delegate void RemoveInventoryFolder(
IClientAPI remoteClient, LLUUID folderID);
public delegate void RezScript(IClientAPI remoteClient, LLUUID itemID, uint localID); public delegate void RezScript(IClientAPI remoteClient, LLUUID itemID, uint localID);
@ -403,7 +411,14 @@ namespace OpenSim.Framework
public delegate void FriendshipTermination(IClientAPI remoteClient,LLUUID agentID, LLUUID ExID); public delegate void FriendshipTermination(IClientAPI remoteClient,LLUUID agentID, LLUUID ExID);
public delegate void ReceiveRexClientScriptCmd(IClientAPI remoteClient,LLUUID agentID,List<string> vParams); // rex public delegate void ReceiveRexClientScriptCmd(IClientAPI remoteClient,LLUUID agentID,List<string> vParams); // rex
public delegate void PacketStats(int inPackets, int outPackets, int unAckedBytes);
public delegate void MoneyTransferRequest(LLUUID sourceID, LLUUID destID, int amount, int transactionType, string description);
// We keep all this information for fraud purposes in the future.
public delegate void MoneyBalanceRequest(IClientAPI remoteClient, LLUUID agentID, LLUUID sessionID, LLUUID TransactionID);
public delegate void ObjectPermissions(IClientAPI controller, LLUUID agentID, LLUUID sessionID, byte field, uint localId, uint mask, byte set);
//Attachments //Attachments
public delegate void RezSingleAttachmentFromInv(IClientAPI remoteClient, LLUUID itemID, LLUUID ownerID, public delegate void RezSingleAttachmentFromInv(IClientAPI remoteClient, LLUUID itemID, LLUUID ownerID,
uint itemFlags, byte attachPoint); uint itemFlags, byte attachPoint);
@ -433,6 +448,8 @@ namespace OpenSim.Framework
event ModifyTerrain OnModifyTerrain; event ModifyTerrain OnModifyTerrain;
event SetAppearance OnSetAppearance; event SetAppearance OnSetAppearance;
event AvatarNowWearing OnAvatarNowWearing; event AvatarNowWearing OnAvatarNowWearing;
event RezSingleAttachmentFromInv OnRezSingleAttachmentFromInv;
event ObjectAttach OnObjectAttach;
event StartAnim OnStartAnim; event StartAnim OnStartAnim;
event StopAnim OnStopAnim; event StopAnim OnStopAnim;
event LinkObjects OnLinkObjects; event LinkObjects OnLinkObjects;
@ -454,6 +471,10 @@ namespace OpenSim.Framework
event Action<IClientAPI> OnRequestAvatarsData; event Action<IClientAPI> OnRequestAvatarsData;
event AddNewPrim OnAddPrim; event AddNewPrim OnAddPrim;
event FetchInventory OnAgentDataUpdateRequest;
event FetchInventory OnUserInfoRequest;
event TeleportLocationRequest OnSetStartLocationRequest;
event RequestGodlikePowers OnRequestGodlikePowers; event RequestGodlikePowers OnRequestGodlikePowers;
event GodKickUser OnGodKickUser; event GodKickUser OnGodKickUser;
@ -493,7 +514,8 @@ namespace OpenSim.Framework
event UpdateInventoryItem OnUpdateInventoryItem; event UpdateInventoryItem OnUpdateInventoryItem;
event CopyInventoryItem OnCopyInventoryItem; event CopyInventoryItem OnCopyInventoryItem;
event MoveInventoryItem OnMoveInventoryItem; event MoveInventoryItem OnMoveInventoryItem;
event RemoveInventoryItem OnRemoveInventoryItem; // rex event RemoveInventoryFolder OnRemoveInventoryFolder;
event RemoveInventoryItem OnRemoveInventoryItem;
event UDPAssetUploadRequest OnAssetUploadRequest; event UDPAssetUploadRequest OnAssetUploadRequest;
event XferReceive OnXferReceive; event XferReceive OnXferReceive;
event RequestXfer OnRequestXfer; event RequestXfer OnRequestXfer;
@ -523,6 +545,12 @@ namespace OpenSim.Framework
event FriendActionDelegate OnApproveFriendRequest; event FriendActionDelegate OnApproveFriendRequest;
event FriendActionDelegate OnDenyFriendRequest; event FriendActionDelegate OnDenyFriendRequest;
event FriendshipTermination OnTerminateFriendship; event FriendshipTermination OnTerminateFriendship;
event PacketStats OnPacketStats;
// Financial packets
event MoneyTransferRequest OnMoneyTransferRequest;
event MoneyBalanceRequest OnMoneyBalanceRequest;
event ReceiveRexClientScriptCmd OnReceiveRexClientScriptCmd; // rex event ReceiveRexClientScriptCmd OnReceiveRexClientScriptCmd; // rex
event ObjectClickAction OnObjectClickAction; // rex event ObjectClickAction OnObjectClickAction; // rex
@ -583,7 +611,7 @@ namespace OpenSim.Framework
void SendRegionTeleport(ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint, uint locationID, void SendRegionTeleport(ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint, uint locationID,
uint flags, string capsURL); uint flags, string capsURL);
void SendTeleportFailed(); void SendTeleportFailed(string reason);
void SendTeleportLocationStart(); void SendTeleportLocationStart();
void SendMoneyBalance(LLUUID transaction, bool success, byte[] description, int balance); void SendMoneyBalance(LLUUID transaction, bool success, byte[] description, int balance);
@ -598,6 +626,10 @@ namespace OpenSim.Framework
void AttachObject(uint localID, LLQuaternion rotation, byte attachPoint); void AttachObject(uint localID, LLQuaternion rotation, byte attachPoint);
void SetChildAgentThrottle(byte[] throttle); void SetChildAgentThrottle(byte[] throttle);
void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimitiveBaseShape primShape,
LLVector3 pos, uint flags, LLUUID objectID, LLUUID ownerID, string text, byte[] color,
uint parentID, byte[] particleSystem, LLQuaternion rotation, byte clickAction, byte[] textureanimation);
void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimitiveBaseShape primShape, void SendPrimitiveToClient(ulong regionHandle, ushort timeDilation, uint localID, PrimitiveBaseShape primShape,
LLVector3 pos, uint flags, LLUUID objectID, LLUUID ownerID, string text, byte[] color, LLVector3 pos, uint flags, LLUUID objectID, LLUUID ownerID, string text, byte[] color,
uint parentID, byte[] particleSystem, LLQuaternion rotation, byte clickAction); uint parentID, byte[] particleSystem, LLQuaternion rotation, byte clickAction);
@ -625,6 +657,8 @@ namespace OpenSim.Framework
void SendXferPacket(ulong xferID, uint packet, byte[] data); void SendXferPacket(ulong xferID, uint packet, byte[] data);
void SendAvatarPickerReply(AvatarPickerReplyPacket Pack); void SendAvatarPickerReply(AvatarPickerReplyPacket Pack);
void SendAgentDataUpdate(LLUUID agentid, LLUUID activegroupid, string firstname, string lastname, ulong grouppowers, string groupname, string grouptitle);
void SendPreLoadSound(LLUUID objectID, LLUUID ownerID, LLUUID soundID); void SendPreLoadSound(LLUUID objectID, LLUUID ownerID, LLUUID soundID);
void SendPlayAttachedSound(LLUUID soundID, LLUUID objectID, LLUUID ownerID, float gain, byte flags); void SendPlayAttachedSound(LLUUID soundID, LLUUID objectID, LLUUID ownerID, float gain, byte flags);
void SendTriggeredSound(LLUUID soundID, LLUUID ownerID, LLUUID objectID, LLUUID parentID, ulong handle, LLVector3 position, float gain); void SendTriggeredSound(LLUUID soundID, LLUUID ownerID, LLUUID objectID, LLUUID parentID, ulong handle, LLVector3 position, float gain);
@ -643,6 +677,8 @@ namespace OpenSim.Framework
void SendAvatarProperties(LLUUID avatarID, string aboutText, string bornOn, string charterMember, string flAbout, void SendAvatarProperties(LLUUID avatarID, string aboutText, string bornOn, string charterMember, string flAbout,
uint flags, LLUUID flImageID, LLUUID imageID, string profileURL, LLUUID partnerID); uint flags, LLUUID flImageID, LLUUID imageID, string profileURL, LLUUID partnerID);
byte[] GetThrottlesPacked(float multiplier);
void SendScriptTeleportRequest(string objectName, string simName, LLVector3 simPosition, LLVector3 lookAt); void SendScriptTeleportRequest(string objectName, string simName, LLVector3 simPosition, LLVector3 lookAt);
void SetDebug(int newDebug); void SetDebug(int newDebug);

View File

@ -13,7 +13,7 @@
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS AS IS AND ANY * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY

View File

@ -44,13 +44,15 @@ namespace OpenSim.Framework
public delegate void AcknowledgePrimCross(ulong regionHandle, LLUUID PrimID); public delegate void AcknowledgePrimCross(ulong regionHandle, LLUUID PrimID);
public delegate void CloseAgentConnection(ulong regionHandle, LLUUID agentID); public delegate bool CloseAgentConnection(ulong regionHandle, LLUUID agentID);
public delegate bool RegionUp(RegionInfo region); public delegate bool RegionUp(RegionInfo region);
public delegate bool ChildAgentUpdate(ulong regionHandle, ChildAgentDataUpdate cAgentData); public delegate bool ChildAgentUpdate(ulong regionHandle, ChildAgentDataUpdate cAgentData);
public interface IRegionCommsListener public interface IRegionCommsListener
{ {
event ExpectUserDelegate OnExpectUser; event ExpectUserDelegate OnExpectUser;
@ -64,5 +66,6 @@ namespace OpenSim.Framework
event CloseAgentConnection OnCloseAgentConnection; event CloseAgentConnection OnCloseAgentConnection;
event RegionUp OnRegionUp; event RegionUp OnRegionUp;
event ChildAgentUpdate OnChildAgentUpdate; event ChildAgentUpdate OnChildAgentUpdate;
} }
} }

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