All Framework.Communications.Clients and Framework.Communications.Services deleted, including old LoginService.

slimupdates
Diva Canto 2010-01-10 20:29:09 -08:00
parent 5cf6d6fa79
commit dc4bbf6065
17 changed files with 4 additions and 4999 deletions

View File

@ -32,7 +32,6 @@ using log4net;
using OpenSim.Data;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Communications.Services;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Communications.Osp;
using OpenSim.Framework.Servers;

View File

@ -1,151 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using Nwc.XmlRpc;
using OpenMetaverse;
namespace OpenSim.Framework.Communications.Clients
{
public class AuthClient
{
public static string GetNewKey(string authurl, UUID userID, UUID authToken)
{
//Hashtable keyParams = new Hashtable();
//keyParams["user_id"] = userID;
//keyParams["auth_token"] = authKey;
List<string> SendParams = new List<string>();
SendParams.Add(userID.ToString());
SendParams.Add(authToken.ToString());
XmlRpcRequest request = new XmlRpcRequest("hg_new_auth_key", SendParams);
XmlRpcResponse reply;
try
{
reply = request.Send(authurl, 6000);
}
catch (Exception e)
{
System.Console.WriteLine("[HGrid]: Failed to get new key. Reason: " + e.Message);
return string.Empty;
}
if (!reply.IsFault)
{
string newKey = string.Empty;
if (reply.Value != null)
newKey = (string)reply.Value;
return newKey;
}
else
{
System.Console.WriteLine("[HGrid]: XmlRpc request to get auth key failed with message {0}" + reply.FaultString + ", code " + reply.FaultCode);
return string.Empty;
}
}
public static bool VerifyKey(string authurl, UUID userID, string authKey)
{
List<string> SendParams = new List<string>();
SendParams.Add(userID.ToString());
SendParams.Add(authKey);
System.Console.WriteLine("[HGrid]: Verifying user key with authority " + authurl);
XmlRpcRequest request = new XmlRpcRequest("hg_verify_auth_key", SendParams);
XmlRpcResponse reply;
try
{
reply = request.Send(authurl, 10000);
}
catch (Exception e)
{
System.Console.WriteLine("[HGrid]: Failed to verify key. Reason: " + e.Message);
return false;
}
if (reply != null)
{
if (!reply.IsFault)
{
bool success = false;
if (reply.Value != null)
success = (bool)reply.Value;
return success;
}
else
{
System.Console.WriteLine("[HGrid]: XmlRpc request to verify key failed with message {0}" + reply.FaultString + ", code " + reply.FaultCode);
return false;
}
}
else
{
System.Console.WriteLine("[HGrid]: XmlRpc request to verify key returned null reply");
return false;
}
}
public static bool VerifySession(string authurl, UUID userID, UUID sessionID)
{
Hashtable requestData = new Hashtable();
requestData["avatar_uuid"] = userID.ToString();
requestData["session_id"] = sessionID.ToString();
ArrayList SendParams = new ArrayList();
SendParams.Add(requestData);
XmlRpcRequest UserReq = new XmlRpcRequest("check_auth_session", SendParams);
XmlRpcResponse UserResp = null;
try
{
UserResp = UserReq.Send(authurl, 3000);
}
catch (Exception e)
{
System.Console.WriteLine("[Session Auth]: VerifySession XmlRpc: " + e.Message);
return false;
}
Hashtable responseData = (Hashtable)UserResp.Value;
if (responseData != null && responseData.ContainsKey("auth_session") && responseData["auth_session"] != null && responseData["auth_session"].ToString() == "TRUE")
{
//System.Console.WriteLine("[Authorization]: userserver reported authorized session for user " + userID);
return true;
}
else
{
//System.Console.WriteLine("[Authorization]: userserver reported unauthorized session for user " + userID);
return false;
}
}
}
}

View File

@ -1,389 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using log4net;
using OpenMetaverse;
using Nwc.XmlRpc;
namespace OpenSim.Framework.Communications.Clients
{
public class GridClient
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public bool RegisterRegion(
string gridServerURL, string sendKey, string receiveKey, RegionInfo regionInfo, out bool forcefulBanLines)
{
m_log.InfoFormat(
"[GRID CLIENT]: Registering region {0} with grid at {1}", regionInfo.RegionName, gridServerURL);
forcefulBanLines = true;
Hashtable GridParams = new Hashtable();
// Login / Authentication
GridParams["authkey"] = sendKey;
GridParams["recvkey"] = receiveKey;
GridParams["UUID"] = regionInfo.RegionID.ToString();
GridParams["sim_ip"] = regionInfo.ExternalHostName;
GridParams["sim_port"] = regionInfo.InternalEndPoint.Port.ToString();
GridParams["region_locx"] = regionInfo.RegionLocX.ToString();
GridParams["region_locy"] = regionInfo.RegionLocY.ToString();
GridParams["sim_name"] = regionInfo.RegionName;
GridParams["http_port"] = regionInfo.HttpPort.ToString();
GridParams["remoting_port"] = ConfigSettings.DefaultRegionRemotingPort.ToString();
GridParams["map-image-id"] = regionInfo.RegionSettings.TerrainImageID.ToString();
GridParams["originUUID"] = regionInfo.originRegionID.ToString();
GridParams["server_uri"] = regionInfo.ServerURI;
GridParams["region_secret"] = regionInfo.regionSecret;
GridParams["major_interface_version"] = VersionInfo.MajorInterfaceVersion.ToString();
GridParams["master_avatar_uuid"] = regionInfo.EstateSettings.EstateOwner.ToString();
// Package into an XMLRPC Request
ArrayList SendParams = new ArrayList();
SendParams.Add(GridParams);
// Send Request
XmlRpcRequest GridReq = new XmlRpcRequest("simulator_login", SendParams);
XmlRpcResponse GridResp;
try
{
// The timeout should always be significantly larger than the timeout for the grid server to request
// the initial status of the region before confirming registration.
GridResp = GridReq.Send(gridServerURL, 90000);
}
catch (Exception e)
{
Exception e2
= new Exception(
String.Format(
"Unable to register region with grid at {0}. Grid service not running?",
gridServerURL),
e);
throw e2;
}
Hashtable GridRespData = (Hashtable)GridResp.Value;
// Hashtable griddatahash = GridRespData;
// Process Response
if (GridRespData.ContainsKey("error"))
{
string errorstring = (string)GridRespData["error"];
Exception e = new Exception(
String.Format("Unable to connect to grid at {0}: {1}", gridServerURL, errorstring));
throw e;
}
else
{
// m_knownRegions = RequestNeighbours(regionInfo.RegionLocX, regionInfo.RegionLocY);
if (GridRespData.ContainsKey("allow_forceful_banlines"))
{
if ((string)GridRespData["allow_forceful_banlines"] != "TRUE")
{
forcefulBanLines = false;
}
}
}
return true;
}
public bool DeregisterRegion(string gridServerURL, string sendKey, string receiveKey, RegionInfo regionInfo, out string errorMsg)
{
errorMsg = "";
Hashtable GridParams = new Hashtable();
GridParams["UUID"] = regionInfo.RegionID.ToString();
// Package into an XMLRPC Request
ArrayList SendParams = new ArrayList();
SendParams.Add(GridParams);
// Send Request
XmlRpcRequest GridReq = new XmlRpcRequest("simulator_after_region_moved", SendParams);
XmlRpcResponse GridResp = null;
try
{
GridResp = GridReq.Send(gridServerURL, 10000);
}
catch (Exception e)
{
Exception e2
= new Exception(
String.Format(
"Unable to deregister region with grid at {0}. Grid service not running?",
gridServerURL),
e);
throw e2;
}
Hashtable GridRespData = (Hashtable)GridResp.Value;
// Hashtable griddatahash = GridRespData;
// Process Response
if (GridRespData != null && GridRespData.ContainsKey("error"))
{
errorMsg = (string)GridRespData["error"];
return false;
}
return true;
}
public bool RequestNeighborInfo(
string gridServerURL, string sendKey, string receiveKey, UUID regionUUID,
out RegionInfo regionInfo, out string errorMsg)
{
// didn't find it so far, we have to go the long way
regionInfo = null;
errorMsg = string.Empty;
Hashtable requestData = new Hashtable();
requestData["region_UUID"] = regionUUID.ToString();
requestData["authkey"] = sendKey;
ArrayList SendParams = new ArrayList();
SendParams.Add(requestData);
XmlRpcRequest gridReq = new XmlRpcRequest("simulator_data_request", SendParams);
XmlRpcResponse gridResp = null;
try
{
gridResp = gridReq.Send(gridServerURL, 3000);
}
catch (Exception e)
{
errorMsg = e.Message;
return false;
}
Hashtable responseData = (Hashtable)gridResp.Value;
if (responseData.ContainsKey("error"))
{
errorMsg = (string)responseData["error"];
return false; ;
}
regionInfo = BuildRegionInfo(responseData, String.Empty);
return true;
}
public bool RequestNeighborInfo(
string gridServerURL, string sendKey, string receiveKey, ulong regionHandle,
out RegionInfo regionInfo, out string errorMsg)
{
// didn't find it so far, we have to go the long way
regionInfo = null;
errorMsg = string.Empty;
try
{
Hashtable requestData = new Hashtable();
requestData["region_handle"] = regionHandle.ToString();
requestData["authkey"] = sendKey;
ArrayList SendParams = new ArrayList();
SendParams.Add(requestData);
XmlRpcRequest GridReq = new XmlRpcRequest("simulator_data_request", SendParams);
XmlRpcResponse GridResp = GridReq.Send(gridServerURL, 3000);
Hashtable responseData = (Hashtable)GridResp.Value;
if (responseData.ContainsKey("error"))
{
errorMsg = (string)responseData["error"];
return false;
}
uint regX = Convert.ToUInt32((string)responseData["region_locx"]);
uint regY = Convert.ToUInt32((string)responseData["region_locy"]);
string externalHostName = (string)responseData["sim_ip"];
uint simPort = Convert.ToUInt32(responseData["sim_port"]);
string regionName = (string)responseData["region_name"];
UUID regionID = new UUID((string)responseData["region_UUID"]);
uint remotingPort = Convert.ToUInt32((string)responseData["remoting_port"]);
uint httpPort = 9000;
if (responseData.ContainsKey("http_port"))
{
httpPort = Convert.ToUInt32((string)responseData["http_port"]);
}
// Ok, so this is definitively the wrong place to do this, way too hard coded, but it doesn't seem we GET this info?
string simURI = "http://" + externalHostName + ":" + simPort;
// string externalUri = (string) responseData["sim_uri"];
//IPEndPoint neighbourInternalEndPoint = new IPEndPoint(IPAddress.Parse(internalIpStr), (int) port);
regionInfo = RegionInfo.Create(regionID, regionName, regX, regY, externalHostName, httpPort, simPort, remotingPort, simURI);
}
catch (Exception e)
{
errorMsg = e.Message;
return false;
}
return true;
}
public bool RequestClosestRegion(
string gridServerURL, string sendKey, string receiveKey, string regionName,
out RegionInfo regionInfo, out string errorMsg)
{
regionInfo = null;
errorMsg = string.Empty;
try
{
Hashtable requestData = new Hashtable();
requestData["region_name_search"] = regionName;
requestData["authkey"] = sendKey;
ArrayList SendParams = new ArrayList();
SendParams.Add(requestData);
XmlRpcRequest GridReq = new XmlRpcRequest("simulator_data_request", SendParams);
XmlRpcResponse GridResp = GridReq.Send(gridServerURL, 3000);
Hashtable responseData = (Hashtable)GridResp.Value;
if (responseData.ContainsKey("error"))
{
errorMsg = (string)responseData["error"];
return false;
}
regionInfo = BuildRegionInfo(responseData, "");
}
catch (Exception e)
{
errorMsg = e.Message;
return false;
}
return true;
}
/// <summary>
/// Performs a XML-RPC query against the grid server returning mapblock information in the specified coordinates
/// </summary>
/// <remarks>REDUNDANT - OGS1 is to be phased out in favour of OGS2</remarks>
/// <param name="minX">Minimum X value</param>
/// <param name="minY">Minimum Y value</param>
/// <param name="maxX">Maximum X value</param>
/// <param name="maxY">Maximum Y value</param>
/// <returns>Hashtable of hashtables containing map data elements</returns>
public bool MapBlockQuery(
string gridServerURL, int minX, int minY, int maxX, int maxY, out Hashtable respData, out string errorMsg)
{
respData = new Hashtable();
errorMsg = string.Empty;
Hashtable param = new Hashtable();
param["xmin"] = minX;
param["ymin"] = minY;
param["xmax"] = maxX;
param["ymax"] = maxY;
IList parameters = new ArrayList();
parameters.Add(param);
try
{
XmlRpcRequest req = new XmlRpcRequest("map_block", parameters);
XmlRpcResponse resp = req.Send(gridServerURL, 10000);
respData = (Hashtable)resp.Value;
return true;
}
catch (Exception e)
{
errorMsg = e.Message;
return false;
}
}
public bool SearchRegionByName(string gridServerURL, IList parameters, out Hashtable respData, out string errorMsg)
{
respData = null;
errorMsg = string.Empty;
try
{
XmlRpcRequest request = new XmlRpcRequest("search_for_region_by_name", parameters);
XmlRpcResponse resp = request.Send(gridServerURL, 10000);
respData = (Hashtable)resp.Value;
if (respData != null && respData.Contains("faultCode"))
{
errorMsg = (string)respData["faultString"];
return false;
}
return true;
}
catch (Exception e)
{
errorMsg = e.Message;
return false;
}
}
public RegionInfo BuildRegionInfo(Hashtable responseData, string prefix)
{
uint regX = Convert.ToUInt32((string)responseData[prefix + "region_locx"]);
uint regY = Convert.ToUInt32((string)responseData[prefix + "region_locy"]);
string internalIpStr = (string)responseData[prefix + "sim_ip"];
uint port = Convert.ToUInt32(responseData[prefix + "sim_port"]);
IPEndPoint neighbourInternalEndPoint = new IPEndPoint(Util.GetHostFromDNS(internalIpStr), (int)port);
RegionInfo regionInfo = new RegionInfo(regX, regY, neighbourInternalEndPoint, internalIpStr);
regionInfo.RemotingPort = Convert.ToUInt32((string)responseData[prefix + "remoting_port"]);
regionInfo.RemotingAddress = internalIpStr;
if (responseData.ContainsKey(prefix + "http_port"))
{
regionInfo.HttpPort = Convert.ToUInt32((string)responseData[prefix + "http_port"]);
}
regionInfo.RegionID = new UUID((string)responseData[prefix + "region_UUID"]);
regionInfo.RegionName = (string)responseData[prefix + "region_name"];
regionInfo.RegionSettings.TerrainImageID = new UUID((string)responseData[prefix + "map_UUID"]);
return regionInfo;
}
}
}

