• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* coap_net.c -- CoAP context inteface
2  *
3  * Copyright (C) 2010--2023 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 /**
12  * @file coap_net.c
13  * @brief CoAP context functions
14  */
15 
16 #include "coap3/coap_internal.h"
17 
18 #include <ctype.h>
19 #include <stdio.h>
20 #ifdef HAVE_LIMITS_H
21 #include <limits.h>
22 #endif
23 #ifdef HAVE_UNISTD_H
24 #include <unistd.h>
25 #else
26 #ifdef HAVE_SYS_UNISTD_H
27 #include <sys/unistd.h>
28 #endif
29 #endif
30 #ifdef HAVE_SYS_TYPES_H
31 #include <sys/types.h>
32 #endif
33 #ifdef HAVE_SYS_SOCKET_H
34 #include <sys/socket.h>
35 #endif
36 #ifdef HAVE_SYS_IOCTL_H
37 #include <sys/ioctl.h>
38 #endif
39 #ifdef HAVE_NETINET_IN_H
40 #include <netinet/in.h>
41 #endif
42 #ifdef HAVE_ARPA_INET_H
43 #include <arpa/inet.h>
44 #endif
45 #ifdef HAVE_NET_IF_H
46 #include <net/if.h>
47 #endif
48 #ifdef COAP_EPOLL_SUPPORT
49 #include <sys/epoll.h>
50 #include <sys/timerfd.h>
51 #endif /* COAP_EPOLL_SUPPORT */
52 #ifdef HAVE_WS2TCPIP_H
53 #include <ws2tcpip.h>
54 #endif
55 
56 #ifdef HAVE_NETDB_H
57 #include <netdb.h>
58 #endif
59 
60 #ifdef WITH_LWIP
61 #include <lwip/pbuf.h>
62 #include <lwip/udp.h>
63 #include <lwip/timeouts.h>
64 #include <lwip/tcpip.h>
65 #endif
66 
67 #ifndef INET6_ADDRSTRLEN
68 #define INET6_ADDRSTRLEN 40
69 #endif
70 
71 #ifndef min
72 #define min(a,b) ((a) < (b) ? (a) : (b))
73 #endif
74 
75 /**
76  * The number of bits for the fractional part of ACK_TIMEOUT and
77  * ACK_RANDOM_FACTOR. Must be less or equal 8.
78  */
79 #define FRAC_BITS 6
80 
81 /**
82  * The maximum number of bits for fixed point integers that are used
83  * for retransmission time calculation. Currently this must be @c 8.
84  */
85 #define MAX_BITS 8
86 
87 #if FRAC_BITS > 8
88 #error FRAC_BITS must be less or equal 8
89 #endif
90 
91 /** creates a Qx.frac from fval in coap_fixed_point_t */
92 #define Q(frac,fval) ((uint16_t)(((1 << (frac)) * fval.integer_part) + \
93                                  ((1 << (frac)) * fval.fractional_part + 500)/1000))
94 
95 /** creates a Qx.FRAC_BITS from session's 'ack_random_factor' */
96 #define ACK_RANDOM_FACTOR                                        \
97   Q(FRAC_BITS, session->ack_random_factor)
98 
99 /** creates a Qx.FRAC_BITS from session's 'ack_timeout' */
100 #define ACK_TIMEOUT Q(FRAC_BITS, session->ack_timeout)
101 
102 #ifndef WITH_LWIP
103 
104 COAP_STATIC_INLINE coap_queue_t *
coap_malloc_node(void)105 coap_malloc_node(void) {
106   return (coap_queue_t *)coap_malloc_type(COAP_NODE, sizeof(coap_queue_t));
107 }
108 
109 COAP_STATIC_INLINE void
coap_free_node(coap_queue_t * node)110 coap_free_node(coap_queue_t *node) {
111   coap_free_type(COAP_NODE, node);
112 }
113 #else /* !WITH_LWIP */
114 
115 #include <lwip/memp.h>
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 #endif /* WITH_LWIP */
127 
128 unsigned int
coap_adjust_basetime(coap_context_t * ctx,coap_tick_t now)129 coap_adjust_basetime(coap_context_t *ctx, coap_tick_t now) {
130   unsigned int result = 0;
131   coap_tick_diff_t delta = now - ctx->sendqueue_basetime;
132 
133   if (ctx->sendqueue) {
134     /* delta < 0 means that the new time stamp is before the old. */
135     if (delta <= 0) {
136       ctx->sendqueue->t -= delta;
137     } else {
138       /* This case is more complex: The time must be advanced forward,
139        * thus possibly leading to timed out elements at the queue's
140        * start. For every element that has timed out, its relative
141        * time is set to zero and the result counter is increased. */
142 
143       coap_queue_t *q = ctx->sendqueue;
144       coap_tick_t t = 0;
145       while (q && (t + q->t < (coap_tick_t)delta)) {
146         t += q->t;
147         q->t = 0;
148         result++;
149         q = q->next;
150       }
151 
152       /* finally adjust the first element that has not expired */
153       if (q) {
154         q->t = (coap_tick_t)delta - t;
155       }
156     }
157   }
158 
159   /* adjust basetime */
160   ctx->sendqueue_basetime += delta;
161 
162   return result;
163 }
164 
165 int
coap_insert_node(coap_queue_t ** queue,coap_queue_t * node)166 coap_insert_node(coap_queue_t **queue, coap_queue_t *node) {
167   coap_queue_t *p, *q;
168   if (!queue || !node)
169     return 0;
170 
171   /* set queue head if empty */
172   if (!*queue) {
173     *queue = node;
174     return 1;
175   }
176 
177   /* replace queue head if PDU's time is less than head's time */
178   q = *queue;
179   if (node->t < q->t) {
180     node->next = q;
181     *queue = node;
182     q->t -= node->t;                /* make q->t relative to node->t */
183     return 1;
184   }
185 
186   /* search for right place to insert */
187   do {
188     node->t -= q->t;                /* make node-> relative to q->t */
189     p = q;
190     q = q->next;
191   } while (q && q->t <= node->t);
192 
193   /* insert new item */
194   if (q) {
195     q->t -= node->t;                /* make q->t relative to node->t */
196   }
197   node->next = q;
198   p->next = node;
199   return 1;
200 }
201 
202 int
coap_delete_node(coap_queue_t * node)203 coap_delete_node(coap_queue_t *node) {
204   if (!node)
205     return 0;
206 
207   coap_delete_pdu(node->pdu);
208   if (node->session) {
209     /*
210      * Need to remove out of context->sendqueue as added in by coap_wait_ack()
211      */
212     if (node->session->context->sendqueue) {
213       LL_DELETE(node->session->context->sendqueue, node);
214     }
215     coap_session_release(node->session);
216   }
217   coap_free_node(node);
218 
219   return 1;
220 }
221 
222 void
coap_delete_all(coap_queue_t * queue)223 coap_delete_all(coap_queue_t *queue) {
224   if (!queue)
225     return;
226 
227   coap_delete_all(queue->next);
228   coap_delete_node(queue);
229 }
230 
231 coap_queue_t *
coap_new_node(void)232 coap_new_node(void) {
233   coap_queue_t *node;
234   node = coap_malloc_node();
235 
236   if (!node) {
237     coap_log_warn("coap_new_node: malloc failed\n");
238     return NULL;
239   }
240 
241   memset(node, 0, sizeof(*node));
242   return node;
243 }
244 
245 coap_queue_t *
coap_peek_next(coap_context_t * context)246 coap_peek_next(coap_context_t *context) {
247   if (!context || !context->sendqueue)
248     return NULL;
249 
250   return context->sendqueue;
251 }
252 
253 coap_queue_t *
coap_pop_next(coap_context_t * context)254 coap_pop_next(coap_context_t *context) {
255   coap_queue_t *next;
256 
257   if (!context || !context->sendqueue)
258     return NULL;
259 
260   next = context->sendqueue;
261   context->sendqueue = context->sendqueue->next;
262   if (context->sendqueue) {
263     context->sendqueue->t += next->t;
264   }
265   next->next = NULL;
266   return next;
267 }
268 
269 #if COAP_CLIENT_SUPPORT
270 const coap_bin_const_t *
coap_get_session_client_psk_key(const coap_session_t * session)271 coap_get_session_client_psk_key(const coap_session_t *session) {
272 
273   if (session->psk_key) {
274     return session->psk_key;
275   }
276   if (session->cpsk_setup_data.psk_info.key.length)
277     return &session->cpsk_setup_data.psk_info.key;
278 
279   /* Not defined in coap_new_client_session_psk2() */
280   return NULL;
281 }
282 #endif /* COAP_CLIENT_SUPPORT */
283 
284 const coap_bin_const_t *
coap_get_session_client_psk_identity(const coap_session_t * session)285 coap_get_session_client_psk_identity(const coap_session_t *session) {
286 
287   if (session->psk_identity) {
288     return session->psk_identity;
289   }
290   if (session->cpsk_setup_data.psk_info.identity.length)
291     return &session->cpsk_setup_data.psk_info.identity;
292 
293   /* Not defined in coap_new_client_session_psk2() */
294   return NULL;
295 }
296 
297 #if COAP_SERVER_SUPPORT
298 const coap_bin_const_t *
coap_get_session_server_psk_key(const coap_session_t * session)299 coap_get_session_server_psk_key(const coap_session_t *session) {
300 
301   if (session->psk_key)
302     return session->psk_key;
303 
304   if (session->context->spsk_setup_data.psk_info.key.length)
305     return &session->context->spsk_setup_data.psk_info.key;
306 
307   /* Not defined in coap_context_set_psk2() */
308   return NULL;
309 }
310 
311 const coap_bin_const_t *
coap_get_session_server_psk_hint(const coap_session_t * session)312 coap_get_session_server_psk_hint(const coap_session_t *session) {
313 
314   if (session->psk_hint)
315     return session->psk_hint;
316 
317   if (session->context->spsk_setup_data.psk_info.hint.length)
318     return &session->context->spsk_setup_data.psk_info.hint;
319 
320   /* Not defined in coap_context_set_psk2() */
321   return NULL;
322 }
323 
324 int
coap_context_set_psk(coap_context_t * ctx,const char * hint,const uint8_t * key,size_t key_len)325 coap_context_set_psk(coap_context_t *ctx,
326                      const char *hint,
327                      const uint8_t *key,
328                      size_t key_len) {
329   coap_dtls_spsk_t setup_data;
330 
331   memset(&setup_data, 0, sizeof(setup_data));
332   if (hint) {
333     setup_data.psk_info.hint.s = (const uint8_t *)hint;
334     setup_data.psk_info.hint.length = strlen(hint);
335   }
336 
337   if (key && key_len > 0) {
338     setup_data.psk_info.key.s = key;
339     setup_data.psk_info.key.length = key_len;
340   }
341 
342   return coap_context_set_psk2(ctx, &setup_data);
343 }
344 
345 int
coap_context_set_psk2(coap_context_t * ctx,coap_dtls_spsk_t * setup_data)346 coap_context_set_psk2(coap_context_t *ctx, coap_dtls_spsk_t *setup_data) {
347   if (!setup_data)
348     return 0;
349 
350   ctx->spsk_setup_data = *setup_data;
351 
352   if (coap_dtls_is_supported() || coap_tls_is_supported()) {
353     return coap_dtls_context_set_spsk(ctx, setup_data);
354   }
355   return 0;
356 }
357 
358 int
coap_context_set_pki(coap_context_t * ctx,const coap_dtls_pki_t * setup_data)359 coap_context_set_pki(coap_context_t *ctx,
360                      const coap_dtls_pki_t *setup_data) {
361   if (!setup_data)
362     return 0;
363   if (setup_data->version != COAP_DTLS_PKI_SETUP_VERSION) {
364     coap_log_err("coap_context_set_pki: Wrong version of setup_data\n");
365     return 0;
366   }
367   if (coap_dtls_is_supported() || coap_tls_is_supported()) {
368     return coap_dtls_context_set_pki(ctx, setup_data, COAP_DTLS_ROLE_SERVER);
369   }
370   return 0;
371 }
372 #endif /* ! COAP_SERVER_SUPPORT */
373 
374 int
coap_context_set_pki_root_cas(coap_context_t * ctx,const char * ca_file,const char * ca_dir)375 coap_context_set_pki_root_cas(coap_context_t *ctx,
376                               const char *ca_file,
377                               const char *ca_dir) {
378   if (coap_dtls_is_supported() || coap_tls_is_supported()) {
379     return coap_dtls_context_set_pki_root_cas(ctx, ca_file, ca_dir);
380   }
381   return 0;
382 }
383 
384 void
coap_context_set_keepalive(coap_context_t * context,unsigned int seconds)385 coap_context_set_keepalive(coap_context_t *context, unsigned int seconds) {
386   context->ping_timeout = seconds;
387 }
388 
389 void
coap_context_set_max_token_size(coap_context_t * context,size_t max_token_size)390 coap_context_set_max_token_size(coap_context_t *context,
391                                 size_t max_token_size) {
392   assert(max_token_size >= COAP_TOKEN_DEFAULT_MAX &&
393          max_token_size <= COAP_TOKEN_EXT_MAX);
394   context->max_token_size = (uint32_t)max_token_size;
395 }
396 
397 void
coap_context_set_max_idle_sessions(coap_context_t * context,unsigned int max_idle_sessions)398 coap_context_set_max_idle_sessions(coap_context_t *context,
399                                    unsigned int max_idle_sessions) {
400   context->max_idle_sessions = max_idle_sessions;
401 }
402 
403 unsigned int
coap_context_get_max_idle_sessions(const coap_context_t * context)404 coap_context_get_max_idle_sessions(const coap_context_t *context) {
405   return context->max_idle_sessions;
406 }
407 
408 void
coap_context_set_max_handshake_sessions(coap_context_t * context,unsigned int max_handshake_sessions)409 coap_context_set_max_handshake_sessions(coap_context_t *context,
410                                         unsigned int max_handshake_sessions) {
411   context->max_handshake_sessions = max_handshake_sessions;
412 }
413 
414 unsigned int
coap_context_get_max_handshake_sessions(const coap_context_t * context)415 coap_context_get_max_handshake_sessions(const coap_context_t *context) {
416   return context->max_handshake_sessions;
417 }
418 
419 void
coap_context_set_csm_timeout(coap_context_t * context,unsigned int csm_timeout)420 coap_context_set_csm_timeout(coap_context_t *context,
421                              unsigned int csm_timeout) {
422   context->csm_timeout = csm_timeout;
423 }
424 
425 unsigned int
coap_context_get_csm_timeout(const coap_context_t * context)426 coap_context_get_csm_timeout(const coap_context_t *context) {
427   return context->csm_timeout;
428 }
429 
430 void
coap_context_set_csm_max_message_size(coap_context_t * context,uint32_t csm_max_message_size)431 coap_context_set_csm_max_message_size(coap_context_t *context,
432                                       uint32_t csm_max_message_size) {
433   assert(csm_max_message_size >= 64);
434   context->csm_max_message_size = csm_max_message_size;
435 }
436 
437 uint32_t
coap_context_get_csm_max_message_size(const coap_context_t * context)438 coap_context_get_csm_max_message_size(const coap_context_t *context) {
439   return context->csm_max_message_size;
440 }
441 
442 void
coap_context_set_session_timeout(coap_context_t * context,unsigned int session_timeout)443 coap_context_set_session_timeout(coap_context_t *context,
444                                  unsigned int session_timeout) {
445   context->session_timeout = session_timeout;
446 }
447 
448 unsigned int
coap_context_get_session_timeout(const coap_context_t * context)449 coap_context_get_session_timeout(const coap_context_t *context) {
450   return context->session_timeout;
451 }
452 
453 int
coap_context_get_coap_fd(const coap_context_t * context)454 coap_context_get_coap_fd(const coap_context_t *context) {
455 #ifdef COAP_EPOLL_SUPPORT
456   return context->epfd;
457 #else /* ! COAP_EPOLL_SUPPORT */
458   (void)context;
459   return -1;
460 #endif /* ! COAP_EPOLL_SUPPORT */
461 }
462 
463 coap_endpoint_t *
coap_context_get_endpoint(const coap_context_t * context)464 coap_context_get_endpoint(const coap_context_t *context) {
465   if (context != NULL)
466     return context->endpoint;
467   return NULL;
468 }
469 
470 coap_context_t *
coap_new_context(const coap_address_t * listen_addr)471 coap_new_context(const coap_address_t *listen_addr) {
472   coap_context_t *c;
473 
474 #if ! COAP_SERVER_SUPPORT
475   (void)listen_addr;
476 #endif /* COAP_SERVER_SUPPORT */
477 
478   if (!coap_started) {
479     coap_startup();
480     coap_log_warn("coap_startup() should be called before any other "
481                   "coap_*() functions are called\n");
482   }
483 
484   c = coap_malloc_type(COAP_CONTEXT, sizeof(coap_context_t));
485   if (!c) {
486     coap_log_emerg("coap_init: malloc: failed\n");
487     return NULL;
488   }
489   memset(c, 0, sizeof(coap_context_t));
490 
491 #ifdef COAP_EPOLL_SUPPORT
492   c->epfd = epoll_create1(0);
493   if (c->epfd == -1) {
494     coap_log_err("coap_new_context: Unable to epoll_create: %s (%d)\n",
495                  coap_socket_strerror(),
496                  errno);
497     goto onerror;
498   }
499   if (c->epfd != -1) {
500     c->eptimerfd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK);
501     if (c->eptimerfd == -1) {
502       coap_log_err("coap_new_context: Unable to timerfd_create: %s (%d)\n",
503                    coap_socket_strerror(),
504                    errno);
505       goto onerror;
506     } else {
507       int ret;
508       struct epoll_event event;
509 
510       /* Needed if running 32bit as ptr is only 32bit */
511       memset(&event, 0, sizeof(event));
512       event.events = EPOLLIN;
513       /* We special case this event by setting to NULL */
514       event.data.ptr = NULL;
515 
516       ret = epoll_ctl(c->epfd, EPOLL_CTL_ADD, c->eptimerfd, &event);
517       if (ret == -1) {
518         coap_log_err("%s: epoll_ctl ADD failed: %s (%d)\n",
519                      "coap_new_context",
520                      coap_socket_strerror(), errno);
521         goto onerror;
522       }
523     }
524   }
525 #endif /* COAP_EPOLL_SUPPORT */
526 
527   if (coap_dtls_is_supported() || coap_tls_is_supported()) {
528     c->dtls_context = coap_dtls_new_context(c);
529     if (!c->dtls_context) {
530       coap_log_emerg("coap_init: no DTLS context available\n");
531       coap_free_context(c);
532       return NULL;
533     }
534   }
535 
536   /* set default CSM values */
537   c->csm_timeout = 30;
538   c->csm_max_message_size = COAP_DEFAULT_MAX_PDU_RX_SIZE;
539 
540 #if COAP_SERVER_SUPPORT
541   if (listen_addr) {
542     coap_endpoint_t *endpoint = coap_new_endpoint(c, listen_addr, COAP_PROTO_UDP);
543     if (endpoint == NULL) {
544       goto onerror;
545     }
546   }
547 #endif /* COAP_SERVER_SUPPORT */
548 
549   c->max_token_size = COAP_TOKEN_DEFAULT_MAX; /* RFC8974 */
550 
551   return c;
552 
553 #if defined(COAP_EPOLL_SUPPORT) || COAP_SERVER_SUPPORT
554 onerror:
555   coap_free_type(COAP_CONTEXT, c);
556   return NULL;
557 #endif /* COAP_EPOLL_SUPPORT || COAP_SERVER_SUPPORT */
558 }
559 
560 void
coap_set_app_data(coap_context_t * ctx,void * app_data)561 coap_set_app_data(coap_context_t *ctx, void *app_data) {
562   assert(ctx);
563   ctx->app = app_data;
564 }
565 
566 void *
coap_get_app_data(const coap_context_t * ctx)567 coap_get_app_data(const coap_context_t *ctx) {
568   assert(ctx);
569   return ctx->app;
570 }
571 
572 void
coap_free_context(coap_context_t * context)573 coap_free_context(coap_context_t *context) {
574   if (!context)
575     return;
576 
577 #if COAP_SERVER_SUPPORT
578   /* Removing a resource may cause a NON unsolicited observe to be sent */
579   coap_delete_all_resources(context);
580 #endif /* COAP_SERVER_SUPPORT */
581 
582   coap_delete_all(context->sendqueue);
583 
584 #ifdef WITH_LWIP
585   context->sendqueue = NULL;
586   if (context->timer_configured) {
587     LOCK_TCPIP_CORE();
588     sys_untimeout(coap_io_process_timeout, (void *)context);
589     UNLOCK_TCPIP_CORE();
590     context->timer_configured = 0;
591   }
592 #endif /* WITH_LWIP */
593 
594 #if COAP_ASYNC_SUPPORT
595   coap_delete_all_async(context);
596 #endif /* COAP_ASYNC_SUPPORT */
597 
598 #if COAP_OSCORE_SUPPORT
599   coap_delete_all_oscore(context);
600 #endif /* COAP_OSCORE_SUPPORT */
601 
602 #if COAP_SERVER_SUPPORT
603   coap_cache_entry_t *cp, *ctmp;
604 
605   HASH_ITER(hh, context->cache, cp, ctmp) {
606     coap_delete_cache_entry(context, cp);
607   }
608   if (context->cache_ignore_count) {
609     coap_free_type(COAP_STRING, context->cache_ignore_options);
610   }
611 
612   coap_endpoint_t *ep, *tmp;
613 
614   LL_FOREACH_SAFE(context->endpoint, ep, tmp) {
615     coap_free_endpoint(ep);
616   }
617 #endif /* COAP_SERVER_SUPPORT */
618 
619 #if COAP_CLIENT_SUPPORT
620   coap_session_t *sp, *rtmp;
621 
622   SESSIONS_ITER_SAFE(context->sessions, sp, rtmp) {
623     coap_session_release(sp);
624   }
625 #endif /* COAP_CLIENT_SUPPORT */
626 
627   if (context->dtls_context)
628     coap_dtls_free_context(context->dtls_context);
629 #ifdef COAP_EPOLL_SUPPORT
630   if (context->eptimerfd != -1) {
631     int ret;
632     struct epoll_event event;
633 
634     /* Kernels prior to 2.6.9 expect non NULL event parameter */
635     ret = epoll_ctl(context->epfd, EPOLL_CTL_DEL, context->eptimerfd, &event);
636     if (ret == -1) {
637       coap_log_err("%s: epoll_ctl DEL failed: %s (%d)\n",
638                    "coap_free_context",
639                    coap_socket_strerror(), errno);
640     }
641     close(context->eptimerfd);
642     context->eptimerfd = -1;
643   }
644   if (context->epfd != -1) {
645     close(context->epfd);
646     context->epfd = -1;
647   }
648 #endif /* COAP_EPOLL_SUPPORT */
649 #if COAP_SERVER_SUPPORT
650 #if COAP_WITH_OBSERVE_PERSIST
651   coap_persist_cleanup(context);
652 #endif /* COAP_WITH_OBSERVE_PERSIST */
653 #endif /* COAP_SERVER_SUPPORT */
654 
655   coap_free_type(COAP_CONTEXT, context);
656 #ifdef WITH_LWIP
657   coap_lwip_dump_memory_pools(COAP_LOG_DEBUG);
658 #endif /* WITH_LWIP */
659 }
660 
661 int
coap_option_check_critical(coap_session_t * session,coap_pdu_t * pdu,coap_opt_filter_t * unknown)662 coap_option_check_critical(coap_session_t *session,
663                            coap_pdu_t *pdu,
664                            coap_opt_filter_t *unknown) {
665   coap_context_t *ctx = session->context;
666   coap_opt_iterator_t opt_iter;
667   int ok = 1;
668   coap_option_num_t last_number = -1;
669 
670   coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
671 
672   while (coap_option_next(&opt_iter)) {
673     if (opt_iter.number & 0x01) {
674       /* first check the known built-in critical options */
675       switch (opt_iter.number) {
676 #if COAP_Q_BLOCK_SUPPORT
677       case COAP_OPTION_Q_BLOCK1:
678       case COAP_OPTION_Q_BLOCK2:
679         if (!(ctx->block_mode & COAP_BLOCK_TRY_Q_BLOCK)) {
680           coap_log_debug("disabled support for critical option %u\n",
681                          opt_iter.number);
682           ok = 0;
683           coap_option_filter_set(unknown, opt_iter.number);
684         }
685         break;
686 #endif /* COAP_Q_BLOCK_SUPPORT */
687       case COAP_OPTION_IF_MATCH:
688       case COAP_OPTION_URI_HOST:
689       case COAP_OPTION_IF_NONE_MATCH:
690       case COAP_OPTION_URI_PORT:
691       case COAP_OPTION_URI_PATH:
692       case COAP_OPTION_URI_QUERY:
693       case COAP_OPTION_ACCEPT:
694       case COAP_OPTION_PROXY_URI:
695       case COAP_OPTION_PROXY_SCHEME:
696       case COAP_OPTION_BLOCK2:
697       case COAP_OPTION_BLOCK1:
698         break;
699       case COAP_OPTION_OSCORE:
700         /* Valid critical if doing OSCORE */
701 #if COAP_OSCORE_SUPPORT
702         if (ctx->p_osc_ctx)
703           break;
704 #endif /* COAP_OSCORE_SUPPORT */
705       /* Fall Through */
706       default:
707         if (coap_option_filter_get(&ctx->known_options, opt_iter.number) <= 0) {
708 #if COAP_SERVER_SUPPORT
709           if ((opt_iter.number & 0x02) == 0) {
710             coap_opt_iterator_t t_iter;
711 
712             /* Safe to forward  - check if proxy pdu */
713             if (session->proxy_session)
714               break;
715             if (COAP_PDU_IS_REQUEST(pdu) && ctx->proxy_uri_resource &&
716                 (coap_check_option(pdu, COAP_OPTION_PROXY_URI, &t_iter) ||
717                  coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &t_iter))) {
718               pdu->crit_opt = 1;
719               break;
720             }
721           }
722 #endif /* COAP_SERVER_SUPPORT */
723           coap_log_debug("unknown critical option %d\n", opt_iter.number);
724           ok = 0;
725 
726           /* When opt_iter.number cannot be set in unknown, all of the appropriate
727            * slots have been used up and no more options can be tracked.
728            * Safe to break out of this loop as ok is already set. */
729           if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
730             break;
731           }
732         }
733       }
734     }
735     if (last_number == opt_iter.number) {
736       /* Check for duplicated option RFC 5272 5.4.5 */
737       if (!coap_option_check_repeatable(opt_iter.number)) {
738         ok = 0;
739         if (coap_option_filter_set(unknown, opt_iter.number) == 0) {
740           break;
741         }
742       }
743     } else if (opt_iter.number == COAP_OPTION_BLOCK2 &&
744                COAP_PDU_IS_REQUEST(pdu)) {
745       /* Check the M Bit is not set on a GET request RFC 7959 2.2 */
746       coap_block_b_t block;
747 
748       if (coap_get_block_b(session, pdu, opt_iter.number, &block)) {
749         if (block.m) {
750           size_t used_size = pdu->used_size;
751           unsigned char buf[4];
752 
753           coap_log_debug("Option Block2 has invalid set M bit - cleared\n");
754           block.m = 0;
755           coap_update_option(pdu, opt_iter.number,
756                              coap_encode_var_safe(buf, sizeof(buf),
757                                                   ((block.num << 4) |
758                                                    (block.m << 3) |
759                                                    block.aszx)),
760                              buf);
761           if (used_size != pdu->used_size) {
762             /* Unfortunately need to restart the scan */
763             coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
764             last_number = -1;
765             continue;
766           }
767         }
768       }
769     }
770     last_number = opt_iter.number;
771   }
772 
773   return ok;
774 }
775 
776 coap_mid_t
coap_send_ack(coap_session_t * session,const coap_pdu_t * request)777 coap_send_ack(coap_session_t *session, const coap_pdu_t *request) {
778   coap_pdu_t *response;
779   coap_mid_t result = COAP_INVALID_MID;
780 
781   if (request && request->type == COAP_MESSAGE_CON &&
782       COAP_PROTO_NOT_RELIABLE(session->proto)) {
783     response = coap_pdu_init(COAP_MESSAGE_ACK, 0, request->mid, 0);
784     if (response)
785       result = coap_send_internal(session, response);
786   }
787   return result;
788 }
789 
790 ssize_t
coap_session_send_pdu(coap_session_t * session,coap_pdu_t * pdu)791 coap_session_send_pdu(coap_session_t *session, coap_pdu_t *pdu) {
792   ssize_t bytes_written = -1;
793   assert(pdu->hdr_size > 0);
794 
795   /* Caller handles partial writes */
796   bytes_written = session->sock.lfunc[COAP_LAYER_SESSION].l_write(session,
797                   pdu->token - pdu->hdr_size,
798                   pdu->used_size + pdu->hdr_size);
799   coap_show_pdu(COAP_LOG_DEBUG, pdu);
800   return bytes_written;
801 }
802 
803 static ssize_t
coap_send_pdu(coap_session_t * session,coap_pdu_t * pdu,coap_queue_t * node)804 coap_send_pdu(coap_session_t *session, coap_pdu_t *pdu, coap_queue_t *node) {
805   ssize_t bytes_written;
806 
807   if (session->state == COAP_SESSION_STATE_NONE) {
808 #if ! COAP_CLIENT_SUPPORT
809     return -1;
810 #else /* COAP_CLIENT_SUPPORT */
811     if (session->type != COAP_SESSION_TYPE_CLIENT)
812       return -1;
813 #endif /* COAP_CLIENT_SUPPORT */
814   }
815 
816   if (pdu->type == COAP_MESSAGE_CON &&
817       (session->sock.flags & COAP_SOCKET_NOT_EMPTY) &&
818       (session->sock.flags & COAP_SOCKET_MULTICAST)) {
819     /* Violates RFC72522 8.1 */
820     coap_log_err("Multicast requests cannot be Confirmable (RFC7252 8.1)\n");
821     return -1;
822   }
823 
824   if (session->state != COAP_SESSION_STATE_ESTABLISHED ||
825       (pdu->type == COAP_MESSAGE_CON &&
826        session->con_active >= COAP_NSTART(session))) {
827     return coap_session_delay_pdu(session, pdu, node);
828   }
829 
830   if ((session->sock.flags & COAP_SOCKET_NOT_EMPTY) &&
831       (session->sock.flags & COAP_SOCKET_WANT_WRITE))
832     return coap_session_delay_pdu(session, pdu, node);
833 
834   bytes_written = coap_session_send_pdu(session, pdu);
835   if (bytes_written >= 0 && pdu->type == COAP_MESSAGE_CON &&
836       COAP_PROTO_NOT_RELIABLE(session->proto))
837     session->con_active++;
838 
839   return bytes_written;
840 }
841 
842 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)843 coap_send_error(coap_session_t *session,
844                 const coap_pdu_t *request,
845                 coap_pdu_code_t code,
846                 coap_opt_filter_t *opts) {
847   coap_pdu_t *response;
848   coap_mid_t result = COAP_INVALID_MID;
849 
850   assert(request);
851   assert(session);
852 
853   response = coap_new_error_response(request, code, opts);
854   if (response)
855     result = coap_send_internal(session, response);
856 
857   return result;
858 }
859 
860 coap_mid_t
coap_send_message_type(coap_session_t * session,const coap_pdu_t * request,coap_pdu_type_t type)861 coap_send_message_type(coap_session_t *session, const coap_pdu_t *request,
862                        coap_pdu_type_t type) {
863   coap_pdu_t *response;
864   coap_mid_t result = COAP_INVALID_MID;
865 
866   if (request && COAP_PROTO_NOT_RELIABLE(session->proto)) {
867     response = coap_pdu_init(type, 0, request->mid, 0);
868     if (response)
869       result = coap_send_internal(session, response);
870   }
871   return result;
872 }
873 
874 /**
875  * Calculates the initial timeout based on the session CoAP transmission
876  * parameters 'ack_timeout', 'ack_random_factor', and COAP_TICKS_PER_SECOND.
877  * The calculation requires 'ack_timeout' and 'ack_random_factor' to be in
878  * Qx.FRAC_BITS fixed point notation, whereas the passed parameter @p r
879  * is interpreted as the fractional part of a Q0.MAX_BITS random value.
880  *
881  * @param session session timeout is associated with
882  * @param r  random value as fractional part of a Q0.MAX_BITS fixed point
883  *           value
884  * @return   COAP_TICKS_PER_SECOND * 'ack_timeout' *
885  *           (1 + ('ack_random_factor' - 1) * r)
886  */
887 unsigned int
coap_calc_timeout(coap_session_t * session,unsigned char r)888 coap_calc_timeout(coap_session_t *session, unsigned char r) {
889   unsigned int result;
890 
891   /* The integer 1.0 as a Qx.FRAC_BITS */
892 #define FP1 Q(FRAC_BITS, ((coap_fixed_point_t){1,0}))
893 
894   /* rounds val up and right shifts by frac positions */
895 #define SHR_FP(val,frac) (((val) + (1 << ((frac) - 1))) >> (frac))
896 
897   /* Inner term: multiply ACK_RANDOM_FACTOR by Q0.MAX_BITS[r] and
898    * make the result a rounded Qx.FRAC_BITS */
899   result = SHR_FP((ACK_RANDOM_FACTOR - FP1) * r, MAX_BITS);
900 
901   /* Add 1 to the inner term and multiply with ACK_TIMEOUT, then
902    * make the result a rounded Qx.FRAC_BITS */
903   result = SHR_FP(((result + FP1) * ACK_TIMEOUT), FRAC_BITS);
904 
905   /* Multiply with COAP_TICKS_PER_SECOND to yield system ticks
906    * (yields a Qx.FRAC_BITS) and shift to get an integer */
907   return SHR_FP((COAP_TICKS_PER_SECOND * result), FRAC_BITS);
908 
909 #undef FP1
910 #undef SHR_FP
911 }
912 
913 coap_mid_t
coap_wait_ack(coap_context_t * context,coap_session_t * session,coap_queue_t * node)914 coap_wait_ack(coap_context_t *context, coap_session_t *session,
915               coap_queue_t *node) {
916   coap_tick_t now;
917 
918   node->session = coap_session_reference(session);
919 
920   /* Set timer for pdu retransmission. If this is the first element in
921   * the retransmission queue, the base time is set to the current
922   * time and the retransmission time is node->timeout. If there is
923   * already an entry in the sendqueue, we must check if this node is
924   * to be retransmitted earlier. Therefore, node->timeout is first
925   * normalized to the base time and then inserted into the queue with
926   * an adjusted relative time.
927   */
928   coap_ticks(&now);
929   if (context->sendqueue == NULL) {
930     node->t = node->timeout << node->retransmit_cnt;
931     context->sendqueue_basetime = now;
932   } else {
933     /* make node->t relative to context->sendqueue_basetime */
934     node->t = (now - context->sendqueue_basetime) +
935               (node->timeout << node->retransmit_cnt);
936   }
937 
938   coap_insert_node(&context->sendqueue, node);
939 
940   coap_log_debug("** %s: mid=0x%04x: added to retransmit queue (%ums)\n",
941                  coap_session_str(node->session), node->id,
942                  (unsigned)((node->timeout << node->retransmit_cnt) * 1000 /
943                             COAP_TICKS_PER_SECOND));
944 
945 #ifdef COAP_EPOLL_SUPPORT
946   coap_update_epoll_timer(context, node->t);
947 #endif /* COAP_EPOLL_SUPPORT */
948 
949   return node->id;
950 }
951 
952 #if COAP_CLIENT_SUPPORT
953 /*
954  * Sent out a test PDU for Extended Token
955  */
956 static coap_mid_t
coap_send_test_extended_token(coap_session_t * session)957 coap_send_test_extended_token(coap_session_t *session) {
958   coap_pdu_t *pdu;
959   coap_mid_t mid = COAP_INVALID_MID;
960   size_t i;
961   coap_binary_t *token;
962 
963   coap_log_debug("Testing for Extended Token support\n");
964   /* https://rfc-editor.org/rfc/rfc8974#section-2.2.2 */
965   pdu = coap_pdu_init(COAP_MESSAGE_CON, COAP_REQUEST_CODE_GET,
966                       coap_new_message_id(session),
967                       coap_session_max_pdu_size(session));
968   if (!pdu)
969     return COAP_INVALID_MID;
970 
971   token = coap_new_binary(session->max_token_size);
972   if (token == NULL) {
973     coap_delete_pdu(pdu);
974     return COAP_INVALID_MID;
975   }
976   for (i = 0; i < session->max_token_size; i++) {
977     token->s[i] = (uint8_t)(i + 1);
978   }
979   coap_add_token(pdu, session->max_token_size, token->s);
980   coap_delete_binary(token);
981 
982   coap_insert_option(pdu, COAP_OPTION_IF_NONE_MATCH, 0, NULL);
983 
984   session->max_token_checked = COAP_EXT_T_CHECKING; /* Checking out this one */
985   if ((mid = coap_send_internal(session, pdu)) == COAP_INVALID_MID)
986     return COAP_INVALID_MID;
987   session->remote_test_mid = mid;
988   return mid;
989 }
990 #endif /* COAP_CLIENT_SUPPORT */
991 
992 int
coap_client_delay_first(coap_session_t * session)993 coap_client_delay_first(coap_session_t *session) {
994 #if COAP_CLIENT_SUPPORT
995   if (session->type == COAP_SESSION_TYPE_CLIENT && session->doing_first) {
996     int timeout_ms = 5000;
997 
998     if (session->delay_recursive) {
999       assert(0);
1000       return 1;
1001     } else {
1002       session->delay_recursive = 1;
1003     }
1004     /*
1005      * Need to wait for first request to get out and response back before
1006      * continuing.. Response handler has to clear doing_first if not an error.
1007      */
1008     coap_session_reference(session);
1009     while (session->doing_first != 0) {
1010       int result = coap_io_process(session->context, 1000);
1011 
1012       if (result < 0) {
1013         session->doing_first = 0;
1014         session->delay_recursive = 0;
1015         coap_session_release(session);
1016         return 0;
1017       }
1018       if (result <= timeout_ms) {
1019         timeout_ms -= result;
1020       } else {
1021         if (session->doing_first == 1) {
1022           /* Timeout failure of some sort with first request */
1023           coap_log_debug("** %s: timeout waiting for first response\n",
1024                          coap_session_str(session));
1025           session->doing_first = 0;
1026         }
1027       }
1028     }
1029     session->delay_recursive = 0;
1030     coap_session_release(session);
1031   }
1032 #else /* ! COAP_CLIENT_SUPPORT */
1033   (void)session;
1034 #endif /* ! COAP_CLIENT_SUPPORT */
1035   return 1;
1036 }
1037 
1038 coap_mid_t
coap_send(coap_session_t * session,coap_pdu_t * pdu)1039 coap_send(coap_session_t *session, coap_pdu_t *pdu) {
1040   coap_mid_t mid = COAP_INVALID_MID;
1041 #if COAP_CLIENT_SUPPORT
1042   coap_lg_crcv_t *lg_crcv = NULL;
1043   coap_opt_iterator_t opt_iter;
1044   coap_block_b_t block;
1045   int observe_action = -1;
1046   int have_block1 = 0;
1047   coap_opt_t *opt;
1048 #endif /* COAP_CLIENT_SUPPORT */
1049 
1050   assert(pdu);
1051 
1052   pdu->session = session;
1053 #if COAP_CLIENT_SUPPORT
1054   if (session->type == COAP_SESSION_TYPE_CLIENT &&
1055       !coap_netif_available(session)) {
1056     coap_log_debug("coap_send: Socket closed\n");
1057     coap_delete_pdu(pdu);
1058     return COAP_INVALID_MID;
1059   }
1060   /*
1061    * If this is not the first client request and are waiting for a response
1062    * to the first client request, then drop sending out this next request
1063    * until all is properly established.
1064    */
1065   if (!coap_client_delay_first(session)) {
1066     coap_delete_pdu(pdu);
1067     return COAP_INVALID_MID;
1068   }
1069 
1070   /* Indicate support for Extended Tokens if appropriate */
1071   if (session->max_token_checked == COAP_EXT_T_NOT_CHECKED &&
1072       session->max_token_size > COAP_TOKEN_DEFAULT_MAX &&
1073       session->type == COAP_SESSION_TYPE_CLIENT &&
1074       COAP_PDU_IS_REQUEST(pdu)) {
1075     if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
1076       /*
1077        * When the pass / fail response for Extended Token is received, this PDU
1078        * will get transmitted.
1079        */
1080       if (coap_send_test_extended_token(session) == COAP_INVALID_MID) {
1081         coap_delete_pdu(pdu);
1082         return COAP_INVALID_MID;
1083       }
1084     }
1085     /*
1086      * For reliable protocols, this will get cleared after CSM exchanged
1087      * in coap_session_connected()
1088      */
1089     session->doing_first = 1;
1090     if (!coap_client_delay_first(session)) {
1091       coap_delete_pdu(pdu);
1092       return COAP_INVALID_MID;
1093     }
1094   }
1095 
1096   /*
1097    * Check validity of token length
1098    */
1099   if (COAP_PDU_IS_REQUEST(pdu) &&
1100       pdu->actual_token.length > session->max_token_size) {
1101     coap_log_warn("coap_send: PDU dropped as token too long (%zu > %" PRIu32 ")\n",
1102                   pdu->actual_token.length, session->max_token_size);
1103     coap_delete_pdu(pdu);
1104     return COAP_INVALID_MID;
1105   }
1106 
1107   /* A lot of the reliable code assumes type is CON */
1108   if (COAP_PROTO_RELIABLE(session->proto) && pdu->type == COAP_MESSAGE_NON)
1109     pdu->type = COAP_MESSAGE_CON;
1110 
1111 #if COAP_OSCORE_SUPPORT
1112   if (session->oscore_encryption) {
1113     if (session->recipient_ctx->initial_state == 1) {
1114       /*
1115        * Not sure if remote supports OSCORE, or is going to send us a
1116        * "4.01 + ECHO" etc. so need to hold off future coap_send()s until all
1117        * is OK. Continue sending current pdu to test things.
1118        */
1119       session->doing_first = 1;
1120     }
1121     /* Need to convert Proxy-Uri to Proxy-Scheme option if needed */
1122     if (COAP_PDU_IS_REQUEST(pdu) && !coap_rebuild_pdu_for_proxy(pdu)) {
1123       coap_delete_pdu(pdu);
1124       return COAP_INVALID_MID;
1125     }
1126   }
1127 #endif /* COAP_OSCORE_SUPPORT */
1128 
1129   if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
1130     return coap_send_internal(session, pdu);
1131   }
1132 
1133   if (COAP_PDU_IS_REQUEST(pdu)) {
1134     uint8_t buf[4];
1135 
1136     opt = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
1137 
1138     if (opt) {
1139       observe_action = coap_decode_var_bytes(coap_opt_value(opt),
1140                                              coap_opt_length(opt));
1141     }
1142 
1143     if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK1, &block) &&
1144         (block.m == 1 || block.bert == 1)) {
1145       have_block1 = 1;
1146     }
1147 #if COAP_Q_BLOCK_SUPPORT
1148     if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block) &&
1149         (block.m == 1 || block.bert == 1)) {
1150       if (have_block1) {
1151         coap_log_warn("Block1 and Q-Block1 cannot be in the same request\n");
1152         coap_remove_option(pdu, COAP_OPTION_BLOCK1);
1153       }
1154       have_block1 = 1;
1155     }
1156 #endif /* COAP_Q_BLOCK_SUPPORT */
1157     if (observe_action != COAP_OBSERVE_CANCEL) {
1158       /* Warn about re-use of tokens */
1159       if (session->last_token &&
1160           coap_binary_equal(&pdu->actual_token, session->last_token)) {
1161         coap_log_debug("Token reused - see https://rfc-editor.org/rfc/rfc9175.html#section-4.2\n");
1162       }
1163       coap_delete_bin_const(session->last_token);
1164       session->last_token = coap_new_bin_const(pdu->actual_token.s,
1165                                                pdu->actual_token.length);
1166     }
1167     if (!coap_check_option(pdu, COAP_OPTION_RTAG, &opt_iter) &&
1168         (session->block_mode & COAP_BLOCK_NO_PREEMPTIVE_RTAG) == 0 &&
1169         pdu->code != COAP_REQUEST_CODE_DELETE)
1170       coap_insert_option(pdu,
1171                          COAP_OPTION_RTAG,
1172                          coap_encode_var_safe(buf, sizeof(buf),
1173                                               ++session->tx_rtag),
1174                          buf);
1175   } else {
1176     memset(&block, 0, sizeof(block));
1177   }
1178 
1179 #if COAP_Q_BLOCK_SUPPORT
1180   /* Indicate support for Q-Block if appropriate */
1181   if (session->block_mode & COAP_BLOCK_TRY_Q_BLOCK &&
1182       session->type == COAP_SESSION_TYPE_CLIENT &&
1183       COAP_PDU_IS_REQUEST(pdu)) {
1184     if (coap_block_test_q_block(session, pdu) == COAP_INVALID_MID) {
1185       coap_delete_pdu(pdu);
1186       return COAP_INVALID_MID;
1187     }
1188     session->doing_first = 1;
1189     if (!coap_client_delay_first(session)) {
1190       /* Q-Block test Session has failed for some reason */
1191       set_block_mode_drop_q(session->block_mode);
1192       coap_delete_pdu(pdu);
1193       return COAP_INVALID_MID;
1194     }
1195   }
1196 #endif /* COAP_Q_BLOCK_SUPPORT */
1197 
1198 #if COAP_Q_BLOCK_SUPPORT
1199   if (!(session->block_mode & COAP_BLOCK_HAS_Q_BLOCK))
1200 #endif /* COAP_Q_BLOCK_SUPPORT */
1201   {
1202     /* Need to check if we need to reset Q-Block to Block */
1203     uint8_t buf[4];
1204 
1205     if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2, &block)) {
1206       coap_remove_option(pdu, COAP_OPTION_Q_BLOCK2);
1207       coap_insert_option(pdu, COAP_OPTION_BLOCK2,
1208                          coap_encode_var_safe(buf, sizeof(buf),
1209                                               (block.num << 4) | (0 << 3) | block.szx),
1210                          buf);
1211       coap_log_debug("Replaced option Q-Block2 with Block2\n");
1212       /* Need to update associated lg_xmit */
1213       coap_lg_xmit_t *lg_xmit;
1214 
1215       LL_FOREACH(session->lg_xmit, lg_xmit) {
1216         if (COAP_PDU_IS_REQUEST(&lg_xmit->pdu) &&
1217             lg_xmit->b.b1.app_token &&
1218             coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1219           /* Update the skeletal PDU with the block1 option */
1220           coap_remove_option(&lg_xmit->pdu, COAP_OPTION_Q_BLOCK2);
1221           coap_update_option(&lg_xmit->pdu, COAP_OPTION_BLOCK2,
1222                              coap_encode_var_safe(buf, sizeof(buf),
1223                                                   (block.num << 4) | (0 << 3) | block.szx),
1224                              buf);
1225           break;
1226         }
1227       }
1228     }
1229     if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
1230       coap_remove_option(pdu, COAP_OPTION_Q_BLOCK1);
1231       coap_insert_option(pdu, COAP_OPTION_BLOCK1,
1232                          coap_encode_var_safe(buf, sizeof(buf),
1233                                               (block.num << 4) | (block.m << 3) | block.szx),
1234                          buf);
1235       coap_log_debug("Replaced option Q-Block1 with Block1\n");
1236       /* Need to update associated lg_xmit */
1237       coap_lg_xmit_t *lg_xmit;
1238 
1239       LL_FOREACH(session->lg_xmit, lg_xmit) {
1240         if (COAP_PDU_IS_REQUEST(&lg_xmit->pdu) &&
1241             lg_xmit->b.b1.app_token &&
1242             coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1243           /* Update the skeletal PDU with the block1 option */
1244           coap_remove_option(&lg_xmit->pdu, COAP_OPTION_Q_BLOCK1);
1245           coap_update_option(&lg_xmit->pdu, COAP_OPTION_BLOCK1,
1246                              coap_encode_var_safe(buf, sizeof(buf),
1247                                                   (block.num << 4) |
1248                                                   (block.m << 3) |
1249                                                   block.szx),
1250                              buf);
1251           /* Update as this is a Request */
1252           lg_xmit->option = COAP_OPTION_BLOCK1;
1253           break;
1254         }
1255       }
1256     }
1257   }
1258 
1259 #if COAP_Q_BLOCK_SUPPORT
1260   if (COAP_PDU_IS_REQUEST(pdu) &&
1261       coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2, &block)) {
1262     if (block.num == 0 && block.m == 0) {
1263       uint8_t buf[4];
1264 
1265       /* M needs to be set as asking for all the blocks */
1266       coap_update_option(pdu, COAP_OPTION_Q_BLOCK2,
1267                          coap_encode_var_safe(buf, sizeof(buf),
1268                                               (0 << 4) | (1 << 3) | block.szx),
1269                          buf);
1270     }
1271   }
1272   if (pdu->type == COAP_MESSAGE_NON && pdu->code == COAP_REQUEST_CODE_FETCH &&
1273       coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter) &&
1274       coap_check_option(pdu, COAP_OPTION_Q_BLOCK1, &opt_iter)) {
1275     /* Issue with Fetch + Observe + Q-Block1 + NON if there are
1276      * retransmits as potential for Token confusion */
1277     pdu->type = COAP_MESSAGE_CON;
1278     /* Need to update associated lg_xmit */
1279     coap_lg_xmit_t *lg_xmit;
1280 
1281     LL_FOREACH(session->lg_xmit, lg_xmit) {
1282       if (lg_xmit->pdu.code == COAP_REQUEST_CODE_FETCH &&
1283           lg_xmit->b.b1.app_token &&
1284           coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1285         /* Update as this is a Request */
1286         lg_xmit->pdu.type = COAP_MESSAGE_CON;
1287         break;
1288       }
1289     }
1290   }
1291 #endif /* COAP_Q_BLOCK_SUPPORT */
1292 
1293   /*
1294    * If type is CON and protocol is not reliable, there is no need to set up
1295    * lg_crcv here as it can be built up based on sent PDU if there is a
1296    * (Q-)Block2 in the response.  However, still need it for Observe, Oscore and
1297    * (Q-)Block1.
1298    */
1299   if (observe_action != -1 || have_block1 ||
1300 #if COAP_OSCORE_SUPPORT
1301       session->oscore_encryption ||
1302 #endif /* COAP_OSCORE_SUPPORT */
1303       ((pdu->type == COAP_MESSAGE_NON || COAP_PROTO_RELIABLE(session->proto)) &&
1304        COAP_PDU_IS_REQUEST(pdu) && pdu->code != COAP_REQUEST_CODE_DELETE)) {
1305     coap_lg_xmit_t *lg_xmit = NULL;
1306 
1307     if (!session->lg_xmit && have_block1) {
1308       coap_log_debug("PDU presented by app\n");
1309       coap_show_pdu(COAP_LOG_DEBUG, pdu);
1310     }
1311     /* See if this token is already in use for large body responses */
1312     LL_FOREACH(session->lg_crcv, lg_crcv) {
1313       if (coap_binary_equal(&pdu->actual_token, lg_crcv->app_token)) {
1314 
1315         if (observe_action == COAP_OBSERVE_CANCEL) {
1316           uint8_t buf[8];
1317           size_t len;
1318 
1319           /* Need to update token to server's version */
1320           len = coap_encode_var_safe8(buf, sizeof(lg_crcv->state_token),
1321                                       lg_crcv->state_token);
1322           if (pdu->code == COAP_REQUEST_CODE_FETCH && lg_crcv->obs_token &&
1323               lg_crcv->obs_token[0]) {
1324             memcpy(buf, lg_crcv->obs_token[0]->s, lg_crcv->obs_token[0]->length);
1325             len = lg_crcv->obs_token[0]->length;
1326           }
1327           coap_update_token(pdu, len, buf);
1328           lg_crcv->initial = 1;
1329           lg_crcv->observe_set = 0;
1330           /* de-reference lg_crcv as potentially linking in later */
1331           LL_DELETE(session->lg_crcv, lg_crcv);
1332           goto send_it;
1333         }
1334 
1335         /* Need to terminate and clean up previous response setup */
1336         LL_DELETE(session->lg_crcv, lg_crcv);
1337         coap_block_delete_lg_crcv(session, lg_crcv);
1338         break;
1339       }
1340     }
1341 
1342     if (have_block1 && session->lg_xmit) {
1343       LL_FOREACH(session->lg_xmit, lg_xmit) {
1344         if (COAP_PDU_IS_REQUEST(&lg_xmit->pdu) &&
1345             lg_xmit->b.b1.app_token &&
1346             coap_binary_equal(&pdu->actual_token, lg_xmit->b.b1.app_token)) {
1347           break;
1348         }
1349       }
1350     }
1351     lg_crcv = coap_block_new_lg_crcv(session, pdu, lg_xmit);
1352     if (lg_crcv == NULL) {
1353       coap_delete_pdu(pdu);
1354       return COAP_INVALID_MID;
1355     }
1356     if (lg_xmit) {
1357       /* Need to update the token as set up in the session->lg_xmit */
1358       lg_xmit->b.b1.state_token = lg_crcv->state_token;
1359     }
1360   }
1361   if (session->sock.flags & COAP_SOCKET_MULTICAST)
1362     coap_address_copy(&session->addr_info.remote, &session->sock.mcast_addr);
1363 
1364 send_it:
1365 #if COAP_Q_BLOCK_SUPPORT
1366   /* See if large xmit using Q-Block1 (but not testing Q-Block1) */
1367   if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
1368     mid = coap_send_q_block1(session, block, pdu, COAP_SEND_INC_PDU);
1369   } else
1370 #endif /* COAP_Q_BLOCK_SUPPORT */
1371     mid = coap_send_internal(session, pdu);
1372 #else /* !COAP_CLIENT_SUPPORT */
1373   mid = coap_send_internal(session, pdu);
1374 #endif /* !COAP_CLIENT_SUPPORT */
1375 #if COAP_CLIENT_SUPPORT
1376   if (lg_crcv) {
1377     if (mid != COAP_INVALID_MID) {
1378       LL_PREPEND(session->lg_crcv, lg_crcv);
1379     } else {
1380       coap_block_delete_lg_crcv(session, lg_crcv);
1381     }
1382   }
1383 #endif /* COAP_CLIENT_SUPPORT */
1384   return mid;
1385 }
1386 
1387 coap_mid_t
coap_send_internal(coap_session_t * session,coap_pdu_t * pdu)1388 coap_send_internal(coap_session_t *session, coap_pdu_t *pdu) {
1389   uint8_t r;
1390   ssize_t bytes_written;
1391   coap_opt_iterator_t opt_iter;
1392 
1393   pdu->session = session;
1394   if (pdu->code == COAP_RESPONSE_CODE(508)) {
1395     /*
1396      * Need to prepend our IP identifier to the data as per
1397      * https://rfc-editor.org/rfc/rfc8768.html#section-4
1398      */
1399     char addr_str[INET6_ADDRSTRLEN + 8 + 1];
1400     coap_opt_t *opt;
1401     size_t hop_limit;
1402 
1403     addr_str[sizeof(addr_str)-1] = '\000';
1404     if (coap_print_addr(&session->addr_info.local, (uint8_t *)addr_str,
1405                         sizeof(addr_str) - 1)) {
1406       char *cp;
1407       size_t len;
1408 
1409       if (addr_str[0] == '[') {
1410         cp = strchr(addr_str, ']');
1411         if (cp)
1412           *cp = '\000';
1413         if (memcmp(&addr_str[1], "::ffff:", 7) == 0) {
1414           /* IPv4 embedded into IPv6 */
1415           cp = &addr_str[8];
1416         } else {
1417           cp = &addr_str[1];
1418         }
1419       } else {
1420         cp = strchr(addr_str, ':');
1421         if (cp)
1422           *cp = '\000';
1423         cp = addr_str;
1424       }
1425       len = strlen(cp);
1426 
1427       /* See if Hop Limit option is being used in return path */
1428       opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
1429       if (opt) {
1430         uint8_t buf[4];
1431 
1432         hop_limit =
1433             coap_decode_var_bytes(coap_opt_value(opt), coap_opt_length(opt));
1434         if (hop_limit == 1) {
1435           coap_log_warn("Proxy loop detected '%s'\n",
1436                         (char *)pdu->data);
1437           coap_delete_pdu(pdu);
1438           return (coap_mid_t)COAP_DROPPED_RESPONSE;
1439         } else if (hop_limit < 1 || hop_limit > 255) {
1440           /* Something is bad - need to drop this pdu (TODO or delete option) */
1441           coap_log_warn("Proxy return has bad hop limit count '%zu'\n",
1442                         hop_limit);
1443           coap_delete_pdu(pdu);
1444           return (coap_mid_t)COAP_DROPPED_RESPONSE;
1445         }
1446         hop_limit--;
1447         coap_update_option(pdu, COAP_OPTION_HOP_LIMIT,
1448                            coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
1449                            buf);
1450       }
1451 
1452       /* Need to check that we are not seeing this proxy in the return loop */
1453       if (pdu->data && opt == NULL) {
1454         char *a_match;
1455         size_t data_len;
1456 
1457         if (pdu->used_size + 1 > pdu->max_size) {
1458           /* No space */
1459           return (coap_mid_t)COAP_DROPPED_RESPONSE;
1460         }
1461         if (!coap_pdu_resize(pdu, pdu->used_size + 1)) {
1462           /* Internal error */
1463           return (coap_mid_t)COAP_DROPPED_RESPONSE;
1464         }
1465         data_len = pdu->used_size - (pdu->data - pdu->token);
1466         pdu->data[data_len] = '\000';
1467         a_match = strstr((char *)pdu->data, cp);
1468         if (a_match && (a_match == (char *)pdu->data || a_match[-1] == ' ') &&
1469             ((size_t)(a_match - (char *)pdu->data + len) == data_len ||
1470              a_match[len] == ' ')) {
1471           coap_log_warn("Proxy loop detected '%s'\n",
1472                         (char *)pdu->data);
1473           coap_delete_pdu(pdu);
1474           return (coap_mid_t)COAP_DROPPED_RESPONSE;
1475         }
1476       }
1477       if (pdu->used_size + len + 1 <= pdu->max_size) {
1478         size_t old_size = pdu->used_size;
1479         if (coap_pdu_resize(pdu, pdu->used_size + len + 1)) {
1480           if (pdu->data == NULL) {
1481             /*
1482              * Set Hop Limit to max for return path.  If this libcoap is in
1483              * a proxy loop path, it will always decrement hop limit in code
1484              * above and hence timeout / drop the response as appropriate
1485              */
1486             hop_limit = 255;
1487             coap_insert_option(pdu, COAP_OPTION_HOP_LIMIT, 1,
1488                                (uint8_t *)&hop_limit);
1489             coap_add_data(pdu, len, (uint8_t *)cp);
1490           } else {
1491             /* prepend with space separator, leaving hop limit "as is" */
1492             memmove(pdu->data + len + 1, pdu->data,
1493                     old_size - (pdu->data - pdu->token));
1494             memcpy(pdu->data, cp, len);
1495             pdu->data[len] = ' ';
1496             pdu->used_size += len + 1;
1497           }
1498         }
1499       }
1500     }
1501   }
1502 
1503   if (session->echo) {
1504     if (!coap_insert_option(pdu, COAP_OPTION_ECHO, session->echo->length,
1505                             session->echo->s))
1506       goto error;
1507     coap_delete_bin_const(session->echo);
1508     session->echo = NULL;
1509   }
1510 #if COAP_OSCORE_SUPPORT
1511   if (session->oscore_encryption) {
1512     /* Need to convert Proxy-Uri to Proxy-Scheme option if needed */
1513     if (COAP_PDU_IS_REQUEST(pdu) && !coap_rebuild_pdu_for_proxy(pdu))
1514       goto error;
1515   }
1516 #endif /* COAP_OSCORE_SUPPORT */
1517 
1518   if (!coap_pdu_encode_header(pdu, session->proto)) {
1519     goto error;
1520   }
1521 
1522 #if !COAP_DISABLE_TCP
1523   if (COAP_PROTO_RELIABLE(session->proto) &&
1524       session->state == COAP_SESSION_STATE_ESTABLISHED) {
1525     if (!session->csm_block_supported) {
1526       /*
1527        * Need to check that this instance is not sending any block options as
1528        * the remote end via CSM has not informed us that there is support
1529        * https://rfc-editor.org/rfc/rfc8323#section-5.3.2
1530        * This includes potential BERT blocks.
1531        */
1532       if (coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter) != NULL) {
1533         coap_log_debug("Remote end did not indicate CSM support for Block1 enabled\n");
1534       }
1535       if (coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter) != NULL) {
1536         coap_log_debug("Remote end did not indicate CSM support for Block2 enabled\n");
1537       }
1538     } else if (!session->csm_bert_rem_support) {
1539       coap_opt_t *opt;
1540 
1541       opt = coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter);
1542       if (opt && COAP_OPT_BLOCK_SZX(opt) == 7) {
1543         coap_log_debug("Remote end did not indicate CSM support for BERT Block1\n");
1544       }
1545       opt = coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter);
1546       if (opt && COAP_OPT_BLOCK_SZX(opt) == 7) {
1547         coap_log_debug("Remote end did not indicate CSM support for BERT Block2\n");
1548       }
1549     }
1550   }
1551 #endif /* !COAP_DISABLE_TCP */
1552 
1553 #if COAP_OSCORE_SUPPORT
1554   if (session->oscore_encryption &&
1555       !(pdu->type == COAP_MESSAGE_ACK && pdu->code == COAP_EMPTY_CODE)) {
1556     /* Refactor PDU as appropriate RFC8613 */
1557     coap_pdu_t *osc_pdu = coap_oscore_new_pdu_encrypted(session, pdu, NULL,
1558                                                         0);
1559 
1560     if (osc_pdu == NULL) {
1561       coap_log_warn("OSCORE: PDU could not be encrypted\n");
1562       goto error;
1563     }
1564     bytes_written = coap_send_pdu(session, osc_pdu, NULL);
1565     coap_delete_pdu(pdu);
1566     pdu = osc_pdu;
1567   } else
1568 #endif /* COAP_OSCORE_SUPPORT */
1569     bytes_written = coap_send_pdu(session, pdu, NULL);
1570 
1571   if (bytes_written == COAP_PDU_DELAYED) {
1572     /* do not free pdu as it is stored with session for later use */
1573     return pdu->mid;
1574   }
1575   if (bytes_written < 0) {
1576     goto error;
1577   }
1578 
1579 #if !COAP_DISABLE_TCP
1580   if (COAP_PROTO_RELIABLE(session->proto) &&
1581       (size_t)bytes_written < pdu->used_size + pdu->hdr_size) {
1582     if (coap_session_delay_pdu(session, pdu, NULL) == COAP_PDU_DELAYED) {
1583       session->partial_write = (size_t)bytes_written;
1584       /* do not free pdu as it is stored with session for later use */
1585       return pdu->mid;
1586     } else {
1587       goto error;
1588     }
1589   }
1590 #endif /* !COAP_DISABLE_TCP */
1591 
1592   if (pdu->type != COAP_MESSAGE_CON
1593       || COAP_PROTO_RELIABLE(session->proto)) {
1594     coap_mid_t id = pdu->mid;
1595     coap_delete_pdu(pdu);
1596     return id;
1597   }
1598 
1599   coap_queue_t *node = coap_new_node();
1600   if (!node) {
1601     coap_log_debug("coap_wait_ack: insufficient memory\n");
1602     goto error;
1603   }
1604 
1605   node->id = pdu->mid;
1606   node->pdu = pdu;
1607   coap_prng(&r, sizeof(r));
1608   /* add timeout in range [ACK_TIMEOUT...ACK_TIMEOUT * ACK_RANDOM_FACTOR] */
1609   node->timeout = coap_calc_timeout(session, r);
1610   return coap_wait_ack(session->context, session, node);
1611 error:
1612   coap_delete_pdu(pdu);
1613   return COAP_INVALID_MID;
1614 }
1615 
1616 coap_mid_t
coap_retransmit(coap_context_t * context,coap_queue_t * node)1617 coap_retransmit(coap_context_t *context, coap_queue_t *node) {
1618   if (!context || !node)
1619     return COAP_INVALID_MID;
1620 
1621   /* re-initialize timeout when maximum number of retransmissions are not reached yet */
1622   if (node->retransmit_cnt < node->session->max_retransmit) {
1623     ssize_t bytes_written;
1624     coap_tick_t now;
1625     coap_tick_t next_delay;
1626 
1627     node->retransmit_cnt++;
1628     coap_handle_event(context, COAP_EVENT_MSG_RETRANSMITTED, node->session);
1629 
1630     next_delay = (coap_tick_t)node->timeout << node->retransmit_cnt;
1631     if (context->ping_timeout &&
1632         context->ping_timeout * COAP_TICKS_PER_SECOND < next_delay) {
1633       uint8_t byte;
1634 
1635       coap_prng(&byte, sizeof(byte));
1636       /* Don't exceed the ping timeout value */
1637       next_delay = context->ping_timeout * COAP_TICKS_PER_SECOND - 255 + byte;
1638     }
1639 
1640     coap_ticks(&now);
1641     if (context->sendqueue == NULL) {
1642       node->t = next_delay;
1643       context->sendqueue_basetime = now;
1644     } else {
1645       /* make node->t relative to context->sendqueue_basetime */
1646       node->t = (now - context->sendqueue_basetime) + next_delay;
1647     }
1648     coap_insert_node(&context->sendqueue, node);
1649 
1650     if (node->is_mcast) {
1651       coap_log_debug("** %s: mid=0x%04x: mcast delayed transmission\n",
1652                      coap_session_str(node->session), node->id);
1653     } else {
1654       coap_log_debug("** %s: mid=0x%04x: retransmission #%d (next %ums)\n",
1655                      coap_session_str(node->session), node->id,
1656                      node->retransmit_cnt,
1657                      (unsigned)(next_delay * 1000 / COAP_TICKS_PER_SECOND));
1658     }
1659 
1660     if (node->session->con_active)
1661       node->session->con_active--;
1662     bytes_written = coap_send_pdu(node->session, node->pdu, node);
1663 
1664     if (node->is_mcast) {
1665       coap_session_connected(node->session);
1666       coap_delete_node(node);
1667       return COAP_INVALID_MID;
1668     }
1669     if (bytes_written == COAP_PDU_DELAYED) {
1670       /* PDU was not retransmitted immediately because a new handshake is
1671          in progress. node was moved to the send queue of the session. */
1672       return node->id;
1673     }
1674 
1675     if (bytes_written < 0)
1676       return (int)bytes_written;
1677 
1678     return node->id;
1679   }
1680 
1681   /* no more retransmissions, remove node from system */
1682   coap_log_warn("** %s: mid=0x%04x: give up after %d attempts\n",
1683                 coap_session_str(node->session), node->id, node->retransmit_cnt);
1684 
1685 #if COAP_SERVER_SUPPORT
1686   /* Check if subscriptions exist that should be canceled after
1687      COAP_OBS_MAX_FAIL */
1688   if (COAP_RESPONSE_CLASS(node->pdu->code) >= 2) {
1689     coap_handle_failed_notify(context, node->session, &node->pdu->actual_token);
1690   }
1691 #endif /* COAP_SERVER_SUPPORT */
1692   if (node->session->con_active) {
1693     node->session->con_active--;
1694     if (node->session->state == COAP_SESSION_STATE_ESTABLISHED) {
1695       /*
1696        * As there may be another CON in a different queue entry on the same
1697        * session that needs to be immediately released,
1698        * coap_session_connected() is called.
1699        * However, there is the possibility coap_wait_ack() may be called for
1700        * this node (queue) and re-added to context->sendqueue.
1701        * coap_delete_node(node) called shortly will handle this and remove it.
1702        */
1703       coap_session_connected(node->session);
1704     }
1705   }
1706 
1707   /* And finally delete the node */
1708   if (node->pdu->type == COAP_MESSAGE_CON && context->nack_handler) {
1709     coap_check_update_token(node->session, node->pdu);
1710     context->nack_handler(node->session, node->pdu, COAP_NACK_TOO_MANY_RETRIES, node->id);
1711   }
1712   coap_delete_node(node);
1713   return COAP_INVALID_MID;
1714 }
1715 
1716 static int
coap_handle_dgram_for_proto(coap_context_t * ctx,coap_session_t * session,coap_packet_t * packet)1717 coap_handle_dgram_for_proto(coap_context_t *ctx, coap_session_t *session, coap_packet_t *packet) {
1718   uint8_t *data;
1719   size_t data_len;
1720   int result = -1;
1721 
1722   coap_packet_get_memmapped(packet, &data, &data_len);
1723   if (session->proto == COAP_PROTO_DTLS) {
1724 #if COAP_SERVER_SUPPORT
1725     if (session->type == COAP_SESSION_TYPE_HELLO)
1726       result = coap_dtls_hello(session, data, data_len);
1727     else
1728 #endif /* COAP_SERVER_SUPPORT */
1729       if (session->tls)
1730         result = coap_dtls_receive(session, data, data_len);
1731   } else if (session->proto == COAP_PROTO_UDP) {
1732     result = coap_handle_dgram(ctx, session, data, data_len);
1733   }
1734   return result;
1735 }
1736 
1737 #if COAP_CLIENT_SUPPORT
1738 static void
coap_connect_session(coap_session_t * session,coap_tick_t now)1739 coap_connect_session(coap_session_t *session, coap_tick_t now) {
1740 #if COAP_DISABLE_TCP
1741   (void)now;
1742 
1743   session->sock.flags &= ~(COAP_SOCKET_WANT_CONNECT | COAP_SOCKET_CAN_CONNECT);
1744 #else /* !COAP_DISABLE_TCP */
1745   if (coap_netif_strm_connect2(session)) {
1746     session->last_rx_tx = now;
1747     coap_handle_event(session->context, COAP_EVENT_TCP_CONNECTED, session);
1748     session->sock.lfunc[COAP_LAYER_SESSION].l_establish(session);
1749   } else {
1750     coap_handle_event(session->context, COAP_EVENT_TCP_FAILED, session);
1751     coap_session_disconnected(session, COAP_NACK_NOT_DELIVERABLE);
1752   }
1753 #endif /* !COAP_DISABLE_TCP */
1754 }
1755 #endif /* COAP_CLIENT_SUPPORT */
1756 
1757 static void
coap_write_session(coap_context_t * ctx,coap_session_t * session,coap_tick_t now)1758 coap_write_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now) {
1759   (void)ctx;
1760   assert(session->sock.flags & COAP_SOCKET_CONNECTED);
1761 
1762   while (session->delayqueue) {
1763     ssize_t bytes_written;
1764     coap_queue_t *q = session->delayqueue;
1765     coap_log_debug("** %s: mid=0x%04x: transmitted after delay\n",
1766                    coap_session_str(session), (int)q->pdu->mid);
1767     assert(session->partial_write < q->pdu->used_size + q->pdu->hdr_size);
1768     bytes_written = session->sock.lfunc[COAP_LAYER_SESSION].l_write(session,
1769                     q->pdu->token - q->pdu->hdr_size + session->partial_write,
1770                     q->pdu->used_size + q->pdu->hdr_size - session->partial_write);
1771     if (bytes_written > 0)
1772       session->last_rx_tx = now;
1773     if (bytes_written <= 0 ||
1774         (size_t)bytes_written < q->pdu->used_size + q->pdu->hdr_size - session->partial_write) {
1775       if (bytes_written > 0)
1776         session->partial_write += (size_t)bytes_written;
1777       break;
1778     }
1779     session->delayqueue = q->next;
1780     session->partial_write = 0;
1781     coap_delete_node(q);
1782   }
1783 }
1784 
1785 static void
coap_read_session(coap_context_t * ctx,coap_session_t * session,coap_tick_t now)1786 coap_read_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now) {
1787 #if COAP_CONSTRAINED_STACK
1788   /* payload and packet protected by mutex m_read_session */
1789   static unsigned char payload[COAP_RXBUFFER_SIZE];
1790   static coap_packet_t s_packet;
1791 #else /* ! COAP_CONSTRAINED_STACK */
1792   unsigned char payload[COAP_RXBUFFER_SIZE];
1793   coap_packet_t s_packet;
1794 #endif /* ! COAP_CONSTRAINED_STACK */
1795   coap_packet_t *packet = &s_packet;
1796 
1797 #if COAP_CONSTRAINED_STACK
1798   coap_mutex_lock(&m_read_session);
1799 #endif /* COAP_CONSTRAINED_STACK */
1800 
1801 #ifdef COAP_SUPPORT_SOCKET_BROADCAST
1802   assert(session->sock.flags & (COAP_SOCKET_CONNECTED | COAP_SOCKET_MULTICAST | COAP_SOCKET_BROADCAST));
1803 #else
1804   assert(session->sock.flags & (COAP_SOCKET_CONNECTED | COAP_SOCKET_MULTICAST));
1805 #endif
1806 
1807   packet->length = sizeof(payload);
1808   packet->payload = payload;
1809 
1810   if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
1811     ssize_t bytes_read;
1812     memcpy(&packet->addr_info, &session->addr_info, sizeof(packet->addr_info));
1813     bytes_read = coap_netif_dgrm_read(session, packet);
1814 
1815     if (bytes_read < 0) {
1816       if (bytes_read == -2)
1817         /* Reset the session back to startup defaults */
1818         coap_session_disconnected(session, COAP_NACK_ICMP_ISSUE);
1819     } else if (bytes_read > 0) {
1820       session->last_rx_tx = now;
1821       memcpy(&session->addr_info, &packet->addr_info,
1822              sizeof(session->addr_info));
1823       coap_handle_dgram_for_proto(ctx, session, packet);
1824     }
1825 #if !COAP_DISABLE_TCP
1826   } else if (session->proto == COAP_PROTO_WS ||
1827              session->proto == COAP_PROTO_WSS) {
1828     ssize_t bytes_read = 0;
1829 
1830     /* WebSocket layer passes us the whole packet */
1831     bytes_read = session->sock.lfunc[COAP_LAYER_SESSION].l_read(session,
1832                                                                 packet->payload,
1833                                                                 packet->length);
1834     if (bytes_read < 0) {
1835       coap_session_disconnected(session, COAP_NACK_NOT_DELIVERABLE);
1836     } else if (bytes_read > 2) {
1837       coap_pdu_t *pdu;
1838 
1839       session->last_rx_tx = now;
1840       /* Need max space incase PDU is updated with updated token etc. */
1841       pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_rcv_size(session));
1842       if (!pdu) {
1843 #if COAP_CONSTRAINED_STACK
1844         coap_mutex_unlock(&m_read_session);
1845 #endif /* COAP_CONSTRAINED_STACK */
1846         return;
1847       }
1848 
1849       if (!coap_pdu_parse(session->proto, packet->payload, bytes_read, pdu)) {
1850         coap_handle_event(session->context, COAP_EVENT_BAD_PACKET, session);
1851         coap_log_warn("discard malformed PDU\n");
1852         coap_delete_pdu(pdu);
1853 #if COAP_CONSTRAINED_STACK
1854         coap_mutex_unlock(&m_read_session);
1855 #endif /* COAP_CONSTRAINED_STACK */
1856         return;
1857       }
1858 
1859 #if COAP_CONSTRAINED_STACK
1860       coap_mutex_unlock(&m_read_session);
1861 #endif /* COAP_CONSTRAINED_STACK */
1862       coap_dispatch(ctx, session, pdu);
1863       coap_delete_pdu(pdu);
1864       return;
1865     }
1866   } else {
1867     ssize_t bytes_read = 0;
1868     const uint8_t *p;
1869     int retry;
1870 
1871     do {
1872       bytes_read = session->sock.lfunc[COAP_LAYER_SESSION].l_read(session,
1873                                                                   packet->payload,
1874                                                                   packet->length);
1875       if (bytes_read > 0) {
1876         session->last_rx_tx = now;
1877       }
1878       p = packet->payload;
1879       retry = bytes_read == (ssize_t)packet->length;
1880       while (bytes_read > 0) {
1881         if (session->partial_pdu) {
1882           size_t len = session->partial_pdu->used_size
1883                        + session->partial_pdu->hdr_size
1884                        - session->partial_read;
1885           size_t n = min(len, (size_t)bytes_read);
1886           memcpy(session->partial_pdu->token - session->partial_pdu->hdr_size
1887                  + session->partial_read, p, n);
1888           p += n;
1889           bytes_read -= n;
1890           if (n == len) {
1891             if (coap_pdu_parse_header(session->partial_pdu, session->proto)
1892                 && coap_pdu_parse_opt(session->partial_pdu)) {
1893 #if COAP_CONSTRAINED_STACK
1894               coap_mutex_unlock(&m_read_session);
1895 #endif /* COAP_CONSTRAINED_STACK */
1896               coap_dispatch(ctx, session, session->partial_pdu);
1897 #if COAP_CONSTRAINED_STACK
1898               coap_mutex_lock(&m_read_session);
1899 #endif /* COAP_CONSTRAINED_STACK */
1900             }
1901             coap_delete_pdu(session->partial_pdu);
1902             session->partial_pdu = NULL;
1903             session->partial_read = 0;
1904           } else {
1905             session->partial_read += n;
1906           }
1907         } else if (session->partial_read > 0) {
1908           size_t hdr_size = coap_pdu_parse_header_size(session->proto,
1909                                                        session->read_header);
1910           size_t tkl = session->read_header[0] & 0x0f;
1911           size_t tok_ext_bytes = tkl == COAP_TOKEN_EXT_1B_TKL ? 1 :
1912                                  tkl == COAP_TOKEN_EXT_2B_TKL ? 2 : 0;
1913           size_t len = hdr_size + tok_ext_bytes - session->partial_read;
1914           size_t n = min(len, (size_t)bytes_read);
1915           memcpy(session->read_header + session->partial_read, p, n);
1916           p += n;
1917           bytes_read -= n;
1918           if (n == len) {
1919             size_t size = coap_pdu_parse_size(session->proto, session->read_header,
1920                                               hdr_size + tok_ext_bytes);
1921             if (size > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
1922               coap_log_warn("** %s: incoming PDU length too large (%zu > %lu)\n",
1923                             coap_session_str(session),
1924                             size, COAP_DEFAULT_MAX_PDU_RX_SIZE);
1925               bytes_read = -1;
1926               break;
1927             }
1928             /* Need max space incase PDU is updated with updated token etc. */
1929             session->partial_pdu = coap_pdu_init(0, 0, 0,
1930                                                  coap_session_max_pdu_rcv_size(session));
1931             if (session->partial_pdu == NULL) {
1932               bytes_read = -1;
1933               break;
1934             }
1935             if (session->partial_pdu->alloc_size < size && !coap_pdu_resize(session->partial_pdu, size)) {
1936               bytes_read = -1;
1937               break;
1938             }
1939             session->partial_pdu->hdr_size = (uint8_t)hdr_size;
1940             session->partial_pdu->used_size = size;
1941             memcpy(session->partial_pdu->token - hdr_size, session->read_header, hdr_size + tok_ext_bytes);
1942             session->partial_read = hdr_size + tok_ext_bytes;
1943             if (size == 0) {
1944               if (coap_pdu_parse_header(session->partial_pdu, session->proto)) {
1945 #if COAP_CONSTRAINED_STACK
1946                 coap_mutex_unlock(&m_read_session);
1947 #endif /* COAP_CONSTRAINED_STACK */
1948                 coap_dispatch(ctx, session, session->partial_pdu);
1949 #if COAP_CONSTRAINED_STACK
1950                 coap_mutex_lock(&m_read_session);
1951 #endif /* COAP_CONSTRAINED_STACK */
1952               }
1953               coap_delete_pdu(session->partial_pdu);
1954               session->partial_pdu = NULL;
1955               session->partial_read = 0;
1956             }
1957           } else {
1958             session->partial_read += bytes_read;
1959           }
1960         } else {
1961           session->read_header[0] = *p++;
1962           bytes_read -= 1;
1963           if (!coap_pdu_parse_header_size(session->proto,
1964                                           session->read_header)) {
1965             bytes_read = -1;
1966             break;
1967           }
1968           session->partial_read = 1;
1969         }
1970       }
1971     } while (bytes_read == 0 && retry);
1972     if (bytes_read < 0)
1973       coap_session_disconnected(session, COAP_NACK_NOT_DELIVERABLE);
1974 #endif /* !COAP_DISABLE_TCP */
1975   }
1976 #if COAP_CONSTRAINED_STACK
1977   coap_mutex_unlock(&m_read_session);
1978 #endif /* COAP_CONSTRAINED_STACK */
1979 }
1980 
1981 #if COAP_SERVER_SUPPORT
1982 static int
coap_read_endpoint(coap_context_t * ctx,coap_endpoint_t * endpoint,coap_tick_t now)1983 coap_read_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
1984   ssize_t bytes_read = -1;
1985   int result = -1;                /* the value to be returned */
1986 #if COAP_CONSTRAINED_STACK
1987   /* payload and e_packet protected by mutex m_read_endpoint */
1988   static unsigned char payload[COAP_RXBUFFER_SIZE];
1989   static coap_packet_t e_packet;
1990 #else /* ! COAP_CONSTRAINED_STACK */
1991   unsigned char payload[COAP_RXBUFFER_SIZE];
1992   coap_packet_t e_packet;
1993 #endif /* ! COAP_CONSTRAINED_STACK */
1994   coap_packet_t *packet = &e_packet;
1995 
1996   assert(COAP_PROTO_NOT_RELIABLE(endpoint->proto));
1997   assert(endpoint->sock.flags & COAP_SOCKET_BOUND);
1998 
1999 #if COAP_CONSTRAINED_STACK
2000   coap_mutex_lock(&m_read_endpoint);
2001 #endif /* COAP_CONSTRAINED_STACK */
2002 
2003   /* Need to do this as there may be holes in addr_info */
2004   memset(&packet->addr_info, 0, sizeof(packet->addr_info));
2005   packet->length = sizeof(payload);
2006   packet->payload = payload;
2007   coap_address_init(&packet->addr_info.remote);
2008   coap_address_copy(&packet->addr_info.local, &endpoint->bind_addr);
2009 
2010   bytes_read = coap_netif_dgrm_read_ep(endpoint, packet);
2011   if (bytes_read < 0) {
2012     coap_log_warn("*  %s: read failed\n", coap_endpoint_str(endpoint));
2013   } else if (bytes_read > 0) {
2014     coap_session_t *session = coap_endpoint_get_session(endpoint, packet, now);
2015     if (session) {
2016       coap_log_debug("*  %s: netif: recv %4zd bytes\n",
2017                      coap_session_str(session), bytes_read);
2018       result = coap_handle_dgram_for_proto(ctx, session, packet);
2019       if (endpoint->proto == COAP_PROTO_DTLS && session->type == COAP_SESSION_TYPE_HELLO && result == 1)
2020         coap_session_new_dtls_session(session, now);
2021     }
2022   }
2023 #if COAP_CONSTRAINED_STACK
2024   coap_mutex_unlock(&m_read_endpoint);
2025 #endif /* COAP_CONSTRAINED_STACK */
2026   return result;
2027 }
2028 
2029 static int
coap_write_endpoint(coap_context_t * ctx,coap_endpoint_t * endpoint,coap_tick_t now)2030 coap_write_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
2031   (void)ctx;
2032   (void)endpoint;
2033   (void)now;
2034   return 0;
2035 }
2036 
2037 #if !COAP_DISABLE_TCP
2038 static int
coap_accept_endpoint(coap_context_t * ctx,coap_endpoint_t * endpoint,coap_tick_t now)2039 coap_accept_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint,
2040                      coap_tick_t now) {
2041   coap_session_t *session = coap_new_server_session(ctx, endpoint);
2042   if (session)
2043     session->last_rx_tx = now;
2044   return session != NULL;
2045 }
2046 #endif /* !COAP_DISABLE_TCP */
2047 #endif /* COAP_SERVER_SUPPORT */
2048 
2049 void
coap_io_do_io(coap_context_t * ctx,coap_tick_t now)2050 coap_io_do_io(coap_context_t *ctx, coap_tick_t now) {
2051 #ifdef COAP_EPOLL_SUPPORT
2052   (void)ctx;
2053   (void)now;
2054   coap_log_emerg("coap_io_do_io() requires libcoap not compiled for using epoll\n");
2055 #else /* ! COAP_EPOLL_SUPPORT */
2056   coap_session_t *s, *rtmp;
2057 
2058 #if COAP_SERVER_SUPPORT
2059   coap_endpoint_t *ep, *tmp;
2060   LL_FOREACH_SAFE(ctx->endpoint, ep, tmp) {
2061     if ((ep->sock.flags & COAP_SOCKET_CAN_READ) != 0)
2062       coap_read_endpoint(ctx, ep, now);
2063     if ((ep->sock.flags & COAP_SOCKET_CAN_WRITE) != 0)
2064       coap_write_endpoint(ctx, ep, now);
2065 #if !COAP_DISABLE_TCP
2066     if ((ep->sock.flags & COAP_SOCKET_CAN_ACCEPT) != 0)
2067       coap_accept_endpoint(ctx, ep, now);
2068 #endif /* !COAP_DISABLE_TCP */
2069     SESSIONS_ITER_SAFE(ep->sessions, s, rtmp) {
2070       /* Make sure the session object is not deleted in one of the callbacks  */
2071       coap_session_reference(s);
2072       if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0) {
2073         coap_read_session(ctx, s, now);
2074       }
2075       if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0) {
2076         coap_write_session(ctx, s, now);
2077       }
2078       coap_session_release(s);
2079     }
2080   }
2081 #endif /* COAP_SERVER_SUPPORT */
2082 
2083 #if COAP_CLIENT_SUPPORT
2084   SESSIONS_ITER_SAFE(ctx->sessions, s, rtmp) {
2085     /* Make sure the session object is not deleted in one of the callbacks  */
2086     coap_session_reference(s);
2087     if ((s->sock.flags & COAP_SOCKET_CAN_CONNECT) != 0) {
2088       coap_connect_session(s, now);
2089     }
2090     if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0 && s->ref > 1) {
2091       coap_read_session(ctx, s, now);
2092     }
2093     if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0 && s->ref > 1) {
2094       coap_write_session(ctx, s, now);
2095     }
2096     coap_session_release(s);
2097   }
2098 #endif /* COAP_CLIENT_SUPPORT */
2099 #endif /* ! COAP_EPOLL_SUPPORT */
2100 }
2101 
2102 /*
2103  * While this code in part replicates coap_io_do_io(), doing the functions
2104  * directly saves having to iterate through the endpoints / sessions.
2105  */
2106 void
coap_io_do_epoll(coap_context_t * ctx,struct epoll_event * events,size_t nevents)2107 coap_io_do_epoll(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
2108 #ifndef COAP_EPOLL_SUPPORT
2109   (void)ctx;
2110   (void)events;
2111   (void)nevents;
2112   coap_log_emerg("coap_io_do_epoll() requires libcoap compiled for using epoll\n");
2113 #else /* COAP_EPOLL_SUPPORT */
2114   coap_tick_t now;
2115   size_t j;
2116 
2117   coap_ticks(&now);
2118   for (j = 0; j < nevents; j++) {
2119     coap_socket_t *sock = (coap_socket_t *)events[j].data.ptr;
2120 
2121     /* Ignore 'timer trigger' ptr  which is NULL */
2122     if (sock) {
2123 #if COAP_SERVER_SUPPORT
2124       if (sock->endpoint) {
2125         coap_endpoint_t *endpoint = sock->endpoint;
2126         if ((sock->flags & COAP_SOCKET_WANT_READ) &&
2127             (events[j].events & EPOLLIN)) {
2128           sock->flags |= COAP_SOCKET_CAN_READ;
2129           coap_read_endpoint(endpoint->context, endpoint, now);
2130         }
2131 
2132         if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
2133             (events[j].events & EPOLLOUT)) {
2134           /*
2135            * Need to update this to EPOLLIN as EPOLLOUT will normally always
2136            * be true causing epoll_wait to return early
2137            */
2138           coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2139           sock->flags |= COAP_SOCKET_CAN_WRITE;
2140           coap_write_endpoint(endpoint->context, endpoint, now);
2141         }
2142 
2143 #if !COAP_DISABLE_TCP
2144         if ((sock->flags & COAP_SOCKET_WANT_ACCEPT) &&
2145             (events[j].events & EPOLLIN)) {
2146           sock->flags |= COAP_SOCKET_CAN_ACCEPT;
2147           coap_accept_endpoint(endpoint->context, endpoint, now);
2148         }
2149 #endif /* !COAP_DISABLE_TCP */
2150 
2151       } else
2152 #endif /* COAP_SERVER_SUPPORT */
2153         if (sock->session) {
2154           coap_session_t *session = sock->session;
2155 
2156           /* Make sure the session object is not deleted
2157              in one of the callbacks  */
2158           coap_session_reference(session);
2159 #if COAP_CLIENT_SUPPORT
2160           if ((sock->flags & COAP_SOCKET_WANT_CONNECT) &&
2161               (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2162             sock->flags |= COAP_SOCKET_CAN_CONNECT;
2163             coap_connect_session(session, now);
2164             if (coap_netif_available(session) &&
2165                 !(sock->flags & COAP_SOCKET_WANT_WRITE)) {
2166               coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2167             }
2168           }
2169 #endif /* COAP_CLIENT_SUPPORT */
2170 
2171           if ((sock->flags & COAP_SOCKET_WANT_READ) &&
2172               (events[j].events & (EPOLLIN|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2173             sock->flags |= COAP_SOCKET_CAN_READ;
2174             coap_read_session(session->context, session, now);
2175           }
2176 
2177           if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
2178               (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2179             /*
2180              * Need to update this to EPOLLIN as EPOLLOUT will normally always
2181              * be true causing epoll_wait to return early
2182              */
2183             coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2184             sock->flags |= COAP_SOCKET_CAN_WRITE;
2185             coap_write_session(session->context, session, now);
2186           }
2187           /* Now dereference session so it can go away if needed */
2188           coap_session_release(session);
2189         }
2190     } else if (ctx->eptimerfd != -1) {
2191       /*
2192        * 'timer trigger' must have fired. eptimerfd needs to be read to clear
2193        *  it so that it does not set EPOLLIN in the next epoll_wait().
2194        */
2195       uint64_t count;
2196 
2197       /* Check the result from read() to suppress the warning on
2198        * systems that declare read() with warn_unused_result. */
2199       if (read(ctx->eptimerfd, &count, sizeof(count)) == -1) {
2200         /* do nothing */;
2201       }
2202     }
2203   }
2204   /* And update eptimerfd as to when to next trigger */
2205   coap_ticks(&now);
2206   coap_io_prepare_epoll(ctx, now);
2207 #endif /* COAP_EPOLL_SUPPORT */
2208 }
2209 
2210 int
coap_handle_dgram(coap_context_t * ctx,coap_session_t * session,uint8_t * msg,size_t msg_len)2211 coap_handle_dgram(coap_context_t *ctx, coap_session_t *session,
2212                   uint8_t *msg, size_t msg_len) {
2213 
2214   coap_pdu_t *pdu = NULL;
2215 
2216   assert(COAP_PROTO_NOT_RELIABLE(session->proto));
2217   if (msg_len < 4) {
2218     /* Minimum size of CoAP header - ignore runt */
2219     return -1;
2220   }
2221 
2222   /* Need max space incase PDU is updated with updated token etc. */
2223   pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_rcv_size(session));
2224   if (!pdu)
2225     goto error;
2226 
2227   if (!coap_pdu_parse(session->proto, msg, msg_len, pdu)) {
2228     coap_handle_event(session->context, COAP_EVENT_BAD_PACKET, session);
2229     coap_log_warn("discard malformed PDU\n");
2230     goto error;
2231   }
2232 
2233   coap_dispatch(ctx, session, pdu);
2234   coap_delete_pdu(pdu);
2235   return 0;
2236 
2237 error:
2238   /*
2239    * https://rfc-editor.org/rfc/rfc7252#section-4.2 MUST send RST
2240    * https://rfc-editor.org/rfc/rfc7252#section-4.3 MAY send RST
2241    */
2242   coap_send_rst(session, pdu);
2243   coap_delete_pdu(pdu);
2244   return -1;
2245 }
2246 
2247 int
coap_remove_from_queue(coap_queue_t ** queue,coap_session_t * session,coap_mid_t id,coap_queue_t ** node)2248 coap_remove_from_queue(coap_queue_t **queue, coap_session_t *session, coap_mid_t id,
2249                        coap_queue_t **node) {
2250   coap_queue_t *p, *q;
2251 
2252   if (!queue || !*queue)
2253     return 0;
2254 
2255   /* replace queue head if PDU's time is less than head's time */
2256 
2257   if (session == (*queue)->session && id == (*queue)->id) { /* found message id */
2258     *node = *queue;
2259     *queue = (*queue)->next;
2260     if (*queue) {          /* adjust relative time of new queue head */
2261       (*queue)->t += (*node)->t;
2262     }
2263     (*node)->next = NULL;
2264     coap_log_debug("** %s: mid=0x%04x: removed (1)\n",
2265                    coap_session_str(session), id);
2266     return 1;
2267   }
2268 
2269   /* search message id queue to remove (only first occurence will be removed) */
2270   q = *queue;
2271   do {
2272     p = q;
2273     q = q->next;
2274   } while (q && (session != q->session || id != q->id));
2275 
2276   if (q) {                        /* found message id */
2277     p->next = q->next;
2278     if (p->next) {                /* must update relative time of p->next */
2279       p->next->t += q->t;
2280     }
2281     q->next = NULL;
2282     *node = q;
2283     coap_log_debug("** %s: mid=0x%04x: removed (2)\n",
2284                    coap_session_str(session), id);
2285     return 1;
2286   }
2287 
2288   return 0;
2289 
2290 }
2291 
2292 void
coap_cancel_session_messages(coap_context_t * context,coap_session_t * session,coap_nack_reason_t reason)2293 coap_cancel_session_messages(coap_context_t *context, coap_session_t *session,
2294                              coap_nack_reason_t reason) {
2295   coap_queue_t *p, *q;
2296 
2297   while (context->sendqueue && context->sendqueue->session == session) {
2298     q = context->sendqueue;
2299     context->sendqueue = q->next;
2300     coap_log_debug("** %s: mid=0x%04x: removed (3)\n",
2301                    coap_session_str(session), q->id);
2302     if (q->pdu->type == COAP_MESSAGE_CON && context->nack_handler) {
2303       coap_check_update_token(session, q->pdu);
2304       context->nack_handler(session, q->pdu, reason, q->id);
2305     }
2306     coap_delete_node(q);
2307   }
2308 
2309   if (!context->sendqueue)
2310     return;
2311 
2312   p = context->sendqueue;
2313   q = p->next;
2314 
2315   while (q) {
2316     if (q->session == session) {
2317       p->next = q->next;
2318       coap_log_debug("** %s: mid=0x%04x: removed (4)\n",
2319                      coap_session_str(session), q->id);
2320       if (q->pdu->type == COAP_MESSAGE_CON && context->nack_handler) {
2321         coap_check_update_token(session, q->pdu);
2322         context->nack_handler(session, q->pdu, reason, q->id);
2323       }
2324       coap_delete_node(q);
2325       q = p->next;
2326     } else {
2327       p = q;
2328       q = q->next;
2329     }
2330   }
2331 }
2332 
2333 void
coap_cancel_all_messages(coap_context_t * context,coap_session_t * session,coap_bin_const_t * token)2334 coap_cancel_all_messages(coap_context_t *context, coap_session_t *session,
2335                          coap_bin_const_t *token) {
2336   /* cancel all messages in sendqueue that belong to session
2337    * and use the specified token */
2338   coap_queue_t **p, *q;
2339 
2340   if (!context->sendqueue)
2341     return;
2342 
2343   p = &context->sendqueue;
2344   q = *p;
2345 
2346   while (q) {
2347     if (q->session == session &&
2348         coap_binary_equal(&q->pdu->actual_token, token)) {
2349       *p = q->next;
2350       coap_log_debug("** %s: mid=0x%04x: removed (6)\n",
2351                      coap_session_str(session), q->id);
2352       if (q->pdu->type == COAP_MESSAGE_CON && session->con_active) {
2353         session->con_active--;
2354         if (session->state == COAP_SESSION_STATE_ESTABLISHED)
2355           /* Flush out any entries on session->delayqueue */
2356           coap_session_connected(session);
2357       }
2358       coap_delete_node(q);
2359     } else {
2360       p = &(q->next);
2361     }
2362     q = *p;
2363   }
2364 }
2365 
2366 coap_pdu_t *
coap_new_error_response(const coap_pdu_t * request,coap_pdu_code_t code,coap_opt_filter_t * opts)2367 coap_new_error_response(const coap_pdu_t *request, coap_pdu_code_t code,
2368                         coap_opt_filter_t *opts) {
2369   coap_opt_iterator_t opt_iter;
2370   coap_pdu_t *response;
2371   size_t size = request->e_token_length;
2372   unsigned char type;
2373   coap_opt_t *option;
2374   coap_option_num_t opt_num = 0;        /* used for calculating delta-storage */
2375 
2376 #if COAP_ERROR_PHRASE_LENGTH > 0
2377   const char *phrase;
2378   if (code != COAP_RESPONSE_CODE(508)) {
2379     phrase = coap_response_phrase(code);
2380 
2381     /* Need some more space for the error phrase and payload start marker */
2382     if (phrase)
2383       size += strlen(phrase) + 1;
2384   } else {
2385     /*
2386      * Need space for IP for 5.08 response which is filled in in
2387      * coap_send_internal()
2388      * https://rfc-editor.org/rfc/rfc8768.html#section-4
2389      */
2390     phrase = NULL;
2391     size += INET6_ADDRSTRLEN;
2392   }
2393 #endif
2394 
2395   assert(request);
2396 
2397   /* cannot send ACK if original request was not confirmable */
2398   type = request->type == COAP_MESSAGE_CON ?
2399          COAP_MESSAGE_ACK : COAP_MESSAGE_NON;
2400 
2401   /* Estimate how much space we need for options to copy from
2402    * request. We always need the Token, for 4.02 the unknown critical
2403    * options must be included as well. */
2404 
2405   /* we do not want these */
2406   coap_option_filter_unset(opts, COAP_OPTION_CONTENT_FORMAT);
2407   coap_option_filter_unset(opts, COAP_OPTION_HOP_LIMIT);
2408   /* Unsafe to send this back */
2409   coap_option_filter_unset(opts, COAP_OPTION_OSCORE);
2410 
2411   coap_option_iterator_init(request, &opt_iter, opts);
2412 
2413   /* Add size of each unknown critical option. As known critical
2414      options as well as elective options are not copied, the delta
2415      value might grow.
2416    */
2417   while ((option = coap_option_next(&opt_iter))) {
2418     uint16_t delta = opt_iter.number - opt_num;
2419     /* calculate space required to encode (opt_iter.number - opt_num) */
2420     if (delta < 13) {
2421       size++;
2422     } else if (delta < 269) {
2423       size += 2;
2424     } else {
2425       size += 3;
2426     }
2427 
2428     /* add coap_opt_length(option) and the number of additional bytes
2429      * required to encode the option length */
2430 
2431     size += coap_opt_length(option);
2432     switch (*option & 0x0f) {
2433     case 0x0e:
2434       size++;
2435     /* fall through */
2436     case 0x0d:
2437       size++;
2438       break;
2439     default:
2440       ;
2441     }
2442 
2443     opt_num = opt_iter.number;
2444   }
2445 
2446   /* Now create the response and fill with options and payload data. */
2447   response = coap_pdu_init(type, code, request->mid, size);
2448   if (response) {
2449     /* copy token */
2450     if (!coap_add_token(response, request->actual_token.length,
2451                         request->actual_token.s)) {
2452       coap_log_debug("cannot add token to error response\n");
2453       coap_delete_pdu(response);
2454       return NULL;
2455     }
2456 
2457     /* copy all options */
2458     coap_option_iterator_init(request, &opt_iter, opts);
2459     while ((option = coap_option_next(&opt_iter))) {
2460       coap_add_option_internal(response, opt_iter.number,
2461                                coap_opt_length(option),
2462                                coap_opt_value(option));
2463     }
2464 
2465 #if COAP_ERROR_PHRASE_LENGTH > 0
2466     /* note that diagnostic messages do not need a Content-Format option. */
2467     if (phrase)
2468       coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
2469 #endif
2470   }
2471 
2472   return response;
2473 }
2474 
2475 #if COAP_SERVER_SUPPORT
2476 /**
2477  * Quick hack to determine the size of the resource description for
2478  * .well-known/core.
2479  */
2480 COAP_STATIC_INLINE ssize_t
get_wkc_len(coap_context_t * context,const coap_string_t * query_filter)2481 get_wkc_len(coap_context_t *context, const coap_string_t *query_filter) {
2482   unsigned char buf[1];
2483   size_t len = 0;
2484 
2485   if (coap_print_wellknown(context, buf, &len, UINT_MAX, query_filter) &
2486       COAP_PRINT_STATUS_ERROR) {
2487     coap_log_warn("cannot determine length of /.well-known/core\n");
2488     return -1L;
2489   }
2490 
2491   return len;
2492 }
2493 
2494 #define SZX_TO_BYTES(SZX) ((size_t)(1 << ((SZX) + 4)))
2495 
2496 static void
free_wellknown_response(coap_session_t * session COAP_UNUSED,void * app_ptr)2497 free_wellknown_response(coap_session_t *session COAP_UNUSED, void *app_ptr) {
2498   coap_delete_string(app_ptr);
2499 }
2500 
2501 static void
hnd_get_wellknown(coap_resource_t * resource,coap_session_t * session,const coap_pdu_t * request,const coap_string_t * query,coap_pdu_t * response)2502 hnd_get_wellknown(coap_resource_t *resource,
2503                   coap_session_t *session,
2504                   const coap_pdu_t *request,
2505                   const coap_string_t *query,
2506                   coap_pdu_t *response) {
2507   size_t len = 0;
2508   coap_string_t *data_string = NULL;
2509   int result = 0;
2510   ssize_t wkc_len = get_wkc_len(session->context, query);
2511 
2512   if (wkc_len) {
2513     if (wkc_len < 0)
2514       goto error;
2515     data_string = coap_new_string(wkc_len);
2516     if (!data_string)
2517       goto error;
2518 
2519     len = wkc_len;
2520     result = coap_print_wellknown(session->context, data_string->s, &len, 0,
2521                                   query);
2522     if ((result & COAP_PRINT_STATUS_ERROR) != 0) {
2523       coap_log_debug("coap_print_wellknown failed\n");
2524       goto error;
2525     }
2526     assert(len <= (size_t)wkc_len);
2527     data_string->length = len;
2528 
2529     if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
2530       uint8_t buf[4];
2531 
2532       if (!coap_insert_option(response, COAP_OPTION_CONTENT_FORMAT,
2533                               coap_encode_var_safe(buf, sizeof(buf),
2534                                                    COAP_MEDIATYPE_APPLICATION_LINK_FORMAT), buf)) {
2535         goto error;
2536       }
2537       if (response->used_size + len + 1 > response->max_size) {
2538         /*
2539          * Data does not fit into a packet and no libcoap block support
2540          * +1 for end of options marker
2541          */
2542         coap_log_debug(".well-known/core: truncating data length to %zu from %zu\n",
2543                        len, response->max_size  - response->used_size - 1);
2544         len = response->max_size - response->used_size - 1;
2545       }
2546       if (!coap_add_data(response, len, data_string->s)) {
2547         goto error;
2548       }
2549       free_wellknown_response(session, data_string);
2550     } else if (!coap_add_data_large_response(resource, session, request,
2551                                              response, query,
2552                                              COAP_MEDIATYPE_APPLICATION_LINK_FORMAT,
2553                                              -1, 0, data_string->length,
2554                                              data_string->s,
2555                                              free_wellknown_response,
2556                                              data_string)) {
2557       goto error_released;
2558     }
2559   }
2560   response->code = COAP_RESPONSE_CODE(205);
2561   return;
2562 
2563 error:
2564   free_wellknown_response(session, data_string);
2565 error_released:
2566   if (response->code == 0) {
2567     /* set error code 5.03 and remove all options and data from response */
2568     response->code = COAP_RESPONSE_CODE(503);
2569     response->used_size = response->e_token_length;
2570     response->data = NULL;
2571   }
2572 }
2573 #endif /* COAP_SERVER_SUPPORT */
2574 
2575 /**
2576  * This function cancels outstanding messages for the session and
2577  * token specified in @p sent. Any observation relationship for
2578  * sent->session and the token are removed. Calling this function is
2579  * required when receiving an RST message (usually in response to a
2580  * notification) or a GET request with the Observe option set to 1.
2581  *
2582  * This function returns @c 0 when the token is unknown with this
2583  * peer, or a value greater than zero otherwise.
2584  */
2585 static int
coap_cancel(coap_context_t * context,const coap_queue_t * sent)2586 coap_cancel(coap_context_t *context, const coap_queue_t *sent) {
2587   int num_cancelled = 0;    /* the number of observers cancelled */
2588 
2589 #ifndef COAP_SERVER_SUPPORT
2590   (void)sent;
2591 #endif /* ! COAP_SERVER_SUPPORT */
2592   (void)context;
2593 
2594 #if COAP_SERVER_SUPPORT
2595   /* remove observer for this resource, if any
2596    * Use token from sent and try to find a matching resource. Uh!
2597    */
2598   RESOURCES_ITER(context->resources, r) {
2599     coap_cancel_all_messages(context, sent->session, &sent->pdu->actual_token);
2600     num_cancelled += coap_delete_observer(r, sent->session, &sent->pdu->actual_token);
2601   }
2602 #endif /* COAP_SERVER_SUPPORT */
2603 
2604   return num_cancelled;
2605 }
2606 
2607 #if COAP_SERVER_SUPPORT
2608 /**
2609  * Internal flags to control the treatment of responses (specifically
2610  * in presence of the No-Response option).
2611  */
2612 enum respond_t { RESPONSE_DEFAULT, RESPONSE_DROP, RESPONSE_SEND };
2613 
2614 /*
2615  * Checks for No-Response option in given @p request and
2616  * returns @c RESPONSE_DROP if @p response should be suppressed
2617  * according to RFC 7967.
2618  *
2619  * If the response is a confirmable piggybacked response and RESPONSE_DROP,
2620  * change it to an empty ACK and @c RESPONSE_SEND so the client does not keep
2621  * on retrying.
2622  *
2623  * Checks if the response code is 0.00 and if either the session is reliable or
2624  * non-confirmable, @c RESPONSE_DROP is also returned.
2625  *
2626  * Multicast response checking is also carried out.
2627  *
2628  * NOTE: It is the responsibility of the application to determine whether
2629  * a delayed separate response should be sent as the original requesting packet
2630  * containing the No-Response option has long since gone.
2631  *
2632  * The value of the No-Response option is encoded as
2633  * follows:
2634  *
2635  * @verbatim
2636  *  +-------+-----------------------+-----------------------------------+
2637  *  | Value | Binary Representation |          Description              |
2638  *  +-------+-----------------------+-----------------------------------+
2639  *  |   0   |      <empty>          | Interested in all responses.      |
2640  *  +-------+-----------------------+-----------------------------------+
2641  *  |   2   |      00000010         | Not interested in 2.xx responses. |
2642  *  +-------+-----------------------+-----------------------------------+
2643  *  |   8   |      00001000         | Not interested in 4.xx responses. |
2644  *  +-------+-----------------------+-----------------------------------+
2645  *  |  16   |      00010000         | Not interested in 5.xx responses. |
2646  *  +-------+-----------------------+-----------------------------------+
2647  * @endverbatim
2648  *
2649  * @param request  The CoAP request to check for the No-Response option.
2650  *                 This parameter must not be NULL.
2651  * @param response The response that is potentially suppressed.
2652  *                 This parameter must not be NULL.
2653  * @param session  The session this request/response are associated with.
2654  *                 This parameter must not be NULL.
2655  * @return RESPONSE_DEFAULT when no special treatment is requested,
2656  *         RESPONSE_DROP    when the response must be discarded, or
2657  *         RESPONSE_SEND    when the response must be sent.
2658  */
2659 static enum respond_t
no_response(coap_pdu_t * request,coap_pdu_t * response,coap_session_t * session,coap_resource_t * resource)2660 no_response(coap_pdu_t *request, coap_pdu_t *response,
2661             coap_session_t *session, coap_resource_t *resource) {
2662   coap_opt_t *nores;
2663   coap_opt_iterator_t opt_iter;
2664   unsigned int val = 0;
2665 
2666   assert(request);
2667   assert(response);
2668 
2669   if (COAP_RESPONSE_CLASS(response->code) > 0) {
2670     nores = coap_check_option(request, COAP_OPTION_NORESPONSE, &opt_iter);
2671 
2672     if (nores) {
2673       val = coap_decode_var_bytes(coap_opt_value(nores), coap_opt_length(nores));
2674 
2675       /* The response should be dropped when the bit corresponding to
2676        * the response class is set (cf. table in function
2677        * documentation). When a No-Response option is present and the
2678        * bit is not set, the sender explicitly indicates interest in
2679        * this response. */
2680       if (((1 << (COAP_RESPONSE_CLASS(response->code) - 1)) & val) > 0) {
2681         /* Should be dropping the response */
2682         if (response->type == COAP_MESSAGE_ACK &&
2683             COAP_PROTO_NOT_RELIABLE(session->proto)) {
2684           /* Still need to ACK the request */
2685           response->code = 0;
2686           /* Remove token/data from piggybacked acknowledgment PDU */
2687           response->actual_token.length = 0;
2688           response->e_token_length = 0;
2689           response->used_size = 0;
2690           response->data = NULL;
2691           return RESPONSE_SEND;
2692         } else {
2693           return RESPONSE_DROP;
2694         }
2695       } else {
2696         /* True for mcast as well RFC7967 2.1 */
2697         return RESPONSE_SEND;
2698       }
2699     } else if (resource && session->context->mcast_per_resource &&
2700                coap_is_mcast(&session->addr_info.local)) {
2701       /* Handle any mcast suppression specifics if no NoResponse option */
2702       if ((resource->flags &
2703            COAP_RESOURCE_FLAGS_LIB_ENA_MCAST_SUPPRESS_2_XX) &&
2704           COAP_RESPONSE_CLASS(response->code) == 2) {
2705         return RESPONSE_DROP;
2706       } else if ((resource->flags &
2707                   COAP_RESOURCE_FLAGS_LIB_ENA_MCAST_SUPPRESS_2_05) &&
2708                  response->code == COAP_RESPONSE_CODE(205)) {
2709         if (response->data == NULL)
2710           return RESPONSE_DROP;
2711       } else if ((resource->flags &
2712                   COAP_RESOURCE_FLAGS_LIB_DIS_MCAST_SUPPRESS_4_XX) == 0 &&
2713                  COAP_RESPONSE_CLASS(response->code) == 4) {
2714         return RESPONSE_DROP;
2715       } else if ((resource->flags &
2716                   COAP_RESOURCE_FLAGS_LIB_DIS_MCAST_SUPPRESS_5_XX) == 0 &&
2717                  COAP_RESPONSE_CLASS(response->code) == 5) {
2718         return RESPONSE_DROP;
2719       }
2720     }
2721   } else if (COAP_PDU_IS_EMPTY(response) &&
2722              (response->type == COAP_MESSAGE_NON ||
2723               COAP_PROTO_RELIABLE(session->proto))) {
2724     /* response is 0.00, and this is reliable or non-confirmable */
2725     return RESPONSE_DROP;
2726   }
2727 
2728   /*
2729    * Do not send error responses for requests that were received via
2730    * IP multicast.  RFC7252 8.1
2731    */
2732 
2733   if (coap_is_mcast(&session->addr_info.local)) {
2734     if (request->type == COAP_MESSAGE_NON &&
2735         response->type == COAP_MESSAGE_RST)
2736       return RESPONSE_DROP;
2737 
2738     if ((!resource || session->context->mcast_per_resource == 0) &&
2739         COAP_RESPONSE_CLASS(response->code) > 2)
2740       return RESPONSE_DROP;
2741   }
2742 
2743   /* Default behavior applies when we are not dealing with a response
2744    * (class == 0) or the request did not contain a No-Response option.
2745    */
2746   return RESPONSE_DEFAULT;
2747 }
2748 
2749 static coap_str_const_t coap_default_uri_wellknown = {
2750   sizeof(COAP_DEFAULT_URI_WELLKNOWN)-1,
2751   (const uint8_t *)COAP_DEFAULT_URI_WELLKNOWN
2752 };
2753 
2754 /* Initialized in coap_startup() */
2755 static coap_resource_t resource_uri_wellknown;
2756 
2757 static void
handle_request(coap_context_t * context,coap_session_t * session,coap_pdu_t * pdu)2758 handle_request(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu) {
2759   coap_method_handler_t h = NULL;
2760   coap_pdu_t *response = NULL;
2761   coap_opt_filter_t opt_filter;
2762   coap_resource_t *resource = NULL;
2763   /* The respond field indicates whether a response must be treated
2764    * specially due to a No-Response option that declares disinterest
2765    * or interest in a specific response class. DEFAULT indicates that
2766    * No-Response has not been specified. */
2767   enum respond_t respond = RESPONSE_DEFAULT;
2768   coap_opt_iterator_t opt_iter;
2769   coap_opt_t *opt;
2770   int is_proxy_uri = 0;
2771   int is_proxy_scheme = 0;
2772   int skip_hop_limit_check = 0;
2773   int resp = 0;
2774   int send_early_empty_ack = 0;
2775   coap_string_t *query = NULL;
2776   coap_opt_t *observe = NULL;
2777   coap_string_t *uri_path = NULL;
2778   int observe_action = COAP_OBSERVE_CANCEL;
2779   coap_block_b_t block;
2780   int added_block = 0;
2781   coap_lg_srcv_t *free_lg_srcv = NULL;
2782 #if COAP_Q_BLOCK_SUPPORT
2783   int lg_xmit_ctrl = 0;
2784 #endif /* COAP_Q_BLOCK_SUPPORT */
2785 #if COAP_ASYNC_SUPPORT
2786   coap_async_t *async;
2787 #endif /* COAP_ASYNC_SUPPORT */
2788 
2789   if (coap_is_mcast(&session->addr_info.local)) {
2790     if (COAP_PROTO_RELIABLE(session->proto) || pdu->type != COAP_MESSAGE_NON) {
2791       coap_log_info("Invalid multicast packet received RFC7252 8.1\n");
2792       return;
2793     }
2794   }
2795 #if COAP_ASYNC_SUPPORT
2796   async = coap_find_async(session, pdu->actual_token);
2797   if (async) {
2798     coap_tick_t now;
2799 
2800     coap_ticks(&now);
2801     if (async->delay == 0 || async->delay > now) {
2802       /* re-transmit missing ACK (only if CON) */
2803       coap_log_info("Retransmit async response\n");
2804       coap_send_ack(session, pdu);
2805       /* and do not pass on to the upper layers */
2806       return;
2807     }
2808   }
2809 #endif /* COAP_ASYNC_SUPPORT */
2810 
2811   coap_option_filter_clear(&opt_filter);
2812   opt = coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter);
2813   if (opt) {
2814     opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
2815     if (!opt) {
2816       coap_log_debug("Proxy-Scheme requires Uri-Host\n");
2817       resp = 402;
2818       goto fail_response;
2819     }
2820     is_proxy_scheme = 1;
2821   }
2822 
2823   opt = coap_check_option(pdu, COAP_OPTION_PROXY_URI, &opt_iter);
2824   if (opt)
2825     is_proxy_uri = 1;
2826 
2827   if (is_proxy_scheme || is_proxy_uri) {
2828     coap_uri_t uri;
2829 
2830     if (!context->proxy_uri_resource) {
2831       /* Need to return a 5.05 RFC7252 Section 5.7.2 */
2832       coap_log_debug("Proxy-%s support not configured\n",
2833                      is_proxy_scheme ? "Scheme" : "Uri");
2834       resp = 505;
2835       goto fail_response;
2836     }
2837     if (((size_t)pdu->code - 1 <
2838          (sizeof(resource->handler) / sizeof(resource->handler[0]))) &&
2839         !(context->proxy_uri_resource->handler[pdu->code - 1])) {
2840       /* Need to return a 5.05 RFC7252 Section 5.7.2 */
2841       coap_log_debug("Proxy-%s code %d.%02d handler not supported\n",
2842                      is_proxy_scheme ? "Scheme" : "Uri",
2843                      pdu->code/100,  pdu->code%100);
2844       resp = 505;
2845       goto fail_response;
2846     }
2847 
2848     /* Need to check if authority is the proxy endpoint RFC7252 Section 5.7.2 */
2849     if (is_proxy_uri) {
2850       if (coap_split_proxy_uri(coap_opt_value(opt),
2851                                coap_opt_length(opt), &uri) < 0) {
2852         /* Need to return a 5.05 RFC7252 Section 5.7.2 */
2853         coap_log_debug("Proxy-URI not decodable\n");
2854         resp = 505;
2855         goto fail_response;
2856       }
2857     } else {
2858       memset(&uri, 0, sizeof(uri));
2859       opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
2860       if (opt) {
2861         uri.host.length = coap_opt_length(opt);
2862         uri.host.s = coap_opt_value(opt);
2863       } else
2864         uri.host.length = 0;
2865     }
2866 
2867     resource = context->proxy_uri_resource;
2868     if (uri.host.length && resource->proxy_name_count &&
2869         resource->proxy_name_list) {
2870       size_t i;
2871 
2872       if (resource->proxy_name_count == 1 &&
2873           resource->proxy_name_list[0]->length == 0) {
2874         /* If proxy_name_list[0] is zero length, then this is the endpoint */
2875         i = 0;
2876       } else {
2877         for (i = 0; i < resource->proxy_name_count; i++) {
2878           if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
2879             break;
2880           }
2881         }
2882       }
2883       if (i != resource->proxy_name_count) {
2884         /* This server is hosting the proxy connection endpoint */
2885         if (pdu->crit_opt) {
2886           /* Cannot handle critical option */
2887           pdu->crit_opt = 0;
2888           resp = 402;
2889           goto fail_response;
2890         }
2891         is_proxy_uri = 0;
2892         is_proxy_scheme = 0;
2893         skip_hop_limit_check = 1;
2894       }
2895     }
2896     resource = NULL;
2897   }
2898 
2899   if (!skip_hop_limit_check) {
2900     opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
2901     if (opt) {
2902       size_t hop_limit;
2903       uint8_t buf[4];
2904 
2905       hop_limit =
2906           coap_decode_var_bytes(coap_opt_value(opt), coap_opt_length(opt));
2907       if (hop_limit == 1) {
2908         /* coap_send_internal() will fill in the IP address for us */
2909         resp = 508;
2910         goto fail_response;
2911       } else if (hop_limit < 1 || hop_limit > 255) {
2912         /* Need to return a 4.00 RFC8768 Section 3 */
2913         coap_log_info("Invalid Hop Limit\n");
2914         resp = 400;
2915         goto fail_response;
2916       }
2917       hop_limit--;
2918       coap_update_option(pdu, COAP_OPTION_HOP_LIMIT,
2919                          coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
2920                          buf);
2921     }
2922   }
2923 
2924   uri_path = coap_get_uri_path(pdu);
2925   if (!uri_path)
2926     return;
2927 
2928   if (!is_proxy_uri && !is_proxy_scheme) {
2929     /* try to find the resource from the request URI */
2930     coap_str_const_t uri_path_c = { uri_path->length, uri_path->s };
2931     resource = coap_get_resource_from_uri_path(context, &uri_path_c);
2932   }
2933 
2934   if ((resource == NULL) || (resource->is_unknown == 1) ||
2935       (resource->is_proxy_uri == 1)) {
2936     /* The resource was not found or there is an unexpected match against the
2937      * resource defined for handling unknown or proxy URIs.
2938      */
2939     if (resource != NULL)
2940       /* Close down unexpected match */
2941       resource = NULL;
2942     /*
2943      * Check if the request URI happens to be the well-known URI, or if the
2944      * unknown resource handler is defined, a PUT or optionally other methods,
2945      * if configured, for the unknown handler.
2946      *
2947      * if a PROXY URI/Scheme request and proxy URI handler defined, call the
2948      *  proxy URI handler
2949      *
2950      * else if well-known URI generate a default response
2951      *
2952      * else if unknown URI handler defined, call the unknown
2953      *  URI handler (to allow for potential generation of resource
2954      *  [RFC7272 5.8.3]) if the appropriate method is defined.
2955      *
2956      * else if DELETE return 2.02 (RFC7252: 5.8.4.  DELETE)
2957      *
2958      * else return 4.04 */
2959 
2960     if (is_proxy_uri || is_proxy_scheme) {
2961       resource = context->proxy_uri_resource;
2962     } else if (coap_string_equal(uri_path, &coap_default_uri_wellknown)) {
2963       /* request for .well-known/core */
2964       resource = &resource_uri_wellknown;
2965     } else if ((context->unknown_resource != NULL) &&
2966                ((size_t)pdu->code - 1 <
2967                 (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
2968                (context->unknown_resource->handler[pdu->code - 1])) {
2969       /*
2970        * The unknown_resource can be used to handle undefined resources
2971        * for a PUT request and can support any other registered handler
2972        * defined for it
2973        * Example set up code:-
2974        *   r = coap_resource_unknown_init(hnd_put_unknown);
2975        *   coap_register_request_handler(r, COAP_REQUEST_POST,
2976        *                                 hnd_post_unknown);
2977        *   coap_register_request_handler(r, COAP_REQUEST_GET,
2978        *                                 hnd_get_unknown);
2979        *   coap_register_request_handler(r, COAP_REQUEST_DELETE,
2980        *                                 hnd_delete_unknown);
2981        *   coap_add_resource(ctx, r);
2982        *
2983        * Note: It is not possible to observe the unknown_resource, a separate
2984        *       resource must be created (by PUT or POST) which has a GET
2985        *       handler to be observed
2986        */
2987       resource = context->unknown_resource;
2988     } else if (pdu->code == COAP_REQUEST_CODE_DELETE) {
2989       /*
2990        * Request for DELETE on non-existant resource (RFC7252: 5.8.4.  DELETE)
2991        */
2992       coap_log_debug("request for unknown resource '%*.*s',"
2993                      " return 2.02\n",
2994                      (int)uri_path->length,
2995                      (int)uri_path->length,
2996                      uri_path->s);
2997       resp = 202;
2998       goto fail_response;
2999     } else { /* request for any another resource, return 4.04 */
3000 
3001       coap_log_debug("request for unknown resource '%*.*s', return 4.04\n",
3002                      (int)uri_path->length, (int)uri_path->length, uri_path->s);
3003       resp = 404;
3004       goto fail_response;
3005     }
3006 
3007   }
3008 
3009 #if COAP_OSCORE_SUPPORT
3010   if ((resource->flags & COAP_RESOURCE_FLAGS_OSCORE_ONLY) && !session->oscore_encryption) {
3011     coap_log_debug("request for OSCORE only resource '%*.*s', return 4.04\n",
3012                    (int)uri_path->length, (int)uri_path->length, uri_path->s);
3013     resp = 401;
3014     goto fail_response;
3015   }
3016 #endif /* COAP_OSCORE_SUPPORT */
3017   if (resource->is_unknown == 0 && resource->is_proxy_uri == 0) {
3018     /* Check for existing resource and If-Non-Match */
3019     opt = coap_check_option(pdu, COAP_OPTION_IF_NONE_MATCH, &opt_iter);
3020     if (opt) {
3021       resp = 412;
3022       goto fail_response;
3023     }
3024   }
3025 
3026   /* the resource was found, check if there is a registered handler */
3027   if ((size_t)pdu->code - 1 <
3028       sizeof(resource->handler) / sizeof(coap_method_handler_t))
3029     h = resource->handler[pdu->code - 1];
3030 
3031   if (h == NULL) {
3032     resp = 405;
3033     goto fail_response;
3034   }
3035   if (pdu->code == COAP_REQUEST_CODE_FETCH) {
3036     opt = coap_check_option(pdu, COAP_OPTION_CONTENT_FORMAT, &opt_iter);
3037     if (opt == NULL) {
3038       /* RFC 8132 2.3.1 */
3039       resp = 415;
3040       goto fail_response;
3041     }
3042   }
3043   if (context->mcast_per_resource &&
3044       (resource->flags & COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT) == 0 &&
3045       coap_is_mcast(&session->addr_info.local)) {
3046     resp = 405;
3047     goto fail_response;
3048   }
3049 
3050   response = coap_pdu_init(pdu->type == COAP_MESSAGE_CON ?
3051                            COAP_MESSAGE_ACK : COAP_MESSAGE_NON,
3052                            0, pdu->mid, coap_session_max_pdu_size(session));
3053   if (!response) {
3054     coap_log_err("could not create response PDU\n");
3055     resp = 500;
3056     goto fail_response;
3057   }
3058   response->session = session;
3059 #if COAP_ASYNC_SUPPORT
3060   /* If handling a separate response, need CON, not ACK response */
3061   if (async && pdu->type == COAP_MESSAGE_CON)
3062     response->type = COAP_MESSAGE_CON;
3063 #endif /* COAP_ASYNC_SUPPORT */
3064 
3065   if (!coap_add_token(response, pdu->actual_token.length,
3066                       pdu->actual_token.s)) {
3067     resp = 500;
3068     goto fail_response;
3069   }
3070 
3071   query = coap_get_query(pdu);
3072 
3073   /* check for Observe option RFC7641 and RFC8132 */
3074   if (resource->observable &&
3075       (pdu->code == COAP_REQUEST_CODE_GET ||
3076        pdu->code == COAP_REQUEST_CODE_FETCH)) {
3077     observe = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
3078   }
3079 
3080   /*
3081    * See if blocks need to be aggregated or next requests sent off
3082    * before invoking application request handler
3083    */
3084   if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
3085     uint8_t block_mode = session->block_mode;
3086 
3087     if (pdu->code == COAP_REQUEST_CODE_FETCH ||
3088         resource->flags & COAP_RESOURCE_FLAGS_FORCE_SINGLE_BODY)
3089       session->block_mode |= COAP_BLOCK_SINGLE_BODY;
3090     if (coap_handle_request_put_block(context, session, pdu, response,
3091                                       resource, uri_path, observe,
3092                                       &added_block, &free_lg_srcv)) {
3093       session->block_mode = block_mode;
3094       goto skip_handler;
3095     }
3096     session->block_mode = block_mode;
3097 
3098     if (coap_handle_request_send_block(session, pdu, response, resource,
3099                                        query)) {
3100 #if COAP_Q_BLOCK_SUPPORT
3101       lg_xmit_ctrl = 1;
3102 #endif /* COAP_Q_BLOCK_SUPPORT */
3103       goto skip_handler;
3104     }
3105   }
3106 
3107   if (observe) {
3108     observe_action =
3109         coap_decode_var_bytes(coap_opt_value(observe),
3110                               coap_opt_length(observe));
3111 
3112     if (observe_action == COAP_OBSERVE_ESTABLISH) {
3113       coap_subscription_t *subscription;
3114 
3115       if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK2, &block)) {
3116         if (block.num != 0) {
3117           response->code = COAP_RESPONSE_CODE(400);
3118           goto skip_handler;
3119         }
3120 #if COAP_Q_BLOCK_SUPPORT
3121       } else if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK2,
3122                                   &block)) {
3123         if (block.num != 0) {
3124           response->code = COAP_RESPONSE_CODE(400);
3125           goto skip_handler;
3126         }
3127 #endif /* COAP_Q_BLOCK_SUPPORT */
3128       }
3129       subscription = coap_add_observer(resource, session, &pdu->actual_token,
3130                                        pdu);
3131       if (subscription) {
3132         uint8_t buf[4];
3133 
3134         coap_touch_observer(context, session, &pdu->actual_token);
3135         coap_add_option_internal(response, COAP_OPTION_OBSERVE,
3136                                  coap_encode_var_safe(buf, sizeof(buf),
3137                                                       resource->observe),
3138                                  buf);
3139       }
3140     } else if (observe_action == COAP_OBSERVE_CANCEL) {
3141       coap_delete_observer(resource, session, &pdu->actual_token);
3142     } else {
3143       coap_log_info("observe: unexpected action %d\n", observe_action);
3144     }
3145   }
3146 
3147   /* TODO for non-proxy requests */
3148   if (resource == context->proxy_uri_resource &&
3149       COAP_PROTO_NOT_RELIABLE(session->proto) &&
3150       pdu->type == COAP_MESSAGE_CON) {
3151     /* Make the proxy response separate and fix response later */
3152     send_early_empty_ack = 1;
3153   }
3154   if (send_early_empty_ack) {
3155     coap_send_ack(session, pdu);
3156     if (pdu->mid == session->last_con_mid) {
3157       /* request has already been processed - do not process it again */
3158       coap_log_debug("Duplicate request with mid=0x%04x - not processed\n",
3159                      pdu->mid);
3160       goto drop_it_no_debug;
3161     }
3162     session->last_con_mid = pdu->mid;
3163   }
3164 #if COAP_WITH_OBSERVE_PERSIST
3165   /* If we are maintaining Observe persist */
3166   if (resource == context->unknown_resource) {
3167     context->unknown_pdu = pdu;
3168     context->unknown_session = session;
3169   } else
3170     context->unknown_pdu = NULL;
3171 #endif /* COAP_WITH_OBSERVE_PERSIST */
3172 
3173   /*
3174    * Call the request handler with everything set up
3175    */
3176   coap_log_debug("call custom handler for resource '%*.*s' (3)\n",
3177                  (int)resource->uri_path->length, (int)resource->uri_path->length,
3178                  resource->uri_path->s);
3179   h(resource, session, pdu, query, response);
3180 
3181   /* Check if lg_xmit generated and update PDU code if so */
3182   coap_check_code_lg_xmit(session, pdu, response, resource, query);
3183 
3184   if (free_lg_srcv) {
3185     /* Check to see if the server is doing a 4.01 + Echo response */
3186     if (response->code ==  COAP_RESPONSE_CODE(401) &&
3187         coap_check_option(response, COAP_OPTION_ECHO, &opt_iter)) {
3188       /* Need to keep lg_srcv around for client's response */
3189     } else {
3190       LL_DELETE(session->lg_srcv, free_lg_srcv);
3191       coap_block_delete_lg_srcv(session, free_lg_srcv);
3192     }
3193   }
3194   if (added_block && COAP_RESPONSE_CLASS(response->code) == 2) {
3195     /* Just in case, as there are more to go */
3196     response->code = COAP_RESPONSE_CODE(231);
3197   }
3198 
3199 skip_handler:
3200   if (send_early_empty_ack &&
3201       response->type == COAP_MESSAGE_ACK) {
3202     /* Response is now separate - convert to CON as needed */
3203     response->type = COAP_MESSAGE_CON;
3204     /* Check for empty ACK - need to drop as already sent */
3205     if (response->code == 0) {
3206       goto drop_it_no_debug;
3207     }
3208   }
3209   respond = no_response(pdu, response, session, resource);
3210   if (respond != RESPONSE_DROP) {
3211 #if (COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG)
3212     coap_mid_t mid = pdu->mid;
3213 #endif
3214     if (COAP_RESPONSE_CLASS(response->code) != 2) {
3215       if (observe) {
3216         coap_remove_option(response, COAP_OPTION_OBSERVE);
3217       }
3218     }
3219     if (COAP_RESPONSE_CLASS(response->code) > 2) {
3220       if (observe)
3221         coap_delete_observer(resource, session, &pdu->actual_token);
3222       if (added_block)
3223         coap_remove_option(response, COAP_OPTION_BLOCK1);
3224     }
3225 
3226     /* If original request contained a token, and the registered
3227      * application handler made no changes to the response, then
3228      * this is an empty ACK with a token, which is a malformed
3229      * PDU */
3230     if ((response->type == COAP_MESSAGE_ACK)
3231         && (response->code == 0)) {
3232       /* Remove token from otherwise-empty acknowledgment PDU */
3233       response->actual_token.length = 0;
3234       response->e_token_length = 0;
3235       response->used_size = 0;
3236       response->data = NULL;
3237     }
3238 
3239     if (!coap_is_mcast(&session->addr_info.local) ||
3240         (context->mcast_per_resource &&
3241          resource &&
3242          (resource->flags & COAP_RESOURCE_FLAGS_LIB_DIS_MCAST_DELAYS))) {
3243       /* No delays to response */
3244 #if COAP_Q_BLOCK_SUPPORT
3245       if (session->block_mode & COAP_BLOCK_USE_LIBCOAP &&
3246           !lg_xmit_ctrl && response->code == COAP_RESPONSE_CODE(205) &&
3247           coap_get_block_b(session, response, COAP_OPTION_Q_BLOCK2, &block) &&
3248           block.m) {
3249         if (coap_send_q_block2(session, resource, query, pdu->code, block,
3250                                response,
3251                                COAP_SEND_INC_PDU) == COAP_INVALID_MID)
3252           coap_log_debug("cannot send response for mid=0x%x\n", mid);
3253         response = NULL;
3254         if (query)
3255           coap_delete_string(query);
3256         goto finish;
3257       }
3258 #endif /* COAP_Q_BLOCK_SUPPORT */
3259       if (coap_send_internal(session, response) == COAP_INVALID_MID) {
3260         coap_log_debug("cannot send response for mid=0x%04x\n", mid);
3261       }
3262     } else {
3263       /* Need to delay mcast response */
3264       coap_queue_t *node = coap_new_node();
3265       uint8_t r;
3266       coap_tick_t delay;
3267 
3268       if (!node) {
3269         coap_log_debug("mcast delay: insufficient memory\n");
3270         goto drop_it_no_debug;
3271       }
3272       if (!coap_pdu_encode_header(response, session->proto)) {
3273         coap_delete_node(node);
3274         goto drop_it_no_debug;
3275       }
3276 
3277       node->id = response->mid;
3278       node->pdu = response;
3279       node->is_mcast = 1;
3280       coap_prng(&r, sizeof(r));
3281       delay = (COAP_DEFAULT_LEISURE_TICKS(session) * r) / 256;
3282       coap_log_debug("   %s: mid=0x%04x: mcast response delayed for %u.%03u secs\n",
3283                      coap_session_str(session),
3284                      response->mid,
3285                      (unsigned int)(delay / COAP_TICKS_PER_SECOND),
3286                      (unsigned int)((delay % COAP_TICKS_PER_SECOND) *
3287                                     1000 / COAP_TICKS_PER_SECOND));
3288       node->timeout = (unsigned int)delay;
3289       /* Use this to delay transmission */
3290       coap_wait_ack(session->context, session, node);
3291     }
3292   } else {
3293     coap_log_debug("   %s: mid=0x%04x: response dropped\n",
3294                    coap_session_str(session),
3295                    response->mid);
3296     coap_show_pdu(COAP_LOG_DEBUG, response);
3297 drop_it_no_debug:
3298     coap_delete_pdu(response);
3299   }
3300   if (query)
3301     coap_delete_string(query);
3302 #if COAP_Q_BLOCK_SUPPORT
3303   if (coap_get_block_b(session, pdu, COAP_OPTION_Q_BLOCK1, &block)) {
3304     if (COAP_PROTO_RELIABLE(session->proto)) {
3305       if (block.m) {
3306         /* All of the sequence not in yet */
3307         goto finish;
3308       }
3309     } else if (pdu->type == COAP_MESSAGE_NON) {
3310       /* More to go and not at a payload break */
3311       if (block.m && ((block.num + 1) % COAP_MAX_PAYLOADS(session))) {
3312         goto finish;
3313       }
3314     }
3315   }
3316 #endif /* COAP_Q_BLOCK_SUPPORT */
3317 
3318 #if COAP_Q_BLOCK_SUPPORT
3319 finish:
3320 #endif /* COAP_Q_BLOCK_SUPPORT */
3321   coap_delete_string(uri_path);
3322   return;
3323 
3324 fail_response:
3325   coap_delete_pdu(response);
3326   response =
3327       coap_new_error_response(pdu, COAP_RESPONSE_CODE(resp),
3328                               &opt_filter);
3329   if (response)
3330     goto skip_handler;
3331   coap_delete_string(uri_path);
3332 }
3333 #endif /* COAP_SERVER_SUPPORT */
3334 
3335 #if COAP_CLIENT_SUPPORT
3336 static void
handle_response(coap_context_t * context,coap_session_t * session,coap_pdu_t * sent,coap_pdu_t * rcvd)3337 handle_response(coap_context_t *context, coap_session_t *session,
3338                 coap_pdu_t *sent, coap_pdu_t *rcvd) {
3339 
3340   /* In a lossy context, the ACK of a separate response may have
3341    * been lost, so we need to stop retransmitting requests with the
3342    * same token. Matching on token potentially containing ext length bytes.
3343    */
3344   if (rcvd->type != COAP_MESSAGE_ACK)
3345     coap_cancel_all_messages(context, session, &rcvd->actual_token);
3346 
3347   /* Check for message duplication */
3348   if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
3349     if (rcvd->type == COAP_MESSAGE_CON) {
3350       if (rcvd->mid == session->last_con_mid) {
3351         /* Duplicate response */
3352         return;
3353       }
3354       session->last_con_mid = rcvd->mid;
3355     } else if (rcvd->type == COAP_MESSAGE_ACK) {
3356       if (rcvd->mid == session->last_ack_mid) {
3357         /* Duplicate response */
3358         return;
3359       }
3360       session->last_ack_mid = rcvd->mid;
3361     }
3362   }
3363   /* Check to see if checking out extended token support */
3364   if (session->max_token_checked == COAP_EXT_T_CHECKING &&
3365       session->remote_test_mid == rcvd->mid) {
3366 
3367     if (rcvd->actual_token.length != session->max_token_size ||
3368         rcvd->code == COAP_RESPONSE_CODE(400) ||
3369         rcvd->code == COAP_RESPONSE_CODE(503)) {
3370       coap_log_debug("Extended Token requested size support not available\n");
3371       session->max_token_size = COAP_TOKEN_DEFAULT_MAX;
3372     } else {
3373       coap_log_debug("Extended Token support available\n");
3374     }
3375     session->max_token_checked = COAP_EXT_T_CHECKED;
3376     session->doing_first = 0;
3377     return;
3378   }
3379 #if COAP_Q_BLOCK_SUPPORT
3380   /* Check to see if checking out Q-Block support */
3381   if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK &&
3382       session->remote_test_mid == rcvd->mid) {
3383     if (rcvd->code == COAP_RESPONSE_CODE(402)) {
3384       coap_log_debug("Q-Block support not available\n");
3385       set_block_mode_drop_q(session->block_mode);
3386     } else {
3387       coap_block_b_t qblock;
3388 
3389       if (coap_get_block_b(session, rcvd, COAP_OPTION_Q_BLOCK2, &qblock)) {
3390         coap_log_debug("Q-Block support available\n");
3391         set_block_mode_has_q(session->block_mode);
3392       } else {
3393         coap_log_debug("Q-Block support not available\n");
3394         set_block_mode_drop_q(session->block_mode);
3395       }
3396     }
3397     session->doing_first = 0;
3398     return;
3399   }
3400 #endif /* COAP_Q_BLOCK_SUPPORT */
3401 
3402   if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
3403     /* See if need to send next block to server */
3404     if (coap_handle_response_send_block(session, sent, rcvd)) {
3405       /* Next block transmitted, no need to inform app */
3406       coap_send_ack(session, rcvd);
3407       return;
3408     }
3409 
3410     /* Need to see if needing to request next block */
3411     if (coap_handle_response_get_block(context, session, sent, rcvd,
3412                                        COAP_RECURSE_OK)) {
3413       /* Next block transmitted, ack sent no need to inform app */
3414       return;
3415     }
3416   }
3417   if (session->doing_first)
3418     session->doing_first = 0;
3419 
3420   /* Call application-specific response handler when available. */
3421   if (context->response_handler) {
3422     if (context->response_handler(session, sent, rcvd,
3423                                   rcvd->mid) == COAP_RESPONSE_FAIL)
3424       coap_send_rst(session, rcvd);
3425     else
3426       coap_send_ack(session, rcvd);
3427   } else {
3428     coap_send_ack(session, rcvd);
3429   }
3430 }
3431 #endif /* COAP_CLIENT_SUPPORT */
3432 
3433 #if !COAP_DISABLE_TCP
3434 static void
handle_signaling(coap_context_t * context,coap_session_t * session,coap_pdu_t * pdu)3435 handle_signaling(coap_context_t *context, coap_session_t *session,
3436                  coap_pdu_t *pdu) {
3437   coap_opt_iterator_t opt_iter;
3438   coap_opt_t *option;
3439   int set_mtu = 0;
3440 
3441   coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
3442 
3443   if (pdu->code == COAP_SIGNALING_CODE_CSM) {
3444     if (session->max_token_checked == COAP_EXT_T_NOT_CHECKED) {
3445       session->max_token_size = COAP_TOKEN_DEFAULT_MAX;
3446     }
3447     while ((option = coap_option_next(&opt_iter))) {
3448       if (opt_iter.number == COAP_SIGNALING_OPTION_MAX_MESSAGE_SIZE) {
3449         coap_session_set_mtu(session, coap_decode_var_bytes(coap_opt_value(option),
3450                                                             coap_opt_length(option)));
3451         set_mtu = 1;
3452       } else if (opt_iter.number == COAP_SIGNALING_OPTION_BLOCK_WISE_TRANSFER) {
3453         session->csm_block_supported = 1;
3454       } else if (opt_iter.number == COAP_SIGNALING_OPTION_EXTENDED_TOKEN_LENGTH) {
3455         session->max_token_size =
3456             coap_decode_var_bytes(coap_opt_value(option),
3457                                   coap_opt_length(option));
3458         if (session->max_token_size < COAP_TOKEN_DEFAULT_MAX)
3459           session->max_token_size = COAP_TOKEN_DEFAULT_MAX;
3460         else if (session->max_token_size > COAP_TOKEN_EXT_MAX)
3461           session->max_token_size = COAP_TOKEN_EXT_MAX;
3462         session->max_token_checked = COAP_EXT_T_CHECKED;
3463       }
3464     }
3465     if (set_mtu) {
3466       if (session->mtu > COAP_BERT_BASE && session->csm_block_supported)
3467         session->csm_bert_rem_support = 1;
3468       else
3469         session->csm_bert_rem_support = 0;
3470     }
3471     if (session->state == COAP_SESSION_STATE_CSM)
3472       coap_session_connected(session);
3473   } else if (pdu->code == COAP_SIGNALING_CODE_PING) {
3474     coap_pdu_t *pong = coap_pdu_init(COAP_MESSAGE_CON, COAP_SIGNALING_CODE_PONG, 0, 1);
3475     if (context->ping_handler) {
3476       context->ping_handler(session, pdu, pdu->mid);
3477     }
3478     if (pong) {
3479       coap_add_option_internal(pong, COAP_SIGNALING_OPTION_CUSTODY, 0, NULL);
3480       coap_send_internal(session, pong);
3481     }
3482   } else if (pdu->code == COAP_SIGNALING_CODE_PONG) {
3483     session->last_pong = session->last_rx_tx;
3484     if (context->pong_handler) {
3485       context->pong_handler(session, pdu, pdu->mid);
3486     }
3487   } else if (pdu->code == COAP_SIGNALING_CODE_RELEASE
3488              || pdu->code == COAP_SIGNALING_CODE_ABORT) {
3489     coap_session_disconnected(session, COAP_NACK_RST);
3490   }
3491 }
3492 #endif /* !COAP_DISABLE_TCP */
3493 
3494 static int
check_token_size(coap_session_t * session,const coap_pdu_t * pdu)3495 check_token_size(coap_session_t *session, const coap_pdu_t *pdu) {
3496   if (COAP_PDU_IS_REQUEST(pdu) &&
3497       pdu->actual_token.length >
3498       (session->type == COAP_SESSION_TYPE_CLIENT ?
3499        session->max_token_size : session->context->max_token_size)) {
3500     /* https://rfc-editor.org/rfc/rfc8974#section-2.2.2 */
3501     if (session->max_token_size > COAP_TOKEN_DEFAULT_MAX) {
3502       coap_opt_filter_t opt_filter;
3503       coap_pdu_t *response;
3504 
3505       memset(&opt_filter, 0, sizeof(coap_opt_filter_t));
3506       response = coap_new_error_response(pdu, COAP_RESPONSE_CODE(400),
3507                                          &opt_filter);
3508       if (!response) {
3509         coap_log_warn("coap_dispatch: cannot create error response\n");
3510       } else {
3511         /*
3512          * Note - have to leave in oversize token as per
3513          * https://rfc-editor.org/rfc/rfc7252#section-5.3.1
3514          */
3515         if (coap_send_internal(session, response) == COAP_INVALID_MID)
3516           coap_log_warn("coap_dispatch: error sending response\n");
3517       }
3518     } else {
3519       /* Indicate no extended token support */
3520       coap_send_rst(session, pdu);
3521     }
3522     return 0;
3523   }
3524   return 1;
3525 }
3526 
3527 void
coap_dispatch(coap_context_t * context,coap_session_t * session,coap_pdu_t * pdu)3528 coap_dispatch(coap_context_t *context, coap_session_t *session,
3529               coap_pdu_t *pdu) {
3530   coap_queue_t *sent = NULL;
3531   coap_pdu_t *response;
3532   coap_opt_filter_t opt_filter;
3533   int is_ping_rst;
3534   int packet_is_bad = 0;
3535 #if COAP_OSCORE_SUPPORT
3536   coap_opt_iterator_t opt_iter;
3537   coap_pdu_t *dec_pdu = NULL;
3538 #endif /* COAP_OSCORE_SUPPORT */
3539   int is_ext_token_rst;
3540 
3541   pdu->session = session;
3542   coap_show_pdu(COAP_LOG_DEBUG, pdu);
3543 
3544   memset(&opt_filter, 0, sizeof(coap_opt_filter_t));
3545 
3546 #if COAP_OSCORE_SUPPORT
3547   if (!COAP_PDU_IS_SIGNALING(pdu) &&
3548       coap_option_check_critical(session, pdu, &opt_filter) == 0) {
3549     if (pdu->type == COAP_MESSAGE_NON) {
3550       coap_send_rst(session, pdu);
3551       goto cleanup;
3552     } else if (pdu->type == COAP_MESSAGE_CON) {
3553       if (COAP_PDU_IS_REQUEST(pdu)) {
3554         response =
3555             coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
3556 
3557         if (!response) {
3558           coap_log_warn("coap_dispatch: cannot create error response\n");
3559         } else {
3560           if (coap_send_internal(session, response) == COAP_INVALID_MID)
3561             coap_log_warn("coap_dispatch: error sending response\n");
3562         }
3563       } else {
3564         coap_send_rst(session, pdu);
3565       }
3566     }
3567     goto cleanup;
3568   }
3569 
3570   if (coap_check_option(pdu, COAP_OPTION_OSCORE, &opt_iter) != NULL) {
3571     int decrypt = 1;
3572 #if COAP_SERVER_SUPPORT
3573     coap_opt_t *opt;
3574     coap_resource_t *resource;
3575     coap_uri_t uri;
3576 #endif /* COAP_SERVER_SUPPORT */
3577 
3578     if (COAP_PDU_IS_RESPONSE(pdu) && !session->oscore_encryption)
3579       decrypt = 0;
3580 
3581 #if COAP_SERVER_SUPPORT
3582     if (decrypt && COAP_PDU_IS_REQUEST(pdu) &&
3583         coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter) != NULL &&
3584         (opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter))
3585         != NULL) {
3586       /* Need to check whether this is a direct or proxy session */
3587       memset(&uri, 0, sizeof(uri));
3588       uri.host.length = coap_opt_length(opt);
3589       uri.host.s = coap_opt_value(opt);
3590       resource = context->proxy_uri_resource;
3591       if (uri.host.length && resource && resource->proxy_name_count &&
3592           resource->proxy_name_list) {
3593         size_t i;
3594         for (i = 0; i < resource->proxy_name_count; i++) {
3595           if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
3596             break;
3597           }
3598         }
3599         if (i == resource->proxy_name_count) {
3600           /* This server is not hosting the proxy connection endpoint */
3601           decrypt = 0;
3602         }
3603       }
3604     }
3605 #endif /* COAP_SERVER_SUPPORT */
3606     if (decrypt) {
3607       /* find message id in sendqueue to stop retransmission and get sent */
3608       coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
3609       if ((dec_pdu = coap_oscore_decrypt_pdu(session, pdu)) == NULL) {
3610         if (session->recipient_ctx == NULL ||
3611             session->recipient_ctx->initial_state == 0) {
3612           coap_log_warn("OSCORE: PDU could not be decrypted\n");
3613         }
3614         coap_delete_node(sent);
3615         return;
3616       } else {
3617         session->oscore_encryption = 1;
3618         pdu = dec_pdu;
3619       }
3620       coap_log_debug("Decrypted PDU\n");
3621       coap_show_pdu(COAP_LOG_DEBUG, pdu);
3622     }
3623   }
3624 #endif /* COAP_OSCORE_SUPPORT */
3625 
3626   switch (pdu->type) {
3627   case COAP_MESSAGE_ACK:
3628     /* find message id in sendqueue to stop retransmission */
3629     coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
3630 
3631     if (sent && session->con_active) {
3632       session->con_active--;
3633       if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3634         /* Flush out any entries on session->delayqueue */
3635         coap_session_connected(session);
3636     }
3637     if (coap_option_check_critical(session, pdu, &opt_filter) == 0) {
3638       packet_is_bad = 1;
3639       goto cleanup;
3640     }
3641 
3642 #if COAP_SERVER_SUPPORT
3643     /* if sent code was >= 64 the message might have been a
3644      * notification. Then, we must flag the observer to be alive
3645      * by setting obs->fail_cnt = 0. */
3646     if (sent && COAP_RESPONSE_CLASS(sent->pdu->code) == 2) {
3647       coap_touch_observer(context, sent->session, &sent->pdu->actual_token);
3648     }
3649 #endif /* COAP_SERVER_SUPPORT */
3650 
3651     if (pdu->code == 0) {
3652 #if COAP_Q_BLOCK_SUPPORT
3653       if (sent) {
3654         coap_block_b_t block;
3655 
3656         if (sent->pdu->type == COAP_MESSAGE_CON &&
3657             COAP_PROTO_NOT_RELIABLE(session->proto) &&
3658             coap_get_block_b(session, sent->pdu,
3659                              COAP_PDU_IS_REQUEST(sent->pdu) ?
3660                              COAP_OPTION_Q_BLOCK1 : COAP_OPTION_Q_BLOCK2,
3661                              &block)) {
3662           if (block.m) {
3663 #if COAP_CLIENT_SUPPORT
3664             if (COAP_PDU_IS_REQUEST(sent->pdu))
3665               coap_send_q_block1(session, block, sent->pdu,
3666                                  COAP_SEND_SKIP_PDU);
3667 #endif /* COAP_CLIENT_SUPPORT */
3668             if (COAP_PDU_IS_RESPONSE(sent->pdu))
3669               coap_send_q_blocks(session, sent->pdu->lg_xmit, block,
3670                                  sent->pdu, COAP_SEND_SKIP_PDU);
3671           }
3672         }
3673       }
3674 #endif /* COAP_Q_BLOCK_SUPPORT */
3675       /* an empty ACK needs no further handling */
3676       goto cleanup;
3677     }
3678 
3679     break;
3680 
3681   case COAP_MESSAGE_RST:
3682     /* We have sent something the receiver disliked, so we remove
3683      * not only the message id but also the subscriptions we might
3684      * have. */
3685     is_ping_rst = 0;
3686     if (pdu->mid == session->last_ping_mid &&
3687         context->ping_timeout && session->last_ping > 0)
3688       is_ping_rst = 1;
3689 
3690 #if COAP_Q_BLOCK_SUPPORT
3691     /* Check to see if checking out Q-Block support */
3692     if (session->block_mode & COAP_BLOCK_PROBE_Q_BLOCK &&
3693         session->remote_test_mid == pdu->mid) {
3694       coap_log_debug("Q-Block support not available\n");
3695       set_block_mode_drop_q(session->block_mode);
3696     }
3697 #endif /* COAP_Q_BLOCK_SUPPORT */
3698 
3699     /* Check to see if checking out extended token support */
3700     is_ext_token_rst = 0;
3701     if (session->max_token_checked == COAP_EXT_T_CHECKING &&
3702         session->remote_test_mid == pdu->mid) {
3703       coap_log_debug("Extended Token support not available\n");
3704       session->max_token_size = COAP_TOKEN_DEFAULT_MAX;
3705       session->max_token_checked = COAP_EXT_T_CHECKED;
3706       session->doing_first = 0;
3707       is_ext_token_rst = 1;
3708     }
3709 
3710     if (!is_ping_rst && !is_ext_token_rst)
3711       coap_log_alert("got RST for mid=0x%04x\n", pdu->mid);
3712 
3713     if (session->con_active) {
3714       session->con_active--;
3715       if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3716         /* Flush out any entries on session->delayqueue */
3717         coap_session_connected(session);
3718     }
3719 
3720     /* find message id in sendqueue to stop retransmission */
3721     coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
3722 
3723     if (sent) {
3724       coap_cancel(context, sent);
3725 
3726       if (!is_ping_rst && !is_ext_token_rst) {
3727         if (sent->pdu->type==COAP_MESSAGE_CON && context->nack_handler) {
3728           coap_check_update_token(sent->session, sent->pdu);
3729           context->nack_handler(sent->session, sent->pdu,
3730                                 COAP_NACK_RST, sent->id);
3731         }
3732       } else if (is_ping_rst) {
3733         if (context->pong_handler) {
3734           context->pong_handler(session, pdu, pdu->mid);
3735         }
3736         session->last_pong = session->last_rx_tx;
3737         session->last_ping_mid = COAP_INVALID_MID;
3738       }
3739     } else {
3740 #if COAP_SERVER_SUPPORT
3741       /* Need to check is there is a subscription active and delete it */
3742       RESOURCES_ITER(context->resources, r) {
3743         coap_subscription_t *obs, *tmp;
3744         LL_FOREACH_SAFE(r->subscribers, obs, tmp) {
3745           if (obs->pdu->mid == pdu->mid && obs->session == session) {
3746             /* Need to do this now as session may get de-referenced */
3747             coap_session_reference(session);
3748             coap_delete_observer(r, session, &obs->pdu->actual_token);
3749             if (context->nack_handler)
3750               context->nack_handler(session, NULL, COAP_NACK_RST, pdu->mid);
3751             coap_session_release(session);
3752             goto cleanup;
3753           }
3754         }
3755       }
3756 #endif /* COAP_SERVER_SUPPORT */
3757       if (context->nack_handler)
3758         context->nack_handler(session, NULL, COAP_NACK_RST, pdu->mid);
3759     }
3760     goto cleanup;
3761 
3762   case COAP_MESSAGE_NON:
3763     /* find transaction in sendqueue in case large response */
3764     coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
3765     /* check for unknown critical options */
3766     if (coap_option_check_critical(session, pdu, &opt_filter) == 0) {
3767       packet_is_bad = 1;
3768       coap_send_rst(session, pdu);
3769       goto cleanup;
3770     }
3771     if (!check_token_size(session, pdu)) {
3772       goto cleanup;
3773     }
3774     break;
3775 
3776   case COAP_MESSAGE_CON:        /* check for unknown critical options */
3777     if (!COAP_PDU_IS_SIGNALING(pdu) &&
3778         coap_option_check_critical(session, pdu, &opt_filter) == 0) {
3779       packet_is_bad = 1;
3780       if (COAP_PDU_IS_REQUEST(pdu)) {
3781         response =
3782             coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
3783 
3784         if (!response) {
3785           coap_log_warn("coap_dispatch: cannot create error response\n");
3786         } else {
3787           if (coap_send_internal(session, response) == COAP_INVALID_MID)
3788             coap_log_warn("coap_dispatch: error sending response\n");
3789         }
3790       } else {
3791         coap_send_rst(session, pdu);
3792       }
3793       goto cleanup;
3794     }
3795     if (!check_token_size(session, pdu)) {
3796       goto cleanup;
3797     }
3798     break;
3799   default:
3800     break;
3801   }
3802 
3803   /* Pass message to upper layer if a specific handler was
3804     * registered for a request that should be handled locally. */
3805 #if !COAP_DISABLE_TCP
3806   if (COAP_PDU_IS_SIGNALING(pdu))
3807     handle_signaling(context, session, pdu);
3808   else
3809 #endif /* !COAP_DISABLE_TCP */
3810 #if COAP_SERVER_SUPPORT
3811     if (COAP_PDU_IS_REQUEST(pdu))
3812       handle_request(context, session, pdu);
3813     else
3814 #endif /* COAP_SERVER_SUPPORT */
3815 #if COAP_CLIENT_SUPPORT
3816       if (COAP_PDU_IS_RESPONSE(pdu))
3817         handle_response(context, session, sent ? sent->pdu : NULL, pdu);
3818       else
3819 #endif /* COAP_CLIENT_SUPPORT */
3820       {
3821         if (COAP_PDU_IS_EMPTY(pdu)) {
3822           if (context->ping_handler) {
3823             context->ping_handler(session, pdu, pdu->mid);
3824           }
3825         } else {
3826           packet_is_bad = 1;
3827         }
3828         coap_log_debug("dropped message with invalid code (%d.%02d)\n",
3829                        COAP_RESPONSE_CLASS(pdu->code),
3830                        pdu->code & 0x1f);
3831 
3832         if (!coap_is_mcast(&session->addr_info.local)) {
3833           if (COAP_PDU_IS_EMPTY(pdu)) {
3834             if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
3835               coap_tick_t now;
3836               coap_ticks(&now);
3837               if (session->last_tx_rst + COAP_TICKS_PER_SECOND/4 < now) {
3838                 coap_send_message_type(session, pdu, COAP_MESSAGE_RST);
3839                 session->last_tx_rst = now;
3840               }
3841             }
3842           } else {
3843             coap_send_message_type(session, pdu, COAP_MESSAGE_RST);
3844           }
3845         }
3846       }
3847 
3848 cleanup:
3849   if (packet_is_bad) {
3850     if (sent) {
3851       if (context->nack_handler) {
3852         coap_check_update_token(session, sent->pdu);
3853         context->nack_handler(session, sent->pdu, COAP_NACK_BAD_RESPONSE, sent->id);
3854       }
3855     } else {
3856       coap_handle_event(context, COAP_EVENT_BAD_PACKET, session);
3857     }
3858   }
3859   coap_delete_node(sent);
3860 #if COAP_OSCORE_SUPPORT
3861   coap_delete_pdu(dec_pdu);
3862 #endif /* COAP_OSCORE_SUPPORT */
3863 }
3864 
3865 #if COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG
3866 static const char *
coap_event_name(coap_event_t event)3867 coap_event_name(coap_event_t event) {
3868   switch (event) {
3869   case COAP_EVENT_DTLS_CLOSED:
3870     return "COAP_EVENT_DTLS_CLOSED";
3871   case COAP_EVENT_DTLS_CONNECTED:
3872     return "COAP_EVENT_DTLS_CONNECTED";
3873   case COAP_EVENT_DTLS_RENEGOTIATE:
3874     return "COAP_EVENT_DTLS_RENEGOTIATE";
3875   case COAP_EVENT_DTLS_ERROR:
3876     return "COAP_EVENT_DTLS_ERROR";
3877   case COAP_EVENT_TCP_CONNECTED:
3878     return "COAP_EVENT_TCP_CONNECTED";
3879   case COAP_EVENT_TCP_CLOSED:
3880     return "COAP_EVENT_TCP_CLOSED";
3881   case COAP_EVENT_TCP_FAILED:
3882     return "COAP_EVENT_TCP_FAILED";
3883   case COAP_EVENT_SESSION_CONNECTED:
3884     return "COAP_EVENT_SESSION_CONNECTED";
3885   case COAP_EVENT_SESSION_CLOSED:
3886     return "COAP_EVENT_SESSION_CLOSED";
3887   case COAP_EVENT_SESSION_FAILED:
3888     return "COAP_EVENT_SESSION_FAILED";
3889   case COAP_EVENT_PARTIAL_BLOCK:
3890     return "COAP_EVENT_PARTIAL_BLOCK";
3891   case COAP_EVENT_XMIT_BLOCK_FAIL:
3892     return "COAP_EVENT_XMIT_BLOCK_FAIL";
3893   case COAP_EVENT_SERVER_SESSION_NEW:
3894     return "COAP_EVENT_SERVER_SESSION_NEW";
3895   case COAP_EVENT_SERVER_SESSION_DEL:
3896     return "COAP_EVENT_SERVER_SESSION_DEL";
3897   case COAP_EVENT_BAD_PACKET:
3898     return "COAP_EVENT_BAD_PACKET";
3899   case COAP_EVENT_MSG_RETRANSMITTED:
3900     return "COAP_EVENT_MSG_RETRANSMITTED";
3901   case COAP_EVENT_OSCORE_DECRYPTION_FAILURE:
3902     return "COAP_EVENT_OSCORE_DECRYPTION_FAILURE";
3903   case COAP_EVENT_OSCORE_NOT_ENABLED:
3904     return "COAP_EVENT_OSCORE_NOT_ENABLED";
3905   case COAP_EVENT_OSCORE_NO_PROTECTED_PAYLOAD:
3906     return "COAP_EVENT_OSCORE_NO_PROTECTED_PAYLOAD";
3907   case COAP_EVENT_OSCORE_NO_SECURITY:
3908     return "COAP_EVENT_OSCORE_NO_SECURITY";
3909   case COAP_EVENT_OSCORE_INTERNAL_ERROR:
3910     return "COAP_EVENT_OSCORE_INTERNAL_ERROR";
3911   case COAP_EVENT_OSCORE_DECODE_ERROR:
3912     return "COAP_EVENT_OSCORE_DECODE_ERROR";
3913   case COAP_EVENT_WS_PACKET_SIZE:
3914     return "COAP_EVENT_WS_PACKET_SIZE";
3915   case COAP_EVENT_WS_CONNECTED:
3916     return "COAP_EVENT_WS_CONNECTED";
3917   case COAP_EVENT_WS_CLOSED:
3918     return "COAP_EVENT_WS_CLOSED";
3919   case COAP_EVENT_KEEPALIVE_FAILURE:
3920     return "COAP_EVENT_KEEPALIVE_FAILURE";
3921   default:
3922     return "???";
3923   }
3924 }
3925 #endif /* COAP_MAX_LOGGING_LEVEL >= _COAP_LOG_DEBUG */
3926 
3927 int
coap_handle_event(coap_context_t * context,coap_event_t event,coap_session_t * session)3928 coap_handle_event(coap_context_t *context, coap_event_t event, coap_session_t *session) {
3929   coap_log_debug("***EVENT: %s\n", coap_event_name(event));
3930 
3931   if (context->handle_event) {
3932     return context->handle_event(session, event);
3933   } else {
3934     return 0;
3935   }
3936 }
3937 
3938 int
coap_can_exit(coap_context_t * context)3939 coap_can_exit(coap_context_t *context) {
3940   coap_session_t *s, *rtmp;
3941   if (!context)
3942     return 1;
3943   if (context->sendqueue)
3944     return 0;
3945 #if COAP_SERVER_SUPPORT
3946   coap_endpoint_t *ep;
3947 
3948   LL_FOREACH(context->endpoint, ep) {
3949     SESSIONS_ITER(ep->sessions, s, rtmp) {
3950       if (s->delayqueue)
3951         return 0;
3952       if (s->lg_xmit)
3953         return 0;
3954     }
3955   }
3956 #endif /* COAP_SERVER_SUPPORT */
3957 #if COAP_CLIENT_SUPPORT
3958   SESSIONS_ITER(context->sessions, s, rtmp) {
3959     if (s->delayqueue)
3960       return 0;
3961     if (s->lg_xmit)
3962       return 0;
3963   }
3964 #endif /* COAP_CLIENT_SUPPORT */
3965   return 1;
3966 }
3967 #if COAP_SERVER_SUPPORT
3968 #if COAP_ASYNC_SUPPORT
3969 coap_tick_t
coap_check_async(coap_context_t * context,coap_tick_t now)3970 coap_check_async(coap_context_t *context, coap_tick_t now) {
3971   coap_tick_t next_due = 0;
3972   coap_async_t *async, *tmp;
3973 
3974   LL_FOREACH_SAFE(context->async_state, async, tmp) {
3975     if (async->delay != 0 && async->delay <= now) {
3976       /* Send off the request to the application */
3977       handle_request(context, async->session, async->pdu);
3978 
3979       /* Remove this async entry as it has now fired */
3980       coap_free_async(async->session, async);
3981     } else {
3982       if (next_due == 0 || next_due > async->delay - now)
3983         next_due = async->delay - now;
3984     }
3985   }
3986   return next_due;
3987 }
3988 #endif /* COAP_ASYNC_SUPPORT */
3989 #endif /* COAP_SERVER_SUPPORT */
3990 
3991 int coap_started = 0;
3992 
3993 #if COAP_CONSTRAINED_STACK
3994 coap_mutex_t m_show_pdu;
3995 coap_mutex_t m_log_impl;
3996 coap_mutex_t m_dtls_recv;
3997 coap_mutex_t m_read_session;
3998 coap_mutex_t m_read_endpoint;
3999 coap_mutex_t m_persist_add;
4000 #endif /* COAP_CONSTRAINED_STACK */
4001 
4002 void
coap_startup(void)4003 coap_startup(void) {
4004   coap_tick_t now;
4005 #ifndef WITH_CONTIKI
4006   uint64_t us;
4007 #endif /* !WITH_CONTIKI */
4008 
4009   if (coap_started)
4010     return;
4011   coap_started = 1;
4012 
4013 #if COAP_CONSTRAINED_STACK
4014   coap_mutex_init(&m_show_pdu);
4015   coap_mutex_init(&m_log_impl);
4016   coap_mutex_init(&m_dtls_recv);
4017   coap_mutex_init(&m_read_session);
4018   coap_mutex_init(&m_read_endpoint);
4019   coap_mutex_init(&m_persist_add);
4020 #endif /* COAP_CONSTRAINED_STACK */
4021 
4022 #if defined(HAVE_WINSOCK2_H)
4023   WORD wVersionRequested = MAKEWORD(2, 2);
4024   WSADATA wsaData;
4025   WSAStartup(wVersionRequested, &wsaData);
4026 #endif
4027   coap_clock_init();
4028   coap_ticks(&now);
4029 #ifndef WITH_CONTIKI
4030   us = coap_ticks_to_rt_us(now);
4031   /* Be accurate to the nearest (approx) us */
4032   coap_prng_init((unsigned int)us);
4033 #else /* WITH_CONTIKI */
4034   coap_start_io_process();
4035 #endif /* WITH_CONTIKI */
4036   coap_memory_init();
4037   coap_dtls_startup();
4038 #if COAP_SERVER_SUPPORT
4039   static coap_str_const_t well_known = { sizeof(".well-known/core")-1,
4040                                          (const uint8_t *)".well-known/core"
4041                                        };
4042   memset(&resource_uri_wellknown, 0, sizeof(resource_uri_wellknown));
4043   resource_uri_wellknown.handler[COAP_REQUEST_GET-1] = hnd_get_wellknown;
4044   resource_uri_wellknown.flags = COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT;
4045   resource_uri_wellknown.uri_path = &well_known;
4046 #endif /* COAP_SERVER_SUPPORT */
4047 }
4048 
4049 void
coap_cleanup(void)4050 coap_cleanup(void) {
4051 #if defined(HAVE_WINSOCK2_H)
4052   WSACleanup();
4053 #elif defined(WITH_CONTIKI)
4054   coap_stop_io_process();
4055 #endif
4056   coap_dtls_shutdown();
4057 
4058 #if COAP_CONSTRAINED_STACK
4059   coap_mutex_destroy(&m_show_pdu);
4060   coap_mutex_destroy(&m_log_impl);
4061   coap_mutex_destroy(&m_dtls_recv);
4062   coap_mutex_destroy(&m_read_session);
4063   coap_mutex_destroy(&m_read_endpoint);
4064   coap_mutex_destroy(&m_persist_add);
4065 #endif /* COAP_CONSTRAINED_STACK */
4066   coap_debug_reset();
4067   coap_started = 0;
4068 }
4069 
4070 void
coap_register_response_handler(coap_context_t * context,coap_response_handler_t handler)4071 coap_register_response_handler(coap_context_t *context,
4072                                coap_response_handler_t handler) {
4073 #if COAP_CLIENT_SUPPORT
4074   context->response_handler = handler;
4075 #else /* ! COAP_CLIENT_SUPPORT */
4076   (void)context;
4077   (void)handler;
4078 #endif /* COAP_CLIENT_SUPPORT */
4079 }
4080 
4081 void
coap_register_nack_handler(coap_context_t * context,coap_nack_handler_t handler)4082 coap_register_nack_handler(coap_context_t *context,
4083                            coap_nack_handler_t handler) {
4084   context->nack_handler = handler;
4085 }
4086 
4087 void
coap_register_ping_handler(coap_context_t * context,coap_ping_handler_t handler)4088 coap_register_ping_handler(coap_context_t *context,
4089                            coap_ping_handler_t handler) {
4090   context->ping_handler = handler;
4091 }
4092 
4093 void
coap_register_pong_handler(coap_context_t * context,coap_pong_handler_t handler)4094 coap_register_pong_handler(coap_context_t *context,
4095                            coap_pong_handler_t handler) {
4096   context->pong_handler = handler;
4097 }
4098 
4099 void
coap_register_option(coap_context_t * ctx,uint16_t type)4100 coap_register_option(coap_context_t *ctx, uint16_t type) {
4101   coap_option_filter_set(&ctx->known_options, type);
4102 }
4103 
4104 #if ! defined WITH_CONTIKI && ! defined WITH_LWIP && ! defined RIOT_VERSION
4105 #if COAP_SERVER_SUPPORT
4106 int
coap_join_mcast_group_intf(coap_context_t * ctx,const char * group_name,const char * ifname)4107 coap_join_mcast_group_intf(coap_context_t *ctx, const char *group_name,
4108                            const char *ifname) {
4109 #if COAP_IPV4_SUPPORT
4110   struct ip_mreq mreq4;
4111 #endif /* COAP_IPV4_SUPPORT */
4112 #if COAP_IPV6_SUPPORT
4113   struct ipv6_mreq mreq6;
4114 #endif /* COAP_IPV6_SUPPORT */
4115   struct addrinfo *resmulti = NULL, hints, *ainfo;
4116   int result = -1;
4117   coap_endpoint_t *endpoint;
4118   int mgroup_setup = 0;
4119 
4120   /* Need to have at least one endpoint! */
4121   assert(ctx->endpoint);
4122   if (!ctx->endpoint)
4123     return -1;
4124 
4125   /* Default is let the kernel choose */
4126 #if COAP_IPV6_SUPPORT
4127   mreq6.ipv6mr_interface = 0;
4128 #endif /* COAP_IPV6_SUPPORT */
4129 #if COAP_IPV4_SUPPORT
4130   mreq4.imr_interface.s_addr = INADDR_ANY;
4131 #endif /* COAP_IPV4_SUPPORT */
4132 
4133   memset(&hints, 0, sizeof(hints));
4134   hints.ai_socktype = SOCK_DGRAM;
4135 
4136   /* resolve the multicast group address */
4137   result = getaddrinfo(group_name, NULL, &hints, &resmulti);
4138 
4139   if (result != 0) {
4140     coap_log_err("coap_join_mcast_group_intf: %s: "
4141                  "Cannot resolve multicast address: %s\n",
4142                  group_name, gai_strerror(result));
4143     goto finish;
4144   }
4145 
4146   /* Need to do a windows equivalent at some point */
4147 #ifndef _WIN32
4148   if (ifname) {
4149     /* interface specified - check if we have correct IPv4/IPv6 information */
4150     int done_ip4 = 0;
4151     int done_ip6 = 0;
4152 #if defined(ESPIDF_VERSION)
4153     struct netif *netif;
4154 #else /* !ESPIDF_VERSION */
4155 #if COAP_IPV4_SUPPORT
4156     int ip4fd;
4157 #endif /* COAP_IPV4_SUPPORT */
4158     struct ifreq ifr;
4159 #endif /* !ESPIDF_VERSION */
4160 
4161     /* See which mcast address family types are being asked for */
4162     for (ainfo = resmulti; ainfo != NULL && !(done_ip4 == 1 && done_ip6 == 1);
4163          ainfo = ainfo->ai_next) {
4164       switch (ainfo->ai_family) {
4165 #if COAP_IPV6_SUPPORT
4166       case AF_INET6:
4167         if (done_ip6)
4168           break;
4169         done_ip6 = 1;
4170 #if defined(ESPIDF_VERSION)
4171         netif = netif_find(ifname);
4172         if (netif)
4173           mreq6.ipv6mr_interface = netif_get_index(netif);
4174         else
4175           coap_log_err("coap_join_mcast_group_intf: %s: "
4176                        "Cannot get IPv4 address: %s\n",
4177                        ifname, coap_socket_strerror());
4178 #else /* !ESPIDF_VERSION */
4179         memset(&ifr, 0, sizeof(ifr));
4180         strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
4181         ifr.ifr_name[IFNAMSIZ - 1] = '\000';
4182 
4183 #ifdef HAVE_IF_NAMETOINDEX
4184         mreq6.ipv6mr_interface = if_nametoindex(ifr.ifr_name);
4185         if (mreq6.ipv6mr_interface == 0) {
4186           coap_log_warn("coap_join_mcast_group_intf: "
4187                         "cannot get interface index for '%s'\n",
4188                         ifname);
4189         }
4190 #else /* !HAVE_IF_NAMETOINDEX */
4191         result = ioctl(ctx->endpoint->sock.fd, SIOCGIFINDEX, &ifr);
4192         if (result != 0) {
4193           coap_log_warn("coap_join_mcast_group_intf: "
4194                         "cannot get interface index for '%s': %s\n",
4195                         ifname, coap_socket_strerror());
4196         } else {
4197           /* Capture the IPv6 if_index for later */
4198           mreq6.ipv6mr_interface = ifr.ifr_ifindex;
4199         }
4200 #endif /* !HAVE_IF_NAMETOINDEX */
4201 #endif /* !ESPIDF_VERSION */
4202 #endif /* COAP_IPV6_SUPPORT */
4203         break;
4204 #if COAP_IPV4_SUPPORT
4205       case AF_INET:
4206         if (done_ip4)
4207           break;
4208         done_ip4 = 1;
4209 #if defined(ESPIDF_VERSION)
4210         netif = netif_find(ifname);
4211         if (netif)
4212           mreq4.imr_interface.s_addr = netif_ip4_addr(netif)->addr;
4213         else
4214           coap_log_err("coap_join_mcast_group_intf: %s: "
4215                        "Cannot get IPv4 address: %s\n",
4216                        ifname, coap_socket_strerror());
4217 #else /* !ESPIDF_VERSION */
4218         /*
4219          * Need an AF_INET socket to do this unfortunately to stop
4220          * "Invalid argument" error if AF_INET6 socket is used for SIOCGIFADDR
4221          */
4222         ip4fd = socket(AF_INET, SOCK_DGRAM, 0);
4223         if (ip4fd == -1) {
4224           coap_log_err("coap_join_mcast_group_intf: %s: socket: %s\n",
4225                        ifname, coap_socket_strerror());
4226           continue;
4227         }
4228         memset(&ifr, 0, sizeof(ifr));
4229         strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
4230         ifr.ifr_name[IFNAMSIZ - 1] = '\000';
4231         result = ioctl(ip4fd, SIOCGIFADDR, &ifr);
4232         if (result != 0) {
4233           coap_log_err("coap_join_mcast_group_intf: %s: "
4234                        "Cannot get IPv4 address: %s\n",
4235                        ifname, coap_socket_strerror());
4236         } else {
4237           /* Capture the IPv4 address for later */
4238           mreq4.imr_interface = ((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr;
4239         }
4240         close(ip4fd);
4241 #endif /* !ESPIDF_VERSION */
4242         break;
4243 #endif /* COAP_IPV4_SUPPORT */
4244       default:
4245         break;
4246       }
4247     }
4248   }
4249 #endif /* ! _WIN32 */
4250 
4251   /* Add in mcast address(es) to appropriate interface */
4252   for (ainfo = resmulti; ainfo != NULL; ainfo = ainfo->ai_next) {
4253     LL_FOREACH(ctx->endpoint, endpoint) {
4254       /* Only UDP currently supported */
4255       if (endpoint->proto == COAP_PROTO_UDP) {
4256         coap_address_t gaddr;
4257 
4258         coap_address_init(&gaddr);
4259 #if COAP_IPV6_SUPPORT
4260         if (ainfo->ai_family == AF_INET6) {
4261           if (!ifname) {
4262             if (endpoint->bind_addr.addr.sa.sa_family == AF_INET6) {
4263               /*
4264                * Do it on the ifindex that the server is listening on
4265                * (sin6_scope_id could still be 0)
4266                */
4267               mreq6.ipv6mr_interface =
4268                   endpoint->bind_addr.addr.sin6.sin6_scope_id;
4269             } else {
4270               mreq6.ipv6mr_interface = 0;
4271             }
4272           }
4273           gaddr.addr.sin6.sin6_family = AF_INET6;
4274           gaddr.addr.sin6.sin6_port = endpoint->bind_addr.addr.sin6.sin6_port;
4275           gaddr.addr.sin6.sin6_addr = mreq6.ipv6mr_multiaddr =
4276                                           ((struct sockaddr_in6 *)ainfo->ai_addr)->sin6_addr;
4277           result = setsockopt(endpoint->sock.fd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
4278                               (char *)&mreq6, sizeof(mreq6));
4279         }
4280 #endif /* COAP_IPV6_SUPPORT */
4281 #if COAP_IPV4_SUPPORT && COAP_IPV6_SUPPORT
4282         else
4283 #endif /* COAP_IPV4_SUPPORT && COAP_IPV6_SUPPORT */
4284 #if COAP_IPV4_SUPPORT
4285           if (ainfo->ai_family == AF_INET) {
4286             if (!ifname) {
4287               if (endpoint->bind_addr.addr.sa.sa_family == AF_INET) {
4288                 /*
4289                  * Do it on the interface that the server is listening on
4290                  * (sin_addr could still be INADDR_ANY)
4291                  */
4292                 mreq4.imr_interface = endpoint->bind_addr.addr.sin.sin_addr;
4293               } else {
4294                 mreq4.imr_interface.s_addr = INADDR_ANY;
4295               }
4296             }
4297             gaddr.addr.sin.sin_family = AF_INET;
4298             gaddr.addr.sin.sin_port = endpoint->bind_addr.addr.sin.sin_port;
4299             gaddr.addr.sin.sin_addr.s_addr = mreq4.imr_multiaddr.s_addr =
4300                                                  ((struct sockaddr_in *)ainfo->ai_addr)->sin_addr.s_addr;
4301             result = setsockopt(endpoint->sock.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4302                                 (char *)&mreq4, sizeof(mreq4));
4303           }
4304 #endif /* COAP_IPV4_SUPPORT */
4305           else {
4306             continue;
4307           }
4308 
4309         if (result == COAP_SOCKET_ERROR) {
4310           coap_log_err("coap_join_mcast_group_intf: %s: setsockopt: %s\n",
4311                        group_name, coap_socket_strerror());
4312         } else {
4313           char addr_str[INET6_ADDRSTRLEN + 8 + 1];
4314 
4315           addr_str[sizeof(addr_str)-1] = '\000';
4316           if (coap_print_addr(&gaddr, (uint8_t *)addr_str,
4317                               sizeof(addr_str) - 1)) {
4318             if (ifname)
4319               coap_log_debug("added mcast group %s i/f %s\n", addr_str,
4320                              ifname);
4321             else
4322               coap_log_debug("added mcast group %s\n", addr_str);
4323           }
4324           mgroup_setup = 1;
4325         }
4326       }
4327     }
4328   }
4329   if (!mgroup_setup) {
4330     result = -1;
4331   }
4332 
4333 finish:
4334   freeaddrinfo(resmulti);
4335 
4336   return result;
4337 }
4338 
4339 void
coap_mcast_per_resource(coap_context_t * context)4340 coap_mcast_per_resource(coap_context_t *context) {
4341   context->mcast_per_resource = 1;
4342 }
4343 
4344 #endif /* ! COAP_SERVER_SUPPORT */
4345 
4346 #if COAP_CLIENT_SUPPORT
4347 int
coap_mcast_set_hops(coap_session_t * session,size_t hops)4348 coap_mcast_set_hops(coap_session_t *session, size_t hops) {
4349   if (session && coap_is_mcast(&session->addr_info.remote)) {
4350     switch (session->addr_info.remote.addr.sa.sa_family) {
4351 #if COAP_IPV4_SUPPORT
4352     case AF_INET:
4353       if (setsockopt(session->sock.fd, IPPROTO_IP, IP_MULTICAST_TTL,
4354                      (const char *)&hops, sizeof(hops)) < 0) {
4355         coap_log_info("coap_mcast_set_hops: %zu: setsockopt: %s\n",
4356                       hops, coap_socket_strerror());
4357         return 0;
4358       }
4359       return 1;
4360 #endif /* COAP_IPV4_SUPPORT */
4361 #if COAP_IPV6_SUPPORT
4362     case AF_INET6:
4363       if (setsockopt(session->sock.fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
4364                      (const char *)&hops, sizeof(hops)) < 0) {
4365         coap_log_info("coap_mcast_set_hops: %zu: setsockopt: %s\n",
4366                       hops, coap_socket_strerror());
4367         return 0;
4368       }
4369       return 1;
4370 #endif /* COAP_IPV6_SUPPORT */
4371     default:
4372       break;
4373     }
4374   }
4375   return 0;
4376 }
4377 #endif /* COAP_CLIENT_SUPPORT */
4378 
4379 #else /* defined WITH_CONTIKI || defined WITH_LWIP */
4380 int
coap_join_mcast_group_intf(coap_context_t * ctx COAP_UNUSED,const char * group_name COAP_UNUSED,const char * ifname COAP_UNUSED)4381 coap_join_mcast_group_intf(coap_context_t *ctx COAP_UNUSED,
4382                            const char *group_name COAP_UNUSED,
4383                            const char *ifname COAP_UNUSED) {
4384   return -1;
4385 }
4386 
4387 int
coap_mcast_set_hops(coap_session_t * session COAP_UNUSED,size_t hops COAP_UNUSED)4388 coap_mcast_set_hops(coap_session_t *session COAP_UNUSED,
4389                     size_t hops COAP_UNUSED) {
4390   return 0;
4391 }
4392 
4393 void
coap_mcast_per_resource(coap_context_t * context COAP_UNUSED)4394 coap_mcast_per_resource(coap_context_t *context COAP_UNUSED) {
4395 }
4396 #endif /* defined WITH_CONTIKI || defined WITH_LWIP */
4397