log4net.ILog.Error(object)

Here are the examples of the csharp api log4net.ILog.Error(object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

517 Examples 7

19 Source : MySQLGridData.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

override public ReservationData GetReservationAtPoint(uint x, uint y)
        {
            try
            {
                Dictionary<string, object> param = new Dictionary<string, object>();
                param["?x"] = x.ToString();
                param["?y"] = y.ToString();

                using (ISimpleDB conn = _connFactory.GetConnection())
                {
                    string query = "SELECT * FROM reservations WHERE resXMin <= ?x AND resXMax >= ?x AND resYMin <= ?y AND resYMax >= ?y";
                    using (IDataReader reader = conn.QueryAndUseReader(query, param))
                    {
                        ReservationData row = this.readReservationRow(reader);
                        return row;
                    }
                }
            }
            catch (Exception e)
            {
                m_log.Error(e.ToString());
                return null;
            } 
        }

19 Source : MySQLAssetTest.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

[TestFixtureSetUp]
        public void Init()
        {
            SuperInit();
            // If we manage to connect to the database with the user
            // and preplacedword above it is our test database, and run
            // these tests.  If anything goes wrong, ignore these
            // tests.
            try 
            {
                database = new MySQLManager(connect);
                db = new MySQLreplacedetData();
                db.Initialise(connect);
            } 
            catch (Exception e)
            {
                m_log.Error(e.ToString());
                replacedert.Ignore();
            }
        }

19 Source : MySQLManager.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public void Reconnect()
        {
            m_log.Info("[REGION DB] Reconnecting database");

            lock (dbcon)
            {
                try
                {
                    // Close the DB connection
                    dbcon.Close();
                    // Try reopen it
                    dbcon = new MySqlConnection(connectionString);
                    dbcon.Open();
                }
                catch (Exception e)
                {
                    m_log.Error("Unable to reconnect to database " + e.ToString());
                }
            }
        }

19 Source : MySQLManager.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public void GetTableVersion(Dictionary<string, string> tableList)
        {
            lock (dbcon)
            {
                CheckConnection();

                MySqlCommand tablesCmd =
                    new MySqlCommand(
                        "SELECT TABLE_NAME, TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=?dbname",
                        dbcon);
                tablesCmd.Parameters.AddWithValue("?dbname", dbcon.Database);

                using (MySqlDataReader tables = tablesCmd.ExecuteReader())
                {
                    while (tables.Read())
                    {
                        try
                        {
                            string tableName = (string)tables["TABLE_NAME"];
                            string comment = (string)tables["TABLE_COMMENT"];
                            if (tableList.ContainsKey(tableName))
                            {
                                tableList[tableName] = comment;
                            }
                        }
                        catch (Exception e)
                        {
                            m_log.Error(e.ToString());
                        }
                    }
                    tables.Close();
                }
            }
        }

19 Source : MySQLManager.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public IDbCommand Query(string sql, Dictionary<string, object> parameters)
        {
            try
            {
                CheckConnection(); // Not sure if this one is necessary

                MySqlCommand dbcommand = (MySqlCommand)dbcon.CreateCommand();
                dbcommand.CommandText = sql;
                foreach (KeyValuePair<string, object> param in parameters)
                {
                    dbcommand.Parameters.AddWithValue(param.Key, param.Value);
                }

                return (IDbCommand)dbcommand;
            }
            catch (Exception e)
            {
                // Return null if it fails.
                m_log.Error("Failed during Query generation: " + e.ToString());
                return null;
            }
        }

19 Source : MySQLManager.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public bool insertRegion(RegionProfileData regiondata)
        {
            bool GRID_ONLY_UPDATE_NECESSARY_DATA = false;

            string sql = String.Empty;
            if (GRID_ONLY_UPDATE_NECESSARY_DATA)
            {
                sql += "INSERT INTO ";
            }
            else
            {
                sql += "REPLACE INTO ";
            }

            sql += "regions (regionHandle, regionName, uuid, regionRecvKey, regionSecret, regionSendKey, regionDataURI, ";
            sql +=
                "serverIP, serverPort, locX, locY, locZ, eastOverrideHandle, westOverrideHandle, southOverrideHandle, northOverrideHandle, regionreplacedetURI, regionreplacedetRecvKey, ";

            // part of an initial brutish effort to provide accurate information (as per the xml region spec)
            // wrt the ownership of a given region
            // the (very bad) replacedumption is that this value is being read and handled inconsistently or
            // not at all. Current strategy is to put the code in place to support the validity of this information
            // and to roll forward debugging any issues from that point
            //
            // this particular section of the mod attempts to implement the commit of a supplied value
            // server for the UUID of the region's owner (master avatar). It consists of the addition of the column and value to the relevant sql,
            // as well as the related parameterization
            sql +=
                "regionreplacedetSendKey, regionUserURI, regionUserRecvKey, regionUserSendKey, regionMapTexture, serverHttpPort, serverRemotingPort, owner_uuid, originUUID, access) VALUES ";

            sql += "(?regionHandle, ?regionName, ?uuid, ?regionRecvKey, ?regionSecret, ?regionSendKey, ?regionDataURI, ";
            sql +=
                "?serverIP, ?serverPort, ?locX, ?locY, ?locZ, ?eastOverrideHandle, ?westOverrideHandle, ?southOverrideHandle, ?northOverrideHandle, ?regionreplacedetURI, ?regionreplacedetRecvKey, ";
            sql +=
                "?regionreplacedetSendKey, ?regionUserURI, ?regionUserRecvKey, ?regionUserSendKey, ?regionMapTexture, ?serverHttpPort, ?serverRemotingPort, ?owner_uuid, ?originUUID, ?access)";

            if (GRID_ONLY_UPDATE_NECESSARY_DATA)
            {
                sql += "ON DUPLICATE KEY UPDATE serverIP = ?serverIP, serverPort = ?serverPort, owner_uuid - ?owner_uuid;";
            }
            else
            {
                sql += ";";
            }

            Dictionary<string, object> parameters = new Dictionary<string, object>();

            parameters["?regionHandle"] = regiondata.regionHandle.ToString();
            parameters["?regionName"] = regiondata.regionName.ToString();
            parameters["?uuid"] = regiondata.UUID.ToString();
            parameters["?regionRecvKey"] = regiondata.regionRecvKey.ToString();
            parameters["?regionSecret"] = regiondata.regionSecret.ToString();
            parameters["?regionSendKey"] = regiondata.regionSendKey.ToString();
            parameters["?regionDataURI"] = regiondata.regionDataURI.ToString();
            parameters["?serverIP"] = regiondata.serverHostName.ToString();
            parameters["?serverPort"] = regiondata.serverPort.ToString();
            parameters["?locX"] = regiondata.regionLocX.ToString();
            parameters["?locY"] = regiondata.regionLocY.ToString();
            parameters["?locZ"] = regiondata.regionLocZ.ToString();
            parameters["?eastOverrideHandle"] = regiondata.regionEastOverrideHandle.ToString();
            parameters["?westOverrideHandle"] = regiondata.regionWestOverrideHandle.ToString();
            parameters["?northOverrideHandle"] = regiondata.regionNorthOverrideHandle.ToString();
            parameters["?southOverrideHandle"] = regiondata.regionSouthOverrideHandle.ToString();
            parameters["?regionreplacedetURI"] = regiondata.regionreplacedetURI.ToString();
            parameters["?regionreplacedetRecvKey"] = regiondata.regionreplacedetRecvKey.ToString();
            parameters["?regionreplacedetSendKey"] = regiondata.regionreplacedetSendKey.ToString();
            parameters["?regionUserURI"] = regiondata.regionUserURI.ToString();
            parameters["?regionUserRecvKey"] = regiondata.regionUserRecvKey.ToString();
            parameters["?regionUserSendKey"] = regiondata.regionUserSendKey.ToString();
            parameters["?regionMapTexture"] = regiondata.regionMapTextureID.ToString();
            parameters["?serverHttpPort"] = regiondata.httpPort.ToString();
            parameters["?serverRemotingPort"] = regiondata.remotingPort.ToString();
            parameters["?owner_uuid"] = regiondata.owner_uuid.ToString();
            parameters["?originUUID"] = regiondata.originUUID.ToString();
            parameters["?access"] = regiondata.maturity.ToString();

            bool returnval = false;

            try
            {
                IDbCommand result = Query(sql, parameters);

                if (result.ExecuteNonQuery() > 0)
                {
                    returnval = true;
                }
                result.Dispose();
            }
            catch (Exception e)
            {
                m_log.Error(e.ToString());
                return false;
            }

            return returnval;
        }

19 Source : RegionClient.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public bool DoChildAgentUpdateCall(RegionInfo region, IAgentData cAgentData)
        {
            // Eventually, we want to use a caps url instead of the agentID
            string uri = "http://" + region.ExternalHostName + ":" + region.HttpPort + "/agent/" + cAgentData.AgentID + "/";
            //Console.WriteLine("   >>> DoChildAgentUpdateCall <<< " + uri);

            HttpWebRequest ChildUpdateRequest = (HttpWebRequest)WebRequest.Create(uri);
            ChildUpdateRequest.Method = "PUT";
            ChildUpdateRequest.ContentType = "application/json";
            ChildUpdateRequest.Timeout = AGENT_UPDATE_TIMEOUT;
            //ChildUpdateRequest.KeepAlive = false;
            ChildUpdateRequest.Headers["authorization"] = GenerateAuthorization();

            // Fill it in
            OSDMap args = null;
            try
            {
                args = cAgentData.Pack();
            }
            catch (Exception e)
            {
                m_log.Error("[REST COMMS]: PackUpdateMessage failed with exception: " + e.Message);
                return false;
            }

            // Add the regionhandle of the destination region
            ulong regionHandle = GetRegionHandle(region.RegionHandle);
            args["destination_handle"] = OSD.FromString(regionHandle.ToString());

            string strBuffer = String.Empty;
            byte[] buffer = new byte[1];
            try
            {
                strBuffer = OSDParser.SerializeJsonString(args);
                UTF8Encoding str = new UTF8Encoding();
                buffer = str.GetBytes(strBuffer);
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[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
                os.Close();
                //m_log.InfoFormat("[REST COMMS]: Posted ChildAgentUpdate request to remote sim {0}", uri);
            }
            catch (WebException)
            {
                // Normal case of network error connecting to a region (e.g. a down one)
                return false;
            }
            catch (Exception ex)
            {
                m_log.ErrorFormat("[REST COMMS]: Bad send on ChildAgentUpdate {0}", ex.Message);
                return false;
            }

            // Let's wait for the response
//            m_log.Info("[REST COMMS]: Waiting for a reply after ChildAgentUpdate");
            try
            {
                WebResponse webResponse = ChildUpdateRequest.GetResponse();
                if (webResponse != null)
                {
                    StreamReader sr = new StreamReader(webResponse.GetResponseStream());
                    string reply = sr.ReadToEnd().Trim();
                    sr.Close();
                    //m_log.InfoFormat("[REST COMMS]: ChildAgentUpdate reply was {0} ", reply);
                    bool rc = false;
                    if (!bool.TryParse(reply, out rc))
                        rc = false;
                    return rc;
                }
                m_log.Info("[REST COMMS]: Null reply on ChildAgentUpdate post");
            }
            catch (Exception ex)
            {
                m_log.InfoFormat("[REST COMMS]: exception on reply of ChildAgentUpdate {0}", ex.Message);
            }
            return false;
        }

19 Source : RegionClient.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public CreateObject2Ret DoCreateObject2Call(RegionInfo region, UUID sogId, byte[] sogBytes, bool allowScriptCrossing,
            Vector3 pos, bool isAttachment, long nonceID, List<UUID> avatars)
        {
            ulong regionHandle = GetRegionHandle(region.RegionHandle);
            string uri = "http://" + region.ExternalHostName + ":" + region.HttpPort + "/object2/" + sogId + "/" + regionHandle.ToString() + "/";

            HttpWebRequest objectCreateRequest = (HttpWebRequest)WebRequest.Create(uri);
            objectCreateRequest.Method = "POST";
            objectCreateRequest.ContentType = "application/octet-stream";
            objectCreateRequest.Timeout = CREATE_OBJECT_TIMEOUT;

            objectCreateRequest.Headers["authorization"] = GenerateAuthorization();
            objectCreateRequest.Headers["x-nonce-id"] = nonceID.ToString();

            Guid[] avatarsArray;
            if (avatars == null)
                avatarsArray = null;
            else
            {
                int count = 0;
                avatarsArray = new Guid[avatars.Count];
                foreach (UUID id in avatars)
                    avatarsArray[count++] = id.Guid;
            }

            ObjectPostMessage message = new ObjectPostMessage { NumAvatars = avatarsArray.Length, Pos = pos, Sog = sogBytes, Avatars = avatarsArray };

            try
            { 
                // send the Post
                Stream os = objectCreateRequest.GetRequestStream();
                ProtoBuf.Serializer.Serialize(os, message);

                os.Flush();
                os.Close();

                m_log.InfoFormat("[REST COMMS]: Posted DoCreateObject2 request to remote sim {0}", uri);
            }
            catch (Exception e)
            {
                m_log.InfoFormat("[REST COMMS]: DoCreateObject2 call failed {0}", e);
                return CreateObject2Ret.Error;
            }

            // Let's wait for the response
            //m_log.Info("[REST COMMS]: Waiting for a reply after DoCreateChildAgentCall");
            try
            {
                HttpWebResponse webResponse = (HttpWebResponse)objectCreateRequest.GetResponse();
                if (webResponse == null)
                {
                    m_log.Info("[REST COMMS]: Null reply on DoCreateObject2 post");
                    return CreateObject2Ret.Error;
                }

                StreamReader sr = new StreamReader(webResponse.GetResponseStream());
                string reply = sr.ReadToEnd().Trim();
                sr.Close();

                //this will happen during the initial rollout and tells us we need to fall back to the 
                //old method
                if (webResponse.StatusCode == HttpStatusCode.Forbidden)
                {
                    m_log.InfoFormat("[REST COMMS]: Entry denied on reply of DoCreateObject2");
                    return CreateObject2Ret.AccessDenied;
                }
                else if (webResponse.StatusCode == HttpStatusCode.NotFound)
                {
                    m_log.InfoFormat("[REST COMMS]: NotFound on reply of DoCreateObject2");
                    return CreateObject2Ret.NotFound;
                }
                else if (webResponse.StatusCode == HttpStatusCode.OK)
                {
                    return CreateObject2Ret.Ok;
                }
                else
                {
                    m_log.WarnFormat("[REST COMMS]: Error on reply of DoCreateObject2 {0}", reply);
                    return CreateObject2Ret.Error;
                }
            }
            catch (WebException ex)
            {
                m_log.InfoFormat("[REST COMMS]: exception on reply of DoCreateObject2 {0} Sz {1}", ex, objectCreateRequest.ContentLength);
                HttpWebResponse response = (HttpWebResponse)ex.Response;
                if (response != null)
                {
                    if (response.StatusCode == HttpStatusCode.Forbidden)
                    {
                        m_log.InfoFormat("[REST COMMS]: Entry denied on reply of DoCreateObject2");
                        return CreateObject2Ret.AccessDenied;
                    }
                    else if (response.StatusCode == HttpStatusCode.NotFound)
                    {
                        m_log.InfoFormat("[REST COMMS]: NotFound on reply of DoCreateObject2");
                        return CreateObject2Ret.NotFound;
                    }
                    else if (response.StatusCode == HttpStatusCode.OK)
                    {
                        return CreateObject2Ret.Ok;
                    }
                    else
                    {
                        m_log.Error("[REST COMMS]: Error on reply of DoCreateObject2: " + ex.Message);
                        return CreateObject2Ret.Error;
                    }
                }
            }

            return CreateObject2Ret.Error;
        }

19 Source : RestClient.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public void AddQueryParameter(string name, string value)
        {
            try
            {
                _parameterElements.Add(HttpUtility.UrlEncode(name), HttpUtility.UrlEncode(value));
            }
            catch (ArgumentException)
            {
                m_log.Error("[REST]: Query parameter " + name + " is already added.");
            }
            catch (Exception e)
            {
                m_log.Error("[REST]: An exception was raised adding query parameter to dictionary. Exception: {0}",e);
            }
        }

19 Source : RestClient.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public void AddQueryParameter(string name)
        {
            try
            {
                _parameterElements.Add(HttpUtility.UrlEncode(name), null);
            }
            catch (ArgumentException)
            {
                m_log.Error("[REST]: Query parameter " + name + " is already added.");
            }
            catch (Exception e)
            {
                m_log.Error("[REST]: An exception was raised adding query parameter to dictionary. Exception: {0}",e);
            }
        }

19 Source : RestClient.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public Stream Request()
        {
            lock (_lock)
            {
                _request = (HttpWebRequest) WebRequest.Create(buildUri());
                _request.KeepAlive = false;
                _request.ContentType = "application/xml";
                _request.Timeout = 200000;
                _request.Method = RequestMethod;
                _asyncException = null;

//                IAsyncResult responseAsyncResult = _request.BeginGetResponse(new AsyncCallback(ResponseIsReadyDelegate), _request);
                try
                {
                    _response = (HttpWebResponse) _request.GetResponse();
                }
                catch (WebException e)
                {
                    HttpWebResponse errorResponse = e.Response as HttpWebResponse;
                    if (null != errorResponse && HttpStatusCode.NotFound == errorResponse.StatusCode)
                    {
                        m_log.Warn("[replacedET] replacedet not found (404)");
                    }
                    else
                    {
                        m_log.Error("[replacedET] Error fetching replacedet from replacedet server");
                        m_log.Debug(e.ToString());
                    }

                    return null;
                }

                Stream src = _response.GetResponseStream();
                int length = src.Read(_readbuf, 0, BufferSize);
                while (length > 0)
                {
                    _resource.Write(_readbuf, 0, length);
                    length = src.Read(_readbuf, 0, BufferSize);
                }


                // TODO! Implement timeout, without killing the server
                // this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted
                //ThreadPool.RegisterWaitForSingleObject(responseAsyncResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true);

//                _allDone.WaitOne();
                if (_response != null)
                    _response.Close();
                if (_asyncException != null)
                    throw _asyncException;

                if (_resource != null)
                {
                    _resource.Flush();
                    _resource.Seek(0, SeekOrigin.Begin);
                }

                return _resource;
            }
        }

19 Source : RemoteConsole.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

private Hashtable HandleHttpSessionCommand(Hashtable request)
        {
            DoExpire();

            var post = DecodePostString(request["body"].ToString());
            var reply = new Hashtable();

            reply["str_response_string"] = string.Empty;
            reply["int_response_code"] = 404;
            reply["content_type"] = "text/plain";

            var headers = (Hashtable)request["headers"];
            if (headers.ContainsKey("Authorization"))
            {
                var authHeader = headers["Authorization"].ToString();
                if (!authHeader.StartsWith("Bearer ", StringComparison.InvariantCultureIgnoreCase))
                {
                    m_log.Warn($"[REMOTECONSOLE] SessionCommand JWT Authorization header format failure from '{headers["remote_addr"]}'.");
                    return reply;
                }

                if (m_sigUtil == null)
                {
                    m_log.Warn("[REMOTECONSOLE] SessionCommand JWT Authorization subsystem not initialized. Does your Halcyon.ini contain a SSLCertFile stanza in the [Network] section?");
                    return reply;
                }

                try
                {
                    var token = new JWToken(authHeader.Substring(7), m_sigUtil);

                    // TODO: Make the scope strings come from some central list that can be registered into?
                    if (token.Payload.Scope != "remote-console")
                    {
                        m_log.Warn($"[REMOTECONSOLE] SessionCommand wrong scope JWToken from '{headers["remote_addr"]}'.");
                        return reply;
                    }

                    m_log.Info($"[REMOTECONSOLE] SessionCommand for session '{post["ID"]}' accessed via JWT by '{token.Payload.Username}' from '{headers["remote_addr"]}' with command '{post["COMMAND"]}'.");
                }
                catch (JWTokenException jte)
                {
                    m_log.Error($"[REMOTECONSOLE] Failure with JWToken in SessionCommand from '{headers["remote_addr"]}': {jte}");
                    return reply;
                }
            }
            else
            {
                m_log.Warn($"[REMOTECONSOLE] SessionCommand for session '{post["ID"]}' from '{headers["remote_addr"]}' being accessed without Authorization header!");
            }
            // BUG: Longstanding issue: if someone gets ahold of, or guesses, the ID of another user they can send comamnds to the console.
            // The only way I can think to close this bug is to replacedociate each session with something the user cannot change. Not sure, but maybe the IP address of the connection would work?

            if (post["ID"] == null)
                return reply;

            UUID id;
            if (!UUID.TryParse(post["ID"].ToString(), out id))
                return reply;

            lock (m_Connections)
            {
                if (!m_Connections.ContainsKey(id))
                    return reply;
            }

            if (post["COMMAND"] == null)
                return reply;

            lock (m_InputData)
            {
                m_DataEvent.Set();
                m_InputData.Add(post["COMMAND"].ToString());
            }

            var xmldoc = new XmlDoreplacedent();
            var xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, string.Empty, string.Empty);

            xmldoc.AppendChild(xmlnode);
            var rootElement = xmldoc.CreateElement(string.Empty, "ConsoleSession", string.Empty);

            xmldoc.AppendChild(rootElement);

            var res = xmldoc.CreateElement(string.Empty, "Result", string.Empty);
            res.AppendChild(xmldoc.CreateTextNode("OK"));

            rootElement.AppendChild(res);

            reply["str_response_string"] = xmldoc.InnerXml;
            reply["int_response_code"] = 200;
            reply["content_type"] = "text/xml";
            reply = CheckOrigin(reply);

            return reply;
        }

19 Source : RegionLoaderWebServer.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public RegionInfo[] LoadRegions()
        {
            if (m_configSource == null)
            {
                m_log.Error("[WEBLOADER]: Unable to load configuration source!");
                return null;
            }
            else
            {
                IConfig startupConfig = (IConfig) m_configSource.Configs["Startup"];
                string url = startupConfig.GetString("regionload_webserver_url", String.Empty).Trim();
                if (String.IsNullOrEmpty(url))
                {
                    m_log.Error("[WEBLOADER]: Unable to load webserver URL - URL was empty.");
                    return null;
                }
                else
                {
                    HttpWebRequest webRequest = (HttpWebRequest) WebRequest.Create(url);
                    webRequest.Timeout = 45000; //30 Second Timeout
                    m_log.Debug("[WEBLOADER]: Sending Download Request...");
                    HttpWebResponse webResponse = (HttpWebResponse) webRequest.GetResponse();
                    m_log.Debug("[WEBLOADER]: Downloading Region Information From Remote Server...");
                    StreamReader reader = new StreamReader(webResponse.GetResponseStream());
                    string xmlSource = String.Empty;
                    string tempStr = reader.ReadLine();
                    while (tempStr != null)
                    {
                        xmlSource = xmlSource + tempStr;
                        tempStr = reader.ReadLine();
                    }
                    m_log.Debug("[WEBLOADER]: Done downloading region information from server. Total Bytes: " +
                                xmlSource.Length);
                    XmlDoreplacedent xmlDoc = new XmlDoreplacedent();
                    xmlDoc.LoadXml(xmlSource);
                    if (xmlDoc.FirstChild.Name == "Regions")
                    {
                        RegionInfo[] regionInfos = new RegionInfo[xmlDoc.FirstChild.ChildNodes.Count];
                        int i;
                        for (i = 0; i < xmlDoc.FirstChild.ChildNodes.Count; i++)
                        {
                            m_log.Debug(xmlDoc.FirstChild.ChildNodes[i].OuterXml);
                            regionInfos[i] =
                                new RegionInfo("REGION CONFIG #" + (i + 1), xmlDoc.FirstChild.ChildNodes[i],false,m_configSource);
                        }

                        return regionInfos;
                    }
                    return null;
                }
            }
        }

19 Source : AsyncHttpRequest.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public void SendResponse(byte[] buffer)
        {
            lock (m_lock)
            {
                if (m_requestCompleted)
                {
                    return;
                }
                else
                {
                    if (m_requestTimer != null)
                    {
                        m_requestTimer.Dispose();
                        m_requestTimer = null;
                    }

                    m_requestCompleted = true;
                }
            }

            try
            {
                m_httpServer.SendResponse(this.HttpRequest, this.HttpResponse, null, buffer);
            }
            catch (Exception e)
            {
                m_log.Error("[PollServiceHttpRequest] SendResponse failed. : " + e.ToString());
            }
        }

19 Source : RestSessionService.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public void Handle(string path, Stream request, Stream responseStream,
                           OSHttpRequest httpRequest, OSHttpResponse httpResponse)
        {
            RestSessionObject<TRequest> deserial = default(RestSessionObject<TRequest>);
            bool fail = false;

            using (XmlTextReader xmlReader = new XmlTextReader(request))
            {
                try
                {
                    XmlSerializer deserializer = new XmlSerializer(typeof(RestSessionObject<TRequest>));
                    deserial = (RestSessionObject<TRequest>)deserializer.Deserialize(xmlReader);
                }
                catch (Exception e)
                {
                    m_log.Error("[REST]: Deserialization problem. Ignoring request. " + e);
                    fail = true;
                }
            }

            TResponse response = default(TResponse);
            if (!fail && m_smethod(deserial.SessionID, deserial.AvatarID))
            {
                response = m_method(deserial.Body);
            }

            using (XmlWriter xmlWriter = XmlTextWriter.Create(responseStream))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(TResponse));
                serializer.Serialize(xmlWriter, response);
            }
        }