View File

@ -1,79 +0,0 @@
/**
* Copyright (c), Contributors. All rights reserved.
* 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 Organizations nor the names of Individual
* Contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
using System;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenMetaverse;
namespace OpenSim.Framework.Communications.Clients
{
public class InventoryClient
{
private string ServerURL;
public InventoryClient(string url)
{
ServerURL = url;
}
public void GetInventoryItemAsync(InventoryItemBase item, ReturnResponse<InventoryItemBase> callBack)
{
System.Console.WriteLine("[HGrid] GetInventory from " + ServerURL);
try
{
RestSessionObjectPosterResponse<InventoryItemBase, InventoryItemBase> requester
= new RestSessionObjectPosterResponse<InventoryItemBase, InventoryItemBase>();
requester.ResponseCallback = callBack;
requester.BeginPostObject(ServerURL + "/GetItem/", item, string.Empty, string.Empty);
}
catch (Exception e)
{
System.Console.WriteLine("[HGrid]: Exception posting to inventory: " + e);
}
}
public InventoryItemBase GetInventoryItem(InventoryItemBase item)
{
System.Console.WriteLine("[HGrid] GetInventory " + item.ID + " from " + ServerURL);
try
{
item = SynchronousRestSessionObjectPoster<Guid, InventoryItemBase>.BeginPostObject("POST", ServerURL + "/GetItem/", item.ID.Guid, "", "");
return item;
}
catch (Exception e)
{
System.Console.WriteLine("[HGrid]: Exception posting to inventory: " + e);
}
return null;
}
}
}

View File

@ -1,755 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using log4net;
namespace OpenSim.Framework.Communications.Clients
{
public class RegionClient
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public bool DoCreateChildAgentCall(GridRegion region, AgentCircuitData aCircuit, string authKey, uint teleportFlags, out string reason)
{
reason = String.Empty;
// Eventually, we want to use a caps url instead of the agentID
string uri = string.Empty;
try
{
uri = "http://" + region.ExternalEndPoint.Address + ":" + region.HttpPort + "/agent/" + aCircuit.AgentID + "/";
}
catch (Exception e)
{
m_log.Debug("[REST COMMS]: Unable to resolve external endpoint on agent create. Reason: " + e.Message);
reason = e.Message;
return false;
}
//Console.WriteLine(" >>> DoCreateChildAgentCall <<< " + uri);
HttpWebRequest AgentCreateRequest = (HttpWebRequest)WebRequest.Create(uri);
AgentCreateRequest.Method = "POST";
AgentCreateRequest.ContentType = "application/json";
AgentCreateRequest.Timeout = 10000;
//AgentCreateRequest.KeepAlive = false;
AgentCreateRequest.Headers.Add("Authorization", authKey);
// Fill it in
OSDMap args = null;
try
{
args = aCircuit.PackAgentCircuitData();
}
catch (Exception e)
{
m_log.Debug("[REST COMMS]: PackAgentCircuitData failed with exception: " + e.Message);
}
// Add the regionhandle of the destination region
ulong regionHandle = GetRegionHandle(region.RegionHandle);
args["destination_handle"] = OSD.FromString(regionHandle.ToString());
args["teleport_flags"] = OSD.FromString(teleportFlags.ToString());
string strBuffer = "";
byte[] buffer = new byte[1];
try
{
strBuffer = OSDParser.SerializeJsonString(args);
Encoding str = Util.UTF8;
buffer = str.GetBytes(strBuffer);
}
catch (Exception e)
{
m_log.WarnFormat("[REST COMMS]: Exception thrown on serialization of ChildCreate: {0}", e.Message);
// ignore. buffer will be empty, caller should check.
}
Stream os = null;
try
{ // send the Post
AgentCreateRequest.ContentLength = buffer.Length; //Count bytes to send
os = AgentCreateRequest.GetRequestStream();
os.Write(buffer, 0, strBuffer.Length); //Send it
//m_log.InfoFormat("[REST COMMS]: Posted CreateChildAgent request to remote sim {0}", uri);
}
//catch (WebException ex)
catch
{
//m_log.InfoFormat("[REST COMMS]: Bad send on ChildAgentUpdate {0}", ex.Message);
reason = "cannot contact remote region";
return false;
}
finally
{
if (os != null)
os.Close();
}
// Let's wait for the response
//m_log.Info("[REST COMMS]: Waiting for a reply after DoCreateChildAgentCall");
WebResponse webResponse = null;
StreamReader sr = null;
try
{
webResponse = AgentCreateRequest.GetResponse();
if (webResponse == null)
{
m_log.Info("[REST COMMS]: Null reply on DoCreateChildAgentCall post");
}
else
{
sr = new StreamReader(webResponse.GetResponseStream());
string response = sr.ReadToEnd().Trim();
m_log.InfoFormat("[REST COMMS]: DoCreateChildAgentCall reply was {0} ", response);
if (!String.IsNullOrEmpty(response))
{
try
{
// we assume we got an OSDMap back
OSDMap r = GetOSDMap(response);
bool success = r["success"].AsBoolean();
reason = r["reason"].AsString();
return success;
}
catch (NullReferenceException e)
{
m_log.InfoFormat("[REST COMMS]: exception on reply of DoCreateChildAgentCall {0}", e.Message);
// check for old style response
if (response.ToLower().StartsWith("true"))
return true;
return false;
}
}
}
}
catch (WebException ex)
{
m_log.InfoFormat("[REST COMMS]: exception on reply of DoCreateChildAgentCall {0}", ex.Message);
// ignore, really
}
finally
{
if (sr != null)
sr.Close();
}
return true;
}
public bool DoChildAgentUpdateCall(GridRegion region, IAgentData cAgentData)
{
// Eventually, we want to use a caps url instead of the agentID
string uri = string.Empty;
try
{
uri = "http://" + region.ExternalEndPoint.Address + ":" + region.HttpPort + "/agent/" + cAgentData.AgentID + "/";
}
catch (Exception e)
{
m_log.Debug("[REST COMMS]: Unable to resolve external endpoint on agent update. Reason: " + e.Message);
return false;
}
//Console.WriteLine(" >>> DoChildAgentUpdateCall <<< " + uri);
HttpWebRequest ChildUpdateRequest = (HttpWebRequest)WebRequest.Create(uri);
ChildUpdateRequest.Method = "PUT";
ChildUpdateRequest.ContentType = "application/json";
ChildUpdateRequest.Timeout = 10000;
//ChildUpdateRequest.KeepAlive = false;
// Fill it in
OSDMap args = null;
try
{
args = cAgentData.Pack();
}
catch (Exception e)
{
m_log.Debug("[REST COMMS]: PackUpdateMessage failed with exception: " + e.Message);
}
// Add the regionhandle of the destination region
ulong regionHandle = GetRegionHandle(region.RegionHandle);
args["destination_handle"] = OSD.FromString(regionHandle.ToString());
string strBuffer = "";
byte[] buffer = new byte[1];
try
{
strBuffer = OSDParser.SerializeJsonString(args);
Encoding str = Util.UTF8;
buffer = str.GetBytes(strBuffer);
}
catch (Exception e)
{
m_log.WarnFormat("[REST COMMS]: Exception thrown on serialization of ChildUpdate: {0}", e.Message);
// ignore. buffer will be empty, caller should check.
}
Stream os = null;
try
{ // send the Post
ChildUpdateRequest.ContentLength = buffer.Length; //Count bytes to send
os = ChildUpdateRequest.GetRequestStream();
os.Write(buffer, 0, strBuffer.Length); //Send it
//m_log.InfoFormat("[REST COMMS]: Posted ChildAgentUpdate request to remote sim {0}", uri);
}
//catch (WebException ex)
catch
{
//m_log.InfoFormat("[REST COMMS]: Bad send on ChildAgentUpdate {0}", ex.Message);
return false;
}
finally
{
if (os != null)
os.Close();
}
// Let's wait for the response
//m_log.Info("[REST COMMS]: Waiting for a reply after ChildAgentUpdate");
WebResponse webResponse = null;
StreamReader sr = null;
try
{
webResponse = ChildUpdateRequest.GetResponse();
if (webResponse == null)
{
m_log.Info("[REST COMMS]: Null reply on ChilAgentUpdate post");
}
sr = new StreamReader(webResponse.GetResponseStream());
//reply = sr.ReadToEnd().Trim();
sr.ReadToEnd().Trim();
sr.Close();
//m_log.InfoFormat("[REST COMMS]: ChilAgentUpdate reply was {0} ", reply);
}
catch (WebException ex)
{
m_log.InfoFormat("[REST COMMS]: exception on reply of ChilAgentUpdate {0}", ex.Message);
// ignore, really
}
finally
{
if (sr != null)
sr.Close();
}
return true;
}
public bool DoRetrieveRootAgentCall(GridRegion region, UUID id, out IAgentData agent)
{
agent = null;
// Eventually, we want to use a caps url instead of the agentID
string uri = "http://" + region.ExternalEndPoint.Address + ":" + region.HttpPort + "/agent/" + id + "/" + region.RegionHandle.ToString() + "/";
//Console.WriteLine(" >>> DoRetrieveRootAgentCall <<< " + uri);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "GET";
request.Timeout = 10000;
//request.Headers.Add("authorization", ""); // coming soon
HttpWebResponse webResponse = null;
string reply = string.Empty;
StreamReader sr = null;
try
{
webResponse = (HttpWebResponse)request.GetResponse();
if (webResponse == null)
{
m_log.Info("[REST COMMS]: Null reply on agent get ");
}
sr = new StreamReader(webResponse.GetResponseStream());
reply = sr.ReadToEnd().Trim();
//Console.WriteLine("[REST COMMS]: ChilAgentUpdate reply was " + reply);
}
catch (WebException ex)
{
m_log.InfoFormat("[REST COMMS]: exception on reply of agent get {0}", ex.Message);
// ignore, really
return false;
}
finally
{
if (sr != null)
sr.Close();
}
if (webResponse.StatusCode == HttpStatusCode.OK)
{
// we know it's jason
OSDMap args = GetOSDMap(reply);
if (args == null)
{
//Console.WriteLine("[REST COMMS]: Error getting OSDMap from reply");
return false;
}
agent = new CompleteAgentData();
agent.Unpack(args);
return true;
}
//Console.WriteLine("[REST COMMS]: DoRetrieveRootAgentCall returned status " + webResponse.StatusCode);
return false;
}
public bool DoReleaseAgentCall(ulong regionHandle, UUID id, string uri)
{
//m_log.Debug(" >>> DoReleaseAgentCall <<< " + uri);
WebRequest request = WebRequest.Create(uri);
request.Method = "DELETE";
request.Timeout = 10000;
StreamReader sr = null;
try
{
WebResponse webResponse = request.GetResponse();
if (webResponse == null)
{
m_log.Info("[REST COMMS]: Null reply on agent delete ");
}
sr = new StreamReader(webResponse.GetResponseStream());
//reply = sr.ReadToEnd().Trim();
sr.ReadToEnd().Trim();
sr.Close();
//m_log.InfoFormat("[REST COMMS]: ChilAgentUpdate reply was {0} ", reply);
}
catch (WebException ex)
{
m_log.InfoFormat("[REST COMMS]: exception on reply of agent delete {0}", ex.Message);
// ignore, really
}
finally
{
if (sr != null)
sr.Close();
}
return true;
}
public bool DoCloseAgentCall(GridRegion region, UUID id)
{
string uri = string.Empty;
try
{
uri = "http://" + region.ExternalEndPoint.Address + ":" + region.HttpPort + "/agent/" + id + "/" + region.RegionHandle.ToString() + "/";
}
catch (Exception e)
{
m_log.Debug("[REST COMMS]: Unable to resolve external endpoint on agent close. Reason: " + e.Message);
return false;
}
//Console.WriteLine(" >>> DoCloseAgentCall <<< " + uri);
WebRequest request = WebRequest.Create(uri);
request.Method = "DELETE";
request.Timeout = 10000;
StreamReader sr = null;
try
{
WebResponse webResponse = request.GetResponse();
if (webResponse == null)
{
m_log.Info("[REST COMMS]: Null reply on agent delete ");
}
sr = new StreamReader(webResponse.GetResponseStream());
//reply = sr.ReadToEnd().Trim();
sr.ReadToEnd().Trim();
sr.Close();
//m_log.InfoFormat("[REST COMMS]: ChilAgentUpdate reply was {0} ", reply);
}
catch (WebException ex)
{
m_log.InfoFormat("[REST COMMS]: exception on reply of agent delete {0}", ex.Message);
// ignore, really
}
finally
{
if (sr != null)
sr.Close();
}
return true;
}
public bool DoCreateObjectCall(GridRegion region, ISceneObject sog, string sogXml2, bool allowScriptCrossing)
{
ulong regionHandle = GetRegionHandle(region.RegionHandle);
string uri
= "http://" + region.ExternalEndPoint.Address + ":" + region.HttpPort
+ "/object/" + sog.UUID + "/" + regionHandle.ToString() + "/";
//m_log.Debug(" >>> DoCreateChildAgentCall <<< " + uri);
WebRequest ObjectCreateRequest = WebRequest.Create(uri);
ObjectCreateRequest.Method = "POST";
ObjectCreateRequest.ContentType = "application/json";
ObjectCreateRequest.Timeout = 10000;
OSDMap args = new OSDMap(2);
args["sog"] = OSD.FromString(sogXml2);
args["extra"] = OSD.FromString(sog.ExtraToXmlString());
if (allowScriptCrossing)
{
string state = sog.GetStateSnapshot();
if (state.Length > 0)
args["state"] = OSD.FromString(state);
}
string strBuffer = "";
byte[] buffer = new byte[1];
try
{
strBuffer = OSDParser.SerializeJsonString(args);
Encoding str = Util.UTF8;
buffer = str.GetBytes(strBuffer);
}
catch (Exception e)
{
m_log.WarnFormat("[REST COMMS]: Exception thrown on serialization of CreateObject: {0}", e.Message);
// ignore. buffer will be empty, caller should check.
}
Stream os = null;
try
{ // send the Post
ObjectCreateRequest.ContentLength = buffer.Length; //Count bytes to send
os = ObjectCreateRequest.GetRequestStream();
os.Write(buffer, 0, strBuffer.Length); //Send it
m_log.InfoFormat("[REST COMMS]: Posted ChildAgentUpdate request to remote sim {0}", uri);
}
//catch (WebException ex)
catch
{
// m_log.InfoFormat("[REST COMMS]: Bad send on CreateObject {0}", ex.Message);
return false;
}
finally
{
if (os != null)
os.Close();
}
// Let's wait for the response
//m_log.Info("[REST COMMS]: Waiting for a reply after DoCreateChildAgentCall");
StreamReader sr = null;
try
{
WebResponse webResponse = ObjectCreateRequest.GetResponse();
if (webResponse == null)
{
m_log.Info("[REST COMMS]: Null reply on DoCreateObjectCall post");
}
sr = new StreamReader(webResponse.GetResponseStream());
//reply = sr.ReadToEnd().Trim();
sr.ReadToEnd().Trim();
//m_log.InfoFormat("[REST COMMS]: DoCreateChildAgentCall reply was {0} ", reply);
}
catch (WebException ex)
{
m_log.InfoFormat("[REST COMMS]: exception on reply of DoCreateObjectCall {0}", ex.Message);
// ignore, really
}
finally
{
if (sr != null)
sr.Close();
}
return true;
}
public bool DoCreateObjectCall(GridRegion region, UUID userID, UUID itemID)
{
ulong regionHandle = GetRegionHandle(region.RegionHandle);
string uri = "http://" + region.ExternalEndPoint.Address + ":" + region.HttpPort + "/object/" + UUID.Zero + "/" + regionHandle.ToString() + "/";
//m_log.Debug(" >>> DoCreateChildAgentCall <<< " + uri);
WebRequest ObjectCreateRequest = WebRequest.Create(uri);
ObjectCreateRequest.Method = "PUT";
ObjectCreateRequest.ContentType = "application/json";
ObjectCreateRequest.Timeout = 10000;
OSDMap args = new OSDMap(2);
args["userid"] = OSD.FromUUID(userID);
args["itemid"] = OSD.FromUUID(itemID);
string strBuffer = "";
byte[] buffer = new byte[1];
try
{
strBuffer = OSDParser.SerializeJsonString(args);
Encoding str = Util.UTF8;
buffer = str.GetBytes(strBuffer);
}
catch (Exception e)
{
m_log.WarnFormat("[REST COMMS]: Exception thrown on serialization of CreateObject: {0}", e.Message);
// ignore. buffer will be empty, caller should check.
}
Stream os = null;
try
{ // send the Post
ObjectCreateRequest.ContentLength = buffer.Length; //Count bytes to send
os = ObjectCreateRequest.GetRequestStream();
os.Write(buffer, 0, strBuffer.Length); //Send it
//m_log.InfoFormat("[REST COMMS]: Posted CreateObject request to remote sim {0}", uri);
}
//catch (WebException ex)
catch
{
// m_log.InfoFormat("[REST COMMS]: Bad send on CreateObject {0}", ex.Message);
return false;
}
finally
{
if (os != null)
os.Close();
}
// Let's wait for the response
//m_log.Info("[REST COMMS]: Waiting for a reply after DoCreateChildAgentCall");
StreamReader sr = null;
try
{
WebResponse webResponse = ObjectCreateRequest.GetResponse();
if (webResponse == null)
{
m_log.Info("[REST COMMS]: Null reply on DoCreateObjectCall post");
}
sr = new StreamReader(webResponse.GetResponseStream());
sr.ReadToEnd().Trim();
sr.ReadToEnd().Trim();
//m_log.InfoFormat("[REST COMMS]: DoCreateChildAgentCall reply was {0} ", reply);
}
catch (WebException ex)
{
m_log.InfoFormat("[REST COMMS]: exception on reply of DoCreateObjectCall {0}", ex.Message);
// ignore, really
}
finally
{
if (sr != null)
sr.Close();
}
return true;
}
public bool DoHelloNeighbourCall(RegionInfo region, RegionInfo thisRegion)
{
string uri = "http://" + region.ExternalEndPoint.Address + ":" + region.HttpPort + "/region/" + thisRegion.RegionID + "/";
//m_log.Debug(" >>> DoHelloNeighbourCall <<< " + uri);
WebRequest HelloNeighbourRequest = WebRequest.Create(uri);
HelloNeighbourRequest.Method = "POST";
HelloNeighbourRequest.ContentType = "application/json";
HelloNeighbourRequest.Timeout = 10000;
// Fill it in
OSDMap args = null;
try
{
args = thisRegion.PackRegionInfoData();
}
catch (Exception e)
{
m_log.Debug("[REST COMMS]: PackRegionInfoData failed with exception: " + e.Message);
}
// Add the regionhandle of the destination region
ulong regionHandle = GetRegionHandle(region.RegionHandle);
args["destination_handle"] = OSD.FromString(regionHandle.ToString());
string strBuffer = "";
byte[] buffer = new byte[1];
try
{
strBuffer = OSDParser.SerializeJsonString(args);
Encoding str = Util.UTF8;
buffer = str.GetBytes(strBuffer);
}
catch (Exception e)
{
m_log.WarnFormat("[REST COMMS]: Exception thrown on serialization of HelloNeighbour: {0}", e.Message);
// ignore. buffer will be empty, caller should check.
}
Stream os = null;
try
{ // send the Post
HelloNeighbourRequest.ContentLength = buffer.Length; //Count bytes to send
os = HelloNeighbourRequest.GetRequestStream();
os.Write(buffer, 0, strBuffer.Length); //Send it
//m_log.InfoFormat("[REST COMMS]: Posted HelloNeighbour request to remote sim {0}", uri);
}
//catch (WebException ex)
catch
{
//m_log.InfoFormat("[REST COMMS]: Bad send on HelloNeighbour {0}", ex.Message);
return false;
}
finally
{
if (os != null)
os.Close();
}
// Let's wait for the response
//m_log.Info("[REST COMMS]: Waiting for a reply after DoHelloNeighbourCall");
StreamReader sr = null;
try
{
WebResponse webResponse = HelloNeighbourRequest.GetResponse();
if (webResponse == null)
{
m_log.Info("[REST COMMS]: Null reply on DoHelloNeighbourCall post");
}
sr = new StreamReader(webResponse.GetResponseStream());
//reply = sr.ReadToEnd().Trim();
sr.ReadToEnd().Trim();
//m_log.InfoFormat("[REST COMMS]: DoHelloNeighbourCall reply was {0} ", reply);
}
catch (WebException ex)
{
m_log.InfoFormat("[REST COMMS]: exception on reply of DoHelloNeighbourCall {0}", ex.Message);
// ignore, really
}
finally
{
if (sr != null)
sr.Close();
}
return true;
}
#region Hyperlinks
public virtual ulong GetRegionHandle(ulong handle)
{
return handle;
}
public virtual bool IsHyperlink(ulong handle)
{
return false;
}
public virtual void SendUserInformation(GridRegion regInfo, AgentCircuitData aCircuit)
{
}
public virtual void AdjustUserInformation(AgentCircuitData aCircuit)
{
}
#endregion /* Hyperlinks */
public static OSDMap GetOSDMap(string data)
{
OSDMap args = null;
try
{
OSD buffer;
// We should pay attention to the content-type, but let's assume we know it's Json
buffer = OSDParser.DeserializeJson(data);
if (buffer.Type == OSDType.Map)
{
args = (OSDMap)buffer;
return args;
}
else
{
// uh?
System.Console.WriteLine("[REST COMMS]: Got OSD of type " + buffer.Type.ToString());
return null;
}
}
catch (Exception ex)
{
System.Console.WriteLine("[REST COMMS]: exception on parse of REST message " + ex.Message);
return null;
}
}
}
}

