Exemple #1
0
 internal void InterceptRSSEvtRequest(TheRequestData pRequest)
 {
     if (pRequest == null)
     {
         return;
     }
     try
     {
         TheStorageMirror <TheEventLogData> tEventLog = TheCDEngines.GetStorageMirror("EventLog") as TheStorageMirror <TheEventLogData>;
         if (tEventLog != null)
         {
             CreateEvtLogFeed(pRequest, tEventLog?.TheValues.OrderByDescending(s => s.cdeCTIM).ThenByDescending(s => s.cdeCTIM.Millisecond).ToList(), 200);
         }
         else
         {
             TheRSSGenerator.CreateRSS(pRequest, new List <TheEventLogData>()
             {
                 new TheEventLogData()
                 {
                     EventName = "No Eventlog on this Node"
                 }
             }, 1);
         }
     }
     catch
     {
         //ignored
     }
 }
Exemple #2
0
 public static void CreateEvtLogFeed(TheRequestData pRequest, List <TheEventLogData> pLogData, int MaxCnt)
 {
     if (pRequest.RequestUri != null && !string.IsNullOrEmpty(pRequest.RequestUri.Query) && pRequest.RequestUri.Query.Length > 1)
     {
         var QParts = TheCommonUtils.ParseQueryString(pRequest.RequestUri.Query); //.Split('=');
         //if (QParts.ContainsKey("SID") && (!TheScopeManager.IsValidScopeID(TheScopeManager.GetScrambledScopeIDFromEasyID(QParts["SID"])) || QParts.ContainsKey("NID")))
         //{
         //    pRequest.SessionState.SScopeID = TheScopeManager.GetScrambledScopeIDFromEasyID(QParts["SID"]);
         //    Guid tTarget = Guid.Empty;
         //    if (QParts.ContainsKey("NID"))
         //        tTarget = TheCommonUtils.CGuid(QParts["NID"]);
         //    TheHttpService.cdeStreamFile(pRequest, true, 300, tTarget);
         //    if (pRequest.ResponseBuffer == null)
         //        TheRSSGenerator.CreateRSS(pRequest, new List<TheEventLogData>() { new TheEventLogData() { EventName = "Relay did not answer" } }, 1);
         //    return;
         //}
     }
     if (pLogData != null)
     {
         TheRSSGenerator.CreateRSS(pRequest, pLogData, 200);
     }
     else
     {
         TheRSSGenerator.CreateRSS(pRequest, new List <TheEventLogData>()
         {
             new TheEventLogData()
             {
                 EventName = "No Eventlog on this Node"
             }
         }, 1);
     }
 }
Exemple #3
0
 public static async Task WaitForWSAccept(HttpListenerContext pContext)
 {
     TheDiagnostics.SetThreadName("WSWait4Accept");
     var wsc = await pContext.AcceptWebSocketAsync(null);
     if (wsc != null)
     {
         TheRequestData tRequestData = new TheRequestData
         {
             RequestUri = pContext.Request.Url,
             UserAgent = pContext.Request.UserAgent,
             HttpMethod = pContext.Request.HttpMethod,
             Header = TheCommonUtils.cdeNameValueToDirectory(pContext.Request.Headers),
             ResponseMimeType = pContext.Request.ContentType,
             ServerTags = null,
             ClientCert = pContext.Request.GetClientCertificate()
         };
         if (TheCommCore.MyHttpService != null && TheBaseAssets.MyServiceHostInfo.ClientCertificateUsage > 1) //If CDE requires a certificate, terminate all incoming requests before any processing
         {
             var err = TheCommCore.MyHttpService.ValidateCertificateRoot(tRequestData);
             if (!string.IsNullOrEmpty(err))
             {
                 pContext.Response.StatusCode = (int)eHttpStatusCode.AccessDenied;
                 pContext.Response.OutputStream.Close();
                 return;
             }
         }
         TheWSProcessor8 tProcessor = new TheWSProcessor8(wsc.WebSocket);
         tProcessor.SetRequest(tRequestData);
         await tProcessor.ProcessWS();
     }
 }
Exemple #4
0
 /// <summary>
 /// Set the first request to the WS-Processor. It will be used to handle all WebSocket data for the session of the related node
 /// </summary>
 /// <param name="pRequest">If null, the Processor will create a new empty TheRequestData to handle all traffic</param>
 public void SetRequest(TheRequestData pRequest)
 {
     if (pRequest == null)
     {
         MySessionRequestData = new TheRequestData();
     }
     else
     {
         MySessionRequestData = pRequest;
     }
     MySessionRequestData.WebSocket = this;
     mre        = new ManualResetEventSlim(true);
     IsActive   = true;
     CloseFired = false;
     try
     {
         if (TheCommCore.MyHttpService != null && MySessionRequestData.RequestUri != null)
         {
             TheCommCore.MyHttpService.cdeProcessPost(MySessionRequestData);
         }
     }
     catch (Exception e)
     {
         TheBaseAssets.MySYSLOG.WriteToLog(4360, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("TheWSProcessor", "cdeProcssPost Error", eMsgLevel.l1_Error, e.ToString()));
     }
 }
