* 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
* 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
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY

View File

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

View File

@ -234,7 +234,7 @@ namespace OpenSim.Framework
public LLUUID CreatorID;
public sbyte InvType;
public sbyte Type;
public string Name = "";
public string Name = System.String.Empty;
public string Description;
public InventoryItem()
@ -245,7 +245,7 @@ namespace OpenSim.Framework
public string ExportString()
{
string typ = "notecard";
string result = "";
string result = System.String.Empty;
result += "\tinv_object\t0\n\t{\n";
result += "\t\tobj_id\t%s\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.Runtime.InteropServices;
@ -10,7 +38,7 @@ using System.Runtime.InteropServices;
[assembly : AssemblyConfiguration("")]
[assembly : AssemblyCompany("")]
[assembly : AssemblyProduct("OpenSim.FrameWork")]
[assembly : AssemblyCopyright("Copyright © 2007")]
[assembly : AssemblyCopyright("Copyright © OpenSimulator.org Developers 2007-2008")]
[assembly : AssemblyTrademark("")]
[assembly : AssemblyCulture("")]

View File

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

View File

@ -13,7 +13,7 @@
* 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
* 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
@ -26,6 +26,9 @@
*
*/
using System;
using OpenSim.Framework.Console;
namespace OpenSim.Framework
{
/// <summary>
@ -33,9 +36,9 @@ namespace OpenSim.Framework
/// </summary>
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 uint HttpPort = DefaultHttpPort;

View File

@ -44,6 +44,8 @@ namespace OpenSim.Framework.AssetLoader.Filesystem
{
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)
{
AssetBase asset = new AssetBase(
@ -53,13 +55,13 @@ namespace OpenSim.Framework.AssetLoader.Filesystem
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);
}
else
{
MainLog.Instance.Verbose("ASSETS", "Instantiated: [{0}]", name);
m_log.InfoFormat("[ASSETS]: Instantiated: [{0}]", name);
}
return asset;
@ -99,21 +101,19 @@ namespace OpenSim.Framework.AssetLoader.Filesystem
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);
}
}
catch (XmlException e)
{
MainLog.Instance.Error("ASSETS", "Error loading {0} : {1}", assetSetPath, e);
m_log.ErrorFormat("[ASSETS]: Error loading {0} : {1}", assetSetPath, e);
}
}
else
{
MainLog.Instance.Error(
"ASSETS",
"Asset set control file assets/AssetSets.xml does not exist! No assets loaded.");
m_log.Error("[ASSETS]: Asset set control file assets/AssetSets.xml does not exist! No assets loaded.");
}
assets.ForEach(action);
@ -126,7 +126,7 @@ namespace OpenSim.Framework.AssetLoader.Filesystem
/// <param name="assets"></param>
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))
{
@ -138,10 +138,10 @@ namespace OpenSim.Framework.AssetLoader.Filesystem
for (int i = 0; i < source.Configs.Count; i++)
{
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 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);
@ -152,12 +152,12 @@ namespace OpenSim.Framework.AssetLoader.Filesystem
}
catch (XmlException e)
{
MainLog.Instance.Error("ASSETS", "Error loading {0} : {1}", assetSetPath, e);
m_log.ErrorFormat("[ASSETS]: Error loading {0} : {1}", assetSetPath, e);
}
}
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;
namespace OpenSim.Framework

View File

