Merge branch '0.6.7-post-fixes' into vehicles

0.6.8-post-fixes
Kitto Flora 2009-09-30 19:07:18 +02:00
commit 07df0e0ab0
93 changed files with 4396 additions and 729 deletions

View File

@ -207,7 +207,7 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory
// This plugin will only be enabled if the broader // This plugin will only be enabled if the broader
// REST plugin mechanism is enabled. // REST plugin mechanism is enabled.
Rest.Log.InfoFormat("{0} Plugin is initializing", MsgId); //Rest.Log.InfoFormat("{0} Plugin is initializing", MsgId);
base.Initialise(openSim); base.Initialise(openSim);
@ -216,7 +216,7 @@ namespace OpenSim.ApplicationPlugins.Rest.Inventory
if (!IsEnabled) if (!IsEnabled)
{ {
Rest.Log.WarnFormat("{0} Plugins are disabled", MsgId); //Rest.Log.WarnFormat("{0} Plugins are disabled", MsgId);
return; return;
} }

View File

@ -68,9 +68,10 @@ namespace OpenSim.ApplicationPlugins.Rest.Regions
base.Initialise(openSim); base.Initialise(openSim);
if (!IsEnabled) if (!IsEnabled)
{ {
m_log.WarnFormat("{0} Rest Plugins are disabled", MsgID); //m_log.WarnFormat("{0} Rest Plugins are disabled", MsgID);
return; return;
} }
m_log.InfoFormat("{0} REST region plugin enabled", MsgID); m_log.InfoFormat("{0} REST region plugin enabled", MsgID);
// add REST method handlers // add REST method handlers

View File

@ -216,7 +216,7 @@ namespace OpenSim.ApplicationPlugins.Rest
if (!_config.GetBoolean("enabled", false)) if (!_config.GetBoolean("enabled", false))
{ {
m_log.WarnFormat("{0} Rest Plugins are disabled", MsgID); //m_log.WarnFormat("{0} Rest Plugins are disabled", MsgID);
return; return;
} }

View File

@ -58,7 +58,7 @@ namespace OpenSim.Client.Linden
{ {
if (m_firstScene != null) if (m_firstScene != null)
{ {
return m_firstScene.CommsManager.GridService.RegionLoginsEnabled; return m_firstScene.SceneGridService.RegionLoginsEnabled;
} }
else else
{ {

View File

@ -62,7 +62,7 @@ namespace OpenSim.Client.Linden
{ {
if (m_firstScene != null) if (m_firstScene != null)
{ {
return m_firstScene.CommsManager.GridService.RegionLoginsEnabled; return m_firstScene.SceneGridService.RegionLoginsEnabled;
} }
else else
{ {

View File

@ -39,6 +39,8 @@ namespace OpenSim.Data
public string RegionName; public string RegionName;
public int posX; public int posX;
public int posY; public int posY;
public int sizeX;
public int sizeY;
public Dictionary<string, object> Data; public Dictionary<string, object> Data;
} }

View File

@ -39,7 +39,7 @@ namespace OpenSim.Data.MySQL
{ {
private string m_Realm; private string m_Realm;
private List<string> m_ColumnNames = null; private List<string> m_ColumnNames = null;
private int m_LastExpire = 0; // private int m_LastExpire = 0;
public MySqlRegionData(string connectionString, string realm) public MySqlRegionData(string connectionString, string realm)
: base(connectionString) : base(connectionString)
@ -77,7 +77,7 @@ namespace OpenSim.Data.MySQL
cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString()); cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
List<RegionData> ret = RunCommand(cmd); List<RegionData> ret = RunCommand(cmd);
if (ret == null) if (ret.Count == 0)
return null; return null;
return ret[0]; return ret[0];
@ -95,7 +95,7 @@ namespace OpenSim.Data.MySQL
cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString()); cmd.Parameters.AddWithValue("?scopeID", scopeID.ToString());
List<RegionData> ret = RunCommand(cmd); List<RegionData> ret = RunCommand(cmd);
if (ret == null) if (ret.Count == 0)
return null; return null;
return ret[0]; return ret[0];
@ -138,6 +138,8 @@ namespace OpenSim.Data.MySQL
ret.RegionName = result["regionName"].ToString(); ret.RegionName = result["regionName"].ToString();
ret.posX = Convert.ToInt32(result["locX"]); ret.posX = Convert.ToInt32(result["locX"]);
ret.posY = Convert.ToInt32(result["locY"]); ret.posY = Convert.ToInt32(result["locY"]);
ret.sizeX = Convert.ToInt32(result["sizeX"]);
ret.sizeY = Convert.ToInt32(result["sizeY"]);
if (m_ColumnNames == null) if (m_ColumnNames == null)
{ {
@ -170,10 +172,7 @@ namespace OpenSim.Data.MySQL
result.Close(); result.Close();
CloseReaderCommand(cmd); CloseReaderCommand(cmd);
if (retList.Count > 0) return retList;
return retList;
return null;
} }
public bool Store(RegionData data) public bool Store(RegionData data)
@ -188,21 +187,25 @@ namespace OpenSim.Data.MySQL
data.Data.Remove("posX"); data.Data.Remove("posX");
if (data.Data.ContainsKey("posY")) if (data.Data.ContainsKey("posY"))
data.Data.Remove("posY"); data.Data.Remove("posY");
if (data.Data.ContainsKey("sizeX"))
data.Data.Remove("sizeX");
if (data.Data.ContainsKey("sizeY"))
data.Data.Remove("sizeY");
if (data.Data.ContainsKey("locX"))
data.Data.Remove("locX");
if (data.Data.ContainsKey("locY"))
data.Data.Remove("locY");
string[] fields = new List<string>(data.Data.Keys).ToArray(); string[] fields = new List<string>(data.Data.Keys).ToArray();
MySqlCommand cmd = new MySqlCommand(); MySqlCommand cmd = new MySqlCommand();
string update = "update `"+m_Realm+"` set "; string update = "update `"+m_Realm+"` set locX=?posX, locY=?posY, sizeX=?sizeX, sizeY=?sizeY";
bool first = true;
foreach (string field in fields) foreach (string field in fields)
{ {
if (!first) update += ", ";
update += ", ";
update += "`" + field + "` = ?"+field; update += "`" + field + "` = ?"+field;
first = false;
cmd.Parameters.AddWithValue("?"+field, data.Data[field]); cmd.Parameters.AddWithValue("?"+field, data.Data[field]);
} }
@ -213,13 +216,18 @@ namespace OpenSim.Data.MySQL
cmd.CommandText = update; cmd.CommandText = update;
cmd.Parameters.AddWithValue("?regionID", data.RegionID.ToString()); cmd.Parameters.AddWithValue("?regionID", data.RegionID.ToString());
cmd.Parameters.AddWithValue("?regionName", data.RegionName);
cmd.Parameters.AddWithValue("?scopeID", data.ScopeID.ToString()); cmd.Parameters.AddWithValue("?scopeID", data.ScopeID.ToString());
cmd.Parameters.AddWithValue("?posX", data.posX.ToString());
cmd.Parameters.AddWithValue("?posY", data.posY.ToString());
cmd.Parameters.AddWithValue("?sizeX", data.sizeX.ToString());
cmd.Parameters.AddWithValue("?sizeY", data.sizeY.ToString());
if (ExecuteNonQuery(cmd) < 1) if (ExecuteNonQuery(cmd) < 1)
{ {
string insert = "insert into `" + m_Realm + "` (`uuid`, `ScopeID`, `" + string insert = "insert into `" + m_Realm + "` (`uuid`, `ScopeID`, `locX`, `locY`, `sizeX`, `sizeY`, `regionName`, `" +
String.Join("`, `", fields) + String.Join("`, `", fields) +
"`) values ( ?regionID, ?scopeID, ?" + String.Join(", ?", fields) + ")"; "`) values ( ?regionID, ?scopeID, ?posX, ?posY, ?sizeX, ?sizeY, ?regionName, ?" + String.Join(", ?", fields) + ")";
cmd.CommandText = insert; cmd.CommandText = insert;

View File

@ -39,7 +39,7 @@ namespace OpenSim.Data.MySQL
{ {
private string m_Realm; private string m_Realm;
private List<string> m_ColumnNames = null; private List<string> m_ColumnNames = null;
private int m_LastExpire = 0; // private int m_LastExpire = 0;
public MySqlUserAccountData(string connectionString, string realm) public MySqlUserAccountData(string connectionString, string realm)
: base(connectionString) : base(connectionString)

View File

@ -0,0 +1,6 @@
BEGIN;
ALTER TABLE regions add column sizeX integer not null default 0;
ALTER TABLE regions add column sizeY integer not null default 0;
COMMIT;

View File

@ -40,6 +40,7 @@ namespace OpenSim.Data.Null
public NullRegionData(string connectionString, string realm) public NullRegionData(string connectionString, string realm)
{ {
//Console.WriteLine("[XXX] NullRegionData constructor");
} }
public List<RegionData> Get(string regionName, UUID scopeID) public List<RegionData> Get(string regionName, UUID scopeID)
@ -100,10 +101,7 @@ namespace OpenSim.Data.Null
ret.Add(r); ret.Add(r);
} }
if (ret.Count > 0) return ret;
return ret;
return null;
} }
public bool Store(RegionData data) public bool Store(RegionData data)

View File

@ -98,7 +98,7 @@ namespace OpenSim.Framework.Communications
/// <param name="friendlistowner">The agent that who's friends list is being updated</param> /// <param name="friendlistowner">The agent that who's friends list is being updated</param>
/// <param name="friend">The agent that is getting or loosing permissions</param> /// <param name="friend">The agent that is getting or loosing permissions</param>
/// <param name="perms">A uint bit vector for set perms that the friend being added has; 0 = none, 1=This friend can see when they sign on, 2 = map, 4 edit objects </param> /// <param name="perms">A uint bit vector for set perms that the friend being added has; 0 = none, 1=This friend can see when they sign on, 2 = map, 4 edit objects </param>
void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms); void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms);
/// <summary> /// <summary>
/// Logs off a user on the user server /// Logs off a user on the user server
@ -137,9 +137,21 @@ namespace OpenSim.Framework.Communications
// But since Scenes only have IUserService references, I'm placing it here for now. // But since Scenes only have IUserService references, I'm placing it here for now.
bool VerifySession(UUID userID, UUID sessionID); bool VerifySession(UUID userID, UUID sessionID);
/// <summary>
/// Authenticate a user by their password.
/// </summary>
///
/// This is used by callers outside the login process that want to
/// verify a user who has given their password.
///
/// This should probably also be in IAuthentication but is here for the same reasons as VerifySession() is
///
/// <param name="userID"></param>
/// <param name="password"></param>
/// <returns></returns>
bool AuthenticateUserByPassword(UUID userID, string password);
// Temporary Hack until we move everything to the new service model // Temporary Hack until we move everything to the new service model
void SetInventoryService(IInventoryService invService); void SetInventoryService(IInventoryService invService);
} }
} }

View File

@ -1221,11 +1221,13 @@ namespace OpenSim.Framework.Communications.Services
{ {
return Util.CreateUnknownUserErrorResponse(); return Util.CreateUnknownUserErrorResponse();
} }
UUID.TryParse((string)requestData["session_id"], out guess_sid); UUID.TryParse((string)requestData["session_id"], out guess_sid);
if (guess_sid == UUID.Zero) if (guess_sid == UUID.Zero)
{ {
return Util.CreateUnknownUserErrorResponse(); return Util.CreateUnknownUserErrorResponse();
} }
if (m_userManager.VerifySession(guess_aid, guess_sid)) if (m_userManager.VerifySession(guess_aid, guess_sid))
{ {
authed = "TRUE"; authed = "TRUE";
@ -1243,6 +1245,5 @@ namespace OpenSim.Framework.Communications.Services
response.Value = responseData; response.Value = responseData;
return response; return response;
} }
} }
} }

View File

@ -149,6 +149,11 @@ namespace OpenSim.Framework.Communications.Tests
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public virtual bool AuthenticateUserByPassword(UUID userID, string password)
{
throw new NotImplementedException();
}
} }
} }
} }

View File

@ -44,7 +44,8 @@ namespace OpenSim.Framework.Communications
/// <summary> /// <summary>
/// Base class for user management (create, read, etc) /// Base class for user management (create, read, etc)
/// </summary> /// </summary>
public abstract class UserManagerBase : IUserService, IUserAdminService, IAvatarService, IMessagingService, IAuthentication public abstract class UserManagerBase
: IUserService, IUserAdminService, IAvatarService, IMessagingService, IAuthentication
{ {
private static readonly ILog m_log private static readonly ILog m_log
= LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
@ -93,9 +94,9 @@ namespace OpenSim.Framework.Communications
public void AddPlugin(string provider, string connect) public void AddPlugin(string provider, string connect)
{ {
m_plugins.AddRange(DataPluginFactory.LoadDataPlugins<IUserDataPlugin>(provider, connect)); m_plugins.AddRange(DataPluginFactory.LoadDataPlugins<IUserDataPlugin>(provider, connect));
} }
#region UserProfile #region UserProfile
public virtual void AddTemporaryUserProfile(UserProfileData userProfile) public virtual void AddTemporaryUserProfile(UserProfileData userProfile)
{ {
@ -891,7 +892,10 @@ namespace OpenSim.Framework.Communications
if (userProfile != null && userProfile.CurrentAgent != null) if (userProfile != null && userProfile.CurrentAgent != null)
{ {
m_log.DebugFormat("[USER AUTH]: Verifying session {0} for {1}; current session {2}", sessionID, userID, userProfile.CurrentAgent.SessionID); m_log.DebugFormat(
"[USER AUTH]: Verifying session {0} for {1}; current session {2}",
sessionID, userID, userProfile.CurrentAgent.SessionID);
if (userProfile.CurrentAgent.SessionID == sessionID) if (userProfile.CurrentAgent.SessionID == sessionID)
{ {
return true; return true;
@ -901,6 +905,26 @@ namespace OpenSim.Framework.Communications
return false; return false;
} }
public virtual bool AuthenticateUserByPassword(UUID userID, string password)
{
// m_log.DebugFormat("[USER AUTH]: Authenticating user {0} given password {1}", userID, password);
UserProfileData userProfile = GetUserProfile(userID);
if (null == userProfile)
return false;
string md5PasswordHash = Util.Md5Hash(Util.Md5Hash(password) + ":" + userProfile.PasswordSalt);
// m_log.DebugFormat(
// "[USER AUTH]: Submitted hash {0}, stored hash {1}", md5PasswordHash, userProfile.PasswordHash);
if (md5PasswordHash == userProfile.PasswordHash)
return true;
else
return false;
}
#endregion #endregion
} }
} }

View File

@ -197,8 +197,8 @@ namespace OpenSim.Framework.Console
string uri = "/ReadResponses/" + sessionID.ToString() + "/"; string uri = "/ReadResponses/" + sessionID.ToString() + "/";
m_Server.AddPollServiceHTTPHandler(uri, HandleHttpCloseSession, m_Server.AddPollServiceHTTPHandler(uri, HandleHttpPoll,
new PollServiceEventArgs(HasEvents, GetEvents, NoEvents, new PollServiceEventArgs(null, HasEvents, GetEvents, NoEvents,
sessionID)); sessionID));
XmlDocument xmldoc = new XmlDocument(); XmlDocument xmldoc = new XmlDocument();
@ -230,6 +230,11 @@ namespace OpenSim.Framework.Console
return reply; return reply;
} }
private Hashtable HandleHttpPoll(Hashtable request)
{
return new Hashtable();
}
private Hashtable HandleHttpCloseSession(Hashtable request) private Hashtable HandleHttpCloseSession(Hashtable request)
{ {
DoExpire(); DoExpire();
@ -365,7 +370,7 @@ namespace OpenSim.Framework.Console
} }
} }
private bool HasEvents(UUID sessionID) private bool HasEvents(UUID RequestID, UUID sessionID)
{ {
ConsoleConnection c = null; ConsoleConnection c = null;
@ -381,19 +386,19 @@ namespace OpenSim.Framework.Console
return false; return false;
} }
private Hashtable GetEvents(UUID sessionID, string request) private Hashtable GetEvents(UUID RequestID, UUID sessionID, string request)
{ {
ConsoleConnection c = null; ConsoleConnection c = null;
lock (m_Connections) lock (m_Connections)
{ {
if (!m_Connections.ContainsKey(sessionID)) if (!m_Connections.ContainsKey(sessionID))
return NoEvents(); return NoEvents(RequestID, UUID.Zero);
c = m_Connections[sessionID]; c = m_Connections[sessionID];
} }
c.last = System.Environment.TickCount; c.last = System.Environment.TickCount;
if (c.lastLineSeen >= m_LineNumber) if (c.lastLineSeen >= m_LineNumber)
return NoEvents(); return NoEvents(RequestID, UUID.Zero);
Hashtable result = new Hashtable(); Hashtable result = new Hashtable();
@ -435,7 +440,7 @@ namespace OpenSim.Framework.Console
return result; return result;
} }
private Hashtable NoEvents() private Hashtable NoEvents(UUID RequestID, UUID id)
{ {
Hashtable result = new Hashtable(); Hashtable result = new Hashtable();

View File

@ -26,6 +26,7 @@
*/ */
using System; using System;
using System.Collections.Generic;
using System.Net; using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
using System.Xml; using System.Xml;
@ -63,6 +64,13 @@ namespace OpenSim.Framework
} }
protected string m_serverURI; protected string m_serverURI;
public string RegionName
{
get { return m_regionName; }
set { m_regionName = value; }
}
protected string m_regionName = String.Empty;
protected bool Allow_Alternate_Ports; protected bool Allow_Alternate_Ports;
public bool m_allow_alternate_ports; public bool m_allow_alternate_ports;
protected string m_externalHostName; protected string m_externalHostName;
@ -100,6 +108,7 @@ namespace OpenSim.Framework
public SimpleRegionInfo(RegionInfo ConvertFrom) public SimpleRegionInfo(RegionInfo ConvertFrom)
{ {
m_regionName = ConvertFrom.RegionName;
m_regionLocX = ConvertFrom.RegionLocX; m_regionLocX = ConvertFrom.RegionLocX;
m_regionLocY = ConvertFrom.RegionLocY; m_regionLocY = ConvertFrom.RegionLocY;
m_internalEndPoint = ConvertFrom.InternalEndPoint; m_internalEndPoint = ConvertFrom.InternalEndPoint;
@ -197,6 +206,67 @@ namespace OpenSim.Framework
{ {
return m_internalEndPoint.Port; return m_internalEndPoint.Port;
} }
public Dictionary<string, object> ToKeyValuePairs()
{
Dictionary<string, object> kvp = new Dictionary<string, object>();
kvp["uuid"] = RegionID.ToString();
kvp["locX"] = RegionLocX.ToString();
kvp["locY"] = RegionLocY.ToString();
kvp["external_ip_address"] = ExternalEndPoint.Address.ToString();
kvp["external_port"] = ExternalEndPoint.Port.ToString();
kvp["external_host_name"] = ExternalHostName;
kvp["http_port"] = HttpPort.ToString();
kvp["internal_ip_address"] = InternalEndPoint.Address.ToString();
kvp["internal_port"] = InternalEndPoint.Port.ToString();
kvp["alternate_ports"] = m_allow_alternate_ports.ToString();
kvp["server_uri"] = ServerURI;
return kvp;
}
public SimpleRegionInfo(Dictionary<string, object> kvp)
{
if ((kvp["external_ip_address"] != null) && (kvp["external_port"] != null))
{
int port = 0;
Int32.TryParse((string)kvp["external_port"], out port);
IPEndPoint ep = new IPEndPoint(IPAddress.Parse((string)kvp["external_ip_address"]), port);
ExternalEndPoint = ep;
}
else
ExternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), 0);
if (kvp["external_host_name"] != null)
ExternalHostName = (string)kvp["external_host_name"];
if (kvp["http_port"] != null)
{
UInt32 port = 0;
UInt32.TryParse((string)kvp["http_port"], out port);
HttpPort = port;
}
if ((kvp["internal_ip_address"] != null) && (kvp["internal_port"] != null))
{
int port = 0;
Int32.TryParse((string)kvp["internal_port"], out port);
IPEndPoint ep = new IPEndPoint(IPAddress.Parse((string)kvp["internal_ip_address"]), port);
InternalEndPoint = ep;
}
else
InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), 0);
if (kvp["alternate_ports"] != null)
{
bool alts = false;
Boolean.TryParse((string)kvp["alternate_ports"], out alts);
m_allow_alternate_ports = alts;
}
if (kvp["server_uri"] != null)
ServerURI = (string)kvp["server_uri"];
}
} }
public class RegionInfo : SimpleRegionInfo public class RegionInfo : SimpleRegionInfo
@ -222,7 +292,6 @@ namespace OpenSim.Framework
public UUID originRegionID = UUID.Zero; public UUID originRegionID = UUID.Zero;
public string proxyUrl = ""; public string proxyUrl = "";
public int ProxyOffset = 0; public int ProxyOffset = 0;
public string RegionName = String.Empty;
public string regionSecret = UUID.Random().ToString(); public string regionSecret = UUID.Random().ToString();
public string osSecret; public string osSecret;

View File

