예제 #1
0
        virtual internal TheThing.TheThingSubscription GetSubscriptionInfo(bool?bGeneralize)
        {
            TheThingReference thingReference;
            var tThing = GetThing();

            if (tThing != null)
            {
                thingReference = new TheThingReference(tThing);
                if (bGeneralize == true)
                {
                    thingReference.ThingMID = null;
                }
            }
            else
            {
                thingReference = new TheThingReference()
                {
                    ThingMID          = (bGeneralize == false && TheCommonUtils.CGuid(this.ThingMID) != Guid.Empty) ? (Guid?)TheCommonUtils.CGuid(this.ThingMID) : null,
                    EngineName        = this.EngineName,
                    DeviceType        = this.DeviceType,
                    FriendlyName      = this.FriendlyName,
                    PropertiesToMatch = TheSenderThing.CStringToDict(this.PropertiesToMatch),
                };
            }

            var sub = new TheThing.TheThingSubscription
            {
                SubscriptionId   = this.cdeMID,
                AddThingIdentity = this.AddThingIdentity,
                SamplingWindow   = this.ChangeBufferTimeBucketSize,
                ContinueMatching = this.ContinueMatching,
                CooldownPeriod   = this.ChangeBufferLatency,
                ThingReference   = thingReference,

                EventFormat            = this.EventFormat,
                ForceAllProperties     = this.ForceAllProperties,
                ForceConfigProperties  = this.ForceConfigProperties,
                IgnoreExistingHistory  = this.IgnoreExistingHistory,
                IgnorePartialFailure   = this.IgnorePartialFailure,
                KeepDurableHistory     = this.KeepDurableHistory,
                MaxHistoryCount        = this.MaxHistoryCount,
                MaxHistoryTime         = this.MaxHistoryTime,
                PartitionKey           = this.PartitionKey,
                PreserveOrder          = this.PreserveOrder,
                PropertiesExcluded     = TheCommonUtils.CStringToList(this.PropertiesExcluded, ','),
                PropertiesIncluded     = TheCommonUtils.CStringToList(this.PropertiesIncluded, ','),
                SendInitialValues      = this.SendInitialValues,
                SendUnchangedValue     = this.SendUnchangedValue,
                StaticProperties       = TheSenderThing.CStringToDict(this.StaticProperties),
                TargetName             = this.TargetName,
                TargetType             = this.TargetType,
                TargetUnit             = this.TargetUnit,
                TokenExpirationInHours = this.TokenExpirationInHours,
            };

            return(sub);
        }
예제 #2
0
 internal ICollection <string> CombineSubscriptions(string pTopics, out bool WasUpdated, bool AreOwnedSubs = false)
 {
     WasUpdated = false;
     if (string.IsNullOrEmpty(pTopics))
     {
         return(MySubscriptions.TheKeys);
     }
     lock (CombineSubscriptionLock)
     {
         List <string> subs = TheCommonUtils.CStringToList(pTopics, ';');
         return(CombineSubscriptions(subs, out WasUpdated, AreOwnedSubs));
     }
 }
예제 #3
0
        void sinkServiceInfo(TSM pMsgMessage)
        {
            if (string.IsNullOrEmpty(pMsgMessage?.PLS))
            {
                return;
            }
            var MyInfo = TheCommonUtils.DeserializeJSONStringToObject <List <TheNodeTopics> >(pMsgMessage.PLS);

            int bk = 0;

            foreach (TheFootPrints tf in MyFootPrints.MyMirrorCache.TheValues)
            {
                tf.Counter = 0;
                tf.IsDirty = false;
            }
            if (MyInfo?.Count > 0)
            {
                foreach (var tIn in MyInfo)
                {
                    if (tIn.NodeType == cdeSenderType.CDE_JAVAJASON)
                    {
                        bk++;
                    }
                    else
                    {
                        foreach (TheFootPrints tf in MyFootPrints.MyMirrorCache.TheValues)
                        {
                            List <string> tFs = TheCommonUtils.CStringToList(tf.Footprint, ';');
                            if (IsListInList(tIn.Topics, tFs) && (tf.ExactCount == 0 || tf.ExactCount == tIn.Topics.Count))
                            {
                                tf.Counter++;
                                tf.IsDirty = true;
                            }
                        }
                    }
                }
                TheThing.SetSafePropertyNumber(MyBaseThing, "BrowserCount", bk);
            }
            foreach (TheFootPrints tf in MyFootPrints.MyMirrorCache.TheValues)
            {
                if (tf.IsDirty || tf.Counter == 0)
                {
                    MyFootPrints.UpdateItem(tf);
                    TheThing.SetSafePropertyNumber(MyBaseThing, $"{tf.NodeType}_Count", tf.Counter);
                }
            }
        }