View File

@ -1,339 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using System.Text.RegularExpressions;
using OpenSim.Framework;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Capabilities;
using OpenSim.Framework.Servers;
using OpenMetaverse;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
namespace OpenSim.Framework.Communications.Services
{
public class HGLoginAuthService : LoginService
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected NetworkServersInfo m_serversInfo;
protected bool m_authUsers = false;
/// <summary>
/// Used by the login service to make requests to the inventory service.
/// </summary>
protected IInterServiceInventoryServices m_interServiceInventoryService;
/// <summary>
/// Used to make requests to the local regions.
/// </summary>
protected ILoginServiceToRegionsConnector m_regionsConnector;
public HGLoginAuthService(
UserManagerBase userManager, string welcomeMess,
IInterServiceInventoryServices interServiceInventoryService,
NetworkServersInfo serversInfo,
bool authenticate, LibraryRootFolder libraryRootFolder, ILoginServiceToRegionsConnector regionsConnector)
: base(userManager, libraryRootFolder, welcomeMess)
{
this.m_serversInfo = serversInfo;
if (m_serversInfo != null)
{
m_defaultHomeX = this.m_serversInfo.DefaultHomeLocX;
m_defaultHomeY = this.m_serversInfo.DefaultHomeLocY;
}
m_authUsers = authenticate;
m_interServiceInventoryService = interServiceInventoryService;
m_regionsConnector = regionsConnector;
m_interInventoryService = interServiceInventoryService;
}
public void SetServersInfo(NetworkServersInfo sinfo)
{
m_serversInfo = sinfo;
}
public override XmlRpcResponse XmlRpcLoginMethod(XmlRpcRequest request, IPEndPoint remoteClient)
{
m_log.Info("[HGLOGIN]: HGLogin called " + request.MethodName);
XmlRpcResponse response = base.XmlRpcLoginMethod(request, remoteClient);
Hashtable responseData = (Hashtable)response.Value;
responseData["grid_service"] = m_serversInfo.GridURL;
responseData["grid_service_send_key"] = m_serversInfo.GridSendKey;
responseData["inventory_service"] = m_serversInfo.InventoryURL;
responseData["asset_service"] = m_serversInfo.AssetURL;
responseData["asset_service_send_key"] = m_serversInfo.AssetSendKey;
int x = (Int32)responseData["region_x"];
int y = (Int32)responseData["region_y"];
uint ux = (uint)(x / Constants.RegionSize);
uint uy = (uint)(y / Constants.RegionSize);
ulong regionHandle = Util.UIntsToLong(ux, uy);
responseData["region_handle"] = regionHandle.ToString();
// Let's remove the seed cap from the login
//responseData.Remove("seed_capability");
// Let's add the appearance
UUID userID = UUID.Zero;
UUID.TryParse((string)responseData["agent_id"], out userID);
AvatarAppearance appearance = m_userManager.GetUserAppearance(userID);
if (appearance == null)
{
m_log.WarnFormat("[INTER]: Appearance not found for {0}. Creating default.", userID);
appearance = new AvatarAppearance();
}
responseData["appearance"] = appearance.ToHashTable();
// Let's also send the auth token
UUID token = UUID.Random();
responseData["auth_token"] = token.ToString();
UserProfileData userProfile = m_userManager.GetUserProfile(userID);
if (userProfile != null)
{
userProfile.WebLoginKey = token;
m_userManager.CommitAgent(ref userProfile);
}
m_log.Warn("[HGLOGIN]: Auth token: " + token);
return response;
}
public XmlRpcResponse XmlRpcGenerateKeyMethod(XmlRpcRequest request, IPEndPoint remoteClient)
{
// Verify the key of who's calling
UUID userID = UUID.Zero;
UUID authKey = UUID.Zero;
UUID.TryParse((string)request.Params[0], out userID);
UUID.TryParse((string)request.Params[1], out authKey);
m_log.InfoFormat("[HGLOGIN] HGGenerateKey called with authToken ", authKey);
string newKey = string.Empty;
if (!(m_userManager is IAuthentication))
{
m_log.Debug("[HGLOGIN]: UserManager is not IAuthentication service. Returning empty key.");
}
else
{
newKey = ((IAuthentication)m_userManager).GetNewKey(m_serversInfo.UserURL, userID, authKey);
}
XmlRpcResponse response = new XmlRpcResponse();
response.Value = (string) newKey;
return response;
}
public XmlRpcResponse XmlRpcVerifyKeyMethod(XmlRpcRequest request, IPEndPoint remoteClient)
{
bool success = false;
if (request.Params.Count >= 2)
{
// Verify the key of who's calling
UUID userID = UUID.Zero;
string authKey = string.Empty;
if (UUID.TryParse((string)request.Params[0], out userID))
{
authKey = (string)request.Params[1];
m_log.InfoFormat("[HGLOGIN] HGVerifyKey called with key {0}", authKey);
if (!(m_userManager is IAuthentication))
{
m_log.Debug("[HGLOGIN]: UserManager is not IAuthentication service. Denying.");
}
else
{
success = ((IAuthentication)m_userManager).VerifyKey(userID, authKey);
}
}
}
m_log.DebugFormat("[HGLOGIN]: Response to VerifyKey is {0}", success);
XmlRpcResponse response = new XmlRpcResponse();
response.Value = success;
return response;
}
public override UserProfileData GetTheUser(string firstname, string lastname)
{
UserProfileData profile = m_userManager.GetUserProfile(firstname, lastname);
if (profile != null)
{
return profile;
}
if (!m_authUsers)
{
//no current user account so make one
m_log.Info("[LOGIN]: No user account found so creating a new one.");
m_userManager.AddUser(firstname, lastname, "test", "", m_defaultHomeX, m_defaultHomeY);
return m_userManager.GetUserProfile(firstname, lastname);
}
return null;
}
public override bool AuthenticateUser(UserProfileData profile, string password)
{
if (!m_authUsers)
{
//for now we will accept any password in sandbox mode
m_log.Info("[LOGIN]: Authorising user (no actual password check)");
return true;
}
else
{
m_log.Info(
"[LOGIN]: Authenticating " + profile.FirstName + " " + profile.SurName);
if (!password.StartsWith("$1$"))
password = "$1$" + Util.Md5Hash(password);
password = password.Remove(0, 3); //remove $1$
string s = Util.Md5Hash(password + ":" + profile.PasswordSalt);
bool loginresult = (profile.PasswordHash.Equals(s.ToString(), StringComparison.InvariantCultureIgnoreCase)
|| profile.PasswordHash.Equals(password, StringComparison.InvariantCulture));
return loginresult;
}
}
protected override RegionInfo RequestClosestRegion(string region)
{
return m_regionsConnector.RequestClosestRegion(region);
}
protected override RegionInfo GetRegionInfo(ulong homeRegionHandle)
{
return m_regionsConnector.RequestNeighbourInfo(homeRegionHandle);
}
protected override RegionInfo GetRegionInfo(UUID homeRegionId)
{
return m_regionsConnector.RequestNeighbourInfo(homeRegionId);
}
/// <summary>
/// Not really informing the region. Just filling out the response fields related to the region.
/// </summary>
/// <param name="sim"></param>
/// <param name="user"></param>
/// <param name="response"></param>
/// <returns>true if the region was successfully contacted, false otherwise</returns>
protected override bool PrepareLoginToRegion(RegionInfo regionInfo, UserProfileData user, LoginResponse response, IPEndPoint remoteClient)
{
IPEndPoint endPoint = regionInfo.ExternalEndPoint;
response.SimAddress = endPoint.Address.ToString();
response.SimPort = (uint)endPoint.Port;
response.RegionX = regionInfo.RegionLocX;
response.RegionY = regionInfo.RegionLocY;
response.SimHttpPort = regionInfo.HttpPort;
string capsPath = CapsUtil.GetRandomCapsObjectPath();
string capsSeedPath = CapsUtil.GetCapsSeedPath(capsPath);
// Don't use the following! It Fails for logging into any region not on the same port as the http server!
// Kept here so it doesn't happen again!
// response.SeedCapability = regionInfo.ServerURI + capsSeedPath;
string seedcap = "http://";
if (m_serversInfo.HttpUsesSSL)
{
// For NAT
string host = NetworkUtil.GetHostFor(remoteClient.Address, m_serversInfo.HttpSSLCN);
seedcap = "https://" + host + ":" + m_serversInfo.httpSSLPort + capsSeedPath;
}
else
{
// For NAT
string host = NetworkUtil.GetHostFor(remoteClient.Address, regionInfo.ExternalHostName);
seedcap = "http://" + host + ":" + m_serversInfo.HttpListenerPort + capsSeedPath;
}
response.SeedCapability = seedcap;
// Notify the target of an incoming user
m_log.InfoFormat(
"[LOGIN]: Telling {0} @ {1},{2} ({3}) to prepare for client connection",
regionInfo.RegionName, response.RegionX, response.RegionY, regionInfo.ServerURI);
// Update agent with target sim
user.CurrentAgent.Region = regionInfo.RegionID;
user.CurrentAgent.Handle = regionInfo.RegionHandle;
return true;
}
public override void LogOffUser(UserProfileData theUser, string message)
{
RegionInfo SimInfo;
try
{
SimInfo = this.m_regionsConnector.RequestNeighbourInfo(theUser.CurrentAgent.Handle);
if (SimInfo == null)
{
m_log.Error("[LOCAL LOGIN]: Region user was in isn't currently logged in");
return;
}
}
catch (Exception)
{
m_log.Error("[LOCAL LOGIN]: Unable to look up region to log user off");
return;
}
m_regionsConnector.LogOffUserFromGrid(SimInfo.RegionHandle, theUser.ID, theUser.CurrentAgent.SecureSessionID, "Logging you off");
}
protected override bool AllowLoginWithoutInventory()
{
return true;
}
}
}

