libcoap  4.2.0rc1
net.c
Go to the documentation of this file.
1 /* net.c -- CoAP network interface
2  *
3  * Copyright (C) 2010--2016 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_config.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 HAVE_WS2TCPIP_H
35 #include <ws2tcpip.h>
36 #endif
37 
38 #ifdef WITH_LWIP
39 #include <lwip/pbuf.h>
40 #include <lwip/udp.h>
41 #include <lwip/timeouts.h>
42 #endif
43 
44 #include "libcoap.h"
45 #include "utlist.h"
46 #include "debug.h"
47 #include "mem.h"
48 #include "str.h"
49 #include "async.h"
50 #include "resource.h"
51 #include "option.h"
52 #include "encode.h"
53 #include "block.h"
54 #include "net.h"
55 #include "utlist.h"
56 
57 #ifndef min
58 #define min(a,b) ((a) < (b) ? (a) : (b))
59 #endif
60 
65 #define FRAC_BITS 6
66 
71 #define MAX_BITS 8
72 
73 #if FRAC_BITS > 8
74 #error FRAC_BITS must be less or equal 8
75 #endif
76 
78 #define Q(frac,fval) ((uint16_t)(((1 << (frac)) * fval.integer_part) + \
79  ((1 << (frac)) * fval.fractional_part + 500)/1000))
80 
82 #define ACK_RANDOM_FACTOR \
83  Q(FRAC_BITS, session->ack_random_factor)
84 
86 #define ACK_TIMEOUT Q(FRAC_BITS, session->ack_timeout)
87 
88 #if !defined(WITH_LWIP) && !defined(WITH_CONTIKI)
89 
93 }
94 
98 }
99 #endif /* !defined(WITH_LWIP) && !defined(WITH_CONTIKI) */
100 
102 
103 #ifdef WITH_LWIP
104 
105 #include <lwip/memp.h>
106 
107 static void coap_retransmittimer_execute(void *arg);
108 static void coap_retransmittimer_restart(coap_context_t *ctx);
109 
112  return (coap_queue_t *)memp_malloc(MEMP_COAP_NODE);
113 }
114 
117  memp_free(MEMP_COAP_NODE, node);
118 }
119 
120 #endif /* WITH_LWIP */
121 #ifdef WITH_CONTIKI
122 # ifndef DEBUG
123 # define DEBUG DEBUG_PRINT
124 # endif /* DEBUG */
125 
126 #include "mem.h"
127 #include "net/ip/uip-debug.h"
128 
129 #define UIP_IP_BUF ((struct uip_ip_hdr *)&uip_buf[UIP_LLH_LEN])
130 #define UIP_UDP_BUF ((struct uip_udp_hdr *)&uip_buf[UIP_LLIPH_LEN])
131 
132 void coap_resources_init();
133 
134 unsigned char initialized = 0;
135 coap_context_t the_coap_context;
136 
137 PROCESS(coap_retransmit_process, "message retransmit process");
138 
142 }
143 
146  coap_free_type(COAP_NODE, node);
147 }
148 #endif /* WITH_CONTIKI */
149 
150 unsigned int
152  unsigned int result = 0;
153  coap_tick_diff_t delta = now - ctx->sendqueue_basetime;
154 
155  if (ctx->sendqueue) {
156  /* delta < 0 means that the new time stamp is before the old. */
157  if (delta <= 0) {
158  ctx->sendqueue->t -= delta;
159  } else {
160  /* This case is more complex: The time must be advanced forward,
161  * thus possibly leading to timed out elements at the queue's
162  * start. For every element that has timed out, its relative
163  * time is set to zero and the result counter is increased. */
164 
165  coap_queue_t *q = ctx->sendqueue;
166  coap_tick_t t = 0;
167  while (q && (t + q->t < (coap_tick_t)delta)) {
168  t += q->t;
169  q->t = 0;
170  result++;
171  q = q->next;
172  }
173 
174  /* finally adjust the first element that has not expired */
175  if (q) {
176  q->t = (coap_tick_t)delta - t;
177  }
178  }
179  }
180 
181  /* adjust basetime */
182  ctx->sendqueue_basetime += delta;
183 
184  return result;
185 }
186 
187 int
189  coap_queue_t *p, *q;
190  if (!queue || !node)
191  return 0;
192 
193  /* set queue head if empty */
194  if (!*queue) {
195  *queue = node;
196  return 1;
197  }
198 
199  /* replace queue head if PDU's time is less than head's time */
200  q = *queue;
201  if (node->t < q->t) {
202  node->next = q;
203  *queue = node;
204  q->t -= node->t; /* make q->t relative to node->t */
205  return 1;
206  }
207 
208  /* search for right place to insert */
209  do {
210  node->t -= q->t; /* make node-> relative to q->t */
211  p = q;
212  q = q->next;
213  } while (q && q->t <= node->t);
214 
215  /* insert new item */
216  if (q) {
217  q->t -= node->t; /* make q->t relative to node->t */
218  }
219  node->next = q;
220  p->next = node;
221  return 1;
222 }
223 
224 int
226  if (!node)
227  return 0;
228 
229  coap_delete_pdu(node->pdu);
230  if ( node->session )
232  coap_free_node(node);
233 
234  return 1;
235 }
236 
237 void
239  if (!queue)
240  return;
241 
242  coap_delete_all(queue->next);
243  coap_delete_node(queue);
244 }
245 
246 coap_queue_t *
248  coap_queue_t *node;
249  node = coap_malloc_node();
250 
251  if (!node) {
252 #ifndef NDEBUG
253  coap_log(LOG_WARNING, "coap_new_node: malloc\n");
254 #endif
255  return NULL;
256  }
257 
258  memset(node, 0, sizeof(*node));
259  return node;
260 }
261 
262 coap_queue_t *
264  if (!context || !context->sendqueue)
265  return NULL;
266 
267  return context->sendqueue;
268 }
269 
270 coap_queue_t *
272  coap_queue_t *next;
273 
274  if (!context || !context->sendqueue)
275  return NULL;
276 
277  next = context->sendqueue;
278  context->sendqueue = context->sendqueue->next;
279  if (context->sendqueue) {
280  context->sendqueue->t += next->t;
281  }
282  next->next = NULL;
283  return next;
284 }
285 
286 static size_t
288  const coap_session_t *session,
289  const uint8_t *hint, size_t hint_len,
290  uint8_t *identity, size_t *identity_len, size_t max_identity_len,
291  uint8_t *psk, size_t max_psk_len
292 ) {
293  (void)hint;
294  (void)hint_len;
295  if (session->psk_identity && session->psk_identity_len > 0 && session->psk_key && session->psk_key_len > 0) {
296  if (session->psk_identity_len <= max_identity_len && session->psk_key_len <= max_psk_len) {
297  memcpy(identity, session->psk_identity, session->psk_identity_len);
298  memcpy(psk, session->psk_key, session->psk_key_len);
299  *identity_len = session->psk_identity_len;
300  return session->psk_key_len;
301  }
302  } else if (session->context && session->context->psk_key && session->context->psk_key_len > 0) {
303  if (session->context->psk_key_len <= max_psk_len) {
304  *identity_len = 0;
305  memcpy(psk, session->context->psk_key, session->context->psk_key_len);
306  return session->context->psk_key_len;
307  }
308  }
309  *identity_len = 0;
310  return 0;
311 }
312 
313 static size_t
315  const coap_session_t *session,
316  const uint8_t *identity, size_t identity_len,
317  uint8_t *psk, size_t max_psk_len
318 ) {
319  (void)identity;
320  (void)identity_len;
321  const coap_context_t *ctx = session->context;
322  if (ctx && ctx->psk_key && ctx->psk_key_len > 0 && ctx->psk_key_len <= max_psk_len) {
323  memcpy(psk, ctx->psk_key, ctx->psk_key_len);
324  return ctx->psk_key_len;
325  }
326  return 0;
327 }
328 
329 static size_t
331  const coap_session_t *session,
332  uint8_t *hint, size_t max_hint_len
333 ) {
334  const coap_context_t *ctx = session->context;
335  if (ctx && ctx->psk_hint && ctx->psk_hint_len > 0 && ctx->psk_hint_len <= max_hint_len) {
336  memcpy(hint, ctx->psk_hint, ctx->psk_hint_len);
337  return ctx->psk_hint_len;
338  }
339  return 0;
340 }
341 
343  const char *hint,
344  const uint8_t *key, size_t key_len
345 ) {
346 
347  if (ctx->psk_hint)
348  coap_free(ctx->psk_hint);
349  ctx->psk_hint = NULL;
350  ctx->psk_hint_len = 0;
351 
352  if (hint) {
353  size_t hint_len = strlen(hint);
354  ctx->psk_hint = (uint8_t*)coap_malloc(hint_len);
355  if (ctx->psk_hint) {
356  memcpy(ctx->psk_hint, hint, hint_len);
357  ctx->psk_hint_len = hint_len;
358  } else {
359  coap_log(LOG_ERR, "No memory to store PSK hint\n");
360  return 0;
361  }
362  }
363 
364  if (ctx->psk_key)
365  coap_free(ctx->psk_key);
366  ctx->psk_key = NULL;
367  ctx->psk_key_len = 0;
368 
369  if (key && key_len > 0) {
370  ctx->psk_key = (uint8_t *)coap_malloc(key_len);
371  if (ctx->psk_key) {
372  memcpy(ctx->psk_key, key, key_len);
373  ctx->psk_key_len = key_len;
374  } else {
375  coap_log(LOG_ERR, "No memory to store PSK key\n");
376  return 0;
377  }
378  }
379  if (coap_dtls_is_supported()) {
381  }
382  return 0;
383 }
384 
386  coap_dtls_pki_t* setup_data
387 ) {
388  if (!setup_data)
389  return 0;
390  if (setup_data->version != COAP_DTLS_PKI_SETUP_VERSION) {
391  coap_log(LOG_ERR, "coap_context_set_pki: Wrong version of setup_data\n");
392  return 0;
393  }
394  if (coap_dtls_is_supported()) {
395  return coap_dtls_context_set_pki(ctx, setup_data, COAP_DTLS_ROLE_SERVER);
396  }
397  return 0;
398 }
399 
401  const char *ca_file,
402  const char *ca_dir
403 ) {
404  if (coap_dtls_is_supported()) {
405  return coap_dtls_context_set_pki_root_cas(ctx, ca_file, ca_dir);
406  }
407  return 0;
408 }
409 
410 void coap_context_set_keepalive(coap_context_t *context, unsigned int seconds) {
411  context->ping_timeout = seconds;
412 }
413 
416  const coap_address_t *listen_addr) {
417  coap_context_t *c;
418 
419 #ifdef WITH_CONTIKI
420  if (initialized)
421  return NULL;
422 #endif /* WITH_CONTIKI */
423 
424  coap_startup();
425 
426 #ifndef WITH_CONTIKI
428 #endif /* not WITH_CONTIKI */
429 
430 #ifndef WITH_CONTIKI
431  if (!c) {
432 #ifndef NDEBUG
433  coap_log(LOG_EMERG, "coap_init: malloc:\n");
434 #endif
435  return NULL;
436  }
437 #endif /* not WITH_CONTIKI */
438 #ifdef WITH_CONTIKI
439  coap_resources_init();
441 
442  c = &the_coap_context;
443  initialized = 1;
444 #endif /* WITH_CONTIKI */
445 
446  memset(c, 0, sizeof(coap_context_t));
447 
448  if (coap_dtls_is_supported()) {
450  if (!c->dtls_context) {
451  coap_log(LOG_EMERG, "coap_init: no DTLS context available\n");
453  return NULL;
454  }
455  }
456 
457  /* set default CSM timeout */
458  c->csm_timeout = 30;
459 
460  /* initialize message id */
461  prng((unsigned char *)&c->message_id, sizeof(uint16_t));
462 
463  if (listen_addr) {
464  coap_endpoint_t *endpoint = coap_new_endpoint(c, listen_addr, COAP_PROTO_UDP);
465  if (endpoint == NULL) {
466  goto onerror;
467  }
468  }
469 
470 #if !defined(WITH_LWIP)
473 #endif
474 
478 
479 #ifdef WITH_CONTIKI
480  process_start(&coap_retransmit_process, (char *)c);
481 
482  PROCESS_CONTEXT_BEGIN(&coap_retransmit_process);
483 #ifndef WITHOUT_OBSERVE
484  etimer_set(&c->notify_timer, COAP_RESOURCE_CHECK_TIME * COAP_TICKS_PER_SECOND);
485 #endif /* WITHOUT_OBSERVE */
486  /* the retransmit timer must be initialized to some large value */
487  etimer_set(&the_coap_context.retransmit_timer, 0xFFFF);
488  PROCESS_CONTEXT_END(&coap_retransmit_process);
489 #endif /* WITH_CONTIKI */
490 
491  return c;
492 
493 onerror:
495  return NULL;
496 }
497 
498 void
499 coap_set_app_data(coap_context_t *ctx, void *app_data) {
500  assert(ctx);
501  ctx->app = app_data;
502 }
503 
504 void *
506  assert(ctx);
507  return ctx->app;
508 }
509 
510 void
512  coap_endpoint_t *ep, *tmp;
513  coap_session_t *sp, *stmp;
514 
515  if (!context)
516  return;
517 
518  coap_delete_all(context->sendqueue);
519 
520 #ifdef WITH_LWIP
521  context->sendqueue = NULL;
522  coap_retransmittimer_restart(context);
523 #endif
524 
525  coap_delete_all_resources(context);
526 
527  LL_FOREACH_SAFE(context->endpoint, ep, tmp) {
528  coap_free_endpoint(ep);
529  }
530 
531  LL_FOREACH_SAFE(context->sessions, sp, stmp) {
533  }
534 
535  if (context->dtls_context)
537 
538  if (context->psk_hint)
539  coap_free(context->psk_hint);
540 
541  if (context->psk_key)
542  coap_free(context->psk_key);
543 
544 #ifndef WITH_CONTIKI
545  coap_free_type(COAP_CONTEXT, context);
546 #endif/* not WITH_CONTIKI */
547 #ifdef WITH_CONTIKI
548  memset(&the_coap_context, 0, sizeof(coap_context_t));
549  initialized = 0;
550 #endif /* WITH_CONTIKI */
551 }
552 
553 int
555  coap_pdu_t *pdu,
556  coap_opt_filter_t unknown) {
557 
558  coap_opt_iterator_t opt_iter;
559  int ok = 1;
560 
561  coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
562 
563  while (coap_option_next(&opt_iter)) {
564 
565  /* The following condition makes use of the fact that
566  * coap_option_getb() returns -1 if type exceeds the bit-vector
567  * filter. As the vector is supposed to be large enough to hold
568  * the largest known option, we know that everything beyond is
569  * bad.
570  */
571  if (opt_iter.type & 0x01) {
572  /* first check the built-in critical options */
573  switch (opt_iter.type) {
580  case COAP_OPTION_ACCEPT:
583  case COAP_OPTION_BLOCK2:
584  case COAP_OPTION_BLOCK1:
585  break;
586  default:
587  if (coap_option_filter_get(ctx->known_options, opt_iter.type) <= 0) {
588  debug("unknown critical option %d\n", opt_iter.type);
589  ok = 0;
590 
591  /* When opt_iter.type is beyond our known option range,
592  * coap_option_filter_set() will return -1 and we are safe to leave
593  * this loop. */
594  if (coap_option_filter_set(unknown, opt_iter.type) == -1) {
595  break;
596  }
597  }
598  }
599  }
600  }
601 
602  return ok;
603 }
604 
607  coap_pdu_t *response;
608  coap_tid_t result = COAP_INVALID_TID;
609 
610  if (request && request->type == COAP_MESSAGE_CON &&
611  COAP_PROTO_NOT_RELIABLE(session->proto)) {
612  response = coap_pdu_init(COAP_MESSAGE_ACK, 0, request->tid, 0);
613  if (response)
614  result = coap_send(session, response);
615  }
616  return result;
617 }
618 
619 ssize_t
621  ssize_t bytes_written = -1;
622  assert(pdu->hdr_size > 0);
623  switch(session->proto) {
624  case COAP_PROTO_UDP:
625  bytes_written = coap_session_send(session, pdu->token - pdu->hdr_size,
626  pdu->used_size + pdu->hdr_size);
627  break;
628  case COAP_PROTO_DTLS:
629  bytes_written = coap_dtls_send(session, pdu->token - pdu->hdr_size,
630  pdu->used_size + pdu->hdr_size);
631  break;
632  case COAP_PROTO_TCP:
633  bytes_written = coap_session_write(session, pdu->token - pdu->hdr_size,
634  pdu->used_size + pdu->hdr_size);
635  break;
636  case COAP_PROTO_TLS:
637  bytes_written = coap_tls_write(session, pdu->token - pdu->hdr_size,
638  pdu->used_size + pdu->hdr_size);
639  break;
640  default:
641  break;
642  }
643  coap_show_pdu(LOG_DEBUG, pdu);
644  return bytes_written;
645 }
646 
647 static ssize_t
649  ssize_t bytes_written;
650 
651 #ifdef WITH_LWIP
652 
653  coap_socket_t *sock = &session->sock;
654  if (sock->flags == COAP_SOCKET_EMPTY) {
655  assert(session->endpoint != NULL);
656  sock = &session->endpoint->sock;
657  }
658  if (pdu->type == COAP_MESSAGE_CON && COAP_PROTO_NOT_RELIABLE(session->proto))
659  session->con_active++;
660 
661  bytes_written = coap_socket_send_pdu(sock, session, pdu);
662  if (LOG_DEBUG <= coap_get_log_level()) {
663  coap_show_pdu(LOG_DEBUG, pdu);
664  }
665  coap_ticks(&session->last_rx_tx);
666 
667 #else
668 
669  /* Do not send error responses for requests that were received via
670  * IP multicast.
671  * FIXME: If No-Response option indicates interest, these responses
672  * must not be dropped. */
673  if (coap_is_mcast(&session->local_addr) &&
674  COAP_RESPONSE_CLASS(pdu->code) > 2) {
675  return COAP_DROPPED_RESPONSE;
676  }
677 
678  if (session->state == COAP_SESSION_STATE_NONE) {
679  if (session->proto == COAP_PROTO_DTLS && !session->tls) {
680  session->tls = coap_dtls_new_client_session(session);
681  if (session->tls) {
683  return coap_session_delay_pdu(session, pdu, node);
684  }
685  coap_handle_event(session->context, COAP_EVENT_DTLS_ERROR, session);
686  return -1;
687  } else if(COAP_PROTO_RELIABLE(session->proto)) {
689  &session->sock, &session->local_if, &session->remote_addr,
691  &session->local_addr, &session->remote_addr
692  )) {
693  coap_handle_event(session->context, COAP_EVENT_TCP_FAILED, session);
694  return -1;
695  }
696  session->last_ping = 0;
697  session->last_pong = 0;
698  session->csm_tx = 0;
699  coap_ticks( &session->last_rx_tx );
700  if ((session->sock.flags & COAP_SOCKET_WANT_CONNECT) != 0) {
702  return coap_session_delay_pdu(session, pdu, node);
703  }
705  if (session->proto == COAP_PROTO_TLS) {
706  int connected = 0;
708  session->tls = coap_tls_new_client_session(session, &connected);
709  if (session->tls) {
710  if (connected) {
712  coap_session_send_csm(session);
713  }
714  return coap_session_delay_pdu(session, pdu, node);
715  }
716  coap_handle_event(session->context, COAP_EVENT_DTLS_ERROR, session);
718  return -1;
719  } else {
720  coap_session_send_csm(session);
721  }
722  } else {
723  return -1;
724  }
725  }
726 
727  if (session->state != COAP_SESSION_STATE_ESTABLISHED ||
728  (pdu->type == COAP_MESSAGE_CON && session->con_active >= COAP_DEFAULT_NSTART)) {
729  return coap_session_delay_pdu(session, pdu, node);
730  }
731 
732  if ((session->sock.flags & COAP_SOCKET_NOT_EMPTY) &&
733  (session->sock.flags & COAP_SOCKET_WANT_WRITE))
734  return coap_session_delay_pdu(session, pdu, node);
735 
736  if (pdu->type == COAP_MESSAGE_CON && COAP_PROTO_NOT_RELIABLE(session->proto))
737  session->con_active++;
738 
739  bytes_written = coap_session_send_pdu(session, pdu);
740 
741 #endif /* WITH_LWIP */
742 
743  return bytes_written;
744 }
745 
748  coap_pdu_t *request,
749  unsigned char code,
750  coap_opt_filter_t opts) {
751  coap_pdu_t *response;
752  coap_tid_t result = COAP_INVALID_TID;
753 
754  assert(request);
755  assert(session);
756 
757  response = coap_new_error_response(request, code, opts);
758  if (response)
759  result = coap_send(session, response);
760 
761  return result;
762 }
763 
765 coap_send_message_type(coap_session_t *session, coap_pdu_t *request, unsigned char type) {
766  coap_pdu_t *response;
767  coap_tid_t result = COAP_INVALID_TID;
768 
769  if (request) {
770  response = coap_pdu_init(type, 0, request->tid, 0);
771  if (response)
772  result = coap_send(session, response);
773  }
774  return result;
775 }
776 
790 unsigned int
791 coap_calc_timeout(coap_session_t *session, unsigned char r) {
792  unsigned int result;
793 
794  /* The integer 1.0 as a Qx.FRAC_BITS */
795 #define FP1 Q(FRAC_BITS, ((coap_fixed_point_t){1,0}))
796 
797  /* rounds val up and right shifts by frac positions */
798 #define SHR_FP(val,frac) (((val) + (1 << ((frac) - 1))) >> (frac))
799 
800  /* Inner term: multiply ACK_RANDOM_FACTOR by Q0.MAX_BITS[r] and
801  * make the result a rounded Qx.FRAC_BITS */
802  result = SHR_FP((ACK_RANDOM_FACTOR - FP1) * r, MAX_BITS);
803 
804  /* Add 1 to the inner term and multiply with ACK_TIMEOUT, then
805  * make the result a rounded Qx.FRAC_BITS */
806  result = SHR_FP(((result + FP1) * ACK_TIMEOUT), FRAC_BITS);
807 
808  /* Multiply with COAP_TICKS_PER_SECOND to yield system ticks
809  * (yields a Qx.FRAC_BITS) and shift to get an integer */
810  return SHR_FP((COAP_TICKS_PER_SECOND * result), FRAC_BITS);
811 
812 #undef FP1
813 #undef SHR_FP
814 }
815 
818  coap_queue_t *node) {
819  coap_tick_t now;
820 
821  node->session = coap_session_reference(session);
822 
823  /* Set timer for pdu retransmission. If this is the first element in
824  * the retransmission queue, the base time is set to the current
825  * time and the retransmission time is node->timeout. If there is
826  * already an entry in the sendqueue, we must check if this node is
827  * to be retransmitted earlier. Therefore, node->timeout is first
828  * normalized to the base time and then inserted into the queue with
829  * an adjusted relative time.
830  */
831  coap_ticks(&now);
832  if (context->sendqueue == NULL) {
833  node->t = node->timeout;
834  context->sendqueue_basetime = now;
835  } else {
836  /* make node->t relative to context->sendqueue_basetime */
837  node->t = (now - context->sendqueue_basetime) + node->timeout;
838  }
839 
840  coap_insert_node(&context->sendqueue, node);
841 
842 #ifdef WITH_LWIP
843  if (node == context->sendqueue) /* don't bother with timer stuff if there are earlier retransmits */
844  coap_retransmittimer_restart(context);
845 #endif
846 
847 #ifdef WITH_CONTIKI
848  { /* (re-)initialize retransmission timer */
849  coap_queue_t *nextpdu;
850 
851  nextpdu = coap_peek_next(context);
852  assert(nextpdu); /* we have just inserted a node */
853 
854  /* must set timer within the context of the retransmit process */
855  PROCESS_CONTEXT_BEGIN(&coap_retransmit_process);
856  etimer_set(&context->retransmit_timer, nextpdu->t);
857  PROCESS_CONTEXT_END(&coap_retransmit_process);
858  }
859 #endif /* WITH_CONTIKI */
860 
861  debug("** %s tid=%d added to retransmit queue (%ums)\n",
862  coap_session_str(node->session), node->id,
863  (unsigned)(node->t * 1000 / COAP_TICKS_PER_SECOND));
864 
865  return node->id;
866 }
867 
870  uint8_t r;
871  ssize_t bytes_written;
872 
873  if (!coap_pdu_encode_header(pdu, session->proto)) {
874  goto error;
875  }
876 
877  bytes_written = coap_send_pdu( session, pdu, NULL );
878 
879  if (bytes_written == COAP_PDU_DELAYED) {
880  /* do not free pdu as it is stored with session for later use */
881  return pdu->tid;
882  }
883 
884  if (bytes_written < 0) {
885  coap_delete_pdu(pdu);
886  return (coap_tid_t)bytes_written;
887  }
888 
889  if (COAP_PROTO_RELIABLE(session->proto) &&
890  (size_t)bytes_written < pdu->used_size + pdu->hdr_size) {
891  if (coap_session_delay_pdu(session, pdu, NULL) == COAP_PDU_DELAYED) {
892  session->partial_write = (size_t)bytes_written;
893  /* do not free pdu as it is stored with session for later use */
894  return pdu->tid;
895  } else {
896  goto error;
897  }
898  }
899 
900  if (pdu->type != COAP_MESSAGE_CON || COAP_PROTO_RELIABLE(session->proto)) {
901  coap_tid_t id = pdu->tid;
902  coap_delete_pdu(pdu);
903  return id;
904  }
905 
906  coap_queue_t *node = coap_new_node();
907  if (!node) {
908  debug("coap_wait_ack: insufficient memory\n");
909  goto error;
910  }
911 
912  node->id = pdu->tid;
913  node->pdu = pdu;
914  prng(&r, sizeof(r));
915  /* add timeout in range [ACK_TIMEOUT...ACK_TIMEOUT * ACK_RANDOM_FACTOR] */
916  node->timeout = coap_calc_timeout(session, r);
917  return coap_wait_ack(session->context, session, node);
918  error:
919  coap_delete_pdu(pdu);
920  return COAP_INVALID_TID;
921 }
922 
925  if (!context || !node)
926  return COAP_INVALID_TID;
927 
928  /* re-initialize timeout when maximum number of retransmissions are not reached yet */
929  if (node->retransmit_cnt < node->session->max_retransmit) {
930  ssize_t bytes_written;
931  coap_tick_t now;
932 
933  node->retransmit_cnt++;
934  coap_ticks(&now);
935  if (context->sendqueue == NULL) {
936  node->t = node->timeout << node->retransmit_cnt;
937  context->sendqueue_basetime = now;
938  } else {
939  /* make node->t relative to context->sendqueue_basetime */
940  node->t = (now - context->sendqueue_basetime) + (node->timeout << node->retransmit_cnt);
941  }
942  coap_insert_node(&context->sendqueue, node);
943 #ifdef WITH_LWIP
944  if (node == context->sendqueue) /* don't bother with timer stuff if there are earlier retransmits */
945  coap_retransmittimer_restart(context);
946 #endif
947 
948  debug("** %s tid=%d: retransmission #%d\n",
949  coap_session_str(node->session), node->id, node->retransmit_cnt);
950 
951  if (node->session->con_active)
952  node->session->con_active--;
953  bytes_written = coap_send_pdu(node->session, node->pdu, node);
954 
955  if (bytes_written == COAP_PDU_DELAYED) {
956  /* PDU was not retransmitted immediately because a new handshake is
957  in progress. node was moved to the send queue of the session. */
958  return node->id;
959  }
960 
961  if (bytes_written < 0)
962  return (int)bytes_written;
963 
964  return node->id;
965  }
966 
967  /* no more retransmissions, remove node from system */
968 
969 #ifndef WITH_CONTIKI
970  debug("** %s tid=%d: give up after %d attempts\n",
971  coap_session_str(node->session), node->id, node->retransmit_cnt);
972 #endif
973 
974 #ifndef WITHOUT_OBSERVE
975  /* Check if subscriptions exist that should be canceled after
976  COAP_MAX_NOTIFY_FAILURES */
977  if (node->pdu->code >= 64) {
978  coap_binary_t token = { 0, NULL };
979 
980  token.length = node->pdu->token_length;
981  token.s = node->pdu->token;
982 
983  coap_handle_failed_notify(context, node->session, &token);
984  }
985 #endif /* WITHOUT_OBSERVE */
986  if (node->session->con_active) {
987  node->session->con_active--;
989  /* Flush out any entries on session->delayqueue */
991  }
992 
993  /* And finally delete the node */
994  if (node->pdu->type == COAP_MESSAGE_CON && context->nack_handler)
995  context->nack_handler(context, node->session, node->pdu, COAP_NACK_TOO_MANY_RETRIES, node->id);
996  coap_delete_node(node);
997  return COAP_INVALID_TID;
998 }
999 
1000 #ifdef WITH_LWIP
1001 /* WITH_LWIP, this is handled by coap_recv in a different way */
1002 void
1004  return;
1005 }
1006 #else /* WITH_LWIP */
1007 
1008 static int
1010  uint8_t *data;
1011  size_t data_len;
1012  int result = -1;
1013 
1014  coap_packet_get_memmapped(packet, &data, &data_len);
1015 
1016  if (session->proto == COAP_PROTO_DTLS) {
1017  if (session->type == COAP_SESSION_TYPE_HELLO)
1018  result = coap_dtls_hello(session, data, data_len);
1019  else if (session->tls)
1020  result = coap_dtls_receive(session, data, data_len);
1021  } else if (session->proto == COAP_PROTO_UDP) {
1022  result = coap_handle_dgram(ctx, session, data, data_len);
1023  }
1024  return result;
1025 }
1026 
1027 static void
1029  (void)ctx;
1030  if (coap_socket_connect_tcp2(&session->sock, &session->local_addr, &session->remote_addr)) {
1031  session->last_rx_tx = now;
1033  if (session->proto == COAP_PROTO_TCP) {
1034  coap_session_send_csm(session);
1035  } else if (session->proto == COAP_PROTO_TLS) {
1036  int connected = 0;
1038  session->tls = coap_tls_new_client_session(session, &connected);
1039  if (session->tls) {
1040  if (connected) {
1042  coap_session_send_csm(session);
1043  }
1044  } else {
1045  coap_handle_event(session->context, COAP_EVENT_DTLS_ERROR, session);
1047  }
1048  }
1049  } else {
1050  coap_handle_event(session->context, COAP_EVENT_TCP_FAILED, session);
1052  }
1053 }
1054 
1055 static void
1057  (void)ctx;
1058  assert(session->sock.flags & COAP_SOCKET_CONNECTED);
1059 
1060  while (session->delayqueue) {
1061  ssize_t bytes_written;
1062  coap_queue_t *q = session->delayqueue;
1063  debug("** %s tid=%d: transmitted after delay\n", coap_session_str(session), (int)q->pdu->tid);
1064  assert(session->partial_write < q->pdu->used_size + q->pdu->hdr_size);
1065  switch (session->proto) {
1066  case COAP_PROTO_TCP:
1067  bytes_written = coap_session_write(
1068  session,
1069  q->pdu->token - q->pdu->hdr_size - session->partial_write,
1070  q->pdu->used_size + q->pdu->hdr_size - session->partial_write
1071  );
1072  break;
1073  case COAP_PROTO_TLS:
1074  bytes_written = coap_tls_write(
1075  session,
1076  q->pdu->token - q->pdu->hdr_size - session->partial_write,
1077  q->pdu->used_size + q->pdu->hdr_size - session->partial_write
1078  );
1079  break;
1080  default:
1081  bytes_written = -1;
1082  break;
1083  }
1084  if (bytes_written > 0)
1085  session->last_rx_tx = now;
1086  if (bytes_written <= 0 || (size_t)bytes_written < q->pdu->used_size + q->pdu->hdr_size - session->partial_write) {
1087  if (bytes_written > 0)
1088  session->partial_write += (size_t)bytes_written;
1089  break;
1090  }
1091  session->delayqueue = q->next;
1092  session->partial_write = 0;
1093  coap_delete_node(q);
1094  }
1095 }
1096 
1097 #ifdef WITH_CONTIKI
1099 coap_malloc_packet(void) {
1101 }
1102 
1103 void
1104 coap_free_packet(coap_packet_t *packet) {
1105  coap_free_type(COAP_PACKET, packet);
1106 }
1107 #endif /* WITH_CONTIKI */
1108 
1109 static void
1111 #ifdef WITH_CONTIKI
1112  coap_packet_t *packet = coap_malloc_packet();
1113  if ( !packet )
1114  return
1115 #else /* WITH_CONTIKI */
1116  coap_packet_t s_packet;
1117  coap_packet_t *packet = &s_packet;
1118 #endif /* WITH_CONTIKI */
1119 
1121 
1122  if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
1123  ssize_t bytes_read;
1124  coap_address_copy(&packet->src, &session->remote_addr);
1125  coap_address_copy(&packet->dst, &session->local_addr);
1126  bytes_read = ctx->network_read(&session->sock, packet);
1127 
1128  if (bytes_read < 0) {
1129  if (bytes_read == -2)
1131  else
1132  warn("* %s: read error\n", coap_session_str(session));
1133  } else if (bytes_read > 0) {
1134  debug("* %s: received %zd bytes\n", coap_session_str(session), bytes_read);
1135  session->last_rx_tx = now;
1136  coap_packet_set_addr(packet, &session->remote_addr, &session->local_addr);
1137  coap_handle_dgram_for_proto(ctx, session, packet);
1138  }
1139  } else {
1140  ssize_t bytes_read = 0;
1141  const uint8_t *p;
1142  int retry;
1143  /* adjust for LWIP */
1144  uint8_t *buf = packet->payload;
1145  size_t buf_len = sizeof(packet->payload);
1146 
1147  do {
1148  if (session->proto == COAP_PROTO_TCP)
1149  bytes_read = coap_socket_read(&session->sock, buf, buf_len);
1150  else if (session->proto == COAP_PROTO_TLS)
1151  bytes_read = coap_tls_read(session, buf, buf_len);
1152  if (bytes_read > 0) {
1153  debug("* %s: received %zd bytes\n", coap_session_str(session), bytes_read);
1154  session->last_rx_tx = now;
1155  }
1156  p = buf;
1157  retry = bytes_read == (ssize_t)buf_len;
1158  while (bytes_read > 0) {
1159  if (session->partial_pdu) {
1160  size_t len = session->partial_pdu->used_size
1161  + session->partial_pdu->hdr_size
1162  - session->partial_read;
1163  size_t n = min(len, (size_t)bytes_read);
1164  memcpy(session->partial_pdu->token - session->partial_pdu->hdr_size
1165  + session->partial_read, p, n);
1166  p += n;
1167  bytes_read -= n;
1168  if (n == len) {
1169  if (coap_pdu_parse_header(session->partial_pdu, session->proto)
1170  && coap_pdu_parse_opt(session->partial_pdu)) {
1171  coap_dispatch(ctx, session, session->partial_pdu);
1172  }
1173  coap_delete_pdu(session->partial_pdu);
1174  session->partial_pdu = NULL;
1175  session->partial_read = 0;
1176  } else {
1177  session->partial_read += n;
1178  }
1179  } else if (session->partial_read > 0) {
1180  size_t hdr_size = coap_pdu_parse_header_size(session->proto,
1181  session->read_header);
1182  size_t len = hdr_size - session->partial_read;
1183  size_t n = min(len, (size_t)bytes_read);
1184  memcpy(session->read_header + session->partial_read, p, n);
1185  p += n;
1186  bytes_read -= n;
1187  if (n == len) {
1188  size_t size = coap_pdu_parse_size(session->proto, session->read_header,
1189  hdr_size);
1190  session->partial_pdu = coap_pdu_init(0, 0, 0, size);
1191  if (session->partial_pdu == NULL) {
1192  bytes_read = -1;
1193  break;
1194  }
1195  if (session->partial_pdu->alloc_size < size && !coap_pdu_resize(session->partial_pdu, size)) {
1196  bytes_read = -1;
1197  break;
1198  }
1199  session->partial_pdu->hdr_size = (uint8_t)hdr_size;
1200  session->partial_pdu->used_size = size;
1201  memcpy(session->partial_pdu->token - hdr_size, session->read_header, hdr_size);
1202  session->partial_read = hdr_size;
1203  if (size == 0) {
1204  if (coap_pdu_parse_header(session->partial_pdu, session->proto)) {
1205  coap_dispatch(ctx, session, session->partial_pdu);
1206  }
1207  coap_delete_pdu(session->partial_pdu);
1208  session->partial_pdu = NULL;
1209  session->partial_read = 0;
1210  }
1211  } else {
1212  session->partial_read += bytes_read;
1213  }
1214  } else {
1215  session->read_header[0] = *p++;
1216  bytes_read -= 1;
1217  if (!coap_pdu_parse_header_size(session->proto,
1218  session->read_header)) {
1219  bytes_read = -1;
1220  break;
1221  }
1222  session->partial_read = 1;
1223  }
1224  }
1225  } while (bytes_read == 0 && retry);
1226  if (bytes_read < 0)
1228  }
1229 
1230 #ifdef WITH_CONTIKI
1231  if ( packet )
1232  coap_free_packet( packet );
1233 #endif
1234 }
1235 
1236 static int
1238  ssize_t bytes_read = -1;
1239  int result = -1; /* the value to be returned */
1240 #ifdef WITH_CONTIKI
1241  coap_packet_t *packet = coap_malloc_packet();
1242 #else /* WITH_CONTIKI */
1243  coap_packet_t s_packet;
1244  coap_packet_t *packet = &s_packet;
1245 #endif /* WITH_CONTIKI */
1246 
1247  assert(COAP_PROTO_NOT_RELIABLE(endpoint->proto));
1248  assert(endpoint->sock.flags & COAP_SOCKET_BOUND);
1249 
1250  if (packet) {
1251  coap_address_init(&packet->src);
1252  coap_address_copy(&packet->dst, &endpoint->bind_addr);
1253  bytes_read = ctx->network_read(&endpoint->sock, packet);
1254  }
1255  else {
1256  coap_log(LOG_WARNING, "* %s: Packet allocation failed\n", coap_endpoint_str(endpoint));
1257  return -1;
1258  }
1259 
1260  if (bytes_read < 0) {
1261  warn("* %s: read failed\n", coap_endpoint_str(endpoint));
1262  } else if (bytes_read > 0) {
1263  coap_session_t *session = coap_endpoint_get_session(endpoint, packet, now);
1264  if (session) {
1265  debug("* %s: received %zd bytes\n", coap_session_str(session), bytes_read);
1266  result = coap_handle_dgram_for_proto(ctx, session, packet);
1267  if (endpoint->proto == COAP_PROTO_DTLS && session->type == COAP_SESSION_TYPE_HELLO && result == 1)
1268  coap_endpoint_new_dtls_session(endpoint, packet, now);
1269  }
1270  }
1271 
1272 #ifdef WITH_CONTIKI
1273  if (packet)
1274  coap_free_packet(packet);
1275 #endif
1276 
1277  return result;
1278 }
1279 
1280 static int
1282  (void)ctx;
1283  (void)endpoint;
1284  (void)now;
1285  return 0;
1286 }
1287 
1288 static int
1290  coap_tick_t now) {
1291  coap_session_t *session = coap_new_server_session(ctx, endpoint);
1292  if (session)
1293  session->last_rx_tx = now;
1294  return session != NULL;
1295 }
1296 
1297 void
1299  coap_endpoint_t *ep, *tmp;
1300  coap_session_t *s, *tmp_s;
1301 
1302  LL_FOREACH_SAFE(ctx->endpoint, ep, tmp) {
1303  if ((ep->sock.flags & COAP_SOCKET_CAN_READ) != 0)
1304  coap_read_endpoint(ctx, ep, now);
1305  if ((ep->sock.flags & COAP_SOCKET_CAN_WRITE) != 0)
1306  coap_write_endpoint(ctx, ep, now);
1307  if ((ep->sock.flags & COAP_SOCKET_CAN_ACCEPT) != 0)
1308  coap_accept_endpoint(ctx, ep, now);
1309  LL_FOREACH_SAFE(ep->sessions, s, tmp_s) {
1310  if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0) {
1311  /* Make sure the session object is not deleted in one of the callbacks */
1313  coap_read_session(ctx, s, now);
1315  }
1316  if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0) {
1317  /* Make sure the session object is not deleted in one of the callbacks */
1319  coap_write_session(ctx, s, now);
1321  }
1322  }
1323  }
1324 
1325  LL_FOREACH_SAFE(ctx->sessions, s, tmp_s) {
1326  if ((s->sock.flags & COAP_SOCKET_CAN_CONNECT) != 0) {
1327  /* Make sure the session object is not deleted in one of the callbacks */
1329  coap_connect_session(ctx, s, now);
1330  coap_session_release( s );
1331  }
1332  if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0) {
1333  /* Make sure the session object is not deleted in one of the callbacks */
1335  coap_read_session(ctx, s, now);
1337  }
1338  if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0) {
1339  /* Make sure the session object is not deleted in one of the callbacks */
1341  coap_write_session(ctx, s, now);
1342  coap_session_release( s );
1343  }
1344  }
1345 }
1346 
1347 int
1349  uint8_t *msg, size_t msg_len) {
1350 
1351  coap_pdu_t *pdu = NULL;
1352 
1354 
1355  pdu = coap_pdu_init(0, 0, 0, msg_len - 4);
1356  if (!pdu)
1357  goto error;
1358 
1359  if (!coap_pdu_parse(session->proto, msg, msg_len, pdu)) {
1360  warn("discard malformed PDU\n");
1361  goto error;
1362  }
1363 
1364  coap_dispatch(ctx, session, pdu);
1365  coap_delete_pdu(pdu);
1366  return 0;
1367 
1368 error:
1369  /* FIXME: send back RST? */
1370  coap_delete_pdu(pdu);
1371  return -1;
1372 }
1373 #endif /* not WITH_LWIP */
1374 
1375 int
1377  coap_queue_t *p, *q;
1378 
1379  if (!queue || !*queue)
1380  return 0;
1381 
1382  /* replace queue head if PDU's time is less than head's time */
1383 
1384  if (session == (*queue)->session && id == (*queue)->id) { /* found transaction */
1385  *node = *queue;
1386  *queue = (*queue)->next;
1387  if (*queue) { /* adjust relative time of new queue head */
1388  (*queue)->t += (*node)->t;
1389  }
1390  (*node)->next = NULL;
1391  debug("** %s tid=%d: removed\n", coap_session_str(session), id);
1392  return 1;
1393  }
1394 
1395  /* search transaction to remove (only first occurence will be removed) */
1396  q = *queue;
1397  do {
1398  p = q;
1399  q = q->next;
1400  } while (q && (session != q->session || id != q->id));
1401 
1402  if (q) { /* found transaction */
1403  p->next = q->next;
1404  if (p->next) { /* must update relative time of p->next */
1405  p->next->t += q->t;
1406  }
1407  q->next = NULL;
1408  *node = q;
1409  debug("** %s tid=%d: removed\n", coap_session_str(session), id);
1410  return 1;
1411  }
1412 
1413  return 0;
1414 
1415 }
1416 
1418 token_match(const uint8_t *a, size_t alen,
1419  const uint8_t *b, size_t blen) {
1420  return alen == blen && (alen == 0 || memcmp(a, b, alen) == 0);
1421 }
1422 
1423 void
1425  coap_nack_reason_t reason) {
1426  coap_queue_t *p, *q;
1427 
1428  while (context->sendqueue && context->sendqueue->session == session) {
1429  q = context->sendqueue;
1430  context->sendqueue = q->next;
1431  debug("** %s tid=%d: removed\n", coap_session_str(session), q->id);
1432  if (q->pdu->type == COAP_MESSAGE_CON && context->nack_handler)
1433  context->nack_handler(context, session, q->pdu, reason, q->id);
1434  coap_delete_node(q);
1435  }
1436 
1437  if (!context->sendqueue)
1438  return;
1439 
1440  p = context->sendqueue;
1441  q = p->next;
1442 
1443  while (q) {
1444  if (q->session == session) {
1445  p->next = q->next;
1446  debug("** %s tid=%d: removed\n", coap_session_str(session), q->id);
1447  if (q->pdu->type == COAP_MESSAGE_CON && context->nack_handler)
1448  context->nack_handler(context, session, q->pdu, reason, q->id);
1449  coap_delete_node(q);
1450  q = p->next;
1451  } else {
1452  p = q;
1453  q = q->next;
1454  }
1455  }
1456 }
1457 
1458 void
1460  const uint8_t *token, size_t token_length) {
1461  /* cancel all messages in sendqueue that belong to session
1462  * and use the specified token */
1463  coap_queue_t *p, *q;
1464 
1465  while (context->sendqueue && context->sendqueue->session == session &&
1466  token_match(token, token_length,
1467  context->sendqueue->pdu->token,
1468  context->sendqueue->pdu->token_length)) {
1469  q = context->sendqueue;
1470  context->sendqueue = q->next;
1471  debug("** %s tid=%d: removed\n", coap_session_str(session), q->id);
1472  coap_delete_node(q);
1473  }
1474 
1475  if (!context->sendqueue)
1476  return;
1477 
1478  p = context->sendqueue;
1479  q = p->next;
1480 
1481  /* when q is not NULL, it does not match (dst, token), so we can skip it */
1482  while (q) {
1483  if (q->session == session &&
1484  token_match(token, token_length,
1485  q->pdu->token, q->pdu->token_length)) {
1486  p->next = q->next;
1487  debug("** %s tid=%d: removed\n", coap_session_str(session), q->id);
1488  coap_delete_node(q);
1489  q = p->next;
1490  } else {
1491  p = q;
1492  q = q->next;
1493  }
1494  }
1495 }
1496 
1497 coap_queue_t *
1499  while (queue && queue->session != session && queue->id != id)
1500  queue = queue->next;
1501 
1502  return queue;
1503 }
1504 
1505 coap_pdu_t *
1506 coap_new_error_response(coap_pdu_t *request, unsigned char code,
1507  coap_opt_filter_t opts) {
1508  coap_opt_iterator_t opt_iter;
1509  coap_pdu_t *response;
1510  size_t size = request->token_length;
1511  unsigned char type;
1512  coap_opt_t *option;
1513  uint16_t opt_type = 0; /* used for calculating delta-storage */
1514 
1515 #if COAP_ERROR_PHRASE_LENGTH > 0
1516  const char *phrase = coap_response_phrase(code);
1517 
1518  /* Need some more space for the error phrase and payload start marker */
1519  if (phrase)
1520  size += strlen(phrase) + 1;
1521 #endif
1522 
1523  assert(request);
1524 
1525  /* cannot send ACK if original request was not confirmable */
1526  type = request->type == COAP_MESSAGE_CON
1528  : COAP_MESSAGE_NON;
1529 
1530  /* Estimate how much space we need for options to copy from
1531  * request. We always need the Token, for 4.02 the unknown critical
1532  * options must be included as well. */
1533  coap_option_clrb(opts, COAP_OPTION_CONTENT_TYPE); /* we do not want this */
1534 
1535  coap_option_iterator_init(request, &opt_iter, opts);
1536 
1537  /* Add size of each unknown critical option. As known critical
1538  options as well as elective options are not copied, the delta
1539  value might grow.
1540  */
1541  while ((option = coap_option_next(&opt_iter))) {
1542  uint16_t delta = opt_iter.type - opt_type;
1543  /* calculate space required to encode (opt_iter.type - opt_type) */
1544  if (delta < 13) {
1545  size++;
1546  } else if (delta < 269) {
1547  size += 2;
1548  } else {
1549  size += 3;
1550  }
1551 
1552  /* add coap_opt_length(option) and the number of additional bytes
1553  * required to encode the option length */
1554 
1555  size += coap_opt_length(option);
1556  switch (*option & 0x0f) {
1557  case 0x0e:
1558  size++;
1559  /* fall through */
1560  case 0x0d:
1561  size++;
1562  break;
1563  default:
1564  ;
1565  }
1566 
1567  opt_type = opt_iter.type;
1568  }
1569 
1570  /* Now create the response and fill with options and payload data. */
1571  response = coap_pdu_init(type, code, request->tid, size);
1572  if (response) {
1573  /* copy token */
1574  if (!coap_add_token(response, request->token_length,
1575  request->token)) {
1576  debug("cannot add token to error response\n");
1577  coap_delete_pdu(response);
1578  return NULL;
1579  }
1580 
1581  /* copy all options */
1582  coap_option_iterator_init(request, &opt_iter, opts);
1583  while ((option = coap_option_next(&opt_iter))) {
1584  coap_add_option(response, opt_iter.type,
1585  coap_opt_length(option),
1586  coap_opt_value(option));
1587  }
1588 
1589 #if COAP_ERROR_PHRASE_LENGTH > 0
1590  /* note that diagnostic messages do not need a Content-Format option. */
1591  if (phrase)
1592  coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
1593 #endif
1594  }
1595 
1596  return response;
1597 }
1598 
1603 COAP_STATIC_INLINE size_t
1604 get_wkc_len(coap_context_t *context, coap_opt_t *query_filter) {
1605  unsigned char buf[1];
1606  size_t len = 0;
1607 
1608  if (coap_print_wellknown(context, buf, &len, UINT_MAX, query_filter)
1610  warn("cannot determine length of /.well-known/core\n");
1611  return 0;
1612  }
1613 
1614  debug("get_wkc_len: coap_print_wellknown() returned %zu\n", len);
1615 
1616  return len;
1617 }
1618 
1619 #define SZX_TO_BYTES(SZX) ((size_t)(1 << ((SZX) + 4)))
1620 
1621 coap_pdu_t *
1623  coap_pdu_t *request) {
1624  coap_pdu_t *resp;
1625  coap_opt_iterator_t opt_iter;
1626  size_t len, wkc_len;
1627  uint8_t buf[2];
1628  int result = 0;
1629  int need_block2 = 0; /* set to 1 if Block2 option is required */
1630  coap_block_t block;
1631  coap_opt_t *query_filter;
1632  size_t offset = 0;
1633  uint8_t *data;
1634 
1635  resp = coap_pdu_init(request->type == COAP_MESSAGE_CON
1637  : COAP_MESSAGE_NON,
1638  COAP_RESPONSE_CODE(205),
1639  request->tid, coap_session_max_pdu_size(session));
1640  if (!resp) {
1641  debug("coap_wellknown_response: cannot create PDU\n");
1642  return NULL;
1643  }
1644 
1645  if (!coap_add_token(resp, request->token_length, request->token)) {
1646  debug("coap_wellknown_response: cannot add token\n");
1647  goto error;
1648  }
1649 
1650  query_filter = coap_check_option(request, COAP_OPTION_URI_QUERY, &opt_iter);
1651  wkc_len = get_wkc_len(context, query_filter);
1652 
1653  /* The value of some resources is undefined and get_wkc_len will return 0.*/
1654  if (wkc_len == 0) {
1655  debug("coap_wellknown_response: undefined resource\n");
1656  /* set error code 4.00 Bad Request*/
1657  resp->code = COAP_RESPONSE_CODE(400);
1658  resp->used_size = resp->token_length;
1659  return resp;
1660  }
1661 
1662  /* check whether the request contains the Block2 option */
1663  if (coap_get_block(request, COAP_OPTION_BLOCK2, &block)) {
1664  debug("create block\n");
1665  offset = block.num << (block.szx + 4);
1666  if (block.szx > 6) { /* invalid, MUST lead to 4.00 Bad Request */
1667  resp->code = COAP_RESPONSE_CODE(400);
1668  return resp;
1669  } else if (block.szx > COAP_MAX_BLOCK_SZX) {
1670  block.szx = COAP_MAX_BLOCK_SZX;
1671  block.num = (unsigned int)(offset >> (block.szx + 4));
1672  }
1673 
1674  need_block2 = 1;
1675  }
1676 
1677  /* Check if there is sufficient space to add Content-Format option
1678  * and data. We do this before adding the Content-Format option to
1679  * avoid sending error responses with that option but no actual
1680  * content. */
1681  if (resp->max_size && resp->max_size <= resp->used_size + 3) {
1682  debug("coap_wellknown_response: insufficient storage space\n");
1683  goto error;
1684  }
1685 
1686  /* Add Content-Format. As we have checked for available storage,
1687  * nothing should go wrong here. */
1688  assert(coap_encode_var_safe(buf, sizeof(buf),
1691  coap_encode_var_safe(buf, sizeof(buf),
1693 
1694  /* check if Block2 option is required even if not requested */
1695  if (!need_block2 && resp->max_size && resp->max_size - resp->used_size < wkc_len + 1) {
1696  assert(resp->used_size <= resp->max_size);
1697  const size_t payloadlen = resp->max_size - resp->used_size;
1698  /* yes, need block-wise transfer */
1699  block.num = 0;
1700  block.m = 0; /* the M bit is set by coap_write_block_opt() */
1701  block.szx = COAP_MAX_BLOCK_SZX;
1702  while (payloadlen < SZX_TO_BYTES(block.szx) + 6) {
1703  if (block.szx == 0) {
1704  debug("coap_wellknown_response: message to small even for szx == 0\n");
1705  goto error;
1706  } else {
1707  block.szx--;
1708  }
1709  }
1710 
1711  need_block2 = 1;
1712  }
1713 
1714  /* write Block2 option if necessary */
1715  if (need_block2) {
1716  if (coap_write_block_opt(&block, COAP_OPTION_BLOCK2, resp, wkc_len) < 0) {
1717  debug("coap_wellknown_response: cannot add Block2 option\n");
1718  goto error;
1719  }
1720  }
1721 
1722  len = need_block2 ? SZX_TO_BYTES( block.szx ) :
1723  resp->max_size && resp->used_size + wkc_len + 1 > resp->max_size ?
1724  resp->max_size - resp->used_size - 1 : wkc_len;
1725  data = coap_add_data_after(resp, len);
1726  if (!data) {
1727  debug( "coap_wellknown_response: coap_add_data failed\n" );
1728  goto error;
1729  }
1730 
1731  result = coap_print_wellknown(context, data, &len, offset, query_filter);
1732  if ((result & COAP_PRINT_STATUS_ERROR) != 0) {
1733  debug("coap_print_wellknown failed\n");
1734  goto error;
1735  }
1736 
1737  return resp;
1738 
1739 error:
1740  /* set error code 5.03 and remove all options and data from response */
1741  resp->code = COAP_RESPONSE_CODE(503);
1742  resp->used_size = resp->token_length;
1743  return resp;
1744 }
1745 
1756 static int
1757 coap_cancel(coap_context_t *context, const coap_queue_t *sent) {
1758 #ifndef WITHOUT_OBSERVE
1759  coap_binary_t token = { 0, NULL };
1760  int num_cancelled = 0; /* the number of observers cancelled */
1761 
1762  /* remove observer for this resource, if any
1763  * get token from sent and try to find a matching resource. Uh!
1764  */
1765 
1766  COAP_SET_STR(&token, sent->pdu->token_length, sent->pdu->token);
1767 
1768  RESOURCES_ITER(context->resources, r) {
1769  num_cancelled += coap_delete_observer(r, sent->session, &token);
1770  coap_cancel_all_messages(context, sent->session, token.s, token.length);
1771  }
1772 
1773  return num_cancelled;
1774 #else /* WITOUT_OBSERVE */
1775  return 0;
1776 #endif /* WITOUT_OBSERVE */
1777 }
1778 
1784 
1813 static enum respond_t
1814 no_response(coap_pdu_t *request, coap_pdu_t *response) {
1815  coap_opt_t *nores;
1816  coap_opt_iterator_t opt_iter;
1817  unsigned int val = 0;
1818 
1819  assert(request);
1820  assert(response);
1821 
1822  if (COAP_RESPONSE_CLASS(response->code) > 0) {
1823  nores = coap_check_option(request, COAP_OPTION_NORESPONSE, &opt_iter);
1824 
1825  if (nores) {
1827 
1828  /* The response should be dropped when the bit corresponding to
1829  * the response class is set (cf. table in funtion
1830  * documentation). When a No-Response option is present and the
1831  * bit is not set, the sender explicitly indicates interest in
1832  * this response. */
1833  if (((1 << (COAP_RESPONSE_CLASS(response->code) - 1)) & val) > 0) {
1834  return RESPONSE_DROP;
1835  } else {
1836  return RESPONSE_SEND;
1837  }
1838  }
1839  }
1840 
1841  /* Default behavior applies when we are not dealing with a response
1842  * (class == 0) or the request did not contain a No-Response option.
1843  */
1844  return RESPONSE_DEFAULT;
1845 }
1846 
1848  { sizeof(COAP_DEFAULT_URI_WELLKNOWN)-1,
1850 
1851 static void
1853  coap_method_handler_t h = NULL;
1854  coap_pdu_t *response = NULL;
1856  coap_resource_t *resource;
1857  /* The respond field indicates whether a response must be treated
1858  * specially due to a No-Response option that declares disinterest
1859  * or interest in a specific response class. DEFAULT indicates that
1860  * No-Response has not been specified. */
1861  enum respond_t respond = RESPONSE_DEFAULT;
1862 
1863  coap_option_filter_clear(opt_filter);
1864 
1865  /* try to find the resource from the request URI */
1866  coap_string_t *uri_path = coap_get_uri_path(pdu);
1867  if (!uri_path)
1868  return;
1869  coap_str_const_t uri_path_c = { uri_path->length, uri_path->s };
1870  resource = coap_get_resource_from_uri_path(context, &uri_path_c);
1871 
1872  if ((resource == NULL) || (resource->is_unknown == 1)) {
1873  /* The resource was not found or there is an unexpected match against the
1874  * resource defined for handling unknown URIs.
1875  * Check if the request URI happens to be the well-known URI, or if the
1876  * unknown resource handler is defined, a PUT or optionally other methods,
1877  * if configured, for the unknown handler.
1878  *
1879  * if well-known URI generate a default response
1880  *
1881  * else if unknown URI handler defined, call the unknown
1882  * URI handler (to allow for potential generation of resource
1883  * [RFC7272 5.8.3]) if the appropriate method is defined.
1884  *
1885  * else if DELETE return 2.02 (RFC7252: 5.8.4. DELETE)
1886  *
1887  * else return 4.04 */
1888 
1889  if (coap_string_equal(uri_path, &coap_default_uri_wellknown)) {
1890  /* request for .well-known/core */
1891  if (pdu->code == COAP_REQUEST_GET) { /* GET */
1892  info("create default response for %s\n", COAP_DEFAULT_URI_WELLKNOWN);
1893  response = coap_wellknown_response(context, session, pdu);
1894  } else {
1895  debug("method not allowed for .well-known/core\n");
1896  response = coap_new_error_response(pdu, COAP_RESPONSE_CODE(405),
1897  opt_filter);
1898  }
1899  } else if ((context->unknown_resource != NULL) &&
1900  ((size_t)pdu->code - 1 <
1901  (sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
1902  (context->unknown_resource->handler[pdu->code - 1])) {
1903  /*
1904  * The unknown_resource can be used to handle undefined resources
1905  * for a PUT request and can support any other registered handler
1906  * defined for it
1907  * Example set up code:-
1908  * r = coap_resource_init_unknown(hnd_put_unknown);
1909  * coap_register_handler(r, COAP_REQUEST_GET, hnd_get_unknown);
1910  * coap_register_handler(r, COAP_REQUEST_DELETE, hnd_delete_unknown);
1911  * coap_add_resource(ctx, r);
1912  */
1913  resource = context->unknown_resource;
1914  } else if (pdu->code == COAP_REQUEST_DELETE) {
1915  /*
1916  * Request for DELETE on non-existant resource (RFC7252: 5.8.4. DELETE)
1917  */
1918  coap_log(LOG_DEBUG, "request for unknown resource '%*.*s',"
1919  " return 2.02\n",
1920  (int)uri_path->length,
1921  (int)uri_path->length,
1922  uri_path->s);
1923  response =
1925  opt_filter);
1926  } else { /* request for any another resource, return 4.04 */
1927 
1928  coap_log(LOG_DEBUG, "request for unknown resource '%*.*s', return 4.04\n",
1929  (int)uri_path->length, (int)uri_path->length, uri_path->s);
1930  response =
1932  opt_filter);
1933  }
1934 
1935  if (!resource) {
1936  if (response && (no_response(pdu, response) != RESPONSE_DROP)) {
1937  if (coap_send(session, response) == COAP_INVALID_TID)
1938  warn("cannot send response for transaction %u\n", pdu->tid);
1939  } else {
1940  coap_delete_pdu(response);
1941  }
1942 
1943  response = NULL;
1944 
1945  coap_delete_string(uri_path);
1946  return;
1947  } else {
1948  if (response) {
1949  /* Need to delete unused response - it will get re-created further on */
1950  coap_delete_pdu(response);
1951  }
1952  }
1953  }
1954 
1955  /* the resource was found, check if there is a registered handler */
1956  if ((size_t)pdu->code - 1 <
1957  sizeof(resource->handler) / sizeof(coap_method_handler_t))
1958  h = resource->handler[pdu->code - 1];
1959 
1960  if (h) {
1961  coap_string_t *query = coap_get_query(pdu);
1962  int owns_query = 1;
1963  coap_log(LOG_DEBUG, "call custom handler for resource '%*.*s'\n",
1964  (int)resource->uri_path->length, (int)resource->uri_path->length,
1965  resource->uri_path->s);
1966  response = coap_pdu_init(pdu->type == COAP_MESSAGE_CON
1968  : COAP_MESSAGE_NON,
1969  0, pdu->tid, coap_session_max_pdu_size(session));
1970 
1971  /* Implementation detail: coap_add_token() immediately returns 0
1972  if response == NULL */
1973  if (coap_add_token(response, pdu->token_length, pdu->token)) {
1974  coap_binary_t token = { pdu->token_length, pdu->token };
1975  coap_opt_iterator_t opt_iter;
1976  coap_opt_t *observe = NULL;
1977  int observe_action = COAP_OBSERVE_CANCEL;
1978 
1979  /* check for Observe option */
1980  if (resource->observable) {
1981  observe = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
1982  if (observe) {
1983  observe_action =
1985  coap_opt_length(observe));
1986 
1987  if ((observe_action & COAP_OBSERVE_CANCEL) == 0) {
1988  coap_subscription_t *subscription;
1989  coap_block_t block2;
1990  int has_block2 = 0;
1991 
1992  if (coap_get_block(pdu, COAP_OPTION_BLOCK2, &block2)) {
1993  has_block2 = 1;
1994  }
1995  subscription = coap_add_observer(resource, session, &token, query, has_block2, block2);
1996  owns_query = 0;
1997  if (subscription) {
1998  coap_touch_observer(context, session, &token);
1999  }
2000  } else {
2001  coap_delete_observer(resource, session, &token);
2002  }
2003  }
2004  }
2005 
2006  h(context, resource, session, pdu, &token, query, response);
2007 
2008  if (query && owns_query)
2009  coap_delete_string(query);
2010 
2011  respond = no_response(pdu, response);
2012  if (respond != RESPONSE_DROP) {
2013  if (observe && (COAP_RESPONSE_CLASS(response->code) > 2)) {
2014  coap_delete_observer(resource, session, &token);
2015  }
2016 
2017  /* If original request contained a token, and the registered
2018  * application handler made no changes to the response, then
2019  * this is an empty ACK with a token, which is a malformed
2020  * PDU */
2021  if ((response->type == COAP_MESSAGE_ACK)
2022  && (response->code == 0)) {
2023  /* Remove token from otherwise-empty acknowledgment PDU */
2024  response->token_length = 0;
2025  response->used_size = 0;
2026  }
2027 
2028  if ((respond == RESPONSE_SEND)
2029  || /* RESPOND_DEFAULT */
2030  (response->type != COAP_MESSAGE_NON ||
2031  (response->code >= 64
2032  && !coap_mcast_interface(&node->local_if)))) {
2033 
2034  if (coap_send(session, response) == COAP_INVALID_TID)
2035  debug("cannot send response for message %d\n", pdu->tid);
2036  } else {
2037  coap_delete_pdu(response);
2038  }
2039  } else {
2040  coap_delete_pdu(response);
2041  }
2042  response = NULL;
2043  } else {
2044  warn("cannot generate response\r\n");
2045  }
2046  } else {
2047  if (coap_string_equal(uri_path, &coap_default_uri_wellknown)) {
2048  /* request for .well-known/core */
2049  debug("create default response for %s\n", COAP_DEFAULT_URI_WELLKNOWN);
2050  response = coap_wellknown_response(context, session, pdu);
2051  debug("have wellknown response %p\n", (void *)response);
2052  } else
2053  response = coap_new_error_response(pdu, COAP_RESPONSE_CODE(405),
2054  opt_filter);
2055 
2056  if (response && (no_response(pdu, response) != RESPONSE_DROP)) {
2057  if (coap_send(session, response) == COAP_INVALID_TID)
2058  debug("cannot send response for transaction %d\n", pdu->tid);
2059  } else {
2060  coap_delete_pdu(response);
2061  }
2062  response = NULL;
2063  }
2064 
2065  assert(response == NULL);
2066  coap_delete_string(uri_path);
2067 }
2068 
2069 static void
2071  coap_pdu_t *sent, coap_pdu_t *rcvd) {
2072 
2073  coap_send_ack(session, rcvd);
2074 
2075  /* In a lossy context, the ACK of a separate response may have
2076  * been lost, so we need to stop retransmitting requests with the
2077  * same token.
2078  */
2079  coap_cancel_all_messages(context, session, rcvd->token, rcvd->token_length);
2080 
2081  /* Call application-specific response handler when available. */
2082  if (context->response_handler) {
2083  context->response_handler(context, session, sent, rcvd, rcvd->tid);
2084  }
2085 }
2086 
2087 static void
2089  coap_pdu_t *pdu) {
2090  coap_opt_iterator_t opt_iter;
2091  coap_opt_t *option;
2092  (void)context;
2093 
2094  coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
2095 
2096  if (pdu->code == COAP_SIGNALING_CSM) {
2097  while ((option = coap_option_next(&opt_iter))) {
2098  if (opt_iter.type == COAP_SIGNALING_OPTION_MAX_MESSAGE_SIZE) {
2100  coap_opt_length(option)));
2101  } else if (opt_iter.type == COAP_SIGNALING_OPTION_BLOCK_WISE_TRANSFER) {
2102  /* ... */
2103  }
2104  }
2105  if (session->state == COAP_SESSION_STATE_CSM)
2106  coap_session_connected(session);
2107  } else if (pdu->code == COAP_SIGNALING_PING) {
2109  if (context->ping_handler) {
2110  context->ping_handler(context, session, pdu, pdu->tid);
2111  }
2112  if (pong) {
2114  coap_send(session, pong);
2115  }
2116  } else if (pdu->code == COAP_SIGNALING_PONG) {
2117  session->last_pong = session->last_rx_tx;
2118  if (context->pong_handler) {
2119  context->pong_handler(context, session, pdu, pdu->tid);
2120  }
2121  } else if (pdu->code == COAP_SIGNALING_RELEASE
2122  || pdu->code == COAP_SIGNALING_ABORT) {
2124  }
2125 }
2126 
2127 void
2129  coap_pdu_t *pdu) {
2130  coap_queue_t *sent = NULL;
2131  coap_pdu_t *response;
2133 
2134 #ifndef NDEBUG
2135  if (LOG_DEBUG <= coap_get_log_level()) {
2136 #ifndef INET6_ADDRSTRLEN
2137 #define INET6_ADDRSTRLEN 40
2138 #endif
2139 
2147  coap_show_pdu(LOG_DEBUG, pdu);
2148  }
2149 #endif
2150 
2151  memset(opt_filter, 0, sizeof(coap_opt_filter_t));
2152 
2153  switch (pdu->type) {
2154  case COAP_MESSAGE_ACK:
2155  /* find transaction in sendqueue to stop retransmission */
2156  coap_remove_from_queue(&context->sendqueue, session, pdu->tid, &sent);
2157 
2158  if (session->con_active) {
2159  session->con_active--;
2160  if (session->state == COAP_SESSION_STATE_ESTABLISHED)
2161  /* Flush out any entries on session->delayqueue */
2162  coap_session_connected(session);
2163  }
2164  if (pdu->code == 0)
2165  goto cleanup;
2166 
2167  /* if sent code was >= 64 the message might have been a
2168  * notification. Then, we must flag the observer to be alive
2169  * by setting obs->fail_cnt = 0. */
2170  if (sent && COAP_RESPONSE_CLASS(sent->pdu->code) == 2) {
2171  const coap_binary_t token =
2172  { sent->pdu->token_length, sent->pdu->token };
2173  coap_touch_observer(context, sent->session, &token);
2174  }
2175  break;
2176 
2177  case COAP_MESSAGE_RST:
2178  /* We have sent something the receiver disliked, so we remove
2179  * not only the transaction but also the subscriptions we might
2180  * have. */
2181 
2182  coap_log(LOG_ALERT, "got RST for message %d\n", pdu->tid);
2183 
2184  if (session->con_active) {
2185  session->con_active--;
2186  if (session->state == COAP_SESSION_STATE_ESTABLISHED)
2187  /* Flush out any entries on session->delayqueue */
2188  coap_session_connected(session);
2189  }
2190 
2191  /* find transaction in sendqueue to stop retransmission */
2192  coap_remove_from_queue(&context->sendqueue, session, pdu->tid, &sent);
2193 
2194  if (sent) {
2195  coap_cancel(context, sent);
2196 
2197  if(sent->pdu->type==COAP_MESSAGE_CON && context->nack_handler)
2198  context->nack_handler(context, sent->session, sent->pdu, COAP_NACK_RST, sent->id);
2199  }
2200  goto cleanup;
2201 
2202  case COAP_MESSAGE_NON: /* check for unknown critical options */
2203  if (coap_option_check_critical(context, pdu, opt_filter) == 0)
2204  goto cleanup;
2205  break;
2206 
2207  case COAP_MESSAGE_CON: /* check for unknown critical options */
2208  if (coap_option_check_critical(context, pdu, opt_filter) == 0) {
2209 
2210  /* FIXME: send response only if we have received a request. Otherwise,
2211  * send RST. */
2212  response =
2213  coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), opt_filter);
2214 
2215  if (!response) {
2216  warn("coap_dispatch: cannot create error response\n");
2217  } else {
2218  if (coap_send(session, response) == COAP_INVALID_TID)
2219  warn("coap_dispatch: error sending response\n");
2220  }
2221 
2222  goto cleanup;
2223  }
2224  default: break;
2225  }
2226 
2227  /* Pass message to upper layer if a specific handler was
2228  * registered for a request that should be handled locally. */
2229  if (COAP_PDU_IS_SIGNALING(pdu))
2230  handle_signaling(context, session, pdu);
2231  else if (COAP_PDU_IS_REQUEST(pdu))
2232  handle_request(context, session, pdu);
2233  else if (COAP_PDU_IS_RESPONSE(pdu))
2234  handle_response(context, session, sent ? sent->pdu : NULL, pdu);
2235  else {
2236  if (COAP_PDU_IS_EMPTY(pdu)) {
2237  if (context->ping_handler) {
2238  context->ping_handler(context, session,
2239  pdu, pdu->tid);
2240  }
2241  }
2242  debug("dropped message with invalid code (%d.%02d)\n",
2243  COAP_RESPONSE_CLASS(pdu->code),
2244  pdu->code & 0x1f);
2245 
2246  if (!coap_is_mcast(&session->local_addr)) {
2247  if (COAP_PDU_IS_EMPTY(pdu)) {
2248  if (session->proto != COAP_PROTO_TCP && session->proto != COAP_PROTO_TLS) {
2249  coap_tick_t now;
2250  coap_ticks(&now);
2251  if (session->last_tx_rst + COAP_TICKS_PER_SECOND/4 < now) {
2253  session->last_tx_rst = now;
2254  }
2255  }
2256  }
2257  else {
2259  }
2260  }
2261  }
2262 
2263 cleanup:
2264  coap_delete_node(sent);
2265 }
2266 
2267 int
2269  coap_log(LOG_DEBUG, "*** EVENT: 0x%04x\n", event);
2270 
2271  if (context->handle_event) {
2272  return context->handle_event(context, event, session);
2273  } else {
2274  return 0;
2275  }
2276 }
2277 
2278 int
2280  coap_endpoint_t *ep;
2281  coap_session_t *s;
2282  if (!context)
2283  return 1;
2284  if (context->sendqueue)
2285  return 0;
2286  LL_FOREACH(context->endpoint, ep) {
2287  LL_FOREACH(ep->sessions, s) {
2288  if (s->delayqueue)
2289  return 0;
2290  }
2291  }
2292  LL_FOREACH(context->sessions, s) {
2293  if (s->delayqueue)
2294  return 0;
2295  }
2296  return 1;
2297 }
2298 
2299 static int coap_started = 0;
2300 
2301 void coap_startup(void) {
2302  if (coap_started)
2303  return;
2304  coap_started = 1;
2305 #if defined(HAVE_WINSOCK2_H)
2306  WORD wVersionRequested = MAKEWORD(2, 2);
2307  WSADATA wsaData;
2308  WSAStartup(wVersionRequested, &wsaData);
2309 #endif
2310  coap_clock_init();
2311 #if defined(WITH_LWIP)
2312  prng_init(LWIP_RAND());
2313 #elif defined(WITH_CONTIKI)
2314  prng_init(0);
2315 #elif !defined(_WIN32)
2316  prng_init(0);
2317 #endif
2319 }
2320 
2321 void coap_cleanup(void) {
2322 #if defined(HAVE_WINSOCK2_H)
2323  WSACleanup();
2324 #endif
2325 }
2326 
2327 #ifdef WITH_CONTIKI
2328 
2329 /*---------------------------------------------------------------------------*/
2330 /* CoAP message retransmission */
2331 /*---------------------------------------------------------------------------*/
2332 PROCESS_THREAD(coap_retransmit_process, ev, data) {
2333  coap_tick_t now;
2334  coap_queue_t *nextpdu;
2335 
2336  PROCESS_BEGIN();
2337 
2338  debug("Started retransmit process\r\n");
2339 
2340  while (1) {
2341  PROCESS_YIELD();
2342  if (ev == PROCESS_EVENT_TIMER) {
2343  if (etimer_expired(&the_coap_context.retransmit_timer)) {
2344 
2345  nextpdu = coap_peek_next(&the_coap_context);
2346 
2347  coap_ticks(&now);
2348  while (nextpdu && nextpdu->t <= now) {
2349  coap_retransmit(&the_coap_context, coap_pop_next(&the_coap_context));
2350  nextpdu = coap_peek_next(&the_coap_context);
2351  }
2352 
2353  /* need to set timer to some value even if no nextpdu is available */
2354  etimer_set(&the_coap_context.retransmit_timer,
2355  nextpdu ? nextpdu->t - now : 0xFFFF);
2356  }
2357 #ifndef WITHOUT_OBSERVE
2358  if (etimer_expired(&the_coap_context.notify_timer)) {
2359  coap_check_notify(&the_coap_context);
2360  etimer_reset(&the_coap_context.notify_timer);
2361  }
2362 #endif /* WITHOUT_OBSERVE */
2363  }
2364  }
2365 
2366  PROCESS_END();
2367 }
2368 /*---------------------------------------------------------------------------*/
2369 
2370 #endif /* WITH_CONTIKI */
2371 
2372 #ifdef WITH_LWIP
2373 /* FIXME: retransmits that are not required any more due to incoming packages
2374  * do *not* get cleared at the moment, the wakeup when the transmission is due
2375  * is silently accepted. this is mainly due to the fact that the required
2376  * checks are similar in two places in the code (when receiving ACK and RST)
2377  * and that they cause more than one patch chunk, as it must be first checked
2378  * whether the sendqueue item to be dropped is the next one pending, and later
2379  * the restart function has to be called. nothing insurmountable, but it can
2380  * also be implemented when things have stabilized, and the performance
2381  * penality is minimal
2382  *
2383  * also, this completely ignores COAP_RESOURCE_CHECK_TIME.
2384  * */
2385 
2386 static void coap_retransmittimer_execute(void *arg) {
2387  coap_context_t *ctx = (coap_context_t*)arg;
2388  coap_tick_t now;
2389  coap_tick_t elapsed;
2390  coap_queue_t *nextinqueue;
2391 
2392  ctx->timer_configured = 0;
2393 
2394  coap_ticks(&now);
2395 
2396  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 */
2397 
2398  nextinqueue = coap_peek_next(ctx);
2399  while (nextinqueue != NULL) {
2400  if (nextinqueue->t > elapsed) {
2401  nextinqueue->t -= elapsed;
2402  break;
2403  } else {
2404  elapsed -= nextinqueue->t;
2405  coap_retransmit(ctx, coap_pop_next(ctx));
2406  nextinqueue = coap_peek_next(ctx);
2407  }
2408  }
2409 
2410  ctx->sendqueue_basetime = now;
2411 
2412  coap_retransmittimer_restart(ctx);
2413 }
2414 
2415 static void coap_retransmittimer_restart(coap_context_t *ctx) {
2416  coap_tick_t now, elapsed, delay;
2417 
2418  if (ctx->timer_configured) {
2419  printf("clearing\n");
2420  sys_untimeout(coap_retransmittimer_execute, (void*)ctx);
2421  ctx->timer_configured = 0;
2422  }
2423  if (ctx->sendqueue != NULL) {
2424  coap_ticks(&now);
2425  elapsed = now - ctx->sendqueue_basetime;
2426  if (ctx->sendqueue->t >= elapsed) {
2427  delay = ctx->sendqueue->t - elapsed;
2428  } else {
2429  /* a strange situation, but not completely impossible.
2430  *
2431  * this happens, for example, right after
2432  * coap_retransmittimer_execute, when a retransmission
2433  * was *just not yet* due, and the clock ticked before
2434  * our coap_ticks was called.
2435  *
2436  * not trying to retransmit anything now, as it might
2437  * cause uncontrollable recursion; let's just try again
2438  * with the next main loop run.
2439  * */
2440  delay = 0;
2441  }
2442 
2443  printf("scheduling for %d ticks\n", delay);
2444  sys_timeout(delay, coap_retransmittimer_execute, (void*)ctx);
2445  ctx->timer_configured = 1;
2446  }
2447 }
2448 #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:282
void coap_show_pdu(coap_log_t level, const coap_pdu_t *pdu)
Display the contents of the specified pdu.
Definition: debug.c:461
#define LL_FOREACH(head, el)
Definition: utlist.h:413
coap_queue_t * sendqueue
Definition: net.h:165
#define COAP_SOCKET_EMPTY
coap_socket_flags_t values
Definition: coap_io.h:54
uint8_t * psk_identity
Definition: coap_session.h:82
int coap_dtls_hello(coap_session_t *session UNUSED, const uint8_t *data UNUSED, size_t data_len UNUSED)
Definition: coap_notls.c:140
static ssize_t coap_send_pdu(coap_session_t *session, coap_pdu_t *pdu, coap_queue_t *node)
Definition: net.c:648
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:505
#define COAP_OPTION_IF_MATCH
Definition: pdu.h:92
coap_tick_t last_rx_tx
Definition: coap_session.h:77
static int coap_accept_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now)
Definition: net.c:1289
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:71
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:865
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:300
coap_tid_t coap_wait_ack(coap_context_t *context, coap_session_t *session, coap_queue_t *node)
Definition: net.c:817
#define COAP_SIGNALING_CSM
Definition: pdu.h:180
#define COAP_RESPONSE_CODE(N)
Definition: pdu.h:132
#define COAP_DTLS_PKI_SETUP_VERSION
Latest PKI setup version.
Definition: coap_dtls.h:185
coap_ping_handler_t ping_handler
Definition: net.h:190
#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:68
#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:96
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:734
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:1498
static void coap_connect_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now)
Definition: net.c:1028
void * tls
security parameters
Definition: coap_session.h:69
unsigned char retransmit_cnt
retransmission counter, will be removed when zero
Definition: net.h:42
#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:838
coap_session_t * sessions
list of active sessions
Definition: coap_session.h:306
coap_endpoint_t * endpoint
the endpoints used for listening
Definition: net.h:166
#define COAP_SESSION_STATE_HANDSHAKE
Definition: coap_session.h:50
int coap_dtls_receive(coap_session_t *session UNUSED, const uint8_t *data UNUSED, size_t data_len UNUSED)
Definition: coap_notls.c:132
#define COAP_OPTION_NORESPONSE
Definition: pdu.h:122
#define COAP_SOCKET_CONNECTED
the socket is connected
Definition: coap_io.h:57
#define COAP_SOCKET_BOUND
the socket is bound
Definition: coap_io.h:56
void coap_startup(void)
Definition: net.c:2301
multi-purpose address abstraction
Definition: address.h:62
State management for asynchronous messages.
#define SHR_FP(val, frac)
#define COAP_SOCKET_MULTICAST
socket is used for multicast communication
Definition: coap_io.h:66
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:312
#define COAP_REQUEST_GET
Definition: pdu.h:79
size_t psk_key_len
Definition: net.h:211
void coap_session_set_mtu(coap_session_t *session, unsigned mtu)
Set the session MTU.
Definition: coap_session.c:203
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:690
ssize_t coap_tls_read(coap_session_t *session UNUSED, uint8_t *data UNUSED, size_t data_len UNUSED)
Definition: coap_notls.c:169
#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:1418
uint8_t version
Definition: coap_dtls.h:191
coap_string_t * coap_get_query(const coap_pdu_t *request)
Definition: uri.c:512
unsigned int coap_encode_var_safe(uint8_t *buf, size_t length, unsigned int val)
Encodes multiple-length byte sequences.
Definition: encode.c:45
uint8_t * psk_hint
Definition: net.h:208
#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:98
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:472
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:763
coap_tid_t coap_send(coap_session_t *session, coap_pdu_t *pdu)
Sends a CoAP message to given peer.
Definition: net.c:869
COAP_STATIC_INLINE void coap_address_init(coap_address_t *addr)
Resets the given coap_address_t object addr to its default values.
Definition: address.h:104
#define COAP_OPTION_OBSERVE
Definition: pdu.h:112
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:253
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:385
int coap_dtls_is_supported(void)
Check whether DTLS is available.
Definition: coap_notls.c:23
void coap_dtls_free_context(void *handle UNUSED)
Definition: coap_notls.c:91
ssize_t coap_tls_write(coap_session_t *session UNUSED, const uint8_t *data UNUSED, size_t data_len UNUSED)
Definition: coap_notls.c:162
#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:615
#define COAP_SOCKET_CAN_READ
non blocking socket can now read without blocking
Definition: coap_io.h:62
coap_address_t local_if
optional local interface address
Definition: coap_session.h:62
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:703
#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:215
#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:530
unsigned int is_unknown
resource created for unknown handler
Definition: resource.h:75
int coap_pdu_parse_opt(coap_pdu_t *pdu)
Verify consistency in the given CoAP PDU structure and locate the data.
Definition: pdu.c:504
#define COAP_PDU_DELAYED
Definition: pdu.h:249
#define prng_init(Value)
Called to set the PRNG seed.
Definition: prng.h:122
Debug.
Definition: debug.h:49
coap_nack_handler_t nack_handler
Definition: net.h:189
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:765
coap_opt_t * coap_option_next(coap_opt_iterator_t *oi)
Updates the iterator oi to point to the next option.
Definition: option.c:157
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:203
#define COAP_OPTION_CONTENT_TYPE
Definition: pdu.h:100
#define COAP_EVENT_TCP_FAILED
Definition: coap_event.h:43
Helpers for handling options in CoAP PDUs.
coap_nack_reason_t
Definition: coap_io.h:206
static int coap_handle_dgram_for_proto(coap_context_t *ctx, coap_session_t *session, coap_packet_t *packet)
Definition: net.c:1009
unsigned char payload[COAP_RXBUFFER_SIZE]
payload
Definition: coap_io.h:201
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:707
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:415
#define COAP_SOCKET_CAN_ACCEPT
non blocking server socket can now accept without blocking
Definition: coap_io.h:64
coap_session_t * coap_session_reference(coap_session_t *session)
Increment reference counter on a session.
Definition: coap_session.c:71
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.
Definition: coap_session.c:931
ssize_t(* network_read)(coap_socket_t *sock, struct coap_packet_t *packet)
Definition: net.h:201
coap_queue_t * coap_peek_next(coap_context_t *context)
Returns the next pdu to send without removing from sendqeue.
Definition: net.c:263
void * coap_tls_new_client_session(coap_session_t *session UNUSED, int *connected UNUSED)
Definition: coap_notls.c:151
#define COAP_OPTION_PROXY_SCHEME
Definition: pdu.h:107
Abstraction of virtual endpoint that can be attached to coap_context_t.
Definition: coap_session.h:299
const char * coap_session_str(const coap_session_t *session)
Get session description.
Definition: coap_session.c:894
#define COAP_RESOURCE_CHECK_TIME
The interval in seconds to check if resources have changed.
Definition: resource.h:22
coap_address_t local_addr
local address and port
Definition: coap_session.h:64
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:205
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:154
#define COAP_SESSION_STATE_ESTABLISHED
Definition: coap_session.h:52
#define SZX_TO_BYTES(SZX)
Definition: net.c:1619
coap_pong_handler_t pong_handler
Definition: net.h:191
coap_tid_t id
CoAP transaction id.
Definition: net.h:46
unsigned int max_retransmit
maximum re-transmit count (default 4)
Definition: coap_session.h:87
#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:400
coap_tick_t sendqueue_basetime
The time stamp in the first element of the sendqeue is relative to sendqueue_basetime.
Definition: net.h:164
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:81
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:1506
Coap string data definition with const data.
Definition: str.h:33
coap_pdu_t * pdu
the CoAP PDU to send
Definition: net.h:47
coap_tick_t t
when to send PDU for the next time
Definition: net.h:41
#define coap_string_equal(string1, string2)
Compares the two strings for equality.
Definition: str.h:121
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:579
unsigned int ping_timeout
Minimum inactivity time before sending a ping message.
Definition: net.h:215
#define COAP_TICKS_PER_SECOND
Use ms resolution on POSIX systems.
Definition: coap_time.h:100
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:207
static int coap_write_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now)
Definition: net.c:1281
int coap_dtls_context_set_pki(coap_context_t *ctx UNUSED, coap_dtls_pki_t *setup_data UNUSED, int server UNUSED)
Definition: coap_notls.c:41
#define FRAC_BITS
The number of bits for the fractional part of ACK_TIMEOUT and ACK_RANDOM_FACTOR.
Definition: net.c:65
size_t psk_hint_len
Definition: net.h:209
#define ACK_TIMEOUT
creates a Qx.FRAC_BITS from session&#39;s &#39;ack_timeout&#39;
Definition: net.c:86
void coap_cleanup(void)
Definition: net.c:2321
#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:79
coap_session_t * coap_endpoint_get_session(coap_endpoint_t *endpoint, const coap_packet_t *packet, coap_tick_t now)
Definition: coap_session.c:438
coap_address_t remote_addr
remote address and port
Definition: coap_session.h:63
#define RESOURCES_ITER(r, tmp)
Definition: resource.h:443
#define COAP_SIGNALING_PONG
Definition: pdu.h:182
static coap_str_const_t coap_default_uri_wellknown
Definition: net.c:1847
coap_address_t src
the packet&#39;s source address
Definition: coap_io.h:197
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:791
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:540
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:188
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:2279
static int coap_read_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now)
Definition: net.c:1237
uint16_t coap_opt_length(const coap_opt_t *opt)
Returns the length of the given option.
Definition: option.c:249
coap_session_t * coap_endpoint_new_dtls_session(coap_endpoint_t *endpoint, const coap_packet_t *packet, coap_tick_t now)
Definition: coap_session.c:486
#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:199
struct coap_queue_t * delayqueue
list of delayed messages waiting to be sent
Definition: coap_session.h:72
static size_t coap_get_session_client_psk(const coap_session_t *session, const uint8_t *hint, size_t hint_len, uint8_t *identity, size_t *identity_len, size_t max_identity_len, uint8_t *psk, size_t max_psk_len)
Definition: net.c:287
coap_proto_t proto
protocol used
Definition: coap_session.h:56
#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:188
#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:73
#define COAP_PDU_IS_EMPTY(pdu)
Definition: pdu.h:312
#define COAP_DTLS_ROLE_SERVER
Internal function invoked for server.
Definition: coap_dtls.h:264
Warning.
Definition: debug.h:46
uint64_t coap_tick_t
This data type represents internal timer ticks with COAP_TICKS_PER_SECOND resolution.
Definition: coap_time.h:85
#define assert(...)
Definition: mem.c:18
#define COAP_SOCKET_NOT_EMPTY
the socket is not empty
Definition: coap_io.h:55
void coap_packet_set_addr(coap_packet_t *packet, const coap_address_t *src, const coap_address_t *dst)
Definition: coap_io.c:843
int coap_dtls_context_set_psk(coap_context_t *ctx UNUSED, const char *hint UNUSED, int server UNUSED)
Definition: coap_notls.c:57
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:342
size_t partial_read
if > 0 indicates number of bytes already read for an incoming message
Definition: coap_session.h:75
coap_pdu_t * partial_pdu
incomplete incoming pdu
Definition: coap_session.h:76
ssize_t coap_session_delay_pdu(coap_session_t *session, coap_pdu_t *pdu, coap_queue_t *node)
Definition: coap_session.c:246
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:346
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:40
coap_socket_t sock
socket object for the session, if any
Definition: coap_session.h:66
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:197
coap_string_t * coap_get_uri_path(const coap_pdu_t *request)
Definition: uri.c:562
#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:1348
#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
coap_proto_t proto
protocol used on this interface
Definition: coap_session.h:302
#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:44
#define COAP_PROTO_TLS
Definition: pdu.h:347
#define coap_mcast_interface(Local)
Definition: coap_io.h:156
Coap binary data definition.
Definition: str.h:49
Generic resource handling.
COAP_STATIC_INLINE void coap_free(void *object)
Wrapper function to coap_free_type() for backwards compatibility.
Definition: mem.h:82
Error.
Definition: debug.h:45
#define COAP_MESSAGE_ACK
Definition: pdu.h:74
coap_session_type_t type
client or server side socket
Definition: coap_session.h:57
void * dtls_context
Definition: net.h:207
void coap_delete_string(coap_string_t *s)
Deletes the given string and releases any memory allocated.
Definition: str.c:34
static void handle_response(coap_context_t *context, coap_session_t *session, coap_pdu_t *sent, coap_pdu_t *rcvd)
Definition: net.c:2070
#define COAP_DEFAULT_NSTART
The number of simultaneous outstanding interactions that a client maintains to a given server...
Definition: coap_session.h:405
coap_session_state_t state
current state of relationaship with peer
Definition: coap_session.h:58
size_t psk_identity_len
Definition: coap_session.h:83
size_t coap_add_option(coap_pdu_t *pdu, uint16_t type, size_t len, const uint8_t *data)
de-duplicate code with coap_add_option_later
Definition: pdu.c:229
#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:1622
void coap_session_release(coap_session_t *session)
Decrement reference counter on a session.
Definition: coap_session.c:77
coap_tick_t last_tx_rst
Definition: coap_session.h:78
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:74
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:1459
#define COAP_SESSION_TYPE_HELLO
server-side ephemeral session for responding to a client hello
Definition: coap_session.h:42
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:1376
#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:205
#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:606
#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:73
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
static size_t coap_get_context_server_hint(const coap_session_t *session, uint8_t *hint, size_t max_hint_len)
Definition: net.c:330
#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:2268
#define COAP_OPTION_BLOCK2
Definition: pdu.h:117
Subscriber information.
Definition: subscribe.h:56
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:141
const char * coap_response_phrase(unsigned char code)
Returns a human-readable response phrase for the specified CoAP response code.
Definition: pdu.c:382
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:234
coap_address_t dst
the packet&#39;s destination address
Definition: coap_io.h:198
void coap_delete_all(coap_queue_t *queue)
Removes all items from given queue and frees the allocated storage.
Definition: net.c:238
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:36
#define warn(...)
Obsoleted.
Definition: debug.h:138
COAP_STATIC_INLINE void coap_address_copy(coap_address_t *dst, const coap_address_t *src)
Definition: address.h:116
void coap_free_context(coap_context_t *context)
CoAP stack context must be released with coap_free_context().
Definition: net.c:511
static void coap_write_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now)
Definition: net.c:1056
struct coap_resource_t * unknown_resource
can be used for handling unknown resources
Definition: net.h:152
void coap_session_connected(coap_session_t *session)
Notify session that it has just connected or reconnected.
Definition: coap_session.c:318
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:554
const uint8_t * coap_opt_value(const coap_opt_t *opt)
Returns a pointer to the value of the given option.
Definition: option.c:286
COAP_STATIC_INLINE coap_queue_t * coap_malloc_node(void)
Definition: net.c:91
#define LL_FOREACH_SAFE(head, el, tmp)
Definition: utlist.h:419
#define COAP_PROTO_RELIABLE(p)
Definition: coap_session.h:34
#define COAP_SESSION_STATE_CONNECTING
Definition: coap_session.h:49
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:554
The structure used for defining the PKI setup data to be used.
Definition: coap_dtls.h:190
#define debug(...)
Obsoleted.
Definition: debug.h:143
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:515
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:49
void coap_delete_all_resources(coap_context_t *context)
Deletes all resources from given context and frees their storage.
Definition: resource.c:494
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:623
unsigned int csm_timeout
Timeout for waiting for a CSM from the remote side.
Definition: net.h:216
#define info(...)
Obsoleted.
Definition: debug.h:133
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:1298
int coap_dtls_send(coap_session_t *session UNUSED, const uint8_t *data UNUSED, size_t data_len UNUSED)
Definition: coap_notls.c:109
#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:61
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:1814
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:204
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:46
#define ACK_RANDOM_FACTOR
creates a Qx.FRAC_BITS from session&#39;s &#39;ack_random_factor&#39;
Definition: net.c:82
uint8_t * psk_key
Definition: net.h:210
void coap_dtls_startup(void)
Initialize the underlying (D)TLS Library layer.
Definition: coap_notls.c:72
#define COAP_SET_STR(st, l, v)
Definition: str.h:44
#define COAP_PRINT_STATUS_ERROR
Definition: resource.h:303
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:314
#define COAP_PROTO_NOT_RELIABLE(p)
Definition: coap_session.h:33
coap_log_t coap_get_log_level(void)
Get the current logging level.
Definition: debug.c:71
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:97
static void coap_read_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now)
Definition: net.c:1110
uint8_t hdr_size
actaul size used for protocol-specific header
Definition: pdu.h:291
size_t psk_key_len
Definition: coap_session.h:85
#define COAP_OPTION_URI_QUERY
Definition: pdu.h:102
void * app
application-specific data
Definition: net.h:218
coap_socket_flags_t flags
Definition: coap_io.h:48
#define COAP_SOCKET_CAN_WRITE
non blocking socket can now write without blocking
Definition: coap_io.h:63
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:417
void coap_session_disconnected(coap_session_t *session, coap_nack_reason_t reason)
Notify session that it has failed.
Definition: coap_session.c:374
coap_session_t * sessions
client sessions
Definition: net.h:167
void coap_set_app_data(coap_context_t *ctx, void *app_data)
Stores data with the given CoAP context.
Definition: net.c:499
#define coap_log(level,...)
Logging function.
Definition: debug.h:122
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:747
#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:1604
size_t coap_session_max_pdu_size(coap_session_t *session)
Get maximum acceptable PDU size.
Definition: coap_session.c:186
coap_print_status_t coap_print_wellknown(coap_context_t *context, unsigned char *buf, size_t *buflen, size_t offset, coap_opt_t *query_filter)
Prints the names of all known resources to buf.
Definition: resource.c:169
coap_socket_t sock
socket object for the interface, if any
Definition: coap_session.h:304
#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:620
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:91
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:926
#define COAP_PDU_IS_SIGNALING(pdu)
Definition: pdu.h:315
coap_session_t * session
the CoAP session
Definition: net.h:45
void coap_free_type(coap_memory_tag_t type, void *p)
Releases the memory that was allocated by coap_malloc_type().
Definition: mem.h:34
coap_str_const_t * uri_path
Request URI Path for this resource.
Definition: resource.h:96
ssize_t coap_network_read(coap_socket_t *sock, coap_packet_t *packet)
Function interface for reading data.
Definition: coap_io.c:849
size_t length
length of binary data
Definition: str.h:50
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:2128
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:1424
void coap_context_set_keepalive(coap_context_t *context, unsigned int seconds)
Set the context keepalive timer for sessions.
Definition: net.c:410
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:67
void coap_free_endpoint(coap_endpoint_t *ep)
Definition: coap_session.c:852
#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:1852
static int coap_started
Definition: net.c:2299
Emergency.
Definition: debug.h:42
uint8_t token_length
length of Token
Definition: pdu.h:292
coap_tick_t last_pong
Definition: coap_session.h:80
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:1757
#define min(a, b)
Definition: net.c:58
#define COAP_SOCKET_CAN_CONNECT
non blocking client socket can now connect without blocking
Definition: coap_io.h:65
#define MAX_BITS
The maximum number of bits for fixed point integers that are used for retransmission time calculation...
Definition: net.c:71
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:36
#define COAP_SESSION_STATE_NONE
coap_session_state_t values
Definition: coap_session.h:48
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:121
coap_tid_t coap_retransmit(coap_context_t *context, coap_queue_t *node)
Handles retransmissions of confirmable messages.
Definition: net.c:924
uint8_t read_header[8]
storage space for header of incoming message header
Definition: coap_session.h:74
void * coap_dtls_new_context(struct coap_context_t *coap_context UNUSED)
Definition: coap_notls.c:86
uint8_t * s
binary data
Definition: str.h:51
#define COAP_OPTION_URI_HOST
Definition: pdu.h:93
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:271
uint16_t message_id
The last message id that was used is stored in this field.
Definition: net.h:186
#define COAP_SIGNALING_ABORT
Definition: pdu.h:184
Queue entry.
Definition: net.h:39
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:84
Alert.
Definition: debug.h:43
coap_queue_t * coap_new_node(void)
Creates a new node suitable for adding to the CoAP sendqueue.
Definition: net.c:247
coap_address_t bind_addr
local interface address
Definition: coap_session.h:305
#define COAP_PROTO_TCP
Definition: pdu.h:346
uint8_t * psk_key
Definition: coap_session.h:84
respond_t
Internal flags to control the treatment of responses (specifically in presence of the No-Response opt...
Definition: net.c:1783
#define FP1
The CoAP stack&#39;s global state is stored in a coap_context_t object.
Definition: net.h:148
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:225
struct coap_resource_t * resources
hash table or list of known resources
Definition: net.h:150
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:440
static void handle_signaling(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu)
Definition: net.c:2088
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:151
#define COAP_SESSION_STATE_CSM
Definition: coap_session.h:51
#define COAP_SOCKET_WANT_WRITE
non blocking socket is waiting for writing
Definition: coap_io.h:59
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:149
#define COAP_DROPPED_RESPONSE
Indicates that a response is suppressed.
Definition: pdu.h:247