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