Beispiel #1
0
        /// <summary>
        /// Create a new node
        /// </summary>
        /// <param name="exchange">Information on current conversation</param>
        protected override void DoPost(CoapExchange exchange)
        {
            Request request = exchange.Request;
            WebLink linkInfo;

            //  Parse the content based on the content type.
            //  Assume content-type of =40

            if (request.HasOption(OptionType.ContentFormat))
            {
                switch (request.ContentFormat)
                {
                case MediaType.ApplicationLinkFormat:
                    linkInfo = LinkFormat.Parse(request.PayloadString).First();
                    break;

                case 64:
                    linkInfo = LinkFormat.Parse(request.PayloadString).First();
                    break;

                default:
                    exchange.Respond(StatusCode.BadRequest);
                    return;
                }
            }
            else
            {
                linkInfo = LinkFormat.Parse(request.PayloadString).First();
            }

            //  Is this a single level create?

            //  Create the topic

            int maxAge = 0;

            if (request.HasOption(OptionType.MaxAge))
            {
                maxAge = request.GetFirstOption(OptionType.MaxAge).IntValue;
            }

            IResource child;

            if (linkInfo.Attributes.GetContentTypes().Any(p =>
                                                          p.Equals("40")
                                                          ))
            {
                child = new PubSubResource(linkInfo.Uri, false)
                {
                    MaxAge = maxAge
                };
            }
            else
            {
                child = new PubSubLeaf(linkInfo.Uri)
                {
                    MaxAge = maxAge
                };
                foreach (string key in linkInfo.Attributes.Keys)
                {
                    bool f = true;
                    foreach (string value in linkInfo.Attributes.GetValues(key))
                    {
                        child.Attributes.Add(key, value);
                        f = false;
                    }
                    if (f)
                    {
                        child.Attributes.Add(key);
                    }
                }
            }


            this.Add(child);

            exchange.LocationPath = child.Uri;
            exchange.Respond(StatusCode.Created);
        }
Beispiel #2
0
 protected override void DoDelete(CoapExchange exchange)
 {
     this.Delete();
     exchange.Respond(StatusCode.Deleted);
 }
Beispiel #3
0
        protected override void DoPost(CoapExchange exchange)
        {
            byte[]         body = exchange.Request.Payload;
            EdhocResponder edhoc;

            try {
                switch (body[1] & 0xf)
                {
                case 1:
                    edhoc            = EdhocResponder.ParseMessage1(body);
                    edhoc.SigningKey = _signKey;
                    body             = edhoc.CreateMessage2();
                    exchange.Respond(CoAP.StatusCode.Changed, body);
                    break;

                case 4:
                    edhoc = EdhocResponder.ParseMessage1(body);
                    OneKey y = null;
                    foreach (OneKey x in _allKeys)
                    {
                        if (x.ContainsName(CoseKeyKeys.KeyIdentifier))
                        {
                            if (x.HasKid(edhoc.KeyIdentifier))
                            {
                                if (y != null)
                                {
                                    exchange.Respond(CoAP.StatusCode.BadRequest);
                                    return;
                                }
                                y = new OneKey(x.AsCBOR());
                            }
                        }
                    }

                    if (y == null)
                    {
                        exchange.Respond(CoAP.StatusCode.BadRequest);
                        return;
                    }

                    if (!y[CoseKeyKeys.KeyType].Equals(GeneralValues.KeyType_Octet))
                    {
                        exchange.Respond(CoAP.StatusCode.BadRequest);
                        return;
                    }

                    edhoc.SharedSecret = y;

                    body = edhoc.CreateMessage2();
                    exchange.Respond(CoAP.StatusCode.Changed, body);
                    break;

                case 3:
                    edhoc = EdhocResponder.ParseMessage3(body, _allKeys);
                    exchange.Respond(StatusCode.Changed);

                    OSCOAP.SecurityContext ctx = edhoc.CreateSecurityContext();
                    OSCOAP.SecurityContextSet.AllContexts.Add(ctx);
                    break;

                case 6:
                    edhoc = EdhocResponder.ParseMessage3(body, _allKeys);
                    exchange.Respond(CoAP.StatusCode.Changed);

                    OSCOAP.SecurityContext ctx2 = edhoc.CreateSecurityContext();
                    OSCOAP.SecurityContextSet.AllContexts.Add(ctx2);
                    break;

                default:
                    exchange.Respond(CoAP.StatusCode.BadRequest);
                    break;
                }
            }
            catch (Exception e) {
                CBORObject obj = CBORObject.NewArray();
                obj.Add(0);
                obj.Add(e.ToString());
                exchange.Respond(CoAP.StatusCode.Content, obj.EncodeToBytes());
            }
        }