Exemple #5
0
        public void readHeaders(TheRequestData pReqData)
        {
            pReqData.Header = new cdeConcurrentDictionary <string, string>();
            string tHeaderLine;

            while ((tHeaderLine = streamReadLine(mRequestStream)) != null && mHServer.IsActive)
            {
                if (tHeaderLine.Equals(""))
                {
                    break;
                }

                int separator = tHeaderLine.IndexOf(':');
                if (separator == -1)
                {
                    throw new Exception("HttpMidiServer: invalid http header line: " + tHeaderLine);
                }
                string name = tHeaderLine.Substring(0, separator);
                int    pos  = separator + 1;
                while ((pos < tHeaderLine.Length) && (tHeaderLine[pos] == ' '))
                {
                    pos++; // strip any spaces
                }
                string value = tHeaderLine.Substring(pos, tHeaderLine.Length - pos);
                pReqData.Header.TryAdd(name, value);
            }
        }
Exemple #6
0
        void sinkLoginFetchSuccess(TheRequestData pdata)
        {
            var tRes = TheCommonUtils.CArray2UTF8String(pdata.ResponseBuffer);

            MyRequestData = pdata;
            if (!string.IsNullOrEmpty(mTokenLocator))
            {
                if (mTokenLocator.StartsWith("HEADER:"))
                {
                    var tHead = mTokenLocator.Substring("HEADER:".Length);
                    if (pdata.Header.TryGetValue(tHead, out string tHeader))
                    {
                        eventTokenReceived?.Invoke(tHeader, pdata);
                        return;
                    }
                }
                else
                {
                    var pos = tRes.IndexOf(mTokenLocator); // "name=\"_token\" value=\"");
                    if (pos > 0)
                    {
                        pos += mTokenLocator.Length; /// "name=\"_token\" value=\"".Length;
                        var pos2   = tRes.IndexOf("\"", pos);
                        var tToken = tRes.Substring(pos, pos2 - pos);
                        eventTokenReceived?.Invoke(tToken, pdata);
                        return;
                    }
                }
            }
            eventTokenReceived?.Invoke(null, pdata);
        }
Exemple #7
0
        void appServer_NewSessionConnected(WebSocketSession session)
        {
            TheBaseAssets.MySYSLOG.WriteToLog(4343, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("TheSWSServer", string.Format("New Session: {0} ID:{1}", session.RemoteEndPoint.ToString(), session.SessionID)));
            try
            {
                TheWSProcessor tProcessor = new TheWSProcessor(session);
                mSessionList.TryAdd(session.SessionID, tProcessor);

                TheRequestData tRequestData = new TheRequestData();
                tRequestData.RequestUri = new Uri(session.UriScheme + "://" + session.Host + session.Path); // pContext.Request.Url;
                tRequestData.Header = new cdeConcurrentDictionary<string, string>();
                foreach (var tKey in session.Items)
                {
                    switch (tKey.Key.ToString().ToLower())
                    {
                        case "user-agent": //tRequestData.UserAgent = pContext.Request.UserAgent;
                            tRequestData.UserAgent = tKey.Value.ToString();
                            break;
                        case "content-type": //tRequestData.ResponseMimeType = pContext.Request.ContentType;
                            tRequestData.ResponseMimeType = tKey.Value.ToString();
                            break;
                    }
                    tRequestData.Header.TryAdd(tKey.Key.ToString(), tKey.Value.ToString());
                }
                tRequestData.ServerTags = null;
                tProcessor.SetRequest(tRequestData);
            }
            catch (Exception e)
            {
                TheBaseAssets.MySYSLOG.WriteToLog(4343, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("TheSWSServer", "Error during new Session-Connect", eMsgLevel.l1_Error,e.ToString()));
            }
        }