View File

@ -1,823 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
namespace OpenSim.Framework.Communications.Services
{
/// <summary>
/// A temp class to handle login response.
/// Should make use of UserProfileManager where possible.
/// </summary>
public class LoginResponse
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Hashtable loginFlagsHash;
private Hashtable globalTexturesHash;
private Hashtable loginError;
private Hashtable uiConfigHash;
private ArrayList loginFlags;
private ArrayList globalTextures;
private ArrayList eventCategories;
private ArrayList uiConfig;
private ArrayList classifiedCategories;
private ArrayList inventoryRoot;
private ArrayList initialOutfit;
private ArrayList agentInventory;
private ArrayList inventoryLibraryOwner;
private ArrayList inventoryLibRoot;
private ArrayList inventoryLibrary;
private ArrayList activeGestures;
private UserInfo userProfile;
private UUID agentID;
private UUID sessionID;
private UUID secureSessionID;
// Login Flags
private string dst;
private string stipendSinceLogin;
private string gendered;
private string everLoggedIn;
private string login;
private uint simPort;
private uint simHttpPort;
private string simAddress;
private string agentAccess;
private string agentAccessMax;
private Int32 circuitCode;
private uint regionX;
private uint regionY;
// Login
private string firstname;
private string lastname;
// Global Textures
private string sunTexture;
private string cloudTexture;
private string moonTexture;
// Error Flags
private string errorReason;
private string errorMessage;
// Response
private XmlRpcResponse xmlRpcResponse;
// private XmlRpcResponse defaultXmlRpcResponse;
private string welcomeMessage;
private string startLocation;
private string allowFirstLife;
private string home;
private string seedCapability;
private string lookAt;
private BuddyList m_buddyList = null;
public LoginResponse()
{
loginFlags = new ArrayList();
globalTextures = new ArrayList();
eventCategories = new ArrayList();
uiConfig = new ArrayList();
classifiedCategories = new ArrayList();
loginError = new Hashtable();
uiConfigHash = new Hashtable();
// defaultXmlRpcResponse = new XmlRpcResponse();
userProfile = new UserInfo();
inventoryRoot = new ArrayList();
initialOutfit = new ArrayList();
agentInventory = new ArrayList();
inventoryLibrary = new ArrayList();
inventoryLibraryOwner = new ArrayList();
activeGestures = new ArrayList();
xmlRpcResponse = new XmlRpcResponse();
// defaultXmlRpcResponse = new XmlRpcResponse();
SetDefaultValues();
}
private void SetDefaultValues()
{
DST = TimeZone.CurrentTimeZone.IsDaylightSavingTime(DateTime.Now) ? "Y" : "N";
StipendSinceLogin = "N";
Gendered = "Y";
EverLoggedIn = "Y";
login = "false";
firstname = "Test";
lastname = "User";
agentAccess = "M";
agentAccessMax = "A";
startLocation = "last";
allowFirstLife = "Y";
SunTexture = "cce0f112-878f-4586-a2e2-a8f104bba271";
CloudTexture = "dc4b9f0b-d008-45c6-96a4-01dd947ac621";
MoonTexture = "ec4b9f0b-d008-45c6-96a4-01dd947ac621";
ErrorMessage = "You have entered an invalid name/password combination. Check Caps/lock.";
ErrorReason = "key";
welcomeMessage = "Welcome to OpenSim!";
seedCapability = String.Empty;
home = "{'region_handle':[r" + (1000*Constants.RegionSize).ToString() + ",r" + (1000*Constants.RegionSize).ToString() + "], 'position':[r" +
userProfile.homepos.X.ToString() + ",r" + userProfile.homepos.Y.ToString() + ",r" +
userProfile.homepos.Z.ToString() + "], 'look_at':[r" + userProfile.homelookat.X.ToString() + ",r" +
userProfile.homelookat.Y.ToString() + ",r" + userProfile.homelookat.Z.ToString() + "]}";
lookAt = "[r0.99949799999999999756,r0.03166859999999999814,r0]";
RegionX = (uint) 255232;
RegionY = (uint) 254976;
// Classifieds;
AddClassifiedCategory((Int32) 1, "Shopping");
AddClassifiedCategory((Int32) 2, "Land Rental");
AddClassifiedCategory((Int32) 3, "Property Rental");
AddClassifiedCategory((Int32) 4, "Special Attraction");
AddClassifiedCategory((Int32) 5, "New Products");
AddClassifiedCategory((Int32) 6, "Employment");
AddClassifiedCategory((Int32) 7, "Wanted");
AddClassifiedCategory((Int32) 8, "Service");
AddClassifiedCategory((Int32) 9, "Personal");
SessionID = UUID.Random();
SecureSessionID = UUID.Random();
AgentID = UUID.Random();
Hashtable InitialOutfitHash = new Hashtable();
InitialOutfitHash["folder_name"] = "Nightclub Female";
InitialOutfitHash["gender"] = "female";
initialOutfit.Add(InitialOutfitHash);
}
#region Login Failure Methods
public XmlRpcResponse GenerateFailureResponse(string reason, string message, string login)
{
// Overwrite any default values;
xmlRpcResponse = new XmlRpcResponse();
// Ensure Login Failed message/reason;
ErrorMessage = message;
ErrorReason = reason;
loginError["reason"] = ErrorReason;
loginError["message"] = ErrorMessage;
loginError["login"] = login;
xmlRpcResponse.Value = loginError;
return (xmlRpcResponse);
}
public OSD GenerateFailureResponseLLSD(string reason, string message, string login)
{
OSDMap map = new OSDMap();
// Ensure Login Failed message/reason;
ErrorMessage = message;
ErrorReason = reason;
map["reason"] = OSD.FromString(ErrorReason);
map["message"] = OSD.FromString(ErrorMessage);
map["login"] = OSD.FromString(login);
return map;
}
public XmlRpcResponse CreateFailedResponse()
{
return (CreateLoginFailedResponse());
}
public OSD CreateFailedResponseLLSD()
{
return CreateLoginFailedResponseLLSD();
}
public XmlRpcResponse CreateLoginFailedResponse()
{
return
(GenerateFailureResponse("key",
"Could not authenticate your avatar. Please check your username and password, and check the grid if problems persist.",
"false"));
}
public OSD CreateLoginFailedResponseLLSD()
{
return GenerateFailureResponseLLSD(
"key",
"Could not authenticate your avatar. Please check your username and password, and check the grid if problems persist.",
"false");
}
/// <summary>
/// Response to indicate that login failed because the agent's inventory was not available.
/// </summary>
/// <returns></returns>
public XmlRpcResponse CreateLoginInventoryFailedResponse()
{
return GenerateFailureResponse(
"key",
"The avatar inventory service is not responding. Please notify your login region operator.",
"false");
}
public XmlRpcResponse CreateAlreadyLoggedInResponse()
{
return
(GenerateFailureResponse("presence",
"You appear to be already logged in. " +
"If this is not the case please wait for your session to timeout. " +
"If this takes longer than a few minutes please contact the grid owner. " +
"Please wait 5 minutes if you are going to connect to a region nearby to the region you were at previously.",
"false"));
}
public OSD CreateAlreadyLoggedInResponseLLSD()
{
return GenerateFailureResponseLLSD(
"presence",
"You appear to be already logged in. " +
"If this is not the case please wait for your session to timeout. " +
"If this takes longer than a few minutes please contact the grid owner",
"false");
}
public XmlRpcResponse CreateLoginBlockedResponse()
{
return
(GenerateFailureResponse("presence",
"Logins are currently restricted. Please try again later",
"false"));
}
public OSD CreateLoginBlockedResponseLLSD()
{
return GenerateFailureResponseLLSD(
"presence",
"Logins are currently restricted. Please try again later",
"false");
}
public XmlRpcResponse CreateDeadRegionResponse()
{
return
(GenerateFailureResponse("key",
"The region you are attempting to log into is not responding. Please select another region and try again.",
"false"));
}
public OSD CreateDeadRegionResponseLLSD()
{
return GenerateFailureResponseLLSD(
"key",
"The region you are attempting to log into is not responding. Please select another region and try again.",
"false");
}
public XmlRpcResponse CreateGridErrorResponse()
{
return
(GenerateFailureResponse("key",
"Error connecting to grid. Could not percieve credentials from login XML.",
"false"));
}
public OSD CreateGridErrorResponseLLSD()
{
return GenerateFailureResponseLLSD(
"key",
"Error connecting to grid. Could not perceive credentials from login XML.",
"false");
}
#endregion
public virtual XmlRpcResponse ToXmlRpcResponse()
{
try
{
Hashtable responseData = new Hashtable();
loginFlagsHash = new Hashtable();
loginFlagsHash["daylight_savings"] = DST;
loginFlagsHash["stipend_since_login"] = StipendSinceLogin;
loginFlagsHash["gendered"] = Gendered;
loginFlagsHash["ever_logged_in"] = EverLoggedIn;
loginFlags.Add(loginFlagsHash);
responseData["first_name"] = Firstname;
responseData["last_name"] = Lastname;
responseData["agent_access"] = agentAccess;
responseData["agent_access_max"] = agentAccessMax;
globalTexturesHash = new Hashtable();
globalTexturesHash["sun_texture_id"] = SunTexture;
globalTexturesHash["cloud_texture_id"] = CloudTexture;
globalTexturesHash["moon_texture_id"] = MoonTexture;
globalTextures.Add(globalTexturesHash);
// this.eventCategories.Add(this.eventCategoriesHash);
AddToUIConfig("allow_first_life", allowFirstLife);
uiConfig.Add(uiConfigHash);
responseData["sim_port"] = (Int32) SimPort;
responseData["sim_ip"] = SimAddress;
responseData["http_port"] = (Int32)SimHttpPort;
responseData["agent_id"] = AgentID.ToString();
responseData["session_id"] = SessionID.ToString();
responseData["secure_session_id"] = SecureSessionID.ToString();
responseData["circuit_code"] = CircuitCode;
responseData["seconds_since_epoch"] = (Int32) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
responseData["login-flags"] = loginFlags;
responseData["global-textures"] = globalTextures;
responseData["seed_capability"] = seedCapability;
responseData["event_categories"] = eventCategories;
responseData["event_notifications"] = new ArrayList(); // todo
responseData["classified_categories"] = classifiedCategories;
responseData["ui-config"] = uiConfig;
if (agentInventory != null)
{
responseData["inventory-skeleton"] = agentInventory;
responseData["inventory-root"] = inventoryRoot;
}
responseData["inventory-skel-lib"] = inventoryLibrary;
responseData["inventory-lib-root"] = inventoryLibRoot;
responseData["gestures"] = activeGestures;
responseData["inventory-lib-owner"] = inventoryLibraryOwner;
responseData["initial-outfit"] = initialOutfit;
responseData["start_location"] = startLocation;
responseData["seed_capability"] = seedCapability;
responseData["home"] = home;
responseData["look_at"] = lookAt;
responseData["message"] = welcomeMessage;
responseData["region_x"] = (Int32)(RegionX * Constants.RegionSize);
responseData["region_y"] = (Int32)(RegionY * Constants.RegionSize);
if (m_buddyList != null)
{
responseData["buddy-list"] = m_buddyList.ToArray();
}
responseData["login"] = "true";
xmlRpcResponse.Value = responseData;
return (xmlRpcResponse);
}
catch (Exception e)
{
m_log.Warn("[CLIENT]: LoginResponse: Error creating XML-RPC Response: " + e.Message);
return (GenerateFailureResponse("Internal Error", "Error generating Login Response", "false"));
}
}
public OSD ToLLSDResponse()
{
try
{
OSDMap map = new OSDMap();
map["first_name"] = OSD.FromString(Firstname);
map["last_name"] = OSD.FromString(Lastname);
map["agent_access"] = OSD.FromString(agentAccess);
map["agent_access_max"] = OSD.FromString(agentAccessMax);
map["sim_port"] = OSD.FromInteger(SimPort);
map["sim_ip"] = OSD.FromString(SimAddress);
map["agent_id"] = OSD.FromUUID(AgentID);
map["session_id"] = OSD.FromUUID(SessionID);
map["secure_session_id"] = OSD.FromUUID(SecureSessionID);
map["circuit_code"] = OSD.FromInteger(CircuitCode);
map["seconds_since_epoch"] = OSD.FromInteger((int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds);
#region Login Flags
OSDMap loginFlagsLLSD = new OSDMap();
loginFlagsLLSD["daylight_savings"] = OSD.FromString(DST);
loginFlagsLLSD["stipend_since_login"] = OSD.FromString(StipendSinceLogin);
loginFlagsLLSD["gendered"] = OSD.FromString(Gendered);
loginFlagsLLSD["ever_logged_in"] = OSD.FromString(EverLoggedIn);
map["login-flags"] = WrapOSDMap(loginFlagsLLSD);
#endregion Login Flags
#region Global Textures
OSDMap globalTexturesLLSD = new OSDMap();
globalTexturesLLSD["sun_texture_id"] = OSD.FromString(SunTexture);
globalTexturesLLSD["cloud_texture_id"] = OSD.FromString(CloudTexture);
globalTexturesLLSD["moon_texture_id"] = OSD.FromString(MoonTexture);
map["global-textures"] = WrapOSDMap(globalTexturesLLSD);
#endregion Global Textures
map["seed_capability"] = OSD.FromString(seedCapability);
map["event_categories"] = ArrayListToOSDArray(eventCategories);
//map["event_notifications"] = new OSDArray(); // todo
map["classified_categories"] = ArrayListToOSDArray(classifiedCategories);
#region UI Config
OSDMap uiConfigLLSD = new OSDMap();
uiConfigLLSD["allow_first_life"] = OSD.FromString(allowFirstLife);
map["ui-config"] = WrapOSDMap(uiConfigLLSD);
#endregion UI Config
#region Inventory
map["inventory-skeleton"] = ArrayListToOSDArray(agentInventory);
map["inventory-skel-lib"] = ArrayListToOSDArray(inventoryLibrary);
map["inventory-root"] = ArrayListToOSDArray(inventoryRoot); ;
map["inventory-lib-root"] = ArrayListToOSDArray(inventoryLibRoot);
map["inventory-lib-owner"] = ArrayListToOSDArray(inventoryLibraryOwner);
#endregion Inventory
map["gestures"] = ArrayListToOSDArray(activeGestures);
map["initial-outfit"] = ArrayListToOSDArray(initialOutfit);
map["start_location"] = OSD.FromString(startLocation);
map["seed_capability"] = OSD.FromString(seedCapability);
map["home"] = OSD.FromString(home);
map["look_at"] = OSD.FromString(lookAt);
map["message"] = OSD.FromString(welcomeMessage);
map["region_x"] = OSD.FromInteger(RegionX * Constants.RegionSize);
map["region_y"] = OSD.FromInteger(RegionY * Constants.RegionSize);
if (m_buddyList != null)
{
map["buddy-list"] = ArrayListToOSDArray(m_buddyList.ToArray());
}
map["login"] = OSD.FromString("true");
return map;
}
catch (Exception e)
{
m_log.Warn("[CLIENT]: LoginResponse: Error creating LLSD Response: " + e.Message);
return GenerateFailureResponseLLSD("Internal Error", "Error generating Login Response", "false");
}
}
public OSDArray ArrayListToOSDArray(ArrayList arrlst)
{
OSDArray llsdBack = new OSDArray();
foreach (Hashtable ht in arrlst)
{
OSDMap mp = new OSDMap();
foreach (DictionaryEntry deHt in ht)
{
mp.Add((string)deHt.Key, OSDString.FromObject(deHt.Value));
}
llsdBack.Add(mp);
}
return llsdBack;
}
private static OSDArray WrapOSDMap(OSDMap wrapMe)
{
OSDArray array = new OSDArray();
array.Add(wrapMe);
return array;
}
public void SetEventCategories(string category, string value)
{
// this.eventCategoriesHash[category] = value;
//TODO
}
public void AddToUIConfig(string itemName, string item)
{
uiConfigHash[itemName] = item;
}
public void AddClassifiedCategory(Int32 ID, string categoryName)
{
Hashtable hash = new Hashtable();
hash["category_name"] = categoryName;
hash["category_id"] = ID;
classifiedCategories.Add(hash);
// this.classifiedCategoriesHash.Clear();
}
#region Properties
public string Login
{
get { return login; }
set { login = value; }
}
public string DST
{
get { return dst; }
set { dst = value; }
}
public string StipendSinceLogin
{
get { return stipendSinceLogin; }
set { stipendSinceLogin = value; }
}
public string Gendered
{
get { return gendered; }
set { gendered = value; }
}
public string EverLoggedIn
{
get { return everLoggedIn; }
set { everLoggedIn = value; }
}
public uint SimPort
{
get { return simPort; }
set { simPort = value; }
}
public uint SimHttpPort
{
get { return simHttpPort; }
set { simHttpPort = value; }
}
public string SimAddress
{
get { return simAddress; }
set { simAddress = value; }
}
public UUID AgentID
{
get { return agentID; }
set { agentID = value; }
}
public UUID SessionID
{
get { return sessionID; }
set { sessionID = value; }
}
public UUID SecureSessionID
{
get { return secureSessionID; }
set { secureSessionID = value; }
}
public Int32 CircuitCode
{
get { return circuitCode; }
set { circuitCode = value; }
}
public uint RegionX
{
get { return regionX; }
set { regionX = value; }
}
public uint RegionY
{
get { return regionY; }
set { regionY = value; }
}
public string SunTexture
{
get { return sunTexture; }
set { sunTexture = value; }
}
public string CloudTexture
{
get { return cloudTexture; }
set { cloudTexture = value; }
}
public string MoonTexture
{
get { return moonTexture; }
set { moonTexture = value; }
}
public string Firstname
{
get { return firstname; }
set { firstname = value; }
}
public string Lastname
{
get { return lastname; }
set { lastname = value; }
}
public string AgentAccess
{
get { return agentAccess; }
set { agentAccess = value; }
}
public string AgentAccessMax
{
get { return agentAccessMax; }
set { agentAccessMax = value; }
}
public string StartLocation
{
get { return startLocation; }
set { startLocation = value; }
}
public string LookAt
{
get { return lookAt; }
set { lookAt = value; }
}
public string SeedCapability
{
get { return seedCapability; }
set { seedCapability = value; }
}
public string ErrorReason
{
get { return errorReason; }
set { errorReason = value; }
}
public string ErrorMessage
{
get { return errorMessage; }
set { errorMessage = value; }
}
public ArrayList InventoryRoot
{
get { return inventoryRoot; }
set { inventoryRoot = value; }
}
public ArrayList InventorySkeleton
{
get { return agentInventory; }
set { agentInventory = value; }
}
public ArrayList InventoryLibrary
{
get { return inventoryLibrary; }
set { inventoryLibrary = value; }
}
public ArrayList InventoryLibraryOwner
{
get { return inventoryLibraryOwner; }
set { inventoryLibraryOwner = value; }
}
public ArrayList InventoryLibRoot
{
get { return inventoryLibRoot; }
set { inventoryLibRoot = value; }
}
public ArrayList ActiveGestures
{
get { return activeGestures; }
set { activeGestures = value; }
}
public string Home
{
get { return home; }
set { home = value; }
}
public string Message
{
get { return welcomeMessage; }
set { welcomeMessage = value; }
}
public BuddyList BuddList
{
get { return m_buddyList; }
set { m_buddyList = value; }
}
#endregion
public class UserInfo
{
public string firstname;
public string lastname;
public ulong homeregionhandle;
public Vector3 homepos;
public Vector3 homelookat;
}
public class BuddyList
{
public List<BuddyInfo> Buddies = new List<BuddyInfo>();
public void AddNewBuddy(BuddyInfo buddy)
{
if (!Buddies.Contains(buddy))
{
Buddies.Add(buddy);
}
}
public ArrayList ToArray()
{
ArrayList buddyArray = new ArrayList();
foreach (BuddyInfo buddy in Buddies)
{
buddyArray.Add(buddy.ToHashTable());
}
return buddyArray;
}
public class BuddyInfo
{
public int BuddyRightsHave = 1;
public int BuddyRightsGiven = 1;
public UUID BuddyID;
public BuddyInfo(string buddyID)
{
BuddyID = new UUID(buddyID);
}
public BuddyInfo(UUID buddyID)
{
BuddyID = buddyID;
}
public Hashtable ToHashTable()
{
Hashtable hTable = new Hashtable();
hTable["buddy_rights_has"] = BuddyRightsHave;
hTable["buddy_rights_given"] = BuddyRightsGiven;
hTable["buddy_id"] = BuddyID.ToString();
return hTable;
}
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -36,7 +36,6 @@ using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Communications.Services;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Console;
using OpenSim.Framework.Servers;

View File

@ -1,319 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Interregion
{
public class LocalInterregionComms : ISharedRegionModule, IInterregionCommsOut, IInterregionCommsIn
{
private bool m_enabled = false;
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private List<Scene> m_sceneList = new List<Scene>();
#region Events
public event ChildAgentUpdateReceived OnChildAgentUpdate;
#endregion /* Events */
#region IRegionModule
public void Initialise(IConfigSource config)
{
if (m_sceneList.Count == 0)
{
IConfig startupConfig = config.Configs["Communications"];
if ((startupConfig != null) && (startupConfig.GetString("InterregionComms", "RESTComms") == "LocalComms"))
{
m_log.Debug("[LOCAL COMMS]: Enabling InterregionComms LocalComms module");
m_enabled = true;
}
}
}
public void PostInitialise()
{
}
public void AddRegion(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
if (m_enabled)
{
RemoveScene(scene);
}
}
public void RegionLoaded(Scene scene)
{
if (m_enabled)
{
Init(scene);
}
}
public void Close()
{
}
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "LocalInterregionCommsModule"; }
}
/// <summary>
/// Can be called from other modules.
/// </summary>
/// <param name="scene"></param>
public void RemoveScene(Scene scene)
{
lock (m_sceneList)
{
if (m_sceneList.Contains(scene))
{
m_sceneList.Remove(scene);
}
}
}
/// <summary>
/// Can be called from other modules.
/// </summary>
/// <param name="scene"></param>
public void Init(Scene scene)
{
if (!m_sceneList.Contains(scene))
{
lock (m_sceneList)
{
m_sceneList.Add(scene);
if (m_enabled)
scene.RegisterModuleInterface<IInterregionCommsOut>(this);
scene.RegisterModuleInterface<IInterregionCommsIn>(this);
}
}
}
#endregion /* IRegionModule */
#region IInterregionComms
/**
* Agent-related communications
*/
public bool SendCreateChildAgent(ulong regionHandle, AgentCircuitData aCircuit, uint teleportFlags, out string reason)
{
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionHandle)
{
// m_log.DebugFormat("[LOCAL COMMS]: Found region {0} to send SendCreateChildAgent", regionHandle);
return s.NewUserConnection(aCircuit, teleportFlags, out reason);
}
}
// m_log.DebugFormat("[LOCAL COMMS]: Did not find region {0} for SendCreateChildAgent", regionHandle);
uint x = 0, y = 0;
Utils.LongToUInts(regionHandle, out x, out y);
reason = "Did not find region " + x + "-" + y;
return false;
}
public bool SendChildAgentUpdate(ulong regionHandle, AgentData cAgentData)
{
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionHandle)
{
//m_log.DebugFormat(
// "[LOCAL COMMS]: Found region {0} {1} to send ChildAgentUpdate",
// s.RegionInfo.RegionName, regionHandle);
s.IncomingChildAgentDataUpdate(cAgentData);
return true;
}
}
// m_log.DebugFormat("[LOCAL COMMS]: Did not find region {0} for ChildAgentUpdate", regionHandle);
return false;
}
public bool SendChildAgentUpdate(ulong regionHandle, AgentPosition cAgentData)
{
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionHandle)
{
//m_log.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate");
s.IncomingChildAgentDataUpdate(cAgentData);
return true;
}
}
//m_log.Debug("[LOCAL COMMS]: region not found for ChildAgentUpdate");
return false;
}
public bool SendRetrieveRootAgent(ulong regionHandle, UUID id, out IAgentData agent)
{
agent = null;
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionHandle)
{
//m_log.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate");
return s.IncomingRetrieveRootAgent(id, out agent);
}
}
//m_log.Debug("[LOCAL COMMS]: region not found for ChildAgentUpdate");
return false;
}
public bool SendReleaseAgent(ulong regionHandle, UUID id, string uri)
{
//uint x, y;
//Utils.LongToUInts(regionHandle, out x, out y);
//x = x / Constants.RegionSize;
//y = y / Constants.RegionSize;
//m_log.Debug("\n >>> Local SendReleaseAgent " + x + "-" + y);
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionHandle)
{
//m_log.Debug("[LOCAL COMMS]: Found region to SendReleaseAgent");
return s.IncomingReleaseAgent(id);
}
}
//m_log.Debug("[LOCAL COMMS]: region not found in SendReleaseAgent");
return false;
}
public bool SendCloseAgent(ulong regionHandle, UUID id)
{
//uint x, y;
//Utils.LongToUInts(regionHandle, out x, out y);
//x = x / Constants.RegionSize;
//y = y / Constants.RegionSize;
//m_log.Debug("\n >>> Local SendCloseAgent " + x + "-" + y);
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionHandle)
{
//m_log.Debug("[LOCAL COMMS]: Found region to SendCloseAgent");
return s.IncomingCloseAgent(id);
}
}
//m_log.Debug("[LOCAL COMMS]: region not found in SendCloseAgent");
return false;
}
/**
* Object-related communications
*/
public bool SendCreateObject(ulong regionHandle, SceneObjectGroup sog, bool isLocalCall)
{
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionHandle)
{
//m_log.Debug("[LOCAL COMMS]: Found region to SendCreateObject");
if (isLocalCall)
{
// We need to make a local copy of the object
ISceneObject sogClone = sog.CloneForNewScene();
sogClone.SetState(sog.GetStateSnapshot(), s);
return s.IncomingCreateObject(sogClone);
}
else
{
// Use the object as it came through the wire
return s.IncomingCreateObject(sog);
}
}
}
return false;
}
public bool SendCreateObject(ulong regionHandle, UUID userID, UUID itemID)
{
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionHandle)
{
return s.IncomingCreateObject(userID, itemID);
}
}
return false;
}
#endregion /* IInterregionComms */
#region Misc
public Scene GetScene(ulong regionhandle)
{
foreach (Scene s in m_sceneList)
{
if (s.RegionInfo.RegionHandle == regionhandle)
return s;
}
// ? weird. should not happen
return m_sceneList[0];
}
public bool IsLocalRegion(ulong regionhandle)
{
foreach (Scene s in m_sceneList)
if (s.RegionInfo.RegionHandle == regionhandle)
return true;
return false;
}
#endregion
}
}

