Example #1
0
        public CoapProtocolAdapter(PiraeusConfig config, IAuthenticator authenticator, IChannel channel, ILogger logger, HttpContext context = null)
        {
            this.context = context;
            this.logger  = logger;
            CoapConfigOptions options    = config.ObserveOption && config.NoResponseOption ? CoapConfigOptions.Observe | CoapConfigOptions.NoResponse : config.ObserveOption ? CoapConfigOptions.Observe : config.NoResponseOption ? CoapConfigOptions.NoResponse : CoapConfigOptions.None;
            CoapConfig        coapConfig = new CoapConfig(authenticator, config.CoapAuthority, options, config.AutoRetry,
                                                          config.KeepAliveSeconds, config.AckTimeoutSeconds, config.AckRandomFactor,
                                                          config.MaxRetransmit, config.NStart, config.DefaultLeisure, config.ProbingRate, config.MaxLatencySeconds);

            coapConfig.IdentityClaimType = config.ClientIdentityNameClaimType;
            coapConfig.Indexes           = config.GetClientIndexes();

            InitializeAuditor(config);

            Channel                = channel;
            Channel.OnClose       += Channel_OnClose;
            Channel.OnError       += Channel_OnError;
            Channel.OnOpen        += Channel_OnOpen;
            Channel.OnReceive     += Channel_OnReceive;
            Channel.OnStateChange += Channel_OnStateChange;
            session                = new CoapSession(coapConfig, context);

            if (Channel.State != ChannelState.Open)
            {
                Channel.OpenAsync().GetAwaiter();
                Channel.ReceiveAsync();
            }
        }
        private List <KeyValuePair <string, string> > GetIndexes(CoapUri coapUri)
        {
            List <KeyValuePair <string, string> > list = new List <KeyValuePair <string, string> >(coapUri.Indexes);

            if (coapUri.Indexes.Contains(new KeyValuePair <string, string>("~", "~")))
            {
                list.Remove(new KeyValuePair <string, string>("~", "~"));
                var query = config.GetClientIndexes().Where((ck) => ck.Key == session.Config.IdentityClaimType);
                if (query.Count() == 1)
                {
                    query.GetEnumerator().MoveNext();
                    list.Add(new KeyValuePair <string, string>(query.GetEnumerator().Current.Value, "~" + session.Identity));
                }
            }

            return(list.Count > 0 ? list : null);
        }
Example #3
0
        public RestProtocolAdapter(PiraeusConfig config, GraphManager graphManager, IChannel channel,
                                   HttpContext context, ILog logger = null)
        {
            this.config  = config;
            this.channel = channel;
            this.logger  = logger;
            method       = context.Request.Method.ToUpperInvariant();
            messageUri   = new MessageUri(context.Request);

            IdentityDecoder decoder =
                new IdentityDecoder(config.ClientIdentityNameClaimType, context, config.GetClientIndexes());

            identity = decoder.Id;
            indexes  = decoder.Indexes;
            adapter  = new OrleansAdapter(identity, channel.TypeId, "REST", graphManager, logger);
            if (method == "GET")
            {
                adapter.OnObserve += Adapter_OnObserve;
            }

            protocolType  = ProtocolType.REST;
            contentType   = messageUri.ContentType;
            resource      = messageUri.Resource;
            subscriptions = messageUri.Subscriptions;

            auditFactory = AuditFactory.CreateSingleton();
            if (config.AuditConnectionString != null &&
                config.AuditConnectionString.Contains("DefaultEndpointsProtocol"))
            {
                auditFactory.Add(new AzureTableAuditor(config.AuditConnectionString, "messageaudit"),
                                 AuditType.Message);
                auditFactory.Add(new AzureTableAuditor(config.AuditConnectionString, "useraudit"), AuditType.User);
            }
            else if (config.AuditConnectionString != null)
            {
                auditFactory.Add(new FileAuditor(config.AuditConnectionString), AuditType.Message);
                auditFactory.Add(new FileAuditor(config.AuditConnectionString), AuditType.User);
            }

            messageAuditor = auditFactory.GetAuditor(AuditType.Message);
            userAuditor    = auditFactory.GetAuditor(AuditType.User);
        }