@ -256,13 +256,51 @@ namespace OpenSim.Framework.Servers.HttpServer
IHttpClientContext context = (IHttpClientContext)source; IHttpClientContext context = (IHttpClientContext)source;
IHttpRequest request = args.Request; IHttpRequest request = args.Request;
PollServiceEventArgs psEvArgs; PollServiceEventArgs psEvArgs;
if (TryGetPollServiceHTTPHandler(request.UriPath.ToString(), out psEvArgs)) if (TryGetPollServiceHTTPHandler(request.UriPath.ToString(), out psEvArgs))
{ {
PollServiceHttpRequest psreq = new PollServiceHttpRequest(psEvArgs, context, request);
m_PollServiceManager.Enqueue(new PollServiceHttpRequest(psEvArgs, context, request));
//DoHTTPGruntWork(psEvArgs.NoEvents(),new OSHttpResponse(new HttpResponse(context, request))); if (psEvArgs.Request != null)
{
OSHttpRequest req = new OSHttpRequest(context, request);
Stream requestStream = req.InputStream;
Encoding encoding = Encoding.UTF8;
StreamReader reader = new StreamReader(requestStream, encoding);
string requestBody = reader.ReadToEnd();
Hashtable keysvals = new Hashtable();
Hashtable headervals = new Hashtable();
string[] querystringkeys = req.QueryString.AllKeys;
string[] rHeaders = req.Headers.AllKeys;
keysvals.Add("body", requestBody);
keysvals.Add("uri", req.RawUrl);
keysvals.Add("content-type", req.ContentType);
keysvals.Add("http-method", req.HttpMethod);
foreach (string queryname in querystringkeys)
{
keysvals.Add(queryname, req.QueryString[queryname]);
}
foreach (string headername in rHeaders)
{
headervals[headername] = req.Headers[headername];
}
keysvals.Add("headers",headervals);
keysvals.Add("querystringkeys", querystringkeys);
psEvArgs.Request(psreq.RequestID, keysvals);
}
m_PollServiceManager.Enqueue(psreq);
} }
else else
{ {
@ -275,48 +313,16 @@ namespace OpenSim.Framework.Servers.HttpServer
{ {
OSHttpRequest req = new OSHttpRequest(context, request); OSHttpRequest req = new OSHttpRequest(context, request);
OSHttpResponse resp = new OSHttpResponse(new HttpResponse(context, request),context); OSHttpResponse resp = new OSHttpResponse(new HttpResponse(context, request),context);
//resp.KeepAlive = req.KeepAlive;
//m_log.Info("[Debug BASE HTTP SERVER]: Got Request");
//HttpServerContextObj objstate= new HttpServerContextObj(req,resp);
//ThreadPool.QueueUserWorkItem(new WaitCallback(ConvertIHttpClientContextToOSHttp), (object)objstate);
HandleRequest(req, resp); HandleRequest(req, resp);
} }
public void ConvertIHttpClientContextToOSHttp(object stateinfo) public void ConvertIHttpClientContextToOSHttp(object stateinfo)
{ {
HttpServerContextObj objstate = (HttpServerContextObj)stateinfo; HttpServerContextObj objstate = (HttpServerContextObj)stateinfo;
//OSHttpRequest request = new OSHttpRequest(objstate.context,objstate.req);
//OSHttpResponse resp = new OSHttpResponse(new HttpServer.HttpResponse(objstate.context, objstate.req));
OSHttpRequest request = objstate.oreq; OSHttpRequest request = objstate.oreq;
OSHttpResponse resp = objstate.oresp; OSHttpResponse resp = objstate.oresp;
//OSHttpResponse resp = new OSHttpResponse(new HttpServer.HttpResponse(objstate.context, objstate.req));
/*
request.AcceptTypes = objstate.req.AcceptTypes;
request.ContentLength = (long)objstate.req.ContentLength;
request.Headers = objstate.req.Headers;
request.HttpMethod = objstate.req.Method;
request.InputStream = objstate.req.Body;
foreach (string str in request.Headers)
{
if (str.ToLower().Contains("content-type: "))
{
request.ContentType = str.Substring(13, str.Length - 13);
break;
}
}
//request.KeepAlive = objstate.req.
foreach (HttpServer.HttpInput httpinput in objstate.req.QueryString)
{
request.QueryString.Add(httpinput.Name, httpinput[httpinput.Name]);
}
//request.Query = objstate.req.//objstate.req.QueryString;
//foreach (
//request.QueryString = objstate.req.QueryString;
*/
HandleRequest(request,resp); HandleRequest(request,resp);
} }
@ -332,6 +338,7 @@ namespace OpenSim.Framework.Servers.HttpServer
// probability event; if a request is matched it is normally expected to be // probability event; if a request is matched it is normally expected to be
// handled // handled
//m_log.Debug("[BASE HTTP SERVER]: Handling Request" + request.RawUrl); //m_log.Debug("[BASE HTTP SERVER]: Handling Request" + request.RawUrl);
IHttpAgentHandler agentHandler; IHttpAgentHandler agentHandler;
if (TryGetAgentHandler(request, response, out agentHandler)) if (TryGetAgentHandler(request, response, out agentHandler))
@ -342,10 +349,11 @@ namespace OpenSim.Framework.Servers.HttpServer
} }
} }
IRequestHandler requestHandler;
//response.KeepAlive = true; //response.KeepAlive = true;
response.SendChunked = false; response.SendChunked = false;
IRequestHandler requestHandler;
string path = request.RawUrl; string path = request.RawUrl;
string handlerKey = GetHandlerKey(request.HttpMethod, path); string handlerKey = GetHandlerKey(request.HttpMethod, path);
@ -359,6 +367,7 @@ namespace OpenSim.Framework.Servers.HttpServer
response.ContentType = requestHandler.ContentType; // Lets do this defaulting before in case handler has varying content type. response.ContentType = requestHandler.ContentType; // Lets do this defaulting before in case handler has varying content type.
if (requestHandler is IStreamedRequestHandler) if (requestHandler is IStreamedRequestHandler)
{ {
IStreamedRequestHandler streamedRequestHandler = requestHandler as IStreamedRequestHandler; IStreamedRequestHandler streamedRequestHandler = requestHandler as IStreamedRequestHandler;
@ -404,6 +413,7 @@ namespace OpenSim.Framework.Servers.HttpServer
// } // }
keysvals.Add("requestbody", requestBody); keysvals.Add("requestbody", requestBody);
keysvals.Add("headers",headervals);
if (keysvals.Contains("method")) if (keysvals.Contains("method"))
{ {
//m_log.Warn("[HTTP]: Contains Method"); //m_log.Warn("[HTTP]: Contains Method");
@ -726,8 +736,11 @@ namespace OpenSim.Framework.Servers.HttpServer
else else
{ {
xmlRpcResponse = new XmlRpcResponse(); xmlRpcResponse = new XmlRpcResponse();
// Code set in accordance with http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php // Code set in accordance with http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php
xmlRpcResponse.SetFault(-32601, String.Format("Requested method [{0}] not found", methodName)); xmlRpcResponse.SetFault(
XmlRpcErrorCodes.SERVER_ERROR_METHOD,
String.Format("Requested method [{0}] not found", methodName));
} }
responseString = XmlRpcResponseSerializer.Singleton.Serialize(xmlRpcResponse); responseString = XmlRpcResponseSerializer.Singleton.Serialize(xmlRpcResponse);
@ -747,6 +760,7 @@ namespace OpenSim.Framework.Servers.HttpServer
response.SendChunked = false; response.SendChunked = false;
response.ContentLength64 = buf.Length; response.ContentLength64 = buf.Length;
response.ContentEncoding = Encoding.UTF8; response.ContentEncoding = Encoding.UTF8;
try try
{ {
response.OutputStream.Write(buf, 0, buf.Length); response.OutputStream.Write(buf, 0, buf.Length);

View File

@ -30,20 +30,23 @@ using System.Collections;
using OpenMetaverse; using OpenMetaverse;
namespace OpenSim.Framework.Servers.HttpServer namespace OpenSim.Framework.Servers.HttpServer
{ {
public delegate bool HasEventsMethod(UUID pId); public delegate void RequestMethod(UUID requestID, Hashtable request);
public delegate bool HasEventsMethod(UUID requestID, UUID pId);
public delegate Hashtable GetEventsMethod(UUID pId, string request); public delegate Hashtable GetEventsMethod(UUID requestID, UUID pId, string request);
public delegate Hashtable NoEventsMethod(); public delegate Hashtable NoEventsMethod(UUID requestID, UUID pId);
public class PollServiceEventArgs : EventArgs public class PollServiceEventArgs : EventArgs
{ {
public HasEventsMethod HasEvents; public HasEventsMethod HasEvents;
public GetEventsMethod GetEvents; public GetEventsMethod GetEvents;
public NoEventsMethod NoEvents; public NoEventsMethod NoEvents;
public RequestMethod Request;
public UUID Id; public UUID Id;
public PollServiceEventArgs(HasEventsMethod pHasEvents, GetEventsMethod pGetEvents, NoEventsMethod pNoEvents,UUID pId) public PollServiceEventArgs(RequestMethod pRequest, HasEventsMethod pHasEvents, GetEventsMethod pGetEvents, NoEventsMethod pNoEvents,UUID pId)
{ {
Request = pRequest;
HasEvents = pHasEvents; HasEvents = pHasEvents;
GetEvents = pGetEvents; GetEvents = pGetEvents;
NoEvents = pNoEvents; NoEvents = pNoEvents;

View File

@ -27,6 +27,7 @@
using System; using System;
using HttpServer; using HttpServer;
using OpenMetaverse;
namespace OpenSim.Framework.Servers.HttpServer namespace OpenSim.Framework.Servers.HttpServer
{ {
@ -37,12 +38,14 @@ namespace OpenSim.Framework.Servers.HttpServer
public readonly IHttpClientContext HttpContext; public readonly IHttpClientContext HttpContext;
public readonly IHttpRequest Request; public readonly IHttpRequest Request;
public readonly int RequestTime; public readonly int RequestTime;
public readonly UUID RequestID;
public PollServiceHttpRequest(PollServiceEventArgs pPollServiceArgs, IHttpClientContext pHttpContext, IHttpRequest pRequest) public PollServiceHttpRequest(PollServiceEventArgs pPollServiceArgs, IHttpClientContext pHttpContext, IHttpRequest pRequest)
{ {
PollServiceArgs = pPollServiceArgs; PollServiceArgs = pPollServiceArgs;
HttpContext = pHttpContext; HttpContext = pHttpContext;
Request = pRequest; Request = pRequest;
RequestTime = System.Environment.TickCount; RequestTime = System.Environment.TickCount;
RequestID = UUID.Random();
} }
} }
} }

View File

@ -130,7 +130,7 @@ namespace OpenSim.Framework.Servers.HttpServer
foreach (object o in m_requests) foreach (object o in m_requests)
{ {
PollServiceHttpRequest req = (PollServiceHttpRequest) o; PollServiceHttpRequest req = (PollServiceHttpRequest) o;
m_server.DoHTTPGruntWork(req.PollServiceArgs.NoEvents(), new OSHttpResponse(new HttpResponse(req.HttpContext, req.Request), req.HttpContext)); m_server.DoHTTPGruntWork(req.PollServiceArgs.NoEvents(req.RequestID, req.PollServiceArgs.Id), new OSHttpResponse(new HttpResponse(req.HttpContext, req.Request), req.HttpContext));
} }
m_requests.Clear(); m_requests.Clear();

View File

@ -100,11 +100,11 @@ namespace OpenSim.Framework.Servers.HttpServer
PollServiceHttpRequest req = m_request.Dequeue(); PollServiceHttpRequest req = m_request.Dequeue();
try try
{ {
if (req.PollServiceArgs.HasEvents(req.PollServiceArgs.Id)) if (req.PollServiceArgs.HasEvents(req.RequestID, req.PollServiceArgs.Id))
{ {
StreamReader str = new StreamReader(req.Request.Body); StreamReader str = new StreamReader(req.Request.Body);
Hashtable responsedata = req.PollServiceArgs.GetEvents(req.PollServiceArgs.Id, str.ReadToEnd()); Hashtable responsedata = req.PollServiceArgs.GetEvents(req.RequestID, req.PollServiceArgs.Id, str.ReadToEnd());
m_server.DoHTTPGruntWork(responsedata, m_server.DoHTTPGruntWork(responsedata,
new OSHttpResponse(new HttpResponse(req.HttpContext, req.Request),req.HttpContext)); new OSHttpResponse(new HttpResponse(req.HttpContext, req.Request),req.HttpContext));
} }
@ -112,7 +112,7 @@ namespace OpenSim.Framework.Servers.HttpServer
{ {
if ((Environment.TickCount - req.RequestTime) > m_timeout) if ((Environment.TickCount - req.RequestTime) > m_timeout)
{ {
m_server.DoHTTPGruntWork(req.PollServiceArgs.NoEvents(), m_server.DoHTTPGruntWork(req.PollServiceArgs.NoEvents(req.RequestID, req.PollServiceArgs.Id),
new OSHttpResponse(new HttpResponse(req.HttpContext, req.Request),req.HttpContext)); new OSHttpResponse(new HttpResponse(req.HttpContext, req.Request),req.HttpContext));
} }
else else

View File

@ -56,14 +56,14 @@ namespace OpenSim.Framework.Servers.HttpServer
request.ContentType = "text/www-form-urlencoded"; request.ContentType = "text/www-form-urlencoded";
MemoryStream buffer = new MemoryStream(); MemoryStream buffer = new MemoryStream();
int length = 0;
using (StreamWriter writer = new StreamWriter(buffer)) using (StreamWriter writer = new StreamWriter(buffer))
{ {
writer.WriteLine(obj); writer.WriteLine(obj);
writer.Flush(); writer.Flush();
length = (int)buffer.Length;
} }
int length = (int) buffer.Length;
request.ContentLength = length; request.ContentLength = length;
Stream requestStream = request.GetRequestStream(); Stream requestStream = request.GetRequestStream();

View File

@ -29,8 +29,8 @@ namespace OpenSim
{ {
public class VersionInfo public class VersionInfo
{ {
private const string VERSION_NUMBER = "0.6.6"; private const string VERSION_NUMBER = "0.6.7";
private const Flavour VERSION_FLAVOUR = Flavour.Dev; private const Flavour VERSION_FLAVOUR = Flavour.Release;
public enum Flavour public enum Flavour
{ {

View File

@ -70,6 +70,39 @@ namespace OpenSim.Framework
public static readonly Regex UUIDPattern public static readonly Regex UUIDPattern
= new Regex("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"); = new Regex("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$");
/// <summary>
/// Linear interpolates B<->C using percent A
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="c"></param>
/// <returns></returns>
public static double lerp(double a, double b, double c)
{
return (b*a) + (c*(1 - a));
}
/// <summary>
/// Bilinear Interpolate, see Lerp but for 2D using 'percents' X & Y.
/// Layout:
/// A B
/// C D
/// A<->C = Y
/// C<->D = X
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="c"></param>
/// <param name="d"></param>
/// <returns></returns>
public static double lerp2D(double x, double y, double a, double b, double c, double d)
{
return lerp(y, lerp(x, a, b), lerp(x, c, d));
}
/// <value> /// <value>
/// Well known UUID for the blank texture used in the Linden SL viewer version 1.20 (and hopefully onwards) /// Well known UUID for the blank texture used in the Linden SL viewer version 1.20 (and hopefully onwards)
/// </value> /// </value>

View File

@ -108,6 +108,9 @@ namespace OpenSim.Grid.UserServer.Modules
m_httpServer.AddXmlRPCHandler("get_user_by_uuid", XmlRPCGetUserMethodUUID); m_httpServer.AddXmlRPCHandler("get_user_by_uuid", XmlRPCGetUserMethodUUID);
m_httpServer.AddXmlRPCHandler("get_avatar_picker_avatar", XmlRPCGetAvatarPickerAvatar); m_httpServer.AddXmlRPCHandler("get_avatar_picker_avatar", XmlRPCGetAvatarPickerAvatar);
// Used by IAR module to do password checks
m_httpServer.AddXmlRPCHandler("authenticate_user_by_password", XmlRPCAuthenticateUserMethodPassword);
m_httpServer.AddXmlRPCHandler("update_user_current_region", XmlRPCAtRegion); m_httpServer.AddXmlRPCHandler("update_user_current_region", XmlRPCAtRegion);
m_httpServer.AddXmlRPCHandler("logout_of_simulator", XmlRPCLogOffUserMethodUUID); m_httpServer.AddXmlRPCHandler("logout_of_simulator", XmlRPCLogOffUserMethodUUID);
m_httpServer.AddXmlRPCHandler("get_agent_by_uuid", XmlRPCGetAgentMethodUUID); m_httpServer.AddXmlRPCHandler("get_agent_by_uuid", XmlRPCGetAgentMethodUUID);
@ -203,6 +206,57 @@ namespace OpenSim.Grid.UserServer.Modules
#region XMLRPC User Methods #region XMLRPC User Methods
/// <summary>
/// Authenticate a user using their password
/// </summary>
/// <param name="request">Must contain values for "user_uuid" and "password" keys</param>
/// <param name="remoteClient"></param>
/// <returns></returns>
public XmlRpcResponse XmlRPCAuthenticateUserMethodPassword(XmlRpcRequest request, IPEndPoint remoteClient)
{
// m_log.DebugFormat("[USER MANAGER]: Received authenticated user by password request from {0}", remoteClient);
Hashtable requestData = (Hashtable)request.Params[0];
string userUuidRaw = (string)requestData["user_uuid"];
string password = (string)requestData["password"];
if (null == userUuidRaw)
return Util.CreateUnknownUserErrorResponse();
UUID userUuid;
if (!UUID.TryParse(userUuidRaw, out userUuid))
return Util.CreateUnknownUserErrorResponse();
UserProfileData userProfile = m_userDataBaseService.GetUserProfile(userUuid);
if (null == userProfile)
return Util.CreateUnknownUserErrorResponse();
string authed;
if (null == password)
{
authed = "FALSE";
}
else
{
if (m_userDataBaseService.AuthenticateUserByPassword(userUuid, password))
authed = "TRUE";
else
authed = "FALSE";
}
// m_log.DebugFormat(
// "[USER MANAGER]: Authentication by password result from {0} for {1} is {2}",
// remoteClient, userUuid, authed);
XmlRpcResponse response = new XmlRpcResponse();
Hashtable responseData = new Hashtable();
responseData["auth_user"] = authed;
response.Value = responseData;
return response;
}
public XmlRpcResponse XmlRPCGetAvatarPickerAvatar(XmlRpcRequest request, IPEndPoint remoteClient) public XmlRpcResponse XmlRPCGetAvatarPickerAvatar(XmlRpcRequest request, IPEndPoint remoteClient)
{ {
// XmlRpcResponse response = new XmlRpcResponse(); // XmlRpcResponse response = new XmlRpcResponse();
@ -246,10 +300,10 @@ namespace OpenSim.Grid.UserServer.Modules
m_userDataBaseService.CommitAgent(ref userProfile); m_userDataBaseService.CommitAgent(ref userProfile);
//setUserProfile(userProfile); //setUserProfile(userProfile);
returnstring = "TRUE"; returnstring = "TRUE";
} }
} }
responseData.Add("returnString", returnstring); responseData.Add("returnString", returnstring);
response.Value = responseData; response.Value = responseData;
return response; return response;

View File

@ -260,8 +260,6 @@ namespace OpenSim.Grid.UserServer
m_userManager.PostInitialise(); m_userManager.PostInitialise();
m_avatarAppearanceModule.PostInitialise(); m_avatarAppearanceModule.PostInitialise();
m_friendsModule.PostInitialise(); m_friendsModule.PostInitialise();
m_avatarAppearanceModule.PostInitialise();
} }
protected virtual void RegisterHttpHandlers() protected virtual void RegisterHttpHandlers()
@ -276,8 +274,6 @@ namespace OpenSim.Grid.UserServer
m_avatarAppearanceModule.RegisterHandlers(m_httpServer); m_avatarAppearanceModule.RegisterHandlers(m_httpServer);
m_messagesService.RegisterHandlers(m_httpServer); m_messagesService.RegisterHandlers(m_httpServer);
m_gridInfoService.RegisterHandlers(m_httpServer); m_gridInfoService.RegisterHandlers(m_httpServer);
m_avatarAppearanceModule.RegisterHandlers(m_httpServer);
} }
public override void ShutdownSpecific() public override void ShutdownSpecific()

View File

@ -557,7 +557,7 @@ namespace OpenSim
/// <param name="cmd"></param> /// <param name="cmd"></param>
private void HandleLoginStatus(string module, string[] cmd) private void HandleLoginStatus(string module, string[] cmd)
{ {
if (m_commsManager.GridService.RegionLoginsEnabled == false) if (m_sceneManager.CurrentOrFirstScene.SceneGridService.RegionLoginsEnabled == false)
m_log.Info("[ Login ] Login are disabled "); m_log.Info("[ Login ] Login are disabled ");
else else

View File

@ -209,9 +209,9 @@ namespace OpenSim
} }
// Only enable logins to the regions once we have completely finished starting up (apart from scripts) // Only enable logins to the regions once we have completely finished starting up (apart from scripts)
if ((m_commsManager != null) && (m_commsManager.GridService != null)) if ((SceneManager.CurrentOrFirstScene != null) && (SceneManager.CurrentOrFirstScene.SceneGridService != null))
{ {
m_commsManager.GridService.RegionLoginsEnabled = true; SceneManager.CurrentOrFirstScene.SceneGridService.RegionLoginsEnabled = true;
} }
AddPluginCommands(); AddPluginCommands();
@ -299,12 +299,12 @@ namespace OpenSim
if (LoginEnabled) if (LoginEnabled)
{ {
m_log.Info("[LOGIN]: Login is now enabled."); m_log.Info("[LOGIN]: Login is now enabled.");
m_commsManager.GridService.RegionLoginsEnabled = true; SceneManager.CurrentOrFirstScene.SceneGridService.RegionLoginsEnabled = true;
} }
else else
{ {
m_log.Info("[LOGIN]: Login is now disabled."); m_log.Info("[LOGIN]: Login is now disabled.");
m_commsManager.GridService.RegionLoginsEnabled = false; SceneManager.CurrentOrFirstScene.SceneGridService.RegionLoginsEnabled = false;
} }
} }

View File

@ -1664,6 +1664,9 @@ namespace OpenSim.Region.ClientStack.LindenUDP
enablesimpacket.SimulatorInfo.IP += (uint)byteIP[1] << 8; enablesimpacket.SimulatorInfo.IP += (uint)byteIP[1] << 8;
enablesimpacket.SimulatorInfo.IP += (uint)byteIP[0]; enablesimpacket.SimulatorInfo.IP += (uint)byteIP[0];
enablesimpacket.SimulatorInfo.Port = neighbourPort; enablesimpacket.SimulatorInfo.Port = neighbourPort;
enablesimpacket.Header.Reliable = true; // ESP's should be reliable.
OutPacket(enablesimpacket, ThrottleOutPacketType.Task); OutPacket(enablesimpacket, ThrottleOutPacketType.Task);
} }

View File

@ -80,6 +80,21 @@ namespace OpenSim.Region.Communications.Local
throw new Exception("[LOCAL USER SERVICES]: Unknown master user UUID. Possible reason: UserServer is not running."); throw new Exception("[LOCAL USER SERVICES]: Unknown master user UUID. Possible reason: UserServer is not running.");
} }
return data; return data;
} }
public override bool AuthenticateUserByPassword(UUID userID, string password)
{
UserProfileData userProfile = GetUserProfile(userID);
if (null == userProfile)
return false;
string md5PasswordHash = Util.Md5Hash(Util.Md5Hash(password) + ":" + userProfile.PasswordSalt);
if (md5PasswordHash == userProfile.PasswordHash)
return true;
else
return false;
}
} }
} }

View File

@ -140,6 +140,37 @@ namespace OpenSim.Region.Communications.OGS1
{ {
m_log.DebugFormat("[OGS1 USER SERVICES]: Verifying user session for " + userID); m_log.DebugFormat("[OGS1 USER SERVICES]: Verifying user session for " + userID);
return AuthClient.VerifySession(GetUserServerURL(userID), userID, sessionID); return AuthClient.VerifySession(GetUserServerURL(userID), userID, sessionID);
} }
public override bool AuthenticateUserByPassword(UUID userID, string password)
{
Hashtable param = new Hashtable();
param["user_uuid"] = userID.ToString();
param["password"] = password;
IList parameters = new ArrayList();
parameters.Add(param);
XmlRpcRequest req = new XmlRpcRequest("authenticate_user_by_password", parameters);
XmlRpcResponse resp = req.Send(m_commsManager.NetworkServersInfo.UserURL, 30000);
// Temporary measure to deal with older services
if (resp.IsFault && resp.FaultCode == XmlRpcErrorCodes.SERVER_ERROR_METHOD)
{
throw new Exception(
String.Format(
"XMLRPC method 'authenticate_user_by_password' not yet implemented by user service at {0}",
m_commsManager.NetworkServersInfo.UserURL));
}
Hashtable respData = (Hashtable)resp.Value;
if ((string)respData["auth_user"] == "TRUE")
{
return true;
}
else
{
return false;
}
}
} }
} }

View File

@ -142,7 +142,7 @@ namespace Flotsam.RegionModules.AssetCache
m_CacheDirectory = assetConfig.GetString("CacheDirectory", m_DefaultCacheDirectory); m_CacheDirectory = assetConfig.GetString("CacheDirectory", m_DefaultCacheDirectory);
m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Cache Directory", m_DefaultCacheDirectory); m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Cache Directory", m_DefaultCacheDirectory);
m_MemoryCacheEnabled = assetConfig.GetBoolean("MemoryCacheEnabled", true); m_MemoryCacheEnabled = assetConfig.GetBoolean("MemoryCacheEnabled", false);
m_MemoryExpiration = TimeSpan.FromHours(assetConfig.GetDouble("MemoryCacheTimeout", m_DefaultMemoryExpiration)); m_MemoryExpiration = TimeSpan.FromHours(assetConfig.GetDouble("MemoryCacheTimeout", m_DefaultMemoryExpiration));
#if WAIT_ON_INPROGRESS_REQUESTS #if WAIT_ON_INPROGRESS_REQUESTS
@ -150,7 +150,7 @@ namespace Flotsam.RegionModules.AssetCache
#endif #endif
m_LogLevel = assetConfig.GetInt("LogLevel", 1); m_LogLevel = assetConfig.GetInt("LogLevel", 1);
m_HitRateDisplay = (ulong)assetConfig.GetInt("HitRateDisplay", 1); m_HitRateDisplay = (ulong)assetConfig.GetInt("HitRateDisplay", 1000);
m_FileExpiration = TimeSpan.FromHours(assetConfig.GetDouble("FileCacheTimeout", m_DefaultFileExpiration)); m_FileExpiration = TimeSpan.FromHours(assetConfig.GetDouble("FileCacheTimeout", m_DefaultFileExpiration));
m_FileExpirationCleanupTimer = TimeSpan.FromHours(assetConfig.GetDouble("FileCleanupTimer", m_DefaultFileExpiration)); m_FileExpirationCleanupTimer = TimeSpan.FromHours(assetConfig.GetDouble("FileCleanupTimer", m_DefaultFileExpiration));

View File

@ -118,6 +118,10 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
protected void ReceivedAllAssets(ICollection<UUID> assetsFoundUuids, ICollection<UUID> assetsNotFoundUuids) protected void ReceivedAllAssets(ICollection<UUID> assetsFoundUuids, ICollection<UUID> assetsNotFoundUuids)
{ {
// We're almost done. Just need to write out the control file now
m_archiveWriter.WriteFile(ArchiveConstants.CONTROL_FILE_PATH, Create0p1ControlFile());
m_log.InfoFormat("[ARCHIVER]: Added control file to archive.");
Exception reportedException = null; Exception reportedException = null;
bool succeeded = true; bool succeeded = true;
@ -320,7 +324,9 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
SaveInvFolder(inventoryFolder, ArchiveConstants.INVENTORY_PATH, !foundStar); SaveInvFolder(inventoryFolder, ArchiveConstants.INVENTORY_PATH, !foundStar);
} }
SaveUsers(); // Don't put all this profile information into the archive right now.
//SaveUsers();
new AssetsRequest( new AssetsRequest(
new AssetsArchiver(m_archiveWriter), m_assetUuids.Keys, new AssetsArchiver(m_archiveWriter), m_assetUuids.Keys,
m_scene.AssetService, ReceivedAllAssets).Execute(); m_scene.AssetService, ReceivedAllAssets).Execute();
@ -409,5 +415,29 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR, ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR,
id); id);
} }
/// <summary>
/// Create the control file for a 0.1 version archive
/// </summary>
/// <returns></returns>
public static string Create0p1ControlFile()
{
StringWriter sw = new StringWriter();
XmlTextWriter xtw = new XmlTextWriter(sw);
xtw.Formatting = Formatting.Indented;
xtw.WriteStartDocument();
xtw.WriteStartElement("archive");
xtw.WriteAttributeString("major_version", "0");
xtw.WriteAttributeString("minor_version", "1");
xtw.WriteEndElement();
xtw.Flush();
xtw.Close();
String s = sw.ToString();
sw.Close();
return s;
}
} }
} }

View File