Exemple #8
0
 public void DoLogin(Uri pLoginUrl, string tPost, string MimeTypeOverride = null, cdeConcurrentDictionary <string, string> paddHeader = null)
 {
     if (MyRequestData == null)
     {
         MyRequestData = new TheRequestData();
     }
     MyRequestData.PostData   = TheCommonUtils.CUTF8String2Array(tPost);
     MyRequestData.RequestUri = pLoginUrl;
     MyRequestData.HttpMethod = "POST";
     MyRequestData.Header     = null;
     if (paddHeader != null)
     {
         MyRequestData.Header = new cdeConcurrentDictionary <string, string>();
         foreach (string key in paddHeader.Keys)
         {
             MyRequestData.Header.TryAdd(key, paddHeader[key]);
         }
     }
     if (!string.IsNullOrEmpty(MimeTypeOverride))
     {
         MyRequestData.ResponseMimeType = MimeTypeOverride; // "application/x-www-form-urlencoded; charset=UTF-8";
     }
     else
     {
         MyRequestData.ResponseMimeType = mPostMimeType; // "application/x-www-form-urlencoded; charset=UTF-8";
     }
     MyRequestData.ResponseBuffer  = null;
     MyRequestData.TimeOut         = 15000;
     MyRequestData.DisableRedirect = true;
     MyRequestData.RequestCookies  = MyRequestData?.SessionState?.StateCookies;
     MyRest.PostRESTAsync(MyRequestData, LoginSuccess, sinkError);
 }
 /// <summary>
 /// Sets a client Certificate on TheRequestData
 /// </summary>
 /// <param name="pData"></param>
 /// <param name="pThumbPrint"></param>
 /// <returns></returns>
 internal static bool SetClientCert(TheRequestData pData, string pThumbPrint)
 {
     if (!string.IsNullOrEmpty(pThumbPrint))
     {
         try
         {
             X509Certificate2Collection certs = null;
             if (pThumbPrint == TheBaseAssets.MyServiceHostInfo.ClientCertificateThumb)
             {
                 certs = TheBaseAssets.MyServiceHostInfo.ClientCerts; //Use cached value if master cache
             }
             else
             {
                 certs = GetClientCertificatesByThumbprint(pThumbPrint);  //load a custom cert for ISB Connect and other client cert scenarios
             }
             if (certs?.Count > 0)
             {
                 pData.ClientCert = certs[0];
                 return(true); //Client cert could be set to TheRequestData
             }
         }
         catch (Exception certex)
         {
             TheBaseAssets.MySYSLOG.WriteToLog(4365, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("TheCommonUtils", "Error setting Client Certificate", eMsgLevel.l1_Error, certex.ToString()));
         }
         return(false); //ClientThumb is set but could not be added to TheRequestData...let caller know
     }
     return(true);      //Not set..all is good
 }
Exemple #10
0
        /// <summary>
        /// Called using a URL like this: /xxxx/xxxxx/Logon?user=xxxx&pwd=yyyyy
        /// </summary>
        /// <param name="pRequest">TheRequestData receive in http interceptor.</param>
        /// <param name="aParameters">Parameter values parsed into a dictionary.</param>
        ///
        public static bool ValidateUserCredentials(TheRequestData pRequest, Dictionary <string, string> aParameters)
        {
            bool bSuccess = false;

            if (aParameters != null & aParameters.Count > 1)
            {
                string strUser = aParameters["user"].ToString();
                string strPwd  = aParameters["pwd"].ToString();

                if (strUser != null && strPwd != null)
                {
                    if (strUser == "myuser" && strPwd == "asterisks")
                    {
                        Guid pToken = CreateToken(pRequest);
                        SaveToValidTokenTable(pToken);

                        // Return access token to caller.
                        SetResponseValue(pRequest, pToken);
                        bSuccess = true;
                    }
                }
            }

            if (bSuccess == false)
            {
                SetEmptyResponse(pRequest);
            }

            return(bSuccess);
        }
 internal void EndSession(TheRequestData pRequestData)
 {
     if (pRequestData.SessionState == null || pRequestData.SessionState.HasExpired)
     {
         return;
     }
     KillSession(pRequestData.SessionState);
 }