19 Source : RestSessionService.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public void Handle(string path, Stream request, Stream responseStream,
                           OSHttpRequest httpRequest, OSHttpResponse httpResponse)
        {
            TRequest deserial = default(TRequest);
            bool fail = false;

            using (XmlTextReader xmlReader = new XmlTextReader(request))
            {
                try
                {
                    XmlSerializer deserializer = new XmlSerializer(typeof(TRequest));
                    deserial = (TRequest)deserializer.Deserialize(xmlReader);
                }
                catch (Exception e)
                {
                    m_log.Error("[REST]: Deserialization problem. Ignoring request. " + e);
                    fail = true;
                }
            }

            TResponse response = default(TResponse);
            if (!fail && m_tmethod(httpRequest.RemoteIPEndPoint))
            {
                response = m_method(deserial);
            }

            using (XmlWriter xmlWriter = XmlTextWriter.Create(responseStream))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(TResponse));
                serializer.Serialize(xmlWriter, response);
            }
        }

19 Source : RemoteConsole.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

private Hashtable HandleHttpStartSession(Hashtable request)
        {
            DoExpire();

            var post = DecodePostString(request["body"].ToString());
            var reply = new Hashtable();

            reply["str_response_string"] = string.Empty;
            reply["int_response_code"] = 401;
            reply["content_type"] = "text/plain";

            var headers = (Hashtable)request["headers"];
            if (headers.ContainsKey("Authorization"))
            {
                var authHeader = headers["Authorization"].ToString();
                if (!authHeader.StartsWith("Bearer ", StringComparison.InvariantCultureIgnoreCase))
                {
                    m_log.Warn($"[REMOTECONSOLE] StartSession JWT Authorization header format failure from '{headers["remote_addr"]}'.");
                    return reply;
                }

                if (m_sigUtil == null)
                {
                    m_log.Warn("[REMOTECONSOLE] StartSession JWT Authorization subsystem not initialized. Does your Halcyon.ini contain a SSLCertFile stanza in the [Network] section?");
                    return reply;
                }

                try
                {
                    var token = new JWToken(authHeader.Substring(7), m_sigUtil);

                    // TODO: Make the scope strings come from some central list that can be registered into?
                    if (token.Payload.Scope != "remote-console")
                    {
                        m_log.Warn($"[REMOTECONSOLE] StartSession invalid/expired/wrong scope JWToken from '{headers["remote_addr"]}'.");
                        return reply;
                    }

                    m_log.Info($"[REMOTECONSOLE] StartSession access granted via JWT to '{token.Payload.Username}' from '{headers["remote_addr"]}'.");
                }
                catch (JWTokenException jte)
                {
                    m_log.Error($"[REMOTECONSOLE] Failure with JWToken in StartSession from '{headers["remote_addr"]}': {jte}");
                    return reply;
                }
            }
            else if (request.ContainsKey("USER") && request.ContainsKey("Preplaced"))
            {
                var username = post["USER"].ToString();
                var preplacedword = post["Preplaced"].ToString();

                // Validate the username/preplacedword pair
                if (Util.AuthenticatereplacedystemUser(username, preplacedword) == false)
                {
                    m_log.Warn($"Failure to authenticate for remote administration from {headers["remote_addr"]} as operating system user '{username}'");
                    Thread.Sleep(2000);
                    return reply;
                }

                m_log.Warn($"[REMOTECONSOLE] StartSession access granted via legacy system username and preplacedword to '{username}' from '{headers["remote_addr"]}'.");
            }
            else
            {
                return reply;
            }

            var c = new ConsoleConnection();
            c.last = Environment.TickCount;
            c.lastLineSeen = 0;

            var sessionID = UUID.Random();

            lock (m_Connections)
            {
                m_Connections[sessionID] = c;
            }

            var uri = "/ReadResponses/" + sessionID + "/";
            var handler = new AsyncRequestHandler("POST", uri, AsyncReadResponses);
            m_Server.AddStreamHandler(handler);

            var xmldoc = new XmlDoreplacedent();
            var xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, string.Empty, string.Empty);

            xmldoc.AppendChild(xmlnode);
            var rootElement = xmldoc.CreateElement(string.Empty, "ConsoleSession", string.Empty);

            xmldoc.AppendChild(rootElement);

            var id = xmldoc.CreateElement(string.Empty, "SessionID", string.Empty);
            id.AppendChild(xmldoc.CreateTextNode(sessionID.ToString()));

            rootElement.AppendChild(id);

            var promptEl = xmldoc.CreateElement(string.Empty, "Prompt", string.Empty);
            promptEl.AppendChild(xmldoc.CreateTextNode(DefaultPrompt));

            rootElement.AppendChild(promptEl);

            rootElement.AppendChild(MainConsole.Instance.Commands.GetXml(xmldoc));

            reply["str_response_string"] = xmldoc.InnerXml;
            reply["int_response_code"] = 200;
            reply["content_type"] = "text/xml";
            reply = CheckOrigin(reply);

            return reply;
        }