@ -322,7 +322,7 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
/// <param name="pass">User password</param> /// <param name="pass">User password</param>
/// <returns></returns> /// <returns></returns>
protected CachedUserInfo GetUserInfo(string firstName, string lastName, string pass) protected CachedUserInfo GetUserInfo(string firstName, string lastName, string pass)
{ {
CachedUserInfo userInfo = m_aScene.CommsManager.UserProfileCacheService.GetUserDetails(firstName, lastName); CachedUserInfo userInfo = m_aScene.CommsManager.UserProfileCacheService.GetUserDetails(firstName, lastName);
//m_aScene.CommsManager.UserService.GetUserProfile(firstName, lastName); //m_aScene.CommsManager.UserService.GetUserProfile(firstName, lastName);
if (null == userInfo) if (null == userInfo)
@ -333,29 +333,25 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
return null; return null;
} }
string md5PasswdHash = Util.Md5Hash(Util.Md5Hash(pass) + ":" + userInfo.UserProfile.PasswordSalt); try
{
if (userInfo.UserProfile.PasswordHash == null || userInfo.UserProfile.PasswordHash == String.Empty) if (m_aScene.CommsManager.UserService.AuthenticateUserByPassword(userInfo.UserProfile.ID, pass))
{
return userInfo;
}
else
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Password for user {0} {1} incorrect. Please try again.",
firstName, lastName);
return null;
}
}
catch (Exception e)
{ {
m_log.ErrorFormat( m_log.ErrorFormat("[INVENTORY ARCHIVER]: Could not authenticate password, {0}", e.Message);
"[INVENTORY ARCHIVER]: Sorry, the grid mode service is not providing password hash details for the check. This will be fixed in an OpenSim git revision soon");
return null; return null;
} }
// m_log.DebugFormat(
// "[INVENTORY ARCHIVER]: received salt {0}, hash {1}, supplied hash {2}",
// userInfo.UserProfile.PasswordSalt, userInfo.UserProfile.PasswordHash, md5PasswdHash);
if (userInfo.UserProfile.PasswordHash != md5PasswdHash)
{
m_log.ErrorFormat(
"[INVENTORY ARCHIVER]: Password for user {0} {1} incorrect. Please try again.",
firstName, lastName);
return null;
}
return userInfo;
} }
/// <summary> /// <summary>
@ -375,9 +371,9 @@ namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
{ {
foreach (InventoryNodeBase node in loadedNodes) foreach (InventoryNodeBase node in loadedNodes)
{ {
m_log.DebugFormat( // m_log.DebugFormat(
"[INVENTORY ARCHIVER]: Notifying {0} of loaded inventory node {1}", // "[INVENTORY ARCHIVER]: Notifying {0} of loaded inventory node {1}",
user.Name, node.Name); // user.Name, node.Name);
user.ControllingClient.SendBulkUpdateInventory(node); user.ControllingClient.SendBulkUpdateInventory(node);
} }

View File

@ -316,7 +316,7 @@ namespace OpenSim.Region.CoreModules.Framework.EventQueue
// This will persist this beyond the expiry of the caps handlers // This will persist this beyond the expiry of the caps handlers
MainServer.Instance.AddPollServiceHTTPHandler( MainServer.Instance.AddPollServiceHTTPHandler(
capsBase + EventQueueGetUUID.ToString() + "/", EventQueuePath2, new PollServiceEventArgs(HasEvents, GetEvents, NoEvents, agentID)); capsBase + EventQueueGetUUID.ToString() + "/", EventQueuePoll, new PollServiceEventArgs(null, HasEvents, GetEvents, NoEvents, agentID));
Random rnd = new Random(Environment.TickCount); Random rnd = new Random(Environment.TickCount);
lock (m_ids) lock (m_ids)
@ -326,7 +326,7 @@ namespace OpenSim.Region.CoreModules.Framework.EventQueue
} }
} }
public bool HasEvents(UUID agentID) public bool HasEvents(UUID requestID, UUID agentID)
{ {
// Don't use this, because of race conditions at agent closing time // Don't use this, because of race conditions at agent closing time
//Queue<OSD> queue = TryGetQueue(agentID); //Queue<OSD> queue = TryGetQueue(agentID);
@ -343,14 +343,14 @@ namespace OpenSim.Region.CoreModules.Framework.EventQueue
return false; return false;
} }
public Hashtable GetEvents(UUID pAgentId, string request) public Hashtable GetEvents(UUID requestID, UUID pAgentId, string request)
{ {
Queue<OSD> queue = TryGetQueue(pAgentId); Queue<OSD> queue = TryGetQueue(pAgentId);
OSD element; OSD element;
lock (queue) lock (queue)
{ {
if (queue.Count == 0) if (queue.Count == 0)
return NoEvents(); return NoEvents(requestID, pAgentId);
element = queue.Dequeue(); // 15s timeout element = queue.Dequeue(); // 15s timeout
} }
@ -398,7 +398,7 @@ namespace OpenSim.Region.CoreModules.Framework.EventQueue
//m_log.DebugFormat("[EVENTQUEUE]: sending response for {0} in region {1}: {2}", agentID, m_scene.RegionInfo.RegionName, responsedata["str_response_string"]); //m_log.DebugFormat("[EVENTQUEUE]: sending response for {0} in region {1}: {2}", agentID, m_scene.RegionInfo.RegionName, responsedata["str_response_string"]);
} }
public Hashtable NoEvents() public Hashtable NoEvents(UUID requestID, UUID agentID)
{ {
Hashtable responsedata = new Hashtable(); Hashtable responsedata = new Hashtable();
responsedata["int_response_code"] = 502; responsedata["int_response_code"] = 502;
@ -491,6 +491,11 @@ namespace OpenSim.Region.CoreModules.Framework.EventQueue
return responsedata; return responsedata;
} }
public Hashtable EventQueuePoll(Hashtable request)
{
return new Hashtable();
}
public Hashtable EventQueuePath2(Hashtable request) public Hashtable EventQueuePath2(Hashtable request)
{ {
string capuuid = (string)request["uri"]; //path.Replace("/CAPS/EQG/",""); string capuuid = (string)request["uri"]; //path.Replace("/CAPS/EQG/","");

View File

@ -61,7 +61,7 @@ namespace OpenSim.Region.CoreModules.Hypergrid
{ {
if (m_firstScene != null) if (m_firstScene != null)
{ {
return m_firstScene.CommsManager.GridService.RegionLoginsEnabled; return m_firstScene.SceneGridService.RegionLoginsEnabled;
} }
else else
{ {

View File

@ -38,11 +38,15 @@
<RegionModule id="RemoteLandServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Land.RemoteLandServicesConnector" /> <RegionModule id="RemoteLandServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Land.RemoteLandServicesConnector" />
<RegionModule id="LocalInterregionComms" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Interregion.LocalInterregionComms" /> <RegionModule id="LocalInterregionComms" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Interregion.LocalInterregionComms" />
<RegionModule id="RESTInterregionComms" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Interregion.RESTInterregionComms" /> <RegionModule id="RESTInterregionComms" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Interregion.RESTInterregionComms" />
<RegionModule id="LocalGridServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid.LocalGridServicesConnector" />
<RegionModule id="RemoteGridServicesConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid.RemoteGridServicesConnector" />
<RegionModule id="HGGridConnector" type="OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid.HGGridConnector" />
<!-- Service connectors IN modules --> <!-- Service connectors IN modules -->
<RegionModule id="AssetServiceInConnectorModule" type="OpenSim.Region.CoreModules.ServiceConnectorsIn.Asset.AssetServiceInConnectorModule" /> <RegionModule id="AssetServiceInConnectorModule" type="OpenSim.Region.CoreModules.ServiceConnectorsIn.Asset.AssetServiceInConnectorModule" />
<RegionModule id="InventoryServiceInConnectorModule" type="OpenSim.Region.CoreModules.ServiceConnectorsIn.Inventory.InventoryServiceInConnectorModule" /> <RegionModule id="InventoryServiceInConnectorModule" type="OpenSim.Region.CoreModules.ServiceConnectorsIn.Inventory.InventoryServiceInConnectorModule" />
<RegionModule id="LandServiceInConnectorModule" type="OpenSim.Region.CoreModules.ServiceConnectorsIn.Land.LandServiceInConnectorModule" /> <RegionModule id="LandServiceInConnectorModule" type="OpenSim.Region.CoreModules.ServiceConnectorsIn.Land.LandServiceInConnectorModule" />
<RegionModule id="NeighbourServiceInConnectorModule" type="OpenSim.Region.CoreModules.ServiceConnectorsIn.Neighbour.NeighbourServiceInConnectorModule" /> \ <RegionModule id="NeighbourServiceInConnectorModule" type="OpenSim.Region.CoreModules.ServiceConnectorsIn.Neighbour.NeighbourServiceInConnectorModule" /> \
<RegionModule id="HypergridServiceInConnectorModule" type="OpenSim.Region.CoreModules.ServiceConnectorsIn.Grid.HypergridServiceInConnectorModule" /> \
</Extension> </Extension>

View File

@ -55,14 +55,19 @@ namespace OpenSim.Region.CoreModules.Scripting.LSLHttp
public UUID requestID; public UUID requestID;
public Dictionary<string, string> headers; public Dictionary<string, string> headers;
public string body; public string body;
public int responseCode;
public string responseBody;
public ManualResetEvent ev; public ManualResetEvent ev;
public bool requestDone;
public int startTime;
public string uri;
} }
public class UrlModule : ISharedRegionModule, IUrlModule public class UrlModule : ISharedRegionModule, IUrlModule
{ {
// private static readonly ILog m_log = private static readonly ILog m_log =
// LogManager.GetLogger( LogManager.GetLogger(
// MethodBase.GetCurrentMethod().DeclaringType); MethodBase.GetCurrentMethod().DeclaringType);
private Dictionary<UUID, UrlData> m_RequestMap = private Dictionary<UUID, UrlData> m_RequestMap =
new Dictionary<UUID, UrlData>(); new Dictionary<UUID, UrlData>();
@ -70,15 +75,23 @@ namespace OpenSim.Region.CoreModules.Scripting.LSLHttp
private Dictionary<string, UrlData> m_UrlMap = private Dictionary<string, UrlData> m_UrlMap =
new Dictionary<string, UrlData>(); new Dictionary<string, UrlData>();
private int m_TotalUrls = 100; private int m_TotalUrls = 100;
private IHttpServer m_HttpServer = null; private IHttpServer m_HttpServer = null;
private string m_ExternalHostNameForLSL = "";
public Type ReplaceableInterface public Type ReplaceableInterface
{ {
get { return null; } get { return null; }
} }
private Hashtable HandleHttpPoll(Hashtable request)
{
return new Hashtable();
}
public string Name public string Name
{ {
get { return "UrlModule"; } get { return "UrlModule"; }
@ -86,6 +99,7 @@ namespace OpenSim.Region.CoreModules.Scripting.LSLHttp
public void Initialise(IConfigSource config) public void Initialise(IConfigSource config)
{ {
m_ExternalHostNameForLSL = config.Configs["Network"].GetString("ExternalHostNameForLSL", System.Environment.MachineName);
} }
public void PostInitialise() public void PostInitialise()
@ -117,7 +131,6 @@ namespace OpenSim.Region.CoreModules.Scripting.LSLHttp
public void Close() public void Close()
{ {
} }
public UUID RequestURL(IScriptModule engine, SceneObjectPart host, UUID itemID) public UUID RequestURL(IScriptModule engine, SceneObjectPart host, UUID itemID)
{ {
UUID urlcode = UUID.Random(); UUID urlcode = UUID.Random();
@ -129,7 +142,7 @@ namespace OpenSim.Region.CoreModules.Scripting.LSLHttp
engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", "" }); engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", "" });
return urlcode; return urlcode;
} }
string url = "http://"+System.Environment.MachineName+":"+m_HttpServer.Port.ToString()+"/lslhttp/"+urlcode.ToString()+"/"; string url = "http://" + m_ExternalHostNameForLSL + ":" + m_HttpServer.Port.ToString() + "/lslhttp/" + urlcode.ToString() + "/";
UrlData urlData = new UrlData(); UrlData urlData = new UrlData();
urlData.hostID = host.UUID; urlData.hostID = host.UUID;
@ -139,9 +152,14 @@ namespace OpenSim.Region.CoreModules.Scripting.LSLHttp
urlData.urlcode = urlcode; urlData.urlcode = urlcode;
urlData.requests = new Dictionary<UUID, RequestData>(); urlData.requests = new Dictionary<UUID, RequestData>();
m_UrlMap[url] = urlData; m_UrlMap[url] = urlData;
m_HttpServer.AddHTTPHandler("/lslhttp/"+urlcode.ToString()+"/", HttpRequestHandler); string uri = "/lslhttp/" + urlcode.ToString() + "/";
m_HttpServer.AddPollServiceHTTPHandler(uri,HandleHttpPoll,
new PollServiceEventArgs(HttpRequestHandler,HasEvents, GetEvents, NoEvents,
urlcode));
engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_GRANTED", url }); engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_GRANTED", url });
} }
@ -165,7 +183,9 @@ namespace OpenSim.Region.CoreModules.Scripting.LSLHttp
UrlData data; UrlData data;
if (!m_UrlMap.TryGetValue(url, out data)) if (!m_UrlMap.TryGetValue(url, out data))
{
return; return;
}
foreach (UUID req in data.requests.Keys) foreach (UUID req in data.requests.Keys)
m_RequestMap.Remove(req); m_RequestMap.Remove(req);
@ -174,13 +194,36 @@ namespace OpenSim.Region.CoreModules.Scripting.LSLHttp
m_UrlMap.Remove(url); m_UrlMap.Remove(url);
} }
} }
public void HttpResponse(UUID request, int status, string body) public void HttpResponse(UUID request, int status, string body)
{ {
if (m_RequestMap.ContainsKey(request))
{
UrlData urlData = m_RequestMap[request];
urlData.requests[request].responseCode = status;
urlData.requests[request].responseBody = body;
//urlData.requests[request].ev.Set();
urlData.requests[request].requestDone =true;
}
else
{
m_log.Info("[HttpRequestHandler] There is no http-in request with id " + request.ToString());
}
} }
public string GetHttpHeader(UUID request, string header) public string GetHttpHeader(UUID requestId, string header)
{ {
if (m_RequestMap.ContainsKey(requestId))
{
UrlData urlData=m_RequestMap[requestId];
string value;
if (urlData.requests[requestId].headers.TryGetValue(header,out value))
return value;
}
else
{
m_log.Warn("[HttpRequestHandler] There was no http-in request with id " + requestId);
}
return String.Empty; return String.Empty;
} }
@ -233,26 +276,214 @@ namespace OpenSim.Region.CoreModules.Scripting.LSLHttp
} }
} }
private void RemoveUrl(UrlData data) private void RemoveUrl(UrlData data)
{ {
m_HttpServer.RemoveHTTPHandler("", "/lslhttp/"+data.urlcode.ToString()+"/"); m_HttpServer.RemoveHTTPHandler("", "/lslhttp/"+data.urlcode.ToString()+"/");
} }
private Hashtable HttpRequestHandler(Hashtable request) private Hashtable NoEvents(UUID requestID, UUID sessionID)
{ {
string uri = request["uri"].ToString();
//A solution to this ugly mess would be to use only the /lslhttp/<UUID>/ part of the URI as the key.
UrlData url = m_UrlMap["http://"+System.Environment.MachineName+":"+m_HttpServer.Port.ToString()+uri];
//UUID.Random() below is a hack! Eventually we will do HTTP requests and responses properly.
url.engine.PostScriptEvent(url.itemID, "http_request", new Object[] { UUID.Random().ToString(), request["http-method"].ToString(), request["body"].ToString() });
Hashtable response = new Hashtable(); Hashtable response = new Hashtable();
response["int_response_code"] = 200; UrlData url;
response["str_response_string"] = "This is a generic response as OpenSim does not yet support proper responses. Your request has been passed to the object."; lock (m_RequestMap)
{
if (!m_RequestMap.ContainsKey(requestID))
return response;
url = m_RequestMap[requestID];
}
if (System.Environment.TickCount - url.requests[requestID].startTime > 25000)
{
response["int_response_code"] = 500;
response["str_response_string"] = "Script timeout";
response["content_type"] = "text/plain";
response["keepalive"] = false;
response["reusecontext"] = false;
//remove from map
lock (url)
{
url.requests.Remove(requestID);
m_RequestMap.Remove(requestID);
}
return response;
}
return response;
}
private bool HasEvents(UUID requestID, UUID sessionID)
{
UrlData url=null;
lock (m_RequestMap)
{
if (!m_RequestMap.ContainsKey(requestID))
{
return false;
}
url = m_RequestMap[requestID];
if (!url.requests.ContainsKey(requestID))
{
return false;
}
}
if (System.Environment.TickCount-url.requests[requestID].startTime>25000)
{
return true;
}
if (url.requests[requestID].requestDone)
return true;
else
return false;
}
private Hashtable GetEvents(UUID requestID, UUID sessionID, string request)
{
UrlData url = null;
RequestData requestData = null;
lock (m_RequestMap)
{
if (!m_RequestMap.ContainsKey(requestID))
return NoEvents(requestID,sessionID);
url = m_RequestMap[requestID];
requestData = url.requests[requestID];
}
if (!requestData.requestDone)
return NoEvents(requestID,sessionID);
Hashtable response = new Hashtable();
if (System.Environment.TickCount - requestData.startTime > 25000)
{
response["int_response_code"] = 500;
response["str_response_string"] = "Script timeout";
response["content_type"] = "text/plain";
response["keepalive"] = false;
response["reusecontext"] = false;
return response;
}
//put response
response["int_response_code"] = requestData.responseCode;
response["str_response_string"] = requestData.responseBody;
response["content_type"] = "text/plain";
response["keepalive"] = false;
response["reusecontext"] = false;
//remove from map
lock (url)
{
url.requests.Remove(requestID);
m_RequestMap.Remove(requestID);
}
return response; return response;
} }
public void HttpRequestHandler(UUID requestID, Hashtable request)
{
lock (request)
{
string uri = request["uri"].ToString();
try
{
Hashtable headers = (Hashtable)request["headers"];
// string uri_full = "http://" + m_ExternalHostNameForLSL + ":" + m_HttpServer.Port.ToString() + uri;// "/lslhttp/" + urlcode.ToString() + "/";
int pos1 = uri.IndexOf("/");// /lslhttp
int pos2 = uri.IndexOf("/", pos1 + 1);// /lslhttp/
int pos3 = uri.IndexOf("/", pos2 + 1);// /lslhttp/<UUID>/
string uri_tmp = uri.Substring(0, pos3 + 1);
//HTTP server code doesn't provide us with QueryStrings
string pathInfo;
string queryString;
queryString = "";
pathInfo = uri.Substring(pos3);
UrlData url = m_UrlMap["http://" + m_ExternalHostNameForLSL + ":" + m_HttpServer.Port.ToString() + uri_tmp];
//for llGetHttpHeader support we need to store original URI here
//to make x-path-info / x-query-string / x-script-url / x-remote-ip headers
//as per http://wiki.secondlife.com/wiki/LlGetHTTPHeader
RequestData requestData = new RequestData();
requestData.requestID = requestID;
requestData.requestDone = false;
requestData.startTime = System.Environment.TickCount;
requestData.uri = uri;
if (requestData.headers == null)
requestData.headers = new Dictionary<string, string>();
foreach (DictionaryEntry header in headers)
{
string key = (string)header.Key;
string value = (string)header.Value;
requestData.headers.Add(key, value);
}
foreach (DictionaryEntry de in request)
{
if (de.Key.ToString() == "querystringkeys")
{
System.String[] keys = (System.String[])de.Value;
foreach (String key in keys)
{
if (request.ContainsKey(key))
{
string val = (String)request[key];
queryString = queryString + key + "=" + val + "&";
}
}
if (queryString.Length > 1)
queryString = queryString.Substring(0, queryString.Length - 1);
}
}
//if this machine is behind DNAT/port forwarding, currently this is being
//set to address of port forwarding router
requestData.headers["x-remote-ip"] = requestData.headers["remote_addr"];
requestData.headers["x-path-info"] = pathInfo;
requestData.headers["x-query-string"] = queryString;
requestData.headers["x-script-url"] = url.url;
requestData.ev = new ManualResetEvent(false);
lock (url.requests)
{
url.requests.Add(requestID, requestData);
}
lock (m_RequestMap)
{
//add to request map
m_RequestMap.Add(requestID, url);
}
url.engine.PostScriptEvent(url.itemID, "http_request", new Object[] { requestID.ToString(), request["http-method"].ToString(), request["body"].ToString() });
//send initial response?
// Hashtable response = new Hashtable();
return;
}
catch (Exception we)
{
//Hashtable response = new Hashtable();
m_log.Warn("[HttpRequestHandler]: http-in request failed");
m_log.Warn(we.Message);
m_log.Warn(we.StackTrace);
}
}
}
private void OnScriptReset(uint localID, UUID itemID) private void OnScriptReset(uint localID, UUID itemID)
{ {

View File

@ -0,0 +1,129 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Reflection;
using System.Collections.Generic;
using log4net;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Server.Base;
using OpenSim.Server.Handlers.Base;
using OpenSim.Server.Handlers.Grid;
namespace OpenSim.Region.CoreModules.ServiceConnectorsIn.Grid
{
public class HypergridServiceInConnectorModule : ISharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static bool m_Enabled = false;
private IConfigSource m_Config;
bool m_Registered = false;
HypergridServiceInConnector m_HypergridHandler;
#region IRegionModule interface
public void Initialise(IConfigSource config)
{
//// This module is only on for standalones in hypergrid mode
//enabled = (!config.Configs["Startup"].GetBoolean("gridmode", true)) &&
// config.Configs["Startup"].GetBoolean("hypergrid", true);
//m_log.DebugFormat("[RegionInventoryService]: enabled? {0}", enabled);
m_Config = config;
IConfig moduleConfig = config.Configs["Modules"];
if (moduleConfig != null)
{
m_Enabled = moduleConfig.GetBoolean("HypergridServiceInConnector", false);
if (m_Enabled)
{
m_log.Info("[HGGRID IN CONNECTOR]: Hypergrid Service In Connector enabled");
}
}
}
public void PostInitialise()
{
}
public void Close()
{
}
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "HypergridService"; }
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
if (!m_Registered)
{
m_Registered = true;
m_log.Info("[HypergridService]: Starting...");
Object[] args = new Object[] { m_Config, MainServer.Instance };
m_HypergridHandler = new HypergridServiceInConnector(m_Config, MainServer.Instance);
//ServerUtils.LoadPlugin<HypergridServiceInConnector>("OpenSim.Server.Handlers.dll:HypergridServiceInConnector", args);
}
SimpleRegionInfo rinfo = new SimpleRegionInfo(scene.RegionInfo);
m_HypergridHandler.AddRegion(rinfo);
}
public void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
SimpleRegionInfo rinfo = new SimpleRegionInfo(scene.RegionInfo);
m_HypergridHandler.RemoveRegion(rinfo);
}
public void RegionLoaded(Scene scene)
{
}
#endregion
}
}

View File

@ -0,0 +1,303 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Xml;
using log4net;
using Nini.Config;
using OpenSim.Framework;
//using OpenSim.Framework.Communications;
using OpenSim.Framework.Console;
using OpenSim.Region.Framework;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Hypergrid;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
{
public class HGCommands
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private HGGridConnector m_HGGridConnector;
private Scene m_scene;
private static uint m_autoMappingX = 0;
private static uint m_autoMappingY = 0;
private static bool m_enableAutoMapping = false;
public HGCommands(HGGridConnector hgConnector, Scene scene)
{
m_HGGridConnector = hgConnector;
m_scene = scene;
}
//public static Scene CreateScene(RegionInfo regionInfo, AgentCircuitManager circuitManager, CommunicationsManager m_commsManager,
// StorageManager storageManager, ModuleLoader m_moduleLoader, ConfigSettings m_configSettings, OpenSimConfigSource m_config, string m_version)
//{
// HGSceneCommunicationService sceneGridService = new HGSceneCommunicationService(m_commsManager, HGServices);
// return
// new HGScene(
// regionInfo, circuitManager, m_commsManager, sceneGridService, storageManager,
// m_moduleLoader, false, m_configSettings.PhysicalPrim,
// m_configSettings.See_into_region_from_neighbor, m_config.Source, m_version);
//}
public void RunCommand(string module, string[] cmdparams)
{
List<string> args = new List<string>(cmdparams);
if (args.Count < 1)
return;
string command = args[0];
args.RemoveAt(0);
cmdparams = args.ToArray();
RunHGCommand(command, cmdparams);
}
private void RunHGCommand(string command, string[] cmdparams)
{
if (command.Equals("linkk-mapping"))
{
if (cmdparams.Length == 2)
{
try
{
m_autoMappingX = Convert.ToUInt32(cmdparams[0]);
m_autoMappingY = Convert.ToUInt32(cmdparams[1]);
m_enableAutoMapping = true;
}
catch (Exception)
{
m_autoMappingX = 0;
m_autoMappingY = 0;
m_enableAutoMapping = false;
}
}
}
else if (command.Equals("linkk-region"))
{
if (cmdparams.Length < 3)
{
if ((cmdparams.Length == 1) || (cmdparams.Length == 2))
{
LoadXmlLinkFile(cmdparams);
}
else
{
LinkRegionCmdUsage();
}
return;
}
if (cmdparams[2].Contains(":"))
{
// New format
int xloc, yloc;
string mapName;
try
{
xloc = Convert.ToInt32(cmdparams[0]);
yloc = Convert.ToInt32(cmdparams[1]);
mapName = cmdparams[2];
if (cmdparams.Length > 3)
for (int i = 3; i < cmdparams.Length; i++)
mapName += " " + cmdparams[i];
m_log.Info(">> MapName: " + mapName);
//internalPort = Convert.ToUInt32(cmdparams[4]);
//remotingPort = Convert.ToUInt32(cmdparams[5]);
}
catch (Exception e)
{
m_log.Warn("[HGrid] Wrong format for link-region command: " + e.Message);
LinkRegionCmdUsage();
return;
}
// Convert cell coordinates given by the user to meters
xloc = xloc * (int)Constants.RegionSize;
yloc = yloc * (int)Constants.RegionSize;
m_HGGridConnector.TryLinkRegionToCoords(m_scene, null, mapName, xloc, yloc);
}
else
{
// old format
GridRegion regInfo;
int xloc, yloc;
uint externalPort;
string externalHostName;
try
{
xloc = Convert.ToInt32(cmdparams[0]);
yloc = Convert.ToInt32(cmdparams[1]);
externalPort = Convert.ToUInt32(cmdparams[3]);
externalHostName = cmdparams[2];
//internalPort = Convert.ToUInt32(cmdparams[4]);
//remotingPort = Convert.ToUInt32(cmdparams[5]);
}
catch (Exception e)
{
m_log.Warn("[HGrid] Wrong format for link-region command: " + e.Message);
LinkRegionCmdUsage();
return;
}
// Convert cell coordinates given by the user to meters
xloc = xloc * (int)Constants.RegionSize;
yloc = yloc * (int)Constants.RegionSize;
if (m_HGGridConnector.TryCreateLink(m_scene, null, xloc, yloc, "", externalPort, externalHostName, out regInfo))
{
if (cmdparams.Length >= 5)
{
regInfo.RegionName = "";
for (int i = 4; i < cmdparams.Length; i++)
regInfo.RegionName += cmdparams[i] + " ";
}
}
}
return;
}
else if (command.Equals("unlinkk-region"))
{
if (cmdparams.Length < 1)
{
UnlinkRegionCmdUsage();
return;
}
if (m_HGGridConnector.TryUnlinkRegion(m_scene, cmdparams[0]))
m_log.InfoFormat("[HGrid]: Successfully unlinked {0}", cmdparams[0]);
else
m_log.InfoFormat("[HGrid]: Unable to unlink {0}, region not found", cmdparams[0]);
}
}
private void LoadXmlLinkFile(string[] cmdparams)
{
//use http://www.hgurl.com/hypergrid.xml for test
try
{
XmlReader r = XmlReader.Create(cmdparams[0]);
XmlConfigSource cs = new XmlConfigSource(r);
string[] excludeSections = null;
if (cmdparams.Length == 2)
{
if (cmdparams[1].ToLower().StartsWith("excludelist:"))
{
string excludeString = cmdparams[1].ToLower();
excludeString = excludeString.Remove(0, 12);
char[] splitter = { ';' };
excludeSections = excludeString.Split(splitter);
}
}
for (int i = 0; i < cs.Configs.Count; i++)
{
bool skip = false;
if ((excludeSections != null) && (excludeSections.Length > 0))
{
for (int n = 0; n < excludeSections.Length; n++)
{
if (excludeSections[n] == cs.Configs[i].Name.ToLower())
{
skip = true;
break;
}
}
}
if (!skip)
{
ReadLinkFromConfig(cs.Configs[i]);
}
}
}
catch (Exception e)
{
m_log.Error(e.ToString());
}
}
private void ReadLinkFromConfig(IConfig config)
{
GridRegion regInfo;
int xloc, yloc;
uint externalPort;
string externalHostName;
uint realXLoc, realYLoc;
xloc = Convert.ToInt32(config.GetString("xloc", "0"));
yloc = Convert.ToInt32(config.GetString("yloc", "0"));
externalPort = Convert.ToUInt32(config.GetString("externalPort", "0"));
externalHostName = config.GetString("externalHostName", "");
realXLoc = Convert.ToUInt32(config.GetString("real-xloc", "0"));
realYLoc = Convert.ToUInt32(config.GetString("real-yloc", "0"));
if (m_enableAutoMapping)
{
xloc = (int)((xloc % 100) + m_autoMappingX);
yloc = (int)((yloc % 100) + m_autoMappingY);
}
if (((realXLoc == 0) && (realYLoc == 0)) ||
(((realXLoc - xloc < 3896) || (xloc - realXLoc < 3896)) &&
((realYLoc - yloc < 3896) || (yloc - realYLoc < 3896))))
{
xloc = xloc * (int)Constants.RegionSize;
yloc = yloc * (int)Constants.RegionSize;
if (
m_HGGridConnector.TryCreateLink(m_scene, null, xloc, yloc, "", externalPort,
externalHostName, out regInfo))
{
regInfo.RegionName = config.GetString("localName", "");
}
}
}
private void LinkRegionCmdUsage()
{
m_log.Info("Usage: link-region <Xloc> <Yloc> <HostName>:<HttpPort>[:<RemoteRegionName>]");
m_log.Info("Usage: link-region <Xloc> <Yloc> <HostName> <HttpPort> [<LocalName>]");
m_log.Info("Usage: link-region <URI_of_xml> [<exclude>]");
}
private void UnlinkRegionCmdUsage()
{
m_log.Info("Usage: unlink-region <HostName>:<HttpPort>");
m_log.Info("Usage: unlink-region <LocalName>");
}
}
}

View File

@ -0,0 +1,560 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using System.Xml;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Hypergrid;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenSim.Server.Base;
using OpenSim.Services.Connectors.Grid;
using OpenSim.Framework.Console;
using OpenMetaverse;
using log4net;
using Nini.Config;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
{
public class HGGridConnector : ISharedRegionModule, IGridService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private bool m_Enabled = false;
private bool m_Initialized = false;
private IGridService m_GridServiceConnector;
private HypergridServiceConnector m_HypergridServiceConnector;
// Hyperlink regions are hyperlinks on the map
protected Dictionary<UUID, GridRegion> m_HyperlinkRegions = new Dictionary<UUID, GridRegion>();
// Known regions are home regions of visiting foreign users.
// They are not on the map as static hyperlinks. They are dynamic hyperlinks, they go away when
// the visitor goes away. They are mapped to X=0 on the map.
// This is key-ed on agent ID
protected Dictionary<UUID, GridRegion> m_knownRegions = new Dictionary<UUID, GridRegion>();
protected Dictionary<UUID, ulong> m_HyperlinkHandles = new Dictionary<UUID, ulong>();
#region ISharedRegionModule
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "HGGridServicesConnector"; }
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("GridServices", "");
if (name == Name)
{
IConfig gridConfig = source.Configs["GridService"];
if (gridConfig == null)
{
m_log.Error("[HGGRID CONNECTOR]: GridService missing from OpenSim.ini");
return;
}
InitialiseConnectorModule(source);
m_Enabled = true;
m_log.Info("[HGGRID CONNECTOR]: HG grid enabled");
}
}
}
private void InitialiseConnectorModule(IConfigSource source)
{
IConfig gridConfig = source.Configs["GridService"];
if (gridConfig == null)
{
m_log.Error("[HGGRID CONNECTOR]: GridService missing from OpenSim.ini");
throw new Exception("Grid connector init error");
}
string module = gridConfig.GetString("GridServiceConnectorModule", String.Empty);
if (module == String.Empty)
{
m_log.Error("[HGGRID CONNECTOR]: No GridServiceConnectorModule named in section GridService");
//return;
throw new Exception("Unable to proceed. Please make sure your ini files in config-include are updated according to .example's");
}
Object[] args = new Object[] { source };
m_GridServiceConnector = ServerUtils.LoadPlugin<IGridService>(module, args);
}
public void PostInitialise()
{
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
scene.RegisterModuleInterface<IGridService>(this);
}
public void RemoveRegion(Scene scene)
{
}
public void RegionLoaded(Scene scene)
{
if (!m_Enabled)
return;
if (!m_Initialized)
{
m_HypergridServiceConnector = new HypergridServiceConnector(scene.AssetService);
HGCommands hgCommands = new HGCommands(this, scene);
MainConsole.Instance.Commands.AddCommand("HGGridServicesConnector", false, "linkk-region",
"link-region <Xloc> <Yloc> <HostName>:<HttpPort>[:<RemoteRegionName>] <cr>",
"Link a hypergrid region", hgCommands.RunCommand);
MainConsole.Instance.Commands.AddCommand("HGGridServicesConnector", false, "unlinkk-region",
"unlink-region <local name> or <HostName>:<HttpPort> <cr>",
"Unlink a hypergrid region", hgCommands.RunCommand);
MainConsole.Instance.Commands.AddCommand("HGGridServicesConnector", false, "linkk-mapping", "link-mapping [<x> <y>] <cr>",
"Set local coordinate to map HG regions to", hgCommands.RunCommand);
m_Initialized = true;
}
//scene.AddCommand("HGGridServicesConnector", "linkk-region",
// "link-region <Xloc> <Yloc> <HostName>:<HttpPort>[:<RemoteRegionName>] <cr>",
// "Link a hypergrid region", hgCommands.RunCommand);
//scene.AddCommand("HGGridServicesConnector", "unlinkk-region",
// "unlink-region <local name> or <HostName>:<HttpPort> <cr>",
// "Unlink a hypergrid region", hgCommands.RunCommand);
//scene.AddCommand("HGGridServicesConnector", "linkk-mapping", "link-mapping [<x> <y>] <cr>",
// "Set local coordinate to map HG regions to", hgCommands.RunCommand);
}
#endregion
#region IGridService
public bool RegisterRegion(UUID scopeID, GridRegion regionInfo)
{
// Region doesn't exist here. Trying to link remote region
if (regionInfo.RegionID.Equals(UUID.Zero))
{
m_log.Info("[HGrid]: Linking remote region " + regionInfo.ExternalHostName + ":" + regionInfo.HttpPort);
ulong regionHandle = 0;
regionInfo.RegionID = m_HypergridServiceConnector.LinkRegion(regionInfo, out regionHandle);
if (!regionInfo.RegionID.Equals(UUID.Zero))
{
AddHyperlinkRegion(regionInfo, regionHandle);
m_log.Info("[HGrid]: Successfully linked to region_uuid " + regionInfo.RegionID);
// Try get the map image
m_HypergridServiceConnector.GetMapImage(regionInfo);
return true;
}
else
{
m_log.Info("[HGrid]: No such region " + regionInfo.ExternalHostName + ":" + regionInfo.HttpPort + "(" + regionInfo.InternalEndPoint.Port + ")");
return false;
}
// Note that these remote regions aren't registered in localBackend, so return null, no local listeners
}
else // normal grid
return m_GridServiceConnector.RegisterRegion(scopeID, regionInfo);
}
public bool DeregisterRegion(UUID regionID)
{
// Try the hyperlink collection
if (m_HyperlinkRegions.ContainsKey(regionID))
{
RemoveHyperlinkRegion(regionID);
return true;
}
// Try the foreign users home collection
foreach (GridRegion r in m_knownRegions.Values)
if (r.RegionID == regionID)
{
RemoveHyperlinkHomeRegion(regionID);
return true;
}
// Finally, try the normal route
return m_GridServiceConnector.DeregisterRegion(regionID);
}
public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID)
{
// No serving neighbours on hyperliked regions.
// Just the regular regions.
return m_GridServiceConnector.GetNeighbours(scopeID, regionID);
}
public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID)
{
// Try the hyperlink collection
if (m_HyperlinkRegions.ContainsKey(regionID))
return m_HyperlinkRegions[regionID];
// Try the foreign users home collection
foreach (GridRegion r in m_knownRegions.Values)
if (r.RegionID == regionID)
return m_knownRegions[regionID];
// Finally, try the normal route
return m_GridServiceConnector.GetRegionByUUID(scopeID, regionID);
}
public GridRegion GetRegionByPosition(UUID scopeID, int x, int y)
{
int snapX = (int) (x / Constants.RegionSize) * (int)Constants.RegionSize;
int snapY = (int) (y / Constants.RegionSize) * (int)Constants.RegionSize;
// Try the hyperlink collection
foreach (GridRegion r in m_HyperlinkRegions.Values)
{
if ((r.RegionLocX == snapX) && (r.RegionLocY == snapY))
return r;
}
// Try the foreign users home collection
foreach (GridRegion r in m_knownRegions.Values)
{
if ((r.RegionLocX == snapX) && (r.RegionLocY == snapY))
return r;
}
// Finally, try the normal route
return m_GridServiceConnector.GetRegionByPosition(scopeID, x, y);
}
public GridRegion GetRegionByName(UUID scopeID, string regionName)
{
// Try normal grid first
GridRegion region = m_GridServiceConnector.GetRegionByName(scopeID, regionName);
if (region != null)
return region;
// Try the hyperlink collection
foreach (GridRegion r in m_HyperlinkRegions.Values)
{
if (r.RegionName == regionName)
return r;
}
// Try the foreign users home collection
foreach (GridRegion r in m_knownRegions.Values)
{
if (r.RegionName == regionName)
return r;
}
return null;
}
public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber)
{
List<GridRegion> rinfos = new List<GridRegion>();
// Commenting until regionname exists
//foreach (SimpleRegionInfo r in m_HyperlinkRegions.Values)
// if ((r.RegionName != null) && r.RegionName.StartsWith(name))
// rinfos.Add(r);
rinfos.AddRange(m_GridServiceConnector.GetRegionsByName(scopeID, name, maxNumber));
return rinfos;
}
public List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax)
{
int snapXmin = (int)(xmin / Constants.RegionSize) * (int)Constants.RegionSize;
int snapXmax = (int)(xmax / Constants.RegionSize) * (int)Constants.RegionSize;
int snapYmin = (int)(ymin / Constants.RegionSize) * (int)Constants.RegionSize;
int snapYmax = (int)(ymax / Constants.RegionSize) * (int)Constants.RegionSize;
List<GridRegion> rinfos = new List<GridRegion>();
foreach (GridRegion r in m_HyperlinkRegions.Values)
if ((r.RegionLocX > snapXmin) && (r.RegionLocX < snapYmax) &&
(r.RegionLocY > snapYmin) && (r.RegionLocY < snapYmax))
rinfos.Add(r);
rinfos.AddRange(m_GridServiceConnector.GetRegionRange(scopeID, xmin, xmax, ymin, ymax));
return rinfos;
}
#endregion
#region Auxiliary
private void AddHyperlinkRegion(GridRegion regionInfo, ulong regionHandle)
{
m_HyperlinkRegions.Add(regionInfo.RegionID, regionInfo);
m_HyperlinkHandles.Add(regionInfo.RegionID, regionHandle);
}
private void RemoveHyperlinkRegion(UUID regionID)
{
m_HyperlinkRegions.Remove(regionID);
m_HyperlinkHandles.Remove(regionID);
}
private void AddHyperlinkHomeRegion(UUID userID, GridRegion regionInfo, ulong regionHandle)
{
m_knownRegions.Add(userID, regionInfo);
m_HyperlinkHandles.Add(regionInfo.RegionID, regionHandle);
}
private void RemoveHyperlinkHomeRegion(UUID regionID)
{
foreach (KeyValuePair<UUID, GridRegion> kvp in m_knownRegions)
{
if (kvp.Value.RegionID == regionID)
{
m_knownRegions.Remove(kvp.Key);
}
}
m_HyperlinkHandles.Remove(regionID);
}
#endregion
#region Hyperlinks
private static Random random = new Random();
public GridRegion TryLinkRegionToCoords(Scene m_scene, IClientAPI client, string mapName, int xloc, int yloc)
{
string host = "127.0.0.1";
string portstr;
string regionName = "";
uint port = 9000;
string[] parts = mapName.Split(new char[] { ':' });
if (parts.Length >= 1)
{
host = parts[0];
}
if (parts.Length >= 2)
{
portstr = parts[1];
if (!UInt32.TryParse(portstr, out port))
regionName = parts[1];
}
// always take the last one
if (parts.Length >= 3)
{
regionName = parts[2];
}
// Sanity check. Don't ever link to this sim.
IPAddress ipaddr = null;
try
{
ipaddr = Util.GetHostFromDNS(host);
}
catch { }
if ((ipaddr != null) &&
!((m_scene.RegionInfo.ExternalEndPoint.Address.Equals(ipaddr)) && (m_scene.RegionInfo.HttpPort == port)))
{
GridRegion regInfo;
bool success = TryCreateLink(m_scene, client, xloc, yloc, regionName, port, host, out regInfo);
if (success)
{
regInfo.RegionName = mapName;
return regInfo;
}
}
return null;
}
// From the map search and secondlife://blah
public GridRegion TryLinkRegion(Scene m_scene, IClientAPI client, string mapName)
{
int xloc = random.Next(0, Int16.MaxValue);
return TryLinkRegionToCoords(m_scene, client, mapName, xloc, 0);
}
public bool TryCreateLink(Scene m_scene, IClientAPI client, int xloc, int yloc,
string externalRegionName, uint externalPort, string externalHostName, out GridRegion regInfo)
{
m_log.DebugFormat("[HGrid]: Link to {0}:{1}, in {2}-{3}", externalHostName, externalPort, xloc, yloc);
regInfo = new GridRegion();
regInfo.RegionName = externalRegionName;
regInfo.HttpPort = externalPort;
regInfo.ExternalHostName = externalHostName;
regInfo.RegionLocX = xloc;
regInfo.RegionLocY = yloc;
try
{
regInfo.InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), (int)0);
}
catch (Exception e)
{
m_log.Warn("[HGrid]: Wrong format for link-region: " + e.Message);
return false;
}
// Finally, link it
try
{
RegisterRegion(UUID.Zero, regInfo);
}
catch (Exception e)
{
m_log.Warn("[HGrid]: Unable to link region: " + e.Message);
return false;
}
int x, y;
if (!Check4096(m_scene, regInfo, out x, out y))
{
DeregisterRegion(regInfo.RegionID);
if (client != null)
client.SendAlertMessage("Region is too far (" + x + ", " + y + ")");
m_log.Info("[HGrid]: Unable to link, region is too far (" + x + ", " + y + ")");
return false;
}
if (!CheckCoords(m_scene.RegionInfo.RegionLocX, m_scene.RegionInfo.RegionLocY, x, y))
{
DeregisterRegion(regInfo.RegionID);
if (client != null)
client.SendAlertMessage("Region has incompatible coordinates (" + x + ", " + y + ")");
m_log.Info("[HGrid]: Unable to link, region has incompatible coordinates (" + x + ", " + y + ")");
return false;
}
m_log.Debug("[HGrid]: link region succeeded");
return true;
}
public bool TryUnlinkRegion(Scene m_scene, string mapName)
{
GridRegion regInfo = null;
if (mapName.Contains(":"))
{
string host = "127.0.0.1";
//string portstr;
//string regionName = "";
uint port = 9000;
string[] parts = mapName.Split(new char[] { ':' });
if (parts.Length >= 1)
{
host = parts[0];
}
// if (parts.Length >= 2)
// {
// portstr = parts[1];
// if (!UInt32.TryParse(portstr, out port))
// regionName = parts[1];
// }
// always take the last one
// if (parts.Length >= 3)
// {
// regionName = parts[2];
// }
foreach (GridRegion r in m_HyperlinkRegions.Values)
if (host.Equals(r.ExternalHostName) && (port == r.HttpPort))
regInfo = r;
}
else
{
foreach (GridRegion r in m_HyperlinkRegions.Values)
if (r.RegionName.Equals(mapName))
regInfo = r;
}
if (regInfo != null)
{
return DeregisterRegion(regInfo.RegionID);
}
else
{
m_log.InfoFormat("[HGrid]: Region {0} not found", mapName);
return false;
}
}
/// <summary>
/// Cope with this viewer limitation.
/// </summary>
/// <param name="regInfo"></param>
/// <returns></returns>
public bool Check4096(Scene m_scene, GridRegion regInfo, out int x, out int y)
{
ulong realHandle = m_HyperlinkHandles[regInfo.RegionID];
uint ux = 0, uy = 0;
Utils.LongToUInts(realHandle, out ux, out uy);
x = (int)(ux / Constants.RegionSize);
y = (int)(uy / Constants.RegionSize);
if ((Math.Abs((int)(m_scene.RegionInfo.RegionLocX / Constants.RegionSize) - x) >= 4096) ||
(Math.Abs((int)(m_scene.RegionInfo.RegionLocY / Constants.RegionSize) - y) >= 4096))
{
return false;
}
return true;
}
public bool CheckCoords(uint thisx, uint thisy, int x, int y)
{
if ((thisx == x) && (thisy == y))
return false;
return true;
}
#endregion
}
}