Beispiel #4
0
 protected override void DoPut(CoapExchange exchange)
 {
     exchange.LocationPath = "/here/it/is";
     exchange.Respond(StatusCode.Changed);
 }
Beispiel #5
0
        protected override void DoPost(CoapExchange exchange)
        {
            Task.Run(async() =>
            {
                try
                {
                    Int32 ct = MediaType.TextPlain;
                    Dictionary <string, object> keyValues = new Dictionary <string, object>();
                    if ((ct = MediaType.NegotiationContent(ct, _supported, exchange.Request.GetOptions(OptionType.Accept))) == MediaType.Undefined)
                    {
                        exchange.Respond(StatusCode.NotAcceptable, "supported list: ApplicationJson,TextPlain,TextXml,ApplicationOctetStream");
                        exchange.Reject();
                    }
                    else
                    {
                        if (!exchange.Request.UriQueries.Any())
                        {
                            exchange.Respond(StatusCode.BadRequest, "Forgot the parameters?");
                            exchange.Reject();
                        }
                        else
                        {
                            var querys   = exchange.Request.UriQueries.ToArray();
                            var acctoken = exchange.Request.UriQueries.FirstOrDefault();
                            switch (ct)
                            {
                            case MediaType.ApplicationJson:
                            case MediaType.TextPlain:
                                keyValues = JToken.Parse(exchange.Request.PayloadString)?.JsonToDictionary();
                                break;

                            case MediaType.TextXml:
                                if (querys.Length >= 2)
                                {
                                    var xml = new System.Xml.XmlDocument();
                                    try
                                    {
                                        xml.LoadXml(exchange.Request.PayloadString);
                                    }
                                    catch (Exception ex)
                                    {
                                        exchange.Respond(StatusCode.BadRequest, $"Can't load xml ,{ex.Message}");
                                    }
                                    keyValues.Add(querys[1], xml);
                                }
                                else
                                {
                                    exchange.Respond(StatusCode.BadRequest, "You did not specify  key name for xml.");
                                    exchange.Reject();
                                }
                                break;

                            case MediaType.ApplicationOctetStream:
                                if (querys.Length >= 2)
                                {
                                    keyValues.Add(querys[1], exchange.Request.Payload);
                                }
                                else
                                {
                                    exchange.Respond(StatusCode.BadRequest, "You did not specify  key name for binary.");
                                    exchange.Reject();
                                }
                                break;

                            default:
                                break;
                            }
                            var mcr = await _dbContext.DeviceIdentities.Include(d => d.Device).FirstOrDefaultAsync(di => di.IdentityType == IdentityType.AccessToken && di.IdentityId == acctoken);
                            var dev = mcr?.Device;
                            if (mcr != null && dev != null)
                            {
                                switch (_res)
                                {
                                case CoApRes.Attributes:
                                    _queue.Enqueue(new RawMsg()
                                    {
                                        MsgType = MsgType.CoAP, MsgBody = keyValues, DataCatalog = DataCatalog.AttributeData, DataSide = DataSide.ClientSide, DeviceId = dev.Id
                                    });
                                    exchange.Respond(StatusCode.Changed, $"OK");
                                    break;

                                case CoApRes.Telemetry:
                                    _queue.Enqueue(new RawMsg()
                                    {
                                        MsgType = MsgType.CoAP, MsgBody = keyValues, DataCatalog = DataCatalog.AttributeData, DataSide = DataSide.ClientSide, DeviceId = dev.Id
                                    });
                                    exchange.Respond(StatusCode.Created, $"OK");
                                    break;

                                default:
                                    break;
                                }
                                exchange.Accept();
                            }
                            else
                            {
                                exchange.Respond(StatusCode.NotFound, "Can't found  device.");
                                exchange.Reject();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    exchange.Respond(StatusCode.BadRequest, ex.Message);
                    exchange.Reject();
                }
            });
        }
        protected override void DoPut(CoapExchange exchange)
        {
            Response response = Response.CreateResponse(exchange.Request, StatusCode.BadRequest);

            exchange.Respond(response);
        }
Beispiel #7
0
 protected override void DoGet(CoapExchange exchange)
 {
     database.GetProducts();
     exchange.Respond("Printed!");
 }
        protected override void DoGet(CoapExchange exchange)
        {
            if (!_fTellAboutOSCOAP)
            {
                exchange.Respond("Hello World!");
                return;
            }

            Console.WriteLine("GET on /hello with ");
            Console.WriteLine(System.DateTime.Now.ToLongDateString());
            Console.WriteLine(Com.AugustCellars.CoAP.Util.Utils.ToString(exchange.Request));

            if (exchange.Request.OscoapContext == null)
            {
                exchange.Respond("Hello World! -- I see no OSCOAP here");
            }
            else
            {
                Request request = exchange.Request;

                if (request.HasOption(OptionType.UriQuery))
                {
                    int      count    = 0;
                    Response response = new Response(StatusCode.Content);
                    foreach (Option options in  request.GetOptions(OptionType.UriQuery))
                    {
                        switch (options.StringValue)
                        {
                        case "first=1":
                            response.PayloadString = "Hello World!";
                            response.AddETag(new byte[] { 0x2b });
                            break;

                        case "second=1":
                        case "second=2":
                            if (!request.HasOption(OptionType.Accept) || request.GetFirstOption(OptionType.Accept).IntValue != 0)
                            {
                                response = new Response(StatusCode.BadRequest);
                                response.PayloadString = "Incorrect Accept option";
                            }
                            else
                            {
                                response.PayloadString = "Hello World!";
                                response.AddETag(new byte[] { 0x2b });
                                response.MaxAge = 5;
                                response.RemoveOptions(OptionType.ContentFormat);
                            }
                            break;

                        default:
                            exchange.Respond(StatusCode.BadRequest, "UriQuery '" + options.StringValue + "' is unrecognized");
                            break;
                        }
                        count++;
                    }
                    if (count > 1)
                    {
                        exchange.Respond(StatusCode.BadRequest, "Only one UriQuery can be supplied");
                    }
                    else
                    {
                        exchange.Respond(response);
                    }
                }
                else
                {
                    String s;
                    if (exchange.Request.OscoapContext.GroupId == null)
                    {
                        s = String.Format("Hello World! -- I see OSCOAP w/ kid of '{0}'", UTF8Encoding.UTF8.GetString(exchange.Request.OscoapContext.Recipient.Id));
                    }
                    else
                    {
                        s = $"Hello World! -- I see OSCOAP w/ gid of '{Encoding.UTF8.GetString(exchange.Request.OscoapContext.GroupId)}'";
                    }
                    exchange.Respond(s);
                }
            }
        }
Beispiel #9
0
 protected override void DoGet(CoapExchange exchange)
 {
     exchange.Respond("Response " + (++_counter) + " from resource " + Name);
 }
Beispiel #10
0
        protected override void DoGet(CoapExchange exchange)
        {
#if true
            exchange.Respond(StatusCode.Content, _now.ToString(), MediaType.TextPlain);
#else
            Request request = exchange.Request;

            IEnumerable <Option> options = request.GetOptions(OptionType.Accept);
            int  useAccept   = MediaType.Undefined;
            bool acceptFound = false;

            foreach (var acccept in options)
            {
                switch (acccept.IntValue)
                {
                case MediaType.TextPlain:
                case MediaType.ApplicationCbor:
                    useAccept = acccept.IntValue;
                    break;

                default:
                    acceptFound = true;
                    break;
                }

                if (useAccept != MediaType.Undefined)
                {
                    break;
                }
            }

            if (useAccept == MediaType.Undefined)
            {
                if (acceptFound)
                {
                    exchange.Respond(StatusCode.UnsupportedMediaType);
                    return;
                }
                useAccept = MediaType.TextPlain;
            }

            Response response = Response.CreateResponse(request, StatusCode.Content);

            switch (useAccept)
            {
            case MediaType.TextPlain:
                string x = request.GetParameter("format");
                if (String.IsNullOrEmpty(x))
                {
                    response.PayloadString = _now.ToShortTimeString();
                }
                else
                {
                    response.PayloadString = _now.ToString(x);
                }
                request.ContentType = useAccept;
                break;

            case MediaType.ApplicationCbor:
                CBORObject obj = CBORObject.FromObject(_now);
                request.Payload     = obj.EncodeToBytes();
                request.ContentType = useAccept;
                break;
            }

            exchange.Respond(response);
#endif
        }
Beispiel #11
0
 protected override void DoGet(CoapExchange exchange)
 {
     exchange.Respond(RESPONSE_PAYLOAD);
 }
Beispiel #12
0
 protected override void DoGet(CoapExchange exchange)
 {
     exchange.Respond(StatusCode.Content, _now.ToString(), MediaType.TextPlain);
 }
        protected override void DoGet(CoapExchange exchange)
        {
            exchange.Respond("Hello World!");

            OneKey who = exchange.Request.TlsContext.AuthenticationKey;
        }
Beispiel #14
0
 /// <inheritdoc />
 protected override void DoDelete(CoapExchange exchange)
 {
     Parent.Remove(this);
     exchange.Respond(StatusCode.Deleted);
 }
Beispiel #15
0
 protected override void DoPut(CoapExchange exchange)
 {
     _content = exchange.Request.PayloadString;
     exchange.Respond(StatusCode.Changed);
 }
Beispiel #16
0
 // override this method to handle GET requests
 protected override void DoGet(CoapExchange exchange)
 {
     // now we get a request, respond it
     exchange.Respond("Hello World!");
 }
Beispiel #17
0
 protected override void DoPost(CoapExchange exchange)
 {
     exchange.Respond(SERVER_RESPONSE);
 }
 protected override void DoDelete(CoapExchange exchange)
 {
     _currentResponseText = "";
     exchange.Respond(StatusCode.Deleted);
 }
Beispiel #19
0
        protected override void DoGet(CoapExchange exchange)
        {
            String str = String.Format("Next sequence # will be {0}", _ctx.Sender.SequenceNumber + 1);

            exchange.Respond(str);
        }
Beispiel #20
0
 protected override void DoGet(CoapExchange exchange)
 {
     exchange.Respond("Hello World!");
 }
Beispiel #21
0
 protected override void DoPost(CoapExchange exchange)
 {
     exchange.LocationPath = "/location1/location2/location3";
     exchange.Respond(StatusCode.Changed);
 }
Beispiel #22
0
 protected override void DoGet(CoapExchange exchange)
 {
     exchange.Respond(payload);
 }
Beispiel #23
0
        /// <summary>
        /// Posting to this resource will cause a new resource to be created.
        /// </summary>
        /// <param name="exchange"></param>
        protected override void DoPost(CoapExchange exchange)
        {
            try {
                Request req = exchange.Request;

                //  If there is a content-format, then it must be "application/link-format"
                if (req.HasOption(OptionType.ContentFormat))
                {
                    if ((req.GetOptions(OptionType.ContentFormat).Count() != 1) && (req.GetFirstOption(OptionType.ContentFormat).IntValue != Application_Link_Format))
                    {
                        exchange.Respond(StatusCode.BadOption);
                        return;
                    }
                }

                //  Parse the payload
                IEnumerable <WebLink> fmt = LinkFormat.Parse(exchange.Request.PayloadString);
                if (fmt.Count() != 1)
                {
                    exchange.Respond(StatusCode.BadRequest);
                    return;
                }

                WebLink item = fmt.First();

                //  Ensure resource does not already exist

                foreach (IResource child in Children)
                {
                    if (child.Name == item.Uri)
                    {
                        exchange.Respond(StatusCode.Forbidden);
                        return;
                    }
                }

                Resource newResource;
                if (item.Attributes.Contains(LinkFormat.ContentType))
                {
                    if (item.Attributes.GetContentTypes().Count() == 1)
                    {
                        if (item.Attributes.GetContentTypes().First() == "application/link-format")
                        {
                            newResource = new PubSubResource(item.Uri);
                        }
                        else
                        {
                            newResource = new PubSubLeaf(item.Uri);
                        }
                    }
                    else
                    {
                        newResource = new PubSubLeaf(item.Uri);
                    }
                }
                else
                {
                    newResource = new PubSubLeaf(item.Uri);
                }

                foreach (string key in item.Attributes.Keys)
                {
                    IEnumerable <string> valueSet = item.Attributes.GetValues(key);
                    foreach (string value in valueSet)
                    {
                        newResource.Attributes.Add(key, value);
                    }
                }

                if (req.HasOption(OptionType.MaxAge))
                {
                    //  Figure out how to time out items M00TODO
                }

                this.Add(newResource);
                Response resp = new Response(StatusCode.Created);
                resp.LocationPath = this.Parent + "/" + item.Uri;
                exchange.Respond(resp);
            } catch (Exception)
            {
                exchange.Respond(StatusCode.BadRequest);
            }
        }