19 Source : RemoteConsole.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

private Hashtable HandleHttpCloseSession(Hashtable request)
        {
            DoExpire();

            var post = DecodePostString(request["body"].ToString());
            var reply = new Hashtable();

            reply["str_response_string"] = string.Empty;
            reply["int_response_code"] = 404;
            reply["content_type"] = "text/plain";

            JWToken token = null;
            var headers = (Hashtable)request["headers"];
            if (headers.ContainsKey("Authorization"))
            {
                var authHeader = headers["Authorization"].ToString();
                if (!authHeader.StartsWith("Bearer ", StringComparison.InvariantCultureIgnoreCase))
                {
                    m_log.Warn($"[REMOTECONSOLE] CloseSession JWT Authorization header format failure from '{headers["remote_addr"]}'.");
                    return reply;
                }

                if (m_sigUtil == null)
                {
                    m_log.Warn("[REMOTECONSOLE] CloseSession JWT Authorization subsystem not initialized. Does your Halcyon.ini contain a SSLCertFile stanza in the [Network] section?");
                    return reply;
                }

                try
                {
                    token = new JWToken(authHeader.Substring(7), m_sigUtil);

                    // TODO: Make the scope strings come from some central list that can be registered into?
                    if (token.Payload.Scope != "remote-console")
                    {
                        m_log.Warn($"[REMOTECONSOLE] CloseSession wrong scope JWToken from '{headers["remote_addr"]}'.");
                        return reply;
                    }

                    m_log.Info($"[REMOTECONSOLE] CloseSession for session '{post["ID"]}' accessed via JWT by '{token.Payload.Username}' from '{headers["remote_addr"]}'.");
                }
                catch (JWTokenException jte)
                {
                    m_log.Error($"[REMOTECONSOLE] Failure with JWToken in CloseSession from '{headers["remote_addr"]}': {jte}");
                    return reply;
                }
            }
            else
            {
                m_log.Warn($"[REMOTECONSOLE] CloseSession for session '{post["ID"]}' from '{headers["remote_addr"]}' being accessed without Authorization header!");
            }
            // BUG: Longstanding issue: if someone gets ahold of, or guesses, the ID and/or JWT of another user they can close the console.
            // The only way I can think to close this bug is to replacedociate each session with something the user cannot change. Not sure, but maybe the IP address of the connection would work?

            if (post["ID"] == null)
                return reply;

            UUID id;
            if (!UUID.TryParse(post["ID"].ToString(), out id))
                return reply;

            lock (m_Connections)
            {
                if (m_Connections.ContainsKey(id))
                {
                    ConsoleConnection connection = m_Connections[id];
                    m_Connections.Remove(id);
                    CloseConnection(id);
                    if (connection.request != null)
                    {
                        AsyncHttpRequest req = connection.request;
                        connection.request = null;
                        req.SendResponse(ProcessEvents(req));
                    }
                }
            }

            var xmldoc = new XmlDoreplacedent();
            var xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, string.Empty, string.Empty);

            xmldoc.AppendChild(xmlnode);
            var rootElement = xmldoc.CreateElement(string.Empty, "ConsoleSession", string.Empty);

            xmldoc.AppendChild(rootElement);

            var res = xmldoc.CreateElement(string.Empty, "Result", string.Empty);
            res.AppendChild(xmldoc.CreateTextNode("OK"));

            rootElement.AppendChild(res);

            reply["str_response_string"] = xmldoc.InnerXml;
            reply["int_response_code"] = 200;
            reply["content_type"] = "text/xml";
            reply = CheckOrigin(reply);

            m_log.Info($"[REMOTECONSOLE] CloseSession successful for user '{token?.Payload.Username}' with session '{id}' from '{headers["remote_addr"]}'.");

            return reply;
        }

19 Source : RemoteConsole.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public void AsyncReadResponses(IHttpServer server, string path, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
        {
            int pos1 = path.IndexOf("/", StringComparison.InvariantCulture);               // /ReadResponses
            int pos2 = path.IndexOf("/", pos1 + 1, StringComparison.InvariantCulture);     // /ReadResponses/
            int pos3 = path.IndexOf("/", pos2 + 1, StringComparison.InvariantCulture);     // /ReadResponses/<UUID>/
            int len = pos3 - pos2 - 1;
            string uri_tmp = path.Substring(pos2 + 1, len);

            var authHeader = httpRequest.Headers.Get("Authorization");
            if (authHeader != null)
            {
                if (!authHeader.StartsWith("Bearer ", StringComparison.InvariantCultureIgnoreCase))
                {
                    m_log.Warn($"[REMOTECONSOLE] ReadResponses JWT Authorization header format failure from '{httpRequest.RemoteIPEndPoint}'.");
                    return;
                }

                if (m_sigUtil == null)
                {
                    m_log.Warn("[REMOTECONSOLE] ReadResponses JWT Authorization subsystem not initialized. Does your Halcyon.ini contain a SSLCertFile stanza in the [Network] section?");
                    return;
                }

                try
                {
                    var token = new JWToken(authHeader.Substring(7), m_sigUtil);

                    // TODO: Make the scope strings come from some central list that can be registered into?
                    if (token.Payload.Scope != "remote-console")
                    {
                        m_log.Warn($"[REMOTECONSOLE] ReadResponses invalid/expired/wrong scope JWToken from '{httpRequest.RemoteIPEndPoint}'.");
                        return;
                    }

                    m_log.Info($"[REMOTECONSOLE] ReadResponses for session '{uri_tmp}' accessed via JWT by '{token.Payload.Username}' from '{httpRequest.RemoteIPEndPoint}'.");
                }
                catch (JWTokenException jte)
                {
                    m_log.Error($"[REMOTECONSOLE] Failure with JWToken in ReadResponses from '{httpRequest.RemoteIPEndPoint}': {jte}");
                    return;
                }
            }
            else
            {
                m_log.Warn($"[REMOTECONSOLE] ReadResponses for session '{uri_tmp}' from '{httpRequest.RemoteIPEndPoint}' being accessed without Authorization header!");
            }
            // BUG: Longstanding issue: if someone gets ahold of, or guesses, the ID of another user they can send comamnds to the console.
            // The only way I can think to close this bug is to replacedociate each session with something the user cannot change. Not sure, but maybe the IP address of the connection would work?

            UUID sessionID;
            if (UUID.TryParse(uri_tmp, out sessionID) == false)
                return;

            // Create the new request
            var newRequest = new AsyncHttpRequest(server, httpRequest, httpResponse, sessionID, TimeoutHandler, 60 * 1000);
            AsyncHttpRequest currentRequest = null;

            lock (m_Connections)
            {
                ConsoleConnection connection = null;
                m_Connections.TryGetValue(sessionID, out connection);
                if (connection == null)
                    return;

                currentRequest = connection.request;
                connection.request = newRequest;
            }

            // If there was a request already posted, signal it.
            if (currentRequest != null)
            {
                currentRequest.SendResponse(ProcessEvents(currentRequest));
            }
        }

19 Source : PluginLoader.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public void Load()
        {
            foreach (string ext in extpoints)
            {
                log.Info("[PLUGINS]: Loading extension point " + ext);

                if (constraints.ContainsKey(ext))
                {
                    IPluginConstraint cons = constraints[ext];
                    if (cons.Apply(ext))
                        log.Error("[PLUGINS]: " + ext + " failed constraint: " + cons.Message);
                }

                IPluginFilter filter = null;

                if (filters.ContainsKey(ext))
                    filter = filters[ext];

                List<T> loadedPlugins = new List<T>();
                foreach (PluginExtensionNode node in AddinManager.GetExtensionNodes(ext))
                {
                    log.Info("[PLUGINS]: Trying plugin " + node.Path);

                    if ((filter != null) && (filter.Apply(node) == false))
                        continue;

                    T plugin = (T)node.CreateInstance();
                    loadedPlugins.Add(plugin);
                }

                // We do Initialize() in a second loop after CreateInstance
                // So that modules who need init before others can do it
                // Example: Script Engine Component System needs to load its components before RegionLoader starts
                foreach (T plugin in loadedPlugins)
                {
                    Initializer.Initialize(plugin);
                    Plugins.Add(plugin);
                }
            }
        }

19 Source : Main.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

private void registerWithUserServer()
        {
        retry:

            if (m_userServerModule.registerWithUserServer())
            {
                m_log.Info("[SERVER]: Starting HTTP process");
                m_httpServer = new BaseHttpServer(Cfg.HttpPort, null);

                m_httpServer.AddXmlRPCHandler("login_to_simulator", msgsvc.UserLoggedOn);
                m_httpServer.AddXmlRPCHandler("logout_of_simulator", msgsvc.UserLoggedOff);
                m_httpServer.AddXmlRPCHandler("get_presence_info_bulk", msgsvc.GetPresenceInfoBulk);
                m_httpServer.AddXmlRPCHandler("process_region_shutdown", msgsvc.ProcessRegionShutdown);
                m_httpServer.AddXmlRPCHandler("agent_location", msgsvc.AgentLocation);
                m_httpServer.AddXmlRPCHandler("agent_leaving", msgsvc.AgentLeaving);
                m_httpServer.AddXmlRPCHandler("region_startup", m_regionModule.RegionStartup);
                m_httpServer.AddXmlRPCHandler("region_shutdown", m_regionModule.RegionShutdown);

                // New Style
                m_httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("login_to_simulator"), msgsvc.UserLoggedOn));
                m_httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("logout_of_simulator"), msgsvc.UserLoggedOff));
                m_httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("get_presence_info_bulk"), msgsvc.GetPresenceInfoBulk));
                m_httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("process_region_shutdown"), msgsvc.ProcessRegionShutdown));
                m_httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("agent_location"), msgsvc.AgentLocation));
                m_httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("agent_leaving"), msgsvc.AgentLeaving));
                m_httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("region_startup"), m_regionModule.RegionStartup));
                m_httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("region_shutdown"), m_regionModule.RegionShutdown));

                m_radmin = new InWorldz.RemoteAdmin.RemoteAdmin(Cfg.SSLPublicCertFile);
                m_radmin.AddCommand("MessagingService", "Shutdown", MessagingServerShutdownHandler);
                m_radmin.AddHandler(m_httpServer);

                m_httpServer.Start();

                m_log.Info("[SERVER]: Userserver registration was successful");
            }
            else
            {
                m_log.Error("[STARTUP]: Unable to connect to User Server, retrying in 5 seconds");
                System.Threading.Thread.Sleep(5000);
                goto retry;
            }

        }