View File

@ -35,6 +35,7 @@ using OpenSim.Server.Base;
using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces; using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenMetaverse; using OpenMetaverse;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
@ -50,6 +51,16 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
private bool m_Enabled = false; private bool m_Enabled = false;
public LocalGridServicesConnector()
{
}
public LocalGridServicesConnector(IConfigSource source)
{
m_log.Debug("[LOCAL GRID CONNECTOR]: LocalGridServicesConnector instantiated");
InitialiseService(source);
}
#region ISharedRegionModule #region ISharedRegionModule
public Type ReplaceableInterface public Type ReplaceableInterface
@ -70,38 +81,43 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
string name = moduleConfig.GetString("GridServices", ""); string name = moduleConfig.GetString("GridServices", "");
if (name == Name) if (name == Name)
{ {
IConfig assetConfig = source.Configs["GridService"]; InitialiseService(source);
if (assetConfig == null)
{
m_log.Error("[GRID CONNECTOR]: GridService missing from OpenSim.ini");
return;
}
string serviceDll = assetConfig.GetString("LocalServiceModule",
String.Empty);
if (serviceDll == String.Empty)
{
m_log.Error("[GRID CONNECTOR]: No LocalServiceModule named in section GridService");
return;
}
Object[] args = new Object[] { source };
m_GridService =
ServerUtils.LoadPlugin<IGridService>(serviceDll,
args);
if (m_GridService == null)
{
m_log.Error("[GRID CONNECTOR]: Can't load asset service");
return;
}
m_Enabled = true; m_Enabled = true;
m_log.Info("[GRID CONNECTOR]: Local grid connector enabled"); m_log.Info("[LOCAL GRID CONNECTOR]: Local grid connector enabled");
} }
} }
} }
private void InitialiseService(IConfigSource source)
{
IConfig assetConfig = source.Configs["GridService"];
if (assetConfig == null)
{
m_log.Error("[LOCAL GRID CONNECTOR]: GridService missing from OpenSim.ini");
return;
}
string serviceDll = assetConfig.GetString("LocalServiceModule",
String.Empty);
if (serviceDll == String.Empty)
{
m_log.Error("[LOCAL GRID CONNECTOR]: No LocalServiceModule named in section GridService");
return;
}
Object[] args = new Object[] { source };
m_GridService =
ServerUtils.LoadPlugin<IGridService>(serviceDll,
args);
if (m_GridService == null)
{
m_log.Error("[LOCAL GRID CONNECTOR]: Can't load grid service");
return;
}
}
public void PostInitialise() public void PostInitialise()
{ {
} }
@ -130,7 +146,7 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
#region IGridService #region IGridService
public bool RegisterRegion(UUID scopeID, SimpleRegionInfo regionInfo) public bool RegisterRegion(UUID scopeID, GridRegion regionInfo)
{ {
return m_GridService.RegisterRegion(scopeID, regionInfo); return m_GridService.RegisterRegion(scopeID, regionInfo);
} }
@ -140,32 +156,32 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
return m_GridService.DeregisterRegion(regionID); return m_GridService.DeregisterRegion(regionID);
} }
public List<SimpleRegionInfo> GetNeighbours(UUID scopeID, int x, int y) public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID)
{ {
return m_GridService.GetNeighbours(scopeID, x, y); return m_GridService.GetNeighbours(scopeID, regionID);
} }
public SimpleRegionInfo GetRegionByUUID(UUID scopeID, UUID regionID) public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID)
{ {
return m_GridService.GetRegionByUUID(scopeID, regionID); return m_GridService.GetRegionByUUID(scopeID, regionID);
} }
public SimpleRegionInfo GetRegionByPosition(UUID scopeID, int x, int y) public GridRegion GetRegionByPosition(UUID scopeID, int x, int y)
{ {
return m_GridService.GetRegionByPosition(scopeID, x, y); return m_GridService.GetRegionByPosition(scopeID, x, y);
} }
public SimpleRegionInfo GetRegionByName(UUID scopeID, string regionName) public GridRegion GetRegionByName(UUID scopeID, string regionName)
{ {
return m_GridService.GetRegionByName(scopeID, regionName); return m_GridService.GetRegionByName(scopeID, regionName);
} }
public List<SimpleRegionInfo> GetRegionsByName(UUID scopeID, string name, int maxNumber) public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber)
{ {
return m_GridService.GetRegionsByName(scopeID, name, maxNumber); return m_GridService.GetRegionsByName(scopeID, name, maxNumber);
} }
public List<SimpleRegionInfo> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax) public List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax)
{ {
return m_GridService.GetRegionRange(scopeID, xmin, xmax, ymin, ymax); return m_GridService.GetRegionRange(scopeID, xmin, xmax, ymin, ymax);
} }

View File

@ -0,0 +1,183 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using System;
using System.Collections.Generic;
using System.Reflection;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Services.Connectors;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
{
public class RemoteGridServicesConnector :
GridServicesConnector, ISharedRegionModule, IGridService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private bool m_Enabled = false;
private IGridService m_LocalGridService;
public RemoteGridServicesConnector()
{
}
public RemoteGridServicesConnector(IConfigSource source)
{
InitialiseServices(source);
}
#region ISharedRegionmodule
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "RemoteGridServicesConnector"; }
}
public override void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("GridServices", "");
if (name == Name)
{
InitialiseServices(source);
m_Enabled = true;
m_log.Info("[REMOTE GRID CONNECTOR]: Remote grid enabled");
}
}
}
private void InitialiseServices(IConfigSource source)
{
IConfig gridConfig = source.Configs["GridService"];
if (gridConfig == null)
{
m_log.Error("[REMOTE GRID CONNECTOR]: GridService missing from OpenSim.ini");
return;
}
base.Initialise(source);
m_LocalGridService = new LocalGridServicesConnector(source);
}
public void PostInitialise()
{
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
scene.RegisterModuleInterface<IGridService>(this);
}
public void RemoveRegion(Scene scene)
{
}
public void RegionLoaded(Scene scene)
{
}
#endregion
#region IGridService
public override bool RegisterRegion(UUID scopeID, GridRegion regionInfo)
{
if (m_LocalGridService.RegisterRegion(scopeID, regionInfo))
return base.RegisterRegion(scopeID, regionInfo);
return false;
}
public override bool DeregisterRegion(UUID regionID)
{
if (m_LocalGridService.DeregisterRegion(regionID))
return base.DeregisterRegion(regionID);
return false;
}
// Let's not override GetNeighbours -- let's get them all from the grid server
public override GridRegion GetRegionByUUID(UUID scopeID, UUID regionID)
{
GridRegion rinfo = m_LocalGridService.GetRegionByUUID(scopeID, regionID);
if (rinfo == null)
rinfo = base.GetRegionByUUID(scopeID, regionID);
return rinfo;
}
public override GridRegion GetRegionByPosition(UUID scopeID, int x, int y)
{
GridRegion rinfo = m_LocalGridService.GetRegionByPosition(scopeID, x, y);
if (rinfo == null)
rinfo = base.GetRegionByPosition(scopeID, x, y);
return rinfo;
}
public override GridRegion GetRegionByName(UUID scopeID, string regionName)
{
GridRegion rinfo = m_LocalGridService.GetRegionByName(scopeID, regionName);
if (rinfo == null)
rinfo = base.GetRegionByName(scopeID, regionName);
return rinfo;
}
// Let's not override GetRegionsByName -- let's get them all from the grid server
// Let's not override GetRegionRange -- let's get them all from the grid server
#endregion
}
}

View File

@ -0,0 +1,131 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading;
using log4net.Config;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
using OpenMetaverse;
using OpenSim.Framework;
using Nini.Config;
using OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid;
using OpenSim.Region.Framework.Scenes;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenSim.Tests.Common;
using OpenSim.Tests.Common.Setup;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid.Tests
{
[TestFixture]
public class GridConnectorsTests
{
LocalGridServicesConnector m_LocalConnector;
private void SetUp()
{
IConfigSource config = new IniConfigSource();
config.AddConfig("Modules");
config.AddConfig("GridService");
config.Configs["Modules"].Set("GridServices", "LocalGridServicesConnector");
config.Configs["GridService"].Set("LocalServiceModule", "OpenSim.Services.GridService.dll:GridService");
config.Configs["GridService"].Set("StorageProvider", "OpenSim.Data.Null.dll:NullRegionData");
m_LocalConnector = new LocalGridServicesConnector(config);
}
/// <summary>
/// Test saving a V0.2 OpenSim Region Archive.
/// </summary>
[Test]
public void TestRegisterRegionV0_2()
{
SetUp();
// Create 3 regions
GridRegion r1 = new GridRegion();
r1.RegionName = "Test Region 1";
r1.RegionID = new UUID(1);
r1.RegionLocX = 1000 * (int)Constants.RegionSize;
r1.RegionLocY = 1000 * (int)Constants.RegionSize;
r1.ExternalHostName = "127.0.0.1";
r1.HttpPort = 9001;
r1.InternalEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("0.0.0.0"), 0);
GridRegion r2 = new GridRegion();
r2.RegionName = "Test Region 2";
r2.RegionID = new UUID(2);
r2.RegionLocX = 1001 * (int)Constants.RegionSize;
r2.RegionLocY = 1000 * (int)Constants.RegionSize;
r2.ExternalHostName = "127.0.0.1";
r2.HttpPort = 9002;
r2.InternalEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("0.0.0.0"), 0);
GridRegion r3 = new GridRegion();
r3.RegionName = "Test Region 3";
r3.RegionID = new UUID(3);
r3.RegionLocX = 1005 * (int)Constants.RegionSize;
r3.RegionLocY = 1000 * (int)Constants.RegionSize;
r3.ExternalHostName = "127.0.0.1";
r3.HttpPort = 9003;
r3.InternalEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("0.0.0.0"), 0);
m_LocalConnector.RegisterRegion(UUID.Zero, r1);
GridRegion result = m_LocalConnector.GetRegionByName(UUID.Zero, "Test");
Assert.IsNotNull(result, "Retrieved GetRegionByName is null");
Assert.That(result.RegionName, Is.EqualTo("Test Region 1"), "Retrieved region's name does not match");
result = m_LocalConnector.GetRegionByUUID(UUID.Zero, new UUID(1));
Assert.IsNotNull(result, "Retrieved GetRegionByUUID is null");
Assert.That(result.RegionID, Is.EqualTo(new UUID(1)), "Retrieved region's UUID does not match");
result = m_LocalConnector.GetRegionByPosition(UUID.Zero, 1000 * (int)Constants.RegionSize, 1000 * (int)Constants.RegionSize);
Assert.IsNotNull(result, "Retrieved GetRegionByPosition is null");
Assert.That(result.RegionLocX, Is.EqualTo(1000 * (int)Constants.RegionSize), "Retrieved region's position does not match");
m_LocalConnector.RegisterRegion(UUID.Zero, r2);
m_LocalConnector.RegisterRegion(UUID.Zero, r3);
List<GridRegion> results = m_LocalConnector.GetNeighbours(UUID.Zero, new UUID(1));
Assert.IsNotNull(results, "Retrieved neighbours list is null");
Assert.That(results.Count, Is.EqualTo(1), "Retrieved neighbour collection is greater than expected");
Assert.That(results[0].RegionID, Is.EqualTo(new UUID(2)), "Retrieved region's UUID does not match");
results = m_LocalConnector.GetRegionsByName(UUID.Zero, "Test", 10);
Assert.IsNotNull(results, "Retrieved GetRegionsByName list is null");
Assert.That(results.Count, Is.EqualTo(3), "Retrieved neighbour collection is less than expected");
results = m_LocalConnector.GetRegionRange(UUID.Zero, 900 * (int)Constants.RegionSize, 1002 * (int)Constants.RegionSize,
900 * (int)Constants.RegionSize, 1100 * (int)Constants.RegionSize);
Assert.IsNotNull(results, "Retrieved GetRegionRange list is null");
Assert.That(results.Count, Is.EqualTo(2), "Retrieved neighbour collection is not the number expected");
}
}
}

View File