@ -64,5 +64,10 @@ namespace OpenSim.Framework
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 float godlevel;
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
* 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
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
@ -26,6 +26,7 @@
*
*/
using System;
using System.Collections.Generic;
using libsecondlife;
using libsecondlife.Packets;
@ -36,11 +37,12 @@ namespace OpenSim.Framework
public class ClientManager
{
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private Dictionary<uint, IClientAPI> m_clients;
public void ForEachClient(ForEachClientDelegate whatToDo)
{
// Wasteful, I know
IClientAPI[] LocalClients = new IClientAPI[0];
lock (m_clients)
@ -57,7 +59,7 @@ namespace OpenSim.Framework
}
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>();
}
private void Remove(uint id)
public void Remove(uint 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)
{
lock (m_clients)
{
m_clients.Add(id, client);
}
}
public void InPacket(uint circuitCode, Packet packet)
{
IClientAPI client;
if (m_clients.TryGetValue(circuitCode, out client))
bool tryGetRet = false;
lock (m_clients)
tryGetRet = m_clients.TryGetValue(circuitCode, out client);
if(tryGetRet)
{
client.InPacket(packet);
}
@ -90,8 +102,10 @@ namespace OpenSim.Framework
public void CloseAllAgents(uint circuitCode)
{
IClientAPI client;
if (m_clients.TryGetValue(circuitCode, out client))
bool tryGetRet = false;
lock (m_clients)
tryGetRet = m_clients.TryGetValue(circuitCode, out client);
if (tryGetRet)
{
CloseAllCircuits(client.AgentId);
}
@ -107,8 +121,10 @@ namespace OpenSim.Framework
IClientAPI client;
try
{
if (m_clients.TryGetValue(circuits[i], out client))
bool tryGetRet = false;
lock (m_clients)
tryGetRet = m_clients.TryGetValue(circuits[i], out client);
if(tryGetRet)
{
Remove(client.CircuitCode);
client.Close(false);
@ -116,11 +132,9 @@ namespace OpenSim.Framework
}
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)
@ -134,7 +148,6 @@ namespace OpenSim.Framework
m_clients.Values.CopyTo(LocalClients, 0);
}
for (int i = 0; i < LocalClients.Length; i++ )
{
if (LocalClients[i].AgentId == agentId)
@ -160,13 +173,13 @@ namespace OpenSim.Framework
m_clients.Values.CopyTo(LocalClients, 0);
}
for (int i = 0; i < LocalClients.Length; i++)
{
if (LocalClients[i].AgentId != sender.AgentId)
{
packet.AgentData.AgentID = LocalClients[i].AgentId;
packet.AgentData.SessionID = LocalClients[i].SessionId;
packet.Header.Reliable = false;
LocalClients[i].OutPacket(packet, ThrottleOutPacketType.Task);
}
@ -174,8 +187,11 @@ namespace OpenSim.Framework
}
public bool TryGetClient(uint circuitId, out IClientAPI 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
* 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
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
@ -32,7 +32,7 @@ namespace OpenSim.Framework.Communications
{
public class CAPSService
{
private BaseHttpServer m_server;
private readonly BaseHttpServer m_server;
public CAPSService(BaseHttpServer httpServer)
{
@ -48,7 +48,7 @@ namespace OpenSim.Framework.Communications
public string CapsRequest(string request, string path, string param)
{
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.
*
*/
//moved to a module, left here until the module is found to have no problems
/*
using System;
using System.Collections.Generic;
using System.IO;
@ -35,18 +37,24 @@ using OpenSim.Region.Capabilities;
namespace OpenSim.Framework.Communications.Cache
{
/// <summary>
/// Manage asset transactions for a single agent.
/// </summary>
public class AgentAssetTransactions
{
private static readonly log4net.ILog m_log
= log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Fields
public List<AssetCapsUploader> CapsUploaders = new List<AssetCapsUploader>();
public List<NoteCardCapsUpdate> NotecardUpdaters = new List<NoteCardCapsUpdate>();
public LLUUID UserID;
public Dictionary<LLUUID, AssetXferUploader> XferUploaders = new Dictionary<LLUUID, AssetXferUploader>();
public AssetTransactionManager Manager;
public AgentAssetTransactionsManager Manager;
private bool m_dumpAssetsToFile;
// Methods
public AgentAssetTransactions(LLUUID agentID, AssetTransactionManager manager, bool dumpAssetsToFile)
public AgentAssetTransactions(LLUUID agentID, AgentAssetTransactionsManager manager, bool dumpAssetsToFile)
{
UserID = agentID;
Manager = manager;
@ -73,22 +81,49 @@ namespace OpenSim.Framework.Communications.Cache
{
AssetXferUploader uploader = new AssetXferUploader(this, m_dumpAssetsToFile);
lock (XferUploaders)
{
XferUploaders.Add(transactionID, uploader);
}
return uploader;
}
return null;
}
public void HandleXfer(ulong xferID, uint packetID, byte[] data)
{
AssetXferUploader uploaderFound = null;
lock (XferUploaders)
{
foreach (AssetXferUploader uploader in XferUploaders.Values)
{
if (uploader.XferID == xferID)
{
uploader.HandleXferPacket(xferID, packetID, data);
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);
}
}
}
public void RequestCreateInventoryItem(IClientAPI remoteClient, LLUUID transactionID, LLUUID folderID,
@ -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)
{
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;
}
@ -123,8 +181,8 @@ namespace OpenSim.Framework.Communications.Cache
public LLUUID TransactionID = LLUUID.Zero;
public bool UploadComplete;
public ulong XferID;
private string m_name = "";
private string m_description = "";
private string m_name = String.Empty;
private string m_description = String.Empty;
private sbyte type = 0;
private sbyte invType = 0;
private uint nextPerm = 0;
@ -140,8 +198,14 @@ namespace OpenSim.Framework.Communications.Cache
m_dumpAssetToFile = dumpAssetToFile;
}
// Methods
public void HandleXferPacket(ulong xferID, uint packetID, byte[] data)
/// <summary>
/// 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)
{
@ -165,11 +229,21 @@ namespace OpenSim.Framework.Communications.Cache
if ((packetID & 0x80000000) != 0)
{
SendCompleteMessage();
}
return true;
}
}
public void Initialise(IClientAPI remoteClient, LLUUID assetID, LLUUID transaction, sbyte type, byte[] data,
return false;
}
/// <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)
{
ourClient = remoteClient;
@ -188,14 +262,17 @@ namespace OpenSim.Framework.Communications.Cache
if (Asset.Data.Length > 2)
{
SendCompleteMessage();
return true;
}
else
{
ReqestStartXfer();
}
RequestStartXfer();
}
protected void ReqestStartXfer()
return false;
}
protected void RequestStartXfer()
{
UploadComplete = false;
XferID = Util.GetNextXferID();
@ -237,6 +314,7 @@ namespace OpenSim.Framework.Communications.Cache
SaveAssetToFile(filename, Asset.Data);
}
}
///Left this in and commented in case there are unforseen issues
//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()
{
//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.invType = invType;
item.parentFolderID = InventFolder;
item.inventoryBasePermissions = 2147483647;
item.inventoryCurrentPermissions = 2147483647;
item.inventoryNextPermissions = nextPerm;
@ -310,10 +427,6 @@ namespace OpenSim.Framework.Communications.Cache
}
}
public void UpdateInventoryItem(LLUUID itemID)
{
}
public AssetBase GetAssetData()
{
if (m_finished)
@ -331,12 +444,12 @@ namespace OpenSim.Framework.Communications.Cache
// Fields
private BaseHttpServer httpListener;
private LLUUID inventoryItemID;
private string m_assetDescription = "";
private string m_assetName = "";
private string m_assetDescription = String.Empty;
private string m_assetName = String.Empty;
private LLUUID m_folderID;
private LLUUID newAssetID;
private bool m_dumpImageToFile;
private string uploaderPath = "";
private string uploaderPath = String.Empty;
// Events
public event UpLoadedAsset OnUpLoad;
@ -367,7 +480,7 @@ namespace OpenSim.Framework.Communications.Cache
public string uploaderCaps(byte[] data, string path, string param)
{
LLUUID inventoryItemID = this.inventoryItemID;
string text = "";
string text = String.Empty;
LLSDAssetUploadComplete complete = new LLSDAssetUploadComplete();
complete.new_asset = newAssetID.ToString();
complete.new_inventory_item = inventoryItemID;
@ -380,7 +493,7 @@ namespace OpenSim.Framework.Communications.Cache
}
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;
}
@ -391,10 +504,10 @@ namespace OpenSim.Framework.Communications.Cache
// Fields
private BaseHttpServer httpListener;
private LLUUID inventoryItemID;
private string m_assetName = "";
private string m_assetName = String.Empty;
private LLUUID newAssetID;
private bool SaveImages = false;
private string uploaderPath = "";
private string uploaderPath = String.Empty;
// Events
public event UpLoadedAsset OnUpLoad;
@ -420,7 +533,7 @@ namespace OpenSim.Framework.Communications.Cache
public string uploaderCaps(byte[] data, string path, string param)
{
LLUUID inventoryItemID = this.inventoryItemID;
string text = "";
string text = String.Empty;
LLSDAssetUploadComplete complete = new LLSDAssetUploadComplete();
complete.new_asset = newAssetID.ToString();
complete.new_inventory_item = inventoryItemID;
@ -433,7 +546,7 @@ namespace OpenSim.Framework.Communications.Cache
}
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;
}
@ -442,3 +555,4 @@ namespace OpenSim.Framework.Communications.Cache
#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 libsecondlife;
using libsecondlife.Packets;
using OpenSim.Framework.Console;
using OpenSim.Framework.Statistics;
namespace OpenSim.Framework.Communications.Cache
{
@ -39,47 +41,142 @@ namespace OpenSim.Framework.Communications.Cache
/// <summary>
/// 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>
public class AssetCache : IAssetReceiver
{
public Dictionary<LLUUID, AssetInfo> Assets;
public Dictionary<LLUUID, TextureImage> Textures;
private static readonly log4net.ILog m_log
= log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public List<AssetRequest> AssetRequests = new List<AssetRequest>(); //assets ready to be sent to viewers
public List<AssetRequest> TextureRequests = new List<AssetRequest>(); //textures ready to be sent
/// <summary>
/// The cache of assets. This does not include textures.
/// </summary>
private Dictionary<LLUUID, AssetInfo> Assets;
public Dictionary<LLUUID, AssetRequest> RequestedAssets = new Dictionary<LLUUID, AssetRequest>();
//Assets requested from the asset server
/// <summary>
/// The cache of textures.
/// </summary>
private Dictionary<LLUUID, TextureImage> Textures;
public Dictionary<LLUUID, AssetRequest> RequestedTextures = new Dictionary<LLUUID, AssetRequest>();
//Textures requested from the asset server
/// <summary>
/// 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 Thread m_assetCacheThread;
private readonly LogBase m_log;
/// <summary>
///
/// Report statistical data.
/// </summary>
public AssetCache(IAssetServer assetServer, LogBase log)
public void ShowState()
{
log.Verbose("ASSETSTORAGE", "Creating Asset cache");
m_assetServer = assetServer;
m_assetServer.SetReceiver(this);
Assets = new Dictionary<LLUUID, AssetInfo>();
Textures = new Dictionary<LLUUID, TextureImage>();
m_assetCacheThread = new Thread(new ThreadStart(RunAssetManager));
m_assetCacheThread.IsBackground = true;
m_assetCacheThread.Start();
m_log.InfoFormat("Assets:{0} Textures:{1} AssetRequests:{2} RequestedAssets:{3} RequestLists:{4}",
Assets.Count,
Textures.Count,
AssetRequests.Count,
RequestedAssets.Count,
RequestLists.Count);
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>
///
/// 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>
public void RunAssetManager()
{
@ -92,7 +189,7 @@ namespace OpenSim.Framework.Communications.Cache
}
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>
/// Only get an asset if we already have it in the cache.
/// </summary>
/// <param name="assetID"></param></param>
/// <param name="assetId"></param></param>
/// <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];
}
return asset;
asset = Assets[assetId];
return true;
}
public void GetAsset(LLUUID assetID, AssetRequestCallback callback)
{
AssetBase asset = null;
if (Textures.ContainsKey(assetID))
{
asset = Textures[assetID];
}
else if (Assets.ContainsKey(assetID))
{
asset = Assets[assetID];
asset = null;
return false;
}
if (asset != null)
/// <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)
{
callback(assetID, asset);
AssetBase asset;
if (TryGetCachedAsset(assetId, out asset))
{
callback(assetId, asset);
}
else
{
NewAssetRequest req = new NewAssetRequest(assetID, callback);
if (RequestLists.ContainsKey(assetID))
{
#if DEBUG
//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)
{
RequestLists[assetID].Requests.Add(req);
}
if (RequestLists.TryGetValue(assetId, out requestList))
{
}
else
{
AssetRequestsList reqList = new AssetRequestsList(assetID);
reqList.Requests.Add(req);
lock (RequestLists)
{
RequestLists.Add(assetID, reqList);
requestList = new AssetRequestsList(assetId);
RequestLists.Add(assetId, requestList);
}
}
m_assetServer.RequestAsset(assetID, false);
requestList.Requests.Add(req);
m_assetServer.RequestAsset(assetId, isTexture);
}
}
/// <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.
///
/// 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
/// 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
/// 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
/// asset is much more likely to have made it into the cache.
/// </summary>
@ -177,30 +298,32 @@ namespace OpenSim.Framework.Communications.Cache
int pollPeriod = 200;
int maxPolls = 15;
AssetBase asset = GetCachedAsset(assetID);
if (asset != null)
AssetBase asset;
if (TryGetCachedAsset(assetID, out asset))
{
return asset;
}
else
{
m_assetServer.RequestAsset(assetID, isTexture);
do
{
Thread.Sleep(pollPeriod);
asset = GetCachedAsset(assetID);
if (asset != null)
if (TryGetCachedAsset(assetID, out asset))
{
return asset;
}
} while (--maxPolls > 0);
MainLog.Instance.Warn(
"ASSETCACHE", "Asset {0} was not received before the retrieval timeout was reached");
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
public List<AssetBase> GetAssetList(int vAssetType)
@ -220,7 +343,7 @@ namespace OpenSim.Framework.Communications.Cache
/// <param name="asset"></param>
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 result = "Ignored";
@ -235,6 +358,10 @@ namespace OpenSim.Framework.Communications.Cache
{
TextureImage textur = new TextureImage(asset);
Textures.Add(textur.FullID, textur);
if (StatsManager.SimExtraStats != null)
StatsManager.SimExtraStats.AddTexture(textur);
if (asset.Temporary)
{
result = "Added to cache";
@ -256,6 +383,10 @@ namespace OpenSim.Framework.Communications.Cache
{
AssetInfo assetInf = new AssetInfo(asset);
Assets.Add(assetInf.FullID, assetInf);
if (StatsManager.SimExtraStats != null)
StatsManager.SimExtraStats.AddAsset(assetInf);
if (asset.Temporary)
{
result = "Added to cache";
@ -267,8 +398,9 @@ namespace OpenSim.Framework.Communications.Cache
}
}
}
m_log.Verbose("ASSETCACHE", "Adding {0} {1} [{2}]: {3}.", temporary, type, asset.FullID, result);
#if DEBUG
//m_log.DebugFormat("[ASSET CACHE]: Adding {0} {1} [{2}]: {3}.", temporary, type, asset.FullID, result);
#endif
}
// rex, new function for "replace asset" functionality
@ -372,25 +504,13 @@ namespace OpenSim.Framework.Communications.Cache
}
public void DeleteAsset(LLUUID assetID)
{
// 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;
}
// See IAssetReceiver
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
{
//check if it is a texture or not
@ -400,42 +520,61 @@ namespace OpenSim.Framework.Communications.Cache
if (IsTexture)
{
//Console.WriteLine("asset received from asset server");
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);
if (RequestedTextures.ContainsKey(image.FullID))
if (StatsManager.SimExtraStats != null)
{
AssetRequest req = RequestedTextures[image.FullID];
req.ImageInfo = image;
req.NumPackets = CalculateNumPackets(image.Data);
RequestedTextures.Remove(image.FullID);
TextureRequests.Add(req);
StatsManager.SimExtraStats.AddTexture(image);
}
}
}
else
{
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);
if (StatsManager.SimExtraStats != null)
{
StatsManager.SimExtraStats.AddAsset(assetInf);
}
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];
req.AssetInf = assetInf;
req.NumPackets = CalculateNumPackets(assetInf.Data);
RequestedAssets.Remove(assetInf.FullID);
AssetRequests.Add(req);
}
}
}
// Notify requesters for this asset
if (RequestLists.ContainsKey(asset.FullID))
{
lock (RequestLists)
{
AssetRequestsList reqList = RequestLists[asset.FullID];
foreach (NewAssetRequest req in reqList.Requests)
@ -443,8 +582,6 @@ namespace OpenSim.Framework.Communications.Cache
req.Callback(asset.FullID, asset);
}
lock (RequestLists)
{
RequestLists.Remove(asset.FullID);
reqList.Requests.Clear();
}
@ -452,23 +589,52 @@ namespace OpenSim.Framework.Communications.Cache
}
}
// See IAssetReceiver
public void AssetNotFound(LLUUID assetID)
{
//if (this.RequestedTextures.ContainsKey(assetID))
//{
// MainLog.Instance.Warn("ASSET CACHE", "sending image not found for {0}", assetID);
// AssetRequest req = this.RequestedTextures[assetID];
// ImageNotInDatabasePacket notFound = new ImageNotInDatabasePacket();
// notFound.ImageID.ID = assetID;
// req.RequestUser.OutPacket(notFound);
// this.RequestedTextures.Remove(assetID);
//}
//else
//{
// MainLog.Instance.Error("ASSET CACHE", "Cound not send image not found for {0}", assetID);
//}
//m_log.ErrorFormat("[ASSET CACHE]: AssetNotFound for {0}", assetID);
// The 'image not found' packet needs to happen, but RequestedTextures is not actually used (should be cleaned up)
// It might also be better to do this in the TextureDownloadModule
/*
*
AssetRequest req;
if (RequestedTextures.TryGetValue(assetID, out req))
{
m_log.WarnFormat("[ASSET CACHE]: sending 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)
{
const uint m_maxPacketSize = 600;
@ -485,10 +651,8 @@ namespace OpenSim.Framework.Communications.Cache
return numPackets;
}
#region Assets
/// <summary>
///
/// Make an asset request the result of which will be packeted up and sent directly back to the client.
/// </summary>
/// <param name="userInfo"></param>
/// <param name="transferRequest"></param>
@ -543,7 +707,7 @@ namespace OpenSim.Framework.Communications.Cache
}
/// <summary>
///
/// Process the asset queue which sends packets directly back to the client.
/// </summary>
private void ProcessAssetQueue()
{
@ -597,7 +761,7 @@ namespace OpenSim.Framework.Communications.Cache
{
int processedLength = 0;
// libsecondlife hardcodes 1500 as the maximum data chunk size
int maxChunkSize = 1500;
int maxChunkSize = 1250;
int packetNumber = 0;
while (processedLength < req.AssetInf.Data.Length)
@ -638,8 +802,6 @@ namespace OpenSim.Framework.Communications.Cache
}
}
#endregion
public class AssetRequest
{
public IClientAPI RequestUser;
@ -698,7 +860,6 @@ namespace OpenSim.Framework.Communications.Cache
}
}
public class AssetRequestsList
{
public LLUUID AssetID;

View File

@ -35,6 +35,8 @@ namespace OpenSim.Framework.Communications.Cache
{
public class LocalAssetServer : AssetServerBase
{
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private IObjectContainer db;
public LocalAssetServer()
@ -43,7 +45,7 @@ namespace OpenSim.Framework.Communications.Cache
yapfile = File.Exists(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)
{
@ -67,7 +69,7 @@ namespace OpenSim.Framework.Communications.Cache
if (db != null)
{
MainLog.Instance.Verbose("ASSETSERVER", "Closing local asset server database");
m_log.Info("[ASSETSERVER]: Closing local asset server database");
db.Close();
}
}
@ -193,7 +195,7 @@ namespace OpenSim.Framework.Communications.Cache
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();
}

View File

@ -37,6 +37,9 @@ namespace OpenSim.Framework.Communications.Cache
{
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 BlockingQueue<AssetRequest> m_assetRequests;
protected Thread m_localAssetServerThread;
@ -70,15 +73,13 @@ namespace OpenSim.Framework.Communications.Cache
if (asset != null)
{
MainLog.Instance.Verbose(
"ASSET", "Asset {0} received from asset server", req.AssetID);
//m_log.InfoFormat("[ASSETSERVER]: Asset {0} received from asset server", req.AssetID);
m_receiver.AssetReceived(asset, req.IsTexture);
}
else
{
MainLog.Instance.Error(
"ASSET", "Asset {0} not found by asset server", req.AssetID);
m_log.ErrorFormat("[ASSET SERVER]: Asset {0} not found by asset server", req.AssetID);
m_receiver.AssetNotFound(req.AssetID);
}
@ -86,22 +87,23 @@ namespace OpenSim.Framework.Communications.Cache
public virtual void LoadDefaultAssets()
{
MainLog.Instance.Verbose("ASSETSERVER", "Setting up asset database");
m_log.Info("[ASSET SERVER]: Setting up asset database");
assetLoader.ForEachDefaultXmlAsset(StoreAsset);
CommitAssets();
}
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_localAssetServerThread = new Thread(RunRequests);
m_localAssetServerThread.Name = "LocalAssetServerThread";
m_localAssetServerThread.IsBackground = true;
m_localAssetServerThread.Start();
OpenSim.Framework.ThreadTracker.Add(m_localAssetServerThread);
}
private void RunRequests()
@ -116,11 +118,15 @@ namespace OpenSim.Framework.Communications.Cache
}
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)
{
m_receiver = receiver;
@ -133,7 +139,9 @@ namespace OpenSim.Framework.Communications.Cache
req.IsTexture = isTexture;
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)

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
{
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private string _assetServerUrl;
public GridAssetClient(string serverUrl)
@ -50,7 +52,9 @@ namespace OpenSim.Framework.Communications.Cache
Stream s = null;
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);
rc.AddResourcePath("assets");
@ -70,9 +74,9 @@ namespace OpenSim.Framework.Communications.Cache
}
catch (Exception e)
{
MainLog.Instance.Error("ASSETCACHE", e.Message);
MainLog.Instance.Debug("ASSETCACHE", "Getting asset {0}", req.AssetID.ToString());
MainLog.Instance.Error("ASSETCACHE", e.StackTrace);
m_log.Error("[GRID ASSET CLIENT]: " + e.Message);
m_log.DebugFormat("[GRID ASSET CLIENT]: Getting asset {0}", req.AssetID.ToString());
m_log.Error("[GRID ASSET CLIENT]: " + e.StackTrace);
}
return null;
@ -93,17 +97,19 @@ namespace OpenSim.Framework.Communications.Cache
// XmlSerializer xs = new XmlSerializer(typeof(AssetBase));
// xs.Serialize(s, asset);
// RestClient rc = new RestClient(_assetServerUrl);
MainLog.Instance.Verbose("ASSET", "Storing asset");
m_log.Info("[GRID ASSET CLIENT]: Storing asset");
//rc.AddResourcePath("assets");
// rc.RequestMethod = "POST";
// rc.Request(s);
//MainLog.Instance.Verbose("ASSET", "Stored {0}", rc);
MainLog.Instance.Verbose("ASSET", "Sending to " + _assetServerUrl + "/assets/");
//m_log.InfoFormat("[ASSET]: Stored {0}", rc);
m_log.Info("[GRID ASSET CLIENT]: Sending to " + _assetServerUrl + "/assets/");
RestObjectPoster.BeginPostObject<AssetBase>(_assetServerUrl + "/assets/", asset);
}
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
* 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
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
@ -26,12 +26,12 @@
*
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using libsecondlife;
using Nini.Config;
using OpenSim.Framework.Console;
namespace OpenSim.Framework.Communications.Cache
@ -42,6 +42,8 @@ namespace OpenSim.Framework.Communications.Cache
/// </summary>
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");
/// <summary>
@ -53,7 +55,7 @@ namespace OpenSim.Framework.Communications.Cache
public LibraryRootFolder()
{
MainLog.Instance.Verbose("LIBRARYINVENTORY", "Loading library inventory");
m_log.Info("[LIBRARY INVENTORY]: Loading library inventory");
agentID = libOwner;
folderID = new LLUUID("00000112-000f-0000-0000-000100bba000");
@ -138,8 +140,8 @@ namespace OpenSim.Framework.Communications.Cache
/// <param name="assets"></param>
protected void LoadLibraries(string librariesControlPath)
{
MainLog.Instance.Verbose(
"LIBRARYINVENTORY", "Loading libraries control file {0}", librariesControlPath);
m_log.InfoFormat(
"[LIBRARY INVENTORY]: Loading libraries control file {0}", librariesControlPath);
LoadFromFile(librariesControlPath, "Libraries control", ReadLibraryFromConfig);
}
@ -152,13 +154,13 @@ namespace OpenSim.Framework.Communications.Cache
{
string foldersPath
= Path.Combine(
Util.inventoryDir(), config.GetString("foldersFile", ""));
Util.inventoryDir(), config.GetString("foldersFile", System.String.Empty));
LoadFromFile(foldersPath, "Library folders", ReadFolderFromConfig);
string itemsPath
= Path.Combine(
Util.inventoryDir(), config.GetString("itemsFile", ""));
Util.inventoryDir(), config.GetString("itemsFile", System.String.Empty));
LoadFromFile(itemsPath, "Library items", ReadItemFromConfig);
}
@ -186,14 +188,12 @@ namespace OpenSim.Framework.Communications.Cache
libraryFolders.Add(folderInfo.folderID, folderInfo);
parentFolder.SubFolders.Add(folderInfo.folderID, folderInfo);
// MainLog.Instance.Verbose(
// "LIBRARYINVENTORY", "Adding folder {0} ({1})", folderInfo.name, folderInfo.folderID);
// m_log.InfoFormat("[LIBRARY INVENTORY]: Adding folder {0} ({1})", folderInfo.name, folderInfo.folderID);
}
else
{
MainLog.Instance.Warn(
"LIBRARYINVENTORY",
"Couldn't add folder {0} ({1}) since parent folder with ID {2} does not exist!",
m_log.WarnFormat(
"[LIBRARY INVENTORY]: Couldn't add folder {0} ({1}) since parent folder with ID {2} does not exist!",
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.assetID = new LLUUID(config.GetString("assetID", LLUUID.Random().ToString()));
item.parentFolderID = new LLUUID(config.GetString("folderID", folderID.ToString()));
item.inventoryDescription = config.GetString("description", "");
item.inventoryName = config.GetString("name", "");
item.inventoryDescription = config.GetString("description", System.String.Empty);
item.inventoryName = config.GetString("name", System.String.Empty);
item.assetType = config.GetInt("assetType", 0);
item.invType = config.GetInt("inventoryType", 0);
item.inventoryCurrentPermissions = (uint)config.GetLong("currentPermissions", 0x7FFFFFFF);
@ -227,9 +227,8 @@ namespace OpenSim.Framework.Communications.Cache
}
else
{
MainLog.Instance.Warn(
"LIBRARYINVENTORY",
"Couldn't add item {0} ({1}) since parent folder with ID {2} does not exist!",
m_log.WarnFormat(
"[LIBRARY INVENTORY]: Couldn't add item {0} ({1}) since parent folder with ID {2} does not exist!",
item.inventoryName, item.inventoryID, item.parentFolderID);
}
}
@ -257,14 +256,12 @@ namespace OpenSim.Framework.Communications.Cache
}
catch (XmlException e)
{
MainLog.Instance.Error(
"LIBRARYINVENTORY", "Error loading {0} : {1}", path, e);
m_log.ErrorFormat("[LIBRARY INVENTORY]: Error loading {0} : {1}", path, e);
}
}
else
{
MainLog.Instance.Error(
"LIBRARYINVENTORY", "{0} file {1} does not exist!", fileDescription, path);
m_log.ErrorFormat("[LIBRARY INVENTORY]: {0} file {1} does not exist!", fileDescription, path);
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -13,7 +13,7 @@
* 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
* 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
@ -33,11 +33,11 @@ namespace OpenSim.Region.Capabilities
[LLSDMap]
public class LLSDAssetUploadRequest
{
public string asset_type = "";
public string description = "";
public string asset_type = System.String.Empty;
public string description = System.String.Empty;
public LLUUID folder_id = LLUUID.Zero;
public string inventory_type = "";
public string name = "";
public string inventory_type = System.String.Empty;
public string name = System.String.Empty;
public LLSDAssetUploadRequest()
{

View File

@ -13,7 +13,7 @@
* 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
* 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
@ -31,8 +31,8 @@ namespace OpenSim.Region.Capabilities
[LLSDMap]
public class LLSDAssetUploadResponse
{
public string uploader = "";
public string state = "";
public string uploader = System.String.Empty;
public string state = System.String.Empty;
public LLSDAssetUploadResponse()
{

View File

@ -13,7 +13,7 @@
* 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
* 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
@ -26,20 +26,22 @@
*
*/
using System;
namespace OpenSim.Region.Capabilities
{
[LLSDType("MAP")]
public class LLSDCapsDetails
{
public string MapLayer = "";
public string NewFileAgentInventory = "";
//public string EventQueueGet = "";
// public string RequestTextureDownload = "";
// public string ChatSessionRequest = "";
public string UpdateNotecardAgentInventory = "";
public string UpdateScriptAgentInventory = "";
public string UpdateScriptTaskInventory = "";
// public string ParcelVoiceInfoRequest = "";
public string MapLayer = String.Empty;
public string NewFileAgentInventory = String.Empty;
//public string EventQueueGet = String.Empty;
// public string RequestTextureDownload = String.Empty;
// public string ChatSessionRequest = String.Empty;
public string UpdateNotecardAgentInventory = String.Empty;
public string UpdateScriptAgentInventory = String.Empty;
public string UpdateScriptTaskInventory = String.Empty;
// public string ParcelVoiceInfoRequest = String.Empty;
public LLSDCapsDetails()
{

View File

@ -13,7 +13,7 @@
* 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
* 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

View File

@ -13,7 +13,7 @@
* 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
* 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

View File

@ -13,7 +13,7 @@
* 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
* 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

View File

@ -13,7 +13,7 @@
* 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
* 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

View File

@ -13,7 +13,7 @@
* 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
* 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

View File

@ -36,6 +36,8 @@ namespace OpenSim.Framework.Communications
{
public class CommunicationsManager
{
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
protected IUserService m_userService;
public IUserService UserService
@ -71,12 +73,12 @@ namespace OpenSim.Framework.Communications
get { return m_userProfileCacheService; }
}
protected AssetTransactionManager m_transactionsManager;
// protected AgentAssetTransactionsManager m_transactionsManager;
public AssetTransactionManager TransactionsManager
{
get { return m_transactionsManager; }
}
// public AgentAssetTransactionsManager TransactionsManager
// {
// get { return m_transactionsManager; }
// }
protected AssetCache m_assetCache;
@ -98,7 +100,7 @@ namespace OpenSim.Framework.Communications
m_networkServersInfo = serversInfo;
m_assetCache = assetCache;
m_userProfileCacheService = new UserProfileCacheService(this);
m_transactionsManager = new AssetTransactionManager(this, dumpAssetsToFile);
// m_transactionsManager = new AgentAssetTransactionsManager(this, dumpAssetsToFile);
}
public void doCreate(string[] cmmdParams)
@ -114,11 +116,11 @@ namespace OpenSim.Framework.Communications
if (cmmdParams.Length < 2)
{
firstName = MainLog.Instance.CmdPrompt("First name", "Default");
lastName = MainLog.Instance.CmdPrompt("Last name", "User");
password = MainLog.Instance.PasswdPrompt("Password");
regX = Convert.ToUInt32(MainLog.Instance.CmdPrompt("Start Region X", "1000"));
regY = Convert.ToUInt32(MainLog.Instance.CmdPrompt("Start Region Y", "1000"));
firstName = MainConsole.Instance.CmdPrompt("First name", "Default");
lastName = MainConsole.Instance.CmdPrompt("Last name", "User");
password = MainConsole.Instance.PasswdPrompt("Password");
regX = Convert.ToUInt32(MainConsole.Instance.CmdPrompt("Start Region X", "1000"));
regY = Convert.ToUInt32(MainConsole.Instance.CmdPrompt("Start Region Y", "1000"));
}
else
{
@ -129,14 +131,30 @@ namespace OpenSim.Framework.Communications
regY = Convert.ToUInt32(cmmdParams[5]);
}
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;
}
}
/// <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)
{
string md5PasswdHash = Util.Md5Hash(Util.Md5Hash(password) + ":" + "");
string md5PasswdHash = Util.Md5Hash(Util.Md5Hash(password) + ":" + String.Empty);
m_userService.AddUserProfile(firstName, lastName, md5PasswdHash, regX, regY);
UserProfileData userProf = UserService.GetUserProfile(firstName, lastName, "");
@ -147,7 +165,7 @@ namespace OpenSim.Framework.Communications
else
{
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;
}
}
@ -163,6 +181,20 @@ namespace OpenSim.Framework.Communications
{
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>
/// Delete friend on friendlistowner's friendlist.

View File

@ -32,6 +32,8 @@ namespace OpenSim.Framework.Communications
public interface IInterRegionCommunications
{
string rdebugRegionName { get; set; }
bool Available { get; }
void CheckRegion(string address, uint port);
bool InformRegionOfChildAgent(ulong regionHandle, AgentCircuitData agentData);
bool InformRegionOfPrimCrossing(ulong regionHandle, LLUUID primID, string objData);
bool RegionUp(SearializableRegionInfo region, ulong regionhandle);
@ -43,6 +45,6 @@ namespace OpenSim.Framework.Communications
bool AcknowledgeAgentCrossed(ulong regionHandle, LLUUID agentId);
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
* 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
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* 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);
/// <summary>
/// Defines all the operations one can perform on a user's inventory.
/// </summary>
public interface IInventoryServices
{
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 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);
/// <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);
/// <summary>
/// Create a new inventory for the given user
/// </summary>
/// <param name="user"></param>
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>
/// Returns the root folder plus any folders in root (so down one level in the Inventory folders tree)
/// for the given user.
/// </summary>
/// <param name="userID"></param>
/// <returns></returns>
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
* 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
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
@ -36,13 +36,12 @@ namespace OpenSim.Framework.Communications
{
public abstract class InventoryServiceBase : IInventoryServices
{
protected Dictionary<string, IInventoryData> m_plugins = new Dictionary<string, IInventoryData>();
//protected IAssetServer m_assetServer;
private static readonly log4net.ILog m_log
= log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public InventoryServiceBase()
{
//m_assetServer = assetServer;
}
protected Dictionary<string, IInventoryData> m_plugins = new Dictionary<string, IInventoryData>();
#region Plugin methods
/// <summary>
/// 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))
{
MainLog.Instance.Verbose("AGENTINVENTORY", "Inventorystorage: Attempting to load " + FileName);
m_log.Info("[AGENTINVENTORY]: Inventorystorage: Attempting to load " + FileName);
Assembly pluginAssembly = Assembly.LoadFrom(FileName);
foreach (Type pluginType in pluginAssembly.GetTypes())
@ -67,24 +66,25 @@ namespace OpenSim.Framework.Communications
(IInventoryData) Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString()));
plug.Initialise();
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)
{
LLUUID userID = new LLUUID(rawUserID);
return RequestFirstLevelFolders(userID);
}
/// <summary>
/// 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>
// See IInventoryServices
public List<InventoryFolderBase> RequestFirstLevelFolders(LLUUID userID)
{
List<InventoryFolderBase> inventoryList = new List<InventoryFolderBase>();
@ -95,9 +95,8 @@ namespace OpenSim.Framework.Communications
rootFolder = plugin.Value.getUserRootFolder(userID);
if (rootFolder != null)
{
MainLog.Instance.Verbose(
"INVENTORY",
"Found root folder for user with ID " + userID + ". Retrieving inventory contents.");
m_log.Info(
"[INVENTORY]: Found root folder for user with ID " + userID + ". Retrieving inventory contents.");
inventoryList = plugin.Value.getInventoryFolders(rootFolder.folderID);
inventoryList.Insert(0, rootFolder);
@ -105,17 +104,13 @@ namespace OpenSim.Framework.Communications
}
}
MainLog.Instance.Warn(
"INVENTORY", "Could not find a root folder belonging to user with ID " + userID);
m_log.Warn(
"[INVENTORY]: Could not find a root folder belonging to user with ID " + userID);
return inventoryList;
}
/// <summary>
/// Get the root folder for a user
/// </summary>
/// <param name="userID"></param>
/// <returns>null if no root folder was found</returns>
// See IInventoryServices
public InventoryFolderBase RequestUsersRoot(LLUUID userID)
{
foreach (KeyValuePair<string, IInventoryData> plugin in m_plugins)
@ -125,9 +120,7 @@ namespace OpenSim.Framework.Communications
return null;
}
/// <summary>
///
/// </summary>
// See IInventoryServices
public void MoveInventoryFolder(LLUUID userID, InventoryFolderBase folder)
{
foreach (KeyValuePair<string, IInventoryData> plugin in m_plugins)
@ -136,11 +129,53 @@ namespace OpenSim.Framework.Communications
}
}
/// <summary>
///
/// </summary>
/// <param name="parentFolderID"></param>
/// <returns></returns>
public virtual bool HasInventoryForUser(LLUUID userID)
{
return false;
}
// 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)
{
List<InventoryFolderBase> inventoryList = new List<InventoryFolderBase>();
@ -162,7 +197,9 @@ namespace OpenSim.Framework.Communications
return itemsList;
}
public void AddFolder(InventoryFolderBase folder)
#endregion
protected void AddFolder(InventoryFolderBase folder)
{
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)
{
@ -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)
{
@ -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)
{
@ -194,11 +231,7 @@ namespace OpenSim.Framework.Communications
}
}
/// <summary>
///
/// </summary>
/// <param name="inventory"></param>
public void AddNewInventorySet(UsersInventory inventory)
private void AddNewInventorySet(UsersInventory inventory)
{
foreach (InventoryFolderBase folder in inventory.Folders.Values)
{
@ -206,41 +239,15 @@ namespace OpenSim.Framework.Communications
}
}
/// <summary>
/// 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
private class UsersInventory
{
public Dictionary<LLUUID, InventoryFolderBase> Folders = new Dictionary<LLUUID, InventoryFolderBase>();
public Dictionary<LLUUID, InventoryItemBase> Items = new Dictionary<LLUUID, InventoryItemBase>();
public UsersInventory()
{
}
public virtual void CreateNewInventorySet(LLUUID user)
{
InventoryFolderBase folder = new InventoryFolderBase();
folder.parentID = LLUUID.Zero;
folder.agentID = user;
folder.folderID = LLUUID.Random();
@ -378,13 +385,5 @@ namespace OpenSim.Framework.Communications
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
* 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
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
@ -42,6 +42,8 @@ namespace OpenSim.Framework.UserManagement
/// </summary>
public class LoginResponse
{
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private Hashtable loginFlagsHash;
private Hashtable globalTexturesHash;
private Hashtable loginError;
@ -130,7 +132,7 @@ namespace OpenSim.Framework.UserManagement
defaultXmlRpcResponse = new XmlRpcResponse();
SetDefaultValues();
} // LoginServer
}
public void SetDefaultValues()
{
@ -152,8 +154,8 @@ namespace OpenSim.Framework.UserManagement
ErrorMessage = "You have entered an invalid name/password combination. Check Caps/lock.";
ErrorReason = "key";
welcomeMessage = "Welcome to OpenSim!";
seedCapability = "";
home = "{'region_handle':[r" + (1000*256).ToString() + ",r" + (1000*256).ToString() + "], 'position':[r" +
seedCapability = String.Empty;
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.Z.ToString() + "], 'look_at':[r" + userProfile.homelookat.X.ToString() + ",r" +
userProfile.homelookat.Y.ToString() + ",r" + userProfile.homelookat.Z.ToString() + "]}";
@ -183,7 +185,7 @@ namespace OpenSim.Framework.UserManagement
InitialOutfitHash["folder_name"] = "Nightclub Female";
InitialOutfitHash["gender"] = "female";
initialOutfit.Add(InitialOutfitHash);
} // SetDefaultValues
}
#region Login Failure Methods
@ -201,7 +203,7 @@ namespace OpenSim.Framework.UserManagement
loginError["login"] = login;
xmlRpcResponse.Value = loginError;
return (xmlRpcResponse);
} // GenerateResponse
}
public LLSD GenerateFailureResponseLLSD(string reason, string message, string login)
{
@ -221,7 +223,7 @@ namespace OpenSim.Framework.UserManagement
public XmlRpcResponse CreateFailedResponse()
{
return (CreateLoginFailedResponse());
} // CreateErrorConnectingToGridResponse()
}
public LLSD CreateFailedResponseLLSD()
{
@ -234,7 +236,7 @@ namespace OpenSim.Framework.UserManagement
(GenerateFailureResponse("key",
"Could not authenticate your avatar. Please check your username and password, and check the grid if problems persist.",
"false"));
} // LoginFailedResponse
}
public LLSD CreateLoginFailedResponseLLSD()
{
@ -250,7 +252,7 @@ namespace OpenSim.Framework.UserManagement
(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",
"false"));
} // CreateAlreadyLoggedInResponse()
}
public LLSD CreateAlreadyLoggedInResponseLLSD()
{
@ -350,8 +352,8 @@ namespace OpenSim.Framework.UserManagement
responseData["home"] = home;
responseData["look_at"] = lookAt;
responseData["message"] = welcomeMessage;
responseData["region_x"] = (Int32) RegionX*256;
responseData["region_y"] = (Int32) RegionY*256;
responseData["region_x"] = (Int32)(RegionX * Constants.RegionSize);
responseData["region_y"] = (Int32)(RegionY * Constants.RegionSize);
responseData["version"] = clientVersion; //rex
@ -369,13 +371,11 @@ namespace OpenSim.Framework.UserManagement
}
catch (Exception e)
{
MainLog.Instance.Warn(
"CLIENT",
"LoginResponse: Error creating XML-RPC Response: " + e.Message
);
m_log.Warn("[CLIENT]: LoginResponse: Error creating XML-RPC Response: " + e.Message);
return (GenerateFailureResponse("Internal Error", "Error generating Login Response", "false"));
}
} // ToXmlRpcResponse
}
public LLSD ToLLSDResponse()
{
@ -454,8 +454,8 @@ namespace OpenSim.Framework.UserManagement
map["home"] = LLSD.FromString(home);
map["look_at"] = LLSD.FromString(lookAt);
map["message"] = LLSD.FromString(welcomeMessage);
map["region_x"] = LLSD.FromInteger(RegionX * 256);
map["region_y"] = LLSD.FromInteger(RegionY * 256);
map["region_x"] = LLSD.FromInteger(RegionX * Constants.RegionSize);
map["region_y"] = LLSD.FromInteger(RegionY * Constants.RegionSize);
map["version"] = LLSD.FromString(clientVersion); //rex
@ -470,10 +470,8 @@ namespace OpenSim.Framework.UserManagement
}
catch (Exception e)
{
MainLog.Instance.Warn(
"CLIENT",
"LoginResponse: Error creating XML-RPC Response: " + e.Message
);
m_log.Warn("[CLIENT]: LoginResponse: Error creating XML-RPC Response: " + e.Message);
return GenerateFailureResponseLLSD("Internal Error", "Error generating Login Response", "false");
}
}
@ -489,12 +487,12 @@ namespace OpenSim.Framework.UserManagement
{
// this.eventCategoriesHash[category] = value;
//TODO
} // SetEventCategories
}
public void AddToUIConfig(string itemName, string item)
{
uiConfigHash[itemName] = item;
} // SetUIConfig
}
public void AddClassifiedCategory(Int32 ID, string categoryName)
{
@ -503,7 +501,7 @@ namespace OpenSim.Framework.UserManagement
hash["category_id"] = ID;
classifiedCategories.Add(hash);
// this.classifiedCategoriesHash.Clear();
} // SetClassifiedCategory
}
#region Properties
@ -511,109 +509,109 @@ namespace OpenSim.Framework.UserManagement
{
get { return login; }
set { login = value; }
} // Login
}
public string DST
{
get { return dst; }
set { dst = value; }
} // DST
}
public string StipendSinceLogin
{
get { return stipendSinceLogin; }
set { stipendSinceLogin = value; }
} // StipendSinceLogin
}
public string Gendered
{
get { return gendered; }
set { gendered = value; }
} // Gendered
}
public string EverLoggedIn
{
get { return everLoggedIn; }
set { everLoggedIn = value; }
} // EverLoggedIn
}
public uint SimPort
{
get { return simPort; }
set { simPort = value; }
} // SimPort
}
public string SimAddress
{
get { return simAddress; }
set { simAddress = value; }
} // SimAddress
}
public LLUUID AgentID
{
get { return agentID; }
set { agentID = value; }
} // AgentID
}
public LLUUID SessionID
{
get { return sessionID; }
set { sessionID = value; }
} // SessionID
}
public LLUUID SecureSessionID
{
get { return secureSessionID; }
set { secureSessionID = value; }
} // SecureSessionID
}
public Int32 CircuitCode
{
get { return circuitCode; }
set { circuitCode = value; }
} // CircuitCode
}
public uint RegionX
{
get { return regionX; }
set { regionX = value; }
} // RegionX
}
public uint RegionY
{
get { return regionY; }
set { regionY = value; }
} // RegionY
}
public string SunTexture
{
get { return sunTexture; }
set { sunTexture = value; }
} // SunTexture
}
public string CloudTexture
{
get { return cloudTexture; }
set { cloudTexture = value; }
} // CloudTexture
}
public string MoonTexture
{
get { return moonTexture; }
set { moonTexture = value; }
} // MoonTexture
}
public string Firstname
{
get { return firstname; }
set { firstname = value; }
} // Firstname
}
public string Lastname
{
get { return lastname; }
set { lastname = value; }
} // Lastname
}
public string ClientVersion
{
@ -631,7 +629,7 @@ namespace OpenSim.Framework.UserManagement
{
get { return startLocation; }
set { startLocation = value; }
} // StartLocation
}
public string LookAt
{
@ -643,19 +641,19 @@ namespace OpenSim.Framework.UserManagement
{
get { return seedCapability; }
set { seedCapability = value; }
} // SeedCapability
}
public string ErrorReason
{
get { return errorReason; }
set { errorReason = value; }
} // ErrorReason
}
public string ErrorMessage
{
get { return errorMessage; }
set { errorMessage = value; }
} // ErrorMessage
}
public ArrayList InventoryRoot
{

View File

@ -13,7 +13,7 @@
* 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
* 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
@ -29,6 +29,8 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using libsecondlife;
using libsecondlife.StructuredData;
@ -36,11 +38,14 @@ using Nwc.XmlRpc;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Console;
using OpenSim.Framework.Statistics;
namespace OpenSim.Framework.UserManagement
{
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 UserManagerBase m_userManager = null;
protected Mutex m_loginMutex = new Mutex(false);
@ -63,7 +68,7 @@ namespace OpenSim.Framework.UserManagement
if (m_rexMode)
m_rexLoginHandler = new RexLoginHandler(this, m_userManager);
if (welcomeMess != "")
if (welcomeMess != String.Empty)
{
m_welcomeMessage = welcomeMess;
}
@ -79,16 +84,14 @@ namespace OpenSim.Framework.UserManagement
// Temporary fix
m_loginMutex.WaitOne();
try
{
if (!m_rexMode)
{
//CFK: CustomizeResponse contains sufficient strings to alleviate the need for this.
//CKF: MainLog.Instance.Verbose("LOGIN", "Attempting login now...");
//CKF: m_log.Info("[LOGIN]: Attempting login now...");
XmlRpcResponse response = new XmlRpcResponse();
Hashtable requestData = (Hashtable) request.Params[0];
bool GoodXML = (requestData.Contains("first") && requestData.Contains("last") &&
requestData.Contains("passwd"));
(requestData.Contains("passwd") || requestData.Contains("web_login_key")));
bool GoodLogin = false;
UserProfileData userProfile;
@ -98,37 +101,51 @@ namespace OpenSim.Framework.UserManagement
{
string firstname = (string) requestData["first"];
string lastname = (string) requestData["last"];
string passwd = (string) requestData["passwd"];
userProfile = GetTheUser(firstname, lastname, "");
if( requestData.Contains("version"))
{
string clientversion = (string)requestData["version"];
m_log.Info("[LOGIN]: Client Version " + clientversion + " for " + firstname + " " + lastname);
}
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
{
return logResponse.CreateGridErrorResponse();
}
m_log.Info("[LOGIN]: Could not find a profile for " + firstname + " " + lastname);
if (!GoodLogin)
{
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
{
// If we already have a session...
if (userProfile.currentAgent != null && userProfile.currentAgent.agentOnline)
return logResponse.CreateFailedResponse();
}
}
else
{
userProfile.currentAgent = null;
m_userManager.CommitAgent(ref userProfile);
return logResponse.CreateGridErrorResponse();
}
// Reject the login
return logResponse.CreateAlreadyLoggedInResponse();
@ -204,9 +221,25 @@ namespace OpenSim.Framework.UserManagement
{
MainLog.Instance.Verbose("LOGIN", E.ToString());
}
//}
catch (Exception e)
{
m_log.Info("[LOGIN]: " + e.ToString());
return logResponse.CreateDeadRegionResponse();
//return logResponse.ToXmlRpcResponse();
}
return response;
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();
}
catch (Exception e)
{
m_log.Info("[LOGIN]: " + e.ToString());
}
//}
}
else
{
@ -241,9 +274,7 @@ namespace OpenSim.Framework.UserManagement
if (map.ContainsKey("first") && map.ContainsKey("last") && map.ContainsKey("passwd"))
{
string firstname = map["first"].AsString();
string lastname = map["last"].AsString();
string passwd = map["passwd"].AsString();
m_log.Info("[LOGIN]: Could not find a profile for " + firstname + " " + lastname);
//REX: Client version
if (map.ContainsKey("version"))
@ -347,7 +378,7 @@ namespace OpenSim.Framework.UserManagement
}
catch (Exception ex)
{
MainLog.Instance.Verbose("LOGIN", ex.ToString());
m_log.Info("[LOGIN]: " + ex.ToString());
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>
/// Remove agent
@ -398,10 +433,8 @@ namespace OpenSim.Framework.UserManagement
if (user != null)
{
ClearUserAgent(ref user, user.authenticationAddr);
MainLog.Instance.Verbose("REMOVE AGENT", "Success. Agent removed from database. UUID = " + user.UUID);
return logResponse.GenerateAgentRemoveSuccessResponse();
m_log.Info("[LOGIN]: " + ex.ToString());
return logResponse.CreateFailedResponseLLSD();
}
}
@ -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>
/// Saves a target agent to the database
/// </summary>
@ -466,14 +704,38 @@ namespace OpenSim.Framework.UserManagement
/// <returns>Authenticated?</returns>
public virtual bool AuthenticateUser(UserProfileData profile, string password)
{
MainLog.Instance.Verbose(
"LOGIN", "Authenticating {0} {1} ({2})", profile.username, profile.surname, profile.UUID);
bool passwordSuccess = false;
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$
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>

View File

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

View File

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

View File

@ -34,6 +34,7 @@ using libsecondlife;
using libsecondlife.StructuredData;
using Nwc.XmlRpc;
using OpenSim.Framework.Console;
using OpenSim.Framework.Statistics;
namespace OpenSim.Framework.UserManagement
{
@ -42,6 +43,8 @@ namespace OpenSim.Framework.UserManagement
/// </summary>
public abstract class UserManagerBase : IUserService
{
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public UserConfig _config;
private Dictionary<string, IUserData> _plugins = new Dictionary<string, IUserData>();
public bool RexMode = false; // _config is not initiated in local mode
@ -54,10 +57,10 @@ namespace OpenSim.Framework.UserManagement
{
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);
MainLog.Instance.Verbose("USERSTORAGE", "Found " + pluginAssembly.GetTypes().Length + " interfaces.");
m_log.Info("[USERSTORAGE]: Found " + pluginAssembly.GetTypes().Length + " interfaces.");
foreach (Type pluginType in pluginAssembly.GetTypes())
{
if (!pluginType.IsAbstract)
@ -79,16 +82,29 @@ namespace OpenSim.Framework.UserManagement
{
plug.Initialise();
_plugins.Add(plug.getName(), plug);
MainLog.Instance.Verbose("USERSTORAGE", "Added IUserData Interface");
m_log.Info("[USERSTORAGE]: Added IUserData Interface");
}
#region Get UserProfile
/// <summary>
/// Loads a user profile from a database by UUID
/// </summary>
/// <param name="uuid">The target UUID</param>
/// <returns>A user profile. Returns null if no user profile is found.</returns>
// see IUserService
public UserProfileData GetUserProfile(string fname, string lname)
{
foreach (KeyValuePair<string, IUserData> plugin in _plugins)
{
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)
{
if (!RexMode)
@ -180,8 +196,7 @@ namespace OpenSim.Framework.UserManagement
}
catch (Exception)
{
MainLog.Instance.Verbose("USERSTORAGE",
"Unable to generate AgentPickerData via " + plugin.Key + "(" + query + ")");
m_log.Info("[USERSTORAGE]: Unable to generate AgentPickerData via " + plugin.Key + "(" + query + ")");
return new List<AvatarPickerAvatar>();
}
}
@ -262,8 +277,7 @@ namespace OpenSim.Framework.UserManagement
}
catch (Exception e)
{
MainLog.Instance.Verbose("USERSTORAGE",
"Unable to set user via " + plugin.Key + "(" + e.ToString() + ")");
m_log.Info("[USERSTORAGE]: Unable to set user via " + plugin.Key + "(" + e.ToString() + ")");
}
}
@ -289,8 +303,7 @@ namespace OpenSim.Framework.UserManagement
}
catch (Exception e)
{
MainLog.Instance.Verbose("USERSTORAGE",
"Unable to find user via " + plugin.Key + "(" + e.ToString() + ")");
m_log.Info("[USERSTORAGE]: Unable to find user via " + plugin.Key + "(" + e.ToString() + ")");
}
}
@ -313,8 +326,7 @@ namespace OpenSim.Framework.UserManagement
}
catch (Exception e)
{
MainLog.Instance.Verbose("USERSTORAGE",
"Unable to GetUserFriendList via " + plugin.Key + "(" + e.ToString() + ")");
m_log.Info("[USERSTORAGE]: 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)
{
foreach (KeyValuePair<string, IUserData> plugin in _plugins)
@ -332,8 +360,7 @@ namespace OpenSim.Framework.UserManagement
}
catch (Exception e)
{
MainLog.Instance.Verbose("USERSTORAGE",
"Unable to AddNewUserFriend via " + plugin.Key + "(" + e.ToString() + ")");
m_log.Info("[USERSTORAGE]: Unable to AddNewUserFriend via " + plugin.Key + "(" + e.ToString() + ")");
}
}
@ -350,8 +377,7 @@ namespace OpenSim.Framework.UserManagement
}
catch (Exception e)
{
MainLog.Instance.Verbose("USERSTORAGE",
"Unable to RemoveUserFriend via " + plugin.Key + "(" + e.ToString() + ")");
m_log.Info("[USERSTORAGE]: Unable to RemoveUserFriend via " + plugin.Key + "(" + e.ToString() + ")");
}
}
}
@ -366,8 +392,7 @@ namespace OpenSim.Framework.UserManagement
}
catch (Exception e)
{
MainLog.Instance.Verbose("USERSTORAGE",
"Unable to UpdateUserFriendPerms via " + plugin.Key + "(" + e.ToString() + ")");
m_log.Info("[USERSTORAGE]: Unable to UpdateUserFriendPerms via " + plugin.Key + "(" + e.ToString() + ")");
}
}
}
@ -386,8 +411,7 @@ namespace OpenSim.Framework.UserManagement
}
catch (Exception e)
{
MainLog.Instance.Verbose("USERSTORAGE",
"Unable to find user via " + plugin.Key + "(" + e.ToString() + ")");
m_log.Info("[USERSTORAGE]: Unable to find user via " + plugin.Key + "(" + e.ToString() + ")");
}
}
@ -443,8 +467,7 @@ namespace OpenSim.Framework.UserManagement
}
catch (Exception e)
{
MainLog.Instance.Verbose("USERSTORAGE",
"Unable to find user via " + plugin.Key + "(" + e.ToString() + ")");
m_log.Info("[USERSTORAGE]: Unable to find user via " + plugin.Key + "(" + e.ToString() + ")");
}
}
@ -519,6 +542,63 @@ namespace OpenSim.Framework.UserManagement
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)
{
UserAgentData agent = new UserAgentData();
@ -579,7 +659,7 @@ namespace OpenSim.Framework.UserManagement
user.username = firstName;
user.surname = lastName;
user.passwordHash = pass;
user.passwordSalt = "";
user.passwordSalt = String.Empty;
user.created = Util.UnixTimeSinceEpoch();
user.homeLookAt = new LLVector3(100, 100, 100);
user.homeRegionX = regX;
@ -594,8 +674,7 @@ namespace OpenSim.Framework.UserManagement
}
catch (Exception e)
{
MainLog.Instance.Verbose("USERSTORAGE",
"Unable to add user via " + plugin.Key + "(" + e.ToString() + ")");
m_log.Info("[USERSTORAGE]: 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
* 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
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
@ -35,11 +35,13 @@ namespace OpenSim.Framework.Configuration.HTTP
{
public class HTTPConfiguration : IGenericConfig
{
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private RemoteConfigSettings remoteConfigSettings;
private XmlConfiguration xmlConfig;
private string configFileName = "";
private string configFileName = System.String.Empty;
public HTTPConfiguration()
{
@ -81,7 +83,7 @@ namespace OpenSim.Framework.Configuration.HTTP
}
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 +
"). Creating local file instead.");
xmlConfig.SetFileName(configFileName);

View File

@ -13,7 +13,7 @@
* 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
* 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
@ -32,7 +32,7 @@ namespace OpenSim.Framework.Configuration.HTTP
{
private ConfigurationMember configMember;
public string baseConfigURL = "";
public string baseConfigURL = System.String.Empty;
public RemoteConfigSettings(string filename)
{

View File

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

View File

@ -13,7 +13,7 @@
* 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
* 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
@ -39,13 +39,15 @@ namespace OpenSim.Framework
{
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 void ConfigurationOptionsLoad();
private List<ConfigurationOption> configurationOptions = new List<ConfigurationOption>();
private string configurationFilename = "";
private string configurationDescription = "";
private string configurationFilename = String.Empty;
private string configurationDescription = String.Empty;
private XmlNode configurationFromXMLNode = null;
private ConfigurationOptionsLoad loadFunction;
private ConfigurationOptionResult resultFunction;
@ -70,7 +72,7 @@ namespace OpenSim.Framework
public ConfigurationMember(XmlNode configuration_xml, string configuration_description,
ConfigurationOptionsLoad load_function, ConfigurationOptionResult result_function, bool use_console_to_prompt_on_error)
{
configurationFilename = "";
configurationFilename = String.Empty;
configurationFromXMLNode = configuration_xml;
configurationDescription = configuration_description;
loadFunction = load_function;
@ -100,8 +102,8 @@ namespace OpenSim.Framework
private void checkAndAddConfigOption(ConfigurationOption option)
{
if ((option.configurationKey != "" && option.configurationQuestion != "") ||
(option.configurationKey != "" && option.configurationUseDefaultNoPrompt))
if ((option.configurationKey != String.Empty && option.configurationQuestion != String.Empty) ||
(option.configurationKey != String.Empty && option.configurationUseDefaultNoPrompt))
{
if (!configurationOptions.Contains(option))
{
@ -110,7 +112,7 @@ namespace OpenSim.Framework
}
else
{
MainLog.Instance.Notice(
m_log.Info(
"Required fields for adding a configuration option is invalid. Will not add this option (" +
option.configurationKey + ")");
}
@ -147,38 +149,36 @@ namespace OpenSim.Framework
checkAndAddConfigOption(configOption);
}
// TEMP - REMOVE
private int cE = 0;
public void performConfigurationRetrieve()
{
if (cE > 1)
MainLog.Instance.Error("READING CONFIGURATION COUT: " + cE.ToString());
m_log.Error("READING CONFIGURATION COUT: " + cE.ToString());
configurationPlugin = LoadConfigDll(configurationPluginFilename);
configurationOptions.Clear();
if (loadFunction == null)
{
MainLog.Instance.Error("Load Function for '" + configurationDescription +
m_log.Error("Load Function for '" + configurationDescription +
"' is null. Refusing to run configuration.");
return;
}
if (resultFunction == null)
{
MainLog.Instance.Error("Result Function for '" + configurationDescription +
m_log.Error("Result Function for '" + configurationDescription +
"' is null. Refusing to run configuration.");
return;
}
MainLog.Instance.Verbose("CONFIG", "Calling Configuration Load Function...");
m_log.Info("[CONFIG]: Calling Configuration Load Function...");
loadFunction();
if (configurationOptions.Count <= 0)
{
MainLog.Instance.Error("CONFIG",
"No configuration options were specified for '" + configurationOptions +
m_log.Error("[CONFIG]: No configuration options were specified for '" + configurationOptions +
"'. Refusing to continue configuration.");
return;
}
@ -186,11 +186,11 @@ namespace OpenSim.Framework
bool useFile = true;
if (configurationPlugin == null)
{
MainLog.Instance.Error("CONFIG", "Configuration Plugin NOT LOADED!");
m_log.Error("[CONFIG]: Configuration Plugin NOT LOADED!");
return;
}
if (configurationFilename.Trim() != "")
if (configurationFilename.Trim() != String.Empty)
{
configurationPlugin.SetFileName(configurationFilename);
try
@ -200,7 +200,7 @@ namespace OpenSim.Framework
}
catch (XmlException e)
{
MainLog.Instance.Error("Error loading " + configurationFilename + ": " + e.ToString());
m_log.Error("Error loading " + configurationFilename + ": " + e.ToString());
useFile = false;
}
}
@ -208,11 +208,11 @@ namespace OpenSim.Framework
{
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);
}
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;
}
@ -220,11 +220,11 @@ namespace OpenSim.Framework
{
bool convertSuccess = false;
object return_result = null;
string errorMessage = "";
string errorMessage = String.Empty;
bool ignoreNextFromConfig = false;
while (convertSuccess == false)
{
string console_result = "";
string console_result = String.Empty;
string attribute = null;
if (useFile || configurationFromXMLNode != null)
{
@ -250,17 +250,17 @@ namespace OpenSim.Framework
configOption.shouldIBeAsked(configOption.configurationKey)) ||
configOption.shouldIBeAsked == null)
{
if (configurationDescription.Trim() != "")
if (configurationDescription.Trim() != String.Empty)
{
console_result =
MainLog.Instance.CmdPrompt(
MainConsole.Instance.CmdPrompt(
configurationDescription + ": " + configOption.configurationQuestion,
configOption.configurationDefault);
}
else
{
console_result =
MainLog.Instance.CmdPrompt(configOption.configurationQuestion,
MainConsole.Instance.CmdPrompt(configOption.configurationQuestion,
configOption.configurationDefault);
}
}
@ -431,7 +431,7 @@ namespace OpenSim.Framework
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.");
convertSuccess = false;
ignoreNextFromConfig = true;
@ -441,18 +441,16 @@ namespace OpenSim.Framework
{
if (configOption.configurationUseDefaultNoPrompt)
{
MainLog.Instance.Error("CONFIG",
string.Format(
"[{3}]:[{1}] is not valid default for parameter [{0}].\nThe configuration result must be parsable to {2}.\n",
m_log.Error(string.Format(
"[CONFIG]: [{3}]:[{1}] is not valid default for parameter [{0}].\nThe configuration result must be parsable to {2}.\n",
configOption.configurationKey, console_result, errorMessage,
configurationFilename));
convertSuccess = true;
}
else
{
MainLog.Instance.Warn("CONFIG",
string.Format(
"[{3}]:[{1}] is not a valid value [{0}].\nThe configuration result must be parsable to {2}.\n",
m_log.Warn(string.Format(
"[CONFIG]: [{3}]:[{1}] is not a valid value [{0}].\nThe configuration result must be parsable to {2}.\n",
configOption.configurationKey, console_result, errorMessage,
configurationFilename));
ignoreNextFromConfig = true;

View File

@ -13,7 +13,7 @@
* 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
* 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
@ -26,6 +26,8 @@
*
*/
using System;
namespace OpenSim.Framework
{
public class ConfigurationOption
@ -52,9 +54,9 @@ namespace OpenSim.Framework
TYPE_DOUBLE
} ;
public string configurationKey = "";
public string configurationQuestion = "";
public string configurationDefault = "";
public string configurationKey = String.Empty;
public string configurationQuestion = String.Empty;
public string configurationDefault = String.Empty;
public ConfigurationTypes configurationType = ConfigurationTypes.TYPE_STRING;
public bool configurationUseDefaultNoPrompt = false;

View File

@ -33,49 +33,28 @@ using System.Net;
namespace OpenSim.Framework.Console
{
public enum LogPriority : int
public class ConsoleBase
{
CRITICAL,
HIGH,
MEDIUM,
NORMAL,
LOW,
VERBOSE,
EXTRAVERBOSE
}
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public class LogBase
private readonly object m_syncRoot = new object();
public conscmd_callback m_cmdParser;
public string m_componentName;
public ConsoleBase(string componentname, conscmd_callback cmdparser)
{
private object m_syncRoot = new object();
m_componentName = componentname;
m_cmdParser = cmdparser;
private StreamWriter Log;
public conscmd_callback cmdparser;
public string componentname;
private bool m_verbose;
public LogBase(string LogFile, string componentname, conscmd_callback cmdparser, bool verbose)
{
this.componentname = componentname;
this.cmdparser = cmdparser;
m_verbose = verbose;
System.Console.WriteLine("Creating new local console");
if (String.IsNullOrEmpty(LogFile))
{
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());
m_log.Info("[" + m_componentName + "]: Started at " + DateTime.Now.ToString());
}
public void Close()
{
Log.WriteLine("Shutdown at " + DateTime.Now.ToString());
Log.Close();
m_log.Info("[" + m_componentName + "]: Shutdown at " + DateTime.Now.ToString());
}
/// <summary>
@ -92,18 +71,17 @@ namespace OpenSim.Framework.Console
}
/// <summary>
/// Sends a warning to the current log output
/// Sends a warning to the current console output
/// </summary>
/// <param name="format">The message to send</param>
/// <param name="args">WriteLine-style message arguments</param>
public void Warn(string format, params object[] args)
{
WriteNewLine(ConsoleColor.Yellow, format, args);
return;
}
/// <summary>
/// Sends a warning to the current log output
/// Sends a warning to the current console output
/// </summary>
/// <param name="sender">The module that sent this message</param>
/// <param name="format">The message to send</param>
@ -112,22 +90,20 @@ namespace OpenSim.Framework.Console
{
WritePrefixLine(DeriveColor(sender), sender);
WriteNewLine(ConsoleColor.Yellow, format, args);
return;
}
/// <summary>
/// Sends a notice to the current log output
/// Sends a notice to the current console output
/// </summary>
/// <param name="format">The message to send</param>
/// <param name="args">WriteLine-style message arguments</param>
public void Notice(string format, params object[] args)
{
WriteNewLine(ConsoleColor.White, format, args);
return;
}
/// <summary>
/// Sends a notice to the current log output
/// Sends a notice to the current console output
/// </summary>
/// <param name="sender">The module that sent this message</param>
/// <param name="format">The message to send</param>
@ -136,22 +112,20 @@ namespace OpenSim.Framework.Console
{
WritePrefixLine(DeriveColor(sender), sender);
WriteNewLine(ConsoleColor.White, format, args);
return;
}
/// <summary>
/// Sends an error to the current log output
/// Sends an error to the current console output
/// </summary>
/// <param name="format">The message to send</param>
/// <param name="args">WriteLine-style message arguments</param>
public void Error(string format, params object[] args)
{
WriteNewLine(ConsoleColor.Red, format, args);
return;
}
/// <summary>
/// Sends an error to the current log output
/// Sends an error to the current console output
/// </summary>
/// <param name="sender">The module that sent this message</param>
/// <param name="format">The message to send</param>
@ -160,38 +134,20 @@ namespace OpenSim.Framework.Console
{
WritePrefixLine(DeriveColor(sender), sender);
Error(format, args);
return;
}
/// <summary>
/// Sends an informational message to the current log 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
/// Sends a status message to the current console output
/// </summary>
/// <param name="format">The message to send</param>
/// <param name="args">WriteLine-style message arguments</param>
public void Status(string format, params object[] args)
{
WriteNewLine(ConsoleColor.Blue, format, args);
return;
}
/// <summary>
/// Sends a status 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>
@ -200,14 +156,12 @@ namespace OpenSim.Framework.Console
{
WritePrefixLine(DeriveColor(sender), sender);
WriteNewLine(ConsoleColor.Blue, format, args);
return;
}
[Conditional("DEBUG")]
public void Debug(string format, params object[] args)
{
WriteNewLine(ConsoleColor.Gray, format, args);
return;
}
[Conditional("DEBUG")]
@ -215,26 +169,14 @@ namespace OpenSim.Framework.Console
{
WritePrefixLine(DeriveColor(sender), sender);
WriteNewLine(ConsoleColor.Gray, format, args);
return;
}
private void WriteNewLine(ConsoleColor color, string format, params object[] args)
{
lock (m_syncRoot)
{
string now = DateTime.Now.ToString("[MM-dd hh:mm:ss] ");
Log.Write(now);
try
{
Log.WriteLine(format, args);
Log.Flush();
}
catch (FormatException)
lock (m_syncRoot)
{
System.Console.WriteLine(args);
}
System.Console.Write(now);
try
{
if (color != ConsoleColor.White)
@ -250,21 +192,24 @@ namespace OpenSim.Framework.Console
}
catch (FormatException)
{
// Some older systems dont support coloured text.
System.Console.WriteLine(args);
}
return;
}
}
catch (ObjectDisposedException)
{
}
}
private void WritePrefixLine(ConsoleColor color, string sender)
{
try
{
lock (m_syncRoot)
{
sender = sender.ToUpper();
Log.WriteLine("[" + sender + "] ");
Log.Flush();
System.Console.WriteLine("[" + sender + "] ");
System.Console.Write("[");
@ -281,32 +226,29 @@ namespace OpenSim.Framework.Console
}
System.Console.Write("] \t");
return;
}
}
catch (ObjectDisposedException)
{
}
}
public string ReadLine()
{
try
{
string TempStr = System.Console.ReadLine();
Log.WriteLine(TempStr);
return TempStr;
return System.Console.ReadLine();
}
catch (Exception e)
{
MainLog.Instance.Error("Console", "System.Console.ReadLine exception " + e.ToString());
return "";
m_log.Error("[Console]: System.Console.ReadLine exception " + e.ToString());
return String.Empty;
}
}
public int Read()
{
int TempInt = System.Console.Read();
Log.Write((char) TempInt);
return TempInt;
return System.Console.Read();
}
public IPAddress CmdPromptIPAddress(string prompt, string defaultvalue)
@ -316,14 +258,14 @@ namespace OpenSim.Framework.Console
while (true)
{
addressStr = MainLog.Instance.CmdPrompt(prompt, defaultvalue);
addressStr = CmdPrompt(prompt, defaultvalue);
if (IPAddress.TryParse(addressStr, out address))
{
break;
}
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)
{
portStr = MainLog.Instance.CmdPrompt(prompt, defaultvalue);
portStr = CmdPrompt(prompt, defaultvalue);
if (uint.TryParse(portStr, out port))
{
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;
}
// 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)
{
// FIXME: Needs to be better abstracted
Log.WriteLine(prompt);
Notice(prompt);
ConsoleColor oldfg = System.Console.ForegroundColor;
System.Console.ForegroundColor = System.Console.BackgroundColor;
System.Console.WriteLine(String.Format("{0}: ", prompt));
//ConsoleColor oldfg = System.Console.ForegroundColor;
//System.Console.ForegroundColor = System.Console.BackgroundColor;
string temp = System.Console.ReadLine();
System.Console.ForegroundColor = oldfg;
//System.Console.ForegroundColor = oldfg;
return temp;
}
// Displays a command prompt and waits for the user to enter a string, then returns that string
public string CmdPrompt(string prompt)
{
Notice(String.Format("{0}: ", prompt));
System.Console.WriteLine(String.Format("{0}: ", prompt));
return ReadLine();
}
@ -377,7 +318,7 @@ namespace OpenSim.Framework.Console
public string CmdPrompt(string prompt, string defaultresponse)
{
string temp = CmdPrompt(String.Format("{0} [{1}]", prompt, defaultresponse));
if (temp == "")
if (temp == String.Empty)
{
return defaultresponse;
}
@ -400,7 +341,7 @@ namespace OpenSim.Framework.Console
}
else
{
Notice("Valid options are " + OptionA + " or " + OptionB);
System.Console.WriteLine("Valid options are " + OptionA + " or " + OptionB);
temp = CmdPrompt(prompt, defaultresponse);
}
}
@ -410,23 +351,23 @@ namespace OpenSim.Framework.Console
// Runs a command with a number of parameters
public Object RunCmd(string Cmd, string[] cmdparams)
{
cmdparser.RunCmd(Cmd, cmdparams);
m_cmdParser.RunCmd(Cmd, cmdparams);
return null;
}
// Shows data about something
public void ShowCommands(string ShowWhat)
{
cmdparser.Show(ShowWhat);
m_cmdParser.Show(ShowWhat);
}
public void MainLogPrompt()
public void Prompt()
{
string tempstr = CmdPrompt(componentname + "# ");
MainLogRunCommand(tempstr);
string tempstr = CmdPrompt(m_componentName + "# ");
RunCommand(tempstr);
}
public void MainLogRunCommand(string command)
public void RunCommand(string command)
{
string[] tempstrarray;
tempstrarray = command.Split(' ');
@ -435,13 +376,14 @@ namespace OpenSim.Framework.Console
Array.Resize<string>(ref tempstrarray, tempstrarray.Length - 1);
Array.Reverse(tempstrarray);
string[] cmdparams = (string[]) tempstrarray;
try
{
RunCmd(cmd, cmdparams);
}
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.
*
*/
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; }
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
* 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
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY

View File

@ -37,6 +37,8 @@ namespace OpenSim.Framework.Data.DB4o
/// </summary>
public class DB4oUserData : IUserData
{
//private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// The database manager
/// </summary>
@ -144,27 +146,33 @@ namespace OpenSim.Framework.Data.DB4o
return null;
}
}
public void StoreWebLoginKey(LLUUID AgentID, LLUUID WebLoginKey)
{
UserProfileData user = GetUserByUUID(AgentID);
user.webLoginKey = WebLoginKey;
UpdateUserProfile(user);
}
#region User Friends List Data
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)
{
//MainLog.Instance.Verbose("FRIEND", "Stub RemoveUserFriend called");
//m_log.Info("[FRIEND]: Stub RemoveUserFriend called");
}
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)
{
//MainLog.Instance.Verbose("FRIEND", "Stub GetUserFriendList called");
//m_log.Info("[FRIEND]: Stub GetUserFriendList called");
return new List<FriendListItem>();
}
@ -172,13 +180,10 @@ namespace OpenSim.Framework.Data.DB4o
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)
{

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

View File

@ -13,7 +13,7 @@
* 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
* 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
@ -37,6 +37,8 @@ namespace OpenSim.Framework.Data.MSSQL
{
internal class MSSQLAssetData : IAssetProvider
{
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private MSSQLManager database;
#region IAssetProvider Members
@ -46,7 +48,7 @@ namespace OpenSim.Framework.Data.MSSQL
// null as the version, indicates that the table didn't exist
if (tableName == null)
{
MainLog.Instance.Notice("ASSETS", "Creating new database tables");
m_log.Info("[ASSETS]: Creating new database tables");
database.ExecuteResourceSql("CreateAssetsTable.sql");
return;
}
@ -168,7 +170,7 @@ namespace OpenSim.Framework.Data.MSSQL
}
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>
/// A grid data interface for Microsoft SQL Server
/// </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>
/// Database manager
/// </summary>
private MSSQLManager database;
private string m_regionsTableName;
/// <summary>
/// Initialises the Grid Interface
/// </summary>
public void Initialise()
{
IniFile GridDataMySqlFile = new IniFile("mssql_connection.ini");
string settingDataSource = GridDataMySqlFile.ParseFileReadValue("data_source");
string settingInitialCatalog = GridDataMySqlFile.ParseFileReadValue("initial_catalog");
string settingPersistSecurityInfo = GridDataMySqlFile.ParseFileReadValue("persist_security_info");
string settingUserId = GridDataMySqlFile.ParseFileReadValue("user_id");
string settingPassword = GridDataMySqlFile.ParseFileReadValue("password");
IniFile iniFile = new IniFile("mssql_connection.ini");
string settingDataSource = iniFile.ParseFileReadValue("data_source");
string settingInitialCatalog = iniFile.ParseFileReadValue("initial_catalog");
string settingPersistSecurityInfo = iniFile.ParseFileReadValue("persist_security_info");
string settingUserId = iniFile.ParseFileReadValue("user_id");
string settingPassword = iniFile.ParseFileReadValue("password");
m_regionsTableName = iniFile.ParseFileReadValue("regionstablename");
if (m_regionsTableName == null)
{
m_regionsTableName = "regions";
}
database =
new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId,
settingPassword);
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>
@ -113,7 +142,7 @@ namespace OpenSim.Framework.Data.MSSQL
{
Dictionary<string, string> param = new Dictionary<string, string>();
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();
RegionProfileData row = database.getRegionRow(reader);
@ -132,88 +161,6 @@ namespace OpenSim.Framework.Data.MSSQL
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>
/// 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>();
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();
RegionProfileData row = database.getRegionRow(reader);
@ -253,7 +200,7 @@ namespace OpenSim.Framework.Data.MSSQL
System.Console.WriteLine("No regions found. Create new one.");
}
if (database.insertRegionRow(profile))
if ( insertRegionRow(profile))
{
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>
/// DEPRECIATED. Attempts to authenticate a region by comparing a shared secret.
/// </summary>

View File

@ -39,6 +39,8 @@ namespace OpenSim.Framework.Data.MSSQL
/// </summary>
public class MSSQLInventoryData : IInventoryData
{
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// The database manager
/// </summary>
@ -159,7 +161,7 @@ namespace OpenSim.Framework.Data.MSSQL
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
return null;
}
}
@ -198,7 +200,7 @@ namespace OpenSim.Framework.Data.MSSQL
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
return null;
}
}
@ -244,7 +246,7 @@ namespace OpenSim.Framework.Data.MSSQL
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
return null;
}
}
@ -282,7 +284,7 @@ namespace OpenSim.Framework.Data.MSSQL
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
return null;
}
}
@ -315,7 +317,7 @@ namespace OpenSim.Framework.Data.MSSQL
}
catch (SqlException e)
{
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
}
return null;
@ -352,7 +354,7 @@ namespace OpenSim.Framework.Data.MSSQL
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
}
return null;
}
@ -377,7 +379,7 @@ namespace OpenSim.Framework.Data.MSSQL
}
catch (Exception e)
{
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
}
return null;
@ -412,7 +414,7 @@ namespace OpenSim.Framework.Data.MSSQL
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
return null;
}
}
@ -452,7 +454,7 @@ namespace OpenSim.Framework.Data.MSSQL
}
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)
{
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
}
}
@ -533,7 +535,7 @@ namespace OpenSim.Framework.Data.MSSQL
catch (SqlException e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
}
}
@ -564,7 +566,7 @@ namespace OpenSim.Framework.Data.MSSQL
}
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)
{
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
}
}
@ -628,7 +630,7 @@ namespace OpenSim.Framework.Data.MSSQL
}
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)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
}
}
@ -695,7 +697,7 @@ namespace OpenSim.Framework.Data.MSSQL
catch (SqlException e)
{
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.
*
*/
using System.Collections.Generic;
using System.Data;
namespace OpenSim.Framework.Data.MSSQL
{
/// <summary>
@ -52,6 +55,18 @@ namespace OpenSim.Framework.Data.MSSQL
database =
new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId,
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>

View File

@ -40,8 +40,10 @@ namespace OpenSim.Framework.Data.MSSQL
/// <summary>
/// A management class for the MS SQL Storage Engine
/// </summary>
internal class MSSQLManager
public class MSSQLManager
{
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// The database connection object
/// </summary>
@ -50,20 +52,10 @@ namespace OpenSim.Framework.Data.MSSQL
/// <summary>
/// Connection string for ADO.net
/// </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,
string password)
{
try
{
connectionString = "Data Source=" + dataSource + ";Initial Catalog=" + initialCatalog +
";Persist Security Info=" + persistSecurityInfo + ";User ID=" + userId + ";Password=" +
@ -116,68 +108,45 @@ namespace OpenSim.Framework.Data.MSSQL
return true;
}
private void InitDB(IDbConnection conn)
{
string createRegions = defineTable(createRegionsTable());
Dictionary<string, string> param = new Dictionary<string, string>();
IDbCommand pcmd = Query(createRegions, param);
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
pcmd.ExecuteNonQuery();
pcmd.Dispose();
// createCol(regions, "regionHandle", typeof (ulong));
// createCol(regions, "regionName", typeof (String));
// createCol(regions, "uuid", typeof (String));
ExecuteResourceSql("Mssql-users.sql");
ExecuteResourceSql("Mssql-agents.sql");
ExecuteResourceSql("Mssql-logs.sql");
// createCol(regions, "regionRecvKey", typeof (String));
// createCol(regions, "regionSecret", typeof (String));
// createCol(regions, "regionSendKey", typeof (String));
conn.Close();
}
private DataTable createRegionsTable()
{
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, "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, "locY", typeof (uint));
createCol(regions, "locZ", typeof (uint));
// createCol(regions, "locX", typeof (uint));
// createCol(regions, "locY", typeof (uint));
// createCol(regions, "locZ", typeof (uint));
createCol(regions, "eastOverrideHandle", typeof (ulong));
createCol(regions, "westOverrideHandle", typeof (ulong));
createCol(regions, "southOverrideHandle", typeof (ulong));
createCol(regions, "northOverrideHandle", typeof (ulong));
// createCol(regions, "eastOverrideHandle", typeof (ulong));
// createCol(regions, "westOverrideHandle", typeof (ulong));
// createCol(regions, "southOverrideHandle", typeof (ulong));
// createCol(regions, "northOverrideHandle", typeof (ulong));
createCol(regions, "regionAssetURI", typeof (String));
createCol(regions, "regionAssetRecvKey", typeof (String));
createCol(regions, "regionAssetSendKey", typeof (String));
// createCol(regions, "regionAssetURI", typeof (String));
// createCol(regions, "regionAssetRecvKey", typeof (String));
// createCol(regions, "regionAssetSendKey", typeof (String));
createCol(regions, "regionUserURI", typeof (String));
createCol(regions, "regionUserRecvKey", typeof (String));
createCol(regions, "regionUserSendKey", typeof (String));
// createCol(regions, "regionUserURI", typeof (String));
// createCol(regions, "regionUserRecvKey", typeof (String));
// createCol(regions, "regionUserSendKey", typeof (String));
createCol(regions, "regionMapTexture", typeof (String));
createCol(regions, "serverHttpPort", typeof (String));
createCol(regions, "serverRemotingPort", typeof (uint));
// createCol(regions, "regionMapTexture", typeof (String));
// createCol(regions, "serverHttpPort", typeof (String));
// createCol(regions, "serverRemotingPort", typeof (uint));
// Add in contraints
regions.PrimaryKey = new DataColumn[] {regions.Columns["UUID"]};
return regions;
}
// // Add in contraints
// regions.PrimaryKey = new DataColumn[] {regions.Columns["UUID"]};
// return regions;
//}
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)
{
string sql = "create table " + dt.TableName + "(";
string subsql = "";
string subsql = String.Empty;
foreach (DataColumn col in dt.Columns)
{
if (subsql.Length > 0)
@ -253,7 +222,6 @@ namespace OpenSim.Framework.Data.MSSQL
{
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
dbcon.Close();
// Try reopen it
@ -262,7 +230,7 @@ namespace OpenSim.Framework.Data.MSSQL
}
catch (Exception e)
{
MainLog.Instance.Error("Unable to reconnect to database " + e.ToString());
m_log.Error("Unable to reconnect to database " + e.ToString());
}
}
}
@ -339,7 +307,7 @@ namespace OpenSim.Framework.Data.MSSQL
// World Map Addition
string tempRegionMap = reader["regionMapTexture"].ToString();
if (tempRegionMap != "")
if (tempRegionMap != String.Empty)
{
regionprofile.regionMapTextureID = new LLUUID(tempRegionMap);
}
@ -468,76 +436,6 @@ namespace OpenSim.Framework.Data.MSSQL
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>
/// Inserts a new row into the log database
@ -576,101 +474,7 @@ namespace OpenSim.Framework.Data.MSSQL
}
catch (Exception e)
{
MainLog.Instance.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());
m_log.Error(e.ToString());
return false;
}
@ -682,18 +486,11 @@ namespace OpenSim.Framework.Data.MSSQL
/// </summary>
/// <param name="name"></param>
public void ExecuteResourceSql(string name)
{
try
{
SqlCommand cmd = new SqlCommand(getResourceString(name), (SqlConnection)dbcon);
cmd.ExecuteNonQuery();
cmd.Dispose();
}
catch (Exception e)
{
MainLog.Instance.Error("Unable to execute query " + e.ToString());
}
}
public SqlConnection getConnection()
{
@ -724,7 +521,7 @@ namespace OpenSim.Framework.Data.MSSQL
}
catch (Exception e)
{
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
}
}
tables.Close();