19 Source : UserServerCommandModule.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public void RunCommand(string module, string[] cmd)
        {
            List<string> args = new List<string>(cmd);
            string command = cmd[0];

            args.RemoveAt(0);

            string[] cmdparams = args.ToArray();

            switch (command)
            {
                case "create":
                    do_create(cmdparams);
                    break;

                case "reset":
                    Reset(cmdparams);
                    break;


                case "test-inventory":
                    //  RestObjectPosterResponse<List<InventoryFolderBase>> requester = new RestObjectPosterResponse<List<InventoryFolderBase>>();
                    // requester.ReturnResponseVal = TestResponse;
                    // requester.BeginPostObject<UUID>(m_userManager._config.InventoryUrl + "RootFolders/", m_lastCreatedUser);
                    SynchronousRestObjectPoster.BeginPostObject<UUID, List<InventoryFolderBase>>(
                        "POST", m_cfg.InventoryUrl + "RootFolders/", m_lastCreatedUser);
                    break;

                case "logoff-user":
                    if (cmdparams.Length >= 3)
                    {
                        string firstname = cmdparams[0];
                        string lastname = cmdparams[1];
                        string message = String.Empty;

                        for (int i = 2; i < cmdparams.Length; i++)
                            message += " " + cmdparams[i];

                        UserProfileData theUser = null;
                        try
                        {
                            theUser = m_loginService.GetTheUser(firstname, lastname);
                        }
                        catch (Exception)
                        {
                            m_log.Error("[LOGOFF]: Error getting user data from the database.");
                        }

                        if (theUser != null)
                        {
                            if (theUser.CurrentAgent != null)
                            {
                                if (theUser.CurrentAgent.AgentOnline)
                                {
                                    m_log.Info("[LOGOFF]: Logging off requested user!");
                                    m_loginService.LogOffUser(theUser, message);

                                    theUser.CurrentAgent.AgentOnline = false;
                                    theUser.CurrentAgent.LogoutTime = Util.UnixTimeSinceEpoch();

                                    m_loginService.CommitAgent(ref theUser);
                                }
                                else
                                {
                                    m_log.Info(
                                        "[LOGOFF]: User Doesn't appear to be online, sending the logoff message anyway.");
                                    m_loginService.LogOffUser(theUser, message);

                                    theUser.CurrentAgent.AgentOnline = false;

                                    m_loginService.CommitAgent(ref theUser);
                                }
                            }
                            else
                            {
                                m_log.Error(
                                    "[LOGOFF]: Unable to logoff-user.  User doesn't have an agent record so I can't find the simulator to notify");
                            }
                        }
                        else
                        {
                            m_log.Info("[LOGOFF]: User doesn't exist in the database");
                        }
                    }
                    else
                    {
                        m_log.Error(
                            "[LOGOFF]: Invalid amount of parameters.  logoff-user takes at least three.  Firstname, Lastname, and message");
                    }

                    break;
            }
        }

19 Source : UserLoginService.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public override void LogOffUser(UserProfileData theUser, string message)
        {
            RegionProfileData SimInfo;
            try
            {
                SimInfo = m_regionProfileService.RequestSimProfileData(
                    theUser.CurrentAgent.Handle, m_config.GridServerURL,
                    m_config.GridSendKey, m_config.GridRecvKey);

                if (SimInfo == null)
                {
                    m_log.Error("[GRID]: Region user was in isn't currently logged in");
                    return;
                }
            }
            catch (Exception)
            {
                m_log.Error("[GRID]: Unable to look up region to log user off");
                return;
            }

            // Prepare notification
            Hashtable SimParams = new Hashtable();
            SimParams["agent_id"] = theUser.ID.ToString();
            SimParams["region_secret"] = theUser.CurrentAgent.SecureSessionID.ToString();
            SimParams["region_secret2"] = SimInfo.regionSecret;
            //m_log.Info(SimInfo.regionSecret);
            SimParams["regionhandle"] = theUser.CurrentAgent.Handle.ToString();
            SimParams["message"] = message;
            ArrayList SendParams = new ArrayList();
            SendParams.Add(SimParams);

            m_log.InfoFormat(
                "[replacedUMED CRASH]: Telling region {0} @ {1},{2} ({3}) that their agent is dead: {4}",
                SimInfo.regionName, SimInfo.regionLocX, SimInfo.regionLocY, SimInfo.httpServerURI,
                theUser.FirstName + " " + theUser.SurName);

            try
            {
                string methodName = "logoff_user";
                XmlRpcRequest GridReq = new XmlRpcRequest(methodName, SendParams);
                XmlRpcResponse GridResp = GridReq.Send(Util.XmlRpcRequestURI(SimInfo.httpServerURI, methodName), 6000);

                if (GridResp.IsFault)
                {
                    m_log.ErrorFormat(
                        "[LOGIN]: XMLRPC request for {0} failed, fault code: {1}, reason: {2}, This is likely an old region revision.",
                        SimInfo.httpServerURI, GridResp.FaultCode, GridResp.FaultString);
                }
            }
            catch (Exception)
            {
                m_log.Error("[LOGIN]: Error telling region to logout user!");
            }

            // Prepare notification
            SimParams = new Hashtable();
            SimParams["agent_id"] = theUser.ID.ToString();
            SimParams["region_secret"] = SimInfo.regionSecret;
            //m_log.Info(SimInfo.regionSecret);
            SimParams["regionhandle"] = theUser.CurrentAgent.Handle.ToString();
            SimParams["message"] = message;
            SendParams = new ArrayList();
            SendParams.Add(SimParams);

            m_log.InfoFormat(
                "[replacedUMED CRASH]: Telling region {0} @ {1},{2} ({3}) that their agent is dead: {4}",
                SimInfo.regionName, SimInfo.regionLocX, SimInfo.regionLocY, SimInfo.httpServerURI,
                theUser.FirstName + " " + theUser.SurName);

            try
            {
                string methodName = "logoff_user";
                XmlRpcRequest GridReq = new XmlRpcRequest(methodName, SendParams);
                XmlRpcResponse GridResp = GridReq.Send(Util.XmlRpcRequestURI(SimInfo.httpServerURI, methodName), 6000);

                if (GridResp.IsFault)
                {
                    m_log.ErrorFormat(
                        "[LOGIN]: XMLRPC request for {0} failed, fault code: {1}, reason: {2}, This is likely an old region revision.",
                        SimInfo.httpServerURI, GridResp.FaultCode, GridResp.FaultString);
                }
            }
            catch (Exception)
            {
                m_log.Error("[LOGIN]: Error telling region to logout user!");
            }
            //base.LogOffUser(theUser);
        }

19 Source : UserManager.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public XmlRpcResponse XmlRpcResponseXmlRPCUpdateUserProfile(XmlRpcRequest request, IPEndPoint remoteClient)
        {
            // Check IP Endpoint Access
            if (!TrustManager.Instance.IsTrustedPeer(remoteClient))
                return (Util.CreateTrustManagerAccessDeniedResponse()); 
            
            m_log.Debug("[UserManager]: Got request to update user profile.");
            XmlRpcResponse response = new XmlRpcResponse();
            Hashtable requestData = (Hashtable)request.Params[0];
            Hashtable responseData = new Hashtable();

            if (!requestData.Contains("avatar_uuid"))
            {
                return Util.CreateUnknownUserErrorResponse();
            }

            UUID UserUUID = new UUID((string)requestData["avatar_uuid"]);
            UserProfileData userProfile = m_userDataBaseService.GetUserProfile(UserUUID);
            if (null == userProfile)
            {
                return Util.CreateUnknownUserErrorResponse();
            }
            // don't know how yet.
            if (requestData.Contains("AllowPublish"))
            {
            }
            if (requestData.Contains("FLImageID"))
            {
                userProfile.FirstLifeImage = new UUID((string)requestData["FLImageID"]);
            }
            if (requestData.Contains("ImageID"))
            {
                userProfile.Image = new UUID((string)requestData["ImageID"]);
            }
            // dont' know how yet
            if (requestData.Contains("MaturePublish"))
            {
            }
            if (requestData.Contains("AboutText"))
            {
                userProfile.AboutText = (string)requestData["AboutText"];
            }
            if (requestData.Contains("FLAboutText"))
            {
                userProfile.FirstLifeAboutText = (string)requestData["FLAboutText"];
            }

            if (requestData.Contains("profileURL"))
            {
                userProfile.ProfileURL = (string)requestData["profileURL"];
            }

            if (requestData.Contains("home_region"))
            {
                try
                {
                    userProfile.HomeRegion = Convert.ToUInt64((string)requestData["home_region"]);
                }
                catch (ArgumentException)
                {
                    m_log.Error("[PROFILE]:Failed to set home region, Invalid Argument");
                }
                catch (FormatException)
                {
                    m_log.Error("[PROFILE]:Failed to set home region, Invalid Format");
                }
                catch (OverflowException)
                {
                    m_log.Error("[PROFILE]:Failed to set home region, Value was too large");
                }
            }
            if (requestData.Contains("home_region_id"))
            {
                UUID regionID;
                UUID.TryParse((string)requestData["home_region_id"], out regionID);
                userProfile.HomeRegionID = regionID;
            }
            if (requestData.Contains("home_pos_x"))
            {
                try
                {
                    userProfile.HomeLocationX = (float)Convert.ToDouble((string)requestData["home_pos_x"]);
                }
                catch (InvalidCastException)
                {
                    m_log.Error("[PROFILE]:Failed to set home postion x");
                }
            }
            if (requestData.Contains("home_pos_y"))
            {
                try
                {
                    userProfile.HomeLocationY = (float)Convert.ToDouble((string)requestData["home_pos_y"]);
                }
                catch (InvalidCastException)
                {
                    m_log.Error("[PROFILE]:Failed to set home postion y");
                }
            }
            if (requestData.Contains("home_pos_z"))
            {
                try
                {
                    userProfile.HomeLocationZ = (float)Convert.ToDouble((string)requestData["home_pos_z"]);
                }
                catch (InvalidCastException)
                {
                    m_log.Error("[PROFILE]:Failed to set home postion z");
                }
            }
            if (requestData.Contains("home_look_x"))
            {
                try
                {
                    userProfile.HomeLookAtX = (float)Convert.ToDouble((string)requestData["home_look_x"]);
                }
                catch (InvalidCastException)
                {
                    m_log.Error("[PROFILE]:Failed to set home lookat x");
                }
            }
            if (requestData.Contains("home_look_y"))
            {
                try
                {
                    userProfile.HomeLookAtY = (float)Convert.ToDouble((string)requestData["home_look_y"]);
                }
                catch (InvalidCastException)
                {
                    m_log.Error("[PROFILE]:Failed to set home lookat y");
                }
            }
            if (requestData.Contains("home_look_z"))
            {
                try
                {
                    userProfile.HomeLookAtZ = (float)Convert.ToDouble((string)requestData["home_look_z"]);
                }
                catch (InvalidCastException)
                {
                    m_log.Error("[PROFILE]:Failed to set home lookat z");
                }
            }
            if (requestData.Contains("user_flags"))
            {
                try
                {
                    userProfile.UserFlags = Convert.ToInt32((string)requestData["user_flags"]);
                }
                catch (InvalidCastException)
                {
                    m_log.Error("[PROFILE]:Failed to set user flags");
                }
            }
            if (requestData.Contains("god_level"))
            {
                try
                {
                    userProfile.GodLevel = Convert.ToInt32((string)requestData["god_level"]);
                }
                catch (InvalidCastException)
                {
                    m_log.Error("[PROFILE]:Failed to set god level");
                }
            }
            if (requestData.Contains("custom_type"))
            {
                try
                {
                    userProfile.CustomType = (string)requestData["custom_type"];
                }
                catch (InvalidCastException)
                {
                    m_log.Error("[PROFILE]:Failed to set custom type");
                }
            }
            if (requestData.Contains("partner"))
            {
                try
                {
                    userProfile.Partner = new UUID((string)requestData["partner"]);
                }
                catch (InvalidCastException)
                {
                    m_log.Error("[PROFILE]:Failed to set partner");
                }
            }
            else
            {
                userProfile.Partner = UUID.Zero;
            }

            // call plugin!
            bool ret = m_userDataBaseService.UpdateUserProfile(userProfile);
            responseData["returnString"] = ret.ToString();
            response.Value = responseData;
            return response;
        }