View File

@ -1,844 +0,0 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Communications.Clients;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Hypergrid;
using OpenSim.Region.Framework.Scenes.Serialization;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Interregion
{
public class RESTInterregionComms : ISharedRegionModule, IInterregionCommsOut
{
private bool initialized = false;
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected bool m_enabled = false;
protected Scene m_aScene;
// RESTInterregionComms does not care about local regions; it delegates that to the Local module
protected LocalInterregionComms m_localBackend;
protected CommunicationsManager m_commsManager;
protected RegionToRegionClient m_regionClient;
protected IHyperlinkService m_hyperlinkService;
protected bool m_safemode;
protected IPAddress m_thisIP;
#region IRegionModule
public virtual void Initialise(IConfigSource config)
{
IConfig startupConfig = config.Configs["Communications"];
if ((startupConfig == null) || ((startupConfig != null)
&& (startupConfig.GetString("InterregionComms", "RESTComms") == "RESTComms")))
{
m_log.Info("[REST COMMS]: Enabling InterregionComms RESTComms module");
m_enabled = true;
if (config.Configs["Hypergrid"] != null)
m_safemode = config.Configs["Hypergrid"].GetBoolean("safemode", false);
}
}
public virtual void PostInitialise()
{
}
public virtual void Close()
{
}
public void AddRegion(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
if (m_enabled)
{
m_localBackend.RemoveScene(scene);
scene.UnregisterModuleInterface<IInterregionCommsOut>(this);
}
}
public void RegionLoaded(Scene scene)
{
if (m_enabled)
{
if (!initialized)
{
InitOnce(scene);
initialized = true;
AddHTTPHandlers();
}
InitEach(scene);
}
}
public Type ReplaceableInterface
{
get { return null; }
}
public virtual string Name
{
get { return "RESTInterregionCommsModule"; }
}
protected virtual void InitEach(Scene scene)
{
m_localBackend.Init(scene);
scene.RegisterModuleInterface<IInterregionCommsOut>(this);
}
protected virtual void InitOnce(Scene scene)
{
m_localBackend = new LocalInterregionComms();
m_commsManager = scene.CommsManager;
m_aScene = scene;
m_hyperlinkService = m_aScene.RequestModuleInterface<IHyperlinkService>();
m_regionClient = new RegionToRegionClient(m_aScene, m_hyperlinkService);
m_thisIP = Util.GetHostFromDNS(scene.RegionInfo.ExternalHostName);
}
protected virtual void AddHTTPHandlers()
{
MainServer.Instance.AddHTTPHandler("/agent/", AgentHandler);
MainServer.Instance.AddHTTPHandler("/object/", ObjectHandler);
}
#endregion /* IRegionModule */
#region IInterregionComms
/**
* Agent-related communications
*/
public bool SendCreateChildAgent(ulong regionHandle, AgentCircuitData aCircuit, uint teleportFlags, out string reason)
{
// Try local first
if (m_localBackend.SendCreateChildAgent(regionHandle, aCircuit, teleportFlags, out reason))
return true;
// else do the remote thing
if (!m_localBackend.IsLocalRegion(regionHandle))
{
uint x = 0, y = 0;
Utils.LongToUInts(regionHandle, out x, out y);
GridRegion regInfo = m_aScene.GridService.GetRegionByPosition(UUID.Zero, (int)x, (int)y);
if (regInfo != null)
{
m_regionClient.SendUserInformation(regInfo, aCircuit);
return m_regionClient.DoCreateChildAgentCall(regInfo, aCircuit, "None", teleportFlags, out reason);
}
//else
// m_log.Warn("[REST COMMS]: Region not found " + regionHandle);
}
return false;
}
public bool SendChildAgentUpdate(ulong regionHandle, AgentData cAgentData)
{
// Try local first
if (m_localBackend.SendChildAgentUpdate(regionHandle, cAgentData))
return true;
// else do the remote thing
if (!m_localBackend.IsLocalRegion(regionHandle))
{
uint x = 0, y = 0;
Utils.LongToUInts(regionHandle, out x, out y);
GridRegion regInfo = m_aScene.GridService.GetRegionByPosition(UUID.Zero, (int)x, (int)y);
if (regInfo != null)
{
return m_regionClient.DoChildAgentUpdateCall(regInfo, cAgentData);
}
//else
// m_log.Warn("[REST COMMS]: Region not found " + regionHandle);
}
return false;
}
public bool SendChildAgentUpdate(ulong regionHandle, AgentPosition cAgentData)
{
// Try local first
if (m_localBackend.SendChildAgentUpdate(regionHandle, cAgentData))
return true;
// else do the remote thing
if (!m_localBackend.IsLocalRegion(regionHandle))
{
uint x = 0, y = 0;
Utils.LongToUInts(regionHandle, out x, out y);
GridRegion regInfo = m_aScene.GridService.GetRegionByPosition(UUID.Zero, (int)x, (int)y);
if (regInfo != null)
{
return m_regionClient.DoChildAgentUpdateCall(regInfo, cAgentData);
}
//else
// m_log.Warn("[REST COMMS]: Region not found " + regionHandle);
}
return false;
}
public bool SendRetrieveRootAgent(ulong regionHandle, UUID id, out IAgentData agent)
{
// Try local first
if (m_localBackend.SendRetrieveRootAgent(regionHandle, id, out agent))
return true;
// else do the remote thing
if (!m_localBackend.IsLocalRegion(regionHandle))
{
uint x = 0, y = 0;
Utils.LongToUInts(regionHandle, out x, out y);
GridRegion regInfo = m_aScene.GridService.GetRegionByPosition(UUID.Zero, (int)x, (int)y);
if (regInfo != null)
{
return m_regionClient.DoRetrieveRootAgentCall(regInfo, id, out agent);
}
//else
// m_log.Warn("[REST COMMS]: Region not found " + regionHandle);
}
return false;
}
public bool SendReleaseAgent(ulong regionHandle, UUID id, string uri)
{
// Try local first
if (m_localBackend.SendReleaseAgent(regionHandle, id, uri))
return true;
// else do the remote thing
return m_regionClient.DoReleaseAgentCall(regionHandle, id, uri);
}
public bool SendCloseAgent(ulong regionHandle, UUID id)
{
// Try local first
if (m_localBackend.SendCloseAgent(regionHandle, id))
return true;
// else do the remote thing
if (!m_localBackend.IsLocalRegion(regionHandle))
{
uint x = 0, y = 0;
Utils.LongToUInts(regionHandle, out x, out y);
GridRegion regInfo = m_aScene.GridService.GetRegionByPosition(UUID.Zero, (int)x, (int)y);
if (regInfo != null)
{
return m_regionClient.DoCloseAgentCall(regInfo, id);
}
//else
// m_log.Warn("[REST COMMS]: Region not found " + regionHandle);
}
return false;
}
/**
* Object-related communications
*/
public bool SendCreateObject(ulong regionHandle, SceneObjectGroup sog, bool isLocalCall)
{
// Try local first
if (m_localBackend.SendCreateObject(regionHandle, sog, true))
{
//m_log.Debug("[REST COMMS]: LocalBackEnd SendCreateObject succeeded");
return true;
}
// else do the remote thing
if (!m_localBackend.IsLocalRegion(regionHandle))
{
uint x = 0, y = 0;
Utils.LongToUInts(regionHandle, out x, out y);
GridRegion regInfo = m_aScene.GridService.GetRegionByPosition(UUID.Zero, (int)x, (int)y);
if (regInfo != null)
{
return m_regionClient.DoCreateObjectCall(
regInfo, sog, SceneObjectSerializer.ToXml2Format(sog), m_aScene.m_allowScriptCrossings);
}
//else
// m_log.Warn("[REST COMMS]: Region not found " + regionHandle);
}
return false;
}
public bool SendCreateObject(ulong regionHandle, UUID userID, UUID itemID)
{
// Not Implemented
return false;
}
#endregion /* IInterregionComms */
#region Incoming calls from remote instances
/**
* Agent-related incoming calls
*/
public Hashtable AgentHandler(Hashtable request)
{
//m_log.Debug("[CONNECTION DEBUGGING]: AgentHandler Called");
m_log.Debug("---------------------------");
m_log.Debug(" >> uri=" + request["uri"]);
m_log.Debug(" >> content-type=" + request["content-type"]);
m_log.Debug(" >> http-method=" + request["http-method"]);
m_log.Debug("---------------------------\n");
Hashtable responsedata = new Hashtable();
responsedata["content_type"] = "text/html";
responsedata["keepalive"] = false;
UUID agentID;
string action;
ulong regionHandle;
if (!GetParams((string)request["uri"], out agentID, out regionHandle, out action))
{
m_log.InfoFormat("[REST COMMS]: Invalid parameters for agent message {0}", request["uri"]);
responsedata["int_response_code"] = 404;
responsedata["str_response_string"] = "false";
return responsedata;
}
// Next, let's parse the verb
string method = (string)request["http-method"];
if (method.Equals("PUT"))
{
DoAgentPut(request, responsedata);
return responsedata;
}
else if (method.Equals("POST"))
{
DoAgentPost(request, responsedata, agentID);
return responsedata;
}
else if (method.Equals("GET"))
{
DoAgentGet(request, responsedata, agentID, regionHandle);
return responsedata;
}
else if (method.Equals("DELETE"))
{
DoAgentDelete(request, responsedata, agentID, action, regionHandle);
return responsedata;
}
else
{
m_log.InfoFormat("[REST COMMS]: method {0} not supported in agent message", method);
responsedata["int_response_code"] = 404;
responsedata["str_response_string"] = "false";
return responsedata;
}
}
protected virtual void DoAgentPost(Hashtable request, Hashtable responsedata, UUID id)
{
if (m_safemode)
{
// Authentication
string authority = string.Empty;
string authToken = string.Empty;
if (!GetAuthentication(request, out authority, out authToken))
{
m_log.InfoFormat("[REST COMMS]: Authentication failed for agent message {0}", request["uri"]);
responsedata["int_response_code"] = 403;
responsedata["str_response_string"] = "Forbidden";
return ;
}
if (!VerifyKey(id, authority, authToken))
{
m_log.InfoFormat("[REST COMMS]: Authentication failed for agent message {0}", request["uri"]);
responsedata["int_response_code"] = 403;
responsedata["str_response_string"] = "Forbidden";
return ;
}
m_log.DebugFormat("[REST COMMS]: Authentication succeeded for {0}", id);
}
OSDMap args = RegionClient.GetOSDMap((string)request["body"]);
if (args == null)
{
responsedata["int_response_code"] = 400;
responsedata["str_response_string"] = "false";
return;
}
// retrieve the regionhandle
ulong regionhandle = 0;
if (args["destination_handle"] != null)
UInt64.TryParse(args["destination_handle"].AsString(), out regionhandle);
AgentCircuitData aCircuit = new AgentCircuitData();
try
{
aCircuit.UnpackAgentCircuitData(args);
}
catch (Exception ex)
{
m_log.InfoFormat("[REST COMMS]: exception on unpacking ChildCreate message {0}", ex.Message);
return;
}
OSDMap resp = new OSDMap(2);
string reason = String.Empty;
uint teleportFlags = 0;
if (args.ContainsKey("teleport_flags"))
{
teleportFlags = args["teleport_flags"].AsUInteger();
}
// This is the meaning of POST agent
m_regionClient.AdjustUserInformation(aCircuit);
bool result = m_localBackend.SendCreateChildAgent(regionhandle, aCircuit, teleportFlags, out reason);
resp["reason"] = OSD.FromString(reason);
resp["success"] = OSD.FromBoolean(result);
// TODO: add reason if not String.Empty?
responsedata["int_response_code"] = 200;
responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp);
}
protected virtual void DoAgentPut(Hashtable request, Hashtable responsedata)
{
OSDMap args = RegionClient.GetOSDMap((string)request["body"]);
if (args == null)
{
responsedata["int_response_code"] = 400;
responsedata["str_response_string"] = "false";
return;
}
// retrieve the regionhandle
ulong regionhandle = 0;
if (args["destination_handle"] != null)
UInt64.TryParse(args["destination_handle"].AsString(), out regionhandle);
string messageType;
if (args["message_type"] != null)
messageType = args["message_type"].AsString();
else
{
m_log.Warn("[REST COMMS]: Agent Put Message Type not found. ");
messageType = "AgentData";
}
bool result = true;
if ("AgentData".Equals(messageType))
{
AgentData agent = new AgentData();
try
{
agent.Unpack(args);
}
catch (Exception ex)
{
m_log.InfoFormat("[REST COMMS]: exception on unpacking ChildAgentUpdate message {0}", ex.Message);
return;
}
//agent.Dump();
// This is one of the meanings of PUT agent
result = m_localBackend.SendChildAgentUpdate(regionhandle, agent);
}
else if ("AgentPosition".Equals(messageType))
{
AgentPosition agent = new AgentPosition();
try
{
agent.Unpack(args);
}
catch (Exception ex)
{
m_log.InfoFormat("[REST COMMS]: exception on unpacking ChildAgentUpdate message {0}", ex.Message);
return;
}
//agent.Dump();
// This is one of the meanings of PUT agent
result = m_localBackend.SendChildAgentUpdate(regionhandle, agent);
}
responsedata["int_response_code"] = 200;
responsedata["str_response_string"] = result.ToString();
}
protected virtual void DoAgentGet(Hashtable request, Hashtable responsedata, UUID id, ulong regionHandle)
{
IAgentData agent = null;
bool result = m_localBackend.SendRetrieveRootAgent(regionHandle, id, out agent);
OSDMap map = null;
if (result)
{
if (agent != null) // just to make sure
{
map = agent.Pack();
string strBuffer = "";
try
{
strBuffer = OSDParser.SerializeJsonString(map);
}
catch (Exception e)
{
m_log.WarnFormat("[REST COMMS]: Exception thrown on serialization of CreateObject: {0}", e.Message);
// ignore. buffer will be empty, caller should check.
}
responsedata["content_type"] = "application/json";
responsedata["int_response_code"] = 200;
responsedata["str_response_string"] = strBuffer;
}
else
{
responsedata["int_response_code"] = 500;
responsedata["str_response_string"] = "Internal error";
}
}
else
{
responsedata["int_response_code"] = 404;
responsedata["str_response_string"] = "Not Found";
}
}
protected virtual void DoAgentDelete(Hashtable request, Hashtable responsedata, UUID id, string action, ulong regionHandle)
{
//m_log.Debug(" >>> DoDelete action:" + action + "; regionHandle:" + regionHandle);
if (action.Equals("release"))
m_localBackend.SendReleaseAgent(regionHandle, id, "");
else
m_localBackend.SendCloseAgent(regionHandle, id);
responsedata["int_response_code"] = 200;
responsedata["str_response_string"] = "OpenSim agent " + id.ToString();
m_log.Debug("[REST COMMS]: Agent Deleted.");
}
/**
* Object-related incoming calls
*/
public Hashtable ObjectHandler(Hashtable request)
{
m_log.Debug("[CONNECTION DEBUGGING]: ObjectHandler Called");
m_log.Debug("---------------------------");
m_log.Debug(" >> uri=" + request["uri"]);
m_log.Debug(" >> content-type=" + request["content-type"]);
m_log.Debug(" >> http-method=" + request["http-method"]);
m_log.Debug("---------------------------\n");
Hashtable responsedata = new Hashtable();
responsedata["content_type"] = "text/html";
UUID objectID;
string action;
ulong regionHandle;
if (!GetParams((string)request["uri"], out objectID, out regionHandle, out action))
{
m_log.InfoFormat("[REST COMMS]: Invalid parameters for object message {0}", request["uri"]);
responsedata["int_response_code"] = 404;
responsedata["str_response_string"] = "false";
return responsedata;
}
// Next, let's parse the verb
string method = (string)request["http-method"];
if (method.Equals("POST"))
{
DoObjectPost(request, responsedata, regionHandle);
return responsedata;
}
else if (method.Equals("PUT"))
{
DoObjectPut(request, responsedata, regionHandle);
return responsedata;
}
//else if (method.Equals("DELETE"))
//{
// DoObjectDelete(request, responsedata, agentID, action, regionHandle);
// return responsedata;
//}
else
{
m_log.InfoFormat("[REST COMMS]: method {0} not supported in object message", method);
responsedata["int_response_code"] = 404;
responsedata["str_response_string"] = "false";
return responsedata;
}
}
protected virtual void DoObjectPost(Hashtable request, Hashtable responsedata, ulong regionhandle)
{
OSDMap args = RegionClient.GetOSDMap((string)request["body"]);
if (args == null)
{
responsedata["int_response_code"] = 400;
responsedata["str_response_string"] = "false";
return;
}
string sogXmlStr = "", extraStr = "", stateXmlStr = "";
if (args["sog"] != null)
sogXmlStr = args["sog"].AsString();
if (args["extra"] != null)
extraStr = args["extra"].AsString();
IScene s = m_localBackend.GetScene(regionhandle);
SceneObjectGroup sog = null;
try
{
sog = SceneObjectSerializer.FromXml2Format(sogXmlStr);
sog.ExtraFromXmlString(extraStr);
}
catch (Exception ex)
{
m_log.InfoFormat("[REST COMMS]: exception on deserializing scene object {0}", ex.Message);
responsedata["int_response_code"] = 400;
responsedata["str_response_string"] = "false";
return;
}
if ((args["state"] != null) && m_aScene.m_allowScriptCrossings)
{
stateXmlStr = args["state"].AsString();
if (stateXmlStr != "")
{
try
{
sog.SetState(stateXmlStr, s);
}
catch (Exception ex)
{
m_log.InfoFormat("[REST COMMS]: exception on setting state for scene object {0}", ex.Message);
}
}
}
// This is the meaning of POST object
bool result = m_localBackend.SendCreateObject(regionhandle, sog, false);
responsedata["int_response_code"] = 200;
responsedata["str_response_string"] = result.ToString();
}
protected virtual void DoObjectPut(Hashtable request, Hashtable responsedata, ulong regionhandle)
{
OSDMap args = RegionClient.GetOSDMap((string)request["body"]);
if (args == null)
{
responsedata["int_response_code"] = 400;
responsedata["str_response_string"] = "false";
return;
}
UUID userID = UUID.Zero, itemID = UUID.Zero;
if (args["userid"] != null)
userID = args["userid"].AsUUID();
if (args["itemid"] != null)
itemID = args["itemid"].AsUUID();
// This is the meaning of PUT object
bool result = m_localBackend.SendCreateObject(regionhandle, userID, itemID);
responsedata["int_response_code"] = 200;
responsedata["str_response_string"] = result.ToString();
}
#endregion
#region Misc
/// <summary>
/// Extract the param from an uri.
/// </summary>
/// <param name="uri">Something like this: /agent/uuid/ or /agent/uuid/handle/release</param>
/// <param name="uri">uuid on uuid field</param>
/// <param name="action">optional action</param>
public static bool GetParams(string uri, out UUID uuid, out ulong regionHandle, out string action)
{
uuid = UUID.Zero;
action = "";
regionHandle = 0;
uri = uri.Trim(new char[] { '/' });
string[] parts = uri.Split('/');
if (parts.Length <= 1)
{
return false;
}
else
{
if (!UUID.TryParse(parts[1], out uuid))
return false;
if (parts.Length >= 3)
UInt64.TryParse(parts[2], out regionHandle);
if (parts.Length >= 4)
action = parts[3];
return true;
}
}
public static bool GetAuthentication(Hashtable request, out string authority, out string authKey)
{
authority = string.Empty;
authKey = string.Empty;
Uri authUri;
Hashtable headers = (Hashtable)request["headers"];
// Authorization keys look like this:
// http://orgrid.org:8002/<uuid>
if (headers.ContainsKey("authorization") && (string)headers["authorization"] != "None")
{
if (Uri.TryCreate((string)headers["authorization"], UriKind.Absolute, out authUri))
{
authority = authUri.Authority;
authKey = authUri.PathAndQuery.Trim('/');
m_log.DebugFormat("[REST COMMS]: Got authority {0} and key {1}", authority, authKey);
return true;
}
else
m_log.Debug("[REST COMMS]: Wrong format for Authorization header: " + (string)headers["authorization"]);
}
else
m_log.Debug("[REST COMMS]: Authorization header not found");
return false;
}
bool VerifyKey(UUID userID, string authority, string key)
{
string[] parts = authority.Split(':');
IPAddress ipaddr = IPAddress.None;
uint port = 0;
if (parts.Length <= 2)
ipaddr = Util.GetHostFromDNS(parts[0]);
if (parts.Length == 2)
UInt32.TryParse(parts[1], out port);
return true;
//// local authority (standalone), local call
//if (m_thisIP.Equals(ipaddr) && (m_aScene.RegionInfo.HttpPort == port))
// return ((IAuthentication)m_aScene.CommsManager.UserAdminService).VerifyKey(userID, key);
//// remote call
//else
// return AuthClient.VerifyKey("http://" + authority, userID, key);
}
#endregion Misc
protected class RegionToRegionClient : RegionClient
{
Scene m_aScene = null;
IHyperlinkService m_hyperlinkService;
public RegionToRegionClient(Scene s, IHyperlinkService hyperService)
{
m_aScene = s;
m_hyperlinkService = hyperService;
}
public override ulong GetRegionHandle(ulong handle)
{
if (m_aScene.SceneGridService is HGSceneCommunicationService)
{
if (m_hyperlinkService != null)
return m_hyperlinkService.FindRegionHandle(handle);
}
return handle;
}
public override bool IsHyperlink(ulong handle)
{
if (m_aScene.SceneGridService is HGSceneCommunicationService)
{
if ((m_hyperlinkService != null) && (m_hyperlinkService.GetHyperlinkRegion(handle) != null))
return true;
}
return false;
}
public override void SendUserInformation(GridRegion regInfo, AgentCircuitData aCircuit)
{
if (m_hyperlinkService != null)
m_hyperlinkService.SendUserInformation(regInfo, aCircuit);
}
public override void AdjustUserInformation(AgentCircuitData aCircuit)
{
if (m_hyperlinkService != null)
m_hyperlinkService.AdjustUserInformation(aCircuit);
}
}
}
}