View File

@ -37,13 +37,19 @@ namespace OpenSim.Framework.Data.MSSQL
/// <summary>
/// A database interface class to a user profile storage system
/// </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>
/// Database manager for MySQL
/// </summary>
public MSSQLManager database;
private string m_agentsTableName;
private string m_usersTableName;
private string m_userFriendsTableName;
/// <summary>
/// Loads and initialises the MySQL storage plugin
/// </summary>
@ -51,18 +57,74 @@ namespace OpenSim.Framework.Data.MSSQL
{
// Load from an INI file connection details
// TODO: move this to XML?
IniFile GridDataMySqlFile = new IniFile("mssql_connection.ini");
string settingDataSource = GridDataMySqlFile.ParseFileReadValue("data_source");
string settingInitialCatalog = GridDataMySqlFile.ParseFileReadValue("initial_catalog");
string settingPersistSecurityInfo = GridDataMySqlFile.ParseFileReadValue("persist_security_info");
string settingUserId = GridDataMySqlFile.ParseFileReadValue("user_id");
string settingPassword = GridDataMySqlFile.ParseFileReadValue("password");
IniFile iniFile = new IniFile("mssql_connection.ini");
string settingDataSource = iniFile.ParseFileReadValue("data_source");
string settingInitialCatalog = iniFile.ParseFileReadValue("initial_catalog");
string settingPersistSecurityInfo = iniFile.ParseFileReadValue("persist_security_info");
string settingUserId = iniFile.ParseFileReadValue("user_id");
string settingPassword = iniFile.ParseFileReadValue("password");
m_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 =
new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId,
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>
/// Searches the database for a specified user profile by name components
/// </summary>
@ -80,7 +142,7 @@ namespace OpenSim.Framework.Data.MSSQL
param["second"] = last;
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();
UserProfileData row = database.readUserRow(reader);
@ -94,7 +156,7 @@ namespace OpenSim.Framework.Data.MSSQL
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
return null;
}
}
@ -103,36 +165,165 @@ namespace OpenSim.Framework.Data.MSSQL
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)
{
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)
{
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)
{
MainLog.Instance.Verbose("FRIEND", "Stub GetUserFriendList called");
return new List<FriendListItem>();
List<FriendListItem> Lfli = 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
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)
{
@ -151,7 +342,7 @@ namespace OpenSim.Framework.Data.MSSQL
IDbCommand result =
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);
IDataReader reader = result.ExecuteReader();
@ -161,7 +352,7 @@ namespace OpenSim.Framework.Data.MSSQL
Framework.AvatarPickerAvatar user = new Framework.AvatarPickerAvatar();
user.AvatarID = new LLUUID((string)reader["UUID"]);
user.firstName = (string)reader["username"];
user.lastName = (string) reader["surname"];
user.lastName = (string)reader["lastname"];
returnlist.Add(user);
}
reader.Close();
@ -171,7 +362,7 @@ namespace OpenSim.Framework.Data.MSSQL
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
return returnlist;
}
}
@ -183,11 +374,10 @@ namespace OpenSim.Framework.Data.MSSQL
{
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",
"SELECT UUID,username,lastname FROM " + m_usersTableName + " WHERE username = @first OR lastname = @first",
param);
IDataReader reader = result.ExecuteReader();
@ -197,7 +387,7 @@ namespace OpenSim.Framework.Data.MSSQL
Framework.AvatarPickerAvatar user = new Framework.AvatarPickerAvatar();
user.AvatarID = new LLUUID((string)reader["UUID"]);
user.firstName = (string)reader["username"];
user.lastName = (string) reader["surname"];
user.lastName = (string)reader["lastname"];
returnlist.Add(user);
}
reader.Close();
@ -207,7 +397,7 @@ namespace OpenSim.Framework.Data.MSSQL
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
return returnlist;
}
}
@ -224,7 +414,7 @@ namespace OpenSim.Framework.Data.MSSQL
Dictionary<string, string> param = new Dictionary<string, string>();
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();
UserProfileData row = database.readUserRow(reader);
@ -238,7 +428,7 @@ namespace OpenSim.Framework.Data.MSSQL
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
return null;
}
}
@ -321,7 +511,7 @@ namespace OpenSim.Framework.Data.MSSQL
Dictionary<string, string> param = new Dictionary<string, string>();
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();
UserAgentData row = database.readAgentRow(reader);
@ -335,11 +525,17 @@ namespace OpenSim.Framework.Data.MSSQL
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
return null;
}
}
public void StoreWebLoginKey(LLUUID AgentID, LLUUID WebLoginKey)
{
UserProfileData user = GetUserByUUID(AgentID);
user.webLoginKey = WebLoginKey;
UpdateUserProfile(user);
}
/// <summary>
/// Creates a new users profile
/// </summary>
@ -350,7 +546,7 @@ namespace OpenSim.Framework.Data.MSSQL
{
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.homeLocation.Z,
user.homeLookAt.X, user.homeLookAt.Y, user.homeLookAt.Z, user.created,
@ -363,10 +559,103 @@ namespace OpenSim.Framework.Data.MSSQL
catch (Exception e)
{
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>
/// Creates a new agent
/// </summary>
@ -379,7 +668,7 @@ namespace OpenSim.Framework.Data.MSSQL
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, " +
"lastname = @lastname," +
"passwordHash = @passwordHash," +
@ -400,7 +689,8 @@ namespace OpenSim.Framework.Data.MSSQL
"profileAboutText = @profileAboutText," +
"profileFirstText = @profileFirstText," +
"profileImage = @profileImage," +
"profileFirstImage = @profileFirstImage where " +
"profileFirstImage = @profileFirstImage, " +
"webLoginKey = @webLoginKey where " +
"UUID = @keyUUUID;", database.getConnection());
SqlParameter param1 = new SqlParameter("@uuid", user.UUID.ToString());
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 param22 = new SqlParameter("@profileFirstImage", LLUUID.Zero.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(param2);
command.Parameters.Add(param3);
@ -448,6 +739,7 @@ namespace OpenSim.Framework.Data.MSSQL
command.Parameters.Add(param21);
command.Parameters.Add(param22);
command.Parameters.Add(param23);
command.Parameters.Add(param24);
try
{
int affected = command.ExecuteNonQuery();
@ -462,7 +754,7 @@ namespace OpenSim.Framework.Data.MSSQL
}
catch (Exception e)
{
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
}
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.Runtime.InteropServices;
@ -10,7 +38,7 @@ using System.Runtime.InteropServices;
[assembly : AssemblyConfiguration("")]
[assembly : AssemblyCompany("")]
[assembly : AssemblyProduct("OpenSim.Framework.Data.MSSQL")]
[assembly : AssemblyCopyright("Copyright © 2007")]
[assembly : AssemblyCopyright("Copyright © OpenSimulator.org Developers 2007-2008")]
[assembly : AssemblyTrademark("")]
[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
* 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
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
@ -37,6 +37,8 @@ namespace OpenSim.Framework.Data.MySQL
{
internal class MySQLAssetData : IAssetProvider
{
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private MySQLManager _dbConnection;
#region IAssetProvider Members
@ -46,7 +48,7 @@ namespace OpenSim.Framework.Data.MySQL
// null as the version, indicates that the table didn't exist
if (oldVersion == null)
{
MainLog.Instance.Notice("ASSETS", "Creating new database tables");
m_log.Info("[ASSETS]: Creating new database tables");
_dbConnection.ExecuteResourceSql("CreateAssetsTable.sql");
return;
}
@ -76,6 +78,7 @@ namespace OpenSim.Framework.Data.MySQL
_dbConnection.Connection);
MySqlParameter p = cmd.Parameters.Add("?id", MySqlDbType.Binary, 16);
p.Value = assetID.GetBytes();
try
{
using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
@ -95,15 +98,20 @@ namespace OpenSim.Framework.Data.MySQL
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;
}
public void CreateAsset(AssetBase asset)
{
lock (_dbConnection)
{
MySqlCommand cmd =
new MySqlCommand(
@ -112,6 +120,8 @@ namespace OpenSim.Framework.Data.MySQL
_dbConnection.Connection);
// need to ensure we dispose
try
{
using (cmd)
{
MySqlParameter p = cmd.Parameters.Add("?id", MySqlDbType.Binary, 16);
@ -127,6 +137,16 @@ namespace OpenSim.Framework.Data.MySQL
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();
}
}
}
public void UpdateAsset(AssetBase asset)
{

View File

@ -42,8 +42,11 @@ namespace OpenSim.Framework.Data.MySQL
{
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_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_landSelect = "select * from land";
private const string m_landAccessListSelect = "select * from landaccesslist";
@ -51,16 +54,22 @@ namespace OpenSim.Framework.Data.MySQL
private DataSet m_dataSet;
private MySqlDataAdapter m_primDataAdapter;
private MySqlDataAdapter m_shapeDataAdapter;
private MySqlDataAdapter m_itemsDataAdapter;
private MySqlConnection m_connection;
private MySqlDataAdapter m_terrainDataAdapter;
private MySqlDataAdapter m_landDataAdapter;
private MySqlDataAdapter m_landAccessListDataAdapter;
private DataTable m_primTable;
private DataTable m_shapeTable;
private DataTable m_itemsTable;
private DataTable m_terrainTable;
private DataTable m_landTable;
private DataTable m_landAccessListTable;
// Temporary attribute while this is experimental
private bool persistPrimInventories;
/***********************************************************************
*
* Public Interface Functions
@ -71,8 +80,9 @@ namespace OpenSim.Framework.Data.MySQL
public void Initialise(string connectionstring, bool persistPrimInventories)
{
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);
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);
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);
m_terrainDataAdapter = new MySqlDataAdapter(terrainSelectCmd);
@ -104,6 +117,14 @@ namespace OpenSim.Framework.Data.MySQL
SetupShapeCommands(m_shapeDataAdapter, m_connection);
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_dataSet.Tables.Add(m_terrainTable);
SetupTerrainCommands(m_terrainDataAdapter, m_connection);
@ -129,12 +150,12 @@ namespace OpenSim.Framework.Data.MySQL
{
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);
}
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)
{
m_log.InfoFormat("[DATASTORE]: Removing obj: {0} from region: {1}", obj.UUID, regionUUID);
DataTable prims = m_primTable;
DataTable shapes = m_shapeTable;
@ -153,12 +176,20 @@ namespace OpenSim.Framework.Data.MySQL
DataRow[] primRows = prims.Select(selectExp);
foreach (DataRow row in primRows)
{
// Remove shapes row
LLUUID uuid = new LLUUID((string) row["UUID"]);
DataRow shapeRow = shapes.Rows.Find(Util.ToRawUuidString(uuid));
if (shapeRow != null)
{
shapeRow.Delete();
}
if (persistPrimInventories)
{
RemoveItems(uuid);
}
// Remove prim row
row.Delete();
}
}
@ -166,6 +197,24 @@ namespace OpenSim.Framework.Data.MySQL
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)
{
Dictionary<LLUUID, SceneObjectGroup> createdObjects = new Dictionary<LLUUID, SceneObjectGroup>();
@ -181,7 +230,7 @@ namespace OpenSim.Framework.Data.MySQL
lock (m_dataSet)
{
DataRow[] primsForRegion = prims.Select(byRegion, orderByParent);
MainLog.Instance.Verbose("DATASTORE",
m_log.Info("[DATASTORE]: " +
"Loaded " + primsForRegion.Length + " prims for region: " + regionUUID);
foreach (DataRow primRow in primsForRegion)
@ -190,10 +239,13 @@ namespace OpenSim.Framework.Data.MySQL
{
string uuid = (string) primRow["UUID"];
string objID = (string) primRow["SceneGroupID"];
SceneObjectPart prim = buildPrim(primRow);
if (uuid == objID) //is new SceneObjectGroup ?
{
SceneObjectGroup group = new SceneObjectGroup();
SceneObjectPart prim = buildPrim(primRow);
DataRow shapeRow = shapes.Rows.Find(Util.ToRawUuidString(prim.UUID));
if (shapeRow != null)
{
@ -201,7 +253,7 @@ namespace OpenSim.Framework.Data.MySQL
}
else
{
MainLog.Instance.Notice(
m_log.Info(
"No shape found for prim in storage, so setting default box shape");
prim.Shape = PrimitiveBaseShape.Default;
}
@ -213,7 +265,6 @@ namespace OpenSim.Framework.Data.MySQL
}
else
{
SceneObjectPart prim = buildPrim(primRow);
DataRow shapeRow = shapes.Rows.Find(Util.ToRawUuidString(prim.UUID));
if (shapeRow != null)
{
@ -221,20 +272,25 @@ namespace OpenSim.Framework.Data.MySQL
}
else
{
MainLog.Instance.Notice(
m_log.Info(
"No shape found for prim in storage, so setting default box shape");
prim.Shape = PrimitiveBaseShape.Default;
}
createdObjects[new LLUUID(objID)].AddPart(prim);
}
if (persistPrimInventories)
{
LoadItems(prim);
}
}
catch (Exception e)
{
MainLog.Instance.Error("DATASTORE", "Failed create prim object, exception and data follows");
MainLog.Instance.Verbose("DATASTORE", e.ToString());
m_log.Error("[DATASTORE]: Failed create prim object, exception and data follows");
m_log.Info("[DATASTORE]: " + e.ToString());
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;
}
/// <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)
{
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"];
lock (m_dataSet)
@ -286,23 +374,24 @@ namespace OpenSim.Framework.Data.MySQL
int rev = 0;
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 y = 0; y < 256; y++)
{
terret[x, y] = BitConverter.ToDouble(heightmap, ((x*256) + y)*8);
terret[x, y] = br.ReadDouble();
}
}
rev = (int) row["Revision"];
}
else
{
MainLog.Instance.Verbose("DATASTORE", "No terrain found for region");
m_log.Info("[DATASTORE]: No terrain found for region");
return null;
}
MainLog.Instance.Verbose("DATASTORE", "Loaded terrain revision r" + rev.ToString());
m_log.Info("[DATASTORE]: Loaded terrain revision r" + rev.ToString());
}
return terret;
@ -328,8 +417,13 @@ namespace OpenSim.Framework.Data.MySQL
}
}
static Random rnd = new Random();
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)
{
DataTable land = m_landTable;
@ -361,8 +455,8 @@ namespace OpenSim.Framework.Data.MySQL
fillLandAccessRow(newAccessRow, entry, parcel.landData.globalID);
landaccesslist.Rows.Add(newAccessRow);
}
}
}
Commit();
}
@ -408,7 +502,7 @@ namespace OpenSim.Framework.Data.MySQL
foreach (DataColumn column in table.Columns)
Debug.Write(column.ColumnName + " = " +
row[column, DataRowVersion.Original] + ", ");
Debug.WriteLine("");
Debug.WriteLine(String.Empty);
}
//--- Display the current values, if there are any.
if (row.HasVersion(DataRowVersion.Current))
@ -417,9 +511,9 @@ namespace OpenSim.Framework.Data.MySQL
foreach (DataColumn column in table.Columns)
Debug.Write(column.ColumnName + " = " +
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_shapeDataAdapter.Update(m_shapeTable);
if (persistPrimInventories)
{
m_itemsDataAdapter.Update(m_itemsTable);
}
m_terrainDataAdapter.Update(m_terrainTable);
m_landDataAdapter.Update(m_landTable);
m_landAccessListDataAdapter.Update(m_landAccessListTable);
@ -445,6 +545,7 @@ namespace OpenSim.Framework.Data.MySQL
}
}
public void Shutdown()
{
Commit();
@ -631,6 +732,38 @@ namespace OpenSim.Framework.Data.MySQL
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
@ -728,6 +861,41 @@ namespace OpenSim.Framework.Data.MySQL
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)
{
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)
{
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
@ -1067,7 +1290,7 @@ namespace OpenSim.Framework.Data.MySQL
private MySqlCommand createUpdateCommand(string table, string pk, DataTable dt)
{
string sql = "update " + table + " set ";
string subsql = "";
string subsql = String.Empty;
foreach (DataColumn col in dt.Columns)
{
if (subsql.Length > 0)
@ -1091,11 +1314,10 @@ namespace OpenSim.Framework.Data.MySQL
return cmd;
}
private string defineTable(DataTable dt)
{
string sql = "create table " + dt.TableName + "(";
string subsql = "";
string subsql = String.Empty;
foreach (DataColumn col in dt.Columns)
{
if (subsql.Length > 0)
@ -1111,6 +1333,9 @@ namespace OpenSim.Framework.Data.MySQL
}
sql += subsql;
sql += ")";
//m_log.InfoFormat("[DATASTORE]: defineTable() sql {0}", sql);
return sql;
}
@ -1167,6 +1392,20 @@ namespace OpenSim.Framework.Data.MySQL
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)
{
da.InsertCommand = createInsertCommand("terrain", m_dataSet.Tables["terrain"]);
@ -1206,64 +1445,84 @@ namespace OpenSim.Framework.Data.MySQL
{
string createPrims = defineTable(createPrimTable());
string createShapes = defineTable(createShapeTable());
string createItems = defineTable(createItemsTable());
string createTerrain = defineTable(createTerrainTable());
string createLand = defineTable(createLandTable());
string createLandAccessList = defineTable(createLandAccessListTable());
MySqlCommand pcmd = new MySqlCommand(createPrims, conn);
MySqlCommand scmd = new MySqlCommand(createShapes, conn);
MySqlCommand icmd = new MySqlCommand(createItems, conn);
MySqlCommand tcmd = new MySqlCommand(createTerrain, conn);
MySqlCommand lcmd = new MySqlCommand(createLand, conn);
MySqlCommand lalcmd = new MySqlCommand(createLandAccessList, conn);
if (conn.State != ConnectionState.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
{
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
{
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
{
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
{
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
{
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();
}
@ -1274,6 +1533,8 @@ namespace OpenSim.Framework.Data.MySQL
MySqlDataAdapter pDa = new MySqlDataAdapter(primSelectCmd);
MySqlCommand shapeSelectCmd = new MySqlCommand(m_shapeSelect, conn);
MySqlDataAdapter sDa = new MySqlDataAdapter(shapeSelectCmd);
MySqlCommand itemsSelectCmd = new MySqlCommand(m_itemsSelect, conn);
MySqlDataAdapter iDa = new MySqlDataAdapter(itemsSelectCmd);
MySqlCommand terrainSelectCmd = new MySqlCommand(m_terrainSelect, conn);
MySqlDataAdapter tDa = new MySqlDataAdapter(terrainSelectCmd);
MySqlCommand landSelectCmd = new MySqlCommand(m_landSelect, conn);
@ -1286,18 +1547,26 @@ namespace OpenSim.Framework.Data.MySQL
{
pDa.Fill(tmpDS, "prims");
sDa.Fill(tmpDS, "primshapes");
if (persistPrimInventories)
iDa.Fill(tmpDS, "primitems");
tDa.Fill(tmpDS, "terrain");
lDa.Fill(tmpDS, "land");
lalDa.Fill(tmpDS, "landaccesslist");
}
catch (MySqlException)
{
MainLog.Instance.Verbose("DATASTORE", "MySql Database doesn't exist... creating");
m_log.Info("[DATASTORE]: MySql Database doesn't exist... creating");
InitDB(conn);
}
pDa.Fill(tmpDS, "prims");
sDa.Fill(tmpDS, "primshapes");
if (persistPrimInventories)
iDa.Fill(tmpDS, "primitems");
tDa.Fill(tmpDS, "terrain");
lDa.Fill(tmpDS, "land");
lalDa.Fill(tmpDS, "landaccesslist");
@ -1306,42 +1575,49 @@ namespace OpenSim.Framework.Data.MySQL
{
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;
}
}
foreach (DataColumn col in createShapeTable().Columns)
{
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;
}
}
// XXX primitems should probably go here eventually
foreach (DataColumn col in createTerrainTable().Columns)
{
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;
}
}
foreach (DataColumn col in createLandTable().Columns)
{
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;
}
}
foreach (DataColumn col in createLandAccessListTable().Columns)
{
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 true;
}
@ -1395,6 +1671,10 @@ namespace OpenSim.Framework.Data.MySQL
{
return "integer";
}
else if (type == typeof (Int64))
{
return "bigint";
}
else if (type == typeof (Double))
{
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>
public class MySQLGridData : IGridData
{
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// MySQL Database Manager
/// </summary>
@ -168,7 +170,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
return null;
}
}
@ -200,95 +202,11 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
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>
/// Returns a sim profile from it's UUID
/// </summary>
@ -316,7 +234,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
return null;
}
}
@ -405,7 +323,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
return null;
}
}

View File

@ -38,6 +38,9 @@ namespace OpenSim.Framework.Data.MySQL
/// </summary>
public class MySQLInventoryData : IInventoryData
{
private static readonly log4net.ILog m_log
= log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// The database manager
/// </summary>
@ -104,8 +107,8 @@ namespace OpenSim.Framework.Data.MySQL
tableList["inventoryitems"] = null;
database.GetTableVersion(tableList);
MainLog.Instance.Verbose("MYSQL", "Inventory Folder Version: " + tableList["inventoryfolders"]);
MainLog.Instance.Verbose("MYSQL", "Inventory Items Version: " + tableList["inventoryitems"]);
m_log.Info("[MYSQL]: Inventory Folder Version: " + tableList["inventoryfolders"]);
m_log.Info("[MYSQL]: Inventory Items Version: " + tableList["inventoryitems"]);
UpgradeFoldersTable(tableList["inventoryfolders"]);
UpgradeItemsTable(tableList["inventoryitems"]);
@ -170,7 +173,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
return null;
}
}
@ -208,7 +211,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
return null;
}
}
@ -254,7 +257,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
return null;
}
}
@ -292,7 +295,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
return null;
}
}
@ -325,7 +328,7 @@ namespace OpenSim.Framework.Data.MySQL
}
catch (MySqlException e)
{
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
}
return null;
@ -362,7 +365,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
}
return null;
}
@ -387,7 +390,7 @@ namespace OpenSim.Framework.Data.MySQL
}
catch (Exception e)
{
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
}
return null;
@ -421,7 +424,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
return null;
}
}
@ -459,7 +462,7 @@ namespace OpenSim.Framework.Data.MySQL
}
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)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
}
}
@ -511,12 +514,15 @@ namespace OpenSim.Framework.Data.MySQL
cmd.Parameters.AddWithValue("?version", folder.version);
try
{
lock (database)
{
cmd.ExecuteNonQuery();
}
}
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("?parentFolderID", folder.parentID.ToString());
try
{
lock (database)
{
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
}
}
@ -588,12 +596,16 @@ namespace OpenSim.Framework.Data.MySQL
MySqlCommand cmd =
new MySqlCommand("DELETE FROM inventoryfolders WHERE folderID=?uuid", database.Connection);
cmd.Parameters.AddWithValue("?uuid", folderID.ToString());
lock (database)
{
cmd.ExecuteNonQuery();
}
}
catch (MySqlException e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
}
}
@ -604,12 +616,16 @@ namespace OpenSim.Framework.Data.MySQL
MySqlCommand cmd =
new MySqlCommand("DELETE FROM inventoryitems WHERE parentFolderID=?uuid", database.Connection);
cmd.Parameters.AddWithValue("?uuid", folderID.ToString());
lock (database)
{
cmd.ExecuteNonQuery();
}
}
catch (MySqlException e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
}
}
@ -619,8 +635,6 @@ namespace OpenSim.Framework.Data.MySQL
/// </summary>
/// <param name="folderId">Id of folder to delete</param>
public void deleteInventoryFolder(LLUUID folderID)
{
lock (database)
{
List<InventoryFolderBase> subFolders = getFolderHierarchy(folderID);
@ -637,4 +651,3 @@ namespace OpenSim.Framework.Data.MySQL
}
}
}
}

View File

@ -29,6 +29,7 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Reflection;
using libsecondlife;
@ -42,6 +43,8 @@ namespace OpenSim.Framework.Data.MySQL
/// </summary>
internal class MySQLManager
{
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// The database connection object
/// </summary>
@ -69,9 +72,16 @@ namespace OpenSim.Framework.Data.MySQL
username + ";Password=" + password + ";Pooling=" + cpooling + ";";
dbcon = new MySqlConnection(connectionString);
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)
{
@ -113,7 +123,7 @@ namespace OpenSim.Framework.Data.MySQL
}
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 comment = (string) tables["TABLE_COMMENT"];
if (tableList.ContainsKey(tableName))
{
tableList[tableName] = comment;
}
}
catch (Exception e)
{
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
}
}
tables.Close();
@ -245,7 +257,7 @@ namespace OpenSim.Framework.Data.MySQL
}
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
@ -263,7 +275,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e)
{
// 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;
}
}
@ -324,7 +336,7 @@ namespace OpenSim.Framework.Data.MySQL
// World Map Addition
string tempRegionMap = reader["regionMapTexture"].ToString();
if (tempRegionMap != "")
if (tempRegionMap != String.Empty)
{
retval.regionMapTextureID = new LLUUID(tempRegionMap);
}
@ -332,6 +344,23 @@ namespace OpenSim.Framework.Data.MySQL
{
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
{
@ -447,8 +476,16 @@ namespace OpenSim.Framework.Data.MySQL
retval.profileImage = new LLUUID((string) reader["profileImage"]);
retval.profileFirstImage = new LLUUID((string) reader["profileFirstImage"]);
if( reader.IsDBNull( reader.GetOrdinal( "webLoginKey" ) ) )
{
retval.webLoginKey = LLUUID.Zero;
}
else
{
retval.webLoginKey = new LLUUID((string)reader["webLoginKey"]);
}
}
else
{
return null;
@ -494,7 +531,7 @@ namespace OpenSim.Framework.Data.MySQL
}
catch (Exception e)
{
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
return false;
}
@ -565,12 +602,12 @@ namespace OpenSim.Framework.Data.MySQL
parameters["?homeLookAtZ"] = homeLookAtZ.ToString();
parameters["?created"] = created.ToString();
parameters["?lastLogin"] = lastlogin.ToString();
parameters["?userInventoryURI"] = "";
parameters["?userAssetURI"] = "";
parameters["?userInventoryURI"] = String.Empty;
parameters["?userAssetURI"] = String.Empty;
parameters["?profileCanDoMask"] = "0";
parameters["?profileWantDoMask"] = "0";
parameters["?profileAboutText"] = "";
parameters["?profileFirstText"] = "";
parameters["?profileAboutText"] = String.Empty;
parameters["?profileFirstText"] = String.Empty;
parameters["?profileImage"] = LLUUID.Zero.ToString();
parameters["?profileFirstImage"] = LLUUID.Zero.ToString();
parameters["?webLoginKey"] = LLUUID.Random().ToString();
@ -588,7 +625,7 @@ namespace OpenSim.Framework.Data.MySQL
}
catch (Exception e)
{
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
return false;
}
@ -605,7 +642,7 @@ namespace OpenSim.Framework.Data.MySQL
{
bool GRID_ONLY_UPDATE_NECESSARY_DATA = false;
string sql = "";
string sql = String.Empty;
if (GRID_ONLY_UPDATE_NECESSARY_DATA)
{
sql += "INSERT INTO ";
@ -618,18 +655,28 @@ namespace OpenSim.Framework.Data.MySQL
sql += "regions (regionHandle, regionName, uuid, regionRecvKey, regionSecret, regionSendKey, regionDataURI, ";
sql +=
"serverIP, serverPort, serverURI, locX, locY, locZ, eastOverrideHandle, westOverrideHandle, southOverrideHandle, northOverrideHandle, regionAssetURI, regionAssetRecvKey, ";
// part of an initial brutish effort to provide accurate information (as per the xml region spec)
// wrt the ownership of a given region
// the (very bad) assumption is that this value is being read and handled inconsistently or
// not at all. Current strategy is to put the code in place to support the validity of this information
// and to roll forward debugging any issues from that point
//
// this particular section of the mod attempts to implement the commit of a supplied value
// server for the UUID of the region's owner (master avatar). It consists of the addition of the column and value to the relevant sql,
// as well as the related parameterization
sql +=
"regionAssetSendKey, regionUserURI, regionUserRecvKey, regionUserSendKey, regionMapTexture, serverHttpPort, serverRemotingPort) VALUES ";
"regionAssetSendKey, regionUserURI, regionUserRecvKey, regionUserSendKey, regionMapTexture, serverHttpPort, serverRemotingPort, owner_uuid) 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)";
"?regionAssetSendKey, ?regionUserURI, ?regionUserRecvKey, ?regionUserSendKey, ?regionMapTexture, ?serverHttpPort, ?serverRemotingPort, ?owner_uuid)";
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
{
@ -664,6 +711,8 @@ namespace OpenSim.Framework.Data.MySQL
parameters["?regionMapTexture"] = regiondata.regionMapTextureID.ToString();
parameters["?serverHttpPort"] = regiondata.httpPort.ToString();
parameters["?serverRemotingPort"] = regiondata.remotingPort.ToString();
parameters["?owner_uuid"] = regiondata.owner_uuid.ToString();
bool returnval = false;
try
@ -680,7 +729,7 @@ namespace OpenSim.Framework.Data.MySQL
}
catch (Exception e)
{
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
return false;
}

View File

@ -39,25 +39,50 @@ namespace OpenSim.Framework.Data.MySQL
/// </summary>
internal class MySQLUserData : IUserData
{
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Database manager for MySQL
/// </summary>
public MySQLManager database;
private string m_agentsTableName;
private string m_usersTableName;
private string m_userFriendsTableName;
/// <summary>
/// Loads and initialises the MySQL storage plugin
/// </summary>
public void Initialise()
{
// Load from an INI file connection details
// TODO: move this to XML?
IniFile GridDataMySqlFile = new IniFile("mysql_connection.ini");
string settingHostname = GridDataMySqlFile.ParseFileReadValue("hostname");
string settingDatabase = GridDataMySqlFile.ParseFileReadValue("database");
string settingUsername = GridDataMySqlFile.ParseFileReadValue("username");
string settingPassword = GridDataMySqlFile.ParseFileReadValue("password");
string settingPooling = GridDataMySqlFile.ParseFileReadValue("pooling");
string settingPort = GridDataMySqlFile.ParseFileReadValue("port");
// TODO: move this to XML? Yes, PLEASE!
IniFile iniFile = new IniFile("mysql_connection.ini");
string settingHostname = iniFile.ParseFileReadValue("hostname");
string settingDatabase = iniFile.ParseFileReadValue("database");
string settingUsername = iniFile.ParseFileReadValue("username");
string settingPassword = iniFile.ParseFileReadValue("password");
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 =
new MySQLManager(settingHostname, settingDatabase, settingUsername, settingPassword, settingPooling,
@ -75,14 +100,14 @@ namespace OpenSim.Framework.Data.MySQL
{
Dictionary<string, string> tableList = new Dictionary<string, string>();
tableList["agents"] = null;
tableList["users"] = null;
tableList["userfriends"] = null;
tableList[m_agentsTableName] = null;
tableList[m_usersTableName] = null;
tableList[m_userFriendsTableName] = null;
database.GetTableVersion(tableList);
UpgradeAgentsTable(tableList["agents"]);
UpgradeUsersTable(tableList["users"]);
UpgradeFriendsTable(tableList["userfriends"]);
UpgradeAgentsTable(tableList[m_agentsTableName]);
UpgradeUsersTable(tableList[m_usersTableName]);
UpgradeFriendsTable(tableList[m_userFriendsTableName]);
}
@ -119,7 +144,7 @@ namespace OpenSim.Framework.Data.MySQL
database.ExecuteResourceSql("UpgradeUsersTableToVersion2.sql");
return;
}
//MainLog.Instance.Verbose("DB","DBVers:" + oldVersion);
//m_log.Info("[DB]: DBVers:" + oldVersion);
}
/// <summary>
@ -151,7 +176,7 @@ namespace OpenSim.Framework.Data.MySQL
param["?second"] = last;
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();
UserProfileData row = database.readUserRow(reader);
@ -164,7 +189,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
return null;
}
}
@ -187,7 +212,7 @@ namespace OpenSim.Framework.Data.MySQL
{
IDbCommand adder =
database.Query(
"INSERT INTO `userfriends` " +
"INSERT INTO `" + m_userFriendsTableName + "` " +
"(`ownerID`,`friendID`,`friendPerms`,`datetimestamp`) " +
"VALUES " +
"(?ownerID,?friendID,?friendPerms,?datetimestamp)",
@ -196,7 +221,7 @@ namespace OpenSim.Framework.Data.MySQL
adder =
database.Query(
"INSERT INTO `userfriends` " +
"INSERT INTO `" + m_userFriendsTableName + "` " +
"(`ownerID`,`friendID`,`friendPerms`,`datetimestamp`) " +
"VALUES " +
"(?friendID,?ownerID,?friendPerms,?datetimestamp)",
@ -208,7 +233,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
return;
}
}
@ -226,15 +251,13 @@ namespace OpenSim.Framework.Data.MySQL
{
IDbCommand updater =
database.Query(
"delete from userfriends " +
"where ownerID = ?ownerID and friendID = ?friendID",
"delete from " + m_userFriendsTableName + " where ownerID = ?ownerID and friendID = ?friendID",
param);
updater.ExecuteNonQuery();
updater =
database.Query(
"delete from userfriends " +
"where ownerID = ?friendID and friendID = ?ownerID",
"delete from " + m_userFriendsTableName + " where ownerID = ?friendID and friendID = ?ownerID",
param);
updater.ExecuteNonQuery();
@ -243,7 +266,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
return;
}
}
@ -261,7 +284,7 @@ namespace OpenSim.Framework.Data.MySQL
{
IDbCommand updater =
database.Query(
"update userfriends " +
"update " + m_userFriendsTableName +
" SET friendPerms = ?friendPerms " +
"where ownerID = ?ownerID and friendID = ?friendID",
param);
@ -272,7 +295,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
return;
}
}
@ -292,7 +315,7 @@ namespace OpenSim.Framework.Data.MySQL
//Left Join userfriends to itself
IDbCommand result =
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",
param);
IDataReader reader = result.ExecuteReader();
@ -317,7 +340,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
return Lfli;
}
@ -328,13 +351,9 @@ namespace OpenSim.Framework.Data.MySQL
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)
{
@ -347,15 +366,15 @@ namespace OpenSim.Framework.Data.MySQL
if (querysplit.Length == 2)
{
Dictionary<string, string> param = new Dictionary<string, string>();
param["?first"] = objAlphaNumericPattern.Replace(querysplit[0], "") + "%";
param["?second"] = objAlphaNumericPattern.Replace(querysplit[1], "") + "%";
param["?first"] = objAlphaNumericPattern.Replace(querysplit[0], String.Empty) + "%";
param["?second"] = objAlphaNumericPattern.Replace(querysplit[1], String.Empty) + "%";
try
{
lock (database)
{
IDbCommand result =
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);
IDataReader reader = result.ExecuteReader();
@ -375,7 +394,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
return returnlist;
}
}
@ -386,11 +405,11 @@ namespace OpenSim.Framework.Data.MySQL
lock (database)
{
Dictionary<string, string> param = new Dictionary<string, string>();
param["?first"] = objAlphaNumericPattern.Replace(querysplit[0], "") + "%";
param["?first"] = objAlphaNumericPattern.Replace(querysplit[0], String.Empty) + "%";
IDbCommand result =
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);
IDataReader reader = result.ExecuteReader();
@ -410,7 +429,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
return returnlist;
}
}
@ -427,7 +446,7 @@ namespace OpenSim.Framework.Data.MySQL
Dictionary<string, string> param = new Dictionary<string, string>();
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();
UserProfileData row = database.readUserRow(reader);
@ -441,7 +460,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
return null;
}
}
@ -499,6 +518,38 @@ namespace OpenSim.Framework.Data.MySQL
{
UserProfileData profile = GetUserByName(user, last);
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>
@ -515,7 +566,7 @@ namespace OpenSim.Framework.Data.MySQL
Dictionary<string, string> param = new Dictionary<string, string>();
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();
UserAgentData row = database.readAgentRow(reader);
@ -529,7 +580,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e)
{
database.Reconnect();
MainLog.Instance.Error(e.ToString());
m_log.Error(e.ToString());
return null;
}
}
@ -557,7 +608,7 @@ namespace OpenSim.Framework.Data.MySQL
catch (Exception e)
{
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.Runtime.InteropServices;
@ -10,7 +38,7 @@ using System.Runtime.InteropServices;
[assembly : AssemblyConfiguration("")]
[assembly : AssemblyCompany("")]
[assembly : AssemblyProduct("OpenSim.Framework.Data.MySQL")]
[assembly : AssemblyCopyright("Copyright © 2007")]
[assembly : AssemblyCopyright("Copyright © OpenSimulator.org Developers 2007-2008")]
[assembly : AssemblyTrademark("")]
[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` (
`ownerID` VARCHAR(37) NOT NULL,
`friendID` VARCHAR(47) NOT NULL,
`friendID` VARCHAR(37) NOT NULL,
`friendPerms` INT NOT NULL,
`datetimestamp` INT NOT NULL,
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.Runtime.InteropServices;
@ -10,7 +38,7 @@ using System.Runtime.InteropServices;
[assembly : AssemblyConfiguration("")]
[assembly : AssemblyCompany("")]
[assembly : AssemblyProduct("OpenSim.Framework.Data.SQLite")]
[assembly : AssemblyCopyright("Copyright © 2007")]
[assembly : AssemblyCopyright("Copyright © OpenSimulator.org Developers 2007-2008")]
[assembly : AssemblyTrademark("")]
[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
// by using the '*' as shown below:
[assembly : AssemblyVersion("0.4.0.0")]
[assembly : AssemblyVersion("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>
public class SQLiteAssetData : SQLiteBase, IAssetProvider
{
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// The database manager
/// </summary>
/// <summary>
/// Artificial constructor called upon plugin load
/// </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 DataSet ds;
private SqliteDataAdapter da;
private SqliteConnection m_conn;
public void Initialise(string dbfile, string dbname)
{
SqliteConnection conn = new SqliteConnection("URI=file:" + dbfile + ",version=3");
TestTables(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());
}
}
m_conn = new SqliteConnection("URI=file:" + dbfile + ",version=3");
m_conn.Open();
TestTables(m_conn);
return;
}
public AssetBase FetchAsset(LLUUID uuid)
{
AssetBase asset = new AssetBase();
DataRow row = ds.Tables["assets"].Rows.Find(Util.ToRawUuidString(uuid));
if (row != null)
using (SqliteCommand cmd = new SqliteCommand(SelectAssetSQL, m_conn))
{
return buildAsset(row);
cmd.Parameters.Add(new SqliteParameter(":UUID", Util.ToRawUuidString(uuid)));
using (IDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
AssetBase asset = buildAsset(reader);
reader.Close();
return asset;
}
else
{
reader.Close();
return null;
}
}
}
}
public void CreateAsset(AssetBase asset)
{
// no difference for now
m_log.Info("[SQLITE]: Creating Asset " + Util.ToRawUuidString(asset.FullID));
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)
{
LogAssetLoad(asset);
DataTable assets = ds.Tables["assets"];
lock (ds)
using (SqliteCommand cmd = new SqliteCommand(UpdateAssetSQL, m_conn))
{
DataRow row = assets.Rows.Find(Util.ToRawUuidString(asset.FullID));
if (row == null)
{
row = assets.NewRow();
fillAssetRow(row, asset);
assets.Rows.Add(row);
}
else
{
fillAssetRow(row, asset);
}
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();
}
}
// rex new function for "replace assets" functionality
@ -141,7 +156,7 @@ namespace OpenSim.Framework.Data.SQLite
string temporary = asset.Temporary ? "Temporary" : "Stored";
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)",
asset.FullID, asset.Name, asset.Description, asset.Type,
asset.InvType, temporary, local, asset.Data.Length));
@ -149,8 +164,23 @@ namespace OpenSim.Framework.Data.SQLite
public bool ExistsAsset(LLUUID uuid)
{
DataRow row = ds.Tables["assets"].Rows.Find(Util.ToRawUuidString(uuid));
return (row != null);
using (SqliteCommand cmd = new SqliteCommand(SelectAssetSQL, m_conn))
{
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
@ -181,24 +211,22 @@ namespace OpenSim.Framework.Data.SQLite
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));
if (row != null)
{
row.Delete();
}
cmd.Parameters.Add(new SqliteParameter(":UUID", Util.ToRawUuidString(uuid)));
cmd.ExecuteNonQuery();
}
}
public void CommitAssets() // force a sync to the database
{
MainLog.Instance.Verbose("SQLITE", "Attempting commit");
lock (ds)
{
da.Update(ds, "assets");
ds.AcceptChanges();
}
m_log.Info("[SQLITE]: Attempting commit");
// lock (ds)
// {
// da.Update(ds, "assets");
// 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
// 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)
{
string createAssets = defineTable(createAssetsTable());
SqliteCommand pcmd = new SqliteCommand(createAssets, conn);
conn.Open();
pcmd.ExecuteNonQuery();
conn.Close();
}
private bool TestTables(SqliteConnection conn)
@ -342,7 +354,7 @@ namespace OpenSim.Framework.Data.SQLite
}
catch (SqliteSyntaxException)
{
MainLog.Instance.Verbose("SQLITE", "SQLite Database doesn't exist... creating");
m_log.Info("[SQLITE]: SQLite Database doesn't exist... creating");
InitDB(conn);
}
return true;

View File

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

View File

@ -13,7 +13,7 @@
* 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
* 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
@ -38,6 +38,8 @@ namespace OpenSim.Framework.Data.SQLite
{
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 invFoldersSelect = "select * from inventoryfolders";
@ -45,6 +47,11 @@ namespace OpenSim.Framework.Data.SQLite
private SqliteDataAdapter invItemsDa;
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>
/// Initialises the interface
/// </summary>
@ -57,7 +64,7 @@ namespace OpenSim.Framework.Data.SQLite
{
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);
TestTables(conn);
@ -74,12 +81,12 @@ namespace OpenSim.Framework.Data.SQLite
ds.Tables.Add(createInventoryFoldersTable());
invFoldersDa.Fill(ds.Tables["inventoryfolders"]);
setupFoldersCommands(invFoldersDa, conn);
MainLog.Instance.Verbose("DATASTORE", "Populated Intentory Folders Definitions");
m_log.Info("[DATASTORE]: Populated Intentory Folders Definitions");
ds.Tables.Add(createInventoryItemsTable());
invItemsDa.Fill(ds.Tables["inventoryitems"]);
setupItemsCommands(invItemsDa, conn);
MainLog.Instance.Verbose("DATASTORE", "Populated Intentory Items Definitions");
m_log.Info("[DATASTORE]: Populated Intentory Items Definitions");
ds.AcceptChanges();
}
@ -123,6 +130,8 @@ namespace OpenSim.Framework.Data.SQLite
}
private void addFolder(InventoryFolderBase folder)
{
lock (InventoryLock)
{
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
@ -140,8 +149,11 @@ namespace OpenSim.Framework.Data.SQLite
invFoldersDa.Update(ds, "inventoryfolders");
}
}
private void moveFolder(InventoryFolderBase folder)
{
lock (InventoryLock)
{
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
@ -159,8 +171,11 @@ namespace OpenSim.Framework.Data.SQLite
invFoldersDa.Update(ds, "inventoryfolders");
}
}
private void addItem(InventoryItemBase item)
{
lock (InventoryLock)
{
DataTable inventoryItemTable = ds.Tables["inventoryitems"];
@ -177,6 +192,7 @@ namespace OpenSim.Framework.Data.SQLite
}
invItemsDa.Update(ds, "inventoryitems");
}
}
public void Shutdown()
{
@ -221,6 +237,8 @@ namespace OpenSim.Framework.Data.SQLite
/// <param name="folderID">The UUID of the target folder</param>
/// <returns>A List of InventoryItemBase items</returns>
public List<InventoryItemBase> getInventoryInFolder(LLUUID folderID)
{
lock (InventoryLock)
{
List<InventoryItemBase> retval = new List<InventoryItemBase>();
DataTable inventoryItemTable = ds.Tables["inventoryitems"];
@ -233,6 +251,7 @@ namespace OpenSim.Framework.Data.SQLite
return retval;
}
}
/// <summary>
/// Returns a list of the root folders within a users inventory
@ -246,6 +265,8 @@ namespace OpenSim.Framework.Data.SQLite
// see InventoryItemBase.getUserRootFolder
public InventoryFolderBase getUserRootFolder(LLUUID user)
{
lock (InventoryLock)
{
List<InventoryFolderBase> folders = new List<InventoryFolderBase>();
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
@ -269,6 +290,7 @@ namespace OpenSim.Framework.Data.SQLite
return null;
}
}
/// <summary>
/// Append a list of all the child folders of a parent folder
@ -276,6 +298,8 @@ namespace OpenSim.Framework.Data.SQLite
/// <param name="folders">list where folders will be appended</param>
/// <param name="parentID">ID of parent</param>
protected void getInventoryFolders(ref List<InventoryFolderBase> folders, LLUUID parentID)
{
lock (InventoryLock)
{
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
string selectExp = "parentID = '" + Util.ToRawUuidString(parentID) + "'";
@ -285,6 +309,7 @@ namespace OpenSim.Framework.Data.SQLite
folders.Add(buildFolder(row));
}
}
}
/// <summary>
/// Returns a list of inventory folders contained in the folder 'parentID'
@ -320,6 +345,8 @@ namespace OpenSim.Framework.Data.SQLite
/// <param name="item">The UUID of the item to be returned</param>
/// <returns>A class containing item information</returns>
public InventoryItemBase getInventoryItem(LLUUID item)
{
lock (InventoryLock)
{
DataRow row = ds.Tables["inventoryitems"].Rows.Find(Util.ToRawUuidString(item));
if (row != null)
@ -331,6 +358,7 @@ namespace OpenSim.Framework.Data.SQLite
return null;
}
}
}
/// <summary>
/// Returns a specified inventory folder by its UUID
@ -344,7 +372,8 @@ namespace OpenSim.Framework.Data.SQLite
// better to leave multi region at this point. It does mean
// that you don't get to see system textures why creating
// clothes and the like. :(
lock (InventoryLock)
{
DataRow row = ds.Tables["inventoryfolders"].Rows.Find(Util.ToRawUuidString(folder));
if (row != null)
{
@ -355,6 +384,7 @@ namespace OpenSim.Framework.Data.SQLite
return null;
}
}
}
/// <summary>
/// Creates a new inventory item based on item
@ -379,6 +409,8 @@ namespace OpenSim.Framework.Data.SQLite
/// </summary>
/// <param name="item"></param>
public void deleteInventoryItem(LLUUID itemID)
{
lock (InventoryLock)
{
DataTable inventoryItemTable = ds.Tables["inventoryitems"];
@ -390,7 +422,7 @@ namespace OpenSim.Framework.Data.SQLite
invItemsDa.Update(ds, "inventoryitems");
}
}
/// <summary>
/// Delete all items in the specified folder
@ -440,6 +472,8 @@ namespace OpenSim.Framework.Data.SQLite
/// </remarks>
/// <param name="item"></param>
public void deleteInventoryFolder(LLUUID folderID)
{
lock (InventoryLock)
{
List<InventoryFolderBase> subFolders = getFolderHierarchy(Util.ToRawUuidString(folderID));
@ -467,6 +501,7 @@ namespace OpenSim.Framework.Data.SQLite
invFoldersDa.Update(ds, "inventoryfolders");
}
}
/***********************************************************************
*
@ -514,6 +549,8 @@ namespace OpenSim.Framework.Data.SQLite
}
private void setupItemsCommands(SqliteDataAdapter da, SqliteConnection conn)
{
lock (InventoryLock)
{
da.InsertCommand = createInsertCommand("inventoryitems", ds.Tables["inventoryitems"]);
da.InsertCommand.Connection = conn;
@ -526,8 +563,11 @@ namespace OpenSim.Framework.Data.SQLite
delete.Connection = conn;
da.DeleteCommand = delete;
}
}
private void setupFoldersCommands(SqliteDataAdapter da, SqliteConnection conn)
{
lock (InventoryLock)
{
da.InsertCommand = createInsertCommand("inventoryfolders", ds.Tables["inventoryfolders"]);
da.InsertCommand.Connection = conn;
@ -540,6 +580,7 @@ namespace OpenSim.Framework.Data.SQLite
delete.Connection = conn;
da.DeleteCommand = delete;
}
}
private InventoryFolderBase buildFolder(DataRow row)
{
@ -576,6 +617,8 @@ namespace OpenSim.Framework.Data.SQLite
**********************************************************************/
private void InitDB(SqliteConnection conn)
{
lock (InventoryLock)
{
string createInventoryItems = defineTable(createInventoryItemsTable());
string createInventoryFolders = defineTable(createInventoryFoldersTable());
@ -587,6 +630,7 @@ namespace OpenSim.Framework.Data.SQLite
scmd.ExecuteNonQuery();
conn.Close();
}
}
private bool TestTables(SqliteConnection conn)
{
@ -603,7 +647,7 @@ namespace OpenSim.Framework.Data.SQLite
}
catch (SqliteSyntaxException)
{
MainLog.Instance.Verbose("DATASTORE", "SQLite Database doesn't exist... creating");
m_log.Info("[DATASTORE]: SQLite Database doesn't exist... creating");
InitDB(conn);
}
@ -614,7 +658,7 @@ namespace OpenSim.Framework.Data.SQLite
{
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;
}
}
@ -622,7 +666,7 @@ namespace OpenSim.Framework.Data.SQLite
{
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;
}
}

View File

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

File diff suppressed because it is too large Load Diff

View File

@ -39,15 +39,24 @@ namespace OpenSim.Framework.Data.SQLite
/// </summary>
public class SQLiteUserData : SQLiteBase, IUserData
{
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// The database manager
/// </summary>
/// <summary>
/// Artificial constructor called upon plugin load
/// </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 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 SqliteDataAdapter da;
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
g_conn = conn;
g_conn.Open();
ds = new DataSet();
da = new SqliteDataAdapter(new SqliteCommand(userSelect, conn));
@ -81,7 +91,7 @@ namespace OpenSim.Framework.Data.SQLite
}
catch (SqliteSyntaxException)
{
MainLog.Instance.Verbose("SQLITE", "userfriends table not found, creating.... ");
m_log.Info("[SQLITE]: userfriends table not found, creating.... ");
InitDB(conn);
daf.Fill(ds.Tables["userfriends"]);
}
@ -169,126 +179,77 @@ namespace OpenSim.Framework.Data.SQLite
public void AddNewUserFriend(LLUUID friendlistowner, LLUUID friend, uint perms)
{
//do stuff;
MainLog.Instance.Verbose("FRIEND", "Stub AddNewUserFriend called");
DataTable friends = ds.Tables["userfriends"];
DataTable ua = ds.Tables["userfriends"];
lock (ds)
string InsertFriends = "insert into userfriends(ownerID, friendID, friendPerms) values(:ownerID, :friendID, :perms)";
using (SqliteCommand cmd = new SqliteCommand(InsertFriends, g_conn))
{
DataRow row = friends.NewRow();
fillFriendRow(row, friendlistowner.UUID.ToString(),friend.UUID.ToString(),perms);
friends.Rows.Add(row);
row = friends.NewRow();
fillFriendRow(row, friend.UUID.ToString(), friendlistowner.UUID.ToString(), perms);
friends.Rows.Add(row);
MainLog.Instance.Verbose("SQLITE",
"Adding Friend: " + ds.Tables["userfriends"].Rows.Count + " friends stored");
// save changes off to disk
daf.Update(ds, "userfriends");
cmd.Parameters.Add(new SqliteParameter(":ownerID", friendlistowner.UUID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":friendID", friend.UUID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":perms", perms));
cmd.ExecuteNonQuery();
}
using (SqliteCommand cmd = new SqliteCommand(InsertFriends, g_conn))
{
cmd.Parameters.Add(new SqliteParameter(":ownerID", friend.UUID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":friendID", friendlistowner.UUID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":perms", perms));
cmd.ExecuteNonQuery();
}
}
public void RemoveUserFriend(LLUUID friendlistowner, LLUUID friend)
{
DataTable ua = ds.Tables["userfriends"];
string select = "`ownerID` ='" + friendlistowner.UUID.ToString() + "' and `friendID` ='" + friend.UUID.ToString() + "'";
lock (ds)
string DeletePerms = "delete from friendlist where (ownerID=:ownerID and friendID=:friendID) or (ownerID=:friendID and friendID=:ownerID)";
using (SqliteCommand cmd = new SqliteCommand(DeletePerms, g_conn))
{
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();
cmd.Parameters.Add(new SqliteParameter(":ownerID", friendlistowner.UUID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":friendID", friend.UUID.ToString()));
cmd.ExecuteNonQuery();
}
}
}
}
}
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)
{
DataTable ua = ds.Tables["userfriends"];
string select = "a.ownerID ='" + friendlistowner.UUID.ToString() + "' and b.friendID ='" + friend.UUID.ToString() + "'";
lock (ds)
string UpdatePerms = "update friendlist set perms=:perms where ownerID=:ownerID and friendID=:friendID";
using (SqliteCommand cmd = new SqliteCommand(UpdatePerms, g_conn))
{
DataRow[] rows = ds.Tables["userfriends"].Select(select);
if ( rows != null)
{
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");
cmd.Parameters.Add(new SqliteParameter(":perms", perms));
cmd.Parameters.Add(new SqliteParameter(":ownerID", friendlistowner.UUID.ToString()));
cmd.Parameters.Add(new SqliteParameter(":friendID", friend.UUID.ToString()));
cmd.ExecuteNonQuery();
}
}
}
MainLog.Instance.Verbose("FRIEND", "Stub UpdateUserFriendPerms called");
}
public List<FriendListItem> GetUserFriendList(LLUUID friendlistowner)
{
List<FriendListItem> returnlist = new List<FriendListItem>();
string select = "ownerID = '" + friendlistowner.UUID.ToString() + "' and fownerID = friendID and ffriendID = ownerID";
lock (ds)
using (SqliteCommand cmd = new SqliteCommand(SelectFriendsByUUID, g_conn))
{
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())
{
while (reader.Read())
{
FriendListItem user = new FriendListItem();
DataRow row = rows[i];
user.FriendListOwner = new LLUUID((string)row[0]);
user.Friend = new LLUUID((string)row[1]);
user.FriendPerms = Convert.ToUInt32(row[2]);
user.FriendListOwnerPerms = Convert.ToUInt32(row[3]);
user.FriendListOwner = friendlistowner;
user.Friend = new LLUUID((string)reader[0]);
user.FriendPerms = Convert.ToUInt32(reader[1]);
user.FriendListOwnerPerms = Convert.ToUInt32(reader[2]);
returnlist.Add(user);
}
reader.Close();
}
}
catch (Exception ex)
{
m_log.Error("[USER]: Exception getting friends list for user: " + ex.ToString());
}
}
return returnlist;
}
@ -299,13 +260,9 @@ namespace OpenSim.Framework.Data.SQLite
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)
{
@ -314,41 +271,43 @@ namespace OpenSim.Framework.Data.SQLite
querysplit = query.Split(' ');
if (querysplit.Length == 2)
{
string select = "username like '" + querysplit[0] + "%' and surname like '" + querysplit[1] + "%'";
lock (ds)
using (SqliteCommand cmd = new SqliteCommand(AvatarPickerAndSQL, g_conn))
{
DataRow[] rows = ds.Tables["users"].Select(select);
if (rows.Length > 0)
cmd.Parameters.Add(new SqliteParameter(":username", querysplit[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();
DataRow row = rows[i];
user.AvatarID = new LLUUID((string) row["UUID"]);
user.firstName = (string) row["username"];
user.lastName = (string) row["surname"];
user.AvatarID = new LLUUID((string) reader["UUID"]);
user.firstName = (string) reader["username"];
user.lastName = (string) reader["surname"];
returnlist.Add(user);
}
reader.Close();
}
}
}
else if (querysplit.Length == 1)
{
string select = "username like '" + querysplit[0] + "%' OR surname like '" + querysplit[0] + "%'";
lock (ds)
using (SqliteCommand cmd = new SqliteCommand(AvatarPickerOrSQL, g_conn))
{
DataRow[] rows = ds.Tables["users"].Select(select);
if (rows.Length > 0)
cmd.Parameters.Add(new SqliteParameter(":username", querysplit[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();
DataRow row = rows[i];
user.AvatarID = new LLUUID((string) row[0]);
user.firstName = (string) row[1];
user.lastName = (string) row[2];
user.AvatarID = new LLUUID((string) reader["UUID"]);
user.firstName = (string) reader["username"];
user.lastName = (string) reader["surname"];
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>
/// Creates a new user profile
/// </summary>
@ -419,6 +401,7 @@ namespace OpenSim.Framework.Data.SQLite
else
{
fillUserRow(row, user);
}
// This is why we're getting the 'logins never log-off'.. because It isn't clearing the
// 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");
// save changes off to disk
da.Update(ds, "users");
@ -677,7 +660,7 @@ namespace OpenSim.Framework.Data.SQLite
{
if (row[col] == null)
{
row[col] = "";
row[col] = String.Empty;
}
}
}
@ -718,7 +701,7 @@ namespace OpenSim.Framework.Data.SQLite
{
if (row[col] == null)
{
row[col] = "";
row[col] = String.Empty;
}
}
}
@ -821,7 +804,7 @@ namespace OpenSim.Framework.Data.SQLite
}
catch (System.Exception)
{
MainLog.Instance.Verbose("USERS", "users table already exists");
m_log.Info("[USERS]: users table already exists");
}
try
@ -830,7 +813,7 @@ namespace OpenSim.Framework.Data.SQLite
}
catch (System.Exception)
{
MainLog.Instance.Verbose("USERS", "userfriends table already exists");
m_log.Info("[USERS]: userfriends table already exists");
}
conn.Close();
@ -853,7 +836,7 @@ namespace OpenSim.Framework.Data.SQLite
}
catch (SqliteSyntaxException)
{
MainLog.Instance.Verbose("DATASTORE", "SQLite Database doesn't exist... creating");
m_log.Info("[DATASTORE]: SQLite Database doesn't exist... creating");
InitDB(conn);
}
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>
RegionProfileData[] GetProfilesInRange(uint Xmin, uint Ymin, uint Xmax, uint Ymax);
List<AvatarPickerAvatar> GeneratePickerResults(LLUUID queryID, string query);
/// <summary>
/// Authenticates a sim by use of its recv key.
/// 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.Runtime.InteropServices;
@ -10,7 +38,7 @@ using System.Runtime.InteropServices;
[assembly : AssemblyConfiguration("")]
[assembly : AssemblyCompany("")]
[assembly : AssemblyProduct("OpenSim.Framework.Data")]
[assembly : AssemblyCopyright("Copyright © 2007")]
[assembly : AssemblyCopyright("Copyright © OpenSimulator.org Developers 2007-2008")]
[assembly : AssemblyTrademark("")]
[assembly : AssemblyCulture("")]

View File

@ -41,7 +41,7 @@ namespace OpenSim.Framework.Data
/// <summary>
/// The name of the region
/// </summary>
public string regionName = "";
public string regionName = String.Empty;
/// <summary>
/// A 64-bit number combining map position into a (mostly) unique ID
@ -65,10 +65,10 @@ namespace OpenSim.Framework.Data
/// Authentication secrets
/// </summary>
/// <remarks>Not very secure, needs improvement.</remarks>
public string regionSendKey = "";
public string regionSendKey = String.Empty;
public string regionRecvKey = "";
public string regionSecret = "";
public string regionRecvKey = String.Empty;
public string regionSecret = String.Empty;
/// <summary>
/// Whether the region is online
@ -78,14 +78,14 @@ namespace OpenSim.Framework.Data
/// <summary>
/// Information about the server that the region is currently hosted on
/// </summary>
public string serverIP = "";
public string serverIP = String.Empty;
public uint serverPort;
public string serverURI = "";
public string serverURI = String.Empty;
public uint httpPort;
public uint remotingPort;
public string httpServerURI = "";
public string httpServerURI = String.Empty;
/// <summary>
/// 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
/// </summary>
/// <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>
/// Region Asset Details
/// </summary>
public string regionAssetURI = "";
public string regionAssetURI = String.Empty;
public string regionAssetSendKey = "";
public string regionAssetRecvKey = "";
public string regionAssetSendKey = String.Empty;
public string regionAssetRecvKey = String.Empty;
/// <summary>
/// Region Userserver Details
/// </summary>
public string regionUserURI = "";
public string regionUserURI = String.Empty;
public string regionUserSendKey = "";
public string regionUserRecvKey = "";
public string regionUserSendKey = String.Empty;
public string regionUserRecvKey = String.Empty;
/// <summary>
/// Region Map Texture Asset
/// </summary>
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>
/// Get Sim profile data from grid server when in grid mode
/// </summary>
@ -151,7 +163,7 @@ namespace OpenSim.Framework.Data
RegionProfileData simData = new RegionProfileData();
simData.regionLocX = Convert.ToUInt32((string) responseData["region_locx"]);
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.serverPort = Convert.ToUInt32((string) responseData["sim_port"]);
simData.httpPort = Convert.ToUInt32((string) responseData["http_port"]);
@ -164,7 +176,15 @@ namespace OpenSim.Framework.Data
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)
{
Hashtable requestData = new Hashtable();
@ -185,7 +205,7 @@ namespace OpenSim.Framework.Data
RegionProfileData simData = new RegionProfileData();
simData.regionLocX = Convert.ToUInt32((string) responseData["region_locx"]);
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.serverPort = Convert.ToUInt32((string) responseData["sim_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 reservationMaxY = 65536;
public string reservationName = "";
public string reservationCompany = "";
public string reservationName = System.String.Empty;
public string reservationCompany = System.String.Empty;
public bool status = true;
public string gridSendKey = "";
public string gridRecvKey = "";
public string gridSendKey = System.String.Empty;
public string gridRecvKey = System.String.Empty;
}
}

View File

@ -28,11 +28,14 @@
using System;
using System.IO;
using libsecondlife;
using OpenSim.Framework.Console;
namespace OpenSim.Framework
{
public class EstateSettings
{
private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Settings to this island
private float m_billableFactor;
@ -734,7 +737,7 @@ namespace OpenSim.Framework
}
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");
}
}
@ -756,106 +759,106 @@ namespace OpenSim.Framework
public void loadConfigurationOptions()
{
configMember.addConfigurationOption("billable_factor", ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, "",
configMember.addConfigurationOption("billable_factor", ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, String.Empty,
"0.0", true);
configMember.addConfigurationOption("estate_id", ConfigurationOption.ConfigurationTypes.TYPE_UINT32, "", "0",
configMember.addConfigurationOption("estate_id", ConfigurationOption.ConfigurationTypes.TYPE_UINT32, String.Empty, "0",
true);
configMember.addConfigurationOption("parent_estate_id", ConfigurationOption.ConfigurationTypes.TYPE_UINT32,
"", "0", true);
configMember.addConfigurationOption("max_agents", ConfigurationOption.ConfigurationTypes.TYPE_BYTE, "", "40",
String.Empty, "0", true);
configMember.addConfigurationOption("max_agents", ConfigurationOption.ConfigurationTypes.TYPE_BYTE, String.Empty, "40",
true);
configMember.addConfigurationOption("object_bonus_factor", ConfigurationOption.ConfigurationTypes.TYPE_FLOAT,
"", "1.0", true);
configMember.addConfigurationOption("redirect_grid_x", ConfigurationOption.ConfigurationTypes.TYPE_INT32, "",
String.Empty, "1.0", true);
configMember.addConfigurationOption("redirect_grid_x", ConfigurationOption.ConfigurationTypes.TYPE_INT32, String.Empty,
"0", true);
configMember.addConfigurationOption("redirect_grid_y", ConfigurationOption.ConfigurationTypes.TYPE_INT32, "",
configMember.addConfigurationOption("redirect_grid_y", ConfigurationOption.ConfigurationTypes.TYPE_INT32, String.Empty,
"0", true);
configMember.addConfigurationOption("region_flags", ConfigurationOption.ConfigurationTypes.TYPE_UINT32, "",
configMember.addConfigurationOption("region_flags", ConfigurationOption.ConfigurationTypes.TYPE_UINT32, String.Empty,
"0", true);
configMember.addConfigurationOption("sim_access", ConfigurationOption.ConfigurationTypes.TYPE_BYTE, "", "21",
configMember.addConfigurationOption("sim_access", ConfigurationOption.ConfigurationTypes.TYPE_BYTE, String.Empty, "21",
true);
configMember.addConfigurationOption("sun_hour", ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, "", "0",
configMember.addConfigurationOption("sun_hour", ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, String.Empty, "0",
true);
configMember.addConfigurationOption("terrain_raise_limit", ConfigurationOption.ConfigurationTypes.TYPE_FLOAT,
"", "0", true);
String.Empty, "0", true);
configMember.addConfigurationOption("terrain_lower_limit", ConfigurationOption.ConfigurationTypes.TYPE_FLOAT,
"", "0", true);
configMember.addConfigurationOption("use_fixed_sun", ConfigurationOption.ConfigurationTypes.TYPE_BOOLEAN, "",
String.Empty, "0", true);
configMember.addConfigurationOption("use_fixed_sun", ConfigurationOption.ConfigurationTypes.TYPE_BOOLEAN, String.Empty,
"false", true);
configMember.addConfigurationOption("price_per_meter", ConfigurationOption.ConfigurationTypes.TYPE_UINT32,
"", "1", true);
String.Empty, "1", true);
configMember.addConfigurationOption("region_water_height",
ConfigurationOption.ConfigurationTypes.TYPE_UINT16, "", "20", true);
ConfigurationOption.ConfigurationTypes.TYPE_UINT16, String.Empty, "20", true);
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);
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);
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);
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);
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,
"", "00000000-0000-0000-0000-000000000000", true);
String.Empty, "00000000-0000-0000-0000-000000000000", true);
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,
"", "00000000-0000-0000-0000-000000000000", true);
String.Empty, "00000000-0000-0000-0000-000000000000", true);
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",
ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, "", "10.0", true);
ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, String.Empty, "10.0", true);
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",
ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, "", "10.0", true);
ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, String.Empty, "10.0", true);
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",
ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, "", "60.0", true);
ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, String.Empty, "60.0", true);
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",
ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, "", "60.0", true);
ConfigurationOption.ConfigurationTypes.TYPE_FLOAT, String.Empty, "60.0", true);
configMember.addConfigurationOption("terrain_file",
ConfigurationOption.ConfigurationTypes.TYPE_STRING_NOT_EMPTY, "",
ConfigurationOption.ConfigurationTypes.TYPE_STRING_NOT_EMPTY, String.Empty,
"default.r32", true);
configMember.addConfigurationOption("terrain_multiplier", ConfigurationOption.ConfigurationTypes.TYPE_FLOAT,
"", "60.0", true);
configMember.addConfigurationOption("water_height", ConfigurationOption.ConfigurationTypes.TYPE_DOUBLE, "",
String.Empty, "60.0", true);
configMember.addConfigurationOption("water_height", ConfigurationOption.ConfigurationTypes.TYPE_DOUBLE, String.Empty,
"20.0", true);
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,
"", "00000000-0000-0000-0000-000000000000", true);
String.Empty, "00000000-0000-0000-0000-000000000000", true);
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,
"", "00000000-0000-0000-0000-000000000000", true);
String.Empty, "00000000-0000-0000-0000-000000000000", true);
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,
"", "00000000-0000-0000-0000-000000000000", true);
String.Empty, "00000000-0000-0000-0000-000000000000", true);
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,
"", "00000000-0000-0000-0000-000000000000", true);
String.Empty, "00000000-0000-0000-0000-000000000000", true);
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,
"", "00000000-0000-0000-0000-000000000000", true);
String.Empty, "00000000-0000-0000-0000-000000000000", true);
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
* 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
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
@ -26,23 +26,26 @@
*
*/
using System;
using OpenSim.Framework.Console;
namespace OpenSim.Framework
{
public class GridConfig
{
public string GridOwner = "";
public string DefaultAssetServer = "";
public string AssetSendKey = "";
public string AssetRecvKey = "";
public string GridOwner = String.Empty;
public string DefaultAssetServer = String.Empty;
public string AssetSendKey = String.Empty;
public string AssetRecvKey = String.Empty;
public string DefaultUserServer = "";
public string UserSendKey = "";
public string UserRecvKey = "";
public string DefaultUserServer = String.Empty;
public string UserSendKey = String.Empty;
public string UserRecvKey = String.Empty;
public string SimSendKey = "";
public string SimRecvKey = "";
public string SimSendKey = String.Empty;
public string SimRecvKey = String.Empty;
public string DatabaseProvider = "";
public string DatabaseProvider = String.Empty;
public static uint DefaultHttpPort = 8001;

View File

@ -13,7 +13,7 @@
* 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
* 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

View File

@ -50,7 +50,17 @@ namespace OpenSim.Framework
// could change to delegate?
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);
/// <summary>
/// Call back made when an asset server could not retrieve a requested asset
/// </summary>
/// <param name="assetID"></param>
void AssetNotFound(LLUUID assetID);
}

