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