View File

@ -37,7 +37,6 @@ using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Communications.Clients;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Hypergrid;
@ -306,52 +305,5 @@ namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation
#endregion /* IInterregionComms */
protected class RegionToRegionClient : RegionClient
{
Scene m_aScene = null;
IHyperlinkService m_hyperlinkService;
public RegionToRegionClient(Scene s, IHyperlinkService hyperService)
{
m_aScene = s;
m_hyperlinkService = hyperService;
}
public override ulong GetRegionHandle(ulong handle)
{
if (m_aScene.SceneGridService is HGSceneCommunicationService)
{
if (m_hyperlinkService != null)
return m_hyperlinkService.FindRegionHandle(handle);
}
return handle;
}
public override bool IsHyperlink(ulong handle)
{
if (m_aScene.SceneGridService is HGSceneCommunicationService)
{
if ((m_hyperlinkService != null) && (m_hyperlinkService.GetHyperlinkRegion(handle) != null))
return true;
}
return false;
}
public override void SendUserInformation(GridRegion regInfo, AgentCircuitData aCircuit)
{
if (m_hyperlinkService != null)
m_hyperlinkService.SendUserInformation(regInfo, aCircuit);
}
public override void AdjustUserInformation(AgentCircuitData aCircuit)
{
if (m_hyperlinkService != null)
m_hyperlinkService.AdjustUserInformation(aCircuit);
}
}
}
}

