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