@ -33,7 +33,6 @@ using log4net;
using Nini.Config; using Nini.Config;
using OpenMetaverse; using OpenMetaverse;
using OpenSim.Framework; using OpenSim.Framework;
using OpenSim.Region.CoreModules.World.Terrain;
using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes;
@ -47,7 +46,7 @@ namespace OpenSim.Region.CoreModules.World.Estate
private Scene m_scene; private Scene m_scene;
private EstateTerrainXferHandler TerrainUploader = null; private EstateTerrainXferHandler TerrainUploader;
#region Packet Data Responders #region Packet Data Responders
@ -155,6 +154,7 @@ namespace OpenSim.Region.CoreModules.World.Estate
break; break;
} }
m_scene.RegionInfo.RegionSettings.Save(); m_scene.RegionInfo.RegionSettings.Save();
sendRegionInfoPacketToAll();
} }
public void setEstateTerrainTextureHeights(IClientAPI client, int corner, float lowValue, float highValue) public void setEstateTerrainTextureHeights(IClientAPI client, int corner, float lowValue, float highValue)
@ -179,6 +179,7 @@ namespace OpenSim.Region.CoreModules.World.Estate
break; break;
} }
m_scene.RegionInfo.RegionSettings.Save(); m_scene.RegionInfo.RegionSettings.Save();
sendRegionInfoPacketToAll();
} }
private void handleCommitEstateTerrainTextureRequest(IClientAPI remoteClient) private void handleCommitEstateTerrainTextureRequest(IClientAPI remoteClient)
@ -668,7 +669,7 @@ namespace OpenSim.Region.CoreModules.World.Estate
LookupUUID(uuidNameLookupList); LookupUUID(uuidNameLookupList);
} }
private void LookupUUIDSCompleted(IAsyncResult iar) private static void LookupUUIDSCompleted(IAsyncResult iar)
{ {
LookupUUIDS icon = (LookupUUIDS)iar.AsyncState; LookupUUIDS icon = (LookupUUIDS)iar.AsyncState;
icon.EndInvoke(iar); icon.EndInvoke(iar);
@ -683,7 +684,7 @@ namespace OpenSim.Region.CoreModules.World.Estate
} }
private void LookupUUIDsAsync(List<UUID> uuidLst) private void LookupUUIDsAsync(List<UUID> uuidLst)
{ {
UUID[] uuidarr = new UUID[0]; UUID[] uuidarr;
lock (uuidLst) lock (uuidLst)
{ {
@ -707,7 +708,7 @@ namespace OpenSim.Region.CoreModules.World.Estate
for (int i = 0; i < avatars.Count; i++) for (int i = 0; i < avatars.Count; i++)
{ {
HandleRegionInfoRequest(avatars[i].ControllingClient); ; HandleRegionInfoRequest(avatars[i].ControllingClient);
} }
} }
@ -768,7 +769,7 @@ namespace OpenSim.Region.CoreModules.World.Estate
else else
{ {
m_scene.RegionInfo.EstateSettings.UseGlobalTime = false; m_scene.RegionInfo.EstateSettings.UseGlobalTime = false;
m_scene.RegionInfo.EstateSettings.SunPosition = (double)(parms2 - 0x1800)/1024.0; m_scene.RegionInfo.EstateSettings.SunPosition = (parms2 - 0x1800)/1024.0;
} }
if ((parms1 & 0x00000010) != 0) if ((parms1 & 0x00000010) != 0)
@ -828,8 +829,60 @@ namespace OpenSim.Region.CoreModules.World.Estate
m_scene.RegisterModuleInterface<IEstateModule>(this); m_scene.RegisterModuleInterface<IEstateModule>(this);
m_scene.EventManager.OnNewClient += EventManager_OnNewClient; m_scene.EventManager.OnNewClient += EventManager_OnNewClient;
m_scene.EventManager.OnRequestChangeWaterHeight += changeWaterHeight; m_scene.EventManager.OnRequestChangeWaterHeight += changeWaterHeight;
m_scene.AddCommand(this, "set terrain texture",
"set terrain texture <number> <uuid> [<x>] [<y>]",
"Sets the terrain <number> to <uuid>, if <x> or <y> are specified, it will only " +
"set it on regions with a matching coordinate. Specify -1 in <x> or <y> to wildcard" +
" that coordinate.",
consoleSetTerrainTexture);
m_scene.AddCommand(this, "set terrain heights",
"set terrain heights <corner> <min> <max> [<x>] [<y>]",
"Sets the terrain texture heights on corner #<corner> to <min>/<max>, if <x> or <y> are specified, it will only " +
"set it on regions with a matching coordinate. Specify -1 in <x> or <y> to wildcard" +
" that coordinate. Corner # SW = 0, NW = 1, SE = 2, NE = 3.",
consoleSetTerrainHeights);
} }
#region Console Commands
public void consoleSetTerrainTexture(string module, string[] args)
{
string num = args[3];
string uuid = args[4];
int x = (args.Length > 5 ? int.Parse(args[5]) : -1);
int y = (args.Length > 6 ? int.Parse(args[6]) : -1);
if (x == -1 || m_scene.RegionInfo.RegionLocX == x)
{
if (y == -1 || m_scene.RegionInfo.RegionLocY == y)
{
m_log.Debug("[ESTATEMODULE] Setting terrain textures for " + m_scene.RegionInfo.RegionName);
setEstateTerrainBaseTexture(null, int.Parse(num), UUID.Parse(uuid));
}
}
}
public void consoleSetTerrainHeights(string module, string[] args)
{
string num = args[3];
string min = args[4];
string max = args[5];
int x = (args.Length > 6 ? int.Parse(args[6]) : -1);
int y = (args.Length > 7 ? int.Parse(args[7]) : -1);
if (x == -1 || m_scene.RegionInfo.RegionLocX == x)
{
if (y == -1 || m_scene.RegionInfo.RegionLocY == y)
{
m_log.Debug("[ESTATEMODULE] Setting terrain heights " + m_scene.RegionInfo.RegionName);
setEstateTerrainTextureHeights(null, int.Parse(num), float.Parse(min), float.Parse(max));
}
}
}
#endregion
public void PostInitialise() public void PostInitialise()
{ {

View File

@ -79,12 +79,12 @@ namespace OpenSim.Region.CoreModules.World.Land
{ {
if (!enabledYN) if (!enabledYN)
return; return;
/*
// For testing on a single instance // For testing on a single instance
if (scene.RegionInfo.RegionLocX == 1004 && scene.RegionInfo.RegionLocY == 1000) if (scene.RegionInfo.RegionLocX == 1004 && scene.RegionInfo.RegionLocY == 1000)
return; return;
// //
*/
lock (m_startingScenes) lock (m_startingScenes)
m_startingScenes.Add(scene.RegionInfo.originRegionID, scene); m_startingScenes.Add(scene.RegionInfo.originRegionID, scene);

View File

@ -47,8 +47,7 @@ namespace OpenSim.Region.Framework.Scenes.Hypergrid
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// This maps between inventory server urls and inventory server clients // This maps between inventory server urls and inventory server clients
private Dictionary<string, InventoryClient> m_inventoryServers = new Dictionary<string, InventoryClient>(); // private Dictionary<string, InventoryClient> m_inventoryServers = new Dictionary<string, InventoryClient>();
private Scene m_scene; private Scene m_scene;
#endregion #endregion
@ -72,13 +71,13 @@ namespace OpenSim.Region.Framework.Scenes.Hypergrid
return null; return null;
} }
private string UserInventoryURL(UUID userID) // private string UserInventoryURL(UUID userID)
{ // {
CachedUserInfo uinfo = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(userID); // CachedUserInfo uinfo = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(userID);
if (uinfo != null) // if (uinfo != null)
return (uinfo.UserProfile.UserInventoryURI == "") ? null : uinfo.UserProfile.UserInventoryURI; // return (uinfo.UserProfile.UserInventoryURI == "") ? null : uinfo.UserProfile.UserInventoryURI;
return null; // return null;
} // }
private bool IsLocalUser(UUID userID) private bool IsLocalUser(UUID userID)
{ {

View File

@ -77,7 +77,7 @@ namespace OpenSim.Region.Framework.Scenes.Hypergrid
if (regionHandle == m_regionInfo.RegionHandle) if (regionHandle == m_regionInfo.RegionHandle)
{ {
// Teleport within the same region // Teleport within the same region
if (position.X < 0 || position.X > Constants.RegionSize || position.Y < 0 || position.Y > Constants.RegionSize || position.Z < 0) if (IsOutsideRegion(avatar.Scene, position) || position.Z < 0)
{ {
Vector3 emergencyPos = new Vector3(128, 128, 128); Vector3 emergencyPos = new Vector3(128, 128, 128);
@ -89,7 +89,13 @@ namespace OpenSim.Region.Framework.Scenes.Hypergrid
// TODO: Get proper AVG Height // TODO: Get proper AVG Height
float localAVHeight = 1.56f; float localAVHeight = 1.56f;
float posZLimit = (float)avatar.Scene.Heightmap[(int)position.X, (int)position.Y]; float posZLimit = 22;
if (position.X > 0 && position.X <= (int)Constants.RegionSize && position.Y > 0 && position.Y <= (int)Constants.RegionSize)
{
posZLimit = (float) avatar.Scene.Heightmap[(int) position.X, (int) position.Y];
}
float newPosZ = posZLimit + localAVHeight; float newPosZ = posZLimit + localAVHeight;
if (posZLimit >= (position.Z - (localAVHeight / 2)) && !(Single.IsInfinity(newPosZ) || Single.IsNaN(newPosZ))) if (posZLimit >= (position.Z - (localAVHeight / 2)) && !(Single.IsInfinity(newPosZ) || Single.IsNaN(newPosZ)))
{ {

View File

@ -63,6 +63,13 @@ namespace OpenSim.Region.Framework.Scenes
protected List<UUID> m_agentsInTransit; protected List<UUID> m_agentsInTransit;
public bool RegionLoginsEnabled
{
get { return m_regionLoginsEnabled; }
set { m_regionLoginsEnabled = value; }
}
private bool m_regionLoginsEnabled = false;
/// <summary> /// <summary>
/// An agent is crossing into this region /// An agent is crossing into this region
/// </summary> /// </summary>
@ -1163,7 +1170,7 @@ namespace OpenSim.Region.Framework.Scenes
} }
} }
private bool IsOutsideRegion(Scene s, Vector3 pos) protected bool IsOutsideRegion(Scene s, Vector3 pos)
{ {
if (s.TestBorderCross(pos,Cardinals.N)) if (s.TestBorderCross(pos,Cardinals.N))

View File

@ -245,6 +245,11 @@ namespace OpenSim.Region.Framework.Scenes
} }
} }
private bool IsAttachmentCheckFull()
{
return (IsAttachment || (m_rootPart.Shape.PCode == 9 && m_rootPart.Shape.State != 0));
}
/// <summary> /// <summary>
/// The absolute position of this scene object in the scene /// The absolute position of this scene object in the scene
/// </summary> /// </summary>
@ -257,7 +262,7 @@ namespace OpenSim.Region.Framework.Scenes
if ((m_scene.TestBorderCross(val - Vector3.UnitX, Cardinals.E) || m_scene.TestBorderCross(val + Vector3.UnitX, Cardinals.W) if ((m_scene.TestBorderCross(val - Vector3.UnitX, Cardinals.E) || m_scene.TestBorderCross(val + Vector3.UnitX, Cardinals.W)
|| m_scene.TestBorderCross(val - Vector3.UnitY, Cardinals.N) || m_scene.TestBorderCross(val + Vector3.UnitY, Cardinals.S)) || m_scene.TestBorderCross(val - Vector3.UnitY, Cardinals.N) || m_scene.TestBorderCross(val + Vector3.UnitY, Cardinals.S))
&& !IsAttachment) && !IsAttachmentCheckFull())
{ {
m_scene.CrossPrimGroupIntoNewRegion(val, this, true); m_scene.CrossPrimGroupIntoNewRegion(val, this, true);
} }

View File

@ -204,7 +204,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
tempAngularVelocity2 = new btVector3(0, 0, 0); tempAngularVelocity2 = new btVector3(0, 0, 0);
tempInertia1 = new btVector3(0, 0, 0); tempInertia1 = new btVector3(0, 0, 0);
tempInertia2 = new btVector3(0, 0, 0); tempInertia2 = new btVector3(0, 0, 0);
tempOrientation1 = new btQuaternion(0,0,0,1); tempOrientation1 = new btQuaternion(0, 0, 0, 1);
tempOrientation2 = new btQuaternion(0, 0, 0, 1); tempOrientation2 = new btQuaternion(0, 0, 0, 1);
_parent_scene = parent_scene; _parent_scene = parent_scene;
tempTransform1 = new btTransform(_parent_scene.QuatIdentity, _parent_scene.VectorZero); tempTransform1 = new btTransform(_parent_scene.QuatIdentity, _parent_scene.VectorZero);
@ -216,10 +216,10 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
tempMotionState2 = new btDefaultMotionState(_parent_scene.TransZero); tempMotionState2 = new btDefaultMotionState(_parent_scene.TransZero);
tempMotionState3 = new btDefaultMotionState(_parent_scene.TransZero); tempMotionState3 = new btDefaultMotionState(_parent_scene.TransZero);
AxisLockLinearLow = new btVector3(-1 * (int)Constants.RegionSize, -1 * (int)Constants.RegionSize, -1 * (int)Constants.RegionSize); AxisLockLinearLow = new btVector3(-1 * (int)Constants.RegionSize, -1 * (int)Constants.RegionSize, -1 * (int)Constants.RegionSize);
int regionsize = (int) Constants.RegionSize; int regionsize = (int)Constants.RegionSize;
if (regionsize == 256) if (regionsize == 256)
regionsize = 512; regionsize = 512;
@ -611,7 +611,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
DisableAxisMotor(); DisableAxisMotor();
DisposeOfBody(); DisposeOfBody();
SetCollisionShape(null); SetCollisionShape(null);
if (tempMotionState3 != null && tempMotionState3.Handle != IntPtr.Zero) if (tempMotionState3 != null && tempMotionState3.Handle != IntPtr.Zero)
{ {
tempMotionState3.Dispose(); tempMotionState3.Dispose();
@ -677,8 +677,8 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
tempInertia2.Dispose(); tempInertia2.Dispose();
tempInertia1 = null; tempInertia1 = null;
} }
if (tempAngularVelocity2 != null && tempAngularVelocity2.Handle != IntPtr.Zero) if (tempAngularVelocity2 != null && tempAngularVelocity2.Handle != IntPtr.Zero)
{ {
tempAngularVelocity2.Dispose(); tempAngularVelocity2.Dispose();
@ -802,7 +802,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
changesize(timestep); changesize(timestep);
} }
// //
if (m_taintshape) if (m_taintshape)
{ {
@ -1001,7 +1001,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
else else
SetBody(0); SetBody(0);
changeSelectedStatus(timestep); changeSelectedStatus(timestep);
resetCollisionAccounting(); resetCollisionAccounting();
m_taintPhysics = m_isphysical; m_taintPhysics = m_isphysical;
} }
@ -1012,7 +1012,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
{ {
if (_parent_scene.needsMeshing(_pbs)) if (_parent_scene.needsMeshing(_pbs))
{ {
ProcessGeomCreationAsTriMesh(PhysicsVector.Zero,Quaternion.Identity); ProcessGeomCreationAsTriMesh(PhysicsVector.Zero, Quaternion.Identity);
// createmesh returns null when it doesn't mesh. // createmesh returns null when it doesn't mesh.
CreateGeom(IntPtr.Zero, _mesh); CreateGeom(IntPtr.Zero, _mesh);
} }
@ -1038,32 +1038,32 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
meshlod = _parent_scene.MeshSculptphysicalLOD; meshlod = _parent_scene.MeshSculptphysicalLOD;
IMesh mesh = _parent_scene.mesher.CreateMesh(SOPName, _pbs, _size, meshlod, IsPhysical); IMesh mesh = _parent_scene.mesher.CreateMesh(SOPName, _pbs, _size, meshlod, IsPhysical);
if (!positionOffset.IsIdentical(PhysicsVector.Zero,0.001f) || orientation != Quaternion.Identity) if (!positionOffset.IsIdentical(PhysicsVector.Zero, 0.001f) || orientation != Quaternion.Identity)
{ {
float[] xyz = new float[3];
xyz[0] = positionOffset.X;
xyz[1] = positionOffset.Y;
xyz[2] = positionOffset.Z;
Matrix4 m4 = Matrix4.CreateFromQuaternion(orientation); float[] xyz = new float[3];
xyz[0] = positionOffset.X;
xyz[1] = positionOffset.Y;
xyz[2] = positionOffset.Z;
float[,] matrix = new float[3,3]; Matrix4 m4 = Matrix4.CreateFromQuaternion(orientation);
float[,] matrix = new float[3, 3];
matrix[0, 0] = m4.M11;
matrix[0, 1] = m4.M12;
matrix[0, 2] = m4.M13;
matrix[1, 0] = m4.M21;
matrix[1, 1] = m4.M22;
matrix[1, 2] = m4.M23;
matrix[2, 0] = m4.M31;
matrix[2, 1] = m4.M32;
matrix[2, 2] = m4.M33;
mesh.TransformLinear(matrix, xyz);
matrix[0, 0] = m4.M11;
matrix[0, 1] = m4.M12;
matrix[0, 2] = m4.M13;
matrix[1, 0] = m4.M21;
matrix[1, 1] = m4.M22;
matrix[1, 2] = m4.M23;
matrix[2, 0] = m4.M31;
matrix[2, 1] = m4.M32;
matrix[2, 2] = m4.M33;
mesh.TransformLinear(matrix, xyz);
} }
@ -1088,12 +1088,12 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
SetCollisionShape(null); SetCollisionShape(null);
// Construction of new prim // Construction of new prim
ProcessGeomCreation(); ProcessGeomCreation();
if (IsPhysical) if (IsPhysical)
SetBody(Mass); SetBody(Mass);
else else
SetBody(0); SetBody(0);
m_taintsize = _size; m_taintsize = _size;
} }
@ -1136,7 +1136,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
//prim_geom = IntPtr.Zero; //prim_geom = IntPtr.Zero;
m_log.Error("[PHYSICS]: PrimGeom dead"); m_log.Error("[PHYSICS]: PrimGeom dead");
} }
// we don't need to do space calculation because the client sends a position update also. // we don't need to do space calculation because the client sends a position update also.
if (_size.X <= 0) _size.X = 0.01f; if (_size.X <= 0) _size.X = 0.01f;
if (_size.Y <= 0) _size.Y = 0.01f; if (_size.Y <= 0) _size.Y = 0.01f;
@ -1153,8 +1153,8 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
tempTransform1.Dispose(); tempTransform1.Dispose();
tempTransform1 = new btTransform(tempOrientation1, tempPosition1); tempTransform1 = new btTransform(tempOrientation1, tempPosition1);
//d.GeomBoxSetLengths(prim_geom, _size.X, _size.Y, _size.Z); //d.GeomBoxSetLengths(prim_geom, _size.X, _size.Y, _size.Z);
if (IsPhysical) if (IsPhysical)
@ -1162,7 +1162,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
SetBody(Mass); SetBody(Mass);
// Re creates body on size. // Re creates body on size.
// EnableBody also does setMass() // EnableBody also does setMass()
} }
else else
{ {
@ -1179,7 +1179,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
} }
} }
resetCollisionAccounting(); resetCollisionAccounting();
m_taintshape = false; m_taintshape = false;
} }
@ -1291,7 +1291,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
{ {
Body.setCollisionFlags((int)ContactFlags.CF_NO_CONTACT_RESPONSE); Body.setCollisionFlags((int)ContactFlags.CF_NO_CONTACT_RESPONSE);
disableBodySoft(); disableBodySoft();
} }
else else
{ {
@ -1299,7 +1299,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
enableBodySoft(); enableBodySoft();
} }
m_isSelected = m_taintselected; m_isSelected = m_taintselected;
} }
private void changevelocity(float timestep) private void changevelocity(float timestep)
@ -1368,7 +1368,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
_parent = m_taintparent; _parent = m_taintparent;
m_taintPhysics = m_isphysical; m_taintPhysics = m_isphysical;
} }
private void changefloatonwater(float timestep) private void changefloatonwater(float timestep)
@ -1627,7 +1627,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
{ {
if (m_zeroPosition == null) if (m_zeroPosition == null)
m_zeroPosition = new PhysicsVector(0, 0, 0); m_zeroPosition = new PhysicsVector(0, 0, 0);
m_zeroPosition.setValues(_position.X,_position.Y,_position.Z); m_zeroPosition.setValues(_position.X, _position.Y, _position.Z);
return; return;
} }
} }
@ -1981,7 +1981,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
//_mesh = _parent_scene.mesher.CreateMesh(m_primName, _pbs, _size, _parent_scene.meshSculptLOD, IsPhysical); //_mesh = _parent_scene.mesher.CreateMesh(m_primName, _pbs, _size, _parent_scene.meshSculptLOD, IsPhysical);
_mesh = p_mesh; _mesh = p_mesh;
setMesh(_parent_scene, _mesh); setMesh(_parent_scene, _mesh);
} }
else else
{ {
@ -1994,15 +1994,15 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
//SetGeom to a Regular Sphere //SetGeom to a Regular Sphere
if (tempSize1 == null) if (tempSize1 == null)
tempSize1 = new btVector3(0, 0, 0); tempSize1 = new btVector3(0, 0, 0);
tempSize1.setValue(_size.X * 0.5f,_size.Y * 0.5f, _size.Z * 0.5f); tempSize1.setValue(_size.X * 0.5f, _size.Y * 0.5f, _size.Z * 0.5f);
SetCollisionShape(new btSphereShape(_size.X*0.5f)); SetCollisionShape(new btSphereShape(_size.X * 0.5f));
} }
else else
{ {
// uses halfextents // uses halfextents
if (tempSize1 == null) if (tempSize1 == null)
tempSize1 = new btVector3(0, 0, 0); tempSize1 = new btVector3(0, 0, 0);
tempSize1.setValue(_size.X*0.5f, _size.Y*0.5f, _size.Z*0.5f); tempSize1.setValue(_size.X * 0.5f, _size.Y * 0.5f, _size.Z * 0.5f);
SetCollisionShape(new btBoxShape(tempSize1)); SetCollisionShape(new btBoxShape(tempSize1));
} }
} }
@ -2052,14 +2052,24 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
} }
} }
//IMesh oldMesh = primMesh;
//primMesh = mesh;
//float[] vertexList = primMesh.getVertexListAsFloatLocked(); // Note, that vertextList is pinned in memory
//int[] indexList = primMesh.getIndexListAsIntLocked(); // Also pinned, needs release after usage
////Array.Reverse(indexList);
//primMesh.releaseSourceMeshData(); // free up the original mesh data to save memory
IMesh oldMesh = primMesh; IMesh oldMesh = primMesh;
primMesh = mesh; primMesh = mesh;
float[] vertexList = primMesh.getVertexListAsFloatLocked(); // Note, that vertextList is pinned in memory float[] vertexList = mesh.getVertexListAsFloatLocked(); // Note, that vertextList is pinned in memory
int[] indexList = primMesh.getIndexListAsIntLocked(); // Also pinned, needs release after usage int[] indexList = mesh.getIndexListAsIntLocked(); // Also pinned, needs release after usage
//Array.Reverse(indexList); //Array.Reverse(indexList);
primMesh.releaseSourceMeshData(); // free up the original mesh data to save memory mesh.releaseSourceMeshData(); // free up the original mesh data to save memory
int VertexCount = vertexList.GetLength(0) / 3; int VertexCount = vertexList.GetLength(0) / 3;
int IndexCount = indexList.GetLength(0); int IndexCount = indexList.GetLength(0);
@ -2068,17 +2078,17 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
btshapeArray.Dispose(); btshapeArray.Dispose();
//Array.Reverse(indexList); //Array.Reverse(indexList);
btshapeArray = new btTriangleIndexVertexArray(IndexCount / 3, indexList, (3 * sizeof(int)), btshapeArray = new btTriangleIndexVertexArray(IndexCount / 3, indexList, (3 * sizeof(int)),
VertexCount, vertexList, 3*sizeof (float)); VertexCount, vertexList, 3 * sizeof(float));
SetCollisionShape(new btGImpactMeshShape(btshapeArray)); SetCollisionShape(new btGImpactMeshShape(btshapeArray));
//((btGImpactMeshShape) prim_geom).updateBound(); //((btGImpactMeshShape) prim_geom).updateBound();
((btGImpactMeshShape)prim_geom).setLocalScaling(new btVector3(1,1, 1)); ((btGImpactMeshShape)prim_geom).setLocalScaling(new btVector3(1, 1, 1));
((btGImpactMeshShape)prim_geom).updateBound(); ((btGImpactMeshShape)prim_geom).updateBound();
_parent_scene.SetUsingGImpact(); _parent_scene.SetUsingGImpact();
if (oldMesh != null) //if (oldMesh != null)
{ //{
oldMesh.releasePinned(); // oldMesh.releasePinned();
oldMesh = null; // oldMesh = null;
} //}
} }
@ -2102,7 +2112,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
} }
*/ */
prim_geom = shape; prim_geom = shape;
//Body.set //Body.set
} }
@ -2143,8 +2153,8 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
if (prim_geom is btGImpactMeshShape) if (prim_geom is btGImpactMeshShape)
{ {
((btGImpactMeshShape) prim_geom).setLocalScaling(new btVector3(1, 1, 1)); ((btGImpactMeshShape)prim_geom).setLocalScaling(new btVector3(1, 1, 1));
((btGImpactMeshShape) prim_geom).updateBound(); ((btGImpactMeshShape)prim_geom).updateBound();
} }
//Body.setCollisionFlags(Body.getCollisionFlags() | (int)ContactFlags.CF_CUSTOM_MATERIAL_CALLBACK); //Body.setCollisionFlags(Body.getCollisionFlags() | (int)ContactFlags.CF_CUSTOM_MATERIAL_CALLBACK);
//Body.setUserPointer((IntPtr) (int)m_localID); //Body.setUserPointer((IntPtr) (int)m_localID);
@ -2159,7 +2169,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
{ {
if (chld == null) if (chld == null)
continue; continue;
// if (chld.NeedsMeshing()) // if (chld.NeedsMeshing())
// hasTrimesh = true; // hasTrimesh = true;
} }
@ -2167,40 +2177,40 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
//if (hasTrimesh) //if (hasTrimesh)
//{ //{
ProcessGeomCreationAsTriMesh(PhysicsVector.Zero, Quaternion.Identity); ProcessGeomCreationAsTriMesh(PhysicsVector.Zero, Quaternion.Identity);
// createmesh returns null when it doesn't mesh. // createmesh returns null when it doesn't mesh.
/*
if (_mesh is Mesh)
{
}
else
{
m_log.Warn("[PHYSICS]: Can't link a OpenSim.Region.Physics.Meshing.Mesh object");
return;
}
*/
/*
if (_mesh is Mesh)
foreach (BulletDotNETPrim chld in childrenPrim) {
{ }
if (chld == null) else
continue; {
PhysicsVector offset = chld.Position - Position; m_log.Warn("[PHYSICS]: Can't link a OpenSim.Region.Physics.Meshing.Mesh object");
Vector3 pos = new Vector3(offset.X, offset.Y, offset.Z); return;
pos *= Quaternion.Inverse(Orientation); }
//pos *= Orientation; */
offset.setValues(pos.X, pos.Y, pos.Z);
chld.ProcessGeomCreationAsTriMesh(offset, chld.Orientation);
_mesh.Append(chld._mesh);
}
setMesh(_parent_scene, _mesh);
foreach (BulletDotNETPrim chld in childrenPrim)
//} {
if (chld == null)
continue;
PhysicsVector offset = chld.Position - Position;
Vector3 pos = new Vector3(offset.X, offset.Y, offset.Z);
pos *= Quaternion.Inverse(Orientation);
//pos *= Orientation;
offset.setValues(pos.X, pos.Y, pos.Z);
chld.ProcessGeomCreationAsTriMesh(offset, chld.Orientation);
_mesh.Append(chld._mesh);
}
setMesh(_parent_scene, _mesh);
//}
if (tempMotionState1 != null && tempMotionState1.Handle != IntPtr.Zero) if (tempMotionState1 != null && tempMotionState1.Handle != IntPtr.Zero)
tempMotionState1.Dispose(); tempMotionState1.Dispose();
@ -2238,7 +2248,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
((btGImpactMeshShape)prim_geom).updateBound(); ((btGImpactMeshShape)prim_geom).updateBound();
} }
_parent_scene.AddPrimToScene(this); _parent_scene.AddPrimToScene(this);
} }
if (IsPhysical) if (IsPhysical)
@ -2252,7 +2262,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
if (Body.Handle != IntPtr.Zero) if (Body.Handle != IntPtr.Zero)
{ {
DisableAxisMotor(); DisableAxisMotor();
_parent_scene.removeFromWorld(this,Body); _parent_scene.removeFromWorld(this, Body);
Body.Dispose(); Body.Dispose();
} }
Body = null; Body = null;
@ -2305,7 +2315,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
return; return;
lock (childrenPrim) lock (childrenPrim)
{ {
if (!childrenPrim.Contains(prm)) if (!childrenPrim.Contains(prm))
@ -2313,8 +2323,8 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
childrenPrim.Add(prm); childrenPrim.Add(prm);
} }
} }
} }
public void disableBody() public void disableBody()
@ -2386,7 +2396,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
{ {
Body.clearForces(); Body.clearForces();
Body.forceActivationState(0); Body.forceActivationState(0);
} }
} }
@ -2400,7 +2410,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
Body.clearForces(); Body.clearForces();
Body.forceActivationState(4); Body.forceActivationState(4);
forceenable = true; forceenable = true;
} }
m_disabled = false; m_disabled = false;
} }
@ -2415,7 +2425,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
SetBody(Mass); SetBody(Mass);
else else
SetBody(0); SetBody(0);
// TODO: Set Collision Category Bits and Flags // TODO: Set Collision Category Bits and Flags
// TODO: Set Auto Disable data // TODO: Set Auto Disable data
@ -2587,10 +2597,10 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
_velocity.Y = tempLinearVelocity1.getY(); _velocity.Y = tempLinearVelocity1.getY();
_velocity.Z = tempLinearVelocity1.getZ(); _velocity.Z = tempLinearVelocity1.getZ();
_acceleration = ((_velocity - m_lastVelocity)/0.1f); _acceleration = ((_velocity - m_lastVelocity) / 0.1f);
_acceleration = new PhysicsVector(_velocity.X - m_lastVelocity.X/0.1f, _acceleration = new PhysicsVector(_velocity.X - m_lastVelocity.X / 0.1f,
_velocity.Y - m_lastVelocity.Y/0.1f, _velocity.Y - m_lastVelocity.Y / 0.1f,
_velocity.Z - m_lastVelocity.Z/0.1f); _velocity.Z - m_lastVelocity.Z / 0.1f);
//m_log.Info("[PHYSICS]: V1: " + _velocity + " V2: " + m_lastVelocity + " Acceleration: " + _acceleration.ToString()); //m_log.Info("[PHYSICS]: V1: " + _velocity + " V2: " + m_lastVelocity + " Acceleration: " + _acceleration.ToString());
if (_velocity.IsIdentical(pv, 0.5f)) if (_velocity.IsIdentical(pv, 0.5f))
@ -2669,7 +2679,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
if (AxisLockAngleHigh != null && AxisLockAngleHigh.Handle != IntPtr.Zero) if (AxisLockAngleHigh != null && AxisLockAngleHigh.Handle != IntPtr.Zero)
AxisLockAngleHigh.Dispose(); AxisLockAngleHigh.Dispose();
m_aMotor = new btGeneric6DofConstraint(Body, _parent_scene.TerrainBody, _parent_scene.TransZero, m_aMotor = new btGeneric6DofConstraint(Body, _parent_scene.TerrainBody, _parent_scene.TransZero,
_parent_scene.TransZero, false); _parent_scene.TransZero, false);
@ -2683,7 +2693,7 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
m_aMotor.setLinearUpperLimit(AxisLockLinearHigh); m_aMotor.setLinearUpperLimit(AxisLockLinearHigh);
_parent_scene.getBulletWorld().addConstraint((btTypedConstraint)m_aMotor); _parent_scene.getBulletWorld().addConstraint((btTypedConstraint)m_aMotor);
//m_aMotor. //m_aMotor.
} }
internal void DisableAxisMotor() internal void DisableAxisMotor()
@ -2698,4 +2708,4 @@ namespace OpenSim.Region.Physics.BulletDotNETPlugin
} }
} }

View File

@ -40,7 +40,6 @@ namespace OpenSim.Region.Physics.Meshing
private List<Triangle> triangles; private List<Triangle> triangles;
GCHandle pinnedVirtexes; GCHandle pinnedVirtexes;
GCHandle pinnedIndex; GCHandle pinnedIndex;
public PrimMesh primMesh = null;
public float[] normals; public float[] normals;
public Mesh() public Mesh()
@ -63,6 +62,8 @@ namespace OpenSim.Region.Physics.Meshing
public void Add(Triangle triangle) public void Add(Triangle triangle)
{ {
if (pinnedIndex.IsAllocated || pinnedVirtexes.IsAllocated)
throw new NotSupportedException("Attempt to Add to a pinned Mesh");
// If a vertex of the triangle is not yet in the vertices list, // If a vertex of the triangle is not yet in the vertices list,
// add it and set its index to the current index count // add it and set its index to the current index count
if (!vertices.ContainsKey(triangle.v1)) if (!vertices.ContainsKey(triangle.v1))
@ -148,40 +149,22 @@ namespace OpenSim.Region.Physics.Meshing
public float[] getVertexListAsFloatLocked() public float[] getVertexListAsFloatLocked()
{ {
if( pinnedVirtexes.IsAllocated )
return (float[])(pinnedVirtexes.Target);
float[] result; float[] result;
if (primMesh == null) //m_log.WarnFormat("vertices.Count = {0}", vertices.Count);
result = new float[vertices.Count * 3];
foreach (KeyValuePair<Vertex, int> kvp in vertices)
{ {
//m_log.WarnFormat("vertices.Count = {0}", vertices.Count); Vertex v = kvp.Key;
result = new float[vertices.Count * 3]; int i = kvp.Value;
foreach (KeyValuePair<Vertex, int> kvp in vertices) //m_log.WarnFormat("kvp.Value = {0}", i);
{ result[3 * i + 0] = v.X;
Vertex v = kvp.Key; result[3 * i + 1] = v.Y;
int i = kvp.Value; result[3 * i + 2] = v.Z;
//m_log.WarnFormat("kvp.Value = {0}", i);
result[3 * i + 0] = v.X;
result[3 * i + 1] = v.Y;
result[3 * i + 2] = v.Z;
}
pinnedVirtexes = GCHandle.Alloc(result, GCHandleType.Pinned);
}
else
{
int count = primMesh.coords.Count;
result = new float[count * 3];
for (int i = 0; i < count; i++)
{
Coord c = primMesh.coords[i];
{
int resultIndex = 3 * i;
result[resultIndex] = c.X;
result[resultIndex + 1] = c.Y;
result[resultIndex + 2] = c.Z;
}
}
pinnedVirtexes = GCHandle.Alloc(result, GCHandleType.Pinned);
} }
pinnedVirtexes = GCHandle.Alloc(result, GCHandleType.Pinned);
return result; return result;
} }
@ -189,33 +172,13 @@ namespace OpenSim.Region.Physics.Meshing
{ {
int[] result; int[] result;
if (primMesh == null) result = new int[triangles.Count * 3];
for (int i = 0; i < triangles.Count; i++)
{ {
result = new int[triangles.Count * 3]; Triangle t = triangles[i];
for (int i = 0; i < triangles.Count; i++) result[3 * i + 0] = vertices[t.v1];
{ result[3 * i + 1] = vertices[t.v2];
Triangle t = triangles[i]; result[3 * i + 2] = vertices[t.v3];
result[3 * i + 0] = vertices[t.v1];
result[3 * i + 1] = vertices[t.v2];
result[3 * i + 2] = vertices[t.v3];
}
}
else
{
int numFaces = primMesh.faces.Count;
result = new int[numFaces * 3];
for (int i = 0; i < numFaces; i++)
{
Face f = primMesh.faces[i];
// Coord c1 = primMesh.coords[f.v1];
// Coord c2 = primMesh.coords[f.v2];
// Coord c3 = primMesh.coords[f.v3];
int resultIndex = i * 3;
result[resultIndex] = f.v1;
result[resultIndex + 1] = f.v2;
result[resultIndex + 2] = f.v3;
}
} }
return result; return result;
} }
@ -226,6 +189,9 @@ namespace OpenSim.Region.Physics.Meshing
/// <returns></returns> /// <returns></returns>
public int[] getIndexListAsIntLocked() public int[] getIndexListAsIntLocked()
{ {
if (pinnedIndex.IsAllocated)
return (int[])(pinnedIndex.Target);
int[] result = getIndexListAsInt(); int[] result = getIndexListAsInt();
pinnedIndex = GCHandle.Alloc(result, GCHandleType.Pinned); pinnedIndex = GCHandle.Alloc(result, GCHandleType.Pinned);
@ -245,11 +211,13 @@ namespace OpenSim.Region.Physics.Meshing
{ {
triangles = null; triangles = null;
vertices = null; vertices = null;
primMesh = null;
} }
public void Append(IMesh newMesh) public void Append(IMesh newMesh)
{ {
if (pinnedIndex.IsAllocated || pinnedVirtexes.IsAllocated)
throw new NotSupportedException("Attempt to Append to a pinned Mesh");
if (!(newMesh is Mesh)) if (!(newMesh is Mesh))
return; return;
@ -260,6 +228,9 @@ namespace OpenSim.Region.Physics.Meshing
// Do a linear transformation of mesh. // Do a linear transformation of mesh.
public void TransformLinear(float[,] matrix, float[] offset) public void TransformLinear(float[,] matrix, float[] offset)
{ {
if (pinnedIndex.IsAllocated || pinnedVirtexes.IsAllocated)
throw new NotSupportedException("Attempt to TransformLinear a pinned Mesh");
foreach (Vertex v in vertices.Keys) foreach (Vertex v in vertices.Keys)
{ {
if (v == null) if (v == null)

View File

@ -76,6 +76,7 @@ namespace OpenSim.Region.Physics.Meshing
private float minSizeForComplexMesh = 0.2f; // prims with all dimensions smaller than this will have a bounding box mesh private float minSizeForComplexMesh = 0.2f; // prims with all dimensions smaller than this will have a bounding box mesh
private Dictionary<ulong, Mesh> m_uniqueMeshes = new Dictionary<ulong, Mesh>();
/// <summary> /// <summary>
/// creates a simple box mesh of the specified size. This mesh is of very low vertex count and may /// creates a simple box mesh of the specified size. This mesh is of very low vertex count and may
@ -170,9 +171,62 @@ namespace OpenSim.Region.Physics.Meshing
} }
public Mesh CreateMeshFromPrimMesher(string primName, PrimitiveBaseShape primShape, PhysicsVector size, float lod) private ulong GetMeshKey( PrimitiveBaseShape pbs, PhysicsVector size, float lod )
{
ulong hash = 5381;
hash = djb2(hash, pbs.PathCurve);
hash = djb2(hash, (byte)((byte)pbs.HollowShape | (byte)pbs.ProfileShape));
hash = djb2(hash, pbs.PathBegin);
hash = djb2(hash, pbs.PathEnd);
hash = djb2(hash, pbs.PathScaleX);
hash = djb2(hash, pbs.PathScaleY);
hash = djb2(hash, pbs.PathShearX);
hash = djb2(hash, pbs.PathShearY);
hash = djb2(hash, (byte)pbs.PathTwist);
hash = djb2(hash, (byte)pbs.PathTwistBegin);
hash = djb2(hash, (byte)pbs.PathRadiusOffset);
hash = djb2(hash, (byte)pbs.PathTaperX);
hash = djb2(hash, (byte)pbs.PathTaperY);
hash = djb2(hash, pbs.PathRevolutions);
hash = djb2(hash, (byte)pbs.PathSkew);
hash = djb2(hash, pbs.ProfileBegin);
hash = djb2(hash, pbs.ProfileEnd);
hash = djb2(hash, pbs.ProfileHollow);
// TODO: Separate scale out from the primitive shape data (after
// scaling is supported at the physics engine level)
byte[] scaleBytes = size.GetBytes();
for (int i = 0; i < scaleBytes.Length; i++)
hash = djb2(hash, scaleBytes[i]);
// Include LOD in hash, accounting for endianness
byte[] lodBytes = new byte[4];
Buffer.BlockCopy(BitConverter.GetBytes(lod), 0, lodBytes, 0, 4);
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(lodBytes, 0, 4);
}
for (int i = 0; i < lodBytes.Length; i++)
hash = djb2(hash, lodBytes[i]);
return hash;
}
private ulong djb2(ulong hash, byte c)
{
return ((hash << 5) + hash) + (ulong)c;
}
private ulong djb2(ulong hash, ushort c)
{
hash = ((hash << 5) + hash) + (ulong)((byte)c);
return ((hash << 5) + hash) + (ulong)(c >> 8);
}
private Mesh CreateMeshFromPrimMesher(string primName, PrimitiveBaseShape primShape, PhysicsVector size, float lod)
{ {
Mesh mesh = new Mesh();
PrimMesh primMesh; PrimMesh primMesh;
PrimMesher.SculptMesh sculptMesh; PrimMesher.SculptMesh sculptMesh;
@ -385,8 +439,6 @@ namespace OpenSim.Region.Physics.Meshing
coords = primMesh.coords; coords = primMesh.coords;
faces = primMesh.faces; faces = primMesh.faces;
} }
@ -401,13 +453,13 @@ namespace OpenSim.Region.Physics.Meshing
vertices.Add(new Vertex(c.X, c.Y, c.Z)); vertices.Add(new Vertex(c.X, c.Y, c.Z));
} }
Mesh mesh = new Mesh();
// Add the corresponding triangles to the mesh // Add the corresponding triangles to the mesh
for (int i = 0; i < numFaces; i++) for (int i = 0; i < numFaces; i++)
{ {
Face f = faces[i]; Face f = faces[i];
mesh.Add(new Triangle(vertices[f.v1], vertices[f.v2], vertices[f.v3])); mesh.Add(new Triangle(vertices[f.v1], vertices[f.v2], vertices[f.v3]));
} }
return mesh; return mesh;
} }
@ -418,7 +470,12 @@ namespace OpenSim.Region.Physics.Meshing
public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, PhysicsVector size, float lod, bool isPhysical) public IMesh CreateMesh(String primName, PrimitiveBaseShape primShape, PhysicsVector size, float lod, bool isPhysical)
{ {
// If this mesh has been created already, return it instead of creating another copy
// For large regions with 100k+ prims and hundreds of copies of each, this can save a GB or more of memory
ulong key = GetMeshKey(primShape, size, lod);
Mesh mesh = null; Mesh mesh = null;
if (m_uniqueMeshes.TryGetValue(key, out mesh))
return mesh;
if (size.X < 0.01f) size.X = 0.01f; if (size.X < 0.01f) size.X = 0.01f;
if (size.Y < 0.01f) size.Y = 0.01f; if (size.Y < 0.01f) size.Y = 0.01f;
@ -441,7 +498,7 @@ namespace OpenSim.Region.Physics.Meshing
// trim the vertex and triangle lists to free up memory // trim the vertex and triangle lists to free up memory
mesh.TrimExcess(); mesh.TrimExcess();
} }
m_uniqueMeshes.Add(key, mesh);
return mesh; return mesh;
} }
} }

