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