Exemple #12
0
        internal static void CreateRSS(TheRequestData pRequest, List <TheEventLogData> pLog, int MaxCnt)
        {
            try
            {
                using (MemoryStream tW = new MemoryStream())
                {
                    TheRSSGenerator gen = new TheRSSGenerator(tW)
                    {
                        Title         = TheBaseAssets.MyServiceHostInfo.ApplicationTitle + " - Event Feed",
                        Description   = "All Events coming from the Rules Event Log",
                        LastBuildDate = DateTimeOffset.Now,
                        Link          = TheBaseAssets.MyServiceHostInfo.SiteName,
                        PubDate       = DateTimeOffset.Now
                    };
                    //gen.Category = "Home-Automation";

                    gen.WriteStartDocument();
                    gen.WriteStartChannel();

                    int cnt = 0;
                    foreach (TheEventLogData tEntry in pLog)
                    {
                        gen.WriteItem(

                            tEntry.EventName,
                            TheBaseAssets.MyServiceHostInfo.SiteName + "/" + TheBaseAssets.MyServiceHostInfo.PortalPage,                                          //"url to the item page",
                            string.Format("{0} occured at {1} on stations {2}. {3}", tEntry.EventName, tEntry.EventTime, tEntry.StationName, tEntry.EventString), //  "the description of the item",
                            tEntry.StationName,                                                                                                                   // "the author",
                            tEntry.EventTrigger,                                                                                                                  // "the category",
                            "",                                                                                                                                   //"comments",
                            tEntry.cdeMID.ToString(),                                                                                                             //"the guid",
                            tEntry.EventTime,                                                                                                                     //    DateTimeOffset.Now,
                            tEntry.StationName,                                                                                                                   //"the source",
                            "",                                                                                                                                   //"enclosure URL",
                            "",                                                                                                                                   //"enclosure length",
                            ""                                                                                                                                    //"enclosure type"
                            );
                        if (MaxCnt > 0 && cnt > MaxCnt)
                        {
                            break;
                        }
                        cnt++;
                    }
                    gen.WriteEndChannel();
                    gen.WriteEndDocument();
                    gen.Close();
                    pRequest.ResponseBuffer = tW.ToArray();
                }
                pRequest.StatusCode       = 200;
                pRequest.ResponseMimeType = "application/rss+xml";
                pRequest.DontCompress     = true;
            }

            catch
            {
                // do something with the error
            }
        }
Exemple #13
0
 // Simplest valid Http Interceptor.
 private void sinkSimplestValidHttpInterceptor(TheRequestData pRequest)
 {
     pRequest.ResponseMimeType  = "text/html";
     pRequest.ResponseBuffer    = new byte[1];
     pRequest.ResponseBuffer[0] = 0;
     pRequest.StatusCode        = (int)eHttpStatusCode.OK;
     pRequest.DontCompress      = true;
     pRequest.AllowStatePush    = false;
 }
Exemple #14
0
 void sinkError(TheRequestData pData)
 {
     eventMessage?.Invoke(pData.ErrorDescription, pData);
     if (IsConnected && mRetryOnError > 0)
     {
         TheCommonUtils.SleepOneEye(mRetryOnError, 100);
         GetDevices();
     }
 }
Exemple #15
0
 public static void SetEmptyResponse(TheRequestData pRequest)
 {
     pRequest.ResponseMimeType  = "text/html";
     pRequest.ResponseBuffer    = new byte[1];
     pRequest.ResponseBuffer[0] = 0;
     pRequest.StatusCode        = (int)eHttpStatusCode.OK;
     pRequest.DontCompress      = true;
     pRequest.AllowStatePush    = false;
 }
 private static void ResponseNotImplemented(TheRequestData pRequest)
 {
     pRequest.ResponseMimeType  = "text/html";
     pRequest.ResponseBuffer    = new byte[1];
     pRequest.ResponseBuffer[0] = 0;
     pRequest.StatusCode        = (int)eHttpStatusCode.OK;
     pRequest.DontCompress      = true;
     pRequest.AllowStatePush    = false;
 }
Exemple #17
0
        internal static void CreateRSS(TheRequestData pRequest, List <TheEventLogEntry> pLog, int MaxCnt)
        {
            try
            {
                using (MemoryStream tW = new MemoryStream())
                {
                    TheRSSGenerator gen = new TheRSSGenerator(tW)
                    {
                        Title         = TheBaseAssets.MyServiceHostInfo.ApplicationTitle + " - System Log Feed",
                        Description   = "Last Events of the System Log",
                        LastBuildDate = DateTimeOffset.Now,
                        Link          = TheBaseAssets.MyServiceHostInfo.SiteName,
                        PubDate       = DateTimeOffset.Now
                    };
                    gen.WriteStartDocument();
                    gen.WriteStartChannel();

                    int cnt = 0;
                    foreach (TheEventLogEntry tEntry in pLog)
                    {
                        gen.WriteItem(

                            tEntry.Message.TXT,
                            TheBaseAssets.MyServiceHostInfo.SiteName + "/" + TheBaseAssets.MyServiceHostInfo.PortalPage, //"url to the item page",
                            tEntry.Message.PLS,                                                                          //  "the description of the item",
                            tEntry.Message.ENG,                                                                          // "the author",
                            tEntry.Message.ENG,                                                                          //"the category",
                            "",                                                                                          //"comments",
                            tEntry.cdeMID.ToString(),                                                                    //"the guid",
                            tEntry.cdeCTIM,                                                                              //    DateTimeOffset.Now,
                            tEntry.Message.ENG,                                                                          //"the source",
                            "",                                                                                          //"enclosure URL",
                            "",                                                                                          //"enclosure length",
                            ""                                                                                           //"enclosure type"
                            );
                        if (MaxCnt > 0 && cnt > MaxCnt)
                        {
                            break;
                        }
                        cnt++;
                    }
                    gen.WriteEndChannel();
                    gen.WriteEndDocument();
                    gen.Close();
                    pRequest.ResponseBuffer = tW.ToArray();
                }
                pRequest.StatusCode       = 200;
                pRequest.ResponseMimeType = "application/rss+xml";
                pRequest.DontCompress     = true;
            }

            catch
            {
                // do something with the error
            }
        }
        internal TheSessionState GetOrCreateSessionState(Guid pSessionID, TheRequestData pRequest)
        {
            TheSessionState tS = ValidateSEID(pSessionID);  //Measure Frequency!!

            if (tS == null)
            {
                tS = CreateSession(pRequest, pSessionID);
            }
            return(tS);
        }