View File

@ -345,6 +345,21 @@ namespace PrimMesher
this.v3.Z *= z; this.v3.Z *= z;
} }
public void AddPos(float x, float y, float z)
{
this.v1.X += x;
this.v2.X += x;
this.v3.X += x;
this.v1.Y += y;
this.v2.Y += y;
this.v3.Y += y;
this.v1.Z += z;
this.v2.Z += z;
this.v3.Z += z;
}
public void AddRot(Quat q) public void AddRot(Quat q)
{ {
this.v1 *= q; this.v1 *= q;
@ -2141,6 +2156,18 @@ namespace PrimMesher
vert.Z += z; vert.Z += z;
this.coords[i] = vert; this.coords[i] = vert;
} }
if (this.viewerFaces != null)
{
int numViewerFaces = this.viewerFaces.Count;
for (i = 0; i < numViewerFaces; i++)
{
ViewerFace v = this.viewerFaces[i];
v.AddPos(x, y, z);
this.viewerFaces[i] = v;
}
}
} }
/// <summary> /// <summary>

View File

@ -494,6 +494,18 @@ namespace PrimMesher
vert.Z += z; vert.Z += z;
this.coords[i] = vert; this.coords[i] = vert;
} }
if (this.viewerFaces != null)
{
int numViewerFaces = this.viewerFaces.Count;
for (i = 0; i < numViewerFaces; i++)
{
ViewerFace v = this.viewerFaces[i];
v.AddPos(x, y, z);
this.viewerFaces[i] = v;
}
}
} }
/// <summary> /// <summary>
@ -556,7 +568,7 @@ namespace PrimMesher
if (path == null) if (path == null)
return; return;
String fileName = name + "_" + title + ".raw"; String fileName = name + "_" + title + ".raw";
String completePath = Path.Combine(path, fileName); String completePath = System.IO.Path.Combine(path, fileName);
StreamWriter sw = new StreamWriter(completePath); StreamWriter sw = new StreamWriter(completePath);
for (int i = 0; i < this.faces.Count; i++) for (int i = 0; i < this.faces.Count; i++)

View File

@ -97,7 +97,6 @@ namespace OpenSim.Region.Physics.OdePlugin
// private float m_tensor = 5f; // private float m_tensor = 5f;
private int body_autodisable_frames = 20; private int body_autodisable_frames = 20;
private IMesh primMesh = null;
private const CollisionCategories m_default_collisionFlags = (CollisionCategories.Geom private const CollisionCategories m_default_collisionFlags = (CollisionCategories.Geom
@ -825,14 +824,10 @@ namespace OpenSim.Region.Physics.OdePlugin
} }
} }
IMesh oldMesh = primMesh; float[] vertexList = mesh.getVertexListAsFloatLocked(); // Note, that vertextList is pinned in memory
int[] indexList = mesh.getIndexListAsIntLocked(); // Also pinned, needs release after usage
primMesh = mesh; mesh.releaseSourceMeshData(); // free up the original mesh data to save memory
float[] vertexList = primMesh.getVertexListAsFloatLocked(); // Note, that vertextList is pinned in memory
int[] indexList = primMesh.getIndexListAsIntLocked(); // Also pinned, needs release after usage
primMesh.releaseSourceMeshData(); // free up the original mesh data to save memory
int VertexCount = vertexList.GetLength(0)/3; int VertexCount = vertexList.GetLength(0)/3;
int IndexCount = indexList.GetLength(0); int IndexCount = indexList.GetLength(0);
@ -859,12 +854,6 @@ namespace OpenSim.Region.Physics.OdePlugin
return; return;
} }
if (oldMesh != null)
{
oldMesh.releasePinned();
oldMesh = null;
}
// if (IsPhysical && Body == (IntPtr) 0) // if (IsPhysical && Body == (IntPtr) 0)
// { // {
// Recreate the body // Recreate the body

View File

@ -24,7 +24,7 @@
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
@ -7841,8 +7841,10 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
public LSL_String llGetHTTPHeader(LSL_Key request_id, string header) public LSL_String llGetHTTPHeader(LSL_Key request_id, string header)
{ {
m_host.AddScriptLPS(1); m_host.AddScriptLPS(1);
NotImplemented("llGetHTTPHeader");
return String.Empty; if (m_UrlModule != null)
return m_UrlModule.GetHttpHeader(new UUID(request_id), header);
return String.Empty;
} }
@ -9120,13 +9122,15 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api
} }
public void llHTTPResponse(string url, int status, string body) public void llHTTPResponse(LSL_Key id, int status, string body)
{ {
// Partial implementation: support for parameter flags needed // Partial implementation: support for parameter flags needed
// see http://wiki.secondlife.com/wiki/llHTTPResponse // see http://wiki.secondlife.com/wiki/llHTTPResponse
m_host.AddScriptLPS(1); m_host.AddScriptLPS(1);
NotImplemented("llHTTPResponse");
if (m_UrlModule != null)
m_UrlModule.HttpResponse(new UUID(id), status,body);
} }
public void llResetLandBanList() public void llResetLandBanList()

View File

@ -201,7 +201,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Api.Interfaces
void llGroundRepel(double height, int water, double tau); void llGroundRepel(double height, int water, double tau);
LSL_Vector llGroundSlope(LSL_Vector offset); LSL_Vector llGroundSlope(LSL_Vector offset);
LSL_String llHTTPRequest(string url, LSL_List parameters, string body); LSL_String llHTTPRequest(string url, LSL_List parameters, string body);
void llHTTPResponse(string url, int status, string body); void llHTTPResponse(LSL_Key id, int status, string body);
LSL_String llInsertString(string dst, int position, string src); LSL_String llInsertString(string dst, int position, string src);
void llInstantMessage(string user, string message); void llInstantMessage(string user, string message);
LSL_String llIntegerToBase64(int number); LSL_String llIntegerToBase64(int number);

View File

@ -864,9 +864,9 @@ namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase
return m_LSL_Functions.llHTTPRequest(url, parameters, body); return m_LSL_Functions.llHTTPRequest(url, parameters, body);
} }
public void llHTTPResponse(string url, int status, string body) public void llHTTPResponse(LSL_Key id, int status, string body)
{ {
m_LSL_Functions.llHTTPResponse(url, status, body); m_LSL_Functions.llHTTPResponse(id, status, body);
} }
public LSL_String llInsertString(string dst, int position, string src) public LSL_String llInsertString(string dst, int position, string src)

View File

@ -542,11 +542,39 @@ namespace OpenSim.Region.ScriptEngine.Shared.CodeTools
break; break;
case enumCompileType.cs: case enumCompileType.cs:
case enumCompileType.lsl: case enumCompileType.lsl:
lock (CScodeProvider) bool complete = false;
bool retried = false;
do
{ {
results = CScodeProvider.CompileAssemblyFromSource( lock (CScodeProvider)
parameters, Script); {
results = CScodeProvider.CompileAssemblyFromSource(
parameters, Script);
}
// Deal with an occasional segv in the compiler.
// Rarely, if ever, occurs twice in succession.
// Line # == 0 and no file name are indications that
// this is a native stack trace rather than a normal
// error log.
if (results.Errors.Count > 0)
{
if (!retried && (results.Errors[0].FileName == null || results.Errors[0].FileName == String.Empty) &&
results.Errors[0].Line == 0)
{
// System.Console.WriteLine("retrying failed compilation");
retried = true;
}
else
{
complete = true;
}
}
else
{
complete = true;
}
} }
while(!complete);
break; break;
case enumCompileType.js: case enumCompileType.js:
results = JScodeProvider.CompileAssemblyFromSource( results = JScodeProvider.CompileAssemblyFromSource(
@ -567,17 +595,13 @@ namespace OpenSim.Region.ScriptEngine.Shared.CodeTools
// //
// WARNINGS AND ERRORS // WARNINGS AND ERRORS
// //
int display = 5; bool hadErrors = false;
string errtext = String.Empty;
if (results.Errors.Count > 0) if (results.Errors.Count > 0)
{ {
string errtext = String.Empty;
foreach (CompilerError CompErr in results.Errors) foreach (CompilerError CompErr in results.Errors)
{ {
// Show 5 errors max
//
if (display <= 0)
break;
display--;
string severity = "Error"; string severity = "Error";
if (CompErr.IsWarning) if (CompErr.IsWarning)
@ -587,36 +611,51 @@ namespace OpenSim.Region.ScriptEngine.Shared.CodeTools
KeyValuePair<int, int> lslPos; KeyValuePair<int, int> lslPos;
lslPos = FindErrorPosition(CompErr.Line, CompErr.Column); // Show 5 errors max, but check entire list for errors
string text = CompErr.ErrorText; if (severity == "Error")
{
lslPos = FindErrorPosition(CompErr.Line, CompErr.Column);
string text = CompErr.ErrorText;
// Use LSL type names // Use LSL type names
if (lang == enumCompileType.lsl) if (lang == enumCompileType.lsl)
text = ReplaceTypes(CompErr.ErrorText); text = ReplaceTypes(CompErr.ErrorText);
// The Second Life viewer's script editor begins // The Second Life viewer's script editor begins
// countingn lines and columns at 0, so we subtract 1. // countingn lines and columns at 0, so we subtract 1.
errtext += String.Format("Line ({0},{1}): {4} {2}: {3}\n", errtext += String.Format("Line ({0},{1}): {4} {2}: {3}\n",
lslPos.Key - 1, lslPos.Value - 1, lslPos.Key - 1, lslPos.Value - 1,
CompErr.ErrorNumber, text, severity); CompErr.ErrorNumber, text, severity);
hadErrors = true;
}
} }
}
if (hadErrors)
{
throw new Exception(errtext);
}
// On today's highly asynchronous systems, the result of
// the compile may not be immediately apparent. Wait a
// reasonable amount of time before giving up on it.
if (!File.Exists(OutFile))
{
for (int i=0; i<20 && !File.Exists(OutFile); i++)
{
System.Threading.Thread.Sleep(250);
}
// One final chance...
if (!File.Exists(OutFile)) if (!File.Exists(OutFile))
{ {
errtext = String.Empty;
errtext += "No compile error. But not able to locate compiled file.";
throw new Exception(errtext); throw new Exception(errtext);
} }
} }
//
// NO ERRORS, BUT NO COMPILED FILE
//
if (!File.Exists(OutFile))
{
string errtext = String.Empty;
errtext += "No compile error. But not able to locate compiled file.";
throw new Exception(errtext);
}
// m_log.DebugFormat("[Compiler] Compiled new assembly "+ // m_log.DebugFormat("[Compiler] Compiled new assembly "+
// "for {0}", asset); // "for {0}", asset);
@ -629,7 +668,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.CodeTools
if (fi == null) if (fi == null)
{ {
string errtext = String.Empty; errtext = String.Empty;
errtext += "No compile error. But not able to stat file."; errtext += "No compile error. But not able to stat file.";
throw new Exception(errtext); throw new Exception(errtext);
} }
@ -644,7 +683,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.CodeTools
} }
catch (Exception) catch (Exception)
{ {
string errtext = String.Empty; errtext = String.Empty;
errtext += "No compile error. But not able to open file."; errtext += "No compile error. But not able to open file.";
throw new Exception(errtext); throw new Exception(errtext);
} }

View File

@ -26,6 +26,7 @@
*/ */
using System; using System;
using System.Collections.Generic;
using System.Threading; using System.Threading;
using System.Reflection; using System.Reflection;
using OpenSim.Framework; using OpenSim.Framework;
@ -40,17 +41,40 @@ namespace OpenSim.Server.Base
{ {
// Logger // Logger
// //
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly ILog m_Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// The http server instance // The http server instance
// //
protected BaseHttpServer m_HttpServer = null; protected BaseHttpServer m_HttpServer = null;
protected uint m_Port = 0;
protected Dictionary<uint, BaseHttpServer> m_Servers =
new Dictionary<uint, BaseHttpServer>();
public IHttpServer HttpServer public IHttpServer HttpServer
{ {
get { return m_HttpServer; } get { return m_HttpServer; }
} }
public uint DefaultPort
{
get { return m_Port; }
}
public IHttpServer GetHttpServer(uint port)
{
m_Log.InfoFormat("[SERVER]: Requested port {0}", port);
if (port == m_Port)
return HttpServer;
if (m_Servers.ContainsKey(port))
return m_Servers[port];
m_Servers[port] = new BaseHttpServer(port);
m_Servers[port].Start();
return m_Servers[port];
}
// Handle all the automagical stuff // Handle all the automagical stuff
// //
public HttpServerBase(string prompt, string[] args) : base(prompt, args) public HttpServerBase(string prompt, string[] args) : base(prompt, args)
@ -74,6 +98,8 @@ namespace OpenSim.Server.Base
Thread.CurrentThread.Abort(); Thread.CurrentThread.Abort();
} }
m_Port = port;
m_HttpServer = new BaseHttpServer(port); m_HttpServer = new BaseHttpServer(port);
MainServer.Instance = m_HttpServer; MainServer.Instance = m_HttpServer;

View File

