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