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