@ -141,7 +141,9 @@ namespace OpenSim.Server.Base
} }
catch (Exception e) catch (Exception e)
{ {
m_log.ErrorFormat("Error loading plugin from {0}, exception {1}", dllName, e.InnerException); if (!(e is System.MissingMethodException))
m_log.ErrorFormat("Error loading plugin from {0}, exception {1}", dllName, e.InnerException);
return null;
} }
return plug; return plug;
@ -258,6 +260,8 @@ namespace OpenSim.Server.Base
public static Dictionary<string, object> ParseXmlResponse(string data) public static Dictionary<string, object> ParseXmlResponse(string data)
{ {
//m_log.DebugFormat("[XXX]: received xml string: {0}", data);
Dictionary<string, object> ret = new Dictionary<string, object>(); Dictionary<string, object> ret = new Dictionary<string, object>();
XmlDocument doc = new XmlDocument(); XmlDocument doc = new XmlDocument();
@ -284,7 +288,7 @@ namespace OpenSim.Server.Base
foreach (XmlNode part in partL) foreach (XmlNode part in partL)
{ {
XmlNode type = part.Attributes.GetNamedItem("Type"); XmlNode type = part.Attributes.GetNamedItem("type");
if (type == null || type.Value != "List") if (type == null || type.Value != "List")
{ {
ret[part.Name] = part.InnerText; ret[part.Name] = part.InnerText;

View File

@ -37,13 +37,17 @@ namespace OpenSim.Server.Handlers.Asset
public class AssetServiceConnector : ServiceConnector public class AssetServiceConnector : ServiceConnector
{ {
private IAssetService m_AssetService; private IAssetService m_AssetService;
private string m_ConfigName = "AssetService";
public AssetServiceConnector(IConfigSource config, IHttpServer server) : public AssetServiceConnector(IConfigSource config, IHttpServer server, string configName) :
base(config, server) base(config, server, configName)
{ {
IConfig serverConfig = config.Configs["AssetService"]; if (configName != String.Empty)
m_ConfigName = configName;
IConfig serverConfig = config.Configs[m_ConfigName];
if (serverConfig == null) if (serverConfig == null)
throw new Exception("No section 'Server' in config file"); throw new Exception(String.Format("No section '{0}' in config file", m_ConfigName));
string assetService = serverConfig.GetString("LocalServiceModule", string assetService = serverConfig.GetString("LocalServiceModule",
String.Empty); String.Empty);
@ -55,7 +59,6 @@ namespace OpenSim.Server.Handlers.Asset
m_AssetService = m_AssetService =
ServerUtils.LoadPlugin<IAssetService>(assetService, args); ServerUtils.LoadPlugin<IAssetService>(assetService, args);
//System.Console.WriteLine("XXXXXXXXXXXXXXXXXXX m_AssetSetvice == null? " + ((m_AssetService == null) ? "yes" : "no"));
server.AddStreamHandler(new AssetServerGetHandler(m_AssetService)); server.AddStreamHandler(new AssetServerGetHandler(m_AssetService));
server.AddStreamHandler(new AssetServerPostHandler(m_AssetService)); server.AddStreamHandler(new AssetServerPostHandler(m_AssetService));
server.AddStreamHandler(new AssetServerDeleteHandler(m_AssetService)); server.AddStreamHandler(new AssetServerDeleteHandler(m_AssetService));

View File

@ -37,13 +37,17 @@ namespace OpenSim.Server.Handlers.Authentication
public class AuthenticationServiceConnector : ServiceConnector public class AuthenticationServiceConnector : ServiceConnector
{ {
private IAuthenticationService m_AuthenticationService; private IAuthenticationService m_AuthenticationService;
private string m_ConfigName = "AuthenticationService";
public AuthenticationServiceConnector(IConfigSource config, IHttpServer server) : public AuthenticationServiceConnector(IConfigSource config, IHttpServer server, string configName) :
base(config, server) base(config, server, configName)
{ {
IConfig serverConfig = config.Configs["AuthenticationService"]; if (configName != String.Empty)
m_ConfigName = configName;
IConfig serverConfig = config.Configs[m_ConfigName];
if (serverConfig == null) if (serverConfig == null)
throw new Exception("No section 'Server' in config file"); throw new Exception(String.Format("No section '{0}' in config file", m_ConfigName));
string authenticationService = serverConfig.GetString("AuthenticationServiceModule", string authenticationService = serverConfig.GetString("AuthenticationServiceModule",
String.Empty); String.Empty);

View File

@ -37,13 +37,16 @@ namespace OpenSim.Server.Handlers.Authorization
public class AuthorizationServerConnector : ServiceConnector public class AuthorizationServerConnector : ServiceConnector
{ {
private IAuthorizationService m_AuthorizationService; private IAuthorizationService m_AuthorizationService;
private string m_ConfigName = "AuthorizationService";
public AuthorizationServerConnector(IConfigSource config, IHttpServer server) : public AuthorizationServerConnector(IConfigSource config, IHttpServer server, string configName) :
base(config, server) base(config, server, configName)
{ {
IConfig serverConfig = config.Configs["AuthorizationService"]; if (configName != String.Empty)
m_ConfigName = configName;
IConfig serverConfig = config.Configs[m_ConfigName];
if (serverConfig == null) if (serverConfig == null)
throw new Exception("No section 'Server' in config file"); throw new Exception(String.Format("No section '{0}' in config file", m_ConfigName));
string authorizationService = serverConfig.GetString("LocalServiceModule", string authorizationService = serverConfig.GetString("LocalServiceModule",
String.Empty); String.Empty);

View File

@ -44,7 +44,7 @@ namespace OpenSim.Server.Handlers.Authorization
{ {
public class AuthorizationServerPostHandler : BaseStreamHandler public class AuthorizationServerPostHandler : BaseStreamHandler
{ {
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IAuthorizationService m_AuthorizationService; private IAuthorizationService m_AuthorizationService;

View File

@ -39,7 +39,7 @@ namespace OpenSim.Server.Handlers.Base
public class ServiceConnector : IServiceConnector public class ServiceConnector : IServiceConnector
{ {
public ServiceConnector(IConfigSource config, IHttpServer server) public ServiceConnector(IConfigSource config, IHttpServer server, string configName)
{ {
} }
} }

View File

@ -37,19 +37,23 @@ namespace OpenSim.Server.Handlers.Freeswitch
public class FreeswitchServerConnector : ServiceConnector public class FreeswitchServerConnector : ServiceConnector
{ {
private IFreeswitchService m_FreeswitchService; private IFreeswitchService m_FreeswitchService;
private string m_ConfigName = "FreeswitchService";
public FreeswitchServerConnector(IConfigSource config, IHttpServer server) : public FreeswitchServerConnector(IConfigSource config, IHttpServer server, string configName) :
base(config, server) base(config, server, configName)
{ {
IConfig serverConfig = config.Configs["FreeswitchService"]; if (configName != String.Empty)
m_ConfigName = configName;
IConfig serverConfig = config.Configs[m_ConfigName];
if (serverConfig == null) if (serverConfig == null)
throw new Exception("No section 'Server' in config file"); throw new Exception(String.Format("No section '{0}' in config file", m_ConfigName));
string freeswitchService = serverConfig.GetString("LocalServiceModule", string freeswitchService = serverConfig.GetString("LocalServiceModule",
String.Empty); String.Empty);
if (freeswitchService == String.Empty) if (freeswitchService == String.Empty)
throw new Exception("No FreeswitchService in config file"); throw new Exception("No LocalServiceModule in config file");
Object[] args = new Object[] { config }; Object[] args = new Object[] { config };
m_FreeswitchService = m_FreeswitchService =

View File

@ -0,0 +1,61 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using Nini.Config;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Server.Handlers.Base;
namespace OpenSim.Server.Handlers.Grid
{
public class GridServiceConnector : ServiceConnector
{
private IGridService m_GridService;
private string m_ConfigName = "GridService";
public GridServiceConnector(IConfigSource config, IHttpServer server, string configName) :
base(config, server, configName)
{
IConfig serverConfig = config.Configs[m_ConfigName];
if (serverConfig == null)
throw new Exception(String.Format("No section {0} in config file", m_ConfigName));
string gridService = serverConfig.GetString("LocalServiceModule",
String.Empty);
if (gridService == String.Empty)
throw new Exception("No LocalServiceModule in config file");
Object[] args = new Object[] { config };
m_GridService = ServerUtils.LoadPlugin<IGridService>(gridService, args);
server.AddStreamHandler(new GridServerPostHandler(m_GridService));
}
}
}

View File

@ -0,0 +1,433 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using Nini.Config;
using log4net;
using System;
using System.Reflection;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenMetaverse;
namespace OpenSim.Server.Handlers.Grid
{
public class GridServerPostHandler : BaseStreamHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IGridService m_GridService;
public GridServerPostHandler(IGridService service) :
base("POST", "/grid")
{
m_GridService = service;
}
public override byte[] Handle(string path, Stream requestData,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
StreamReader sr = new StreamReader(requestData);
string body = sr.ReadToEnd();
sr.Close();
body = body.Trim();
//m_log.DebugFormat("[XXX]: query String: {0}", body);
Dictionary<string, string> request =
ServerUtils.ParseQueryString(body);
if (!request.ContainsKey("METHOD"))
return FailureResult();
string method = request["METHOD"];
switch (method)
{
case "register":
return Register(request);
case "deregister":
return Deregister(request);
case "get_neighbours":
return GetNeighbours(request);
case "get_region_by_uuid":
return GetRegionByUUID(request);
case "get_region_by_position":
return GetRegionByPosition(request);
case "get_region_by_name":
return GetRegionByName(request);
case "get_regions_by_name":
return GetRegionsByName(request);
case "get_region_range":
return GetRegionRange(request);
}
m_log.DebugFormat("[GRID HANDLER]: unknown method {0} request {1}", method.Length, method);
return FailureResult();
}
#region Method-specific handlers
byte[] Register(Dictionary<string, string> request)
{
UUID scopeID = UUID.Zero;
if (request["SCOPEID"] != null)
UUID.TryParse(request["SCOPEID"], out scopeID);
else
m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to register region");
Dictionary<string, object> rinfoData = new Dictionary<string, object>();
foreach (KeyValuePair<string, string> kvp in request)
rinfoData[kvp.Key] = kvp.Value;
GridRegion rinfo = new GridRegion(rinfoData);
bool result = m_GridService.RegisterRegion(scopeID, rinfo);
if (result)
return SuccessResult();
else
return FailureResult();
}
byte[] Deregister(Dictionary<string, string> request)
{
UUID regionID = UUID.Zero;
if (request["REGIONID"] != null)
UUID.TryParse(request["REGIONID"], out regionID);
else
m_log.WarnFormat("[GRID HANDLER]: no regionID in request to deregister region");
bool result = m_GridService.DeregisterRegion(regionID);
if (result)
return SuccessResult();
else
return FailureResult();
}
byte[] GetNeighbours(Dictionary<string, string> request)
{
UUID scopeID = UUID.Zero;
if (request["SCOPEID"] != null)
UUID.TryParse(request["SCOPEID"], out scopeID);
else
m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get neighbours");
UUID regionID = UUID.Zero;
if (request["REGIONID"] != null)
UUID.TryParse(request["REGIONID"], out regionID);
else
m_log.WarnFormat("[GRID HANDLER]: no regionID in request to get neighbours");
List<GridRegion> rinfos = m_GridService.GetNeighbours(scopeID, regionID);
//m_log.DebugFormat("[GRID HANDLER]: neighbours for region {0}: {1}", regionID, rinfos.Count);
Dictionary<string, object> result = new Dictionary<string, object>();
if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0)))
result["result"] = "null";
else
{
int i = 0;
foreach (GridRegion rinfo in rinfos)
{
Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs();
result["region" + i] = rinfoDict;
i++;
}
}
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] GetRegionByUUID(Dictionary<string, string> request)
{
UUID scopeID = UUID.Zero;
if (request["SCOPEID"] != null)
UUID.TryParse(request["SCOPEID"], out scopeID);
else
m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get neighbours");
UUID regionID = UUID.Zero;
if (request["REGIONID"] != null)
UUID.TryParse(request["REGIONID"], out regionID);
else
m_log.WarnFormat("[GRID HANDLER]: no regionID in request to get neighbours");
GridRegion rinfo = m_GridService.GetRegionByUUID(scopeID, regionID);
//m_log.DebugFormat("[GRID HANDLER]: neighbours for region {0}: {1}", regionID, rinfos.Count);
Dictionary<string, object> result = new Dictionary<string, object>();
if (rinfo == null)
result["result"] = "null";
else
result["result"] = rinfo.ToKeyValuePairs();
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] GetRegionByPosition(Dictionary<string, string> request)
{
UUID scopeID = UUID.Zero;
if (request["SCOPEID"] != null)
UUID.TryParse(request["SCOPEID"], out scopeID);
else
m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get region by position");
int x = 0, y = 0;
if (request["X"] != null)
Int32.TryParse(request["X"], out x);
else
m_log.WarnFormat("[GRID HANDLER]: no X in request to get region by position");
if (request["Y"] != null)
Int32.TryParse(request["Y"], out y);
else
m_log.WarnFormat("[GRID HANDLER]: no Y in request to get region by position");
GridRegion rinfo = m_GridService.GetRegionByPosition(scopeID, x, y);
//m_log.DebugFormat("[GRID HANDLER]: neighbours for region {0}: {1}", regionID, rinfos.Count);
Dictionary<string, object> result = new Dictionary<string, object>();
if (rinfo == null)
result["result"] = "null";
else
result["result"] = rinfo.ToKeyValuePairs();
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] GetRegionByName(Dictionary<string, string> request)
{
UUID scopeID = UUID.Zero;
if (request["SCOPEID"] != null)
UUID.TryParse(request["SCOPEID"], out scopeID);
else
m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get region by name");
string regionName = string.Empty;
if (request["NAME"] != null)
regionName = request["NAME"];
else
m_log.WarnFormat("[GRID HANDLER]: no name in request to get region by name");
GridRegion rinfo = m_GridService.GetRegionByName(scopeID, regionName);
//m_log.DebugFormat("[GRID HANDLER]: neighbours for region {0}: {1}", regionID, rinfos.Count);
Dictionary<string, object> result = new Dictionary<string, object>();
if (rinfo == null)
result["result"] = "null";
else
result["result"] = rinfo.ToKeyValuePairs();
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] GetRegionsByName(Dictionary<string, string> request)
{
UUID scopeID = UUID.Zero;
if (request["SCOPEID"] != null)
UUID.TryParse(request["SCOPEID"], out scopeID);
else
m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get regions by name");
string regionName = string.Empty;
if (request["NAME"] != null)
regionName = request["NAME"];
else
m_log.WarnFormat("[GRID HANDLER]: no NAME in request to get regions by name");
int max = 0;
if (request["MAX"] != null)
Int32.TryParse(request["MAX"], out max);
else
m_log.WarnFormat("[GRID HANDLER]: no MAX in request to get regions by name");
List<GridRegion> rinfos = m_GridService.GetRegionsByName(scopeID, regionName, max);
//m_log.DebugFormat("[GRID HANDLER]: neighbours for region {0}: {1}", regionID, rinfos.Count);
Dictionary<string, object> result = new Dictionary<string, object>();
if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0)))
result["result"] = "null";
else
{
int i = 0;
foreach (GridRegion rinfo in rinfos)
{
Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs();
result["region" + i] = rinfoDict;
i++;
}
}
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] GetRegionRange(Dictionary<string, string> request)
{
//m_log.DebugFormat("[GRID HANDLER]: GetRegionRange");
UUID scopeID = UUID.Zero;
if (request.ContainsKey("SCOPEID"))
UUID.TryParse(request["SCOPEID"], out scopeID);
else
m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get region range");
int xmin = 0, xmax = 0, ymin = 0, ymax = 0;
if (request.ContainsKey("XMIN"))
Int32.TryParse(request["XMIN"], out xmin);
else
m_log.WarnFormat("[GRID HANDLER]: no XMIN in request to get region range");
if (request.ContainsKey("XMAX"))
Int32.TryParse(request["XMAX"], out xmax);
else
m_log.WarnFormat("[GRID HANDLER]: no XMAX in request to get region range");
if (request.ContainsKey("YMIN"))
Int32.TryParse(request["YMIN"], out ymin);
else
m_log.WarnFormat("[GRID HANDLER]: no YMIN in request to get region range");
if (request.ContainsKey("YMAX"))
Int32.TryParse(request["YMAX"], out ymax);
else
m_log.WarnFormat("[GRID HANDLER]: no YMAX in request to get region range");
List<GridRegion> rinfos = m_GridService.GetRegionRange(scopeID, xmin, xmax, ymin, ymax);
Dictionary<string, object> result = new Dictionary<string, object>();
if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0)))
result["result"] = "null";
else
{
int i = 0;
foreach (GridRegion rinfo in rinfos)
{
Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs();
result["region" + i] = rinfoDict;
i++;
}
}
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
#endregion
#region Misc
private byte[] SuccessResult()
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "Result", "");
result.AppendChild(doc.CreateTextNode("Success"));
rootElement.AppendChild(result);
return DocToBytes(doc);
}
private byte[] FailureResult()
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "Result", "");
result.AppendChild(doc.CreateTextNode("Failure"));
rootElement.AppendChild(result);
return DocToBytes(doc);
}
private byte[] DocToBytes(XmlDocument doc)
{
MemoryStream ms = new MemoryStream();
XmlTextWriter xw = new XmlTextWriter(ms, null);
xw.Formatting = Formatting.Indented;
doc.WriteTo(xw);
xw.Flush();
return ms.ToArray();
}
#endregion
}
}

View File

@ -0,0 +1,112 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Net;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Server.Handlers.Base;
using log4net;
using Nwc.XmlRpc;
namespace OpenSim.Server.Handlers.Grid
{
public class HypergridServiceInConnector : ServiceConnector
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private List<SimpleRegionInfo> m_RegionsOnSim = new List<SimpleRegionInfo>();
public HypergridServiceInConnector(IConfigSource config, IHttpServer server) :
base(config, server, String.Empty)
{
server.AddXmlRPCHandler("linkk_region", LinkRegionRequest, false);
}
/// <summary>
/// Someone wants to link to us
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public XmlRpcResponse LinkRegionRequest(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
//string host = (string)requestData["host"];
//string portstr = (string)requestData["port"];
string name = (string)requestData["region_name"];
m_log.DebugFormat("[HGrid]: Hyperlink request");
SimpleRegionInfo regInfo = null;
foreach (SimpleRegionInfo r in m_RegionsOnSim)
{
if ((r.RegionName != null) && (name != null) && (r.RegionName.ToLower() == name.ToLower()))
{
regInfo = r;
break;
}
}
if (regInfo == null)
regInfo = m_RegionsOnSim[0]; // Send out the first region
Hashtable hash = new Hashtable();
hash["uuid"] = regInfo.RegionID.ToString();
hash["handle"] = regInfo.RegionHandle.ToString();
//m_log.Debug(">> Here " + regInfo.RegionHandle);
//hash["region_image"] = regInfo.RegionSettings.TerrainImageID.ToString();
hash["region_name"] = regInfo.RegionName;
hash["internal_port"] = regInfo.InternalEndPoint.Port.ToString();
//m_log.Debug(">> Here: " + regInfo.InternalEndPoint.Port);
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
public void AddRegion(SimpleRegionInfo rinfo)
{
m_RegionsOnSim.Add(rinfo);
}
public void RemoveRegion(SimpleRegionInfo rinfo)
{
if (m_RegionsOnSim.Contains(rinfo))
m_RegionsOnSim.Remove(rinfo);
}
}
}

View File

@ -54,19 +54,20 @@ namespace OpenSim.Server.Handlers.Inventory
//private AuthedSessionCache m_session_cache = new AuthedSessionCache(INVENTORY_DEFAULT_SESSION_TIME); //private AuthedSessionCache m_session_cache = new AuthedSessionCache(INVENTORY_DEFAULT_SESSION_TIME);
private string m_userserver_url; private string m_userserver_url;
private string m_ConfigName = "InventoryService";
public InventoryServiceInConnector(IConfigSource config, IHttpServer server) : public InventoryServiceInConnector(IConfigSource config, IHttpServer server, string configName) :
base(config, server) base(config, server, configName)
{ {
IConfig serverConfig = config.Configs["InventoryService"]; IConfig serverConfig = config.Configs[m_ConfigName];
if (serverConfig == null) if (serverConfig == null)
throw new Exception("No section 'InventoryService' in config file"); throw new Exception(String.Format("No section '{0}' in config file", m_ConfigName));
string inventoryService = serverConfig.GetString("LocalServiceModule", string inventoryService = serverConfig.GetString("LocalServiceModule",
String.Empty); String.Empty);
if (inventoryService == String.Empty) if (inventoryService == String.Empty)
throw new Exception("No InventoryService in config file"); throw new Exception("No LocalServiceModule in config file");
Object[] args = new Object[] { config }; Object[] args = new Object[] { config };
m_InventoryService = m_InventoryService =

View File

@ -46,7 +46,7 @@ namespace OpenSim.Server.Handlers.Land
// TODO : private IAuthenticationService m_AuthenticationService; // TODO : private IAuthenticationService m_AuthenticationService;
public LandServiceInConnector(IConfigSource source, IHttpServer server, ILandService service, IScene scene) : public LandServiceInConnector(IConfigSource source, IHttpServer server, ILandService service, IScene scene) :
base(source, server) base(source, server, String.Empty)
{ {
m_LandService = service; m_LandService = service;
if (m_LandService == null) if (m_LandService == null)

View File

@ -46,7 +46,7 @@ namespace OpenSim.Server.Handlers.Neighbour
private IAuthenticationService m_AuthenticationService = null; private IAuthenticationService m_AuthenticationService = null;
public NeighbourServiceInConnector(IConfigSource source, IHttpServer server, INeighbourService nService, IScene scene) : public NeighbourServiceInConnector(IConfigSource source, IHttpServer server, INeighbourService nService, IScene scene) :
base(source, server) base(source, server, String.Empty)
{ {
m_NeighbourService = nService; m_NeighbourService = nService;

View File

@ -41,7 +41,7 @@ namespace OpenSim.Server.Handlers.Simulation
private IAuthenticationService m_AuthenticationService; private IAuthenticationService m_AuthenticationService;
public SimulationServiceInConnector(IConfigSource config, IHttpServer server, IScene scene) : public SimulationServiceInConnector(IConfigSource config, IHttpServer server, IScene scene) :
base(config, server) base(config, server, String.Empty)
{ {
IConfig serverConfig = config.Configs["SimulationService"]; IConfig serverConfig = config.Configs["SimulationService"];
if (serverConfig == null) if (serverConfig == null)

View File

@ -30,6 +30,7 @@ using log4net;
using System.Reflection; using System.Reflection;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Server.Base; using OpenSim.Server.Base;
using OpenSim.Server.Handlers.Base; using OpenSim.Server.Handlers.Base;
@ -60,22 +61,59 @@ namespace OpenSim.Server
string connList = serverConfig.GetString("ServiceConnectors", String.Empty); string connList = serverConfig.GetString("ServiceConnectors", String.Empty);
string[] conns = connList.Split(new char[] {',', ' '}); string[] conns = connList.Split(new char[] {',', ' '});
foreach (string conn in conns) int i = 0;
foreach (string c in conns)
{ {
if (conn == String.Empty) if (c == String.Empty)
continue; continue;
string configName = String.Empty;
string conn = c;
uint port = 0;
string[] split1 = conn.Split(new char[] {'/'});
if (split1.Length > 1)
{
conn = split1[1];
string[] split2 = split1[0].Split(new char[] {'@'});
if (split2.Length > 1)
{
configName = split2[0];
port = Convert.ToUInt32(split2[1]);
}
else
{
port = Convert.ToUInt32(split1[0]);
}
}
string[] parts = conn.Split(new char[] {':'}); string[] parts = conn.Split(new char[] {':'});
string friendlyName = parts[0]; string friendlyName = parts[0];
if (parts.Length > 1) if (parts.Length > 1)
friendlyName = parts[1]; friendlyName = parts[1];
m_log.InfoFormat("[SERVER]: Loading {0}", friendlyName); IHttpServer server = m_Server.HttpServer;
if (port != 0)
server = m_Server.GetHttpServer(port);
Object[] modargs = new Object[] { m_Server.Config, m_Server.HttpServer }; if (port != m_Server.DefaultPort)
IServiceConnector connector = m_log.InfoFormat("[SERVER]: Loading {0} on port {1}", friendlyName, port);
ServerUtils.LoadPlugin<IServiceConnector>(conn, else
m_log.InfoFormat("[SERVER]: Loading {0}", friendlyName);
IServiceConnector connector = null;
Object[] modargs = new Object[] { m_Server.Config, server,
configName };
connector = ServerUtils.LoadPlugin<IServiceConnector>(conn,
modargs); modargs);
if (connector == null)
{
modargs = new Object[] { m_Server.Config, server };
connector =
ServerUtils.LoadPlugin<IServiceConnector>(conn,
modargs);
}
if (connector != null) if (connector != null)
{ {

View File

@ -43,9 +43,9 @@ namespace OpenSim.Services.AuthenticationService
// //
public class AuthenticationServiceBase : ServiceBase public class AuthenticationServiceBase : ServiceBase
{ {
private static readonly ILog m_log = // private static readonly ILog m_log =
LogManager.GetLogger( // LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType); // MethodBase.GetCurrentMethod().DeclaringType);
protected IAuthenticationData m_Database; protected IAuthenticationData m_Database;

View File

@ -47,9 +47,9 @@ namespace OpenSim.Services.AuthenticationService
public class PasswordAuthenticationService : public class PasswordAuthenticationService :
AuthenticationServiceBase, IAuthenticationService AuthenticationServiceBase, IAuthenticationService
{ {
private static readonly ILog m_log = // private static readonly ILog m_log =
LogManager.GetLogger( // LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType); // MethodBase.GetCurrentMethod().DeclaringType);
public PasswordAuthenticationService(IConfigSource config) : public PasswordAuthenticationService(IConfigSource config) :
base(config) base(config)

View File

@ -43,9 +43,9 @@ namespace OpenSim.Services.AuthenticationService
public class WebkeyAuthenticationService : public class WebkeyAuthenticationService :
AuthenticationServiceBase, IAuthenticationService AuthenticationServiceBase, IAuthenticationService
{ {
private static readonly ILog m_log = // private static readonly ILog m_log =
LogManager.GetLogger( // LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType); // MethodBase.GetCurrentMethod().DeclaringType);
public WebkeyAuthenticationService(IConfigSource config) : public WebkeyAuthenticationService(IConfigSource config) :
base(config) base(config)

View File

@ -0,0 +1,448 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenSim.Server.Base;
using OpenMetaverse;
namespace OpenSim.Services.Connectors
{
public class GridServicesConnector : IGridService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private string m_ServerURI = String.Empty;
public GridServicesConnector()
{
}
public GridServicesConnector(string serverURI)
{
m_ServerURI = serverURI.TrimEnd('/');
}
public GridServicesConnector(IConfigSource source)
{
Initialise(source);
}
public virtual void Initialise(IConfigSource source)
{
IConfig gridConfig = source.Configs["GridService"];
if (gridConfig == null)
{
m_log.Error("[GRID CONNECTOR]: GridService missing from OpenSim.ini");
throw new Exception("Grid connector init error");
}
string serviceURI = gridConfig.GetString("GridServerURI",
String.Empty);
if (serviceURI == String.Empty)
{
m_log.Error("[GRID CONNECTOR]: No Server URI named in section GridService");
throw new Exception("Grid connector init error");
}
m_ServerURI = serviceURI;
}
#region IGridService
public virtual bool RegisterRegion(UUID scopeID, GridRegion regionInfo)
{
Dictionary<string, object> rinfo = regionInfo.ToKeyValuePairs();
Dictionary<string, string> sendData = new Dictionary<string,string>();
foreach (KeyValuePair<string, object> kvp in rinfo)
sendData[kvp.Key] = (string)kvp.Value;
sendData["SCOPEID"] = scopeID.ToString();
sendData["METHOD"] = "register";
string reqString = ServerUtils.BuildQueryString(sendData);
//m_log.DebugFormat("[GRID CONNECTOR]: queryString = {0}", reqString);
try
{
string reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/grid",
reqString);
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if ((replyData["Result"] != null) && (replyData["Result"].ToString().ToLower() == "success"))
return true;
}
else
m_log.DebugFormat("[GRID CONNECTOR]: RegisterRegion received null reply");
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
}
return false;
}
public virtual bool DeregisterRegion(UUID regionID)
{
Dictionary<string, string> sendData = new Dictionary<string, string>();
sendData["REGIONID"] = regionID.ToString();
sendData["METHOD"] = "deregister";
try
{
string reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/grid",
ServerUtils.BuildQueryString(sendData));
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if ((replyData["Result"] != null) && (replyData["Result"].ToString().ToLower() == "success"))
return true;
}
else
m_log.DebugFormat("[GRID CONNECTOR]: DeregisterRegion received null reply");
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
}
return false;
}
public virtual List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID)
{
Dictionary<string, string> sendData = new Dictionary<string, string>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["REGIONID"] = regionID.ToString();
sendData["METHOD"] = "get_neighbours";
List<GridRegion> rinfos = new List<GridRegion>();
string reqString = ServerUtils.BuildQueryString(sendData);
string reply = string.Empty;
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/grid",
reqString);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
return rinfos;
}
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData != null)
{
Dictionary<string, object>.ValueCollection rinfosList = replyData.Values;
//m_log.DebugFormat("[GRID CONNECTOR]: get neighbours returned {0} elements", rinfosList.Count);
foreach (object r in rinfosList)
{
if (r is Dictionary<string, object>)
{
GridRegion rinfo = new GridRegion((Dictionary<string, object>)r);
rinfos.Add(rinfo);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetNeighbours {0}, {1} received invalid response type {2}",
scopeID, regionID, r.GetType());
}
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetNeighbours {0}, {1} received null response",
scopeID, regionID);
return rinfos;
}
public virtual GridRegion GetRegionByUUID(UUID scopeID, UUID regionID)
{
Dictionary<string, string> sendData = new Dictionary<string, string>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["REGIONID"] = regionID.ToString();
sendData["METHOD"] = "get_region_by_uuid";
string reply = string.Empty;
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/grid",
ServerUtils.BuildQueryString(sendData));
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
return null;
}
GridRegion rinfo = null;
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if ((replyData != null) && (replyData["result"] != null))
{
if (replyData["result"] is Dictionary<string, object>)
rinfo = new GridRegion((Dictionary<string, object>)replyData["result"]);
//else
// m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByUUID {0}, {1} received null response",
// scopeID, regionID);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByUUID {0}, {1} received null response",
scopeID, regionID);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByUUID received null reply");
return rinfo;
}
public virtual GridRegion GetRegionByPosition(UUID scopeID, int x, int y)
{
Dictionary<string, string> sendData = new Dictionary<string, string>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["X"] = x.ToString();
sendData["Y"] = y.ToString();
sendData["METHOD"] = "get_region_by_position";
string reply = string.Empty;
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/grid",
ServerUtils.BuildQueryString(sendData));
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
return null;
}
GridRegion rinfo = null;
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if ((replyData != null) && (replyData["result"] != null))
{
if (replyData["result"] is Dictionary<string, object>)
rinfo = new GridRegion((Dictionary<string, object>)replyData["result"]);
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition {0}, {1}-{2} received invalid response",
scopeID, x, y);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition {0}, {1}-{2} received null response",
scopeID, x, y);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition received null reply");
return rinfo;
}
public virtual GridRegion GetRegionByName(UUID scopeID, string regionName)
{
Dictionary<string, string> sendData = new Dictionary<string, string>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["NAME"] = regionName;
sendData["METHOD"] = "get_region_by_name";
string reply = string.Empty;
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/grid",
ServerUtils.BuildQueryString(sendData));
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
return null;
}
GridRegion rinfo = null;
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if ((replyData != null) && (replyData["result"] != null))
{
if (replyData["result"] is Dictionary<string, object>)
rinfo = new GridRegion((Dictionary<string, object>)replyData["result"]);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByPosition {0}, {1} received null response",
scopeID, regionName);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionByName received null reply");
return rinfo;
}
public virtual List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber)
{
Dictionary<string, string> sendData = new Dictionary<string, string>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["NAME"] = name;
sendData["MAX"] = maxNumber.ToString();
sendData["METHOD"] = "get_regions_by_name";
List<GridRegion> rinfos = new List<GridRegion>();
string reply = string.Empty;
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/grid",
ServerUtils.BuildQueryString(sendData));
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
return rinfos;
}
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData != null)
{
Dictionary<string, object>.ValueCollection rinfosList = replyData.Values;
foreach (object r in rinfosList)
{
if (r is Dictionary<string, object>)
{
GridRegion rinfo = new GridRegion((Dictionary<string, object>)r);
rinfos.Add(rinfo);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionsByName {0}, {1}, {2} received invalid response",
scopeID, name, maxNumber);
}
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionsByName {0}, {1}, {2} received null response",
scopeID, name, maxNumber);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionsByName received null reply");
return rinfos;
}
public virtual List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax)
{
Dictionary<string, string> sendData = new Dictionary<string, string>();
sendData["SCOPEID"] = scopeID.ToString();
sendData["XMIN"] = xmin.ToString();
sendData["XMAX"] = xmax.ToString();
sendData["YMIN"] = ymin.ToString();
sendData["YMAX"] = ymax.ToString();
sendData["METHOD"] = "get_region_range";
List<GridRegion> rinfos = new List<GridRegion>();
string reply = string.Empty;
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
m_ServerURI + "/grid",
ServerUtils.BuildQueryString(sendData));
//m_log.DebugFormat("[GRID CONNECTOR]: reply was {0}", reply);
}
catch (Exception e)
{
m_log.DebugFormat("[GRID CONNECTOR]: Exception when contacting grid server: {0}", e.Message);
return rinfos;
}
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData != null)
{
Dictionary<string, object>.ValueCollection rinfosList = replyData.Values;
foreach (object r in rinfosList)
{
if (r is Dictionary<string, object>)
{
GridRegion rinfo = new GridRegion((Dictionary<string, object>)r);
rinfos.Add(rinfo);
}
}
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionRange {0}, {1}-{2} {3}-{4} received null response",
scopeID, xmin, xmax, ymin, ymax);
}
else
m_log.DebugFormat("[GRID CONNECTOR]: GetRegionRange received null reply");
return rinfos;
}
#endregion
}
}

View File

@ -0,0 +1,152 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Net;
using System.Reflection;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenSim.Framework;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using log4net;
using Nwc.XmlRpc;
namespace OpenSim.Services.Connectors.Grid
{
public class HypergridServiceConnector
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IAssetService m_AssetService;
public HypergridServiceConnector(IAssetService assService)
{
m_AssetService = assService;
}
public UUID LinkRegion(GridRegion info, out ulong realHandle)
{
UUID uuid = UUID.Zero;
realHandle = 0;
Hashtable hash = new Hashtable();
hash["region_name"] = info.RegionName;
IList paramList = new ArrayList();
paramList.Add(hash);
XmlRpcRequest request = new XmlRpcRequest("linkk_region", paramList);
string uri = "http://" + info.ExternalEndPoint.Address + ":" + info.HttpPort + "/";
m_log.Debug("[HGrid]: Linking to " + uri);
XmlRpcResponse response = request.Send(uri, 10000);
if (response.IsFault)
{
m_log.ErrorFormat("[HGrid]: remote call returned an error: {0}", response.FaultString);
}
else
{
hash = (Hashtable)response.Value;
//foreach (Object o in hash)
// m_log.Debug(">> " + ((DictionaryEntry)o).Key + ":" + ((DictionaryEntry)o).Value);
try
{
UUID.TryParse((string)hash["uuid"], out uuid);
info.RegionID = uuid;
if ((string)hash["handle"] != null)
{
realHandle = Convert.ToUInt64((string)hash["handle"]);
m_log.Debug(">> HERE, realHandle: " + realHandle);
}
//if (hash["region_image"] != null)
//{
// UUID img = UUID.Zero;
// UUID.TryParse((string)hash["region_image"], out img);
// info.RegionSettings.TerrainImageID = img;
//}
if (hash["region_name"] != null)
{
info.RegionName = (string)hash["region_name"];
//m_log.Debug(">> " + info.RegionName);
}
if (hash["internal_port"] != null)
{
int port = Convert.ToInt32((string)hash["internal_port"]);
info.InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), port);
//m_log.Debug(">> " + info.InternalEndPoint.ToString());
}
}
catch (Exception e)
{
m_log.Error("[HGrid]: Got exception while parsing hyperlink response " + e.StackTrace);
}
}
return uuid;
}
public void GetMapImage(GridRegion info)
{
try
{
string regionimage = "regionImage" + info.RegionID.ToString();
regionimage = regionimage.Replace("-", "");
WebClient c = new WebClient();
string uri = "http://" + info.ExternalHostName + ":" + info.HttpPort + "/index.php?method=" + regionimage;
//m_log.Debug("JPEG: " + uri);
c.DownloadFile(uri, info.RegionID.ToString() + ".jpg");
Bitmap m = new Bitmap(info.RegionID.ToString() + ".jpg");
//m_log.Debug("Size: " + m.PhysicalDimension.Height + "-" + m.PhysicalDimension.Width);
byte[] imageData = OpenJPEG.EncodeFromImage(m, true);
AssetBase ass = new AssetBase(UUID.Random(), "region " + info.RegionID.ToString());
// !!! for now
//info.RegionSettings.TerrainImageID = ass.FullID;
ass.Type = (int)AssetType.Texture;
ass.Temporary = true;
ass.Local = true;
ass.Data = imageData;
m_AssetService.Store(ass);
}
catch // LEGIT: Catching problems caused by OpenJPEG p/invoke
{
m_log.Warn("[HGrid]: Failed getting/storing map image, because it is probably already in the cache");
}
}
}
}

View File

@ -35,6 +35,7 @@ using OpenSim.Framework;
using OpenSim.Framework.Console; using OpenSim.Framework.Console;
using OpenSim.Data; using OpenSim.Data;
using OpenSim.Services.Interfaces; using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenMetaverse; using OpenMetaverse;
namespace OpenSim.Services.GridService namespace OpenSim.Services.GridService
@ -48,33 +49,28 @@ namespace OpenSim.Services.GridService
public GridService(IConfigSource config) public GridService(IConfigSource config)
: base(config) : base(config)
{ {
MainConsole.Instance.Commands.AddCommand("kfs", false, m_log.DebugFormat("[GRID SERVICE]: Starting...");
"show digest",
"show digest <ID>",
"Show asset digest", HandleShowDigest);
MainConsole.Instance.Commands.AddCommand("kfs", false,
"delete asset",
"delete asset <ID>",
"Delete asset from database", HandleDeleteAsset);
} }
#region IGridService #region IGridService
public bool RegisterRegion(UUID scopeID, SimpleRegionInfo regionInfos) public bool RegisterRegion(UUID scopeID, GridRegion regionInfos)
{ {
if (m_Database.Get(regionInfos.RegionID, scopeID) != null) // This needs better sanity testing. What if regionInfo is registering in
{ // overlapping coords?
m_log.WarnFormat("[GRID SERVICE]: Region {0} already registered in scope {1}.", regionInfos.RegionID, scopeID); RegionData region = m_Database.Get(regionInfos.RegionLocX, regionInfos.RegionLocY, scopeID);
return false; if ((region != null) && (region.RegionID != regionInfos.RegionID))
}
if (m_Database.Get((int)regionInfos.RegionLocX, (int)regionInfos.RegionLocY, scopeID) != null)
{ {
m_log.WarnFormat("[GRID SERVICE]: Region {0} tried to register in coordinates {1}, {2} which are already in use in scope {3}.", m_log.WarnFormat("[GRID SERVICE]: Region {0} tried to register in coordinates {1}, {2} which are already in use in scope {3}.",
regionInfos.RegionID, regionInfos.RegionLocX, regionInfos.RegionLocY, scopeID); regionInfos.RegionID, regionInfos.RegionLocX, regionInfos.RegionLocY, scopeID);
return false; return false;
} }
if ((region != null) && (region.RegionID == regionInfos.RegionID) &&
((region.posX != regionInfos.RegionLocX) || (region.posY != regionInfos.RegionLocY)))
{
// Region reregistering in other coordinates. Delete the old entry
m_Database.Delete(regionInfos.RegionID);
}
// Everything is ok, let's register // Everything is ok, let's register
RegionData rdata = RegionInfo2RegionData(regionInfos); RegionData rdata = RegionInfo2RegionData(regionInfos);
@ -88,17 +84,25 @@ namespace OpenSim.Services.GridService
return m_Database.Delete(regionID); return m_Database.Delete(regionID);
} }
public List<SimpleRegionInfo> GetNeighbours(UUID scopeID, int x, int y) public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID)
{ {
List<RegionData> rdatas = m_Database.Get(x - 1, y - 1, x + 1, y + 1, scopeID); List<GridRegion> rinfos = new List<GridRegion>();
List<SimpleRegionInfo> rinfos = new List<SimpleRegionInfo>(); RegionData region = m_Database.Get(regionID, scopeID);
foreach (RegionData rdata in rdatas) if (region != null)
rinfos.Add(RegionData2RegionInfo(rdata)); {
// Not really? Maybe?
List<RegionData> rdatas = m_Database.Get(region.posX - (int)Constants.RegionSize, region.posY - (int)Constants.RegionSize,
region.posX + (int)Constants.RegionSize, region.posY + (int)Constants.RegionSize, scopeID);
foreach (RegionData rdata in rdatas)
if (rdata.RegionID != regionID)
rinfos.Add(RegionData2RegionInfo(rdata));
}
return rinfos; return rinfos;
} }
public SimpleRegionInfo GetRegionByUUID(UUID scopeID, UUID regionID) public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID)
{ {
RegionData rdata = m_Database.Get(regionID, scopeID); RegionData rdata = m_Database.Get(regionID, scopeID);
if (rdata != null) if (rdata != null)
@ -107,16 +111,18 @@ namespace OpenSim.Services.GridService
return null; return null;
} }
public SimpleRegionInfo GetRegionByPosition(UUID scopeID, int x, int y) public GridRegion GetRegionByPosition(UUID scopeID, int x, int y)
{ {
RegionData rdata = m_Database.Get(x, y, scopeID); int snapX = (int)(x / Constants.RegionSize) * (int)Constants.RegionSize;
int snapY = (int)(y / Constants.RegionSize) * (int)Constants.RegionSize;
RegionData rdata = m_Database.Get(snapX, snapY, scopeID);
if (rdata != null) if (rdata != null)
return RegionData2RegionInfo(rdata); return RegionData2RegionInfo(rdata);
return null; return null;
} }
public SimpleRegionInfo GetRegionByName(UUID scopeID, string regionName) public GridRegion GetRegionByName(UUID scopeID, string regionName)
{ {
List<RegionData> rdatas = m_Database.Get(regionName + "%", scopeID); List<RegionData> rdatas = m_Database.Get(regionName + "%", scopeID);
if ((rdatas != null) && (rdatas.Count > 0)) if ((rdatas != null) && (rdatas.Count > 0))
@ -125,12 +131,12 @@ namespace OpenSim.Services.GridService
return null; return null;
} }
public List<SimpleRegionInfo> GetRegionsByName(UUID scopeID, string name, int maxNumber) public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber)
{ {
List<RegionData> rdatas = m_Database.Get("%" + name + "%", scopeID); List<RegionData> rdatas = m_Database.Get("%" + name + "%", scopeID);
int count = 0; int count = 0;
List<SimpleRegionInfo> rinfos = new List<SimpleRegionInfo>(); List<GridRegion> rinfos = new List<GridRegion>();
if (rdatas != null) if (rdatas != null)
{ {
@ -144,10 +150,15 @@ namespace OpenSim.Services.GridService
return rinfos; return rinfos;
} }
public List<SimpleRegionInfo> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax) public List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax)
{ {
List<RegionData> rdatas = m_Database.Get(xmin, ymin, xmax, ymax, scopeID); int xminSnap = (int)(xmin / Constants.RegionSize) * (int)Constants.RegionSize;
List<SimpleRegionInfo> rinfos = new List<SimpleRegionInfo>(); int xmaxSnap = (int)(xmax / Constants.RegionSize) * (int)Constants.RegionSize;
int yminSnap = (int)(ymin / Constants.RegionSize) * (int)Constants.RegionSize;
int ymaxSnap = (int)(ymax / Constants.RegionSize) * (int)Constants.RegionSize;
List<RegionData> rdatas = m_Database.Get(xminSnap, yminSnap, xmaxSnap, ymaxSnap, scopeID);
List<GridRegion> rinfos = new List<GridRegion>();
foreach (RegionData rdata in rdatas) foreach (RegionData rdata in rdatas)
rinfos.Add(RegionData2RegionInfo(rdata)); rinfos.Add(RegionData2RegionInfo(rdata));
@ -158,140 +169,31 @@ namespace OpenSim.Services.GridService
#region Data structure conversions #region Data structure conversions
protected RegionData RegionInfo2RegionData(SimpleRegionInfo rinfo) protected RegionData RegionInfo2RegionData(GridRegion rinfo)
{ {
RegionData rdata = new RegionData(); RegionData rdata = new RegionData();
rdata.posX = (int)rinfo.RegionLocX; rdata.posX = (int)rinfo.RegionLocX;
rdata.posY = (int)rinfo.RegionLocY; rdata.posY = (int)rinfo.RegionLocY;
rdata.RegionID = rinfo.RegionID; rdata.RegionID = rinfo.RegionID;
//rdata.RegionName = rinfo.RegionName; rdata.RegionName = rinfo.RegionName;
rdata.Data["external_ip_address"] = rinfo.ExternalEndPoint.Address.ToString(); rdata.Data = rinfo.ToKeyValuePairs();
rdata.Data["external_port"] = rinfo.ExternalEndPoint.Port.ToString(); rdata.Data["regionHandle"] = Utils.UIntsToLong((uint)rdata.posX, (uint)rdata.posY);
rdata.Data["external_host_name"] = rinfo.ExternalHostName;
rdata.Data["http_port"] = rinfo.HttpPort.ToString();
rdata.Data["internal_ip_address"] = rinfo.InternalEndPoint.Address.ToString();
rdata.Data["internal_port"] = rinfo.InternalEndPoint.Port.ToString();
rdata.Data["alternate_ports"] = rinfo.m_allow_alternate_ports.ToString();
rdata.Data["server_uri"] = rinfo.ServerURI;
return rdata; return rdata;
} }
protected SimpleRegionInfo RegionData2RegionInfo(RegionData rdata) protected GridRegion RegionData2RegionInfo(RegionData rdata)
{ {
SimpleRegionInfo rinfo = new SimpleRegionInfo(); GridRegion rinfo = new GridRegion(rdata.Data);
rinfo.RegionLocX = (uint)rdata.posX; rinfo.RegionLocX = rdata.posX;
rinfo.RegionLocY = (uint)rdata.posY; rinfo.RegionLocY = rdata.posY;
rinfo.RegionID = rdata.RegionID; rinfo.RegionID = rdata.RegionID;
//rinfo.RegionName = rdata.RegionName; rinfo.RegionName = rdata.RegionName;
rinfo.ScopeID = rdata.ScopeID;
// Now for the variable data
if ((rdata.Data["external_ip_address"] != null) && (rdata.Data["external_port"] != null))
{
int port = 0;
Int32.TryParse((string)rdata.Data["external_port"], out port);
IPEndPoint ep = new IPEndPoint(IPAddress.Parse((string)rdata.Data["external_ip_address"]), port);
rinfo.ExternalEndPoint = ep;
}
else
rinfo.ExternalEndPoint = new IPEndPoint(new IPAddress(0), 0);
if (rdata.Data["external_host_name"] != null)
rinfo.ExternalHostName = (string)rdata.Data["external_host_name"] ;
if (rdata.Data["http_port"] != null)
{
UInt32 port = 0;
UInt32.TryParse((string)rdata.Data["http_port"], out port);
rinfo.HttpPort = port;
}
if ((rdata.Data["internal_ip_address"] != null) && (rdata.Data["internal_port"] != null))
{
int port = 0;
Int32.TryParse((string)rdata.Data["internal_port"], out port);
IPEndPoint ep = new IPEndPoint(IPAddress.Parse((string)rdata.Data["internal_ip_address"]), port);
rinfo.InternalEndPoint = ep;
}
else
rinfo.InternalEndPoint = new IPEndPoint(new IPAddress(0), 0);
if (rdata.Data["alternate_ports"] != null)
{
bool alts = false;
Boolean.TryParse((string)rdata.Data["alternate_ports"], out alts);
rinfo.m_allow_alternate_ports = alts;
}
if (rdata.Data["server_uri"] != null)
rinfo.ServerURI = (string)rdata.Data["server_uri"];
return rinfo; return rinfo;
} }
#endregion #endregion
void HandleShowDigest(string module, string[] args)
{
//if (args.Length < 3)
//{
// MainConsole.Instance.Output("Syntax: show digest <ID>");
// return;
//}
//AssetBase asset = Get(args[2]);
//if (asset == null || asset.Data.Length == 0)
//{
// MainConsole.Instance.Output("Asset not found");
// return;
//}
//int i;
//MainConsole.Instance.Output(String.Format("Name: {0}", asset.Name));
//MainConsole.Instance.Output(String.Format("Description: {0}", asset.Description));
//MainConsole.Instance.Output(String.Format("Type: {0}", asset.Type));
//MainConsole.Instance.Output(String.Format("Content-type: {0}", asset.Metadata.ContentType));
//for (i = 0 ; i < 5 ; i++)
//{
// int off = i * 16;
// if (asset.Data.Length <= off)
// break;
// int len = 16;
// if (asset.Data.Length < off + len)
// len = asset.Data.Length - off;
// byte[] line = new byte[len];
// Array.Copy(asset.Data, off, line, 0, len);
// string text = BitConverter.ToString(line);
// MainConsole.Instance.Output(String.Format("{0:x4}: {1}", off, text));
//}
}
void HandleDeleteAsset(string module, string[] args)
{
//if (args.Length < 3)
//{
// MainConsole.Instance.Output("Syntax: delete asset <ID>");
// return;
//}
//AssetBase asset = Get(args[2]);
//if (asset == null || asset.Data.Length == 0)
// MainConsole.Instance.Output("Asset not found");
// return;
//}
//Delete(args[2]);
////MainConsole.Instance.Output("Asset deleted");
//// TODO: Implement this
//MainConsole.Instance.Output("Asset deletion not supported by database");
}
} }
} }

View File

@ -46,17 +46,6 @@ namespace OpenSim.Services.GridService
string connString = String.Empty; string connString = String.Empty;
string realm = "regions"; string realm = "regions";
//
// Try reading the [AssetService] section first, if it exists
//
IConfig gridConfig = config.Configs["GridService"];
if (gridConfig != null)
{
dllName = gridConfig.GetString("StorageProvider", dllName);
connString = gridConfig.GetString("ConnectionString", connString);
realm = gridConfig.GetString("Realm", realm);
}
// //
// Try reading the [DatabaseService] section, if it exists // Try reading the [DatabaseService] section, if it exists
// //
@ -69,6 +58,17 @@ namespace OpenSim.Services.GridService
connString = dbConfig.GetString("ConnectionString", String.Empty); connString = dbConfig.GetString("ConnectionString", String.Empty);
} }
//
// [GridService] section overrides [DatabaseService], if it exists
//
IConfig gridConfig = config.Configs["GridService"];
if (gridConfig != null)
{
dllName = gridConfig.GetString("StorageProvider", dllName);
connString = gridConfig.GetString("ConnectionString", connString);
realm = gridConfig.GetString("Realm", realm);
}
// //
// We tried, but this doesn't exist. We can't proceed. // We tried, but this doesn't exist. We can't proceed.
// //

