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;
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   assert(session->sock.flags & (COAP_SOCKET_CONNECTED | COAP_SOCKET_MULTICAST));
1548 
1549   if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
1550     ssize_t bytes_read;
1551     memcpy(&packet->addr_info, &session->addr_info, sizeof(packet->addr_info));
1552     bytes_read = ctx->network_read(&session->sock, packet);
1553 
1554     if (bytes_read < 0) {
1555       if (bytes_read == -2)
1556         /* Reset the session back to startup defaults */
1557         coap_session_disconnected(session, COAP_NACK_ICMP_ISSUE);
1558       else
1559         coap_log(LOG_WARNING, "*  %s: read error\n",
1560                  coap_session_str(session));
1561     } else if (bytes_read > 0) {
1562       session->last_rx_tx = now;
1563       memcpy(&session->addr_info, &packet->addr_info,
1564              sizeof(session->addr_info));
1565       coap_log(LOG_DEBUG, "*  %s: received %zd bytes\n",
1566                coap_session_str(session), bytes_read);
1567       coap_handle_dgram_for_proto(ctx, session, packet);
1568     }
1569 #if !COAP_DISABLE_TCP
1570   } else {
1571     ssize_t bytes_read = 0;
1572     const uint8_t *p;
1573     int retry;
1574     /* adjust for LWIP */
1575     uint8_t *buf = packet->payload;
1576     size_t buf_len = sizeof(packet->payload);
1577 
1578     do {
1579       if (session->proto == COAP_PROTO_TCP)
1580         bytes_read = coap_socket_read(&session->sock, buf, buf_len);
1581       else if (session->proto == COAP_PROTO_TLS)
1582         bytes_read = coap_tls_read(session, buf, buf_len);
1583       if (bytes_read > 0) {
1584         coap_log(LOG_DEBUG, "*  %s: received %zd bytes\n",
1585                  coap_session_str(session), bytes_read);
1586         session->last_rx_tx = now;
1587       }
1588       p = buf;
1589       retry = bytes_read == (ssize_t)buf_len;
1590       while (bytes_read > 0) {
1591         if (session->partial_pdu) {
1592           size_t len = session->partial_pdu->used_size
1593                      + session->partial_pdu->hdr_size
1594                      - session->partial_read;
1595           size_t n = min(len, (size_t)bytes_read);
1596           memcpy(session->partial_pdu->token - session->partial_pdu->hdr_size
1597                  + session->partial_read, p, n);
1598           p += n;
1599           bytes_read -= n;
1600           if (n == len) {
1601             if (coap_pdu_parse_header(session->partial_pdu, session->proto)
1602               && coap_pdu_parse_opt(session->partial_pdu)) {
1603               coap_dispatch(ctx, session, session->partial_pdu);
1604             }
1605             coap_delete_pdu(session->partial_pdu);
1606             session->partial_pdu = NULL;
1607             session->partial_read = 0;
1608           } else {
1609             session->partial_read += n;
1610           }
1611         } else if (session->partial_read > 0) {
1612           size_t hdr_size = coap_pdu_parse_header_size(session->proto,
1613             session->read_header);
1614           size_t len = hdr_size - session->partial_read;
1615           size_t n = min(len, (size_t)bytes_read);
1616           memcpy(session->read_header + session->partial_read, p, n);
1617           p += n;
1618           bytes_read -= n;
1619           if (n == len) {
1620             size_t size = coap_pdu_parse_size(session->proto, session->read_header,
1621               hdr_size);
1622             if (size > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
1623               coap_log(LOG_WARNING,
1624                        "** %s: incoming PDU length too large (%zu > %lu)\n",
1625                        coap_session_str(session),
1626                        size, COAP_DEFAULT_MAX_PDU_RX_SIZE);
1627               bytes_read = -1;
1628               break;
1629             }
1630             /* Need max space incase PDU is updated with updated token etc. */
1631             session->partial_pdu = coap_pdu_init(0, 0, 0,
1632                                            coap_session_max_pdu_size(session));
1633             if (session->partial_pdu == NULL) {
1634               bytes_read = -1;
1635               break;
1636             }
1637             if (session->partial_pdu->alloc_size < size && !coap_pdu_resize(session->partial_pdu, size)) {
1638               bytes_read = -1;
1639               break;
1640             }
1641             session->partial_pdu->hdr_size = (uint8_t)hdr_size;
1642             session->partial_pdu->used_size = size;
1643             memcpy(session->partial_pdu->token - hdr_size, session->read_header, hdr_size);
1644             session->partial_read = hdr_size;
1645             if (size == 0) {
1646               if (coap_pdu_parse_header(session->partial_pdu, session->proto)) {
1647                 coap_dispatch(ctx, session, session->partial_pdu);
1648               }
1649               coap_delete_pdu(session->partial_pdu);
1650               session->partial_pdu = NULL;
1651               session->partial_read = 0;
1652             }
1653           } else {
1654             session->partial_read += bytes_read;
1655           }
1656         } else {
1657           session->read_header[0] = *p++;
1658           bytes_read -= 1;
1659           if (!coap_pdu_parse_header_size(session->proto,
1660                                           session->read_header)) {
1661             bytes_read = -1;
1662             break;
1663           }
1664           session->partial_read = 1;
1665         }
1666       }
1667     } while (bytes_read == 0 && retry);
1668     if (bytes_read < 0)
1669       coap_session_disconnected(session, COAP_NACK_NOT_DELIVERABLE);
1670 #endif /* !COAP_DISABLE_TCP */
1671   }
1672 #if COAP_CONSTRAINED_STACK
1673   coap_mutex_unlock(&s_static_mutex);
1674 #endif /* COAP_CONSTRAINED_STACK */
1675 }
1676 
1677 static int
coap_read_endpoint(coap_context_t * ctx,coap_endpoint_t * endpoint,coap_tick_t now)1678 coap_read_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
1679   ssize_t bytes_read = -1;
1680   int result = -1;                /* the value to be returned */
1681 #if COAP_CONSTRAINED_STACK
1682   static coap_mutex_t e_static_mutex = COAP_MUTEX_INITIALIZER;
1683   static coap_packet_t e_packet;
1684 #else /* ! COAP_CONSTRAINED_STACK */
1685   coap_packet_t e_packet;
1686 #endif /* ! COAP_CONSTRAINED_STACK */
1687   coap_packet_t *packet = &e_packet;
1688 
1689   assert(COAP_PROTO_NOT_RELIABLE(endpoint->proto));
1690   assert(endpoint->sock.flags & COAP_SOCKET_BOUND);
1691 
1692 #if COAP_CONSTRAINED_STACK
1693   coap_mutex_lock(&e_static_mutex);
1694 #endif /* COAP_CONSTRAINED_STACK */
1695 
1696   /* Need to do this as there may be holes in addr_info */
1697   memset(&packet->addr_info, 0, sizeof(packet->addr_info));
1698   coap_address_init(&packet->addr_info.remote);
1699   coap_address_copy(&packet->addr_info.local, &endpoint->bind_addr);
1700   bytes_read = ctx->network_read(&endpoint->sock, packet);
1701 
1702   if (bytes_read < 0) {
1703     coap_log(LOG_WARNING, "*  %s: read failed\n", coap_endpoint_str(endpoint));
1704   } else if (bytes_read > 0) {
1705     coap_session_t *session = coap_endpoint_get_session(endpoint, packet, now);
1706     if (session) {
1707       coap_log(LOG_DEBUG, "*  %s: received %zd bytes\n",
1708                coap_session_str(session), bytes_read);
1709       result = coap_handle_dgram_for_proto(ctx, session, packet);
1710       if (endpoint->proto == COAP_PROTO_DTLS && session->type == COAP_SESSION_TYPE_HELLO && result == 1)
1711         coap_session_new_dtls_session(session, now);
1712     }
1713   }
1714 #if COAP_CONSTRAINED_STACK
1715   coap_mutex_unlock(&e_static_mutex);
1716 #endif /* COAP_CONSTRAINED_STACK */
1717   return result;
1718 }
1719 
1720 static int
coap_write_endpoint(coap_context_t * ctx,coap_endpoint_t * endpoint,coap_tick_t now)1721 coap_write_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
1722   (void)ctx;
1723   (void)endpoint;
1724   (void)now;
1725   return 0;
1726 }
1727 
1728 static int
coap_accept_endpoint(coap_context_t * ctx,coap_endpoint_t * endpoint,coap_tick_t now)1729 coap_accept_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint,
1730   coap_tick_t now) {
1731   coap_session_t *session = coap_new_server_session(ctx, endpoint);
1732   if (session)
1733     session->last_rx_tx = now;
1734   return session != NULL;
1735 }
1736 
1737 void
coap_io_do_io(coap_context_t * ctx,coap_tick_t now)1738 coap_io_do_io(coap_context_t *ctx, coap_tick_t now) {
1739 #ifdef COAP_EPOLL_SUPPORT
1740   (void)ctx;
1741   (void)now;
1742    coap_log(LOG_EMERG,
1743             "coap_io_do_io() requires libcoap not compiled for using epoll\n");
1744 #else /* ! COAP_EPOLL_SUPPORT */
1745   coap_endpoint_t *ep, *tmp;
1746   coap_session_t *s, *rtmp;
1747 
1748   LL_FOREACH_SAFE(ctx->endpoint, ep, tmp) {
1749     if ((ep->sock.flags & COAP_SOCKET_CAN_READ) != 0)
1750       coap_read_endpoint(ctx, ep, now);
1751     if ((ep->sock.flags & COAP_SOCKET_CAN_WRITE) != 0)
1752       coap_write_endpoint(ctx, ep, now);
1753     if ((ep->sock.flags & COAP_SOCKET_CAN_ACCEPT) != 0)
1754       coap_accept_endpoint(ctx, ep, now);
1755     SESSIONS_ITER_SAFE(ep->sessions, s, rtmp) {
1756       if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0) {
1757         /* Make sure the session object is not deleted in one of the callbacks  */
1758         coap_session_reference(s);
1759         coap_read_session(ctx, s, now);
1760         coap_session_release(s);
1761       }
1762       if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0) {
1763         /* Make sure the session object is not deleted in one of the callbacks  */
1764         coap_session_reference(s);
1765         coap_write_session(ctx, s, now);
1766         coap_session_release(s);
1767       }
1768     }
1769   }
1770 
1771   SESSIONS_ITER_SAFE(ctx->sessions, s, rtmp) {
1772     if ((s->sock.flags & COAP_SOCKET_CAN_CONNECT) != 0) {
1773       /* Make sure the session object is not deleted in one of the callbacks  */
1774       coap_session_reference(s);
1775       coap_connect_session(ctx, s, now);
1776       coap_session_release( s );
1777     }
1778     if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0) {
1779       /* Make sure the session object is not deleted in one of the callbacks  */
1780       coap_session_reference(s);
1781       coap_read_session(ctx, s, now);
1782       coap_session_release(s);
1783     }
1784     if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0) {
1785       /* Make sure the session object is not deleted in one of the callbacks  */
1786       coap_session_reference(s);
1787       coap_write_session(ctx, s, now);
1788       coap_session_release( s );
1789     }
1790   }
1791 #endif /* ! COAP_EPOLL_SUPPORT */
1792 }
1793 
1794 /*
1795  * While this code in part replicates coap_io_do_io(), doing the functions
1796  * directly saves having to iterate through the endpoints / sessions.
1797  */
1798 void
coap_io_do_epoll(coap_context_t * ctx,struct epoll_event * events,size_t nevents)1799 coap_io_do_epoll(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
1800 #ifndef COAP_EPOLL_SUPPORT
1801   (void)ctx;
1802   (void)events;
1803   (void)nevents;
1804    coap_log(LOG_EMERG,
1805             "coap_io_do_epoll() requires libcoap compiled for using epoll\n");
1806 #else /* COAP_EPOLL_SUPPORT */
1807   coap_tick_t now;
1808   size_t j;
1809 
1810   coap_ticks(&now);
1811   for(j = 0; j < nevents; j++) {
1812     coap_socket_t *sock = (coap_socket_t*)events[j].data.ptr;
1813 
1814     /* Ignore 'timer trigger' ptr  which is NULL */
1815     if (sock) {
1816       if (sock->endpoint) {
1817         coap_endpoint_t *endpoint = sock->endpoint;
1818         if ((sock->flags & COAP_SOCKET_WANT_READ) &&
1819             (events[j].events & EPOLLIN)) {
1820           sock->flags |= COAP_SOCKET_CAN_READ;
1821           coap_read_endpoint(endpoint->context, endpoint, now);
1822         }
1823 
1824         if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
1825             (events[j].events & EPOLLOUT)) {
1826           /*
1827            * Need to update this to EPOLLIN as EPOLLOUT will normally always
1828            * be true causing epoll_wait to return early
1829            */
1830           coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
1831           sock->flags |= COAP_SOCKET_CAN_WRITE;
1832           coap_write_endpoint(endpoint->context, endpoint, now);
1833         }
1834 
1835         if ((sock->flags & COAP_SOCKET_WANT_ACCEPT) &&
1836             (events[j].events & EPOLLIN)) {
1837           sock->flags |= COAP_SOCKET_CAN_ACCEPT;
1838           coap_accept_endpoint(endpoint->context, endpoint, now);
1839         }
1840 
1841       }
1842       else if (sock->session) {
1843         coap_session_t *session = sock->session;
1844 
1845         /* Make sure the session object is not deleted
1846            in one of the callbacks  */
1847         coap_session_reference(session);
1848         if ((sock->flags & COAP_SOCKET_WANT_CONNECT) &&
1849             (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
1850           sock->flags |= COAP_SOCKET_CAN_CONNECT;
1851           coap_connect_session(session->context, session, now);
1852           if (!(sock->flags & COAP_SOCKET_WANT_WRITE)) {
1853             coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
1854           }
1855         }
1856 
1857         if ((sock->flags & COAP_SOCKET_WANT_READ) &&
1858             (events[j].events & (EPOLLIN|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
1859           sock->flags |= COAP_SOCKET_CAN_READ;
1860           coap_read_session(session->context, session, now);
1861         }
1862 
1863         if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
1864             (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
1865           /*
1866            * Need to update this to EPOLLIN as EPOLLOUT will normally always
1867            * be true causing epoll_wait to return early
1868            */
1869           coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
1870           sock->flags |= COAP_SOCKET_CAN_WRITE;
1871           coap_write_session(session->context, session, now);
1872         }
1873         /* Now dereference session so it can go away if needed */
1874         coap_session_release(session);
1875       }
1876     }
1877     else if (ctx->eptimerfd != -1) {
1878       /*
1879        * 'timer trigger' must have fired. eptimerfd needs to be read to clear
1880        *  it so that it does not set EPOLLIN in the next epoll_wait().
1881        */
1882       uint64_t count;
1883 
1884       /* Check the result from read() to suppress the warning on
1885        * systems that declare read() with warn_unused_result. */
1886       if (read(ctx->eptimerfd, &count, sizeof(count)) == -1) {
1887         /* do nothing */;
1888       }
1889     }
1890     /* And update eptimerfd as to when to next trigger */
1891     coap_ticks(&now);
1892     coap_io_prepare_epoll(ctx, now);
1893   }
1894 #endif /* COAP_EPOLL_SUPPORT */
1895 }
1896 
1897 int
coap_handle_dgram(coap_context_t * ctx,coap_session_t * session,uint8_t * msg,size_t msg_len)1898 coap_handle_dgram(coap_context_t *ctx, coap_session_t *session,
1899   uint8_t *msg, size_t msg_len) {
1900 
1901   coap_pdu_t *pdu = NULL;
1902 
1903   assert(COAP_PROTO_NOT_RELIABLE(session->proto));
1904   if (msg_len < 4) {
1905     /* Minimum size of CoAP header - ignore runt */
1906     return -1;
1907   }
1908 
1909   /* Need max space incase PDU is updated with updated token etc. */
1910   pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_size(session));
1911   if (!pdu)
1912     goto error;
1913 
1914   if (!coap_pdu_parse(session->proto, msg, msg_len, pdu)) {
1915     coap_log(LOG_WARNING, "discard malformed PDU\n");
1916     goto error;
1917   }
1918 
1919   coap_dispatch(ctx, session, pdu);
1920   coap_delete_pdu(pdu);
1921   return 0;
1922 
1923 error:
1924   /*
1925    * https://tools.ietf.org/html/rfc7252#section-4.2 MUST send RST
1926    * https://tools.ietf.org/html/rfc7252#section-4.3 MAY send RST
1927    */
1928   coap_send_rst(session, pdu);
1929   coap_delete_pdu(pdu);
1930   return -1;
1931 }
1932 #endif /* not WITH_LWIP */
1933 
1934 int
coap_remove_from_queue(coap_queue_t ** queue,coap_session_t * session,coap_mid_t id,coap_queue_t ** node)1935 coap_remove_from_queue(coap_queue_t **queue, coap_session_t *session, coap_mid_t id, coap_queue_t **node) {
1936   coap_queue_t *p, *q;
1937 
1938   if (!queue || !*queue)
1939     return 0;
1940 
1941   /* replace queue head if PDU's time is less than head's time */
1942 
1943   if (session == (*queue)->session && id == (*queue)->id) { /* found message id */
1944     *node = *queue;
1945     *queue = (*queue)->next;
1946     if (*queue) {          /* adjust relative time of new queue head */
1947       (*queue)->t += (*node)->t;
1948     }
1949     (*node)->next = NULL;
1950     coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed\n",
1951              coap_session_str(session), id);
1952     return 1;
1953   }
1954 
1955   /* search message id queue to remove (only first occurence will be removed) */
1956   q = *queue;
1957   do {
1958     p = q;
1959     q = q->next;
1960   } while (q && (session != q->session || id != q->id));
1961 
1962   if (q) {                        /* found message id */
1963     p->next = q->next;
1964     if (p->next) {                /* must update relative time of p->next */
1965       p->next->t += q->t;
1966     }
1967     q->next = NULL;
1968     *node = q;
1969     coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed\n",
1970              coap_session_str(session), id);
1971     return 1;
1972   }
1973 
1974   return 0;
1975 
1976 }
1977 
1978 void
coap_cancel_session_messages(coap_context_t * context,coap_session_t * session,coap_nack_reason_t reason)1979 coap_cancel_session_messages(coap_context_t *context, coap_session_t *session,
1980   coap_nack_reason_t reason) {
1981   coap_queue_t *p, *q;
1982 
1983   while (context->sendqueue && context->sendqueue->session == session) {
1984     q = context->sendqueue;
1985     context->sendqueue = q->next;
1986     coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed\n",
1987              coap_session_str(session), q->id);
1988     if (q->pdu->type == COAP_MESSAGE_CON && context->nack_handler)
1989       context->nack_handler(session, q->pdu, reason, q->id);
1990     coap_delete_node(q);
1991   }
1992 
1993   if (!context->sendqueue)
1994     return;
1995 
1996   p = context->sendqueue;
1997   q = p->next;
1998 
1999   while (q) {
2000     if (q->session == session) {
2001       p->next = q->next;
2002       coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed\n",
2003                coap_session_str(session), q->id);
2004       if (q->pdu->type == COAP_MESSAGE_CON && context->nack_handler)
2005         context->nack_handler(session, q->pdu, reason, q->id);
2006       coap_delete_node(q);
2007       q = p->next;
2008     } else {
2009       p = q;
2010       q = q->next;
2011     }
2012   }
2013 }
2014 
2015 void
coap_cancel_all_messages(coap_context_t * context,coap_session_t * session,const uint8_t * token,size_t token_length)2016 coap_cancel_all_messages(coap_context_t *context, coap_session_t *session,
2017   const uint8_t *token, size_t token_length) {
2018   /* cancel all messages in sendqueue that belong to session
2019    * and use the specified token */
2020   coap_queue_t *p, *q;
2021 
2022   while (context->sendqueue && context->sendqueue->session == session &&
2023     token_match(token, token_length,
2024       context->sendqueue->pdu->token,
2025       context->sendqueue->pdu->token_length)) {
2026     q = context->sendqueue;
2027     context->sendqueue = q->next;
2028     coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed\n",
2029              coap_session_str(session), q->id);
2030     coap_delete_node(q);
2031   }
2032 
2033   if (!context->sendqueue)
2034     return;
2035 
2036   p = context->sendqueue;
2037   q = p->next;
2038 
2039   /* when q is not NULL, it does not match (dst, token), so we can skip it */
2040   while (q) {
2041     if (q->session == session &&
2042       token_match(token, token_length,
2043         q->pdu->token, q->pdu->token_length)) {
2044       p->next = q->next;
2045       coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed\n",
2046                coap_session_str(session), q->id);
2047       coap_delete_node(q);
2048       q = p->next;
2049     } else {
2050       p = q;
2051       q = q->next;
2052     }
2053   }
2054 }
2055 
2056 coap_pdu_t *
coap_new_error_response(const coap_pdu_t * request,coap_pdu_code_t code,coap_opt_filter_t * opts)2057 coap_new_error_response(const coap_pdu_t *request, coap_pdu_code_t code,
2058   coap_opt_filter_t *opts) {
2059   coap_opt_iterator_t opt_iter;
2060   coap_pdu_t *response;
2061   size_t size = request->token_length;
2062   unsigned char type;
2063   coap_opt_t *option;
2064   coap_option_num_t opt_num = 0;        /* used for calculating delta-storage */
2065 
2066 #if COAP_ERROR_PHRASE_LENGTH > 0
2067   const char *phrase;
2068   if (code != COAP_RESPONSE_CODE(508)) {
2069     phrase = coap_response_phrase(code);
2070 
2071     /* Need some more space for the error phrase and payload start marker */
2072     if (phrase)
2073       size += strlen(phrase) + 1;
2074   }
2075   else {
2076     /*
2077      * Need space for IP for 5.08 response which is filled in in
2078      * coap_send_internal()
2079      * https://www.rfc-editor.org/rfc/rfc8768.html#section-4
2080      */
2081     phrase = NULL;
2082     size += INET6_ADDRSTRLEN;
2083   }
2084 #endif
2085 
2086   assert(request);
2087 
2088   /* cannot send ACK if original request was not confirmable */
2089   type = request->type == COAP_MESSAGE_CON
2090     ? COAP_MESSAGE_ACK
2091     : COAP_MESSAGE_NON;
2092 
2093   /* Estimate how much space we need for options to copy from
2094    * request. We always need the Token, for 4.02 the unknown critical
2095    * options must be included as well. */
2096 
2097   /* we do not want these */
2098   coap_option_filter_unset(opts, COAP_OPTION_CONTENT_TYPE);
2099   coap_option_filter_unset(opts, COAP_OPTION_HOP_LIMIT);
2100 
2101   coap_option_iterator_init(request, &opt_iter, opts);
2102 
2103   /* Add size of each unknown critical option. As known critical
2104      options as well as elective options are not copied, the delta
2105      value might grow.
2106    */
2107   while ((option = coap_option_next(&opt_iter))) {
2108     uint16_t delta = opt_iter.number - opt_num;
2109     /* calculate space required to encode (opt_iter.number - opt_num) */
2110     if (delta < 13) {
2111       size++;
2112     } else if (delta < 269) {
2113       size += 2;
2114     } else {
2115       size += 3;
2116     }
2117 
2118     /* add coap_opt_length(option) and the number of additional bytes
2119      * required to encode the option length */
2120 
2121     size += coap_opt_length(option);
2122     switch (*option & 0x0f) {
2123     case 0x0e:
2124       size++;
2125       /* fall through */
2126     case 0x0d:
2127       size++;
2128       break;
2129     default:
2130       ;
2131     }
2132 
2133     opt_num = opt_iter.number;
2134   }
2135 
2136   /* Now create the response and fill with options and payload data. */
2137   response = coap_pdu_init(type, code, request->mid, size);
2138   if (response) {
2139     /* copy token */
2140     if (!coap_add_token(response, request->token_length,
2141       request->token)) {
2142       coap_log(LOG_DEBUG, "cannot add token to error response\n");
2143       coap_delete_pdu(response);
2144       return NULL;
2145     }
2146 
2147     /* copy all options */
2148     coap_option_iterator_init(request, &opt_iter, opts);
2149     while ((option = coap_option_next(&opt_iter))) {
2150       coap_add_option(response, opt_iter.number,
2151         coap_opt_length(option),
2152         coap_opt_value(option));
2153     }
2154 
2155 #if COAP_ERROR_PHRASE_LENGTH > 0
2156     /* note that diagnostic messages do not need a Content-Format option. */
2157     if (phrase)
2158       coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
2159 #endif
2160   }
2161 
2162   return response;
2163 }
2164 
2165 /**
2166  * Quick hack to determine the size of the resource description for
2167  * .well-known/core.
2168  */
2169 COAP_STATIC_INLINE size_t
get_wkc_len(coap_context_t * context,coap_opt_t * query_filter)2170 get_wkc_len(coap_context_t *context, coap_opt_t *query_filter) {
2171   unsigned char buf[1];
2172   size_t len = 0;
2173 
2174   if (coap_print_wellknown(context, buf, &len, UINT_MAX, query_filter)
2175     & COAP_PRINT_STATUS_ERROR) {
2176     coap_log(LOG_WARNING, "cannot determine length of /.well-known/core\n");
2177     return 0;
2178   }
2179 
2180   coap_log(LOG_DEBUG, "get_wkc_len: coap_print_wellknown() returned %zu\n", len);
2181 
2182   return len;
2183 }
2184 
2185 #define SZX_TO_BYTES(SZX) ((size_t)(1 << ((SZX) + 4)))
2186 
2187 coap_pdu_t *
coap_wellknown_response(coap_context_t * context,coap_session_t * session,coap_pdu_t * request)2188 coap_wellknown_response(coap_context_t *context, coap_session_t *session,
2189   coap_pdu_t *request) {
2190   coap_pdu_t *resp;
2191   coap_opt_iterator_t opt_iter;
2192   size_t len, wkc_len;
2193   uint8_t buf[4];
2194   int result = 0;
2195   int need_block2 = 0;           /* set to 1 if Block2 option is required */
2196   coap_block_t block;
2197   coap_opt_t *query_filter;
2198   size_t offset = 0;
2199   uint8_t *data;
2200 
2201   resp = coap_pdu_init(request->type == COAP_MESSAGE_CON
2202     ? COAP_MESSAGE_ACK
2203     : COAP_MESSAGE_NON,
2204     COAP_RESPONSE_CODE(205),
2205     request->mid, coap_session_max_pdu_size(session));
2206   if (!resp) {
2207     coap_log(LOG_DEBUG, "coap_wellknown_response: cannot create PDU\n");
2208     return NULL;
2209   }
2210 
2211   if (!coap_add_token(resp, request->token_length, request->token)) {
2212     coap_log(LOG_DEBUG, "coap_wellknown_response: cannot add token\n");
2213     goto error;
2214   }
2215 
2216   query_filter = coap_check_option(request, COAP_OPTION_URI_QUERY, &opt_iter);
2217   wkc_len = get_wkc_len(context, query_filter);
2218 
2219   /* The value of some resources is undefined and get_wkc_len will return 0.*/
2220   if (wkc_len == 0) {
2221     coap_log(LOG_DEBUG, "coap_wellknown_response: undefined resource\n");
2222     /* set error code 4.00 Bad Request*/
2223     resp->code = COAP_RESPONSE_CODE(400);
2224     resp->used_size = resp->token_length;
2225     return resp;
2226   }
2227 
2228   /* check whether the request contains the Block2 option */
2229   if (coap_get_block(request, COAP_OPTION_BLOCK2, &block)) {
2230     coap_log(LOG_DEBUG, "create block\n");
2231     offset = block.num << (block.szx + 4);
2232     if (block.szx > 6) {  /* invalid, MUST lead to 4.00 Bad Request */
2233       resp->code = COAP_RESPONSE_CODE(400);
2234       return resp;
2235     } else if (block.szx > COAP_MAX_BLOCK_SZX) {
2236       block.szx = COAP_MAX_BLOCK_SZX;
2237       block.num = (unsigned int)(offset >> (block.szx + 4));
2238     }
2239 
2240     need_block2 = 1;
2241   }
2242 
2243   /* Check if there is sufficient space to add Content-Format option
2244    * and data. We do this before adding the Content-Format option to
2245    * avoid sending error responses with that option but no actual
2246    * content. */
2247   if (resp->max_size && resp->max_size <= resp->used_size + 8) {
2248     coap_log(LOG_DEBUG, "coap_wellknown_response: insufficient storage space\n");
2249     goto error;
2250   }
2251 
2252   /* check if Block2 option is required even if not requested */
2253   if (!need_block2 && resp->max_size && resp->max_size - resp->used_size < wkc_len + 1) {
2254     assert(resp->used_size <= resp->max_size);
2255     const size_t payloadlen = resp->max_size - resp->used_size;
2256     /* yes, need block-wise transfer */
2257     block.num = 0;
2258     block.m = 0;      /* the M bit is set by coap_write_block_opt() */
2259     block.szx = COAP_MAX_BLOCK_SZX;
2260     while (payloadlen < SZX_TO_BYTES(block.szx) + 6) {
2261       if (block.szx == 0) {
2262         coap_log(LOG_DEBUG,
2263              "coap_wellknown_response: message to small even for szx == 0\n");
2264         goto error;
2265       } else {
2266         block.szx--;
2267       }
2268     }
2269 
2270     need_block2 = 1;
2271   }
2272 
2273   if (need_block2) {
2274     /* Add in a pseudo etag (use wkc_len) in case .well-known/core
2275        changes over time */
2276     coap_add_option(resp,
2277                     COAP_OPTION_ETAG,
2278                     coap_encode_var_safe8(buf, sizeof(buf), wkc_len),
2279                     buf);
2280   }
2281 
2282   /* Add Content-Format. As we have checked for available storage,
2283    * nothing should go wrong here. */
2284   assert(coap_encode_var_safe(buf, sizeof(buf),
2285     COAP_MEDIATYPE_APPLICATION_LINK_FORMAT) == 1);
2286   coap_add_option(resp, COAP_OPTION_CONTENT_FORMAT,
2287     coap_encode_var_safe(buf, sizeof(buf),
2288       COAP_MEDIATYPE_APPLICATION_LINK_FORMAT), buf);
2289 
2290 
2291   /* write Block2 option if necessary */
2292   if (need_block2) {
2293     if (coap_write_block_opt(&block, COAP_OPTION_BLOCK2, resp, wkc_len) < 0) {
2294       coap_log(LOG_DEBUG,
2295                "coap_wellknown_response: cannot add Block2 option\n");
2296       goto error;
2297     }
2298   }
2299 
2300   coap_add_option(resp,
2301                   COAP_OPTION_SIZE2,
2302                   coap_encode_var_safe8(buf, sizeof(buf), wkc_len),
2303                   buf);
2304 
2305   len = need_block2 ?
2306         min(SZX_TO_BYTES(block.szx), wkc_len - (block.num << (block.szx + 4))) :
2307         resp->max_size && resp->used_size + wkc_len + 1 > resp->max_size ?
2308         resp->max_size - resp->used_size - 1 : wkc_len;
2309   data = coap_add_data_after(resp, len);
2310   if (!data) {
2311     coap_log(LOG_DEBUG, "coap_wellknown_response: coap_add_data failed\n" );
2312     goto error;
2313   }
2314 
2315   result = coap_print_wellknown(context, data, &len, offset, query_filter);
2316   if ((result & COAP_PRINT_STATUS_ERROR) != 0) {
2317     coap_log(LOG_DEBUG, "coap_print_wellknown failed\n");
2318     goto error;
2319   }
2320 
2321   return resp;
2322 
2323 error:
2324   /* set error code 5.03 and remove all options and data from response */
2325   resp->code = COAP_RESPONSE_CODE(503);
2326   resp->used_size = resp->token_length;
2327   return resp;
2328 }
2329 
2330 /**
2331  * This function cancels outstanding messages for the session and
2332  * token specified in @p sent. Any observation relationship for
2333  * sent->session and the token are removed. Calling this function is
2334  * required when receiving an RST message (usually in response to a
2335  * notification) or a GET request with the Observe option set to 1.
2336  *
2337  * This function returns @c 0 when the token is unknown with this
2338  * peer, or a value greater than zero otherwise.
2339  */
2340 static int
coap_cancel(coap_context_t * context,const coap_queue_t * sent)2341 coap_cancel(coap_context_t *context, const coap_queue_t *sent) {
2342   coap_binary_t token = { 0, NULL };
2343   int num_cancelled = 0;    /* the number of observers cancelled */
2344 
2345   /* remove observer for this resource, if any
2346    * get token from sent and try to find a matching resource. Uh!
2347    */
2348 
2349   COAP_SET_STR(&token, sent->pdu->token_length, sent->pdu->token);
2350 
2351   RESOURCES_ITER(context->resources, r) {
2352     coap_cancel_all_messages(context, sent->session, token.s, token.length);
2353     num_cancelled += coap_delete_observer(r, sent->session, &token);
2354   }
2355 
2356   return num_cancelled;
2357 }
2358 
2359 /**
2360  * Internal flags to control the treatment of responses (specifically
2361  * in presence of the No-Response option).
2362  */
2363 enum respond_t { RESPONSE_DEFAULT, RESPONSE_DROP, RESPONSE_SEND };
2364 
2365 /*
2366  * Checks for No-Response option in given @p request and
2367  * returns @c RESPONSE_DROP if @p response should be suppressed
2368  * according to RFC 7967.
2369  *
2370  * If the response is a confirmable piggybacked response and RESPONSE_DROP,
2371  * change it to an empty ACK and @c RESPONSE_SEND so the client does not keep
2372  * on retrying.
2373  *
2374  * Checks if the response code is 0.00 and if either the session is reliable or
2375  * non-confirmable, @c RESPONSE_DROP is also returned.
2376  *
2377  * Multicast response checking is also carried out.
2378  *
2379  * NOTE: It is the responsibility of the application to determine whether
2380  * a delayed separate response should be sent as the original requesting packet
2381  * containing the No-Response option has long since gone.
2382  *
2383  * The value of the No-Response option is encoded as
2384  * follows:
2385  *
2386  * @verbatim
2387  *  +-------+-----------------------+-----------------------------------+
2388  *  | Value | Binary Representation |          Description              |
2389  *  +-------+-----------------------+-----------------------------------+
2390  *  |   0   |      <empty>          | Interested in all responses.      |
2391  *  +-------+-----------------------+-----------------------------------+
2392  *  |   2   |      00000010         | Not interested in 2.xx responses. |
2393  *  +-------+-----------------------+-----------------------------------+
2394  *  |   8   |      00001000         | Not interested in 4.xx responses. |
2395  *  +-------+-----------------------+-----------------------------------+
2396  *  |  16   |      00010000         | Not interested in 5.xx responses. |
2397  *  +-------+-----------------------+-----------------------------------+
2398  * @endverbatim
2399  *
2400  * @param request  The CoAP request to check for the No-Response option.
2401  *                 This parameter must not be NULL.
2402  * @param response The response that is potentially suppressed.
2403  *                 This parameter must not be NULL.
2404  * @param session  The session this request/response are associated with.
2405  *                 This parameter must not be NULL.
2406  * @return RESPONSE_DEFAULT when no special treatment is requested,
2407  *         RESPONSE_DROP    when the response must be discarded, or
2408  *         RESPONSE_SEND    when the response must be sent.
2409  */
2410 static enum respond_t
no_response(coap_pdu_t * request,coap_pdu_t * response,coap_session_t * session)2411 no_response(coap_pdu_t *request, coap_pdu_t *response,
2412             coap_session_t *session) {
2413   coap_opt_t *nores;
2414   coap_opt_iterator_t opt_iter;
2415   unsigned int val = 0;
2416 
2417   assert(request);
2418   assert(response);
2419 
2420   if (COAP_RESPONSE_CLASS(response->code) > 0) {
2421     nores = coap_check_option(request, COAP_OPTION_NORESPONSE, &opt_iter);
2422 
2423     if (nores) {
2424       val = coap_decode_var_bytes(coap_opt_value(nores), coap_opt_length(nores));
2425 
2426       /* The response should be dropped when the bit corresponding to
2427        * the response class is set (cf. table in function
2428        * documentation). When a No-Response option is present and the
2429        * bit is not set, the sender explicitly indicates interest in
2430        * this response. */
2431       if (((1 << (COAP_RESPONSE_CLASS(response->code) - 1)) & val) > 0) {
2432         /* Should be dropping the response */
2433         if (response->type == COAP_MESSAGE_ACK &&
2434             COAP_PROTO_NOT_RELIABLE(session->proto)) {
2435           /* Still need to ACK the request */
2436           response->code = 0;
2437           /* Remove token/data from piggybacked acknowledgment PDU */
2438           response->token_length = 0;
2439           response->used_size = 0;
2440           return RESPONSE_SEND;
2441         }
2442         else {
2443           return RESPONSE_DROP;
2444         }
2445       } else {
2446         /* True for mcast as well RFC7967 2.1 */
2447         return RESPONSE_SEND;
2448       }
2449     }
2450   }
2451   else if (COAP_PDU_IS_EMPTY(response) &&
2452            (response->type == COAP_MESSAGE_NON ||
2453             COAP_PROTO_RELIABLE(session->proto))) {
2454     /* response is 0.00, and this is reliable or non-confirmable */
2455     return RESPONSE_DROP;
2456   }
2457 
2458   /*
2459    * Do not send error responses for requests that were received via
2460    * IP multicast.  RFC7252 8.1
2461    */
2462 
2463   if (coap_is_mcast(&session->addr_info.local)) {
2464     if (request->type == COAP_MESSAGE_NON &&
2465         response->type == COAP_MESSAGE_RST)
2466       return RESPONSE_DROP;
2467 
2468     if (COAP_RESPONSE_CLASS(response->code) > 2)
2469       return RESPONSE_DROP;
2470   }
2471 
2472   /* Default behavior applies when we are not dealing with a response
2473    * (class == 0) or the request did not contain a No-Response option.
2474    */
2475   return RESPONSE_DEFAULT;
2476 }
2477 
2478 static coap_str_const_t coap_default_uri_wellknown =
2479           { sizeof(COAP_DEFAULT_URI_WELLKNOWN)-1,
2480            (const uint8_t *)COAP_DEFAULT_URI_WELLKNOWN };
2481 
2482 static void
handle_request(coap_context_t * context,coap_session_t * session,coap_pdu_t * pdu)2483 handle_request(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu) {
2484   coap_method_handler_t h = NULL;
2485   coap_pdu_t *response = NULL;
2486   coap_opt_filter_t opt_filter;
2487   coap_resource_t *resource = NULL;
2488   /* The respond field indicates whether a response must be treated
2489    * specially due to a No-Response option that declares disinterest
2490    * or interest in a specific response class. DEFAULT indicates that
2491    * No-Response has not been specified. */
2492   enum respond_t respond = RESPONSE_DEFAULT;
2493   coap_opt_iterator_t opt_iter;
2494   coap_opt_t *opt;
2495   int is_proxy_uri = 0;
2496   int is_proxy_scheme = 0;
2497   int skip_hop_limit_check = 0;
2498   int resp;
2499   coap_binary_t token = { pdu->token_length, pdu->token };
2500 #ifndef WITHOUT_ASYNC
2501   coap_bin_const_t tokenc = { pdu->token_length, pdu->token };
2502   coap_async_t *async;
2503 #endif /* WITHOUT_ASYNC */
2504 
2505   if (coap_is_mcast(&session->addr_info.local)) {
2506     if (COAP_PROTO_RELIABLE(session->proto) || pdu->type != COAP_MESSAGE_NON) {
2507       coap_log(LOG_INFO, "Invalid multicast packet received RFC7252 8.1\n");
2508       return;
2509     }
2510   }
2511 #ifndef WITHOUT_ASYNC
2512   async = coap_find_async(session, tokenc);
2513   if (async) {
2514     coap_tick_t now;
2515 
2516     coap_ticks(&now);
2517     if (async->delay == 0 || async->delay > now) {
2518       /* re-transmit missing ACK (only if CON) */
2519       coap_log(LOG_INFO, "Retransmit async response\n");
2520       coap_send_ack(session, pdu);
2521       /* and do not pass on to the upper layers */
2522       return;
2523     }
2524   }
2525   else if (coap_is_mcast(&session->addr_info.local)) {
2526     uint8_t r;
2527     coap_tick_t delay;
2528 
2529     /* Need to delay sending mcast request to application layer, so response
2530        is not immediate. */
2531     coap_prng(&r, sizeof(r));
2532     delay = (COAP_DEFAULT_LEISURE * COAP_TICKS_PER_SECOND * r) / 256;
2533     /* Register request to be internally re-transmitted after delay */
2534     if (coap_register_async(session, pdu, delay))
2535       return;
2536   }
2537 #endif /* WITHOUT_ASYNC */
2538 
2539   coap_option_filter_clear(&opt_filter);
2540   opt = coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter);
2541   if (opt)
2542     is_proxy_scheme = 1;
2543 
2544   opt = coap_check_option(pdu, COAP_OPTION_PROXY_URI, &opt_iter);
2545   if (opt)
2546     is_proxy_uri = 1;
2547 
2548   if (is_proxy_scheme || is_proxy_uri) {
2549     coap_uri_t uri;
2550 
2551     if (!context->proxy_uri_resource) {
2552       /* Need to return a 5.05 RFC7252 Section 5.7.2 */
2553       coap_log(LOG_DEBUG, "Proxy-%s support not configured\n",
2554                is_proxy_scheme ? "Scheme" : "Uri");
2555       resp = 505;
2556       goto fail_response;
2557     }
2558     if (((size_t)pdu->code - 1 <
2559                 (sizeof(resource->handler) / sizeof(resource->handler[0]))) &&
2560         !(context->proxy_uri_resource->handler[pdu->code - 1])) {
2561       /* Need to return a 5.05 RFC7252 Section 5.7.2 */
2562       coap_log(LOG_DEBUG, "Proxy-%s code %d.%02d handler not supported\n",
2563                is_proxy_scheme ? "Scheme" : "Uri",
2564                pdu->code/100,  pdu->code%100);
2565       resp = 505;
2566       goto fail_response;
2567     }
2568 
2569     /* Need to check if authority is the proxy endpoint RFC7252 Section 5.7.2 */
2570     if (is_proxy_uri) {
2571       if (coap_split_proxy_uri(coap_opt_value(opt),
2572                                coap_opt_length(opt), &uri) < 0) {
2573         /* Need to return a 5.05 RFC7252 Section 5.7.2 */
2574         coap_log(LOG_DEBUG, "Proxy-URI not decodable\n");
2575         resp = 505;
2576         goto fail_response;
2577       }
2578     }
2579     else {
2580       memset(&uri, 0, sizeof(uri));
2581       opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
2582       if (opt) {
2583         uri.host.length = coap_opt_length(opt);
2584         uri.host.s = coap_opt_value(opt);
2585       }
2586     }
2587     resource = context->proxy_uri_resource;
2588     if (uri.host.length && resource->proxy_name_count && resource->proxy_name_list) {
2589       size_t i;
2590       for (i = 0; i < resource->proxy_name_count; i++) {
2591         if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
2592           break;
2593         }
2594       }
2595       if (i != resource->proxy_name_count) {
2596         /* This server is hosting the proxy connection endpoint */
2597         is_proxy_uri = 0;
2598         is_proxy_scheme = 0;
2599         skip_hop_limit_check = 1;
2600       }
2601     }
2602     resource = NULL;
2603   }
2604 
2605   if (!skip_hop_limit_check) {
2606     opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
2607     if (opt) {
2608       size_t hop_limit;
2609       uint8_t buf[4];
2610 
2611       hop_limit =
2612         coap_decode_var_bytes (coap_opt_value (opt), coap_opt_length (opt));
2613       if (hop_limit == 1) {
2614         /* coap_send_internal() will fill in the IP address for us */
2615         resp = 508;
2616         goto fail_response;
2617       }
2618       else if (hop_limit < 1 || hop_limit > 255) {
2619         /* Need to return a 4.00 RFC8768 Section 3 */
2620         coap_log(LOG_INFO, "Invalid Hop Limit\n");
2621         resp = 400;
2622         goto fail_response;
2623       }
2624       hop_limit--;
2625       coap_update_option(pdu, COAP_OPTION_HOP_LIMIT,
2626                          coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
2627                          buf);
2628     }
2629   }
2630 
2631   coap_string_t *uri_path = coap_get_uri_path(pdu);
2632   if (!uri_path)
2633     return;
2634 
2635   if (!is_proxy_uri && !is_proxy_scheme) {
2636     /* try to find the resource from the request URI */
2637     coap_str_const_t uri_path_c = { uri_path->length, uri_path->s };
2638     resource = coap_get_resource_from_uri_path(context, &uri_path_c);
2639   }
2640 
2641   if ((resource == NULL) || (resource->is_unknown == 1) ||
2642       (resource->is_proxy_uri == 1)) {
2643     /* The resource was not found or there is an unexpected match against the
2644      * resource defined for handling unknown or proxy URIs.
2645      * Check if the request URI happens to be the well-known URI, or if the
2646      * unknown resource handler is defined, a PUT or optionally other methods,
2647      * if configured, for the unknown handler.
2648      *
2649      * if well-known URI generate a default response
2650      *
2651      * else if a PROXY URI/Scheme request and proxy URI handler defined, call the
2652      *  proxy URI handler
2653      *
2654      * else if unknown URI handler defined, call the unknown
2655      *  URI handler (to allow for potential generation of resource
2656      *  [RFC7272 5.8.3]) if the appropriate method is defined.
2657      *
2658      * else if DELETE return 2.02 (RFC7252: 5.8.4.  DELETE)
2659      *
2660      * else return 4.04 */
2661 
2662     if (coap_string_equal(uri_path, &coap_default_uri_wellknown)) {
2663       /* request for .well-known/core */
2664       if (pdu->code == COAP_REQUEST_CODE_GET) { /* GET */
2665         coap_log(LOG_INFO, "create default response for %s\n",
2666                  COAP_DEFAULT_URI_WELLKNOWN);
2667         response = coap_wellknown_response(context, session, pdu);
2668       } else {
2669         coap_log(LOG_DEBUG, "method not allowed for .well-known/core\n");
2670         response = coap_new_error_response(pdu, COAP_RESPONSE_CODE(405),
2671           &opt_filter);
2672       }
2673     } else if (is_proxy_uri || is_proxy_scheme) {
2674       resource = context->proxy_uri_resource;
2675     } else if ((context->unknown_resource != NULL) &&
2676                ((size_t)pdu->code - 1 <
2677                 (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
2678                (context->unknown_resource->handler[pdu->code - 1])) {
2679       /*
2680        * The unknown_resource can be used to handle undefined resources
2681        * for a PUT request and can support any other registered handler
2682        * defined for it
2683        * Example set up code:-
2684        *   r = coap_resource_unknown_init(hnd_put_unknown);
2685        *   coap_register_handler(r, COAP_REQUEST_POST, hnd_post_unknown);
2686        *   coap_register_handler(r, COAP_REQUEST_GET, hnd_get_unknown);
2687        *   coap_register_handler(r, COAP_REQUEST_DELETE, hnd_delete_unknown);
2688        *   coap_add_resource(ctx, r);
2689        *
2690        * Note: It is not possible to observe the unknown_resource, a separate
2691        *       resource must be created (by PUT or POST) which has a GET
2692        *       handler to be observed
2693        */
2694       resource = context->unknown_resource;
2695     } else if (pdu->code == COAP_REQUEST_CODE_DELETE) {
2696       /*
2697        * Request for DELETE on non-existant resource (RFC7252: 5.8.4.  DELETE)
2698        */
2699       coap_log(LOG_DEBUG, "request for unknown resource '%*.*s',"
2700                           " return 2.02\n",
2701                           (int)uri_path->length,
2702                           (int)uri_path->length,
2703                           uri_path->s);
2704       response =
2705         coap_new_error_response(pdu, COAP_RESPONSE_CODE(202),
2706           &opt_filter);
2707     } else { /* request for any another resource, return 4.04 */
2708 
2709       coap_log(LOG_DEBUG, "request for unknown resource '%*.*s', return 4.04\n",
2710                (int)uri_path->length, (int)uri_path->length, uri_path->s);
2711       response =
2712         coap_new_error_response(pdu, COAP_RESPONSE_CODE(404),
2713           &opt_filter);
2714     }
2715 
2716     if (!resource) {
2717       if (response && (no_response(pdu, response, session) != RESPONSE_DROP)) {
2718         coap_mid_t mid = pdu->mid;
2719         if (coap_send_internal(session, response) == COAP_INVALID_MID)
2720           coap_log(LOG_WARNING, "cannot send response for mid=0x%x\n", mid);
2721       } else {
2722         coap_delete_pdu(response);
2723       }
2724 
2725       response = NULL;
2726 
2727       coap_delete_string(uri_path);
2728       return;
2729     } else {
2730       if (response) {
2731         /* Need to delete unused response - it will get re-created further on */
2732         coap_delete_pdu(response);
2733       }
2734     }
2735   }
2736 
2737   /* the resource was found, check if there is a registered handler */
2738   if ((size_t)pdu->code - 1 <
2739     sizeof(resource->handler) / sizeof(coap_method_handler_t))
2740     h = resource->handler[pdu->code - 1];
2741 
2742   if (h) {
2743      coap_log(LOG_DEBUG, "call custom handler for resource '%*.*s'\n",
2744               (int)resource->uri_path->length, (int)resource->uri_path->length,
2745               resource->uri_path->s);
2746     response = coap_pdu_init(pdu->type == COAP_MESSAGE_CON
2747       ? COAP_MESSAGE_ACK
2748       : COAP_MESSAGE_NON,
2749       0, pdu->mid, coap_session_max_pdu_size(session));
2750 
2751     /* Implementation detail: coap_add_token() immediately returns 0
2752        if response == NULL */
2753     if (coap_add_token(response, pdu->token_length, pdu->token)) {
2754       coap_opt_t *observe = NULL;
2755       int observe_action = COAP_OBSERVE_CANCEL;
2756       coap_string_t *query = coap_get_query(pdu);
2757       coap_block_t block;
2758       int added_block = 0;
2759 
2760       /* check for Observe option RFC7641 and RFC8132 */
2761       if (resource->observable &&
2762           (pdu->code == COAP_REQUEST_CODE_GET ||
2763            pdu->code == COAP_REQUEST_CODE_FETCH)) {
2764         observe = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
2765         if (observe) {
2766           observe_action =
2767             coap_decode_var_bytes(coap_opt_value(observe),
2768               coap_opt_length(observe));
2769 
2770           if (observe_action == COAP_OBSERVE_ESTABLISH) {
2771             coap_subscription_t *subscription;
2772 
2773             if (coap_get_block(pdu, COAP_OPTION_BLOCK2, &block)) {
2774               if (block.num != 0) {
2775                 response->code = COAP_RESPONSE_CODE(400);
2776                 goto skip_handler;
2777               }
2778             }
2779             subscription = coap_add_observer(resource, session, &token,
2780                                              pdu);
2781             if (subscription) {
2782               uint8_t buf[4];
2783 
2784               coap_touch_observer(context, session, &token);
2785               coap_add_option(response, COAP_OPTION_OBSERVE,
2786                               coap_encode_var_safe(buf, sizeof (buf),
2787                                                    resource->observe),
2788                               buf);
2789             }
2790           }
2791           else if (observe_action == COAP_OBSERVE_CANCEL) {
2792             coap_delete_observer(resource, session, &token);
2793           }
2794           else {
2795             coap_log(LOG_INFO, "observe: unexpected action %d\n", observe_action);
2796           }
2797         }
2798       }
2799 
2800       if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
2801         if (coap_handle_request_put_block(context, session, pdu, response,
2802                                           resource, uri_path, observe,
2803                                           query, h, &added_block)) {
2804           goto skip_handler;
2805         }
2806 
2807         if (coap_handle_request_send_block(session, pdu, response, resource,
2808                                            query)) {
2809           goto skip_handler;
2810         }
2811       }
2812 
2813       /*
2814        * Call the request handler with everything set up
2815        */
2816       h(resource, session, pdu, query, response);
2817 
2818       /* Check if lg_xmit generated and update PDU code if so */
2819       coap_check_code_lg_xmit(session, response, resource, query);
2820 
2821 skip_handler:
2822       respond = no_response(pdu, response, session);
2823       if (respond != RESPONSE_DROP) {
2824         coap_mid_t mid = pdu->mid;
2825         if (COAP_RESPONSE_CLASS(response->code) != 2) {
2826           if (observe) {
2827             coap_remove_option(response, COAP_OPTION_OBSERVE);
2828           }
2829         }
2830         if (COAP_RESPONSE_CLASS(response->code) > 2) {
2831           if (observe)
2832             coap_delete_observer(resource, session, &token);
2833           if (added_block)
2834             coap_remove_option(pdu, COAP_OPTION_BLOCK1);
2835         }
2836 
2837         /* If original request contained a token, and the registered
2838          * application handler made no changes to the response, then
2839          * this is an empty ACK with a token, which is a malformed
2840          * PDU */
2841         if ((response->type == COAP_MESSAGE_ACK)
2842           && (response->code == 0)) {
2843           /* Remove token from otherwise-empty acknowledgment PDU */
2844           response->token_length = 0;
2845           response->used_size = 0;
2846         }
2847 
2848         if (coap_send_internal(session, response) == COAP_INVALID_MID) {
2849           coap_log(LOG_DEBUG, "cannot send response for mid=0x%x\n", mid);
2850         }
2851       } else {
2852         coap_delete_pdu(response);
2853       }
2854       if (query)
2855         coap_delete_string(query);
2856     } else {
2857       coap_log(LOG_WARNING, "cannot generate response\r\n");
2858       coap_delete_pdu(response);
2859     }
2860     response = NULL;
2861   } else {
2862     if (coap_string_equal(uri_path, &coap_default_uri_wellknown)) {
2863       /* request for .well-known/core */
2864       coap_log(LOG_DEBUG, "create default response for %s\n",
2865                COAP_DEFAULT_URI_WELLKNOWN);
2866       response = coap_wellknown_response(context, session, pdu);
2867       coap_log(LOG_DEBUG, "have wellknown response %p\n", (void *)response);
2868     } else
2869       response = coap_new_error_response(pdu, COAP_RESPONSE_CODE(405),
2870         &opt_filter);
2871 
2872     if (response && (no_response(pdu, response, session) != RESPONSE_DROP)) {
2873       coap_mid_t mid = pdu->mid;
2874       if (coap_send_internal(session, response) == COAP_INVALID_MID)
2875         coap_log(LOG_DEBUG, "cannot send response for mid=0x%x\n", mid);
2876     } else {
2877       coap_delete_pdu(response);
2878     }
2879     response = NULL;
2880   }
2881 
2882   assert(response == NULL);
2883   coap_delete_string(uri_path);
2884   return;
2885 
2886 fail_response:
2887   response =
2888      coap_new_error_response(pdu, COAP_RESPONSE_CODE(resp),
2889        &opt_filter);
2890   if (response) {
2891     coap_mid_t mid = pdu->mid;
2892     if (coap_send_internal(session, response) == COAP_INVALID_MID)
2893       coap_log(LOG_WARNING, "cannot send response for mid=0x%x\n", mid);
2894   }
2895 }
2896 
2897 static void
handle_response(coap_context_t * context,coap_session_t * session,coap_pdu_t * sent,coap_pdu_t * rcvd)2898 handle_response(coap_context_t *context, coap_session_t *session,
2899   coap_pdu_t *sent, coap_pdu_t *rcvd) {
2900 
2901   /* In a lossy context, the ACK of a separate response may have
2902    * been lost, so we need to stop retransmitting requests with the
2903    * same token.
2904    */
2905   coap_cancel_all_messages(context, session, rcvd->token, rcvd->token_length);
2906 
2907   if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
2908     /* See if need to send next block to server */
2909     if (coap_handle_response_send_block(session, rcvd)) {
2910       /* Next block transmitted, no need to inform app */
2911       coap_send_ack(session, rcvd);
2912       return;
2913     }
2914 
2915     /* Need to see if needing to request next block */
2916     if (coap_handle_response_get_block(context, session, sent, rcvd,
2917                                        COAP_RECURSE_OK)) {
2918       /* Next block requested, no need to inform app */
2919       coap_send_ack(session, rcvd);
2920       return;
2921     }
2922   }
2923 
2924   /* Call application-specific response handler when available. */
2925   if (context->response_handler) {
2926     if (context->response_handler(session, sent, rcvd,
2927                                   rcvd->mid) == COAP_RESPONSE_FAIL)
2928       coap_send_rst(session, rcvd);
2929     else
2930       coap_send_ack(session, rcvd);
2931   }
2932   else {
2933     coap_send_ack(session, rcvd);
2934   }
2935 }
2936 
2937 #if !COAP_DISABLE_TCP
2938 static void
handle_signaling(coap_context_t * context,coap_session_t * session,coap_pdu_t * pdu)2939 handle_signaling(coap_context_t *context, coap_session_t *session,
2940   coap_pdu_t *pdu) {
2941   coap_opt_iterator_t opt_iter;
2942   coap_opt_t *option;
2943   (void)context;
2944 
2945   coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
2946 
2947   if (pdu->code == COAP_SIGNALING_CODE_CSM) {
2948     while ((option = coap_option_next(&opt_iter))) {
2949       if (opt_iter.number == COAP_SIGNALING_OPTION_MAX_MESSAGE_SIZE) {
2950         coap_session_set_mtu(session, coap_decode_var_bytes(coap_opt_value(option),
2951           coap_opt_length(option)));
2952       } else if (opt_iter.number == COAP_SIGNALING_OPTION_BLOCK_WISE_TRANSFER) {
2953         session->csm_block_supported = 1;
2954       }
2955     }
2956     if (session->state == COAP_SESSION_STATE_CSM)
2957       coap_session_connected(session);
2958   } else if (pdu->code == COAP_SIGNALING_CODE_PING) {
2959     coap_pdu_t *pong = coap_pdu_init(COAP_MESSAGE_CON, COAP_SIGNALING_CODE_PONG, 0, 1);
2960     if (context->ping_handler) {
2961       context->ping_handler(session, pdu, pdu->mid);
2962     }
2963     if (pong) {
2964       coap_add_option(pong, COAP_SIGNALING_OPTION_CUSTODY, 0, NULL);
2965       coap_send_internal(session, pong);
2966     }
2967   } else if (pdu->code == COAP_SIGNALING_CODE_PONG) {
2968     session->last_pong = session->last_rx_tx;
2969     if (context->pong_handler) {
2970       context->pong_handler(session, pdu, pdu->mid);
2971     }
2972   } else if (pdu->code == COAP_SIGNALING_CODE_RELEASE
2973           || pdu->code == COAP_SIGNALING_CODE_ABORT) {
2974     coap_session_disconnected(session, COAP_NACK_RST);
2975   }
2976 }
2977 #endif /* !COAP_DISABLE_TCP */
2978 
2979 void
coap_dispatch(coap_context_t * context,coap_session_t * session,coap_pdu_t * pdu)2980 coap_dispatch(coap_context_t *context, coap_session_t *session,
2981   coap_pdu_t *pdu) {
2982   coap_queue_t *sent = NULL;
2983   coap_pdu_t *response;
2984   coap_opt_filter_t opt_filter;
2985   int is_ping_rst;
2986 
2987   if (LOG_DEBUG <= coap_get_log_level()) {
2988     /* FIXME: get debug to work again **
2989     unsigned char addr[INET6_ADDRSTRLEN+8], localaddr[INET6_ADDRSTRLEN+8];
2990     if (coap_print_addr(remote, addr, INET6_ADDRSTRLEN+8) &&
2991         coap_print_addr(&packet->dst, localaddr, INET6_ADDRSTRLEN+8) )
2992       coap_log(LOG_DEBUG, "** received %d bytes from %s on interface %s:\n",
2993             (int)msg_len, addr, localaddr);
2994 
2995             */
2996     coap_show_pdu(LOG_DEBUG, pdu);
2997   }
2998 
2999   memset(&opt_filter, 0, sizeof(coap_opt_filter_t));
3000 
3001   switch (pdu->type) {
3002     case COAP_MESSAGE_ACK:
3003       /* find message id in sendqueue to stop retransmission */
3004       coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
3005 
3006       if (sent && session->con_active) {
3007         session->con_active--;
3008         if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3009           /* Flush out any entries on session->delayqueue */
3010           coap_session_connected(session);
3011       }
3012       if (coap_option_check_critical(context, pdu, &opt_filter) == 0)
3013         goto cleanup;
3014 
3015       /* if sent code was >= 64 the message might have been a
3016        * notification. Then, we must flag the observer to be alive
3017        * by setting obs->fail_cnt = 0. */
3018       if (sent && COAP_RESPONSE_CLASS(sent->pdu->code) == 2) {
3019         const coap_binary_t token =
3020         { sent->pdu->token_length, sent->pdu->token };
3021         coap_touch_observer(context, sent->session, &token);
3022       }
3023 
3024       if (pdu->code == 0) {
3025         /* an empty ACK needs no further handling */
3026         goto cleanup;
3027       }
3028 
3029       break;
3030 
3031     case COAP_MESSAGE_RST:
3032       /* We have sent something the receiver disliked, so we remove
3033        * not only the message id but also the subscriptions we might
3034        * have. */
3035 
3036       is_ping_rst = 0;
3037       if (pdu->mid == session->last_ping_mid &&
3038           context->ping_timeout && session->last_ping > 0)
3039         is_ping_rst = 1;
3040 
3041       if (!is_ping_rst)
3042         coap_log(LOG_ALERT, "got RST for mid=0x%x\n", pdu->mid);
3043 
3044       if (session->con_active) {
3045         session->con_active--;
3046         if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3047           /* Flush out any entries on session->delayqueue */
3048           coap_session_connected(session);
3049       }
3050 
3051       /* find message id in sendqueue to stop retransmission */
3052       coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
3053 
3054       if (sent) {
3055         coap_cancel(context, sent);
3056 
3057         if (!is_ping_rst) {
3058           if(sent->pdu->type==COAP_MESSAGE_CON && context->nack_handler)
3059             context->nack_handler(sent->session, sent->pdu,
3060                                   COAP_NACK_RST, sent->id);
3061         }
3062         else {
3063           if (context->pong_handler) {
3064             context->pong_handler(session, pdu, pdu->mid);
3065           }
3066           session->last_pong = session->last_rx_tx;
3067           session->last_ping_mid = COAP_INVALID_MID;
3068         }
3069       }
3070       else {
3071         /* Need to check is there is a subscription active and delete it */
3072         RESOURCES_ITER(context->resources, r) {
3073           coap_subscription_t *obs, *tmp;
3074           LL_FOREACH_SAFE(r->subscribers, obs, tmp) {
3075             if (obs->pdu->mid == pdu->mid && obs->session == session) {
3076               coap_binary_t token = { 0, NULL };
3077               COAP_SET_STR(&token, obs->pdu->token_length, obs->pdu->token);
3078               coap_delete_observer(r, session, &token);
3079               goto cleanup;
3080             }
3081           }
3082         }
3083       }
3084       goto cleanup;
3085 
3086     case COAP_MESSAGE_NON:
3087       /* find transaction in sendqueue in case large response */
3088       coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
3089       /* check for unknown critical options */
3090       if (coap_option_check_critical(context, pdu, &opt_filter) == 0) {
3091         coap_send_rst(session, pdu);
3092         goto cleanup;
3093       }
3094       break;
3095 
3096     case COAP_MESSAGE_CON:        /* check for unknown critical options */
3097       if (coap_option_check_critical(context, pdu, &opt_filter) == 0) {
3098 
3099         if (COAP_PDU_IS_REQUEST(pdu)) {
3100           response =
3101             coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
3102 
3103           if (!response) {
3104             coap_log(LOG_WARNING,
3105                      "coap_dispatch: cannot create error response\n");
3106           } else {
3107             if (coap_send_internal(session, response) == COAP_INVALID_MID)
3108               coap_log(LOG_WARNING, "coap_dispatch: error sending response\n");
3109           }
3110         }
3111         else {
3112           coap_send_rst(session, pdu);
3113         }
3114 
3115         goto cleanup;
3116       }
3117     default: break;
3118   }
3119 
3120   /* Pass message to upper layer if a specific handler was
3121     * registered for a request that should be handled locally. */
3122 #if !COAP_DISABLE_TCP
3123   if (COAP_PDU_IS_SIGNALING(pdu))
3124     handle_signaling(context, session, pdu);
3125   else
3126 #endif /* !COAP_DISABLE_TCP */
3127   if (COAP_PDU_IS_REQUEST(pdu))
3128     handle_request(context, session, pdu);
3129   else if (COAP_PDU_IS_RESPONSE(pdu))
3130     handle_response(context, session, sent ? sent->pdu : NULL, pdu);
3131   else {
3132     if (COAP_PDU_IS_EMPTY(pdu)) {
3133       if (context->ping_handler) {
3134         context->ping_handler(session, pdu, pdu->mid);
3135       }
3136     }
3137     coap_log(LOG_DEBUG, "dropped message with invalid code (%d.%02d)\n",
3138              COAP_RESPONSE_CLASS(pdu->code),
3139       pdu->code & 0x1f);
3140 
3141     if (!coap_is_mcast(&session->addr_info.local)) {
3142       if (COAP_PDU_IS_EMPTY(pdu)) {
3143         if (session->proto != COAP_PROTO_TCP && session->proto != COAP_PROTO_TLS) {
3144           coap_tick_t now;
3145           coap_ticks(&now);
3146           if (session->last_tx_rst + COAP_TICKS_PER_SECOND/4 < now) {
3147             coap_send_message_type(session, pdu, COAP_MESSAGE_RST);
3148             session->last_tx_rst = now;
3149           }
3150         }
3151       }
3152       else {
3153         coap_send_message_type(session, pdu, COAP_MESSAGE_RST);
3154       }
3155     }
3156   }
3157 
3158 cleanup:
3159   coap_delete_node(sent);
3160 }
3161 
3162 int
coap_handle_event(coap_context_t * context,coap_event_t event,coap_session_t * session)3163 coap_handle_event(coap_context_t *context, coap_event_t event, coap_session_t *session) {
3164   coap_log(LOG_DEBUG, "***EVENT: 0x%04x\n", event);
3165 
3166   if (context->handle_event) {
3167     return context->handle_event(session, event);
3168   } else {
3169     return 0;
3170   }
3171 }
3172 
3173 int
coap_can_exit(coap_context_t * context)3174 coap_can_exit(coap_context_t *context) {
3175   coap_endpoint_t *ep;
3176   coap_session_t *s, *rtmp;
3177   if (!context)
3178     return 1;
3179   if (context->sendqueue)
3180     return 0;
3181   LL_FOREACH(context->endpoint, ep) {
3182     SESSIONS_ITER(ep->sessions, s, rtmp) {
3183       if (s->delayqueue)
3184         return 0;
3185       if (s->lg_xmit)
3186         return 0;
3187     }
3188   }
3189   SESSIONS_ITER(context->sessions, s, rtmp) {
3190     if (s->delayqueue)
3191       return 0;
3192     if (s->lg_xmit)
3193       return 0;
3194   }
3195   return 1;
3196 }
3197 #ifndef WITHOUT_ASYNC
3198 coap_tick_t
coap_check_async(coap_context_t * context,coap_tick_t now)3199 coap_check_async(coap_context_t *context, coap_tick_t now) {
3200   coap_tick_t next_due = 0;
3201   coap_async_t *async, *tmp;
3202 
3203   LL_FOREACH_SAFE(context->async_state, async, tmp) {
3204     if (async->delay <= now) {
3205       /* Send off the request to the application */
3206       handle_request(context, async->session, async->pdu);
3207 
3208       /* Remove this async entry as it has now fired */
3209       coap_free_async(async->session, async);
3210     }
3211     else {
3212       if (next_due == 0 || next_due > async->delay - now)
3213         next_due = async->delay - now;
3214     }
3215   }
3216   return next_due;
3217 }
3218 #endif /* WITHOUT_ASYNC */
3219 
3220 static int coap_started = 0;
3221 
coap_startup(void)3222 void coap_startup(void) {
3223   coap_tick_t now;
3224   uint64_t us;
3225   if (coap_started)
3226     return;
3227   coap_started = 1;
3228 #if defined(HAVE_WINSOCK2_H)
3229   WORD wVersionRequested = MAKEWORD(2, 2);
3230   WSADATA wsaData;
3231   WSAStartup(wVersionRequested, &wsaData);
3232 #endif
3233   coap_clock_init();
3234   coap_ticks(&now);
3235   us = coap_ticks_to_rt_us(now);
3236   /* Be accurate to the nearest (approx) us */
3237   coap_prng_init((unsigned int)us);
3238   coap_memory_init();
3239   coap_dtls_startup();
3240 }
3241 
coap_cleanup(void)3242 void coap_cleanup(void) {
3243 #if defined(HAVE_WINSOCK2_H)
3244   WSACleanup();
3245 #endif
3246   coap_dtls_shutdown();
3247 }
3248 
3249 void
coap_register_response_handler(coap_context_t * context,coap_response_handler_t handler)3250 coap_register_response_handler(coap_context_t *context,
3251                                coap_response_handler_t handler) {
3252   context->response_handler = handler;
3253 }
3254 
3255 void
coap_register_nack_handler(coap_context_t * context,coap_nack_handler_t handler)3256 coap_register_nack_handler(coap_context_t *context,
3257                            coap_nack_handler_t handler) {
3258   context->nack_handler = handler;
3259 }
3260 
3261 void
coap_register_ping_handler(coap_context_t * context,coap_ping_handler_t handler)3262 coap_register_ping_handler(coap_context_t *context,
3263                            coap_ping_handler_t handler) {
3264   context->ping_handler = handler;
3265 }
3266 
3267 void
coap_register_pong_handler(coap_context_t * context,coap_pong_handler_t handler)3268 coap_register_pong_handler(coap_context_t *context,
3269                            coap_pong_handler_t handler) {
3270   context->pong_handler = handler;
3271 }
3272 
3273 void
coap_register_option(coap_context_t * ctx,uint16_t type)3274 coap_register_option(coap_context_t *ctx, uint16_t type) {
3275   coap_option_filter_set(&ctx->known_options, type);
3276 }
3277 
3278 #if ! defined WITH_CONTIKI && ! defined WITH_LWIP && ! defined RIOT_VERSION
3279 int
coap_join_mcast_group_intf(coap_context_t * ctx,const char * group_name,const char * ifname)3280 coap_join_mcast_group_intf(coap_context_t *ctx, const char *group_name,
3281                            const char *ifname) {
3282   struct ip_mreq mreq4;
3283   struct ipv6_mreq mreq6;
3284   struct addrinfo *resmulti = NULL, hints, *ainfo;
3285   int result = -1;
3286   coap_endpoint_t *endpoint;
3287   int mgroup_setup = 0;
3288 
3289   /* Need to have at least one endpoint! */
3290   assert(ctx->endpoint);
3291   if (!ctx->endpoint)
3292     return -1;
3293 
3294   /* Default is let the kernel choose */
3295   mreq6.ipv6mr_interface = 0;
3296   mreq4.imr_interface.s_addr = INADDR_ANY;
3297 
3298   memset(&hints, 0, sizeof(hints));
3299   hints.ai_socktype = SOCK_DGRAM;
3300 
3301   /* resolve the multicast group address */
3302   result = getaddrinfo(group_name, NULL, &hints, &resmulti);
3303 
3304   if (result != 0) {
3305     coap_log(LOG_ERR,
3306              "coap_join_mcast_group_intf: %s: "
3307               "Cannot resolve multicast address: %s\n",
3308              group_name, gai_strerror(result));
3309     goto finish;
3310   }
3311 
3312 /* Need to do a windows equivalent at some point */
3313 #ifndef _WIN32
3314   if (ifname) {
3315     /* interface specified - check if we have correct IPv4/IPv6 information */
3316     int done_ip4 = 0;
3317     int done_ip6 = 0;
3318 #if defined(ESPIDF_VERSION)
3319     struct netif *netif;
3320 #else /* !ESPIDF_VERSION */
3321     int ip4fd;
3322     struct ifreq ifr;
3323 #endif /* !ESPIDF_VERSION */
3324 
3325     /* See which mcast address family types are being asked for */
3326     for (ainfo = resmulti; ainfo != NULL && !(done_ip4 == 1 && done_ip6 == 1);
3327          ainfo = ainfo->ai_next) {
3328       switch (ainfo->ai_family) {
3329       case AF_INET6:
3330         if (done_ip6)
3331           break;
3332         done_ip6 = 1;
3333 #if defined(ESPIDF_VERSION)
3334         netif = netif_find(ifname);
3335         if (netif)
3336           mreq6.ipv6mr_interface = netif_get_index(netif);
3337         else
3338           coap_log(LOG_ERR,
3339                    "coap_join_mcast_group_intf: %s: "
3340                     "Cannot get IPv4 address: %s\n",
3341                     ifname, coap_socket_strerror());
3342 #else /* !ESPIDF_VERSION */
3343         memset (&ifr, 0, sizeof(ifr));
3344         strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
3345         ifr.ifr_name[IFNAMSIZ - 1] = '\000';
3346 
3347 #ifdef HAVE_IF_NAMETOINDEX
3348         mreq6.ipv6mr_interface = if_nametoindex(ifr.ifr_name);
3349         if (mreq6.ipv6mr_interface == 0) {
3350           coap_log(LOG_WARNING, "coap_join_mcast_group_intf: "
3351                     "cannot get interface index for '%s'\n",
3352                    ifname);
3353         }
3354 #else /* !HAVE_IF_NAMETOINDEX */
3355         result = ioctl(ctx->endpoint->sock.fd, SIOCGIFINDEX, &ifr);
3356         if (result != 0) {
3357           coap_log(LOG_WARNING, "coap_join_mcast_group_intf: "
3358                     "cannot get interface index for '%s': %s\n",
3359                    ifname, coap_socket_strerror());
3360         }
3361         else {
3362           /* Capture the IPv6 if_index for later */
3363           mreq6.ipv6mr_interface = ifr.ifr_ifindex;
3364         }
3365 #endif /* !HAVE_IF_NAMETOINDEX */
3366 #endif /* !ESPIDF_VERSION */
3367         break;
3368       case AF_INET:
3369         if (done_ip4)
3370           break;
3371         done_ip4 = 1;
3372 #if defined(ESPIDF_VERSION)
3373         netif = netif_find(ifname);
3374         if (netif)
3375           mreq4.imr_interface.s_addr = netif_ip4_addr(netif)->addr;
3376         else
3377           coap_log(LOG_ERR,
3378                    "coap_join_mcast_group_intf: %s: "
3379                     "Cannot get IPv4 address: %s\n",
3380                     ifname, coap_socket_strerror());
3381 #else /* !ESPIDF_VERSION */
3382         /*
3383          * Need an AF_INET socket to do this unfortunately to stop
3384          * "Invalid argument" error if AF_INET6 socket is used for SIOCGIFADDR
3385          */
3386         ip4fd = socket(AF_INET, SOCK_DGRAM, 0);
3387         if (ip4fd == -1) {
3388           coap_log(LOG_ERR,
3389                    "coap_join_mcast_group_intf: %s: socket: %s\n",
3390                    ifname, coap_socket_strerror());
3391           continue;
3392         }
3393         memset (&ifr, 0, sizeof(ifr));
3394         strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
3395         ifr.ifr_name[IFNAMSIZ - 1] = '\000';
3396         result = ioctl(ip4fd, SIOCGIFADDR, &ifr);
3397         if (result != 0) {
3398           coap_log(LOG_ERR,
3399                    "coap_join_mcast_group_intf: %s: "
3400                     "Cannot get IPv4 address: %s\n",
3401                     ifname, coap_socket_strerror());
3402         }
3403         else {
3404           /* Capture the IPv4 address for later */
3405           mreq4.imr_interface = ((struct sockaddr_in*)&ifr.ifr_addr)->sin_addr;
3406         }
3407         close(ip4fd);
3408 #endif /* !ESPIDF_VERSION */
3409         break;
3410       default:
3411         break;
3412       }
3413     }
3414   }
3415 #endif /* ! _WIN32 */
3416 
3417   /* Add in mcast address(es) to appropriate interface */
3418   for (ainfo = resmulti; ainfo != NULL; ainfo = ainfo->ai_next) {
3419     LL_FOREACH(ctx->endpoint, endpoint) {
3420       /* Only UDP currently supported */
3421       if (endpoint->proto == COAP_PROTO_UDP) {
3422         coap_address_t gaddr;
3423 
3424         coap_address_init(&gaddr);
3425         if (ainfo->ai_family == AF_INET6) {
3426           if (!ifname) {
3427             if(endpoint->bind_addr.addr.sa.sa_family == AF_INET6) {
3428               /*
3429                * Do it on the ifindex that the server is listening on
3430                * (sin6_scope_id could still be 0)
3431                */
3432               mreq6.ipv6mr_interface =
3433                                  endpoint->bind_addr.addr.sin6.sin6_scope_id;
3434             }
3435             else {
3436               mreq6.ipv6mr_interface = 0;
3437             }
3438           }
3439           gaddr.addr.sin6.sin6_family = AF_INET6;
3440           gaddr.addr.sin6.sin6_port = endpoint->bind_addr.addr.sin6.sin6_port;
3441           gaddr.addr.sin6.sin6_addr = mreq6.ipv6mr_multiaddr =
3442                     ((struct sockaddr_in6 *)ainfo->ai_addr)->sin6_addr;
3443           result = setsockopt(endpoint->sock.fd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
3444                               (char *)&mreq6, sizeof(mreq6));
3445         }
3446         else if (ainfo->ai_family == AF_INET) {
3447           if (!ifname) {
3448             if(endpoint->bind_addr.addr.sa.sa_family == AF_INET) {
3449               /*
3450                * Do it on the interface that the server is listening on
3451                * (sin_addr could still be INADDR_ANY)
3452                */
3453               mreq4.imr_interface = endpoint->bind_addr.addr.sin.sin_addr;
3454             }
3455             else {
3456               mreq4.imr_interface.s_addr = INADDR_ANY;
3457             }
3458           }
3459           gaddr.addr.sin.sin_family = AF_INET;
3460           gaddr.addr.sin.sin_port = endpoint->bind_addr.addr.sin.sin_port;
3461           gaddr.addr.sin.sin_addr.s_addr = mreq4.imr_multiaddr.s_addr =
3462               ((struct sockaddr_in *)ainfo->ai_addr)->sin_addr.s_addr;
3463           result = setsockopt(endpoint->sock.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3464                               (char *)&mreq4, sizeof(mreq4));
3465         }
3466         else {
3467           continue;
3468         }
3469 
3470         if (result == COAP_SOCKET_ERROR) {
3471           coap_log(LOG_ERR,
3472                    "coap_join_mcast_group_intf: %s: setsockopt: %s\n",
3473                    group_name, coap_socket_strerror());
3474         }
3475         else {
3476           char addr_str[INET6_ADDRSTRLEN + 8 + 1];
3477 
3478           addr_str[sizeof(addr_str)-1] = '\000';
3479           if (coap_print_addr(&gaddr, (uint8_t*)addr_str,
3480                             sizeof(addr_str) - 1)) {
3481             if (ifname)
3482               coap_log(LOG_DEBUG, "added mcast group %s i/f %s\n", addr_str,
3483                        ifname);
3484             else
3485               coap_log(LOG_DEBUG, "added mcast group %s\n", addr_str);
3486           }
3487           mgroup_setup = 1;
3488         }
3489       }
3490     }
3491   }
3492   if (!mgroup_setup) {
3493     result = -1;
3494   }
3495 
3496  finish:
3497   freeaddrinfo(resmulti);
3498 
3499   return result;
3500 }
3501 
3502 int
coap_mcast_set_hops(coap_session_t * session,size_t hops)3503 coap_mcast_set_hops(coap_session_t *session, size_t hops) {
3504   if (session && coap_is_mcast(&session->addr_info.remote)) {
3505     switch (session->addr_info.remote.addr.sa.sa_family) {
3506     case AF_INET:
3507       if (setsockopt(session->sock.fd, IPPROTO_IP, IP_MULTICAST_TTL,
3508           (const char *)&hops, sizeof(hops)) < 0) {
3509         coap_log(LOG_INFO, "coap_mcast_set_hops: %zu: setsockopt: %s\n",
3510                  hops, coap_socket_strerror());
3511         return 0;
3512       }
3513       return 1;
3514     case AF_INET6:
3515       if (setsockopt(session->sock.fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
3516           (const char *)&hops, sizeof(hops)) < 0) {
3517         coap_log(LOG_INFO, "coap_mcast_set_hops: %zu: setsockopt: %s\n",
3518                  hops, coap_socket_strerror());
3519         return 0;
3520       }
3521       return 1;
3522     default:
3523       break;
3524     }
3525   }
3526   return 0;
3527 }
3528 #else /* defined WITH_CONTIKI || defined WITH_LWIP */
3529 int
coap_join_mcast_group_intf(coap_context_t * ctx COAP_UNUSED,const char * group_name COAP_UNUSED,const char * ifname COAP_UNUSED)3530 coap_join_mcast_group_intf(coap_context_t *ctx COAP_UNUSED,
3531                            const char *group_name COAP_UNUSED,
3532                            const char *ifname COAP_UNUSED) {
3533   return -1;
3534 }
3535 int
coap_mcast_set_hops(coap_session_t * session COAP_UNUSED,size_t hops COAP_UNUSED)3536 coap_mcast_set_hops(coap_session_t *session COAP_UNUSED,
3537                     size_t hops COAP_UNUSED) {
3538   return 0;
3539 }
3540 #endif /* defined WITH_CONTIKI || defined WITH_LWIP */
3541 
3542 #ifdef WITH_CONTIKI
3543 
3544 /*---------------------------------------------------------------------------*/
3545 /* CoAP message retransmission */
3546 /*---------------------------------------------------------------------------*/
PROCESS_THREAD(coap_retransmit_process,ev,data)3547 PROCESS_THREAD(coap_retransmit_process, ev, data) {
3548   coap_tick_t now;
3549   coap_queue_t *nextpdu;
3550 
3551   PROCESS_BEGIN();
3552 
3553   coap_log(LOG_DEBUG, "Started retransmit process\n");
3554 
3555   while (1) {
3556     PROCESS_YIELD();
3557     if (ev == PROCESS_EVENT_TIMER) {
3558       if (etimer_expired(&the_coap_context.retransmit_timer)) {
3559 
3560         nextpdu = coap_peek_next(&the_coap_context);
3561 
3562         coap_ticks(&now);
3563         while (nextpdu && nextpdu->t <= now) {
3564           coap_retransmit(&the_coap_context, coap_pop_next(&the_coap_context));
3565           nextpdu = coap_peek_next(&the_coap_context);
3566         }
3567 
3568         /* need to set timer to some value even if no nextpdu is available */
3569         etimer_set(&the_coap_context.retransmit_timer,
3570           nextpdu ? nextpdu->t - now : 0xFFFF);
3571       }
3572       if (etimer_expired(&the_coap_context.notify_timer)) {
3573         coap_check_notify(&the_coap_context);
3574         etimer_reset(&the_coap_context.notify_timer);
3575       }
3576     }
3577   }
3578 
3579   PROCESS_END();
3580 }
3581 /*---------------------------------------------------------------------------*/
3582 
3583 #endif /* WITH_CONTIKI */
3584 
3585 #ifdef WITH_LWIP
3586 /* FIXME: retransmits that are not required any more due to incoming packages
3587  * do *not* get cleared at the moment, the wakeup when the transmission is due
3588  * is silently accepted. this is mainly due to the fact that the required
3589  * checks are similar in two places in the code (when receiving ACK and RST)
3590  * and that they cause more than one patch chunk, as it must be first checked
3591  * whether the sendqueue item to be dropped is the next one pending, and later
3592  * the restart function has to be called. nothing insurmountable, but it can
3593  * also be implemented when things have stabilized, and the performance
3594  * penality is minimal
3595  *
3596  * also, this completely ignores COAP_RESOURCE_CHECK_TIME.
3597  * */
3598 
coap_retransmittimer_execute(void * arg)3599 static void coap_retransmittimer_execute(void *arg) {
3600   coap_context_t *ctx = (coap_context_t*)arg;
3601   coap_tick_t now;
3602   coap_tick_t elapsed;
3603   coap_queue_t *nextinqueue;
3604 
3605   ctx->timer_configured = 0;
3606 
3607   coap_ticks(&now);
3608 
3609   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 */
3610 
3611   nextinqueue = coap_peek_next(ctx);
3612   while (nextinqueue != NULL) {
3613     if (nextinqueue->t > elapsed) {
3614       nextinqueue->t -= elapsed;
3615       break;
3616     } else {
3617       elapsed -= nextinqueue->t;
3618       coap_retransmit(ctx, coap_pop_next(ctx));
3619       nextinqueue = coap_peek_next(ctx);
3620     }
3621   }
3622 
3623   ctx->sendqueue_basetime = now;
3624 
3625   coap_retransmittimer_restart(ctx);
3626 }
3627 
coap_retransmittimer_restart(coap_context_t * ctx)3628 static void coap_retransmittimer_restart(coap_context_t *ctx) {
3629   coap_tick_t now, elapsed, delay;
3630 
3631   if (ctx->timer_configured) {
3632     printf("clearing\n");
3633     sys_untimeout(coap_retransmittimer_execute, (void*)ctx);
3634     ctx->timer_configured = 0;
3635   }
3636   if (ctx->sendqueue != NULL) {
3637     coap_ticks(&now);
3638     elapsed = now - ctx->sendqueue_basetime;
3639     if (ctx->sendqueue->t >= elapsed) {
3640       delay = ctx->sendqueue->t - elapsed;
3641     } else {
3642       /* a strange situation, but not completely impossible.
3643        *
3644        * this happens, for example, right after
3645        * coap_retransmittimer_execute, when a retransmission
3646        * was *just not yet* due, and the clock ticked before
3647        * our coap_ticks was called.
3648        *
3649        * not trying to retransmit anything now, as it might
3650        * cause uncontrollable recursion; let's just try again
3651        * with the next main loop run.
3652        * */
3653       delay = 0;
3654     }
3655 
3656     printf("scheduling for %d ticks\n", delay);
3657     sys_timeout(delay, coap_retransmittimer_execute, (void*)ctx);
3658     ctx->timer_configured = 1;
3659   }
3660 }
3661 #endif
3662