1 /* net.c -- CoAP network interface
2  *
3  * Copyright (C) 2010--2015 Olaf Bergmann <bergmann@tzi.org>
4  *
5  * This file is part of the CoAP library libcoap. Please see
6  * README for terms of use.
7  */
8 
9 #include "coap_config.h"
10 
11 #include <ctype.h>
12 #include <stdio.h>
13 #include <errno.h>
14 #ifdef HAVE_LIMITS_H
15 #include <limits.h>
16 #endif
17 #ifdef HAVE_UNISTD_H
18 #include <unistd.h>
19 #elif HAVE_SYS_UNISTD_H
20 #include <sys/unistd.h>
21 #endif
22 #include <sys/types.h>
23 #ifdef HAVE_SYS_SOCKET_H
24 #include <sys/socket.h>
25 #endif
26 #ifdef HAVE_NETINET_IN_H
27 #include <netinet/in.h>
28 #endif
29 #ifdef HAVE_ARPA_INET_H
30 #include <arpa/inet.h>
31 #endif
32 
33 #ifdef WITH_LWIP
34 #include <lwip/pbuf.h>
35 #include <lwip/udp.h>
36 #include <lwip/timers.h>
37 #endif
38 
39 #include "debug.h"
40 #include "mem.h"
41 #include "str.h"
42 #include "async.h"
43 #include "resource.h"
44 #include "option.h"
45 #include "encode.h"
46 #include "block.h"
47 #include "net.h"
48 
49 /**
50  * @defgroup cc Rate Control
51  * The transmission parameters for CoAP rate control ("Congestion
52  * Control" in stream-oriented protocols) are defined in
53  * https://tools.ietf.org/html/rfc7252#section-4.8
54  * @{
55  */
56 
57 #ifndef COAP_DEFAULT_ACK_TIMEOUT
58 /**
59  * Number of seconds when to expect an ACK or a response to an
60  * outstanding CON message.
61  */
62 #define COAP_DEFAULT_ACK_TIMEOUT  2 /* see RFC 7252, Section 4.8 */
63 #endif
64 
65 #ifndef COAP_DEFAULT_ACK_RANDOM_FACTOR
66 /**
67  * A factor that is used to randomize the wait time before a message
68  * is retransmitted to prevent synchronization effects.
69  */
70 #define COAP_DEFAULT_ACK_RANDOM_FACTOR  1.5 /* see RFC 7252, Section 4.8 */
71 #endif
72 
73 #ifndef COAP_DEFAULT_MAX_RETRANSMIT
74 /**
75  * Number of message retransmissions before message sending is stopped
76  */
77 #define COAP_DEFAULT_MAX_RETRANSMIT  4 /* see RFC 7252, Section 4.8 */
78 #endif
79 
80 #ifndef COAP_DEFAULT_NSTART
81 /**
82  * The number of simultaneous outstanding interactions that a client
83  * maintains to a given server.
84  */
85 #define COAP_DEFAULT_NSTART 1 /* see RFC 7252, Section 4.8 */
86 #endif
87 
88 /** @} */
89 
90 /**
91  * The number of bits for the fractional part of ACK_TIMEOUT and
92  * ACK_RANDOM_FACTOR. Must be less or equal 8.
93  */
94 #define FRAC_BITS 6
95 
96 /**
97  * The maximum number of bits for fixed point integers that are used
98  * for retransmission time calculation. Currently this must be @c 8.
99  */
100 #define MAX_BITS 8
101 
102 #if FRAC_BITS > 8
103 #error FRAC_BITS must be less or equal 8
104 #endif
105 
106 /** creates a Qx.frac from fval */
107 #define Q(frac,fval) ((unsigned short)(((1 << (frac)) * (fval))))
108 
109 /** creates a Qx.FRAC_BITS from COAP_DEFAULT_ACK_RANDOM_FACTOR */
110 #define ACK_RANDOM_FACTOR					\
111   Q(FRAC_BITS, COAP_DEFAULT_ACK_RANDOM_FACTOR)
112 
113 /** creates a Qx.FRAC_BITS from COAP_DEFAULT_ACK_TIMEOUT */
114 #define ACK_TIMEOUT Q(FRAC_BITS, COAP_DEFAULT_ACK_TIMEOUT)
115 
116 #if defined(WITH_POSIX)
117 
118 time_t clock_offset;
119 
120 static inline coap_queue_t *
coap_malloc_node(void)121 coap_malloc_node(void) {
122   return (coap_queue_t *)coap_malloc_type(COAP_NODE, sizeof(coap_queue_t));
123 }
124 
125 static inline void
coap_free_node(coap_queue_t * node)126 coap_free_node(coap_queue_t *node) {
127   coap_free_type(COAP_NODE, node);
128 }
129 #endif /* WITH_POSIX */
130 #ifdef WITH_LWIP
131 
132 #include <lwip/memp.h>
133 
134 static void coap_retransmittimer_execute(void *arg);
135 static void coap_retransmittimer_restart(coap_context_t *ctx);
136 
137 static inline coap_queue_t *
coap_malloc_node()138 coap_malloc_node() {
139 	return (coap_queue_t *)memp_malloc(MEMP_COAP_NODE);
140 }
141 
142 static inline void
coap_free_node(coap_queue_t * node)143 coap_free_node(coap_queue_t *node) {
144 	memp_free(MEMP_COAP_NODE, node);
145 }
146 
147 #endif /* WITH_LWIP */
148 #ifdef WITH_CONTIKI
149 # ifndef DEBUG
150 #  define DEBUG DEBUG_PRINT
151 # endif /* DEBUG */
152 
153 #include "mem.h"
154 #include "net/ip/uip-debug.h"
155 
156 clock_time_t clock_offset;
157 
158 #define UIP_IP_BUF   ((struct uip_ip_hdr *)&uip_buf[UIP_LLH_LEN])
159 #define UIP_UDP_BUF  ((struct uip_udp_hdr *)&uip_buf[UIP_LLIPH_LEN])
160 
161 void coap_resources_init();
162 
163 unsigned char initialized = 0;
164 coap_context_t the_coap_context;
165 
166 PROCESS(coap_retransmit_process, "message retransmit process");
167 
168 static inline coap_queue_t *
coap_malloc_node()169 coap_malloc_node() {
170   return (coap_queue_t *)coap_malloc_type(COAP_NODE, 0);
171 }
172 
173 static inline void
coap_free_node(coap_queue_t * node)174 coap_free_node(coap_queue_t *node) {
175   coap_free_type(COAP_NODE, node);
176 }
177 #endif /* WITH_CONTIKI */
178 
179 unsigned int
coap_adjust_basetime(coap_context_t * ctx,coap_tick_t now)180 coap_adjust_basetime(coap_context_t *ctx, coap_tick_t now) {
181   unsigned int result = 0;
182   coap_tick_diff_t delta = now - ctx->sendqueue_basetime;
183 
184   if (ctx->sendqueue) {
185     /* delta < 0 means that the new time stamp is before the old. */
186     if (delta <= 0) {
187       ctx->sendqueue->t -= delta;
188     } else {
189       /* This case is more complex: The time must be advanced forward,
190        * thus possibly leading to timed out elements at the queue's
191        * start. For every element that has timed out, its relative
192        * time is set to zero and the result counter is increased. */
193 
194       coap_queue_t *q = ctx->sendqueue;
195       coap_tick_t t = 0;
196       while (q && (t + q->t < (coap_tick_t)delta)) {
197 	t += q->t;
198 	q->t = 0;
199 	result++;
200 	q = q->next;
201       }
202 
203       /* finally adjust the first element that has not expired */
204       if (q) {
205 	q->t = (coap_tick_t)delta - t;
206       }
207     }
208   }
209 
210   /* adjust basetime */
211   ctx->sendqueue_basetime += delta;
212 
213   return result;
214 }
215 
216 int
coap_insert_node(coap_queue_t ** queue,coap_queue_t * node)217 coap_insert_node(coap_queue_t **queue, coap_queue_t *node) {
218   coap_queue_t *p, *q;
219   if ( !queue || !node )
220     return 0;
221 
222   /* set queue head if empty */
223   if ( !*queue ) {
224     *queue = node;
225     return 1;
226   }
227 
228   /* replace queue head if PDU's time is less than head's time */
229   q = *queue;
230   if (node->t < q->t) {
231     node->next = q;
232     *queue = node;
233     q->t -= node->t;		/* make q->t relative to node->t */
234     return 1;
235   }
236 
237   /* search for right place to insert */
238   do {
239     node->t -= q->t;		/* make node-> relative to q->t */
240     p = q;
241     q = q->next;
242   } while (q && q->t <= node->t);
243 
244   /* insert new item */
245   if (q) {
246     q->t -= node->t;		/* make q->t relative to node->t */
247   }
248   node->next = q;
249   p->next = node;
250   return 1;
251 }
252 
253 int
coap_delete_node(coap_queue_t * node)254 coap_delete_node(coap_queue_t *node) {
255   if ( !node )
256     return 0;
257 
258   coap_delete_pdu(node->pdu);
259   coap_free_node(node);
260 
261   return 1;
262 }
263 
264 void
coap_delete_all(coap_queue_t * queue)265 coap_delete_all(coap_queue_t *queue) {
266   if ( !queue )
267     return;
268 
269   coap_delete_all( queue->next );
270   coap_delete_node( queue );
271 }
272 
273 coap_queue_t *
coap_new_node(void)274 coap_new_node(void) {
275   coap_queue_t *node;
276   node = coap_malloc_node();
277 
278   if ( ! node ) {
279 #ifndef NDEBUG
280     coap_log(LOG_WARNING, "coap_new_node: malloc\n");
281 #endif
282     return NULL;
283   }
284 
285   memset(node, 0, sizeof(*node));
286   return node;
287 }
288 
289 coap_queue_t *
coap_peek_next(coap_context_t * context)290 coap_peek_next( coap_context_t *context ) {
291   if ( !context || !context->sendqueue )
292     return NULL;
293 
294   return context->sendqueue;
295 }
296 
297 coap_queue_t *
coap_pop_next(coap_context_t * context)298 coap_pop_next( coap_context_t *context ) {
299   coap_queue_t *next;
300 
301   if ( !context || !context->sendqueue )
302     return NULL;
303 
304   next = context->sendqueue;
305   context->sendqueue = context->sendqueue->next;
306   if (context->sendqueue) {
307     context->sendqueue->t += next->t;
308   }
309   next->next = NULL;
310   return next;
311 }
312 
313 #ifdef COAP_DEFAULT_WKC_HASHKEY
314 /** Checks if @p Key is equal to the pre-defined hash key for.well-known/core. */
315 #define is_wkc(Key)							\
316   (memcmp((Key), COAP_DEFAULT_WKC_HASHKEY, sizeof(coap_key_t)) == 0)
317 #else
318 /* Implements a singleton to store a hash key for the .wellknown/core
319  * resources. */
320 int
is_wkc(coap_key_t k)321 is_wkc(coap_key_t k) {
322   static coap_key_t wkc;
323   static unsigned char _initialized = 0;
324   if (!_initialized) {
325     _initialized = coap_hash_path((unsigned char *)COAP_DEFAULT_URI_WELLKNOWN,
326 				 sizeof(COAP_DEFAULT_URI_WELLKNOWN) - 1, wkc);
327   }
328   return memcmp(k, wkc, sizeof(coap_key_t)) == 0;
329 }
330 #endif
331 
332 coap_context_t *
coap_new_context(const coap_address_t * listen_addr)333 coap_new_context(
334   const coap_address_t *listen_addr) {
335 #ifndef WITH_CONTIKI
336   coap_context_t *c = coap_malloc_type(COAP_CONTEXT, sizeof( coap_context_t ) );
337 #endif /* not WITH_CONTIKI */
338 #ifdef WITH_CONTIKI
339   coap_context_t *c;
340 
341   if (initialized)
342     return NULL;
343 #endif /* WITH_CONTIKI */
344 
345   if (!listen_addr) {
346     coap_log(LOG_EMERG, "no listen address specified\n");
347     return NULL;
348   }
349 
350   coap_clock_init();
351 #ifdef WITH_LWIP
352   prng_init(LWIP_RAND());
353 #endif /* WITH_LWIP */
354 #ifdef WITH_CONTIKI
355   prng_init((ptrdiff_t)listen_addr ^ clock_offset);
356 #endif /* WITH_LWIP */
357 #ifdef WITH_POSIX
358   prng_init((unsigned long)listen_addr ^ clock_offset);
359 #endif /* WITH_POSIX */
360 
361 #ifndef WITH_CONTIKI
362   if (!c) {
363 #ifndef NDEBUG
364     coap_log(LOG_EMERG, "coap_init: malloc:\n");
365 #endif
366     return NULL;
367   }
368 #endif /* not WITH_CONTIKI */
369 #ifdef WITH_CONTIKI
370   coap_resources_init();
371   coap_memory_init();
372 
373   c = &the_coap_context;
374   initialized = 1;
375 #endif /* WITH_CONTIKI */
376 
377   memset(c, 0, sizeof( coap_context_t ) );
378 
379   /* initialize message id */
380   prng((unsigned char *)&c->message_id, sizeof(unsigned short));
381 
382   c->endpoint = coap_new_endpoint(listen_addr, COAP_ENDPOINT_NOSEC);
383 #ifdef WITH_LWIP
384   c->endpoint->context = c;
385 #endif
386   if (c->endpoint == NULL) {
387     goto onerror;
388   }
389 
390 #ifdef WITH_POSIX
391   c->sockfd = c->endpoint->handle.fd;
392 #endif /* WITH_POSIX */
393 
394 #if defined(WITH_POSIX) || defined(WITH_CONTIKI)
395   c->network_send = coap_network_send;
396   c->network_read = coap_network_read;
397 #endif /* WITH_POSIX or WITH_CONTIKI */
398 
399 #ifdef WITH_CONTIKI
400   process_start(&coap_retransmit_process, (char *)c);
401 
402   PROCESS_CONTEXT_BEGIN(&coap_retransmit_process);
403 #ifndef WITHOUT_OBSERVE
404   etimer_set(&c->notify_timer, COAP_RESOURCE_CHECK_TIME * COAP_TICKS_PER_SECOND);
405 #endif /* WITHOUT_OBSERVE */
406   /* the retransmit timer must be initialized to some large value */
407   etimer_set(&the_coap_context.retransmit_timer, 0xFFFF);
408   PROCESS_CONTEXT_END(&coap_retransmit_process);
409 #endif /* WITH_CONTIKI */
410 
411   return c;
412 
413  onerror:
414   coap_free(c);
415   return NULL;
416 }
417 
418 void
coap_free_context(coap_context_t * context)419 coap_free_context(coap_context_t *context) {
420 
421   if (!context)
422     return;
423 
424   coap_delete_all(context->sendqueue);
425 
426 #ifdef WITH_LWIP
427   context->sendqueue = NULL;
428   coap_retransmittimer_restart(context);
429 #endif
430 
431   coap_delete_all_resources(context);
432 
433   coap_free_endpoint(context->endpoint);
434 #ifndef WITH_CONTIKI
435   coap_free_type(COAP_CONTEXT, context);
436 #endif/* not WITH_CONTIKI */
437 #ifdef WITH_CONTIKI
438   memset(&the_coap_context, 0, sizeof(coap_context_t));
439   initialized = 0;
440 #endif /* WITH_CONTIKI */
441 }
442 
443 int
coap_option_check_critical(coap_context_t * ctx,coap_pdu_t * pdu,coap_opt_filter_t unknown)444 coap_option_check_critical(coap_context_t *ctx,
445 			   coap_pdu_t *pdu,
446 			   coap_opt_filter_t unknown) {
447 
448   coap_opt_iterator_t opt_iter;
449   int ok = 1;
450 
451   coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
452 
453   while (coap_option_next(&opt_iter)) {
454 
455     /* The following condition makes use of the fact that
456      * coap_option_getb() returns -1 if type exceeds the bit-vector
457      * filter. As the vector is supposed to be large enough to hold
458      * the largest known option, we know that everything beyond is
459      * bad.
460      */
461     if (opt_iter.type & 0x01) {
462       /* first check the built-in critical options */
463       switch (opt_iter.type) {
464       case COAP_OPTION_IF_MATCH:
465       case COAP_OPTION_URI_HOST:
466       case COAP_OPTION_IF_NONE_MATCH:
467       case COAP_OPTION_URI_PORT:
468       case COAP_OPTION_URI_PATH:
469       case COAP_OPTION_URI_QUERY:
470       case COAP_OPTION_ACCEPT:
471       case COAP_OPTION_PROXY_URI:
472       case COAP_OPTION_PROXY_SCHEME:
473       case COAP_OPTION_BLOCK2:
474       case COAP_OPTION_BLOCK1:
475 	break;
476       default:
477 	if (coap_option_filter_get(ctx->known_options, opt_iter.type) <= 0) {
478 	  debug("unknown critical option %d\n", opt_iter.type);
479 	  ok = 0;
480 
481 	  /* When opt_iter.type is beyond our known option range,
482 	   * coap_option_filter_set() will return -1 and we are safe to leave
483 	   * this loop. */
484 	  if (coap_option_filter_set(unknown, opt_iter.type) == -1) {
485 	    break;
486 	  }
487 	}
488       }
489     }
490   }
491 
492   return ok;
493 }
494 
495 void
coap_transaction_id(const coap_address_t * peer,const coap_pdu_t * pdu,coap_tid_t * id)496 coap_transaction_id(const coap_address_t *peer, const coap_pdu_t *pdu,
497 		    coap_tid_t *id) {
498   coap_key_t h;
499 
500   memset(h, 0, sizeof(coap_key_t));
501 
502   /* Compare the transport address. */
503 
504 #ifdef WITH_POSIX
505   switch (peer->addr.sa.sa_family) {
506   case AF_INET:
507     coap_hash((const unsigned char *)&peer->addr.sin.sin_port,
508 	      sizeof(peer->addr.sin.sin_port), h);
509     coap_hash((const unsigned char *)&peer->addr.sin.sin_addr,
510 	      sizeof(peer->addr.sin.sin_addr), h);
511     break;
512   case AF_INET6:
513     coap_hash((const unsigned char *)&peer->addr.sin6.sin6_port,
514 	      sizeof(peer->addr.sin6.sin6_port), h);
515     coap_hash((const unsigned char *)&peer->addr.sin6.sin6_addr,
516 	      sizeof(peer->addr.sin6.sin6_addr), h);
517     break;
518   default:
519     return;
520   }
521 #endif
522 #if defined(WITH_LWIP) || defined(WITH_CONTIKI)
523     /* FIXME: with lwip, we can do better */
524     coap_hash((const unsigned char *)&peer->port, sizeof(peer->port), h);
525     coap_hash((const unsigned char *)&peer->addr, sizeof(peer->addr), h);
526 #endif /* WITH_LWIP || WITH_CONTIKI */
527 
528   coap_hash((const unsigned char *)&pdu->hdr->id, sizeof(unsigned short), h);
529 
530   *id = (((h[0] << 8) | h[1]) ^ ((h[2] << 8) | h[3])) & INT_MAX;
531 }
532 
533 coap_tid_t
coap_send_ack(coap_context_t * context,const coap_endpoint_t * local_interface,const coap_address_t * dst,coap_pdu_t * request)534 coap_send_ack(coap_context_t *context,
535 	      const coap_endpoint_t *local_interface,
536 	      const coap_address_t *dst,
537 	      coap_pdu_t *request) {
538   coap_pdu_t *response;
539   coap_tid_t result = COAP_INVALID_TID;
540 
541   if (request && request->hdr->type == COAP_MESSAGE_CON) {
542     response = coap_pdu_init(COAP_MESSAGE_ACK, 0, request->hdr->id,
543 			     sizeof(coap_pdu_t));
544     if (response) {
545       result = coap_send(context, local_interface, dst, response);
546       coap_delete_pdu(response);
547     }
548   }
549   return result;
550 }
551 
552 #if defined(WITH_POSIX) || defined(WITH_CONTIKI)
553 static coap_tid_t
coap_send_impl(coap_context_t * context,const coap_endpoint_t * local_interface,const coap_address_t * dst,coap_pdu_t * pdu)554 coap_send_impl(coap_context_t *context,
555 	       const coap_endpoint_t *local_interface,
556 	       const coap_address_t *dst,
557 	       coap_pdu_t *pdu) {
558   ssize_t bytes_written;
559   coap_tid_t id = COAP_INVALID_TID;
560 
561   if ( !context || !dst || !pdu )
562     return id;
563 
564   /* Do not send error responses for requests that were received via
565    * IP multicast. */
566   if (coap_is_mcast(&local_interface->addr) &&
567       COAP_RESPONSE_CLASS(pdu->hdr->code) > 2) {
568     return COAP_DROPPED_RESPONSE;
569   }
570 
571   bytes_written = context->network_send(context, local_interface, dst,
572 				    (unsigned char *)pdu->hdr, pdu->length);
573 
574   if (bytes_written >= 0) {
575     coap_transaction_id(dst, pdu, &id);
576   } else {
577     coap_log(LOG_CRIT, "coap_send_impl: %s\n", strerror(errno));
578   }
579 
580   return id;
581 }
582 #endif /* WITH_POSIX */
583 #ifdef WITH_LWIP
584 coap_tid_t
coap_send_impl(coap_context_t * context,const coap_endpoint_t * local_interface,const coap_address_t * dst,coap_pdu_t * pdu)585 coap_send_impl(coap_context_t *context,
586 	       const coap_endpoint_t *local_interface,
587 	       const coap_address_t *dst,
588 	       coap_pdu_t *pdu) {
589   coap_tid_t id = COAP_INVALID_TID;
590   uint8_t err;
591   char *data_backup;
592 
593   if ( !context || !dst || !pdu )
594   {
595     return id;
596   }
597 
598   data_backup = pdu->data;
599 
600   /* FIXME: we can't check this here with the existing infrastructure, but we
601    * should actually check that the pdu is not held by anyone but us. the
602    * respective pbuf is already exclusively owned by the pdu. */
603 
604   pbuf_realloc(pdu->pbuf, pdu->length);
605 
606   coap_transaction_id(dst, pdu, &id);
607 
608   udp_sendto(context->endpoint->pcb, pdu->pbuf,
609 			&dst->addr, dst->port);
610 
611   return id;
612 }
613 #endif /* WITH_LWIP */
614 
615 coap_tid_t
coap_send(coap_context_t * context,const coap_endpoint_t * local_interface,const coap_address_t * dst,coap_pdu_t * pdu)616 coap_send(coap_context_t *context,
617 	  const coap_endpoint_t *local_interface,
618 	  const coap_address_t *dst,
619 	  coap_pdu_t *pdu) {
620   return coap_send_impl(context, local_interface, dst, pdu);
621 }
622 
623 coap_tid_t
coap_send_error(coap_context_t * context,coap_pdu_t * request,const coap_endpoint_t * local_interface,const coap_address_t * dst,unsigned char code,coap_opt_filter_t opts)624 coap_send_error(coap_context_t *context,
625 		coap_pdu_t *request,
626 		const coap_endpoint_t *local_interface,
627 		const coap_address_t *dst,
628 		unsigned char code,
629 		coap_opt_filter_t opts) {
630   coap_pdu_t *response;
631   coap_tid_t result = COAP_INVALID_TID;
632 
633   assert(request);
634   assert(dst);
635 
636   response = coap_new_error_response(request, code, opts);
637   if (response) {
638     result = coap_send(context, local_interface, dst, response);
639     coap_delete_pdu(response);
640   }
641 
642   return result;
643 }
644 
645 coap_tid_t
coap_send_message_type(coap_context_t * context,const coap_endpoint_t * local_interface,const coap_address_t * dst,coap_pdu_t * request,unsigned char type)646 coap_send_message_type(coap_context_t *context,
647 		       const coap_endpoint_t *local_interface,
648 		       const coap_address_t *dst,
649 		       coap_pdu_t *request,
650 		       unsigned char type) {
651   coap_pdu_t *response;
652   coap_tid_t result = COAP_INVALID_TID;
653 
654   if (request) {
655     response = coap_pdu_init(type, 0, request->hdr->id, sizeof(coap_pdu_t));
656     if (response) {
657       result = coap_send(context, local_interface, dst, response);
658       coap_delete_pdu(response);
659     }
660   }
661   return result;
662 }
663 
664 /**
665  * Calculates the initial timeout based on the global CoAP transmission
666  * parameters ACK_TIMEOUT, ACK_RANDOM_FACTOR, and COAP_TICKS_PER_SECOND.
667  * The calculation requires ACK_TIMEOUT and ACK_RANDOM_FACTOR to be in
668  * Qx.FRAC_BITS fixed point notation, whereas the passed parameter @p r
669  * is interpreted as the fractional part of a Q0.MAX_BITS random value.
670  *
671  * @param r  random value as fractional part of a Q0.MAX_BITS fixed point
672  *           value
673  * @return   COAP_TICKS_PER_SECOND * ACK_TIMEOUT * (1 + (ACK_RANDOM_FACTOR - 1) * r)
674  */
675 static inline unsigned int
calc_timeout(unsigned char r)676 calc_timeout(unsigned char r) {
677   unsigned int result;
678 
679   /* The integer 1.0 as a Qx.FRAC_BITS */
680 #define FP1 Q(FRAC_BITS, 1)
681 
682   /* rounds val up and right shifts by frac positions */
683 #define SHR_FP(val,frac) (((val) + (1 << ((frac) - 1))) >> (frac))
684 
685   /* Inner term: multiply ACK_RANDOM_FACTOR by Q0.MAX_BITS[r] and
686    * make the result a rounded Qx.FRAC_BITS */
687   result = SHR_FP((ACK_RANDOM_FACTOR - FP1) * r, MAX_BITS);
688 
689   /* Add 1 to the inner term and multiply with ACK_TIMEOUT, then
690    * make the result a rounded Qx.FRAC_BITS */
691   result = SHR_FP(((result + FP1) * ACK_TIMEOUT), FRAC_BITS);
692 
693   /* Multiply with COAP_TICKS_PER_SECOND to yield system ticks
694    * (yields a Qx.FRAC_BITS) and shift to get an integer */
695   return SHR_FP((COAP_TICKS_PER_SECOND * result), FRAC_BITS);
696 
697 #undef FP1
698 #undef SHR_FP
699 }
700 
701 coap_tid_t
coap_send_confirmed(coap_context_t * context,const coap_endpoint_t * local_interface,const coap_address_t * dst,coap_pdu_t * pdu)702 coap_send_confirmed(coap_context_t *context,
703 		    const coap_endpoint_t *local_interface,
704 		    const coap_address_t *dst,
705 		    coap_pdu_t *pdu) {
706   coap_queue_t *node;
707   coap_tick_t now;
708   unsigned char r;
709 
710   node = coap_new_node();
711   if (!node) {
712     debug("coap_send_confirmed: insufficient memory\n");
713     return COAP_INVALID_TID;
714   }
715 
716   node->id = coap_send_impl(context, local_interface, dst, pdu);
717   if (COAP_INVALID_TID == node->id) {
718     debug("coap_send_confirmed: error sending pdu\n");
719     coap_free_node(node);
720     return COAP_INVALID_TID;
721   }
722 
723   prng((unsigned char *)&r,sizeof(r));
724 
725   /* add timeout in range [ACK_TIMEOUT...ACK_TIMEOUT * ACK_RANDOM_FACTOR] */
726   node->timeout = calc_timeout(r);
727 
728   node->local_if = *local_interface;
729   memcpy(&node->remote, dst, sizeof(coap_address_t));
730   node->pdu = pdu;
731 
732   /* Set timer for pdu retransmission. If this is the first element in
733    * the retransmission queue, the base time is set to the current
734    * time and the retransmission time is node->timeout. If there is
735    * already an entry in the sendqueue, we must check if this node is
736    * to be retransmitted earlier. Therefore, node->timeout is first
737    * normalized to the base time and then inserted into the queue with
738    * an adjusted relative time.
739    */
740   coap_ticks(&now);
741   if (context->sendqueue == NULL) {
742     node->t = node->timeout;
743     context->sendqueue_basetime = now;
744   } else {
745     /* make node->t relative to context->sendqueue_basetime */
746     node->t = (now - context->sendqueue_basetime) + node->timeout;
747   }
748 
749   coap_insert_node(&context->sendqueue, node);
750 
751 #ifdef WITH_LWIP
752   if (node == context->sendqueue) /* don't bother with timer stuff if there are earlier retransmits */
753     coap_retransmittimer_restart(context);
754 #endif
755 
756 #ifdef WITH_CONTIKI
757   {			    /* (re-)initialize retransmission timer */
758     coap_queue_t *nextpdu;
759 
760     nextpdu = coap_peek_next(context);
761     assert(nextpdu);		/* we have just inserted a node */
762 
763     /* must set timer within the context of the retransmit process */
764     PROCESS_CONTEXT_BEGIN(&coap_retransmit_process);
765     etimer_set(&context->retransmit_timer, nextpdu->t);
766     PROCESS_CONTEXT_END(&coap_retransmit_process);
767   }
768 #endif /* WITH_CONTIKI */
769 
770   return node->id;
771 }
772 
773 coap_tid_t
coap_retransmit(coap_context_t * context,coap_queue_t * node)774 coap_retransmit(coap_context_t *context, coap_queue_t *node) {
775   if (!context || !node)
776     return COAP_INVALID_TID;
777 
778   /* re-initialize timeout when maximum number of retransmissions are not reached yet */
779   if (node->retransmit_cnt < COAP_DEFAULT_MAX_RETRANSMIT) {
780     node->retransmit_cnt++;
781     node->t = node->timeout << node->retransmit_cnt;
782     coap_insert_node(&context->sendqueue, node);
783 #ifdef WITH_LWIP
784     if (node == context->sendqueue) /* don't bother with timer stuff if there are earlier retransmits */
785       coap_retransmittimer_restart(context);
786 #endif
787 
788     debug("** retransmission #%d of transaction %d\n",
789 	  node->retransmit_cnt, ntohs(node->pdu->hdr->id));
790 
791     node->id = coap_send_impl(context, &node->local_if,
792 			      &node->remote, node->pdu);
793     return node->id;
794   }
795 
796   /* no more retransmissions, remove node from system */
797 
798 #ifndef WITH_CONTIKI
799   debug("** removed transaction %d\n", ntohs(node->id));
800 #endif
801 
802 #ifndef WITHOUT_OBSERVE
803   /* Check if subscriptions exist that should be canceled after
804      COAP_MAX_NOTIFY_FAILURES */
805   if (node->pdu->hdr->code >= 64) {
806     str token = { 0, NULL };
807 
808     token.length = node->pdu->hdr->token_length;
809     token.s = node->pdu->hdr->token;
810 
811     coap_handle_failed_notify(context, &node->remote, &token);
812   }
813 #endif /* WITHOUT_OBSERVE */
814 
815   /* And finally delete the node */
816   coap_delete_node( node );
817   return COAP_INVALID_TID;
818 }
819 
820 void coap_dispatch(coap_context_t *context, coap_queue_t *rcvd);
821 
822 int
coap_read(coap_context_t * ctx)823 coap_read( coap_context_t *ctx ) {
824   ssize_t bytes_read = -1;
825   coap_packet_t *packet;
826   coap_address_t src;
827   int result = -1;		/* the value to be returned */
828 
829   coap_address_init(&src);
830 
831 #if defined(WITH_POSIX) || defined(WITH_CONTIKI)
832   bytes_read = ctx->network_read(ctx->endpoint, &packet);
833 #endif /* WITH_POSIX or WITH_CONTIKI */
834 
835   if ( bytes_read < 0 ) {
836     warn("coap_read: recvfrom");
837   } else {
838 #if defined(WITH_POSIX) || defined(WITH_CONTIKI)
839     result = coap_handle_message(ctx, packet);
840 #endif /* WITH_POSIX or WITH_CONTIKI */
841   }
842 
843   coap_free_packet(packet);
844 
845   return result;
846 }
847 
848 int
coap_handle_message(coap_context_t * ctx,coap_packet_t * packet)849 coap_handle_message(coap_context_t *ctx,
850 		    coap_packet_t *packet) {
851 		    /* const coap_address_t *remote,  */
852 		    /* unsigned char *msg, size_t msg_len) { */
853   unsigned char *msg;
854   size_t msg_len;
855   coap_queue_t *node;
856 
857   /* the negated result code */
858   enum result_t { RESULT_OK, RESULT_ERR_EARLY, RESULT_ERR };
859   int result = RESULT_ERR_EARLY;
860 
861   coap_packet_get_memmapped(packet, &msg, &msg_len);
862 
863   if (msg_len < sizeof(coap_hdr_t)) {
864     debug("coap_handle_message: discarded invalid frame\n" );
865     goto error_early;
866   }
867 
868   /* check version identifier */
869   if (((*msg >> 6) & 0x03) != COAP_DEFAULT_VERSION) {
870     debug("coap_handle_message: unknown protocol version %d\n", (*msg >> 6) & 0x03);
871     goto error_early;
872   }
873 
874   node = coap_new_node();
875   if (!node) {
876     goto error_early;
877   }
878 
879   /* from this point, the result code indicates that */
880   result = RESULT_ERR;
881 
882 #ifdef WITH_LWIP
883   node->pdu = coap_pdu_from_pbuf(coap_packet_extract_pbuf(packet));
884 #else
885   node->pdu = coap_pdu_init(0, 0, 0, msg_len);
886 #endif
887   if (!node->pdu) {
888     goto error;
889   }
890 
891   if (!coap_pdu_parse(msg, msg_len, node->pdu)) {
892     warn("discard malformed PDU\n");
893     goto error;
894   }
895 
896   coap_ticks(&node->t);
897 
898   coap_packet_populate_endpoint(packet, &node->local_if);
899   coap_packet_copy_source(packet, &node->remote);
900 
901   /* and add new node to receive queue */
902   coap_transaction_id(&node->remote, node->pdu, &node->id);
903 
904 #ifndef NDEBUG
905   if (LOG_DEBUG <= coap_get_log_level()) {
906 #ifndef INET6_ADDRSTRLEN
907 #define INET6_ADDRSTRLEN 40
908 #endif
909     /** @FIXME get debug to work again **
910     unsigned char addr[INET6_ADDRSTRLEN+8], localaddr[INET6_ADDRSTRLEN+8];
911     if (coap_print_addr(remote, addr, INET6_ADDRSTRLEN+8) &&
912 	coap_print_addr(&packet->dst, localaddr, INET6_ADDRSTRLEN+8) )
913       debug("** received %d bytes from %s on interface %s:\n",
914 	    (int)msg_len, addr, localaddr);
915 
916 	    */
917     coap_show_pdu(node->pdu);
918   }
919 #endif
920 
921   coap_dispatch(ctx, node);
922   return -RESULT_OK;
923 
924  error:
925   /* FIXME: send back RST? */
926   coap_delete_node(node);
927   return -result;
928 
929  error_early:
930   return -result;
931 }
932 
933 int
coap_remove_from_queue(coap_queue_t ** queue,coap_tid_t id,coap_queue_t ** node)934 coap_remove_from_queue(coap_queue_t **queue, coap_tid_t id, coap_queue_t **node) {
935   coap_queue_t *p, *q;
936 
937   if ( !queue || !*queue)
938     return 0;
939 
940   /* replace queue head if PDU's time is less than head's time */
941 
942   if ( id == (*queue)->id ) { /* found transaction */
943     *node = *queue;
944     *queue = (*queue)->next;
945     if (*queue) {	  /* adjust relative time of new queue head */
946       (*queue)->t += (*node)->t;
947     }
948     (*node)->next = NULL;
949     /* coap_delete_node( q ); */
950     debug("*** removed transaction %u\n", id);
951     return 1;
952   }
953 
954   /* search transaction to remove (only first occurence will be removed) */
955   q = *queue;
956   do {
957     p = q;
958     q = q->next;
959   } while ( q && id != q->id );
960 
961   if ( q ) {			/* found transaction */
962     p->next = q->next;
963     if (p->next) {		/* must update relative time of p->next */
964       p->next->t += q->t;
965     }
966     q->next = NULL;
967     *node = q;
968     /* coap_delete_node( q ); */
969     debug("*** removed transaction %u\n", id);
970     return 1;
971   }
972 
973   return 0;
974 
975 }
976 
977 static inline int
token_match(const unsigned char * a,size_t alen,const unsigned char * b,size_t blen)978 token_match(const unsigned char *a, size_t alen,
979 	    const unsigned char *b, size_t blen) {
980   return alen == blen && (alen == 0 || memcmp(a, b, alen) == 0);
981 }
982 
983 void
coap_cancel_all_messages(coap_context_t * context,const coap_address_t * dst,const unsigned char * token,size_t token_length)984 coap_cancel_all_messages(coap_context_t *context, const coap_address_t *dst,
985 			 const unsigned char *token, size_t token_length) {
986   /* cancel all messages in sendqueue that are for dst
987    * and use the specified token */
988   coap_queue_t *p, *q;
989 
990   while (context->sendqueue &&
991 	 coap_address_equals(dst, &context->sendqueue->remote) &&
992 	 token_match(token, token_length,
993 		     context->sendqueue->pdu->hdr->token,
994 		     context->sendqueue->pdu->hdr->token_length)) {
995     q = context->sendqueue;
996     context->sendqueue = q->next;
997     debug("**** removed transaction %d\n", ntohs(q->pdu->hdr->id));
998     coap_delete_node(q);
999   }
1000 
1001   if (!context->sendqueue)
1002     return;
1003 
1004   p = context->sendqueue;
1005   q = p->next;
1006 
1007   /* when q is not NULL, it does not match (dst, token), so we can skip it */
1008   while (q) {
1009     if (coap_address_equals(dst, &q->remote) &&
1010 	token_match(token, token_length,
1011 		    q->pdu->hdr->token, q->pdu->hdr->token_length)) {
1012       p->next = q->next;
1013       debug("**** removed transaction %d\n", ntohs(q->pdu->hdr->id));
1014       coap_delete_node(q);
1015       q = p->next;
1016     } else {
1017       p = q;
1018       q = q->next;
1019     }
1020   }
1021 }
1022 
1023 coap_queue_t *
coap_find_transaction(coap_queue_t * queue,coap_tid_t id)1024 coap_find_transaction(coap_queue_t *queue, coap_tid_t id) {
1025   while (queue && queue->id != id)
1026     queue = queue->next;
1027 
1028   return queue;
1029 }
1030 
1031 coap_pdu_t *
coap_new_error_response(coap_pdu_t * request,unsigned char code,coap_opt_filter_t opts)1032 coap_new_error_response(coap_pdu_t *request, unsigned char code,
1033 			coap_opt_filter_t opts) {
1034   coap_opt_iterator_t opt_iter;
1035   coap_pdu_t *response;
1036   size_t size = sizeof(coap_hdr_t) + request->hdr->token_length;
1037   int type;
1038   coap_opt_t *option;
1039   unsigned short opt_type = 0;	/* used for calculating delta-storage */
1040 
1041 #if COAP_ERROR_PHRASE_LENGTH > 0
1042   char *phrase = coap_response_phrase(code);
1043 
1044   /* Need some more space for the error phrase and payload start marker */
1045   if (phrase)
1046     size += strlen(phrase) + 1;
1047 #endif
1048 
1049   assert(request);
1050 
1051   /* cannot send ACK if original request was not confirmable */
1052   type = request->hdr->type == COAP_MESSAGE_CON
1053     ? COAP_MESSAGE_ACK
1054     : COAP_MESSAGE_NON;
1055 
1056   /* Estimate how much space we need for options to copy from
1057    * request. We always need the Token, for 4.02 the unknown critical
1058    * options must be included as well. */
1059   coap_option_clrb(opts, COAP_OPTION_CONTENT_TYPE); /* we do not want this */
1060 
1061   coap_option_iterator_init(request, &opt_iter, opts);
1062 
1063   /* Add size of each unknown critical option. As known critical
1064      options as well as elective options are not copied, the delta
1065      value might grow.
1066    */
1067   while((option = coap_option_next(&opt_iter))) {
1068     unsigned short delta = opt_iter.type - opt_type;
1069     /* calculate space required to encode (opt_iter.type - opt_type) */
1070     if (delta < 13) {
1071       size++;
1072     } else if (delta < 269) {
1073       size += 2;
1074     } else {
1075       size += 3;
1076     }
1077 
1078     /* add coap_opt_length(option) and the number of additional bytes
1079      * required to encode the option length */
1080 
1081     size += coap_opt_length(option);
1082     switch (*option & 0x0f) {
1083     case 0x0e:
1084       size++;
1085       /* fall through */
1086     case 0x0d:
1087       size++;
1088       break;
1089     default:
1090       ;
1091     }
1092 
1093     opt_type = opt_iter.type;
1094   }
1095 
1096   /* Now create the response and fill with options and payload data. */
1097   response = coap_pdu_init(type, code, request->hdr->id, size);
1098   if (response) {
1099     /* copy token */
1100     if (!coap_add_token(response, request->hdr->token_length,
1101 			request->hdr->token)) {
1102       debug("cannot add token to error response\n");
1103       coap_delete_pdu(response);
1104       return NULL;
1105     }
1106 
1107     /* copy all options */
1108     coap_option_iterator_init(request, &opt_iter, opts);
1109     while((option = coap_option_next(&opt_iter)))
1110       coap_add_option(response, opt_iter.type,
1111 		      COAP_OPT_LENGTH(option),
1112 		      COAP_OPT_VALUE(option));
1113 
1114 #if COAP_ERROR_PHRASE_LENGTH > 0
1115     /* note that diagnostic messages do not need a Content-Format option. */
1116     if (phrase)
1117       coap_add_data(response, strlen(phrase), (unsigned char *)phrase);
1118 #endif
1119   }
1120 
1121   return response;
1122 }
1123 
1124 /**
1125  * Quick hack to determine the size of the resource description for
1126  * .well-known/core.
1127  */
1128 static inline size_t
get_wkc_len(coap_context_t * context,coap_opt_t * query_filter)1129 get_wkc_len(coap_context_t *context, coap_opt_t *query_filter) {
1130   unsigned char buf[1];
1131   size_t len = 0;
1132 
1133   if (coap_print_wellknown(context, buf, &len, UINT_MAX, query_filter)
1134       & COAP_PRINT_STATUS_ERROR) {
1135     warn("cannot determine length of /.well-known/core\n");
1136     return 0;
1137   }
1138 
1139   debug("get_wkc_len: coap_print_wellknown() returned %zu\n", len);
1140 
1141   return len;
1142 }
1143 
1144 #define SZX_TO_BYTES(SZX) ((size_t)(1 << ((SZX) + 4)))
1145 
1146 coap_pdu_t *
coap_wellknown_response(coap_context_t * context,coap_pdu_t * request)1147 coap_wellknown_response(coap_context_t *context, coap_pdu_t *request) {
1148   coap_pdu_t *resp;
1149   coap_opt_iterator_t opt_iter;
1150   size_t len, wkc_len;
1151   unsigned char buf[2];
1152   int result = 0;
1153   int need_block2 = 0;	   /* set to 1 if Block2 option is required */
1154   coap_block_t block;
1155   coap_opt_t *query_filter;
1156   size_t offset = 0;
1157 
1158   resp = coap_pdu_init(request->hdr->type == COAP_MESSAGE_CON
1159 		       ? COAP_MESSAGE_ACK
1160 		       : COAP_MESSAGE_NON,
1161 		       COAP_RESPONSE_CODE(205),
1162 		       request->hdr->id, COAP_MAX_PDU_SIZE);
1163   if (!resp) {
1164     debug("coap_wellknown_response: cannot create PDU\n");
1165     return NULL;
1166   }
1167 
1168   if (!coap_add_token(resp, request->hdr->token_length, request->hdr->token)) {
1169     debug("coap_wellknown_response: cannot add token\n");
1170     goto error;
1171   }
1172 
1173   query_filter = coap_check_option(request, COAP_OPTION_URI_QUERY, &opt_iter);
1174   wkc_len = get_wkc_len(context, query_filter);
1175 
1176   /* The value of some resources is undefined and get_wkc_len will return 0.*/
1177   if (wkc_len == 0){
1178     debug("coap_wellknown_response: undefined resource\n");
1179     /* set error code 4.00 Bad Request*/
1180     resp->hdr->code = COAP_RESPONSE_CODE(400);
1181     resp->length = sizeof(coap_hdr_t) + resp->hdr->token_length;
1182     return resp;
1183   }
1184 
1185   /* check whether the request contains the Block2 option */
1186   if (coap_get_block(request, COAP_OPTION_BLOCK2, &block)) {
1187     debug("create block\n");
1188     offset = block.num << (block.szx + 4);
1189     if (block.szx > 6) {  /* invalid, MUST lead to 4.00 Bad Request */
1190       resp->hdr->code = COAP_RESPONSE_CODE(400);
1191       return resp;
1192     } else if (block.szx > COAP_MAX_BLOCK_SZX) {
1193       block.szx = COAP_MAX_BLOCK_SZX;
1194       block.num = offset >> (block.szx + 4);
1195     }
1196 
1197     need_block2 = 1;
1198   }
1199 
1200   /* Check if there is sufficient space to add Content-Format option
1201    * and data. We do this before adding the Content-Format option to
1202    * avoid sending error responses with that option but no actual
1203    * content. */
1204   if (resp->max_size <= (size_t)resp->length + 3) {
1205     debug("coap_wellknown_response: insufficient storage space\n");
1206     goto error;
1207   }
1208 
1209   /* Add Content-Format. As we have checked for available storage,
1210    * nothing should go wrong here. */
1211   assert(coap_encode_var_bytes(buf,
1212 		    COAP_MEDIATYPE_APPLICATION_LINK_FORMAT) == 1);
1213   coap_add_option(resp, COAP_OPTION_CONTENT_FORMAT,
1214 		  coap_encode_var_bytes(buf,
1215 			COAP_MEDIATYPE_APPLICATION_LINK_FORMAT), buf);
1216 
1217   /* check if Block2 option is required even if not requested */
1218   if (!need_block2 && (resp->max_size - (size_t)resp->length < wkc_len)) {
1219     assert(resp->length <= resp->max_size);
1220     const size_t payloadlen = resp->max_size - resp->length;
1221     /* yes, need block-wise transfer */
1222     block.num = 0;
1223     block.m = 0;      /* the M bit is set by coap_write_block_opt() */
1224     block.szx = COAP_MAX_BLOCK_SZX;
1225     while (payloadlen < SZX_TO_BYTES(block.szx)) {
1226       if (block.szx == 0) {
1227 	debug("coap_wellknown_response: message to small even for szx == 0\n");
1228 	goto error;
1229       } else {
1230 	block.szx--;
1231       }
1232     }
1233 
1234     need_block2 = 1;
1235   }
1236 
1237   /* write Block2 option if necessary */
1238   if (need_block2) {
1239     if (coap_write_block_opt(&block, COAP_OPTION_BLOCK2, resp, wkc_len) < 0) {
1240       debug("coap_wellknown_response: cannot add Block2 option\n");
1241       goto error;
1242     }
1243   }
1244 
1245   /* Manually set payload of response to let print_wellknown() write,
1246    * into our buffer without copying data. */
1247 
1248   resp->data = (unsigned char *)resp->hdr + resp->length;
1249   *resp->data = COAP_PAYLOAD_START;
1250   resp->data++;
1251   resp->length++;
1252   len = need_block2 ? SZX_TO_BYTES(block.szx) : resp->max_size - resp->length;
1253 
1254   result = coap_print_wellknown(context, resp->data, &len, offset, query_filter);
1255   if ((result & COAP_PRINT_STATUS_ERROR) != 0) {
1256     debug("coap_print_wellknown failed\n");
1257     goto error;
1258   }
1259 
1260   resp->length += COAP_PRINT_OUTPUT_LENGTH(result);
1261   return resp;
1262 
1263  error:
1264   /* set error code 5.03 and remove all options and data from response */
1265   resp->hdr->code = COAP_RESPONSE_CODE(503);
1266   resp->length = sizeof(coap_hdr_t) + resp->hdr->token_length;
1267   return resp;
1268 }
1269 
1270 /**
1271  * This function cancels outstanding messages for the remote peer and
1272  * token specified in @p sent. Any observation relationship for
1273  * sent->remote and the token are removed. Calling this function is
1274  * required when receiving an RST message (usually in response to a
1275  * notification) or a GET request with the Observe option set to 1.
1276  *
1277  * This function returns @c 0 when the token is unknown with this
1278  * peer, or a value greater than zero otherwise.
1279  */
1280 static int
coap_cancel(coap_context_t * context,const coap_queue_t * sent)1281 coap_cancel(coap_context_t *context, const coap_queue_t *sent) {
1282 #ifndef WITHOUT_OBSERVE
1283   str token = { 0, NULL };
1284   int num_cancelled = 0;    /* the number of observers cancelled */
1285 
1286   /* remove observer for this resource, if any
1287    * get token from sent and try to find a matching resource. Uh!
1288    */
1289 
1290   COAP_SET_STR(&token, sent->pdu->hdr->token_length, sent->pdu->hdr->token);
1291 
1292   RESOURCES_ITER(context->resources, r) {
1293     num_cancelled += coap_delete_observer(r, &sent->remote, &token);
1294     coap_cancel_all_messages(context, &sent->remote, token.s, token.length);
1295   }
1296 
1297   return num_cancelled;
1298 #else /* WITOUT_OBSERVE */
1299   return 0;
1300 #endif /* WITOUT_OBSERVE */
1301 }
1302 
1303 /**
1304  * Checks for No-Response option in given @p request and
1305  * returns @c 1 if @p response should be suppressed
1306  * according to draft-tcs-coap-no-response-option-11.txt.
1307  *
1308  * The value of the No-Response option is encoded as
1309  * follows:
1310  *
1311  *  +-------+-------------+--------------------------+
1312  *  | Value | Binary Rep. | Description              |
1313  *  +-------+-------------+--------------------------+
1314  *  |     0 |   <empty>   | Allow all responses.     |
1315  *  +-------+-------------+--------------------------+
1316  *  |     2 |   00000010  | Suppress 2.xx responses. |
1317  *  +-------+-------------+--------------------------+
1318  *  |     8 |   00001000  | Suppress 4.xx responses. |
1319  *  +-------+-------------+--------------------------+
1320  *  |    16 |   00010000  | Suppress 5.xx responses. |
1321  *  +-------+-------------+--------------------------+
1322  *  |   127 |   01111111  | Suppress all responses.  |
1323  *  +-------+-------------+--------------------------+
1324  *
1325  * @param request  The CoAP request to check for the No-Response option.
1326  *                 This parameter must not be NULL.
1327  * @param response The response that is potentially suppressed.
1328  *                 This parameter must not be NULL.
1329  * @return @c 1 if the response code matches the No-Response option,
1330  *         or @c 0, otherwise.
1331  */
1332 static inline int
no_response(coap_pdu_t * request,coap_pdu_t * response)1333 no_response(coap_pdu_t *request, coap_pdu_t *response) {
1334   coap_opt_t *nores;
1335   coap_opt_iterator_t opt_iter;
1336   uint8_t val = 0;
1337 
1338   assert(request);
1339   assert(response);
1340 
1341   nores = coap_check_option(request, COAP_OPTION_NORESPONSE, &opt_iter);
1342 
1343   if (nores) {
1344     val = coap_decode_var_bytes(coap_opt_value(nores), coap_opt_length(nores));
1345   }
1346 
1347   return (COAP_RESPONSE_CLASS(response->hdr->code) > 0)
1348     && (((1 << (COAP_RESPONSE_CLASS(response->hdr->code) - 1)) & val) > 0);
1349 }
1350 
1351 #define WANT_WKC(Pdu,Key)					\
1352   (((Pdu)->hdr->code == COAP_REQUEST_GET) && is_wkc(Key))
1353 
1354 static void
handle_request(coap_context_t * context,coap_queue_t * node)1355 handle_request(coap_context_t *context, coap_queue_t *node) {
1356   coap_method_handler_t h = NULL;
1357   coap_pdu_t *response = NULL;
1358   coap_opt_filter_t opt_filter;
1359   coap_resource_t *resource;
1360   coap_key_t key;
1361 
1362   coap_option_filter_clear(opt_filter);
1363 
1364   /* try to find the resource from the request URI */
1365   coap_hash_request_uri(node->pdu, key);
1366   resource = coap_get_resource_from_key(context, key);
1367 
1368   if (!resource) {
1369     /* The resource was not found. Check if the request URI happens to
1370      * be the well-known URI. In that case, we generate a default
1371      * response, otherwise, we return 4.04 */
1372 
1373     switch(node->pdu->hdr->code) {
1374 
1375     case COAP_REQUEST_GET:
1376       if (is_wkc(key)) {	/* GET request for .well-known/core */
1377 	info("create default response for %s\n", COAP_DEFAULT_URI_WELLKNOWN);
1378 	response = coap_wellknown_response(context, node->pdu);
1379 
1380       } else { /* GET request for any another resource, return 4.04 */
1381 
1382 	debug("GET for unknown resource 0x%02x%02x%02x%02x, return 4.04\n",
1383 	      key[0], key[1], key[2], key[3]);
1384 	response =
1385 	  coap_new_error_response(node->pdu, COAP_RESPONSE_CODE(404),
1386 				  opt_filter);
1387       }
1388       break;
1389 
1390     default: 			/* any other request type */
1391 
1392       debug("unhandled request for unknown resource 0x%02x%02x%02x%02x\r\n",
1393 	    key[0], key[1], key[2], key[3]);
1394 
1395 	response = coap_new_error_response(node->pdu, COAP_RESPONSE_CODE(405),
1396 					   opt_filter);
1397     }
1398 
1399     if (response && !no_response(node->pdu, response) && coap_send(context, &node->local_if,
1400 			      &node->remote, response) == COAP_INVALID_TID) {
1401       warn("cannot send response for transaction %u\n", node->id);
1402     }
1403     coap_delete_pdu(response);
1404 
1405     return;
1406   }
1407 
1408   /* the resource was found, check if there is a registered handler */
1409   if ((size_t)node->pdu->hdr->code - 1 <
1410       sizeof(resource->handler)/sizeof(coap_method_handler_t))
1411     h = resource->handler[node->pdu->hdr->code - 1];
1412 
1413   if (h) {
1414     debug("call custom handler for resource 0x%02x%02x%02x%02x\n",
1415 	  key[0], key[1], key[2], key[3]);
1416     response = coap_pdu_init(node->pdu->hdr->type == COAP_MESSAGE_CON
1417 			     ? COAP_MESSAGE_ACK
1418 			     : COAP_MESSAGE_NON,
1419 			     0, node->pdu->hdr->id, COAP_MAX_PDU_SIZE);
1420 
1421     /* Implementation detail: coap_add_token() immediately returns 0
1422        if response == NULL */
1423     if (coap_add_token(response, node->pdu->hdr->token_length,
1424 		       node->pdu->hdr->token)) {
1425       str token = { node->pdu->hdr->token_length, node->pdu->hdr->token };
1426       coap_opt_iterator_t opt_iter;
1427       coap_opt_t *observe = NULL;
1428       int observe_action = COAP_OBSERVE_CANCEL;
1429 
1430       /* check for Observe option */
1431       if (resource->observable) {
1432 	observe = coap_check_option(node->pdu, COAP_OPTION_OBSERVE, &opt_iter);
1433 	if (observe) {
1434 	  observe_action =
1435 	    coap_decode_var_bytes(coap_opt_value(observe),
1436 				  coap_opt_length(observe));
1437 
1438 	  if ((observe_action & COAP_OBSERVE_CANCEL) == 0) {
1439 	    coap_subscription_t *subscription;
1440 
1441 	    coap_log(LOG_DEBUG, "create new subscription\n");
1442 	    subscription = coap_add_observer(resource, &node->local_if,
1443 					     &node->remote, &token);
1444 	    if (subscription) {
1445 	      coap_touch_observer(context, &node->remote, &token);
1446 	    }
1447 	  }
1448 	}
1449       }
1450 
1451       h(context, resource, &node->local_if, &node->remote,
1452 	node->pdu, &token, response);
1453 
1454       if (!no_response(node->pdu, response)) {
1455       if (observe && ((COAP_RESPONSE_CLASS(response->hdr->code) > 2)
1456 		      || ((observe_action & COAP_OBSERVE_CANCEL) != 0))) {
1457 	coap_log(LOG_DEBUG, "removed observer");
1458 	coap_delete_observer(resource,  &node->remote, &token);
1459       }
1460 
1461       /* If original request contained a token, and the registered
1462        * application handler made no changes to the response, then
1463        * this is an empty ACK with a token, which is a malformed
1464        * PDU */
1465       if ((response->hdr->type == COAP_MESSAGE_ACK)
1466 	  && (response->hdr->code == 0)) {
1467 	/* Remove token from otherwise-empty acknowledgment PDU */
1468 	response->hdr->token_length = 0;
1469 	response->length = sizeof(coap_hdr_t);
1470       }
1471 
1472       if (response->hdr->type != COAP_MESSAGE_NON ||
1473 	  (response->hdr->code >= 64
1474 	   && !coap_mcast_interface(&node->local_if))) {
1475 
1476 	if (coap_send(context, &node->local_if,
1477 		      &node->remote, response) == COAP_INVALID_TID) {
1478 	  debug("cannot send response for message %d\n", node->pdu->hdr->id);
1479 	  }
1480       }
1481       }
1482       coap_delete_pdu(response);
1483     } else {
1484       warn("cannot generate response\r\n");
1485     }
1486   } else {
1487     if (WANT_WKC(node->pdu, key)) {
1488       debug("create default response for %s\n", COAP_DEFAULT_URI_WELLKNOWN);
1489       response = coap_wellknown_response(context, node->pdu);
1490       debug("have wellknown response %p\n", (void *)response);
1491     } else
1492       response = coap_new_error_response(node->pdu, COAP_RESPONSE_CODE(405),
1493 					 opt_filter);
1494 
1495     if (!response || (coap_send(context, &node->local_if, &node->remote,
1496 				response) == COAP_INVALID_TID)) {
1497       debug("cannot send response for transaction %u\n", node->id);
1498     }
1499     coap_delete_pdu(response);
1500   }
1501 }
1502 
1503 static inline void
handle_response(coap_context_t * context,coap_queue_t * sent,coap_queue_t * rcvd)1504 handle_response(coap_context_t *context,
1505 		coap_queue_t *sent, coap_queue_t *rcvd) {
1506 
1507   coap_send_ack(context, &rcvd->local_if, &rcvd->remote, rcvd->pdu);
1508 
1509   /* In a lossy context, the ACK of a separate response may have
1510    * been lost, so we need to stop retransmitting requests with the
1511    * same token.
1512    */
1513   coap_cancel_all_messages(context, &rcvd->remote,
1514 			   rcvd->pdu->hdr->token,
1515 			   rcvd->pdu->hdr->token_length);
1516 
1517   /* Call application-specific response handler when available. */
1518   if (context->response_handler) {
1519     context->response_handler(context, &rcvd->local_if,
1520 			      &rcvd->remote, sent ? sent->pdu : NULL,
1521 			      rcvd->pdu, rcvd->id);
1522   }
1523 }
1524 
1525 static inline int
1526 #ifdef __GNUC__
handle_locally(coap_context_t * context,coap_queue_t * node)1527 handle_locally(coap_context_t *context __attribute__ ((unused)),
1528 	       coap_queue_t *node __attribute__ ((unused))) {
1529 #else /* not a GCC */
1530 handle_locally(coap_context_t *context, coap_queue_t *node) {
1531 #endif /* GCC */
1532   /* this function can be used to check if node->pdu is really for us */
1533   return 1;
1534 }
1535 
1536 void
1537 coap_dispatch(coap_context_t *context, coap_queue_t *rcvd) {
1538   coap_queue_t *sent = NULL;
1539   coap_pdu_t *response;
1540   coap_opt_filter_t opt_filter;
1541 
1542   if (!context)
1543     return;
1544 
1545   memset(opt_filter, 0, sizeof(coap_opt_filter_t));
1546 
1547   {
1548     /* version has been checked in coap_handle_message() */
1549     /* if ( rcvd->pdu->hdr->version != COAP_DEFAULT_VERSION ) { */
1550     /*   debug("dropped packet with unknown version %u\n", rcvd->pdu->hdr->version); */
1551     /*   goto cleanup; */
1552     /* } */
1553 
1554     switch (rcvd->pdu->hdr->type) {
1555     case COAP_MESSAGE_ACK:
1556       /* find transaction in sendqueue to stop retransmission */
1557       coap_remove_from_queue(&context->sendqueue, rcvd->id, &sent);
1558 
1559       if (rcvd->pdu->hdr->code == 0)
1560 	goto cleanup;
1561 
1562       /* if sent code was >= 64 the message might have been a
1563        * notification. Then, we must flag the observer to be alive
1564        * by setting obs->fail_cnt = 0. */
1565       if (sent && COAP_RESPONSE_CLASS(sent->pdu->hdr->code) == 2) {
1566 	const str token =
1567 	  { sent->pdu->hdr->token_length, sent->pdu->hdr->token };
1568 	coap_touch_observer(context, &sent->remote, &token);
1569       }
1570       break;
1571 
1572     case COAP_MESSAGE_RST :
1573       /* We have sent something the receiver disliked, so we remove
1574        * not only the transaction but also the subscriptions we might
1575        * have. */
1576 
1577 #ifndef WITH_CONTIKI
1578       coap_log(LOG_ALERT, "got RST for message %u\n", ntohs(rcvd->pdu->hdr->id));
1579 #else /* WITH_CONTIKI */
1580       coap_log(LOG_ALERT, "got RST for message %u\n", uip_ntohs(rcvd->pdu->hdr->id));
1581 #endif /* WITH_CONTIKI */
1582 
1583       /* find transaction in sendqueue to stop retransmission */
1584       coap_remove_from_queue(&context->sendqueue, rcvd->id, &sent);
1585 
1586       if (sent)
1587 	coap_cancel(context, sent);
1588       goto cleanup;
1589 
1590     case COAP_MESSAGE_NON :	/* check for unknown critical options */
1591       if (coap_option_check_critical(context, rcvd->pdu, opt_filter) == 0)
1592 	goto cleanup;
1593       break;
1594 
1595     case COAP_MESSAGE_CON :	/* check for unknown critical options */
1596       if (coap_option_check_critical(context, rcvd->pdu, opt_filter) == 0) {
1597 
1598 	/* FIXME: send response only if we have received a request. Otherwise,
1599 	 * send RST. */
1600 	response =
1601 	  coap_new_error_response(rcvd->pdu, COAP_RESPONSE_CODE(402), opt_filter);
1602 
1603 	if (!response)
1604 	  warn("coap_dispatch: cannot create error response\n");
1605 	else {
1606 	  if (coap_send(context, &rcvd->local_if, &rcvd->remote, response)
1607 	      == COAP_INVALID_TID) {
1608 	    warn("coap_dispatch: error sending response\n");
1609 	  }
1610           coap_delete_pdu(response);
1611 	}
1612 
1613 	goto cleanup;
1614       }
1615     default: break;
1616     }
1617 
1618     /* Pass message to upper layer if a specific handler was
1619      * registered for a request that should be handled locally. */
1620     if (handle_locally(context, rcvd)) {
1621       if (COAP_MESSAGE_IS_REQUEST(rcvd->pdu->hdr))
1622 	handle_request(context, rcvd);
1623       else if (COAP_MESSAGE_IS_RESPONSE(rcvd->pdu->hdr))
1624 	handle_response(context, sent, rcvd);
1625       else {
1626 	debug("dropped message with invalid code (%d.%02d)\n",
1627 	      COAP_RESPONSE_CLASS(rcvd->pdu->hdr->code),
1628 	      rcvd->pdu->hdr->code & 0x1f);
1629 
1630 	if (!coap_is_mcast(&rcvd->local_if.addr)) {
1631 	  coap_send_message_type(context, &rcvd->local_if, &rcvd->remote,
1632 				 rcvd->pdu, COAP_MESSAGE_RST);
1633 	}
1634       }
1635     }
1636 
1637   cleanup:
1638     coap_delete_node(sent);
1639     coap_delete_node(rcvd);
1640   }
1641 }
1642 
1643 int
1644 coap_can_exit( coap_context_t *context ) {
1645   return !context || (context->sendqueue == NULL);
1646 }
1647 
1648 #ifdef WITH_CONTIKI
1649 
1650 /*---------------------------------------------------------------------------*/
1651 /* CoAP message retransmission */
1652 /*---------------------------------------------------------------------------*/
1653 PROCESS_THREAD(coap_retransmit_process, ev, data)
1654 {
1655   coap_tick_t now;
1656   coap_queue_t *nextpdu;
1657 
1658   PROCESS_BEGIN();
1659 
1660   debug("Started retransmit process\r\n");
1661 
1662   while(1) {
1663     PROCESS_YIELD();
1664     if (ev == PROCESS_EVENT_TIMER) {
1665       if (etimer_expired(&the_coap_context.retransmit_timer)) {
1666 
1667 	nextpdu = coap_peek_next(&the_coap_context);
1668 
1669 	coap_ticks(&now);
1670 	while (nextpdu && nextpdu->t <= now) {
1671 	  coap_retransmit(&the_coap_context, coap_pop_next(&the_coap_context));
1672 	  nextpdu = coap_peek_next(&the_coap_context);
1673 	}
1674 
1675 	/* need to set timer to some value even if no nextpdu is available */
1676 	etimer_set(&the_coap_context.retransmit_timer,
1677 		   nextpdu ? nextpdu->t - now : 0xFFFF);
1678       }
1679 #ifndef WITHOUT_OBSERVE
1680       if (etimer_expired(&the_coap_context.notify_timer)) {
1681 	coap_check_notify(&the_coap_context);
1682 	etimer_reset(&the_coap_context.notify_timer);
1683       }
1684 #endif /* WITHOUT_OBSERVE */
1685     }
1686   }
1687 
1688   PROCESS_END();
1689 }
1690 /*---------------------------------------------------------------------------*/
1691 
1692 #endif /* WITH_CONTIKI */
1693 
1694 #ifdef WITH_LWIP
1695 /* FIXME: retransmits that are not required any more due to incoming packages
1696  * do *not* get cleared at the moment, the wakeup when the transmission is due
1697  * is silently accepted. this is mainly due to the fact that the required
1698  * checks are similar in two places in the code (when receiving ACK and RST)
1699  * and that they cause more than one patch chunk, as it must be first checked
1700  * whether the sendqueue item to be dropped is the next one pending, and later
1701  * the restart function has to be called. nothing insurmountable, but it can
1702  * also be implemented when things have stabilized, and the performance
1703  * penality is minimal
1704  *
1705  * also, this completely ignores COAP_RESOURCE_CHECK_TIME.
1706  * */
1707 
1708 static void coap_retransmittimer_execute(void *arg)
1709 {
1710 	coap_context_t *ctx = (coap_context_t*)arg;
1711 	coap_tick_t now;
1712 	coap_tick_t elapsed;
1713 	coap_queue_t *nextinqueue;
1714 
1715 	ctx->timer_configured = 0;
1716 
1717 	coap_ticks(&now);
1718 
1719 	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 */
1720 
1721 	nextinqueue = coap_peek_next(ctx);
1722 	while (nextinqueue != NULL)
1723 	{
1724 		if (nextinqueue->t > elapsed) {
1725 			nextinqueue->t -= elapsed;
1726 			break;
1727 		} else {
1728 			elapsed -= nextinqueue->t;
1729 			coap_retransmit(ctx, coap_pop_next(ctx));
1730 			nextinqueue = coap_peek_next(ctx);
1731 		}
1732 	}
1733 
1734 	ctx->sendqueue_basetime = now;
1735 
1736 	coap_retransmittimer_restart(ctx);
1737 }
1738 
1739 static void coap_retransmittimer_restart(coap_context_t *ctx)
1740 {
1741 	coap_tick_t now, elapsed, delay;
1742 
1743 	if (ctx->timer_configured)
1744 	{
1745 		printf("clearing\n");
1746 		sys_untimeout(coap_retransmittimer_execute, (void*)ctx);
1747 		ctx->timer_configured = 0;
1748 	}
1749 	if (ctx->sendqueue != NULL)
1750 	{
1751 		coap_ticks(&now);
1752 		elapsed = now - ctx->sendqueue_basetime;
1753 		if (ctx->sendqueue->t >= elapsed) {
1754 			delay = ctx->sendqueue->t - elapsed;
1755 		} else {
1756 			/* a strange situation, but not completely impossible.
1757 			 *
1758 			 * this happens, for example, right after
1759 			 * coap_retransmittimer_execute, when a retransmission
1760 			 * was *just not yet* due, and the clock ticked before
1761 			 * our coap_ticks was called.
1762 			 *
1763 			 * not trying to retransmit anything now, as it might
1764 			 * cause uncontrollable recursion; let's just try again
1765 			 * with the next main loop run.
1766 			 * */
1767 			delay = 0;
1768 		}
1769 
1770 		printf("scheduling for %d ticks\n", delay);
1771 		sys_timeout(delay, coap_retransmittimer_execute, (void*)ctx);
1772 		ctx->timer_configured = 1;
1773 	}
1774 }
1775 #endif
1776