View File

@ -25,8 +25,11 @@
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ */
using OpenSim.Framework; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using OpenSim.Framework;
using OpenMetaverse; using OpenMetaverse;
namespace OpenSim.Services.Interfaces namespace OpenSim.Services.Interfaces
@ -39,7 +42,7 @@ namespace OpenSim.Services.Interfaces
/// <param name="regionInfos"> </param> /// <param name="regionInfos"> </param>
/// <returns></returns> /// <returns></returns>
/// <exception cref="System.Exception">Thrown if region registration failed</exception> /// <exception cref="System.Exception">Thrown if region registration failed</exception>
bool RegisterRegion(UUID scopeID, SimpleRegionInfo regionInfos); bool RegisterRegion(UUID scopeID, GridRegion regionInfos);
/// <summary> /// <summary>
/// Deregister a region with the grid service. /// Deregister a region with the grid service.
@ -55,9 +58,9 @@ namespace OpenSim.Services.Interfaces
/// <param name="x"></param> /// <param name="x"></param>
/// <param name="y"></param> /// <param name="y"></param>
/// <returns></returns> /// <returns></returns>
List<SimpleRegionInfo> GetNeighbours(UUID scopeID, int x, int y); List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID);
SimpleRegionInfo GetRegionByUUID(UUID scopeID, UUID regionID); GridRegion GetRegionByUUID(UUID scopeID, UUID regionID);
/// <summary> /// <summary>
/// Get the region at the given position (in meters) /// Get the region at the given position (in meters)
@ -66,9 +69,9 @@ namespace OpenSim.Services.Interfaces
/// <param name="x"></param> /// <param name="x"></param>
/// <param name="y"></param> /// <param name="y"></param>
/// <returns></returns> /// <returns></returns>
SimpleRegionInfo GetRegionByPosition(UUID scopeID, int x, int y); GridRegion GetRegionByPosition(UUID scopeID, int x, int y);
SimpleRegionInfo GetRegionByName(UUID scopeID, string regionName); GridRegion GetRegionByName(UUID scopeID, string regionName);
/// <summary> /// <summary>
/// Get information about regions starting with the provided name. /// Get information about regions starting with the provided name.
@ -83,9 +86,233 @@ namespace OpenSim.Services.Interfaces
/// A list of <see cref="RegionInfo"/>s of regions with matching name. If the /// A list of <see cref="RegionInfo"/>s of regions with matching name. If the
/// grid-server couldn't be contacted or returned an error, return null. /// grid-server couldn't be contacted or returned an error, return null.
/// </returns> /// </returns>
List<SimpleRegionInfo> GetRegionsByName(UUID scopeID, string name, int maxNumber); List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber);
List<SimpleRegionInfo> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax); List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax);
} }
public class GridRegion
{
/// <summary>
/// The port by which http communication occurs with the region
/// </summary>
public uint HttpPort
{
get { return m_httpPort; }
set { m_httpPort = value; }
}
protected uint m_httpPort;
/// <summary>
/// A well-formed URI for the host region server (namely "http://" + ExternalHostName)
/// </summary>
public string ServerURI
{
get { return m_serverURI; }
set { m_serverURI = value; }
}
protected string m_serverURI;
public string RegionName
{
get { return m_regionName; }
set { m_regionName = value; }
}
protected string m_regionName = String.Empty;
protected bool Allow_Alternate_Ports;
public bool m_allow_alternate_ports;
protected string m_externalHostName;
protected IPEndPoint m_internalEndPoint;
public int RegionLocX
{
get { return m_regionLocX; }
set { m_regionLocX = value; }
}
protected int m_regionLocX;
public int RegionLocY
{
get { return m_regionLocY; }
set { m_regionLocY = value; }
}
protected int m_regionLocY;
public UUID RegionID = UUID.Zero;
public UUID ScopeID = UUID.Zero;
public GridRegion()
{
}
public GridRegion(int regionLocX, int regionLocY, IPEndPoint internalEndPoint, string externalUri)
{
m_regionLocX = regionLocX;
m_regionLocY = regionLocY;
m_internalEndPoint = internalEndPoint;
m_externalHostName = externalUri;
}
public GridRegion(int regionLocX, int regionLocY, string externalUri, uint port)
{
m_regionLocX = regionLocX;
m_regionLocY = regionLocY;
m_externalHostName = externalUri;
m_internalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), (int)port);
}
public GridRegion(uint xcell, uint ycell)
{
m_regionLocX = (int)(xcell * Constants.RegionSize);
m_regionLocY = (int)(ycell * Constants.RegionSize);
}
public GridRegion(RegionInfo ConvertFrom)
{
m_regionName = ConvertFrom.RegionName;
m_regionLocX = (int)(ConvertFrom.RegionLocX * Constants.RegionSize);
m_regionLocY = (int)(ConvertFrom.RegionLocY * Constants.RegionSize);
m_internalEndPoint = ConvertFrom.InternalEndPoint;
m_externalHostName = ConvertFrom.ExternalHostName;
m_httpPort = ConvertFrom.HttpPort;
m_allow_alternate_ports = ConvertFrom.m_allow_alternate_ports;
RegionID = UUID.Zero;
ServerURI = ConvertFrom.ServerURI;
}
/// <value>
/// This accessor can throw all the exceptions that Dns.GetHostAddresses can throw.
///
/// XXX Isn't this really doing too much to be a simple getter, rather than an explict method?
/// </value>
public IPEndPoint ExternalEndPoint
{
get
{
// Old one defaults to IPv6
//return new IPEndPoint(Dns.GetHostAddresses(m_externalHostName)[0], m_internalEndPoint.Port);
IPAddress ia = null;
// If it is already an IP, don't resolve it - just return directly
if (IPAddress.TryParse(m_externalHostName, out ia))
return new IPEndPoint(ia, m_internalEndPoint.Port);
// Reset for next check
ia = null;
try
{
foreach (IPAddress Adr in Dns.GetHostAddresses(m_externalHostName))
{
if (ia == null)
ia = Adr;
if (Adr.AddressFamily == AddressFamily.InterNetwork)
{
ia = Adr;
break;
}
}
}
catch (SocketException e)
{
throw new Exception(
"Unable to resolve local hostname " + m_externalHostName + " innerException of type '" +
e + "' attached to this exception", e);
}
return new IPEndPoint(ia, m_internalEndPoint.Port);
}
set { m_externalHostName = value.ToString(); }
}
public string ExternalHostName
{
get { return m_externalHostName; }
set { m_externalHostName = value; }
}
public IPEndPoint InternalEndPoint
{
get { return m_internalEndPoint; }
set { m_internalEndPoint = value; }
}
public ulong RegionHandle
{
get { return Util.UIntsToLong((uint)RegionLocX, (uint)RegionLocY); }
}
public int getInternalEndPointPort()
{
return m_internalEndPoint.Port;
}
public Dictionary<string, object> ToKeyValuePairs()
{
Dictionary<string, object> kvp = new Dictionary<string, object>();
kvp["uuid"] = RegionID.ToString();
kvp["locX"] = RegionLocX.ToString();
kvp["locY"] = RegionLocY.ToString();
kvp["regionName"] = RegionName;
kvp["serverIP"] = ExternalHostName; //ExternalEndPoint.Address.ToString();
kvp["serverHttpPort"] = HttpPort.ToString();
kvp["serverURI"] = ServerURI;
kvp["serverPort"] = InternalEndPoint.Port.ToString();
return kvp;
}
public GridRegion(Dictionary<string, object> kvp)
{
if (kvp.ContainsKey("uuid"))
RegionID = new UUID((string)kvp["uuid"]);
if (kvp.ContainsKey("locX"))
RegionLocX = Convert.ToInt32((string)kvp["locX"]);
if (kvp.ContainsKey("locY"))
RegionLocY = Convert.ToInt32((string)kvp["locY"]);
if (kvp.ContainsKey("regionName"))
RegionName = (string)kvp["regionName"];
if (kvp.ContainsKey("serverIP"))
{
//int port = 0;
//Int32.TryParse((string)kvp["serverPort"], out port);
//IPEndPoint ep = new IPEndPoint(IPAddress.Parse((string)kvp["serverIP"]), port);
ExternalHostName = (string)kvp["serverIP"];
}
else
ExternalHostName = "127.0.0.1";
if (kvp.ContainsKey("serverPort"))
{
Int32 port = 0;
Int32.TryParse((string)kvp["serverPort"], out port);
InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), port);
}
if (kvp.ContainsKey("serverHttpPort"))
{
UInt32 port = 0;
UInt32.TryParse((string)kvp["serverHttpPort"], out port);
HttpPort = port;
}
if (kvp.ContainsKey("serverURI"))
ServerURI = (string)kvp["serverURI"];
}
}
} }

View File

@ -0,0 +1,177 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using OpenMetaverse;
using log4net;
using log4net.Appender;
using log4net.Layout;
using OpenSim.Framework;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenSim.Services.Connectors;
namespace OpenSim.Tests.Clients.GridClient
{
public class GridClient
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
public static void Main(string[] args)
{
ConsoleAppender consoleAppender = new ConsoleAppender();
consoleAppender.Layout =
new PatternLayout("%date [%thread] %-5level %logger [%property{NDC}] - %message%newline");
log4net.Config.BasicConfigurator.Configure(consoleAppender);
string serverURI = "http://127.0.0.1:8002";
GridServicesConnector m_Connector = new GridServicesConnector(serverURI);
GridRegion r1 = CreateRegion("Test Region 1", 1000, 1000);
GridRegion r2 = CreateRegion("Test Region 2", 1001, 1000);
GridRegion r3 = CreateRegion("Test Region 3", 1005, 1000);
Console.WriteLine("[GRID CLIENT]: *** Registering region 1");
bool success = m_Connector.RegisterRegion(UUID.Zero, r1);
if (success)
Console.WriteLine("[GRID CLIENT]: Successfully registered region 1");
else
Console.WriteLine("[GRID CLIENT]: region 1 failed to register");
Console.WriteLine("[GRID CLIENT]: *** Registering region 2");
success = m_Connector.RegisterRegion(UUID.Zero, r2);
if (success)
Console.WriteLine("[GRID CLIENT]: Successfully registered region 2");
else
Console.WriteLine("[GRID CLIENT]: region 2 failed to register");
Console.WriteLine("[GRID CLIENT]: *** Registering region 3");
success = m_Connector.RegisterRegion(UUID.Zero, r3);
if (success)
Console.WriteLine("[GRID CLIENT]: Successfully registered region 3");
else
Console.WriteLine("[GRID CLIENT]: region 3 failed to register");
Console.WriteLine("[GRID CLIENT]: *** Deregistering region 3");
success = m_Connector.DeregisterRegion(r3.RegionID);
if (success)
Console.WriteLine("[GRID CLIENT]: Successfully deregistered region 3");
else
Console.WriteLine("[GRID CLIENT]: region 3 failed to deregister");
Console.WriteLine("[GRID CLIENT]: *** Registering region 3 again");
success = m_Connector.RegisterRegion(UUID.Zero, r3);
if (success)
Console.WriteLine("[GRID CLIENT]: Successfully registered region 3");
else
Console.WriteLine("[GRID CLIENT]: region 3 failed to register");
Console.WriteLine("[GRID CLIENT]: *** GetNeighbours of region 1");
List<GridRegion> regions = m_Connector.GetNeighbours(UUID.Zero, r1.RegionID);
if (regions == null)
Console.WriteLine("[GRID CLIENT]: GetNeighbours of region 1 failed");
else if (regions.Count > 0)
{
if (regions.Count != 1)
Console.WriteLine("[GRID CLIENT]: GetNeighbours of region 1 returned more neighbours than expected: " + regions.Count);
else
Console.WriteLine("[GRID CLIENT]: GetNeighbours of region 1 returned the right neighbour " + regions[0].RegionName);
}
else
Console.WriteLine("[GRID CLIENT]: GetNeighbours of region 1 returned 0 neighbours");
Console.WriteLine("[GRID CLIENT]: *** GetRegionByUUID of region 2 (this should succeed)");
GridRegion region = m_Connector.GetRegionByUUID(UUID.Zero, r2.RegionID);
if (region == null)
Console.WriteLine("[GRID CLIENT]: GetRegionByUUID returned null");
else
Console.WriteLine("[GRID CLIENT]: GetRegionByUUID returned region " + region.RegionName);
Console.WriteLine("[GRID CLIENT]: *** GetRegionByUUID of non-existent region (this should fail)");
region = m_Connector.GetRegionByUUID(UUID.Zero, UUID.Random());
if (region == null)
Console.WriteLine("[GRID CLIENT]: GetRegionByUUID returned null");
else
Console.WriteLine("[GRID CLIENT]: GetRegionByUUID returned region " + region.RegionName);
Console.WriteLine("[GRID CLIENT]: *** GetRegionByName of region 3 (this should succeed)");
region = m_Connector.GetRegionByName(UUID.Zero, r3.RegionName);
if (region == null)
Console.WriteLine("[GRID CLIENT]: GetRegionByName returned null");
else
Console.WriteLine("[GRID CLIENT]: GetRegionByName returned region " + region.RegionName);
Console.WriteLine("[GRID CLIENT]: *** GetRegionByName of non-existent region (this should fail)");
region = m_Connector.GetRegionByName(UUID.Zero, "Foo");
if (region == null)
Console.WriteLine("[GRID CLIENT]: GetRegionByName returned null");
else
Console.WriteLine("[GRID CLIENT]: GetRegionByName returned region " + region.RegionName);
Console.WriteLine("[GRID CLIENT]: *** GetRegionsByName (this should return 3 regions)");
regions = m_Connector.GetRegionsByName(UUID.Zero, "Test", 10);
if (regions == null)
Console.WriteLine("[GRID CLIENT]: GetRegionsByName returned null");
else
Console.WriteLine("[GRID CLIENT]: GetRegionsByName returned " + regions.Count + " regions");
Console.WriteLine("[GRID CLIENT]: *** GetRegionRange (this should return 2 regions)");
regions = m_Connector.GetRegionRange(UUID.Zero,
900 * (int)Constants.RegionSize, 1002 * (int) Constants.RegionSize,
900 * (int)Constants.RegionSize, 1002 * (int) Constants.RegionSize);
if (regions == null)
Console.WriteLine("[GRID CLIENT]: GetRegionRange returned null");
else
Console.WriteLine("[GRID CLIENT]: GetRegionRange returned " + regions.Count + " regions");
Console.WriteLine("[GRID CLIENT]: *** GetRegionRange (this should return 0 regions)");
regions = m_Connector.GetRegionRange(UUID.Zero,
900 * (int)Constants.RegionSize, 950 * (int)Constants.RegionSize,
900 * (int)Constants.RegionSize, 950 * (int)Constants.RegionSize);
if (regions == null)
Console.WriteLine("[GRID CLIENT]: GetRegionRange returned null");
else
Console.WriteLine("[GRID CLIENT]: GetRegionRange returned " + regions.Count + " regions");
Console.Write("Proceed to deregister? Press enter...");
Console.ReadLine();
// Deregister them all
Console.WriteLine("[GRID CLIENT]: *** Deregistering region 1");
success = m_Connector.DeregisterRegion(r1.RegionID);
if (success)
Console.WriteLine("[GRID CLIENT]: Successfully deregistered region 1");
else
Console.WriteLine("[GRID CLIENT]: region 1 failed to deregister");
Console.WriteLine("[GRID CLIENT]: *** Deregistering region 2");
success = m_Connector.DeregisterRegion(r2.RegionID);
if (success)
Console.WriteLine("[GRID CLIENT]: Successfully deregistered region 2");
else
Console.WriteLine("[GRID CLIENT]: region 2 failed to deregister");
Console.WriteLine("[GRID CLIENT]: *** Deregistering region 3");
success = m_Connector.DeregisterRegion(r3.RegionID);
if (success)
Console.WriteLine("[GRID CLIENT]: Successfully deregistered region 3");
else
Console.WriteLine("[GRID CLIENT]: region 3 failed to deregister");
}
private static GridRegion CreateRegion(string name, uint xcell, uint ycell)
{
GridRegion region = new GridRegion(xcell, ycell);
region.RegionName = name;
region.RegionID = UUID.Random();
region.ExternalHostName = "127.0.0.1";
region.HttpPort = 9000;
region.InternalEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("0.0.0.0"), 9000);
return region;
}
}
}

View File

@ -0,0 +1,11 @@
<html>
<form name="input" action="http://127.0.0.1:8002/grid" method="post">
xmin:<input type="text" name="XMIN" value="0">
xmax:<input type="text" name="XMAX" value="0">
ymin:<input type="text" name="YMIN" value="0">
ymax:<input type="text" name="YMAX" value="0">
<input type="hidden" name="METHOD" value="get_region_range">
<input type="submit" value="Submit" />
</form>
</html>

View File

@ -1,35 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
<appSettings>
</appSettings>
<log4net>
<appender name="Console" type="OpenSim.Framework.Console.OpenSimAppender, OpenSim.Framework.Console">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{HH:mm:ss} - %message%newline" />
</layout>
</appender>
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
<file value="OpenSim.Grid.AssetServer.log" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level - %logger %message%newline" />
</layout>
</appender>
<!-- if you'd like to know what NHibernate is doing more set value="DEBUG" -->
<logger name="NHibernate" additivity="false">
<level value="INFO"/>
<appender-ref ref="NHibernateFileLog"/>
</logger>
<root>
<level value="DEBUG" />
<appender-ref ref="Console" />
<appender-ref ref="LogFileAppender" />
</root>
</log4net>
</configuration>

View File

@ -1,35 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
<appSettings>
</appSettings>
<log4net>
<appender name="Console" type="OpenSim.Framework.Console.OpenSimAppender, OpenSim.Framework.Console">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{HH:mm:ss} - %message%newline" />
</layout>
</appender>
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
<file value="OpenSim.Grid.InventoryServer.log" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level - %logger %message%newline" />
</layout>
</appender>
<!-- if you'd like to know what NHibernate is doing more set value="DEBUG" -->
<logger name="NHibernate" additivity="false">
<level value="INFO"/>
<appender-ref ref="NHibernateFileLog"/>
</logger>
<root>
<level value="DEBUG" />
<appender-ref ref="Console" />
<appender-ref ref="LogFileAppender" />
</root>
</log4net>
</configuration>

View File

@ -0,0 +1,35 @@
; * The startup section lists all the connectors to start up in this server
; * instance. This may be only one, or it may be the entire server suite.
; * Multiple connectors should be seaprated by commas.
; *
; * These are the IN connectors the server uses, the in connectors
; * read this config file and load the needed OUT and database connectors
; *
; *
[Startup]
ServiceConnectors = "OpenSim.Server.Handlers.dll:GridServiceConnector"
; * This is common for all services, it's the network setup for the entire
; * server instance
; *
[Network]
port = 8002
; * The following are for the remote console
; * They have no effect for the local or basic console types
; * Leave commented to diable logins to the console
;ConsoleUser = Test
;ConsolePass = secret
; * As an example, the below configuration precisely mimicks the legacy
; * asset server. It is read by the asset IN connector (defined above)
; * and it then loads the OUT connector (a local database module). That,
; * in turn, reads the asset loader and database connection information
; *
[GridService]
LocalServiceModule = "OpenSim.Services.GridService.dll:GridService"
StorageProvider = "OpenSim.Data.Null.dll:NullRegionData"
;StorageProvider = "OpenSim.Data.MySQL.dll:MySqlRegionData"
;ConnectionString = "Data Source=localhost;Database=opensim;User ID=opensim;Password=***;"
Realm = "regions"

View File

@ -305,6 +305,10 @@
http_listener_sslport = 9001 ; Use this port for SSL connections http_listener_sslport = 9001 ; Use this port for SSL connections
http_listener_ssl_cert = "" ; Currently unused, but will be used for OSHttpServer http_listener_ssl_cert = "" ; Currently unused, but will be used for OSHttpServer
; Hostname to use in llRequestURL/llRequestSecureURL
; if not defined - default machine name is being used
; (on Windows this mean NETBIOS name - useably only inside local network)
; ExternalHostNameForLSL=127.0.0.1
; Uncomment below to enable llRemoteData/remote channels ; Uncomment below to enable llRemoteData/remote channels
; remoteDataPort = 20800 ; remoteDataPort = 20800
@ -1307,7 +1311,7 @@
;NoticesEnabled = true ;NoticesEnabled = true
; This makes the Groups modules very chatty on the console. ; This makes the Groups modules very chatty on the console.
;DebugEnabled = true DebugEnabled = false
; Specify which messaging module to use for groups messaging and if it's enabled ; Specify which messaging module to use for groups messaging and if it's enabled
;MessagingModule = GroupsMessagingModule ;MessagingModule = GroupsMessagingModule

View File

@ -12,6 +12,7 @@
InventoryServices = "LocalInventoryServicesConnector" InventoryServices = "LocalInventoryServicesConnector"
NeighbourServices = "LocalNeighbourServicesConnector" NeighbourServices = "LocalNeighbourServicesConnector"
AuthorizationServices = "LocalAuthorizationServicesConnector" AuthorizationServices = "LocalAuthorizationServicesConnector"
GridServices = "LocalGridServicesConnector"
[AssetService] [AssetService]
LocalServiceModule = "OpenSim.Services.AssetService.dll:AssetService" LocalServiceModule = "OpenSim.Services.AssetService.dll:AssetService"
@ -21,3 +22,8 @@
[AuthorizationService] [AuthorizationService]
LocalServiceModule = "OpenSim.Services.AuthorizationService.dll:AuthorizationService" LocalServiceModule = "OpenSim.Services.AuthorizationService.dll:AuthorizationService"
[GridService]
LocalServiceModule = "OpenSim.Services.GridService.dll:GridService"
StorageProvider = "OpenSim.Data.Null.dll:NullRegionData"

View File

@ -12,9 +12,11 @@
InventoryServices = "HGInventoryBroker" InventoryServices = "HGInventoryBroker"
NeighbourServices = "LocalNeighbourServicesConnector" NeighbourServices = "LocalNeighbourServicesConnector"
AuthorizationServices = "LocalAuthorizationServicesConnector" AuthorizationServices = "LocalAuthorizationServicesConnector"
GridServices = "HGGridServicesConnector"
InventoryServiceInConnector = true InventoryServiceInConnector = true
AssetServiceInConnector = true AssetServiceInConnector = true
HGAuthServiceInConnector = true HGAuthServiceInConnector = true
HypergridServiceInConnector = true
[AssetService] [AssetService]
; For the AssetServiceInConnector ; For the AssetServiceInConnector
@ -39,4 +41,7 @@
; For the HGAuthServiceInConnector ; For the HGAuthServiceInConnector
LocalServiceModule = "OpenSim.Services.AuthenticationService.dll:HGAuthenticationService" LocalServiceModule = "OpenSim.Services.AuthenticationService.dll:HGAuthenticationService"
[GridService]
LocalServiceModule = "OpenSim.Services.GridService.dll:GridService"
GridServiceConnectorModule = "OpenSim.Region.CoreModules.dll:LocalGridServicesConnector"
StorageProvider = "OpenSim.Data.Null.dll:NullRegionData"

View File

@ -1205,6 +1205,7 @@
<ReferencePath>../../../bin/</ReferencePath> <ReferencePath>../../../bin/</ReferencePath>
<Reference name="System"/> <Reference name="System"/>
<Reference name="System.Xml"/> <Reference name="System.Xml"/>
<Reference name="System.Drawing"/>
<Reference name="OpenMetaverseTypes.dll"/> <Reference name="OpenMetaverseTypes.dll"/>
<Reference name="OpenMetaverse.dll"/> <Reference name="OpenMetaverse.dll"/>
<Reference name="OpenMetaverse.StructuredData.dll"/> <Reference name="OpenMetaverse.StructuredData.dll"/>
@ -3220,6 +3221,35 @@
</Files> </Files>
</Project> </Project>
<!-- Test Clients -->
<Project frameworkVersion="v3_5" name="OpenSim.Tests.Clients.GridClient" path="OpenSim/Tests/Clients/Grid" type="Exe">
<Configuration name="Debug">
<Options>
<OutputPath>../../../../bin/</OutputPath>
</Options>
</Configuration>
<Configuration name="Release">
<Options>
<OutputPath>../../../../bin/</OutputPath>
</Options>
</Configuration>
<ReferencePath>../../../../bin/</ReferencePath>
<Reference name="System"/>
<Reference name="OpenMetaverseTypes.dll"/>
<Reference name="OpenMetaverse.dll"/>
<Reference name="OpenSim.Framework"/>
<Reference name="OpenSim.Services.Interfaces" />
<Reference name="OpenSim.Services.Connectors" />
<Reference name="Nini.dll" />
<Reference name="log4net.dll"/>
<Files>
<Match pattern="*.cs" recurse="true"/>
</Files>
</Project>
<!-- Test assemblies --> <!-- Test assemblies -->
<Project frameworkVersion="v3_5" name="OpenSim.Tests.Common" path="OpenSim/Tests/Common" type="Library"> <Project frameworkVersion="v3_5" name="OpenSim.Tests.Common" path="OpenSim/Tests/Common" type="Library">
<Configuration name="Debug"> <Configuration name="Debug">
@ -3591,6 +3621,7 @@
<Match path="World/Archiver/Tests" pattern="*.cs" recurse="true" /> <Match path="World/Archiver/Tests" pattern="*.cs" recurse="true" />
<Match path="World/Serialiser/Tests" pattern="*.cs" recurse="true" /> <Match path="World/Serialiser/Tests" pattern="*.cs" recurse="true" />
<Match path="World/Terrain/Tests" pattern="*.cs" recurse="true" /> <Match path="World/Terrain/Tests" pattern="*.cs" recurse="true" />
<Match path="ServiceConnectorsOut/Grid/Tests" pattern="*.cs" recurse="true" />
</Files> </Files>
</Project> </Project>