19 Source : ConfigurationMember.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public void performConfigurationRetrieve()
        {
            if (cE > 1)
                m_log.Error("[CONFIG]: READING CONFIGURATION COUT: " + cE.ToString());


            configurationPlugin = LoadConfigDll(configurationPluginFilename);
            configurationOptions.Clear();
            if (loadFunction == null)
            {
                m_log.Error("[CONFIG]: Load Function for '" + configurationDescription +
                            "' is null. Refusing to run configuration.");
                return;
            }

            if (resultFunction == null)
            {
                m_log.Error("[CONFIG]: Result Function for '" + configurationDescription +
                            "' is null. Refusing to run configuration.");
                return;
            }

            //m_log.Debug("[CONFIG]: Calling Configuration Load Function...");
            loadFunction();

            if (configurationOptions.Count <= 0)
            {
                m_log.Error("[CONFIG]: No configuration options were specified for '" + configurationOptions +
                            "'. Refusing to continue configuration.");
                return;
            }

            bool useFile = true;
            if (configurationPlugin == null)
            {
                m_log.Error("[CONFIG]: Configuration Plugin NOT LOADED!");
                return;
            }

            if (!String.IsNullOrWhiteSpace(configurationFilename))
            {
                configurationPlugin.SetFileName(configurationFilename);
                try
                {
                    configurationPlugin.LoadData();
                    useFile = true;
                }
                catch (XmlException e)
                {
                    m_log.WarnFormat("[CONFIG]: Not using {0}: {1}",
                            configurationFilename,
                            e.Message.ToString());
                    //m_log.Error("Error loading " + configurationFilename + ": " + e.ToString());
                    useFile = false;
                }
            }
            else
            {
                if (configurationFromXMLNode != null)
                {
                    m_log.Info("[CONFIG]: Loading from XML Node, will not save to the file");
                    configurationPlugin.LoadDataFromString(configurationFromXMLNode.OuterXml);
                }

                m_log.Info("[CONFIG]: XML Configuration Filename is not valid; will not save to the file.");
                useFile = false;
            }

            foreach (ConfigurationOption configOption in configurationOptions)
            {
                bool convertSuccess = false;
                object return_result = null;
                string errorMessage = String.Empty;
                bool ignoreNextFromConfig = false;
                while (convertSuccess == false)
                {
                    string console_result = String.Empty;
                    string attribute = null;
                    if (useFile || configurationFromXMLNode != null)
                    {
                        if (!ignoreNextFromConfig)
                        {
                            attribute = configurationPlugin.GetAttribute(configOption.configurationKey);
                        }
                        else
                        {
                            ignoreNextFromConfig = false;
                        }
                    }

                    if (attribute == null)
                    {
                        if (configOption.configurationUseDefaultNoPrompt || useConsoleToPromptOnError == false)
                        {
                            console_result = configOption.configurationDefault;
                        }
                        else
                        {
                            if ((configOption.shouldIBeAsked != null &&
                                 configOption.shouldIBeAsked(configOption.configurationKey)) ||
                                configOption.shouldIBeAsked == null)
                            {
                                if (!String.IsNullOrWhiteSpace(configurationDescription))
                                {
                                    console_result =
                                        MainConsole.Instance.CmdPrompt(
                                            configurationDescription + ": " + configOption.configurationQuestion,
                                            configOption.configurationDefault);
                                }
                                else
                                {
                                    console_result =
                                        MainConsole.Instance.CmdPrompt(configOption.configurationQuestion,
                                                                       configOption.configurationDefault);
                                }
                            }
                            else
                            {
                                //Dont Ask! Just use default
                                console_result = configOption.configurationDefault;
                            }
                        }
                    }
                    else
                    {
                        console_result = attribute;
                    }

                    // If the first character of a multicharacter string is a "$", replacedume it's the name of an environment variable and subsreplacedute with the value of that variable.
                    if (console_result.StartsWith("$", StringComparison.InvariantCulture) && console_result.Length > 1)
                    {
                        // Using a second $ to be an escape character was experimented with, but that would require modifying the write process to re-apply the escape character.  Over-all escapes seem too fragile, and the below code handles it cleanly.  If the admin wants to use a value that collides with an environment variable, then the admin can make sure to unset it first.
                        var env_var_key = console_result.Substring(1);
                        var env_var_value = Environment.GetEnvironmentVariable(env_var_key);
                        if (env_var_value != null)
                        {
                            // Log the use of an environment variable just in case someone didn't expect it.
                            m_log.Info($"[CONFIG]: Parameter [{configOption.configurationKey}] started with '$'. Value replaced with environment variable '{env_var_key}' value '{env_var_value}'.");
                            console_result = env_var_value;
                        }
                        else
                        {
                            // Unless there is no such variable, in which case just move on with the original and let the user know that happened.
                            m_log.Warn($"[CONFIG]: Parameter [{configOption.configurationKey}] started with '$', however there was no environment variable found with the name '{env_var_key}'.");
                        }
                    }

                    switch (configOption.configurationType)
                    {
                        case ConfigurationOption.ConfigurationTypes.TYPE_STRING:
                            return_result = console_result;
                            convertSuccess = true;
                            break;
                        case ConfigurationOption.ConfigurationTypes.TYPE_STRING_NOT_EMPTY:
                            if (!String.IsNullOrEmpty(console_result))
                            {
                                return_result = console_result;
                                convertSuccess = true;
                            }
                            errorMessage = "a string that is not empty";
                            break;
                        case ConfigurationOption.ConfigurationTypes.TYPE_BOOLEAN:
                            bool boolResult;
                            if (Boolean.TryParse(console_result, out boolResult))
                            {
                                convertSuccess = true;
                                return_result = boolResult;
                            }
                            errorMessage = "'true' or 'false' (Boolean)";
                            break;
                        case ConfigurationOption.ConfigurationTypes.TYPE_BYTE:
                            byte byteResult;
                            if (Byte.TryParse(console_result, out byteResult))
                            {
                                convertSuccess = true;
                                return_result = byteResult;
                            }
                            errorMessage = "a byte (Byte)";
                            break;
                        case ConfigurationOption.ConfigurationTypes.TYPE_CHARACTER:
                            char charResult;
                            if (Char.TryParse(console_result, out charResult))
                            {
                                convertSuccess = true;
                                return_result = charResult;
                            }
                            errorMessage = "a character (Char)";
                            break;
                        case ConfigurationOption.ConfigurationTypes.TYPE_INT16:
                            short shortResult;
                            if (Int16.TryParse(console_result, out shortResult))
                            {
                                convertSuccess = true;
                                return_result = shortResult;
                            }
                            errorMessage = "a signed 32 bit integer (short)";
                            break;
                        case ConfigurationOption.ConfigurationTypes.TYPE_INT32:
                            int intResult;
                            if (Int32.TryParse(console_result, out intResult))
                            {
                                convertSuccess = true;
                                return_result = intResult;
                            }
                            errorMessage = "a signed 32 bit integer (int)";
                            break;
                        case ConfigurationOption.ConfigurationTypes.TYPE_INT64:
                            long longResult;
                            if (Int64.TryParse(console_result, out longResult))
                            {
                                convertSuccess = true;
                                return_result = longResult;
                            }
                            errorMessage = "a signed 32 bit integer (long)";
                            break;
                        case ConfigurationOption.ConfigurationTypes.TYPE_IP_ADDRESS:
                            IPAddress ipAddressResult;
                            if (IPAddress.TryParse(console_result, out ipAddressResult))
                            {
                                convertSuccess = true;
                                return_result = ipAddressResult;
                            }
                            errorMessage = "an IP Address (IPAddress)";
                            break;
                        case ConfigurationOption.ConfigurationTypes.TYPE_UUID:
                            UUID uuidResult;
                            if (UUID.TryParse(console_result, out uuidResult))
                            {
                                convertSuccess = true;
                                return_result = uuidResult;
                            }
                            errorMessage = "a UUID (UUID)";
                            break;
                        case ConfigurationOption.ConfigurationTypes.TYPE_UUID_NULL_FREE:
                            UUID uuidResult2;
                            if (UUID.TryParse(console_result, out uuidResult2))
                            {
                                convertSuccess = true;

                                if (uuidResult2 == UUID.Zero)
                                    uuidResult2 = UUID.Random();

                                return_result = uuidResult2;
                            }
                            errorMessage = "a non-null UUID (UUID)";
                            break;
                        case ConfigurationOption.ConfigurationTypes.TYPE_Vector3:
                            Vector3 vectorResult;
                            if (Vector3.TryParse(console_result, out vectorResult))
                            {
                                convertSuccess = true;
                                return_result = vectorResult;
                            }
                            errorMessage = "a vector (Vector3)";
                            break;
                        case ConfigurationOption.ConfigurationTypes.TYPE_UINT16:
                            ushort ushortResult;
                            if (UInt16.TryParse(console_result, out ushortResult))
                            {
                                convertSuccess = true;
                                return_result = ushortResult;
                            }
                            errorMessage = "an unsigned 16 bit integer (ushort)";
                            break;
                        case ConfigurationOption.ConfigurationTypes.TYPE_UINT32:
                            uint uintResult;
                            if (UInt32.TryParse(console_result, out uintResult))
                            {
                                convertSuccess = true;
                                return_result = uintResult;
                            }
                            errorMessage = "an unsigned 32 bit integer (uint)";
                            break;
                        case ConfigurationOption.ConfigurationTypes.TYPE_UINT64:
                            ulong ulongResult;
                            if (UInt64.TryParse(console_result, out ulongResult))
                            {
                                convertSuccess = true;
                                return_result = ulongResult;
                            }
                            errorMessage = "an unsigned 64 bit integer (ulong)";
                            break;
                        case ConfigurationOption.ConfigurationTypes.TYPE_FLOAT:
                            float floatResult;
                            if (
                                float.TryParse(console_result, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, Culture.NumberFormatInfo,
                                               out floatResult))
                            {
                                convertSuccess = true;
                                return_result = floatResult;
                            }
                            errorMessage = "a single-precision floating point number (float)";
                            break;
                        case ConfigurationOption.ConfigurationTypes.TYPE_DOUBLE:
                            double doubleResult;
                            if (
                                Double.TryParse(console_result, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, Culture.NumberFormatInfo,
                                                out doubleResult))
                            {
                                convertSuccess = true;
                                return_result = doubleResult;
                            }
                            errorMessage = "an double-precision floating point number (double)";
                            break;
                    }

                    if (convertSuccess)
                    {
                        if (useFile)
                        {
                            configurationPlugin.SetAttribute(configOption.configurationKey, console_result);
                        }

                        if (!resultFunction(configOption.configurationKey, return_result))
                        {
                            m_log.Info(
                                "[CONFIG]: The handler for the last configuration option denied that input, please try again.");
                            convertSuccess = false;
                            ignoreNextFromConfig = true;
                        }
                    }
                    else
                    {
                        if (configOption.configurationUseDefaultNoPrompt)
                        {
                            m_log.Error(string.Format(
                                            "[CONFIG]: [{3}]:[{1}] is not valid default for parameter [{0}].\nThe configuration result must be parsable to {2}.\n",
                                            configOption.configurationKey, console_result, errorMessage,
                                            configurationFilename));
                            convertSuccess = true;
                        }
                        else
                        {
                            m_log.Warn(string.Format(
                                           "[CONFIG]: [{3}]:[{1}] is not a valid value [{0}].\nThe configuration result must be parsable to {2}.\n",
                                           configOption.configurationKey, console_result, errorMessage,
                                           configurationFilename));
                            ignoreNextFromConfig = true;
                        }
                    }
                }
            }

            if (useFile)
            {
                configurationPlugin.Commit();
                configurationPlugin.Close();
            }
        }

19 Source : PluginLoader.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

private void on_addinloaderror_(object sender, AddinErrorEventArgs args)
        {
            if (args.Exception == null)
                log.Error ("[PLUGINS]: Plugin Error: "
                        + args.Message);
            else
                log.Error ("[PLUGINS]: Plugin Error: "
                        + args.Exception.Message + "\n"
                        + args.Exception.StackTrace);
        }

19 Source : MessageService.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

private GetUserFriendListResult GetUserFriendList2(UUID friendlistowner, out Dictionary<UUID, FriendLisreplacedem> results)
        {
            Util.SlowTimeReporter slowCheck = new Util.SlowTimeReporter("[FRIEND]: GetUserFriendList2 for " + friendlistowner.ToString() + " took", TimeSpan.FromMilliseconds(1000));
            try
            {
                Dictionary<UUID, FriendLisreplacedem> EMPTY_RESULTS = new Dictionary<UUID, FriendLisreplacedem>();
                string uri = m_cfg.UserServerURL + "/get_user_friend_list2/";
                HttpWebRequest friendListRequest = (HttpWebRequest)WebRequest.Create(uri);
                friendListRequest.Method = "POST";
                friendListRequest.ContentType = "application/octet-stream";
                friendListRequest.Timeout = FriendsListRequest.TIMEOUT;

                // Default results are empty
                results = EMPTY_RESULTS;

//                m_log.WarnFormat("[FRIEND]: Msg/GetUserFriendList2({0}) using URI '{1}'", friendlistowner, uri);
                FriendsListRequest request = FriendsListRequest.FromUUID(friendlistowner);
                try
                {
                    // send the Post
                    Stream os = friendListRequest.GetRequestStream();
                    ProtoBuf.Serializer.Serialize(os, request);
                    os.Flush();
                    os.Close();
                }
                catch (Exception e)
                {
                    m_log.InfoFormat("[FRIEND]: GetUserFriendList2 call failed {0}", e);
                    return GetUserFriendListResult.ERROR;
                }

                // Let's wait for the response
                try
                {
                    HttpWebResponse webResponse = (HttpWebResponse)friendListRequest.GetResponse();
                    if (webResponse == null)
                    {
                        m_log.Error("[FRIEND]: Null reply on GetUserFriendList2 put");
                        return GetUserFriendListResult.ERROR;
                    }
                    //this will happen during the initial rollout and tells us we need to fall back to the old method
                    if (webResponse.StatusCode == HttpStatusCode.NotFound)
                    {
                        m_log.WarnFormat("[FRIEND]: NotFound on reply of GetUserFriendList2");
                        return GetUserFriendListResult.NOTIMPLEMENTED;
                    }
                    if (webResponse.StatusCode != HttpStatusCode.OK)
                    {
                        m_log.ErrorFormat("[FRIEND]: Error on reply of GetUserFriendList2 {0}", friendlistowner);
                        return GetUserFriendListResult.ERROR;
                    }

                    // We have a reply.
                    FriendsListResponse response = ProtoBuf.Serializer.Deserialize<FriendsListResponse>(webResponse.GetResponseStream());
                    if (response == null)
                    {
                        m_log.ErrorFormat("[FRIEND]: Could not deserialize reply of GetUserFriendList2");
                        return GetUserFriendListResult.ERROR;
                    }

                    // Request/response succeeded.
                    results = response.ToDict();
                    // m_log.InfoFormat("[FRIEND]: Returning {0} friends for {1}", results.Count, friendlistowner);
                    return GetUserFriendListResult.OK;
                }
                catch (WebException ex)
                {
                    HttpWebResponse webResponse = ex.Response as HttpWebResponse;
                    if (webResponse != null)
                    {
                        //this will happen during the initial rollout and tells us we need to fall back to the 
                        //old method
                        if (webResponse.StatusCode == HttpStatusCode.NotFound)
                        {
                            m_log.InfoFormat("[FRIEND]: NotFound exception on reply of GetUserFriendList2");
                            return GetUserFriendListResult.NOTIMPLEMENTED;
                        }
                    }
                    m_log.ErrorFormat("[FRIEND]: exception on reply of GetUserFriendList2 for {0}", request.FriendListOwner);
                }
                return GetUserFriendListResult.ERROR;
            }
            finally
            {
                slowCheck.Complete();
            }
        }

