libcoap 4.3.1rc1
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 if (pdu->used_size + 1 <= pdu->max_size) {
1309 char *a_match;
1310 size_t data_len = pdu->used_size - (pdu->data - pdu->token);
1311 pdu->data[data_len] = '\000';
1312 a_match = strstr((char*)pdu->data, cp);
1313 if (a_match && (a_match == (char*)pdu->data || a_match[-1] == ' ') &&
1314 ((size_t)(a_match - (char*)pdu->data + len) == data_len ||
1315 a_match[len] == ' ')) {
1316 coap_log(LOG_WARNING, "Proxy loop detected '%s'\n",
1317 (char*)pdu->data);
1318 coap_delete_pdu(pdu);
1320 }
1321 }
1322 }
1323 if (pdu->used_size + len + 1 <= pdu->max_size) {
1324 size_t old_size = pdu->used_size;
1325 if (coap_pdu_resize(pdu, pdu->used_size + len + 1)) {
1326 if (pdu->data == NULL) {
1327 /*
1328 * Set Hop Limit to max for return path. If this libcoap is in
1329 * a proxy loop path, it will always decrement hop limit in code
1330 * above and hence timeout / drop the response as appropriate
1331 */
1332 hop_limit = 255;
1334 (uint8_t *)&hop_limit);
1335 coap_add_data(pdu, len, (uint8_t*)cp);
1336 }
1337 else {
1338 /* prepend with space separator, leaving hop limit "as is" */
1339 memmove(pdu->data + len + 1, pdu->data,
1340 old_size - (pdu->data - pdu->token));
1341 memcpy(pdu->data, cp, len);
1342 pdu->data[len] = ' ';
1343 pdu->used_size += len + 1;
1344 }
1345 }
1346 }
1347 }
1348 }
1349
1350 if (session->echo) {
1351 if (!coap_insert_option(pdu, COAP_OPTION_ECHO, session->echo->length,
1352 session->echo->s))
1353 goto error;
1354 coap_delete_bin_const(session->echo);
1355 session->echo = NULL;
1356 }
1357
1358 if (!coap_pdu_encode_header(pdu, session->proto)) {
1359 goto error;
1360 }
1361
1362#if !COAP_DISABLE_TCP
1363 if (COAP_PROTO_RELIABLE(session->proto) &&
1365 if (!session->csm_block_supported) {
1366 /*
1367 * Need to check that this instance is not sending any block options as
1368 * the remote end via CSM has not informed us that there is support
1369 * https://tools.ietf.org/html/rfc8323#section-5.3.2
1370 * This includes potential BERT blocks.
1371 */
1372 if (coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter) != NULL) {
1374 "Remote end did not indicate CSM support for Block1 enabled\n");
1375 }
1376 if (coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter) != NULL) {
1378 "Remote end did not indicate CSM support for Block2 enabled\n");
1379 }
1380 }
1381 else if (!session->csm_bert_rem_support) {
1382 coap_opt_t *opt;
1383
1384 opt = coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter);
1385 if (opt && COAP_OPT_BLOCK_SZX(opt) == 7) {
1387 "Remote end did not indicate CSM support for BERT Block1\n");
1388 }
1389 opt = coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter);
1390 if (opt && COAP_OPT_BLOCK_SZX(opt) == 7) {
1392 "Remote end did not indicate CSM support for BERT Block2\n");
1393 }
1394 }
1395 }
1396#endif /* !COAP_DISABLE_TCP */
1397
1398 bytes_written = coap_send_pdu( session, pdu, NULL );
1399
1400 if (bytes_written == COAP_PDU_DELAYED) {
1401 /* do not free pdu as it is stored with session for later use */
1402 return pdu->mid;
1403 }
1404
1405 if (bytes_written < 0) {
1406 goto error;
1407 }
1408
1409#if !COAP_DISABLE_TCP
1410 if (COAP_PROTO_RELIABLE(session->proto) &&
1411 (size_t)bytes_written < pdu->used_size + pdu->hdr_size) {
1412 if (coap_session_delay_pdu(session, pdu, NULL) == COAP_PDU_DELAYED) {
1413 session->partial_write = (size_t)bytes_written;
1414 /* do not free pdu as it is stored with session for later use */
1415 return pdu->mid;
1416 } else {
1417 goto error;
1418 }
1419 }
1420#endif /* !COAP_DISABLE_TCP */
1421
1422 if (pdu->type != COAP_MESSAGE_CON
1423 || COAP_PROTO_RELIABLE(session->proto)) {
1424 coap_mid_t id = pdu->mid;
1425 coap_delete_pdu(pdu);
1426 return id;
1427 }
1428
1429 coap_queue_t *node = coap_new_node();
1430 if (!node) {
1431 coap_log(LOG_DEBUG, "coap_wait_ack: insufficient memory\n");
1432 goto error;
1433 }
1434
1435 node->id = pdu->mid;
1436 node->pdu = pdu;
1437 coap_prng(&r, sizeof(r));
1438 /* add timeout in range [ACK_TIMEOUT...ACK_TIMEOUT * ACK_RANDOM_FACTOR] */
1439 node->timeout = coap_calc_timeout(session, r);
1440 return coap_wait_ack(session->context, session, node);
1441 error:
1442 coap_delete_pdu(pdu);
1443 return COAP_INVALID_MID;
1444}
1445
1448 if (!context || !node)
1449 return COAP_INVALID_MID;
1450
1451 /* re-initialize timeout when maximum number of retransmissions are not reached yet */
1452 if (node->retransmit_cnt < node->session->max_retransmit) {
1453 ssize_t bytes_written;
1454 coap_tick_t now;
1455
1456 node->retransmit_cnt++;
1457 coap_ticks(&now);
1458 if (context->sendqueue == NULL) {
1459 node->t = node->timeout << node->retransmit_cnt;
1460 context->sendqueue_basetime = now;
1461 } else {
1462 /* make node->t relative to context->sendqueue_basetime */
1463 node->t = (now - context->sendqueue_basetime) + (node->timeout << node->retransmit_cnt);
1464 }
1465 coap_insert_node(&context->sendqueue, node);
1466#ifdef WITH_LWIP
1467 if (node == context->sendqueue) /* don't bother with timer stuff if there are earlier retransmits */
1468 coap_retransmittimer_restart(context);
1469#endif
1470
1471 if (node->retransmit_cnt == node->session->max_retransmit) {
1472 coap_log(LOG_DEBUG, "** %s: mid=0x%x: final retransmission\n",
1473 coap_session_str(node->session), node->id);
1474 } else {
1475 coap_log(LOG_DEBUG, "** %s: mid=0x%x: retransmission #%d\n",
1476 coap_session_str(node->session), node->id, node->retransmit_cnt);
1477 }
1478
1479 if (node->session->con_active)
1480 node->session->con_active--;
1481 bytes_written = coap_send_pdu(node->session, node->pdu, node);
1482
1483 if (bytes_written == COAP_PDU_DELAYED) {
1484 /* PDU was not retransmitted immediately because a new handshake is
1485 in progress. node was moved to the send queue of the session. */
1486 return node->id;
1487 }
1488
1489 if (bytes_written < 0)
1490 return (int)bytes_written;
1491
1492 return node->id;
1493 }
1494
1495 /* no more retransmissions, remove node from system */
1496
1497#ifndef WITH_CONTIKI
1498 coap_log(LOG_DEBUG, "** %s: mid=0x%x: give up after %d attempts\n",
1499 coap_session_str(node->session), node->id, node->retransmit_cnt);
1500#endif
1501
1502#if COAP_SERVER_SUPPORT
1503 /* Check if subscriptions exist that should be canceled after
1504 COAP_MAX_NOTIFY_FAILURES */
1505 if (node->pdu->code >= 64) {
1506 coap_binary_t token = { 0, NULL };
1507
1508 token.length = node->pdu->token_length;
1509 token.s = node->pdu->token;
1510
1511 coap_handle_failed_notify(context, node->session, &token);
1512 }
1513#endif /* COAP_SERVER_SUPPORT */
1514 if (node->session->con_active) {
1515 node->session->con_active--;
1517 /*
1518 * As there may be another CON in a different queue entry on the same
1519 * session that needs to be immediately released,
1520 * coap_session_connected() is called.
1521 * However, there is the possibility coap_wait_ack() may be called for
1522 * this node (queue) and re-added to context->sendqueue.
1523 * coap_delete_node(node) called shortly will handle this and remove it.
1524 */
1526 }
1527 }
1528
1529 /* And finally delete the node */
1530 if (node->pdu->type == COAP_MESSAGE_CON && context->nack_handler)
1531 context->nack_handler(node->session, node->pdu, COAP_NACK_TOO_MANY_RETRIES, node->id);
1532 coap_delete_node(node);
1533 return COAP_INVALID_MID;
1534}
1535
1536#ifdef WITH_LWIP
1537/* WITH_LWIP, this is handled by coap_recv in a different way */
1538void
1540 return;
1541}
1542#else /* WITH_LWIP */
1543
1544static int
1546 uint8_t *data;
1547 size_t data_len;
1548 int result = -1;
1549
1550 coap_packet_get_memmapped(packet, &data, &data_len);
1551
1552 if (session->proto == COAP_PROTO_DTLS) {
1553#if COAP_SERVER_SUPPORT
1554 if (session->type == COAP_SESSION_TYPE_HELLO)
1555 result = coap_dtls_hello(session, data, data_len);
1556 else
1557#endif /* COAP_SERVER_SUPPORT */
1558 if (session->tls)
1559 result = coap_dtls_receive(session, data, data_len);
1560 } else if (session->proto == COAP_PROTO_UDP) {
1561 result = coap_handle_dgram(ctx, session, data, data_len);
1562 }
1563 return result;
1564}
1565
1566#if COAP_CLIENT_SUPPORT
1567static void
1568coap_connect_session(coap_context_t *ctx,
1569 coap_session_t *session,
1570 coap_tick_t now) {
1571 (void)ctx;
1572#if COAP_DISABLE_TCP
1573 (void)session;
1574 (void)now;
1575#else /* !COAP_DISABLE_TCP */
1576 if (coap_socket_connect_tcp2(&session->sock, &session->addr_info.local,
1577 &session->addr_info.remote)) {
1578 session->last_rx_tx = now;
1580 if (session->proto == COAP_PROTO_TCP) {
1581 coap_session_send_csm(session);
1582 } else if (session->proto == COAP_PROTO_TLS) {
1583 int connected = 0;
1585 session->tls = coap_tls_new_client_session(session, &connected);
1586 if (session->tls) {
1587 if (connected) {
1589 session);
1590 coap_session_send_csm(session);
1591 }
1592 } else {
1595 }
1596 }
1597 } else {
1600 }
1601#endif /* !COAP_DISABLE_TCP */
1602}
1603#endif /* COAP_CLIENT_SUPPORT */
1604
1605static void
1607 (void)ctx;
1608 assert(session->sock.flags & COAP_SOCKET_CONNECTED);
1609
1610 while (session->delayqueue) {
1611 ssize_t bytes_written;
1612 coap_queue_t *q = session->delayqueue;
1613 coap_log(LOG_DEBUG, "** %s: mid=0x%x: transmitted after delay\n",
1614 coap_session_str(session), (int)q->pdu->mid);
1615 assert(session->partial_write < q->pdu->used_size + q->pdu->hdr_size);
1616 switch (session->proto) {
1617 case COAP_PROTO_TCP:
1618#if !COAP_DISABLE_TCP
1619 bytes_written = coap_session_write(
1620 session,
1621 q->pdu->token - q->pdu->hdr_size + session->partial_write,
1622 q->pdu->used_size + q->pdu->hdr_size - session->partial_write
1623 );
1624#endif /* !COAP_DISABLE_TCP */
1625 break;
1626 case COAP_PROTO_TLS:
1627#if !COAP_DISABLE_TCP
1628 bytes_written = coap_tls_write(
1629 session,
1630 q->pdu->token - q->pdu->hdr_size - session->partial_write,
1631 q->pdu->used_size + q->pdu->hdr_size - session->partial_write
1632 );
1633#endif /* !COAP_DISABLE_TCP */
1634 break;
1635 case COAP_PROTO_NONE:
1636 case COAP_PROTO_UDP:
1637 case COAP_PROTO_DTLS:
1638 default:
1639 bytes_written = -1;
1640 break;
1641 }
1642 if (bytes_written > 0)
1643 session->last_rx_tx = now;
1644 if (bytes_written <= 0 || (size_t)bytes_written < q->pdu->used_size + q->pdu->hdr_size - session->partial_write) {
1645 if (bytes_written > 0)
1646 session->partial_write += (size_t)bytes_written;
1647 break;
1648 }
1649 session->delayqueue = q->next;
1650 session->partial_write = 0;
1652 }
1653}
1654
1655static void
1657#if COAP_CONSTRAINED_STACK
1658 static coap_mutex_t s_static_mutex = COAP_MUTEX_INITIALIZER;
1659 static coap_packet_t s_packet;
1660#else /* ! COAP_CONSTRAINED_STACK */
1661 coap_packet_t s_packet;
1662#endif /* ! COAP_CONSTRAINED_STACK */
1663 coap_packet_t *packet = &s_packet;
1664
1665#if COAP_CONSTRAINED_STACK
1666 coap_mutex_lock(&s_static_mutex);
1667#endif /* COAP_CONSTRAINED_STACK */
1668
1670
1671 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
1672 ssize_t bytes_read;
1673 memcpy(&packet->addr_info, &session->addr_info, sizeof(packet->addr_info));
1674 bytes_read = ctx->network_read(&session->sock, packet);
1675
1676 if (bytes_read < 0) {
1677 if (bytes_read == -2)
1678 /* Reset the session back to startup defaults */
1680 else
1681 coap_log(LOG_WARNING, "* %s: read error\n",
1682 coap_session_str(session));
1683 } else if (bytes_read > 0) {
1684 session->last_rx_tx = now;
1685 memcpy(&session->addr_info, &packet->addr_info,
1686 sizeof(session->addr_info));
1687 coap_log(LOG_DEBUG, "* %s: received %zd bytes\n",
1688 coap_session_str(session), bytes_read);
1689 coap_handle_dgram_for_proto(ctx, session, packet);
1690 }
1691#if !COAP_DISABLE_TCP
1692 } else {
1693 ssize_t bytes_read = 0;
1694 const uint8_t *p;
1695 int retry;
1696 /* adjust for LWIP */
1697 uint8_t *buf = packet->payload;
1698 size_t buf_len = sizeof(packet->payload);
1699
1700 do {
1701 if (session->proto == COAP_PROTO_TCP)
1702 bytes_read = coap_socket_read(&session->sock, buf, buf_len);
1703 else if (session->proto == COAP_PROTO_TLS)
1704 bytes_read = coap_tls_read(session, buf, buf_len);
1705 if (bytes_read > 0) {
1706 coap_log(LOG_DEBUG, "* %s: received %zd bytes\n",
1707 coap_session_str(session), bytes_read);
1708 session->last_rx_tx = now;
1709 }
1710 p = buf;
1711 retry = bytes_read == (ssize_t)buf_len;
1712 while (bytes_read > 0) {
1713 if (session->partial_pdu) {
1714 size_t len = session->partial_pdu->used_size
1715 + session->partial_pdu->hdr_size
1716 - session->partial_read;
1717 size_t n = min(len, (size_t)bytes_read);
1718 memcpy(session->partial_pdu->token - session->partial_pdu->hdr_size
1719 + session->partial_read, p, n);
1720 p += n;
1721 bytes_read -= n;
1722 if (n == len) {
1723 if (coap_pdu_parse_header(session->partial_pdu, session->proto)
1724 && coap_pdu_parse_opt(session->partial_pdu)) {
1725#if COAP_CONSTRAINED_STACK
1726 coap_mutex_unlock(&s_static_mutex);
1727#endif /* COAP_CONSTRAINED_STACK */
1728 coap_dispatch(ctx, session, session->partial_pdu);
1729#if COAP_CONSTRAINED_STACK
1730 coap_mutex_lock(&s_static_mutex);
1731#endif /* COAP_CONSTRAINED_STACK */
1732 }
1733 coap_delete_pdu(session->partial_pdu);
1734 session->partial_pdu = NULL;
1735 session->partial_read = 0;
1736 } else {
1737 session->partial_read += n;
1738 }
1739 } else if (session->partial_read > 0) {
1740 size_t hdr_size = coap_pdu_parse_header_size(session->proto,
1741 session->read_header);
1742 size_t len = hdr_size - session->partial_read;
1743 size_t n = min(len, (size_t)bytes_read);
1744 memcpy(session->read_header + session->partial_read, p, n);
1745 p += n;
1746 bytes_read -= n;
1747 if (n == len) {
1748 size_t size = coap_pdu_parse_size(session->proto, session->read_header,
1749 hdr_size);
1750 if (size > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
1752 "** %s: incoming PDU length too large (%zu > %lu)\n",
1753 coap_session_str(session),
1754 size, COAP_DEFAULT_MAX_PDU_RX_SIZE);
1755 bytes_read = -1;
1756 break;
1757 }
1758 /* Need max space incase PDU is updated with updated token etc. */
1759 session->partial_pdu = coap_pdu_init(0, 0, 0,
1761 if (session->partial_pdu == NULL) {
1762 bytes_read = -1;
1763 break;
1764 }
1765 if (session->partial_pdu->alloc_size < size && !coap_pdu_resize(session->partial_pdu, size)) {
1766 bytes_read = -1;
1767 break;
1768 }
1769 session->partial_pdu->hdr_size = (uint8_t)hdr_size;
1770 session->partial_pdu->used_size = size;
1771 memcpy(session->partial_pdu->token - hdr_size, session->read_header, hdr_size);
1772 session->partial_read = hdr_size;
1773 if (size == 0) {
1774 if (coap_pdu_parse_header(session->partial_pdu, session->proto)) {
1775#if COAP_CONSTRAINED_STACK
1776 coap_mutex_unlock(&s_static_mutex);
1777#endif /* COAP_CONSTRAINED_STACK */
1778 coap_dispatch(ctx, session, session->partial_pdu);
1779#if COAP_CONSTRAINED_STACK
1780 coap_mutex_lock(&s_static_mutex);
1781#endif /* COAP_CONSTRAINED_STACK */
1782 }
1783 coap_delete_pdu(session->partial_pdu);
1784 session->partial_pdu = NULL;
1785 session->partial_read = 0;
1786 }
1787 } else {
1788 session->partial_read += bytes_read;
1789 }
1790 } else {
1791 session->read_header[0] = *p++;
1792 bytes_read -= 1;
1793 if (!coap_pdu_parse_header_size(session->proto,
1794 session->read_header)) {
1795 bytes_read = -1;
1796 break;
1797 }
1798 session->partial_read = 1;
1799 }
1800 }
1801 } while (bytes_read == 0 && retry);
1802 if (bytes_read < 0)
1804#endif /* !COAP_DISABLE_TCP */
1805 }
1806#if COAP_CONSTRAINED_STACK
1807 coap_mutex_unlock(&s_static_mutex);
1808#endif /* COAP_CONSTRAINED_STACK */
1809}
1810
1811#if COAP_SERVER_SUPPORT
1812static int
1813coap_read_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
1814 ssize_t bytes_read = -1;
1815 int result = -1; /* the value to be returned */
1816#if COAP_CONSTRAINED_STACK
1817 static coap_mutex_t e_static_mutex = COAP_MUTEX_INITIALIZER;
1818 static coap_packet_t e_packet;
1819#else /* ! COAP_CONSTRAINED_STACK */
1820 coap_packet_t e_packet;
1821#endif /* ! COAP_CONSTRAINED_STACK */
1822 coap_packet_t *packet = &e_packet;
1823
1824 assert(COAP_PROTO_NOT_RELIABLE(endpoint->proto));
1825 assert(endpoint->sock.flags & COAP_SOCKET_BOUND);
1826
1827#if COAP_CONSTRAINED_STACK
1828 coap_mutex_lock(&e_static_mutex);
1829#endif /* COAP_CONSTRAINED_STACK */
1830
1831 /* Need to do this as there may be holes in addr_info */
1832 memset(&packet->addr_info, 0, sizeof(packet->addr_info));
1834 coap_address_copy(&packet->addr_info.local, &endpoint->bind_addr);
1835 bytes_read = ctx->network_read(&endpoint->sock, packet);
1836
1837 if (bytes_read < 0) {
1838 coap_log(LOG_WARNING, "* %s: read failed\n", coap_endpoint_str(endpoint));
1839 } else if (bytes_read > 0) {
1840 coap_session_t *session = coap_endpoint_get_session(endpoint, packet, now);
1841 if (session) {
1842 coap_log(LOG_DEBUG, "* %s: received %zd bytes\n",
1843 coap_session_str(session), bytes_read);
1844 result = coap_handle_dgram_for_proto(ctx, session, packet);
1845 if (endpoint->proto == COAP_PROTO_DTLS && session->type == COAP_SESSION_TYPE_HELLO && result == 1)
1846 coap_session_new_dtls_session(session, now);
1847 }
1848 }
1849#if COAP_CONSTRAINED_STACK
1850 coap_mutex_unlock(&e_static_mutex);
1851#endif /* COAP_CONSTRAINED_STACK */
1852 return result;
1853}
1854
1855static int
1856coap_write_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
1857 (void)ctx;
1858 (void)endpoint;
1859 (void)now;
1860 return 0;
1861}
1862
1863static int
1864coap_accept_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint,
1865 coap_tick_t now) {
1866 coap_session_t *session = coap_new_server_session(ctx, endpoint);
1867 if (session)
1868 session->last_rx_tx = now;
1869 return session != NULL;
1870}
1871#endif /* COAP_SERVER_SUPPORT */
1872
1873void
1875#ifdef COAP_EPOLL_SUPPORT
1876 (void)ctx;
1877 (void)now;
1879 "coap_io_do_io() requires libcoap not compiled for using epoll\n");
1880#else /* ! COAP_EPOLL_SUPPORT */
1881 coap_session_t *s, *rtmp;
1882
1883#if COAP_SERVER_SUPPORT
1884 coap_endpoint_t *ep, *tmp;
1885 LL_FOREACH_SAFE(ctx->endpoint, ep, tmp) {
1886 if ((ep->sock.flags & COAP_SOCKET_CAN_READ) != 0)
1887 coap_read_endpoint(ctx, ep, now);
1888 if ((ep->sock.flags & COAP_SOCKET_CAN_WRITE) != 0)
1889 coap_write_endpoint(ctx, ep, now);
1890 if ((ep->sock.flags & COAP_SOCKET_CAN_ACCEPT) != 0)
1891 coap_accept_endpoint(ctx, ep, now);
1892 SESSIONS_ITER_SAFE(ep->sessions, s, rtmp) {
1893 /* Make sure the session object is not deleted in one of the callbacks */
1895 if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0) {
1896 coap_read_session(ctx, s, now);
1897 }
1898 if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0) {
1899 coap_write_session(ctx, s, now);
1900 }
1902 }
1903 }
1904#endif /* COAP_SERVER_SUPPORT */
1905
1906#if COAP_CLIENT_SUPPORT
1907 SESSIONS_ITER_SAFE(ctx->sessions, s, rtmp) {
1908 /* Make sure the session object is not deleted in one of the callbacks */
1910 if ((s->sock.flags & COAP_SOCKET_CAN_CONNECT) != 0) {
1911 coap_connect_session(ctx, s, now);
1912 }
1913 if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0 && s->ref > 1) {
1914 coap_read_session(ctx, s, now);
1915 }
1916 if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0 && s->ref > 1) {
1917 coap_write_session(ctx, s, now);
1918 }
1920 }
1921#endif /* COAP_CLIENT_SUPPORT */
1922#endif /* ! COAP_EPOLL_SUPPORT */
1923}
1924
1925/*
1926 * While this code in part replicates coap_io_do_io(), doing the functions
1927 * directly saves having to iterate through the endpoints / sessions.
1928 */
1929void
1930coap_io_do_epoll(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
1931#ifndef COAP_EPOLL_SUPPORT
1932 (void)ctx;
1933 (void)events;
1934 (void)nevents;
1936 "coap_io_do_epoll() requires libcoap compiled for using epoll\n");
1937#else /* COAP_EPOLL_SUPPORT */
1938 coap_tick_t now;
1939 size_t j;
1940
1941 coap_ticks(&now);
1942 for(j = 0; j < nevents; j++) {
1943 coap_socket_t *sock = (coap_socket_t*)events[j].data.ptr;
1944
1945 /* Ignore 'timer trigger' ptr which is NULL */
1946 if (sock) {
1947#if COAP_SERVER_SUPPORT
1948 if (sock->endpoint) {
1949 coap_endpoint_t *endpoint = sock->endpoint;
1950 if ((sock->flags & COAP_SOCKET_WANT_READ) &&
1951 (events[j].events & EPOLLIN)) {
1952 sock->flags |= COAP_SOCKET_CAN_READ;
1953 coap_read_endpoint(endpoint->context, endpoint, now);
1954 }
1955
1956 if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
1957 (events[j].events & EPOLLOUT)) {
1958 /*
1959 * Need to update this to EPOLLIN as EPOLLOUT will normally always
1960 * be true causing epoll_wait to return early
1961 */
1962 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
1964 coap_write_endpoint(endpoint->context, endpoint, now);
1965 }
1966
1967 if ((sock->flags & COAP_SOCKET_WANT_ACCEPT) &&
1968 (events[j].events & EPOLLIN)) {
1970 coap_accept_endpoint(endpoint->context, endpoint, now);
1971 }
1972
1973 }
1974 else
1975#endif /* COAP_SERVER_SUPPORT */
1976 if (sock->session) {
1977 coap_session_t *session = sock->session;
1978
1979 /* Make sure the session object is not deleted
1980 in one of the callbacks */
1981 coap_session_reference(session);
1982#if COAP_CLIENT_SUPPORT
1983 if ((sock->flags & COAP_SOCKET_WANT_CONNECT) &&
1984 (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
1986 coap_connect_session(session->context, session, now);
1987 if (sock->flags != COAP_SOCKET_EMPTY &&
1988 !(sock->flags & COAP_SOCKET_WANT_WRITE)) {
1989 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
1990 }
1991 }
1992#endif /* COAP_CLIENT_SUPPORT */
1993
1994 if ((sock->flags & COAP_SOCKET_WANT_READ) &&
1995 (events[j].events & (EPOLLIN|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
1996 sock->flags |= COAP_SOCKET_CAN_READ;
1997 coap_read_session(session->context, session, now);
1998 }
1999
2000 if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
2001 (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
2002 /*
2003 * Need to update this to EPOLLIN as EPOLLOUT will normally always
2004 * be true causing epoll_wait to return early
2005 */
2006 coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
2008 coap_write_session(session->context, session, now);
2009 }
2010 /* Now dereference session so it can go away if needed */
2011 coap_session_release(session);
2012 }
2013 }
2014 else if (ctx->eptimerfd != -1) {
2015 /*
2016 * 'timer trigger' must have fired. eptimerfd needs to be read to clear
2017 * it so that it does not set EPOLLIN in the next epoll_wait().
2018 */
2019 uint64_t count;
2020
2021 /* Check the result from read() to suppress the warning on
2022 * systems that declare read() with warn_unused_result. */
2023 if (read(ctx->eptimerfd, &count, sizeof(count)) == -1) {
2024 /* do nothing */;
2025 }
2026 }
2027 }
2028 /* And update eptimerfd as to when to next trigger */
2029 coap_ticks(&now);
2030 coap_io_prepare_epoll(ctx, now);
2031#endif /* COAP_EPOLL_SUPPORT */
2032}
2033
2034int
2036 uint8_t *msg, size_t msg_len) {
2037
2038 coap_pdu_t *pdu = NULL;
2039
2040 assert(COAP_PROTO_NOT_RELIABLE(session->proto));
2041 if (msg_len < 4) {
2042 /* Minimum size of CoAP header - ignore runt */
2043 return -1;
2044 }
2045
2046 /* Need max space incase PDU is updated with updated token etc. */
2047 pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_size(session));
2048 if (!pdu)
2049 goto error;
2050
2051 if (!coap_pdu_parse(session->proto, msg, msg_len, pdu)) {
2052 coap_log(LOG_WARNING, "discard malformed PDU\n");
2053 goto error;
2054 }
2055
2056 coap_dispatch(ctx, session, pdu);
2057 coap_delete_pdu(pdu);
2058 return 0;
2059
2060error:
2061 /*
2062 * https://tools.ietf.org/html/rfc7252#section-4.2 MUST send RST
2063 * https://tools.ietf.org/html/rfc7252#section-4.3 MAY send RST
2064 */
2065 coap_send_rst(session, pdu);
2066 coap_delete_pdu(pdu);
2067 return -1;
2068}
2069#endif /* not WITH_LWIP */
2070
2071int
2073 coap_queue_t *p, *q;
2074
2075 if (!queue || !*queue)
2076 return 0;
2077
2078 /* replace queue head if PDU's time is less than head's time */
2079
2080 if (session == (*queue)->session && id == (*queue)->id) { /* found message id */
2081 *node = *queue;
2082 *queue = (*queue)->next;
2083 if (*queue) { /* adjust relative time of new queue head */
2084 (*queue)->t += (*node)->t;
2085 }
2086 (*node)->next = NULL;
2087 coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed 1\n",
2088 coap_session_str(session), id);
2089 return 1;
2090 }
2091
2092 /* search message id queue to remove (only first occurence will be removed) */
2093 q = *queue;
2094 do {
2095 p = q;
2096 q = q->next;
2097 } while (q && (session != q->session || id != q->id));
2098
2099 if (q) { /* found message id */
2100 p->next = q->next;
2101 if (p->next) { /* must update relative time of p->next */
2102 p->next->t += q->t;
2103 }
2104 q->next = NULL;
2105 *node = q;
2106 coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed 2\n",
2107 coap_session_str(session), id);
2108 return 1;
2109 }
2110
2111 return 0;
2112
2113}
2114
2115void
2117 coap_nack_reason_t reason) {
2118 coap_queue_t *p, *q;
2119
2120 while (context->sendqueue && context->sendqueue->session == session) {
2121 q = context->sendqueue;
2122 context->sendqueue = q->next;
2123 coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed 3\n",
2124 coap_session_str(session), q->id);
2125 if (q->pdu->type == COAP_MESSAGE_CON && context->nack_handler)
2126 context->nack_handler(session, q->pdu, reason, q->id);
2128 }
2129
2130 if (!context->sendqueue)
2131 return;
2132
2133 p = context->sendqueue;
2134 q = p->next;
2135
2136 while (q) {
2137 if (q->session == session) {
2138 p->next = q->next;
2139 coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed 4\n",
2140 coap_session_str(session), q->id);
2141 if (q->pdu->type == COAP_MESSAGE_CON && context->nack_handler)
2142 context->nack_handler(session, q->pdu, reason, q->id);
2144 q = p->next;
2145 } else {
2146 p = q;
2147 q = q->next;
2148 }
2149 }
2150}
2151
2152void
2154 const uint8_t *token, size_t token_length) {
2155 /* cancel all messages in sendqueue that belong to session
2156 * and use the specified token */
2157 coap_queue_t *p, *q;
2158
2159 while (context->sendqueue && context->sendqueue->session == session &&
2160 token_match(token, token_length,
2161 context->sendqueue->pdu->token,
2162 context->sendqueue->pdu->token_length)) {
2163 q = context->sendqueue;
2164 context->sendqueue = q->next;
2165 coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed 5\n",
2166 coap_session_str(session), q->id);
2168 }
2169
2170 if (!context->sendqueue)
2171 return;
2172
2173 p = context->sendqueue;
2174 q = p->next;
2175
2176 /* when q is not NULL, it does not match (dst, token), so we can skip it */
2177 while (q) {
2178 if (q->session == session &&
2179 token_match(token, token_length,
2180 q->pdu->token, q->pdu->token_length)) {
2181 p->next = q->next;
2182 coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed 6\n",
2183 coap_session_str(session), q->id);
2185 q = p->next;
2186 } else {
2187 p = q;
2188 q = q->next;
2189 }
2190 }
2191}
2192
2193coap_pdu_t *
2195 coap_opt_filter_t *opts) {
2196 coap_opt_iterator_t opt_iter;
2197 coap_pdu_t *response;
2198 size_t size = request->token_length;
2199 unsigned char type;
2200 coap_opt_t *option;
2201 coap_option_num_t opt_num = 0; /* used for calculating delta-storage */
2202
2203#if COAP_ERROR_PHRASE_LENGTH > 0
2204 const char *phrase;
2205 if (code != COAP_RESPONSE_CODE(508)) {
2206 phrase = coap_response_phrase(code);
2207
2208 /* Need some more space for the error phrase and payload start marker */
2209 if (phrase)
2210 size += strlen(phrase) + 1;
2211 }
2212 else {
2213 /*
2214 * Need space for IP for 5.08 response which is filled in in
2215 * coap_send_internal()
2216 * https://www.rfc-editor.org/rfc/rfc8768.html#section-4
2217 */
2218 phrase = NULL;
2219 size += INET6_ADDRSTRLEN;
2220 }
2221#endif
2222
2223 assert(request);
2224
2225 /* cannot send ACK if original request was not confirmable */
2226 type = request->type == COAP_MESSAGE_CON
2229
2230 /* Estimate how much space we need for options to copy from
2231 * request. We always need the Token, for 4.02 the unknown critical
2232 * options must be included as well. */
2233
2234 /* we do not want these */
2237 /* Unsafe to send this back */
2239
2240 coap_option_iterator_init(request, &opt_iter, opts);
2241
2242 /* Add size of each unknown critical option. As known critical
2243 options as well as elective options are not copied, the delta
2244 value might grow.
2245 */
2246 while ((option = coap_option_next(&opt_iter))) {
2247 uint16_t delta = opt_iter.number - opt_num;
2248 /* calculate space required to encode (opt_iter.number - opt_num) */
2249 if (delta < 13) {
2250 size++;
2251 } else if (delta < 269) {
2252 size += 2;
2253 } else {
2254 size += 3;
2255 }
2256
2257 /* add coap_opt_length(option) and the number of additional bytes
2258 * required to encode the option length */
2259
2260 size += coap_opt_length(option);
2261 switch (*option & 0x0f) {
2262 case 0x0e:
2263 size++;
2264 /* fall through */
2265 case 0x0d:
2266 size++;
2267 break;
2268 default:
2269 ;
2270 }
2271
2272 opt_num = opt_iter.number;
2273 }
2274
2275 /* Now create the response and fill with options and payload data. */
2276 response = coap_pdu_init(type, code, request->mid, size);
2277 if (response) {
2278 /* copy token */
2279 if (!coap_add_token(response, request->token_length,
2280 request->token)) {
2281 coap_log(LOG_DEBUG, "cannot add token to error response\n");
2282 coap_delete_pdu(response);
2283 return NULL;
2284 }
2285
2286 /* copy all options */
2287 coap_option_iterator_init(request, &opt_iter, opts);
2288 while ((option = coap_option_next(&opt_iter))) {
2289 coap_add_option_internal(response, opt_iter.number,
2290 coap_opt_length(option),
2291 coap_opt_value(option));
2292 }
2293
2294#if COAP_ERROR_PHRASE_LENGTH > 0
2295 /* note that diagnostic messages do not need a Content-Format option. */
2296 if (phrase)
2297 coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
2298#endif
2299 }
2300
2301 return response;
2302}
2303
2304#if COAP_SERVER_SUPPORT
2309COAP_STATIC_INLINE ssize_t
2310get_wkc_len(coap_context_t *context, const coap_string_t *query_filter) {
2311 unsigned char buf[1];
2312 size_t len = 0;
2313
2314 if (coap_print_wellknown(context, buf, &len, UINT_MAX, query_filter) &
2316 coap_log(LOG_WARNING, "cannot determine length of /.well-known/core\n");
2317 return -1L;
2318 }
2319
2320 return len;
2321}
2322
2323#define SZX_TO_BYTES(SZX) ((size_t)(1 << ((SZX) + 4)))
2324
2325static void
2326free_wellknown_response(coap_session_t *session COAP_UNUSED, void *app_ptr) {
2327 coap_delete_string(app_ptr);
2328}
2329
2330static void
2331hnd_get_wellknown(coap_resource_t *resource,
2332 coap_session_t *session,
2333 const coap_pdu_t *request,
2334 const coap_string_t *query,
2335 coap_pdu_t *response) {
2336 size_t len = 0;
2337 coap_string_t *data_string = NULL;
2338 int result = 0;
2339 ssize_t wkc_len = get_wkc_len(session->context, query);
2340
2341 if (wkc_len) {
2342 if (wkc_len < 0)
2343 goto error;
2344 data_string = coap_new_string(wkc_len);
2345 if (!data_string)
2346 goto error;
2347
2348 len = wkc_len;
2349 result = coap_print_wellknown(session->context, data_string->s, &len, 0,
2350 query);
2351 if ((result & COAP_PRINT_STATUS_ERROR) != 0) {
2352 coap_log(LOG_DEBUG, "coap_print_wellknown failed\n");
2353 goto error;
2354 }
2355 assert (len <= (size_t)wkc_len);
2356 data_string->length = len;
2357
2358 if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
2359 uint8_t buf[4];
2360
2362 coap_encode_var_safe(buf, sizeof(buf),
2364 goto error;
2365 }
2366 if (response->used_size + len + 1 > response->max_size) {
2367 /*
2368 * Data does not fit into a packet and no libcoap block support
2369 * +1 for end of options marker
2370 */
2372 ".well-known/core: truncating data length to %zu from %zu\n",
2373 len, response->max_size - response->used_size - 1);
2374 len = response->max_size - response->used_size - 1;
2375 }
2376 if (!coap_add_data(response, len, data_string->s)) {
2377 goto error;
2378 }
2379 free_wellknown_response(session, data_string);
2380 } else if (!coap_add_data_large_response(resource, session, request,
2381 response, query,
2383 -1, 0, data_string->length,
2384 data_string->s,
2385 free_wellknown_response,
2386 data_string)) {
2387 goto error_released;
2388 }
2389 }
2390 response->code = COAP_RESPONSE_CODE(205);
2391 return;
2392
2393error:
2394 free_wellknown_response(session, data_string);
2395error_released:
2396 if (response->code == 0) {
2397 /* set error code 5.03 and remove all options and data from response */
2398 response->code = COAP_RESPONSE_CODE(503);
2399 response->used_size = response->token_length;
2400 response->data = NULL;
2401 }
2402}
2403#endif /* COAP_SERVER_SUPPORT */
2404
2415static int
2417 coap_binary_t token = { 0, NULL };
2418 int num_cancelled = 0; /* the number of observers cancelled */
2419
2420 (void)context;
2421 /* remove observer for this resource, if any
2422 * get token from sent and try to find a matching resource. Uh!
2423 */
2424
2425 COAP_SET_STR(&token, sent->pdu->token_length, sent->pdu->token);
2426
2427#if COAP_SERVER_SUPPORT
2428 RESOURCES_ITER(context->resources, r) {
2429 coap_cancel_all_messages(context, sent->session, token.s, token.length);
2430 num_cancelled += coap_delete_observer(r, sent->session, &token);
2431 }
2432#endif /* COAP_SERVER_SUPPORT */
2433
2434 return num_cancelled;
2435}
2436
2437#if COAP_SERVER_SUPPORT
2442enum respond_t { RESPONSE_DEFAULT, RESPONSE_DROP, RESPONSE_SEND };
2443
2444/*
2445 * Checks for No-Response option in given @p request and
2446 * returns @c RESPONSE_DROP if @p response should be suppressed
2447 * according to RFC 7967.
2448 *
2449 * If the response is a confirmable piggybacked response and RESPONSE_DROP,
2450 * change it to an empty ACK and @c RESPONSE_SEND so the client does not keep
2451 * on retrying.
2452 *
2453 * Checks if the response code is 0.00 and if either the session is reliable or
2454 * non-confirmable, @c RESPONSE_DROP is also returned.
2455 *
2456 * Multicast response checking is also carried out.
2457 *
2458 * NOTE: It is the responsibility of the application to determine whether
2459 * a delayed separate response should be sent as the original requesting packet
2460 * containing the No-Response option has long since gone.
2461 *
2462 * The value of the No-Response option is encoded as
2463 * follows:
2464 *
2465 * @verbatim
2466 * +-------+-----------------------+-----------------------------------+
2467 * | Value | Binary Representation | Description |
2468 * +-------+-----------------------+-----------------------------------+
2469 * | 0 | <empty> | Interested in all responses. |
2470 * +-------+-----------------------+-----------------------------------+
2471 * | 2 | 00000010 | Not interested in 2.xx responses. |
2472 * +-------+-----------------------+-----------------------------------+
2473 * | 8 | 00001000 | Not interested in 4.xx responses. |
2474 * +-------+-----------------------+-----------------------------------+
2475 * | 16 | 00010000 | Not interested in 5.xx responses. |
2476 * +-------+-----------------------+-----------------------------------+
2477 * @endverbatim
2478 *
2479 * @param request The CoAP request to check for the No-Response option.
2480 * This parameter must not be NULL.
2481 * @param response The response that is potentially suppressed.
2482 * This parameter must not be NULL.
2483 * @param session The session this request/response are associated with.
2484 * This parameter must not be NULL.
2485 * @return RESPONSE_DEFAULT when no special treatment is requested,
2486 * RESPONSE_DROP when the response must be discarded, or
2487 * RESPONSE_SEND when the response must be sent.
2488 */
2489static enum respond_t
2490no_response(coap_pdu_t *request, coap_pdu_t *response,
2491 coap_session_t *session, coap_resource_t *resource) {
2492 coap_opt_t *nores;
2493 coap_opt_iterator_t opt_iter;
2494 unsigned int val = 0;
2495
2496 assert(request);
2497 assert(response);
2498
2499 if (COAP_RESPONSE_CLASS(response->code) > 0) {
2500 nores = coap_check_option(request, COAP_OPTION_NORESPONSE, &opt_iter);
2501
2502 if (nores) {
2504
2505 /* The response should be dropped when the bit corresponding to
2506 * the response class is set (cf. table in function
2507 * documentation). When a No-Response option is present and the
2508 * bit is not set, the sender explicitly indicates interest in
2509 * this response. */
2510 if (((1 << (COAP_RESPONSE_CLASS(response->code) - 1)) & val) > 0) {
2511 /* Should be dropping the response */
2512 if (response->type == COAP_MESSAGE_ACK &&
2513 COAP_PROTO_NOT_RELIABLE(session->proto)) {
2514 /* Still need to ACK the request */
2515 response->code = 0;
2516 /* Remove token/data from piggybacked acknowledgment PDU */
2517 response->token_length = 0;
2518 response->used_size = 0;
2519 return RESPONSE_SEND;
2520 }
2521 else {
2522 return RESPONSE_DROP;
2523 }
2524 } else {
2525 /* True for mcast as well RFC7967 2.1 */
2526 return RESPONSE_SEND;
2527 }
2528 } else if (resource && session->context->mcast_per_resource &&
2529 coap_is_mcast(&session->addr_info.local)) {
2530 /* Handle any mcast suppression specifics if no NoResponse option */
2531 if ((resource->flags &
2533 COAP_RESPONSE_CLASS(response->code) == 2) {
2534 return RESPONSE_DROP;
2535 } else if ((resource->flags &
2537 response->code == COAP_RESPONSE_CODE(205)) {
2538 if (response->data == NULL)
2539 return RESPONSE_DROP;
2540 } else if ((resource->flags &
2542 COAP_RESPONSE_CLASS(response->code) == 4) {
2543 return RESPONSE_DROP;
2544 } else if ((resource->flags &
2546 COAP_RESPONSE_CLASS(response->code) == 5) {
2547 return RESPONSE_DROP;
2548 }
2549 }
2550 }
2551 else if (COAP_PDU_IS_EMPTY(response) &&
2552 (response->type == COAP_MESSAGE_NON ||
2553 COAP_PROTO_RELIABLE(session->proto))) {
2554 /* response is 0.00, and this is reliable or non-confirmable */
2555 return RESPONSE_DROP;
2556 }
2557
2558 /*
2559 * Do not send error responses for requests that were received via
2560 * IP multicast. RFC7252 8.1
2561 */
2562
2563 if (coap_is_mcast(&session->addr_info.local)) {
2564 if (request->type == COAP_MESSAGE_NON &&
2565 response->type == COAP_MESSAGE_RST)
2566 return RESPONSE_DROP;
2567
2568 if ((!resource || session->context->mcast_per_resource == 0) &&
2569 COAP_RESPONSE_CLASS(response->code) > 2)
2570 return RESPONSE_DROP;
2571 }
2572
2573 /* Default behavior applies when we are not dealing with a response
2574 * (class == 0) or the request did not contain a No-Response option.
2575 */
2576 return RESPONSE_DEFAULT;
2577}
2578
2579static coap_str_const_t coap_default_uri_wellknown =
2580 { sizeof(COAP_DEFAULT_URI_WELLKNOWN)-1,
2581 (const uint8_t *)COAP_DEFAULT_URI_WELLKNOWN };
2582
2583/* Initialized in coap_startup() */
2584static coap_resource_t resource_uri_wellknown;
2585
2586static void
2587handle_request(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu) {
2588 coap_method_handler_t h = NULL;
2589 coap_pdu_t *response = NULL;
2590 coap_opt_filter_t opt_filter;
2591 coap_resource_t *resource = NULL;
2592 /* The respond field indicates whether a response must be treated
2593 * specially due to a No-Response option that declares disinterest
2594 * or interest in a specific response class. DEFAULT indicates that
2595 * No-Response has not been specified. */
2596 enum respond_t respond = RESPONSE_DEFAULT;
2597 coap_opt_iterator_t opt_iter;
2598 coap_opt_t *opt;
2599 int is_proxy_uri = 0;
2600 int is_proxy_scheme = 0;
2601 int skip_hop_limit_check = 0;
2602 int resp;
2603 int send_early_empty_ack = 0;
2604 coap_binary_t token = { pdu->token_length, pdu->token };
2605 coap_string_t *query = NULL;
2606 coap_opt_t *observe = NULL;
2607 coap_string_t *uri_path = NULL;
2608#ifndef WITHOUT_ASYNC
2609 coap_bin_const_t tokenc = { pdu->token_length, pdu->token };
2610 coap_async_t *async;
2611#endif /* WITHOUT_ASYNC */
2612
2613 if (coap_is_mcast(&session->addr_info.local)) {
2614 if (COAP_PROTO_RELIABLE(session->proto) || pdu->type != COAP_MESSAGE_NON) {
2615 coap_log(LOG_INFO, "Invalid multicast packet received RFC7252 8.1\n");
2616 return;
2617 }
2618 }
2619#ifndef WITHOUT_ASYNC
2620 async = coap_find_async(session, tokenc);
2621 if (async) {
2622 coap_tick_t now;
2623
2624 coap_ticks(&now);
2625 if (async->delay == 0 || async->delay > now) {
2626 /* re-transmit missing ACK (only if CON) */
2627 coap_log(LOG_INFO, "Retransmit async response\n");
2628 coap_send_ack(session, pdu);
2629 /* and do not pass on to the upper layers */
2630 return;
2631 }
2632 }
2633#endif /* WITHOUT_ASYNC */
2634
2635 coap_option_filter_clear(&opt_filter);
2636 opt = coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter);
2637 if (opt)
2638 is_proxy_scheme = 1;
2639
2640 opt = coap_check_option(pdu, COAP_OPTION_PROXY_URI, &opt_iter);
2641 if (opt)
2642 is_proxy_uri = 1;
2643
2644 if (is_proxy_scheme || is_proxy_uri) {
2645 coap_uri_t uri;
2646
2647 if (!context->proxy_uri_resource) {
2648 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
2649 coap_log(LOG_DEBUG, "Proxy-%s support not configured\n",
2650 is_proxy_scheme ? "Scheme" : "Uri");
2651 resp = 505;
2652 goto fail_response;
2653 }
2654 if (((size_t)pdu->code - 1 <
2655 (sizeof(resource->handler) / sizeof(resource->handler[0]))) &&
2656 !(context->proxy_uri_resource->handler[pdu->code - 1])) {
2657 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
2658 coap_log(LOG_DEBUG, "Proxy-%s code %d.%02d handler not supported\n",
2659 is_proxy_scheme ? "Scheme" : "Uri",
2660 pdu->code/100, pdu->code%100);
2661 resp = 505;
2662 goto fail_response;
2663 }
2664
2665 /* Need to check if authority is the proxy endpoint RFC7252 Section 5.7.2 */
2666 if (is_proxy_uri) {
2668 coap_opt_length(opt), &uri) < 0) {
2669 /* Need to return a 5.05 RFC7252 Section 5.7.2 */
2670 coap_log(LOG_DEBUG, "Proxy-URI not decodable\n");
2671 resp = 505;
2672 goto fail_response;
2673 }
2674 }
2675 else {
2676 memset(&uri, 0, sizeof(uri));
2677 opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
2678 if (opt) {
2679 uri.host.length = coap_opt_length(opt);
2680 uri.host.s = coap_opt_value(opt);
2681 } else
2682 uri.host.length = 0;
2683 }
2684
2685 resource = context->proxy_uri_resource;
2686 if (uri.host.length && resource->proxy_name_count &&
2687 resource->proxy_name_list) {
2688 size_t i;
2689
2690 if (resource->proxy_name_count == 1 &&
2691 resource->proxy_name_list[0]->length == 0) {
2692 /* If proxy_name_list[0] is zero length, then this is the endpoint */
2693 i = 0;
2694 } else {
2695 for (i = 0; i < resource->proxy_name_count; i++) {
2696 if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
2697 break;
2698 }
2699 }
2700 }
2701 if (i != resource->proxy_name_count) {
2702 /* This server is hosting the proxy connection endpoint */
2703 if (pdu->crit_opt) {
2704 /* Cannot handle critical option */
2705 pdu->crit_opt = 0;
2706 resp = 402;
2707 goto fail_response;
2708 }
2709 is_proxy_uri = 0;
2710 is_proxy_scheme = 0;
2711 skip_hop_limit_check = 1;
2712 }
2713 }
2714 resource = NULL;
2715 }
2716
2717 if (!skip_hop_limit_check) {
2718 opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
2719 if (opt) {
2720 size_t hop_limit;
2721 uint8_t buf[4];
2722
2723 hop_limit =
2725 if (hop_limit == 1) {
2726 /* coap_send_internal() will fill in the IP address for us */
2727 resp = 508;
2728 goto fail_response;
2729 }
2730 else if (hop_limit < 1 || hop_limit > 255) {
2731 /* Need to return a 4.00 RFC8768 Section 3 */
2732 coap_log(LOG_INFO, "Invalid Hop Limit\n");
2733 resp = 400;
2734 goto fail_response;
2735 }
2736 hop_limit--;
2738 coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
2739 buf);
2740 }
2741 }
2742
2743 uri_path = coap_get_uri_path(pdu);
2744 if (!uri_path)
2745 return;
2746
2747 if (!is_proxy_uri && !is_proxy_scheme) {
2748 /* try to find the resource from the request URI */
2749 coap_str_const_t uri_path_c = { uri_path->length, uri_path->s };
2750 resource = coap_get_resource_from_uri_path(context, &uri_path_c);
2751 }
2752
2753 if ((resource == NULL) || (resource->is_unknown == 1) ||
2754 (resource->is_proxy_uri == 1)) {
2755 /* The resource was not found or there is an unexpected match against the
2756 * resource defined for handling unknown or proxy URIs.
2757 */
2758 if (resource != NULL)
2759 /* Close down unexpected match */
2760 resource = NULL;
2761 /*
2762 * Check if the request URI happens to be the well-known URI, or if the
2763 * unknown resource handler is defined, a PUT or optionally other methods,
2764 * if configured, for the unknown handler.
2765 *
2766 * if a PROXY URI/Scheme request and proxy URI handler defined, call the
2767 * proxy URI handler
2768 *
2769 * else if well-known URI generate a default response
2770 *
2771 * else if unknown URI handler defined, call the unknown
2772 * URI handler (to allow for potential generation of resource
2773 * [RFC7272 5.8.3]) if the appropriate method is defined.
2774 *
2775 * else if DELETE return 2.02 (RFC7252: 5.8.4. DELETE)
2776 *
2777 * else return 4.04 */
2778
2779 if (is_proxy_uri || is_proxy_scheme) {
2780 resource = context->proxy_uri_resource;
2781 } else if (coap_string_equal(uri_path, &coap_default_uri_wellknown)) {
2782 /* request for .well-known/core */
2783 resource = &resource_uri_wellknown;
2784 } else if ((context->unknown_resource != NULL) &&
2785 ((size_t)pdu->code - 1 <
2786 (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
2787 (context->unknown_resource->handler[pdu->code - 1])) {
2788 /*
2789 * The unknown_resource can be used to handle undefined resources
2790 * for a PUT request and can support any other registered handler
2791 * defined for it
2792 * Example set up code:-
2793 * r = coap_resource_unknown_init(hnd_put_unknown);
2794 * coap_register_request_handler(r, COAP_REQUEST_POST,
2795 * hnd_post_unknown);
2796 * coap_register_request_handler(r, COAP_REQUEST_GET,
2797 * hnd_get_unknown);
2798 * coap_register_request_handler(r, COAP_REQUEST_DELETE,
2799 * hnd_delete_unknown);
2800 * coap_add_resource(ctx, r);
2801 *
2802 * Note: It is not possible to observe the unknown_resource, a separate
2803 * resource must be created (by PUT or POST) which has a GET
2804 * handler to be observed
2805 */
2806 resource = context->unknown_resource;
2807 } else if (pdu->code == COAP_REQUEST_CODE_DELETE) {
2808 /*
2809 * Request for DELETE on non-existant resource (RFC7252: 5.8.4. DELETE)
2810 */
2811 coap_log(LOG_DEBUG, "request for unknown resource '%*.*s',"
2812 " return 2.02\n",
2813 (int)uri_path->length,
2814 (int)uri_path->length,
2815 uri_path->s);
2816 resp = 202;
2817 goto fail_response;
2818 } else { /* request for any another resource, return 4.04 */
2819
2820 coap_log(LOG_DEBUG, "request for unknown resource '%*.*s', return 4.04\n",
2821 (int)uri_path->length, (int)uri_path->length, uri_path->s);
2822 resp = 404;
2823 goto fail_response;
2824 }
2825
2826 }
2827
2828 /* the resource was found, check if there is a registered handler */
2829 if ((size_t)pdu->code - 1 <
2830 sizeof(resource->handler) / sizeof(coap_method_handler_t))
2831 h = resource->handler[pdu->code - 1];
2832
2833 if (h) {
2834 if (context->mcast_per_resource &&
2835 (resource->flags & COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT) == 0 &&
2836 coap_is_mcast(&session->addr_info.local)) {
2837 resp = 405;
2838 goto fail_response;
2839 }
2840
2841 response = coap_pdu_init(pdu->type == COAP_MESSAGE_CON
2844 0, pdu->mid, coap_session_max_pdu_size(session));
2845 if (!response) {
2846 coap_log(LOG_ERR, "could not create response PDU\n");
2847 resp = 500;
2848 goto fail_response;
2849 }
2850#ifndef WITHOUT_ASYNC
2851 /* If handling a separate response, need CON, not ACK response */
2852 if (async && pdu->type == COAP_MESSAGE_CON)
2853 response->type = COAP_MESSAGE_CON;
2854#endif /* WITHOUT_ASYNC */
2855
2856 /* Implementation detail: coap_add_token() immediately returns 0
2857 if response == NULL */
2858 if (coap_add_token(response, pdu->token_length, pdu->token)) {
2859 int observe_action = COAP_OBSERVE_CANCEL;
2860 coap_block_b_t block;
2861 int added_block = 0;
2862
2863 query = coap_get_query(pdu);
2864 /* check for Observe option RFC7641 and RFC8132 */
2865 if (resource->observable &&
2866 (pdu->code == COAP_REQUEST_CODE_GET ||
2867 pdu->code == COAP_REQUEST_CODE_FETCH)) {
2868 observe = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
2869 if (observe) {
2870 observe_action =
2872 coap_opt_length(observe));
2873
2874 if (observe_action == COAP_OBSERVE_ESTABLISH) {
2875 coap_subscription_t *subscription;
2876
2877 if (coap_get_block_b(session, pdu, COAP_OPTION_BLOCK2, &block)) {
2878 if (block.num != 0) {
2879 response->code = COAP_RESPONSE_CODE(400);
2880 goto skip_handler;
2881 }
2882 }
2883 subscription = coap_add_observer(resource, session, &token,
2884 pdu);
2885 if (subscription) {
2886 uint8_t buf[4];
2887
2888 coap_touch_observer(context, session, &token);
2890 coap_encode_var_safe(buf, sizeof (buf),
2891 resource->observe),
2892 buf);
2893 }
2894 }
2895 else if (observe_action == COAP_OBSERVE_CANCEL) {
2896 coap_delete_observer(resource, session, &token);
2897 }
2898 else {
2899 coap_log(LOG_INFO, "observe: unexpected action %d\n", observe_action);
2900 }
2901 }
2902 }
2903
2904 /* TODO for non-proxy requests */
2905 if (resource == context->proxy_uri_resource &&
2906 COAP_PROTO_NOT_RELIABLE(session->proto) &&
2907 pdu->type == COAP_MESSAGE_CON) {
2908 /* Make the proxy response separate and fix response later */
2909 send_early_empty_ack = 1;
2910 }
2911 if (send_early_empty_ack) {
2912 coap_send_ack(session, pdu);
2913 if (pdu->mid == session->last_con_mid) {
2914 /* request has already been processed - do not process it again */
2916 "Duplicate request with mid=0x%04x - not processed\n",
2917 pdu->mid);
2918 goto drop_it_no_debug;
2919 }
2920 session->last_con_mid = pdu->mid;
2921 }
2922 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
2923 if (coap_handle_request_put_block(context, session, pdu, response,
2924 resource, uri_path, observe,
2925 query, h, &added_block)) {
2926 goto skip_handler;
2927 }
2928
2929 if (coap_handle_request_send_block(session, pdu, response, resource,
2930 query)) {
2931 goto skip_handler;
2932 }
2933 }
2934
2935 /*
2936 * Call the request handler with everything set up
2937 */
2938 coap_log(LOG_DEBUG, "call custom handler for resource '%*.*s'\n",
2939 (int)resource->uri_path->length, (int)resource->uri_path->length,
2940 resource->uri_path->s);
2941 h(resource, session, pdu, query, response);
2942
2943 /* Check if lg_xmit generated and update PDU code if so */
2944 coap_check_code_lg_xmit(session, response, resource, query, pdu->code);
2945
2946skip_handler:
2947 if (send_early_empty_ack &&
2948 response->type == COAP_MESSAGE_ACK) {
2949 /* Response is now separate - convert to CON as needed */
2950 response->type = COAP_MESSAGE_CON;
2951 /* Check for empty ACK - need to drop as already sent */
2952 if (response->code == 0) {
2953 goto drop_it_no_debug;
2954 }
2955 }
2956 respond = no_response(pdu, response, session, resource);
2957 if (respond != RESPONSE_DROP) {
2958 coap_mid_t mid = pdu->mid;
2959 if (COAP_RESPONSE_CLASS(response->code) != 2) {
2960 if (observe) {
2962 }
2963 }
2964 if (COAP_RESPONSE_CLASS(response->code) > 2) {
2965 if (observe)
2966 coap_delete_observer(resource, session, &token);
2967 if (added_block)
2969 }
2970
2971 /* If original request contained a token, and the registered
2972 * application handler made no changes to the response, then
2973 * this is an empty ACK with a token, which is a malformed
2974 * PDU */
2975 if ((response->type == COAP_MESSAGE_ACK)
2976 && (response->code == 0)) {
2977 /* Remove token from otherwise-empty acknowledgment PDU */
2978 response->token_length = 0;
2979 response->used_size = 0;
2980 }
2981
2982 if (!coap_is_mcast(&session->addr_info.local) ||
2983 (context->mcast_per_resource &&
2984 resource &&
2986 if (coap_send_internal(session, response) == COAP_INVALID_MID) {
2987 coap_log(LOG_DEBUG, "cannot send response for mid=0x%x\n", mid);
2988 }
2989 } else {
2990 /* Need to delay mcast response */
2991 coap_queue_t *node = coap_new_node();
2992 uint8_t r;
2993 coap_tick_t delay;
2994
2995 if (!node) {
2996 coap_log(LOG_DEBUG, "mcast delay: insufficient memory\n");
2997 goto clean_up;
2998 }
2999 if (!coap_pdu_encode_header(response, session->proto)) {
3000 coap_delete_node(node);
3001 goto clean_up;
3002 }
3003
3004 node->id = response->mid;
3005 node->pdu = response;
3006 coap_prng(&r, sizeof(r));
3007 delay = (COAP_DEFAULT_LEISURE_TICKS(session) * r) / 256;
3009 " %s: mid=0x%x: mcast response delayed for %u.%03u secs\n",
3010 coap_session_str(session),
3011 response->mid,
3012 (unsigned int)(delay / COAP_TICKS_PER_SECOND),
3013 (unsigned int)((delay % COAP_TICKS_PER_SECOND) *
3014 1000 / COAP_TICKS_PER_SECOND));
3015 /* Force only on retransmission */
3016 node->retransmit_cnt = session->max_retransmit -1;
3017 node->timeout = (unsigned int)(delay) /
3018 (1 << (session->max_retransmit - 1));
3019 /* Use this to delay transmission */
3020 coap_wait_ack(session->context, session, node);
3021 }
3022 } else {
3023 coap_log(LOG_DEBUG, " %s: mid=0x%x: response dropped\n",
3024 coap_session_str(session),
3025 response->mid);
3026 coap_show_pdu(LOG_DEBUG, response);
3027drop_it_no_debug:
3028 coap_delete_pdu(response);
3029 }
3030clean_up:
3031 if (query)
3032 coap_delete_string(query);
3033 } else {
3034 coap_log(LOG_WARNING, "cannot generate response\r\n");
3035 coap_delete_pdu(response);
3036 }
3037 } else {
3038 resp = 405;
3039 goto fail_response;
3040 }
3041
3042 coap_delete_string(uri_path);
3043 return;
3044
3045fail_response:
3046 response =
3048 &opt_filter);
3049 if (response)
3050 goto skip_handler;
3051 coap_delete_string(uri_path);
3052}
3053#endif /* COAP_SERVER_SUPPORT */
3054
3055#if COAP_CLIENT_SUPPORT
3056static void
3057handle_response(coap_context_t *context, coap_session_t *session,
3058 coap_pdu_t *sent, coap_pdu_t *rcvd) {
3059 /* In a lossy context, the ACK of a separate response may have
3060 * been lost, so we need to stop retransmitting requests with the
3061 * same token.
3062 */
3063 if (rcvd->type != COAP_MESSAGE_ACK)
3064 coap_cancel_all_messages(context, session, rcvd->token, rcvd->token_length);
3065
3066 /* Check for message duplication */
3067 if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
3068 if (rcvd->type == COAP_MESSAGE_CON) {
3069 if (rcvd->mid == session->last_con_mid) {
3070 /* Duplicate response */
3071 return;
3072 }
3073 session->last_con_mid = rcvd->mid;
3074 } else if (rcvd->type == COAP_MESSAGE_ACK) {
3075 if (rcvd->mid == session->last_ack_mid) {
3076 /* Duplicate response */
3077 return;
3078 }
3079 session->last_ack_mid = rcvd->mid;
3080 }
3081 }
3082
3083 if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
3084 /* See if need to send next block to server */
3085 if (coap_handle_response_send_block(session, sent, rcvd)) {
3086 /* Next block transmitted, no need to inform app */
3087 coap_send_ack(session, rcvd);
3088 return;
3089 }
3090
3091 /* Need to see if needing to request next block */
3092 if (coap_handle_response_get_block(context, session, sent, rcvd,
3093 COAP_RECURSE_OK)) {
3094 /* Next block requested, no need to inform app */
3095 coap_send_ack(session, rcvd);
3096 return;
3097 }
3098 }
3099
3100 /* Call application-specific response handler when available. */
3101 if (context->response_handler) {
3102 if (context->response_handler(session, sent, rcvd,
3103 rcvd->mid) == COAP_RESPONSE_FAIL)
3104 coap_send_rst(session, rcvd);
3105 else
3106 coap_send_ack(session, rcvd);
3107 }
3108 else {
3109 coap_send_ack(session, rcvd);
3110 }
3111}
3112#endif /* COAP_CLIENT_SUPPORT */
3113
3114#if !COAP_DISABLE_TCP
3115static void
3117 coap_pdu_t *pdu) {
3118 coap_opt_iterator_t opt_iter;
3119 coap_opt_t *option;
3120 int set_mtu = 0;
3121
3122 coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
3123
3124 if (pdu->code == COAP_SIGNALING_CODE_CSM) {
3125 while ((option = coap_option_next(&opt_iter))) {
3128 coap_opt_length(option)));
3129 set_mtu = 1;
3130 } else if (opt_iter.number == COAP_SIGNALING_OPTION_BLOCK_WISE_TRANSFER) {
3131 session->csm_block_supported = 1;
3132 }
3133 }
3134 if (set_mtu) {
3135 if (session->mtu > COAP_BERT_BASE && session->csm_block_supported)
3136 session->csm_bert_rem_support = 1;
3137 else
3138 session->csm_bert_rem_support = 0;
3139 }
3140 if (session->state == COAP_SESSION_STATE_CSM)
3141 coap_session_connected(session);
3142 } else if (pdu->code == COAP_SIGNALING_CODE_PING) {
3144 if (context->ping_handler) {
3145 context->ping_handler(session, pdu, pdu->mid);
3146 }
3147 if (pong) {
3149 coap_send_internal(session, pong);
3150 }
3151 } else if (pdu->code == COAP_SIGNALING_CODE_PONG) {
3152 session->last_pong = session->last_rx_tx;
3153 if (context->pong_handler) {
3154 context->pong_handler(session, pdu, pdu->mid);
3155 }
3156 } else if (pdu->code == COAP_SIGNALING_CODE_RELEASE
3157 || pdu->code == COAP_SIGNALING_CODE_ABORT) {
3159 }
3160}
3161#endif /* !COAP_DISABLE_TCP */
3162
3163void
3165 coap_pdu_t *pdu) {
3166 coap_queue_t *sent = NULL;
3167 coap_pdu_t *response;
3168 coap_opt_filter_t opt_filter;
3169 int is_ping_rst;
3170
3171 if (LOG_DEBUG <= coap_get_log_level()) {
3172 /* FIXME: get debug to work again **
3173 unsigned char addr[INET6_ADDRSTRLEN+8], localaddr[INET6_ADDRSTRLEN+8];
3174 if (coap_print_addr(remote, addr, INET6_ADDRSTRLEN+8) &&
3175 coap_print_addr(&packet->dst, localaddr, INET6_ADDRSTRLEN+8) )
3176 coap_log(LOG_DEBUG, "** received %d bytes from %s on interface %s:\n",
3177 (int)msg_len, addr, localaddr);
3178
3179 */
3181 }
3182
3183 memset(&opt_filter, 0, sizeof(coap_opt_filter_t));
3184
3185 switch (pdu->type) {
3186 case COAP_MESSAGE_ACK:
3187 /* find message id in sendqueue to stop retransmission */
3188 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
3189
3190 if (sent && session->con_active) {
3191 session->con_active--;
3192 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3193 /* Flush out any entries on session->delayqueue */
3194 coap_session_connected(session);
3195 }
3196 if (coap_option_check_critical(session, pdu, &opt_filter) == 0)
3197 goto cleanup;
3198
3199#if COAP_SERVER_SUPPORT
3200 /* if sent code was >= 64 the message might have been a
3201 * notification. Then, we must flag the observer to be alive
3202 * by setting obs->fail_cnt = 0. */
3203 if (sent && COAP_RESPONSE_CLASS(sent->pdu->code) == 2) {
3204 const coap_binary_t token =
3205 { sent->pdu->token_length, sent->pdu->token };
3206 coap_touch_observer(context, sent->session, &token);
3207 }
3208#endif /* COAP_SERVER_SUPPORT */
3209
3210 if (pdu->code == 0) {
3211 /* an empty ACK needs no further handling */
3212 goto cleanup;
3213 }
3214
3215 break;
3216
3217 case COAP_MESSAGE_RST:
3218 /* We have sent something the receiver disliked, so we remove
3219 * not only the message id but also the subscriptions we might
3220 * have. */
3221 is_ping_rst = 0;
3222 if (pdu->mid == session->last_ping_mid &&
3223 context->ping_timeout && session->last_ping > 0)
3224 is_ping_rst = 1;
3225
3226 if (!is_ping_rst)
3227 coap_log(LOG_ALERT, "got RST for mid=0x%x\n", pdu->mid);
3228
3229 if (session->con_active) {
3230 session->con_active--;
3231 if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3232 /* Flush out any entries on session->delayqueue */
3233 coap_session_connected(session);
3234 }
3235
3236 /* find message id in sendqueue to stop retransmission */
3237 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
3238
3239 if (sent) {
3240 coap_cancel(context, sent);
3241
3242 if (!is_ping_rst) {
3243 if(sent->pdu->type==COAP_MESSAGE_CON && context->nack_handler)
3244 context->nack_handler(sent->session, sent->pdu,
3245 COAP_NACK_RST, sent->id);
3246 }
3247 else {
3248 if (context->pong_handler) {
3249 context->pong_handler(session, pdu, pdu->mid);
3250 }
3251 session->last_pong = session->last_rx_tx;
3253 }
3254 }
3255#if COAP_SERVER_SUPPORT
3256 else {
3257 /* Need to check is there is a subscription active and delete it */
3258 RESOURCES_ITER(context->resources, r) {
3259 coap_subscription_t *obs, *tmp;
3260 LL_FOREACH_SAFE(r->subscribers, obs, tmp) {
3261 if (obs->pdu->mid == pdu->mid && obs->session == session) {
3262 coap_binary_t token = { 0, NULL };
3263 COAP_SET_STR(&token, obs->pdu->token_length, obs->pdu->token);
3264 coap_delete_observer(r, session, &token);
3265 goto cleanup;
3266 }
3267 }
3268 }
3269 }
3270#endif /* COAP_SERVER_SUPPORT */
3271 goto cleanup;
3272
3273 case COAP_MESSAGE_NON:
3274 /* find transaction in sendqueue in case large response */
3275 coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
3276 /* check for unknown critical options */
3277 if (coap_option_check_critical(session, pdu, &opt_filter) == 0) {
3278 coap_send_rst(session, pdu);
3279 goto cleanup;
3280 }
3281 break;
3282
3283 case COAP_MESSAGE_CON: /* check for unknown critical options */
3284 if (coap_option_check_critical(session, pdu, &opt_filter) == 0) {
3285
3286 if (COAP_PDU_IS_REQUEST(pdu)) {
3287 response =
3288 coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
3289
3290 if (!response) {
3292 "coap_dispatch: cannot create error response\n");
3293 } else {
3294 if (coap_send_internal(session, response) == COAP_INVALID_MID)
3295 coap_log(LOG_WARNING, "coap_dispatch: error sending response\n");
3296 }
3297 }
3298 else {
3299 coap_send_rst(session, pdu);
3300 }
3301
3302 goto cleanup;
3303 }
3304 default: break;
3305 }
3306
3307 /* Pass message to upper layer if a specific handler was
3308 * registered for a request that should be handled locally. */
3309#if !COAP_DISABLE_TCP
3310 if (COAP_PDU_IS_SIGNALING(pdu))
3311 handle_signaling(context, session, pdu);
3312 else
3313#endif /* !COAP_DISABLE_TCP */
3314#if COAP_SERVER_SUPPORT
3315 if (COAP_PDU_IS_REQUEST(pdu))
3316 handle_request(context, session, pdu);
3317 else
3318#endif /* COAP_SERVER_SUPPORT */
3319#if COAP_CLIENT_SUPPORT
3320 if (COAP_PDU_IS_RESPONSE(pdu))
3321 handle_response(context, session, sent ? sent->pdu : NULL, pdu);
3322 else
3323#endif /* COAP_CLIENT_SUPPORT */
3324 {
3325 if (COAP_PDU_IS_EMPTY(pdu)) {
3326 if (context->ping_handler) {
3327 context->ping_handler(session, pdu, pdu->mid);
3328 }
3329 }
3330 coap_log(LOG_DEBUG, "dropped message with invalid code (%d.%02d)\n",
3332 pdu->code & 0x1f);
3333
3334 if (!coap_is_mcast(&session->addr_info.local)) {
3335 if (COAP_PDU_IS_EMPTY(pdu)) {
3336 if (session->proto != COAP_PROTO_TCP && session->proto != COAP_PROTO_TLS) {
3337 coap_tick_t now;
3338 coap_ticks(&now);
3339 if (session->last_tx_rst + COAP_TICKS_PER_SECOND/4 < now) {
3341 session->last_tx_rst = now;
3342 }
3343 }
3344 }
3345 else {
3347 }
3348 }
3349 }
3350
3351cleanup:
3352 coap_delete_node(sent);
3353}
3354
3355int
3357 coap_log(LOG_DEBUG, "***EVENT: 0x%04x\n", event);
3358
3359 if (context->handle_event) {
3360 return context->handle_event(session, event);
3361 } else {
3362 return 0;
3363 }
3364}
3365
3366int
3368 coap_session_t *s, *rtmp;
3369 if (!context)
3370 return 1;
3371 if (context->sendqueue)
3372 return 0;
3373#if COAP_SERVER_SUPPORT
3374 coap_endpoint_t *ep;
3375
3376 LL_FOREACH(context->endpoint, ep) {
3377 SESSIONS_ITER(ep->sessions, s, rtmp) {
3378 if (s->delayqueue)
3379 return 0;
3380 if (s->lg_xmit)
3381 return 0;
3382 }
3383 }
3384#endif /* COAP_SERVER_SUPPORT */
3385#if COAP_CLIENT_SUPPORT
3386 SESSIONS_ITER(context->sessions, s, rtmp) {
3387 if (s->delayqueue)
3388 return 0;
3389 if (s->lg_xmit)
3390 return 0;
3391 }
3392#endif /* COAP_CLIENT_SUPPORT */
3393 return 1;
3394}
3395#ifndef WITHOUT_ASYNC
3398 coap_tick_t next_due = 0;
3399 coap_async_t *async, *tmp;
3400
3401 LL_FOREACH_SAFE(context->async_state, async, tmp) {
3402 if (async->delay != 0 && async->delay <= now) {
3403 /* Send off the request to the application */
3404 handle_request(context, async->session, async->pdu);
3405
3406 /* Remove this async entry as it has now fired */
3407 coap_free_async(async->session, async);
3408 }
3409 else {
3410 if (next_due == 0 || next_due > async->delay - now)
3411 next_due = async->delay - now;
3412 }
3413 }
3414 return next_due;
3415}
3416#endif /* WITHOUT_ASYNC */
3417
3418static int coap_started = 0;
3419
3420void coap_startup(void) {
3421 coap_tick_t now;
3422 uint64_t us;
3423
3424 if (coap_started)
3425 return;
3426 coap_started = 1;
3427#if defined(HAVE_WINSOCK2_H)
3428 WORD wVersionRequested = MAKEWORD(2, 2);
3429 WSADATA wsaData;
3430 WSAStartup(wVersionRequested, &wsaData);
3431#endif
3433 coap_ticks(&now);
3434 us = coap_ticks_to_rt_us(now);
3435 /* Be accurate to the nearest (approx) us */
3436 coap_prng_init((unsigned int)us);
3439#if COAP_SERVER_SUPPORT
3440 static coap_str_const_t well_known = { sizeof(".well-known/core")-1,
3441 (const uint8_t *)".well-known/core" };
3442 memset(&resource_uri_wellknown, 0, sizeof(resource_uri_wellknown));
3443 resource_uri_wellknown.handler[COAP_REQUEST_GET-1] = hnd_get_wellknown;
3444 resource_uri_wellknown.flags = COAP_RESOURCE_FLAGS_HAS_MCAST_SUPPORT;
3445 resource_uri_wellknown.uri_path = &well_known;
3446#endif /* COAP_SERVER_SUPPORT */
3447}
3448
3449void coap_cleanup(void) {
3450#if defined(HAVE_WINSOCK2_H)
3451 WSACleanup();
3452#endif
3454}
3455
3456void
3458 coap_response_handler_t handler) {
3459#if COAP_CLIENT_SUPPORT
3460 context->response_handler = handler;
3461#else /* ! COAP_CLIENT_SUPPORT */
3462 (void)context;
3463 (void)handler;
3464#endif /* COAP_CLIENT_SUPPORT */
3465}
3466
3467void
3469 coap_nack_handler_t handler) {
3470 context->nack_handler = handler;
3471}
3472
3473void
3475 coap_ping_handler_t handler) {
3476 context->ping_handler = handler;
3477}
3478
3479void
3481 coap_pong_handler_t handler) {
3482 context->pong_handler = handler;
3483}
3484
3485void
3488}
3489
3490#if ! defined WITH_CONTIKI && ! defined WITH_LWIP && ! defined RIOT_VERSION
3491#if COAP_SERVER_SUPPORT
3492int
3493coap_join_mcast_group_intf(coap_context_t *ctx, const char *group_name,
3494 const char *ifname) {
3495 struct ip_mreq mreq4;
3496 struct ipv6_mreq mreq6;
3497 struct addrinfo *resmulti = NULL, hints, *ainfo;
3498 int result = -1;
3499 coap_endpoint_t *endpoint;
3500 int mgroup_setup = 0;
3501
3502 /* Need to have at least one endpoint! */
3503 assert(ctx->endpoint);
3504 if (!ctx->endpoint)
3505 return -1;
3506
3507 /* Default is let the kernel choose */
3508 mreq6.ipv6mr_interface = 0;
3509 mreq4.imr_interface.s_addr = INADDR_ANY;
3510
3511 memset(&hints, 0, sizeof(hints));
3512 hints.ai_socktype = SOCK_DGRAM;
3513
3514 /* resolve the multicast group address */
3515 result = getaddrinfo(group_name, NULL, &hints, &resmulti);
3516
3517 if (result != 0) {
3519 "coap_join_mcast_group_intf: %s: "
3520 "Cannot resolve multicast address: %s\n",
3521 group_name, gai_strerror(result));
3522 goto finish;
3523 }
3524
3525/* Need to do a windows equivalent at some point */
3526#ifndef _WIN32
3527 if (ifname) {
3528 /* interface specified - check if we have correct IPv4/IPv6 information */
3529 int done_ip4 = 0;
3530 int done_ip6 = 0;
3531#if defined(ESPIDF_VERSION)
3532 struct netif *netif;
3533#else /* !ESPIDF_VERSION */
3534 int ip4fd;
3535 struct ifreq ifr;
3536#endif /* !ESPIDF_VERSION */
3537
3538 /* See which mcast address family types are being asked for */
3539 for (ainfo = resmulti; ainfo != NULL && !(done_ip4 == 1 && done_ip6 == 1);
3540 ainfo = ainfo->ai_next) {
3541 switch (ainfo->ai_family) {
3542 case AF_INET6:
3543 if (done_ip6)
3544 break;
3545 done_ip6 = 1;
3546#if defined(ESPIDF_VERSION)
3547 netif = netif_find(ifname);
3548 if (netif)
3549 mreq6.ipv6mr_interface = netif_get_index(netif);
3550 else
3552 "coap_join_mcast_group_intf: %s: "
3553 "Cannot get IPv4 address: %s\n",
3554 ifname, coap_socket_strerror());
3555#else /* !ESPIDF_VERSION */
3556 memset (&ifr, 0, sizeof(ifr));
3557 strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
3558 ifr.ifr_name[IFNAMSIZ - 1] = '\000';
3559
3560#ifdef HAVE_IF_NAMETOINDEX
3561 mreq6.ipv6mr_interface = if_nametoindex(ifr.ifr_name);
3562 if (mreq6.ipv6mr_interface == 0) {
3563 coap_log(LOG_WARNING, "coap_join_mcast_group_intf: "
3564 "cannot get interface index for '%s'\n",
3565 ifname);
3566 }
3567#else /* !HAVE_IF_NAMETOINDEX */
3568 result = ioctl(ctx->endpoint->sock.fd, SIOCGIFINDEX, &ifr);
3569 if (result != 0) {
3570 coap_log(LOG_WARNING, "coap_join_mcast_group_intf: "
3571 "cannot get interface index for '%s': %s\n",
3572 ifname, coap_socket_strerror());
3573 }
3574 else {
3575 /* Capture the IPv6 if_index for later */
3576 mreq6.ipv6mr_interface = ifr.ifr_ifindex;
3577 }
3578#endif /* !HAVE_IF_NAMETOINDEX */
3579#endif /* !ESPIDF_VERSION */
3580 break;
3581 case AF_INET:
3582 if (done_ip4)
3583 break;
3584 done_ip4 = 1;
3585#if defined(ESPIDF_VERSION)
3586 netif = netif_find(ifname);
3587 if (netif)
3588 mreq4.imr_interface.s_addr = netif_ip4_addr(netif)->addr;
3589 else
3591 "coap_join_mcast_group_intf: %s: "
3592 "Cannot get IPv4 address: %s\n",
3593 ifname, coap_socket_strerror());
3594#else /* !ESPIDF_VERSION */
3595 /*
3596 * Need an AF_INET socket to do this unfortunately to stop
3597 * "Invalid argument" error if AF_INET6 socket is used for SIOCGIFADDR
3598 */
3599 ip4fd = socket(AF_INET, SOCK_DGRAM, 0);
3600 if (ip4fd == -1) {
3602 "coap_join_mcast_group_intf: %s: socket: %s\n",
3603 ifname, coap_socket_strerror());
3604 continue;
3605 }
3606 memset (&ifr, 0, sizeof(ifr));
3607 strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
3608 ifr.ifr_name[IFNAMSIZ - 1] = '\000';
3609 result = ioctl(ip4fd, SIOCGIFADDR, &ifr);
3610 if (result != 0) {
3612 "coap_join_mcast_group_intf: %s: "
3613 "Cannot get IPv4 address: %s\n",
3614 ifname, coap_socket_strerror());
3615 }
3616 else {
3617 /* Capture the IPv4 address for later */
3618 mreq4.imr_interface = ((struct sockaddr_in*)&ifr.ifr_addr)->sin_addr;
3619 }
3620 close(ip4fd);
3621#endif /* !ESPIDF_VERSION */
3622 break;
3623 default:
3624 break;
3625 }
3626 }
3627 }
3628#endif /* ! _WIN32 */
3629
3630 /* Add in mcast address(es) to appropriate interface */
3631 for (ainfo = resmulti; ainfo != NULL; ainfo = ainfo->ai_next) {
3632 LL_FOREACH(ctx->endpoint, endpoint) {
3633 /* Only UDP currently supported */
3634 if (endpoint->proto == COAP_PROTO_UDP) {
3635 coap_address_t gaddr;
3636
3637 coap_address_init(&gaddr);
3638 if (ainfo->ai_family == AF_INET6) {
3639 if (!ifname) {
3640 if(endpoint->bind_addr.addr.sa.sa_family == AF_INET6) {
3641 /*
3642 * Do it on the ifindex that the server is listening on
3643 * (sin6_scope_id could still be 0)
3644 */
3645 mreq6.ipv6mr_interface =
3646 endpoint->bind_addr.addr.sin6.sin6_scope_id;
3647 }
3648 else {
3649 mreq6.ipv6mr_interface = 0;
3650 }
3651 }
3652 gaddr.addr.sin6.sin6_family = AF_INET6;
3653 gaddr.addr.sin6.sin6_port = endpoint->bind_addr.addr.sin6.sin6_port;
3654 gaddr.addr.sin6.sin6_addr = mreq6.ipv6mr_multiaddr =
3655 ((struct sockaddr_in6 *)ainfo->ai_addr)->sin6_addr;
3656 result = setsockopt(endpoint->sock.fd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
3657 (char *)&mreq6, sizeof(mreq6));
3658 }
3659 else if (ainfo->ai_family == AF_INET) {
3660 if (!ifname) {
3661 if(endpoint->bind_addr.addr.sa.sa_family == AF_INET) {
3662 /*
3663 * Do it on the interface that the server is listening on
3664 * (sin_addr could still be INADDR_ANY)
3665 */
3666 mreq4.imr_interface = endpoint->bind_addr.addr.sin.sin_addr;
3667 }
3668 else {
3669 mreq4.imr_interface.s_addr = INADDR_ANY;
3670 }
3671 }
3672 gaddr.addr.sin.sin_family = AF_INET;
3673 gaddr.addr.sin.sin_port = endpoint->bind_addr.addr.sin.sin_port;
3674 gaddr.addr.sin.sin_addr.s_addr = mreq4.imr_multiaddr.s_addr =
3675 ((struct sockaddr_in *)ainfo->ai_addr)->sin_addr.s_addr;
3676 result = setsockopt(endpoint->sock.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3677 (char *)&mreq4, sizeof(mreq4));
3678 }
3679 else {
3680 continue;
3681 }
3682
3683 if (result == COAP_SOCKET_ERROR) {
3685 "coap_join_mcast_group_intf: %s: setsockopt: %s\n",
3686 group_name, coap_socket_strerror());
3687 }
3688 else {
3689 char addr_str[INET6_ADDRSTRLEN + 8 + 1];
3690
3691 addr_str[sizeof(addr_str)-1] = '\000';
3692 if (coap_print_addr(&gaddr, (uint8_t*)addr_str,
3693 sizeof(addr_str) - 1)) {
3694 if (ifname)
3695 coap_log(LOG_DEBUG, "added mcast group %s i/f %s\n", addr_str,
3696 ifname);
3697 else
3698 coap_log(LOG_DEBUG, "added mcast group %s\n", addr_str);
3699 }
3700 mgroup_setup = 1;
3701 }
3702 }
3703 }
3704 }
3705 if (!mgroup_setup) {
3706 result = -1;
3707 }
3708
3709 finish:
3710 freeaddrinfo(resmulti);
3711
3712 return result;
3713}
3714
3715void
3717 context->mcast_per_resource = 1;
3718}
3719
3720#endif /* ! COAP_SERVER_SUPPORT */
3721
3722#if COAP_CLIENT_SUPPORT
3723int
3724coap_mcast_set_hops(coap_session_t *session, size_t hops) {
3725 if (session && coap_is_mcast(&session->addr_info.remote)) {
3726 switch (session->addr_info.remote.addr.sa.sa_family) {
3727 case AF_INET:
3728 if (setsockopt(session->sock.fd, IPPROTO_IP, IP_MULTICAST_TTL,
3729 (const char *)&hops, sizeof(hops)) < 0) {
3730 coap_log(LOG_INFO, "coap_mcast_set_hops: %zu: setsockopt: %s\n",
3731 hops, coap_socket_strerror());
3732 return 0;
3733 }
3734 return 1;
3735 case AF_INET6:
3736 if (setsockopt(session->sock.fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
3737 (const char *)&hops, sizeof(hops)) < 0) {
3738 coap_log(LOG_INFO, "coap_mcast_set_hops: %zu: setsockopt: %s\n",
3739 hops, coap_socket_strerror());
3740 return 0;
3741 }
3742 return 1;
3743 default:
3744 break;
3745 }
3746 }
3747 return 0;
3748}
3749#endif /* COAP_CLIENT_SUPPORT */
3750
3751#else /* defined WITH_CONTIKI || defined WITH_LWIP */
3752int
3754 const char *group_name COAP_UNUSED,
3755 const char *ifname COAP_UNUSED) {
3756 return -1;
3757}
3758
3759int
3761 size_t hops COAP_UNUSED) {
3762 return 0;
3763}
3764
3765void
3767}
3768#endif /* defined WITH_CONTIKI || defined WITH_LWIP */
3769
3770#ifdef WITH_CONTIKI
3771
3772/*---------------------------------------------------------------------------*/
3773/* CoAP message retransmission */
3774/*---------------------------------------------------------------------------*/
3775PROCESS_THREAD(coap_retransmit_process, ev, data) {
3776 coap_tick_t now;
3777 coap_queue_t *nextpdu;
3778
3779 PROCESS_BEGIN();
3780
3781 coap_log(LOG_DEBUG, "Started retransmit process\n");
3782
3783 while (1) {
3784 PROCESS_YIELD();
3785 if (ev == PROCESS_EVENT_TIMER) {
3786 if (etimer_expired(&the_coap_context.retransmit_timer)) {
3787
3788 nextpdu = coap_peek_next(&the_coap_context);
3789
3790 coap_ticks(&now);
3791 while (nextpdu && nextpdu->t <= now) {
3792 coap_retransmit(&the_coap_context, coap_pop_next(&the_coap_context));
3793 nextpdu = coap_peek_next(&the_coap_context);
3794 }
3795
3796 /* need to set timer to some value even if no nextpdu is available */
3797 etimer_set(&the_coap_context.retransmit_timer,
3798 nextpdu ? nextpdu->t - now : 0xFFFF);
3799 }
3800 if (etimer_expired(&the_coap_context.notify_timer)) {
3801 coap_check_notify(&the_coap_context);
3802 etimer_reset(&the_coap_context.notify_timer);
3803 }
3804 }
3805 }
3806
3807 PROCESS_END();
3808}
3809/*---------------------------------------------------------------------------*/
3810
3811#endif /* WITH_CONTIKI */
3812
3813#ifdef WITH_LWIP
3814/* FIXME: retransmits that are not required any more due to incoming packages
3815 * do *not* get cleared at the moment, the wakeup when the transmission is due
3816 * is silently accepted. this is mainly due to the fact that the required
3817 * checks are similar in two places in the code (when receiving ACK and RST)
3818 * and that they cause more than one patch chunk, as it must be first checked
3819 * whether the sendqueue item to be dropped is the next one pending, and later
3820 * the restart function has to be called. nothing insurmountable, but it can
3821 * also be implemented when things have stabilized, and the performance
3822 * penality is minimal
3823 *
3824 * also, this completely ignores COAP_RESOURCE_CHECK_TIME.
3825 * */
3826
3827static void coap_retransmittimer_execute(void *arg) {
3828 coap_context_t *ctx = (coap_context_t*)arg;
3829 coap_tick_t now;
3830 coap_tick_t elapsed;
3831 coap_queue_t *nextinqueue;
3832
3833 ctx->timer_configured = 0;
3834
3835 coap_ticks(&now);
3836
3837 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 */
3838
3839 nextinqueue = coap_peek_next(ctx);
3840 while (nextinqueue != NULL) {
3841 if (nextinqueue->t > elapsed) {
3842 nextinqueue->t -= elapsed;
3843 break;
3844 } else {
3845 elapsed -= nextinqueue->t;
3846 coap_retransmit(ctx, coap_pop_next(ctx));
3847 nextinqueue = coap_peek_next(ctx);
3848 }
3849 }
3850
3851 ctx->sendqueue_basetime = now;
3852
3853 coap_retransmittimer_restart(ctx);
3854}
3855
3856static void coap_retransmittimer_restart(coap_context_t *ctx) {
3857 coap_tick_t now, elapsed, delay;
3858
3859 if (ctx->timer_configured) {
3860 printf("clearing\n");
3861 sys_untimeout(coap_retransmittimer_execute, (void*)ctx);
3862 ctx->timer_configured = 0;
3863 }
3864 if (ctx->sendqueue != NULL) {
3865 coap_ticks(&now);
3866 elapsed = now - ctx->sendqueue_basetime;
3867 if (ctx->sendqueue->t >= elapsed) {
3868 delay = ctx->sendqueue->t - elapsed;
3869 } else {
3870 /* a strange situation, but not completely impossible.
3871 *
3872 * this happens, for example, right after
3873 * coap_retransmittimer_execute, when a retransmission
3874 * was *just not yet* due, and the clock ticked before
3875 * our coap_ticks was called.
3876 *
3877 * not trying to retransmit anything now, as it might
3878 * cause uncontrollable recursion; let's just try again
3879 * with the next main loop run.
3880 * */
3881 delay = 0;
3882 }
3883
3884 printf("scheduling for %d ticks\n", delay);
3885 sys_timeout(delay, coap_retransmittimer_execute, (void*)ctx);
3886 ctx->timer_configured = 1;
3887 }
3888}
3889#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:1594
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:1874
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:1930
int coap_io_process(coap_context_t *ctx, uint32_t timeout_ms)
The main I/O processing function.
Definition: coap_io.c:1350
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:2344
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:3397
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:2072
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:3164
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:1447
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:2153
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:2116
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:2035
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:3367
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:3457
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:2194
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:3356
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:3474
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:3486
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:3480
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:3468
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
Definition: coap_event.h:48
@ COAP_EVENT_DTLS_CONNECTED
Definition: coap_event.h:39
@ COAP_EVENT_TCP_CONNECTED
TCP events for COAP_PROTO_TCP and COAP_PROTO_TLS.
Definition: coap_event.h:46
@ COAP_EVENT_DTLS_ERROR
Definition: coap_event.h:41
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:466
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:322
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:288
#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:873
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:818
#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:1027
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:554
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:1177
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:841
int coap_pdu_resize(coap_pdu_t *pdu, size_t new_size)
Dynamically grows the size of pdu to new_size.
Definition: pdu.c:213
#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:604
#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:777
#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:148
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:264
#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:1152
#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:93
#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:671
coap_bin_const_t coap_pdu_get_token(const coap_pdu_t *pdu)
Gets the token associated with pdu.
Definition: pdu.c:1275
@ 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:432
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:473
#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:345
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:395
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:528
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:418
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:381
size_t coap_session_max_pdu_size(const coap_session_t *session)
Get maximum acceptable PDU size.
Definition: coap_session.c:355
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:126
void coap_session_disconnected(coap_session_t *session, coap_nack_reason_t reason)
Notify session that it has failed.
Definition: coap_session.c:587
coap_session_t * coap_session_reference(coap_session_t *session)
Increment reference counter on a session.
Definition: coap_session.c:120
@ 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:3449
#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:2416
static int coap_started
Definition: net.c:3418
static int coap_handle_dgram_for_proto(coap_context_t *ctx, coap_session_t *session, coap_packet_t *packet)
Definition: net.c:1545
static void coap_write_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now)
Definition: net.c:1606
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:3116
#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:1656
void coap_startup(void)
Definition: net.c:3420
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 (and observe 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 token, if any, follows the fixed size header, then options until payload mark...
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
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
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
Subscriber information.
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