예제 #4
0
        public void ProcessHttpRequest(HttpListenerContext mContext)
        {
            TheRequestData tRequestData = new TheRequestData();

            try
            {
                tRequestData.RequestUri = mContext.Request.Url;
                // TheSystemMessageLog.ToCo(tRequestData.RequestUri.ToString(), true);
                tRequestData.UserAgent        = mContext.Request.UserAgent;
                tRequestData.ServerTags       = null;
                tRequestData.HttpMethod       = mContext.Request.HttpMethod; //NEW 3.200
                tRequestData.Header           = TheCommonUtils.cdeNameValueToDirectory(mContext.Request.Headers);
                tRequestData.ResponseMimeType = mContext.Request.ContentType;

                tRequestData.ClientCert = mContext.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 (TheBaseAssets.MyServiceHostInfo.DisableNMI && !string.IsNullOrEmpty(err))
                    {
                        mContext.Response.StatusCode = (int)eHttpStatusCode.NotAcceptable;
                        mContext.Response.OutputStream.Close();
                        return;
                    }
                }

                if (mContext.Request.InputStream != null)
                {
#if CDE_NET4 || CDE_NET45
                    using (MemoryStream ms = new MemoryStream())
                    {
                        mContext.Request.InputStream.CopyTo(ms);
                        tRequestData.PostData = ms.ToArray();
                    }
#else
                    byte[] buffer = new byte[TheBaseAssets.MAX_MessageSize[0]];
                    using (MemoryStream ms = new MemoryStream())
                    {
                        int read;
                        while ((read = mContext.Request.InputStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            ms.Write(buffer, 0, read);
                        }
                        tRequestData.PostData = ms.ToArray();
                    }
#endif

                    tRequestData.PostDataLength = tRequestData.PostData.Length;
                }

                if (TheCommCore.MyHttpService != null)
                {
                    TheCommCore.MyHttpService.cdeProcessPost(tRequestData);
                }
            }
            catch (Exception e)
            {
                TheBaseAssets.MySYSLOG.WriteToLog(4350, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("HttpMidiServer", "ProcessRequest Error:" + firstRequestLine, eMsgLevel.l1_Error, e.ToString()));
                tRequestData.ResponseBuffer = TheCommonUtils.CUTF8String2Array(e.ToString());
                tRequestData.StatusCode     = (int)eHttpStatusCode.ServerError;
            }

            if ((tRequestData.ResponseBuffer == null && tRequestData.StatusCode != 200) || tRequestData.StatusCode == 404)    //NEW:UPNP
            {
                tRequestData.ResponseBufferStr  = "<html><head><meta http-equiv=\"Expires\" content=\"0\" /><meta http-equiv=\"Cache-Control\" content=\"no-cache\" /><meta http-equiv=\"Pragma\" content=\"no-cache\" /></html><body style=\"background-color: " + TheBaseAssets.MyServiceHostInfo.BaseBackgroundColor + ";\"><table width=\"100%\" style=\"height:100%;\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr><td style=\"text-align:center;\"><p style=\"color: " + TheBaseAssets.MyServiceHostInfo.BaseForegroundColor + "; font-family: Arial; font-size: 36px\">";
                tRequestData.ResponseBufferStr += string.Format("Resource {0} not found", tRequestData.RequestUri);
                tRequestData.ResponseBufferStr += "</p></td></tr></table></body></HTML>";
                tRequestData.ResponseMimeType   = "text/html";
                tRequestData.ResponseBuffer     = TheCommonUtils.CUTF8String2Array(tRequestData.ResponseBufferStr);
                tRequestData.StatusCode         = (int)eHttpStatusCode.NotFound;
            }

            try
            {
                if (tRequestData.AllowStatePush && tRequestData.ResponseBuffer != null &&
                    (tRequestData.StatusCode == (int)eHttpStatusCode.OK || tRequestData.StatusCode == (int)eHttpStatusCode.PermanentMoved))
                {
                    if (tRequestData.SessionState != null && tRequestData.SessionState.StateCookies != null && tRequestData.SessionState.StateCookies.Count > 0)
                    {
                        string tCookie = "";
                        foreach (string nam in tRequestData.SessionState.StateCookies.Keys)
                        {
                            try
                            {
                                if (tCookie.Length > 0)
                                {
                                    tCookie += ";";
                                }
                                string[] cp = tRequestData.SessionState.StateCookies[nam].Split(';');
                                tCookie  = "";
                                tCookie += $"{nam}={cp[0]}; SameSite=none; Secure";
                                mContext.Response.Headers.Add(HttpResponseHeader.SetCookie, tCookie);
                            }
                            catch
                            {
                                //ignored
                            }
                        }
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(tRequestData.cdeRealPage) && tRequestData.cdeRealPage.StartsWith("/cdeClean", StringComparison.OrdinalIgnoreCase) &&
                        tRequestData.Header != null && tRequestData.Header.ContainsKey("Cookie"))
                    {
                        string cookieDate   = DateTime.UtcNow.AddMilliseconds(100).ToString("ddd, dd-MMM-yyyy H:mm:ss"); //Offset not needed
                        string cookieHeader = tRequestData.Header.cdeSafeGetValue("Cookie");
                        if (!string.IsNullOrEmpty(cookieHeader))
                        {
                            string        tCookie  = "";
                            List <string> tCookies = TheCommonUtils.CStringToList(cookieHeader, ';');
                            foreach (string t in tCookies)
                            {
                                if (tCookie.Length > 0)
                                {
                                    tCookie += ";";
                                }
                                string[] tc = t.Split('=');
                                tCookie += string.Format("{0}=;Path=/;Expires={1} GMT", tc[0], cookieDate);
                            }
                            mContext.Response.Headers.Add(HttpResponseHeader.SetCookie, tCookie);
                        }
                    }
                }

                if (!tRequestData.DontCompress)
                {
                    if (tRequestData.AllowCaching && !TheBaseAssets.MyServiceHostInfo.DisableCache)
                    {
                        mContext.Response.AddHeader("Cache-Control", $"max-age={TheBaseAssets.MyServiceHostInfo.CacheMaxAge}, public");
                    }
                    else
                    {
                        mContext.Response.AddHeader("Cache-Control", "no-cache");
                    }
                    mContext.Response.AddHeader("cdeDeviceID", TheBaseAssets.MyServiceHostInfo.MyDeviceInfo.DeviceID.ToString());
                    if (tRequestData.StatusCode > 300 && tRequestData.StatusCode < 400 && tRequestData.Header != null)
                    {
                        mContext.Response.AddHeader("Location", tRequestData.Header.cdeSafeGetValue("Location"));
                    }
                }
                else
                {
                    mContext.Response.Headers.Clear();
                }

                mContext.Response.Headers.Set(HttpResponseHeader.Server, "C-DEngine V4");
                if (TheBaseAssets.MyServiceHostInfo.IsSSLEnforced)
                {
                    mContext.Response.Headers.Set("Strict-Transport-Security", "max-age=298000; includeSubDomains; preload"); //HSTS Header for SSL sites...test still required
                    mContext.Response.Headers.Set("X-Frame-Options", "sameorigin");                                           //iFrame protection Header for SSL sites...test still required
                }

                var tCors = TheBaseAssets.MySettings.GetSetting("Access-Control-Allow-Origin");
                if (!string.IsNullOrEmpty(tCors))
                {
                    mContext.Response.AppendHeader("Access-Control-Allow-Origin", tCors);
                }
                if (!string.IsNullOrEmpty(tRequestData.AllowedMethods))
                {
                    mContext.Response.AppendHeader("Access-Control-Allow-Methods", tRequestData.AllowedMethods);
                }
                if (!string.IsNullOrEmpty(tRequestData.AllowedMethods))
                {
                    mContext.Response.AppendHeader("Access-Control-Allow-Headers", tRequestData.AllowedHeaders);
                }

                mContext.Response.StatusCode = tRequestData.StatusCode;
                if (tRequestData.StatusCode != 200)
                {
                    TheCDEKPIs.IncrementKPI(eKPINames.BruteDelay);
                    //Security Fix: ID#770 - wait 200 ms before returning anything with error code to limit BruteForce
                    TheCommonUtils.SleepOneEye(200, 100);
                }
                mContext.Response.ContentType = tRequestData.ResponseMimeType;

                if (tRequestData.ResponseBuffer != null)
                {
                    if (!tRequestData.DontCompress && (TheBaseAssets.MyServiceHostInfo.IsOutputCompressed || (tRequestData.Header != null && tRequestData.Header.ContainsKey("Accept-Encoding") && tRequestData.Header["Accept-Encoding"].Contains("gzip"))))
                    {
                        byte[] bBuffer = TheCommonUtils.cdeCompressBuffer(tRequestData.ResponseBuffer, 0, tRequestData.ResponseBuffer.Length);
                        mContext.Response.AddHeader("Content-Encoding", "gzip");
                        mContext.Response.ContentLength64 = bBuffer.Length;
                        mContext.Response.OutputStream.Write(bBuffer, 0, bBuffer.Length);
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(tRequestData.ResponseEncoding))
                        {
                            mContext.Response.AddHeader("Content-Encoding", tRequestData.ResponseEncoding);
                        }
                        mContext.Response.ContentLength64 = tRequestData.ResponseBuffer.Length;
                        mContext.Response.OutputStream.Write(tRequestData.ResponseBuffer, 0, tRequestData.ResponseBuffer.Length);
                    }
                }
                if (tRequestData.DisableChunking)
                {
                    mContext.Response.SendChunked = false;
                }
                if (tRequestData.DisableKeepAlive)
                {
                    mContext.Response.KeepAlive = false;
                }
                mContext.Response.OutputStream.Close();
            }
            catch (Exception ee)
            {
                TheBaseAssets.MySYSLOG.WriteToLog(4351, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM("HttpMidiServer", "HttpWriteResponse Error", eMsgLevel.l1_Error, ee.ToString()));
            }
        }