19 Source : ClientStackManager.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public IClientNetworkServer CreateServer(
            IPAddress _listenIP, ref uint port, int proxyPortOffset, bool allow_alternate_port, IConfigSource configSource,
            IreplacedetCache replacedetCache)
        {            
            if (plugin != null)
            {
                IClientNetworkServer server =
                    (IClientNetworkServer)Activator.CreateInstance(pluginreplacedembly.GetType(plugin.ToString()));
                
                server.Initialize(
                    _listenIP, ref port, proxyPortOffset, allow_alternate_port, 
                    configSource);
                
                return server;
            }
            
            m_log.Error("[CLIENTSTACK]: Couldn't initialize a new server");
            return null;
        }

19 Source : RegionApplicationBase.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

protected override void StartupSpecific()
        {
            m_storageManager = CreateStorageManager();

            m_clientStackManager = CreateClientStackManager();

            Initialize();

            // Main HTTP server first
            m_httpServer = new BaseHttpServer(m_httpServerPort, null);
            m_httpServer.HostName = m_networkServersInfo.HostName; 
            MainServer.AddHttpServer(m_httpServer);

            m_log.InfoFormat("[REGION]: Starting HTTP server on {0}:{1}", m_httpServer.HostName, m_httpServerPort);
            m_httpServer.Start();

            // If specified configure an ssl server for use as well
            // you need a Cert Request/Signed pair installed in the MY store with the CN specified
            if (m_networkServersInfo.HttpUsesSSL)
            {
                if (m_networkServersInfo.HttpListenerPort == m_networkServersInfo.httpSSLPort)
                {
                    m_log.Error("[HTTP]: HTTP Server config failed.   HTTP Server and HTTPS server must be on different ports");
                }
                else
                {
                    /// XXX Should also support specifying an IP Address
                    BaseHttpServer secureServer = new BaseHttpServer(m_networkServersInfo.httpSSLPort, null);
                    secureServer.HostName = m_networkServersInfo.HostName;

                    if (m_networkServersInfo.HttpSSLCN != null)
                        secureServer.SetSecureParams(m_networkServersInfo.HttpSSLCN, m_networkServersInfo.sslProtocol);
                    else
                        secureServer.SetSecureParams(m_networkServersInfo.HttpSSLCert, m_networkServersInfo.HttpSSLPreplacedword, m_networkServersInfo.sslProtocol);

                    MainServer.AddHttpServer(secureServer);

                    m_log.Info("[REGION]: Starting HTTPS server");
                    secureServer.Start();
                }
            }

            base.StartupSpecific();
        }

19 Source : LocalBackEndServices.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public RegionCommsListener RegisterRegion(RegionInfo regionInfo)
        {
            //m_log.Debug("CommsManager - Region " + regionInfo.RegionHandle + " , " + regionInfo.RegionLocX + " , "+ regionInfo.RegionLocY +" is registering");
            if (!m_regions.ContainsKey(regionInfo.RegionHandle))
            {
                //m_log.Debug("CommsManager - Adding Region " + regionInfo.RegionHandle);
                m_regions.Add(regionInfo.RegionHandle, regionInfo);

                RegionCommsListener regionHost = new RegionCommsListener();
                if (m_regionListeners.ContainsKey(regionInfo.RegionHandle))
                {
                    m_log.Error("[INTERREGION STANDALONE]: " +
                                "Error:Region registered twice as an Events listener for Interregion Communications but not as a listed region.  " +
                                "In Standalone mode this will cause BIG issues.  In grid mode, it means a region went down and came back up.");
                    m_regionListeners.Remove(regionInfo.RegionHandle);
                }
                m_regionListeners.Add(regionInfo.RegionHandle, regionHost);

                return regionHost;
            }
            else
            {
                // Already in our list, so the region went dead and restarted.
                // don't replace the old regioninfo..    this might be a locking issue..  however we need to
                // remove it and let it add normally below or we get extremely strange and intermittant
                // connectivity errors.
                // Don't change this line below to 'm_regions[regionInfo.RegionHandle] = regionInfo' unless you
                // *REALLY* know what you are doing here.
                m_regions[regionInfo.RegionHandle] = regionInfo;

                m_log.Warn("[INTERREGION STANDALONE]: Region registered twice. Region went down and came back up.");

                RegionCommsListener regionHost = new RegionCommsListener();
                if (m_regionListeners.ContainsKey(regionInfo.RegionHandle))
                {
                    m_regionListeners.Remove(regionInfo.RegionHandle);
                }
                m_regionListeners.Add(regionInfo.RegionHandle, regionHost);

                return regionHost;
            }
        }

19 Source : OGS1GridServices.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public bool DeregisterRegion(RegionInfo regionInfo)
        {
            Hashtable GridParams = new Hashtable();

            GridParams["UUID"] = regionInfo.RegionID.ToString();

            // Package into an XMLRPC Request
            ArrayList SendParams = new ArrayList();
            SendParams.Add(GridParams);

            // Send Request
            string methodName = "simulator_after_region_moved";
            XmlRpcRequest GridReq = new XmlRpcRequest(methodName, SendParams);
            XmlRpcResponse GridResp = null;
            
            try
            {            
                GridResp = GridReq.Send(Util.XmlRpcRequestURI(serversInfo.GridURL, methodName), 10000);
            }
            catch (Exception e)
            {
                Exception e2
                    = new Exception(
                        String.Format(
                            "Unable to deregister region with grid at {0}. Grid service not running?", 
                            serversInfo.GridURL),
                        e);

                throw e2;
            }
        
            Hashtable GridRespData = (Hashtable) GridResp.Value;

            // Hashtable griddatahash = GridRespData;

            // Process Response
            if (GridRespData != null && GridRespData.ContainsKey("error"))
            {
                string errorstring = (string)GridRespData["error"];
                m_log.Error("Unable to connect to grid: " + errorstring);
                return false;
            }

            return m_localBackend.DeregisterRegion(regionInfo);
        }

19 Source : OGS1GridServices.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public RegionInfo RequestClosestRegion(string regionName)
        {
            if (m_useRemoteRegionCache)
            {
                lock (m_remoteRegionInfoCache)
                {
                    foreach (RegionInfoCacheEntry ri in m_remoteRegionInfoCache.Values)
                    {
                        if (ri.Exists && ri.Info != null)
                            if (ri.Info.RegionName == regionName)
                                return ri.Info; // .Info is not valid if Exists is false
                    }
                }
            }

            RegionInfo regionInfo = null;
            try
            {
                Hashtable requestData = new Hashtable();
                requestData["region_name_search"] = regionName;
                requestData["authkey"] = serversInfo.GridSendKey;
                ArrayList SendParams = new ArrayList();
                SendParams.Add(requestData);

                string methodName = "simulator_data_request";
                XmlRpcRequest GridReq = new XmlRpcRequest(methodName, SendParams);
                XmlRpcResponse GridResp = GridReq.Send(Util.XmlRpcRequestURI(serversInfo.GridURL, methodName), 3000);

                Hashtable responseData = (Hashtable) GridResp.Value;

                if (responseData.ContainsKey("error"))
                {
                    m_log.ErrorFormat("[OGS1 GRID SERVICES]: Error received from grid server: ", responseData["error"]);
#if NEEDS_REPLACEMENT
                    lock (m_remoteRegionInfoCache)
                    {
                        m_remoteRegionInfoCache[regionInfo.RegionHandle] = new RegionInfoCacheEntry
                        {
                            CachedTime = DateTime.Now,
                            Info = null,
                            Exists = false
                        };
                    }
#endif

                    return null;
                }

                regionInfo = buildRegionInfo(responseData, String.Empty);

                if (m_useRemoteRegionCache)
                {
                    lock (m_remoteRegionInfoCache)
                    {
                        m_remoteRegionInfoCache[regionInfo.RegionHandle] = new RegionInfoCacheEntry {
                            CachedTime = DateTime.Now,
                            Exists = true,
                            Info = regionInfo
                        };
                    }
                }
            }
            catch
            {
                m_log.Error("[OGS1 GRID SERVICES]: " +
                            "Region lookup failed for: " + regionName +
                            " - Is the GridServer down?");
            }

            return regionInfo;
        }

19 Source : J2KDecoderFileCache.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public bool TryLoadCacheForreplacedet(UUID replacedetId, out OpenJPEG.J2KLayerInfo[] Layers)
        {
            // Check if it's cached in memory
            if (m_decodedCache.TryGetValue(replacedetId, out Layers))
            {
                return true;
            }
            
            // Look for it in the file cache
            string filename = String.Format("{0}/{1}", m_cacheDecodeFolder, FileNameFromreplacedetId(replacedetId));
            Layers = new OpenJPEG.J2KLayerInfo[0];

            if ((File.Exists(filename) == false) || (enabled == false))
                return false;

            string readResult = String.Empty;

            try
            {
                using (FileStream fsCachefile = new FileStream(filename, FileMode.Open))
                {

                    using (StreamReader sr = new StreamReader(fsCachefile))
                    {
                        readResult = sr.ReadToEnd();

                        sr.Close();
                    }
                }

            }
            catch (IOException ioe)
            {
                if (ioe is PathTooLongException)
                {
                    m_log.Error(
                        "[J2KDecodeCache]: Cache Read failed. Path is too long.");
                }
                else if (ioe is DirectoryNotFoundException)
                {
                    m_log.Error(
                        "[J2KDecodeCache]: Cache Read failed. Cache Directory does not exist!");
                    enabled = false;
                }
                else
                {
                    m_log.Error(
                        "[J2KDecodeCache]: Cache Read failed. IO Exception.");
                }
                return false;

            }
            catch (UnauthorizedAccessException)
            {
                m_log.Error(
                    "[J2KDecodeCache]: Cache Read failed. UnauthorizedAccessException Exception. Do you have the proper permissions on this file?");
                return false;
            }
            catch (ArgumentException ae)
            {
                if (ae is ArgumentNullException)
                {
                    m_log.Error(
                        "[J2KDecodeCache]: Cache Read failed. No Filename provided");
                }
                else
                {
                    m_log.Error(
                   "[J2KDecodeCache]: Cache Read failed. Filname was invalid");
                }
                return false;
            }
            catch (NotSupportedException)
            {
                m_log.Error(
                    "[J2KDecodeCache]: Cache Read failed, not supported. Cache disabled!");
                enabled = false;

                return false;
            }
            catch (Exception e)
            {
                m_log.ErrorFormat(
                    "[J2KDecodeCache]: Cache Read failed, unknown exception.  Error: {0}",
                    e.ToString());
                return false;
            }

            string[] lines = readResult.Split('\n');

            if (lines.Length <= 0)
                return false;

            Layers = new OpenJPEG.J2KLayerInfo[lines.Length];
            
            for (int i = 0; i < lines.Length; i++)
            {
                string[] elements = lines[i].Split('|');
                if (elements.Length == 3)
                {
                    int element1, element2;

                    try
                    {
                        element1 = Convert.ToInt32(elements[0]);
                        element2 = Convert.ToInt32(elements[1]);
                    }
                    catch (FormatException)
                    {
                        m_log.WarnFormat("[J2KDecodeCache]: Cache Read failed with ErrorConvert for {0}", replacedetId);
                        Layers = new OpenJPEG.J2KLayerInfo[0];
                        return false;
                    }

                    Layers[i] = new OpenJPEG.J2KLayerInfo();
                    Layers[i].Start = element1;
                    Layers[i].End = element2;

                }
                else
                {
                    // reading failed
                    m_log.WarnFormat("[J2KDecodeCache]: Cache Read failed for {0}", replacedetId);
                    Layers = new OpenJPEG.J2KLayerInfo[0];
                    return false;
                }
            }

            return true;
        }

