• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* net.c -- CoAP network interface
2  *
3  * Copyright (C) 2010--2019 Olaf Bergmann <bergmann@tzi.org> and others
4  *
5  * SPDX-License-Identifier: BSD-2-Clause
6  *
7  * This file is part of the CoAP library libcoap. Please see
8  * README for terms of use.
9  */
10 
11 #include "coap3/coap_internal.h"
12 
13 #include <ctype.h>
14 #include <stdio.h>
15 #include <errno.h>
16 #ifdef HAVE_LIMITS_H
17 #include <limits.h>
18 #endif
19 #ifdef HAVE_UNISTD_H
20 #include <unistd.h>
21 #else
22 #ifdef HAVE_SYS_UNISTD_H
23 #include <sys/unistd.h>
24 #endif
25 #endif
26 #ifdef HAVE_SYS_TYPES_H
27 #include <sys/types.h>
28 #endif
29 #ifdef HAVE_SYS_SOCKET_H
30 #include <sys/socket.h>
31 #endif
32 #ifdef HAVE_SYS_IOCTL_H
33 #include <sys/ioctl.h>
34 #endif
35 #ifdef HAVE_NETINET_IN_H
36 #include <netinet/in.h>
37 #endif
38 #ifdef HAVE_ARPA_INET_H
39 #include <arpa/inet.h>
40 #endif
41 #ifdef HAVE_NET_IF_H
42 #include <net/if.h>
43 #endif
44 #ifdef COAP_EPOLL_SUPPORT
45 #include <sys/epoll.h>
46 #include <sys/timerfd.h>
47 #endif /* COAP_EPOLL_SUPPORT */
48 #ifdef HAVE_WS2TCPIP_H
49 #include <ws2tcpip.h>
50 #endif
51 
52 #ifdef HAVE_NETDB_H
53 #include <netdb.h>
54 #endif
55 
56 #ifdef WITH_LWIP
57 #include <lwip/pbuf.h>
58 #include <lwip/udp.h>
59 #include <lwip/timeouts.h>
60 #endif
61 
62 #ifndef INET6_ADDRSTRLEN
63 #define INET6_ADDRSTRLEN 40
64 #endif
65 
66 #ifndef min
67 #define min(a,b) ((a) < (b) ? (a) : (b))
68 #endif
69 
70       /**
71        * The number of bits for the fractional part of ACK_TIMEOUT and
72        * ACK_RANDOM_FACTOR. Must be less or equal 8.
73        */
74 #define FRAC_BITS 6
75 
76        /**
77         * The maximum number of bits for fixed point integers that are used
78         * for retransmission time calculation. Currently this must be @c 8.
79         */
80 #define MAX_BITS 8
81 
82 #if FRAC_BITS > 8
83 #error FRAC_BITS must be less or equal 8
84 #endif
85 
86         /** creates a Qx.frac from fval in coap_fixed_point_t */
87 #define Q(frac,fval) ((uint16_t)(((1 << (frac)) * fval.integer_part) + \
88                       ((1 << (frac)) * fval.fractional_part + 500)/1000))
89 
90 /** creates a Qx.FRAC_BITS from session's 'ack_random_factor' */
91 #define ACK_RANDOM_FACTOR                                        \
92   Q(FRAC_BITS, session->ack_random_factor)
93 
94 /** creates a Qx.FRAC_BITS from session's 'ack_timeout' */
95 #define ACK_TIMEOUT Q(FRAC_BITS, session->ack_timeout)
96 
97 #if !defined(WITH_LWIP) && !defined(WITH_CONTIKI)
98 
99 COAP_STATIC_INLINE coap_queue_t *
coap_malloc_node(void)100 coap_malloc_node(void) {
101   return (coap_queue_t *)coap_malloc_type(COAP_NODE, sizeof(coap_queue_t));
102 }
103 
104 COAP_STATIC_INLINE void
coap_free_node(coap_queue_t * node)105 coap_free_node(coap_queue_t *node) {
106   coap_free_type(COAP_NODE, node);
107 }
108 #endif /* !defined(WITH_LWIP) && !defined(WITH_CONTIKI) */
109 
110 #ifdef WITH_LWIP
111 
112 #include <lwip/memp.h>
113 
114 static void coap_retransmittimer_execute(void *arg);
115 static void coap_retransmittimer_restart(coap_context_t *ctx);
116 
117 COAP_STATIC_INLINE coap_queue_t *
coap_malloc_node()118 coap_malloc_node() {
119   return (coap_queue_t *)memp_malloc(MEMP_COAP_NODE);
120 }
121 
122 COAP_STATIC_INLINE void
coap_free_node(coap_queue_t * node)123 coap_free_node(coap_queue_t *node) {
124   memp_free(MEMP_COAP_NODE, node);
125 }
126 
127 #endif /* WITH_LWIP */
128 #ifdef WITH_CONTIKI
129 # ifndef DEBUG
130 #  define DEBUG DEBUG_PRINT
131 # endif /* DEBUG */
132 
133 #include "net/ip/uip-debug.h"
134 
135 #define UIP_IP_BUF   ((struct uip_ip_hdr *)&uip_buf[UIP_LLH_LEN])
136 #define UIP_UDP_BUF  ((struct uip_udp_hdr *)&uip_buf[UIP_LLIPH_LEN])
137 
138 void coap_resources_init();
139 
140 unsigned char initialized = 0;
141 coap_context_t the_coap_context;
142 
143 PROCESS(coap_retransmit_process, "message retransmit process");
144 
145 COAP_STATIC_INLINE coap_queue_t *
coap_malloc_node()146 coap_malloc_node() {
147   return (coap_queue_t *)coap_malloc_type(COAP_NODE, 0);
148 }
149 
150 COAP_STATIC_INLINE void
coap_free_node(coap_queue_t * node)151 coap_free_node(coap_queue_t *node) {
152   coap_free_type(COAP_NODE, node);
153 }
154 #endif /* WITH_CONTIKI */
155 
156 unsigned int
coap_adjust_basetime(coap_context_t * ctx,coap_tick_t now)157 coap_adjust_basetime(coap_context_t *ctx, coap_tick_t now) {
158   unsigned int result = 0;
159   coap_tick_diff_t delta = now - ctx->sendqueue_basetime;
160 
161   if (ctx->sendqueue) {
162     /* delta < 0 means that the new time stamp is before the old. */
163     if (delta <= 0) {
164       ctx->sendqueue->t -= delta;
165     } else {
166       /* This case is more complex: The time must be advanced forward,
167        * thus possibly leading to timed out elements at the queue's
168        * start. For every element that has timed out, its relative
169        * time is set to zero and the result counter is increased. */
170 
171       coap_queue_t *q = ctx->sendqueue;
172       coap_tick_t t = 0;
173       while (q && (t + q->t < (coap_tick_t)delta)) {
174         t += q->t;
175         q->t = 0;
176         result++;
177         q = q->next;
178       }
179 
180       /* finally adjust the first element that has not expired */
181       if (q) {
182         q->t = (coap_tick_t)delta - t;
183       }
184     }
185   }
186 
187   /* adjust basetime */
188   ctx->sendqueue_basetime += delta;
189 
190   return result;
191 }
192 
193 int
coap_insert_node(coap_queue_t ** queue,coap_queue_t * node)194 coap_insert_node(coap_queue_t **queue, coap_queue_t *node) {
195   coap_queue_t *p, *q;
196   if (!queue || !node)
197     return 0;
198 
199   /* set queue head if empty */
200   if (!*queue) {
201     *queue = node;
202     return 1;
203   }
204 
205   /* replace queue head if PDU's time is less than head's time */
206   q = *queue;
207   if (node->t < q->t) {
208     node->next = q;
209     *queue = node;
210     q->t -= node->t;                /* make q->t relative to node->t */
211     return 1;
212   }
213 
214   /* search for right place to insert */
215   do {
216     node->t -= q->t;                /* make node-> relative to q->t */
217     p = q;
218     q = q->next;
219   } while (q && q->t <= node->t);
220 
221   /* insert new item */
222   if (q) {
223     q->t -= node->t;                /* make q->t relative to node->t */
224   }
225   node->next = q;
226   p->next = node;
227   return 1;
228 }
229 
230 int
coap_delete_node(coap_queue_t * node)231 coap_delete_node(coap_queue_t *node) {
232   if (!node)
233     return 0;
234 
235   coap_delete_pdu(node->pdu);
236   if ( node->session ) {
237     /*
238      * Need to remove out of context->sendqueue as added in by coap_wait_ack()
239      */
240     if (node->session->context->sendqueue) {
241       LL_DELETE(node->session->context->sendqueue, node);
242     }
243     coap_session_release(node->session);
244   }
245   coap_free_node(node);
246 
247   return 1;
248 }
249 
250 void
coap_delete_all(coap_queue_t * queue)251 coap_delete_all(coap_queue_t *queue) {
252   if (!queue)
253     return;
254 
255   coap_delete_all(queue->next);
256   coap_delete_node(queue);
257 }
258 
259 coap_queue_t *
coap_new_node(void)260 coap_new_node(void) {
261   coap_queue_t *node;
262   node = coap_malloc_node();
263 
264   if (!node) {
265     coap_log(LOG_WARNING, "coap_new_node: malloc failed\n");
266     return NULL;
267   }
268 
269   memset(node, 0, sizeof(*node));
270   return node;
271 }
272 
273 coap_queue_t *
coap_peek_next(coap_context_t * context)274 coap_peek_next(coap_context_t *context) {
275   if (!context || !context->sendqueue)
276     return NULL;
277 
278   return context->sendqueue;
279 }
280 
281 coap_queue_t *
coap_pop_next(coap_context_t * context)282 coap_pop_next(coap_context_t *context) {
283   coap_queue_t *next;
284 
285   if (!context || !context->sendqueue)
286     return NULL;
287 
288   next = context->sendqueue;
289   context->sendqueue = context->sendqueue->next;
290   if (context->sendqueue) {
291     context->sendqueue->t += next->t;
292   }
293   next->next = NULL;
294   return next;
295 }
296 
297 static size_t
coap_get_session_client_psk(const coap_session_t * session,const uint8_t * hint,size_t hint_len,uint8_t * identity,size_t * identity_len,size_t max_identity_len,uint8_t * psk,size_t max_psk_len)298 coap_get_session_client_psk(
299   const coap_session_t *session,
300   const uint8_t *hint, size_t hint_len,
301   uint8_t *identity, size_t *identity_len, size_t max_identity_len,
302   uint8_t *psk, size_t max_psk_len
303 ) {
304   const coap_dtls_cpsk_info_t *psk_info;
305   (void)hint;
306   (void)hint_len;
307 
308   if (session->psk_identity && session->psk_key) {
309     if (session->psk_identity->length <= max_identity_len &&
310         session->psk_key->length <= max_psk_len) {
311       memcpy(identity, session->psk_identity->s, session->psk_identity->length);
312       memcpy(psk, session->psk_key->s, session->psk_key->length);
313       *identity_len = session->psk_identity->length;
314       return session->psk_key->length;
315     }
316   }
317   psk_info = &session->cpsk_setup_data.psk_info;
318   if (psk_info->identity.s && psk_info->identity.length > 0 &&
319       psk_info->key.s && psk_info->key.length > 0) {
320     if (psk_info->identity.length <= max_identity_len &&
321       psk_info->key.length <= max_psk_len) {
322       memcpy(identity, psk_info->identity.s, psk_info->identity.length);
323       memcpy(psk, psk_info->key.s, psk_info->key.length);
324       *identity_len = psk_info->identity.length;
325       return psk_info->key.length;
326     }
327   }
328   /* Not defined in coap_new_client_session_psk2() */
329   *identity_len = 0;
330   return 0;
331 }
332 
333 static size_t
coap_get_context_server_psk(const coap_session_t * session,const uint8_t * identity,size_t identity_len,uint8_t * psk,size_t max_psk_len)334 coap_get_context_server_psk(
335   const coap_session_t *session,
336   const uint8_t *identity, size_t identity_len,
337   uint8_t *psk, size_t max_psk_len
338 ) {
339   const coap_dtls_spsk_info_t *psk_info;
340   (void)identity;
341   (void)identity_len;
342 
343   if (!session)
344     return 0;
345 
346   if (session->psk_key &&
347       session->psk_key->length <= max_psk_len) {
348     memcpy(psk, session->psk_key->s, session->psk_key->length);
349     return session->psk_key->length;
350   }
351   psk_info = &session->context->spsk_setup_data.psk_info;
352   if (psk_info->key.s && psk_info->key.length > 0 &&
353       psk_info->key.length <= max_psk_len) {
354     memcpy(psk, psk_info->key.s, psk_info->key.length);
355     return psk_info->key.length;
356   }
357   /* Not defined in coap_context_set_psk2() */
358   return 0;
359 }
360 
361 static size_t
coap_get_context_server_hint(const coap_session_t * session,uint8_t * hint,size_t max_hint_len)362 coap_get_context_server_hint(
363   const coap_session_t *session,
364   uint8_t *hint, size_t max_hint_len
365 ) {
366   const coap_dtls_spsk_info_t *psk_info;
367 
368   if (!session)
369     return 0;
370 
371   if (session->psk_hint &&
372       session->psk_hint->s && session->psk_hint->length > 0 &&
373       session->psk_hint->length <= max_hint_len) {
374     memcpy(hint, session->psk_hint->s, session->psk_hint->length);
375     return session->psk_hint->length;
376   }
377   psk_info = &session->context->spsk_setup_data.psk_info;
378   if (psk_info->hint.s &&
379       psk_info->hint.length > 0 &&
380       psk_info->hint.length <= max_hint_len) {
381     memcpy(hint, psk_info->hint.s, psk_info->hint.length);
382     return psk_info->hint.length;
383   }
384   /* Not defined in coap_context_set_psk2() */
385   return 0;
386 }
387 
coap_context_set_psk(coap_context_t * ctx,const char * hint,const uint8_t * key,size_t key_len)388 int coap_context_set_psk(coap_context_t *ctx,
389   const char *hint,
390   const uint8_t *key, size_t key_len
391 ) {
392   coap_dtls_spsk_t setup_data;
393 
394   memset (&setup_data, 0, sizeof(setup_data));
395   if (hint) {
396     setup_data.psk_info.hint.s = (const uint8_t *)hint;
397     setup_data.psk_info.hint.length = strlen(hint);
398   }
399 
400   if (key && key_len > 0) {
401     setup_data.psk_info.key.s = key;
402     setup_data.psk_info.key.length = key_len;
403   }
404 
405   return coap_context_set_psk2(ctx, &setup_data);
406 }
407 
coap_context_set_psk2(coap_context_t * ctx,coap_dtls_spsk_t * setup_data)408 int coap_context_set_psk2(coap_context_t *ctx,
409   coap_dtls_spsk_t *setup_data
410 ) {
411   if (!setup_data)
412     return 0;
413 
414   ctx->spsk_setup_data = *setup_data;
415 
416   if (coap_dtls_is_supported()) {
417     return coap_dtls_context_set_spsk(ctx, setup_data);
418   }
419   return 0;
420 }
421 
coap_context_set_pki(coap_context_t * ctx,const coap_dtls_pki_t * setup_data)422 int coap_context_set_pki(coap_context_t *ctx,
423   const coap_dtls_pki_t* setup_data
424 ) {
425   if (!setup_data)
426     return 0;
427   if (setup_data->version != COAP_DTLS_PKI_SETUP_VERSION) {
428     coap_log(LOG_ERR, "coap_context_set_pki: Wrong version of setup_data\n");
429     return 0;
430   }
431   if (coap_dtls_is_supported()) {
432     return coap_dtls_context_set_pki(ctx, setup_data, COAP_DTLS_ROLE_SERVER);
433   }
434   return 0;
435 }
436 
coap_context_set_pki_root_cas(coap_context_t * ctx,const char * ca_file,const char * ca_dir)437 int coap_context_set_pki_root_cas(coap_context_t *ctx,
438   const char *ca_file,
439   const char *ca_dir
440 ) {
441   if (coap_dtls_is_supported()) {
442     return coap_dtls_context_set_pki_root_cas(ctx, ca_file, ca_dir);
443   }
444   return 0;
445 }
446 
coap_context_set_keepalive(coap_context_t * context,unsigned int seconds)447 void coap_context_set_keepalive(coap_context_t *context, unsigned int seconds) {
448   context->ping_timeout = seconds;
449 }
450 
451 void
coap_context_set_max_idle_sessions(coap_context_t * context,unsigned int max_idle_sessions)452 coap_context_set_max_idle_sessions(coap_context_t *context,
453                                    unsigned int max_idle_sessions) {
454   context->max_idle_sessions = max_idle_sessions;
455 }
456 
457 unsigned int
coap_context_get_max_idle_sessions(const coap_context_t * context)458 coap_context_get_max_idle_sessions(const coap_context_t *context) {
459   return context->max_idle_sessions;
460 }
461 
462 void
coap_context_set_max_handshake_sessions(coap_context_t * context,unsigned int max_handshake_sessions)463 coap_context_set_max_handshake_sessions(coap_context_t *context,
464                                         unsigned int max_handshake_sessions) {
465   context->max_handshake_sessions = max_handshake_sessions;
466 }
467 
468 unsigned int
coap_context_get_max_handshake_sessions(const coap_context_t * context)469 coap_context_get_max_handshake_sessions(const coap_context_t *context) {
470   return context->max_handshake_sessions;
471 }
472 
473 void
coap_context_set_csm_timeout(coap_context_t * context,unsigned int csm_timeout)474 coap_context_set_csm_timeout(coap_context_t *context,
475                              unsigned int csm_timeout) {
476   context->csm_timeout = csm_timeout;
477 }
478 
479 unsigned int
coap_context_get_csm_timeout(const coap_context_t * context)480 coap_context_get_csm_timeout(const coap_context_t *context) {
481   return context->csm_timeout;
482 }
483 
484 void
coap_context_set_session_timeout(coap_context_t * context,unsigned int session_timeout)485 coap_context_set_session_timeout(coap_context_t *context,
486                                    unsigned int session_timeout) {
487   context->session_timeout = session_timeout;
488 }
489 
490 unsigned int
coap_context_get_session_timeout(const coap_context_t * context)491 coap_context_get_session_timeout(const coap_context_t *context) {
492   return context->session_timeout;
493 }
494 
coap_context_get_coap_fd(const coap_context_t * context)495 int coap_context_get_coap_fd(const coap_context_t *context) {
496 #ifdef COAP_EPOLL_SUPPORT
497   return context->epfd;
498 #else /* ! COAP_EPOLL_SUPPORT */
499   (void)context;
500   return -1;
501 #endif /* ! COAP_EPOLL_SUPPORT */
502 }
503 
504 coap_context_t *
coap_new_context(const coap_address_t * listen_addr)505 coap_new_context(
506   const coap_address_t *listen_addr) {
507   coap_context_t *c;
508 
509 #ifdef WITH_CONTIKI
510   if (initialized)
511     return NULL;
512 #endif /* WITH_CONTIKI */
513 
514   coap_startup();
515 
516 #ifndef WITH_CONTIKI
517   c = coap_malloc_type(COAP_CONTEXT, sizeof(coap_context_t));
518 #endif /* not WITH_CONTIKI */
519 
520 #ifndef WITH_CONTIKI
521   if (!c) {
522     coap_log(LOG_EMERG, "coap_init: malloc: failed\n");
523     return NULL;
524   }
525 #endif /* not WITH_CONTIKI */
526 #ifdef WITH_CONTIKI
527   coap_resources_init();
528 
529   c = &the_coap_context;
530   initialized = 1;
531 #endif /* WITH_CONTIKI */
532 
533   memset(c, 0, sizeof(coap_context_t));
534 
535 #ifdef COAP_EPOLL_SUPPORT
536   c->epfd = epoll_create1(0);
537   if (c->epfd == -1) {
538     coap_log(LOG_ERR, "coap_new_context: Unable to epoll_create: %s (%d)\n",
539              coap_socket_strerror(),
540              errno);
541     goto onerror;
542   }
543   if (c->epfd != -1) {
544     c->eptimerfd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK);
545     if (c->eptimerfd == -1) {
546       coap_log(LOG_ERR, "coap_new_context: Unable to timerfd_create: %s (%d)\n",
547                coap_socket_strerror(),
548                errno);
549       goto onerror;
550     }
551     else {
552       int ret;
553       struct epoll_event event;
554 
555       /* Needed if running 32bit as ptr is only 32bit */
556       memset(&event, 0, sizeof(event));
557       event.events = EPOLLIN;
558       /* We special case this event by setting to NULL */
559       event.data.ptr = NULL;
560 
561       ret = epoll_ctl(c->epfd, EPOLL_CTL_ADD, c->eptimerfd, &event);
562       if (ret == -1) {
563          coap_log(LOG_ERR,
564                   "%s: epoll_ctl ADD failed: %s (%d)\n",
565                   "coap_new_context",
566                   coap_socket_strerror(), errno);
567         goto onerror;
568       }
569     }
570   }
571 #endif /* COAP_EPOLL_SUPPORT */
572 
573   if (coap_dtls_is_supported()) {
574     c->dtls_context = coap_dtls_new_context(c);
575     if (!c->dtls_context) {
576       coap_log(LOG_EMERG, "coap_init: no DTLS context available\n");
577       coap_free_context(c);
578       return NULL;
579     }
580   }
581 
582   /* set default CSM timeout */
583   c->csm_timeout = 30;
584 
585   if (listen_addr) {
586     coap_endpoint_t *endpoint = coap_new_endpoint(c, listen_addr, COAP_PROTO_UDP);
587     if (endpoint == NULL) {
588       goto onerror;
589     }
590   }
591 
592 #if !defined(WITH_LWIP)
593   c->network_send = coap_network_send;
594   c->network_read = coap_network_read;
595 #endif
596 
597   c->get_client_psk = coap_get_session_client_psk;
598   c->get_server_psk = coap_get_context_server_psk;
599   c->get_server_hint = coap_get_context_server_hint;
600 
601 #ifdef WITH_CONTIKI
602   process_start(&coap_retransmit_process, (char *)c);
603 
604   PROCESS_CONTEXT_BEGIN(&coap_retransmit_process);
605   etimer_set(&c->notify_timer, COAP_RESOURCE_CHECK_TIME * COAP_TICKS_PER_SECOND);
606   /* the retransmit timer must be initialized to some large value */
607   etimer_set(&the_coap_context.retransmit_timer, 0xFFFF);
608   PROCESS_CONTEXT_END(&coap_retransmit_process);
609 #endif /* WITH_CONTIKI */
610 
611   return c;
612 
613 onerror:
614   coap_free_type(COAP_CONTEXT, c);
615   return NULL;
616 }
617 
618 void
coap_set_app_data(coap_context_t * ctx,void * app_data)619 coap_set_app_data(coap_context_t *ctx, void *app_data) {
620   assert(ctx);
621   ctx->app = app_data;
622 }
623 
624 void *
coap_get_app_data(const coap_context_t * ctx)625 coap_get_app_data(const coap_context_t *ctx) {
626   assert(ctx);
627   return ctx->app;
628 }
629 
630 void
coap_free_context(coap_context_t * context)631 coap_free_context(coap_context_t *context) {
632   coap_endpoint_t *ep, *tmp;
633   coap_session_t *sp, *rtmp;
634   coap_cache_entry_t *cp, *ctmp;
635 
636   if (!context)
637     return;
638 
639   /* Removing a resource may cause a CON observe to be sent */
640   coap_delete_all_resources(context);
641 
642   coap_delete_all(context->sendqueue);
643 
644 #ifdef WITH_LWIP
645   context->sendqueue = NULL;
646   coap_retransmittimer_restart(context);
647 #endif
648 
649 #ifndef WITHOUT_ASYNC
650   coap_delete_all_async(context);
651 #endif /* WITHOUT_ASYNC */
652   HASH_ITER(hh, context->cache, cp, ctmp) {
653     coap_delete_cache_entry(context, cp);
654   }
655   if (context->cache_ignore_count) {
656     coap_free(context->cache_ignore_options);
657   }
658 
659   LL_FOREACH_SAFE(context->endpoint, ep, tmp) {
660     coap_free_endpoint(ep);
661   }
662 
663   SESSIONS_ITER_SAFE(context->sessions, sp, rtmp) {
664     coap_session_release(sp);
665   }
666 
667   if (context->dtls_context)
668     coap_dtls_free_context(context->dtls_context);
669 #ifdef COAP_EPOLL_SUPPORT
670   if (context->eptimerfd != -1) {
671     int ret;
672     struct epoll_event event;
673 
674     /* Kernels prior to 2.6.9 expect non NULL event parameter */
675     ret = epoll_ctl(context->epfd, EPOLL_CTL_DEL, context->eptimerfd, &event);
676     if (ret == -1) {
677        coap_log(LOG_ERR,
678                 "%s: epoll_ctl DEL failed: %s (%d)\n",
679                 "coap_free_context",
680                 coap_socket_strerror(), errno);
681     }
682     close(context->eptimerfd);
683     context->eptimerfd = -1;
684   }
685   if (context->epfd != -1) {
686     close(context->epfd);
687     context->epfd = -1;
688   }
689 #endif /* COAP_EPOLL_SUPPORT */
690 
691 #ifndef WITH_CONTIKI
692   coap_free_type(COAP_CONTEXT, context);
693 #else /* WITH_CONTIKI */
694   memset(&the_coap_context, 0, sizeof(coap_context_t));
695   initialized = 0;
696 #endif /* WITH_CONTIKI */
697 }
698 
699 int
coap_option_check_critical(coap_context_t * ctx,coap_pdu_t * pdu,coap_opt_filter_t * unknown)700 coap_option_check_critical(coap_context_t *ctx,
701   coap_pdu_t *pdu,
702   coap_opt_filter_t *unknown) {
703 
704   coap_opt_iterator_t opt_iter;
705   int ok = 1;
706 
707   coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
708 
709   while (coap_option_next(&opt_iter)) {
710 
711     /* The following condition makes use of the fact that
712      * coap_option_getb() returns -1 if type exceeds the bit-vector
713      * filter. As the vector is supposed to be large enough to hold
714      * the largest known option, we know that everything beyond is
715      * bad.
716      */
717     if (opt_iter.number & 0x01) {
718       /* first check the built-in critical options */
719       switch (opt_iter.number) {
720       case COAP_OPTION_IF_MATCH:
721       case COAP_OPTION_URI_HOST:
722       case COAP_OPTION_IF_NONE_MATCH:
723       case COAP_OPTION_URI_PORT:
724       case COAP_OPTION_URI_PATH:
725       case COAP_OPTION_URI_QUERY:
726       case COAP_OPTION_ACCEPT:
727       case COAP_OPTION_PROXY_URI:
728       case COAP_OPTION_PROXY_SCHEME:
729       case COAP_OPTION_BLOCK2:
730       case COAP_OPTION_BLOCK1:
731         break;
732       default:
733         if (coap_option_filter_get(&ctx->known_options, opt_iter.number) <= 0) {
734           coap_log(LOG_DEBUG, "unknown critical option %d\n", opt_iter.number);
735           ok = 0;
736 
737           /* When opt_iter.number is beyond our known option range,
738            * coap_option_filter_set() will return -1 and we are safe to leave
739            * this loop. */
740           if (coap_option_filter_set(unknown, opt_iter.number) == -1) {
741             break;
742           }
743         }
744       }
745     }
746   }
747 
748   return ok;
749 }
750 
751 coap_mid_t
coap_send_ack(coap_session_t * session,const coap_pdu_t * request)752 coap_send_ack(coap_session_t *session, const coap_pdu_t *request) {
753   coap_pdu_t *response;
754   coap_mid_t result = COAP_INVALID_MID;
755 
756   if (request && request->type == COAP_MESSAGE_CON &&
757     COAP_PROTO_NOT_RELIABLE(session->proto)) {
758     response = coap_pdu_init(COAP_MESSAGE_ACK, 0, request->mid, 0);
759     if (response)
760       result = coap_send_internal(session, response);
761   }
762   return result;
763 }
764 
765 ssize_t
coap_session_send_pdu(coap_session_t * session,coap_pdu_t * pdu)766 coap_session_send_pdu(coap_session_t *session, coap_pdu_t *pdu) {
767   ssize_t bytes_written = -1;
768   assert(pdu->hdr_size > 0);
769   switch(session->proto) {
770     case COAP_PROTO_UDP:
771       bytes_written = coap_session_send(session, pdu->token - pdu->hdr_size,
772                                         pdu->used_size + pdu->hdr_size);
773       break;
774     case COAP_PROTO_DTLS:
775       bytes_written = coap_dtls_send(session, pdu->token - pdu->hdr_size,
776                                      pdu->used_size + pdu->hdr_size);
777       break;
778     case COAP_PROTO_TCP:
779 #if !COAP_DISABLE_TCP
780       bytes_written = coap_session_write(session, pdu->token - pdu->hdr_size,
781                                          pdu->used_size + pdu->hdr_size);
782 #endif /* !COAP_DISABLE_TCP */
783       break;
784     case COAP_PROTO_TLS:
785 #if !COAP_DISABLE_TCP
786       bytes_written = coap_tls_write(session, pdu->token - pdu->hdr_size,
787                                      pdu->used_size + pdu->hdr_size);
788 #endif /* !COAP_DISABLE_TCP */
789       break;
790     case COAP_PROTO_NONE:
791     default:
792       break;
793   }
794   coap_show_pdu(LOG_DEBUG, pdu);
795   return bytes_written;
796 }
797 
798 static ssize_t
coap_send_pdu(coap_session_t * session,coap_pdu_t * pdu,coap_queue_t * node)799 coap_send_pdu(coap_session_t *session, coap_pdu_t *pdu, coap_queue_t *node) {
800   ssize_t bytes_written;
801 
802 #ifdef WITH_LWIP
803 
804   coap_socket_t *sock = &session->sock;
805   if (sock->flags == COAP_SOCKET_EMPTY) {
806     assert(session->endpoint != NULL);
807     sock = &session->endpoint->sock;
808   }
809 
810   bytes_written = coap_socket_send_pdu(sock, session, pdu);
811   if (bytes_written >= 0 && pdu->type == COAP_MESSAGE_CON &&
812       COAP_PROTO_NOT_RELIABLE(session->proto))
813     session->con_active++;
814 
815   if (LOG_DEBUG <= coap_get_log_level()) {
816     coap_show_pdu(LOG_DEBUG, pdu);
817   }
818   coap_ticks(&session->last_rx_tx);
819 
820 #else
821 
822   if (session->state == COAP_SESSION_STATE_NONE) {
823     if (session->proto == COAP_PROTO_DTLS && !session->tls) {
824       session->tls = coap_dtls_new_client_session(session);
825       if (session->tls) {
826         session->state = COAP_SESSION_STATE_HANDSHAKE;
827         return coap_session_delay_pdu(session, pdu, node);
828       }
829       coap_handle_event(session->context, COAP_EVENT_DTLS_ERROR, session);
830       return -1;
831 #if !COAP_DISABLE_TCP
832     } else if(COAP_PROTO_RELIABLE(session->proto)) {
833       if (!coap_socket_connect_tcp1(
834         &session->sock, &session->addr_info.local, &session->addr_info.remote,
835         session->proto == COAP_PROTO_TLS ? COAPS_DEFAULT_PORT :
836                                            COAP_DEFAULT_PORT,
837         &session->addr_info.local, &session->addr_info.remote
838       )) {
839         coap_handle_event(session->context, COAP_EVENT_TCP_FAILED, session);
840         return -1;
841       }
842       session->last_ping = 0;
843       session->last_pong = 0;
844       session->csm_tx = 0;
845       coap_ticks( &session->last_rx_tx );
846       if ((session->sock.flags & COAP_SOCKET_WANT_CONNECT) != 0) {
847         session->state = COAP_SESSION_STATE_CONNECTING;
848         return coap_session_delay_pdu(session, pdu, node);
849       }
850       coap_handle_event(session->context, COAP_EVENT_TCP_CONNECTED, session);
851       if (session->proto == COAP_PROTO_TLS) {
852         int connected = 0;
853         session->state = COAP_SESSION_STATE_HANDSHAKE;
854         session->tls = coap_tls_new_client_session(session, &connected);
855         if (session->tls) {
856           if (connected) {
857             coap_handle_event(session->context, COAP_EVENT_DTLS_CONNECTED, session);
858             coap_session_send_csm(session);
859           }
860           return coap_session_delay_pdu(session, pdu, node);
861         }
862         coap_handle_event(session->context, COAP_EVENT_DTLS_ERROR, session);
863         coap_session_disconnected(session, COAP_NACK_TLS_FAILED);
864         return -1;
865       } else {
866         coap_session_send_csm(session);
867       }
868 #endif /* !COAP_DISABLE_TCP */
869     } else {
870       return -1;
871     }
872   }
873 
874   if (pdu->type == COAP_MESSAGE_CON &&
875       (session->sock.flags & COAP_SOCKET_NOT_EMPTY) &&
876       (session->sock.flags & COAP_SOCKET_MULTICAST)) {
877     /* Violates RFC72522 8.1 */
878     coap_log(LOG_ERR, "Multicast requests cannot be Confirmable (RFC7252 8.1)\n");
879     return -1;
880   }
881 
882   if (session->state != COAP_SESSION_STATE_ESTABLISHED ||
883       (pdu->type == COAP_MESSAGE_CON && session->con_active >= COAP_DEFAULT_NSTART)) {
884     return coap_session_delay_pdu(session, pdu, node);
885   }
886 
887   if ((session->sock.flags & COAP_SOCKET_NOT_EMPTY) &&
888     (session->sock.flags & COAP_SOCKET_WANT_WRITE))
889     return coap_session_delay_pdu(session, pdu, node);
890 
891   bytes_written = coap_session_send_pdu(session, pdu);
892   if (bytes_written >= 0 && pdu->type == COAP_MESSAGE_CON &&
893       COAP_PROTO_NOT_RELIABLE(session->proto))
894     session->con_active++;
895 
896 #endif /* WITH_LWIP */
897 
898   return bytes_written;
899 }
900 
901 coap_mid_t
coap_send_error(coap_session_t * session,const coap_pdu_t * request,coap_pdu_code_t code,coap_opt_filter_t * opts)902 coap_send_error(coap_session_t *session,
903   const coap_pdu_t *request,
904   coap_pdu_code_t code,
905   coap_opt_filter_t *opts) {
906   coap_pdu_t *response;
907   coap_mid_t result = COAP_INVALID_MID;
908 
909   assert(request);
910   assert(session);
911 
912   response = coap_new_error_response(request, code, opts);
913   if (response)
914     result = coap_send_internal(session, response);
915 
916   return result;
917 }
918 
919 coap_mid_t
coap_send_message_type(coap_session_t * session,const coap_pdu_t * request,coap_pdu_type_t type)920 coap_send_message_type(coap_session_t *session, const coap_pdu_t *request,
921                        coap_pdu_type_t type) {
922   coap_pdu_t *response;
923   coap_mid_t result = COAP_INVALID_MID;
924 
925   if (request) {
926     response = coap_pdu_init(type, 0, request->mid, 0);
927     if (response)
928       result = coap_send_internal(session, response);
929   }
930   return result;
931 }
932 
933 /**
934  * Calculates the initial timeout based on the session CoAP transmission
935  * parameters 'ack_timeout', 'ack_random_factor', and COAP_TICKS_PER_SECOND.
936  * The calculation requires 'ack_timeout' and 'ack_random_factor' to be in
937  * Qx.FRAC_BITS fixed point notation, whereas the passed parameter @p r
938  * is interpreted as the fractional part of a Q0.MAX_BITS random value.
939  *
940  * @param session session timeout is associated with
941  * @param r  random value as fractional part of a Q0.MAX_BITS fixed point
942  *           value
943  * @return   COAP_TICKS_PER_SECOND * 'ack_timeout' *
944  *           (1 + ('ack_random_factor' - 1) * r)
945  */
946 unsigned int
coap_calc_timeout(coap_session_t * session,unsigned char r)947 coap_calc_timeout(coap_session_t *session, unsigned char r) {
948   unsigned int result;
949 
950   /* The integer 1.0 as a Qx.FRAC_BITS */
951 #define FP1 Q(FRAC_BITS, ((coap_fixed_point_t){1,0}))
952 
953   /* rounds val up and right shifts by frac positions */
954 #define SHR_FP(val,frac) (((val) + (1 << ((frac) - 1))) >> (frac))
955 
956   /* Inner term: multiply ACK_RANDOM_FACTOR by Q0.MAX_BITS[r] and
957    * make the result a rounded Qx.FRAC_BITS */
958   result = SHR_FP((ACK_RANDOM_FACTOR - FP1) * r, MAX_BITS);
959 
960   /* Add 1 to the inner term and multiply with ACK_TIMEOUT, then
961    * make the result a rounded Qx.FRAC_BITS */
962   result = SHR_FP(((result + FP1) * ACK_TIMEOUT), FRAC_BITS);
963 
964   /* Multiply with COAP_TICKS_PER_SECOND to yield system ticks
965    * (yields a Qx.FRAC_BITS) and shift to get an integer */
966   return SHR_FP((COAP_TICKS_PER_SECOND * result), FRAC_BITS);
967 
968 #undef FP1
969 #undef SHR_FP
970 }
971 
972 coap_mid_t
coap_wait_ack(coap_context_t * context,coap_session_t * session,coap_queue_t * node)973 coap_wait_ack(coap_context_t *context, coap_session_t *session,
974               coap_queue_t *node) {
975   coap_tick_t now;
976 
977   node->session = coap_session_reference(session);
978 
979   /* Set timer for pdu retransmission. If this is the first element in
980   * the retransmission queue, the base time is set to the current
981   * time and the retransmission time is node->timeout. If there is
982   * already an entry in the sendqueue, we must check if this node is
983   * to be retransmitted earlier. Therefore, node->timeout is first
984   * normalized to the base time and then inserted into the queue with
985   * an adjusted relative time.
986   */
987   coap_ticks(&now);
988   if (context->sendqueue == NULL) {
989     node->t = node->timeout << node->retransmit_cnt;
990     context->sendqueue_basetime = now;
991   } else {
992     /* make node->t relative to context->sendqueue_basetime */
993     node->t = (now - context->sendqueue_basetime) +
994               (node->timeout << node->retransmit_cnt);
995   }
996 
997   coap_insert_node(&context->sendqueue, node);
998 
999 #ifdef WITH_LWIP
1000   if (node == context->sendqueue) /* don't bother with timer stuff if there are earlier retransmits */
1001     coap_retransmittimer_restart(context);
1002 #endif
1003 
1004 #ifdef WITH_CONTIKI
1005   {                            /* (re-)initialize retransmission timer */
1006     coap_queue_t *nextpdu;
1007 
1008     nextpdu = coap_peek_next(context);
1009     assert(nextpdu);                /* we have just inserted a node */
1010 
1011                                 /* must set timer within the context of the retransmit process */
1012     PROCESS_CONTEXT_BEGIN(&coap_retransmit_process);
1013     etimer_set(&context->retransmit_timer, nextpdu->t);
1014     PROCESS_CONTEXT_END(&coap_retransmit_process);
1015   }
1016 #endif /* WITH_CONTIKI */
1017 
1018   coap_log(LOG_DEBUG, "** %s: mid=0x%x: added to retransmit queue (%ums)\n",
1019     coap_session_str(node->session), node->id,
1020     (unsigned)(node->t * 1000 / COAP_TICKS_PER_SECOND));
1021 
1022 #ifdef COAP_EPOLL_SUPPORT
1023   if (context->eptimerfd != -1) {
1024     coap_ticks(&now);
1025     if (context->next_timeout == 0 ||
1026         context->next_timeout > now + (node->t * 1000 / COAP_TICKS_PER_SECOND)) {
1027       struct itimerspec new_value;
1028       int ret;
1029 
1030       context->next_timeout = now + (node->t * 1000 / COAP_TICKS_PER_SECOND);
1031       memset(&new_value, 0, sizeof(new_value));
1032       coap_tick_t rem_timeout = (node->t * 1000 / COAP_TICKS_PER_SECOND);
1033       /* Need to trigger an event on context->epfd in the future */
1034       new_value.it_value.tv_sec = rem_timeout / 1000;
1035       new_value.it_value.tv_nsec = (rem_timeout % 1000) * 1000000;
1036       ret = timerfd_settime(context->eptimerfd, 0, &new_value, NULL);
1037       if (ret == -1) {
1038         coap_log(LOG_ERR,
1039                   "%s: timerfd_settime failed: %s (%d)\n",
1040                   "coap_wait_ack",
1041                   coap_socket_strerror(), errno);
1042       }
1043     }
1044   }
1045 #endif /* COAP_EPOLL_SUPPORT */
1046 
1047   return node->id;
1048 }
1049 
1050 COAP_STATIC_INLINE int
token_match(const uint8_t * a,size_t alen,const uint8_t * b,size_t blen)1051 token_match(const uint8_t *a, size_t alen,
1052   const uint8_t *b, size_t blen) {
1053   return alen == blen && (alen == 0 || memcmp(a, b, alen) == 0);
1054 }
1055 
1056 coap_mid_t
coap_send(coap_session_t * session,coap_pdu_t * pdu)1057 coap_send(coap_session_t *session, coap_pdu_t *pdu) {
1058   coap_mid_t mid = COAP_INVALID_MID;
1059   coap_lg_crcv_t *lg_crcv = NULL;
1060   coap_opt_iterator_t opt_iter;
1061   int observe_action = -1;
1062   int have_block1 = 0;
1063   coap_opt_t *opt;
1064 
1065   assert(pdu);
1066 
1067   if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
1068     return coap_send_internal(session, pdu);
1069   }
1070 
1071   if (COAP_PDU_IS_REQUEST(pdu)) {
1072     coap_block_t block;
1073 
1074     opt = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
1075 
1076     if (opt) {
1077       observe_action = coap_decode_var_bytes(coap_opt_value(opt),
1078                                                      coap_opt_length(opt));
1079     }
1080 
1081     if (coap_get_block(pdu, COAP_OPTION_BLOCK1, &block) && block.m == 1)
1082       have_block1 = 1;
1083   }
1084 
1085   /*
1086    * If type is CON and protocol is not reliable, there is no need to set up
1087    * lg_crcv here as it can be built up based on sent PDU if there is a
1088    * Block2 in the response.  However, still need it for observe and block1.
1089    */
1090   if (observe_action != -1 || have_block1 ||
1091       ((pdu->type == COAP_MESSAGE_NON || COAP_PROTO_RELIABLE(session->proto)) &&
1092        COAP_PDU_IS_REQUEST(pdu) && pdu->code != COAP_REQUEST_CODE_DELETE)) {
1093     /* See if this token is already in use for large body responses */
1094     LL_FOREACH(session->lg_crcv, lg_crcv) {
1095       if (token_match(pdu->token, pdu->token_length,
1096                       lg_crcv->app_token->s, lg_crcv->app_token->length)) {
1097 
1098         if (observe_action == COAP_OBSERVE_CANCEL) {
1099           /* Need to update token to server's version */
1100           coap_update_token(pdu, lg_crcv->base_token_length,
1101                             lg_crcv->base_token);
1102           memcpy(lg_crcv->token, lg_crcv->base_token,
1103                  lg_crcv->base_token_length);
1104           lg_crcv->token_length = lg_crcv->base_token_length;
1105           lg_crcv->initial = 1;
1106           lg_crcv->observe_set = 0;
1107           /* de-reference lg_crcv as potentially linking in later */
1108           LL_DELETE(session->lg_crcv, lg_crcv);
1109           goto send_it;
1110         }
1111 
1112         /* Need to terminate and clean up previous response setup */
1113         LL_DELETE(session->lg_crcv, lg_crcv);
1114         coap_block_delete_lg_crcv(session, lg_crcv);
1115         break;
1116       }
1117     }
1118 
1119     lg_crcv = coap_block_new_lg_crcv(session, pdu);
1120     if (lg_crcv == NULL)
1121       return COAP_INVALID_MID;
1122     if (have_block1 && session->lg_xmit) {
1123       coap_lg_xmit_t *lg_xmit;
1124 
1125       LL_FOREACH(session->lg_xmit, lg_xmit) {
1126         if (COAP_PDU_IS_REQUEST(&lg_xmit->pdu) &&
1127             lg_xmit->b.b1.app_token &&
1128             token_match(pdu->token, pdu->token_length,
1129                         lg_xmit->b.b1.app_token->s,
1130                         lg_xmit->b.b1.app_token->length)) {
1131           /* Need to update the token as set up in the session->lg_xmit */
1132           coap_update_token(pdu, session->lg_xmit->b.b1.token_length,
1133                             session->lg_xmit->b.b1.token);
1134           break;
1135         }
1136       }
1137     }
1138   }
1139 
1140 send_it:
1141   mid = coap_send_internal(session, pdu);
1142   if (lg_crcv) {
1143     if (mid != COAP_INVALID_MID) {
1144       LL_PREPEND(session->lg_crcv, lg_crcv);
1145     }
1146     else {
1147       coap_block_delete_lg_crcv(session, lg_crcv);
1148     }
1149   }
1150   return mid;
1151 }
1152 
1153 coap_mid_t
coap_send_internal(coap_session_t * session,coap_pdu_t * pdu)1154 coap_send_internal(coap_session_t *session, coap_pdu_t *pdu) {
1155   uint8_t r;
1156   ssize_t bytes_written;
1157   coap_opt_iterator_t opt_iter;
1158 
1159   if (pdu->code == COAP_RESPONSE_CODE(508)) {
1160     /*
1161      * Need to prepend our IP identifier to the data as per
1162      * https://www.rfc-editor.org/rfc/rfc8768.html#section-4
1163      */
1164     char addr_str[INET6_ADDRSTRLEN + 8 + 1];
1165     coap_opt_t *opt;
1166     size_t hop_limit;
1167 
1168     addr_str[sizeof(addr_str)-1] = '\000';
1169     if (coap_print_addr(&session->addr_info.local, (uint8_t*)addr_str,
1170                             sizeof(addr_str) - 1)) {
1171       char *cp;
1172       size_t len;
1173 
1174       if (addr_str[0] == '[') {
1175         cp = strchr(addr_str, ']');
1176         if (cp) *cp = '\000';
1177         if (memcmp(&addr_str[1], "::ffff:", 7) == 0) {
1178           /* IPv4 embedded into IPv6 */
1179           cp = &addr_str[8];
1180         }
1181         else {
1182           cp = &addr_str[1];
1183         }
1184       }
1185       else {
1186         cp = strchr(addr_str, ':');
1187         if (cp) *cp = '\000';
1188         cp = addr_str;
1189       }
1190       len = strlen(cp);
1191 
1192       /* See if Hop Limit option is being used in return path */
1193       opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
1194       if (opt) {
1195         uint8_t buf[4];
1196 
1197         hop_limit =
1198           coap_decode_var_bytes (coap_opt_value (opt), coap_opt_length (opt));
1199         if (hop_limit == 1) {
1200           coap_log(LOG_WARNING, "Proxy loop detected '%s'\n",
1201                    (char*)pdu->data);
1202           coap_delete_pdu(pdu);
1203           return (coap_mid_t)COAP_DROPPED_RESPONSE;
1204         }
1205         else if (hop_limit < 1 || hop_limit > 255) {
1206           /* Something is bad - need to drop this pdu (TODO or delete option) */
1207           coap_log(LOG_WARNING, "Proxy return has bad hop limit count '%zu'\n",
1208                                  hop_limit);
1209           coap_delete_pdu(pdu);
1210           return (coap_mid_t)COAP_DROPPED_RESPONSE;
1211         }
1212         hop_limit--;
1213         coap_update_option(pdu, COAP_OPTION_HOP_LIMIT,
1214                            coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
1215                            buf);
1216       }
1217 
1218       /* Need to check that we are not seeing this proxy in the return loop */
1219       if (pdu->data && opt == NULL) {
1220         if (pdu->used_size + 1 <= pdu->max_size) {
1221           char *a_match;
1222           size_t data_len = pdu->used_size - (pdu->data - pdu->token);
1223           pdu->data[data_len] = '\000';
1224           a_match = strstr((char*)pdu->data, cp);
1225           if (a_match && (a_match == (char*)pdu->data || a_match[-1] == ' ') &&
1226               ((size_t)(a_match - (char*)pdu->data + len) == data_len ||
1227                a_match[len] == ' ')) {
1228             coap_log(LOG_WARNING, "Proxy loop detected '%s'\n",
1229                      (char*)pdu->data);
1230             coap_delete_pdu(pdu);
1231             return (coap_mid_t)COAP_DROPPED_RESPONSE;
1232           }
1233         }
1234       }
1235       if (pdu->used_size + len + 1 <= pdu->max_size) {
1236         size_t old_size = pdu->used_size;
1237         if (coap_pdu_resize(pdu, pdu->used_size + len + 1)) {
1238           if (pdu->data == NULL) {
1239             /*
1240              * Set Hop Limit to max for return path.  If this libcoap is in
1241              * a proxy loop path, it will always decrement hop limit in code
1242              * above and hence timeout / drop the response as appropriate
1243              */
1244             hop_limit = 255;
1245             coap_insert_option(pdu, COAP_OPTION_HOP_LIMIT, 1,
1246                                (uint8_t *)&hop_limit);
1247             coap_add_data(pdu, len, (uint8_t*)cp);
1248           }
1249           else {
1250             /* prepend with space separator, leaving hop limit "as is" */
1251             memmove(pdu->data + len + 1, pdu->data,
1252                     old_size - (pdu->data - pdu->token));
1253             memcpy(pdu->data, cp, len);
1254             pdu->data[len] = ' ';
1255             pdu->used_size += len + 1;
1256           }
1257         }
1258       }
1259     }
1260   }
1261 
1262   if (!coap_pdu_encode_header(pdu, session->proto)) {
1263     goto error;
1264   }
1265 
1266 #if !COAP_DISABLE_TCP
1267   if (COAP_PROTO_RELIABLE(session->proto) &&
1268       session->state == COAP_SESSION_STATE_ESTABLISHED &&
1269       !session->csm_block_supported) {
1270     /*
1271      * Need to check that this instance is not sending any block options as the
1272      * remote end via CSM has not informed us that there is support
1273      * https://tools.ietf.org/html/rfc8323#section-5.3.2
1274      * Note that this also includes BERT which is application specific.
1275      */
1276     if (coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter) != NULL) {
1277       coap_log(LOG_DEBUG,
1278                "Remote end did not indicate CSM support for BLOCK1 enabled\n");
1279     }
1280     if (coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter) != NULL) {
1281       coap_log(LOG_DEBUG,
1282                "Remote end did not indicate CSM support for BLOCK2 enabled\n");
1283     }
1284   }
1285 #endif /* !COAP_DISABLE_TCP */
1286 
1287   bytes_written = coap_send_pdu( session, pdu, NULL );
1288 
1289   if (bytes_written == COAP_PDU_DELAYED) {
1290     /* do not free pdu as it is stored with session for later use */
1291     return pdu->mid;
1292   }
1293 
1294   if (bytes_written < 0) {
1295     coap_delete_pdu(pdu);
1296     return (coap_mid_t)bytes_written;
1297   }
1298 
1299 #if !COAP_DISABLE_TCP
1300   if (COAP_PROTO_RELIABLE(session->proto) &&
1301       (size_t)bytes_written < pdu->used_size + pdu->hdr_size) {
1302     if (coap_session_delay_pdu(session, pdu, NULL) == COAP_PDU_DELAYED) {
1303       session->partial_write = (size_t)bytes_written;
1304       /* do not free pdu as it is stored with session for later use */
1305       return pdu->mid;
1306     } else {
1307       goto error;
1308     }
1309   }
1310 #endif /* !COAP_DISABLE_TCP */
1311 
1312   if (pdu->type != COAP_MESSAGE_CON
1313       || COAP_PROTO_RELIABLE(session->proto)) {
1314     coap_mid_t id = pdu->mid;
1315     coap_delete_pdu(pdu);
1316     return id;
1317   }
1318 
1319   coap_queue_t *node = coap_new_node();
1320   if (!node) {
1321     coap_log(LOG_DEBUG, "coap_wait_ack: insufficient memory\n");
1322     goto error;
1323   }
1324 
1325   node->id = pdu->mid;
1326   node->pdu = pdu;
1327   coap_prng(&r, sizeof(r));
1328   /* add timeout in range [ACK_TIMEOUT...ACK_TIMEOUT * ACK_RANDOM_FACTOR] */
1329   node->timeout = coap_calc_timeout(session, r);
1330   return coap_wait_ack(session->context, session, node);
1331  error:
1332   coap_delete_pdu(pdu);
1333   return COAP_INVALID_MID;
1334 }
1335 
1336 coap_mid_t
coap_retransmit(coap_context_t * context,coap_queue_t * node)1337 coap_retransmit(coap_context_t *context, coap_queue_t *node) {
1338   if (!context || !node)
1339     return COAP_INVALID_MID;
1340 
1341   /* re-initialize timeout when maximum number of retransmissions are not reached yet */
1342   if (node->retransmit_cnt < node->session->max_retransmit) {
1343     ssize_t bytes_written;
1344     coap_tick_t now;
1345 
1346     node->retransmit_cnt++;
1347     coap_ticks(&now);
1348     if (context->sendqueue == NULL) {
1349       node->t = node->timeout << node->retransmit_cnt;
1350       context->sendqueue_basetime = now;
1351     } else {
1352       /* make node->t relative to context->sendqueue_basetime */
1353       node->t = (now - context->sendqueue_basetime) + (node->timeout << node->retransmit_cnt);
1354     }
1355     coap_insert_node(&context->sendqueue, node);
1356 #ifdef WITH_LWIP
1357     if (node == context->sendqueue) /* don't bother with timer stuff if there are earlier retransmits */
1358       coap_retransmittimer_restart(context);
1359 #endif
1360 
1361     coap_log(LOG_DEBUG, "** %s: mid=0x%x: retransmission #%d\n",
1362              coap_session_str(node->session), node->id, node->retransmit_cnt);
1363 
1364     if (node->session->con_active)
1365       node->session->con_active--;
1366     bytes_written = coap_send_pdu(node->session, node->pdu, node);
1367 
1368     if (bytes_written == COAP_PDU_DELAYED) {
1369       /* PDU was not retransmitted immediately because a new handshake is
1370          in progress. node was moved to the send queue of the session. */
1371       return node->id;
1372     }
1373 
1374     if (bytes_written < 0)
1375       return (int)bytes_written;
1376 
1377     return node->id;
1378   }
1379 
1380   /* no more retransmissions, remove node from system */
1381 
1382 #ifndef WITH_CONTIKI
1383   coap_log(LOG_DEBUG, "** %s: mid=0x%x: give up after %d attempts\n",
1384            coap_session_str(node->session), node->id, node->retransmit_cnt);
1385 #endif
1386 
1387   /* Check if subscriptions exist that should be canceled after
1388      COAP_MAX_NOTIFY_FAILURES */
1389   if (node->pdu->code >= 64) {
1390     coap_binary_t token = { 0, NULL };
1391 
1392     token.length = node->pdu->token_length;
1393     token.s = node->pdu->token;
1394 
1395     coap_handle_failed_notify(context, node->session, &token);
1396   }
1397   if (node->session->con_active) {
1398     node->session->con_active--;
1399     if (node->session->state == COAP_SESSION_STATE_ESTABLISHED) {
1400       /*
1401        * As there may be another CON in a different queue entry on the same
1402        * session that needs to be immediately released,
1403        * coap_session_connected() is called.
1404        * However, there is the possibility coap_wait_ack() may be called for
1405        * this node (queue) and re-added to context->sendqueue.
1406        * coap_delete_node(node) called shortly will handle this and remove it.
1407        */
1408       coap_session_connected(node->session);
1409     }
1410  }
1411 
1412   /* And finally delete the node */
1413   if (node->pdu->type == COAP_MESSAGE_CON && context->nack_handler)
1414     context->nack_handler(node->session, node->pdu, COAP_NACK_TOO_MANY_RETRIES, node->id);
1415   coap_delete_node(node);
1416   return COAP_INVALID_MID;
1417 }
1418 
1419 #ifdef WITH_LWIP
1420 /* WITH_LWIP, this is handled by coap_recv in a different way */
1421 void
coap_io_do_io(coap_context_t * ctx,coap_tick_t now)1422 coap_io_do_io(coap_context_t *ctx, coap_tick_t now) {
1423   return;
1424 }
1425 #else /* WITH_LWIP */
1426 
1427 static int
coap_handle_dgram_for_proto(coap_context_t * ctx,coap_session_t * session,coap_packet_t * packet)1428 coap_handle_dgram_for_proto(coap_context_t *ctx, coap_session_t *session, coap_packet_t *packet) {
1429   uint8_t *data;
1430   size_t data_len;
1431   int result = -1;
1432 
1433   coap_packet_get_memmapped(packet, &data, &data_len);
1434 
1435   if (session->proto == COAP_PROTO_DTLS) {
1436     if (session->type == COAP_SESSION_TYPE_HELLO)
1437       result = coap_dtls_hello(session, data, data_len);
1438     else if (session->tls)
1439       result = coap_dtls_receive(session, data, data_len);
1440   } else if (session->proto == COAP_PROTO_UDP) {
1441     result = coap_handle_dgram(ctx, session, data, data_len);
1442   }
1443   return result;
1444 }
1445 
1446 static void
coap_connect_session(coap_context_t * ctx,coap_session_t * session,coap_tick_t now)1447 coap_connect_session(coap_context_t *ctx,
1448                           coap_session_t *session,
1449                           coap_tick_t now) {
1450   (void)ctx;
1451 #if COAP_DISABLE_TCP
1452   (void)session;
1453   (void)now;
1454 #else /* !COAP_DISABLE_TCP */
1455   if (coap_socket_connect_tcp2(&session->sock, &session->addr_info.local,
1456                                &session->addr_info.remote)) {
1457     session->last_rx_tx = now;
1458     coap_handle_event(session->context, COAP_EVENT_TCP_CONNECTED, session);
1459     if (session->proto == COAP_PROTO_TCP) {
1460       coap_session_send_csm(session);
1461     } else if (session->proto == COAP_PROTO_TLS) {
1462       int connected = 0;
1463       session->state = COAP_SESSION_STATE_HANDSHAKE;
1464       session->tls = coap_tls_new_client_session(session, &connected);
1465       if (session->tls) {
1466         if (connected) {
1467           coap_handle_event(session->context, COAP_EVENT_DTLS_CONNECTED,
1468                             session);
1469           coap_session_send_csm(session);
1470         }
1471       } else {
1472         coap_handle_event(session->context, COAP_EVENT_DTLS_ERROR, session);
1473         coap_session_disconnected(session, COAP_NACK_TLS_FAILED);
1474       }
1475     }
1476   } else {
1477     coap_handle_event(session->context, COAP_EVENT_TCP_FAILED, session);
1478     coap_session_disconnected(session, COAP_NACK_NOT_DELIVERABLE);
1479   }
1480 #endif /* !COAP_DISABLE_TCP */
1481 }
1482 
1483 static void
coap_write_session(coap_context_t * ctx,coap_session_t * session,coap_tick_t now)1484 coap_write_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now) {
1485   (void)ctx;
1486   assert(session->sock.flags & COAP_SOCKET_CONNECTED);
1487 
1488   while (session->delayqueue) {
1489     ssize_t bytes_written = -1;
1490     coap_queue_t *q = session->delayqueue;
1491     coap_log(LOG_DEBUG, "** %s: mid=0x%x: transmitted after delay\n",
1492              coap_session_str(session), (int)q->pdu->mid);
1493     assert(session->partial_write < q->pdu->used_size + q->pdu->hdr_size);
1494     switch (session->proto) {
1495       case COAP_PROTO_TCP:
1496 #if !COAP_DISABLE_TCP
1497         bytes_written = coap_session_write(
1498           session,
1499           q->pdu->token - q->pdu->hdr_size - session->partial_write,
1500           q->pdu->used_size + q->pdu->hdr_size - session->partial_write
1501         );
1502 #endif /* !COAP_DISABLE_TCP */
1503         break;
1504       case COAP_PROTO_TLS:
1505 #if !COAP_DISABLE_TCP
1506         bytes_written = coap_tls_write(
1507           session,
1508           q->pdu->token - q->pdu->hdr_size - session->partial_write,
1509           q->pdu->used_size + q->pdu->hdr_size - session->partial_write
1510         );
1511 #endif /* !COAP_DISABLE_TCP */
1512         break;
1513       case COAP_PROTO_NONE:
1514       case COAP_PROTO_UDP:
1515       case COAP_PROTO_DTLS:
1516       default:
1517         bytes_written = -1;
1518         break;
1519     }
1520     if (bytes_written > 0)
1521       session->last_rx_tx = now;
1522     if (bytes_written <= 0 || (size_t)bytes_written < q->pdu->used_size + q->pdu->hdr_size - session->partial_write) {
1523       if (bytes_written > 0)
1524         session->partial_write += (size_t)bytes_written;
1525       break;
1526     }
1527     session->delayqueue = q->next;
1528     session->partial_write = 0;
1529     coap_delete_node(q);
1530   }
1531 }
1532 
1533 static void
coap_read_session(coap_context_t * ctx,coap_session_t * session,coap_tick_t now)1534 coap_read_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now) {
1535 #if COAP_CONSTRAINED_STACK
1536   static coap_mutex_t s_static_mutex = COAP_MUTEX_INITIALIZER;
1537   static coap_packet_t s_packet;
1538 #else /* ! COAP_CONSTRAINED_STACK */
1539   coap_packet_t s_packet;
1540 #endif /* ! COAP_CONSTRAINED_STACK */
1541   coap_packet_t *packet = &s_packet;
1542 
1543 #if COAP_CONSTRAINED_STACK
1544   coap_mutex_lock(&s_static_mutex);
1545 #endif /* COAP_CONSTRAINED_STACK */
1546 
1547 #ifdef COAP_SUPPORT_SOCKET_BROADCAST
1548   assert(session->sock.flags & (COAP_SOCKET_CONNECTED | COAP_SOCKET_MULTICAST | COAP_SOCKET_BROADCAST));
1549 #else
1550   assert(session->sock.flags & (COAP_SOCKET_CONNECTED | COAP_SOCKET_MULTICAST));
1551 #endif
1552 
1553   if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
1554     ssize_t bytes_read;
1555     memcpy(&packet->addr_info, &session->addr_info, sizeof(packet->addr_info));
1556     bytes_read = ctx->network_read(&session->sock, packet);
1557 
1558     if (bytes_read < 0) {
1559       if (bytes_read == -2)
1560         /* Reset the session back to startup defaults */
1561         coap_session_disconnected(session, COAP_NACK_ICMP_ISSUE);
1562       else
1563         coap_log(LOG_WARNING, "*  %s: read error\n",
1564                  coap_session_str(session));
1565     } else if (bytes_read > 0) {
1566       session->last_rx_tx = now;
1567       memcpy(&session->addr_info, &packet->addr_info,
1568              sizeof(session->addr_info));
1569       coap_log(LOG_DEBUG, "*  %s: received %zd bytes\n",
1570                coap_session_str(session), bytes_read);
1571       coap_handle_dgram_for_proto(ctx, session, packet);
1572     }
1573 #if !COAP_DISABLE_TCP
1574   } else {
1575     ssize_t bytes_read = 0;
1576     const uint8_t *p;
1577     int retry;
1578     /* adjust for LWIP */
1579     uint8_t *buf = packet->payload;
1580     size_t buf_len = sizeof(packet->payload);
1581 
1582     do {
1583       if (session->proto == COAP_PROTO_TCP)
1584         bytes_read = coap_socket_read(&session->sock, buf, buf_len);
1585       else if (session->proto == COAP_PROTO_TLS)
1586         bytes_read = coap_tls_read(session, buf, buf_len);
1587       if (bytes_read > 0) {
1588         coap_log(LOG_DEBUG, "*  %s: received %zd bytes\n",
1589                  coap_session_str(session), bytes_read);
1590         session->last_rx_tx = now;
1591       }
1592       p = buf;
1593       retry = bytes_read == (ssize_t)buf_len;
1594       while (bytes_read > 0) {
1595         if (session->partial_pdu) {
1596           size_t len = session->partial_pdu->used_size
1597                      + session->partial_pdu->hdr_size
1598                      - session->partial_read;
1599           size_t n = min(len, (size_t)bytes_read);
1600           memcpy(session->partial_pdu->token - session->partial_pdu->hdr_size
1601                  + session->partial_read, p, n);
1602           p += n;
1603           bytes_read -= n;
1604           if (n == len) {
1605             if (coap_pdu_parse_header(session->partial_pdu, session->proto)
1606               && coap_pdu_parse_opt(session->partial_pdu)) {
1607               coap_dispatch(ctx, session, session->partial_pdu);
1608             }
1609             coap_delete_pdu(session->partial_pdu);
1610             session->partial_pdu = NULL;
1611             session->partial_read = 0;
1612           } else {
1613             session->partial_read += n;
1614           }
1615         } else if (session->partial_read > 0) {
1616           size_t hdr_size = coap_pdu_parse_header_size(session->proto,
1617             session->read_header);
1618           size_t len = hdr_size - session->partial_read;
1619           size_t n = min(len, (size_t)bytes_read);
1620           memcpy(session->read_header + session->partial_read, p, n);
1621           p += n;
1622           bytes_read -= n;
1623           if (n == len) {
1624             size_t size = coap_pdu_parse_size(session->proto, session->read_header,
1625               hdr_size);
1626             if (size > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
1627               coap_log(LOG_WARNING,
1628                        "** %s: incoming PDU length too large (%zu > %lu)\n",
1629                        coap_session_str(session),
1630                        size, COAP_DEFAULT_MAX_PDU_RX_SIZE);
1631               bytes_read = -1;
1632               break;
1633             }
1634             /* Need max space incase PDU is updated with updated token etc. */
1635             session->partial_pdu = coap_pdu_init(0, 0, 0,
1636                                            coap_session_max_pdu_size(session));
1637             if (session->partial_pdu == NULL) {
1638               bytes_read = -1;
1639               break;
1640             }
1641             if (session->partial_pdu->alloc_size < size && !coap_pdu_resize(session->partial_pdu, size)) {
1642               bytes_read = -1;
1643               break;
1644             }
1645             session->partial_pdu->hdr_size = (uint8_t)hdr_size;
1646             session->partial_pdu->used_size = size;
1647             memcpy(session->partial_pdu->token - hdr_size, session->read_header, hdr_size);
1648             session->partial_read = hdr_size;
1649             if (size == 0) {
1650               if (coap_pdu_parse_header(session->partial_pdu, session->proto)) {
1651                 coap_dispatch(ctx, session, session->partial_pdu);
1652               }
1653               coap_delete_pdu(session->partial_pdu);
1654               session->partial_pdu = NULL;
1655               session->partial_read = 0;
1656             }
1657           } else {
1658             session->partial_read += bytes_read;
1659           }
1660         } else {
1661           session->read_header[0] = *p++;
1662           bytes_read -= 1;
1663           if (!coap_pdu_parse_header_size(session->proto,
1664                                           session->read_header)) {
1665             bytes_read = -1;
1666             break;
1667           }
1668           session->partial_read = 1;
1669         }
1670       }
1671     } while (bytes_read == 0 && retry);
1672     if (bytes_read < 0)
1673       coap_session_disconnected(session, COAP_NACK_NOT_DELIVERABLE);
1674 #endif /* !COAP_DISABLE_TCP */
1675   }
1676 #if COAP_CONSTRAINED_STACK
1677   coap_mutex_unlock(&s_static_mutex);
1678 #endif /* COAP_CONSTRAINED_STACK */
1679 }
1680 
1681 static int
coap_read_endpoint(coap_context_t * ctx,coap_endpoint_t * endpoint,coap_tick_t now)1682 coap_read_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
1683   ssize_t bytes_read = -1;
1684   int result = -1;                /* the value to be returned */
1685 #if COAP_CONSTRAINED_STACK
1686   static coap_mutex_t e_static_mutex = COAP_MUTEX_INITIALIZER;
1687   static coap_packet_t e_packet;
1688 #else /* ! COAP_CONSTRAINED_STACK */
1689   coap_packet_t e_packet;
1690 #endif /* ! COAP_CONSTRAINED_STACK */
1691   coap_packet_t *packet = &e_packet;
1692 
1693   assert(COAP_PROTO_NOT_RELIABLE(endpoint->proto));
1694   assert(endpoint->sock.flags & COAP_SOCKET_BOUND);
1695 
1696 #if COAP_CONSTRAINED_STACK
1697   coap_mutex_lock(&e_static_mutex);
1698 #endif /* COAP_CONSTRAINED_STACK */
1699 
1700   /* Need to do this as there may be holes in addr_info */
1701   memset(&packet->addr_info, 0, sizeof(packet->addr_info));
1702   coap_address_init(&packet->addr_info.remote);
1703   coap_address_copy(&packet->addr_info.local, &endpoint->bind_addr);
1704   bytes_read = ctx->network_read(&endpoint->sock, packet);
1705 
1706   if (bytes_read < 0) {
1707     coap_log(LOG_WARNING, "*  %s: read failed\n", coap_endpoint_str(endpoint));
1708   } else if (bytes_read > 0) {
1709     coap_session_t *session = coap_endpoint_get_session(endpoint, packet, now);
1710     if (session) {
1711       coap_log(LOG_DEBUG, "*  %s: received %zd bytes\n",
1712                coap_session_str(session), bytes_read);
1713       result = coap_handle_dgram_for_proto(ctx, session, packet);
1714       if (endpoint->proto == COAP_PROTO_DTLS && session->type == COAP_SESSION_TYPE_HELLO && result == 1)
1715         coap_session_new_dtls_session(session, now);
1716     }
1717   }
1718 #if COAP_CONSTRAINED_STACK
1719   coap_mutex_unlock(&e_static_mutex);
1720 #endif /* COAP_CONSTRAINED_STACK */
1721   return result;
1722 }
1723 
1724 static int
coap_write_endpoint(coap_context_t * ctx,coap_endpoint_t * endpoint,coap_tick_t now)1725 coap_write_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
1726   (void)ctx;
1727   (void)endpoint;
1728   (void)now;
1729   return 0;
1730 }
1731 
1732 static int
coap_accept_endpoint(coap_context_t * ctx,coap_endpoint_t * endpoint,coap_tick_t now)1733 coap_accept_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint,
1734   coap_tick_t now) {
1735   coap_session_t *session = coap_new_server_session(ctx, endpoint);
1736   if (session)
1737     session->last_rx_tx = now;
1738   return session != NULL;
1739 }
1740 
1741 void
coap_io_do_io(coap_context_t * ctx,coap_tick_t now)1742 coap_io_do_io(coap_context_t *ctx, coap_tick_t now) {
1743 #ifdef COAP_EPOLL_SUPPORT
1744   (void)ctx;
1745   (void)now;
1746    coap_log(LOG_EMERG,
1747             "coap_io_do_io() requires libcoap not compiled for using epoll\n");
1748 #else /* ! COAP_EPOLL_SUPPORT */
1749   coap_endpoint_t *ep, *tmp;
1750   coap_session_t *s, *rtmp;
1751   LL_FOREACH_SAFE(ctx->endpoint, ep, tmp) {
1752     if ((ep->sock.flags & COAP_SOCKET_CAN_READ) != 0)
1753       coap_read_endpoint(ctx, ep, now);
1754     if ((ep->sock.flags & COAP_SOCKET_CAN_WRITE) != 0)
1755       coap_write_endpoint(ctx, ep, now);
1756     if ((ep->sock.flags & COAP_SOCKET_CAN_ACCEPT) != 0)
1757       coap_accept_endpoint(ctx, ep, now);
1758     SESSIONS_ITER_SAFE(ep->sessions, s, rtmp) {
1759       /* Make sure the session object is not deleted in one of the callbacks  */
1760       coap_session_reference(s);
1761       if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0) {
1762         coap_read_session(ctx, s, now);
1763       }
1764       if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0) {
1765         coap_write_session(ctx, s, now);
1766       }
1767       coap_session_release(s);
1768     }
1769   }
1770 
1771   SESSIONS_ITER_SAFE(ctx->sessions, s, rtmp) {
1772     /* Make sure the session object is not deleted in one of the callbacks  */
1773     coap_session_reference(s);
1774     if ((s->sock.flags & COAP_SOCKET_CAN_CONNECT) != 0) {
1775       coap_connect_session(ctx, s, now);
1776     }
1777     if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0) {
1778       coap_read_session(ctx, s, now);
1779     }
1780     if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0) {
1781       coap_write_session(ctx, s, now);
1782     }
1783     coap_session_release(s);
1784   }
1785 #endif /* ! COAP_EPOLL_SUPPORT */
1786 }
1787 
1788 /*
1789  * While this code in part replicates coap_io_do_io(), doing the functions
1790  * directly saves having to iterate through the endpoints / sessions.
1791  */
1792 void
coap_io_do_epoll(coap_context_t * ctx,struct epoll_event * events,size_t nevents)1793 coap_io_do_epoll(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
1794 #ifndef COAP_EPOLL_SUPPORT
1795   (void)ctx;
1796   (void)events;
1797   (void)nevents;
1798    coap_log(LOG_EMERG,
1799             "coap_io_do_epoll() requires libcoap compiled for using epoll\n");
1800 #else /* COAP_EPOLL_SUPPORT */
1801   coap_tick_t now;
1802   size_t j;
1803 
1804   coap_ticks(&now);
1805   for(j = 0; j < nevents; j++) {
1806     coap_socket_t *sock = (coap_socket_t*)events[j].data.ptr;
1807 
1808     /* Ignore 'timer trigger' ptr  which is NULL */
1809     if (sock) {
1810       if (sock->endpoint) {
1811         coap_endpoint_t *endpoint = sock->endpoint;
1812         if ((sock->flags & COAP_SOCKET_WANT_READ) &&
1813             (events[j].events & EPOLLIN)) {
1814           sock->flags |= COAP_SOCKET_CAN_READ;
1815           coap_read_endpoint(endpoint->context, endpoint, now);
1816         }
1817 
1818         if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
1819             (events[j].events & EPOLLOUT)) {
1820           /*
1821            * Need to update this to EPOLLIN as EPOLLOUT will normally always
1822            * be true causing epoll_wait to return early
1823            */
1824           coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
1825           sock->flags |= COAP_SOCKET_CAN_WRITE;
1826           coap_write_endpoint(endpoint->context, endpoint, now);
1827         }
1828 
1829         if ((sock->flags & COAP_SOCKET_WANT_ACCEPT) &&
1830             (events[j].events & EPOLLIN)) {
1831           sock->flags |= COAP_SOCKET_CAN_ACCEPT;
1832           coap_accept_endpoint(endpoint->context, endpoint, now);
1833         }
1834 
1835       }
1836       else if (sock->session) {
1837         coap_session_t *session = sock->session;
1838 
1839         /* Make sure the session object is not deleted
1840            in one of the callbacks  */
1841         coap_session_reference(session);
1842         if ((sock->flags & COAP_SOCKET_WANT_CONNECT) &&
1843             (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
1844           sock->flags |= COAP_SOCKET_CAN_CONNECT;
1845           coap_connect_session(session->context, session, now);
1846           if (!(sock->flags & COAP_SOCKET_WANT_WRITE)) {
1847             coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
1848           }
1849         }
1850 
1851         if ((sock->flags & COAP_SOCKET_WANT_READ) &&
1852             (events[j].events & (EPOLLIN|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
1853           sock->flags |= COAP_SOCKET_CAN_READ;
1854           coap_read_session(session->context, session, now);
1855         }
1856 
1857         if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
1858             (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
1859           /*
1860            * Need to update this to EPOLLIN as EPOLLOUT will normally always
1861            * be true causing epoll_wait to return early
1862            */
1863           coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
1864           sock->flags |= COAP_SOCKET_CAN_WRITE;
1865           coap_write_session(session->context, session, now);
1866         }
1867         /* Now dereference session so it can go away if needed */
1868         coap_session_release(session);
1869       }
1870     }
1871     else if (ctx->eptimerfd != -1) {
1872       /*
1873        * 'timer trigger' must have fired. eptimerfd needs to be read to clear
1874        *  it so that it does not set EPOLLIN in the next epoll_wait().
1875        */
1876       uint64_t count;
1877 
1878       /* Check the result from read() to suppress the warning on
1879        * systems that declare read() with warn_unused_result. */
1880       if (read(ctx->eptimerfd, &count, sizeof(count)) == -1) {
1881         /* do nothing */;
1882       }
1883     }
1884     /* And update eptimerfd as to when to next trigger */
1885     coap_ticks(&now);
1886     coap_io_prepare_epoll(ctx, now);
1887   }
1888 #endif /* COAP_EPOLL_SUPPORT */
1889 }
1890 
coap_get_endpoint(const coap_context_t * ctx)1891 coap_endpoint_t *coap_get_endpoint(const coap_context_t *ctx)
1892 {
1893     return ctx->endpoint;
1894 }
1895 
1896 int
coap_handle_dgram(coap_context_t * ctx,coap_session_t * session,uint8_t * msg,size_t msg_len)1897 coap_handle_dgram(coap_context_t *ctx, coap_session_t *session,
1898   uint8_t *msg, size_t msg_len) {
1899 
1900   coap_pdu_t *pdu = NULL;
1901 
1902   assert(COAP_PROTO_NOT_RELIABLE(session->proto));
1903   if (msg_len < 4) {
1904     /* Minimum size of CoAP header - ignore runt */
1905     return -1;
1906   }
1907 
1908   /* Need max space incase PDU is updated with updated token etc. */
1909   pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_size(session));
1910   if (!pdu)
1911     goto error;
1912 
1913   if (!coap_pdu_parse(session->proto, msg, msg_len, pdu)) {
1914     coap_log(LOG_WARNING, "discard malformed PDU\n");
1915     goto error;
1916   }
1917 
1918   coap_dispatch(ctx, session, pdu);
1919   coap_delete_pdu(pdu);
1920   return 0;
1921 
1922 error:
1923   /*
1924    * https://tools.ietf.org/html/rfc7252#section-4.2 MUST send RST
1925    * https://tools.ietf.org/html/rfc7252#section-4.3 MAY send RST
1926    */
1927   coap_send_rst(session, pdu);
1928   coap_delete_pdu(pdu);
1929   return -1;
1930 }
1931 #endif /* not WITH_LWIP */
1932 
1933 int
coap_remove_from_queue(coap_queue_t ** queue,coap_session_t * session,coap_mid_t id,coap_queue_t ** node)1934 coap_remove_from_queue(coap_queue_t **queue, coap_session_t *session, coap_mid_t id, coap_queue_t **node) {
1935   coap_queue_t *p, *q;
1936 
1937   if (!queue || !*queue)
1938     return 0;
1939 
1940   /* replace queue head if PDU's time is less than head's time */
1941 
1942   if (session == (*queue)->session && id == (*queue)->id) { /* found message id */
1943     *node = *queue;
1944     *queue = (*queue)->next;
1945     if (*queue) {          /* adjust relative time of new queue head */
1946       (*queue)->t += (*node)->t;
1947     }
1948     (*node)->next = NULL;
1949     coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed\n",
1950              coap_session_str(session), id);
1951     return 1;
1952   }
1953 
1954   /* search message id queue to remove (only first occurence will be removed) */
1955   q = *queue;
1956   do {
1957     p = q;
1958     q = q->next;
1959   } while (q && (session != q->session || id != q->id));
1960 
1961   if (q) {                        /* found message id */
1962     p->next = q->next;
1963     if (p->next) {                /* must update relative time of p->next */
1964       p->next->t += q->t;
1965     }
1966     q->next = NULL;
1967     *node = q;
1968     coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed\n",
1969              coap_session_str(session), id);
1970     return 1;
1971   }
1972 
1973   return 0;
1974 
1975 }
1976 
1977 void
coap_cancel_session_messages(coap_context_t * context,coap_session_t * session,coap_nack_reason_t reason)1978 coap_cancel_session_messages(coap_context_t *context, coap_session_t *session,
1979   coap_nack_reason_t reason) {
1980   coap_queue_t *p, *q;
1981 
1982   while (context->sendqueue && context->sendqueue->session == session) {
1983     q = context->sendqueue;
1984     context->sendqueue = q->next;
1985     coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed\n",
1986              coap_session_str(session), q->id);
1987     if (q->pdu->type == COAP_MESSAGE_CON && context->nack_handler)
1988       context->nack_handler(session, q->pdu, reason, q->id);
1989     coap_delete_node(q);
1990   }
1991 
1992   if (!context->sendqueue)
1993     return;
1994 
1995   p = context->sendqueue;
1996   q = p->next;
1997 
1998   while (q) {
1999     if (q->session == session) {
2000       p->next = q->next;
2001       coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed\n",
2002                coap_session_str(session), q->id);
2003       if (q->pdu->type == COAP_MESSAGE_CON && context->nack_handler)
2004         context->nack_handler(session, q->pdu, reason, q->id);
2005       coap_delete_node(q);
2006       q = p->next;
2007     } else {
2008       p = q;
2009       q = q->next;
2010     }
2011   }
2012 }
2013 
2014 void
coap_cancel_all_messages(coap_context_t * context,coap_session_t * session,const uint8_t * token,size_t token_length)2015 coap_cancel_all_messages(coap_context_t *context, coap_session_t *session,
2016   const uint8_t *token, size_t token_length) {
2017   /* cancel all messages in sendqueue that belong to session
2018    * and use the specified token */
2019   coap_queue_t *p, *q;
2020 
2021   while (context->sendqueue && context->sendqueue->session == session &&
2022     token_match(token, token_length,
2023       context->sendqueue->pdu->token,
2024       context->sendqueue->pdu->token_length)) {
2025     q = context->sendqueue;
2026     context->sendqueue = q->next;
2027     coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed\n",
2028              coap_session_str(session), q->id);
2029     coap_delete_node(q);
2030   }
2031 
2032   if (!context->sendqueue)
2033     return;
2034 
2035   p = context->sendqueue;
2036   q = p->next;
2037 
2038   /* when q is not NULL, it does not match (dst, token), so we can skip it */
2039   while (q) {
2040     if (q->session == session &&
2041       token_match(token, token_length,
2042         q->pdu->token, q->pdu->token_length)) {
2043       p->next = q->next;
2044       coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed\n",
2045                coap_session_str(session), q->id);
2046       coap_delete_node(q);
2047       q = p->next;
2048     } else {
2049       p = q;
2050       q = q->next;
2051     }
2052   }
2053 }
2054 
2055 coap_pdu_t *
coap_new_error_response(const coap_pdu_t * request,coap_pdu_code_t code,coap_opt_filter_t * opts)2056 coap_new_error_response(const coap_pdu_t *request, coap_pdu_code_t code,
2057   coap_opt_filter_t *opts) {
2058   coap_opt_iterator_t opt_iter;
2059   coap_pdu_t *response;
2060   size_t size = request->token_length;
2061   unsigned char type;
2062   coap_opt_t *option;
2063   coap_option_num_t opt_num = 0;        /* used for calculating delta-storage */
2064 
2065 #if COAP_ERROR_PHRASE_LENGTH > 0
2066   const char *phrase;
2067   if (code != COAP_RESPONSE_CODE(508)) {
2068     phrase = coap_response_phrase(code);
2069 
2070     /* Need some more space for the error phrase and payload start marker */
2071     if (phrase)
2072       size += strlen(phrase) + 1;
2073   }
2074   else {
2075     /*
2076      * Need space for IP for 5.08 response which is filled in in
2077      * coap_send_internal()
2078      * https://www.rfc-editor.org/rfc/rfc8768.html#section-4
2079      */
2080     phrase = NULL;
2081     size += INET6_ADDRSTRLEN;
2082   }
2083 #endif
2084 
2085   assert(request);
2086 
2087   /* cannot send ACK if original request was not confirmable */
2088   type = request->type == COAP_MESSAGE_CON
2089     ? COAP_MESSAGE_ACK
2090     : COAP_MESSAGE_NON;
2091 
2092   /* Estimate how much space we need for options to copy from
2093    * request. We always need the Token, for 4.02 the unknown critical
2094    * options must be included as well. */
2095 
2096   /* we do not want these */
2097   coap_option_filter_unset(opts, COAP_OPTION_CONTENT_TYPE);
2098   coap_option_filter_unset(opts, COAP_OPTION_HOP_LIMIT);
2099 
2100   coap_option_iterator_init(request, &opt_iter, opts);
2101 
2102   /* Add size of each unknown critical option. As known critical
2103      options as well as elective options are not copied, the delta
2104      value might grow.
2105    */
2106   while ((option = coap_option_next(&opt_iter))) {
2107     uint16_t delta = opt_iter.number - opt_num;
2108     /* calculate space required to encode (opt_iter.number - opt_num) */
2109     if (delta < 13) {
2110       size++;
2111     } else if (delta < 269) {
2112       size += 2;
2113     } else {
2114       size += 3;
2115     }
2116 
2117     /* add coap_opt_length(option) and the number of additional bytes
2118      * required to encode the option length */
2119 
2120     size += coap_opt_length(option);
2121     switch (*option & 0x0f) {
2122     case 0x0e:
2123       size++;
2124       /* fall through */
2125     case 0x0d:
2126       size++;
2127       break;
2128     default:
2129       ;
2130     }
2131 
2132     opt_num = opt_iter.number;
2133   }
2134 
2135   /* Now create the response and fill with options and payload data. */
2136   response = coap_pdu_init(type, code, request->mid, size);
2137   if (response) {
2138     /* copy token */
2139     if (!coap_add_token(response, request->token_length,
2140       request->token)) {
2141       coap_log(LOG_DEBUG, "cannot add token to error response\n");
2142       coap_delete_pdu(response);
2143       return NULL;
2144     }
2145 
2146     /* copy all options */
2147     coap_option_iterator_init(request, &opt_iter, opts);
2148     while ((option = coap_option_next(&opt_iter))) {
2149       coap_add_option(response, opt_iter.number,
2150         coap_opt_length(option),
2151         coap_opt_value(option));
2152     }
2153 
2154 #if COAP_ERROR_PHRASE_LENGTH > 0
2155     /* note that diagnostic messages do not need a Content-Format option. */
2156     if (phrase)
2157       coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
2158 #endif
2159   }
2160 
2161   return response;
2162 }
2163 
2164 /**
2165  * Quick hack to determine the size of the resource description for
2166  * .well-known/core.
2167  */
2168 COAP_STATIC_INLINE size_t
get_wkc_len(coap_context_t * context,coap_opt_t * query_filter)2169 get_wkc_len(coap_context_t *context, coap_opt_t *query_filter) {
2170   unsigned char buf[1];
2171   size_t len = 0;
2172 
2173   if (coap_print_wellknown(context, buf, &len, UINT_MAX, query_filter)
2174     & COAP_PRINT_STATUS_ERROR) {
2175     coap_log(LOG_WARNING, "cannot determine length of /.well-known/core\n");
2176     return 0;
2177   }
2178 
2179   coap_log(LOG_DEBUG, "get_wkc_len: coap_print_wellknown() returned %zu\n", len);
2180 
2181   return len;
2182 }
2183 
2184 #define SZX_TO_BYTES(SZX) ((size_t)(1 << ((SZX) + 4)))
2185 
2186 coap_pdu_t *
coap_wellknown_response(coap_context_t * context,coap_session_t * session,coap_pdu_t * request)2187 coap_wellknown_response(coap_context_t *context, coap_session_t *session,
2188   coap_pdu_t *request) {
2189   coap_pdu_t *resp;
2190   coap_opt_iterator_t opt_iter;
2191   size_t len, wkc_len;
2192   uint8_t buf[4];
2193   int result = 0;
2194   int need_block2 = 0;           /* set to 1 if Block2 option is required */
2195   coap_block_t block;
2196   coap_opt_t *query_filter;
2197   size_t offset = 0;
2198   uint8_t *data;
2199 
2200   resp = coap_pdu_init(request->type == COAP_MESSAGE_CON
2201     ? COAP_MESSAGE_ACK
2202     : COAP_MESSAGE_NON,
2203     COAP_RESPONSE_CODE(205),
2204     request->mid, coap_session_max_pdu_size(session));
2205   if (!resp) {
2206     coap_log(LOG_DEBUG, "coap_wellknown_response: cannot create PDU\n");
2207     return NULL;
2208   }
2209 
2210   if (!coap_add_token(resp, request->token_length, request->token)) {
2211     coap_log(LOG_DEBUG, "coap_wellknown_response: cannot add token\n");
2212     goto error;
2213   }
2214 
2215   query_filter = coap_check_option(request, COAP_OPTION_URI_QUERY, &opt_iter);
2216   wkc_len = get_wkc_len(context, query_filter);
2217 
2218   /* The value of some resources is undefined and get_wkc_len will return 0.*/
2219   if (wkc_len == 0) {
2220     coap_log(LOG_DEBUG, "coap_wellknown_response: undefined resource\n");
2221     /* set error code 4.00 Bad Request*/
2222     resp->code = COAP_RESPONSE_CODE(400);
2223     resp->used_size = resp->token_length;
2224     return resp;
2225   }
2226 
2227   /* check whether the request contains the Block2 option */
2228   if (coap_get_block(request, COAP_OPTION_BLOCK2, &block)) {
2229     coap_log(LOG_DEBUG, "create block\n");
2230     offset = block.num << (block.szx + 4);
2231     if (block.szx > 6) {  /* invalid, MUST lead to 4.00 Bad Request */
2232       resp->code = COAP_RESPONSE_CODE(400);
2233       return resp;
2234     } else if (block.szx > COAP_MAX_BLOCK_SZX) {
2235       block.szx = COAP_MAX_BLOCK_SZX;
2236       block.num = (unsigned int)(offset >> (block.szx + 4));
2237     }
2238 
2239     need_block2 = 1;
2240   }
2241 
2242   /* Check if there is sufficient space to add Content-Format option
2243    * and data. We do this before adding the Content-Format option to
2244    * avoid sending error responses with that option but no actual
2245    * content. */
2246   if (resp->max_size && resp->max_size <= resp->used_size + 8) {
2247     coap_log(LOG_DEBUG, "coap_wellknown_response: insufficient storage space\n");
2248     goto error;
2249   }
2250 
2251   /* check if Block2 option is required even if not requested */
2252   if (!need_block2 && resp->max_size && resp->max_size - resp->used_size < wkc_len + 1) {
2253     assert(resp->used_size <= resp->max_size);
2254     const size_t payloadlen = resp->max_size - resp->used_size;
2255     /* yes, need block-wise transfer */
2256     block.num = 0;
2257     block.m = 0;      /* the M bit is set by coap_write_block_opt() */
2258     block.szx = COAP_MAX_BLOCK_SZX;
2259     while (payloadlen < SZX_TO_BYTES(block.szx) + 6) {
2260       if (block.szx == 0) {
2261         coap_log(LOG_DEBUG,
2262              "coap_wellknown_response: message to small even for szx == 0\n");
2263         goto error;
2264       } else {
2265         block.szx--;
2266       }
2267     }
2268 
2269     need_block2 = 1;
2270   }
2271 
2272   if (need_block2) {
2273     /* Add in a pseudo etag (use wkc_len) in case .well-known/core
2274        changes over time */
2275     coap_add_option(resp,
2276                     COAP_OPTION_ETAG,
2277                     coap_encode_var_safe8(buf, sizeof(buf), wkc_len),
2278                     buf);
2279   }
2280 
2281   /* Add Content-Format. As we have checked for available storage,
2282    * nothing should go wrong here. */
2283   assert(coap_encode_var_safe(buf, sizeof(buf),
2284     COAP_MEDIATYPE_APPLICATION_LINK_FORMAT) == 1);
2285   coap_add_option(resp, COAP_OPTION_CONTENT_FORMAT,
2286     coap_encode_var_safe(buf, sizeof(buf),
2287       COAP_MEDIATYPE_APPLICATION_LINK_FORMAT), buf);
2288 
2289 
2290   /* write Block2 option if necessary */
2291   if (need_block2) {
2292     if (coap_write_block_opt(&block, COAP_OPTION_BLOCK2, resp, wkc_len) < 0) {
2293       coap_log(LOG_DEBUG,
2294                "coap_wellknown_response: cannot add Block2 option\n");
2295       goto error;
2296     }
2297   }
2298 
2299   coap_add_option(resp,
2300                   COAP_OPTION_SIZE2,
2301                   coap_encode_var_safe8(buf, sizeof(buf), wkc_len),
2302                   buf);
2303 
2304   len = need_block2 ?
2305         min(SZX_TO_BYTES(block.szx), wkc_len - (block.num << (block.szx + 4))) :
2306         resp->max_size && resp->used_size + wkc_len + 1 > resp->max_size ?
2307         resp->max_size - resp->used_size - 1 : wkc_len;
2308   data = coap_add_data_after(resp, len);
2309   if (!data) {
2310     coap_log(LOG_DEBUG, "coap_wellknown_response: coap_add_data failed\n" );
2311     goto error;
2312   }
2313 
2314   result = coap_print_wellknown(context, data, &len, offset, query_filter);
2315   if ((result & COAP_PRINT_STATUS_ERROR) != 0) {
2316     coap_log(LOG_DEBUG, "coap_print_wellknown failed\n");
2317     goto error;
2318   }
2319 
2320   return resp;
2321 
2322 error:
2323   /* set error code 5.03 and remove all options and data from response */
2324   resp->code = COAP_RESPONSE_CODE(503);
2325   resp->used_size = resp->token_length;
2326   return resp;
2327 }
2328 
2329 /**
2330  * This function cancels outstanding messages for the session and
2331  * token specified in @p sent. Any observation relationship for
2332  * sent->session and the token are removed. Calling this function is
2333  * required when receiving an RST message (usually in response to a
2334  * notification) or a GET request with the Observe option set to 1.
2335  *
2336  * This function returns @c 0 when the token is unknown with this
2337  * peer, or a value greater than zero otherwise.
2338  */
2339 static int
coap_cancel(coap_context_t * context,const coap_queue_t * sent)2340 coap_cancel(coap_context_t *context, const coap_queue_t *sent) {
2341   coap_binary_t token = { 0, NULL };
2342   int num_cancelled = 0;    /* the number of observers cancelled */
2343 
2344   /* remove observer for this resource, if any
2345    * get token from sent and try to find a matching resource. Uh!
2346    */
2347 
2348   COAP_SET_STR(&token, sent->pdu->token_length, sent->pdu->token);
2349 
2350   RESOURCES_ITER(context->resources, r) {
2351     coap_cancel_all_messages(context, sent->session, token.s, token.length);
2352     num_cancelled += coap_delete_observer(r, sent->session, &token);
2353   }
2354 
2355   return num_cancelled;
2356 }
2357 
2358 /**
2359  * Internal flags to control the treatment of responses (specifically
2360  * in presence of the No-Response option).
2361  */
2362 enum respond_t { RESPONSE_DEFAULT, RESPONSE_DROP, RESPONSE_SEND };
2363 
2364 /*
2365  * Checks for No-Response option in given @p request and
2366  * returns @c RESPONSE_DROP if @p response should be suppressed
2367  * according to RFC 7967.
2368  *
2369  * If the response is a confirmable piggybacked response and RESPONSE_DROP,
2370  * change it to an empty ACK and @c RESPONSE_SEND so the client does not keep
2371  * on retrying.
2372  *
2373  * Checks if the response code is 0.00 and if either the session is reliable or
2374  * non-confirmable, @c RESPONSE_DROP is also returned.
2375  *
2376  * Multicast response checking is also carried out.
2377  *
2378  * NOTE: It is the responsibility of the application to determine whether
2379  * a delayed separate response should be sent as the original requesting packet
2380  * containing the No-Response option has long since gone.
2381  *
2382  * The value of the No-Response option is encoded as
2383  * follows:
2384  *
2385  * @verbatim
2386  *  +-------+-----------------------+-----------------------------------+
2387  *  | Value | Binary Representation |          Description              |
2388  *  +-------+-----------------------+-----------------------------------+
2389  *  |   0   |      <empty>          | Interested in all responses.      |
2390  *  +-------+-----------------------+-----------------------------------+
2391  *  |   2   |      00000010         | Not interested in 2.xx responses. |
2392  *  +-------+-----------------------+-----------------------------------+
2393  *  |   8   |      00001000         | Not interested in 4.xx responses. |
2394  *  +-------+-----------------------+-----------------------------------+
2395  *  |  16   |      00010000         | Not interested in 5.xx responses. |
2396  *  +-------+-----------------------+-----------------------------------+
2397  * @endverbatim
2398  *
2399  * @param request  The CoAP request to check for the No-Response option.
2400  *                 This parameter must not be NULL.
2401  * @param response The response that is potentially suppressed.
2402  *                 This parameter must not be NULL.
2403  * @param session  The session this request/response are associated with.
2404  *                 This parameter must not be NULL.
2405  * @return RESPONSE_DEFAULT when no special treatment is requested,
2406  *         RESPONSE_DROP    when the response must be discarded, or
2407  *         RESPONSE_SEND    when the response must be sent.
2408  */
2409 static enum respond_t
no_response(coap_pdu_t * request,coap_pdu_t * response,coap_session_t * session)2410 no_response(coap_pdu_t *request, coap_pdu_t *response,
2411             coap_session_t *session) {
2412   coap_opt_t *nores;
2413   coap_opt_iterator_t opt_iter;
2414   unsigned int val = 0;
2415 
2416   assert(request);
2417   assert(response);
2418 
2419   if (COAP_RESPONSE_CLASS(response->code) > 0) {
2420     nores = coap_check_option(request, COAP_OPTION_NORESPONSE, &opt_iter);
2421 
2422     if (nores) {
2423       val = coap_decode_var_bytes(coap_opt_value(nores), coap_opt_length(nores));
2424 
2425       /* The response should be dropped when the bit corresponding to
2426        * the response class is set (cf. table in function
2427        * documentation). When a No-Response option is present and the
2428        * bit is not set, the sender explicitly indicates interest in
2429        * this response. */
2430       if (((1 << (COAP_RESPONSE_CLASS(response->code) - 1)) & val) > 0) {
2431         /* Should be dropping the response */
2432         if (response->type == COAP_MESSAGE_ACK &&
2433             COAP_PROTO_NOT_RELIABLE(session->proto)) {
2434           /* Still need to ACK the request */
2435           response->code = 0;
2436           /* Remove token/data from piggybacked acknowledgment PDU */
2437           response->token_length = 0;
2438           response->used_size = 0;
2439           return RESPONSE_SEND;
2440         }
2441         else {
2442           return RESPONSE_DROP;
2443         }
2444       } else {
2445         /* True for mcast as well RFC7967 2.1 */
2446         return RESPONSE_SEND;
2447       }
2448     }
2449   }
2450   else if (COAP_PDU_IS_EMPTY(response) &&
2451            (response->type == COAP_MESSAGE_NON ||
2452             COAP_PROTO_RELIABLE(session->proto))) {
2453     /* response is 0.00, and this is reliable or non-confirmable */
2454     return RESPONSE_DROP;
2455   }
2456 
2457   /*
2458    * Do not send error responses for requests that were received via
2459    * IP multicast.  RFC7252 8.1
2460    */
2461 
2462   if (coap_is_mcast(&session->addr_info.local)) {
2463     if (request->type == COAP_MESSAGE_NON &&
2464         response->type == COAP_MESSAGE_RST)
2465       return RESPONSE_DROP;
2466 
2467     if (COAP_RESPONSE_CLASS(response->code) > 2)
2468       return RESPONSE_DROP;
2469   }
2470 
2471   /* Default behavior applies when we are not dealing with a response
2472    * (class == 0) or the request did not contain a No-Response option.
2473    */
2474   return RESPONSE_DEFAULT;
2475 }
2476 
2477 static coap_str_const_t coap_default_uri_wellknown =
2478           { sizeof(COAP_DEFAULT_URI_WELLKNOWN)-1,
2479            (const uint8_t *)COAP_DEFAULT_URI_WELLKNOWN };
2480 
2481 static void
handle_request(coap_context_t * context,coap_session_t * session,coap_pdu_t * pdu)2482 handle_request(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu) {
2483   coap_method_handler_t h = NULL;
2484   coap_pdu_t *response = NULL;
2485   coap_opt_filter_t opt_filter;
2486   coap_resource_t *resource = NULL;
2487   /* The respond field indicates whether a response must be treated
2488    * specially due to a No-Response option that declares disinterest
2489    * or interest in a specific response class. DEFAULT indicates that
2490    * No-Response has not been specified. */
2491   enum respond_t respond = RESPONSE_DEFAULT;
2492   coap_opt_iterator_t opt_iter;
2493   coap_opt_t *opt;
2494   int is_proxy_uri = 0;
2495   int is_proxy_scheme = 0;
2496   int skip_hop_limit_check = 0;
2497   int resp;
2498   coap_binary_t token = { pdu->token_length, pdu->token };
2499 #ifndef WITHOUT_ASYNC
2500   coap_bin_const_t tokenc = { pdu->token_length, pdu->token };
2501   coap_async_t *async;
2502 #endif /* WITHOUT_ASYNC */
2503 
2504   if (coap_is_mcast(&session->addr_info.local)) {
2505     if (COAP_PROTO_RELIABLE(session->proto) || pdu->type != COAP_MESSAGE_NON) {
2506       coap_log(LOG_INFO, "Invalid multicast packet received RFC7252 8.1\n");
2507       return;
2508     }
2509   }
2510 #ifndef WITHOUT_ASYNC
2511   async = coap_find_async(session, tokenc);
2512   if (async) {
2513     coap_tick_t now;
2514 
2515     coap_ticks(&now);
2516     if (async->delay == 0 || async->delay > now) {
2517       /* re-transmit missing ACK (only if CON) */
2518       coap_log(LOG_INFO, "Retransmit async response\n");
2519       coap_send_ack(session, pdu);
2520       /* and do not pass on to the upper layers */
2521       return;
2522     }
2523   }
2524   else if (coap_is_mcast(&session->addr_info.local)) {
2525     uint8_t r;
2526     coap_tick_t delay;
2527 
2528     /* Need to delay sending mcast request to application layer, so response
2529        is not immediate. */
2530     coap_prng(&r, sizeof(r));
2531     delay = (COAP_DEFAULT_LEISURE * COAP_TICKS_PER_SECOND * r) / 256;
2532     /* Register request to be internally re-transmitted after delay */
2533     if (coap_register_async(session, pdu, delay))
2534       return;
2535   }
2536 #endif /* WITHOUT_ASYNC */
2537 
2538   coap_option_filter_clear(&opt_filter);
2539   opt = coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter);
2540   if (opt)
2541     is_proxy_scheme = 1;
2542 
2543   opt = coap_check_option(pdu, COAP_OPTION_PROXY_URI, &opt_iter);
2544   if (opt)
2545     is_proxy_uri = 1;
2546 
2547   if (is_proxy_scheme || is_proxy_uri) {
2548     coap_uri_t uri;
2549 
2550     if (!context->proxy_uri_resource) {
2551       /* Need to return a 5.05 RFC7252 Section 5.7.2 */
2552       coap_log(LOG_DEBUG, "Proxy-%s support not configured\n",
2553                is_proxy_scheme ? "Scheme" : "Uri");
2554       resp = 505;
2555       goto fail_response;
2556     }
2557     if (((size_t)pdu->code - 1 <
2558                 (sizeof(resource->handler) / sizeof(resource->handler[0]))) &&
2559         !(context->proxy_uri_resource->handler[pdu->code - 1])) {
2560       /* Need to return a 5.05 RFC7252 Section 5.7.2 */
2561       coap_log(LOG_DEBUG, "Proxy-%s code %d.%02d handler not supported\n",
2562                is_proxy_scheme ? "Scheme" : "Uri",
2563                pdu->code/100,  pdu->code%100);
2564       resp = 505;
2565       goto fail_response;
2566     }
2567 
2568     /* Need to check if authority is the proxy endpoint RFC7252 Section 5.7.2 */
2569     if (is_proxy_uri) {
2570       if (coap_split_proxy_uri(coap_opt_value(opt),
2571                                coap_opt_length(opt), &uri) < 0) {
2572         /* Need to return a 5.05 RFC7252 Section 5.7.2 */
2573         coap_log(LOG_DEBUG, "Proxy-URI not decodable\n");
2574         resp = 505;
2575         goto fail_response;
2576       }
2577     }
2578     else {
2579       memset(&uri, 0, sizeof(uri));
2580       opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
2581       if (opt) {
2582         uri.host.length = coap_opt_length(opt);
2583         uri.host.s = coap_opt_value(opt);
2584       }
2585     }
2586     resource = context->proxy_uri_resource;
2587     if (uri.host.length && resource->proxy_name_count && resource->proxy_name_list) {
2588       size_t i;
2589       for (i = 0; i < resource->proxy_name_count; i++) {
2590         if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
2591           break;
2592         }
2593       }
2594       if (i != resource->proxy_name_count) {
2595         /* This server is hosting the proxy connection endpoint */
2596         is_proxy_uri = 0;
2597         is_proxy_scheme = 0;
2598         skip_hop_limit_check = 1;
2599       }
2600     }
2601     resource = NULL;
2602   }
2603 
2604   if (!skip_hop_limit_check) {
2605     opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
2606     if (opt) {
2607       size_t hop_limit;
2608       uint8_t buf[4];
2609 
2610       hop_limit =
2611         coap_decode_var_bytes (coap_opt_value (opt), coap_opt_length (opt));
2612       if (hop_limit == 1) {
2613         /* coap_send_internal() will fill in the IP address for us */
2614         resp = 508;
2615         goto fail_response;
2616       }
2617       else if (hop_limit < 1 || hop_limit > 255) {
2618         /* Need to return a 4.00 RFC8768 Section 3 */
2619         coap_log(LOG_INFO, "Invalid Hop Limit\n");
2620         resp = 400;
2621         goto fail_response;
2622       }
2623       hop_limit--;
2624       coap_update_option(pdu, COAP_OPTION_HOP_LIMIT,
2625                          coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
2626                          buf);
2627     }
2628   }
2629 
2630   coap_string_t *uri_path = coap_get_uri_path(pdu);
2631   if (!uri_path)
2632     return;
2633 
2634   if (!is_proxy_uri && !is_proxy_scheme) {
2635     /* try to find the resource from the request URI */
2636     coap_str_const_t uri_path_c = { uri_path->length, uri_path->s };
2637     resource = coap_get_resource_from_uri_path(context, &uri_path_c);
2638   }
2639 
2640   if ((resource == NULL) || (resource->is_unknown == 1) ||
2641       (resource->is_proxy_uri == 1)) {
2642     /* The resource was not found or there is an unexpected match against the
2643      * resource defined for handling unknown or proxy URIs.
2644      * Check if the request URI happens to be the well-known URI, or if the
2645      * unknown resource handler is defined, a PUT or optionally other methods,
2646      * if configured, for the unknown handler.
2647      *
2648      * if well-known URI generate a default response
2649      *
2650      * else if a PROXY URI/Scheme request and proxy URI handler defined, call the
2651      *  proxy URI handler
2652      *
2653      * else if unknown URI handler defined, call the unknown
2654      *  URI handler (to allow for potential generation of resource
2655      *  [RFC7272 5.8.3]) if the appropriate method is defined.
2656      *
2657      * else if DELETE return 2.02 (RFC7252: 5.8.4.  DELETE)
2658      *
2659      * else return 4.04 */
2660 
2661     if (coap_string_equal(uri_path, &coap_default_uri_wellknown)) {
2662       /* request for .well-known/core */
2663       if (pdu->code == COAP_REQUEST_CODE_GET) { /* GET */
2664         coap_log(LOG_INFO, "create default response for %s\n",
2665                  COAP_DEFAULT_URI_WELLKNOWN);
2666         response = coap_wellknown_response(context, session, pdu);
2667       } else {
2668         coap_log(LOG_DEBUG, "method not allowed for .well-known/core\n");
2669         response = coap_new_error_response(pdu, COAP_RESPONSE_CODE(405),
2670           &opt_filter);
2671       }
2672     } else if (is_proxy_uri || is_proxy_scheme) {
2673       resource = context->proxy_uri_resource;
2674     } else if ((context->unknown_resource != NULL) &&
2675                ((size_t)pdu->code - 1 <
2676                 (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
2677                (context->unknown_resource->handler[pdu->code - 1])) {
2678       /*
2679        * The unknown_resource can be used to handle undefined resources
2680        * for a PUT request and can support any other registered handler
2681        * defined for it
2682        * Example set up code:-
2683        *   r = coap_resource_unknown_init(hnd_put_unknown);
2684        *   coap_register_handler(r, COAP_REQUEST_POST, hnd_post_unknown);
2685        *   coap_register_handler(r, COAP_REQUEST_GET, hnd_get_unknown);
2686        *   coap_register_handler(r, COAP_REQUEST_DELETE, hnd_delete_unknown);
2687        *   coap_add_resource(ctx, r);
2688        *
2689        * Note: It is not possible to observe the unknown_resource, a separate
2690        *       resource must be created (by PUT or POST) which has a GET
2691        *       handler to be observed
2692        */
2693       resource = context->unknown_resource;
2694     } else if (pdu->code == COAP_REQUEST_CODE_DELETE) {
2695       /*
2696        * Request for DELETE on non-existant resource (RFC7252: 5.8.4.  DELETE)
2697        */
2698       coap_log(LOG_DEBUG, "request for unknown resource '%*.*s',"
2699                           " return 2.02\n",
2700                           (int)uri_path->length,
2701                           (int)uri_path->length,
2702                           uri_path->s);
2703       response =
2704         coap_new_error_response(pdu, COAP_RESPONSE_CODE(202),
2705           &opt_filter);
2706     } else { /* request for any another resource, return 4.04 */
2707 
2708       coap_log(LOG_DEBUG, "request for unknown resource '%*.*s', return 4.04\n",
2709                (int)uri_path->length, (int)uri_path->length, uri_path->s);
2710       response =
2711         coap_new_error_response(pdu, COAP_RESPONSE_CODE(404),
2712           &opt_filter);
2713     }
2714 
2715     if (!resource) {
2716       if (response && (no_response(pdu, response, session) != RESPONSE_DROP)) {
2717         coap_mid_t mid = pdu->mid;
2718         if (coap_send_internal(session, response) == COAP_INVALID_MID)
2719           coap_log(LOG_WARNING, "cannot send response for mid=0x%x\n", mid);
2720       } else {
2721         coap_delete_pdu(response);
2722       }
2723 
2724       response = NULL;
2725 
2726       coap_delete_string(uri_path);
2727       return;
2728     } else {
2729       if (response) {
2730         /* Need to delete unused response - it will get re-created further on */
2731         coap_delete_pdu(response);
2732       }
2733     }
2734   }
2735 
2736   /* the resource was found, check if there is a registered handler */
2737   if ((size_t)pdu->code - 1 <
2738     sizeof(resource->handler) / sizeof(coap_method_handler_t))
2739     h = resource->handler[pdu->code - 1];
2740 
2741   if (h) {
2742      coap_log(LOG_DEBUG, "call custom handler for resource '%*.*s'\n",
2743               (int)resource->uri_path->length, (int)resource->uri_path->length,
2744               resource->uri_path->s);
2745     response = coap_pdu_init(pdu->type == COAP_MESSAGE_CON
2746       ? COAP_MESSAGE_ACK
2747       : COAP_MESSAGE_NON,
2748       0, pdu->mid, coap_session_max_pdu_size(session));
2749 
2750     /* Implementation detail: coap_add_token() immediately returns 0
2751        if response == NULL */
2752     if (coap_add_token(response, pdu->token_length, pdu->token)) {
2753       coap_opt_t *observe = NULL;
2754       int observe_action = COAP_OBSERVE_CANCEL;
2755       coap_string_t *query = coap_get_query(pdu);
2756       coap_block_t block;
2757       int added_block = 0;
2758 
2759       /* check for Observe option RFC7641 and RFC8132 */
2760       if (resource->observable &&
2761           (pdu->code == COAP_REQUEST_CODE_GET ||
2762            pdu->code == COAP_REQUEST_CODE_FETCH)) {
2763         observe = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
2764         if (observe) {
2765           observe_action =
2766             coap_decode_var_bytes(coap_opt_value(observe),
2767               coap_opt_length(observe));
2768 
2769           if (observe_action == COAP_OBSERVE_ESTABLISH) {
2770             coap_subscription_t *subscription;
2771 
2772             if (coap_get_block(pdu, COAP_OPTION_BLOCK2, &block)) {
2773               if (block.num != 0) {
2774                 response->code = COAP_RESPONSE_CODE(400);
2775                 goto skip_handler;
2776               }
2777             }
2778             subscription = coap_add_observer(resource, session, &token,
2779                                              pdu);
2780             if (subscription) {
2781               uint8_t buf[4];
2782 
2783               coap_touch_observer(context, session, &token);
2784               coap_add_option(response, COAP_OPTION_OBSERVE,
2785                               coap_encode_var_safe(buf, sizeof (buf),
2786                                                    resource->observe),
2787                               buf);
2788             }
2789           }
2790           else if (observe_action == COAP_OBSERVE_CANCEL) {
2791             coap_delete_observer(resource, session, &token);
2792           }
2793           else {
2794             coap_log(LOG_INFO, "observe: unexpected action %d\n", observe_action);
2795           }
2796         }
2797       }
2798 
2799       if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
2800         if (coap_handle_request_put_block(context, session, pdu, response,
2801                                           resource, uri_path, observe,
2802                                           query, h, &added_block)) {
2803           goto skip_handler;
2804         }
2805 
2806         if (coap_handle_request_send_block(session, pdu, response, resource,
2807                                            query)) {
2808           goto skip_handler;
2809         }
2810       }
2811 
2812       /*
2813        * Call the request handler with everything set up
2814        */
2815       h(resource, session, pdu, query, response);
2816 
2817       /* Check if lg_xmit generated and update PDU code if so */
2818       coap_check_code_lg_xmit(session, response, resource, query);
2819 
2820 skip_handler:
2821       respond = no_response(pdu, response, session);
2822       if (respond != RESPONSE_DROP) {
2823         coap_mid_t mid = pdu->mid;
2824         if (COAP_RESPONSE_CLASS(response->code) != 2) {
2825           if (observe) {
2826             coap_remove_option(response, COAP_OPTION_OBSERVE);
2827           }
2828         }
2829         if (COAP_RESPONSE_CLASS(response->code) > 2) {
2830           if (observe)
2831             coap_delete_observer(resource, session, &token);
2832           if (added_block)
2833             coap_remove_option(pdu, COAP_OPTION_BLOCK1);
2834         }
2835 
2836         /* If original request contained a token, and the registered
2837          * application handler made no changes to the response, then
2838          * this is an empty ACK with a token, which is a malformed
2839          * PDU */
2840         if ((response->type == COAP_MESSAGE_ACK)
2841           && (response->code == 0)) {
2842           /* Remove token from otherwise-empty acknowledgment PDU */
2843           response->token_length = 0;
2844           response->used_size = 0;
2845         }
2846 
2847         if (coap_send_internal(session, response) == COAP_INVALID_MID) {
2848           coap_log(LOG_DEBUG, "cannot send response for mid=0x%x\n", mid);
2849         }
2850       } else {
2851         coap_delete_pdu(response);
2852       }
2853       if (query)
2854         coap_delete_string(query);
2855     } else {
2856       coap_log(LOG_WARNING, "cannot generate response\r\n");
2857       coap_delete_pdu(response);
2858     }
2859     response = NULL;
2860   } else {
2861     if (coap_string_equal(uri_path, &coap_default_uri_wellknown)) {
2862       /* request for .well-known/core */
2863       coap_log(LOG_DEBUG, "create default response for %s\n",
2864                COAP_DEFAULT_URI_WELLKNOWN);
2865       response = coap_wellknown_response(context, session, pdu);
2866       coap_log(LOG_DEBUG, "have wellknown response %p\n", (void *)response);
2867     } else
2868       response = coap_new_error_response(pdu, COAP_RESPONSE_CODE(405),
2869         &opt_filter);
2870 
2871     if (response && (no_response(pdu, response, session) != RESPONSE_DROP)) {
2872       coap_mid_t mid = pdu->mid;
2873       if (coap_send_internal(session, response) == COAP_INVALID_MID)
2874         coap_log(LOG_DEBUG, "cannot send response for mid=0x%x\n", mid);
2875     } else {
2876       coap_delete_pdu(response);
2877     }
2878     response = NULL;
2879   }
2880 
2881   assert(response == NULL);
2882   coap_delete_string(uri_path);
2883   return;
2884 
2885 fail_response:
2886   response =
2887      coap_new_error_response(pdu, COAP_RESPONSE_CODE(resp),
2888        &opt_filter);
2889   if (response) {
2890     coap_mid_t mid = pdu->mid;
2891     if (coap_send_internal(session, response) == COAP_INVALID_MID)
2892       coap_log(LOG_WARNING, "cannot send response for mid=0x%x\n", mid);
2893   }
2894 }
2895 
2896 static void
handle_response(coap_context_t * context,coap_session_t * session,coap_pdu_t * sent,coap_pdu_t * rcvd)2897 handle_response(coap_context_t *context, coap_session_t *session,
2898   coap_pdu_t *sent, coap_pdu_t *rcvd) {
2899 
2900   /* In a lossy context, the ACK of a separate response may have
2901    * been lost, so we need to stop retransmitting requests with the
2902    * same token.
2903    */
2904   if (rcvd->token_length != 0) {
2905     coap_cancel_all_messages(context, session, rcvd->token, rcvd->token_length);
2906   }
2907 
2908   if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
2909     /* See if need to send next block to server */
2910     if (coap_handle_response_send_block(session, rcvd)) {
2911       /* Next block transmitted, no need to inform app */
2912       coap_send_ack(session, rcvd);
2913       return;
2914     }
2915 
2916     /* Need to see if needing to request next block */
2917     if (coap_handle_response_get_block(context, session, sent, rcvd,
2918                                        COAP_RECURSE_OK)) {
2919       /* Next block requested, no need to inform app */
2920       coap_send_ack(session, rcvd);
2921       return;
2922     }
2923   }
2924 
2925   /* Call application-specific response handler when available. */
2926   if (context->response_handler) {
2927     if (context->response_handler(session, sent, rcvd,
2928                                   rcvd->mid) == COAP_RESPONSE_FAIL)
2929       coap_send_rst(session, rcvd);
2930     else
2931       coap_send_ack(session, rcvd);
2932   }
2933   else {
2934     coap_send_ack(session, rcvd);
2935   }
2936 }
2937 
2938 #if !COAP_DISABLE_TCP
2939 static void
handle_signaling(coap_context_t * context,coap_session_t * session,coap_pdu_t * pdu)2940 handle_signaling(coap_context_t *context, coap_session_t *session,
2941   coap_pdu_t *pdu) {
2942   coap_opt_iterator_t opt_iter;
2943   coap_opt_t *option;
2944   (void)context;
2945 
2946   coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
2947 
2948   if (pdu->code == COAP_SIGNALING_CODE_CSM) {
2949     while ((option = coap_option_next(&opt_iter))) {
2950       if (opt_iter.number == COAP_SIGNALING_OPTION_MAX_MESSAGE_SIZE) {
2951         coap_session_set_mtu(session, coap_decode_var_bytes(coap_opt_value(option),
2952           coap_opt_length(option)));
2953       } else if (opt_iter.number == COAP_SIGNALING_OPTION_BLOCK_WISE_TRANSFER) {
2954         session->csm_block_supported = 1;
2955       }
2956     }
2957     if (session->state == COAP_SESSION_STATE_CSM)
2958       coap_session_connected(session);
2959   } else if (pdu->code == COAP_SIGNALING_CODE_PING) {
2960     coap_pdu_t *pong = coap_pdu_init(COAP_MESSAGE_CON, COAP_SIGNALING_CODE_PONG, 0, 1);
2961     if (context->ping_handler) {
2962       context->ping_handler(session, pdu, pdu->mid);
2963     }
2964     if (pong) {
2965       coap_add_option(pong, COAP_SIGNALING_OPTION_CUSTODY, 0, NULL);
2966       coap_send_internal(session, pong);
2967     }
2968   } else if (pdu->code == COAP_SIGNALING_CODE_PONG) {
2969     session->last_pong = session->last_rx_tx;
2970     if (context->pong_handler) {
2971       context->pong_handler(session, pdu, pdu->mid);
2972     }
2973   } else if (pdu->code == COAP_SIGNALING_CODE_RELEASE
2974           || pdu->code == COAP_SIGNALING_CODE_ABORT) {
2975     coap_session_disconnected(session, COAP_NACK_RST);
2976   }
2977 }
2978 #endif /* !COAP_DISABLE_TCP */
2979 
2980 void
coap_dispatch(coap_context_t * context,coap_session_t * session,coap_pdu_t * pdu)2981 coap_dispatch(coap_context_t *context, coap_session_t *session,
2982   coap_pdu_t *pdu) {
2983   coap_queue_t *sent = NULL;
2984   coap_pdu_t *response;
2985   coap_opt_filter_t opt_filter;
2986   int is_ping_rst;
2987 
2988   if (LOG_DEBUG <= coap_get_log_level()) {
2989     /* FIXME: get debug to work again **
2990     unsigned char addr[INET6_ADDRSTRLEN+8], localaddr[INET6_ADDRSTRLEN+8];
2991     if (coap_print_addr(remote, addr, INET6_ADDRSTRLEN+8) &&
2992         coap_print_addr(&packet->dst, localaddr, INET6_ADDRSTRLEN+8) )
2993       coap_log(LOG_DEBUG, "** received %d bytes from %s on interface %s:\n",
2994             (int)msg_len, addr, localaddr);
2995 
2996             */
2997     coap_show_pdu(LOG_DEBUG, pdu);
2998   }
2999 
3000   memset(&opt_filter, 0, sizeof(coap_opt_filter_t));
3001 
3002   switch (pdu->type) {
3003     case COAP_MESSAGE_ACK:
3004       /* find message id in sendqueue to stop retransmission */
3005       coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
3006 
3007       if (sent && session->con_active) {
3008         session->con_active--;
3009         if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3010           /* Flush out any entries on session->delayqueue */
3011           coap_session_connected(session);
3012       }
3013       if (coap_option_check_critical(context, pdu, &opt_filter) == 0)
3014         goto cleanup;
3015 
3016       /* if sent code was >= 64 the message might have been a
3017        * notification. Then, we must flag the observer to be alive
3018        * by setting obs->fail_cnt = 0. */
3019       if (sent && COAP_RESPONSE_CLASS(sent->pdu->code) == 2) {
3020         const coap_binary_t token =
3021         { sent->pdu->token_length, sent->pdu->token };
3022         coap_touch_observer(context, sent->session, &token);
3023       }
3024 
3025       if (pdu->code == 0) {
3026         /* an empty ACK needs no further handling */
3027         goto cleanup;
3028       }
3029 
3030       break;
3031 
3032     case COAP_MESSAGE_RST:
3033       /* We have sent something the receiver disliked, so we remove
3034        * not only the message id but also the subscriptions we might
3035        * have. */
3036 
3037       is_ping_rst = 0;
3038       if (pdu->mid == session->last_ping_mid &&
3039           context->ping_timeout && session->last_ping > 0)
3040         is_ping_rst = 1;
3041 
3042       if (!is_ping_rst)
3043         coap_log(LOG_ALERT, "got RST for mid=0x%x\n", pdu->mid);
3044 
3045       if (session->con_active) {
3046         session->con_active--;
3047         if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3048           /* Flush out any entries on session->delayqueue */
3049           coap_session_connected(session);
3050       }
3051 
3052       /* find message id in sendqueue to stop retransmission */
3053       coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
3054 
3055       if (sent) {
3056         coap_cancel(context, sent);
3057 
3058         if (!is_ping_rst) {
3059           if(sent->pdu->type==COAP_MESSAGE_CON && context->nack_handler)
3060             context->nack_handler(sent->session, sent->pdu,
3061                                   COAP_NACK_RST, sent->id);
3062         }
3063         else {
3064           if (context->pong_handler) {
3065             context->pong_handler(session, pdu, pdu->mid);
3066           }
3067           session->last_pong = session->last_rx_tx;
3068           session->last_ping_mid = COAP_INVALID_MID;
3069         }
3070       }
3071       else {
3072         /* Need to check is there is a subscription active and delete it */
3073         RESOURCES_ITER(context->resources, r) {
3074           coap_subscription_t *obs, *tmp;
3075           LL_FOREACH_SAFE(r->subscribers, obs, tmp) {
3076             if (obs->pdu->mid == pdu->mid && obs->session == session) {
3077               coap_binary_t token = { 0, NULL };
3078               COAP_SET_STR(&token, obs->pdu->token_length, obs->pdu->token);
3079               coap_delete_observer(r, session, &token);
3080               goto cleanup;
3081             }
3082           }
3083         }
3084       }
3085       goto cleanup;
3086 
3087     case COAP_MESSAGE_NON:
3088       /* find transaction in sendqueue in case large response */
3089       coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
3090       /* check for unknown critical options */
3091       if (coap_option_check_critical(context, pdu, &opt_filter) == 0) {
3092         coap_send_rst(session, pdu);
3093         goto cleanup;
3094       }
3095       break;
3096 
3097     case COAP_MESSAGE_CON:        /* check for unknown critical options */
3098       if (coap_option_check_critical(context, pdu, &opt_filter) == 0) {
3099 
3100         if (COAP_PDU_IS_REQUEST(pdu)) {
3101           response =
3102             coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
3103 
3104           if (!response) {
3105             coap_log(LOG_WARNING,
3106                      "coap_dispatch: cannot create error response\n");
3107           } else {
3108             if (coap_send_internal(session, response) == COAP_INVALID_MID)
3109               coap_log(LOG_WARNING, "coap_dispatch: error sending response\n");
3110           }
3111         }
3112         else {
3113           coap_send_rst(session, pdu);
3114         }
3115 
3116         goto cleanup;
3117       }
3118     default: break;
3119   }
3120 
3121   /* Pass message to upper layer if a specific handler was
3122     * registered for a request that should be handled locally. */
3123 #if !COAP_DISABLE_TCP
3124   if (COAP_PDU_IS_SIGNALING(pdu))
3125     handle_signaling(context, session, pdu);
3126   else
3127 #endif /* !COAP_DISABLE_TCP */
3128   if (COAP_PDU_IS_REQUEST(pdu))
3129     handle_request(context, session, pdu);
3130   else if (COAP_PDU_IS_RESPONSE(pdu))
3131     handle_response(context, session, sent ? sent->pdu : NULL, pdu);
3132   else {
3133     if (COAP_PDU_IS_EMPTY(pdu)) {
3134       if (context->ping_handler) {
3135         context->ping_handler(session, pdu, pdu->mid);
3136       }
3137     }
3138     coap_log(LOG_DEBUG, "dropped message with invalid code (%d.%02d)\n",
3139              COAP_RESPONSE_CLASS(pdu->code),
3140       pdu->code & 0x1f);
3141 
3142     if (!coap_is_mcast(&session->addr_info.local)) {
3143       if (COAP_PDU_IS_EMPTY(pdu)) {
3144         if (session->proto != COAP_PROTO_TCP && session->proto != COAP_PROTO_TLS) {
3145           coap_tick_t now;
3146           coap_ticks(&now);
3147           if (session->last_tx_rst + COAP_TICKS_PER_SECOND/4 < now) {
3148             coap_send_message_type(session, pdu, COAP_MESSAGE_RST);
3149             session->last_tx_rst = now;
3150           }
3151         }
3152       }
3153       else {
3154         coap_send_message_type(session, pdu, COAP_MESSAGE_RST);
3155       }
3156     }
3157   }
3158 
3159 cleanup:
3160   coap_delete_node(sent);
3161 }
3162 
3163 int
coap_handle_event(coap_context_t * context,coap_event_t event,coap_session_t * session)3164 coap_handle_event(coap_context_t *context, coap_event_t event, coap_session_t *session) {
3165   coap_log(LOG_DEBUG, "***EVENT: 0x%04x\n", event);
3166 
3167   if (context->handle_event) {
3168     return context->handle_event(session, event);
3169   } else {
3170     return 0;
3171   }
3172 }
3173 
3174 int
coap_can_exit(coap_context_t * context)3175 coap_can_exit(coap_context_t *context) {
3176   coap_endpoint_t *ep;
3177   coap_session_t *s, *rtmp;
3178   if (!context)
3179     return 1;
3180   if (context->sendqueue)
3181     return 0;
3182   LL_FOREACH(context->endpoint, ep) {
3183     SESSIONS_ITER(ep->sessions, s, rtmp) {
3184       if (s->delayqueue)
3185         return 0;
3186       if (s->lg_xmit)
3187         return 0;
3188     }
3189   }
3190   SESSIONS_ITER(context->sessions, s, rtmp) {
3191     if (s->delayqueue)
3192       return 0;
3193     if (s->lg_xmit)
3194       return 0;
3195   }
3196   return 1;
3197 }
3198 #ifndef WITHOUT_ASYNC
3199 coap_tick_t
coap_check_async(coap_context_t * context,coap_tick_t now)3200 coap_check_async(coap_context_t *context, coap_tick_t now) {
3201   coap_tick_t next_due = 0;
3202   coap_async_t *async, *tmp;
3203 
3204   LL_FOREACH_SAFE(context->async_state, async, tmp) {
3205     if (async->delay <= now) {
3206       /* Send off the request to the application */
3207       handle_request(context, async->session, async->pdu);
3208 
3209       /* Remove this async entry as it has now fired */
3210       coap_free_async(async->session, async);
3211     }
3212     else {
3213       if (next_due == 0 || next_due > async->delay - now)
3214         next_due = async->delay - now;
3215     }
3216   }
3217   return next_due;
3218 }
3219 #endif /* WITHOUT_ASYNC */
3220 
3221 static int coap_started = 0;
3222 
coap_startup(void)3223 void coap_startup(void) {
3224   coap_tick_t now;
3225   uint64_t us;
3226   if (coap_started)
3227     return;
3228   coap_started = 1;
3229 #if defined(HAVE_WINSOCK2_H)
3230   WORD wVersionRequested = MAKEWORD(2, 2);
3231   WSADATA wsaData;
3232   WSAStartup(wVersionRequested, &wsaData);
3233 #endif
3234   coap_clock_init();
3235   coap_ticks(&now);
3236   us = coap_ticks_to_rt_us(now);
3237   /* Be accurate to the nearest (approx) us */
3238   coap_prng_init((unsigned int)us);
3239   coap_memory_init();
3240   coap_dtls_startup();
3241 }
3242 
coap_cleanup(void)3243 void coap_cleanup(void) {
3244 #if defined(HAVE_WINSOCK2_H)
3245   WSACleanup();
3246 #endif
3247   coap_dtls_shutdown();
3248 }
3249 
3250 void
coap_register_response_handler(coap_context_t * context,coap_response_handler_t handler)3251 coap_register_response_handler(coap_context_t *context,
3252                                coap_response_handler_t handler) {
3253   context->response_handler = handler;
3254 }
3255 
3256 void
coap_register_nack_handler(coap_context_t * context,coap_nack_handler_t handler)3257 coap_register_nack_handler(coap_context_t *context,
3258                            coap_nack_handler_t handler) {
3259   context->nack_handler = handler;
3260 }
3261 
3262 void
coap_register_ping_handler(coap_context_t * context,coap_ping_handler_t handler)3263 coap_register_ping_handler(coap_context_t *context,
3264                            coap_ping_handler_t handler) {
3265   context->ping_handler = handler;
3266 }
3267 
3268 void
coap_register_pong_handler(coap_context_t * context,coap_pong_handler_t handler)3269 coap_register_pong_handler(coap_context_t *context,
3270                            coap_pong_handler_t handler) {
3271   context->pong_handler = handler;
3272 }
3273 
3274 void
coap_register_option(coap_context_t * ctx,uint16_t type)3275 coap_register_option(coap_context_t *ctx, uint16_t type) {
3276   coap_option_filter_set(&ctx->known_options, type);
3277 }
3278 
3279 #if ! defined WITH_CONTIKI && ! defined WITH_LWIP && ! defined RIOT_VERSION
3280 int
coap_join_mcast_group_intf(coap_context_t * ctx,const char * group_name,const char * ifname)3281 coap_join_mcast_group_intf(coap_context_t *ctx, const char *group_name,
3282                            const char *ifname) {
3283   struct ip_mreq mreq4;
3284   struct ipv6_mreq mreq6;
3285   struct addrinfo *resmulti = NULL, hints, *ainfo;
3286   int result = -1;
3287   coap_endpoint_t *endpoint;
3288   int mgroup_setup = 0;
3289 
3290   /* Need to have at least one endpoint! */
3291   assert(ctx->endpoint);
3292   if (!ctx->endpoint)
3293     return -1;
3294 
3295   /* Default is let the kernel choose */
3296   mreq6.ipv6mr_interface = 0;
3297   mreq4.imr_interface.s_addr = INADDR_ANY;
3298 
3299   memset(&hints, 0, sizeof(hints));
3300   hints.ai_socktype = SOCK_DGRAM;
3301 
3302   /* resolve the multicast group address */
3303   result = getaddrinfo(group_name, NULL, &hints, &resmulti);
3304 
3305   if (result != 0) {
3306     coap_log(LOG_ERR,
3307              "coap_join_mcast_group_intf: %s: "
3308               "Cannot resolve multicast address: %s\n",
3309              group_name, gai_strerror(result));
3310     goto finish;
3311   }
3312 
3313 /* Need to do a windows equivalent at some point */
3314 #ifndef _WIN32
3315   if (ifname) {
3316     /* interface specified - check if we have correct IPv4/IPv6 information */
3317     int done_ip4 = 0;
3318     int done_ip6 = 0;
3319 #if defined(ESPIDF_VERSION)
3320     struct netif *netif;
3321 #else /* !ESPIDF_VERSION */
3322     int ip4fd;
3323     struct ifreq ifr;
3324 #endif /* !ESPIDF_VERSION */
3325 
3326     /* See which mcast address family types are being asked for */
3327     for (ainfo = resmulti; ainfo != NULL && !(done_ip4 == 1 && done_ip6 == 1);
3328          ainfo = ainfo->ai_next) {
3329       switch (ainfo->ai_family) {
3330       case AF_INET6:
3331         if (done_ip6)
3332           break;
3333         done_ip6 = 1;
3334 #if defined(ESPIDF_VERSION)
3335         netif = netif_find(ifname);
3336         if (netif)
3337           mreq6.ipv6mr_interface = netif_get_index(netif);
3338         else
3339           coap_log(LOG_ERR,
3340                    "coap_join_mcast_group_intf: %s: "
3341                     "Cannot get IPv4 address: %s\n",
3342                     ifname, coap_socket_strerror());
3343 #else /* !ESPIDF_VERSION */
3344         memset (&ifr, 0, sizeof(ifr));
3345         strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
3346         ifr.ifr_name[IFNAMSIZ - 1] = '\000';
3347 
3348 #ifdef HAVE_IF_NAMETOINDEX
3349         mreq6.ipv6mr_interface = if_nametoindex(ifr.ifr_name);
3350         if (mreq6.ipv6mr_interface == 0) {
3351           coap_log(LOG_WARNING, "coap_join_mcast_group_intf: "
3352                     "cannot get interface index for '%s'\n",
3353                    ifname);
3354         }
3355 #else /* !HAVE_IF_NAMETOINDEX */
3356         result = ioctl(ctx->endpoint->sock.fd, SIOCGIFINDEX, &ifr);
3357         if (result != 0) {
3358           coap_log(LOG_WARNING, "coap_join_mcast_group_intf: "
3359                     "cannot get interface index for '%s': %s\n",
3360                    ifname, coap_socket_strerror());
3361         }
3362         else {
3363           /* Capture the IPv6 if_index for later */
3364           mreq6.ipv6mr_interface = ifr.ifr_ifindex;
3365         }
3366 #endif /* !HAVE_IF_NAMETOINDEX */
3367 #endif /* !ESPIDF_VERSION */
3368         break;
3369       case AF_INET:
3370         if (done_ip4)
3371           break;
3372         done_ip4 = 1;
3373 #if defined(ESPIDF_VERSION)
3374         netif = netif_find(ifname);
3375         if (netif)
3376           mreq4.imr_interface.s_addr = netif_ip4_addr(netif)->addr;
3377         else
3378           coap_log(LOG_ERR,
3379                    "coap_join_mcast_group_intf: %s: "
3380                     "Cannot get IPv4 address: %s\n",
3381                     ifname, coap_socket_strerror());
3382 #else /* !ESPIDF_VERSION */
3383         /*
3384          * Need an AF_INET socket to do this unfortunately to stop
3385          * "Invalid argument" error if AF_INET6 socket is used for SIOCGIFADDR
3386          */
3387         ip4fd = socket(AF_INET, SOCK_DGRAM, 0);
3388         if (ip4fd == -1) {
3389           coap_log(LOG_ERR,
3390                    "coap_join_mcast_group_intf: %s: socket: %s\n",
3391                    ifname, coap_socket_strerror());
3392           continue;
3393         }
3394         memset (&ifr, 0, sizeof(ifr));
3395         strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
3396         ifr.ifr_name[IFNAMSIZ - 1] = '\000';
3397         result = ioctl(ip4fd, SIOCGIFADDR, &ifr);
3398         if (result != 0) {
3399           coap_log(LOG_ERR,
3400                    "coap_join_mcast_group_intf: %s: "
3401                     "Cannot get IPv4 address: %s\n",
3402                     ifname, coap_socket_strerror());
3403         }
3404         else {
3405           /* Capture the IPv4 address for later */
3406           mreq4.imr_interface = ((struct sockaddr_in*)&ifr.ifr_addr)->sin_addr;
3407         }
3408         close(ip4fd);
3409 #endif /* !ESPIDF_VERSION */
3410         break;
3411       default:
3412         break;
3413       }
3414     }
3415   }
3416 #endif /* ! _WIN32 */
3417 
3418   /* Add in mcast address(es) to appropriate interface */
3419   for (ainfo = resmulti; ainfo != NULL; ainfo = ainfo->ai_next) {
3420     LL_FOREACH(ctx->endpoint, endpoint) {
3421       /* Only UDP currently supported */
3422       if (endpoint->proto == COAP_PROTO_UDP) {
3423         coap_address_t gaddr;
3424 
3425         coap_address_init(&gaddr);
3426         if (ainfo->ai_family == AF_INET6) {
3427           if (!ifname) {
3428             if(endpoint->bind_addr.addr.sa.sa_family == AF_INET6) {
3429               /*
3430                * Do it on the ifindex that the server is listening on
3431                * (sin6_scope_id could still be 0)
3432                */
3433               mreq6.ipv6mr_interface =
3434                                  endpoint->bind_addr.addr.sin6.sin6_scope_id;
3435             }
3436             else {
3437               mreq6.ipv6mr_interface = 0;
3438             }
3439           }
3440           gaddr.addr.sin6.sin6_family = AF_INET6;
3441           gaddr.addr.sin6.sin6_port = endpoint->bind_addr.addr.sin6.sin6_port;
3442           gaddr.addr.sin6.sin6_addr = mreq6.ipv6mr_multiaddr =
3443                     ((struct sockaddr_in6 *)ainfo->ai_addr)->sin6_addr;
3444           result = setsockopt(endpoint->sock.fd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
3445                               (char *)&mreq6, sizeof(mreq6));
3446         }
3447         else if (ainfo->ai_family == AF_INET) {
3448           if (!ifname) {
3449             if(endpoint->bind_addr.addr.sa.sa_family == AF_INET) {
3450               /*
3451                * Do it on the interface that the server is listening on
3452                * (sin_addr could still be INADDR_ANY)
3453                */
3454               mreq4.imr_interface = endpoint->bind_addr.addr.sin.sin_addr;
3455             }
3456             else {
3457               mreq4.imr_interface.s_addr = INADDR_ANY;
3458             }
3459           }
3460           gaddr.addr.sin.sin_family = AF_INET;
3461           gaddr.addr.sin.sin_port = endpoint->bind_addr.addr.sin.sin_port;
3462           gaddr.addr.sin.sin_addr.s_addr = mreq4.imr_multiaddr.s_addr =
3463               ((struct sockaddr_in *)ainfo->ai_addr)->sin_addr.s_addr;
3464           result = setsockopt(endpoint->sock.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3465                               (char *)&mreq4, sizeof(mreq4));
3466         }
3467         else {
3468           continue;
3469         }
3470 
3471         if (result == COAP_SOCKET_ERROR) {
3472           coap_log(LOG_ERR,
3473                    "coap_join_mcast_group_intf: %s: setsockopt: %s\n",
3474                    group_name, coap_socket_strerror());
3475         }
3476         else {
3477           char addr_str[INET6_ADDRSTRLEN + 8 + 1];
3478 
3479           addr_str[sizeof(addr_str)-1] = '\000';
3480           if (coap_print_addr(&gaddr, (uint8_t*)addr_str,
3481                             sizeof(addr_str) - 1)) {
3482             if (ifname)
3483               coap_log(LOG_DEBUG, "added mcast group %s i/f %s\n", addr_str,
3484                        ifname);
3485             else
3486               coap_log(LOG_DEBUG, "added mcast group %s\n", addr_str);
3487           }
3488           mgroup_setup = 1;
3489         }
3490       }
3491     }
3492   }
3493   if (!mgroup_setup) {
3494     result = -1;
3495   }
3496 
3497  finish:
3498   freeaddrinfo(resmulti);
3499 
3500   return result;
3501 }
3502 
3503 int
coap_mcast_set_hops(coap_session_t * session,size_t hops)3504 coap_mcast_set_hops(coap_session_t *session, size_t hops) {
3505   if (session && coap_is_mcast(&session->addr_info.remote)) {
3506     switch (session->addr_info.remote.addr.sa.sa_family) {
3507     case AF_INET:
3508       if (setsockopt(session->sock.fd, IPPROTO_IP, IP_MULTICAST_TTL,
3509           (const char *)&hops, sizeof(hops)) < 0) {
3510         coap_log(LOG_INFO, "coap_mcast_set_hops: %zu: setsockopt: %s\n",
3511                  hops, coap_socket_strerror());
3512         return 0;
3513       }
3514       return 1;
3515     case AF_INET6:
3516       if (setsockopt(session->sock.fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
3517           (const char *)&hops, sizeof(hops)) < 0) {
3518         coap_log(LOG_INFO, "coap_mcast_set_hops: %zu: setsockopt: %s\n",
3519                  hops, coap_socket_strerror());
3520         return 0;
3521       }
3522       return 1;
3523     default:
3524       break;
3525     }
3526   }
3527   return 0;
3528 }
3529 #else /* defined WITH_CONTIKI || defined WITH_LWIP */
3530 int
coap_join_mcast_group_intf(coap_context_t * ctx COAP_UNUSED,const char * group_name COAP_UNUSED,const char * ifname COAP_UNUSED)3531 coap_join_mcast_group_intf(coap_context_t *ctx COAP_UNUSED,
3532                            const char *group_name COAP_UNUSED,
3533                            const char *ifname COAP_UNUSED) {
3534   return -1;
3535 }
3536 int
coap_mcast_set_hops(coap_session_t * session COAP_UNUSED,size_t hops COAP_UNUSED)3537 coap_mcast_set_hops(coap_session_t *session COAP_UNUSED,
3538                     size_t hops COAP_UNUSED) {
3539   return 0;
3540 }
3541 #endif /* defined WITH_CONTIKI || defined WITH_LWIP */
3542 
3543 #ifdef WITH_CONTIKI
3544 
3545 /*---------------------------------------------------------------------------*/
3546 /* CoAP message retransmission */
3547 /*---------------------------------------------------------------------------*/
PROCESS_THREAD(coap_retransmit_process,ev,data)3548 PROCESS_THREAD(coap_retransmit_process, ev, data) {
3549   coap_tick_t now;
3550   coap_queue_t *nextpdu;
3551 
3552   PROCESS_BEGIN();
3553 
3554   coap_log(LOG_DEBUG, "Started retransmit process\n");
3555 
3556   while (1) {
3557     PROCESS_YIELD();
3558     if (ev == PROCESS_EVENT_TIMER) {
3559       if (etimer_expired(&the_coap_context.retransmit_timer)) {
3560 
3561         nextpdu = coap_peek_next(&the_coap_context);
3562 
3563         coap_ticks(&now);
3564         while (nextpdu && nextpdu->t <= now) {
3565           coap_retransmit(&the_coap_context, coap_pop_next(&the_coap_context));
3566           nextpdu = coap_peek_next(&the_coap_context);
3567         }
3568 
3569         /* need to set timer to some value even if no nextpdu is available */
3570         etimer_set(&the_coap_context.retransmit_timer,
3571           nextpdu ? nextpdu->t - now : 0xFFFF);
3572       }
3573       if (etimer_expired(&the_coap_context.notify_timer)) {
3574         coap_check_notify(&the_coap_context);
3575         etimer_reset(&the_coap_context.notify_timer);
3576       }
3577     }
3578   }
3579 
3580   PROCESS_END();
3581 }
3582 /*---------------------------------------------------------------------------*/
3583 
3584 #endif /* WITH_CONTIKI */
3585 
3586 #ifdef WITH_LWIP
3587 /* FIXME: retransmits that are not required any more due to incoming packages
3588  * do *not* get cleared at the moment, the wakeup when the transmission is due
3589  * is silently accepted. this is mainly due to the fact that the required
3590  * checks are similar in two places in the code (when receiving ACK and RST)
3591  * and that they cause more than one patch chunk, as it must be first checked
3592  * whether the sendqueue item to be dropped is the next one pending, and later
3593  * the restart function has to be called. nothing insurmountable, but it can
3594  * also be implemented when things have stabilized, and the performance
3595  * penality is minimal
3596  *
3597  * also, this completely ignores COAP_RESOURCE_CHECK_TIME.
3598  * */
3599 
coap_retransmittimer_execute(void * arg)3600 static void coap_retransmittimer_execute(void *arg) {
3601   coap_context_t *ctx = (coap_context_t*)arg;
3602   coap_tick_t now;
3603   coap_tick_t elapsed;
3604   coap_queue_t *nextinqueue;
3605 
3606   ctx->timer_configured = 0;
3607 
3608   coap_ticks(&now);
3609 
3610   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 */
3611 
3612   nextinqueue = coap_peek_next(ctx);
3613   while (nextinqueue != NULL) {
3614     if (nextinqueue->t > elapsed) {
3615       nextinqueue->t -= elapsed;
3616       break;
3617     } else {
3618       elapsed -= nextinqueue->t;
3619       coap_retransmit(ctx, coap_pop_next(ctx));
3620       nextinqueue = coap_peek_next(ctx);
3621     }
3622   }
3623 
3624   ctx->sendqueue_basetime = now;
3625 
3626   coap_retransmittimer_restart(ctx);
3627 }
3628 
coap_retransmittimer_restart(coap_context_t * ctx)3629 static void coap_retransmittimer_restart(coap_context_t *ctx) {
3630   coap_tick_t now, elapsed, delay;
3631 
3632   if (ctx->timer_configured) {
3633     printf("clearing\n");
3634     sys_untimeout(coap_retransmittimer_execute, (void*)ctx);
3635     ctx->timer_configured = 0;
3636   }
3637   if (ctx->sendqueue != NULL) {
3638     coap_ticks(&now);
3639     elapsed = now - ctx->sendqueue_basetime;
3640     if (ctx->sendqueue->t >= elapsed) {
3641       delay = ctx->sendqueue->t - elapsed;
3642     } else {
3643       /* a strange situation, but not completely impossible.
3644        *
3645        * this happens, for example, right after
3646        * coap_retransmittimer_execute, when a retransmission
3647        * was *just not yet* due, and the clock ticked before
3648        * our coap_ticks was called.
3649        *
3650        * not trying to retransmit anything now, as it might
3651        * cause uncontrollable recursion; let's just try again
3652        * with the next main loop run.
3653        * */
3654       delay = 0;
3655     }
3656 
3657     printf("scheduling for %d ticks\n", delay);
3658     sys_timeout(delay, coap_retransmittimer_execute, (void*)ctx);
3659     ctx->timer_configured = 1;
3660   }
3661 }
3662 #endif
3663