1 /* net.c -- CoAP network interface
3 * Copyright (C) 2010--2014 Olaf Bergmann <bergmann@tzi.org>
5 * This file is part of the CoAP library libcoap. Please see
6 * README for terms of use.
18 #elif HAVE_SYS_UNISTD_H
19 #include <sys/unistd.h>
21 #ifdef HAVE_SYS_TYPES_H
22 #include <sys/types.h>
24 #ifdef HAVE_SYS_SOCKET_H
25 #include <sys/socket.h>
27 #ifdef HAVE_NETINET_IN_H
28 #include <netinet/in.h>
30 #ifdef HAVE_ARPA_INET_H
31 #include <arpa/inet.h>
35 #include <lwip/pbuf.h>
37 #include <lwip/timers.h>
49 #if defined(WITH_POSIX) || defined(WITH_ARDUINO)
54 #define MOD_NAME ("net.c")
58 static inline coap_queue_t *
60 return (coap_queue_t *)coap_malloc(sizeof(coap_queue_t));
64 coap_free_node(coap_queue_t *node) {
67 #endif /* WITH_POSIX || WITH_ARDUINO */
70 #include <lwip/memp.h>
72 static void coap_retransmittimer_execute(void *arg);
73 static void coap_retransmittimer_restart(coap_context_t *ctx);
75 static inline coap_queue_t *
77 return (coap_queue_t *)memp_malloc(MEMP_COAP_NODE);
81 coap_free_node(coap_queue_t *node) {
82 memp_free(MEMP_COAP_NODE, node);
85 #endif /* WITH_LWIP */
88 # define DEBUG DEBUG_PRINT
92 #include "net/uip-debug.h"
94 clock_time_t clock_offset;
96 #define UIP_IP_BUF ((struct uip_ip_hdr *)&uip_buf[UIP_LLH_LEN])
97 #define UIP_UDP_BUF ((struct uip_udp_hdr *)&uip_buf[UIP_LLIPH_LEN])
99 void coap_resources_init();
100 void coap_pdu_resources_init();
102 unsigned char initialized = 0;
103 coap_context_t the_coap_context;
105 MEMB(node_storage, coap_queue_t, COAP_PDU_MAXCNT);
107 PROCESS(coap_retransmit_process, "message retransmit process");
109 static inline coap_queue_t *
111 return (coap_queue_t *)memb_alloc(&node_storage);
115 coap_free_node(coap_queue_t *node) {
116 memb_free(&node_storage, node);
118 #endif /* WITH_CONTIKI */
121 /** Callback to udp_recv when using lwIP. Gets called by lwIP on arriving
122 * packages, places a reference in context->pending_package, and calls
123 * coap_read to process the package. Thus, coap_read needs not be called in
124 * lwIP main loops. (When modifying this for thread-like operation, ie. if you
125 * remove the coap_read call from this, make sure that coap_read gets a chance
126 * to run before this callback is entered the next time.)
128 static void received_package(void *arg, struct udp_pcb *upcb, struct pbuf *p, ip_addr_t *addr, u16_t port)
130 struct coap_context_t *context = (coap_context_t *)arg;
132 LWIP_ASSERT("pending_package was not cleared.", context->pending_package == NULL);
134 context->pending_package = p; /* we don't free it, coap_read has to do that */
135 context->pending_address.addr = addr->addr; /* FIXME: this has to become address-type independent, probably there'll be an lwip function for that */
136 context->pending_port = port;
138 coap_read(context, -1); /* we want to read from unicast socket */
141 #endif /* WITH_LWIP */
143 unsigned int coap_adjust_basetime(coap_context_t *ctx, coap_tick_t now) {
144 unsigned int result = 0;
145 coap_tick_diff_t delta = now - ctx->sendqueue_basetime;
147 if (ctx->sendqueue) {
148 /* delta < 0 means that the new time stamp is before the old. */
150 ctx->sendqueue->t -= delta;
152 /* This case is more complex: The time must be advanced forward,
153 * thus possibly leading to timed out elements at the queue's
154 * start. For every element that has timed out, its relative
155 * time is set to zero and the result counter is increased. */
157 coap_queue_t *q = ctx->sendqueue;
159 while (q && (t + q->t < (coap_tick_t) delta)) {
166 /* finally adjust the first element that has not expired */
168 q->t = (coap_tick_t) delta - t;
173 /* adjust basetime */
174 ctx->sendqueue_basetime += delta;
179 int coap_insert_node(coap_queue_t **queue, coap_queue_t *node) {
184 /* set queue head if empty */
190 /* replace queue head if PDU's time is less than head's time */
192 if (node->t < q->t) {
195 q->t -= node->t; /* make q->t relative to node->t */
199 /* search for right place to insert */
201 node->t -= q->t; /* make node-> relative to q->t */
204 } while (q && q->t <= node->t);
206 /* insert new item */
208 q->t -= node->t; /* make q->t relative to node->t */
215 int coap_delete_node(coap_queue_t *node) {
219 coap_delete_pdu(node->pdu);
220 coap_free_node(node);
225 void coap_delete_all(coap_queue_t *queue) {
229 coap_delete_all(queue->next);
230 coap_delete_node(queue);
236 node = coap_malloc_node();
240 coap_log(LOG_WARNING, "coap_new_node: malloc\n");
245 memset(node, 0, sizeof *node);
250 coap_peek_next(coap_context_t *context) {
251 if (!context || !context->sendqueue)
254 return context->sendqueue;
258 coap_pop_next(coap_context_t *context) {
261 if (!context || !context->sendqueue)
264 next = context->sendqueue;
265 context->sendqueue = context->sendqueue->next;
266 if (context->sendqueue) {
267 context->sendqueue->t += next->t;
273 #ifdef COAP_DEFAULT_WKC_HASHKEY
274 /** Checks if @p Key is equal to the pre-defined hash key for.well-known/core. */
275 #define is_wkc(Key) \
276 (memcmp((Key), COAP_DEFAULT_WKC_HASHKEY, sizeof(coap_key_t)) == 0)
278 /* Implements a singleton to store a hash key for the .wellknown/core
281 is_wkc(coap_key_t k) {
282 static coap_key_t wkc;
283 static unsigned char _initialized = 0;
285 _initialized = coap_hash_path((unsigned char *)COAP_DEFAULT_URI_WELLKNOWN,
286 sizeof(COAP_DEFAULT_URI_WELLKNOWN) - 1, wkc);
288 return memcmp(k, wkc, sizeof(coap_key_t)) == 0;
293 coap_new_context(const coap_address_t *listen_addr) {
294 #if defined(WITH_POSIX) || defined(WITH_ARDUINO)
295 coap_context_t *c = (coap_context_t*)coap_malloc( sizeof( coap_context_t ) );
297 #endif /* WITH_POSIX || WITH_ARDUINO */
299 coap_context_t *c = memp_malloc(MEMP_COAP_CONTEXT);
300 #endif /* WITH_LWIP */
306 #endif /* WITH_CONTIKI */
310 coap_log(LOG_EMERG, "no listen address specified\n");
316 prng_init(LWIP_RAND());
317 #else /* WITH_LWIP */
318 prng_init((unsigned long)listen_addr ^ clock_offset);
319 #endif /* WITH_LWIP */
324 coap_log(LOG_EMERG, "coap_init: malloc:\n");
328 #endif /* not WITH_CONTIKI */
330 coap_resources_init();
331 coap_pdu_resources_init();
333 c = &the_coap_context;
335 #endif /* WITH_CONTIKI */
337 memset(c, 0, sizeof(coap_context_t));
339 /* set well-known sockfd to uninitialize value */
340 c->sockfd_wellknown = -1;
342 /* initialize message id */
343 prng((unsigned char * )&c->message_id, sizeof(unsigned short));
345 /* register the critical options that we know */
346 coap_register_option(c, COAP_OPTION_IF_MATCH);
347 coap_register_option(c, COAP_OPTION_URI_HOST);
348 coap_register_option(c, COAP_OPTION_IF_NONE_MATCH);
349 coap_register_option(c, COAP_OPTION_URI_PORT);
350 coap_register_option(c, COAP_OPTION_URI_PATH);
351 coap_register_option(c, COAP_OPTION_URI_QUERY);
352 coap_register_option(c, COAP_OPTION_ACCEPT);
353 coap_register_option(c, COAP_OPTION_PROXY_URI);
354 coap_register_option(c, COAP_OPTION_PROXY_SCHEME);
355 coap_register_option(c, COAP_OPTION_BLOCK2);
356 coap_register_option(c, COAP_OPTION_BLOCK1);
358 #if defined(WITH_POSIX) || defined(WITH_ARDUINO)
359 if (OCInitUDP((OCDevAddr *)listen_addr, (int32_t *)&(c->sockfd)) != ERR_SUCCESS) {
367 #endif /* WITH_POSIX || WITH_ARDUINO */
369 c->conn = udp_new(NULL, 0, NULL);
370 udp_bind(c->conn, listen_addr->port);
372 process_start(&coap_retransmit_process, (char *)c);
374 PROCESS_CONTEXT_BEGIN(&coap_retransmit_process);
375 #ifndef WITHOUT_OBSERVE
376 etimer_set(&c->notify_timer, COAP_RESOURCE_CHECK_TIME * COAP_TICKS_PER_SECOND);
377 #endif /* WITHOUT_OBSERVE */
378 /* the retransmit timer must be initialized to some large value */
379 etimer_set(&the_coap_context.retransmit_timer, 0xFFFF);
380 PROCESS_CONTEXT_END(&coap_retransmit_process);
382 #endif /* WITH_CONTIKI */
385 /* hard assert: this is not expected to fail dynamically */
386 LWIP_ASSERT("Failed to allocate PCB for CoAP", c->pcb != NULL);
388 udp_recv(c->pcb, received_package, (void*)c);
389 udp_bind(c->pcb, &listen_addr->addr, listen_addr->port);
391 c->timer_configured = 0;
398 void coap_free_context(coap_context_t *context) {
402 coap_delete_all(context->recvqueue);
403 coap_delete_all(context->sendqueue);
406 context->sendqueue = NULL;
407 coap_retransmittimer_restart(context);
410 #if defined(WITH_POSIX) || defined(WITH_ARDUINO)
411 /* coap_delete_list(context->subscriptions); */
412 OCClose( context->sockfd );
413 if (context->sockfd_wellknown != -1) {
414 OCClose( context->sockfd_wellknown );
416 coap_free( context );
419 udp_remove(context->pcb);
420 memp_free(MEMP_COAP_CONTEXT, context);
423 memset(&the_coap_context, 0, sizeof(coap_context_t));
425 #endif /* WITH_CONTIKI */
428 int coap_join_wellknown_group(coap_context_t *ctx,
429 const coap_address_t *multicast_addr) {
430 #if defined(WITH_POSIX) || defined(WITH_ARDUINO)
431 if (OCInitUDPMulticast((OCDevAddr *)multicast_addr,
432 (int32_t *)&(ctx->sockfd_wellknown)) != ERR_SUCCESS) {
440 int coap_option_check_critical(coap_context_t *ctx, coap_pdu_t *pdu,
441 coap_opt_filter_t unknown) {
443 coap_opt_iterator_t opt_iter;
446 coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
448 while (coap_option_next(&opt_iter)) {
450 /* The following condition makes use of the fact that
451 * coap_option_getb() returns -1 if type exceeds the bit-vector
452 * filter. As the vector is supposed to be large enough to hold
453 * the largest known option, we know that everything beyond is
456 if ((opt_iter.type & 0x01)
457 && coap_option_getb(ctx->known_options, opt_iter.type) < 1) {
458 debug("unknown critical option %d\n", opt_iter.type);
462 /* When opt_iter.type is beyond our known option range,
463 * coap_option_setb() will return -1 and we are safe to leave
465 if (coap_option_setb(unknown, opt_iter.type) == -1)
473 void coap_transaction_id(const coap_address_t *peer, const coap_pdu_t *pdu,
477 memset(h, 0, sizeof(coap_key_t));
479 /* Compare the complete address structure in case of IPv4. For IPv6,
480 * we need to look at the transport address only. */
483 switch (peer->addr.sa.sa_family) {
485 coap_hash((const unsigned char *)&peer->addr.sa, peer->size, h);
488 coap_hash((const unsigned char *)&peer->addr.sin6.sin6_port,
489 sizeof(peer->addr.sin6.sin6_port), h);
490 coap_hash((const unsigned char *)&peer->addr.sin6.sin6_addr,
491 sizeof(peer->addr.sin6.sin6_addr), h);
499 coap_hash((const unsigned char *)peer->addr, peer->size, h);
500 #endif /* WITH_ARDUINO */
502 #if defined(WITH_LWIP) || defined(WITH_CONTIKI)
503 /* FIXME: with lwip, we can do better */
504 coap_hash((const unsigned char *)&peer->port, sizeof(peer->port), h);
505 coap_hash((const unsigned char *)&peer->addr, sizeof(peer->addr), h);
506 #endif /* WITH_LWIP || WITH_CONTIKI */
508 coap_hash((const unsigned char * )&pdu->hdr->id, sizeof(unsigned short), h);
510 *id = ((h[0] << 8) | h[1]) ^ ((h[2] << 8) | h[3]);
513 coap_tid_t coap_send_ack(coap_context_t *context, const coap_address_t *dst,
514 coap_pdu_t *request, coap_send_flags_t flag) {
515 coap_pdu_t *response;
516 coap_tid_t result = COAP_INVALID_TID;
518 if (request && request->hdr->type == COAP_MESSAGE_CON) {
519 response = coap_pdu_init(COAP_MESSAGE_ACK, 0, request->hdr->id,
522 result = coap_send(context, dst, response, flag);
523 coap_delete_pdu(response);
529 #if defined(WITH_POSIX) || defined(WITH_ARDUINO)
530 /* releases space allocated by PDU if free_pdu is set */
532 coap_send_impl(coap_context_t *context,
533 const coap_address_t *dst,
536 int bytes_written = -1;
538 if ( !context || !dst || !pdu )
539 return bytes_written;
541 bytes_written = OCSendTo( context->sockfd, (uint8_t*)(pdu->hdr), pdu->length, 0,
543 debug("bytes_written %d\n", (int)bytes_written);
545 return bytes_written;
547 #endif /* WITH_POSIX || WITH_ARDUINO */
549 /* releases space allocated by PDU if free_pdu is set */
551 coap_send_impl(coap_context_t *context,
552 const coap_address_t *dst,
554 coap_tid_t id = COAP_INVALID_TID;
556 if ( !context || !dst || !pdu )
559 /* FIXME: is there a way to check if send was successful? */
560 uip_udp_packet_sendto(context->conn, pdu->hdr, pdu->length,
561 &dst->addr, dst->port);
563 coap_transaction_id(dst, pdu, &id);
567 #endif /* WITH_CONTIKI */
570 coap_send_impl(coap_context_t *context,
571 const coap_address_t *dst,
573 coap_tid_t id = COAP_INVALID_TID;
578 if ( !context || !dst || !pdu )
583 data_backup = pdu->data;
585 /* FIXME: we can't check this here with the existing infrastructure, but we
586 * should actually check that the pdu is not held by anyone but us. the
587 * respective pbuf is already exclusively owned by the pdu. */
590 LWIP_ASSERT("The PDU header is not where it is expected", pdu->hdr == p->payload + sizeof(coap_pdu_t));
592 err = pbuf_header(p, -sizeof(coap_pdu_t));
595 debug("coap_send_impl: pbuf_header failed\n");
600 coap_transaction_id(dst, pdu, &id);
602 pbuf_realloc(p, pdu->length);
604 udp_sendto(context->pcb, p,
605 &dst->addr, dst->port);
607 pbuf_header(p, -(ptrdiff_t)((uint8_t*)pdu - (uint8_t*)p->payload) - sizeof(coap_pdu_t)); /* FIXME hack around udp_sendto not restoring; see http://lists.gnu.org/archive/html/lwip-users/2013-06/msg00008.html. for udp over ip over ethernet, this was -42; as we're doing ppp too, this has to be calculated generically */
609 err = pbuf_header(p, sizeof(coap_pdu_t));
610 LWIP_ASSERT("Cannot undo pbuf_header", err == 0);
612 /* restore destroyed pdu data */
613 LWIP_ASSERT("PDU not restored", p->payload == pdu);
614 pdu->max_size = p->tot_len - sizeof(coap_pdu_t); /* reduced after pbuf_realloc */
615 pdu->hdr = p->payload + sizeof(coap_pdu_t);
616 pdu->max_delta = 0; /* won't be used any more */
617 pdu->length = pdu->max_size;
618 pdu->data = data_backup;
623 #endif /* WITH_LWIP */
625 coap_tid_t coap_send_error(coap_context_t *context, coap_pdu_t *request,
626 const coap_address_t *dst, unsigned char code, coap_opt_filter_t opts,
627 coap_send_flags_t flag) {
628 coap_pdu_t *response;
629 coap_tid_t result = COAP_INVALID_TID;
634 response = coap_new_error_response(request, code, opts);
636 result = coap_send(context, dst, response, flag);
637 coap_delete_pdu(response);
643 coap_tid_t coap_send_message_type(coap_context_t *context,
644 const coap_address_t *dst, coap_pdu_t *request,
645 coap_send_flags_t flag, unsigned char type) {
646 coap_pdu_t *response;
647 coap_tid_t result = COAP_INVALID_TID;
650 response = coap_pdu_init(type, 0, request->hdr->id, sizeof(coap_pdu_t));
652 result = coap_send(context, dst, response, flag);
653 coap_delete_pdu(response);
659 coap_tid_t coap_send(coap_context_t *context,
660 const coap_address_t *dst, coap_pdu_t *pdu, coap_send_flags_t flag)
662 coap_queue_t *node = NULL;
669 return COAP_INVALID_TID;
670 if(!(flag & SEND_RETX)){
671 coap_transaction_id(dst, pdu, &tid);
673 if((flag & SEND_NOW) || (flag & SEND_RETX))
678 node = coap_new_node();
680 debug("coap_send: insufficient memory\n");
681 return COAP_INVALID_TID;
684 prng((unsigned char * )&r, sizeof(r));
685 /* add randomized RESPONSE_TIMEOUT to determine retransmission timeout */
686 if(flag & SEND_NOW_CON) {
687 node->timeout = COAP_DEFAULT_RESPONSE_TIMEOUT * COAP_TICKS_PER_SECOND
688 + (COAP_DEFAULT_RESPONSE_TIMEOUT >> 1)
689 * ((COAP_TICKS_PER_SECOND * (r & 0xFF)) >> 8);
693 node->timeout = MAX_MULTICAST_DELAY_SEC * ((COAP_TICKS_PER_SECOND * (r & 0xFF)) >> 8);
694 node->delayedResponse = 1;
697 if (flag & SEND_SECURE_PORT) {
701 memcpy(&node->remote, dst, sizeof(coap_address_t));
705 /* Set timer for pdu retransmission. If this is the first element in
706 * the retransmission queue, the base time is set to the current
707 * time and the retransmission time is node->timeout. If there is
708 * already an entry in the sendqueue, we must check if this node is
709 * to be retransmitted earlier. Therefore, node->timeout is first
710 * normalized to the base time and then inserted into the queue with
711 * an adjusted relative time.
715 if (context->sendqueue == NULL)
717 node->t = node->timeout;
718 context->sendqueue_basetime = now;
722 /* make node->t relative to context->sendqueue_basetime */
723 node->t = (now - context->sendqueue_basetime) + node->timeout;
725 coap_insert_node(&context->sendqueue, node);
728 if (node == context->sendqueue)
729 /* don't bother with timer stuff if there are earlier retransmits */
730 coap_retransmittimer_restart(context);
734 { /* (re-)initialize retransmission timer */
735 coap_queue_t *nextpdu;
737 nextpdu = coap_peek_next(context);
738 assert(nextpdu); /* we have just inserted a node */
740 /* must set timer within the context of the retransmit process */
741 PROCESS_CONTEXT_BEGIN(&coap_retransmit_process);
742 etimer_set(&context->retransmit_timer, nextpdu->t);
743 PROCESS_CONTEXT_END(&coap_retransmit_process);
745 #endif /* WITH_CONTIKI */
747 if(flag & SEND_NOW_CON)
754 bytesWritten = coap_send_impl(context, dst, pdu);
759 debug("coap_send_impl: error sending pdu\n");
760 coap_free_node(node);
761 return COAP_INVALID_TID;
764 coap_tid_t coap_retransmit(coap_context_t *context, coap_queue_t *node) {
765 coap_tid_t tid = COAP_INVALID_TID;
766 coap_send_flags_t flag;
768 if (!context || !node)
769 return COAP_INVALID_TID;
771 /* re-initialize timeout when maximum number of retransmissions are not reached yet */
772 if (node->retransmit_cnt < COAP_DEFAULT_MAX_RETRANSMIT) {
773 node->retransmit_cnt++;
774 node->t = node->timeout << node->retransmit_cnt;
775 coap_insert_node(&context->sendqueue, node);
777 if (node == context->sendqueue) /* don't bother with timer stuff if there are earlier retransmits */
778 coap_retransmittimer_restart(context);
781 debug("** retransmission #%d of transaction %d\n", node->retransmit_cnt,
782 ntohs(node->pdu->hdr->id));
783 flag = (coap_send_flags_t)(SEND_RETX | (node->secure ? SEND_SECURE_PORT : 0));
784 tid = coap_send(context, (coap_address_t *)&(node->remote),node->pdu, flag);
785 return (tid == COAP_INVALID_TID)? COAP_INVALID_TID : node->id;
788 /* no more retransmissions, remove node from system */
791 debug("** removed transaction %d\n", ntohs(node->id));
794 // deletion of node will happen in ocoap since we still need the info node has
795 return COAP_INVALID_TID;
799 * Checks if @p opt fits into the message that ends with @p maxpos.
800 * This function returns @c 1 on success, or @c 0 if the option @p opt
801 * would exceed @p maxpos.
803 static inline int check_opt_size(coap_opt_t *opt, unsigned char *maxpos) {
804 if (opt && opt < maxpos) {
805 if (((*opt & 0x0f) < 0x0f) || (opt + 1 < maxpos))
806 return opt + COAP_OPT_SIZE(opt) < maxpos;
811 int coap_read(coap_context_t *ctx, int sockfd) {
812 #if defined(WITH_POSIX) || defined(WITH_ARDUINO)
813 static char buf[COAP_MAX_PDU_SIZE];
815 #if defined(WITH_LWIP) || defined(WITH_CONTIKI)
821 coap_address_t src, dst;
823 unsigned char delayRes = 0;
827 #endif /* WITH_CONTIKI */
829 LWIP_ASSERT("No package pending", ctx->pending_package != NULL);
830 LWIP_ASSERT("Can only deal with contiguous PBUFs to read the initial details", ctx->pending_package->tot_len == ctx->pending_package->len);
831 buf = ctx->pending_package->payload;
832 #endif /* WITH_LWIP */
834 pdu = (coap_hdr_t *) buf;
836 coap_address_init(&src);
838 #if defined(WITH_POSIX) || defined(WITH_ARDUINO)
840 bytes_read = OCRecvFrom( sockfd, (uint8_t*)buf, sizeof(buf), 0,
843 // Set the delayed response flag for responding to multicast requests
844 if (sockfd == ctx->sockfd_wellknown && bytes_read > 0) {
848 #endif /* WITH_POSIX || WITH_ARDUINO */
851 uip_ipaddr_copy(&src.addr, &UIP_IP_BUF->srcipaddr);
852 src.port = UIP_UDP_BUF->srcport;
853 uip_ipaddr_copy(&dst.addr, &UIP_IP_BUF->destipaddr);
854 dst.port = UIP_UDP_BUF->destport;
856 bytes_read = uip_datalen();
857 ((char *)uip_appdata)[bytes_read] = 0;
858 PRINTF("Server received %d bytes from [", (int)bytes_read);
859 PRINT6ADDR(&src.addr);
860 PRINTF("]:%d\n", uip_ntohs(src.port));
862 #endif /* WITH_CONTIKI */
864 /* FIXME: use lwip address operation functions */
865 src.addr.addr = ctx->pending_address.addr;
866 src.port = ctx->pending_port;
867 bytes_read = ctx->pending_package->tot_len;
868 #endif /* WITH_LWIP */
870 if (bytes_read < 0) {
871 warn("coap_read: recvfrom");
875 if ((size_t) bytes_read < sizeof(coap_hdr_t)) {
876 debug("coap_read: discarded invalid frame\n");
880 if (pdu->version != COAP_DEFAULT_VERSION) {
881 debug("coap_read: unknown protocol version\n");
885 node = coap_new_node();
890 node->pdu = coap_pdu_from_pbuf(ctx->pending_package);
891 ctx->pending_package = NULL;
893 node->pdu = coap_pdu_init(0, 0, 0, bytes_read);
898 coap_ticks(&node->t);
899 memcpy(&node->local, &dst, sizeof(coap_address_t));
900 memcpy(&node->remote, &src, sizeof(coap_address_t));
902 if (!coap_pdu_parse((unsigned char *) buf, bytes_read, node->pdu)) {
903 warn("discard malformed PDU");
907 //set the delayed response flag
908 node->delayedResponse = delayRes;
910 /* and add new node to receive queue */
911 coap_transaction_id(&node->remote, node->pdu, &node->id);
912 coap_insert_node(&ctx->recvqueue, node);
915 if (LOG_DEBUG <= coap_get_log_level()) {
916 #ifndef INET6_ADDRSTRLEN
917 #define INET6_ADDRSTRLEN 40
919 unsigned char addr[INET6_ADDRSTRLEN + 8];
921 if (coap_print_addr(&src, addr, INET6_ADDRSTRLEN + 8))
922 debug("** received %d bytes from %s:\n", (int )bytes_read, addr);
924 coap_show_pdu(node->pdu);
931 /* FIXME: send back RST? */
932 coap_delete_node(node);
936 /* even if there was an error, clean up */
937 pbuf_free(ctx->pending_package);
938 ctx->pending_package = NULL;
943 int coap_remove_from_queue(coap_queue_t **queue, coap_tid_t id,
944 coap_queue_t **node) {
947 if (!queue || !*queue)
950 /* replace queue head if PDU's time is less than head's time */
952 if (id == (*queue)->id) { /* found transaction */
954 *queue = (*queue)->next;
955 if (*queue) { /* adjust relative time of new queue head */
956 (*queue)->t += (*node)->t;
958 (*node)->next = NULL;
959 /* coap_delete_node( q ); */
960 debug("*** removed transaction %u\n", id);
964 /* search transaction to remove (only first occurence will be removed) */
969 } while (q && id != q->id);
971 if (q) { /* found transaction */
973 if (p->next) { /* must update relative time of p->next */
978 /* coap_delete_node( q ); */
979 debug("*** removed transaction %u\n", id);
987 static inline int token_match(const unsigned char *a, size_t alen,
988 const unsigned char *b, size_t blen) {
989 return alen == blen && (alen == 0 || memcmp(a, b, alen) == 0);
992 void coap_cancel_all_messages(coap_context_t *context,
993 const coap_address_t *dst, const unsigned char *token,
994 size_t token_length) {
995 /* cancel all messages in sendqueue that are for dst
996 * and use the specified token */
999 debug("cancel_all_messages\n");
1000 while (context->sendqueue
1001 && coap_address_equals(dst, &context->sendqueue->remote)
1002 && token_match(token, token_length,
1003 context->sendqueue->pdu->hdr->token,
1004 context->sendqueue->pdu->hdr->token_length)) {
1005 q = context->sendqueue;
1006 context->sendqueue = q->next;
1007 debug("**** removed transaction %d\n", ntohs(q->pdu->hdr->id));
1008 coap_delete_node(q);
1011 if (!context->sendqueue)
1014 p = context->sendqueue;
1017 /* when q is not NULL, it does not match (dst, token), so we can skip it */
1019 if (coap_address_equals(dst, &q->remote)
1020 && token_match(token, token_length, q->pdu->hdr->token,
1021 q->pdu->hdr->token_length)) {
1023 debug("**** removed transaction %d\n", ntohs(q->pdu->hdr->id));
1024 coap_delete_node(q);
1034 coap_find_transaction(coap_queue_t *queue, coap_tid_t id) {
1035 while (queue && queue->id != id)
1036 queue = queue->next;
1042 coap_new_error_response(coap_pdu_t *request, unsigned char code,
1043 coap_opt_filter_t opts) {
1044 coap_opt_iterator_t opt_iter;
1045 coap_pdu_t *response;
1046 size_t size = sizeof(coap_hdr_t) + request->hdr->token_length;
1049 unsigned short opt_type = 0; /* used for calculating delta-storage */
1051 #if COAP_ERROR_PHRASE_LENGTH > 0
1052 const char *phrase = coap_response_phrase(code);
1054 /* Need some more space for the error phrase and payload start marker */
1056 size += strlen(phrase) + 1;
1061 /* cannot send ACK if original request was not confirmable */
1062 type = request->hdr->type == COAP_MESSAGE_CON ?
1063 COAP_MESSAGE_ACK : COAP_MESSAGE_NON;
1065 /* Estimate how much space we need for options to copy from
1066 * request. We always need the Token, for 4.02 the unknown critical
1067 * options must be included as well. */
1068 coap_option_clrb(opts, COAP_OPTION_CONTENT_TYPE); /* we do not want this */
1070 coap_option_iterator_init(request, &opt_iter, opts);
1072 /* Add size of each unknown critical option. As known critical
1073 options as well as elective options are not copied, the delta
1076 while ((option = coap_option_next(&opt_iter))) {
1077 unsigned short delta = opt_iter.type - opt_type;
1078 /* calculate space required to encode (opt_iter.type - opt_type) */
1081 } else if (delta < 269) {
1087 /* add coap_opt_length(option) and the number of additional bytes
1088 * required to encode the option length */
1090 size += coap_opt_length(option);
1091 switch (*option & 0x0f) {
1103 opt_type = opt_iter.type;
1106 /* Now create the response and fill with options and payload data. */
1107 response = coap_pdu_init(type, code, request->hdr->id, size);
1110 if (!coap_add_token(response, request->hdr->token_length,
1111 request->hdr->token)) {
1112 debug("cannot add token to error response\n");
1113 coap_delete_pdu(response);
1117 /* copy all options */
1118 coap_option_iterator_init(request, &opt_iter, opts);
1119 while ((option = coap_option_next(&opt_iter)))
1120 coap_add_option(response, opt_iter.type, COAP_OPT_LENGTH(option),
1121 COAP_OPT_VALUE(option));
1123 #if COAP_ERROR_PHRASE_LENGTH > 0
1124 /* note that diagnostic messages do not need a Content-Format option. */
1126 coap_add_data(response, strlen(phrase), (unsigned char *) phrase);
1134 #define SZX_TO_BYTES(SZX) ((size_t)(1 << ((SZX) + 4)))
1136 #define WANT_WKC(Pdu,Key) \
1137 (((Pdu)->hdr->code == COAP_REQUEST_GET) && is_wkc(Key))
1139 /************************************************************************************************
1140 * Following code will be moved to newer handle_request in the future and kept for reference
1141 ************************************************************************************************/
1144 handle_request(coap_context_t *context, coap_queue_t *node) {
1145 coap_method_handler_t h = NULL;
1146 coap_pdu_t *response = NULL;
1147 coap_opt_filter_t opt_filter;
1148 coap_resource_t *resource;
1151 coap_option_filter_clear(opt_filter);
1153 /* try to find the resource from the request URI */
1154 coap_hash_request_uri(node->pdu, key);
1155 resource = coap_get_resource_from_key(context, key);
1158 /* The resource was not found. Check if the request URI happens to
1159 * be the well-known URI. In that case, we generate a default
1160 * response, otherwise, we return 4.04 */
1162 switch(node->pdu->hdr->code) {
1164 case COAP_REQUEST_GET:
1165 if (is_wkc(key)) { /* GET request for .well-known/core */
1166 info("create default response for %s\n", COAP_DEFAULT_URI_WELLKNOWN);
1167 response = wellknown_response(context, node->pdu);
1169 } else { /* GET request for any another resource, return 4.04 */
1171 debug("GET for unknown resource 0x%02x%02x%02x%02x, return 4.04\n",
1172 key[0], key[1], key[2], key[3]);
1174 coap_new_error_response(node->pdu, COAP_RESPONSE_CODE(404),
1179 default: /* any other request type */
1181 debug("unhandled request for unknown resource 0x%02x%02x%02x%02x\r\n",
1182 key[0], key[1], key[2], key[3]);
1183 if (!coap_is_mcast(&node->local))
1184 response = coap_new_error_response(node->pdu, COAP_RESPONSE_CODE(405),
1188 if (response && coap_send(context, &node->remote, response) == COAP_INVALID_TID) {
1189 warn("cannot send response for transaction %u\n", node->id);
1191 coap_delete_pdu(response);
1196 /* the resource was found, check if there is a registered handler */
1197 if ((size_t)node->pdu->hdr->code - 1 <
1198 sizeof(resource->handler)/sizeof(coap_method_handler_t))
1199 h = resource->handler[node->pdu->hdr->code - 1];
1202 debug("call custom handler for resource 0x%02x%02x%02x%02x\n",
1203 key[0], key[1], key[2], key[3]);
1204 response = coap_pdu_init(node->pdu->hdr->type == COAP_MESSAGE_CON
1207 0, node->pdu->hdr->id, COAP_MAX_PDU_SIZE);
1209 /* Implementation detail: coap_add_token() immediately returns 0
1210 if response == NULL */
1211 if (coap_add_token(response, node->pdu->hdr->token_length,
1212 node->pdu->hdr->token)) {
1213 str token = {node->pdu->hdr->token_length, node->pdu->hdr->token};
1215 h(context, resource, &node->remote,
1216 node->pdu, &token, response);
1217 if (response->hdr->type != COAP_MESSAGE_NON ||
1218 (response->hdr->code >= 64
1219 && !coap_is_mcast(&node->local))) {
1220 if (coap_send(context, &node->remote, response) == COAP_INVALID_TID) {
1221 debug("cannot send response for message %d\n", node->pdu->hdr->id);
1225 coap_delete_pdu(response);
1227 warn("cannot generate response\r\n");
1230 if (WANT_WKC(node->pdu, key)) {
1231 debug("create default response for %s\n", COAP_DEFAULT_URI_WELLKNOWN);
1232 response = wellknown_response(context, node->pdu);
1234 response = coap_new_error_response(node->pdu, COAP_RESPONSE_CODE(405),
1237 if (!response || (coap_send(context, &node->remote, response)
1238 == COAP_INVALID_TID)) {
1239 debug("cannot send response for transaction %u\n", node->id);
1241 coap_delete_pdu(response);
1245 static void handle_request(coap_context_t *context, coap_queue_t *rcvd) {
1246 /* Call application-specific reponse handler when available. If
1247 * not, we must acknowledge confirmable messages. */
1248 if (context->request_handler) {
1249 context->request_handler(context, rcvd);
1251 coap_send_flags_t flag = SEND_NOW;
1252 flag = (coap_send_flags_t)(flag | (rcvd->secure ? SEND_SECURE_PORT : 0));
1253 /* send ACK if rcvd is confirmable (i.e. a separate response) */
1254 coap_send_ack(context, &rcvd->remote, rcvd->pdu, flag);
1258 static void handle_response(coap_context_t *context, coap_queue_t *rcvd) {
1259 /* Call application-specific reponse handler when available. If
1260 * not, we must acknowledge confirmable messages. */
1261 if (context->response_handler) {
1262 context->response_handler(context, rcvd);
1264 coap_send_flags_t flag = SEND_NOW;
1265 flag = (coap_send_flags_t)(flag | (rcvd->secure ? SEND_SECURE_PORT : 0));
1266 /* send ACK if rcvd is confirmable (i.e. a separate response) */
1267 coap_send_ack(context, &rcvd->remote, rcvd->pdu, flag);
1271 static void handle_ack_rst(coap_context_t *context, uint8_t msgType, coap_queue_t *sent) {
1272 /* Call application-specific reponse handler when available. If
1273 * not, we must acknowledge confirmable messages. */
1274 if (context->ack_rst_handler) {
1275 context->ack_rst_handler(context, msgType, sent);
1281 handle_locally(coap_context_t *context __attribute__ ((unused)),
1282 coap_queue_t *node __attribute__ ((unused))) {
1283 #else /* not a GCC */
1284 handle_locally(coap_context_t *context, coap_queue_t *node) {
1286 /* this function can be used to check if node->pdu is really for us */
1290 void coap_dispatch(coap_context_t *context) {
1291 coap_queue_t *rcvd = NULL, *sent = NULL;
1292 coap_pdu_t *response;
1293 coap_opt_filter_t opt_filter;
1298 memset(opt_filter, 0, sizeof(coap_opt_filter_t));
1300 while (context->recvqueue) {
1301 rcvd = context->recvqueue;
1303 /* remove node from recvqueue */
1304 context->recvqueue = context->recvqueue->next;
1307 if (rcvd->pdu->hdr->version != COAP_DEFAULT_VERSION) {
1308 debug("dropped packet with unknown version %u\n",
1309 rcvd->pdu->hdr->version);
1313 switch (rcvd->pdu->hdr->type) {
1314 case COAP_MESSAGE_ACK:
1315 /* find transaction in sendqueue to stop retransmission */
1316 if(coap_remove_from_queue(&context->sendqueue, rcvd->id, &sent)){
1317 handle_ack_rst(context, COAP_MESSAGE_ACK, sent);
1320 //delete empty messages, this is ACK only message no piggybacked response
1321 if (rcvd->pdu->hdr->code == 0)
1325 case COAP_MESSAGE_NON: /* check for unknown critical options */
1326 if (coap_option_check_critical(context, rcvd->pdu, opt_filter)
1331 case COAP_MESSAGE_CON: /* check for unknown critical options */
1332 if (coap_option_check_critical(context, rcvd->pdu, opt_filter)
1334 /* FIXME: send response only if we have received a request. Otherwise,
1336 response = coap_new_error_response(rcvd->pdu,
1337 COAP_RESPONSE_CODE(402), opt_filter);
1339 warn("coap_dispatch: cannot create error reponse\n");
1341 coap_send_flags_t flag = SEND_NOW;
1342 flag = (coap_send_flags_t)(flag | rcvd->secure ? SEND_SECURE_PORT : 0);
1343 if (coap_send(context, &rcvd->remote, response, flag)
1344 == COAP_INVALID_TID) {
1345 warn("coap_dispatch: error sending reponse\n");
1347 coap_delete_pdu(response);
1353 case COAP_MESSAGE_RST:
1354 /* find transaction in sendqueue to stop retransmission */
1355 if(coap_remove_from_queue(&context->sendqueue, rcvd->id, &sent)){
1356 handle_ack_rst(context, COAP_MESSAGE_RST, sent);
1363 "TODO: Need to handle other message types in coap_dispatch");
1366 /************************************************************************************************
1367 * Following code will be replaced at different parts of the stack
1368 ************************************************************************************************/
1370 switch (rcvd->pdu->hdr->type) {
1371 case COAP_MESSAGE_ACK:
1372 /* find transaction in sendqueue to stop retransmission */
1373 coap_remove_from_queue(&context->sendqueue, rcvd->id, &sent);
1375 if (rcvd->pdu->hdr->code == 0)
1378 /* FIXME: if sent code was >= 64 the message might have been a
1379 * notification. Then, we must flag the observer to be alive
1380 * by setting obs->fail_cnt = 0. */
1381 if (sent && COAP_RESPONSE_CLASS(sent->pdu->hdr->code) == 2) {
1382 const str token = {sent->pdu->hdr->token_length,
1383 sent->pdu->hdr->token};
1384 coap_touch_observer(context, &sent->remote, &token);
1388 case COAP_MESSAGE_RST:
1389 /* We have sent something the receiver disliked, so we remove
1390 * not only the transaction but also the subscriptions we might
1393 coap_log(LOG_ALERT, "got RST for message %u\n",
1394 ntohs(rcvd->pdu->hdr->id));
1396 /* find transaction in sendqueue to stop retransmission */
1397 coap_remove_from_queue(&context->sendqueue, rcvd->id, &sent);
1400 coap_handle_rst(context, sent);
1403 case COAP_MESSAGE_NON: /* check for unknown critical options */
1404 if (coap_option_check_critical(context, rcvd->pdu, opt_filter)
1409 case COAP_MESSAGE_CON: /* check for unknown critical options */
1410 if (coap_option_check_critical(context, rcvd->pdu, opt_filter)
1413 /* FIXME: send response only if we have received a request. Otherwise,
1415 response = coap_new_error_response(rcvd->pdu,
1416 COAP_RESPONSE_CODE(402), opt_filter);
1419 warn("coap_dispatch: cannot create error reponse\n");
1421 if (coap_send(context, &rcvd->remote,
1422 response) == COAP_INVALID_TID) {
1423 warn("coap_dispatch: error sending reponse\n");
1425 coap_delete_pdu(response);
1434 /* Pass message to upper layer if a specific handler was
1435 * registered for a request that should be handled locally. */
1436 if (handle_locally(context, rcvd)) {
1437 if (COAP_MESSAGE_IS_REQUEST(rcvd->pdu->hdr)){
1438 handle_request(context, rcvd);
1440 else if (COAP_MESSAGE_IS_RESPONSE(rcvd->pdu->hdr)){
1441 handle_response(context, rcvd);
1444 coap_send_flags_t flag;
1445 flag = (coap_send_flags_t)(SEND_NOW |
1446 (rcvd->secure ? SEND_SECURE_PORT : 0));
1447 debug("dropped message with invalid code\n");
1448 coap_send_message_type(context, &rcvd->remote, rcvd->pdu,
1449 flag, COAP_MESSAGE_RST);
1453 // we should not retry responses.....
1455 coap_delete_node(sent);
1457 coap_delete_node(rcvd);
1462 int coap_can_exit(coap_context_t *context) {
1464 || (context->recvqueue == NULL && context->sendqueue == NULL);
1469 /*---------------------------------------------------------------------------*/
1470 /* CoAP message retransmission */
1471 /*---------------------------------------------------------------------------*/
1472 PROCESS_THREAD(coap_retransmit_process, ev, data)
1475 coap_queue_t *nextpdu;
1479 debug("Started retransmit process\r\n");
1483 if (ev == PROCESS_EVENT_TIMER) {
1484 if (etimer_expired(&the_coap_context.retransmit_timer)) {
1486 nextpdu = coap_peek_next(&the_coap_context);
1489 while (nextpdu && nextpdu->t <= now) {
1490 coap_retransmit(&the_coap_context, coap_pop_next(&the_coap_context));
1491 nextpdu = coap_peek_next(&the_coap_context);
1494 /* need to set timer to some value even if no nextpdu is available */
1495 etimer_set(&the_coap_context.retransmit_timer,
1496 nextpdu ? nextpdu->t - now : 0xFFFF);
1498 #ifndef WITHOUT_OBSERVE
1499 if (etimer_expired(&the_coap_context.notify_timer)) {
1500 coap_check_notify(&the_coap_context);
1501 etimer_reset(&the_coap_context.notify_timer);
1503 #endif /* WITHOUT_OBSERVE */
1509 /*---------------------------------------------------------------------------*/
1511 #endif /* WITH_CONTIKI */
1514 /* FIXME: retransmits that are not required any more due to incoming packages
1515 * do *not* get cleared at the moment, the wakeup when the transmission is due
1516 * is silently accepted. this is mainly due to the fact that the required
1517 * checks are similar in two places in the code (when receiving ACK and RST)
1518 * and that they cause more than one patch chunk, as it must be first checked
1519 * whether the sendqueue item to be dropped is the next one pending, and later
1520 * the restart function has to be called. nothing insurmountable, but it can
1521 * also be implemented when things have stabilized, and the performance
1522 * penality is minimal
1524 * also, this completely ignores COAP_RESOURCE_CHECK_TIME.
1527 static void coap_retransmittimer_execute(void *arg)
1529 coap_context_t *ctx = (coap_context_t*)arg;
1531 coap_tick_t elapsed;
1532 coap_queue_t *nextinqueue;
1534 ctx->timer_configured = 0;
1538 elapsed = now - ctx->sendqueue_basetime; /* that's positive for sure, and unless we haven't been called for a complete wrapping cycle, did not wrap */
1540 nextinqueue = coap_peek_next(ctx);
1541 while (nextinqueue != NULL)
1543 if (nextinqueue->t > elapsed) {
1544 nextinqueue->t -= elapsed;
1547 elapsed -= nextinqueue->t;
1548 coap_retransmit(ctx, coap_pop_next(ctx));
1549 nextinqueue = coap_peek_next(ctx);
1553 ctx->sendqueue_basetime = now;
1555 coap_retransmittimer_restart(ctx);
1558 static void coap_retransmittimer_restart(coap_context_t *ctx)
1560 coap_tick_t now, elapsed, delay;
1562 if (ctx->timer_configured)
1564 printf("clearing\n");
1565 sys_untimeout(coap_retransmittimer_execute, (void*)ctx);
1566 ctx->timer_configured = 0;
1568 if (ctx->sendqueue != NULL)
1571 elapsed = now - ctx->sendqueue_basetime;
1572 if (ctx->sendqueue->t >= elapsed) {
1573 delay = ctx->sendqueue->t - elapsed;
1575 /* a strange situation, but not completely impossible.
1577 * this happens, for example, right after
1578 * coap_retransmittimer_execute, when a retransmission
1579 * was *just not yet* due, and the clock ticked before
1580 * our coap_ticks was called.
1582 * not trying to retransmit anything now, as it might
1583 * cause uncontrollable recursion; let's just try again
1584 * with the next main loop run.
1589 printf("scheduling for %d ticks\n", delay);
1590 sys_timeout(delay, coap_retransmittimer_execute, (void*)ctx);
1591 ctx->timer_configured = 1;