libcoap  4.3.0rc2
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 
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  coap_pdu_t *request,
902  unsigned char 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 
918 coap_send_message_type(coap_session_t *session, coap_pdu_t *request, unsigned char type) {
919  coap_pdu_t *response;
920  coap_mid_t result = COAP_INVALID_MID;
921 
922  if (request) {
923  response = coap_pdu_init(type, 0, request->mid, 0);
924  if (response)
925  result = coap_send(session, response);
926  }
927  return result;
928 }
929 
943 unsigned int
944 coap_calc_timeout(coap_session_t *session, unsigned char r) {
945  unsigned int result;
946 
947  /* The integer 1.0 as a Qx.FRAC_BITS */
948 #define FP1 Q(FRAC_BITS, ((coap_fixed_point_t){1,0}))
949 
950  /* rounds val up and right shifts by frac positions */
951 #define SHR_FP(val,frac) (((val) + (1 << ((frac) - 1))) >> (frac))
952 
953  /* Inner term: multiply ACK_RANDOM_FACTOR by Q0.MAX_BITS[r] and
954  * make the result a rounded Qx.FRAC_BITS */
955  result = SHR_FP((ACK_RANDOM_FACTOR - FP1) * r, MAX_BITS);
956 
957  /* Add 1 to the inner term and multiply with ACK_TIMEOUT, then
958  * make the result a rounded Qx.FRAC_BITS */
959  result = SHR_FP(((result + FP1) * ACK_TIMEOUT), FRAC_BITS);
960 
961  /* Multiply with COAP_TICKS_PER_SECOND to yield system ticks
962  * (yields a Qx.FRAC_BITS) and shift to get an integer */
963  return SHR_FP((COAP_TICKS_PER_SECOND * result), FRAC_BITS);
964 
965 #undef FP1
966 #undef SHR_FP
967 }
968 
971  coap_queue_t *node) {
972  coap_tick_t now;
973 
974  node->session = coap_session_reference(session);
975 
976  /* Set timer for pdu retransmission. If this is the first element in
977  * the retransmission queue, the base time is set to the current
978  * time and the retransmission time is node->timeout. If there is
979  * already an entry in the sendqueue, we must check if this node is
980  * to be retransmitted earlier. Therefore, node->timeout is first
981  * normalized to the base time and then inserted into the queue with
982  * an adjusted relative time.
983  */
984  coap_ticks(&now);
985  if (context->sendqueue == NULL) {
986  node->t = node->timeout << node->retransmit_cnt;
987  context->sendqueue_basetime = now;
988  } else {
989  /* make node->t relative to context->sendqueue_basetime */
990  node->t = (now - context->sendqueue_basetime) +
991  (node->timeout << node->retransmit_cnt);
992  }
993 
994  coap_insert_node(&context->sendqueue, node);
995 
996 #ifdef WITH_LWIP
997  if (node == context->sendqueue) /* don't bother with timer stuff if there are earlier retransmits */
998  coap_retransmittimer_restart(context);
999 #endif
1000 
1001 #ifdef WITH_CONTIKI
1002  { /* (re-)initialize retransmission timer */
1003  coap_queue_t *nextpdu;
1004 
1005  nextpdu = coap_peek_next(context);
1006  assert(nextpdu); /* we have just inserted a node */
1007 
1008  /* must set timer within the context of the retransmit process */
1009  PROCESS_CONTEXT_BEGIN(&coap_retransmit_process);
1010  etimer_set(&context->retransmit_timer, nextpdu->t);
1011  PROCESS_CONTEXT_END(&coap_retransmit_process);
1012  }
1013 #endif /* WITH_CONTIKI */
1014 
1015  coap_log(LOG_DEBUG, "** %s: mid=0x%x: added to retransmit queue (%ums)\n",
1016  coap_session_str(node->session), node->id,
1017  (unsigned)(node->t * 1000 / COAP_TICKS_PER_SECOND));
1018 
1019 #ifdef COAP_EPOLL_SUPPORT
1020  if (context->eptimerfd != -1) {
1021  coap_ticks(&now);
1022  if (context->next_timeout == 0 ||
1023  context->next_timeout > now + (node->t * 1000 / COAP_TICKS_PER_SECOND)) {
1024  struct itimerspec new_value;
1025  int ret;
1026 
1027  context->next_timeout = now + (node->t * 1000 / COAP_TICKS_PER_SECOND);
1028  memset(&new_value, 0, sizeof(new_value));
1029  coap_tick_t rem_timeout = (node->t * 1000 / COAP_TICKS_PER_SECOND);
1030  /* Need to trigger an event on context->epfd in the future */
1031  new_value.it_value.tv_sec = rem_timeout / 1000;
1032  new_value.it_value.tv_nsec = (rem_timeout % 1000) * 1000000;
1033  ret = timerfd_settime(context->eptimerfd, 0, &new_value, NULL);
1034  if (ret == -1) {
1035  coap_log(LOG_ERR,
1036  "%s: timerfd_settime failed: %s (%d)\n",
1037  "coap_wait_ack",
1038  coap_socket_strerror(), errno);
1039  }
1040  }
1041  }
1042 #endif /* COAP_EPOLL_SUPPORT */
1043 
1044  return node->id;
1045 }
1046 
1048 token_match(const uint8_t *a, size_t alen,
1049  const uint8_t *b, size_t blen) {
1050  return alen == blen && (alen == 0 || memcmp(a, b, alen) == 0);
1051 }
1052 
1053 coap_mid_t
1056  coap_lg_crcv_t *lg_crcv = NULL;
1057  coap_opt_iterator_t opt_iter;
1058  int observe_action = -1;
1059  int have_block1 = 0;
1060  coap_opt_t *opt;
1061 
1062  assert(pdu);
1063 
1064  if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
1066  "** %s: coap_send_large: COAP_BLOCK_USE_LIBCOAP not enabled\n",
1067  coap_session_str(session));
1068  return coap_send(session, pdu);
1069  }
1070 
1071  if (COAP_PDU_IS_REQUEST(pdu)) {
1072  coap_block_t block;
1073 
1074  opt = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
1075 
1076  if (opt) {
1077  observe_action = coap_decode_var_bytes(coap_opt_value(opt),
1078  coap_opt_length(opt));
1079  }
1080 
1081  if (coap_get_block(pdu, COAP_OPTION_BLOCK1, &block) && block.m == 1)
1082  have_block1 = 1;
1083  }
1084 
1085  /*
1086  * If type is CON and protocol is not reliable, there is no need to set up
1087  * lg_crcv here as it can be built up based on sent PDU if there is a
1088  * Block2 in the response. However, still need it for observe and block1.
1089  */
1090  if (observe_action != -1 || have_block1 ||
1091  ((pdu->type == COAP_MESSAGE_NON || COAP_PROTO_RELIABLE(session->proto)) &&
1093  /* See if this token is already in use for large body responses */
1094  LL_FOREACH(session->lg_crcv, lg_crcv) {
1095  if (token_match(pdu->token, pdu->token_length,
1096  lg_crcv->app_token->s, lg_crcv->app_token->length)) {
1097 
1098  if (observe_action == COAP_OBSERVE_CANCEL) {
1099  /* Need to update token to server's version */
1100  coap_update_token(pdu, lg_crcv->base_token_length,
1101  lg_crcv->base_token);
1102  memcpy(lg_crcv->token, lg_crcv->base_token,
1103  lg_crcv->base_token_length);
1104  lg_crcv->token_length = lg_crcv->base_token_length;
1105  lg_crcv->initial = 1;
1106  lg_crcv->observe_set = 0;
1107  /* de-reference lg_crcv as potentially linking in later */
1108  LL_DELETE(session->lg_crcv, lg_crcv);
1109  goto send_it;
1110  }
1111 
1112  /* Need to terminate and clean up previous response setup */
1113  LL_DELETE(session->lg_crcv, lg_crcv);
1114  coap_block_delete_lg_crcv(session, lg_crcv);
1115  break;
1116  }
1117  }
1118 
1119  lg_crcv = coap_block_new_lg_crcv(session, pdu);
1120  if (lg_crcv == NULL)
1121  return COAP_INVALID_MID;
1122  if (have_block1 && session->lg_xmit) {
1123  coap_lg_xmit_t *lg_xmit;
1124 
1125  LL_FOREACH(session->lg_xmit, lg_xmit) {
1126  if (COAP_PDU_IS_REQUEST(&lg_xmit->pdu) &&
1127  lg_xmit->b.b1.app_token &&
1128  token_match(pdu->token, pdu->token_length,
1129  lg_xmit->b.b1.app_token->s,
1130  lg_xmit->b.b1.app_token->length)) {
1131  /* Need to update the token as set up in the session->lg_xmit */
1132  coap_update_token(pdu, session->lg_xmit->b.b1.token_length,
1133  session->lg_xmit->b.b1.token);
1134  break;
1135  }
1136  }
1137  }
1138  }
1139 
1140 send_it:
1141  mid = coap_send(session, pdu);
1142  if (lg_crcv) {
1143  if (mid != COAP_INVALID_MID) {
1144  LL_PREPEND(session->lg_crcv, lg_crcv);
1145  }
1146  else {
1147  coap_block_delete_lg_crcv(session, lg_crcv);
1148  }
1149  }
1150  return mid;
1151 }
1152 
1153 coap_mid_t
1155  uint8_t r;
1156  ssize_t bytes_written;
1157  coap_opt_iterator_t opt_iter;
1158 
1159  if (pdu->code == COAP_RESPONSE_CODE(508)) {
1160  /*
1161  * Need to prepend our IP identifier to the data as per
1162  * https://www.rfc-editor.org/rfc/rfc8768.html#section-4
1163  */
1164  char addr_str[INET6_ADDRSTRLEN + 8 + 1];
1165  coap_opt_t *opt;
1166  size_t hop_limit;
1167 
1168  addr_str[sizeof(addr_str)-1] = '\000';
1169  if (coap_print_addr(&session->addr_info.local, (uint8_t*)addr_str,
1170  sizeof(addr_str) - 1)) {
1171  char *cp;
1172  size_t len;
1173 
1174  if (addr_str[0] == '[') {
1175  cp = strchr(addr_str, ']');
1176  if (cp) *cp = '\000';
1177  if (memcmp(&addr_str[1], "::ffff:", 7) == 0) {
1178  /* IPv4 embedded into IPv6 */
1179  cp = &addr_str[8];
1180  }
1181  else {
1182  cp = &addr_str[1];
1183  }
1184  }
1185  else {
1186  cp = strchr(addr_str, ':');
1187  if (cp) *cp = '\000';
1188  cp = addr_str;
1189  }
1190  len = strlen(cp);
1191 
1192  /* See if Hop Limit option is being used in return path */
1193  opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
1194  if (opt) {
1195  uint8_t buf[4];
1196 
1197  hop_limit =
1199  if (hop_limit == 1) {
1200  coap_log(LOG_WARNING, "Proxy loop detected '%s'\n",
1201  (char*)pdu->data);
1202  coap_delete_pdu(pdu);
1204  }
1205  else if (hop_limit < 1 || hop_limit > 255) {
1206  /* Something is bad - need to drop this pdu (TODO or delete option) */
1207  coap_log(LOG_WARNING, "Proxy return has bad hop limit count '%zu'\n",
1208  hop_limit);
1209  coap_delete_pdu(pdu);
1211  }
1212  hop_limit--;
1214  coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
1215  buf);
1216  }
1217 
1218  /* Need to check that we are not seeing this proxy in the return loop */
1219  if (pdu->data && opt == NULL) {
1220  if (pdu->used_size + 1 <= pdu->max_size) {
1221  char *a_match;
1222  size_t data_len = pdu->used_size - (pdu->data - pdu->token);
1223  pdu->data[data_len] = '\000';
1224  a_match = strstr((char*)pdu->data, cp);
1225  if (a_match && (a_match == (char*)pdu->data || a_match[-1] == ' ') &&
1226  ((size_t)(a_match - (char*)pdu->data + len) == data_len ||
1227  a_match[len] == ' ')) {
1228  coap_log(LOG_WARNING, "Proxy loop detected '%s'\n",
1229  (char*)pdu->data);
1230  coap_delete_pdu(pdu);
1232  }
1233  }
1234  }
1235  if (pdu->used_size + len + 1 <= pdu->max_size) {
1236  size_t old_size = pdu->used_size;
1237  if (coap_pdu_resize(pdu, pdu->used_size + len + 1)) {
1238  if (pdu->data == NULL) {
1239  /*
1240  * Set Hop Limit to max for return path. If this libcoap is in
1241  * a proxy loop path, it will always decrement hop limit in code
1242  * above and hence timeout / drop the response as appropriate
1243  */
1244  hop_limit = 255;
1246  (uint8_t *)&hop_limit);
1247  coap_add_data(pdu, len, (uint8_t*)cp);
1248  }
1249  else {
1250  /* prepend with space separator, leaving hop limit "as is" */
1251  memmove(pdu->data + len + 1, pdu->data,
1252  old_size - (pdu->data - pdu->token));
1253  memcpy(pdu->data, cp, len);
1254  pdu->data[len] = ' ';
1255  pdu->used_size += len + 1;
1256  }
1257  }
1258  }
1259  }
1260  }
1261 
1262  if (!coap_pdu_encode_header(pdu, session->proto)) {
1263  goto error;
1264  }
1265 
1266 #if !COAP_DISABLE_TCP
1267  if (COAP_PROTO_RELIABLE(session->proto) &&
1268  session->state == COAP_SESSION_STATE_ESTABLISHED &&
1269  !session->csm_block_supported) {
1270  /*
1271  * Need to check that this instance is not sending any block options as the
1272  * remote end via CSM has not informed us that there is support
1273  * https://tools.ietf.org/html/rfc8323#section-5.3.2
1274  * Note that this also includes BERT which is application specific.
1275  */
1276  if (coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter) != NULL) {
1278  "Remote end did not indicate CSM support for BLOCK1 enabled\n");
1279  }
1280  if (coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter) != NULL) {
1282  "Remote end did not indicate CSM support for BLOCK2 enabled\n");
1283  }
1284  }
1285 #endif /* !COAP_DISABLE_TCP */
1286 
1287  bytes_written = coap_send_pdu( session, pdu, NULL );
1288 
1289  if (bytes_written == COAP_PDU_DELAYED) {
1290  /* do not free pdu as it is stored with session for later use */
1291  return pdu->mid;
1292  }
1293 
1294  if (bytes_written < 0) {
1295  coap_delete_pdu(pdu);
1296  return (coap_mid_t)bytes_written;
1297  }
1298 
1299 #if !COAP_DISABLE_TCP
1300  if (COAP_PROTO_RELIABLE(session->proto) &&
1301  (size_t)bytes_written < pdu->used_size + pdu->hdr_size) {
1302  if (coap_session_delay_pdu(session, pdu, NULL) == COAP_PDU_DELAYED) {
1303  session->partial_write = (size_t)bytes_written;
1304  /* do not free pdu as it is stored with session for later use */
1305  return pdu->mid;
1306  } else {
1307  goto error;
1308  }
1309  }
1310 #endif /* !COAP_DISABLE_TCP */
1311 
1312  if (pdu->type != COAP_MESSAGE_CON
1313  || COAP_PROTO_RELIABLE(session->proto)) {
1314  coap_mid_t id = pdu->mid;
1315  coap_delete_pdu(pdu);
1316  return id;
1317  }
1318 
1319  coap_queue_t *node = coap_new_node();
1320  if (!node) {
1321  coap_log(LOG_DEBUG, "coap_wait_ack: insufficient memory\n");
1322  goto error;
1323  }
1324 
1325  node->id = pdu->mid;
1326  node->pdu = pdu;
1327  coap_prng(&r, sizeof(r));
1328  /* add timeout in range [ACK_TIMEOUT...ACK_TIMEOUT * ACK_RANDOM_FACTOR] */
1329  node->timeout = coap_calc_timeout(session, r);
1330  return coap_wait_ack(session->context, session, node);
1331  error:
1332  coap_delete_pdu(pdu);
1333  return COAP_INVALID_MID;
1334 }
1335 
1336 coap_mid_t
1338  if (!context || !node)
1339  return COAP_INVALID_MID;
1340 
1341  /* re-initialize timeout when maximum number of retransmissions are not reached yet */
1342  if (node->retransmit_cnt < node->session->max_retransmit) {
1343  ssize_t bytes_written;
1344  coap_tick_t now;
1345 
1346  node->retransmit_cnt++;
1347  coap_ticks(&now);
1348  if (context->sendqueue == NULL) {
1349  node->t = node->timeout << node->retransmit_cnt;
1350  context->sendqueue_basetime = now;
1351  } else {
1352  /* make node->t relative to context->sendqueue_basetime */
1353  node->t = (now - context->sendqueue_basetime) + (node->timeout << node->retransmit_cnt);
1354  }
1355  coap_insert_node(&context->sendqueue, node);
1356 #ifdef WITH_LWIP
1357  if (node == context->sendqueue) /* don't bother with timer stuff if there are earlier retransmits */
1358  coap_retransmittimer_restart(context);
1359 #endif
1360 
1361  coap_log(LOG_DEBUG, "** %s: mid=0x%x: retransmission #%d\n",
1362  coap_session_str(node->session), node->id, node->retransmit_cnt);
1363 
1364  if (node->session->con_active)
1365  node->session->con_active--;
1366  bytes_written = coap_send_pdu(node->session, node->pdu, node);
1367 
1368  if (bytes_written == COAP_PDU_DELAYED) {
1369  /* PDU was not retransmitted immediately because a new handshake is
1370  in progress. node was moved to the send queue of the session. */
1371  return node->id;
1372  }
1373 
1374  if (bytes_written < 0)
1375  return (int)bytes_written;
1376 
1377  return node->id;
1378  }
1379 
1380  /* no more retransmissions, remove node from system */
1381 
1382 #ifndef WITH_CONTIKI
1383  coap_log(LOG_DEBUG, "** %s: mid=0x%x: give up after %d attempts\n",
1384  coap_session_str(node->session), node->id, node->retransmit_cnt);
1385 #endif
1386 
1387  /* Check if subscriptions exist that should be canceled after
1388  COAP_MAX_NOTIFY_FAILURES */
1389  if (node->pdu->code >= 64) {
1390  coap_binary_t token = { 0, NULL };
1391 
1392  token.length = node->pdu->token_length;
1393  token.s = node->pdu->token;
1394 
1395  coap_handle_failed_notify(context, node->session, &token);
1396  }
1397  if (node->session->con_active) {
1398  node->session->con_active--;
1400  /*
1401  * As there may be another CON in a different queue entry on the same
1402  * session that needs to be immediately released,
1403  * coap_session_connected() is called.
1404  * However, there is the possibility coap_wait_ack() may be called for
1405  * this node (queue) and re-added to context->sendqueue.
1406  * coap_delete_node(node) called shortly will handle this and remove it.
1407  */
1409  }
1410  }
1411 
1412  /* And finally delete the node */
1413  if (node->pdu->type == COAP_MESSAGE_CON && context->nack_handler)
1414  context->nack_handler(context, node->session, node->pdu, COAP_NACK_TOO_MANY_RETRIES, node->id);
1415  coap_delete_node(node);
1416  return COAP_INVALID_MID;
1417 }
1418 
1419 #ifdef WITH_LWIP
1420 /* WITH_LWIP, this is handled by coap_recv in a different way */
1421 void
1423  return;
1424 }
1425 #else /* WITH_LWIP */
1426 
1427 static int
1429  uint8_t *data;
1430  size_t data_len;
1431  int result = -1;
1432 
1433  coap_packet_get_memmapped(packet, &data, &data_len);
1434 
1435  if (session->proto == COAP_PROTO_DTLS) {
1436  if (session->type == COAP_SESSION_TYPE_HELLO)
1437  result = coap_dtls_hello(session, data, data_len);
1438  else if (session->tls)
1439  result = coap_dtls_receive(session, data, data_len);
1440  } else if (session->proto == COAP_PROTO_UDP) {
1441  result = coap_handle_dgram(ctx, session, data, data_len);
1442  }
1443  return result;
1444 }
1445 
1446 static void
1448  coap_session_t *session,
1449  coap_tick_t now) {
1450  (void)ctx;
1451 #if COAP_DISABLE_TCP
1452  (void)session;
1453  (void)now;
1454 #else /* !COAP_DISABLE_TCP */
1455  if (coap_socket_connect_tcp2(&session->sock, &session->addr_info.local,
1456  &session->addr_info.remote)) {
1457  session->last_rx_tx = now;
1459  if (session->proto == COAP_PROTO_TCP) {
1460  coap_session_send_csm(session);
1461  } else if (session->proto == COAP_PROTO_TLS) {
1462  int connected = 0;
1464  session->tls = coap_tls_new_client_session(session, &connected);
1465  if (session->tls) {
1466  if (connected) {
1468  session);
1469  coap_session_send_csm(session);
1470  }
1471  } else {
1472  coap_handle_event(session->context, COAP_EVENT_DTLS_ERROR, session);
1474  }
1475  }
1476  } else {
1477  coap_handle_event(session->context, COAP_EVENT_TCP_FAILED, session);
1479  }
1480 #endif /* !COAP_DISABLE_TCP */
1481 }
1482 
1483 static void
1485  (void)ctx;
1486  assert(session->sock.flags & COAP_SOCKET_CONNECTED);
1487 
1488  while (session->delayqueue) {
1489  ssize_t bytes_written;
1490  coap_queue_t *q = session->delayqueue;
1491  coap_log(LOG_DEBUG, "** %s: mid=0x%x: transmitted after delay\n",
1492  coap_session_str(session), (int)q->pdu->mid);
1493  assert(session->partial_write < q->pdu->used_size + q->pdu->hdr_size);
1494  switch (session->proto) {
1495  case COAP_PROTO_TCP:
1496 #if !COAP_DISABLE_TCP
1497  bytes_written = coap_session_write(
1498  session,
1499  q->pdu->token - q->pdu->hdr_size - session->partial_write,
1500  q->pdu->used_size + q->pdu->hdr_size - session->partial_write
1501  );
1502 #endif /* !COAP_DISABLE_TCP */
1503  break;
1504  case COAP_PROTO_TLS:
1505 #if !COAP_DISABLE_TCP
1506  bytes_written = coap_tls_write(
1507  session,
1508  q->pdu->token - q->pdu->hdr_size - session->partial_write,
1509  q->pdu->used_size + q->pdu->hdr_size - session->partial_write
1510  );
1511 #endif /* !COAP_DISABLE_TCP */
1512  break;
1513  case COAP_PROTO_NONE:
1514  case COAP_PROTO_UDP:
1515  case COAP_PROTO_DTLS:
1516  default:
1517  bytes_written = -1;
1518  break;
1519  }
1520  if (bytes_written > 0)
1521  session->last_rx_tx = now;
1522  if (bytes_written <= 0 || (size_t)bytes_written < q->pdu->used_size + q->pdu->hdr_size - session->partial_write) {
1523  if (bytes_written > 0)
1524  session->partial_write += (size_t)bytes_written;
1525  break;
1526  }
1527  session->delayqueue = q->next;
1528  session->partial_write = 0;
1529  coap_delete_node(q);
1530  }
1531 }
1532 
1533 static void
1535 #if COAP_CONSTRAINED_STACK
1536  static coap_mutex_t s_static_mutex = COAP_MUTEX_INITIALIZER;
1537  static coap_packet_t s_packet;
1538 #else /* ! COAP_CONSTRAINED_STACK */
1539  coap_packet_t s_packet;
1540 #endif /* ! COAP_CONSTRAINED_STACK */
1541  coap_packet_t *packet = &s_packet;
1542 
1543 #if COAP_CONSTRAINED_STACK
1544  coap_mutex_lock(&s_static_mutex);
1545 #endif /* COAP_CONSTRAINED_STACK */
1546 
1547  assert(session->sock.flags & (COAP_SOCKET_CONNECTED | COAP_SOCKET_MULTICAST));
1548 
1549  if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
1550  ssize_t bytes_read;
1551  memcpy(&packet->addr_info, &session->addr_info, sizeof(packet->addr_info));
1552  bytes_read = ctx->network_read(&session->sock, packet);
1553 
1554  if (bytes_read < 0) {
1555  if (bytes_read == -2)
1556  /* Reset the session back to startup defaults */
1558  else
1559  coap_log(LOG_WARNING, "* %s: read error\n",
1560  coap_session_str(session));
1561  } else if (bytes_read > 0) {
1562  session->last_rx_tx = now;
1563  memcpy(&session->addr_info, &packet->addr_info,
1564  sizeof(session->addr_info));
1565  coap_log(LOG_DEBUG, "* %s: received %zd bytes\n",
1566  coap_session_str(session), bytes_read);
1567  coap_handle_dgram_for_proto(ctx, session, packet);
1568  }
1569 #if !COAP_DISABLE_TCP
1570  } else {
1571  ssize_t bytes_read = 0;
1572  const uint8_t *p;
1573  int retry;
1574  /* adjust for LWIP */
1575  uint8_t *buf = packet->payload;
1576  size_t buf_len = sizeof(packet->payload);
1577 
1578  do {
1579  if (session->proto == COAP_PROTO_TCP)
1580  bytes_read = coap_socket_read(&session->sock, buf, buf_len);
1581  else if (session->proto == COAP_PROTO_TLS)
1582  bytes_read = coap_tls_read(session, buf, buf_len);
1583  if (bytes_read > 0) {
1584  coap_log(LOG_DEBUG, "* %s: received %zd bytes\n",
1585  coap_session_str(session), bytes_read);
1586  session->last_rx_tx = now;
1587  }
1588  p = buf;
1589  retry = bytes_read == (ssize_t)buf_len;
1590  while (bytes_read > 0) {
1591  if (session->partial_pdu) {
1592  size_t len = session->partial_pdu->used_size
1593  + session->partial_pdu->hdr_size
1594  - session->partial_read;
1595  size_t n = min(len, (size_t)bytes_read);
1596  memcpy(session->partial_pdu->token - session->partial_pdu->hdr_size
1597  + session->partial_read, p, n);
1598  p += n;
1599  bytes_read -= n;
1600  if (n == len) {
1601  if (coap_pdu_parse_header(session->partial_pdu, session->proto)
1602  && coap_pdu_parse_opt(session->partial_pdu)) {
1603  coap_dispatch(ctx, session, session->partial_pdu);
1604  }
1605  coap_delete_pdu(session->partial_pdu);
1606  session->partial_pdu = NULL;
1607  session->partial_read = 0;
1608  } else {
1609  session->partial_read += n;
1610  }
1611  } else if (session->partial_read > 0) {
1612  size_t hdr_size = coap_pdu_parse_header_size(session->proto,
1613  session->read_header);
1614  size_t len = hdr_size - session->partial_read;
1615  size_t n = min(len, (size_t)bytes_read);
1616  memcpy(session->read_header + session->partial_read, p, n);
1617  p += n;
1618  bytes_read -= n;
1619  if (n == len) {
1620  size_t size = coap_pdu_parse_size(session->proto, session->read_header,
1621  hdr_size);
1622  if (size > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
1624  "** %s: incoming PDU length too large (%zu > %lu)\n",
1625  coap_session_str(session),
1627  bytes_read = -1;
1628  break;
1629  }
1630  /* Need max space incase PDU is updated with updated token etc. */
1631  session->partial_pdu = coap_pdu_init(0, 0, 0,
1632  coap_session_max_pdu_size(session));
1633  if (session->partial_pdu == NULL) {
1634  bytes_read = -1;
1635  break;
1636  }
1637  if (session->partial_pdu->alloc_size < size && !coap_pdu_resize(session->partial_pdu, size)) {
1638  bytes_read = -1;
1639  break;
1640  }
1641  session->partial_pdu->hdr_size = (uint8_t)hdr_size;
1642  session->partial_pdu->used_size = size;
1643  memcpy(session->partial_pdu->token - hdr_size, session->read_header, hdr_size);
1644  session->partial_read = hdr_size;
1645  if (size == 0) {
1646  if (coap_pdu_parse_header(session->partial_pdu, session->proto)) {
1647  coap_dispatch(ctx, session, session->partial_pdu);
1648  }
1649  coap_delete_pdu(session->partial_pdu);
1650  session->partial_pdu = NULL;
1651  session->partial_read = 0;
1652  }
1653  } else {
1654  session->partial_read += bytes_read;
1655  }
1656  } else {
1657  session->read_header[0] = *p++;
1658  bytes_read -= 1;
1659  if (!coap_pdu_parse_header_size(session->proto,
1660  session->read_header)) {
1661  bytes_read = -1;
1662  break;
1663  }
1664  session->partial_read = 1;
1665  }
1666  }
1667  } while (bytes_read == 0 && retry);
1668  if (bytes_read < 0)
1670 #endif /* !COAP_DISABLE_TCP */
1671  }
1672 #if COAP_CONSTRAINED_STACK
1673  coap_mutex_unlock(&s_static_mutex);
1674 #endif /* COAP_CONSTRAINED_STACK */
1675 }
1676 
1677 static int
1679  ssize_t bytes_read = -1;
1680  int result = -1; /* the value to be returned */
1681 #if COAP_CONSTRAINED_STACK
1682  static coap_mutex_t e_static_mutex = COAP_MUTEX_INITIALIZER;
1683  static coap_packet_t e_packet;
1684 #else /* ! COAP_CONSTRAINED_STACK */
1685  coap_packet_t e_packet;
1686 #endif /* ! COAP_CONSTRAINED_STACK */
1687  coap_packet_t *packet = &e_packet;
1688 
1689  assert(COAP_PROTO_NOT_RELIABLE(endpoint->proto));
1690  assert(endpoint->sock.flags & COAP_SOCKET_BOUND);
1691 
1692 #if COAP_CONSTRAINED_STACK
1693  coap_mutex_lock(&e_static_mutex);
1694 #endif /* COAP_CONSTRAINED_STACK */
1695 
1696  /* Need to do this as there may be holes in addr_info */
1697  memset(&packet->addr_info, 0, sizeof(packet->addr_info));
1699  coap_address_copy(&packet->addr_info.local, &endpoint->bind_addr);
1700  bytes_read = ctx->network_read(&endpoint->sock, packet);
1701 
1702  if (bytes_read < 0) {
1703  coap_log(LOG_WARNING, "* %s: read failed\n", coap_endpoint_str(endpoint));
1704  } else if (bytes_read > 0) {
1705  coap_session_t *session = coap_endpoint_get_session(endpoint, packet, now);
1706  if (session) {
1707  coap_log(LOG_DEBUG, "* %s: received %zd bytes\n",
1708  coap_session_str(session), bytes_read);
1709  result = coap_handle_dgram_for_proto(ctx, session, packet);
1710  if (endpoint->proto == COAP_PROTO_DTLS && session->type == COAP_SESSION_TYPE_HELLO && result == 1)
1711  coap_session_new_dtls_session(session, now);
1712  }
1713  }
1714 #if COAP_CONSTRAINED_STACK
1715  coap_mutex_unlock(&e_static_mutex);
1716 #endif /* COAP_CONSTRAINED_STACK */
1717  return result;
1718 }
1719 
1720 static int
1722  (void)ctx;
1723  (void)endpoint;
1724  (void)now;
1725  return 0;
1726 }
1727 
1728 static int
1730  coap_tick_t now) {
1731  coap_session_t *session = coap_new_server_session(ctx, endpoint);
1732  if (session)
1733  session->last_rx_tx = now;
1734  return session != NULL;
1735 }
1736 
1737 void
1739 #ifdef COAP_EPOLL_SUPPORT
1740  (void)ctx;
1741  (void)now;
1743  "coap_io_do_io() requires libcoap not compiled for using epoll\n");
1744 #else /* ! COAP_EPOLL_SUPPORT */
1745  coap_endpoint_t *ep, *tmp;
1746  coap_session_t *s, *rtmp;
1747 
1748  LL_FOREACH_SAFE(ctx->endpoint, ep, tmp) {
1749  if ((ep->sock.flags & COAP_SOCKET_CAN_READ) != 0)
1750  coap_read_endpoint(ctx, ep, now);
1751  if ((ep->sock.flags & COAP_SOCKET_CAN_WRITE) != 0)
1752  coap_write_endpoint(ctx, ep, now);
1753  if ((ep->sock.flags & COAP_SOCKET_CAN_ACCEPT) != 0)
1754  coap_accept_endpoint(ctx, ep, now);
1755  SESSIONS_ITER_SAFE(ep->sessions, s, rtmp) {
1756  if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0) {
1757  /* Make sure the session object is not deleted in one of the callbacks */
1759  coap_read_session(ctx, s, now);
1761  }
1762  if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0) {
1763  /* Make sure the session object is not deleted in one of the callbacks */
1765  coap_write_session(ctx, s, now);
1767  }
1768  }
1769  }
1770 
1771  SESSIONS_ITER_SAFE(ctx->sessions, s, rtmp) {
1772  if ((s->sock.flags & COAP_SOCKET_CAN_CONNECT) != 0) {
1773  /* Make sure the session object is not deleted in one of the callbacks */
1775  coap_connect_session(ctx, s, now);
1776  coap_session_release( s );
1777  }
1778  if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0) {
1779  /* Make sure the session object is not deleted in one of the callbacks */
1781  coap_read_session(ctx, s, now);
1783  }
1784  if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0) {
1785  /* Make sure the session object is not deleted in one of the callbacks */
1787  coap_write_session(ctx, s, now);
1788  coap_session_release( s );
1789  }
1790  }
1791 #endif /* ! COAP_EPOLL_SUPPORT */
1792 }
1793 
1794 /*
1795  * While this code in part replicates coap_io_do_io(), doing the functions
1796  * directly saves having to iterate through the endpoints / sessions.
1797  */
1798 void
1799 coap_io_do_epoll(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
1800 #ifndef COAP_EPOLL_SUPPORT
1801  (void)ctx;
1802  (void)events;
1803  (void)nevents;
1805  "coap_io_do_epoll() requires libcoap compiled for using epoll\n");
1806 #else /* COAP_EPOLL_SUPPORT */
1807  coap_tick_t now;
1808  size_t j;
1809 
1810  coap_ticks(&now);
1811  for(j = 0; j < nevents; j++) {
1812  coap_socket_t *sock = (coap_socket_t*)events[j].data.ptr;
1813 
1814  /* Ignore 'timer trigger' ptr which is NULL */
1815  if (sock) {
1816  if (sock->endpoint) {
1817  coap_endpoint_t *endpoint = sock->endpoint;
1818  if ((sock->flags & COAP_SOCKET_WANT_READ) &&
1819  (events[j].events & EPOLLIN)) {
1820  sock->flags |= COAP_SOCKET_CAN_READ;
1821  coap_read_endpoint(endpoint->context, endpoint, now);
1822  }
1823 
1824  if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
1825  (events[j].events & EPOLLOUT)) {
1826  /*
1827  * Need to update this to EPOLLIN as EPOLLOUT will normally always
1828  * be true causing epoll_wait to return early
1829  */
1830  coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
1831  sock->flags |= COAP_SOCKET_CAN_WRITE;
1832  coap_write_endpoint(endpoint->context, endpoint, now);
1833  }
1834 
1835  if ((sock->flags & COAP_SOCKET_WANT_ACCEPT) &&
1836  (events[j].events & EPOLLIN)) {
1837  sock->flags |= COAP_SOCKET_CAN_ACCEPT;
1838  coap_accept_endpoint(endpoint->context, endpoint, now);
1839  }
1840 
1841  }
1842  else if (sock->session) {
1843  coap_session_t *session = sock->session;
1844 
1845  /* Make sure the session object is not deleted
1846  in one of the callbacks */
1847  coap_session_reference(session);
1848  if ((sock->flags & COAP_SOCKET_WANT_CONNECT) &&
1849  (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
1850  sock->flags |= COAP_SOCKET_CAN_CONNECT;
1851  coap_connect_session(session->context, session, now);
1852  if (!(sock->flags & COAP_SOCKET_WANT_WRITE)) {
1853  coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
1854  }
1855  }
1856 
1857  if ((sock->flags & COAP_SOCKET_WANT_READ) &&
1858  (events[j].events & (EPOLLIN|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
1859  sock->flags |= COAP_SOCKET_CAN_READ;
1860  coap_read_session(session->context, session, now);
1861  }
1862 
1863  if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
1864  (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
1865  /*
1866  * Need to update this to EPOLLIN as EPOLLOUT will normally always
1867  * be true causing epoll_wait to return early
1868  */
1869  coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
1870  sock->flags |= COAP_SOCKET_CAN_WRITE;
1871  coap_write_session(session->context, session, now);
1872  }
1873  /* Now dereference session so it can go away if needed */
1874  coap_session_release(session);
1875  }
1876  }
1877  else if (ctx->eptimerfd != -1) {
1878  /*
1879  * 'timer trigger' must have fired. eptimerfd needs to be read to clear
1880  * it so that it does not set EPOLLIN in the next epoll_wait().
1881  */
1882  uint64_t count;
1883 
1884  /* Check the result from read() to suppress the warning on
1885  * systems that declare read() with warn_unused_result. */
1886  if (read(ctx->eptimerfd, &count, sizeof(count)) == -1) {
1887  /* do nothing */;
1888  }
1889  }
1890  /* And update eptimerfd as to when to next trigger */
1891  coap_ticks(&now);
1892  coap_io_prepare_epoll(ctx, now);
1893  }
1894 #endif /* COAP_EPOLL_SUPPORT */
1895 }
1896 
1897 int
1899  uint8_t *msg, size_t msg_len) {
1900 
1901  coap_pdu_t *pdu = NULL;
1902 
1903  assert(COAP_PROTO_NOT_RELIABLE(session->proto));
1904  if (msg_len < 4) {
1905  /* Minimum size of CoAP header - ignore runt */
1906  return -1;
1907  }
1908 
1909  /* Need max space incase PDU is updated with updated token etc. */
1910  pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_size(session));
1911  if (!pdu)
1912  goto error;
1913 
1914  if (!coap_pdu_parse(session->proto, msg, msg_len, pdu)) {
1915  coap_log(LOG_WARNING, "discard malformed PDU\n");
1916  goto error;
1917  }
1918 
1919  coap_dispatch(ctx, session, pdu);
1920  coap_delete_pdu(pdu);
1921  return 0;
1922 
1923 error:
1924  /*
1925  * https://tools.ietf.org/html/rfc7252#section-4.2 MUST send RST
1926  * https://tools.ietf.org/html/rfc7252#section-4.3 MAY send RST
1927  */
1928  coap_send_rst(session, pdu);
1929  coap_delete_pdu(pdu);
1930  return -1;
1931 }
1932 #endif /* not WITH_LWIP */
1933 
1934 int
1936  coap_queue_t *p, *q;
1937 
1938  if (!queue || !*queue)
1939  return 0;
1940 
1941  /* replace queue head if PDU's time is less than head's time */
1942 
1943  if (session == (*queue)->session && id == (*queue)->id) { /* found message id */
1944  *node = *queue;
1945  *queue = (*queue)->next;
1946  if (*queue) { /* adjust relative time of new queue head */
1947  (*queue)->t += (*node)->t;
1948  }
1949  (*node)->next = NULL;
1950  coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed\n",
1951  coap_session_str(session), id);
1952  return 1;
1953  }
1954 
1955  /* search message id queue to remove (only first occurence will be removed) */
1956  q = *queue;
1957  do {
1958  p = q;
1959  q = q->next;
1960  } while (q && (session != q->session || id != q->id));
1961 
1962  if (q) { /* found message id */
1963  p->next = q->next;
1964  if (p->next) { /* must update relative time of p->next */
1965  p->next->t += q->t;
1966  }
1967  q->next = NULL;
1968  *node = q;
1969  coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed\n",
1970  coap_session_str(session), id);
1971  return 1;
1972  }
1973 
1974  return 0;
1975 
1976 }
1977 
1978 void
1980  coap_nack_reason_t reason) {
1981  coap_queue_t *p, *q;
1982 
1983  while (context->sendqueue && context->sendqueue->session == session) {
1984  q = context->sendqueue;
1985  context->sendqueue = q->next;
1986  coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed\n",
1987  coap_session_str(session), q->id);
1988  if (q->pdu->type == COAP_MESSAGE_CON && context->nack_handler)
1989  context->nack_handler(context, session, q->pdu, reason, q->id);
1990  coap_delete_node(q);
1991  }
1992 
1993  if (!context->sendqueue)
1994  return;
1995 
1996  p = context->sendqueue;
1997  q = p->next;
1998 
1999  while (q) {
2000  if (q->session == session) {
2001  p->next = q->next;
2002  coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed\n",
2003  coap_session_str(session), q->id);
2004  if (q->pdu->type == COAP_MESSAGE_CON && context->nack_handler)
2005  context->nack_handler(context, session, q->pdu, reason, q->id);
2006  coap_delete_node(q);
2007  q = p->next;
2008  } else {
2009  p = q;
2010  q = q->next;
2011  }
2012  }
2013 }
2014 
2015 void
2017  const uint8_t *token, size_t token_length) {
2018  /* cancel all messages in sendqueue that belong to session
2019  * and use the specified token */
2020  coap_queue_t *p, *q;
2021 
2022  while (context->sendqueue && context->sendqueue->session == session &&
2023  token_match(token, token_length,
2024  context->sendqueue->pdu->token,
2025  context->sendqueue->pdu->token_length)) {
2026  q = context->sendqueue;
2027  context->sendqueue = q->next;
2028  coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed\n",
2029  coap_session_str(session), q->id);
2030  coap_delete_node(q);
2031  }
2032 
2033  if (!context->sendqueue)
2034  return;
2035 
2036  p = context->sendqueue;
2037  q = p->next;
2038 
2039  /* when q is not NULL, it does not match (dst, token), so we can skip it */
2040  while (q) {
2041  if (q->session == session &&
2042  token_match(token, token_length,
2043  q->pdu->token, q->pdu->token_length)) {
2044  p->next = q->next;
2045  coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed\n",
2046  coap_session_str(session), q->id);
2047  coap_delete_node(q);
2048  q = p->next;
2049  } else {
2050  p = q;
2051  q = q->next;
2052  }
2053  }
2054 }
2055 
2056 coap_pdu_t *
2057 coap_new_error_response(coap_pdu_t *request, unsigned char code,
2058  coap_opt_filter_t *opts) {
2059  coap_opt_iterator_t opt_iter;
2060  coap_pdu_t *response;
2061  size_t size = request->token_length;
2062  unsigned char type;
2063  coap_opt_t *option;
2064  coap_option_num_t opt_num = 0; /* used for calculating delta-storage */
2065 
2066 #if COAP_ERROR_PHRASE_LENGTH > 0
2067  const char *phrase;
2068  if (code != COAP_RESPONSE_CODE(508)) {
2069  phrase = coap_response_phrase(code);
2070 
2071  /* Need some more space for the error phrase and payload start marker */
2072  if (phrase)
2073  size += strlen(phrase) + 1;
2074  }
2075  else {
2076  /*
2077  * Need space for IP for 5.08 response which is filled in in coap_send()
2078  * https://www.rfc-editor.org/rfc/rfc8768.html#section-4
2079  */
2080  phrase = NULL;
2081  size += INET6_ADDRSTRLEN;
2082  }
2083 #endif
2084 
2085  assert(request);
2086 
2087  /* cannot send ACK if original request was not confirmable */
2088  type = request->type == COAP_MESSAGE_CON
2090  : COAP_MESSAGE_NON;
2091 
2092  /* Estimate how much space we need for options to copy from
2093  * request. We always need the Token, for 4.02 the unknown critical
2094  * options must be included as well. */
2095 
2096  /* we do not want these */
2099 
2100  coap_option_iterator_init(request, &opt_iter, opts);
2101 
2102  /* Add size of each unknown critical option. As known critical
2103  options as well as elective options are not copied, the delta
2104  value might grow.
2105  */
2106  while ((option = coap_option_next(&opt_iter))) {
2107  uint16_t delta = opt_iter.number - opt_num;
2108  /* calculate space required to encode (opt_iter.number - opt_num) */
2109  if (delta < 13) {
2110  size++;
2111  } else if (delta < 269) {
2112  size += 2;
2113  } else {
2114  size += 3;
2115  }
2116 
2117  /* add coap_opt_length(option) and the number of additional bytes
2118  * required to encode the option length */
2119 
2120  size += coap_opt_length(option);
2121  switch (*option & 0x0f) {
2122  case 0x0e:
2123  size++;
2124  /* fall through */
2125  case 0x0d:
2126  size++;
2127  break;
2128  default:
2129  ;
2130  }
2131 
2132  opt_num = opt_iter.number;
2133  }
2134 
2135  /* Now create the response and fill with options and payload data. */
2136  response = coap_pdu_init(type, code, request->mid, size);
2137  if (response) {
2138  /* copy token */
2139  if (!coap_add_token(response, request->token_length,
2140  request->token)) {
2141  coap_log(LOG_DEBUG, "cannot add token to error response\n");
2142  coap_delete_pdu(response);
2143  return NULL;
2144  }
2145 
2146  /* copy all options */
2147  coap_option_iterator_init(request, &opt_iter, opts);
2148  while ((option = coap_option_next(&opt_iter))) {
2149  coap_add_option(response, opt_iter.number,
2150  coap_opt_length(option),
2151  coap_opt_value(option));
2152  }
2153 
2154 #if COAP_ERROR_PHRASE_LENGTH > 0
2155  /* note that diagnostic messages do not need a Content-Format option. */
2156  if (phrase)
2157  coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
2158 #endif
2159  }
2160 
2161  return response;
2162 }
2163 
2168 COAP_STATIC_INLINE size_t
2169 get_wkc_len(coap_context_t *context, coap_opt_t *query_filter) {
2170  unsigned char buf[1];
2171  size_t len = 0;
2172 
2173  if (coap_print_wellknown(context, buf, &len, UINT_MAX, query_filter)
2175  coap_log(LOG_WARNING, "cannot determine length of /.well-known/core\n");
2176  return 0;
2177  }
2178 
2179  coap_log(LOG_DEBUG, "get_wkc_len: coap_print_wellknown() returned %zu\n", len);
2180 
2181  return len;
2182 }
2183 
2184 #define SZX_TO_BYTES(SZX) ((size_t)(1 << ((SZX) + 4)))
2185 
2186 coap_pdu_t *
2188  coap_pdu_t *request) {
2189  coap_pdu_t *resp;
2190  coap_opt_iterator_t opt_iter;
2191  size_t len, wkc_len;
2192  uint8_t buf[4];
2193  int result = 0;
2194  int need_block2 = 0; /* set to 1 if Block2 option is required */
2195  coap_block_t block;
2196  coap_opt_t *query_filter;
2197  size_t offset = 0;
2198  uint8_t *data;
2199 
2200  resp = coap_pdu_init(request->type == COAP_MESSAGE_CON
2202  : COAP_MESSAGE_NON,
2203  COAP_RESPONSE_CODE(205),
2204  request->mid, coap_session_max_pdu_size(session));
2205  if (!resp) {
2206  coap_log(LOG_DEBUG, "coap_wellknown_response: cannot create PDU\n");
2207  return NULL;
2208  }
2209 
2210  if (!coap_add_token(resp, request->token_length, request->token)) {
2211  coap_log(LOG_DEBUG, "coap_wellknown_response: cannot add token\n");
2212  goto error;
2213  }
2214 
2215  query_filter = coap_check_option(request, COAP_OPTION_URI_QUERY, &opt_iter);
2216  wkc_len = get_wkc_len(context, query_filter);
2217 
2218  /* The value of some resources is undefined and get_wkc_len will return 0.*/
2219  if (wkc_len == 0) {
2220  coap_log(LOG_DEBUG, "coap_wellknown_response: undefined resource\n");
2221  /* set error code 4.00 Bad Request*/
2222  resp->code = COAP_RESPONSE_CODE(400);
2223  resp->used_size = resp->token_length;
2224  return resp;
2225  }
2226 
2227  /* check whether the request contains the Block2 option */
2228  if (coap_get_block(request, COAP_OPTION_BLOCK2, &block)) {
2229  coap_log(LOG_DEBUG, "create block\n");
2230  offset = block.num << (block.szx + 4);
2231  if (block.szx > 6) { /* invalid, MUST lead to 4.00 Bad Request */
2232  resp->code = COAP_RESPONSE_CODE(400);
2233  return resp;
2234  } else if (block.szx > COAP_MAX_BLOCK_SZX) {
2235  block.szx = COAP_MAX_BLOCK_SZX;
2236  block.num = (unsigned int)(offset >> (block.szx + 4));
2237  }
2238 
2239  need_block2 = 1;
2240  }
2241 
2242  /* Check if there is sufficient space to add Content-Format option
2243  * and data. We do this before adding the Content-Format option to
2244  * avoid sending error responses with that option but no actual
2245  * content. */
2246  if (resp->max_size && resp->max_size <= resp->used_size + 8) {
2247  coap_log(LOG_DEBUG, "coap_wellknown_response: insufficient storage space\n");
2248  goto error;
2249  }
2250 
2251  /* check if Block2 option is required even if not requested */
2252  if (!need_block2 && resp->max_size && resp->max_size - resp->used_size < wkc_len + 1) {
2253  assert(resp->used_size <= resp->max_size);
2254  const size_t payloadlen = resp->max_size - resp->used_size;
2255  /* yes, need block-wise transfer */
2256  block.num = 0;
2257  block.m = 0; /* the M bit is set by coap_write_block_opt() */
2258  block.szx = COAP_MAX_BLOCK_SZX;
2259  while (payloadlen < SZX_TO_BYTES(block.szx) + 6) {
2260  if (block.szx == 0) {
2262  "coap_wellknown_response: message to small even for szx == 0\n");
2263  goto error;
2264  } else {
2265  block.szx--;
2266  }
2267  }
2268 
2269  need_block2 = 1;
2270  }
2271 
2272  if (need_block2) {
2273  /* Add in a pseudo etag (use wkc_len) in case .well-known/core
2274  changes over time */
2275  coap_add_option(resp,
2277  coap_encode_var_safe8(buf, sizeof(buf), wkc_len),
2278  buf);
2279  }
2280 
2281  /* Add Content-Format. As we have checked for available storage,
2282  * nothing should go wrong here. */
2283  assert(coap_encode_var_safe(buf, sizeof(buf),
2286  coap_encode_var_safe(buf, sizeof(buf),
2288 
2289 
2290  /* write Block2 option if necessary */
2291  if (need_block2) {
2292  if (coap_write_block_opt(&block, COAP_OPTION_BLOCK2, resp, wkc_len) < 0) {
2294  "coap_wellknown_response: cannot add Block2 option\n");
2295  goto error;
2296  }
2297  }
2298 
2299  coap_add_option(resp,
2301  coap_encode_var_safe8(buf, sizeof(buf), wkc_len),
2302  buf);
2303 
2304  len = need_block2 ?
2305  min(SZX_TO_BYTES(block.szx), wkc_len - (block.num << (block.szx + 4))) :
2306  resp->max_size && resp->used_size + wkc_len + 1 > resp->max_size ?
2307  resp->max_size - resp->used_size - 1 : wkc_len;
2308  data = coap_add_data_after(resp, len);
2309  if (!data) {
2310  coap_log(LOG_DEBUG, "coap_wellknown_response: coap_add_data failed\n" );
2311  goto error;
2312  }
2313 
2314  result = coap_print_wellknown(context, data, &len, offset, query_filter);
2315  if ((result & COAP_PRINT_STATUS_ERROR) != 0) {
2316  coap_log(LOG_DEBUG, "coap_print_wellknown failed\n");
2317  goto error;
2318  }
2319 
2320  return resp;
2321 
2322 error:
2323  /* set error code 5.03 and remove all options and data from response */
2324  resp->code = COAP_RESPONSE_CODE(503);
2325  resp->used_size = resp->token_length;
2326  return resp;
2327 }
2328 
2339 static int
2340 coap_cancel(coap_context_t *context, const coap_queue_t *sent) {
2341  coap_binary_t token = { 0, NULL };
2342  int num_cancelled = 0; /* the number of observers cancelled */
2343 
2344  /* remove observer for this resource, if any
2345  * get token from sent and try to find a matching resource. Uh!
2346  */
2347 
2348  COAP_SET_STR(&token, sent->pdu->token_length, sent->pdu->token);
2349 
2350  RESOURCES_ITER(context->resources, r) {
2351  coap_cancel_all_messages(context, sent->session, token.s, token.length);
2352  num_cancelled += coap_delete_observer(r, sent->session, &token);
2353  }
2354 
2355  return num_cancelled;
2356 }
2357 
2363 
2364 /*
2365  * Checks for No-Response option in given @p request and
2366  * returns @c RESPONSE_DROP if @p response should be suppressed
2367  * according to RFC 7967.
2368  *
2369  * If the response is a confirmable piggybacked response and RESPONSE_DROP,
2370  * change it to an empty ACK and @c RESPONSE_SEND so the client does not keep
2371  * on retrying.
2372  *
2373  * Checks if the response code is 0.00 and if either the session is reliable or
2374  * non-confirmable, @c RESPONSE_DROP is also returned.
2375  *
2376  * Multicast response checking is also carried out.
2377  *
2378  * NOTE: It is the responsibility of the application to determine whether
2379  * a delayed separate response should be sent as the original requesting packet
2380  * containing the No-Response option has long since gone.
2381  *
2382  * The value of the No-Response option is encoded as
2383  * follows:
2384  *
2385  * @verbatim
2386  * +-------+-----------------------+-----------------------------------+
2387  * | Value | Binary Representation | Description |
2388  * +-------+-----------------------+-----------------------------------+
2389  * | 0 | <empty> | Interested in all responses. |
2390  * +-------+-----------------------+-----------------------------------+
2391  * | 2 | 00000010 | Not interested in 2.xx responses. |
2392  * +-------+-----------------------+-----------------------------------+
2393  * | 8 | 00001000 | Not interested in 4.xx responses. |
2394  * +-------+-----------------------+-----------------------------------+
2395  * | 16 | 00010000 | Not interested in 5.xx responses. |
2396  * +-------+-----------------------+-----------------------------------+
2397  * @endverbatim
2398  *
2399  * @param request The CoAP request to check for the No-Response option.
2400  * This parameter must not be NULL.
2401  * @param response The response that is potentially suppressed.
2402  * This parameter must not be NULL.
2403  * @param session The session this request/response are associated with.
2404  * This parameter must not be NULL.
2405  * @return RESPONSE_DEFAULT when no special treatment is requested,
2406  * RESPONSE_DROP when the response must be discarded, or
2407  * RESPONSE_SEND when the response must be sent.
2408  */
2409 static enum respond_t
2410 no_response(coap_pdu_t *request, coap_pdu_t *response,
2411  coap_session_t *session) {
2412  coap_opt_t *nores;
2413  coap_opt_iterator_t opt_iter;
2414  unsigned int val = 0;
2415 
2416  assert(request);
2417  assert(response);
2418 
2419  if (COAP_RESPONSE_CLASS(response->code) > 0) {
2420  nores = coap_check_option(request, COAP_OPTION_NORESPONSE, &opt_iter);
2421 
2422  if (nores) {
2424 
2425  /* The response should be dropped when the bit corresponding to
2426  * the response class is set (cf. table in function
2427  * documentation). When a No-Response option is present and the
2428  * bit is not set, the sender explicitly indicates interest in
2429  * this response. */
2430  if (((1 << (COAP_RESPONSE_CLASS(response->code) - 1)) & val) > 0) {
2431  /* Should be dropping the response */
2432  if (response->type == COAP_MESSAGE_ACK &&
2433  COAP_PROTO_NOT_RELIABLE(session->proto)) {
2434  /* Still need to ACK the request */
2435  response->code = 0;
2436  /* Remove token/data from piggybacked acknowledgment PDU */
2437  response->token_length = 0;
2438  response->used_size = 0;
2439  return RESPONSE_SEND;
2440  }
2441  else {
2442  return RESPONSE_DROP;
2443  }
2444  } else {
2445  /* True for mcast as well RFC7967 2.1 */
2446  return RESPONSE_SEND;
2447  }
2448  }
2449  }
2450  else if (COAP_PDU_IS_EMPTY(response) &&
2451  (response->type == COAP_MESSAGE_NON ||
2452  COAP_PROTO_RELIABLE(session->proto))) {
2453  /* response is 0.00, and this is reliable or non-confirmable */
2454  return RESPONSE_DROP;
2455  }
2456 
2457  /*
2458  * Do not send error responses for requests that were received via
2459  * IP multicast. RFC7252 8.1
2460  */
2461 
2462  if (coap_is_mcast(&session->addr_info.local)) {
2463  if (request->type == COAP_MESSAGE_NON &&
2464  response->type == COAP_MESSAGE_RST)
2465  return RESPONSE_DROP;
2466 
2467  if (COAP_RESPONSE_CLASS(response->code) > 2)
2468  return RESPONSE_DROP;
2469  }
2470 
2471  /* Default behavior applies when we are not dealing with a response
2472  * (class == 0) or the request did not contain a No-Response option.
2473  */
2474  return RESPONSE_DEFAULT;
2475 }
2476 
2478  { sizeof(COAP_DEFAULT_URI_WELLKNOWN)-1,
2479  (const uint8_t *)COAP_DEFAULT_URI_WELLKNOWN };
2480 
2481 static void
2483  coap_method_handler_t h = NULL;
2484  coap_pdu_t *response = NULL;
2485  coap_opt_filter_t opt_filter;
2486  coap_resource_t *resource = NULL;
2487  /* The respond field indicates whether a response must be treated
2488  * specially due to a No-Response option that declares disinterest
2489  * or interest in a specific response class. DEFAULT indicates that
2490  * No-Response has not been specified. */
2491  enum respond_t respond = RESPONSE_DEFAULT;
2492  coap_opt_iterator_t opt_iter;
2493  coap_opt_t *opt;
2494  int is_proxy_uri = 0;
2495  int is_proxy_scheme = 0;
2496  int skip_hop_limit_check = 0;
2497  int resp;
2498  coap_binary_t token = { pdu->token_length, pdu->token };
2499 #ifndef WITHOUT_ASYNC
2500  coap_async_t *async;
2501 #endif /* WITHOUT_ASYNC */
2502 
2503  if (coap_is_mcast(&session->addr_info.local)) {
2504  if (COAP_PROTO_RELIABLE(session->proto) || pdu->type != COAP_MESSAGE_NON) {
2505  coap_log(LOG_INFO, "Invalid multicast packet received RFC7252 8.1\n");
2506  return;
2507  }
2508  }
2509 #ifndef WITHOUT_ASYNC
2510  async = coap_find_async(context, session, token);
2511  if (async) {
2512  coap_tick_t now;
2513 
2514  coap_ticks(&now);
2515  if (async->delay == 0 || async->delay > now) {
2516  /* re-transmit missing ACK (only if CON) */
2517  coap_log(LOG_INFO, "Retransmit async response\n");
2518  coap_send_ack(session, pdu);
2519  /* and do not pass on to the upper layers */
2520  return;
2521  }
2522  }
2523  else if (coap_is_mcast(&session->addr_info.local)) {
2524  uint8_t r;
2525  coap_tick_t delay;
2526 
2527  /* Need to delay sending mcast request to application layer, so response
2528  is not immediate. */
2529  coap_prng(&r, sizeof(r));
2530  delay = (COAP_DEFAULT_LEISURE * COAP_TICKS_PER_SECOND * r) / 256;
2531  /* Register request to be internally re-transmitted after delay */
2532  if (coap_register_async(context, session, pdu, delay))
2533  return;
2534  }
2535 #endif /* WITHOUT_ASYNC */
2536 
2537  coap_option_filter_clear(&opt_filter);
2538  opt = coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter);
2539  if (opt)
2540  is_proxy_scheme = 1;
2541 
2542  opt = coap_check_option(pdu, COAP_OPTION_PROXY_URI, &opt_iter);
2543  if (opt)
2544  is_proxy_uri = 1;
2545 
2546  if (is_proxy_scheme || is_proxy_uri) {
2547  coap_uri_t uri;
2548 
2549  if (!context->proxy_uri_resource) {
2550  /* Need to return a 5.05 RFC7252 Section 5.7.2 */
2551  coap_log(LOG_DEBUG, "Proxy-%s support not configured\n",
2552  is_proxy_scheme ? "Scheme" : "Uri");
2553  resp = 505;
2554  goto fail_response;
2555  }
2556  if (((size_t)pdu->code - 1 <
2557  (sizeof(resource->handler) / sizeof(resource->handler[0]))) &&
2558  !(context->proxy_uri_resource->handler[pdu->code - 1])) {
2559  /* Need to return a 5.05 RFC7252 Section 5.7.2 */
2560  coap_log(LOG_DEBUG, "Proxy-%s code %d.%02d handler not supported\n",
2561  is_proxy_scheme ? "Scheme" : "Uri",
2562  pdu->code/100, pdu->code%100);
2563  resp = 505;
2564  goto fail_response;
2565  }
2566 
2567  /* Need to check if authority is the proxy endpoint RFC7252 Section 5.7.2 */
2568  if (is_proxy_uri) {
2570  coap_opt_length(opt), &uri) < 0) {
2571  /* Need to return a 5.05 RFC7252 Section 5.7.2 */
2572  coap_log(LOG_DEBUG, "Proxy-URI not decodable\n");
2573  resp = 505;
2574  goto fail_response;
2575  }
2576  }
2577  else {
2578  memset(&uri, 0, sizeof(uri));
2579  opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
2580  if (opt) {
2581  uri.host.length = coap_opt_length(opt);
2582  uri.host.s = coap_opt_value(opt);
2583  }
2584  }
2585  resource = context->proxy_uri_resource;
2586  if (uri.host.length && resource->proxy_name_count && resource->proxy_name_list) {
2587  size_t i;
2588  for (i = 0; i < resource->proxy_name_count; i++) {
2589  if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
2590  break;
2591  }
2592  }
2593  if (i != resource->proxy_name_count) {
2594  /* This server is hosting the proxy connection endpoint */
2595  is_proxy_uri = 0;
2596  is_proxy_scheme = 0;
2597  skip_hop_limit_check = 1;
2598  }
2599  }
2600  resource = NULL;
2601  }
2602 
2603  if (!skip_hop_limit_check) {
2604  opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
2605  if (opt) {
2606  size_t hop_limit;
2607  uint8_t buf[4];
2608 
2609  hop_limit =
2611  if (hop_limit == 1) {
2612  /* coap_send() will fill in the IP address for us */
2613  resp = 508;
2614  goto fail_response;
2615  }
2616  else if (hop_limit < 1 || hop_limit > 255) {
2617  /* Need to return a 4.00 RFC8768 Section 3 */
2618  coap_log(LOG_INFO, "Invalid Hop Limit\n");
2619  resp = 400;
2620  goto fail_response;
2621  }
2622  hop_limit--;
2624  coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
2625  buf);
2626  }
2627  }
2628 
2629  coap_string_t *uri_path = coap_get_uri_path(pdu);
2630  if (!uri_path)
2631  return;
2632 
2633  if (!is_proxy_uri && !is_proxy_scheme) {
2634  /* try to find the resource from the request URI */
2635  coap_str_const_t uri_path_c = { uri_path->length, uri_path->s };
2636  resource = coap_get_resource_from_uri_path(context, &uri_path_c);
2637  }
2638 
2639  if ((resource == NULL) || (resource->is_unknown == 1) ||
2640  (resource->is_proxy_uri == 1)) {
2641  /* The resource was not found or there is an unexpected match against the
2642  * resource defined for handling unknown or proxy URIs.
2643  * Check if the request URI happens to be the well-known URI, or if the
2644  * unknown resource handler is defined, a PUT or optionally other methods,
2645  * if configured, for the unknown handler.
2646  *
2647  * if well-known URI generate a default response
2648  *
2649  * else if a PROXY URI/Scheme request and proxy URI handler defined, call the
2650  * proxy URI handler
2651  *
2652  * else if unknown URI handler defined, call the unknown
2653  * URI handler (to allow for potential generation of resource
2654  * [RFC7272 5.8.3]) if the appropriate method is defined.
2655  *
2656  * else if DELETE return 2.02 (RFC7252: 5.8.4. DELETE)
2657  *
2658  * else return 4.04 */
2659 
2661  /* request for .well-known/core */
2662  if (pdu->code == COAP_REQUEST_CODE_GET) { /* GET */
2663  coap_log(LOG_INFO, "create default response for %s\n",
2665  response = coap_wellknown_response(context, session, pdu);
2666  } else {
2667  coap_log(LOG_DEBUG, "method not allowed for .well-known/core\n");
2668  response = coap_new_error_response(pdu, COAP_RESPONSE_CODE(405),
2669  &opt_filter);
2670  }
2671  } else if (is_proxy_uri || is_proxy_scheme) {
2672  resource = context->proxy_uri_resource;
2673  } else if ((context->unknown_resource != NULL) &&
2674  ((size_t)pdu->code - 1 <
2675  (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
2676  (context->unknown_resource->handler[pdu->code - 1])) {
2677  /*
2678  * The unknown_resource can be used to handle undefined resources
2679  * for a PUT request and can support any other registered handler
2680  * defined for it
2681  * Example set up code:-
2682  * r = coap_resource_unknown_init(hnd_put_unknown);
2683  * coap_register_handler(r, COAP_REQUEST_POST, hnd_post_unknown);
2684  * coap_register_handler(r, COAP_REQUEST_GET, hnd_get_unknown);
2685  * coap_register_handler(r, COAP_REQUEST_DELETE, hnd_delete_unknown);
2686  * coap_add_resource(ctx, r);
2687  *
2688  * Note: It is not possible to observe the unknown_resource, a separate
2689  * resource must be created (by PUT or POST) which has a GET
2690  * handler to be observed
2691  */
2692  resource = context->unknown_resource;
2693  } else if (pdu->code == COAP_REQUEST_CODE_DELETE) {
2694  /*
2695  * Request for DELETE on non-existant resource (RFC7252: 5.8.4. DELETE)
2696  */
2697  coap_log(LOG_DEBUG, "request for unknown resource '%*.*s',"
2698  " return 2.02\n",
2699  (int)uri_path->length,
2700  (int)uri_path->length,
2701  uri_path->s);
2702  response =
2704  &opt_filter);
2705  } else { /* request for any another resource, return 4.04 */
2706 
2707  coap_log(LOG_DEBUG, "request for unknown resource '%*.*s', return 4.04\n",
2708  (int)uri_path->length, (int)uri_path->length, uri_path->s);
2709  response =
2711  &opt_filter);
2712  }
2713 
2714  if (!resource) {
2715  if (response && (no_response(pdu, response, session) != RESPONSE_DROP)) {
2716  coap_mid_t mid = pdu->mid;
2717  if (coap_send(session, response) == COAP_INVALID_MID)
2718  coap_log(LOG_WARNING, "cannot send response for mid=0x%x\n", mid);
2719  } else {
2720  coap_delete_pdu(response);
2721  }
2722 
2723  response = NULL;
2724 
2725  coap_delete_string(uri_path);
2726  return;
2727  } else {
2728  if (response) {
2729  /* Need to delete unused response - it will get re-created further on */
2730  coap_delete_pdu(response);
2731  }
2732  }
2733  }
2734 
2735  /* the resource was found, check if there is a registered handler */
2736  if ((size_t)pdu->code - 1 <
2737  sizeof(resource->handler) / sizeof(coap_method_handler_t))
2738  h = resource->handler[pdu->code - 1];
2739 
2740  if (h) {
2741  coap_log(LOG_DEBUG, "call custom handler for resource '%*.*s'\n",
2742  (int)resource->uri_path->length, (int)resource->uri_path->length,
2743  resource->uri_path->s);
2744  response = coap_pdu_init(pdu->type == COAP_MESSAGE_CON
2746  : COAP_MESSAGE_NON,
2747  0, pdu->mid, coap_session_max_pdu_size(session));
2748 
2749  /* Implementation detail: coap_add_token() immediately returns 0
2750  if response == NULL */
2751  if (coap_add_token(response, pdu->token_length, pdu->token)) {
2752  coap_opt_t *observe = NULL;
2753  int observe_action = COAP_OBSERVE_CANCEL;
2754  coap_string_t *query = coap_get_query(pdu);
2755  int owns_query = 1;
2756  coap_block_t block;
2757  int added_block = 0;
2758 
2759  /* check for Observe option RFC7641 and RFC8132 */
2760  if (resource->observable &&
2761  (pdu->code == COAP_REQUEST_CODE_GET ||
2762  pdu->code == COAP_REQUEST_CODE_FETCH)) {
2763  observe = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
2764  if (observe) {
2765  observe_action =
2767  coap_opt_length(observe));
2768 
2769  if (observe_action == COAP_OBSERVE_ESTABLISH) {
2770  coap_subscription_t *subscription;
2771  int has_block2 = 0;
2772 
2773  if (coap_get_block(pdu, COAP_OPTION_BLOCK2, &block)) {
2774  has_block2 = 1;
2775  }
2776  subscription = coap_add_observer(resource, session, &token,
2777  query, has_block2,
2778  block, pdu->code);
2779  if (subscription) {
2780  /* Ownership of query is taken by subscription if not
2781  * NULL. In this case, we must not delete query here
2782  * hence owns_query is cleared. */
2783  owns_query = 0;
2784  coap_touch_observer(context, session, &token);
2785  }
2786  }
2787  else if (observe_action == COAP_OBSERVE_CANCEL) {
2788  coap_delete_observer(resource, session, &token);
2789  }
2790  else {
2791  coap_log(LOG_INFO, "observe: unexpected action %d\n", observe_action);
2792  }
2793  }
2794  }
2795 
2796  if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
2797  if (coap_handle_request_put_block(context, session, pdu, response,
2798  resource, uri_path, observe, &token,
2799  query, h, &added_block)) {
2800  goto skip_handler;
2801  }
2802 
2803  if (coap_handle_request_send_block(session, pdu, response, resource,
2804  query)) {
2805  goto skip_handler;
2806  }
2807  }
2808 
2809  /*
2810  * Call the request handler with everything set up
2811  */
2812  h(context, resource, session, pdu, &token, query, response);
2813 
2814  /* Check if lg_xmit generated and update PDU code if so */
2815  coap_check_code_lg_xmit(session, response, resource, query);
2816 
2817 skip_handler:
2818  respond = no_response(pdu, response, session);
2819  if (respond != RESPONSE_DROP) {
2820  coap_mid_t mid = pdu->mid;
2821  if (COAP_RESPONSE_CLASS(response->code) > 2) {
2822  if (observe)
2823  coap_delete_observer(resource, session, &token);
2824  if (added_block)
2826  }
2827 
2828  /* If original request contained a token, and the registered
2829  * application handler made no changes to the response, then
2830  * this is an empty ACK with a token, which is a malformed
2831  * PDU */
2832  if ((response->type == COAP_MESSAGE_ACK)
2833  && (response->code == 0)) {
2834  /* Remove token from otherwise-empty acknowledgment PDU */
2835  response->token_length = 0;
2836  response->used_size = 0;
2837  }
2838 
2839  if (coap_send(session, response) == COAP_INVALID_MID) {
2840  coap_log(LOG_DEBUG, "cannot send response for mid=0x%x\n", mid);
2841  }
2842  } else {
2843  coap_delete_pdu(response);
2844  }
2845  if (query && owns_query)
2846  coap_delete_string(query);
2847  } else {
2848  coap_log(LOG_WARNING, "cannot generate response\r\n");
2849  coap_delete_pdu(response);
2850  }
2851  response = NULL;
2852  } else {
2854  /* request for .well-known/core */
2855  coap_log(LOG_DEBUG, "create default response for %s\n",
2857  response = coap_wellknown_response(context, session, pdu);
2858  coap_log(LOG_DEBUG, "have wellknown response %p\n", (void *)response);
2859  } else
2860  response = coap_new_error_response(pdu, COAP_RESPONSE_CODE(405),
2861  &opt_filter);
2862 
2863  if (response && (no_response(pdu, response, session) != RESPONSE_DROP)) {
2864  coap_mid_t mid = pdu->mid;
2865  if (coap_send(session, response) == COAP_INVALID_MID)
2866  coap_log(LOG_DEBUG, "cannot send response for mid=0x%x\n", mid);
2867  } else {
2868  coap_delete_pdu(response);
2869  }
2870  response = NULL;
2871  }
2872 
2873  assert(response == NULL);
2874  coap_delete_string(uri_path);
2875  return;
2876 
2877 fail_response:
2878  response =
2880  &opt_filter);
2881  if (response) {
2882  coap_mid_t mid = pdu->mid;
2883  if (coap_send(session, response) == COAP_INVALID_MID)
2884  coap_log(LOG_WARNING, "cannot send response for mid=0x%x\n", mid);
2885  }
2886 }
2887 
2888 static void
2890  coap_pdu_t *sent, coap_pdu_t *rcvd) {
2891 
2892  /* In a lossy context, the ACK of a separate response may have
2893  * been lost, so we need to stop retransmitting requests with the
2894  * same token.
2895  */
2896  coap_cancel_all_messages(context, session, rcvd->token, rcvd->token_length);
2897 
2898  if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
2899  /* See if need to send next block to server */
2900  if (coap_handle_response_send_block(session, rcvd)) {
2901  /* Next block transmitted, no need to inform app */
2902  coap_send_ack(session, rcvd);
2903  return;
2904  }
2905 
2906  /* Need to see if needing to request next block */
2907  if (coap_handle_response_get_block(context, session, sent, rcvd,
2908  COAP_RECURSE_OK)) {
2909  /* Next block requested, no need to inform app */
2910  coap_send_ack(session, rcvd);
2911  return;
2912  }
2913  }
2914 
2915  /* Call application-specific response handler when available. */
2916  if (context->response_handler) {
2917  if (context->response_handler(context, session, sent, rcvd,
2918  rcvd->mid) == COAP_RESPONSE_FAIL)
2919  coap_send_rst(session, rcvd);
2920  else
2921  coap_send_ack(session, rcvd);
2922  }
2923  else {
2924  coap_send_ack(session, rcvd);
2925  }
2926 }
2927 
2928 #if !COAP_DISABLE_TCP
2929 static void
2931  coap_pdu_t *pdu) {
2932  coap_opt_iterator_t opt_iter;
2933  coap_opt_t *option;
2934  (void)context;
2935 
2936  coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
2937 
2938  if (pdu->code == COAP_SIGNALING_CODE_CSM) {
2939  while ((option = coap_option_next(&opt_iter))) {
2942  coap_opt_length(option)));
2943  } else if (opt_iter.number == COAP_SIGNALING_OPTION_BLOCK_WISE_TRANSFER) {
2944  session->csm_block_supported = 1;
2945  }
2946  }
2947  if (session->state == COAP_SESSION_STATE_CSM)
2948  coap_session_connected(session);
2949  } else if (pdu->code == COAP_SIGNALING_CODE_PING) {
2951  if (context->ping_handler) {
2952  context->ping_handler(context, session, pdu, pdu->mid);
2953  }
2954  if (pong) {
2956  coap_send(session, pong);
2957  }
2958  } else if (pdu->code == COAP_SIGNALING_CODE_PONG) {
2959  session->last_pong = session->last_rx_tx;
2960  if (context->pong_handler) {
2961  context->pong_handler(context, session, pdu, pdu->mid);
2962  }
2963  } else if (pdu->code == COAP_SIGNALING_CODE_RELEASE
2964  || pdu->code == COAP_SIGNALING_CODE_ABORT) {
2966  }
2967 }
2968 #endif /* !COAP_DISABLE_TCP */
2969 
2970 void
2972  coap_pdu_t *pdu) {
2973  coap_queue_t *sent = NULL;
2974  coap_pdu_t *response;
2975  coap_opt_filter_t opt_filter;
2976  int is_ping_rst;
2977 
2978  if (LOG_DEBUG <= coap_get_log_level()) {
2979  /* FIXME: get debug to work again **
2980  unsigned char addr[INET6_ADDRSTRLEN+8], localaddr[INET6_ADDRSTRLEN+8];
2981  if (coap_print_addr(remote, addr, INET6_ADDRSTRLEN+8) &&
2982  coap_print_addr(&packet->dst, localaddr, INET6_ADDRSTRLEN+8) )
2983  coap_log(LOG_DEBUG, "** received %d bytes from %s on interface %s:\n",
2984  (int)msg_len, addr, localaddr);
2985 
2986  */
2987  coap_show_pdu(LOG_DEBUG, pdu);
2988  }
2989 
2990  memset(&opt_filter, 0, sizeof(coap_opt_filter_t));
2991 
2992  switch (pdu->type) {
2993  case COAP_MESSAGE_ACK:
2994  /* find message id in sendqueue to stop retransmission */
2995  coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
2996 
2997  if (sent && session->con_active) {
2998  session->con_active--;
2999  if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3000  /* Flush out any entries on session->delayqueue */
3001  coap_session_connected(session);
3002  }
3003  if (coap_option_check_critical(context, pdu, opt_filter) == 0)
3004  goto cleanup;
3005 
3006  /* if sent code was >= 64 the message might have been a
3007  * notification. Then, we must flag the observer to be alive
3008  * by setting obs->fail_cnt = 0. */
3009  if (sent && COAP_RESPONSE_CLASS(sent->pdu->code) == 2) {
3010  const coap_binary_t token =
3011  { sent->pdu->token_length, sent->pdu->token };
3012  coap_touch_observer(context, sent->session, &token);
3013  }
3014 
3015  if (pdu->code == 0) {
3016  /* an empty ACK needs no further handling */
3017  goto cleanup;
3018  }
3019 
3020  break;
3021 
3022  case COAP_MESSAGE_RST:
3023  /* We have sent something the receiver disliked, so we remove
3024  * not only the message id but also the subscriptions we might
3025  * have. */
3026 
3027  is_ping_rst = 0;
3028  if (pdu->mid == session->last_ping_mid &&
3029  context->ping_timeout && session->last_ping > 0)
3030  is_ping_rst = 1;
3031 
3032  if (!is_ping_rst)
3033  coap_log(LOG_ALERT, "got RST for mid=0x%x\n", pdu->mid);
3034 
3035  if (session->con_active) {
3036  session->con_active--;
3037  if (session->state == COAP_SESSION_STATE_ESTABLISHED)
3038  /* Flush out any entries on session->delayqueue */
3039  coap_session_connected(session);
3040  }
3041 
3042  /* find message id in sendqueue to stop retransmission */
3043  coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
3044 
3045  if (sent) {
3046  coap_cancel(context, sent);
3047 
3048  if (!is_ping_rst) {
3049  if(sent->pdu->type==COAP_MESSAGE_CON && context->nack_handler)
3050  context->nack_handler(context, sent->session, sent->pdu,
3051  COAP_NACK_RST, sent->id);
3052  }
3053  else {
3054  if (context->pong_handler) {
3055  context->pong_handler(context, session, pdu, pdu->mid);
3056  }
3057  session->last_pong = session->last_rx_tx;
3058  session->last_ping_mid = COAP_INVALID_MID;
3059  }
3060  }
3061  else {
3062  /* Need to check is there is a subscription active and delete it */
3063  RESOURCES_ITER(context->resources, r) {
3064  coap_subscription_t *obs, *tmp;
3065  LL_FOREACH_SAFE(r->subscribers, obs, tmp) {
3066  if (obs->mid == pdu->mid && obs->session == session) {
3067  coap_binary_t token = { 0, NULL };
3068  COAP_SET_STR(&token, obs->token_length, obs->token);
3069  coap_delete_observer(r, session, &token);
3070  goto cleanup;
3071  }
3072  }
3073  }
3074  }
3075  goto cleanup;
3076 
3077  case COAP_MESSAGE_NON:
3078  /* find transaction in sendqueue in case large response */
3079  coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
3080  /* check for unknown critical options */
3081  if (coap_option_check_critical(context, pdu, opt_filter) == 0) {
3082  coap_send_rst(session, pdu);
3083  goto cleanup;
3084  }
3085  break;
3086 
3087  case COAP_MESSAGE_CON: /* check for unknown critical options */
3088  if (coap_option_check_critical(context, pdu, opt_filter) == 0) {
3089 
3090  if (COAP_PDU_IS_REQUEST(pdu)) {
3091  response =
3092  coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
3093 
3094  if (!response) {
3096  "coap_dispatch: cannot create error response\n");
3097  } else {
3098  if (coap_send(session, response) == COAP_INVALID_MID)
3099  coap_log(LOG_WARNING, "coap_dispatch: error sending response\n");
3100  }
3101  }
3102  else {
3103  coap_send_rst(session, pdu);
3104  }
3105 
3106  goto cleanup;
3107  }
3108  default: break;
3109  }
3110 
3111  /* Pass message to upper layer if a specific handler was
3112  * registered for a request that should be handled locally. */
3113 #if !COAP_DISABLE_TCP
3114  if (COAP_PDU_IS_SIGNALING(pdu))
3115  handle_signaling(context, session, pdu);
3116  else
3117 #endif /* !COAP_DISABLE_TCP */
3118  if (COAP_PDU_IS_REQUEST(pdu))
3119  handle_request(context, session, pdu);
3120  else if (COAP_PDU_IS_RESPONSE(pdu))
3121  handle_response(context, session, sent ? sent->pdu : NULL, pdu);
3122  else {
3123  if (COAP_PDU_IS_EMPTY(pdu)) {
3124  if (context->ping_handler) {
3125  context->ping_handler(context, session,
3126  pdu, pdu->mid);
3127  }
3128  }
3129  coap_log(LOG_DEBUG, "dropped message with invalid code (%d.%02d)\n",
3130  COAP_RESPONSE_CLASS(pdu->code),
3131  pdu->code & 0x1f);
3132 
3133  if (!coap_is_mcast(&session->addr_info.local)) {
3134  if (COAP_PDU_IS_EMPTY(pdu)) {
3135  if (session->proto != COAP_PROTO_TCP && session->proto != COAP_PROTO_TLS) {
3136  coap_tick_t now;
3137  coap_ticks(&now);
3138  if (session->last_tx_rst + COAP_TICKS_PER_SECOND/4 < now) {
3140  session->last_tx_rst = now;
3141  }
3142  }
3143  }
3144  else {
3146  }
3147  }
3148  }
3149 
3150 cleanup:
3151  coap_delete_node(sent);
3152 }
3153 
3154 int
3156  coap_log(LOG_DEBUG, "***EVENT: 0x%04x\n", event);
3157 
3158  if (context->handle_event) {
3159  return context->handle_event(context, event, session);
3160  } else {
3161  return 0;
3162  }
3163 }
3164 
3165 int
3167  coap_endpoint_t *ep;
3168  coap_session_t *s, *rtmp;
3169  if (!context)
3170  return 1;
3171  if (context->sendqueue)
3172  return 0;
3173  LL_FOREACH(context->endpoint, ep) {
3174  SESSIONS_ITER(ep->sessions, s, rtmp) {
3175  if (s->delayqueue)
3176  return 0;
3177  if (s->lg_xmit)
3178  return 0;
3179  }
3180  }
3181  SESSIONS_ITER(context->sessions, s, rtmp) {
3182  if (s->delayqueue)
3183  return 0;
3184  if (s->lg_xmit)
3185  return 0;
3186  }
3187  return 1;
3188 }
3189 #ifndef WITHOUT_ASYNC
3192  coap_tick_t next_due = 0;
3193  coap_async_t *async, *tmp;
3194 
3195  LL_FOREACH_SAFE(context->async_state, async, tmp) {
3196  if (async->delay <= now) {
3197  /* Send off the request to the application */
3198  handle_request(context, async->session, async->pdu);
3199 
3200  /* Remove this async entry as it has now fired */
3201  coap_free_async(context, async);
3202  }
3203  else {
3204  if (next_due == 0 || next_due > async->delay - now)
3205  next_due = async->delay - now;
3206  }
3207  }
3208  return next_due;
3209 }
3210 #endif /* WITHOUT_ASYNC */
3211 
3212 static int coap_started = 0;
3213 
3214 void coap_startup(void) {
3215  coap_tick_t now;
3216  uint64_t us;
3217  if (coap_started)
3218  return;
3219  coap_started = 1;
3220 #if defined(HAVE_WINSOCK2_H)
3221  WORD wVersionRequested = MAKEWORD(2, 2);
3222  WSADATA wsaData;
3223  WSAStartup(wVersionRequested, &wsaData);
3224 #endif
3225  coap_clock_init();
3226  coap_ticks(&now);
3227  us = coap_ticks_to_rt_us(now);
3228  /* Be accurate to the nearest (approx) us */
3229  coap_prng_init((unsigned int)us);
3230  coap_memory_init();
3232 }
3233 
3234 void coap_cleanup(void) {
3235 #if defined(HAVE_WINSOCK2_H)
3236  WSACleanup();
3237 #endif
3239 }
3240 
3241 void
3243  coap_response_handler_t handler) {
3244  context->response_handler = handler;
3245 }
3246 
3247 void
3249  coap_nack_handler_t handler) {
3250  context->nack_handler = handler;
3251 }
3252 
3253 void
3255  coap_ping_handler_t handler) {
3256  context->ping_handler = handler;
3257 }
3258 
3259 void
3261  coap_pong_handler_t handler) {
3262  context->pong_handler = handler;
3263 }
3264 
3265 void
3266 coap_register_option(coap_context_t *ctx, uint16_t type) {
3268 }
3269 
3270 #if ! defined WITH_CONTIKI && ! defined WITH_LWIP && ! defined RIOT_VERSION
3271 int
3272 coap_join_mcast_group_intf(coap_context_t *ctx, const char *group_name,
3273  const char *ifname) {
3274  struct ip_mreq mreq4;
3275  struct ipv6_mreq mreq6;
3276  struct addrinfo *resmulti = NULL, hints, *ainfo;
3277  int result = -1;
3278  coap_endpoint_t *endpoint;
3279  int mgroup_setup = 0;
3280 
3281  /* Need to have at least one endpoint! */
3282  assert(ctx->endpoint);
3283  if (!ctx->endpoint)
3284  return -1;
3285 
3286  /* Default is let the kernel choose */
3287  mreq6.ipv6mr_interface = 0;
3288  mreq4.imr_interface.s_addr = INADDR_ANY;
3289 
3290  memset(&hints, 0, sizeof(hints));
3291  hints.ai_socktype = SOCK_DGRAM;
3292 
3293  /* resolve the multicast group address */
3294  result = getaddrinfo(group_name, NULL, &hints, &resmulti);
3295 
3296  if (result != 0) {
3297  coap_log(LOG_ERR,
3298  "coap_join_mcast_group_intf: %s: "
3299  "Cannot resolve multicast address: %s\n",
3300  group_name, gai_strerror(result));
3301  goto finish;
3302  }
3303 
3304 /* Need to do a windows equivalent at some point */
3305 #ifndef _WIN32
3306  if (ifname) {
3307  /* interface specified - check if we have correct IPv4/IPv6 information */
3308  int done_ip4 = 0;
3309  int done_ip6 = 0;
3310 #if defined(ESPIDF_VERSION)
3311  struct netif *netif;
3312 #else /* !ESPIDF_VERSION */
3313  int ip4fd;
3314  struct ifreq ifr;
3315 #endif /* !ESPIDF_VERSION */
3316 
3317  /* See which mcast address family types are being asked for */
3318  for (ainfo = resmulti; ainfo != NULL && !(done_ip4 == 1 && done_ip6 == 1);
3319  ainfo = ainfo->ai_next) {
3320  switch (ainfo->ai_family) {
3321  case AF_INET6:
3322  if (done_ip6)
3323  break;
3324  done_ip6 = 1;
3325 #if defined(ESPIDF_VERSION)
3326  netif = netif_find(ifname);
3327  if (netif)
3328  mreq6.ipv6mr_interface = netif_get_index(netif);
3329  else
3330  coap_log(LOG_ERR,
3331  "coap_join_mcast_group_intf: %s: "
3332  "Cannot get IPv4 address: %s\n",
3333  ifname, coap_socket_strerror());
3334 #else /* !ESPIDF_VERSION */
3335  memset (&ifr, 0, sizeof(ifr));
3336  strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
3337  ifr.ifr_name[IFNAMSIZ - 1] = '\000';
3338 
3339 #ifdef HAVE_IF_NAMETOINDEX
3340  mreq6.ipv6mr_interface = if_nametoindex(ifr.ifr_name);
3341  if (mreq6.ipv6mr_interface == 0) {
3342  coap_log(LOG_WARNING, "coap_join_mcast_group_intf: "
3343  "cannot get interface index for '%s'\n",
3344  ifname);
3345  }
3346 #else /* !HAVE_IF_NAMETOINDEX */
3347  result = ioctl(ctx->endpoint->sock.fd, SIOCGIFINDEX, &ifr);
3348  if (result != 0) {
3349  coap_log(LOG_WARNING, "coap_join_mcast_group_intf: "
3350  "cannot get interface index for '%s': %s\n",
3351  ifname, coap_socket_strerror());
3352  }
3353  else {
3354  /* Capture the IPv6 if_index for later */
3355  mreq6.ipv6mr_interface = ifr.ifr_ifindex;
3356  }
3357 #endif /* !HAVE_IF_NAMETOINDEX */
3358 #endif /* !ESPIDF_VERSION */
3359  break;
3360  case AF_INET:
3361  if (done_ip4)
3362  break;
3363  done_ip4 = 1;
3364 #if defined(ESPIDF_VERSION)
3365  netif = netif_find(ifname);
3366  if (netif)
3367  mreq4.imr_interface.s_addr = netif_ip4_addr(netif)->addr;
3368  else
3369  coap_log(LOG_ERR,
3370  "coap_join_mcast_group_intf: %s: "
3371  "Cannot get IPv4 address: %s\n",
3372  ifname, coap_socket_strerror());
3373 #else /* !ESPIDF_VERSION */
3374  /*
3375  * Need an AF_INET socket to do this unfortunately to stop
3376  * "Invalid argument" error if AF_INET6 socket is used for SIOCGIFADDR
3377  */
3378  ip4fd = socket(AF_INET, SOCK_DGRAM, 0);
3379  if (ip4fd == -1) {
3380  coap_log(LOG_ERR,
3381  "coap_join_mcast_group_intf: %s: socket: %s\n",
3382  ifname, coap_socket_strerror());
3383  continue;
3384  }
3385  memset (&ifr, 0, sizeof(ifr));
3386  strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
3387  ifr.ifr_name[IFNAMSIZ - 1] = '\000';
3388  result = ioctl(ip4fd, SIOCGIFADDR, &ifr);
3389  if (result != 0) {
3390  coap_log(LOG_ERR,
3391  "coap_join_mcast_group_intf: %s: "
3392  "Cannot get IPv4 address: %s\n",
3393  ifname, coap_socket_strerror());
3394  }
3395  else {
3396  /* Capture the IPv4 address for later */
3397  mreq4.imr_interface = ((struct sockaddr_in*)&ifr.ifr_addr)->sin_addr;
3398  }
3399  close(ip4fd);
3400 #endif /* !ESPIDF_VERSION */
3401  break;
3402  default:
3403  break;
3404  }
3405  }
3406  }
3407 #endif /* ! _WIN32 */
3408 
3409  /* Add in mcast address(es) to appropriate interface */
3410  for (ainfo = resmulti; ainfo != NULL; ainfo = ainfo->ai_next) {
3411  LL_FOREACH(ctx->endpoint, endpoint) {
3412  /* Only UDP currently supported */
3413  if (endpoint->proto == COAP_PROTO_UDP) {
3414  coap_address_t gaddr;
3415 
3416  coap_address_init(&gaddr);
3417  if (ainfo->ai_family == AF_INET6) {
3418  if (!ifname) {
3419  if(endpoint->bind_addr.addr.sa.sa_family == AF_INET6) {
3420  /*
3421  * Do it on the ifindex that the server is listening on
3422  * (sin6_scope_id could still be 0)
3423  */
3424  mreq6.ipv6mr_interface =
3425  endpoint->bind_addr.addr.sin6.sin6_scope_id;
3426  }
3427  else {
3428  mreq6.ipv6mr_interface = 0;
3429  }
3430  }
3431  gaddr.addr.sin6.sin6_family = AF_INET6;
3432  gaddr.addr.sin6.sin6_port = endpoint->bind_addr.addr.sin6.sin6_port;
3433  gaddr.addr.sin6.sin6_addr = mreq6.ipv6mr_multiaddr =
3434  ((struct sockaddr_in6 *)ainfo->ai_addr)->sin6_addr;
3435  result = setsockopt(endpoint->sock.fd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
3436  (char *)&mreq6, sizeof(mreq6));
3437  }
3438  else if (ainfo->ai_family == AF_INET) {
3439  if (!ifname) {
3440  if(endpoint->bind_addr.addr.sa.sa_family == AF_INET) {
3441  /*
3442  * Do it on the interface that the server is listening on
3443  * (sin_addr could still be INADDR_ANY)
3444  */
3445  mreq4.imr_interface = endpoint->bind_addr.addr.sin.sin_addr;
3446  }
3447  else {
3448  mreq4.imr_interface.s_addr = INADDR_ANY;
3449  }
3450  }
3451  gaddr.addr.sin.sin_family = AF_INET;
3452  gaddr.addr.sin.sin_port = endpoint->bind_addr.addr.sin.sin_port;
3453  gaddr.addr.sin.sin_addr.s_addr = mreq4.imr_multiaddr.s_addr =
3454  ((struct sockaddr_in *)ainfo->ai_addr)->sin_addr.s_addr;
3455  result = setsockopt(endpoint->sock.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3456  (char *)&mreq4, sizeof(mreq4));
3457  }
3458  else {
3459  continue;
3460  }
3461 
3462  if (result == COAP_SOCKET_ERROR) {
3463  coap_log(LOG_ERR,
3464  "coap_join_mcast_group_intf: %s: setsockopt: %s\n",
3465  group_name, coap_socket_strerror());
3466  }
3467  else {
3468  char addr_str[INET6_ADDRSTRLEN + 8 + 1];
3469 
3470  addr_str[sizeof(addr_str)-1] = '\000';
3471  if (coap_print_addr(&gaddr, (uint8_t*)addr_str,
3472  sizeof(addr_str) - 1)) {
3473  if (ifname)
3474  coap_log(LOG_DEBUG, "added mcast group %s i/f %s\n", addr_str,
3475  ifname);
3476  else
3477  coap_log(LOG_DEBUG, "added mcast group %s\n", addr_str);
3478  }
3479  mgroup_setup = 1;
3480  }
3481  }
3482  }
3483  }
3484  if (!mgroup_setup) {
3485  result = -1;
3486  }
3487 
3488  finish:
3489  freeaddrinfo(resmulti);
3490 
3491  return result;
3492 }
3493 
3494 int
3495 coap_mcast_set_hops(coap_session_t *session, size_t hops) {
3496  if (session && coap_is_mcast(&session->addr_info.remote)) {
3497  switch (session->addr_info.remote.addr.sa.sa_family) {
3498  case AF_INET:
3499  if (setsockopt(session->sock.fd, IPPROTO_IP, IP_MULTICAST_TTL,
3500  (const char *)&hops, sizeof(hops)) < 0) {
3501  coap_log(LOG_INFO, "coap_mcast_set_hops: %zu: setsockopt: %s\n",
3502  hops, coap_socket_strerror());
3503  return 0;
3504  }
3505  return 1;
3506  case AF_INET6:
3507  if (setsockopt(session->sock.fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
3508  (const char *)&hops, sizeof(hops)) < 0) {
3509  coap_log(LOG_INFO, "coap_mcast_set_hops: %zu: setsockopt: %s\n",
3510  hops, coap_socket_strerror());
3511  return 0;
3512  }
3513  return 1;
3514  default:
3515  break;
3516  }
3517  }
3518  return 0;
3519 }
3520 #else /* defined WITH_CONTIKI || defined WITH_LWIP */
3521 int
3523  const char *group_name COAP_UNUSED,
3524  const char *ifname COAP_UNUSED) {
3525  return -1;
3526 }
3527 int
3529  size_t hops COAP_UNUSED) {
3530  return 0;
3531 }
3532 #endif /* defined WITH_CONTIKI || defined WITH_LWIP */
3533 
3534 #ifdef WITH_CONTIKI
3535 
3536 /*---------------------------------------------------------------------------*/
3537 /* CoAP message retransmission */
3538 /*---------------------------------------------------------------------------*/
3539 PROCESS_THREAD(coap_retransmit_process, ev, data) {
3540  coap_tick_t now;
3541  coap_queue_t *nextpdu;
3542 
3543  PROCESS_BEGIN();
3544 
3545  coap_log(LOG_DEBUG, "Started retransmit process\n");
3546 
3547  while (1) {
3548  PROCESS_YIELD();
3549  if (ev == PROCESS_EVENT_TIMER) {
3550  if (etimer_expired(&the_coap_context.retransmit_timer)) {
3551 
3552  nextpdu = coap_peek_next(&the_coap_context);
3553 
3554  coap_ticks(&now);
3555  while (nextpdu && nextpdu->t <= now) {
3556  coap_retransmit(&the_coap_context, coap_pop_next(&the_coap_context));
3557  nextpdu = coap_peek_next(&the_coap_context);
3558  }
3559 
3560  /* need to set timer to some value even if no nextpdu is available */
3561  etimer_set(&the_coap_context.retransmit_timer,
3562  nextpdu ? nextpdu->t - now : 0xFFFF);
3563  }
3564  if (etimer_expired(&the_coap_context.notify_timer)) {
3565  coap_check_notify(&the_coap_context);
3566  etimer_reset(&the_coap_context.notify_timer);
3567  }
3568  }
3569  }
3570 
3571  PROCESS_END();
3572 }
3573 /*---------------------------------------------------------------------------*/
3574 
3575 #endif /* WITH_CONTIKI */
3576 
3577 #ifdef WITH_LWIP
3578 /* FIXME: retransmits that are not required any more due to incoming packages
3579  * do *not* get cleared at the moment, the wakeup when the transmission is due
3580  * is silently accepted. this is mainly due to the fact that the required
3581  * checks are similar in two places in the code (when receiving ACK and RST)
3582  * and that they cause more than one patch chunk, as it must be first checked
3583  * whether the sendqueue item to be dropped is the next one pending, and later
3584  * the restart function has to be called. nothing insurmountable, but it can
3585  * also be implemented when things have stabilized, and the performance
3586  * penality is minimal
3587  *
3588  * also, this completely ignores COAP_RESOURCE_CHECK_TIME.
3589  * */
3590 
3591 static void coap_retransmittimer_execute(void *arg) {
3592  coap_context_t *ctx = (coap_context_t*)arg;
3593  coap_tick_t now;
3594  coap_tick_t elapsed;
3595  coap_queue_t *nextinqueue;
3596 
3597  ctx->timer_configured = 0;
3598 
3599  coap_ticks(&now);
3600 
3601  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 */
3602 
3603  nextinqueue = coap_peek_next(ctx);
3604  while (nextinqueue != NULL) {
3605  if (nextinqueue->t > elapsed) {
3606  nextinqueue->t -= elapsed;
3607  break;
3608  } else {
3609  elapsed -= nextinqueue->t;
3610  coap_retransmit(ctx, coap_pop_next(ctx));
3611  nextinqueue = coap_peek_next(ctx);
3612  }
3613  }
3614 
3615  ctx->sendqueue_basetime = now;
3616 
3617  coap_retransmittimer_restart(ctx);
3618 }
3619 
3620 static void coap_retransmittimer_restart(coap_context_t *ctx) {
3621  coap_tick_t now, elapsed, delay;
3622 
3623  if (ctx->timer_configured) {
3624  printf("clearing\n");
3625  sys_untimeout(coap_retransmittimer_execute, (void*)ctx);
3626  ctx->timer_configured = 0;
3627  }
3628  if (ctx->sendqueue != NULL) {
3629  coap_ticks(&now);
3630  elapsed = now - ctx->sendqueue_basetime;
3631  if (ctx->sendqueue->t >= elapsed) {
3632  delay = ctx->sendqueue->t - elapsed;
3633  } else {
3634  /* a strange situation, but not completely impossible.
3635  *
3636  * this happens, for example, right after
3637  * coap_retransmittimer_execute, when a retransmission
3638  * was *just not yet* due, and the clock ticked before
3639  * our coap_ticks was called.
3640  *
3641  * not trying to retransmit anything now, as it might
3642  * cause uncontrollable recursion; let's just try again
3643  * with the next main loop run.
3644  * */
3645  delay = 0;
3646  }
3647 
3648  printf("scheduling for %d ticks\n", delay);
3649  sys_timeout(delay, coap_retransmittimer_execute, (void*)ctx);
3650  ctx->timer_configured = 1;
3651  }
3652 }
3653 #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:1504
#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:1738
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:1799
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_binary_t *token, coap_string_t *query, coap_method_handler_t h, int *added_block)
Definition: block.c:1240
void coap_block_delete_lg_crcv(coap_session_t *session, coap_lg_crcv_t *lg_crcv)
Definition: block.c:880
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:1630
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:1970
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:969
coap_lg_crcv_t * coap_block_new_lg_crcv(coap_session_t *session, coap_pdu_t *pdu)
Definition: block.c:828
int coap_handle_response_send_block(coap_session_t *session, coap_pdu_t *rcvd)
Definition: block.c:1466
@ COAP_RECURSE_OK
int coap_get_block(coap_pdu_t *pdu, coap_option_num_t number, coap_block_t *block)
Initializes block from pdu.
Definition: block.c:35
#define COAP_MAX_BLOCK_SZX
The largest value for the SZX component in a Block option.
Definition: block.h:27
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:63
#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:3191
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:133
coap_async_t * coap_find_async(coap_context_t *context, coap_session_t *session, coap_binary_t token)
Retrieves the object identified by token from the list of asynchronous transactions that are register...
Definition: async.c:107
void coap_free_async(coap_context_t *context, coap_async_t *s)
Releases the memory that was allocated by coap_async_state_init() for the object async.
Definition: async.c:118
coap_async_t * coap_register_async(coap_context_t *context, coap_session_t *session, 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
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_context_t *, coap_resource_t *, coap_session_t *, coap_pdu_t *, coap_binary_t *, coap_string_t *, coap_pdu_t *)
Definition of message handler function.
Definition: resource.h:41
#define COAP_PRINT_STATUS_ERROR
Definition: resource.h:329
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:1935
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:2187
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:2971
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:944
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:1337
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:2016
coap_mid_t coap_wait_ack(coap_context_t *context, coap_session_t *session, coap_queue_t *node)
Definition: net.c:970
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:1979
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:1898
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
coap_pdu_t * coap_new_error_response(coap_pdu_t *request, unsigned char code, coap_opt_filter_t *opts)
Creates a new ACK PDU with specified error code.
Definition: net.c:2057
unsigned int coap_context_get_max_idle_sessions(const coap_context_t *context)
Get the maximum idle sessions count.
Definition: net.c:456
coap_response_t(* coap_response_handler_t)(coap_context_t *context, coap_session_t *session, coap_pdu_t *sent, coap_pdu_t *received, const coap_mid_t id)
Response handler that is used as callback in coap_context_t.
Definition: net.h:53
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:3166
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:3242
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
void(* coap_pong_handler_t)(coap_context_t *context, coap_session_t *session, coap_pdu_t *received, const coap_mid_t id)
Received Pong handler that is used as callback in coap_context_t.
Definition: net.h:95
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:3155
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:3495
coap_mid_t coap_send_message_type(coap_session_t *session, coap_pdu_t *request, unsigned char type)
Helper function to create and send a message with type (usually ACK or RST).
Definition: net.c:918
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
coap_mid_t coap_send_ack(coap_session_t *session, coap_pdu_t *request)
Sends an ACK message with code 0 for the specified request to dst.
Definition: net.c:750
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
unsigned int coap_context_get_session_timeout(const coap_context_t *context)
Get the session timeout value.
Definition: net.c:489
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:3254
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:3266
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:3272
coap_mid_t coap_send_error(coap_session_t *session, coap_pdu_t *request, unsigned char code, coap_opt_filter_t *opts)
Sends an error response with code code for request request to dst.
Definition: net.c:900
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
void(* coap_nack_handler_t)(coap_context_t *context, coap_session_t *session, coap_pdu_t *sent, coap_nack_reason_t reason, const coap_mid_t id)
Negative Acknowedge handler that is used as callback in coap_context_t.
Definition: net.h:68
coap_mid_t coap_send_large(coap_session_t *session, coap_pdu_t *pdu)
Sends a CoAP message to given peer.
Definition: net.c:1054
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
COAP_STATIC_INLINE coap_mid_t coap_send_rst(coap_session_t *session, coap_pdu_t *request)
Sends an RST message with code 0 for the specified request to dst.
Definition: net.h:457
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:3260
coap_mid_t coap_send(coap_session_t *session, coap_pdu_t *pdu)
Sends a CoAP message to given peer.
Definition: net.c:1154
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:3248
void(* coap_ping_handler_t)(coap_context_t *context, coap_session_t *session, coap_pdu_t *received, const coap_mid_t id)
Received Ping handler that is used as callback in coap_context_t.
Definition: net.h:82
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:692
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:235
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:29
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
size_t coap_print_addr(const struct 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_session_str(const coap_session_t *session)
Get session description.
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
#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:555
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:1046
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:1109
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:1048
respond_t
Internal flags to control the treatment of responses (specifically in presence of the No-Response opt...
Definition: net.c:2362
@ RESPONSE_DROP
Definition: net.c:2362
@ RESPONSE_DEFAULT
Definition: net.c:2362
@ RESPONSE_SEND
Definition: net.c:2362
static void handle_request(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu)
Definition: net.c:2482
static coap_str_const_t coap_default_uri_wellknown
Definition: net.c:2477
static int coap_read_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now)
Definition: net.c:1678
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:2169
#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:3234
#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:2184
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:2340
static int coap_started
Definition: net.c:3212
static int coap_accept_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now)
Definition: net.c:1729
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:1721
static int coap_handle_dgram_for_proto(coap_context_t *ctx, coap_session_t *session, coap_packet_t *packet)
Definition: net.c:1428
static void coap_write_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now)
Definition: net.c:1484
static void coap_connect_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now)
Definition: net.c:1447
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:2410
static void handle_signaling(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu)
Definition: net.c:2930
#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:1534
void coap_startup(void)
Definition: net.c:3214
#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:2889
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.
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:303
coap_bin_const_t key
Definition: coap_dtls.h:305
coap_bin_const_t identity
Definition: coap_dtls.h:304
coap_dtls_cpsk_info_t psk_info
Client PSK definition.
Definition: coap_dtls.h:363
The structure used for defining the PKI setup data to be used.
Definition: coap_dtls.h:240
uint8_t version
Definition: coap_dtls.h:241
The structure that holds the Server Pre-Shared Key and Identity Hint information.
Definition: coap_dtls.h:370
coap_bin_const_t hint
Definition: coap_dtls.h:371
coap_bin_const_t key
Definition: coap_dtls.h:372
The structure used for defining the Server PSK setup data to be used.
Definition: coap_dtls.h:421
coap_dtls_spsk_info_t psk_info
Server PSK definition.
Definition: coap_dtls.h:451
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.
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
#define HASH_ITER(hh, head, el, tmp)
Definition: uthash.h:1059
#define LL_DELETE(head, del)
Definition: utlist.h:385
#define LL_FOREACH(head, el)
Definition: utlist.h:413
#define LL_PREPEND(head, add)
Definition: utlist.h:314
#define LL_FOREACH_SAFE(head, el, tmp)
Definition: utlist.h:419