Example #1
0
        /// <summary>
        /// A funny little static routine to read in a parameter set. You pass it the delegate
        /// that is called to actually add the key/value to the ParameterSet.
        /// </summary>
        /// <param name="inFile"></param>
        /// <param name="storeParam"></param>
        public static bool ReadParameterSet(string inFile, InsertParam storeParam)
        {
            bool ret = true;

            if (File.Exists(inFile))
            {
                try {
                    using (Stream inStream = new FileStream(inFile, FileMode.Open)) {
                        if (inFile.EndsWith(".json"))
                        {
                            // READ JSON
                            OMVSD.OSD parms = OMVSD.OSDParser.DeserializeJson(inStream);
                            if (parms.Type == OpenMetaverse.StructuredData.OSDType.Map)
                            {
                                OMVSD.OSDMap mapParms = (OMVSD.OSDMap)parms;
                                foreach (KeyValuePair <string, OMVSD.OSD> kvp in mapParms)
                                {
                                    storeParam(kvp.Key, kvp.Value);
                                }
                            }
                            else
                            {
                                LogManager.Log.Log(LogLevel.DBADERROR, "AppParameters: CONFIG FILE WAS NOT A JSON MAP");
                                ret = false;
                            }
                        }
                        else
                        {
                            // READ INI
                            using (StreamReader sr = new StreamReader(inStream)) {
                                string inLine;
                                while ((inLine = sr.ReadLine()) != null)
                                {
                                    int    pos  = inLine.IndexOf(";");
                                    string desc = null;
                                    if (pos >= 0)
                                    {
                                        desc   = inLine.Substring(pos + 1).Trim();
                                        inLine = inLine.Substring(0, pos);
                                    }
                                    pos = inLine.IndexOf("=");
                                    if (pos >= 0)
                                    {
                                        string key   = inLine.Substring(0, pos).Trim();
                                        string value = inLine.Substring(pos + 1).Trim();
                                        storeParam(key, new OMVSD.OSDString(value));
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception e) {
                    LogManager.Log.Log(LogLevel.DBADERROR, "AppParameters: FAILURE PARSING CONFIG FILE'"
                                       + inFile + "':" + e.ToString());
                    ret = false;
                }
            }
            return(ret);
        }
        /// <summary>
        /// Add default features
        /// </summary>
        /// <remarks>
        /// TODO: These should be added from other modules rather than hardcoded.
        /// </remarks>
        private void AddDefaultFeatures()
        {
            lock (m_features)
            {
                m_features["MeshRezEnabled"]            = m_MeshEnabled;
                m_features["MeshUploadEnabled"]         = m_MeshEnabled;
                m_features["MeshXferEnabled"]           = m_MeshEnabled;
                m_features["PhysicsMaterialsEnabled"]   = m_PhysicsMaterialsEnabled;
                m_features["DynamicPathfindingEnabled"] = m_DynamicPathfindingEnabled;

                OSDMap typesMap = new OSDMap();
                typesMap["convex"] = true;
                typesMap["none"]   = true;
                typesMap["prim"]   = true;
                m_features["PhysicsShapeTypes"] = typesMap;

                // Extra information for viewers that want to use it
                OSDMap opensimFeatures = new OSDMap();
                if (m_MapImageServerURL != string.Empty)
                {
                    opensimFeatures["map-server-url"] = OSD.FromString(m_MapImageServerURL);
                }
                if (m_SearchURL != string.Empty)
                {
                    opensimFeatures["search-server-url"] = OSD.FromString(m_SearchURL);
                }
                opensimFeatures["ExportSupported"] = m_ExportSupported;
                opensimFeatures["whisper-range"]   = m_whisperdistance;
                opensimFeatures["say-range"]       = m_saydistance;
                opensimFeatures["shout-range"]     = m_shoutdistance;
                m_features["OpenSimExtras"]        = opensimFeatures;

                m_log.InfoFormat("[SimulatorFeatures]: mesh={0} physMat={1} exp={2} map='{3}' search='{4}'", m_MeshEnabled, m_PhysicsMaterialsEnabled, m_ExportSupported, m_MapImageServerURL, m_SearchURL);
            }
        }
        /// <summary>
        /// Posting to this communication instance. The URI comes in as "/api/MYNAME/ACTION" where
        /// ACTION is "login", "logout".
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="body"></param>
        /// <returns></returns>
        public OMVSD.OSD ProcessPost(RestHandler handler, Uri uri, string after, OMVSD.OSD body)
        {
            OMVSD.OSDMap ret = new OMVSD.OSDMap();
            if (m_comm == null)
            {
                m_log.Log(LogLevel.DBADERROR, "POST WITHOUT COMM CONNECTION!! URL=" + uri.ToString());
                return(new OMVSD.OSD());
            }
            m_log.Log(LogLevel.DCOMMDETAIL, "Post action: {0}", uri.ToString());
            switch (after)
            {
            case "/login":
                ret = PostActionLogin(body);
                break;

            case "/teleport":
                ret = PostActionTeleport(body);
                break;

            case "/logout":
                ret = PostActionLogout(body);
                break;

            case "/exit":
                ret = PostActionExit(body);
                break;

            default:
                m_log.Log(LogLevel.DBADERROR, "UNKNOWN ACTION: " + uri.ToString());
                ret.Add(RestHandler.RESTREQUESTERRORCODE, new OMVSD.OSDInteger(1));
                ret.Add(RestHandler.RESTREQUESTERRORMSG, new OMVSD.OSDString("Unknown action"));
                break;
            }
            return(ret);
        }
        /// <summary>
        /// Receive parcel voice cap
        /// </summary>
        /// <param name="client"></param>
        /// <param name="result"></param>
        /// <param name="error"></param>
        void pCap_OnComplete(OpenMetaverse.Http.CapsClient client,
                             OpenMetaverse.StructuredData.OSD result,
                             Exception error)
        {
            parcelCap.OnComplete -=
                new OpenMetaverse.Http.CapsClient.CompleteCallback(pCap_OnComplete);
            parcelCap = null;

            if (error != null)
            {
                Logger.Log("Region voice cap " + error.Message, Helpers.LogLevel.Error);
                return;
            }

            OpenMetaverse.StructuredData.OSDMap pMap = result as OpenMetaverse.StructuredData.OSDMap;

            regionName = pMap["region_name"].AsString();
            ReportConnectionState(ConnectionState.RegionCapAvailable);

            if (pMap.ContainsKey("voice_credentials"))
            {
                OpenMetaverse.StructuredData.OSDMap cred =
                    pMap["voice_credentials"] as OpenMetaverse.StructuredData.OSDMap;

                if (cred.ContainsKey("channel_uri"))
                {
                    spatialUri = cred["channel_uri"].AsString();
                }
                if (cred.ContainsKey("channel_credentials"))
                {
                    spatialCredentials = cred["channel_credentials"].AsString();
                }
            }

            if (spatialUri == null || spatialUri == "")
            {
                // "No voice chat allowed here");
                return;
            }

            Logger.Log("Voice connecting for region " + regionName, Helpers.LogLevel.Info);

            // STEP 5
            int reqId = SessionCreate(
                accountHandle,
                spatialUri,         // uri
                "",                 // Channel name seems to be always null
                spatialCredentials, // spatialCredentials, // session password
                true,               // Join Audio
                false,              // Join Text
                "");

            if (reqId < 0)
            {
                Logger.Log("Voice Session ReqID " + reqId.ToString(), Helpers.LogLevel.Error);
            }
        }
Example #5
0
        /// <summary>
        /// Fire the events registered for this event type asynchronously
        /// </summary>
        /// <param name="capsEvent">Capability name</param>
        /// <param name="body">Decoded event body</param>
        /// <param name="simulator">Reference to the simulator that
        /// generated this event</param>
        internal void BeginRaiseEvent(string capsEvent, StructuredData.OSD body, Simulator simulator)
        {
            bool specialHandler = false;

            Caps.EventQueueCallback callback;

            // Default handler first, if one exists
            if (_EventTable.TryGetValue(String.Empty, out callback))
            {
                if (callback != null)
                {
                    CapsCallbackWrapper wrapper;
                    wrapper.Callback  = callback;
                    wrapper.CapsEvent = capsEvent;
                    wrapper.Body      = body;
                    wrapper.Simulator = simulator;
                    ThreadPool.QueueUserWorkItem(_ThreadPoolCallback, wrapper);
                }
            }

            // Generic parser next, don't generic parse events we've manually registered for
            if (body.Type == StructuredData.OSDType.Map && !_EventTable.ContainsKey(capsEvent))
            {
                StructuredData.OSDMap map = (StructuredData.OSDMap)body;
                Packet packet             = Packet.BuildPacket(capsEvent, map);
                if (packet != null)
                {
                    NetworkManager.IncomingPacket incomingPacket;
                    incomingPacket.Simulator = simulator;
                    incomingPacket.Packet    = packet;

                    Logger.DebugLog("Serializing " + packet.Type.ToString() + " capability with generic handler", Client);

                    Client.Network.PacketInbox.Enqueue(incomingPacket);
                    specialHandler = true;
                }
            }

            // Explicit handler next
            if (_EventTable.TryGetValue(capsEvent, out callback) && callback != null)
            {
                CapsCallbackWrapper wrapper;
                wrapper.Callback  = callback;
                wrapper.CapsEvent = capsEvent;
                wrapper.Body      = body;
                wrapper.Simulator = simulator;
                ThreadPool.QueueUserWorkItem(_ThreadPoolCallback, wrapper);

                specialHandler = true;
            }

            if (!specialHandler)
            {
                Logger.Log("Unhandled CAPS event " + capsEvent, Helpers.LogLevel.Warning, Client);
            }
        }
Example #6
0
        /// <summary>
        /// Return all of the values for the key. This finds multiple values in the
        /// ini array only.
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public List <string> ParamStringArray(string key)
        {
            string        lkey = key.ToLower();
            List <string> ret  = new List <string>();

            OMVSD.OSD paramVal = null;
            bool      success  = false;

            lock (m_params) {
                try {
                    if (m_runtimeValues.ContainsKey(lkey))
                    {
                        paramVal = m_runtimeValues[lkey](lkey);
                    }
                    else
                    {
                        if (m_params.ContainsKey(lkey))
                        {
                            paramVal = m_params[lkey];
                        }
                    }
                    if (paramVal != null)
                    {
                        if (paramVal.Type == OMVSD.OSDType.Array)
                        {
                            OMVSD.OSDArray values = (OMVSD.OSDArray)paramVal;
                            foreach (OMVSD.OSD val in values)
                            {
                                ret.Add(val.AsString());
                            }
                            success = true;
                        }
                    }
                }
                catch {
                    success = false;
                }
            }
            if (!success)
            {
                switch (ParamErrorMethod)
                {
                case paramErrorType.eDefaultValue:
                    // return empty list
                    break;

                case paramErrorType.eException:
                    throw new ParameterException("String array param '" + key + "' not found");

                case paramErrorType.eNullValue:
                    ret = null;
                    break;
                }
            }
            return(ret);
        }
Example #7
0
 public void Update(string key, OMVSD.OSD value)
 {
     if (InternalUpdate(key, value))
     {
         if (OnModifiedCallback != null)
         {
             OnModifiedCallback(this, key, value);
         }
     }
 }
Example #8
0
        public void Add(string key, OMVSD.OSD value)
        {
            string lkey = key.ToLower();

            lock (m_params) {
                if (m_params.ContainsKey(lkey))
                {
                    m_params.Remove(lkey);
                }
                m_params.Add(lkey, value);
            }
        }
Example #9
0
        // updates and returns true if the value changed
        private bool InternalUpdate(string key, OMVSD.OSD value)
        {
            bool ret = false;

            lock (m_params) {
                if (m_params.ContainsKey(key.ToLower()))
                {
                    m_params[key.ToLower()] = value;
                    ret = true;
                }
            }
            return(ret);
        }
Example #10
0
        /// <summary>
        /// Get the module specifications from the configuration, load all the modules,
        /// and call their post all loaded entries then start them.
        /// </summary>
        /// <returns>true if it looks like everything worked</returns>
        public bool LoadAndStartModules()
        {
            bool successFlag = true;

            try {
                OMVSD.OSD modulesRaw = m_lgb.AppParams.ParamValue("Modules");
                // modules are specified by an array of maps
                if ((modulesRaw != null) && (modulesRaw.Type == OMVSD.OSDType.Array))
                {
                    OMVSD.OSDArray moduleArray = (OMVSD.OSDArray)modulesRaw;
                    foreach (OMVSD.OSDMap modSpec in moduleArray)
                    {
                        string modAssembly  = modSpec["Assembly"].AsString();
                        string modInterface = modSpec["Interface"].AsString();
                        string modName      = modSpec["Name"].AsString();
                        Object obj          = LoadModule(modAssembly, modInterface, modName);
                        if (obj == null)
                        {
                            m_log.Log(LogLevel.DBADERROR, "Failed to load module."
                                      + " a='" + modAssembly
                                      + "', i='" + modInterface
                                      + "', n=" + modName);
                            successFlag = false;
                            break;
                        }
                    }
                }
                else
                {
                    m_log.Log(LogLevel.DBADERROR, "'Modules' parameter is not an array of maps. Could not load modules");
                    successFlag = false;
                }
            }
            catch (Exception e) {
                m_log.Log(LogLevel.DBADERROR, "Failed starting modules: " + e.ToString());
                successFlag = false;
            }

            try {
                if (successFlag && AfterAllModulesLoaded())
                {
                    successFlag = Start();
                }
            }
            catch (Exception e) {
                m_log.Log(LogLevel.DBADERROR, "Failed starting modules: " + e.ToString());
                successFlag = false;
            }

            return(successFlag);
        }
        public OMVSD.OSD ParamValue(string key)
        {
            OMVSD.OSD ret = null;
            bool      set = false;

            if (m_overrideParams.HasParameter(key))
            {
                ret = m_overrideParams.ParamValue(key);
                // LogManager.Log.Log(LogLevel.DALL, "AppParameters: OverrideValue: {0}->{1}", key, ret.ToString());
                set = true;
            }
            else if (m_userParams.HasParameter(key))
            {
                ret = m_userParams.ParamValue(key);
                // LogManager.Log.Log(LogLevel.DALL, "AppParameters: UserValue: {0}->{1}", key, ret.ToString());
                set = true;
            }
            else if (m_iniParams.HasParameter(key))
            {
                ret = m_iniParams.ParamValue(key);
                // LogManager.Log.Log(LogLevel.DALL, "AppParameters: INIValue: {0}->{1}", key, ret.ToString());
                set = true;
            }
            else if (m_defaultParams.HasParameter(key))
            {
                ret = m_defaultParams.ParamValue(key);
                // LogManager.Log.Log(LogLevel.DALL, "AppParameters: DefaultValue: {0}->{1}", key, ret.ToString());
                set = true;
            }
            if (!set)
            {
                LogManager.Log.Log(LogLevel.DBADERROR, "AppParameters: OSD parameter '{0}' not found", key);
                switch (ParamErrorMethod)
                {
                case paramErrorType.eDefaultValue:
                    ret = new OMVSD.OSDMap();
                    break;

                case paramErrorType.eException:
                    throw new ParameterException("OSD parameter '" + key + "' not found");

                case paramErrorType.eNullValue:
                    ret = null;
                    break;
                }
            }
            return(ret);
        }
Example #12
0
        /// <summary>
        /// Fire the events registered for this event type synchronously
        /// </summary>
        /// <param name="capsEvent">Capability name</param>
        /// <param name="body">Decoded event body</param>
        /// <param name="simulator">Reference to the simulator that
        /// generated this event</param>
        internal void RaiseEvent(string capsEvent, StructuredData.OSD body, Simulator simulator)
        {
            bool specialHandler = false;

            Caps.EventQueueCallback callback;

            // Default handler first, if one exists
            if (_EventTable.TryGetValue(capsEvent, out callback))
            {
                if (callback != null)
                {
                    try { callback(capsEvent, body, simulator); }
                    catch (Exception ex) { Logger.Log("CAPS Event Handler: " + ex.ToString(), Helpers.LogLevel.Error, Client); }
                }
            }

            // Generic parser next
            if (body.Type == StructuredData.OSDType.Map)
            {
                StructuredData.OSDMap map = (StructuredData.OSDMap)body;
                Packet packet             = Packet.BuildPacket(capsEvent, map);
                if (packet != null)
                {
                    NetworkManager.IncomingPacket incomingPacket;
                    incomingPacket.Simulator = simulator;
                    incomingPacket.Packet    = packet;

                    Logger.DebugLog("Serializing " + packet.Type.ToString() + " capability with generic handler", Client);

                    Client.Network.PacketInbox.Enqueue(incomingPacket);
                    specialHandler = true;
                }
            }

            // Explicit handler next
            if (_EventTable.TryGetValue(capsEvent, out callback) && callback != null)
            {
                try { callback(capsEvent, body, simulator); }
                catch (Exception ex) { Logger.Log("CAPS Event Handler: " + ex.ToString(), Helpers.LogLevel.Error, Client); }

                specialHandler = true;
            }

            if (!specialHandler)
            {
                Logger.Log("Unhandled CAPS event " + capsEvent, Helpers.LogLevel.Warning, Client);
            }
        }
 // Note that this does not do the update event thing
 public void UpdateSilent(string key, OMVSD.OSD value)
 {
     if (m_overrideParams.HasParameter(key))
     {
         m_overrideParams.Update(key, value);
         return;
     }
     else if (m_userParams.HasParameter(key))
     {
         m_userParams.Update(key, value);
         return;
     }
     else if (m_iniParams.HasParameter(key))
     {
         m_iniParams.Update(key, value);
         return;
     }
 }
Example #14
0
        public OMVSD.OSD ParamValue(string key)
        {
            OMVSD.OSD ret     = null;
            string    lkey    = key.ToLower();
            bool      success = false;

            lock (m_params) {
                try {
                    if (m_runtimeValues.ContainsKey(lkey))
                    {
                        ret     = m_runtimeValues[lkey](key);
                        success = true;
                    }
                    else
                    {
                        if (m_params.ContainsKey(lkey))
                        {
                            ret     = m_params[lkey];
                            success = true;
                        }
                    }
                }
                catch {
                    success = false;
                }
            }
            if (!success)
            {
                switch (ParamErrorMethod)
                {
                case paramErrorType.eDefaultValue:
                    ret = new OMVSD.OSDMap();
                    break;

                case paramErrorType.eException:
                    throw new ParameterException("OSD parameter " + key + " not found");

                case paramErrorType.eNullValue:
                    ret = null;
                    break;
                }
            }
            return(ret);
        }
        private OMVSD.OSD PostHandler(RestHandler handler, Uri uri, String after, OMVSD.OSD body)
        {
            try {
                OMVSD.OSDMap mapBody = (OMVSD.OSDMap)body;
                m_log.Log(LogLevel.DCOMMDETAIL, "PostHandler: received chat '{0}'", mapBody["Message"]);
                // collect parameters and send it to the simulator
                string    msg           = Uri.UnescapeDataString(mapBody["Message"].AsString().Replace("+", " "));
                OMVSD.OSD channelString = new OMVSD.OSDString("0");
                mapBody.TryGetValue("Channel", out channelString);
                int       channel    = Int32.Parse(channelString.AsString());
                OMVSD.OSD typeString = new OMVSD.OSDString("Normal");
                mapBody.TryGetValue("Type", out typeString);
                OMV.ChatType chatType = OpenMetaverse.ChatType.Normal;
                if (typeString.AsString().Equals("Whisper"))
                {
                    chatType = OMV.ChatType.Whisper;
                }
                if (typeString.AsString().Equals("Shout"))
                {
                    chatType = OMV.ChatType.Shout;
                }
                m_comm.GridClient.Self.Chat(msg, channel, chatType);

                // echo my own message back for the log and chat window

                /* NOTE: Don't have to do this. The simulator echos it back
                 * OMV.ChatEventArgs cea = new OpenMetaverse.ChatEventArgs(m_comm.GridClient.Network.CurrentSim,
                 *              msg,
                 *              OpenMetaverse.ChatAudibleLevel.Fully,
                 *              chatType,
                 *              OpenMetaverse.ChatSourceType.Agent,
                 *              m_comm.GridClient.Self.Name,
                 *              OMV.UUID.Zero,
                 *              OMV.UUID.Zero,
                 *              m_comm.GridClient.Self.RelativePosition);
                 * this.Self_ChatFromSimulator(this, cea);
                 */
            }
            catch (Exception e) {
                m_log.Log(LogLevel.DCOMM, "ERROR PARSING CHAT MESSAGE: {0}", e);
            }
            // the return value does not matter
            return(new OMVSD.OSDMap());
        }
        /// <summary>
        /// Handle completion of main voice cap request.
        /// </summary>
        /// <param name="client"></param>
        /// <param name="result"></param>
        /// <param name="error"></param>
        void cClient_OnComplete(OpenMetaverse.Http.CapsClient client,
                                OpenMetaverse.StructuredData.OSD result,
                                Exception error)
        {
            if (error != null)
            {
                Logger.Log("Voice cap error " + error.Message, Helpers.LogLevel.Error);
                return;
            }

            Logger.Log("Voice provisioned", Helpers.LogLevel.Info);
            ReportConnectionState(ConnectionState.Provisioned);

            OpenMetaverse.StructuredData.OSDMap pMap = result as OpenMetaverse.StructuredData.OSDMap;

            // We can get back 4 interesting values:
            //      voice_sip_uri_hostname
            //      voice_account_server_name   (actually a full URI)
            //      username
            //      password
            if (pMap.ContainsKey("voice_sip_uri_hostname"))
            {
                sipServer = pMap["voice_sip_uri_hostname"].AsString();
            }
            if (pMap.ContainsKey("voice_account_server_name"))
            {
                acctServer = pMap["voice_account_server_name"].AsString();
            }
            voiceUser     = pMap["username"].AsString();
            voicePassword = pMap["password"].AsString();

            // Start the SLVoice daemon
            slvoicePath = GetVoiceDaemonPath();

            // Test if the executable exists
            if (!System.IO.File.Exists(slvoicePath))
            {
                Logger.Log("SLVoice is missing", Helpers.LogLevel.Error);
                return;
            }

            // STEP 1
            StartDaemon(slvoicePath, slvoiceArgs);
        }
        private OMVSD.OSDMap PostActionTeleport(OMVSD.OSD body)
        {
            OMVSD.OSDMap ret         = new OMVSD.OSDMap();
            ParameterSet loginParams = new ParameterSet();

            try {
                OMVSD.OSDMap paramMap = (OMVSD.OSDMap)body;
                string       dest     = paramMap["DESTINATION"].AsString();
                m_log.Log(LogLevel.DCOMMDETAIL, "Request to teleport to {0}", dest);
                m_comm.DoTeleport(dest);
            }
            catch (Exception e) {
                m_log.Log(LogLevel.DBADERROR, "CONNECT EXCEPTION: " + e.ToString());
                ret.Add(RestHandler.RESTREQUESTERRORCODE, new OMVSD.OSDInteger(1));
                ret.Add(RestHandler.RESTREQUESTERRORMSG, new OMVSD.OSDString("Connection threw exception: " + e.ToString()));
                return(ret);
            }
            return(ret);
        }
Example #18
0
        /// <summary>
        /// Deserializes OSD in to a list of primitives
        /// </summary>
        /// <param name="osd">Structure holding the serialized primitive list,
        /// must be of the SDMap type</param>
        /// <returns>A list of deserialized primitives</returns>
        public static List <Primitive> OSDToPrimList(StructuredData.OSD osd)
        {
            if (osd.Type != StructuredData.OSDType.Map)
            {
                throw new ArgumentException("LLSD must be in the Map structure");
            }

            StructuredData.OSDMap map   = (StructuredData.OSDMap)osd;
            List <Primitive>      prims = new List <Primitive>(map.Count);

            foreach (KeyValuePair <string, StructuredData.OSD> kvp in map)
            {
                Primitive prim = Primitive.FromOSD(kvp.Value);
                prim.LocalID = UInt32.Parse(kvp.Key);
                prims.Add(prim);
            }

            return(prims);
        }
Example #19
0
        private static OSD DeserializeLLSDNotationInteger(StringReader reader)
        {
            int character;
            StringBuilder s = new StringBuilder();
            if (((character = reader.Peek()) > 0) && ((char)character == '-'))
            {
                s.Append((char)character);
                reader.Read();
            }

            while ((character = reader.Peek()) > 0 &&
                           Char.IsDigit((char)character))
            {
                s.Append((char)character);
                reader.Read();
            }
            int integer;
            if (!Int32.TryParse(s.ToString(), out integer))
                throw new OSDException("Notation LLSD parsing: Can't parse integer value." + s.ToString());

            return OSD.FromInteger(integer);
        }
        private OMVSD.OSDMap PostActionLogin(OMVSD.OSD body)
        {
            OMVSD.OSDMap ret         = new OMVSD.OSDMap();
            ParameterSet loginParams = new ParameterSet();

            try {
                OMVSD.OSDMap paramMap = (OMVSD.OSDMap)body;
                loginParams.Add(CommLLLP.FIELDFIRST, paramMap["LOGINFIRST"].AsString());
                loginParams.Add(CommLLLP.FIELDLAST, paramMap["LOGINLAST"].AsString());
                loginParams.Add(CommLLLP.FIELDPASS, paramMap["LOGINPASS"].AsString());
                loginParams.Add(CommLLLP.FIELDGRID, paramMap["LOGINGRID"].AsString());
                loginParams.Add(CommLLLP.FIELDSIM, paramMap["LOGINSIM"].AsString());
            }
            catch {
                m_log.Log(LogLevel.DBADERROR, "MISFORMED POST REQUEST: ");
                ret.Add(RestHandler.RESTREQUESTERRORCODE, new OMVSD.OSDInteger(1));
                ret.Add(RestHandler.RESTREQUESTERRORMSG, new OMVSD.OSDString("Misformed POST request"));
                return(ret);
            }

            try {
                if (!m_comm.Connect(loginParams))
                {
                    m_log.Log(LogLevel.DBADERROR, "CONNECT FAILED");
                    ret.Add(RestHandler.RESTREQUESTERRORCODE, new OMVSD.OSDInteger(1));
                    ret.Add(RestHandler.RESTREQUESTERRORMSG, new OMVSD.OSDString("Could not log in"));
                    return(ret);
                }
            }
            catch (Exception e) {
                m_log.Log(LogLevel.DBADERROR, "CONNECT EXCEPTION: " + e.ToString());
                ret.Add(RestHandler.RESTREQUESTERRORCODE, new OMVSD.OSDInteger(1));
                ret.Add(RestHandler.RESTREQUESTERRORMSG, new OMVSD.OSDString("Connection threw exception: " + e.ToString()));
                return(ret);
            }

            return(ret);
        }
Example #21
0
        private static OSD DeserializeLLSDNotationReal(StringReader reader)
        {
            int character;
            StringBuilder s = new StringBuilder();
            if (((character = reader.Peek()) > 0) &&
                ((char)character == '-' && (char)character == '+'))
            {
                s.Append((char)character);
                reader.Read();
            }
            while (((character = reader.Peek()) > 0) &&
                   (Char.IsDigit((char)character) || (char)character == '.' ||
                    (char)character == 'e' || (char)character == 'E' ||
                    (char)character == '+' || (char)character == '-'))
            {
                s.Append((char)character);
                reader.Read();
            }
            double dbl;
            if (!Utils.TryParseDouble(s.ToString(), out dbl))
                throw new OSDException("Notation LLSD parsing: Can't parse real value: " + s.ToString());

            return OSD.FromReal(dbl);
        }
        private static OSD DeserializeLLSDNotationInteger(TextReader reader)
        {
            char character;
            bool neg = false;

            if (((character = (char)reader.Peek()) > 0) && (character == '-'))
            {
                neg = true;
                reader.Read();
            }
            int integer = 0;

            while ((character = (char)reader.Peek()) > 0 && Char.IsDigit(character))
            {
                integer *= 10;
                integer += character - '0';
                reader.Read();
            }
            if (neg)
            {
                return(OSD.FromInteger(-integer));
            }
            return(OSD.FromInteger(integer));
        }
Example #23
0
        private UserSessionID ParseViewerStats(string request, UUID agentID)
        {
            UserSessionID   uid = new UserSessionID();
            UserSessionData usd;
            OSD             message = OSDParser.DeserializeLLSDXml(request);
            OSDMap          mmap;

            lock (m_sessions)
            {
                if (agentID != UUID.Zero)
                {
                    if (!m_sessions.ContainsKey(agentID))
                    {
                        m_log.WarnFormat("[WEB STATS MODULE]: no session for stat disclosure for agent {0}", agentID);
                        return(new UserSessionID());
                    }
                    uid = m_sessions[agentID];
                }
                else
                {
                    // parse through the beginning to locate the session
                    if (message.Type != OSDType.Map)
                    {
                        return(new UserSessionID());
                    }

                    mmap = (OSDMap)message;
                    {
                        UUID sessionID = mmap["session_id"].AsUUID();

                        if (sessionID == UUID.Zero)
                        {
                            return(new UserSessionID());
                        }


                        // search through each session looking for the owner
                        foreach (UUID usersessionid in m_sessions.Keys)
                        {
                            // got it!
                            if (m_sessions[usersessionid].session_id == sessionID)
                            {
                                agentID = usersessionid;
                                uid     = m_sessions[usersessionid];
                                break;
                            }
                        }

                        // can't find a session
                        if (agentID == UUID.Zero)
                        {
                            return(new UserSessionID());
                        }
                    }
                }
            }

            usd = uid.session_data;

            if (message.Type != OSDType.Map)
            {
                return(new UserSessionID());
            }

            mmap = (OSDMap)message;
            {
                if (mmap["agent"].Type != OSDType.Map)
                {
                    return(new UserSessionID());
                }
                OSDMap agent_map = (OSDMap)mmap["agent"];
                usd.agent_id        = agentID;
                usd.name_f          = uid.name_f;
                usd.name_l          = uid.name_l;
                usd.region_id       = uid.region_id;
                usd.a_language      = agent_map["language"].AsString();
                usd.mem_use         = (float)agent_map["mem_use"].AsReal();
                usd.meters_traveled = (float)agent_map["meters_traveled"].AsReal();
                usd.regions_visited = agent_map["regions_visited"].AsInteger();
                usd.run_time        = (float)agent_map["run_time"].AsReal();
                usd.start_time      = (float)agent_map["start_time"].AsReal();
                usd.client_version  = agent_map["version"].AsString();

                UserSessionUtil.UpdateMultiItems(ref usd, agent_map["agents_in_view"].AsInteger(),
                                                 (float)agent_map["ping"].AsReal(),
                                                 (float)agent_map["sim_fps"].AsReal(),
                                                 (float)agent_map["fps"].AsReal());

                if (mmap["downloads"].Type != OSDType.Map)
                {
                    return(new UserSessionID());
                }
                OSDMap downloads_map = (OSDMap)mmap["downloads"];
                usd.d_object_kb  = (float)downloads_map["object_kbytes"].AsReal();
                usd.d_texture_kb = (float)downloads_map["texture_kbytes"].AsReal();
                usd.d_world_kb   = (float)downloads_map["workd_kbytes"].AsReal();


                usd.session_id = mmap["session_id"].AsUUID();

                if (mmap["system"].Type != OSDType.Map)
                {
                    return(new UserSessionID());
                }
                OSDMap system_map = (OSDMap)mmap["system"];

                usd.s_cpu = system_map["cpu"].AsString();
                usd.s_gpu = system_map["gpu"].AsString();
                usd.s_os  = system_map["os"].AsString();
                usd.s_ram = system_map["ram"].AsInteger();

                if (mmap["stats"].Type != OSDType.Map)
                {
                    return(new UserSessionID());
                }

                OSDMap stats_map = (OSDMap)mmap["stats"];
                {
                    if (stats_map["failures"].Type != OSDType.Map)
                    {
                        return(new UserSessionID());
                    }
                    OSDMap stats_failures = (OSDMap)stats_map["failures"];
                    usd.f_dropped        = stats_failures["dropped"].AsInteger();
                    usd.f_failed_resends = stats_failures["failed_resends"].AsInteger();
                    usd.f_invalid        = stats_failures["invalid"].AsInteger();
                    usd.f_resent         = stats_failures["resent"].AsInteger();
                    usd.f_send_packet    = stats_failures["send_packet"].AsInteger();

                    if (stats_map["net"].Type != OSDType.Map)
                    {
                        return(new UserSessionID());
                    }
                    OSDMap stats_net = (OSDMap)stats_map["net"];
                    {
                        if (stats_net["in"].Type != OSDType.Map)
                        {
                            return(new UserSessionID());
                        }

                        OSDMap net_in = (OSDMap)stats_net["in"];
                        usd.n_in_kb = (float)net_in["kbytes"].AsReal();
                        usd.n_in_pk = net_in["packets"].AsInteger();

                        if (stats_net["out"].Type != OSDType.Map)
                        {
                            return(new UserSessionID());
                        }
                        OSDMap net_out = (OSDMap)stats_net["out"];

                        usd.n_out_kb = (float)net_out["kbytes"].AsReal();
                        usd.n_out_pk = net_out["packets"].AsInteger();
                    }
                }
            }

            uid.session_data    = usd;
            m_sessions[agentID] = uid;
            return(uid);
        }
 public bool TryGetFeature(string name, out OSD value)
 {
     lock (m_features)
         return(m_features.TryGetValue(name, out value));
 }
 public OMVSD.OSD ProcessPostParam(RestHandler handler, Uri uri, string afterString, OMVSD.OSD rawbody)
 {
     OMVSD.OSD ret = new OMVSD.OSDMap();
     try {
         OMVSD.OSDMap body = (OMVSD.OSDMap)rawbody;
         foreach (string akey in body.Keys)
         {
             if (handler.m_parameterSet.HasParameter(akey))
             {
                 handler.m_parameterSet.Update(akey, body[akey]);
             }
         }
         ret = handler.m_parameterSet.GetDisplayable();
     }
     catch (Exception e) {
         m_log.Log(LogLevel.DREST, "Failed setting param in POST: {0}", e);
     }
     return(ret);
 }
 public virtual void GetPostAsync(string afterString)
 {
     if (m_request.HttpMethod.ToUpper().Equals("GET"))
     {
         if (m_processGet == null && m_dir != null)
         {
             // no processor but we have a dir. Return the file in that dir.
             string filename = m_dir + "/" + afterString;
             if (File.Exists(filename))
             {
                 // m_log.Log(LogLevel.DRESTDETAIL, "GET: file: {0}", afterString);
                 string[] fileContents = File.ReadAllLines(filename);
                 string   mimeType     = RestManager.MIMEDEFAULT;
                 if (filename.EndsWith(".css"))
                 {
                     mimeType = "text/css";
                 }
                 if (filename.EndsWith(".json"))
                 {
                     mimeType = "text/json";
                 }
                 RestManager.Instance.ConstructSimpleResponse(m_response, mimeType,
                                                              delegate(ref StringBuilder buff) {
                     foreach (string line in fileContents)
                     {
                         buff.Append(line);
                         buff.Append("\r\n");
                     }
                 }
                                                              );
             }
             else
             {
                 m_log.Log(LogLevel.DRESTDETAIL, "GET: file does not exist: {0}", filename);
             }
             return;
         }
         try {
             if (m_processGet == null)
             {
                 throw new LookingGlassException("HTTP GET with no processing routine");
             }
             // m_log.Log(LogLevel.DRESTDETAIL, "GET: " + m_request.Url);
             OMVSD.OSD resp = m_processGet(this, m_request.Url, afterString);
             RestManager.Instance.ConstructSimpleResponse(m_response, "text/json",
                                                          delegate(ref StringBuilder buff) {
                 buff.Append(OMVSD.OSDParser.SerializeJsonString(resp));
             }
                                                          );
         }
         catch (Exception e) {
             m_log.Log(LogLevel.DREST, "Failed getHandler: u="
                       + m_request.Url.ToString() + ":" + e.ToString());
             RestManager.Instance.ConstructErrorResponse(m_response, HttpStatusCode.InternalServerError,
                                                         delegate(ref StringBuilder buff) {
                 buff.Append("<div>");
                 buff.Append("FAILED GETTING '" + m_request.Url.ToString() + "'");
                 buff.Append("</div>");
                 buff.Append("<div>");
                 buff.Append("ERROR = '" + e.ToString() + "'");
                 buff.Append("</div>");
             }
                                                         );
         }
         return;
     }
     if (m_request.HttpMethod.ToUpper().Equals("POST"))
     {
         m_log.Log(LogLevel.DRESTDETAIL, "POST: " + m_request.Url);
         string strBody = "";
         using (StreamReader rdr = new StreamReader(m_request.InputStream)) {
             strBody = rdr.ReadToEnd();
             // m_log.Log(LogLevel.DRESTDETAIL, "APIPostHandler: Body: '" + strBody + "'");
         }
         try {
             if (m_processPost == null)
             {
                 throw new LookingGlassException("HTTP POST with no processing routine");
             }
             OMVSD.OSD body = MapizeTheBody(strBody);
             OMVSD.OSD resp = m_processPost(this, m_request.Url, afterString, body);
             if (resp != null)
             {
                 RestManager.Instance.ConstructSimpleResponse(m_response, "text/json",
                                                              delegate(ref StringBuilder buff) {
                     buff.Append(OMVSD.OSDParser.SerializeJsonString(resp));
                 }
                                                              );
             }
             else
             {
                 m_log.Log(LogLevel.DREST, "Failure which creating POST response");
                 throw new LookingGlassException("Failure processing POST");
             }
         }
         catch (Exception e) {
             m_log.Log(LogLevel.DREST, "Failed postHandler: u="
                       + m_request.Url.ToString() + ":" + e.ToString());
             RestManager.Instance.ConstructErrorResponse(m_response, HttpStatusCode.InternalServerError,
                                                         delegate(ref StringBuilder buff) {
                 buff.Append("<div>");
                 buff.Append("FAILED GETTING '" + m_request.Url.ToString() + "'");
                 buff.Append("</div>");
                 buff.Append("<div>");
                 buff.Append("ERROR = '" + e.ToString() + "'");
                 buff.Append("</div>");
             }
                                                         );
             // make up a response
         }
         return;
     }
 }
 private OMVSD.OSDMap PostActionExit(OMVSD.OSD body)
 {
     OMVSD.OSDMap ret = new OMVSD.OSDMap();
     LGB.KeepRunning = false;
     return(ret);
 }
 private OMVSD.OSDMap PostActionLogout(OMVSD.OSD body)
 {
     OMVSD.OSDMap ret = new OMVSD.OSDMap();
     m_comm.Disconnect();
     return(ret);
 }
 public void AddFeature(string name, OSD value)
 {
     lock (m_features)
         m_features[name] = value;
 }
 public void AddFeature(string name, OSD value)
 {
     lock (m_features)
         m_features[name] = value;
 }
 public bool TryGetFeature(string name, out OSD value)
 {
     lock (m_features)
         return m_features.TryGetValue(name, out value);
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="reader"></param>
        /// <returns></returns>
        private static OSD ParseLLSDXmlElement(XmlTextReader reader)
        {
            SkipWhitespace(reader);

            if (reader.NodeType != XmlNodeType.Element)
            {
                throw new OSDException("Expected an element");
            }

            string type = reader.LocalName;
            OSD    ret;

            switch (type)
            {
            case "undef":
                if (reader.IsEmptyElement)
                {
                    reader.Read();
                    return(new OSD());
                }

                reader.Read();
                SkipWhitespace(reader);
                ret = new OSD();
                break;

            case "boolean":
                if (reader.IsEmptyElement)
                {
                    reader.Read();
                    return(OSD.FromBoolean(false));
                }

                if (reader.Read())
                {
                    string s = reader.ReadString().Trim();

                    if (!String.IsNullOrEmpty(s) && (s == "true" || s == "1"))
                    {
                        ret = OSD.FromBoolean(true);
                        break;
                    }
                }

                ret = OSD.FromBoolean(false);
                break;

            case "integer":
                if (reader.IsEmptyElement)
                {
                    reader.Read();
                    return(OSD.FromInteger(0));
                }

                if (reader.Read())
                {
                    int value = 0;
                    Int32.TryParse(reader.ReadString().Trim(), out value);
                    ret = OSD.FromInteger(value);
                    break;
                }

                ret = OSD.FromInteger(0);
                break;

            case "real":
                if (reader.IsEmptyElement)
                {
                    reader.Read();
                    return(OSD.FromReal(0d));
                }

                if (reader.Read())
                {
                    double value = 0d;
                    string str   = reader.ReadString().Trim().ToLower();

                    if (str == "nan")
                    {
                        value = Double.NaN;
                    }
                    else
                    {
                        Utils.TryParseDouble(str, out value);
                    }

                    ret = OSD.FromReal(value);
                    break;
                }

                ret = OSD.FromReal(0d);
                break;

            case "uuid":
                if (reader.IsEmptyElement)
                {
                    reader.Read();
                    return(OSD.FromUUID(UUID.Zero));
                }

                if (reader.Read())
                {
                    UUID value = UUID.Zero;
                    UUID.TryParse(reader.ReadString().Trim(), out value);
                    ret = OSD.FromUUID(value);
                    break;
                }

                ret = OSD.FromUUID(UUID.Zero);
                break;

            case "date":
                if (reader.IsEmptyElement)
                {
                    reader.Read();
                    return(OSD.FromDate(Utils.Epoch));
                }

                if (reader.Read())
                {
                    DateTime value = Utils.Epoch;
                    DateTime.TryParse(reader.ReadString().Trim(), out value);
                    ret = OSD.FromDate(value);
                    break;
                }

                ret = OSD.FromDate(Utils.Epoch);
                break;

            case "string":
                if (reader.IsEmptyElement)
                {
                    reader.Read();
                    return(OSD.FromString(String.Empty));
                }

                if (reader.Read())
                {
                    ret = OSD.FromString(reader.ReadString());
                    break;
                }

                ret = OSD.FromString(String.Empty);
                break;

            case "binary":
                if (reader.IsEmptyElement)
                {
                    reader.Read();
                    return(OSD.FromBinary(Utils.EmptyBytes));
                }

                if (reader.GetAttribute("encoding") != null && reader.GetAttribute("encoding") != "base64")
                {
                    throw new OSDException("Unsupported binary encoding: " + reader.GetAttribute("encoding"));
                }

                if (reader.Read())
                {
                    try
                    {
                        ret = OSD.FromBinary(Convert.FromBase64String(reader.ReadString().Trim()));
                        break;
                    }
                    catch (FormatException ex)
                    {
                        throw new OSDException("Binary decoding exception: " + ex.Message);
                    }
                }

                ret = OSD.FromBinary(Utils.EmptyBytes);
                break;

            case "uri":
                if (reader.IsEmptyElement)
                {
                    reader.Read();
                    return(OSD.FromUri(new Uri(String.Empty, UriKind.RelativeOrAbsolute)));
                }

                if (reader.Read())
                {
                    ret = OSD.FromUri(new Uri(reader.ReadString(), UriKind.RelativeOrAbsolute));
                    break;
                }

                ret = OSD.FromUri(new Uri(String.Empty, UriKind.RelativeOrAbsolute));
                break;

            case "map":
                return(ParseLLSDXmlMap(reader));

            case "array":
                return(ParseLLSDXmlArray(reader));

            default:
                reader.Read();
                ret = null;
                break;
            }

            if (reader.NodeType != XmlNodeType.EndElement || reader.LocalName != type)
            {
                throw new OSDException("Expected </" + type + ">");
            }
            else
            {
                reader.Read();
                return(ret);
            }
        }