19 Source : J2KDecoderFileCache.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public void Createj2KCacheFolder(string pFolder)
        {
            try
            {
                Directory.CreateDirectory(pFolder);
            }
            catch (IOException ioe)
            {
                if (ioe is PathTooLongException)
                {
                    m_log.Error(
                        "[J2KDecodeCache]: Cache Directory does not exist and create failed because the path to the cache folder is too long.  Cache disabled!");
                }
                else if (ioe is DirectoryNotFoundException)
                {
                    m_log.Error(
                        "[J2KDecodeCache]: Cache Directory does not exist and create failed because the supplied base of the directory folder does not exist.  Cache disabled!");
                }
                else
                {
                    m_log.Error(
                        "[J2KDecodeCache]: Cache Directory does not exist and create failed because of an IO Exception.  Cache disabled!");
                }
                enabled = false;

            }
            catch (UnauthorizedAccessException)
            {
                m_log.Error(
                    "[J2KDecodeCache]: Cache Directory does not exist and create failed because of an UnauthorizedAccessException Exception.  Cache disabled!");
                enabled = false;
            }
            catch (ArgumentException ae)
            {
                if (ae is ArgumentNullException)
                {
                    m_log.Error(
                        "[J2KDecodeCache]: Cache Directory does not exist and create failed because the folder provided is invalid!  Cache disabled!");
                }
                else
                {
                    m_log.Error(
                   "[J2KDecodeCache]: Cache Directory does not exist and create failed because no cache folder was provided!  Cache disabled!");
                }
                enabled = false;
            }
            catch (NotSupportedException)
            {
                m_log.Error(
                    "[J2KDecodeCache]: Cache Directory does not exist and create failed because it's not supported.  Cache disabled!");
                enabled = false;
            }
            catch (Exception e)
            {
                m_log.ErrorFormat(
                    "[J2KDecodeCache]: Cache Directory does not exist and create failed because of an unknown exception.  Cache disabled!  Error: {0}",
                    e.ToString());
                enabled = false;
            }
        }

19 Source : MessageRegionModule.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public RegionProfileData RequestRegionInfo(ulong regionHandle)
        {
            RegionProfileData regionProfile = null;
            try
            {
                Hashtable requestData = new Hashtable();
                requestData["region_handle"] = regionHandle.ToString();
                requestData["authkey"] = m_cfg.GridSendKey;

                ArrayList SendParams = new ArrayList();
                SendParams.Add(requestData);

                string methodName = "simulator_data_request";
                XmlRpcRequest GridReq = new XmlRpcRequest(methodName, SendParams);
                XmlRpcResponse GridResp = GridReq.Send(Util.XmlRpcRequestURI(m_cfg.GridServerURL, methodName), 3000);

                Hashtable responseData = (Hashtable)GridResp.Value;

                if (responseData.ContainsKey("error"))
                {
                    m_log.Error("[GRID]: error received from grid server" + responseData["error"]);
                    return null;
                }

                uint regX = Convert.ToUInt32((string)responseData["region_locx"]);
                uint regY = Convert.ToUInt32((string)responseData["region_locy"]);

                regionProfile = new RegionProfileData();
                regionProfile.serverHostName = (string)responseData["sim_ip"];
                regionProfile.serverPort = Convert.ToUInt16((string)responseData["sim_port"]);
                regionProfile.httpPort = (uint)Convert.ToInt32((string)responseData["http_port"]);
                
                regionProfile.regionHandle = Utils.UIntsToLong((regX * Constants.RegionSize), (regY * Constants.RegionSize));
                regionProfile.regionLocX = regX;
                regionProfile.regionLocY = regY;

                regionProfile.remotingPort = Convert.ToUInt32((string)responseData["remoting_port"]);
                regionProfile.UUID = new UUID((string)responseData["region_UUID"]);
                regionProfile.regionName = (string)responseData["region_name"];

                if (requestData.ContainsKey("product"))
                    regionProfile.product = (ProductRulesUse)Convert.ToInt32(requestData["product"]);
                else
                    regionProfile.product = ProductRulesUse.UnknownUse;

                if (requestData.ContainsKey("outside_ip"))
                    regionProfile.OutsideIP = (string)responseData["outside_ip"];

            }
            catch (WebException e)
            {
                m_log.ErrorFormat("[GRID]: Region lookup failed for {0}: {1} ", regionHandle.ToString(), e.Message);
            }

            return regionProfile;
        }