Exemple #19
0
        public static void SetResponseValue(TheRequestData pRequest, Guid guidValue)
        {
            pRequest.ResponseMimeType = "application/json";
            string strJson = TheCommonUtils.SerializeObjectToJSONString <Guid>(guidValue);

            pRequest.ResponseBuffer = TheCommonUtils.CUTF8String2Array(strJson);
            pRequest.StatusCode     = (int)eHttpStatusCode.OK;
            pRequest.DontCompress   = true;
            pRequest.AllowStatePush = false;
        }
Exemple #20
0
        public static void CreateJsonResponse <T>(TheRequestData pRequest, T responsedata)
        {
            pRequest.ResponseMimeType = "application/json";
            string strJson = TheCommonUtils.SerializeObjectToJSONString <T>(responsedata);

            pRequest.ResponseBuffer = TheCommonUtils.CUTF8String2Array(strJson);
            pRequest.StatusCode     = (int)eHttpStatusCode.OK;
            pRequest.DontCompress   = true;
            pRequest.AllowStatePush = false;
        }
        /// <summary>
        /// If this is a service the SimplexProc event will be called when the C-DEngine receives a new event sent by a subscriber to this service
        /// </summary>
        /// <param name="pMsg">The Message to be Processed</param>
        private void ProcessServiceMessage(TheProcessMessage pMsg)
        {
            string[] cmd = pMsg.Message.TXT.Split(':');
            switch (cmd[0]) //string 2 cases
            {
            case "WEBRELAY_RESPONSE":
                TheRequestData tState = TheCommonUtils.DeserializeJSONStringToObject <TheRequestData>(pMsg.Message.PLS);
                if (pMsg.Message.PLB != null && pMsg.Message.PLB.Length > 0)
                {
                    tState.ResponseBuffer = pMsg.Message.PLB;
                }
                tState.RequestUri = new Uri(tState.RequestUriString);
                //tState.SessionState = new TheSessionState() { SScopeID = pMsg.SID };
                sinkResults(tState);
                break;

            case "WEBRELAY_REQUEST":
                TheRequestData tData = TheCommonUtils.DeserializeJSONStringToObject <TheRequestData>(pMsg.Message.PLS);
                if (tData != null)
                {
                    tData.RequestUri = new Uri(tData.RequestUriString);
                    //tData.SessionState = new TheSessionState() { SScopeID = pMsg.SID };
                    if (pMsg.Message.PLB != null && pMsg.Message.PLB.Length > 0)
                    {
                        tData.PostData = pMsg.Message.PLB;
                    }
                    tData.CookieObject = pMsg.Message;
                    ReadHttpPage(tData, tData.SessionState.ARApp, null, sinkProcessResponse);
                    //InterceptHttpRequest(tData,tData.SessionState.ARApp);
                }
                break;

            case "WEBRELAY_REQUESTWRA":
                TSM             tTSM    = new TSM();
                List <TheThing> webApps = TheThingRegistry.GetThingsOfEngine(MyBaseEngine.GetEngineName());
                foreach (TheThing tApp in webApps)
                {
                    if (tApp.Address.Equals(pMsg.Message.PLS))
                    {
                        tTSM.PLS = $"/CDEWRA{tApp.cdeMID}" + TheThing.GetSafePropertyString(tApp, "HomePage");
                        break;
                    }
                }
                if (!string.IsNullOrEmpty(tTSM.PLS))
                {
                    string[]    org          = pMsg.Message.ORG.Split(':');
                    TheThing    senderThing  = TheThingRegistry.GetThingByMID(TheCommonUtils.CGuid(org[1]), true);
                    IBaseEngine senderEngine = TheThingRegistry.GetBaseEngine(senderThing, true);
                    tTSM.ENG = senderEngine.GetEngineName();
                    tTSM.TXT = "RESPONSEWRA";
                    TheCommCore.PublishToOriginator(pMsg.Message, tTSM, true);
                }
                break;
            }
        }
 private void sinkGetStatus(TheRequestData pReq)
 {
     if (MyServiceHealth == null)
     {
         return;
     }
     if (string.IsNullOrEmpty(pReq.ResponseBufferStr))
     {
         pReq.ResponseBufferStr = "";
     }
 }
 private void sinkRequestMeshInfo(TheRequestData request)
 {
     if (request != null)
     {
         request.ResponseMimeType = "application/json";
         string errorText = "";
         Dictionary <string, string> tQ = TheCommonUtils.ParseQueryString(request.RequestUri?.Query);
         if (tQ != null)
         {
             tQ.TryGetValue("MESHINFOTOKEN", out string meshInfoToken);
             if (tQ.TryGetValue("ORG", out string tOrg))
             {
                 Guid requestorMID = TheCommonUtils.CGuid(tOrg);
                 if (requestorMID != Guid.Empty)
                 {
                     TheMeshInfoStatus meshInfoStatus = TheQueuedSenderRegistry.GetMeshInfoForNodeID(requestorMID, meshInfoToken);
                     if (string.IsNullOrEmpty(meshInfoStatus?.StatusMessage))
                     {
                         request.StatusCode     = (int)eHttpStatusCode.OK;
                         request.ResponseBuffer = TheCommonUtils.CUTF8String2Array(TheCommonUtils.SerializeObjectToJSONString(meshInfoStatus.MeshInfo));
                     }
                     else
                     {
                         request.StatusCode = meshInfoStatus.StatusCode; //Better if meshInfoStatus also defines this as there are different messages (wrong MIT, too frequent tests etc)
                         errorText          = meshInfoStatus.StatusMessage;
                     }
                 }
                 else
                 {
                     request.StatusCode = 400;
                     errorText          = "Invalid or badly formed ORG parameter.";
                 }
             }
             else
             {
                 request.StatusCode = 400;
                 errorText          = "No ORG parameter found for mesh info request.";
             }
         }
         else
         {
             request.StatusCode = (int)eHttpStatusCode.AccessDenied;
             errorText          = "Access denied";
         }
         if (!string.IsNullOrEmpty(errorText))
         {
             TheErrorResponse errorResponse = new TheErrorResponse {
                 Error = errorText, CTIM = DateTimeOffset.Now
             };
             request.ResponseBuffer = TheCommonUtils.CUTF8String2Array(TheCommonUtils.SerializeObjectToJSONString(errorResponse));
         }
     }
 }
 private void InterceptHttpRequest(TheRequestData pRequest)
 {
     if (pRequest == null || pRequest.SessionState == null)
     {
         return;
     }
     if (pRequest.cdeRealPage.StartsWith("/CDEWRA"))
     {
         pRequest.SessionState.ARApp = TheCommonUtils.CGuid(pRequest.cdeRealPage.Substring(7, Guid.Empty.ToString().Length));
     }
     InterceptHttpRequest(pRequest, pRequest.SessionState.ARApp, MyBaseEngine, RequestTimeout);
 }
        internal bool GetSessionState(Guid pSessionID, TheRequestData pRequestData, bool NoCreate)
        {
            if (pRequestData == null)
            {
                return(false);
            }
            bool IsNewState = false;

            try
            {
                //lock (MySessionStates.MyRecordsLock) //CODE-REVIEW: Why? Validate get session back and has its own log. If Session is null, we can create a
                {
                    //TheSystemMessageLog.ToCo("SESS: Validating");
                    if (Guid.Empty != pSessionID)
                    {
                        pRequestData.SessionState = ValidateSEID(pSessionID);   //Measure Frequency
                    }
                    if (pRequestData.SessionState == null)
                    {
                        pRequestData.SessionState = GetSessionIDByDeviceID(pRequestData.DeviceID);
                        if (pRequestData.SessionState == null && NoCreate == false)
                        {
                            TheBaseAssets.MySYSLOG.WriteToLog(1234, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM("SSM", $"SESS: Creating new Session for {pRequestData.cdeRealPage}"));
                            pRequestData.SessionState = CreateSession(pRequestData, pSessionID);
                            //if (pSessionID != Guid.Empty) pRequestData.SessionState.cdeMID = pSessionID; //Moved to CreateSession to prevent double sessions in StorageMirror
                            if (pRequestData.SessionState.StateCookies == null)
                            {
                                pRequestData.SessionState.StateCookies = new cdeConcurrentDictionary <string, string>();
                            }
                            if (pRequestData.SessionState.StateCookies.ContainsKey(MySite.cdeMID.ToString() + "CDESEID"))
                            {
                                pRequestData.SessionState.StateCookies[MySite.cdeMID.ToString() + "CDESEID"] = TheCommonUtils.cdeEscapeString(TheCommonUtils.cdeEncrypt(TheCommonUtils.CStr(pRequestData.SessionState.cdeMID), TheBaseAssets.MySecrets.GetAI()));   //3.083: Must use SecureID
                            }
                            else
                            {
                                pRequestData.SessionState.StateCookies.TryAdd(MySite.cdeMID.ToString() + "CDESEID", TheCommonUtils.cdeEscapeString(TheCommonUtils.cdeEncrypt(TheCommonUtils.CStr(pRequestData.SessionState.cdeMID), TheBaseAssets.MySecrets.GetAI()))); //3.083: Must use SecureID
                            }
                            WriteSession(pRequestData.SessionState);
                            IsNewState = true;
                            //TheSystemMessageLog.ToCo(string.Format("SESS: Creating Done. New CNT:{0} ID:{1}", MySessionStates.Count, pRequestData.SessionState.cdeMID));
                        }
                    }
                    //if (!IsNewState)
                    //  TheSystemMessageLog.ToCo(string.Format("SESS: Found {0}", pRequestData.SessionState));
                }
            }
            catch (Exception e)
            {
                TheBaseAssets.MySYSLOG.WriteToLog(1233, new TSM("SSM", "<HR>GetSessionState: Exception occured:", e.ToString()));
            }
            return(IsNewState);
        }
        private void sinkProcessResponse(TheRequestData pRequest)
        {
            if (pRequest.StatusCode >= 400 && pRequest.ResponseBuffer == null && !string.IsNullOrEmpty(pRequest.ErrorDescription))
            {
                pRequest.ResponseBuffer = TheCommonUtils.CUTF8String2Array(pRequest.ErrorDescription);
            }
            if (pRequest.ResponseBuffer == null && string.IsNullOrEmpty(pRequest.ResponseBufferStr))
            {
                pRequest.ResponseBuffer = TheCommonUtils.CUTF8String2Array("EMPTY");
            }
            if (pRequest.ResponseMimeType.StartsWith("text/html") || pRequest.ResponseMimeType.Contains("javascript"))  //OK
            {
                pRequest.ResponseBufferStr = TheCommonUtils.CArray2UTF8String(pRequest.ResponseBuffer);
            }
            string tReqUri = pRequest.RequestUri.Host;

            if (pRequest.RequestUri.Port != 80)
            {
                tReqUri += ":" + pRequest.RequestUri.Port;
            }
            if (!string.IsNullOrEmpty(pRequest.ResponseBufferStr) && (pRequest.ResponseMimeType.StartsWith("text/html") || pRequest.ResponseMimeType.Contains("javascript")) && pRequest.ResponseBufferStr.IndexOf(tReqUri, StringComparison.CurrentCultureIgnoreCase) >= 0)
            {
                if (pRequest.SessionState.ARApp != Guid.Empty)
                {
                    TheRelayAppInfo tMyApp = TheThingRegistry.GetThingObjectByMID(MyBaseEngine.GetEngineName(), pRequest.SessionState.ARApp) as TheRelayAppInfo; //MyRelayApps.MyMirrorCache.GetEntryByFunc(s => s.cdeMID.Equals(pRequest.SessionState.ARApp));
                    if (tMyApp != null)
                    {
                        Uri tCloudUri = new Uri(pRequest.RequestUriString);
                        //pRequest.ResponseBufferStr = pRequest.ResponseBufferStr.Replace(pRequest.RequestUri.Host + ":" + pRequest.RequestUri.Port, new Uri(tMyApp.CloudUrl).Host + ":" + new Uri(tMyApp.CloudUrl).Port);
                        pRequest.ResponseBufferStr = pRequest.ResponseBufferStr.Replace(pRequest.RequestUri.Scheme + "://" + tReqUri, tCloudUri.Scheme + "://" + tCloudUri.Host + ":" + tCloudUri.Port);
                        pRequest.ResponseBuffer    = TheCommonUtils.CUTF8String2Array(pRequest.ResponseBufferStr);
                    }
                }
            }
            TheBaseAssets.MySYSLOG.WriteToLog(400, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM(MyBaseEngine.GetEngineName(), string.Format("Response Bytes:{1} For Page:{0} Sent", pRequest.cdeRealPage, pRequest.ResponseBuffer != null ? pRequest.ResponseBuffer.Length : 0), eMsgLevel.l3_ImportantMessage));
            if (pRequest.ResponseBuffer != null)
            {
                //TheCommonUtils.SleepOneEye(5000, 100);
                TSM message3 = new TSM(MyBaseEngine.GetEngineName(), "WEBRELAY_RESPONSE")
                {
                    PLB = pRequest.ResponseBuffer
                };
                pRequest.ResponseBuffer    = null;
                pRequest.ResponseBufferStr = null;
                pRequest.RequestUriString  = pRequest.RequestUri.ToString();
                TSM tMSG = pRequest.CookieObject as TSM;
                pRequest.CookieObject = null;
                pRequest.PostData     = null;
                message3.PLS          = TheCommonUtils.SerializeObjectToJSONString(pRequest);
                TheCommCore.PublishToOriginator(tMSG, message3);
            }
        }