Example #4
0
        public WsnProtocolAdapter(PiraeusConfig config, GraphManager graphManager, IChannel channel,
                                  HttpContext context, ILog logger = null)
        {
            this.config       = config;
            this.graphManager = graphManager;
            Channel           = channel;
            this.logger       = logger;

            IdentityDecoder decoder =
                new IdentityDecoder(config.ClientIdentityNameClaimType, context, config.GetClientIndexes());

            identity     = decoder.Id;
            localIndexes = decoder.Indexes;

            MessageUri messageUri = new MessageUri(context.Request);

            contentType   = messageUri.ContentType;
            cacheKey      = messageUri.CacheKey;
            resource      = messageUri.Resource;
            subscriptions = messageUri.Subscriptions != null ? new List <string>(messageUri.Subscriptions) : null;
            indexes       = messageUri.Indexes != null ? new List <KeyValuePair <string, string> >(messageUri.Indexes) : null;

            auditFactory = AuditFactory.CreateSingleton();
            if (config.AuditConnectionString != null &&
                config.AuditConnectionString.Contains("DefaultEndpointsProtocol"))
            {
                auditFactory.Add(new AzureTableAuditor(config.AuditConnectionString, "messageaudit"),
                                 AuditType.Message);
                auditFactory.Add(new AzureTableAuditor(config.AuditConnectionString, "useraudit"), AuditType.User);
            }
            else if (config.AuditConnectionString != null)
            {
                auditFactory.Add(new FileAuditor(config.AuditConnectionString), AuditType.Message);
                auditFactory.Add(new FileAuditor(config.AuditConnectionString), AuditType.User);
            }

            messageAuditor = auditFactory.GetAuditor(AuditType.Message);
            userAuditor    = auditFactory.GetAuditor(AuditType.User);
        }
Example #5
0
        public MqttProtocolAdapter(PiraeusConfig config, IAuthenticator authenticator, IChannel channel, ILogger logger, HttpContext context = null)
        {
            this.config = config;
            this.logger = logger;

            MqttConfig mqttConfig = new MqttConfig(config.KeepAliveSeconds, config.AckTimeoutSeconds, config.AckRandomFactor, config.MaxRetransmit, config.MaxLatencySeconds, authenticator, config.ClientIdentityNameClaimType, config.GetClientIndexes());


            this.context = context;
            session      = new MqttSession(mqttConfig);
            InitializeAuditor(config);


            Channel                = channel;
            Channel.OnClose       += Channel_OnClose;
            Channel.OnError       += Channel_OnError;
            Channel.OnStateChange += Channel_OnStateChange;
            Channel.OnReceive     += Channel_OnReceive;
            Channel.OnOpen        += Channel_OnOpen;
        }
Example #6
0
        private void Channel_OnOpen(object sender, ChannelOpenEventArgs e)
        {
            if (!Channel.IsAuthenticated)  //requires channel authentication
            {
                OnError?.Invoke(this, new ProtocolAdapterErrorEventArgs(Channel.Id, new SecurityException("Not authenticated.")));
                Channel.CloseAsync().Ignore();
                return;
            }

            if (e.Message.Method != HttpMethod.Post && e.Message.Method != HttpMethod.Get)
            {
                Channel.CloseAsync().Ignore();
                OnError?.Invoke(this, new ProtocolAdapterErrorEventArgs(Channel.Id, new SecurityException("Rest protocol adapter requires GET or POST only.")));
            }

            MessageUri      uri     = new MessageUri(e.Message);
            IdentityDecoder decoder = new IdentityDecoder(config.ClientIdentityNameClaimType, context, config.GetClientIndexes());

            identity = decoder.Id;

            adapter            = new OrleansAdapter(decoder.Id, "HTTP", "REST");
            adapter.OnObserve += Adapter_OnObserve;
            HttpRequestMessage request = (HttpRequestMessage)e.Message;

            AuditRecord record = new UserAuditRecord(Channel.Id, identity, config.ClientIdentityNameClaimType, Channel.TypeId, String.Format("REST-{0}", request.Method.ToString()), "Granted", DateTime.UtcNow);

            userAuditor?.WriteAuditRecordAsync(record).Ignore();

            if (request.Method == HttpMethod.Get)
            {
                foreach (var item in uri.Subscriptions)
                {
                    Task t = Task.Factory.StartNew(async() =>
                    {
                        await SubscribeAsync(item, decoder.Id, decoder.Indexes);
                    });

                    t.LogExceptions();
                }
            }

            if (request.Method == HttpMethod.Post)
            {
                byte[] buffer = request.Content.ReadAsByteArrayAsync().Result;
                Task   t      = Task.Factory.StartNew(async() =>
                {
                    EventMetadata metadata = await GraphManager.GetPiSystemMetadataAsync(uri.Resource);
                    EventMessage message   = new EventMessage(uri.ContentType, uri.Resource, ProtocolType.REST, buffer, DateTime.UtcNow, metadata.Audit);

                    if (!string.IsNullOrEmpty(uri.CacheKey))
                    {
                        message.CacheKey = uri.CacheKey;
                    }

                    List <KeyValuePair <string, string> > indexList = uri.Indexes == null ? null : new List <KeyValuePair <string, string> >(uri.Indexes);

                    await PublishAsync(decoder.Id, message, indexList);
                    await Channel.CloseAsync();
                });

                t.LogExceptions();
            }
        }