libcoap  4.3.0beta
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 "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_NETINET_IN_H
31 #include <netinet/in.h>
32 #endif
33 #ifdef HAVE_ARPA_INET_H
34 #include <arpa/inet.h>
35 #endif
36 #ifdef COAP_EPOLL_SUPPORT
37 #include <sys/epoll.h>
38 #include <sys/timerfd.h>
39 #endif /* COAP_EPOLL_SUPPORT */
40 #ifdef HAVE_WS2TCPIP_H
41 #include <ws2tcpip.h>
42 #endif
43 
44 #ifdef HAVE_NETDB_H
45 #include <netdb.h>
46 #endif
47 
48 #ifdef WITH_LWIP
49 #include <lwip/pbuf.h>
50 #include <lwip/udp.h>
51 #include <lwip/timeouts.h>
52 #endif
53 
54 #ifndef INET6_ADDRSTRLEN
55 #define INET6_ADDRSTRLEN 40
56 #endif
57 
58 #ifndef min
59 #define min(a,b) ((a) < (b) ? (a) : (b))
60 #endif
61 
66 #define FRAC_BITS 6
67 
72 #define MAX_BITS 8
73 
74 #if FRAC_BITS > 8
75 #error FRAC_BITS must be less or equal 8
76 #endif
77 
79 #define Q(frac,fval) ((uint16_t)(((1 << (frac)) * fval.integer_part) + \
80  ((1 << (frac)) * fval.fractional_part + 500)/1000))
81 
83 #define ACK_RANDOM_FACTOR \
84  Q(FRAC_BITS, session->ack_random_factor)
85 
87 #define ACK_TIMEOUT Q(FRAC_BITS, session->ack_timeout)
88 
89 #if !defined(WITH_LWIP) && !defined(WITH_CONTIKI)
90 
94 }
95 
99 }
100 #endif /* !defined(WITH_LWIP) && !defined(WITH_CONTIKI) */
101 
102 #ifdef WITH_LWIP
103 
104 #include <lwip/memp.h>
105 
106 static void coap_retransmittimer_execute(void *arg);
107 static void coap_retransmittimer_restart(coap_context_t *ctx);
108 
111  return (coap_queue_t *)memp_malloc(MEMP_COAP_NODE);
112 }
113 
116  memp_free(MEMP_COAP_NODE, node);
117 }
118 
119 #endif /* WITH_LWIP */
120 #ifdef WITH_CONTIKI
121 # ifndef DEBUG
122 # define DEBUG DEBUG_PRINT
123 # endif /* DEBUG */
124 
125 #include "net/ip/uip-debug.h"
126 
127 #define UIP_IP_BUF ((struct uip_ip_hdr *)&uip_buf[UIP_LLH_LEN])
128 #define UIP_UDP_BUF ((struct uip_udp_hdr *)&uip_buf[UIP_LLIPH_LEN])
129 
130 void coap_resources_init();
131 
132 unsigned char initialized = 0;
133 coap_context_t the_coap_context;
134 
135 PROCESS(coap_retransmit_process, "message retransmit process");
136 
140 }
141 
144  coap_free_type(COAP_NODE, node);
145 }
146 #endif /* WITH_CONTIKI */
147 
148 unsigned int
150  unsigned int result = 0;
151  coap_tick_diff_t delta = now - ctx->sendqueue_basetime;
152 
153  if (ctx->sendqueue) {
154  /* delta < 0 means that the new time stamp is before the old. */
155  if (delta <= 0) {
156  ctx->sendqueue->t -= delta;
157  } else {
158  /* This case is more complex: The time must be advanced forward,
159  * thus possibly leading to timed out elements at the queue's
160  * start. For every element that has timed out, its relative
161  * time is set to zero and the result counter is increased. */
162 
163  coap_queue_t *q = ctx->sendqueue;
164  coap_tick_t t = 0;
165  while (q && (t + q->t < (coap_tick_t)delta)) {
166  t += q->t;
167  q->t = 0;
168  result++;
169  q = q->next;
170  }
171 
172  /* finally adjust the first element that has not expired */
173  if (q) {
174  q->t = (coap_tick_t)delta - t;
175  }
176  }
177  }
178 
179  /* adjust basetime */
180  ctx->sendqueue_basetime += delta;
181 
182  return result;
183 }
184 
185 int
187  coap_queue_t *p, *q;
188  if (!queue || !node)
189  return 0;
190 
191  /* set queue head if empty */
192  if (!*queue) {
193  *queue = node;
194  return 1;
195  }
196 
197  /* replace queue head if PDU's time is less than head's time */
198  q = *queue;
199  if (node->t < q->t) {
200  node->next = q;
201  *queue = node;
202  q->t -= node->t; /* make q->t relative to node->t */
203  return 1;
204  }
205 
206  /* search for right place to insert */
207  do {
208  node->t -= q->t; /* make node-> relative to q->t */
209  p = q;
210  q = q->next;
211  } while (q && q->t <= node->t);
212 
213  /* insert new item */
214  if (q) {
215  q->t -= node->t; /* make q->t relative to node->t */
216  }
217  node->next = q;
218  p->next = node;
219  return 1;
220 }
221 
222 int
224  if (!node)
225  return 0;
226 
227  coap_delete_pdu(node->pdu);
228  if ( node->session ) {
229  /*
230  * Need to remove out of context->sendqueue as added in by coap_wait_ack()
231  */
232  if (node->session->context->sendqueue) {
233  LL_DELETE(node->session->context->sendqueue, node);
234  }
236  }
237  coap_free_node(node);
238 
239  return 1;
240 }
241 
242 void
244  if (!queue)
245  return;
246 
247  coap_delete_all(queue->next);
248  coap_delete_node(queue);
249 }
250 
251 coap_queue_t *
253  coap_queue_t *node;
254  node = coap_malloc_node();
255 
256  if (!node) {
257  coap_log(LOG_WARNING, "coap_new_node: malloc failed\n");
258  return NULL;
259  }
260 
261  memset(node, 0, sizeof(*node));
262  return node;
263 }
264 
265 coap_queue_t *
267  if (!context || !context->sendqueue)
268  return NULL;
269 
270  return context->sendqueue;
271 }
272 
273 coap_queue_t *
275  coap_queue_t *next;
276 
277  if (!context || !context->sendqueue)
278  return NULL;
279 
280  next = context->sendqueue;
281  context->sendqueue = context->sendqueue->next;
282  if (context->sendqueue) {
283  context->sendqueue->t += next->t;
284  }
285  next->next = NULL;
286  return next;
287 }
288 
289 static size_t
291  const coap_session_t *session,
292  const uint8_t *hint, size_t hint_len,
293  uint8_t *identity, size_t *identity_len, size_t max_identity_len,
294  uint8_t *psk, size_t max_psk_len
295 ) {
296  const coap_dtls_cpsk_info_t *psk_info;
297  (void)hint;
298  (void)hint_len;
299 
300  if (session->psk_identity && session->psk_key) {
301  if (session->psk_identity->length <= max_identity_len &&
302  session->psk_key->length <= max_psk_len) {
303  memcpy(identity, session->psk_identity->s, session->psk_identity->length);
304  memcpy(psk, session->psk_key->s, session->psk_key->length);
305  *identity_len = session->psk_identity->length;
306  return session->psk_key->length;
307  }
308  }
309  psk_info = &session->cpsk_setup_data.psk_info;
310  if (psk_info->identity.s && psk_info->identity.length > 0 &&
311  psk_info->key.s && psk_info->key.length > 0) {
312  if (psk_info->identity.length <= max_identity_len &&
313  psk_info->key.length <= max_psk_len) {
314  memcpy(identity, psk_info->identity.s, psk_info->identity.length);
315  memcpy(psk, psk_info->key.s, psk_info->key.length);
316  *identity_len = psk_info->identity.length;
317  return psk_info->key.length;
318  }
319  }
320  /* Not defined in coap_new_client_session_psk2() */
321  *identity_len = 0;
322  return 0;
323 }
324 
325 static size_t
327  const coap_session_t *session,
328  const uint8_t *identity, size_t identity_len,
329  uint8_t *psk, size_t max_psk_len
330 ) {
331  const coap_dtls_spsk_info_t *psk_info;
332  (void)identity;
333  (void)identity_len;
334 
335  if (!session)
336  return 0;
337 
338  if (session->psk_key &&
339  session->psk_key->length <= max_psk_len) {
340  memcpy(psk, session->psk_key->s, session->psk_key->length);
341  return session->psk_key->length;
342  }
343  psk_info = &session->context->spsk_setup_data.psk_info;
344  if (psk_info->key.s && psk_info->key.length > 0 &&
345  psk_info->key.length <= max_psk_len) {
346  memcpy(psk, psk_info->key.s, psk_info->key.length);
347  return psk_info->key.length;
348  }
349  /* Not defined in coap_context_set_psk2() */
350  return 0;
351 }
352 
353 static size_t
355  const coap_session_t *session,
356  uint8_t *hint, size_t max_hint_len
357 ) {
358  const coap_dtls_spsk_info_t *psk_info;
359 
360  if (!session)
361  return 0;
362 
363  if (session->psk_hint &&
364  session->psk_hint->s && session->psk_hint->length > 0 &&
365  session->psk_hint->length <= max_hint_len) {
366  memcpy(hint, session->psk_hint->s, session->psk_hint->length);
367  return session->psk_hint->length;
368  }
369  psk_info = &session->context->spsk_setup_data.psk_info;
370  if (psk_info->hint.s &&
371  psk_info->hint.length > 0 &&
372  psk_info->hint.length <= max_hint_len) {
373  memcpy(hint, psk_info->hint.s, psk_info->hint.length);
374  return psk_info->hint.length;
375  }
376  /* Not defined in coap_context_set_psk2() */
377  return 0;
378 }
379 
381  const char *hint,
382  const uint8_t *key, size_t key_len
383 ) {
384  coap_dtls_spsk_t setup_data;
385 
386  memset (&setup_data, 0, sizeof(setup_data));
387  if (hint) {
388  setup_data.psk_info.hint.s = (const uint8_t *)hint;
389  setup_data.psk_info.hint.length = strlen(hint);
390  }
391 
392  if (key && key_len > 0) {
393  setup_data.psk_info.key.s = key;
394  setup_data.psk_info.key.length = key_len;
395  }
396 
397  return coap_context_set_psk2(ctx, &setup_data);
398 }
399 
401  coap_dtls_spsk_t *setup_data
402 ) {
403  if (!setup_data)
404  return 0;
405 
406  ctx->spsk_setup_data = *setup_data;
407 
408  if (coap_dtls_is_supported()) {
409  return coap_dtls_context_set_spsk(ctx, setup_data);
410  }
411  return 0;
412 }
413 
415  const coap_dtls_pki_t* setup_data
416 ) {
417  if (!setup_data)
418  return 0;
419  if (setup_data->version != COAP_DTLS_PKI_SETUP_VERSION) {
420  coap_log(LOG_ERR, "coap_context_set_pki: Wrong version of setup_data\n");
421  return 0;
422  }
423  if (coap_dtls_is_supported()) {
424  return coap_dtls_context_set_pki(ctx, setup_data, COAP_DTLS_ROLE_SERVER);
425  }
426  return 0;
427 }
428 
430  const char *ca_file,
431  const char *ca_dir
432 ) {
433  if (coap_dtls_is_supported()) {
434  return coap_dtls_context_set_pki_root_cas(ctx, ca_file, ca_dir);
435  }
436  return 0;
437 }
438 
439 void coap_context_set_keepalive(coap_context_t *context, unsigned int seconds) {
440  context->ping_timeout = seconds;
441 }
442 
444 #ifdef COAP_EPOLL_SUPPORT
445  return context->epfd;
446 #else /* ! COAP_EPOLL_SUPPORT */
447  (void)context;
448  return -1;
449 #endif /* ! COAP_EPOLL_SUPPORT */
450 }
451 
454  const coap_address_t *listen_addr) {
455  coap_context_t *c;
456 
457 #ifdef WITH_CONTIKI
458  if (initialized)
459  return NULL;
460 #endif /* WITH_CONTIKI */
461 
462  coap_startup();
463 
464 #ifndef WITH_CONTIKI
466 #endif /* not WITH_CONTIKI */
467 
468 #ifndef WITH_CONTIKI
469  if (!c) {
470  coap_log(LOG_EMERG, "coap_init: malloc: failed\n");
471  return NULL;
472  }
473 #endif /* not WITH_CONTIKI */
474 #ifdef WITH_CONTIKI
475  coap_resources_init();
476 
477  c = &the_coap_context;
478  initialized = 1;
479 #endif /* WITH_CONTIKI */
480 
481  memset(c, 0, sizeof(coap_context_t));
482 
483 #ifdef COAP_EPOLL_SUPPORT
484  c->epfd = epoll_create1(0);
485  if (c->epfd == -1) {
486  coap_log(LOG_ERR, "coap_new_context: Unable to epoll_create: %s (%d)\n",
488  errno);
489  goto onerror;
490  }
491  if (c->epfd != -1) {
492  c->eptimerfd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK);
493  if (c->eptimerfd == -1) {
494  coap_log(LOG_ERR, "coap_new_context: Unable to timerfd_create: %s (%d)\n",
496  errno);
497  goto onerror;
498  }
499  else {
500  int ret;
501  struct epoll_event event;
502 
503  /* Needed if running 32bit as ptr is only 32bit */
504  memset(&event, 0, sizeof(event));
505  event.events = EPOLLIN;
506  /* We special case this event by setting to NULL */
507  event.data.ptr = NULL;
508 
509  ret = epoll_ctl(c->epfd, EPOLL_CTL_ADD, c->eptimerfd, &event);
510  if (ret == -1) {
512  "%s: epoll_ctl ADD failed: %s (%d)\n",
513  "coap_new_context",
514  coap_socket_strerror(), errno);
515  goto onerror;
516  }
517  }
518  }
519 #endif /* COAP_EPOLL_SUPPORT */
520 
521  if (coap_dtls_is_supported()) {
523  if (!c->dtls_context) {
524  coap_log(LOG_EMERG, "coap_init: no DTLS context available\n");
526  return NULL;
527  }
528  }
529 
530  /* set default CSM timeout */
531  c->csm_timeout = 30;
532 
533  if (listen_addr) {
534  coap_endpoint_t *endpoint = coap_new_endpoint(c, listen_addr, COAP_PROTO_UDP);
535  if (endpoint == NULL) {
536  goto onerror;
537  }
538  }
539 
540 #if !defined(WITH_LWIP)
543 #endif
544 
548 
549 #ifdef WITH_CONTIKI
550  process_start(&coap_retransmit_process, (char *)c);
551 
552  PROCESS_CONTEXT_BEGIN(&coap_retransmit_process);
553 #ifndef WITHOUT_OBSERVE
554  etimer_set(&c->notify_timer, COAP_RESOURCE_CHECK_TIME * COAP_TICKS_PER_SECOND);
555 #endif /* WITHOUT_OBSERVE */
556  /* the retransmit timer must be initialized to some large value */
557  etimer_set(&the_coap_context.retransmit_timer, 0xFFFF);
558  PROCESS_CONTEXT_END(&coap_retransmit_process);
559 #endif /* WITH_CONTIKI */
560 
561  return c;
562 
563 onerror:
565  return NULL;
566 }
567 
568 void
569 coap_set_app_data(coap_context_t *ctx, void *app_data) {
570  assert(ctx);
571  ctx->app = app_data;
572 }
573 
574 void *
576  assert(ctx);
577  return ctx->app;
578 }
579 
580 void
582  coap_endpoint_t *ep, *tmp;
583  coap_session_t *sp, *rtmp;
584  coap_cache_entry_t *cp, *ctmp;
585 
586  if (!context)
587  return;
588 
589  coap_delete_all(context->sendqueue);
590 
591 #ifdef WITH_LWIP
592  context->sendqueue = NULL;
593  coap_retransmittimer_restart(context);
594 #endif
595 
596  coap_delete_all_resources(context);
597 
598 #ifndef WITHOUT_ASYNC
599  coap_delete_all_async(context);
600 #endif /* WITHOUT_ASYNC */
601  HASH_ITER(hh, context->cache, cp, ctmp) {
602  coap_delete_cache_entry(context, cp);
603  }
604  if (context->cache_ignore_count) {
606  }
607 
608  LL_FOREACH_SAFE(context->endpoint, ep, tmp) {
609  coap_free_endpoint(ep);
610  }
611 
612  SESSIONS_ITER_SAFE(context->sessions, sp, rtmp) {
614  }
615 
616  if (context->dtls_context)
618 #ifdef COAP_EPOLL_SUPPORT
619  if (context->eptimerfd != -1) {
620  int ret;
621  struct epoll_event event;
622 
623  /* Kernels prior to 2.6.9 expect non NULL event parameter */
624  ret = epoll_ctl(context->epfd, EPOLL_CTL_DEL, context->eptimerfd, &event);
625  if (ret == -1) {
627  "%s: epoll_ctl DEL failed: %s (%d)\n",
628  "coap_free_context",
629  coap_socket_strerror(), errno);
630  }
631  close(context->eptimerfd);
632  context->eptimerfd = -1;
633  }
634  if (context->epfd != -1) {
635  close(context->epfd);
636  context->epfd = -1;
637  }
638 #endif /* COAP_EPOLL_SUPPORT */
639 
640 #ifndef WITH_CONTIKI
641  coap_free_type(COAP_CONTEXT, context);
642 #else /* WITH_CONTIKI */
643  memset(&the_coap_context, 0, sizeof(coap_context_t));
644  initialized = 0;
645 #endif /* WITH_CONTIKI */
646 }
647 
648 int
650  coap_pdu_t *pdu,
651  coap_opt_filter_t unknown) {
652 
653  coap_opt_iterator_t opt_iter;
654  int ok = 1;
655 
656  coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
657 
658  while (coap_option_next(&opt_iter)) {
659 
660  /* The following condition makes use of the fact that
661  * coap_option_getb() returns -1 if type exceeds the bit-vector
662  * filter. As the vector is supposed to be large enough to hold
663  * the largest known option, we know that everything beyond is
664  * bad.
665  */
666  if (opt_iter.type & 0x01) {
667  /* first check the built-in critical options */
668  switch (opt_iter.type) {
675  case COAP_OPTION_ACCEPT:
678  case COAP_OPTION_BLOCK2:
679  case COAP_OPTION_BLOCK1:
680  break;
681  default:
682  if (coap_option_filter_get(ctx->known_options, opt_iter.type) <= 0) {
683  coap_log(LOG_DEBUG, "unknown critical option %d\n", opt_iter.type);
684  ok = 0;
685 
686  /* When opt_iter.type is beyond our known option range,
687  * coap_option_filter_set() will return -1 and we are safe to leave
688  * this loop. */
689  if (coap_option_filter_set(unknown, opt_iter.type) == -1) {
690  break;
691  }
692  }
693  }
694  }
695  }
696 
697  return ok;
698 }
699 
702  coap_pdu_t *response;
703  coap_tid_t result = COAP_INVALID_TID;
704 
705  if (request && request->type == COAP_MESSAGE_CON &&
706  COAP_PROTO_NOT_RELIABLE(session->proto)) {
707  response = coap_pdu_init(COAP_MESSAGE_ACK, 0, request->tid, 0);
708  if (response)
709  result = coap_send(session, response);
710  }
711  return result;
712 }
713 
714 ssize_t
716  ssize_t bytes_written = -1;
717  assert(pdu->hdr_size > 0);
718  switch(session->proto) {
719  case COAP_PROTO_UDP:
720  bytes_written = coap_session_send(session, pdu->token - pdu->hdr_size,
721  pdu->used_size + pdu->hdr_size);
722  break;
723  case COAP_PROTO_DTLS:
724  bytes_written = coap_dtls_send(session, pdu->token - pdu->hdr_size,
725  pdu->used_size + pdu->hdr_size);
726  break;
727  case COAP_PROTO_TCP:
728 #if !COAP_DISABLE_TCP
729  bytes_written = coap_session_write(session, pdu->token - pdu->hdr_size,
730  pdu->used_size + pdu->hdr_size);
731 #endif /* !COAP_DISABLE_TCP */
732  break;
733  case COAP_PROTO_TLS:
734 #if !COAP_DISABLE_TCP
735  bytes_written = coap_tls_write(session, pdu->token - pdu->hdr_size,
736  pdu->used_size + pdu->hdr_size);
737 #endif /* !COAP_DISABLE_TCP */
738  break;
739  default:
740  break;
741  }
742  coap_show_pdu(LOG_DEBUG, pdu);
743  return bytes_written;
744 }
745 
746 static ssize_t
748  ssize_t bytes_written;
749 
750 #ifdef WITH_LWIP
751 
752  coap_socket_t *sock = &session->sock;
753  if (sock->flags == COAP_SOCKET_EMPTY) {
754  assert(session->endpoint != NULL);
755  sock = &session->endpoint->sock;
756  }
757 
758  bytes_written = coap_socket_send_pdu(sock, session, pdu);
759  if (bytes_written >= 0 && pdu->type == COAP_MESSAGE_CON &&
760  COAP_PROTO_NOT_RELIABLE(session->proto))
761  session->con_active++;
762 
763  if (LOG_DEBUG <= coap_get_log_level()) {
764  coap_show_pdu(LOG_DEBUG, pdu);
765  }
766  coap_ticks(&session->last_rx_tx);
767 
768 #else
769 
770  /* Do not send error responses for requests that were received via
771  * IP multicast.
772  * FIXME: If No-Response option indicates interest, these responses
773  * must not be dropped. */
774  if (coap_is_mcast(&session->addr_info.local) &&
775  COAP_RESPONSE_CLASS(pdu->code) > 2) {
776  return COAP_DROPPED_RESPONSE;
777  }
778 
779  if (session->state == COAP_SESSION_STATE_NONE) {
780  if (session->proto == COAP_PROTO_DTLS && !session->tls) {
781  session->tls = coap_dtls_new_client_session(session);
782  if (session->tls) {
784  return coap_session_delay_pdu(session, pdu, node);
785  }
786  coap_handle_event(session->context, COAP_EVENT_DTLS_ERROR, session);
787  return -1;
788 #if !COAP_DISABLE_TCP
789  } else if(COAP_PROTO_RELIABLE(session->proto)) {
791  &session->sock, &session->local_if, &session->addr_info.remote,
793  &session->addr_info.local, &session->addr_info.remote
794  )) {
795  coap_handle_event(session->context, COAP_EVENT_TCP_FAILED, session);
796  return -1;
797  }
798  session->last_ping = 0;
799  session->last_pong = 0;
800  session->csm_tx = 0;
801  coap_ticks( &session->last_rx_tx );
802  if ((session->sock.flags & COAP_SOCKET_WANT_CONNECT) != 0) {
804  return coap_session_delay_pdu(session, pdu, node);
805  }
807  if (session->proto == COAP_PROTO_TLS) {
808  int connected = 0;
810  session->tls = coap_tls_new_client_session(session, &connected);
811  if (session->tls) {
812  if (connected) {
814  coap_session_send_csm(session);
815  }
816  return coap_session_delay_pdu(session, pdu, node);
817  }
818  coap_handle_event(session->context, COAP_EVENT_DTLS_ERROR, session);
820  return -1;
821  } else {
822  coap_session_send_csm(session);
823  }
824 #endif /* !COAP_DISABLE_TCP */
825  } else {
826  return -1;
827  }
828  }
829 
830  if (pdu->type == COAP_MESSAGE_CON &&
831  (session->sock.flags & COAP_SOCKET_NOT_EMPTY) &&
832  (session->sock.flags & COAP_SOCKET_MULTICAST)) {
833  /* Violates RFC72522 8.1 */
834  coap_log(LOG_ERR, "Multicast requests cannot be Confirmable (RFC7252 8.1)\n");
835  return -1;
836  }
837 
838  if (session->state != COAP_SESSION_STATE_ESTABLISHED ||
839  (pdu->type == COAP_MESSAGE_CON && session->con_active >= COAP_DEFAULT_NSTART)) {
840  return coap_session_delay_pdu(session, pdu, node);
841  }
842 
843  if ((session->sock.flags & COAP_SOCKET_NOT_EMPTY) &&
844  (session->sock.flags & COAP_SOCKET_WANT_WRITE))
845  return coap_session_delay_pdu(session, pdu, node);
846 
847  bytes_written = coap_session_send_pdu(session, pdu);
848  if (bytes_written >= 0 && pdu->type == COAP_MESSAGE_CON &&
849  COAP_PROTO_NOT_RELIABLE(session->proto))
850  session->con_active++;
851 
852 #endif /* WITH_LWIP */
853 
854  return bytes_written;
855 }
856 
859  coap_pdu_t *request,
860  unsigned char code,
861  coap_opt_filter_t opts) {
862  coap_pdu_t *response;
863  coap_tid_t result = COAP_INVALID_TID;
864 
865  assert(request);
866  assert(session);
867 
868  response = coap_new_error_response(request, code, opts);
869  if (response)
870  result = coap_send(session, response);
871 
872  return result;
873 }
874 
876 coap_send_message_type(coap_session_t *session, coap_pdu_t *request, unsigned char type) {
877  coap_pdu_t *response;
878  coap_tid_t result = COAP_INVALID_TID;
879 
880  if (request) {
881  response = coap_pdu_init(type, 0, request->tid, 0);
882  if (response)
883  result = coap_send(session, response);
884  }
885  return result;
886 }
887 
901 unsigned int
902 coap_calc_timeout(coap_session_t *session, unsigned char r) {
903  unsigned int result;
904 
905  /* The integer 1.0 as a Qx.FRAC_BITS */
906 #define FP1 Q(FRAC_BITS, ((coap_fixed_point_t){1,0}))
907 
908  /* rounds val up and right shifts by frac positions */
909 #define SHR_FP(val,frac) (((val) + (1 << ((frac) - 1))) >> (frac))
910 
911  /* Inner term: multiply ACK_RANDOM_FACTOR by Q0.MAX_BITS[r] and
912  * make the result a rounded Qx.FRAC_BITS */
913  result = SHR_FP((ACK_RANDOM_FACTOR - FP1) * r, MAX_BITS);
914 
915  /* Add 1 to the inner term and multiply with ACK_TIMEOUT, then
916  * make the result a rounded Qx.FRAC_BITS */
917  result = SHR_FP(((result + FP1) * ACK_TIMEOUT), FRAC_BITS);
918 
919  /* Multiply with COAP_TICKS_PER_SECOND to yield system ticks
920  * (yields a Qx.FRAC_BITS) and shift to get an integer */
921  return SHR_FP((COAP_TICKS_PER_SECOND * result), FRAC_BITS);
922 
923 #undef FP1
924 #undef SHR_FP
925 }
926 
929  coap_queue_t *node) {
930  coap_tick_t now;
931 
932  node->session = coap_session_reference(session);
933 
934  /* Set timer for pdu retransmission. If this is the first element in
935  * the retransmission queue, the base time is set to the current
936  * time and the retransmission time is node->timeout. If there is
937  * already an entry in the sendqueue, we must check if this node is
938  * to be retransmitted earlier. Therefore, node->timeout is first
939  * normalized to the base time and then inserted into the queue with
940  * an adjusted relative time.
941  */
942  coap_ticks(&now);
943  if (context->sendqueue == NULL) {
944  node->t = node->timeout << node->retransmit_cnt;
945  context->sendqueue_basetime = now;
946  } else {
947  /* make node->t relative to context->sendqueue_basetime */
948  node->t = (now - context->sendqueue_basetime) +
949  (node->timeout << node->retransmit_cnt);
950  }
951 
952  coap_insert_node(&context->sendqueue, node);
953 
954 #ifdef WITH_LWIP
955  if (node == context->sendqueue) /* don't bother with timer stuff if there are earlier retransmits */
956  coap_retransmittimer_restart(context);
957 #endif
958 
959 #ifdef WITH_CONTIKI
960  { /* (re-)initialize retransmission timer */
961  coap_queue_t *nextpdu;
962 
963  nextpdu = coap_peek_next(context);
964  assert(nextpdu); /* we have just inserted a node */
965 
966  /* must set timer within the context of the retransmit process */
967  PROCESS_CONTEXT_BEGIN(&coap_retransmit_process);
968  etimer_set(&context->retransmit_timer, nextpdu->t);
969  PROCESS_CONTEXT_END(&coap_retransmit_process);
970  }
971 #endif /* WITH_CONTIKI */
972 
973  coap_log(LOG_DEBUG, "** %s: mid=0x%x: added to retransmit queue (%ums)\n",
974  coap_session_str(node->session), node->id,
975  (unsigned)(node->t * 1000 / COAP_TICKS_PER_SECOND));
976 
977 #ifdef COAP_EPOLL_SUPPORT
978  if (context->eptimerfd != -1) {
979  coap_ticks(&now);
980  if (context->next_timeout == 0 ||
981  context->next_timeout > now + (node->t * 1000 / COAP_TICKS_PER_SECOND)) {
982  struct itimerspec new_value;
983  int ret;
984 
985  context->next_timeout = now + (node->t * 1000 / COAP_TICKS_PER_SECOND);
986  memset(&new_value, 0, sizeof(new_value));
987  coap_tick_t rem_timeout = (node->t * 1000 / COAP_TICKS_PER_SECOND);
988  /* Need to trigger an event on context->epfd in the future */
989  new_value.it_value.tv_sec = rem_timeout / 1000;
990  new_value.it_value.tv_nsec = (rem_timeout % 1000) * 1000000;
991  ret = timerfd_settime(context->eptimerfd, 0, &new_value, NULL);
992  if (ret == -1) {
994  "%s: timerfd_settime failed: %s (%d)\n",
995  "coap_wait_ack",
996  coap_socket_strerror(), errno);
997  }
998  }
999  }
1000 #endif /* COAP_EPOLL_SUPPORT */
1001 
1002  return node->id;
1003 }
1004 
1005 coap_tid_t
1007  uint8_t r;
1008  ssize_t bytes_written;
1009 
1010  if (pdu->code == COAP_RESPONSE_CODE(508)) {
1011  /*
1012  * Need to prepend our IP identifier to the data as per
1013  * https://www.rfc-editor.org/rfc/rfc8768.html#section-4
1014  */
1015  char addr_str[INET6_ADDRSTRLEN + 8 + 1];
1016  coap_opt_iterator_t opt_iter;
1017  coap_opt_t *opt;
1018  size_t hop_limit;
1019 
1020  addr_str[sizeof(addr_str)-1] = '\000';
1021  if (coap_print_addr(&session->addr_info.local, (uint8_t*)addr_str,
1022  sizeof(addr_str) - 1)) {
1023  char *cp;
1024  int len;
1025 
1026  if (addr_str[0] == '[') {
1027  cp = strchr(addr_str, ']');
1028  if (cp) *cp = '\000';
1029  if (memcmp(&addr_str[1], "::ffff:", 7) == 0) {
1030  /* IPv4 embedded into IPv6 */
1031  cp = &addr_str[8];
1032  }
1033  else {
1034  cp = &addr_str[1];
1035  }
1036  }
1037  else {
1038  cp = strchr(addr_str, ':');
1039  if (cp) *cp = '\000';
1040  cp = addr_str;
1041  }
1042  len = strlen(cp);
1043 
1044  /* See if Hop Limit option is being used in return path */
1045  opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
1046  if (opt) {
1047  uint8_t buf[4];
1048 
1049  hop_limit =
1051  if (hop_limit == 1) {
1052  coap_log(LOG_WARNING, "Proxy loop detected '%s'\n",
1053  (char*)pdu->data);
1054  coap_delete_pdu(pdu);
1056  }
1057  else if (hop_limit < 1 || hop_limit > 255) {
1058  /* Something is bad - need to drop this pdu (TODO or delete option) */
1059  coap_log(LOG_WARNING, "Proxy return has bad hop limit count '%zu'\n",
1060  hop_limit);
1061  coap_delete_pdu(pdu);
1063  }
1064  hop_limit--;
1066  coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
1067  buf);
1068  }
1069 
1070  /* Need to check that we are not seeing this proxy in the return loop */
1071  if (pdu->data && opt == NULL) {
1072  if (pdu->used_size + 1 <= pdu->max_size) {
1073  char *a_match;
1074  size_t data_len = pdu->used_size - (pdu->data - pdu->token);
1075  pdu->data[data_len] = '\000';
1076  a_match = strstr((char*)pdu->data, cp);
1077  if (a_match && (a_match == (char*)pdu->data || a_match[-1] == ' ') &&
1078  ((size_t)(a_match - (char*)pdu->data + len) == data_len ||
1079  a_match[len] == ' ')) {
1080  coap_log(LOG_WARNING, "Proxy loop detected '%s'\n",
1081  (char*)pdu->data);
1082  coap_delete_pdu(pdu);
1084  }
1085  }
1086  }
1087  if (pdu->used_size + len + 1 <= pdu->max_size) {
1088  size_t old_size = pdu->used_size;
1089  if (coap_pdu_resize(pdu, pdu->used_size + len + 1)) {
1090  if (pdu->data == NULL) {
1091  /*
1092  * Set Hop Limit to max for return path. If this libcoap is in
1093  * a proxy loop path, it will always decrement hop limit in code
1094  * above and hence timeout / drop the response as appropriate
1095  */
1096  hop_limit = 255;
1098  (uint8_t *)&hop_limit);
1099  coap_add_data(pdu, len, (uint8_t*)cp);
1100  }
1101  else {
1102  /* prepend with space separator, leaving hop limit "as is" */
1103  memmove(pdu->data + len + 1, pdu->data,
1104  old_size - (pdu->data - pdu->token));
1105  memcpy(pdu->data, cp, len);
1106  pdu->data[len] = ' ';
1107  pdu->used_size += len + 1;
1108  }
1109  }
1110  }
1111  }
1112  }
1113 
1114  if (!coap_pdu_encode_header(pdu, session->proto)) {
1115  goto error;
1116  }
1117 
1118 #if !COAP_DISABLE_TCP
1119  if (COAP_PROTO_RELIABLE(session->proto) &&
1120  session->state == COAP_SESSION_STATE_ESTABLISHED &&
1121  !session->csm_block_supported) {
1122  /*
1123  * Need to check that this instance is not sending any block options as the
1124  * remote end via CSM has not informed us that there is support
1125  * https://tools.ietf.org/html/rfc8323#section-5.3.2
1126  * Note that this also includes BERT which is application specific.
1127  */
1128  coap_opt_iterator_t opt_iter;
1129 
1130  if (coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter) != NULL) {
1132  "Remote end did not indicate CSM support for BLOCK1 enabled\n");
1133  }
1134  if (coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter) != NULL) {
1136  "Remote end did not indicate CSM support for BLOCK2 enabled\n");
1137  }
1138  }
1139 #endif /* !COAP_DISABLE_TCP */
1140 
1141  bytes_written = coap_send_pdu( session, pdu, NULL );
1142 
1143  if (bytes_written == COAP_PDU_DELAYED) {
1144  /* do not free pdu as it is stored with session for later use */
1145  return pdu->tid;
1146  }
1147 
1148  if (bytes_written < 0) {
1149  coap_delete_pdu(pdu);
1150  return (coap_tid_t)bytes_written;
1151  }
1152 
1153 #if !COAP_DISABLE_TCP
1154  if (COAP_PROTO_RELIABLE(session->proto) &&
1155  (size_t)bytes_written < pdu->used_size + pdu->hdr_size) {
1156  if (coap_session_delay_pdu(session, pdu, NULL) == COAP_PDU_DELAYED) {
1157  session->partial_write = (size_t)bytes_written;
1158  /* do not free pdu as it is stored with session for later use */
1159  return pdu->tid;
1160  } else {
1161  goto error;
1162  }
1163  }
1164 #endif /* !COAP_DISABLE_TCP */
1165 
1166  if (pdu->type != COAP_MESSAGE_CON
1167  || COAP_PROTO_RELIABLE(session->proto)) {
1168  coap_tid_t id = pdu->tid;
1169  coap_delete_pdu(pdu);
1170  return id;
1171  }
1172 
1173  coap_queue_t *node = coap_new_node();
1174  if (!node) {
1175  coap_log(LOG_DEBUG, "coap_wait_ack: insufficient memory\n");
1176  goto error;
1177  }
1178 
1179  node->id = pdu->tid;
1180  node->pdu = pdu;
1181  coap_prng(&r, sizeof(r));
1182  /* add timeout in range [ACK_TIMEOUT...ACK_TIMEOUT * ACK_RANDOM_FACTOR] */
1183  node->timeout = coap_calc_timeout(session, r);
1184  return coap_wait_ack(session->context, session, node);
1185  error:
1186  coap_delete_pdu(pdu);
1187  return COAP_INVALID_TID;
1188 }
1189 
1190 coap_tid_t
1192  if (!context || !node)
1193  return COAP_INVALID_TID;
1194 
1195  /* re-initialize timeout when maximum number of retransmissions are not reached yet */
1196  if (node->retransmit_cnt < node->session->max_retransmit) {
1197  ssize_t bytes_written;
1198  coap_tick_t now;
1199 
1200  node->retransmit_cnt++;
1201  coap_ticks(&now);
1202  if (context->sendqueue == NULL) {
1203  node->t = node->timeout << node->retransmit_cnt;
1204  context->sendqueue_basetime = now;
1205  } else {
1206  /* make node->t relative to context->sendqueue_basetime */
1207  node->t = (now - context->sendqueue_basetime) + (node->timeout << node->retransmit_cnt);
1208  }
1209  coap_insert_node(&context->sendqueue, node);
1210 #ifdef WITH_LWIP
1211  if (node == context->sendqueue) /* don't bother with timer stuff if there are earlier retransmits */
1212  coap_retransmittimer_restart(context);
1213 #endif
1214 
1215  coap_log(LOG_DEBUG, "** %s: mid=0x%x: retransmission #%d\n",
1216  coap_session_str(node->session), node->id, node->retransmit_cnt);
1217 
1218  if (node->session->con_active)
1219  node->session->con_active--;
1220  bytes_written = coap_send_pdu(node->session, node->pdu, node);
1221 
1222  if (bytes_written == COAP_PDU_DELAYED) {
1223  /* PDU was not retransmitted immediately because a new handshake is
1224  in progress. node was moved to the send queue of the session. */
1225  return node->id;
1226  }
1227 
1228  if (bytes_written < 0)
1229  return (int)bytes_written;
1230 
1231  return node->id;
1232  }
1233 
1234  /* no more retransmissions, remove node from system */
1235 
1236 #ifndef WITH_CONTIKI
1237  coap_log(LOG_DEBUG, "** %s: mid=0x%x: give up after %d attempts\n",
1238  coap_session_str(node->session), node->id, node->retransmit_cnt);
1239 #endif
1240 
1241 #ifndef WITHOUT_OBSERVE
1242  /* Check if subscriptions exist that should be canceled after
1243  COAP_MAX_NOTIFY_FAILURES */
1244  if (node->pdu->code >= 64) {
1245  coap_binary_t token = { 0, NULL };
1246 
1247  token.length = node->pdu->token_length;
1248  token.s = node->pdu->token;
1249 
1250  coap_handle_failed_notify(context, node->session, &token);
1251  }
1252 #endif /* WITHOUT_OBSERVE */
1253  if (node->session->con_active) {
1254  node->session->con_active--;
1256  /*
1257  * As there may be another CON in a different queue entry on the same
1258  * session that needs to be immediately released,
1259  * coap_session_connected() is called.
1260  * However, there is the possibility coap_wait_ack() may be called for
1261  * this node (queue) and re-added to context->sendqueue.
1262  * coap_delete_node(node) called shortly will handle this and remove it.
1263  */
1265  }
1266  }
1267 
1268  /* And finally delete the node */
1269  if (node->pdu->type == COAP_MESSAGE_CON && context->nack_handler)
1270  context->nack_handler(context, node->session, node->pdu, COAP_NACK_TOO_MANY_RETRIES, node->id);
1271  coap_delete_node(node);
1272  return COAP_INVALID_TID;
1273 }
1274 
1275 #ifdef WITH_LWIP
1276 /* WITH_LWIP, this is handled by coap_recv in a different way */
1277 void
1279  return;
1280 }
1281 #else /* WITH_LWIP */
1282 
1283 static int
1285  uint8_t *data;
1286  size_t data_len;
1287  int result = -1;
1288 
1289  coap_packet_get_memmapped(packet, &data, &data_len);
1290 
1291  if (session->proto == COAP_PROTO_DTLS) {
1292  if (session->type == COAP_SESSION_TYPE_HELLO)
1293  result = coap_dtls_hello(session, data, data_len);
1294  else if (session->tls)
1295  result = coap_dtls_receive(session, data, data_len);
1296  } else if (session->proto == COAP_PROTO_UDP) {
1297  result = coap_handle_dgram(ctx, session, data, data_len);
1298  }
1299  return result;
1300 }
1301 
1302 static void
1304  coap_session_t *session,
1305  coap_tick_t now) {
1306  (void)ctx;
1307 #if COAP_DISABLE_TCP
1308  (void)session;
1309  (void)now;
1310 #else /* !COAP_DISABLE_TCP */
1311  if (coap_socket_connect_tcp2(&session->sock, &session->addr_info.local,
1312  &session->addr_info.remote)) {
1313  session->last_rx_tx = now;
1315  if (session->proto == COAP_PROTO_TCP) {
1316  coap_session_send_csm(session);
1317  } else if (session->proto == COAP_PROTO_TLS) {
1318  int connected = 0;
1320  session->tls = coap_tls_new_client_session(session, &connected);
1321  if (session->tls) {
1322  if (connected) {
1324  session);
1325  coap_session_send_csm(session);
1326  }
1327  } else {
1328  coap_handle_event(session->context, COAP_EVENT_DTLS_ERROR, session);
1330  }
1331  }
1332  } else {
1333  coap_handle_event(session->context, COAP_EVENT_TCP_FAILED, session);
1335  }
1336 #endif /* !COAP_DISABLE_TCP */
1337 }
1338 
1339 static void
1341  (void)ctx;
1342  assert(session->sock.flags & COAP_SOCKET_CONNECTED);
1343 
1344  while (session->delayqueue) {
1345  ssize_t bytes_written;
1346  coap_queue_t *q = session->delayqueue;
1347  coap_log(LOG_DEBUG, "** %s: mid=0x%x: transmitted after delay\n",
1348  coap_session_str(session), (int)q->pdu->tid);
1349  assert(session->partial_write < q->pdu->used_size + q->pdu->hdr_size);
1350  switch (session->proto) {
1351  case COAP_PROTO_TCP:
1352 #if !COAP_DISABLE_TCP
1353  bytes_written = coap_session_write(
1354  session,
1355  q->pdu->token - q->pdu->hdr_size - session->partial_write,
1356  q->pdu->used_size + q->pdu->hdr_size - session->partial_write
1357  );
1358 #endif /* !COAP_DISABLE_TCP */
1359  break;
1360  case COAP_PROTO_TLS:
1361 #if !COAP_DISABLE_TCP
1362  bytes_written = coap_tls_write(
1363  session,
1364  q->pdu->token - q->pdu->hdr_size - session->partial_write,
1365  q->pdu->used_size + q->pdu->hdr_size - session->partial_write
1366  );
1367 #endif /* !COAP_DISABLE_TCP */
1368  break;
1369  default:
1370  bytes_written = -1;
1371  break;
1372  }
1373  if (bytes_written > 0)
1374  session->last_rx_tx = now;
1375  if (bytes_written <= 0 || (size_t)bytes_written < q->pdu->used_size + q->pdu->hdr_size - session->partial_write) {
1376  if (bytes_written > 0)
1377  session->partial_write += (size_t)bytes_written;
1378  break;
1379  }
1380  session->delayqueue = q->next;
1381  session->partial_write = 0;
1382  coap_delete_node(q);
1383  }
1384 }
1385 
1386 static void
1388 #if COAP_CONSTRAINED_STACK
1389  static coap_mutex_t s_static_mutex = COAP_MUTEX_INITIALIZER;
1390  static coap_packet_t s_packet;
1391 #else /* ! COAP_CONSTRAINED_STACK */
1392  coap_packet_t s_packet;
1393 #endif /* ! COAP_CONSTRAINED_STACK */
1394  coap_packet_t *packet = &s_packet;
1395 
1396 #if COAP_CONSTRAINED_STACK
1397  coap_mutex_lock(&s_static_mutex);
1398 #endif /* COAP_CONSTRAINED_STACK */
1399 
1400  assert(session->sock.flags & (COAP_SOCKET_CONNECTED | COAP_SOCKET_MULTICAST));
1401 
1402  if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
1403  ssize_t bytes_read;
1404  memcpy(&packet->addr_info, &session->addr_info, sizeof(packet->addr_info));
1405  bytes_read = ctx->network_read(&session->sock, packet);
1406 
1407  if (bytes_read < 0) {
1408  if (bytes_read == -2)
1409  /* Reset the session back to startup defaults */
1411  else
1412  coap_log(LOG_WARNING, "* %s: read error\n",
1413  coap_session_str(session));
1414  } else if (bytes_read > 0) {
1415  session->last_rx_tx = now;
1416  memcpy(&session->addr_info, &packet->addr_info,
1417  sizeof(session->addr_info));
1418  coap_log(LOG_DEBUG, "* %s: received %zd bytes\n",
1419  coap_session_str(session), bytes_read);
1420  coap_handle_dgram_for_proto(ctx, session, packet);
1421  }
1422 #if !COAP_DISABLE_TCP
1423  } else {
1424  ssize_t bytes_read = 0;
1425  const uint8_t *p;
1426  int retry;
1427  /* adjust for LWIP */
1428  uint8_t *buf = packet->payload;
1429  size_t buf_len = sizeof(packet->payload);
1430 
1431  do {
1432  if (session->proto == COAP_PROTO_TCP)
1433  bytes_read = coap_socket_read(&session->sock, buf, buf_len);
1434  else if (session->proto == COAP_PROTO_TLS)
1435  bytes_read = coap_tls_read(session, buf, buf_len);
1436  if (bytes_read > 0) {
1437  coap_log(LOG_DEBUG, "* %s: received %zd bytes\n",
1438  coap_session_str(session), bytes_read);
1439  session->last_rx_tx = now;
1440  }
1441  p = buf;
1442  retry = bytes_read == (ssize_t)buf_len;
1443  while (bytes_read > 0) {
1444  if (session->partial_pdu) {
1445  size_t len = session->partial_pdu->used_size
1446  + session->partial_pdu->hdr_size
1447  - session->partial_read;
1448  size_t n = min(len, (size_t)bytes_read);
1449  memcpy(session->partial_pdu->token - session->partial_pdu->hdr_size
1450  + session->partial_read, p, n);
1451  p += n;
1452  bytes_read -= n;
1453  if (n == len) {
1454  if (coap_pdu_parse_header(session->partial_pdu, session->proto)
1455  && coap_pdu_parse_opt(session->partial_pdu)) {
1456  coap_dispatch(ctx, session, session->partial_pdu);
1457  }
1458  coap_delete_pdu(session->partial_pdu);
1459  session->partial_pdu = NULL;
1460  session->partial_read = 0;
1461  } else {
1462  session->partial_read += n;
1463  }
1464  } else if (session->partial_read > 0) {
1465  size_t hdr_size = coap_pdu_parse_header_size(session->proto,
1466  session->read_header);
1467  size_t len = hdr_size - session->partial_read;
1468  size_t n = min(len, (size_t)bytes_read);
1469  memcpy(session->read_header + session->partial_read, p, n);
1470  p += n;
1471  bytes_read -= n;
1472  if (n == len) {
1473  size_t size = coap_pdu_parse_size(session->proto, session->read_header,
1474  hdr_size);
1475  if (size > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
1477  "** %s: incoming PDU length too large (%zu > %lu)\n",
1478  coap_session_str(session),
1480  bytes_read = -1;
1481  break;
1482  }
1483  session->partial_pdu = coap_pdu_init(0, 0, 0, size);
1484  if (session->partial_pdu == NULL) {
1485  bytes_read = -1;
1486  break;
1487  }
1488  if (session->partial_pdu->alloc_size < size && !coap_pdu_resize(session->partial_pdu, size)) {
1489  bytes_read = -1;
1490  break;
1491  }
1492  session->partial_pdu->hdr_size = (uint8_t)hdr_size;
1493  session->partial_pdu->used_size = size;
1494  memcpy(session->partial_pdu->token - hdr_size, session->read_header, hdr_size);
1495  session->partial_read = hdr_size;
1496  if (size == 0) {
1497  if (coap_pdu_parse_header(session->partial_pdu, session->proto)) {
1498  coap_dispatch(ctx, session, session->partial_pdu);
1499  }
1500  coap_delete_pdu(session->partial_pdu);
1501  session->partial_pdu = NULL;
1502  session->partial_read = 0;
1503  }
1504  } else {
1505  session->partial_read += bytes_read;
1506  }
1507  } else {
1508  session->read_header[0] = *p++;
1509  bytes_read -= 1;
1510  if (!coap_pdu_parse_header_size(session->proto,
1511  session->read_header)) {
1512  bytes_read = -1;
1513  break;
1514  }
1515  session->partial_read = 1;
1516  }
1517  }
1518  } while (bytes_read == 0 && retry);
1519  if (bytes_read < 0)
1521 #endif /* !COAP_DISABLE_TCP */
1522  }
1523 #if COAP_CONSTRAINED_STACK
1524  coap_mutex_unlock(&s_static_mutex);
1525 #endif /* COAP_CONSTRAINED_STACK */
1526 }
1527 
1528 static int
1530  ssize_t bytes_read = -1;
1531  int result = -1; /* the value to be returned */
1532 #if COAP_CONSTRAINED_STACK
1533  static coap_mutex_t e_static_mutex = COAP_MUTEX_INITIALIZER;
1534  static coap_packet_t e_packet;
1535 #else /* ! COAP_CONSTRAINED_STACK */
1536  coap_packet_t e_packet;
1537 #endif /* ! COAP_CONSTRAINED_STACK */
1538  coap_packet_t *packet = &e_packet;
1539 
1540  assert(COAP_PROTO_NOT_RELIABLE(endpoint->proto));
1541  assert(endpoint->sock.flags & COAP_SOCKET_BOUND);
1542 
1543 #if COAP_CONSTRAINED_STACK
1544  coap_mutex_lock(&e_static_mutex);
1545 #endif /* COAP_CONSTRAINED_STACK */
1546 
1547  /* Need to do this as there may be holes in addr_info */
1548  memset(&packet->addr_info, 0, sizeof(packet->addr_info));
1550  coap_address_copy(&packet->addr_info.local, &endpoint->bind_addr);
1551  bytes_read = ctx->network_read(&endpoint->sock, packet);
1552 
1553  if (bytes_read < 0) {
1554  coap_log(LOG_WARNING, "* %s: read failed\n", coap_endpoint_str(endpoint));
1555  } else if (bytes_read > 0) {
1556  coap_session_t *session = coap_endpoint_get_session(endpoint, packet, now);
1557  if (session) {
1558  coap_log(LOG_DEBUG, "* %s: received %zd bytes\n",
1559  coap_session_str(session), bytes_read);
1560  result = coap_handle_dgram_for_proto(ctx, session, packet);
1561  if (endpoint->proto == COAP_PROTO_DTLS && session->type == COAP_SESSION_TYPE_HELLO && result == 1)
1562  coap_session_new_dtls_session(session, now);
1563  }
1564  }
1565 #if COAP_CONSTRAINED_STACK
1566  coap_mutex_unlock(&e_static_mutex);
1567 #endif /* COAP_CONSTRAINED_STACK */
1568  return result;
1569 }
1570 
1571 static int
1573  (void)ctx;
1574  (void)endpoint;
1575  (void)now;
1576  return 0;
1577 }
1578 
1579 static int
1581  coap_tick_t now) {
1582  coap_session_t *session = coap_new_server_session(ctx, endpoint);
1583  if (session)
1584  session->last_rx_tx = now;
1585  return session != NULL;
1586 }
1587 
1588 void
1590 #ifdef COAP_EPOLL_SUPPORT
1591  (void)ctx;
1592  (void)now;
1594  "coap_io_do_io() requires libcoap not compiled for using epoll\n");
1595 #else /* ! COAP_EPOLL_SUPPORT */
1596  coap_endpoint_t *ep, *tmp;
1597  coap_session_t *s, *rtmp;
1598 
1599  LL_FOREACH_SAFE(ctx->endpoint, ep, tmp) {
1600  if ((ep->sock.flags & COAP_SOCKET_CAN_READ) != 0)
1601  coap_read_endpoint(ctx, ep, now);
1602  if ((ep->sock.flags & COAP_SOCKET_CAN_WRITE) != 0)
1603  coap_write_endpoint(ctx, ep, now);
1604  if ((ep->sock.flags & COAP_SOCKET_CAN_ACCEPT) != 0)
1605  coap_accept_endpoint(ctx, ep, now);
1606  SESSIONS_ITER_SAFE(ep->sessions, s, rtmp) {
1607  if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0) {
1608  /* Make sure the session object is not deleted in one of the callbacks */
1610  coap_read_session(ctx, s, now);
1612  }
1613  if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0) {
1614  /* Make sure the session object is not deleted in one of the callbacks */
1616  coap_write_session(ctx, s, now);
1618  }
1619  }
1620  }
1621 
1622  SESSIONS_ITER_SAFE(ctx->sessions, s, rtmp) {
1623  if ((s->sock.flags & COAP_SOCKET_CAN_CONNECT) != 0) {
1624  /* Make sure the session object is not deleted in one of the callbacks */
1626  coap_connect_session(ctx, s, now);
1627  coap_session_release( s );
1628  }
1629  if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0) {
1630  /* Make sure the session object is not deleted in one of the callbacks */
1632  coap_read_session(ctx, s, now);
1634  }
1635  if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0) {
1636  /* Make sure the session object is not deleted in one of the callbacks */
1638  coap_write_session(ctx, s, now);
1639  coap_session_release( s );
1640  }
1641  }
1642 #endif /* ! COAP_EPOLL_SUPPORT */
1643 }
1644 
1645 /*
1646  * While this code in part replicates coap_io_do_io(), doing the functions
1647  * directly saves having to iterate through the endpoints / sessions.
1648  */
1649 void
1650 coap_io_do_epoll(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
1651 #ifndef COAP_EPOLL_SUPPORT
1652  (void)ctx;
1653  (void)events;
1654  (void)nevents;
1656  "coap_io_do_epoll() requires libcoap compiled for using epoll\n");
1657 #else /* COAP_EPOLL_SUPPORT */
1658  coap_tick_t now;
1659  size_t j;
1660 
1661  coap_ticks(&now);
1662  for(j = 0; j < nevents; j++) {
1663  coap_socket_t *sock = (coap_socket_t*)events[j].data.ptr;
1664 
1665  /* Ignore 'timer trigger' ptr which is NULL */
1666  if (sock) {
1667  if (sock->endpoint) {
1668  coap_endpoint_t *endpoint = sock->endpoint;
1669  if ((sock->flags & COAP_SOCKET_WANT_READ) &&
1670  (events[j].events & EPOLLIN)) {
1671  sock->flags |= COAP_SOCKET_CAN_READ;
1672  coap_read_endpoint(endpoint->context, endpoint, now);
1673  }
1674 
1675  if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
1676  (events[j].events & EPOLLOUT)) {
1677  /*
1678  * Need to update this to EPOLLIN as EPOLLOUT will normally always
1679  * be true causing epoll_wait to return early
1680  */
1681  coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
1682  sock->flags |= COAP_SOCKET_CAN_WRITE;
1683  coap_write_endpoint(endpoint->context, endpoint, now);
1684  }
1685 
1686  if ((sock->flags & COAP_SOCKET_WANT_ACCEPT) &&
1687  (events[j].events & EPOLLIN)) {
1688  sock->flags |= COAP_SOCKET_CAN_ACCEPT;
1689  coap_accept_endpoint(endpoint->context, endpoint, now);
1690  }
1691 
1692  }
1693  else if (sock->session) {
1694  coap_session_t *session = sock->session;
1695 
1696  /* Make sure the session object is not deleted
1697  in one of the callbacks */
1698  coap_session_reference(session);
1699  if ((sock->flags & COAP_SOCKET_WANT_CONNECT) &&
1700  (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
1701  sock->flags |= COAP_SOCKET_CAN_CONNECT;
1702  coap_connect_session(session->context, session, now);
1703  if (!(sock->flags & COAP_SOCKET_WANT_WRITE)) {
1704  coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
1705  }
1706  }
1707 
1708  if ((sock->flags & COAP_SOCKET_WANT_READ) &&
1709  (events[j].events & (EPOLLIN|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
1710  sock->flags |= COAP_SOCKET_CAN_READ;
1711  coap_read_session(session->context, session, now);
1712  }
1713 
1714  if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
1715  (events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
1716  /*
1717  * Need to update this to EPOLLIN as EPOLLOUT will normally always
1718  * be true causing epoll_wait to return early
1719  */
1720  coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
1721  sock->flags |= COAP_SOCKET_CAN_WRITE;
1722  coap_write_session(session->context, session, now);
1723  }
1724  /* Now dereference session so it can go away if needed */
1725  coap_session_release(session);
1726  }
1727  }
1728  else if (ctx->eptimerfd != -1) {
1729  /*
1730  * 'timer trigger' must have fired. eptimerfd needs to be read to clear
1731  * it so that it does not set EPOLLIN in the next epoll_wait().
1732  */
1733  uint64_t count;
1734 
1735  /* Check the result from read() to suppress the warning on
1736  * systems that declare read() with warn_unused_result. */
1737  if (read(ctx->eptimerfd, &count, sizeof(count)) == -1) {
1738  /* do nothing */;
1739  }
1740  /* And process any timed out events */
1741  coap_ticks(&now);
1742  coap_io_prepare_epoll(ctx, now);
1743  }
1744  }
1745 #endif /* COAP_EPOLL_SUPPORT */
1746 }
1747 
1748 int
1750  uint8_t *msg, size_t msg_len) {
1751 
1752  coap_pdu_t *pdu = NULL;
1753 
1754  assert(COAP_PROTO_NOT_RELIABLE(session->proto));
1755  if (msg_len < 4) {
1756  /* Minimum size of CoAP header - ignore runt */
1757  return -1;
1758  }
1759 
1760  pdu = coap_pdu_init(0, 0, 0, msg_len - 4);
1761  if (!pdu)
1762  goto error;
1763 
1764  if (!coap_pdu_parse(session->proto, msg, msg_len, pdu)) {
1765  coap_log(LOG_WARNING, "discard malformed PDU\n");
1766  goto error;
1767  }
1768 
1769  coap_dispatch(ctx, session, pdu);
1770  coap_delete_pdu(pdu);
1771  return 0;
1772 
1773 error:
1774  /*
1775  * https://tools.ietf.org/html/rfc7252#section-4.2 MUST send RST
1776  * https://tools.ietf.org/html/rfc7252#section-4.3 MAY send RST
1777  */
1778  coap_send_rst(session, pdu);
1779  coap_delete_pdu(pdu);
1780  return -1;
1781 }
1782 #endif /* not WITH_LWIP */
1783 
1784 int
1786  coap_queue_t *p, *q;
1787 
1788  if (!queue || !*queue)
1789  return 0;
1790 
1791  /* replace queue head if PDU's time is less than head's time */
1792 
1793  if (session == (*queue)->session && id == (*queue)->id) { /* found transaction */
1794  *node = *queue;
1795  *queue = (*queue)->next;
1796  if (*queue) { /* adjust relative time of new queue head */
1797  (*queue)->t += (*node)->t;
1798  }
1799  (*node)->next = NULL;
1800  coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed\n",
1801  coap_session_str(session), id);
1802  return 1;
1803  }
1804 
1805  /* search transaction to remove (only first occurence will be removed) */
1806  q = *queue;
1807  do {
1808  p = q;
1809  q = q->next;
1810  } while (q && (session != q->session || id != q->id));
1811 
1812  if (q) { /* found transaction */
1813  p->next = q->next;
1814  if (p->next) { /* must update relative time of p->next */
1815  p->next->t += q->t;
1816  }
1817  q->next = NULL;
1818  *node = q;
1819  coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed\n",
1820  coap_session_str(session), id);
1821  return 1;
1822  }
1823 
1824  return 0;
1825 
1826 }
1827 
1829 token_match(const uint8_t *a, size_t alen,
1830  const uint8_t *b, size_t blen) {
1831  return alen == blen && (alen == 0 || memcmp(a, b, alen) == 0);
1832 }
1833 
1834 void
1836  coap_nack_reason_t reason) {
1837  coap_queue_t *p, *q;
1838 
1839  while (context->sendqueue && context->sendqueue->session == session) {
1840  q = context->sendqueue;
1841  context->sendqueue = q->next;
1842  coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed\n",
1843  coap_session_str(session), q->id);
1844  if (q->pdu->type == COAP_MESSAGE_CON && context->nack_handler)
1845  context->nack_handler(context, session, q->pdu, reason, q->id);
1846  coap_delete_node(q);
1847  }
1848 
1849  if (!context->sendqueue)
1850  return;
1851 
1852  p = context->sendqueue;
1853  q = p->next;
1854 
1855  while (q) {
1856  if (q->session == session) {
1857  p->next = q->next;
1858  coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed\n",
1859  coap_session_str(session), q->id);
1860  if (q->pdu->type == COAP_MESSAGE_CON && context->nack_handler)
1861  context->nack_handler(context, session, q->pdu, reason, q->id);
1862  coap_delete_node(q);
1863  q = p->next;
1864  } else {
1865  p = q;
1866  q = q->next;
1867  }
1868  }
1869 }
1870 
1871 void
1873  const uint8_t *token, size_t token_length) {
1874  /* cancel all messages in sendqueue that belong to session
1875  * and use the specified token */
1876  coap_queue_t *p, *q;
1877 
1878  while (context->sendqueue && context->sendqueue->session == session &&
1879  token_match(token, token_length,
1880  context->sendqueue->pdu->token,
1881  context->sendqueue->pdu->token_length)) {
1882  q = context->sendqueue;
1883  context->sendqueue = q->next;
1884  coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed\n",
1885  coap_session_str(session), q->id);
1886  coap_delete_node(q);
1887  }
1888 
1889  if (!context->sendqueue)
1890  return;
1891 
1892  p = context->sendqueue;
1893  q = p->next;
1894 
1895  /* when q is not NULL, it does not match (dst, token), so we can skip it */
1896  while (q) {
1897  if (q->session == session &&
1898  token_match(token, token_length,
1899  q->pdu->token, q->pdu->token_length)) {
1900  p->next = q->next;
1901  coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed\n",
1902  coap_session_str(session), q->id);
1903  coap_delete_node(q);
1904  q = p->next;
1905  } else {
1906  p = q;
1907  q = q->next;
1908  }
1909  }
1910 }
1911 
1912 coap_queue_t *
1914  while (queue && queue->session != session && queue->id != id)
1915  queue = queue->next;
1916 
1917  return queue;
1918 }
1919 
1920 coap_pdu_t *
1921 coap_new_error_response(coap_pdu_t *request, unsigned char code,
1922  coap_opt_filter_t opts) {
1923  coap_opt_iterator_t opt_iter;
1924  coap_pdu_t *response;
1925  size_t size = request->token_length;
1926  unsigned char type;
1927  coap_opt_t *option;
1928  uint16_t opt_type = 0; /* used for calculating delta-storage */
1929 
1930 #if COAP_ERROR_PHRASE_LENGTH > 0
1931  const char *phrase;
1932  if (code != COAP_RESPONSE_CODE(508)) {
1933  phrase = coap_response_phrase(code);
1934 
1935  /* Need some more space for the error phrase and payload start marker */
1936  if (phrase)
1937  size += strlen(phrase) + 1;
1938  }
1939  else {
1940  /*
1941  * Need space for IP for 5.08 response which is filled in in coap_send()
1942  * https://www.rfc-editor.org/rfc/rfc8768.html#section-4
1943  */
1944  phrase = NULL;
1945  size += INET6_ADDRSTRLEN;
1946  }
1947 #endif
1948 
1949  assert(request);
1950 
1951  /* cannot send ACK if original request was not confirmable */
1952  type = request->type == COAP_MESSAGE_CON
1954  : COAP_MESSAGE_NON;
1955 
1956  /* Estimate how much space we need for options to copy from
1957  * request. We always need the Token, for 4.02 the unknown critical
1958  * options must be included as well. */
1959 
1960  /* we do not want these */
1963 
1964  coap_option_iterator_init(request, &opt_iter, opts);
1965 
1966  /* Add size of each unknown critical option. As known critical
1967  options as well as elective options are not copied, the delta
1968  value might grow.
1969  */
1970  while ((option = coap_option_next(&opt_iter))) {
1971  uint16_t delta = opt_iter.type - opt_type;
1972  /* calculate space required to encode (opt_iter.type - opt_type) */
1973  if (delta < 13) {
1974  size++;
1975  } else if (delta < 269) {
1976  size += 2;
1977  } else {
1978  size += 3;
1979  }
1980 
1981  /* add coap_opt_length(option) and the number of additional bytes
1982  * required to encode the option length */
1983 
1984  size += coap_opt_length(option);
1985  switch (*option & 0x0f) {
1986  case 0x0e:
1987  size++;
1988  /* fall through */
1989  case 0x0d:
1990  size++;
1991  break;
1992  default:
1993  ;
1994  }
1995 
1996  opt_type = opt_iter.type;
1997  }
1998 
1999  /* Now create the response and fill with options and payload data. */
2000  response = coap_pdu_init(type, code, request->tid, size);
2001  if (response) {
2002  /* copy token */
2003  if (!coap_add_token(response, request->token_length,
2004  request->token)) {
2005  coap_log(LOG_DEBUG, "cannot add token to error response\n");
2006  coap_delete_pdu(response);
2007  return NULL;
2008  }
2009 
2010  /* copy all options */
2011  coap_option_iterator_init(request, &opt_iter, opts);
2012  while ((option = coap_option_next(&opt_iter))) {
2013  coap_add_option(response, opt_iter.type,
2014  coap_opt_length(option),
2015  coap_opt_value(option));
2016  }
2017 
2018 #if COAP_ERROR_PHRASE_LENGTH > 0
2019  /* note that diagnostic messages do not need a Content-Format option. */
2020  if (phrase)
2021  coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
2022 #endif
2023  }
2024 
2025  return response;
2026 }
2027 
2032 COAP_STATIC_INLINE size_t
2033 get_wkc_len(coap_context_t *context, coap_opt_t *query_filter) {
2034  unsigned char buf[1];
2035  size_t len = 0;
2036 
2037  if (coap_print_wellknown(context, buf, &len, UINT_MAX, query_filter)
2039  coap_log(LOG_WARNING, "cannot determine length of /.well-known/core\n");
2040  return 0;
2041  }
2042 
2043  coap_log(LOG_DEBUG, "get_wkc_len: coap_print_wellknown() returned %zu\n", len);
2044 
2045  return len;
2046 }
2047 
2048 #define SZX_TO_BYTES(SZX) ((size_t)(1 << ((SZX) + 4)))
2049 
2050 coap_pdu_t *
2052  coap_pdu_t *request) {
2053  coap_pdu_t *resp;
2054  coap_opt_iterator_t opt_iter;
2055  size_t len, wkc_len;
2056  uint8_t buf[4];
2057  int result = 0;
2058  int need_block2 = 0; /* set to 1 if Block2 option is required */
2059  coap_block_t block;
2060  coap_opt_t *query_filter;
2061  size_t offset = 0;
2062  uint8_t *data;
2063 
2064  resp = coap_pdu_init(request->type == COAP_MESSAGE_CON
2066  : COAP_MESSAGE_NON,
2067  COAP_RESPONSE_CODE(205),
2068  request->tid, coap_session_max_pdu_size(session));
2069  if (!resp) {
2070  coap_log(LOG_DEBUG, "coap_wellknown_response: cannot create PDU\n");
2071  return NULL;
2072  }
2073 
2074  if (!coap_add_token(resp, request->token_length, request->token)) {
2075  coap_log(LOG_DEBUG, "coap_wellknown_response: cannot add token\n");
2076  goto error;
2077  }
2078 
2079  query_filter = coap_check_option(request, COAP_OPTION_URI_QUERY, &opt_iter);
2080  wkc_len = get_wkc_len(context, query_filter);
2081 
2082  /* The value of some resources is undefined and get_wkc_len will return 0.*/
2083  if (wkc_len == 0) {
2084  coap_log(LOG_DEBUG, "coap_wellknown_response: undefined resource\n");
2085  /* set error code 4.00 Bad Request*/
2086  resp->code = COAP_RESPONSE_CODE(400);
2087  resp->used_size = resp->token_length;
2088  return resp;
2089  }
2090 
2091  /* check whether the request contains the Block2 option */
2092  if (coap_get_block(request, COAP_OPTION_BLOCK2, &block)) {
2093  coap_log(LOG_DEBUG, "create block\n");
2094  offset = block.num << (block.szx + 4);
2095  if (block.szx > 6) { /* invalid, MUST lead to 4.00 Bad Request */
2096  resp->code = COAP_RESPONSE_CODE(400);
2097  return resp;
2098  } else if (block.szx > COAP_MAX_BLOCK_SZX) {
2099  block.szx = COAP_MAX_BLOCK_SZX;
2100  block.num = (unsigned int)(offset >> (block.szx + 4));
2101  }
2102 
2103  need_block2 = 1;
2104  }
2105 
2106  /* Check if there is sufficient space to add Content-Format option
2107  * and data. We do this before adding the Content-Format option to
2108  * avoid sending error responses with that option but no actual
2109  * content. */
2110  if (resp->max_size && resp->max_size <= resp->used_size + 8) {
2111  coap_log(LOG_DEBUG, "coap_wellknown_response: insufficient storage space\n");
2112  goto error;
2113  }
2114 
2115  /* check if Block2 option is required even if not requested */
2116  if (!need_block2 && resp->max_size && resp->max_size - resp->used_size < wkc_len + 1) {
2117  assert(resp->used_size <= resp->max_size);
2118  const size_t payloadlen = resp->max_size - resp->used_size;
2119  /* yes, need block-wise transfer */
2120  block.num = 0;
2121  block.m = 0; /* the M bit is set by coap_write_block_opt() */
2122  block.szx = COAP_MAX_BLOCK_SZX;
2123  while (payloadlen < SZX_TO_BYTES(block.szx) + 6) {
2124  if (block.szx == 0) {
2126  "coap_wellknown_response: message to small even for szx == 0\n");
2127  goto error;
2128  } else {
2129  block.szx--;
2130  }
2131  }
2132 
2133  need_block2 = 1;
2134  }
2135 
2136  if (need_block2) {
2137  /* Add in a pseudo etag (use wkc_len) in case .well-known/core
2138  changes over time */
2139  coap_add_option(resp,
2141  coap_encode_var_safe8(buf, sizeof(buf), wkc_len),
2142  buf);
2143  }
2144 
2145  /* Add Content-Format. As we have checked for available storage,
2146  * nothing should go wrong here. */
2147  assert(coap_encode_var_safe(buf, sizeof(buf),
2150  coap_encode_var_safe(buf, sizeof(buf),
2152 
2153 
2154  /* write Block2 option if necessary */
2155  if (need_block2) {
2156  if (coap_write_block_opt(&block, COAP_OPTION_BLOCK2, resp, wkc_len) < 0) {
2158  "coap_wellknown_response: cannot add Block2 option\n");
2159  goto error;
2160  }
2161  }
2162 
2163  coap_add_option(resp,
2165  coap_encode_var_safe8(buf, sizeof(buf), wkc_len),
2166  buf);
2167 
2168  len = need_block2 ?
2169  min(SZX_TO_BYTES(block.szx), wkc_len - (block.num << (block.szx + 4))) :
2170  resp->max_size && resp->used_size + wkc_len + 1 > resp->max_size ?
2171  resp->max_size - resp->used_size - 1 : wkc_len;
2172  data = coap_add_data_after(resp, len);
2173  if (!data) {
2174  coap_log(LOG_DEBUG, "coap_wellknown_response: coap_add_data failed\n" );
2175  goto error;
2176  }
2177 
2178  result = coap_print_wellknown(context, data, &len, offset, query_filter);
2179  if ((result & COAP_PRINT_STATUS_ERROR) != 0) {
2180  coap_log(LOG_DEBUG, "coap_print_wellknown failed\n");
2181  goto error;
2182  }
2183 
2184  return resp;
2185 
2186 error:
2187  /* set error code 5.03 and remove all options and data from response */
2188  resp->code = COAP_RESPONSE_CODE(503);
2189  resp->used_size = resp->token_length;
2190  return resp;
2191 }
2192 
2203 static int
2204 coap_cancel(coap_context_t *context, const coap_queue_t *sent) {
2205 #ifndef WITHOUT_OBSERVE
2206  coap_binary_t token = { 0, NULL };
2207  int num_cancelled = 0; /* the number of observers cancelled */
2208 
2209  /* remove observer for this resource, if any
2210  * get token from sent and try to find a matching resource. Uh!
2211  */
2212 
2213  COAP_SET_STR(&token, sent->pdu->token_length, sent->pdu->token);
2214 
2215  RESOURCES_ITER(context->resources, r) {
2216  coap_cancel_all_messages(context, sent->session, token.s, token.length);
2217  num_cancelled += coap_delete_observer(r, sent->session, &token);
2218  }
2219 
2220  return num_cancelled;
2221 #else /* WITOUT_OBSERVE */
2222  return 0;
2223 #endif /* WITOUT_OBSERVE */
2224 }
2225 
2231 
2262 static enum respond_t
2263 no_response(coap_pdu_t *request, coap_pdu_t *response) {
2264  coap_opt_t *nores;
2265  coap_opt_iterator_t opt_iter;
2266  unsigned int val = 0;
2267 
2268  assert(request);
2269  assert(response);
2270 
2271  if (COAP_RESPONSE_CLASS(response->code) > 0) {
2272  nores = coap_check_option(request, COAP_OPTION_NORESPONSE, &opt_iter);
2273 
2274  if (nores) {
2276 
2277  /* The response should be dropped when the bit corresponding to
2278  * the response class is set (cf. table in function
2279  * documentation). When a No-Response option is present and the
2280  * bit is not set, the sender explicitly indicates interest in
2281  * this response. */
2282  if (((1 << (COAP_RESPONSE_CLASS(response->code) - 1)) & val) > 0) {
2283  return RESPONSE_DROP;
2284  } else {
2285  return RESPONSE_SEND;
2286  }
2287  }
2288  }
2289 
2290  /* Default behavior applies when we are not dealing with a response
2291  * (class == 0) or the request did not contain a No-Response option.
2292  */
2293  return RESPONSE_DEFAULT;
2294 }
2295 
2297  { sizeof(COAP_DEFAULT_URI_WELLKNOWN)-1,
2299 
2300 static void
2302  coap_method_handler_t h = NULL;
2303  coap_pdu_t *response = NULL;
2305  coap_resource_t *resource = NULL;
2306  /* The respond field indicates whether a response must be treated
2307  * specially due to a No-Response option that declares disinterest
2308  * or interest in a specific response class. DEFAULT indicates that
2309  * No-Response has not been specified. */
2310  enum respond_t respond = RESPONSE_DEFAULT;
2311  coap_opt_iterator_t opt_iter;
2312  coap_opt_t *opt;
2313  int is_proxy_uri = 0;
2314  int is_proxy_scheme = 0;
2315  int skip_hop_limit_check = 0;
2316  int resp;
2317 
2319  opt = coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter);
2320  if (opt)
2321  is_proxy_scheme = 1;
2322 
2323  opt = coap_check_option(pdu, COAP_OPTION_PROXY_URI, &opt_iter);
2324  if (opt)
2325  is_proxy_uri = 1;
2326 
2327  if (is_proxy_scheme || is_proxy_uri) {
2328  coap_uri_t uri;
2329 
2330  if (!context->proxy_uri_resource) {
2331  /* Need to return a 5.05 RFC7252 Section 5.7.2 */
2332  coap_log(LOG_DEBUG, "Proxy-%s support not configured\n",
2333  is_proxy_scheme ? "Scheme" : "Uri");
2334  resp = 505;
2335  goto fail_response;
2336  }
2337  if (((size_t)pdu->code - 1 <
2338  (sizeof(resource->handler) / sizeof(resource->handler[0]))) &&
2339  !(context->proxy_uri_resource->handler[pdu->code - 1])) {
2340  /* Need to return a 5.05 RFC7252 Section 5.7.2 */
2341  coap_log(LOG_DEBUG, "Proxy-%s code %d.%02d handler not supported\n",
2342  is_proxy_scheme ? "Scheme" : "Uri",
2343  pdu->code/100, pdu->code%100);
2344  resp = 505;
2345  goto fail_response;
2346  }
2347 
2348  /* Need to check if authority is the proxy endpoint RFC7252 Section 5.7.2 */
2349  if (is_proxy_uri) {
2351  coap_opt_length(opt), &uri) < 0) {
2352  /* Need to return a 5.05 RFC7252 Section 5.7.2 */
2353  coap_log(LOG_DEBUG, "Proxy-URI not decodable\n");
2354  resp = 505;
2355  goto fail_response;
2356  }
2357  }
2358  else {
2359  memset(&uri, 0, sizeof(uri));
2360  opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
2361  if (opt) {
2362  uri.host.length = coap_opt_length(opt);
2363  uri.host.s = coap_opt_value(opt);
2364  }
2365  }
2366  resource = context->proxy_uri_resource;
2367  if (uri.host.length && resource->proxy_name_count && resource->proxy_name_list) {
2368  size_t i;
2369  for (i = 0; i < resource->proxy_name_count; i++) {
2370  if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
2371  break;
2372  }
2373  }
2374  if (i != resource->proxy_name_count) {
2375  /* This server is hosting the proxy connection endpoint */
2376  is_proxy_uri = 0;
2377  is_proxy_scheme = 0;
2378  skip_hop_limit_check = 1;
2379  }
2380  }
2381  resource = NULL;
2382  }
2383 
2384  if (!skip_hop_limit_check) {
2385  opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
2386  if (opt) {
2387  size_t hop_limit;
2388  uint8_t buf[4];
2389 
2390  hop_limit =
2392  if (hop_limit == 1) {
2393  /* coap_send() will fill in the IP address for us */
2394  resp = 508;
2395  goto fail_response;
2396  }
2397  else if (hop_limit < 1 || hop_limit > 255) {
2398  /* Need to return a 4.00 RFC8768 Section 3 */
2399  coap_log(LOG_INFO, "Invalid Hop Limit\n");
2400  resp = 400;
2401  goto fail_response;
2402  }
2403  hop_limit--;
2405  coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
2406  buf);
2407  }
2408  }
2409 
2410  coap_string_t *uri_path = coap_get_uri_path(pdu);
2411  if (!uri_path)
2412  return;
2413 
2414  if (!is_proxy_uri && !is_proxy_scheme) {
2415  /* try to find the resource from the request URI */
2416  coap_str_const_t uri_path_c = { uri_path->length, uri_path->s };
2417  resource = coap_get_resource_from_uri_path(context, &uri_path_c);
2418  }
2419 
2420  if ((resource == NULL) || (resource->is_unknown == 1) ||
2421  (resource->is_proxy_uri == 1)) {
2422  /* The resource was not found or there is an unexpected match against the
2423  * resource defined for handling unknown or proxy URIs.
2424  * Check if the request URI happens to be the well-known URI, or if the
2425  * unknown resource handler is defined, a PUT or optionally other methods,
2426  * if configured, for the unknown handler.
2427  *
2428  * if well-known URI generate a default response
2429  *
2430  * else if a PROXY URI/Scheme request and proxy URI handler defined, call the
2431  * proxy URI handler
2432  *
2433  * else if unknown URI handler defined, call the unknown
2434  * URI handler (to allow for potential generation of resource
2435  * [RFC7272 5.8.3]) if the appropriate method is defined.
2436  *
2437  * else if DELETE return 2.02 (RFC7252: 5.8.4. DELETE)
2438  *
2439  * else return 4.04 */
2440 
2442  /* request for .well-known/core */
2443  if (pdu->code == COAP_REQUEST_GET) { /* GET */
2444  coap_log(LOG_INFO, "create default response for %s\n",
2446  response = coap_wellknown_response(context, session, pdu);
2447  } else {
2448  coap_log(LOG_DEBUG, "method not allowed for .well-known/core\n");
2449  response = coap_new_error_response(pdu, COAP_RESPONSE_CODE(405),
2450  opt_filter);
2451  }
2452  } else if (is_proxy_uri || is_proxy_scheme) {
2453  resource = context->proxy_uri_resource;
2454  } else if ((context->unknown_resource != NULL) &&
2455  ((size_t)pdu->code - 1 <
2456  (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
2457  (context->unknown_resource->handler[pdu->code - 1])) {
2458  /*
2459  * The unknown_resource can be used to handle undefined resources
2460  * for a PUT request and can support any other registered handler
2461  * defined for it
2462  * Example set up code:-
2463  * r = coap_resource_unknown_init(hnd_put_unknown);
2464  * coap_register_handler(r, COAP_REQUEST_POST, hnd_post_unknown);
2465  * coap_register_handler(r, COAP_REQUEST_GET, hnd_get_unknown);
2466  * coap_register_handler(r, COAP_REQUEST_DELETE, hnd_delete_unknown);
2467  * coap_add_resource(ctx, r);
2468  *
2469  * Note: It is not possible to observe the unknown_resource, a separate
2470  * resource must be created (by PUT or POST) which has a GET
2471  * handler to be observed
2472  */
2473  resource = context->unknown_resource;
2474  } else if (pdu->code == COAP_REQUEST_DELETE) {
2475  /*
2476  * Request for DELETE on non-existant resource (RFC7252: 5.8.4. DELETE)
2477  */
2478  coap_log(LOG_DEBUG, "request for unknown resource '%*.*s',"
2479  " return 2.02\n",
2480  (int)uri_path->length,
2481  (int)uri_path->length,
2482  uri_path->s);
2483  response =
2485  opt_filter);
2486  } else { /* request for any another resource, return 4.04 */
2487 
2488  coap_log(LOG_DEBUG, "request for unknown resource '%*.*s', return 4.04\n",
2489  (int)uri_path->length, (int)uri_path->length, uri_path->s);
2490  response =
2492  opt_filter);
2493  }
2494 
2495  if (!resource) {
2496  if (response && (no_response(pdu, response) != RESPONSE_DROP)) {
2497  if (coap_send(session, response) == COAP_INVALID_TID)
2498  coap_log(LOG_WARNING, "cannot send response for mid=0x%x\n",
2499  pdu->tid);
2500  } else {
2501  coap_delete_pdu(response);
2502  }
2503 
2504  response = NULL;
2505 
2506  coap_delete_string(uri_path);
2507  return;
2508  } else {
2509  if (response) {
2510  /* Need to delete unused response - it will get re-created further on */
2511  coap_delete_pdu(response);
2512  }
2513  }
2514  }
2515 
2516  /* the resource was found, check if there is a registered handler */
2517  if ((size_t)pdu->code - 1 <
2518  sizeof(resource->handler) / sizeof(coap_method_handler_t))
2519  h = resource->handler[pdu->code - 1];
2520 
2521  if (h) {
2522  coap_log(LOG_DEBUG, "call custom handler for resource '%*.*s'\n",
2523  (int)resource->uri_path->length, (int)resource->uri_path->length,
2524  resource->uri_path->s);
2525  response = coap_pdu_init(pdu->type == COAP_MESSAGE_CON
2527  : COAP_MESSAGE_NON,
2528  0, pdu->tid, coap_session_max_pdu_size(session));
2529 
2530  /* Implementation detail: coap_add_token() immediately returns 0
2531  if response == NULL */
2532  if (coap_add_token(response, pdu->token_length, pdu->token)) {
2533  coap_binary_t token = { pdu->token_length, pdu->token };
2534  coap_opt_t *observe = NULL;
2535  int observe_action = COAP_OBSERVE_CANCEL;
2536  coap_string_t *query = coap_get_query(pdu);
2537  int owns_query = 1;
2538 
2539  /* check for Observe option RFC7641 and RFC8132 */
2540  if (resource->observable &&
2541  (pdu->code == COAP_REQUEST_GET || pdu->code == COAP_REQUEST_FETCH)) {
2542  observe = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
2543  if (observe) {
2544  observe_action =
2546  coap_opt_length(observe));
2547 
2548  if (observe_action == COAP_OBSERVE_ESTABLISH) {
2549  coap_subscription_t *subscription;
2550  coap_block_t block2;
2551  int has_block2 = 0;
2552 
2553  if (coap_get_block(pdu, COAP_OPTION_BLOCK2, &block2)) {
2554  has_block2 = 1;
2555  }
2556  subscription = coap_add_observer(resource, session, &token, query, has_block2, block2, pdu->code);
2557  if (subscription) {
2558  /* Ownership of query is taken by subscription if not
2559  * NULL. In this case, we must not delete query here
2560  * hence owns_query is cleared. */
2561  owns_query = 0;
2562  coap_touch_observer(context, session, &token);
2563  }
2564  }
2565  else if (observe_action == COAP_OBSERVE_CANCEL) {
2566  coap_delete_observer(resource, session, &token);
2567  }
2568  else {
2569  coap_log(LOG_INFO, "observe: unexpected action %d\n", observe_action);
2570  }
2571  }
2572  }
2573 
2574  h(context, resource, session, pdu, &token, query, response);
2575 
2576  if (query && owns_query)
2577  coap_delete_string(query);
2578 
2579  respond = no_response(pdu, response);
2580  if (respond != RESPONSE_DROP) {
2581  if (observe && (COAP_RESPONSE_CLASS(response->code) > 2)) {
2582  coap_delete_observer(resource, session, &token);
2583  }
2584 
2585  /* If original request contained a token, and the registered
2586  * application handler made no changes to the response, then
2587  * this is an empty ACK with a token, which is a malformed
2588  * PDU */
2589  if ((response->type == COAP_MESSAGE_ACK)
2590  && (response->code == 0)) {
2591  /* Remove token from otherwise-empty acknowledgment PDU */
2592  response->token_length = 0;
2593  response->used_size = 0;
2594  }
2595 
2596  if ((respond == RESPONSE_SEND)
2597  || /* RESPOND_DEFAULT */
2598  (response->type != COAP_MESSAGE_NON ||
2599  (response->code >= 64
2600  && !coap_mcast_interface(&node->local_if)))) {
2601 
2602  if (coap_send(session, response) == COAP_INVALID_TID)
2603  coap_log(LOG_DEBUG, "cannot send response for mid=0x%x\n",
2604  pdu->tid);
2605  } else {
2606  coap_delete_pdu(response);
2607  }
2608  } else {
2609  coap_delete_pdu(response);
2610  }
2611  } else {
2612  coap_log(LOG_WARNING, "cannot generate response\r\n");
2613  coap_delete_pdu(response);
2614  }
2615  response = NULL;
2616  } else {
2618  /* request for .well-known/core */
2619  coap_log(LOG_DEBUG, "create default response for %s\n",
2621  response = coap_wellknown_response(context, session, pdu);
2622  coap_log(LOG_DEBUG, "have wellknown response %p\n", (void *)response);
2623  } else
2624  response = coap_new_error_response(pdu, COAP_RESPONSE_CODE(405),
2625  opt_filter);
2626 
2627  if (response && (no_response(pdu, response) != RESPONSE_DROP)) {
2628  if (coap_send(session, response) == COAP_INVALID_TID)
2629  coap_log(LOG_DEBUG, "cannot send response for mid=0x%x\n",
2630  pdu->tid);
2631  } else {
2632  coap_delete_pdu(response);
2633  }
2634  response = NULL;
2635  }
2636 
2637  assert(response == NULL);
2638  coap_delete_string(uri_path);
2639  return;
2640 
2641 fail_response:
2642  response =
2644  opt_filter);
2645  if (response) {
2646  if (coap_send(session, response) == COAP_INVALID_TID)
2647  coap_log(LOG_WARNING, "cannot send response for mid=0x%x\n",
2648  pdu->tid);
2649  }
2650 }
2651 
2652 static void
2654  coap_pdu_t *sent, coap_pdu_t *rcvd) {
2655 
2656  coap_send_ack(session, rcvd);
2657 
2658  /* In a lossy context, the ACK of a separate response may have
2659  * been lost, so we need to stop retransmitting requests with the
2660  * same token.
2661  */
2662  coap_cancel_all_messages(context, session, rcvd->token, rcvd->token_length);
2663 
2664  /* Call application-specific response handler when available. */
2665  if (context->response_handler) {
2666  context->response_handler(context, session, sent, rcvd, rcvd->tid);
2667  }
2668 }
2669 
2670 #if !COAP_DISABLE_TCP
2671 static void
2673  coap_pdu_t *pdu) {
2674  coap_opt_iterator_t opt_iter;
2675  coap_opt_t *option;
2676  (void)context;
2677 
2678  coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
2679 
2680  if (pdu->code == COAP_SIGNALING_CSM) {
2681  while ((option = coap_option_next(&opt_iter))) {
2682  if (opt_iter.type == COAP_SIGNALING_OPTION_MAX_MESSAGE_SIZE) {
2684  coap_opt_length(option)));
2685  } else if (opt_iter.type == COAP_SIGNALING_OPTION_BLOCK_WISE_TRANSFER) {
2686  session->csm_block_supported = 1;
2687  }
2688  }
2689  if (session->state == COAP_SESSION_STATE_CSM)
2690  coap_session_connected(session);
2691  } else if (pdu->code == COAP_SIGNALING_PING) {
2693  if (context->ping_handler) {
2694  context->ping_handler(context, session, pdu, pdu->tid);
2695  }
2696  if (pong) {
2698  coap_send(session, pong);
2699  }
2700  } else if (pdu->code == COAP_SIGNALING_PONG) {
2701  session->last_pong = session->last_rx_tx;
2702  if (context->pong_handler) {
2703  context->pong_handler(context, session, pdu, pdu->tid);
2704  }
2705  } else if (pdu->code == COAP_SIGNALING_RELEASE
2706  || pdu->code == COAP_SIGNALING_ABORT) {
2708  }
2709 }
2710 #endif /* !COAP_DISABLE_TCP */
2711 
2712 void
2714  coap_pdu_t *pdu) {
2715  coap_queue_t *sent = NULL;
2716  coap_pdu_t *response;
2718  int is_ping_rst;
2719 
2720  if (LOG_DEBUG <= coap_get_log_level()) {
2721  /* FIXME: get debug to work again **
2722  unsigned char addr[INET6_ADDRSTRLEN+8], localaddr[INET6_ADDRSTRLEN+8];
2723  if (coap_print_addr(remote, addr, INET6_ADDRSTRLEN+8) &&
2724  coap_print_addr(&packet->dst, localaddr, INET6_ADDRSTRLEN+8) )
2725  coap_log(LOG_DEBUG, "** received %d bytes from %s on interface %s:\n",
2726  (int)msg_len, addr, localaddr);
2727 
2728  */
2729  coap_show_pdu(LOG_DEBUG, pdu);
2730  }
2731 
2732  memset(opt_filter, 0, sizeof(coap_opt_filter_t));
2733 
2734  switch (pdu->type) {
2735  case COAP_MESSAGE_ACK:
2736  /* find transaction in sendqueue to stop retransmission */
2737  coap_remove_from_queue(&context->sendqueue, session, pdu->tid, &sent);
2738 
2739  if (session->con_active) {
2740  session->con_active--;
2741  if (session->state == COAP_SESSION_STATE_ESTABLISHED)
2742  /* Flush out any entries on session->delayqueue */
2743  coap_session_connected(session);
2744  }
2745  /* if sent code was >= 64 the message might have been a
2746  * notification. Then, we must flag the observer to be alive
2747  * by setting obs->fail_cnt = 0. */
2748  if (sent && COAP_RESPONSE_CLASS(sent->pdu->code) == 2) {
2749  const coap_binary_t token =
2750  { sent->pdu->token_length, sent->pdu->token };
2751  coap_touch_observer(context, sent->session, &token);
2752  }
2753 
2754  /* an empty ACK needs no further handling */
2755  if (pdu->code == 0)
2756  goto cleanup;
2757 
2758  break;
2759 
2760  case COAP_MESSAGE_RST:
2761  /* We have sent something the receiver disliked, so we remove
2762  * not only the transaction but also the subscriptions we might
2763  * have. */
2764  is_ping_rst = 0;
2765  if (pdu->tid == session->last_ping_mid &&
2766  context->ping_timeout && session->last_ping > 0)
2767  is_ping_rst = 1;
2768 
2769  if (!is_ping_rst)
2770  coap_log(LOG_ALERT, "got RST for mid=0x%x\n", pdu->tid);
2771 
2772  if (session->con_active) {
2773  session->con_active--;
2774  if (session->state == COAP_SESSION_STATE_ESTABLISHED)
2775  /* Flush out any entries on session->delayqueue */
2776  coap_session_connected(session);
2777  }
2778 
2779  /* find transaction in sendqueue to stop retransmission */
2780  coap_remove_from_queue(&context->sendqueue, session, pdu->tid, &sent);
2781 
2782  if (sent) {
2783  coap_cancel(context, sent);
2784 
2785  if (!is_ping_rst) {
2786  if(sent->pdu->type==COAP_MESSAGE_CON && context->nack_handler)
2787  context->nack_handler(context, sent->session, sent->pdu,
2788  COAP_NACK_RST, sent->id);
2789  }
2790  else {
2791  if (context->pong_handler) {
2792  context->pong_handler(context, session, pdu, pdu->tid);
2793  }
2794  session->last_pong = session->last_rx_tx;
2795  session->last_ping_mid = COAP_INVALID_TID;
2796  }
2797  }
2798  else {
2799  /* Need to check is there is a subscription active and delete it */
2800  RESOURCES_ITER(context->resources, r) {
2801  coap_subscription_t *obs, *tmp;
2802  LL_FOREACH_SAFE(r->subscribers, obs, tmp) {
2803  if (obs->tid == pdu->tid && obs->session == session) {
2804  coap_binary_t token = { 0, NULL };
2805  COAP_SET_STR(&token, obs->token_length, obs->token);
2806  coap_delete_observer(r, session, &token);
2807  goto cleanup;
2808  }
2809  }
2810  }
2811  }
2812  goto cleanup;
2813 
2814  case COAP_MESSAGE_NON: /* check for unknown critical options */
2815  if (coap_option_check_critical(context, pdu, opt_filter) == 0)
2816  goto cleanup;
2817  break;
2818 
2819  case COAP_MESSAGE_CON: /* check for unknown critical options */
2820  if (coap_option_check_critical(context, pdu, opt_filter) == 0) {
2821 
2822  /* FIXME: send response only if we have received a request. Otherwise,
2823  * send RST. */
2824  response =
2826 
2827  if (!response) {
2829  "coap_dispatch: cannot create error response\n");
2830  } else {
2831  if (coap_send(session, response) == COAP_INVALID_TID)
2832  coap_log(LOG_WARNING, "coap_dispatch: error sending response\n");
2833  }
2834 
2835  goto cleanup;
2836  }
2837  default: break;
2838  }
2839 
2840  /* Pass message to upper layer if a specific handler was
2841  * registered for a request that should be handled locally. */
2842 #if !COAP_DISABLE_TCP
2843  if (COAP_PDU_IS_SIGNALING(pdu))
2844  handle_signaling(context, session, pdu);
2845  else
2846 #endif /* !COAP_DISABLE_TCP */
2847  if (COAP_PDU_IS_REQUEST(pdu))
2848  handle_request(context, session, pdu);
2849  else if (COAP_PDU_IS_RESPONSE(pdu))
2850  handle_response(context, session, sent ? sent->pdu : NULL, pdu);
2851  else {
2852  if (COAP_PDU_IS_EMPTY(pdu)) {
2853  if (context->ping_handler) {
2854  context->ping_handler(context, session,
2855  pdu, pdu->tid);
2856  }
2857  }
2858  coap_log(LOG_DEBUG, "dropped message with invalid code (%d.%02d)\n",
2859  COAP_RESPONSE_CLASS(pdu->code),
2860  pdu->code & 0x1f);
2861 
2862  if (!coap_is_mcast(&session->addr_info.local)) {
2863  if (COAP_PDU_IS_EMPTY(pdu)) {
2864  if (session->proto != COAP_PROTO_TCP && session->proto != COAP_PROTO_TLS) {
2865  coap_tick_t now;
2866  coap_ticks(&now);
2867  if (session->last_tx_rst + COAP_TICKS_PER_SECOND/4 < now) {
2869  session->last_tx_rst = now;
2870  }
2871  }
2872  }
2873  else {
2875  }
2876  }
2877  }
2878 
2879 cleanup:
2880  coap_delete_node(sent);
2881 }
2882 
2883 int
2885  coap_log(LOG_DEBUG, "***EVENT: 0x%04x\n", event);
2886 
2887  if (context->handle_event) {
2888  return context->handle_event(context, event, session);
2889  } else {
2890  return 0;
2891  }
2892 }
2893 
2894 int
2896  coap_endpoint_t *ep;
2897  coap_session_t *s, *rtmp;
2898  if (!context)
2899  return 1;
2900  if (context->sendqueue)
2901  return 0;
2902  LL_FOREACH(context->endpoint, ep) {
2903  SESSIONS_ITER(ep->sessions, s, rtmp) {
2904  if (s->delayqueue)
2905  return 0;
2906  }
2907  }
2908  SESSIONS_ITER(context->sessions, s, rtmp) {
2909  if (s->delayqueue)
2910  return 0;
2911  }
2912  return 1;
2913 }
2914 
2915 static int coap_started = 0;
2916 
2917 void coap_startup(void) {
2918  coap_tick_t now;
2919  uint64_t us;
2920  if (coap_started)
2921  return;
2922  coap_started = 1;
2923 #if defined(HAVE_WINSOCK2_H)
2924  WORD wVersionRequested = MAKEWORD(2, 2);
2925  WSADATA wsaData;
2926  WSAStartup(wVersionRequested, &wsaData);
2927 #endif
2928  coap_clock_init();
2929  coap_ticks(&now);
2930  us = coap_ticks_to_rt_us(now);
2931  /* Be accurate to the nearest (approx) us */
2932  coap_prng_init(us);
2933  coap_memory_init();
2935 }
2936 
2937 void coap_cleanup(void) {
2938 #if defined(HAVE_WINSOCK2_H)
2939  WSACleanup();
2940 #endif
2942 }
2943 
2944 #if ! defined WITH_CONTIKI && ! defined WITH_LWIP && ! defined RIOT_VERSION
2945 int
2946 coap_join_mcast_group(coap_context_t *ctx, const char *group_name) {
2947  struct ipv6_mreq mreq;
2948  struct addrinfo *reslocal = NULL, *resmulti = NULL, hints, *ainfo;
2949  int result = -1;
2950  coap_endpoint_t *endpoint;
2951  int mgroup_setup = 0;
2952 
2953  /* we have to resolve the link-local interface to get the interface id */
2954  memset(&hints, 0, sizeof(hints));
2955  hints.ai_family = AF_INET6;
2956  hints.ai_socktype = SOCK_DGRAM;
2957 
2958  result = getaddrinfo("::", NULL, &hints, &reslocal);
2959  if (result != 0) {
2960  coap_log(LOG_ERR,
2961  "coap_join_mcast_group: cannot resolve link-local interface: %s\n",
2962  gai_strerror(result));
2963  goto finish;
2964  }
2965 
2966  /* get the first suitable interface identifier */
2967  for (ainfo = reslocal; ainfo != NULL; ainfo = ainfo->ai_next) {
2968  if (ainfo->ai_family == AF_INET6) {
2969  mreq.ipv6mr_interface =
2970  ((struct sockaddr_in6 *)ainfo->ai_addr)->sin6_scope_id;
2971  break;
2972  }
2973  }
2974 
2975  memset(&hints, 0, sizeof(hints));
2976  hints.ai_family = AF_INET6;
2977  hints.ai_socktype = SOCK_DGRAM;
2978 
2979  /* resolve the multicast group address */
2980  result = getaddrinfo(group_name, NULL, &hints, &resmulti);
2981 
2982  if (result != 0) {
2983  coap_log(LOG_ERR,
2984  "coap_join_mcast_group: cannot resolve multicast address: %s\n",
2985  gai_strerror(result));
2986  goto finish;
2987  }
2988 
2989  for (ainfo = resmulti; ainfo != NULL; ainfo = ainfo->ai_next) {
2990  if (ainfo->ai_family == AF_INET6) {
2991  mreq.ipv6mr_multiaddr =
2992  ((struct sockaddr_in6 *)ainfo->ai_addr)->sin6_addr;
2993  break;
2994  }
2995  }
2996 
2997  LL_FOREACH(ctx->endpoint, endpoint) {
2998  if (endpoint->proto == COAP_PROTO_UDP ||
2999  endpoint->proto == COAP_PROTO_DTLS) {
3000  result = setsockopt(endpoint->sock.fd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
3001  (char *)&mreq, sizeof(mreq));
3002  if (result == COAP_SOCKET_ERROR) {
3003  coap_log(LOG_ERR,
3004  "coap_join_mcast_group: setsockopt: %s: '%s'\n",
3005  coap_socket_strerror(), group_name);
3006  }
3007  else {
3008  mgroup_setup = 1;
3009  }
3010  }
3011  }
3012  if (!mgroup_setup) {
3013  result = -1;
3014  }
3015 
3016  finish:
3017  freeaddrinfo(resmulti);
3018  freeaddrinfo(reslocal);
3019 
3020  return result;
3021 }
3022 #else /* defined WITH_CONTIKI || defined WITH_LWIP */
3023 int
3024 coap_join_mcast_group(coap_context_t *ctx, const char *group_name) {
3025  (void)ctx;
3026  (void)group_name;
3027  return -1;
3028 }
3029 #endif /* defined WITH_CONTIKI || defined WITH_LWIP */
3030 
3031 #ifdef WITH_CONTIKI
3032 
3033 /*---------------------------------------------------------------------------*/
3034 /* CoAP message retransmission */
3035 /*---------------------------------------------------------------------------*/
3036 PROCESS_THREAD(coap_retransmit_process, ev, data) {
3037  coap_tick_t now;
3038  coap_queue_t *nextpdu;
3039 
3040  PROCESS_BEGIN();
3041 
3042  coap_log(LOG_DEBUG, "Started retransmit process\n");
3043 
3044  while (1) {
3045  PROCESS_YIELD();
3046  if (ev == PROCESS_EVENT_TIMER) {
3047  if (etimer_expired(&the_coap_context.retransmit_timer)) {
3048 
3049  nextpdu = coap_peek_next(&the_coap_context);
3050 
3051  coap_ticks(&now);
3052  while (nextpdu && nextpdu->t <= now) {
3053  coap_retransmit(&the_coap_context, coap_pop_next(&the_coap_context));
3054  nextpdu = coap_peek_next(&the_coap_context);
3055  }
3056 
3057  /* need to set timer to some value even if no nextpdu is available */
3058  etimer_set(&the_coap_context.retransmit_timer,
3059  nextpdu ? nextpdu->t - now : 0xFFFF);
3060  }
3061 #ifndef WITHOUT_OBSERVE
3062  if (etimer_expired(&the_coap_context.notify_timer)) {
3063  coap_check_notify(&the_coap_context);
3064  etimer_reset(&the_coap_context.notify_timer);
3065  }
3066 #endif /* WITHOUT_OBSERVE */
3067  }
3068  }
3069 
3070  PROCESS_END();
3071 }
3072 /*---------------------------------------------------------------------------*/
3073 
3074 #endif /* WITH_CONTIKI */
3075 
3076 #ifdef WITH_LWIP
3077 /* FIXME: retransmits that are not required any more due to incoming packages
3078  * do *not* get cleared at the moment, the wakeup when the transmission is due
3079  * is silently accepted. this is mainly due to the fact that the required
3080  * checks are similar in two places in the code (when receiving ACK and RST)
3081  * and that they cause more than one patch chunk, as it must be first checked
3082  * whether the sendqueue item to be dropped is the next one pending, and later
3083  * the restart function has to be called. nothing insurmountable, but it can
3084  * also be implemented when things have stabilized, and the performance
3085  * penality is minimal
3086  *
3087  * also, this completely ignores COAP_RESOURCE_CHECK_TIME.
3088  * */
3089 
3090 static void coap_retransmittimer_execute(void *arg) {
3091  coap_context_t *ctx = (coap_context_t*)arg;
3092  coap_tick_t now;
3093  coap_tick_t elapsed;
3094  coap_queue_t *nextinqueue;
3095 
3096  ctx->timer_configured = 0;
3097 
3098  coap_ticks(&now);
3099 
3100  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 */
3101 
3102  nextinqueue = coap_peek_next(ctx);
3103  while (nextinqueue != NULL) {
3104  if (nextinqueue->t > elapsed) {
3105  nextinqueue->t -= elapsed;
3106  break;
3107  } else {
3108  elapsed -= nextinqueue->t;
3109  coap_retransmit(ctx, coap_pop_next(ctx));
3110  nextinqueue = coap_peek_next(ctx);
3111  }
3112  }
3113 
3114  ctx->sendqueue_basetime = now;
3115 
3116  coap_retransmittimer_restart(ctx);
3117 }
3118 
3119 static void coap_retransmittimer_restart(coap_context_t *ctx) {
3120  coap_tick_t now, elapsed, delay;
3121 
3122  if (ctx->timer_configured) {
3123  printf("clearing\n");
3124  sys_untimeout(coap_retransmittimer_execute, (void*)ctx);
3125  ctx->timer_configured = 0;
3126  }
3127  if (ctx->sendqueue != NULL) {
3128  coap_ticks(&now);
3129  elapsed = now - ctx->sendqueue_basetime;
3130  if (ctx->sendqueue->t >= elapsed) {
3131  delay = ctx->sendqueue->t - elapsed;
3132  } else {
3133  /* a strange situation, but not completely impossible.
3134  *
3135  * this happens, for example, right after
3136  * coap_retransmittimer_execute, when a retransmission
3137  * was *just not yet* due, and the clock ticked before
3138  * our coap_ticks was called.
3139  *
3140  * not trying to retransmit anything now, as it might
3141  * cause uncontrollable recursion; let's just try again
3142  * with the next main loop run.
3143  * */
3144  delay = 0;
3145  }
3146 
3147  printf("scheduling for %d ticks\n", delay);
3148  sys_timeout(delay, coap_retransmittimer_execute, (void*)ctx);
3149  ctx->timer_configured = 1;
3150  }
3151 }
3152 #endif
void coap_address_init(coap_address_t *addr)
Resets the given coap_address_t object addr to its default values.
Definition: address.c:98
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
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:109
void coap_dtls_free_context(struct coap_dtls_context_t *dtls_context)
Releases the storage allocated for dtls_context.
int coap_dtls_send(struct coap_context_t *coap_context, struct coap_dtls_session_t *session, const coap_pdu_t *pdu)
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:457
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:729
ssize_t coap_network_read(coap_socket_t *sock, coap_packet_t *packet)
Function interface for reading data.
Definition: coap_io.c:736
ssize_t coap_network_send(coap_socket_t *sock, const coap_session_t *session, const uint8_t *data, size_t datalen)
Definition: coap_io.c:555
const char * coap_socket_strerror(void)
Definition: coap_io.c:1459
#define COAP_SOCKET_MULTICAST
socket is used for multicast communication
Definition: coap_io.h:91
#define COAP_SOCKET_WANT_ACCEPT
non blocking server socket is waiting for accept
Definition: coap_io.h:85
#define coap_mcast_interface(Local)
Definition: coap_io.h:169
#define COAP_SOCKET_NOT_EMPTY
the socket is not empty
Definition: coap_io.h:80
#define COAP_SOCKET_CAN_WRITE
non blocking socket can now write without blocking
Definition: coap_io.h:88
#define COAP_SOCKET_BOUND
the socket is bound
Definition: coap_io.h:81
#define COAP_SOCKET_WANT_READ
non blocking socket is waiting for reading
Definition: coap_io.h:83
#define COAP_SOCKET_ERROR
Definition: coap_io.h:42
coap_nack_reason_t
Definition: coap_io.h:214
@ COAP_NACK_NOT_DELIVERABLE
Definition: coap_io.h:216
@ COAP_NACK_TOO_MANY_RETRIES
Definition: coap_io.h:215
@ COAP_NACK_TLS_FAILED
Definition: coap_io.h:218
@ COAP_NACK_ICMP_ISSUE
Definition: coap_io.h:219
@ COAP_NACK_RST
Definition: coap_io.h:217
#define COAP_SOCKET_CAN_ACCEPT
non blocking server socket can now accept without blocking
Definition: coap_io.h:89
#define COAP_SOCKET_WANT_WRITE
non blocking socket is waiting for writing
Definition: coap_io.h:84
#define COAP_SOCKET_CAN_CONNECT
non blocking client socket can now connect without blocking
Definition: coap_io.h:90
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
Definition: coap_io.h:86
#define COAP_SOCKET_CAN_READ
non blocking socket can now read without blocking
Definition: coap_io.h:87
#define COAP_SOCKET_CONNECTED
the socket is connected
Definition: coap_io.h:82
#define COAP_SOCKET_EMPTY
coap_socket_flags_t values
Definition: coap_io.h:79
void coap_free_endpoint(coap_endpoint_t *ep)
int coap_dtls_context_set_pki_root_cas(struct coap_context_t *ctx UNUSED, const char *ca_file UNUSED, const char *ca_path UNUSED)
Definition: coap_notls.c:47
int coap_dtls_context_set_pki(coap_context_t *ctx UNUSED, const coap_dtls_pki_t *setup_data UNUSED, const coap_dtls_role_t role UNUSED)
Definition: coap_notls.c:39
void * coap_dtls_new_client_session(coap_session_t *session UNUSED)
Definition: coap_notls.c:105
void * coap_tls_new_client_session(coap_session_t *session UNUSED, int *connected UNUSED)
Definition: coap_notls.c:159
int coap_dtls_receive(coap_session_t *session UNUSED, const uint8_t *data UNUSED, size_t data_len UNUSED)
Definition: coap_notls.c:140
int coap_dtls_hello(coap_session_t *session UNUSED, const uint8_t *data UNUSED, size_t data_len UNUSED)
Definition: coap_notls.c:148
ssize_t coap_tls_read(coap_session_t *session UNUSED, uint8_t *data UNUSED, size_t data_len UNUSED)
Definition: coap_notls.c:177
int coap_dtls_context_set_spsk(coap_context_t *ctx UNUSED, coap_dtls_spsk_t *setup_data UNUSED)
Definition: coap_notls.c:62
ssize_t coap_tls_write(coap_session_t *session UNUSED, const uint8_t *data UNUSED, size_t data_len UNUSED)
Definition: coap_notls.c:170
coap_session_t * coap_endpoint_get_session(coap_endpoint_t *endpoint, const coap_packet_t *packet, coap_tick_t now)
Definition: coap_session.c:499
ssize_t coap_session_delay_pdu(coap_session_t *session, coap_pdu_t *pdu, coap_queue_t *node)
Definition: coap_session.c:277
void coap_session_set_mtu(coap_session_t *session, unsigned mtu)
Set the session MTU.
Definition: coap_session.c:230
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:315
size_t coap_session_max_pdu_size(const coap_session_t *session)
Get maximum acceptable PDU size.
Definition: coap_session.c:209
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:242
coap_session_t * coap_session_reference(coap_session_t *session)
Increment reference counter on a session.
Definition: coap_session.c:68
void coap_session_release(coap_session_t *session)
Decrement reference counter on a session.
Definition: coap_session.c:74
void coap_session_connected(coap_session_t *session)
Notify session that it has just connected or reconnected.
Definition: coap_session.c:363
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.
coap_session_t * coap_new_server_session(struct coap_context_t *ctx, coap_endpoint_t *ep)
Creates a new server session for the specified endpoint.
void coap_session_disconnected(coap_session_t *session, coap_nack_reason_t reason)
Notify session that it has failed.
Definition: coap_session.c:420
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:263
#define SESSIONS_ITER_SAFE(e, el, rtmp)
Definition: coap_session.h:640
#define COAP_SESSION_STATE_HANDSHAKE
Definition: coap_session.h:56
#define COAP_SESSION_STATE_CSM
Definition: coap_session.h:57
#define COAP_SESSION_TYPE_HELLO
server-side ephemeral session for responding to a client hello
Definition: coap_session.h:48
#define COAP_PROTO_NOT_RELIABLE(p)
Definition: coap_session.h:39
#define COAP_SESSION_STATE_CONNECTING
Definition: coap_session.h:55
#define COAP_PROTO_RELIABLE(p)
Definition: coap_session.h:40
#define COAP_SESSION_STATE_NONE
coap_session_state_t values
Definition: coap_session.h:54
#define COAP_SESSION_STATE_ESTABLISHED
Definition: coap_session.h:58
#define SESSIONS_ITER(e, el, rtmp)
Definition: coap_session.h:637
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:1589
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:991
void coap_io_do_epoll(coap_context_t *ctx, struct epoll_event *events, size_t nevents)
Process all the epoll events.
Definition: net.c:1650
int coap_write_block_opt(coap_block_t *block, uint16_t type, coap_pdu_t *pdu, size_t data_length)
Writes a block option of type type to message pdu.
Definition: block.c:64
#define COAP_MAX_BLOCK_SZX
The largest value for the SZX component in a Block option.
Definition: block.h:27
int coap_get_block(coap_pdu_t *pdu, uint16_t type, coap_block_t *block)
Initializes block from pdu.
Definition: block.c:36
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:203
#define COAP_DEFAULT_NSTART
The number of simultaneous outstanding interactions that a client maintains to a given server.
Definition: coap_session.h:477
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.
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 long seed)
Seeds the default random number generation function with the given seed.
Definition: coap_prng.c:74
void(* coap_method_handler_t)(coap_context_t *, struct 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
void coap_delete_all_resources(coap_context_t *context)
Deletes all resources from given context and frees their storage.
Definition: resource.c:578
#define COAP_PRINT_STATUS_ERROR
Definition: resource.h:367
void coap_dtls_startup(void)
Initialize the underlying (D)TLS Library layer.
Definition: coap_notls.c:76
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:632
void coap_dtls_shutdown(void)
Close down the underlying (D)TLS Library layer.
Definition: coap_notls.c:79
struct coap_dtls_context_t * coap_dtls_new_context(struct coap_context_t *coap_context)
Creates a new DTLS context for the given coap_context.
@ COAP_DTLS_ROLE_SERVER
Internal function invoked for server.
Definition: coap_dtls.h:483
#define COAP_DTLS_PKI_SETUP_VERSION
Latest PKI setup version.
Definition: coap_dtls.h:240
int coap_dtls_is_supported(void)
Returns 1 if support for DTLS is enabled, or 0 otherwise.
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, unsigned int 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:481
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:167
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
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:795
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 block2, uint8_t code)
Adds the specified peer as observer for resource.
Definition: resource.c:711
#define COAP_OBSERVE_CANCEL
The value COAP_OBSERVE_CANCEL in a GET request indicates that the observe relationship for (sender ad...
Definition: subscribe.h:35
#define COAP_OBSERVE_ESTABLISH
The value COAP_OBSERVE_ESTABLISH in a GET request indicates a new observe relationship for (sender ad...
Definition: subscribe.h:29
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:782
uint16_t coap_opt_filter_t[COAP_OPT_FILTER_SIZE]
Fixed-size vector we use for option filtering.
Definition: option.h:119
int coap_option_filter_set(coap_opt_filter_t filter, uint16_t type)
Sets the corresponding entry for type in filter.
Definition: option.c:494
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
int coap_option_filter_get(coap_opt_filter_t filter, uint16_t type)
Checks if type is contained in filter.
Definition: option.c:504
uint32_t coap_opt_length(const coap_opt_t *opt)
Returns the length of the given option.
Definition: option.c:209
int coap_option_filter_unset(coap_opt_filter_t filter, uint16_t type)
Clears the corresponding entry for type in filter.
Definition: option.c:499
#define COAP_OPT_ALL
Pre-defined filter that includes all options.
Definition: option.h:122
COAP_STATIC_INLINE void coap_option_filter_clear(coap_opt_filter_t f)
Clears filter f.
Definition: option.h:130
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
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_t * coap_check_option(coap_pdu_t *pdu, uint16_t type, coap_opt_iterator_t *oi)
Retrieves the first option of type type from pdu.
Definition: option.c:196
#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:178
void coap_delete_string(coap_string_t *s)
Deletes the given string and releases any memory allocated.
Definition: str.c:38
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.
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_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:100
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
coap_queue_t * coap_peek_next(coap_context_t *context)
Returns the next pdu to send without removing from sendqeue.
Definition: net.c:266
#define FRAC_BITS
The number of bits for the fractional part of ACK_TIMEOUT and ACK_RANDOM_FACTOR.
Definition: net.c:66
static ssize_t coap_send_pdu(coap_session_t *session, coap_pdu_t *pdu, coap_queue_t *node)
Definition: net.c:747
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:149
COAP_STATIC_INLINE int token_match(const uint8_t *a, size_t alen, const uint8_t *b, size_t blen)
Definition: net.c:1829
respond_t
Internal flags to control the treatment of responses (specifically in presence of the No-Response opt...
Definition: net.c:2230
@ RESPONSE_DROP
Definition: net.c:2230
@ RESPONSE_DEFAULT
Definition: net.c:2230
@ RESPONSE_SEND
Definition: net.c:2230
static void handle_request(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu)
Definition: net.c:2301
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:2895
void coap_delete_all(coap_queue_t *queue)
Removes all items from given queue and frees the allocated storage.
Definition: net.c:243
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:1749
int coap_context_get_coap_fd(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:443
static coap_str_const_t coap_default_uri_wellknown
Definition: net.c:2296
int coap_delete_node(coap_queue_t *node)
Destroys specified node.
Definition: net.c:223
static int coap_read_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now)
Definition: net.c:1529
coap_queue_t * coap_new_node(void)
Creates a new node suitable for adding to the CoAP sendqueue.
Definition: net.c:252
int coap_remove_from_queue(coap_queue_t **queue, coap_session_t *session, coap_tid_t id, coap_queue_t **node)
This function removes the element with given id from the list given list.
Definition: net.c:1785
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:274
void coap_free_context(coap_context_t *context)
CoAP stack context must be released with coap_free_context().
Definition: net.c:581
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:2033
#define MAX_BITS
The maximum number of bits for fixed point integers that are used for retransmission time calculation...
Definition: net.c:72
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:290
void coap_cleanup(void)
Definition: net.c:2937
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:2884
#define ACK_TIMEOUT
creates a Qx.FRAC_BITS from session's 'ack_timeout'
Definition: net.c:87
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:414
#define SZX_TO_BYTES(SZX)
Definition: net.c:2048
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:326
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:2051
coap_tid_t coap_send_message_type(coap_session_t *session, coap_pdu_t *request, unsigned char type)
Helper funktion to create and send a message with type (usually ACK or RST).
Definition: net.c:876
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:2204
static int coap_started
Definition: net.c:2915
static int coap_accept_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now)
Definition: net.c:1580
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:2713
coap_tid_t coap_wait_ack(coap_context_t *context, coap_session_t *session, coap_queue_t *node)
Definition: net.c:928
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:186
static size_t coap_get_context_server_hint(const coap_session_t *session, uint8_t *hint, size_t max_hint_len)
Definition: net.c:354
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:902
static int coap_write_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now)
Definition: net.c:1572
static int coap_handle_dgram_for_proto(coap_context_t *ctx, coap_session_t *session, coap_packet_t *packet)
Definition: net.c:1284
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:453
static void coap_write_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now)
Definition: net.c:1340
coap_queue_t * coap_find_transaction(coap_queue_t *queue, coap_session_t *session, coap_tid_t id)
Retrieves transaction from the queue.
Definition: net.c:1913
coap_tid_t coap_retransmit(coap_context_t *context, coap_queue_t *node)
Handles retransmissions of confirmable messages.
Definition: net.c:1191
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:649
static void coap_connect_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now)
Definition: net.c:1303
COAP_STATIC_INLINE void coap_free_node(coap_queue_t *node)
Definition: net.c:97
static enum respond_t no_response(coap_pdu_t *request, coap_pdu_t *response)
Checks for No-Response option in given request and returns 1 if response should be suppressed accordi...
Definition: net.c:2263
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:380
void coap_set_app_data(coap_context_t *ctx, void *app_data)
Stores data with the given CoAP context.
Definition: net.c:569
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:715
coap_tid_t coap_send(coap_session_t *session, coap_pdu_t *pdu)
Sends a CoAP message to given peer.
Definition: net.c:1006
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:1872
coap_tid_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:858
#define SHR_FP(val, frac)
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:1921
coap_tid_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:701
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:400
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:575
static void handle_signaling(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu)
Definition: net.c:2672
#define min(a, b)
Definition: net.c:59
void coap_context_set_keepalive(coap_context_t *context, unsigned int seconds)
Set the context keepalive timer for sessions.
Definition: net.c:439
static void coap_read_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now)
Definition: net.c:1387
void coap_startup(void)
Definition: net.c:2917
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:1835
#define FP1
int coap_join_mcast_group(coap_context_t *ctx, const char *group_name)
Function interface for joining a multicast group for listening.
Definition: net.c:2946
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:429
#define ACK_RANDOM_FACTOR
creates a Qx.FRAC_BITS from session's 'ack_random_factor'
Definition: net.c:83
COAP_STATIC_INLINE coap_queue_t * coap_malloc_node(void)
Definition: net.c:92
#define INET6_ADDRSTRLEN
Definition: net.c:55
static void handle_response(coap_context_t *context, coap_session_t *session, coap_pdu_t *sent, coap_pdu_t *rcvd)
Definition: net.c:2653
COAP_STATIC_INLINE coap_tid_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:516
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:25
int coap_update_option(coap_pdu_t *pdu, uint16_t type, size_t len, const uint8_t *data)
Updates existing first option of given type in the pdu with the new data.
Definition: pdu.c:303
void coap_delete_pdu(coap_pdu_t *pdu)
Dispose of an CoAP PDU and frees associated storage.
Definition: pdu.c:127
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:593
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:538
coap_pdu_t * coap_pdu_init(uint8_t type, uint8_t code, uint16_t tid, size_t size)
Creates a new CoAP PDU with at least enough storage space for the given size maximum message size.
Definition: pdu.c:79
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:191
size_t coap_add_option(coap_pdu_t *pdu, uint16_t type, size_t len, const uint8_t *data)
Adds option of given type to pdu that is passed as first parameter.
Definition: pdu.c:344
int coap_pdu_parse_opt(coap_pdu_t *pdu)
Verify consistency in the given CoAP PDU structure and locate the data.
Definition: pdu.c:679
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:426
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:797
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:772
const char * coap_response_phrase(unsigned char code)
Returns a human-readable response phrase for the specified CoAP response code.
Definition: pdu.c:497
size_t coap_insert_option(coap_pdu_t *pdu, uint16_t type, size_t len, const uint8_t *data)
Inserts option of given type in the pdu with the appropriate data.
Definition: pdu.c:214
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:561
int coap_pdu_resize(coap_pdu_t *pdu, size_t new_size)
Dynamically grows the size of pdu to new_size.
Definition: pdu.c:140
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:414
#define COAP_PDU_IS_RESPONSE(pdu)
Definition: pdu.h:314
#define COAP_OPTION_HOP_LIMIT
Definition: pdu.h:136
#define COAP_OPTION_NORESPONSE
Definition: pdu.h:145
#define COAP_OPTION_URI_HOST
Definition: pdu.h:123
#define COAP_OPTION_IF_MATCH
Definition: pdu.h:122
#define COAP_OPTION_BLOCK2
Definition: pdu.h:139
#define COAP_OPTION_CONTENT_FORMAT
Definition: pdu.h:131
#define COAP_OPTION_SIZE2
Definition: pdu.h:141
#define COAP_PROTO_TCP
Definition: pdu.h:346
#define COAP_OPTION_BLOCK1
Definition: pdu.h:140
#define COAP_OPTION_PROXY_SCHEME
Definition: pdu.h:143
#define COAP_DEFAULT_PORT
Definition: pdu.h:26
#define COAP_SIGNALING_PONG
Definition: pdu.h:184
#define COAP_OPTION_URI_QUERY
Definition: pdu.h:135
#define COAP_DROPPED_RESPONSE
Indicates that a response is suppressed.
Definition: pdu.h:253
#define COAP_OPTION_IF_NONE_MATCH
Definition: pdu.h:125
@ COAP_REQUEST_DELETE
Definition: pdu.h:85
@ COAP_REQUEST_GET
Definition: pdu.h:82
@ COAP_REQUEST_FETCH
Definition: pdu.h:86
#define COAP_PDU_DELAYED
Definition: pdu.h:255
#define COAP_OPTION_URI_PATH
Definition: pdu.h:130
#define COAP_SIGNALING_CSM
Definition: pdu.h:182
#define COAP_RESPONSE_CODE(N)
Definition: pdu.h:155
#define COAP_RESPONSE_CLASS(C)
Definition: pdu.h:158
#define COAP_PROTO_TLS
Definition: pdu.h:347
#define COAP_PDU_IS_EMPTY(pdu)
Definition: pdu.h:312
#define COAP_DEFAULT_MAX_PDU_RX_SIZE
Definition: pdu.h:53
#define COAP_PDU_IS_SIGNALING(pdu)
Definition: pdu.h:315
#define COAP_SIGNALING_OPTION_BLOCK_WISE_TRANSFER
Definition: pdu.h:190
#define COAP_MESSAGE_NON
Definition: pdu.h:75
#define COAP_OPTION_CONTENT_TYPE
Definition: pdu.h:132
#define COAP_MESSAGE_RST
Definition: pdu.h:77
#define COAP_SIGNALING_OPTION_CUSTODY
Definition: pdu.h:192
#define COAP_MESSAGE_ACK
Definition: pdu.h:76
#define COAP_MESSAGE_CON
Definition: pdu.h:74
#define COAPS_DEFAULT_PORT
Definition: pdu.h:27
#define COAP_PROTO_DTLS
Definition: pdu.h:345
#define COAP_OPTION_URI_PORT
Definition: pdu.h:127
int coap_tid_t
coap_tid_t is used to store CoAP transaction id, i.e.
Definition: pdu.h:244
#define COAP_OPTION_ACCEPT
Definition: pdu.h:137
#define COAP_SIGNALING_RELEASE
Definition: pdu.h:185
#define COAP_OPTION_ETAG
Definition: pdu.h:124
#define COAP_OPTION_PROXY_URI
Definition: pdu.h:142
#define COAP_SIGNALING_PING
Definition: pdu.h:183
#define COAP_OPTION_OBSERVE
Definition: pdu.h:126
#define COAP_PDU_IS_REQUEST(pdu)
Definition: pdu.h:313
#define COAP_DEFAULT_URI_WELLKNOWN
well-known resources URI
Definition: pdu.h:70
#define COAP_PROTO_UDP
Definition: pdu.h:344
#define COAP_MEDIATYPE_APPLICATION_LINK_FORMAT
Definition: pdu.h:202
#define COAP_SIGNALING_OPTION_MAX_MESSAGE_SIZE
Definition: pdu.h:189
#define COAP_SIGNALING_ABORT
Definition: pdu.h:186
#define COAP_INVALID_TID
Indicates an invalid transaction id.
Definition: pdu.h:247
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:603
void coap_check_notify(coap_context_t *context)
Checks for all known resources, if they are dirty and notifies subscribed observers.
Definition: resource.c:999
void coap_handle_failed_notify(coap_context_t *context, coap_session_t *session, const coap_binary_t *token)
Definition: resource.c:1062
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
#define COAP_RESOURCE_CHECK_TIME
The interval in seconds to check if resources have changed.
Definition: resource.h:20
#define RESOURCES_ITER(r, tmp)
Definition: resource.h:428
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
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.
Definition: net.h:141
coap_tick_t sendqueue_basetime
The time stamp in the first element of the sendqeue is relative to sendqueue_basetime.
Definition: net.h:159
coap_pong_handler_t pong_handler
Definition: net.h:179
ssize_t(* network_read)(coap_socket_t *sock, struct coap_packet_t *packet)
Definition: net.h:189
unsigned int csm_timeout
Timeout for waiting for a CSM from the remote side.
Definition: net.h:203
void * app
application-specific data
Definition: net.h:209
struct coap_resource_t * unknown_resource
can be used for handling unknown resources
Definition: net.h:145
coap_session_t * sessions
client sessions
Definition: net.h:162
coap_nack_handler_t nack_handler
Definition: net.h:177
unsigned int ping_timeout
Minimum inactivity time before sending a ping message.
Definition: net.h:202
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)
Definition: net.h:192
ssize_t(* network_send)(coap_socket_t *sock, const coap_session_t *session, const uint8_t *data, size_t datalen)
Definition: net.h:187
uint16_t * cache_ignore_options
CoAP options to ignore when creating a cache-key.
Definition: net.h:207
void * dtls_context
Definition: net.h:195
coap_opt_filter_t known_options
Definition: net.h:142
coap_ping_handler_t ping_handler
Definition: net.h:178
size_t cache_ignore_count
The number of CoAP options to ignore when creating a cache-key.
Definition: net.h:208
coap_queue_t * sendqueue
Definition: net.h:160
coap_response_handler_t response_handler
Definition: net.h:176
struct coap_resource_t * resources
hash table or list of known resources
Definition: net.h:143
coap_cache_entry_t * cache
CoAP cache-entry cache.
Definition: net.h:206
coap_endpoint_t * endpoint
the endpoints used for listening
Definition: net.h:161
size_t(* get_server_hint)(const coap_session_t *session, uint8_t *hint, size_t max_hint_len)
Definition: net.h:193
coap_event_handler_t handle_event
Callback function that is used to signal events to the application.
Definition: net.h:185
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)
Definition: net.h:191
coap_dtls_spsk_t spsk_setup_data
Contains the initial PSK server setup data.
Definition: net.h:197
struct coap_resource_t * proxy_uri_resource
can be used for handling proxy URI resources
Definition: net.h:147
The structure that holds the Client PSK information.
Definition: coap_dtls.h:308
coap_bin_const_t key
Definition: coap_dtls.h:310
coap_bin_const_t identity
Definition: coap_dtls.h:309
coap_dtls_cpsk_info_t psk_info
Client PSK definition.
Definition: coap_dtls.h:368
The structure used for defining the PKI setup data to be used.
Definition: coap_dtls.h:245
uint8_t version
Definition: coap_dtls.h:246
The structure that holds the Server Pre-Shared Key and Identity Hint information.
Definition: coap_dtls.h:375
coap_bin_const_t hint
Definition: coap_dtls.h:376
coap_bin_const_t key
Definition: coap_dtls.h:377
The structure used for defining the Server PSK setup data to be used.
Definition: coap_dtls.h:426
coap_dtls_spsk_info_t psk_info
Server PSK definition.
Definition: coap_dtls.h:456
Abstraction of virtual endpoint that can be attached to coap_context_t.
struct coap_context_t * context
endpoint's context
struct 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
Iterator to run through PDU options.
Definition: option.h:186
uint16_t type
decoded option type
Definition: option.h:188
coap_addr_tuple_t addr_info
local and remote addresses
Definition: coap_io.h:206
unsigned char payload[COAP_RXBUFFER_SIZE]
payload
Definition: coap_io.h:209
structure for CoAP PDUs token, if any, follows the fixed size header, then options until payload mark...
Definition: pdu.h:287
uint8_t type
message type
Definition: pdu.h:288
uint8_t * token
first byte of token, if any, or options
Definition: pdu.h:298
size_t max_size
maximum size for token, options and payload, or zero for variable size pdu
Definition: pdu.h:297
uint16_t tid
transaction id, if any, in regular host byte order
Definition: pdu.h:293
uint8_t code
request method (value 1–31) or response code (value 64-255)
Definition: pdu.h:289
uint8_t token_length
length of Token
Definition: pdu.h:292
uint8_t hdr_size
actual size used for protocol-specific header
Definition: pdu.h:291
uint8_t * data
first byte of payload, if any
Definition: pdu.h:299
size_t used_size
used bytes of storage for token, options and payload
Definition: pdu.h:296
size_t alloc_size
allocated storage for token, options and payload
Definition: pdu.h:295
Queue entry.
Definition: net.h:36
coap_session_t * session
the CoAP session
Definition: net.h:42
coap_pdu_t * pdu
the CoAP PDU to send
Definition: net.h:44
unsigned int timeout
the randomized timeout value
Definition: net.h:41
struct coap_queue_t * next
Definition: net.h:37
coap_tick_t t
when to send PDU for the next time
Definition: net.h:38
coap_tid_t id
CoAP transaction id.
Definition: net.h:43
unsigned char retransmit_cnt
retransmission counter, will be removed when zero
Definition: net.h:39
coap_str_const_t ** proxy_name_list
Array valid names this host is known by (proxy support)
Definition: resource.h:135
coap_str_const_t * uri_path
Request URI Path for this resource.
Definition: resource.h:113
coap_method_handler_t handler[7]
Used to store handlers for the seven coap methods GET, POST, PUT, DELETE, FETCH, PATCH and IPATCH.
Definition: resource.h:101
unsigned int is_proxy_uri
resource created for proxy URI handler
Definition: resource.h:92
unsigned int is_unknown
resource created for unknown handler
Definition: resource.h:91
unsigned int observable
can be observed
Definition: resource.h:89
size_t proxy_name_count
Count of valid names this host is known by (proxy support)
Definition: resource.h:130
coap_tick_t last_pong
Definition: coap_session.h:87
coap_bin_const_t * psk_key
If client, this field contains the current pre-shared key for server; When this field is NULL,...
Definition: coap_session.h:100
coap_endpoint_t * endpoint
session's endpoint
Definition: coap_session.h:72
coap_tick_t last_rx_tx
Definition: coap_session.h:84
coap_socket_t sock
socket object for the session, if any
Definition: coap_session.h:71
unsigned int max_retransmit
maximum re-transmit count (default 4)
Definition: coap_session.h:119
coap_pdu_t * partial_pdu
incomplete incoming pdu
Definition: coap_session.h:83
coap_bin_const_t * psk_identity
If client, this field contains the current identity for server; When this field is NULL,...
Definition: coap_session.h:91
coap_session_state_t state
current state of relationaship with peer
Definition: coap_session.h:63
uint8_t read_header[8]
storage space for header of incoming message header
Definition: coap_session.h:81
coap_addr_tuple_t addr_info
key: remote/local address info
Definition: coap_session.h:69
coap_proto_t proto
protocol used
Definition: coap_session.h:61
coap_bin_const_t * psk_hint
If client, this field contains the server provided identity hint.
Definition: coap_session.h:109
coap_dtls_cpsk_t cpsk_setup_data
client provided PSK initial setup data
Definition: coap_session.h:89
struct coap_queue_t * delayqueue
list of delayed messages waiting to be sent
Definition: coap_session.h:79
struct coap_context_t * context
session's context
Definition: coap_session.h:73
size_t partial_read
if > 0 indicates number of bytes already read for an incoming message
Definition: coap_session.h:82
void * tls
security parameters
Definition: coap_session.h:74
uint8_t csm_block_supported
CSM TCP blocks supported.
Definition: coap_session.h:77
uint8_t con_active
Active CON request sent.
Definition: coap_session.h:76
coap_address_t local_if
optional local interface address
Definition: coap_session.h:67
coap_tick_t last_ping
Definition: coap_session.h:86
coap_session_type_t type
client or server side socket
Definition: coap_session.h:62
coap_tick_t last_tx_rst
Definition: coap_session.h:85
coap_tid_t last_ping_mid
the last keepalive message id that was used in this session
Definition: coap_session.h:78
size_t partial_write
if > 0 indicates number of bytes already written from the pdu at the head of sendqueue
Definition: coap_session.h:80
coap_tick_t csm_tx
Definition: coap_session.h:88
coap_endpoint_t * endpoint
Definition: coap_io.h:69
coap_fd_t fd
Definition: coap_io.h:59
struct coap_session_t * session
Definition: coap_io.h:65
coap_socket_flags_t flags
Definition: coap_io.h:64
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
size_t token_length
actual length of token
struct coap_session_t * session
subscriber session
uint16_t tid
request type code (GET/FETCH)
Representation of parsed URI.
Definition: uri.h:38
coap_str_const_t host
host part of the URI
Definition: uri.h:39
coap_string_t * coap_get_uri_path(const coap_pdu_t *request)
Definition: uri.c:604
coap_string_t * coap_get_query(const coap_pdu_t *request)
Definition: uri.c:554
#define HASH_ITER(hh, head, el, tmp)
Definition: uthash.h:1031
unsigned char uint8_t
Definition: uthash.h:79
#define LL_DELETE(head, del)
Definition: utlist.h:385
#define LL_FOREACH(head, el)
Definition: utlist.h:413
#define LL_FOREACH_SAFE(head, el, tmp)
Definition: utlist.h:419