Exemple #27
0
 private void sinkRelay(TheRequestData pRequest)
 {
     pRequest.ResponseMimeType  = "text/html";
     pRequest.ResponseBufferStr = "<html>"
                                  + "    <body>"
                                  + "        <h1>This is My *Dynamic* Relay Server</h1>"
                                  + "    </body>"
                                  + "</html>";
     pRequest.ResponseBuffer = TheCommonUtils.CUTF8String2Array(pRequest.ResponseBufferStr);
     pRequest.StatusCode     = (int)eHttpStatusCode.OK;
     pRequest.DontCompress   = true;
     pRequest.AllowStatePush = false;
 }
Exemple #28
0
 private void parseRequest(TheRequestData pReqData)
 {
     firstRequestLine = streamReadLine(mRequestStream);
     string[] tokens = firstRequestLine.Split(' ');
     if (tokens.Length != 3)
     {
         throw new Exception("HttpMidiServer: invalid http request head-line");
     }
     pReqData.HttpMethod     = tokens[0].ToUpper();
     pReqData.RequestUri     = tokens[1].StartsWith("http", StringComparison.OrdinalIgnoreCase) ? TheCommonUtils.CUri(tokens[1], false) : TheCommonUtils.CUri(TheBaseAssets.MyServiceHostInfo.GetPrimaryStationURL(false) + tokens[1], false);
     pReqData.HttpVersionStr = tokens[2];
     pReqData.HttpVersion    = TheCommonUtils.CDbl(pReqData.HttpVersionStr.Split('/')[1]);
 }
        private static Guid CreateToken(TheRequestData pRequest)
        {
            Guid pNewToken = Guid.NewGuid();

            //DateTime pNow = DateTime.Now;

            //if (dictValidAccessTokens == null)
            //    InitAccessTokenTable();

            //dictValidAccessTokens[pNewToken] = pNow;

            return(pNewToken);
        }