View File

@ -65,7 +65,7 @@ namespace OpenSim.Framework
Task = 4,
Texture = 5,
Asset = 6,
Unknown = 7,
Unknown = 7, // Also doubles as 'do not throttle'
Back = 8
}
@ -234,6 +234,11 @@ namespace OpenSim.Framework
uint EveryoneMask, uint GroupMask, uint NextOwnerMask, uint ItemFlags,
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(
float height, float seconds, byte size, byte action, float north, float west, float south, float east,
IClientAPI remoteClient);
@ -380,7 +385,10 @@ namespace OpenSim.Framework
IClientAPI remoteClient, LLUUID folderID, LLUUID itemID, int length, string newName);
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);
@ -403,7 +411,14 @@ namespace OpenSim.Framework
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 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
public delegate void RezSingleAttachmentFromInv(IClientAPI remoteClient, LLUUID itemID, LLUUID ownerID,
uint itemFlags, byte attachPoint);
@ -433,6 +448,8 @@ namespace OpenSim.Framework
event ModifyTerrain OnModifyTerrain;
event SetAppearance OnSetAppearance;
event AvatarNowWearing OnAvatarNowWearing;
event RezSingleAttachmentFromInv OnRezSingleAttachmentFromInv;
event ObjectAttach OnObjectAttach;
event StartAnim OnStartAnim;
event StopAnim OnStopAnim;
event LinkObjects OnLinkObjects;
@ -454,6 +471,10 @@ namespace OpenSim.Framework
event Action<IClientAPI> OnRequestAvatarsData;
event AddNewPrim OnAddPrim;
event FetchInventory OnAgentDataUpdateRequest;
event FetchInventory OnUserInfoRequest;
event TeleportLocationRequest OnSetStartLocationRequest;
event RequestGodlikePowers OnRequestGodlikePowers;
event GodKickUser OnGodKickUser;
@ -493,7 +514,8 @@ namespace OpenSim.Framework
event UpdateInventoryItem OnUpdateInventoryItem;
event CopyInventoryItem OnCopyInventoryItem;
event MoveInventoryItem OnMoveInventoryItem;
event RemoveInventoryItem OnRemoveInventoryItem; // rex
event RemoveInventoryFolder OnRemoveInventoryFolder;
event RemoveInventoryItem OnRemoveInventoryItem;
event UDPAssetUploadRequest OnAssetUploadRequest;
event XferReceive OnXferReceive;
event RequestXfer OnRequestXfer;
@ -523,6 +545,12 @@ namespace OpenSim.Framework
event FriendActionDelegate OnApproveFriendRequest;
event FriendActionDelegate OnDenyFriendRequest;
event FriendshipTermination OnTerminateFriendship;
event PacketStats OnPacketStats;
// Financial packets
event MoneyTransferRequest OnMoneyTransferRequest;
event MoneyBalanceRequest OnMoneyBalanceRequest;
event ReceiveRexClientScriptCmd OnReceiveRexClientScriptCmd; // rex
event ObjectClickAction OnObjectClickAction; // rex
@ -583,7 +611,7 @@ namespace OpenSim.Framework
void SendRegionTeleport(ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint, uint locationID,
uint flags, string capsURL);
void SendTeleportFailed();
void SendTeleportFailed(string reason);
void SendTeleportLocationStart();
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 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,
LLVector3 pos, uint flags, LLUUID objectID, LLUUID ownerID, string text, byte[] color,
uint parentID, byte[] particleSystem, LLQuaternion rotation, byte clickAction);
@ -625,6 +657,8 @@ namespace OpenSim.Framework
void SendXferPacket(ulong xferID, uint packet, byte[] data);
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 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);
@ -643,6 +677,8 @@ namespace OpenSim.Framework
void SendAvatarProperties(LLUUID avatarID, string aboutText, string bornOn, string charterMember, string flAbout,
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 SetDebug(int newDebug);

View File

@ -13,7 +13,7 @@
* 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
* 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

View File

@ -44,13 +44,15 @@ namespace OpenSim.Framework
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 ChildAgentUpdate(ulong regionHandle, ChildAgentDataUpdate cAgentData);
public interface IRegionCommsListener
{
event ExpectUserDelegate OnExpectUser;
@ -64,5 +66,6 @@ namespace OpenSim.Framework
event CloseAgentConnection OnCloseAgentConnection;
event RegionUp OnRegionUp;
event ChildAgentUpdate OnChildAgentUpdate;
}
}

View File

@ -53,6 +53,8 @@ namespace OpenSim.Framework
void Restart(int seconds);
bool OtherRegionUp(RegionInfo thisRegion);
string GetSimulatorVersion();
RegionInfo RegionInfo { get; }
uint NextLocalId { get; }

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