View File

@ -33,7 +33,6 @@ using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Communications.Clients;
using OpenSim.Region.Framework.Scenes.Serialization;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Services.Interfaces;

View File

@ -36,7 +36,6 @@ using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Communications.Services;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Console;
using OpenSim.Framework.Servers;

View File

@ -42,7 +42,6 @@ using OpenSim.Framework;
using OpenSim.Services.Interfaces;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Communications.Clients;
using OpenSim.Framework.Console;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes.Scripting;

View File

@ -40,8 +40,8 @@ using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.CoreModules.ServiceConnectorsOut.Interregion;
using OpenSim.Region.CoreModules.World.Serialiser;
using OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation;
using OpenSim.Tests.Common;
using OpenSim.Tests.Common.Mock;
using OpenSim.Tests.Common.Setup;
@ -71,7 +71,7 @@ namespace OpenSim.Region.Framework.Scenes.Tests
scene2 = SceneSetupHelpers.SetupScene("Neighbour x+1", UUID.Random(), 1001, 1000, cm);
scene3 = SceneSetupHelpers.SetupScene("Neighbour x-1", UUID.Random(), 999, 1000, cm);
ISharedRegionModule interregionComms = new RESTInterregionComms();
ISharedRegionModule interregionComms = new LocalSimulationConnectorModule();
interregionComms.Initialise(new IniConfigSource());
interregionComms.PostInitialise();
SceneSetupHelpers.SetupSceneModules(scene, new IniConfigSource(), interregionComms);

View File

@ -34,7 +34,7 @@ using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.CoreModules.ServiceConnectorsOut.Interregion;
using OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation;
using OpenSim.Tests.Common;
using OpenSim.Tests.Common.Mock;
using OpenSim.Tests.Common.Setup;
@ -116,7 +116,7 @@ namespace OpenSim.Region.Framework.Scenes.Tests
TestCommunicationsManager cm = new TestCommunicationsManager();
// shared module
ISharedRegionModule interregionComms = new RESTInterregionComms();
ISharedRegionModule interregionComms = new LocalSimulationConnectorModule();
Scene sceneB = SceneSetupHelpers.SetupScene("sceneB", sceneBId, 1010, 1010, cm, "grid");