Exemple #30
0
        private void sinkProcessBand(TheRequestData pRequest)
        {
            if (pRequest == null)
            {
                return;
            }
            if (IsInterceptorProcessing)
            {
                return;
            }

            IsInterceptorProcessing = true;
            try
            {
                if (pRequest.RequestUri != null && !string.IsNullOrEmpty(pRequest.RequestUri.Query) && pRequest.RequestUri.Query.Length > 1)
                {
                    string[] QParts = pRequest.RequestUri.Query.Split('=');
                    if (QParts.Length > 1 && QParts[0].ToUpper() == "?SID")
                    {
                        lock (LastMsgs.MyLock)
                        {
                            string msg   = "ERR: No Message from target, yet";
                            string token = TheScopeManager.GetTokenFromScrambledScopeID(TheScopeManager.GetScrambledScopeIDFromEasyID(QParts[1])) + "@";
                            if (TheScopeManager.IsValidScopeID(TheScopeManager.GetScrambledScopeIDFromEasyID(QParts[1])))
                            {
                                msg             = ReturnLastMessage();
                                LastMsgs[token] = msg;
                            }
                            else
                            {
                                TSM tTSM = new TSM(MyBaseEngine.GetEngineName(), "GET_LAST_MSG");
                                tTSM.SID = TheScopeManager.GetScrambledScopeIDFromEasyID(QParts[1]);
                                TheCommCore.PublishToService(tTSM);
                                //TODO: Wait here until SET_LAST_MSG returns
                                if (LastMsgs.ContainsKey(token))
                                {
                                    msg = LastMsgs[token];
                                }
                            }
                            pRequest.ResponseBuffer   = TheCommonUtils.CUTF8String2Array(msg);
                            pRequest.StatusCode       = 200;
                            pRequest.ResponseMimeType = "text/html";
                            LastMsgs.RemoveNoCare(token);
                        }
                    }
                }
            }
            catch { }
            IsInterceptorProcessing = false;
        }