19 Source : OGS1GridServices.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public RegionInfo RequestNeighbourInfo(ulong regionHandle)
        {
            RegionInfo regionInfo = m_localBackend.RequestNeighbourInfo(regionHandle);

            if (regionInfo != null)
            {
                return regionInfo;
            }

            if (m_useRemoteRegionCache)
            {
                lock (m_remoteRegionInfoCache)
                {
                    RegionInfoCacheEntry entry;
                    if (m_remoteRegionInfoCache.TryGetValue(regionHandle, out entry))
                    {
                        if (DateTime.Now - entry.CachedTime < TimeSpan.FromMinutes(15.0))
                        {
                            if (entry.Exists)
                            {
                                return entry.Info;
                            }
                            else
                            {
                                return null;
                            }
                        }
                        else
                        {
                            m_remoteRegionInfoCache.Remove(regionHandle);
                        }
                    }
                }
            }

            try
            {
                Hashtable requestData = new Hashtable();
                requestData["region_handle"] = regionHandle.ToString();
                requestData["authkey"] = serversInfo.GridSendKey;
                ArrayList SendParams = new ArrayList();
                SendParams.Add(requestData);

                string methodName = "simulator_data_request";
                XmlRpcRequest GridReq = new XmlRpcRequest(methodName, SendParams);
                XmlRpcResponse GridResp = GridReq.Send(Util.XmlRpcRequestURI(serversInfo.GridURL, methodName), 3000);

                Hashtable responseData = (Hashtable) GridResp.Value;

                if (responseData.ContainsKey("error"))
                {
                    m_log.Error("[OGS1 GRID SERVICES]: Error received from grid server: " + responseData["error"]);

                    if (m_useRemoteRegionCache)
                    {
                        lock (m_remoteRegionInfoCache)
                        {
                            if (!m_remoteRegionInfoCache.ContainsKey(regionHandle))
                            {
                                RegionInfoCacheEntry entry = new RegionInfoCacheEntry
                                {
                                    CachedTime = DateTime.Now,
                                    Info = null,
                                    Exists = false
                                };

                                m_remoteRegionInfoCache[regionHandle] = entry;
                            }
                        }
                    }

                    return null;
                }

                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"]);
                }

                string outsideIp = null;
                if (responseData.ContainsKey("outside_ip"))
                    outsideIp = (string)responseData["outside_ip"];

                //IPEndPoint neighbourInternalEndPoint = new IPEndPoint(IPAddress.Parse(internalIpStr), (int) port);
                regionInfo = RegionInfo.Create(regionID, regionName, regX, regY, externalHostName, httpPort, simPort, remotingPort, outsideIp);

                if (requestData.ContainsKey("product"))
                    regionInfo.Product = (ProductRulesUse)Convert.ToInt32(requestData["product"]);
                
                if (m_useRemoteRegionCache)
                {
                    lock (m_remoteRegionInfoCache)
                    {
                        if (!m_remoteRegionInfoCache.ContainsKey(regionHandle))
                        {
                            RegionInfoCacheEntry entry = new RegionInfoCacheEntry
                            {
                                CachedTime = DateTime.Now,
                                Info = regionInfo, 
                                Exists = true
                            };

                            m_remoteRegionInfoCache[regionHandle] = entry;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                m_log.Error("[OGS1 GRID SERVICES]: " +
                            "Region lookup failed for: " + regionHandle.ToString() +
                            " - Is the GridServer down?" + e.ToString());
                return null;
            }
            

            return regionInfo;
        }

19 Source : OGS1GridServices.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

private Hashtable MapBlockQuery(int minX, int minY, int maxX, int maxY)
        {
            Hashtable param = new Hashtable();
            param["xmin"] = minX;
            param["ymin"] = minY;
            param["xmax"] = maxX;
            param["ymax"] = maxY;
            IList parameters = new ArrayList();
            parameters.Add(param);
            
            try
            {
                string methodName = "map_block";
                XmlRpcRequest req = new XmlRpcRequest(methodName, parameters);
                XmlRpcResponse resp = req.Send(Util.XmlRpcRequestURI(serversInfo.GridURL, methodName), 10000);
                Hashtable respData = (Hashtable)resp.Value;
                if (respData != null && respData.Contains("faultCode"))
                {
                    m_log.ErrorFormat("[OGS1 GRID SERVICES]: Got an error while contacting GridServer: {0}", respData["faultString"]);
                    return null;
                }

                return respData;
            }
            catch (Exception e)
            {
                m_log.Error("MapBlockQuery XMLRPC failure: " + e);
                return new Hashtable();
            }
        }

19 Source : InstantMessageModule.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public void PostInitialize()
        {
            if (!m_enabled)
                return;
            
            m_TransferModule =
                m_scenes[0].RequestModuleInterface<IMessageTransferModule>();

            if (m_TransferModule == null)
                m_log.Error("[INSTANT MESSAGE]: No message transfer module, "+
                "IM will not work!");
        }

19 Source : InventoryArchiverModule.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

protected void HandleLoadInvConsoleCommand(string module, string[] cmdparams)
        {
            if (cmdparams.Length < 5)
            {
                m_log.Error(
                    "[INVENTORY ARCHIVER]: usage is load iar <first name> <last name> <inventory path> [<load file path>]");
                return;
            }

            string firstName = cmdparams[2];
            string lastName = cmdparams[3];
            string invPath = cmdparams[4];
            string loadPath = (cmdparams.Length > 5 ? cmdparams[5] : DEFAULT_INV_BACKUP_FILENAME);

            m_log.InfoFormat(
                "[INVENTORY ARCHIVER]: Loading archive {0} to inventory path {1} for {2} {3}",
                loadPath, invPath, firstName, lastName);
            
            DearchiveInventory(firstName, lastName, invPath, loadPath);
            
            m_log.InfoFormat(
                "[INVENTORY ARCHIVER]: Loaded archive {0} for {1} {2}",
                loadPath, firstName, lastName);
        }

19 Source : InventoryTransferModule.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public void Initialize(Scene scene, IConfigSource config)
        {
            if (config.Configs["Messaging"] != null)
            {
                // Allow disabling this module in config
                //
                if (config.Configs["Messaging"].GetString(
                        "InventoryTransferModule", "InventoryTransferModule") !=
                        "InventoryTransferModule")
                    return;
            }

            if (!m_Scenelist.Contains(scene))
            {
                if (m_Scenelist.Count == 0)
                {
                    m_TransferModule = scene.RequestModuleInterface<IMessageTransferModule>();
                    if (m_TransferModule == null)
                        m_log.Error("[INVENTORY TRANSFER]: No Message transfer module found, transfers will be local only");
                }

                m_Scenelist.Add(scene);

                scene.RegisterModuleInterface<IInventoryTransferModule>(this);

                scene.EventManager.OnNewClient += OnNewClient;
                scene.EventManager.OnClientClosed += ClientLoggedOut;
                scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage;

                m_TransferModule = scene.RequestModuleInterface<IMessageTransferModule>();
            }
        }

19 Source : LureModule.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public void PostInitialize()
        {
            m_TransferModule =
                m_scenes[0].RequestModuleInterface<IMessageTransferModule>();

            if (m_TransferModule == null)
                m_log.Error("[INSTANT MESSAGE]: No message transfer module, "+
                "lures will not work!");
        }

19 Source : XMPPHTTPService.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public override byte[] Handle(string path, Stream request,
                                      OSHttpRequest httpRequest, OSHttpResponse httpResponse)
        {
            string param = GetParam(path);
            byte[] result = new byte[] {};
            try
            {
                string[] p = param.Split(new char[] {'/', '?', '&'}, StringSplitOptions.RemoveEmptyEntries);

                if (p.Length > 0)
                {
                    UUID replacedetID = UUID.Zero;

                    if (!UUID.TryParse(p[0], out replacedetID))
                    {
                        m_log.InfoFormat(
                            "[REST]: GET:/presence ignoring request with malformed UUID {0}", p[0]);
                        return result;
                    }

                }
            }
            catch (Exception e)
            {
                m_log.Error(e.ToString());
            }
            return result;
        }

19 Source : JWTAuthenticator.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public string RESTRequestToken(string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
        {
            httpResponse.ContentType = "application/json";

            if (m_authGateway == null)
            {
                m_log.Error("[JWTAUTH] Hit a bug check: the JWT gatway is not initialized... Why?");
                return JWTAuthErrors.BadAuthGateway;
            }

            if (httpRequest.ContentType != "application/json")
            {
                return JWTAuthErrors.BadJsonRead;
            }

            if (httpRequest.ContentLength <= 1)
            {
                return JWTAuthErrors.BadJsonRead;
            }

            if (!m_levelsAllowedPerScope.ContainsKey(param))
            {
                return JWTAuthErrors.BadScope;
            }

            var username = string.Empty;
            var preplacedword = string.Empty;

            try
            {
                var data = JsonMapper.ToObject(request);

                username = data["username"].ToString().Trim();
                preplacedword = data["preplacedword"].ToString();
            }
            catch (Exception)
            {
                return JWTAuthErrors.BadJsonRead;
            }

            var payload = new PayloadOptions();
            payload.Exp = DateTime.UtcNow.AddDays(1);
            payload.Scope = param;
            payload.Username = username;

            var nameSplit = Regex.Replace(username.ToLower(), @"[\s]+", " ").Split(' ');
            var firstname = nameSplit[0];
            var lastname = nameSplit.Length > 1 ? nameSplit[1] : "resident";

            try
            {
                var response = new Dictionary<string, string>
                {
                    {"token", m_authGateway.Authenticate(firstname, lastname, preplacedword, m_levelsAllowedPerScope[param], payload).ToString()}
                };

                return JsonMapper.ToJson(response);
            }
            catch (AuthenticationException ae)
            {
                m_log.Warn($"[JWTAUTH] Failed attempt to get token from {httpRequest.RemoteIPEndPoint} for user '{username}'. Error: {ae.Cause}");
                return JWTAuthErrors.AuthFailed(ae.Cause.ToString());
            }
        }

19 Source : J2KDecoderModule.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

private bool DoJ2KDecode(UUID replacedetID, byte[] j2kdata, out OpenJPEG.J2KLayerInfo[] layers)
        {
            int DecodeTime = 0;
            DecodeTime = Environment.TickCount;
            bool decodedSuccessfully = true;
            
            layers = new OpenJPEG.J2KLayerInfo[0]; // Dummy result for if it fails.  Informs that there's only full quality

            try
            {

                replacedetTexture texture = new replacedetTexture(replacedetID, j2kdata);
                bool sane = false;

                if (texture.DecodeLayerBoundaries())
                {
                    sane = true;

                    // Sanity check all of the layers
                    for (int i = 0; i < texture.LayerInfo.Length; i++)
                    {
                        if (texture.LayerInfo[i].End > texture.replacedetData.Length)
                        {
                            sane = false;
                            break;
                        }
                    }
                }

                if (sane)
                {
                    m_log.InfoFormat("[J2KDecoderModule]: {0} Decode Time: {1}", Environment.TickCount - DecodeTime, replacedetID); 
                    layers = texture.LayerInfo;
                }
                else
                {
                    m_log.Warn("[J2KDecoderModule]: Failed to decode layer data for texture " + replacedetID + ", guessing sane defaults");
                    decodedSuccessfully = false;
                    
                    // Layer decoding completely failed. Guess at sane defaults for the layer boundaries
                    layers = CreateDefaultLayers(j2kdata.Length);
                }
                
                fCache.SaveCacheForreplacedet(replacedetID, layers); 
                texture = null; // dereference and dispose of ManagedImage
            }
            catch (DllNotFoundException)
            {
                m_log.Error(
                    "[J2KDecoderModule]: OpenJpeg is not installed properly. Decoding disabled!  This will slow down texture performance!  Often times this is because of an old version of GLIBC.  You must have version 2.4 or above!");
                OpenJpegFail = true;
                decodedSuccessfully = false;
            }
            catch (Exception ex)
            {
                m_log.WarnFormat(
                    "[J2KDecoderModule]: JPEG2000 texture decoding threw an exception for {0}, {1}",
                    replacedetID, ex);
                decodedSuccessfully = false;
            }

            return (decodedSuccessfully);
        }

19 Source : CoreAssetCache.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public void Initialize(IConfigSource source)
        {
            IConfig moduleConfig = source.Configs["Modules"];
            if (moduleConfig != null)
            {
                string name = moduleConfig.GetString("replacedetCaching", "CorereplacedetCache");
                if (name == Name)
                {
                    IConfig replacedetConfig = source.Configs["replacedetCache"];
                    if (replacedetConfig == null)
                    {
                        m_log.Error("[replacedET CACHE]: replacedetCache missing from Halcyon.ini");
                        return;
                    }

                    m_Enabled = true;

                    m_log.Info("[replacedET CACHE]: Core replacedet cache enabled");

                    m_Cache.Size = replacedetConfig.GetInt("CacheBuckets", 32768);
                }
            }
        }

19 Source : AvatarFactoryModule.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public void AvatarIsWearing(Object sender, AvatarWearingArgs e)
        {
            IClientAPI clientView = (IClientAPI)sender;
            ScenePresence avatar = m_scene.GetScenePresence(clientView.AgentId);
            
            if (avatar == null) 
            {
                m_log.Error("[APPEARANCE]: Avatar is child agent, ignoring AvatarIsWearing event");
                return;
            }

            CachedUserInfo profile = m_scene.CommsManager.UserService.GetUserDetails(clientView.AgentId);
            if (profile != null)
            {
                AvatarAppearance appearance = avatar.Appearance;

                // we need to clean out the existing textures
                appearance.Texture = AvatarAppearance.GetDefaultTexture();

                List<AvatarWearable> wearables = new List<AvatarWearable>();
                lock (_currentlyWaitingCOFBuilds)
                {
                    //Check to see whether the client can manage itself
                    if (_cofSyncEnabled && !_viewer2Users.Contains(clientView.AgentId))
                    {
                        foreach (AvatarWearingArgs.Wearable wear in e.NowWearing)
                        {
                            wearables.Add(new AvatarWearable(wear.Type, wear.ItemID, UUID.Zero));
                            AvatarWearable oldWearable = appearance.GetWearableOfType(wear.Type);
                            if (wear.ItemID != UUID.Zero)
                            {
                                if (oldWearable == null || oldWearable.ItemID == UUID.Zero || wear.ItemID != oldWearable.ItemID)
                                {
                                    bool add = false;
                                    Dictionary<UUID, BuildCOF> waitingCOFs = new Dictionary<UUID, BuildCOF>();
                                    if ((add = !_currentlyWaitingCOFBuilds.TryGetValue(clientView.AgentId, out waitingCOFs)))
                                        waitingCOFs = new Dictionary<UUID, BuildCOF>();
                                    //Make sure that the new item is added
                                    if (waitingCOFs.ContainsKey(wear.ItemID))
                                    {
                                        BuildCOF cof = waitingCOFs[wear.ItemID];
                                        cof.SetWearableToLookFor(wear.ItemID, m_scene, clientView.AgentId, true);
                                        if (cof.Finished())
                                            waitingCOFs.Remove(wear.ItemID);
                                    }
                                    else
                                    {
                                        BuildCOF cof = new BuildCOF(ClearWaitingCOF);
                                        cof.SetWearableToLookFor(wear.ItemID, m_scene, clientView.AgentId, true);
                                        waitingCOFs.Add(wear.ItemID, cof);
                                    }
                                    if (add)
                                        _currentlyWaitingCOFBuilds.Add(clientView.AgentId, waitingCOFs);
                                }
                                if (oldWearable != null && oldWearable.ItemID != UUID.Zero && wear.ItemID != oldWearable.ItemID)
                                {
                                    bool add = false;
                                    Dictionary<UUID, BuildCOF> waitingCOFs = new Dictionary<UUID, BuildCOF>();
                                    if ((add = !_currentlyWaitingCOFBuilds.TryGetValue(clientView.AgentId, out waitingCOFs)))
                                        waitingCOFs = new Dictionary<UUID, BuildCOF>();
                                    //Check for removal of old item
                                    if (waitingCOFs.ContainsKey(oldWearable.ItemID))
                                    {
                                        BuildCOF cof = waitingCOFs[oldWearable.ItemID];
                                        cof.SetWearableToLookFor(oldWearable.ItemID, m_scene, clientView.AgentId, false);
                                        if (cof.Finished())
                                            waitingCOFs.Remove(oldWearable.ItemID);
                                    }
                                    else
                                    {
                                        BuildCOF cof = new BuildCOF(ClearWaitingCOF);
                                        cof.SetWearableToLookFor(oldWearable.ItemID, m_scene, clientView.AgentId, false);
                                        waitingCOFs.Add(oldWearable.ItemID, cof);
                                    }
                                    if (add)
                                        _currentlyWaitingCOFBuilds.Add(clientView.AgentId, waitingCOFs);
                                }
                            }
                            else if (oldWearable != null && oldWearable.ItemID != UUID.Zero)
                            {
                                bool add = false;
                                Dictionary<UUID, BuildCOF> waitingCOFs = new Dictionary<UUID, BuildCOF>();
                                if ((add = !_currentlyWaitingCOFBuilds.TryGetValue(clientView.AgentId, out waitingCOFs)))
                                    waitingCOFs = new Dictionary<UUID, BuildCOF>();
                                //Remove the item if it was just removed
                                if (waitingCOFs.ContainsKey(oldWearable.ItemID))
                                {
                                    BuildCOF cof = waitingCOFs[oldWearable.ItemID];
                                    cof.SetWearableToLookFor(oldWearable.ItemID, m_scene, clientView.AgentId, false);
                                    if (cof.Finished())
                                        waitingCOFs.Remove(oldWearable.ItemID);
                                }
                                else
                                {
                                    BuildCOF cof = new BuildCOF(ClearWaitingCOF);
                                    cof.SetWearableToLookFor(oldWearable.ItemID, m_scene, clientView.AgentId, false);
                                    waitingCOFs.Add(oldWearable.ItemID, cof);
                                }
                                if (add)
                                    _currentlyWaitingCOFBuilds.Add(clientView.AgentId, waitingCOFs);
                            }
                        }
                    }
                    else
                    {
                        foreach (AvatarWearingArgs.Wearable wear in e.NowWearing)
                            wearables.Add(new AvatarWearable(wear.Type, wear.ItemID, UUID.Zero));
                    }
                }
                // Wearables are a stack. The entries we have represent the current "top" stack state.  Apply them

                SetAppearancereplacedets(profile, ref wearables, clientView);
                avatar.Appearance.SetWearables(wearables);
                this.UpdateDatabase(clientView.AgentId, avatar.Appearance, null, null);
            }
            else
            {
                m_log.WarnFormat("[APPEARANCE]: Cannot set wearables for {0}, no user profile found", clientView.Name);
            }
        }

19 Source : InventoryArchiverModule.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

protected void HandleSaveInvConsoleCommand(string module, string[] cmdparams)
        {
            if (cmdparams.Length < 5)
            {
                m_log.Error(
                    "[INVENTORY ARCHIVER]: usage is save iar <first name> <last name> <inventory path> [<save file path>]");
                return;
            }

            string firstName = cmdparams[2];
            string lastName = cmdparams[3];
            string invPath = cmdparams[4];
            string savePath = (cmdparams.Length > 5 ? cmdparams[5] : DEFAULT_INV_BACKUP_FILENAME);

            m_log.InfoFormat(
                "[INVENTORY ARCHIVER]: Saving archive {0} from inventory path {1} for {2} {3}",
                savePath, invPath, firstName, lastName);
            
            ArchiveInventory(firstName, lastName, invPath, savePath);                      
        }

19 Source : GetEmailModule.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

private Email QueryNextEmail(ISimpleDB db, UUID uuid, string sender, string subject)
        {
            Email msg = new Email();

            try
            {
                Dictionary<string, object> parms = new Dictionary<string, object>();
                string query = "SELECT * FROM emailmessages WHERE uuid = ?uuid";
                parms.Add("?uuid", uuid);
                if (!String.IsNullOrEmpty(sender))
                {
                    query += " AND from = ?from";
                    parms.Add("?from", sender);
                }
                if (!String.IsNullOrEmpty(subject))
                {
                    query += " AND subject = ?subject";
                    parms.Add("?subject", subject);
                }
                query += " ORDER BY sent LIMIT 1";

                List<Dictionary<string, string>> results = db.QueryWithResults(query, parms);
                if (results.Count != 1)
                    return null;

                uint ID = Convert.ToUInt32(results[0]["ID"]);
                uint unixtime = Convert.ToUInt32(results[0]["sent"]);
                msg.time = unixtime.ToString();     // Note: email event is doreplacedented as string form of *UTC* unix time
                msg.sender = results[0]["from"];
                msg.subject = results[0]["subject"];
                msg.message = results[0]["body"];

                // This one has been handled, remove it from those queued in the DB.
                DeleteMessage(db, ID);
            }
            catch (Exception e)
            {
                m_log.Error("[InboundEmail]: Exception during database call to store message: " + e.Message);
                m_log.Error(e.StackTrace);
                return null;
            }

            msg.numLeft = (int)QueryEmailCount(db, uuid);
            return msg;
        }

19 Source : GetEmailModule.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public Email GetNextEmail(UUID objectID, string sender, string subject)
        {
            try
            {
                using (ISimpleDB db = _connectionFactory.GetConnection())
                {
                    UUID regionUUID;
                    SceneObjectPart part = findPrim(objectID, out regionUUID);
                    if (part != null)
                    {
                        UpdateRegistration(db, objectID, regionUUID);
                        return QueryNextEmail(db, objectID, sender, subject);
                    }
                }
            }
            catch (Exception e)
            {
                m_log.Error("[InboundEmail]: Exception during database call to check messages: " + e.Message);
                m_log.Error(e.StackTrace);
            }
            m_log.Error("[InboundEmail]: Next email not available. Part " + objectID.ToString() + " not found.");
            return null;
        }

19 Source : OfflineMessageModule.cs
with BSD 3-Clause "New" or "Revised" License
from HalcyonGrid

public void Initialize(Scene scene, IConfigSource config)
        {
            if (!enabled)
                return;

            IConfig cnf = config.Configs["Messaging"];
            if (cnf == null)
            {
                enabled = false;
                return;
            }
            if (cnf != null && cnf.GetString(
                    "OfflineMessageModule", "None") !=
                    "OfflineMessageModule")
            {
                enabled = false;
                return;
            }

            lock (m_SceneList)
            {
                if (m_SceneList.Count == 0)
                {
                    m_RestURL = cnf.GetString("OfflineMessageURL", String.Empty);
                    if (String.IsNullOrEmpty(m_RestURL))
                    {
                        m_log.Error("[OFFLINE MESSAGING]: Module was enabled, but no URL is given, disabling");
                        enabled = false;
                        return;
                    }
                }
                if (!m_SceneList.Contains(scene))
                    m_SceneList.Add(scene);

                scene.EventManager.OnNewClient += OnNewClient;
            }
        }

See More Examples