net.c
Go to the documentation of this file.
/* net.c -- CoAP network interface
*
* Copyright (C) 2010--2019 Olaf Bergmann <bergmann@tzi.org> and others
*
* SPDX-License-Identifier: BSD-2-Clause
*
* This file is part of the CoAP library libcoap. Please see
* README for terms of use.
*/
#include "coap3/coap_internal.h"
#include <ctype.h>
#include <stdio.h>
#include <errno.h>
#ifdef HAVE_LIMITS_H
#include <limits.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#else
#ifdef HAVE_SYS_UNISTD_H
#include <sys/unistd.h>
#endif
#endif
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifdef HAVE_NET_IF_H
#include <net/if.h>
#endif
#ifdef COAP_EPOLL_SUPPORT
#include <sys/epoll.h>
#include <sys/timerfd.h>
#endif /* COAP_EPOLL_SUPPORT */
#ifdef HAVE_WS2TCPIP_H
#include <ws2tcpip.h>
#endif
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef WITH_LWIP
#include <lwip/pbuf.h>
#include <lwip/udp.h>
#include <lwip/timeouts.h>
#endif
#ifndef INET6_ADDRSTRLEN
#define INET6_ADDRSTRLEN 40
#endif
#ifndef min
#define min(a,b) ((a) < (b) ? (a) : (b))
#endif
#define FRAC_BITS 6
#define MAX_BITS 8
#if FRAC_BITS > 8
#error FRAC_BITS must be less or equal 8
#endif
#define Q(frac,fval) ((uint16_t)(((1 << (frac)) * fval.integer_part) + \
((1 << (frac)) * fval.fractional_part + 500)/1000))
#define ACK_RANDOM_FACTOR \
Q(FRAC_BITS, session->ack_random_factor)
#define ACK_TIMEOUT Q(FRAC_BITS, session->ack_timeout)
#if !defined(WITH_LWIP) && !defined(WITH_CONTIKI)
COAP_STATIC_INLINE coap_queue_t *
coap_malloc_node(void) {
return (coap_queue_t *)coap_malloc_type(COAP_NODE, sizeof(coap_queue_t));
}
COAP_STATIC_INLINE void
coap_free_node(coap_queue_t *node) {
coap_free_type(COAP_NODE, node);
}
#endif /* !defined(WITH_LWIP) && !defined(WITH_CONTIKI) */
#ifdef WITH_LWIP
#include <lwip/memp.h>
static void coap_retransmittimer_execute(void *arg);
static void coap_retransmittimer_restart(coap_context_t *ctx);
COAP_STATIC_INLINE coap_queue_t *
coap_malloc_node() {
return (coap_queue_t *)memp_malloc(MEMP_COAP_NODE);
}
COAP_STATIC_INLINE void
coap_free_node(coap_queue_t *node) {
memp_free(MEMP_COAP_NODE, node);
}
#endif /* WITH_LWIP */
#ifdef WITH_CONTIKI
# ifndef DEBUG
# define DEBUG DEBUG_PRINT
# endif /* DEBUG */
#include "net/ip/uip-debug.h"
#define UIP_IP_BUF ((struct uip_ip_hdr *)&uip_buf[UIP_LLH_LEN])
#define UIP_UDP_BUF ((struct uip_udp_hdr *)&uip_buf[UIP_LLIPH_LEN])
void coap_resources_init();
unsigned char initialized = 0;
coap_context_t the_coap_context;
PROCESS(coap_retransmit_process, "message retransmit process");
COAP_STATIC_INLINE coap_queue_t *
coap_malloc_node() {
return (coap_queue_t *)coap_malloc_type(COAP_NODE, 0);
}
COAP_STATIC_INLINE void
coap_free_node(coap_queue_t *node) {
coap_free_type(COAP_NODE, node);
}
#endif /* WITH_CONTIKI */
unsigned int
coap_adjust_basetime(coap_context_t *ctx, coap_tick_t now) {
unsigned int result = 0;
coap_tick_diff_t delta = now - ctx->sendqueue_basetime;
if (ctx->sendqueue) {
/* delta < 0 means that the new time stamp is before the old. */
if (delta <= 0) {
ctx->sendqueue->t -= delta;
} else {
/* This case is more complex: The time must be advanced forward,
* thus possibly leading to timed out elements at the queue's
* start. For every element that has timed out, its relative
* time is set to zero and the result counter is increased. */
coap_queue_t *q = ctx->sendqueue;
coap_tick_t t = 0;
while (q && (t + q->t < (coap_tick_t)delta)) {
t += q->t;
q->t = 0;
result++;
q = q->next;
}
/* finally adjust the first element that has not expired */
if (q) {
q->t = (coap_tick_t)delta - t;
}
}
}
/* adjust basetime */
ctx->sendqueue_basetime += delta;
return result;
}
int
coap_insert_node(coap_queue_t **queue, coap_queue_t *node) {
coap_queue_t *p, *q;
if (!queue || !node)
return 0;
/* set queue head if empty */
if (!*queue) {
*queue = node;
return 1;
}
/* replace queue head if PDU's time is less than head's time */
q = *queue;
if (node->t < q->t) {
node->next = q;
*queue = node;
q->t -= node->t; /* make q->t relative to node->t */
return 1;
}
/* search for right place to insert */
do {
node->t -= q->t; /* make node-> relative to q->t */
p = q;
q = q->next;
} while (q && q->t <= node->t);
/* insert new item */
if (q) {
q->t -= node->t; /* make q->t relative to node->t */
}
node->next = q;
p->next = node;
return 1;
}
int
coap_delete_node(coap_queue_t *node) {
if (!node)
return 0;
coap_delete_pdu(node->pdu);
if ( node->session ) {
/*
* Need to remove out of context->sendqueue as added in by coap_wait_ack()
*/
if (node->session->context->sendqueue) {
LL_DELETE(node->session->context->sendqueue, node);
}
coap_session_release(node->session);
}
coap_free_node(node);
return 1;
}
void
coap_delete_all(coap_queue_t *queue) {
if (!queue)
return;
coap_delete_all(queue->next);
coap_delete_node(queue);
}
coap_queue_t *
coap_new_node(void) {
coap_queue_t *node;
node = coap_malloc_node();
if (!node) {
coap_log(LOG_WARNING, "coap_new_node: malloc failed\n");
return NULL;
}
memset(node, 0, sizeof(*node));
return node;
}
coap_queue_t *
coap_peek_next(coap_context_t *context) {
if (!context || !context->sendqueue)
return NULL;
return context->sendqueue;
}
coap_queue_t *
coap_pop_next(coap_context_t *context) {
coap_queue_t *next;
if (!context || !context->sendqueue)
return NULL;
next = context->sendqueue;
context->sendqueue = context->sendqueue->next;
if (context->sendqueue) {
context->sendqueue->t += next->t;
}
next->next = NULL;
return next;
}
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
) {
const coap_dtls_cpsk_info_t *psk_info;
(void)hint;
(void)hint_len;
if (session->psk_identity && session->psk_key) {
if (session->psk_identity->length <= max_identity_len &&
session->psk_key->length <= max_psk_len) {
memcpy(identity, session->psk_identity->s, session->psk_identity->length);
memcpy(psk, session->psk_key->s, session->psk_key->length);
*identity_len = session->psk_identity->length;
return session->psk_key->length;
}
}
psk_info = &session->cpsk_setup_data.psk_info;
if (psk_info->identity.s && psk_info->identity.length > 0 &&
psk_info->key.s && psk_info->key.length > 0) {
if (psk_info->identity.length <= max_identity_len &&
psk_info->key.length <= max_psk_len) {
memcpy(identity, psk_info->identity.s, psk_info->identity.length);
memcpy(psk, psk_info->key.s, psk_info->key.length);
*identity_len = psk_info->identity.length;
return psk_info->key.length;
}
}
/* Not defined in coap_new_client_session_psk2() */
*identity_len = 0;
return 0;
}
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
) {
const coap_dtls_spsk_info_t *psk_info;
(void)identity;
(void)identity_len;
if (!session)
return 0;
if (session->psk_key &&
session->psk_key->length <= max_psk_len) {
memcpy(psk, session->psk_key->s, session->psk_key->length);
return session->psk_key->length;
}
psk_info = &session->context->spsk_setup_data.psk_info;
if (psk_info->key.s && psk_info->key.length > 0 &&
psk_info->key.length <= max_psk_len) {
memcpy(psk, psk_info->key.s, psk_info->key.length);
return psk_info->key.length;
}
/* Not defined in coap_context_set_psk2() */
return 0;
}
static size_t
coap_get_context_server_hint(
const coap_session_t *session,
uint8_t *hint, size_t max_hint_len
) {
const coap_dtls_spsk_info_t *psk_info;
if (!session)
return 0;
if (session->psk_hint &&
session->psk_hint->s && session->psk_hint->length > 0 &&
session->psk_hint->length <= max_hint_len) {
memcpy(hint, session->psk_hint->s, session->psk_hint->length);
return session->psk_hint->length;
}
psk_info = &session->context->spsk_setup_data.psk_info;
if (psk_info->hint.s &&
psk_info->hint.length > 0 &&
psk_info->hint.length <= max_hint_len) {
memcpy(hint, psk_info->hint.s, psk_info->hint.length);
return psk_info->hint.length;
}
/* Not defined in coap_context_set_psk2() */
return 0;
}
int coap_context_set_psk(coap_context_t *ctx,
const char *hint,
const uint8_t *key, size_t key_len
) {
coap_dtls_spsk_t setup_data;
memset (&setup_data, 0, sizeof(setup_data));
if (hint) {
setup_data.psk_info.hint.s = (const uint8_t *)hint;
setup_data.psk_info.hint.length = strlen(hint);
}
if (key && key_len > 0) {
setup_data.psk_info.key.s = key;
setup_data.psk_info.key.length = key_len;
}
return coap_context_set_psk2(ctx, &setup_data);
}
int coap_context_set_psk2(coap_context_t *ctx,
coap_dtls_spsk_t *setup_data
) {
if (!setup_data)
return 0;
ctx->spsk_setup_data = *setup_data;
if (coap_dtls_is_supported()) {
return coap_dtls_context_set_spsk(ctx, setup_data);
}
return 0;
}
int coap_context_set_pki(coap_context_t *ctx,
const coap_dtls_pki_t* setup_data
) {
if (!setup_data)
return 0;
if (setup_data->version != COAP_DTLS_PKI_SETUP_VERSION) {
coap_log(LOG_ERR, "coap_context_set_pki: Wrong version of setup_data\n");
return 0;
}
if (coap_dtls_is_supported()) {
return coap_dtls_context_set_pki(ctx, setup_data, COAP_DTLS_ROLE_SERVER);
}
return 0;
}
int coap_context_set_pki_root_cas(coap_context_t *ctx,
const char *ca_file,
const char *ca_dir
) {
if (coap_dtls_is_supported()) {
return coap_dtls_context_set_pki_root_cas(ctx, ca_file, ca_dir);
}
return 0;
}
void coap_context_set_keepalive(coap_context_t *context, unsigned int seconds) {
context->ping_timeout = seconds;
}
void
coap_context_set_max_idle_sessions(coap_context_t *context,
unsigned int max_idle_sessions) {
context->max_idle_sessions = max_idle_sessions;
}
unsigned int
coap_context_get_max_idle_sessions(const coap_context_t *context) {
return context->max_idle_sessions;
}
void
coap_context_set_max_handshake_sessions(coap_context_t *context,
unsigned int max_handshake_sessions) {
context->max_handshake_sessions = max_handshake_sessions;
}
unsigned int
coap_context_get_max_handshake_sessions(const coap_context_t *context) {
return context->max_handshake_sessions;
}
void
coap_context_set_csm_timeout(coap_context_t *context,
unsigned int csm_timeout) {
context->csm_timeout = csm_timeout;
}
unsigned int
coap_context_get_csm_timeout(const coap_context_t *context) {
return context->csm_timeout;
}
void
coap_context_set_session_timeout(coap_context_t *context,
unsigned int session_timeout) {
context->session_timeout = session_timeout;
}
unsigned int
coap_context_get_session_timeout(const coap_context_t *context) {
return context->session_timeout;
}
int coap_context_get_coap_fd(const coap_context_t *context) {
#ifdef COAP_EPOLL_SUPPORT
return context->epfd;
#else /* ! COAP_EPOLL_SUPPORT */
(void)context;
return -1;
#endif /* ! COAP_EPOLL_SUPPORT */
}
coap_context_t *
coap_new_context(
const coap_address_t *listen_addr) {
coap_context_t *c;
#ifdef WITH_CONTIKI
if (initialized)
return NULL;
#endif /* WITH_CONTIKI */
coap_startup();
#ifndef WITH_CONTIKI
c = coap_malloc_type(COAP_CONTEXT, sizeof(coap_context_t));
#endif /* not WITH_CONTIKI */
#ifndef WITH_CONTIKI
if (!c) {
coap_log(LOG_EMERG, "coap_init: malloc: failed\n");
return NULL;
}
#endif /* not WITH_CONTIKI */
#ifdef WITH_CONTIKI
coap_resources_init();
c = &the_coap_context;
initialized = 1;
#endif /* WITH_CONTIKI */
memset(c, 0, sizeof(coap_context_t));
#ifdef COAP_EPOLL_SUPPORT
c->epfd = epoll_create1(0);
if (c->epfd == -1) {
coap_log(LOG_ERR, "coap_new_context: Unable to epoll_create: %s (%d)\n",
coap_socket_strerror(),
errno);
goto onerror;
}
if (c->epfd != -1) {
c->eptimerfd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK);
if (c->eptimerfd == -1) {
coap_log(LOG_ERR, "coap_new_context: Unable to timerfd_create: %s (%d)\n",
coap_socket_strerror(),
errno);
goto onerror;
}
else {
int ret;
struct epoll_event event;
/* Needed if running 32bit as ptr is only 32bit */
memset(&event, 0, sizeof(event));
event.events = EPOLLIN;
/* We special case this event by setting to NULL */
event.data.ptr = NULL;
ret = epoll_ctl(c->epfd, EPOLL_CTL_ADD, c->eptimerfd, &event);
if (ret == -1) {
coap_log(LOG_ERR,
"%s: epoll_ctl ADD failed: %s (%d)\n",
"coap_new_context",
coap_socket_strerror(), errno);
goto onerror;
}
}
}
#endif /* COAP_EPOLL_SUPPORT */
if (coap_dtls_is_supported()) {
c->dtls_context = coap_dtls_new_context(c);
if (!c->dtls_context) {
coap_log(LOG_EMERG, "coap_init: no DTLS context available\n");
coap_free_context(c);
return NULL;
}
}
/* set default CSM timeout */
c->csm_timeout = 30;
if (listen_addr) {
coap_endpoint_t *endpoint = coap_new_endpoint(c, listen_addr, COAP_PROTO_UDP);
if (endpoint == NULL) {
goto onerror;
}
}
#if !defined(WITH_LWIP)
c->network_send = coap_network_send;
c->network_read = coap_network_read;
#endif
c->get_client_psk = coap_get_session_client_psk;
c->get_server_psk = coap_get_context_server_psk;
c->get_server_hint = coap_get_context_server_hint;
#ifdef WITH_CONTIKI
process_start(&coap_retransmit_process, (char *)c);
PROCESS_CONTEXT_BEGIN(&coap_retransmit_process);
etimer_set(&c->notify_timer, COAP_RESOURCE_CHECK_TIME * COAP_TICKS_PER_SECOND);
/* the retransmit timer must be initialized to some large value */
etimer_set(&the_coap_context.retransmit_timer, 0xFFFF);
PROCESS_CONTEXT_END(&coap_retransmit_process);
#endif /* WITH_CONTIKI */
return c;
onerror:
coap_free_type(COAP_CONTEXT, c);
return NULL;
}
void
coap_set_app_data(coap_context_t *ctx, void *app_data) {
assert(ctx);
ctx->app = app_data;
}
void *
coap_get_app_data(const coap_context_t *ctx) {
assert(ctx);
return ctx->app;
}
void
coap_free_context(coap_context_t *context) {
coap_endpoint_t *ep, *tmp;
coap_session_t *sp, *rtmp;
coap_cache_entry_t *cp, *ctmp;
if (!context)
return;
/* Removing a resource may cause a CON observe to be sent */
coap_delete_all_resources(context);
coap_delete_all(context->sendqueue);
#ifdef WITH_LWIP
context->sendqueue = NULL;
coap_retransmittimer_restart(context);
#endif
#ifndef WITHOUT_ASYNC
coap_delete_all_async(context);
#endif /* WITHOUT_ASYNC */
HASH_ITER(hh, context->cache, cp, ctmp) {
coap_delete_cache_entry(context, cp);
}
if (context->cache_ignore_count) {
coap_free(context->cache_ignore_options);
}
LL_FOREACH_SAFE(context->endpoint, ep, tmp) {
coap_free_endpoint(ep);
}
SESSIONS_ITER_SAFE(context->sessions, sp, rtmp) {
coap_session_release(sp);
}
if (context->dtls_context)
coap_dtls_free_context(context->dtls_context);
#ifdef COAP_EPOLL_SUPPORT
if (context->eptimerfd != -1) {
int ret;
struct epoll_event event;
/* Kernels prior to 2.6.9 expect non NULL event parameter */
ret = epoll_ctl(context->epfd, EPOLL_CTL_DEL, context->eptimerfd, &event);
if (ret == -1) {
coap_log(LOG_ERR,
"%s: epoll_ctl DEL failed: %s (%d)\n",
"coap_free_context",
coap_socket_strerror(), errno);
}
close(context->eptimerfd);
context->eptimerfd = -1;
}
if (context->epfd != -1) {
close(context->epfd);
context->epfd = -1;
}
#endif /* COAP_EPOLL_SUPPORT */
#ifndef WITH_CONTIKI
coap_free_type(COAP_CONTEXT, context);
#else /* WITH_CONTIKI */
memset(&the_coap_context, 0, sizeof(coap_context_t));
initialized = 0;
#endif /* WITH_CONTIKI */
}
int
coap_option_check_critical(coap_context_t *ctx,
coap_pdu_t *pdu,
coap_opt_filter_t *unknown) {
coap_opt_iterator_t opt_iter;
int ok = 1;
coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
while (coap_option_next(&opt_iter)) {
/* The following condition makes use of the fact that
* coap_option_getb() returns -1 if type exceeds the bit-vector
* filter. As the vector is supposed to be large enough to hold
* the largest known option, we know that everything beyond is
* bad.
*/
if (opt_iter.number & 0x01) {
/* first check the built-in critical options */
switch (opt_iter.number) {
case COAP_OPTION_IF_MATCH:
case COAP_OPTION_URI_HOST:
case COAP_OPTION_IF_NONE_MATCH:
case COAP_OPTION_URI_PORT:
case COAP_OPTION_URI_PATH:
case COAP_OPTION_URI_QUERY:
case COAP_OPTION_ACCEPT:
case COAP_OPTION_PROXY_URI:
case COAP_OPTION_PROXY_SCHEME:
case COAP_OPTION_BLOCK2:
case COAP_OPTION_BLOCK1:
break;
default:
if (coap_option_filter_get(&ctx->known_options, opt_iter.number) <= 0) {
coap_log(LOG_DEBUG, "unknown critical option %d\n", opt_iter.number);
ok = 0;
/* When opt_iter.number is beyond our known option range,
* coap_option_filter_set() will return -1 and we are safe to leave
* this loop. */
if (coap_option_filter_set(unknown, opt_iter.number) == -1) {
break;
}
}
}
}
}
return ok;
}
coap_mid_t
coap_send_ack(coap_session_t *session, const coap_pdu_t *request) {
coap_pdu_t *response;
coap_mid_t result = COAP_INVALID_MID;
if (request && request->type == COAP_MESSAGE_CON &&
COAP_PROTO_NOT_RELIABLE(session->proto)) {
response = coap_pdu_init(COAP_MESSAGE_ACK, 0, request->mid, 0);
if (response)
result = coap_send_internal(session, response);
}
return result;
}
ssize_t
coap_session_send_pdu(coap_session_t *session, coap_pdu_t *pdu) {
ssize_t bytes_written = -1;
assert(pdu->hdr_size > 0);
switch(session->proto) {
case COAP_PROTO_UDP:
bytes_written = coap_session_send(session, pdu->token - pdu->hdr_size,
pdu->used_size + pdu->hdr_size);
break;
case COAP_PROTO_DTLS:
bytes_written = coap_dtls_send(session, pdu->token - pdu->hdr_size,
pdu->used_size + pdu->hdr_size);
break;
case COAP_PROTO_TCP:
#if !COAP_DISABLE_TCP
bytes_written = coap_session_write(session, pdu->token - pdu->hdr_size,
pdu->used_size + pdu->hdr_size);
#endif /* !COAP_DISABLE_TCP */
break;
case COAP_PROTO_TLS:
#if !COAP_DISABLE_TCP
bytes_written = coap_tls_write(session, pdu->token - pdu->hdr_size,
pdu->used_size + pdu->hdr_size);
#endif /* !COAP_DISABLE_TCP */
break;
case COAP_PROTO_NONE:
default:
break;
}
coap_show_pdu(LOG_DEBUG, pdu);
return bytes_written;
}
static ssize_t
coap_send_pdu(coap_session_t *session, coap_pdu_t *pdu, coap_queue_t *node) {
ssize_t bytes_written;
#ifdef WITH_LWIP
coap_socket_t *sock = &session->sock;
if (sock->flags == COAP_SOCKET_EMPTY) {
assert(session->endpoint != NULL);
sock = &session->endpoint->sock;
}
bytes_written = coap_socket_send_pdu(sock, session, pdu);
if (bytes_written >= 0 && pdu->type == COAP_MESSAGE_CON &&
COAP_PROTO_NOT_RELIABLE(session->proto))
session->con_active++;
if (LOG_DEBUG <= coap_get_log_level()) {
coap_show_pdu(LOG_DEBUG, pdu);
}
coap_ticks(&session->last_rx_tx);
#else
if (session->state == COAP_SESSION_STATE_NONE) {
if (session->proto == COAP_PROTO_DTLS && !session->tls) {
session->tls = coap_dtls_new_client_session(session);
if (session->tls) {
session->state = COAP_SESSION_STATE_HANDSHAKE;
return coap_session_delay_pdu(session, pdu, node);
}
coap_handle_event(session->context, COAP_EVENT_DTLS_ERROR, session);
return -1;
#if !COAP_DISABLE_TCP
} else if(COAP_PROTO_RELIABLE(session->proto)) {
if (!coap_socket_connect_tcp1(
&session->sock, &session->addr_info.local, &session->addr_info.remote,
session->proto == COAP_PROTO_TLS ? COAPS_DEFAULT_PORT :
COAP_DEFAULT_PORT,
&session->addr_info.local, &session->addr_info.remote
)) {
coap_handle_event(session->context, COAP_EVENT_TCP_FAILED, session);
return -1;
}
session->last_ping = 0;
session->last_pong = 0;
session->csm_tx = 0;
coap_ticks( &session->last_rx_tx );
if ((session->sock.flags & COAP_SOCKET_WANT_CONNECT) != 0) {
session->state = COAP_SESSION_STATE_CONNECTING;
return coap_session_delay_pdu(session, pdu, node);
}
coap_handle_event(session->context, COAP_EVENT_TCP_CONNECTED, session);
if (session->proto == COAP_PROTO_TLS) {
int connected = 0;
session->state = COAP_SESSION_STATE_HANDSHAKE;
session->tls = coap_tls_new_client_session(session, &connected);
if (session->tls) {
if (connected) {
coap_handle_event(session->context, COAP_EVENT_DTLS_CONNECTED, session);
coap_session_send_csm(session);
}
return coap_session_delay_pdu(session, pdu, node);
}
coap_handle_event(session->context, COAP_EVENT_DTLS_ERROR, session);
coap_session_disconnected(session, COAP_NACK_TLS_FAILED);
return -1;
} else {
coap_session_send_csm(session);
}
#endif /* !COAP_DISABLE_TCP */
} else {
return -1;
}
}
if (pdu->type == COAP_MESSAGE_CON &&
(session->sock.flags & COAP_SOCKET_NOT_EMPTY) &&
(session->sock.flags & COAP_SOCKET_MULTICAST)) {
/* Violates RFC72522 8.1 */
coap_log(LOG_ERR, "Multicast requests cannot be Confirmable (RFC7252 8.1)\n");
return -1;
}
if (session->state != COAP_SESSION_STATE_ESTABLISHED ||
(pdu->type == COAP_MESSAGE_CON && session->con_active >= COAP_DEFAULT_NSTART)) {
return coap_session_delay_pdu(session, pdu, node);
}
if ((session->sock.flags & COAP_SOCKET_NOT_EMPTY) &&
(session->sock.flags & COAP_SOCKET_WANT_WRITE))
return coap_session_delay_pdu(session, pdu, node);
bytes_written = coap_session_send_pdu(session, pdu);
if (bytes_written >= 0 && pdu->type == COAP_MESSAGE_CON &&
COAP_PROTO_NOT_RELIABLE(session->proto))
session->con_active++;
#endif /* WITH_LWIP */
return bytes_written;
}
coap_mid_t
coap_send_error(coap_session_t *session,
const coap_pdu_t *request,
coap_pdu_code_t code,
coap_opt_filter_t *opts) {
coap_pdu_t *response;
coap_mid_t result = COAP_INVALID_MID;
assert(request);
assert(session);
response = coap_new_error_response(request, code, opts);
if (response)
result = coap_send_internal(session, response);
return result;
}
coap_mid_t
coap_send_message_type(coap_session_t *session, const coap_pdu_t *request,
coap_pdu_type_t type) {
coap_pdu_t *response;
coap_mid_t result = COAP_INVALID_MID;
if (request) {
response = coap_pdu_init(type, 0, request->mid, 0);
if (response)
result = coap_send_internal(session, response);
}
return result;
}
unsigned int
coap_calc_timeout(coap_session_t *session, unsigned char r) {
unsigned int result;
/* The integer 1.0 as a Qx.FRAC_BITS */
#define FP1 Q(FRAC_BITS, ((coap_fixed_point_t){1,0}))
/* rounds val up and right shifts by frac positions */
#define SHR_FP(val,frac) (((val) + (1 << ((frac) - 1))) >> (frac))
/* Inner term: multiply ACK_RANDOM_FACTOR by Q0.MAX_BITS[r] and
* make the result a rounded Qx.FRAC_BITS */
result = SHR_FP((ACK_RANDOM_FACTOR - FP1) * r, MAX_BITS);
/* Add 1 to the inner term and multiply with ACK_TIMEOUT, then
* make the result a rounded Qx.FRAC_BITS */
result = SHR_FP(((result + FP1) * ACK_TIMEOUT), FRAC_BITS);
/* Multiply with COAP_TICKS_PER_SECOND to yield system ticks
* (yields a Qx.FRAC_BITS) and shift to get an integer */
return SHR_FP((COAP_TICKS_PER_SECOND * result), FRAC_BITS);
#undef FP1
#undef SHR_FP
}
coap_mid_t
coap_wait_ack(coap_context_t *context, coap_session_t *session,
coap_queue_t *node) {
coap_tick_t now;
node->session = coap_session_reference(session);
/* Set timer for pdu retransmission. If this is the first element in
* the retransmission queue, the base time is set to the current
* time and the retransmission time is node->timeout. If there is
* already an entry in the sendqueue, we must check if this node is
* to be retransmitted earlier. Therefore, node->timeout is first
* normalized to the base time and then inserted into the queue with
* an adjusted relative time.
*/
coap_ticks(&now);
if (context->sendqueue == NULL) {
node->t = node->timeout << node->retransmit_cnt;
context->sendqueue_basetime = now;
} else {
/* make node->t relative to context->sendqueue_basetime */
node->t = (now - context->sendqueue_basetime) +
(node->timeout << node->retransmit_cnt);
}
coap_insert_node(&context->sendqueue, node);
#ifdef WITH_LWIP
if (node == context->sendqueue) /* don't bother with timer stuff if there are earlier retransmits */
coap_retransmittimer_restart(context);
#endif
#ifdef WITH_CONTIKI
{ /* (re-)initialize retransmission timer */
coap_queue_t *nextpdu;
nextpdu = coap_peek_next(context);
assert(nextpdu); /* we have just inserted a node */
/* must set timer within the context of the retransmit process */
PROCESS_CONTEXT_BEGIN(&coap_retransmit_process);
etimer_set(&context->retransmit_timer, nextpdu->t);
PROCESS_CONTEXT_END(&coap_retransmit_process);
}
#endif /* WITH_CONTIKI */
coap_log(LOG_DEBUG, "** %s: mid=0x%x: added to retransmit queue (%ums)\n",
coap_session_str(node->session), node->id,
(unsigned)(node->t * 1000 / COAP_TICKS_PER_SECOND));
#ifdef COAP_EPOLL_SUPPORT
if (context->eptimerfd != -1) {
coap_ticks(&now);
if (context->next_timeout == 0 ||
context->next_timeout > now + (node->t * 1000 / COAP_TICKS_PER_SECOND)) {
struct itimerspec new_value;
int ret;
context->next_timeout = now + (node->t * 1000 / COAP_TICKS_PER_SECOND);
memset(&new_value, 0, sizeof(new_value));
coap_tick_t rem_timeout = (node->t * 1000 / COAP_TICKS_PER_SECOND);
/* Need to trigger an event on context->epfd in the future */
new_value.it_value.tv_sec = rem_timeout / 1000;
new_value.it_value.tv_nsec = (rem_timeout % 1000) * 1000000;
ret = timerfd_settime(context->eptimerfd, 0, &new_value, NULL);
if (ret == -1) {
coap_log(LOG_ERR,
"%s: timerfd_settime failed: %s (%d)\n",
"coap_wait_ack",
coap_socket_strerror(), errno);
}
}
}
#endif /* COAP_EPOLL_SUPPORT */
return node->id;
}
COAP_STATIC_INLINE int
token_match(const uint8_t *a, size_t alen,
const uint8_t *b, size_t blen) {
return alen == blen && (alen == 0 || memcmp(a, b, alen) == 0);
}
coap_mid_t
coap_send(coap_session_t *session, coap_pdu_t *pdu) {
coap_mid_t mid = COAP_INVALID_MID;
coap_lg_crcv_t *lg_crcv = NULL;
coap_opt_iterator_t opt_iter;
int observe_action = -1;
int have_block1 = 0;
coap_opt_t *opt;
assert(pdu);
if (!(session->block_mode & COAP_BLOCK_USE_LIBCOAP)) {
return coap_send_internal(session, pdu);
}
if (COAP_PDU_IS_REQUEST(pdu)) {
coap_block_t block;
opt = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
if (opt) {
observe_action = coap_decode_var_bytes(coap_opt_value(opt),
coap_opt_length(opt));
}
if (coap_get_block(pdu, COAP_OPTION_BLOCK1, &block) && block.m == 1)
have_block1 = 1;
}
/*
* If type is CON and protocol is not reliable, there is no need to set up
* lg_crcv here as it can be built up based on sent PDU if there is a
* Block2 in the response. However, still need it for observe and block1.
*/
if (observe_action != -1 || have_block1 ||
((pdu->type == COAP_MESSAGE_NON || COAP_PROTO_RELIABLE(session->proto)) &&
COAP_PDU_IS_REQUEST(pdu) && pdu->code != COAP_REQUEST_CODE_DELETE)) {
/* See if this token is already in use for large body responses */
LL_FOREACH(session->lg_crcv, lg_crcv) {
if (token_match(pdu->token, pdu->token_length,
lg_crcv->app_token->s, lg_crcv->app_token->length)) {
if (observe_action == COAP_OBSERVE_CANCEL) {
/* Need to update token to server's version */
coap_update_token(pdu, lg_crcv->base_token_length,
lg_crcv->base_token);
memcpy(lg_crcv->token, lg_crcv->base_token,
lg_crcv->base_token_length);
lg_crcv->token_length = lg_crcv->base_token_length;
lg_crcv->initial = 1;
lg_crcv->observe_set = 0;
/* de-reference lg_crcv as potentially linking in later */
LL_DELETE(session->lg_crcv, lg_crcv);
goto send_it;
}
/* Need to terminate and clean up previous response setup */
LL_DELETE(session->lg_crcv, lg_crcv);
coap_block_delete_lg_crcv(session, lg_crcv);
break;
}
}
lg_crcv = coap_block_new_lg_crcv(session, pdu);
if (lg_crcv == NULL)
return COAP_INVALID_MID;
if (have_block1 && session->lg_xmit) {
coap_lg_xmit_t *lg_xmit;
LL_FOREACH(session->lg_xmit, lg_xmit) {
if (COAP_PDU_IS_REQUEST(&lg_xmit->pdu) &&
lg_xmit->b.b1.app_token &&
token_match(pdu->token, pdu->token_length,
lg_xmit->b.b1.app_token->s,
lg_xmit->b.b1.app_token->length)) {
/* Need to update the token as set up in the session->lg_xmit */
coap_update_token(pdu, session->lg_xmit->b.b1.token_length,
session->lg_xmit->b.b1.token);
break;
}
}
}
}
send_it:
mid = coap_send_internal(session, pdu);
if (lg_crcv) {
if (mid != COAP_INVALID_MID) {
LL_PREPEND(session->lg_crcv, lg_crcv);
}
else {
coap_block_delete_lg_crcv(session, lg_crcv);
}
}
return mid;
}
coap_mid_t
coap_send_internal(coap_session_t *session, coap_pdu_t *pdu) {
uint8_t r;
ssize_t bytes_written;
coap_opt_iterator_t opt_iter;
if (pdu->code == COAP_RESPONSE_CODE(508)) {
/*
* Need to prepend our IP identifier to the data as per
* https://www.rfc-editor.org/rfc/rfc8768.html#section-4
*/
char addr_str[INET6_ADDRSTRLEN + 8 + 1];
coap_opt_t *opt;
size_t hop_limit;
addr_str[sizeof(addr_str)-1] = '\000';
if (coap_print_addr(&session->addr_info.local, (uint8_t*)addr_str,
sizeof(addr_str) - 1)) {
char *cp;
size_t len;
if (addr_str[0] == '[') {
cp = strchr(addr_str, ']');
if (cp) *cp = '\000';
if (memcmp(&addr_str[1], "::ffff:", 7) == 0) {
/* IPv4 embedded into IPv6 */
cp = &addr_str[8];
}
else {
cp = &addr_str[1];
}
}
else {
cp = strchr(addr_str, ':');
if (cp) *cp = '\000';
cp = addr_str;
}
len = strlen(cp);
/* See if Hop Limit option is being used in return path */
opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
if (opt) {
uint8_t buf[4];
hop_limit =
coap_decode_var_bytes (coap_opt_value (opt), coap_opt_length (opt));
if (hop_limit == 1) {
coap_log(LOG_WARNING, "Proxy loop detected '%s'\n",
(char*)pdu->data);
coap_delete_pdu(pdu);
return (coap_mid_t)COAP_DROPPED_RESPONSE;
}
else if (hop_limit < 1 || hop_limit > 255) {
/* Something is bad - need to drop this pdu (TODO or delete option) */
coap_log(LOG_WARNING, "Proxy return has bad hop limit count '%zu'\n",
hop_limit);
coap_delete_pdu(pdu);
return (coap_mid_t)COAP_DROPPED_RESPONSE;
}
hop_limit--;
coap_update_option(pdu, COAP_OPTION_HOP_LIMIT,
coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
buf);
}
/* Need to check that we are not seeing this proxy in the return loop */
if (pdu->data && opt == NULL) {
if (pdu->used_size + 1 <= pdu->max_size) {
char *a_match;
size_t data_len = pdu->used_size - (pdu->data - pdu->token);
pdu->data[data_len] = '\000';
a_match = strstr((char*)pdu->data, cp);
if (a_match && (a_match == (char*)pdu->data || a_match[-1] == ' ') &&
((size_t)(a_match - (char*)pdu->data + len) == data_len ||
a_match[len] == ' ')) {
coap_log(LOG_WARNING, "Proxy loop detected '%s'\n",
(char*)pdu->data);
coap_delete_pdu(pdu);
return (coap_mid_t)COAP_DROPPED_RESPONSE;
}
}
}
if (pdu->used_size + len + 1 <= pdu->max_size) {
size_t old_size = pdu->used_size;
if (coap_pdu_resize(pdu, pdu->used_size + len + 1)) {
if (pdu->data == NULL) {
/*
* Set Hop Limit to max for return path. If this libcoap is in
* a proxy loop path, it will always decrement hop limit in code
* above and hence timeout / drop the response as appropriate
*/
hop_limit = 255;
coap_insert_option(pdu, COAP_OPTION_HOP_LIMIT, 1,
(uint8_t *)&hop_limit);
coap_add_data(pdu, len, (uint8_t*)cp);
}
else {
/* prepend with space separator, leaving hop limit "as is" */
memmove(pdu->data + len + 1, pdu->data,
old_size - (pdu->data - pdu->token));
memcpy(pdu->data, cp, len);
pdu->data[len] = ' ';
pdu->used_size += len + 1;
}
}
}
}
}
if (!coap_pdu_encode_header(pdu, session->proto)) {
goto error;
}
#if !COAP_DISABLE_TCP
if (COAP_PROTO_RELIABLE(session->proto) &&
session->state == COAP_SESSION_STATE_ESTABLISHED &&
!session->csm_block_supported) {
/*
* Need to check that this instance is not sending any block options as the
* remote end via CSM has not informed us that there is support
* https://tools.ietf.org/html/rfc8323#section-5.3.2
* Note that this also includes BERT which is application specific.
*/
if (coap_check_option(pdu, COAP_OPTION_BLOCK1, &opt_iter) != NULL) {
coap_log(LOG_DEBUG,
"Remote end did not indicate CSM support for BLOCK1 enabled\n");
}
if (coap_check_option(pdu, COAP_OPTION_BLOCK2, &opt_iter) != NULL) {
coap_log(LOG_DEBUG,
"Remote end did not indicate CSM support for BLOCK2 enabled\n");
}
}
#endif /* !COAP_DISABLE_TCP */
bytes_written = coap_send_pdu( session, pdu, NULL );
if (bytes_written == COAP_PDU_DELAYED) {
/* do not free pdu as it is stored with session for later use */
return pdu->mid;
}
if (bytes_written < 0) {
coap_delete_pdu(pdu);
return (coap_mid_t)bytes_written;
}
#if !COAP_DISABLE_TCP
if (COAP_PROTO_RELIABLE(session->proto) &&
(size_t)bytes_written < pdu->used_size + pdu->hdr_size) {
if (coap_session_delay_pdu(session, pdu, NULL) == COAP_PDU_DELAYED) {
session->partial_write = (size_t)bytes_written;
/* do not free pdu as it is stored with session for later use */
return pdu->mid;
} else {
goto error;
}
}
#endif /* !COAP_DISABLE_TCP */
if (pdu->type != COAP_MESSAGE_CON
|| COAP_PROTO_RELIABLE(session->proto)) {
coap_mid_t id = pdu->mid;
coap_delete_pdu(pdu);
return id;
}
coap_queue_t *node = coap_new_node();
if (!node) {
coap_log(LOG_DEBUG, "coap_wait_ack: insufficient memory\n");
goto error;
}
node->id = pdu->mid;
node->pdu = pdu;
coap_prng(&r, sizeof(r));
/* add timeout in range [ACK_TIMEOUT...ACK_TIMEOUT * ACK_RANDOM_FACTOR] */
node->timeout = coap_calc_timeout(session, r);
return coap_wait_ack(session->context, session, node);
error:
coap_delete_pdu(pdu);
return COAP_INVALID_MID;
}
coap_mid_t
coap_retransmit(coap_context_t *context, coap_queue_t *node) {
if (!context || !node)
return COAP_INVALID_MID;
/* re-initialize timeout when maximum number of retransmissions are not reached yet */
if (node->retransmit_cnt < node->session->max_retransmit) {
ssize_t bytes_written;
coap_tick_t now;
node->retransmit_cnt++;
coap_ticks(&now);
if (context->sendqueue == NULL) {
node->t = node->timeout << node->retransmit_cnt;
context->sendqueue_basetime = now;
} else {
/* make node->t relative to context->sendqueue_basetime */
node->t = (now - context->sendqueue_basetime) + (node->timeout << node->retransmit_cnt);
}
coap_insert_node(&context->sendqueue, node);
#ifdef WITH_LWIP
if (node == context->sendqueue) /* don't bother with timer stuff if there are earlier retransmits */
coap_retransmittimer_restart(context);
#endif
coap_log(LOG_DEBUG, "** %s: mid=0x%x: retransmission #%d\n",
coap_session_str(node->session), node->id, node->retransmit_cnt);
if (node->session->con_active)
node->session->con_active--;
bytes_written = coap_send_pdu(node->session, node->pdu, node);
if (bytes_written == COAP_PDU_DELAYED) {
/* PDU was not retransmitted immediately because a new handshake is
in progress. node was moved to the send queue of the session. */
return node->id;
}
if (bytes_written < 0)
return (int)bytes_written;
return node->id;
}
/* no more retransmissions, remove node from system */
#ifndef WITH_CONTIKI
coap_log(LOG_DEBUG, "** %s: mid=0x%x: give up after %d attempts\n",
coap_session_str(node->session), node->id, node->retransmit_cnt);
#endif
/* Check if subscriptions exist that should be canceled after
COAP_MAX_NOTIFY_FAILURES */
if (node->pdu->code >= 64) {
coap_binary_t token = { 0, NULL };
token.length = node->pdu->token_length;
token.s = node->pdu->token;
coap_handle_failed_notify(context, node->session, &token);
}
if (node->session->con_active) {
node->session->con_active--;
if (node->session->state == COAP_SESSION_STATE_ESTABLISHED) {
/*
* As there may be another CON in a different queue entry on the same
* session that needs to be immediately released,
* coap_session_connected() is called.
* However, there is the possibility coap_wait_ack() may be called for
* this node (queue) and re-added to context->sendqueue.
* coap_delete_node(node) called shortly will handle this and remove it.
*/
coap_session_connected(node->session);
}
}
/* And finally delete the node */
if (node->pdu->type == COAP_MESSAGE_CON && context->nack_handler)
context->nack_handler(node->session, node->pdu, COAP_NACK_TOO_MANY_RETRIES, node->id);
coap_delete_node(node);
return COAP_INVALID_MID;
}
#ifdef WITH_LWIP
/* WITH_LWIP, this is handled by coap_recv in a different way */
void
coap_io_do_io(coap_context_t *ctx, coap_tick_t now) {
return;
}
#else /* WITH_LWIP */
static int
coap_handle_dgram_for_proto(coap_context_t *ctx, coap_session_t *session, coap_packet_t *packet) {
uint8_t *data;
size_t data_len;
int result = -1;
coap_packet_get_memmapped(packet, &data, &data_len);
if (session->proto == COAP_PROTO_DTLS) {
if (session->type == COAP_SESSION_TYPE_HELLO)
result = coap_dtls_hello(session, data, data_len);
else if (session->tls)
result = coap_dtls_receive(session, data, data_len);
} else if (session->proto == COAP_PROTO_UDP) {
result = coap_handle_dgram(ctx, session, data, data_len);
}
return result;
}
static void
coap_connect_session(coap_context_t *ctx,
coap_session_t *session,
coap_tick_t now) {
(void)ctx;
#if COAP_DISABLE_TCP
(void)session;
(void)now;
#else /* !COAP_DISABLE_TCP */
if (coap_socket_connect_tcp2(&session->sock, &session->addr_info.local,
&session->addr_info.remote)) {
session->last_rx_tx = now;
coap_handle_event(session->context, COAP_EVENT_TCP_CONNECTED, session);
if (session->proto == COAP_PROTO_TCP) {
coap_session_send_csm(session);
} else if (session->proto == COAP_PROTO_TLS) {
int connected = 0;
session->state = COAP_SESSION_STATE_HANDSHAKE;
session->tls = coap_tls_new_client_session(session, &connected);
if (session->tls) {
if (connected) {
coap_handle_event(session->context, COAP_EVENT_DTLS_CONNECTED,
session);
coap_session_send_csm(session);
}
} else {
coap_handle_event(session->context, COAP_EVENT_DTLS_ERROR, session);
coap_session_disconnected(session, COAP_NACK_TLS_FAILED);
}
}
} else {
coap_handle_event(session->context, COAP_EVENT_TCP_FAILED, session);
coap_session_disconnected(session, COAP_NACK_NOT_DELIVERABLE);
}
#endif /* !COAP_DISABLE_TCP */
}
static void
coap_write_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now) {
(void)ctx;
assert(session->sock.flags & COAP_SOCKET_CONNECTED);
while (session->delayqueue) {
ssize_t bytes_written;
coap_queue_t *q = session->delayqueue;
coap_log(LOG_DEBUG, "** %s: mid=0x%x: transmitted after delay\n",
coap_session_str(session), (int)q->pdu->mid);
assert(session->partial_write < q->pdu->used_size + q->pdu->hdr_size);
switch (session->proto) {
case COAP_PROTO_TCP:
#if !COAP_DISABLE_TCP
bytes_written = coap_session_write(
session,
q->pdu->token - q->pdu->hdr_size - session->partial_write,
q->pdu->used_size + q->pdu->hdr_size - session->partial_write
);
#endif /* !COAP_DISABLE_TCP */
break;
case COAP_PROTO_TLS:
#if !COAP_DISABLE_TCP
bytes_written = coap_tls_write(
session,
q->pdu->token - q->pdu->hdr_size - session->partial_write,
q->pdu->used_size + q->pdu->hdr_size - session->partial_write
);
#endif /* !COAP_DISABLE_TCP */
break;
case COAP_PROTO_NONE:
case COAP_PROTO_UDP:
case COAP_PROTO_DTLS:
default:
bytes_written = -1;
break;
}
if (bytes_written > 0)
session->last_rx_tx = now;
if (bytes_written <= 0 || (size_t)bytes_written < q->pdu->used_size + q->pdu->hdr_size - session->partial_write) {
if (bytes_written > 0)
session->partial_write += (size_t)bytes_written;
break;
}
session->delayqueue = q->next;
session->partial_write = 0;
coap_delete_node(q);
}
}
static void
coap_read_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now) {
#if COAP_CONSTRAINED_STACK
static coap_mutex_t s_static_mutex = COAP_MUTEX_INITIALIZER;
static coap_packet_t s_packet;
#else /* ! COAP_CONSTRAINED_STACK */
coap_packet_t s_packet;
#endif /* ! COAP_CONSTRAINED_STACK */
coap_packet_t *packet = &s_packet;
#if COAP_CONSTRAINED_STACK
coap_mutex_lock(&s_static_mutex);
#endif /* COAP_CONSTRAINED_STACK */
assert(session->sock.flags & (COAP_SOCKET_CONNECTED | COAP_SOCKET_MULTICAST));
if (COAP_PROTO_NOT_RELIABLE(session->proto)) {
ssize_t bytes_read;
memcpy(&packet->addr_info, &session->addr_info, sizeof(packet->addr_info));
bytes_read = ctx->network_read(&session->sock, packet);
if (bytes_read < 0) {
if (bytes_read == -2)
/* Reset the session back to startup defaults */
coap_session_disconnected(session, COAP_NACK_ICMP_ISSUE);
else
coap_log(LOG_WARNING, "* %s: read error\n",
coap_session_str(session));
} else if (bytes_read > 0) {
session->last_rx_tx = now;
memcpy(&session->addr_info, &packet->addr_info,
sizeof(session->addr_info));
coap_log(LOG_DEBUG, "* %s: received %zd bytes\n",
coap_session_str(session), bytes_read);
coap_handle_dgram_for_proto(ctx, session, packet);
}
#if !COAP_DISABLE_TCP
} else {
ssize_t bytes_read = 0;
const uint8_t *p;
int retry;
/* adjust for LWIP */
uint8_t *buf = packet->payload;
size_t buf_len = sizeof(packet->payload);
do {
if (session->proto == COAP_PROTO_TCP)
bytes_read = coap_socket_read(&session->sock, buf, buf_len);
else if (session->proto == COAP_PROTO_TLS)
bytes_read = coap_tls_read(session, buf, buf_len);
if (bytes_read > 0) {
coap_log(LOG_DEBUG, "* %s: received %zd bytes\n",
coap_session_str(session), bytes_read);
session->last_rx_tx = now;
}
p = buf;
retry = bytes_read == (ssize_t)buf_len;
while (bytes_read > 0) {
if (session->partial_pdu) {
size_t len = session->partial_pdu->used_size
+ session->partial_pdu->hdr_size
- session->partial_read;
size_t n = min(len, (size_t)bytes_read);
memcpy(session->partial_pdu->token - session->partial_pdu->hdr_size
+ session->partial_read, p, n);
p += n;
bytes_read -= n;
if (n == len) {
if (coap_pdu_parse_header(session->partial_pdu, session->proto)
&& coap_pdu_parse_opt(session->partial_pdu)) {
coap_dispatch(ctx, session, session->partial_pdu);
}
coap_delete_pdu(session->partial_pdu);
session->partial_pdu = NULL;
session->partial_read = 0;
} else {
session->partial_read += n;
}
} else if (session->partial_read > 0) {
size_t hdr_size = coap_pdu_parse_header_size(session->proto,
session->read_header);
size_t len = hdr_size - session->partial_read;
size_t n = min(len, (size_t)bytes_read);
memcpy(session->read_header + session->partial_read, p, n);
p += n;
bytes_read -= n;
if (n == len) {
size_t size = coap_pdu_parse_size(session->proto, session->read_header,
hdr_size);
if (size > COAP_DEFAULT_MAX_PDU_RX_SIZE) {
coap_log(LOG_WARNING,
"** %s: incoming PDU length too large (%zu > %lu)\n",
coap_session_str(session),
size, COAP_DEFAULT_MAX_PDU_RX_SIZE);
bytes_read = -1;
break;
}
/* Need max space incase PDU is updated with updated token etc. */
session->partial_pdu = coap_pdu_init(0, 0, 0,
coap_session_max_pdu_size(session));
if (session->partial_pdu == NULL) {
bytes_read = -1;
break;
}
if (session->partial_pdu->alloc_size < size && !coap_pdu_resize(session->partial_pdu, size)) {
bytes_read = -1;
break;
}
session->partial_pdu->hdr_size = (uint8_t)hdr_size;
session->partial_pdu->used_size = size;
memcpy(session->partial_pdu->token - hdr_size, session->read_header, hdr_size);
session->partial_read = hdr_size;
if (size == 0) {
if (coap_pdu_parse_header(session->partial_pdu, session->proto)) {
coap_dispatch(ctx, session, session->partial_pdu);
}
coap_delete_pdu(session->partial_pdu);
session->partial_pdu = NULL;
session->partial_read = 0;
}
} else {
session->partial_read += bytes_read;
}
} else {
session->read_header[0] = *p++;
bytes_read -= 1;
if (!coap_pdu_parse_header_size(session->proto,
session->read_header)) {
bytes_read = -1;
break;
}
session->partial_read = 1;
}
}
} while (bytes_read == 0 && retry);
if (bytes_read < 0)
coap_session_disconnected(session, COAP_NACK_NOT_DELIVERABLE);
#endif /* !COAP_DISABLE_TCP */
}
#if COAP_CONSTRAINED_STACK
coap_mutex_unlock(&s_static_mutex);
#endif /* COAP_CONSTRAINED_STACK */
}
static int
coap_read_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
ssize_t bytes_read = -1;
int result = -1; /* the value to be returned */
#if COAP_CONSTRAINED_STACK
static coap_mutex_t e_static_mutex = COAP_MUTEX_INITIALIZER;
static coap_packet_t e_packet;
#else /* ! COAP_CONSTRAINED_STACK */
coap_packet_t e_packet;
#endif /* ! COAP_CONSTRAINED_STACK */
coap_packet_t *packet = &e_packet;
assert(COAP_PROTO_NOT_RELIABLE(endpoint->proto));
assert(endpoint->sock.flags & COAP_SOCKET_BOUND);
#if COAP_CONSTRAINED_STACK
coap_mutex_lock(&e_static_mutex);
#endif /* COAP_CONSTRAINED_STACK */
/* Need to do this as there may be holes in addr_info */
memset(&packet->addr_info, 0, sizeof(packet->addr_info));
coap_address_init(&packet->addr_info.remote);
coap_address_copy(&packet->addr_info.local, &endpoint->bind_addr);
bytes_read = ctx->network_read(&endpoint->sock, packet);
if (bytes_read < 0) {
coap_log(LOG_WARNING, "* %s: read failed\n", coap_endpoint_str(endpoint));
} else if (bytes_read > 0) {
coap_session_t *session = coap_endpoint_get_session(endpoint, packet, now);
if (session) {
coap_log(LOG_DEBUG, "* %s: received %zd bytes\n",
coap_session_str(session), bytes_read);
result = coap_handle_dgram_for_proto(ctx, session, packet);
if (endpoint->proto == COAP_PROTO_DTLS && session->type == COAP_SESSION_TYPE_HELLO && result == 1)
coap_session_new_dtls_session(session, now);
}
}
#if COAP_CONSTRAINED_STACK
coap_mutex_unlock(&e_static_mutex);
#endif /* COAP_CONSTRAINED_STACK */
return result;
}
static int
coap_write_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now) {
(void)ctx;
(void)endpoint;
(void)now;
return 0;
}
static int
coap_accept_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint,
coap_tick_t now) {
coap_session_t *session = coap_new_server_session(ctx, endpoint);
if (session)
session->last_rx_tx = now;
return session != NULL;
}
void
coap_io_do_io(coap_context_t *ctx, coap_tick_t now) {
#ifdef COAP_EPOLL_SUPPORT
(void)ctx;
(void)now;
coap_log(LOG_EMERG,
"coap_io_do_io() requires libcoap not compiled for using epoll\n");
#else /* ! COAP_EPOLL_SUPPORT */
coap_endpoint_t *ep, *tmp;
coap_session_t *s, *rtmp;
LL_FOREACH_SAFE(ctx->endpoint, ep, tmp) {
if ((ep->sock.flags & COAP_SOCKET_CAN_READ) != 0)
coap_read_endpoint(ctx, ep, now);
if ((ep->sock.flags & COAP_SOCKET_CAN_WRITE) != 0)
coap_write_endpoint(ctx, ep, now);
if ((ep->sock.flags & COAP_SOCKET_CAN_ACCEPT) != 0)
coap_accept_endpoint(ctx, ep, now);
SESSIONS_ITER_SAFE(ep->sessions, s, rtmp) {
if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0) {
/* Make sure the session object is not deleted in one of the callbacks */
coap_session_reference(s);
coap_read_session(ctx, s, now);
coap_session_release(s);
}
if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0) {
/* Make sure the session object is not deleted in one of the callbacks */
coap_session_reference(s);
coap_write_session(ctx, s, now);
coap_session_release(s);
}
}
}
SESSIONS_ITER_SAFE(ctx->sessions, s, rtmp) {
if ((s->sock.flags & COAP_SOCKET_CAN_CONNECT) != 0) {
/* Make sure the session object is not deleted in one of the callbacks */
coap_session_reference(s);
coap_connect_session(ctx, s, now);
coap_session_release( s );
}
if ((s->sock.flags & COAP_SOCKET_CAN_READ) != 0) {
/* Make sure the session object is not deleted in one of the callbacks */
coap_session_reference(s);
coap_read_session(ctx, s, now);
coap_session_release(s);
}
if ((s->sock.flags & COAP_SOCKET_CAN_WRITE) != 0) {
/* Make sure the session object is not deleted in one of the callbacks */
coap_session_reference(s);
coap_write_session(ctx, s, now);
coap_session_release( s );
}
}
#endif /* ! COAP_EPOLL_SUPPORT */
}
/*
* While this code in part replicates coap_io_do_io(), doing the functions
* directly saves having to iterate through the endpoints / sessions.
*/
void
coap_io_do_epoll(coap_context_t *ctx, struct epoll_event *events, size_t nevents) {
#ifndef COAP_EPOLL_SUPPORT
(void)ctx;
(void)events;
(void)nevents;
coap_log(LOG_EMERG,
"coap_io_do_epoll() requires libcoap compiled for using epoll\n");
#else /* COAP_EPOLL_SUPPORT */
coap_tick_t now;
size_t j;
coap_ticks(&now);
for(j = 0; j < nevents; j++) {
coap_socket_t *sock = (coap_socket_t*)events[j].data.ptr;
/* Ignore 'timer trigger' ptr which is NULL */
if (sock) {
if (sock->endpoint) {
coap_endpoint_t *endpoint = sock->endpoint;
if ((sock->flags & COAP_SOCKET_WANT_READ) &&
(events[j].events & EPOLLIN)) {
sock->flags |= COAP_SOCKET_CAN_READ;
coap_read_endpoint(endpoint->context, endpoint, now);
}
if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
(events[j].events & EPOLLOUT)) {
/*
* Need to update this to EPOLLIN as EPOLLOUT will normally always
* be true causing epoll_wait to return early
*/
coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
sock->flags |= COAP_SOCKET_CAN_WRITE;
coap_write_endpoint(endpoint->context, endpoint, now);
}
if ((sock->flags & COAP_SOCKET_WANT_ACCEPT) &&
(events[j].events & EPOLLIN)) {
sock->flags |= COAP_SOCKET_CAN_ACCEPT;
coap_accept_endpoint(endpoint->context, endpoint, now);
}
}
else if (sock->session) {
coap_session_t *session = sock->session;
/* Make sure the session object is not deleted
in one of the callbacks */
coap_session_reference(session);
if ((sock->flags & COAP_SOCKET_WANT_CONNECT) &&
(events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
sock->flags |= COAP_SOCKET_CAN_CONNECT;
coap_connect_session(session->context, session, now);
if (!(sock->flags & COAP_SOCKET_WANT_WRITE)) {
coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
}
}
if ((sock->flags & COAP_SOCKET_WANT_READ) &&
(events[j].events & (EPOLLIN|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
sock->flags |= COAP_SOCKET_CAN_READ;
coap_read_session(session->context, session, now);
}
if ((sock->flags & COAP_SOCKET_WANT_WRITE) &&
(events[j].events & (EPOLLOUT|EPOLLERR|EPOLLHUP|EPOLLRDHUP))) {
/*
* Need to update this to EPOLLIN as EPOLLOUT will normally always
* be true causing epoll_wait to return early
*/
coap_epoll_ctl_mod(sock, EPOLLIN, __func__);
sock->flags |= COAP_SOCKET_CAN_WRITE;
coap_write_session(session->context, session, now);
}
/* Now dereference session so it can go away if needed */
coap_session_release(session);
}
}
else if (ctx->eptimerfd != -1) {
/*
* 'timer trigger' must have fired. eptimerfd needs to be read to clear
* it so that it does not set EPOLLIN in the next epoll_wait().
*/
uint64_t count;
/* Check the result from read() to suppress the warning on
* systems that declare read() with warn_unused_result. */
if (read(ctx->eptimerfd, &count, sizeof(count)) == -1) {
/* do nothing */;
}
}
/* And update eptimerfd as to when to next trigger */
coap_ticks(&now);
coap_io_prepare_epoll(ctx, now);
}
#endif /* COAP_EPOLL_SUPPORT */
}
int
coap_handle_dgram(coap_context_t *ctx, coap_session_t *session,
uint8_t *msg, size_t msg_len) {
coap_pdu_t *pdu = NULL;
assert(COAP_PROTO_NOT_RELIABLE(session->proto));
if (msg_len < 4) {
/* Minimum size of CoAP header - ignore runt */
return -1;
}
/* Need max space incase PDU is updated with updated token etc. */
pdu = coap_pdu_init(0, 0, 0, coap_session_max_pdu_size(session));
if (!pdu)
goto error;
if (!coap_pdu_parse(session->proto, msg, msg_len, pdu)) {
coap_log(LOG_WARNING, "discard malformed PDU\n");
goto error;
}
coap_dispatch(ctx, session, pdu);
coap_delete_pdu(pdu);
return 0;
error:
/*
* https://tools.ietf.org/html/rfc7252#section-4.2 MUST send RST
* https://tools.ietf.org/html/rfc7252#section-4.3 MAY send RST
*/
coap_send_rst(session, pdu);
coap_delete_pdu(pdu);
return -1;
}
#endif /* not WITH_LWIP */
int
coap_remove_from_queue(coap_queue_t **queue, coap_session_t *session, coap_mid_t id, coap_queue_t **node) {
coap_queue_t *p, *q;
if (!queue || !*queue)
return 0;
/* replace queue head if PDU's time is less than head's time */
if (session == (*queue)->session && id == (*queue)->id) { /* found message id */
*node = *queue;
*queue = (*queue)->next;
if (*queue) { /* adjust relative time of new queue head */
(*queue)->t += (*node)->t;
}
(*node)->next = NULL;
coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed\n",
coap_session_str(session), id);
return 1;
}
/* search message id queue to remove (only first occurence will be removed) */
q = *queue;
do {
p = q;
q = q->next;
} while (q && (session != q->session || id != q->id));
if (q) { /* found message id */
p->next = q->next;
if (p->next) { /* must update relative time of p->next */
p->next->t += q->t;
}
q->next = NULL;
*node = q;
coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed\n",
coap_session_str(session), id);
return 1;
}
return 0;
}
void
coap_cancel_session_messages(coap_context_t *context, coap_session_t *session,
coap_nack_reason_t reason) {
coap_queue_t *p, *q;
while (context->sendqueue && context->sendqueue->session == session) {
q = context->sendqueue;
context->sendqueue = q->next;
coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed\n",
coap_session_str(session), q->id);
if (q->pdu->type == COAP_MESSAGE_CON && context->nack_handler)
context->nack_handler(session, q->pdu, reason, q->id);
coap_delete_node(q);
}
if (!context->sendqueue)
return;
p = context->sendqueue;
q = p->next;
while (q) {
if (q->session == session) {
p->next = q->next;
coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed\n",
coap_session_str(session), q->id);
if (q->pdu->type == COAP_MESSAGE_CON && context->nack_handler)
context->nack_handler(session, q->pdu, reason, q->id);
coap_delete_node(q);
q = p->next;
} else {
p = q;
q = q->next;
}
}
}
void
coap_cancel_all_messages(coap_context_t *context, coap_session_t *session,
const uint8_t *token, size_t token_length) {
/* cancel all messages in sendqueue that belong to session
* and use the specified token */
coap_queue_t *p, *q;
while (context->sendqueue && context->sendqueue->session == session &&
token_match(token, token_length,
context->sendqueue->pdu->token,
context->sendqueue->pdu->token_length)) {
q = context->sendqueue;
context->sendqueue = q->next;
coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed\n",
coap_session_str(session), q->id);
coap_delete_node(q);
}
if (!context->sendqueue)
return;
p = context->sendqueue;
q = p->next;
/* when q is not NULL, it does not match (dst, token), so we can skip it */
while (q) {
if (q->session == session &&
token_match(token, token_length,
q->pdu->token, q->pdu->token_length)) {
p->next = q->next;
coap_log(LOG_DEBUG, "** %s: mid=0x%x: removed\n",
coap_session_str(session), q->id);
coap_delete_node(q);
q = p->next;
} else {
p = q;
q = q->next;
}
}
}
coap_pdu_t *
coap_new_error_response(const coap_pdu_t *request, coap_pdu_code_t code,
coap_opt_filter_t *opts) {
coap_opt_iterator_t opt_iter;
coap_pdu_t *response;
size_t size = request->token_length;
unsigned char type;
coap_opt_t *option;
coap_option_num_t opt_num = 0; /* used for calculating delta-storage */
#if COAP_ERROR_PHRASE_LENGTH > 0
const char *phrase;
if (code != COAP_RESPONSE_CODE(508)) {
phrase = coap_response_phrase(code);
/* Need some more space for the error phrase and payload start marker */
if (phrase)
size += strlen(phrase) + 1;
}
else {
/*
* Need space for IP for 5.08 response which is filled in in
* coap_send_internal()
* https://www.rfc-editor.org/rfc/rfc8768.html#section-4
*/
phrase = NULL;
size += INET6_ADDRSTRLEN;
}
#endif
assert(request);
/* cannot send ACK if original request was not confirmable */
type = request->type == COAP_MESSAGE_CON
? COAP_MESSAGE_ACK
: COAP_MESSAGE_NON;
/* Estimate how much space we need for options to copy from
* request. We always need the Token, for 4.02 the unknown critical
* options must be included as well. */
/* we do not want these */
coap_option_filter_unset(opts, COAP_OPTION_CONTENT_TYPE);
coap_option_filter_unset(opts, COAP_OPTION_HOP_LIMIT);
coap_option_iterator_init(request, &opt_iter, opts);
/* Add size of each unknown critical option. As known critical
options as well as elective options are not copied, the delta
value might grow.
*/
while ((option = coap_option_next(&opt_iter))) {
uint16_t delta = opt_iter.number - opt_num;
/* calculate space required to encode (opt_iter.number - opt_num) */
if (delta < 13) {
size++;
} else if (delta < 269) {
size += 2;
} else {
size += 3;
}
/* add coap_opt_length(option) and the number of additional bytes
* required to encode the option length */
size += coap_opt_length(option);
switch (*option & 0x0f) {
case 0x0e:
size++;
/* fall through */
case 0x0d:
size++;
break;
default:
;
}
opt_num = opt_iter.number;
}
/* Now create the response and fill with options and payload data. */
response = coap_pdu_init(type, code, request->mid, size);
if (response) {
/* copy token */
if (!coap_add_token(response, request->token_length,
request->token)) {
coap_log(LOG_DEBUG, "cannot add token to error response\n");
coap_delete_pdu(response);
return NULL;
}
/* copy all options */
coap_option_iterator_init(request, &opt_iter, opts);
while ((option = coap_option_next(&opt_iter))) {
coap_add_option(response, opt_iter.number,
coap_opt_length(option),
coap_opt_value(option));
}
#if COAP_ERROR_PHRASE_LENGTH > 0
/* note that diagnostic messages do not need a Content-Format option. */
if (phrase)
coap_add_data(response, (size_t)strlen(phrase), (const uint8_t *)phrase);
#endif
}
return response;
}
COAP_STATIC_INLINE size_t
get_wkc_len(coap_context_t *context, coap_opt_t *query_filter) {
unsigned char buf[1];
size_t len = 0;
if (coap_print_wellknown(context, buf, &len, UINT_MAX, query_filter)
& COAP_PRINT_STATUS_ERROR) {
coap_log(LOG_WARNING, "cannot determine length of /.well-known/core\n");
return 0;
}
coap_log(LOG_DEBUG, "get_wkc_len: coap_print_wellknown() returned %zu\n", len);
return len;
}
#define SZX_TO_BYTES(SZX) ((size_t)(1 << ((SZX) + 4)))
coap_pdu_t *
coap_wellknown_response(coap_context_t *context, coap_session_t *session,
coap_pdu_t *request) {
coap_pdu_t *resp;
coap_opt_iterator_t opt_iter;
size_t len, wkc_len;
uint8_t buf[4];
int result = 0;
int need_block2 = 0; /* set to 1 if Block2 option is required */
coap_block_t block;
coap_opt_t *query_filter;
size_t offset = 0;
uint8_t *data;
resp = coap_pdu_init(request->type == COAP_MESSAGE_CON
? COAP_MESSAGE_ACK
: COAP_MESSAGE_NON,
COAP_RESPONSE_CODE(205),
request->mid, coap_session_max_pdu_size(session));
if (!resp) {
coap_log(LOG_DEBUG, "coap_wellknown_response: cannot create PDU\n");
return NULL;
}
if (!coap_add_token(resp, request->token_length, request->token)) {
coap_log(LOG_DEBUG, "coap_wellknown_response: cannot add token\n");
goto error;
}
query_filter = coap_check_option(request, COAP_OPTION_URI_QUERY, &opt_iter);
wkc_len = get_wkc_len(context, query_filter);
/* The value of some resources is undefined and get_wkc_len will return 0.*/
if (wkc_len == 0) {
coap_log(LOG_DEBUG, "coap_wellknown_response: undefined resource\n");
/* set error code 4.00 Bad Request*/
resp->code = COAP_RESPONSE_CODE(400);
resp->used_size = resp->token_length;
return resp;
}
/* check whether the request contains the Block2 option */
if (coap_get_block(request, COAP_OPTION_BLOCK2, &block)) {
coap_log(LOG_DEBUG, "create block\n");
offset = block.num << (block.szx + 4);
if (block.szx > 6) { /* invalid, MUST lead to 4.00 Bad Request */
resp->code = COAP_RESPONSE_CODE(400);
return resp;
} else if (block.szx > COAP_MAX_BLOCK_SZX) {
block.szx = COAP_MAX_BLOCK_SZX;
block.num = (unsigned int)(offset >> (block.szx + 4));
}
need_block2 = 1;
}
/* Check if there is sufficient space to add Content-Format option
* and data. We do this before adding the Content-Format option to
* avoid sending error responses with that option but no actual
* content. */
if (resp->max_size && resp->max_size <= resp->used_size + 8) {
coap_log(LOG_DEBUG, "coap_wellknown_response: insufficient storage space\n");
goto error;
}
/* check if Block2 option is required even if not requested */
if (!need_block2 && resp->max_size && resp->max_size - resp->used_size < wkc_len + 1) {
assert(resp->used_size <= resp->max_size);
const size_t payloadlen = resp->max_size - resp->used_size;
/* yes, need block-wise transfer */
block.num = 0;
block.m = 0; /* the M bit is set by coap_write_block_opt() */
block.szx = COAP_MAX_BLOCK_SZX;
while (payloadlen < SZX_TO_BYTES(block.szx) + 6) {
if (block.szx == 0) {
coap_log(LOG_DEBUG,
"coap_wellknown_response: message to small even for szx == 0\n");
goto error;
} else {
block.szx--;
}
}
need_block2 = 1;
}
if (need_block2) {
/* Add in a pseudo etag (use wkc_len) in case .well-known/core
changes over time */
coap_add_option(resp,
COAP_OPTION_ETAG,
coap_encode_var_safe8(buf, sizeof(buf), wkc_len),
buf);
}
/* Add Content-Format. As we have checked for available storage,
* nothing should go wrong here. */
assert(coap_encode_var_safe(buf, sizeof(buf),
COAP_MEDIATYPE_APPLICATION_LINK_FORMAT) == 1);
coap_add_option(resp, COAP_OPTION_CONTENT_FORMAT,
coap_encode_var_safe(buf, sizeof(buf),
COAP_MEDIATYPE_APPLICATION_LINK_FORMAT), buf);
/* write Block2 option if necessary */
if (need_block2) {
if (coap_write_block_opt(&block, COAP_OPTION_BLOCK2, resp, wkc_len) < 0) {
coap_log(LOG_DEBUG,
"coap_wellknown_response: cannot add Block2 option\n");
goto error;
}
}
coap_add_option(resp,
COAP_OPTION_SIZE2,
coap_encode_var_safe8(buf, sizeof(buf), wkc_len),
buf);
len = need_block2 ?
min(SZX_TO_BYTES(block.szx), wkc_len - (block.num << (block.szx + 4))) :
resp->max_size && resp->used_size + wkc_len + 1 > resp->max_size ?
resp->max_size - resp->used_size - 1 : wkc_len;
data = coap_add_data_after(resp, len);
if (!data) {
coap_log(LOG_DEBUG, "coap_wellknown_response: coap_add_data failed\n" );
goto error;
}
result = coap_print_wellknown(context, data, &len, offset, query_filter);
if ((result & COAP_PRINT_STATUS_ERROR) != 0) {
coap_log(LOG_DEBUG, "coap_print_wellknown failed\n");
goto error;
}
return resp;
error:
/* set error code 5.03 and remove all options and data from response */
resp->code = COAP_RESPONSE_CODE(503);
resp->used_size = resp->token_length;
return resp;
}
static int
coap_cancel(coap_context_t *context, const coap_queue_t *sent) {
coap_binary_t token = { 0, NULL };
int num_cancelled = 0; /* the number of observers cancelled */
/* remove observer for this resource, if any
* get token from sent and try to find a matching resource. Uh!
*/
COAP_SET_STR(&token, sent->pdu->token_length, sent->pdu->token);
RESOURCES_ITER(context->resources, r) {
coap_cancel_all_messages(context, sent->session, token.s, token.length);
num_cancelled += coap_delete_observer(r, sent->session, &token);
}
return num_cancelled;
}
enum respond_t { RESPONSE_DEFAULT, RESPONSE_DROP, RESPONSE_SEND };
/*
* Checks for No-Response option in given @p request and
* returns @c RESPONSE_DROP if @p response should be suppressed
* according to RFC 7967.
*
* If the response is a confirmable piggybacked response and RESPONSE_DROP,
* change it to an empty ACK and @c RESPONSE_SEND so the client does not keep
* on retrying.
*
* Checks if the response code is 0.00 and if either the session is reliable or
* non-confirmable, @c RESPONSE_DROP is also returned.
*
* Multicast response checking is also carried out.
*
* NOTE: It is the responsibility of the application to determine whether
* a delayed separate response should be sent as the original requesting packet
* containing the No-Response option has long since gone.
*
* The value of the No-Response option is encoded as
* follows:
*
* @verbatim
* +-------+-----------------------+-----------------------------------+
* | Value | Binary Representation | Description |
* +-------+-----------------------+-----------------------------------+
* | 0 | <empty> | Interested in all responses. |
* +-------+-----------------------+-----------------------------------+
* | 2 | 00000010 | Not interested in 2.xx responses. |
* +-------+-----------------------+-----------------------------------+
* | 8 | 00001000 | Not interested in 4.xx responses. |
* +-------+-----------------------+-----------------------------------+
* | 16 | 00010000 | Not interested in 5.xx responses. |
* +-------+-----------------------+-----------------------------------+
* @endverbatim
*
* @param request The CoAP request to check for the No-Response option.
* This parameter must not be NULL.
* @param response The response that is potentially suppressed.
* This parameter must not be NULL.
* @param session The session this request/response are associated with.
* This parameter must not be NULL.
* @return RESPONSE_DEFAULT when no special treatment is requested,
* RESPONSE_DROP when the response must be discarded, or
* RESPONSE_SEND when the response must be sent.
*/
static enum respond_t
no_response(coap_pdu_t *request, coap_pdu_t *response,
coap_session_t *session) {
coap_opt_t *nores;
coap_opt_iterator_t opt_iter;
unsigned int val = 0;
assert(request);
assert(response);
if (COAP_RESPONSE_CLASS(response->code) > 0) {
nores = coap_check_option(request, COAP_OPTION_NORESPONSE, &opt_iter);
if (nores) {
val = coap_decode_var_bytes(coap_opt_value(nores), coap_opt_length(nores));
/* The response should be dropped when the bit corresponding to
* the response class is set (cf. table in function
* documentation). When a No-Response option is present and the
* bit is not set, the sender explicitly indicates interest in
* this response. */
if (((1 << (COAP_RESPONSE_CLASS(response->code) - 1)) & val) > 0) {
/* Should be dropping the response */
if (response->type == COAP_MESSAGE_ACK &&
COAP_PROTO_NOT_RELIABLE(session->proto)) {
/* Still need to ACK the request */
response->code = 0;
/* Remove token/data from piggybacked acknowledgment PDU */
response->token_length = 0;
response->used_size = 0;
return RESPONSE_SEND;
}
else {
return RESPONSE_DROP;
}
} else {
/* True for mcast as well RFC7967 2.1 */
return RESPONSE_SEND;
}
}
}
else if (COAP_PDU_IS_EMPTY(response) &&
(response->type == COAP_MESSAGE_NON ||
COAP_PROTO_RELIABLE(session->proto))) {
/* response is 0.00, and this is reliable or non-confirmable */
return RESPONSE_DROP;
}
/*
* Do not send error responses for requests that were received via
* IP multicast. RFC7252 8.1
*/
if (coap_is_mcast(&session->addr_info.local)) {
if (request->type == COAP_MESSAGE_NON &&
response->type == COAP_MESSAGE_RST)
return RESPONSE_DROP;
if (COAP_RESPONSE_CLASS(response->code) > 2)
return RESPONSE_DROP;
}
/* Default behavior applies when we are not dealing with a response
* (class == 0) or the request did not contain a No-Response option.
*/
return RESPONSE_DEFAULT;
}
static coap_str_const_t coap_default_uri_wellknown =
{ sizeof(COAP_DEFAULT_URI_WELLKNOWN)-1,
(const uint8_t *)COAP_DEFAULT_URI_WELLKNOWN };
static void
handle_request(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu) {
coap_method_handler_t h = NULL;
coap_pdu_t *response = NULL;
coap_opt_filter_t opt_filter;
coap_resource_t *resource = NULL;
/* The respond field indicates whether a response must be treated
* specially due to a No-Response option that declares disinterest
* or interest in a specific response class. DEFAULT indicates that
* No-Response has not been specified. */
enum respond_t respond = RESPONSE_DEFAULT;
coap_opt_iterator_t opt_iter;
coap_opt_t *opt;
int is_proxy_uri = 0;
int is_proxy_scheme = 0;
int skip_hop_limit_check = 0;
int resp;
coap_binary_t token = { pdu->token_length, pdu->token };
#ifndef WITHOUT_ASYNC
coap_bin_const_t tokenc = { pdu->token_length, pdu->token };
coap_async_t *async;
#endif /* WITHOUT_ASYNC */
if (coap_is_mcast(&session->addr_info.local)) {
if (COAP_PROTO_RELIABLE(session->proto) || pdu->type != COAP_MESSAGE_NON) {
coap_log(LOG_INFO, "Invalid multicast packet received RFC7252 8.1\n");
return;
}
}
#ifndef WITHOUT_ASYNC
async = coap_find_async(session, tokenc);
if (async) {
coap_tick_t now;
coap_ticks(&now);
if (async->delay == 0 || async->delay > now) {
/* re-transmit missing ACK (only if CON) */
coap_log(LOG_INFO, "Retransmit async response\n");
coap_send_ack(session, pdu);
/* and do not pass on to the upper layers */
return;
}
}
else if (coap_is_mcast(&session->addr_info.local)) {
uint8_t r;
coap_tick_t delay;
/* Need to delay sending mcast request to application layer, so response
is not immediate. */
coap_prng(&r, sizeof(r));
delay = (COAP_DEFAULT_LEISURE * COAP_TICKS_PER_SECOND * r) / 256;
/* Register request to be internally re-transmitted after delay */
if (coap_register_async(session, pdu, delay))
return;
}
#endif /* WITHOUT_ASYNC */
coap_option_filter_clear(&opt_filter);
opt = coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter);
if (opt)
is_proxy_scheme = 1;
opt = coap_check_option(pdu, COAP_OPTION_PROXY_URI, &opt_iter);
if (opt)
is_proxy_uri = 1;
if (is_proxy_scheme || is_proxy_uri) {
coap_uri_t uri;
if (!context->proxy_uri_resource) {
/* Need to return a 5.05 RFC7252 Section 5.7.2 */
coap_log(LOG_DEBUG, "Proxy-%s support not configured\n",
is_proxy_scheme ? "Scheme" : "Uri");
resp = 505;
goto fail_response;
}
if (((size_t)pdu->code - 1 <
(sizeof(resource->handler) / sizeof(resource->handler[0]))) &&
!(context->proxy_uri_resource->handler[pdu->code - 1])) {
/* Need to return a 5.05 RFC7252 Section 5.7.2 */
coap_log(LOG_DEBUG, "Proxy-%s code %d.%02d handler not supported\n",
is_proxy_scheme ? "Scheme" : "Uri",
pdu->code/100, pdu->code%100);
resp = 505;
goto fail_response;
}
/* Need to check if authority is the proxy endpoint RFC7252 Section 5.7.2 */
if (is_proxy_uri) {
if (coap_split_proxy_uri(coap_opt_value(opt),
coap_opt_length(opt), &uri) < 0) {
/* Need to return a 5.05 RFC7252 Section 5.7.2 */
coap_log(LOG_DEBUG, "Proxy-URI not decodable\n");
resp = 505;
goto fail_response;
}
}
else {
memset(&uri, 0, sizeof(uri));
opt = coap_check_option(pdu, COAP_OPTION_URI_HOST, &opt_iter);
if (opt) {
uri.host.length = coap_opt_length(opt);
uri.host.s = coap_opt_value(opt);
}
}
resource = context->proxy_uri_resource;
if (uri.host.length && resource->proxy_name_count && resource->proxy_name_list) {
size_t i;
for (i = 0; i < resource->proxy_name_count; i++) {
if (coap_string_equal(&uri.host, resource->proxy_name_list[i])) {
break;
}
}
if (i != resource->proxy_name_count) {
/* This server is hosting the proxy connection endpoint */
is_proxy_uri = 0;
is_proxy_scheme = 0;
skip_hop_limit_check = 1;
}
}
resource = NULL;
}
if (!skip_hop_limit_check) {
opt = coap_check_option(pdu, COAP_OPTION_HOP_LIMIT, &opt_iter);
if (opt) {
size_t hop_limit;
uint8_t buf[4];
hop_limit =
coap_decode_var_bytes (coap_opt_value (opt), coap_opt_length (opt));
if (hop_limit == 1) {
/* coap_send_internal() will fill in the IP address for us */
resp = 508;
goto fail_response;
}
else if (hop_limit < 1 || hop_limit > 255) {
/* Need to return a 4.00 RFC8768 Section 3 */
coap_log(LOG_INFO, "Invalid Hop Limit\n");
resp = 400;
goto fail_response;
}
hop_limit--;
coap_update_option(pdu, COAP_OPTION_HOP_LIMIT,
coap_encode_var_safe8(buf, sizeof(buf), hop_limit),
buf);
}
}
coap_string_t *uri_path = coap_get_uri_path(pdu);
if (!uri_path)
return;
if (!is_proxy_uri && !is_proxy_scheme) {
/* try to find the resource from the request URI */
coap_str_const_t uri_path_c = { uri_path->length, uri_path->s };
resource = coap_get_resource_from_uri_path(context, &uri_path_c);
}
if ((resource == NULL) || (resource->is_unknown == 1) ||
(resource->is_proxy_uri == 1)) {
/* The resource was not found or there is an unexpected match against the
* resource defined for handling unknown or proxy URIs.
* Check if the request URI happens to be the well-known URI, or if the
* unknown resource handler is defined, a PUT or optionally other methods,
* if configured, for the unknown handler.
*
* if well-known URI generate a default response
*
* else if a PROXY URI/Scheme request and proxy URI handler defined, call the
* proxy URI handler
*
* else if unknown URI handler defined, call the unknown
* URI handler (to allow for potential generation of resource
* [RFC7272 5.8.3]) if the appropriate method is defined.
*
* else if DELETE return 2.02 (RFC7252: 5.8.4. DELETE)
*
* else return 4.04 */
if (coap_string_equal(uri_path, &coap_default_uri_wellknown)) {
/* request for .well-known/core */
if (pdu->code == COAP_REQUEST_CODE_GET) { /* GET */
coap_log(LOG_INFO, "create default response for %s\n",
COAP_DEFAULT_URI_WELLKNOWN);
response = coap_wellknown_response(context, session, pdu);
} else {
coap_log(LOG_DEBUG, "method not allowed for .well-known/core\n");
response = coap_new_error_response(pdu, COAP_RESPONSE_CODE(405),
&opt_filter);
}
} else if (is_proxy_uri || is_proxy_scheme) {
resource = context->proxy_uri_resource;
} else if ((context->unknown_resource != NULL) &&
((size_t)pdu->code - 1 <
(sizeof(resource->handler) / sizeof(coap_method_handler_t))) &&
(context->unknown_resource->handler[pdu->code - 1])) {
/*
* The unknown_resource can be used to handle undefined resources
* for a PUT request and can support any other registered handler
* defined for it
* Example set up code:-
* r = coap_resource_unknown_init(hnd_put_unknown);
* coap_register_handler(r, COAP_REQUEST_POST, hnd_post_unknown);
* coap_register_handler(r, COAP_REQUEST_GET, hnd_get_unknown);
* coap_register_handler(r, COAP_REQUEST_DELETE, hnd_delete_unknown);
* coap_add_resource(ctx, r);
*
* Note: It is not possible to observe the unknown_resource, a separate
* resource must be created (by PUT or POST) which has a GET
* handler to be observed
*/
resource = context->unknown_resource;
} else if (pdu->code == COAP_REQUEST_CODE_DELETE) {
/*
* Request for DELETE on non-existant resource (RFC7252: 5.8.4. DELETE)
*/
coap_log(LOG_DEBUG, "request for unknown resource '%*.*s',"
" return 2.02\n",
(int)uri_path->length,
(int)uri_path->length,
uri_path->s);
response =
coap_new_error_response(pdu, COAP_RESPONSE_CODE(202),
&opt_filter);
} else { /* request for any another resource, return 4.04 */
coap_log(LOG_DEBUG, "request for unknown resource '%*.*s', return 4.04\n",
(int)uri_path->length, (int)uri_path->length, uri_path->s);
response =
coap_new_error_response(pdu, COAP_RESPONSE_CODE(404),
&opt_filter);
}
if (!resource) {
if (response && (no_response(pdu, response, session) != RESPONSE_DROP)) {
coap_mid_t mid = pdu->mid;
if (coap_send_internal(session, response) == COAP_INVALID_MID)
coap_log(LOG_WARNING, "cannot send response for mid=0x%x\n", mid);
} else {
coap_delete_pdu(response);
}
response = NULL;
coap_delete_string(uri_path);
return;
} else {
if (response) {
/* Need to delete unused response - it will get re-created further on */
coap_delete_pdu(response);
}
}
}
/* the resource was found, check if there is a registered handler */
if ((size_t)pdu->code - 1 <
sizeof(resource->handler) / sizeof(coap_method_handler_t))
h = resource->handler[pdu->code - 1];
if (h) {
coap_log(LOG_DEBUG, "call custom handler for resource '%*.*s'\n",
(int)resource->uri_path->length, (int)resource->uri_path->length,
resource->uri_path->s);
response = coap_pdu_init(pdu->type == COAP_MESSAGE_CON
? COAP_MESSAGE_ACK
: COAP_MESSAGE_NON,
0, pdu->mid, coap_session_max_pdu_size(session));
/* Implementation detail: coap_add_token() immediately returns 0
if response == NULL */
if (coap_add_token(response, pdu->token_length, pdu->token)) {
coap_opt_t *observe = NULL;
int observe_action = COAP_OBSERVE_CANCEL;
coap_string_t *query = coap_get_query(pdu);
coap_block_t block;
int added_block = 0;
/* check for Observe option RFC7641 and RFC8132 */
if (resource->observable &&
(pdu->code == COAP_REQUEST_CODE_GET ||
pdu->code == COAP_REQUEST_CODE_FETCH)) {
observe = coap_check_option(pdu, COAP_OPTION_OBSERVE, &opt_iter);
if (observe) {
observe_action =
coap_decode_var_bytes(coap_opt_value(observe),
coap_opt_length(observe));
if (observe_action == COAP_OBSERVE_ESTABLISH) {
coap_subscription_t *subscription;
if (coap_get_block(pdu, COAP_OPTION_BLOCK2, &block)) {
if (block.num != 0) {
response->code = COAP_RESPONSE_CODE(400);
goto skip_handler;
}
}
subscription = coap_add_observer(resource, session, &token,
pdu);
if (subscription) {
uint8_t buf[4];
coap_touch_observer(context, session, &token);
coap_add_option(response, COAP_OPTION_OBSERVE,
coap_encode_var_safe(buf, sizeof (buf),
resource->observe),
buf);
}
}
else if (observe_action == COAP_OBSERVE_CANCEL) {
coap_delete_observer(resource, session, &token);
}
else {
coap_log(LOG_INFO, "observe: unexpected action %d\n", observe_action);
}
}
}
if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
if (coap_handle_request_put_block(context, session, pdu, response,
resource, uri_path, observe,
query, h, &added_block)) {
goto skip_handler;
}
if (coap_handle_request_send_block(session, pdu, response, resource,
query)) {
goto skip_handler;
}
}
/*
* Call the request handler with everything set up
*/
h(resource, session, pdu, query, response);
/* Check if lg_xmit generated and update PDU code if so */
coap_check_code_lg_xmit(session, response, resource, query);
skip_handler:
respond = no_response(pdu, response, session);
if (respond != RESPONSE_DROP) {
coap_mid_t mid = pdu->mid;
if (COAP_RESPONSE_CLASS(response->code) != 2) {
if (observe) {
coap_remove_option(response, COAP_OPTION_OBSERVE);
}
}
if (COAP_RESPONSE_CLASS(response->code) > 2) {
if (observe)
coap_delete_observer(resource, session, &token);
if (added_block)
coap_remove_option(pdu, COAP_OPTION_BLOCK1);
}
/* If original request contained a token, and the registered
* application handler made no changes to the response, then
* this is an empty ACK with a token, which is a malformed
* PDU */
if ((response->type == COAP_MESSAGE_ACK)
&& (response->code == 0)) {
/* Remove token from otherwise-empty acknowledgment PDU */
response->token_length = 0;
response->used_size = 0;
}
if (coap_send_internal(session, response) == COAP_INVALID_MID) {
coap_log(LOG_DEBUG, "cannot send response for mid=0x%x\n", mid);
}
} else {
coap_delete_pdu(response);
}
if (query)
coap_delete_string(query);
} else {
coap_log(LOG_WARNING, "cannot generate response\r\n");
coap_delete_pdu(response);
}
response = NULL;
} else {
if (coap_string_equal(uri_path, &coap_default_uri_wellknown)) {
/* request for .well-known/core */
coap_log(LOG_DEBUG, "create default response for %s\n",
COAP_DEFAULT_URI_WELLKNOWN);
response = coap_wellknown_response(context, session, pdu);
coap_log(LOG_DEBUG, "have wellknown response %p\n", (void *)response);
} else
response = coap_new_error_response(pdu, COAP_RESPONSE_CODE(405),
&opt_filter);
if (response && (no_response(pdu, response, session) != RESPONSE_DROP)) {
coap_mid_t mid = pdu->mid;
if (coap_send_internal(session, response) == COAP_INVALID_MID)
coap_log(LOG_DEBUG, "cannot send response for mid=0x%x\n", mid);
} else {
coap_delete_pdu(response);
}
response = NULL;
}
assert(response == NULL);
coap_delete_string(uri_path);
return;
fail_response:
response =
coap_new_error_response(pdu, COAP_RESPONSE_CODE(resp),
&opt_filter);
if (response) {
coap_mid_t mid = pdu->mid;
if (coap_send_internal(session, response) == COAP_INVALID_MID)
coap_log(LOG_WARNING, "cannot send response for mid=0x%x\n", mid);
}
}
static void
handle_response(coap_context_t *context, coap_session_t *session,
coap_pdu_t *sent, coap_pdu_t *rcvd) {
/* In a lossy context, the ACK of a separate response may have
* been lost, so we need to stop retransmitting requests with the
* same token.
*/
coap_cancel_all_messages(context, session, rcvd->token, rcvd->token_length);
if (session->block_mode & COAP_BLOCK_USE_LIBCOAP) {
/* See if need to send next block to server */
if (coap_handle_response_send_block(session, rcvd)) {
/* Next block transmitted, no need to inform app */
coap_send_ack(session, rcvd);
return;
}
/* Need to see if needing to request next block */
if (coap_handle_response_get_block(context, session, sent, rcvd,
COAP_RECURSE_OK)) {
/* Next block requested, no need to inform app */
coap_send_ack(session, rcvd);
return;
}
}
/* Call application-specific response handler when available. */
if (context->response_handler) {
if (context->response_handler(session, sent, rcvd,
rcvd->mid) == COAP_RESPONSE_FAIL)
coap_send_rst(session, rcvd);
else
coap_send_ack(session, rcvd);
}
else {
coap_send_ack(session, rcvd);
}
}
#if !COAP_DISABLE_TCP
static void
handle_signaling(coap_context_t *context, coap_session_t *session,
coap_pdu_t *pdu) {
coap_opt_iterator_t opt_iter;
coap_opt_t *option;
(void)context;
coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL);
if (pdu->code == COAP_SIGNALING_CODE_CSM) {
while ((option = coap_option_next(&opt_iter))) {
if (opt_iter.number == COAP_SIGNALING_OPTION_MAX_MESSAGE_SIZE) {
coap_session_set_mtu(session, coap_decode_var_bytes(coap_opt_value(option),
coap_opt_length(option)));
} else if (opt_iter.number == COAP_SIGNALING_OPTION_BLOCK_WISE_TRANSFER) {
session->csm_block_supported = 1;
}
}
if (session->state == COAP_SESSION_STATE_CSM)
coap_session_connected(session);
} else if (pdu->code == COAP_SIGNALING_CODE_PING) {
coap_pdu_t *pong = coap_pdu_init(COAP_MESSAGE_CON, COAP_SIGNALING_CODE_PONG, 0, 1);
if (context->ping_handler) {
context->ping_handler(session, pdu, pdu->mid);
}
if (pong) {
coap_add_option(pong, COAP_SIGNALING_OPTION_CUSTODY, 0, NULL);
coap_send_internal(session, pong);
}
} else if (pdu->code == COAP_SIGNALING_CODE_PONG) {
session->last_pong = session->last_rx_tx;
if (context->pong_handler) {
context->pong_handler(session, pdu, pdu->mid);
}
} else if (pdu->code == COAP_SIGNALING_CODE_RELEASE
|| pdu->code == COAP_SIGNALING_CODE_ABORT) {
coap_session_disconnected(session, COAP_NACK_RST);
}
}
#endif /* !COAP_DISABLE_TCP */
void
coap_dispatch(coap_context_t *context, coap_session_t *session,
coap_pdu_t *pdu) {
coap_queue_t *sent = NULL;
coap_pdu_t *response;
coap_opt_filter_t opt_filter;
int is_ping_rst;
if (LOG_DEBUG <= coap_get_log_level()) {
/* FIXME: get debug to work again **
unsigned char addr[INET6_ADDRSTRLEN+8], localaddr[INET6_ADDRSTRLEN+8];
if (coap_print_addr(remote, addr, INET6_ADDRSTRLEN+8) &&
coap_print_addr(&packet->dst, localaddr, INET6_ADDRSTRLEN+8) )
coap_log(LOG_DEBUG, "** received %d bytes from %s on interface %s:\n",
(int)msg_len, addr, localaddr);
*/
coap_show_pdu(LOG_DEBUG, pdu);
}
memset(&opt_filter, 0, sizeof(coap_opt_filter_t));
switch (pdu->type) {
case COAP_MESSAGE_ACK:
/* find message id in sendqueue to stop retransmission */
coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
if (sent && session->con_active) {
session->con_active--;
if (session->state == COAP_SESSION_STATE_ESTABLISHED)
/* Flush out any entries on session->delayqueue */
coap_session_connected(session);
}
if (coap_option_check_critical(context, pdu, &opt_filter) == 0)
goto cleanup;
/* if sent code was >= 64 the message might have been a
* notification. Then, we must flag the observer to be alive
* by setting obs->fail_cnt = 0. */
if (sent && COAP_RESPONSE_CLASS(sent->pdu->code) == 2) {
const coap_binary_t token =
{ sent->pdu->token_length, sent->pdu->token };
coap_touch_observer(context, sent->session, &token);
}
if (pdu->code == 0) {
/* an empty ACK needs no further handling */
goto cleanup;
}
break;
case COAP_MESSAGE_RST:
/* We have sent something the receiver disliked, so we remove
* not only the message id but also the subscriptions we might
* have. */
is_ping_rst = 0;
if (pdu->mid == session->last_ping_mid &&
context->ping_timeout && session->last_ping > 0)
is_ping_rst = 1;
if (!is_ping_rst)
coap_log(LOG_ALERT, "got RST for mid=0x%x\n", pdu->mid);
if (session->con_active) {
session->con_active--;
if (session->state == COAP_SESSION_STATE_ESTABLISHED)
/* Flush out any entries on session->delayqueue */
coap_session_connected(session);
}
/* find message id in sendqueue to stop retransmission */
coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
if (sent) {
coap_cancel(context, sent);
if (!is_ping_rst) {
if(sent->pdu->type==COAP_MESSAGE_CON && context->nack_handler)
context->nack_handler(sent->session, sent->pdu,
COAP_NACK_RST, sent->id);
}
else {
if (context->pong_handler) {
context->pong_handler(session, pdu, pdu->mid);
}
session->last_pong = session->last_rx_tx;
session->last_ping_mid = COAP_INVALID_MID;
}
}
else {
/* Need to check is there is a subscription active and delete it */
RESOURCES_ITER(context->resources, r) {
coap_subscription_t *obs, *tmp;
LL_FOREACH_SAFE(r->subscribers, obs, tmp) {
if (obs->pdu->mid == pdu->mid && obs->session == session) {
coap_binary_t token = { 0, NULL };
COAP_SET_STR(&token, obs->pdu->token_length, obs->pdu->token);
coap_delete_observer(r, session, &token);
goto cleanup;
}
}
}
}
goto cleanup;
case COAP_MESSAGE_NON:
/* find transaction in sendqueue in case large response */
coap_remove_from_queue(&context->sendqueue, session, pdu->mid, &sent);
/* check for unknown critical options */
if (coap_option_check_critical(context, pdu, &opt_filter) == 0) {
coap_send_rst(session, pdu);
goto cleanup;
}
break;
case COAP_MESSAGE_CON: /* check for unknown critical options */
if (coap_option_check_critical(context, pdu, &opt_filter) == 0) {
if (COAP_PDU_IS_REQUEST(pdu)) {
response =
coap_new_error_response(pdu, COAP_RESPONSE_CODE(402), &opt_filter);
if (!response) {
coap_log(LOG_WARNING,
"coap_dispatch: cannot create error response\n");
} else {
if (coap_send_internal(session, response) == COAP_INVALID_MID)
coap_log(LOG_WARNING, "coap_dispatch: error sending response\n");
}
}
else {
coap_send_rst(session, pdu);
}
goto cleanup;
}
default: break;
}
/* Pass message to upper layer if a specific handler was
* registered for a request that should be handled locally. */
#if !COAP_DISABLE_TCP
if (COAP_PDU_IS_SIGNALING(pdu))
handle_signaling(context, session, pdu);
else
#endif /* !COAP_DISABLE_TCP */
if (COAP_PDU_IS_REQUEST(pdu))
handle_request(context, session, pdu);
else if (COAP_PDU_IS_RESPONSE(pdu))
handle_response(context, session, sent ? sent->pdu : NULL, pdu);
else {
if (COAP_PDU_IS_EMPTY(pdu)) {
if (context->ping_handler) {
context->ping_handler(session, pdu, pdu->mid);
}
}
coap_log(LOG_DEBUG, "dropped message with invalid code (%d.%02d)\n",
COAP_RESPONSE_CLASS(pdu->code),
pdu->code & 0x1f);
if (!coap_is_mcast(&session->addr_info.local)) {
if (COAP_PDU_IS_EMPTY(pdu)) {
if (session->proto != COAP_PROTO_TCP && session->proto != COAP_PROTO_TLS) {
coap_tick_t now;
coap_ticks(&now);
if (session->last_tx_rst + COAP_TICKS_PER_SECOND/4 < now) {
coap_send_message_type(session, pdu, COAP_MESSAGE_RST);
session->last_tx_rst = now;
}
}
}
else {
coap_send_message_type(session, pdu, COAP_MESSAGE_RST);
}
}
}
cleanup:
coap_delete_node(sent);
}
int
coap_handle_event(coap_context_t *context, coap_event_t event, coap_session_t *session) {
coap_log(LOG_DEBUG, "***EVENT: 0x%04x\n", event);
if (context->handle_event) {
return context->handle_event(session, event);
} else {
return 0;
}
}
int
coap_can_exit(coap_context_t *context) {
coap_endpoint_t *ep;
coap_session_t *s, *rtmp;
if (!context)
return 1;
if (context->sendqueue)
return 0;
LL_FOREACH(context->endpoint, ep) {
SESSIONS_ITER(ep->sessions, s, rtmp) {
if (s->delayqueue)
return 0;
if (s->lg_xmit)
return 0;
}
}
SESSIONS_ITER(context->sessions, s, rtmp) {
if (s->delayqueue)
return 0;
if (s->lg_xmit)
return 0;
}
return 1;
}
#ifndef WITHOUT_ASYNC
coap_tick_t
coap_check_async(coap_context_t *context, coap_tick_t now) {
coap_tick_t next_due = 0;
coap_async_t *async, *tmp;
LL_FOREACH_SAFE(context->async_state, async, tmp) {
if (async->delay <= now) {
/* Send off the request to the application */
handle_request(context, async->session, async->pdu);
/* Remove this async entry as it has now fired */
coap_free_async(async->session, async);
}
else {
if (next_due == 0 || next_due > async->delay - now)
next_due = async->delay - now;
}
}
return next_due;
}
#endif /* WITHOUT_ASYNC */
static int coap_started = 0;
void coap_startup(void) {
coap_tick_t now;
uint64_t us;
if (coap_started)
return;
coap_started = 1;
#if defined(HAVE_WINSOCK2_H)
WORD wVersionRequested = MAKEWORD(2, 2);
WSADATA wsaData;
WSAStartup(wVersionRequested, &wsaData);
#endif
coap_clock_init();
coap_ticks(&now);
us = coap_ticks_to_rt_us(now);
/* Be accurate to the nearest (approx) us */
coap_prng_init((unsigned int)us);
coap_memory_init();
coap_dtls_startup();
}
void coap_cleanup(void) {
#if defined(HAVE_WINSOCK2_H)
WSACleanup();
#endif
coap_dtls_shutdown();
}
void
coap_register_response_handler(coap_context_t *context,
coap_response_handler_t handler) {
context->response_handler = handler;
}
void
coap_register_nack_handler(coap_context_t *context,
coap_nack_handler_t handler) {
context->nack_handler = handler;
}
void
coap_register_ping_handler(coap_context_t *context,
coap_ping_handler_t handler) {
context->ping_handler = handler;
}
void
coap_register_pong_handler(coap_context_t *context,
coap_pong_handler_t handler) {
context->pong_handler = handler;
}
void
coap_register_option(coap_context_t *ctx, uint16_t type) {
coap_option_filter_set(&ctx->known_options, type);
}
#if ! defined WITH_CONTIKI && ! defined WITH_LWIP && ! defined RIOT_VERSION
int
coap_join_mcast_group_intf(coap_context_t *ctx, const char *group_name,
const char *ifname) {
struct ip_mreq mreq4;
struct ipv6_mreq mreq6;
struct addrinfo *resmulti = NULL, hints, *ainfo;
int result = -1;
coap_endpoint_t *endpoint;
int mgroup_setup = 0;
/* Need to have at least one endpoint! */
assert(ctx->endpoint);
if (!ctx->endpoint)
return -1;
/* Default is let the kernel choose */
mreq6.ipv6mr_interface = 0;
mreq4.imr_interface.s_addr = INADDR_ANY;
memset(&hints, 0, sizeof(hints));
hints.ai_socktype = SOCK_DGRAM;
/* resolve the multicast group address */
result = getaddrinfo(group_name, NULL, &hints, &resmulti);
if (result != 0) {
coap_log(LOG_ERR,
"coap_join_mcast_group_intf: %s: "
"Cannot resolve multicast address: %s\n",
group_name, gai_strerror(result));
goto finish;
}
/* Need to do a windows equivalent at some point */
#ifndef _WIN32
if (ifname) {
/* interface specified - check if we have correct IPv4/IPv6 information */
int done_ip4 = 0;
int done_ip6 = 0;
#if defined(ESPIDF_VERSION)
struct netif *netif;
#else /* !ESPIDF_VERSION */
int ip4fd;
struct ifreq ifr;
#endif /* !ESPIDF_VERSION */
/* See which mcast address family types are being asked for */
for (ainfo = resmulti; ainfo != NULL && !(done_ip4 == 1 && done_ip6 == 1);
ainfo = ainfo->ai_next) {
switch (ainfo->ai_family) {
case AF_INET6:
if (done_ip6)
break;
done_ip6 = 1;
#if defined(ESPIDF_VERSION)
netif = netif_find(ifname);
if (netif)
mreq6.ipv6mr_interface = netif_get_index(netif);
else
coap_log(LOG_ERR,
"coap_join_mcast_group_intf: %s: "
"Cannot get IPv4 address: %s\n",
ifname, coap_socket_strerror());
#else /* !ESPIDF_VERSION */
memset (&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
ifr.ifr_name[IFNAMSIZ - 1] = '\000';
#ifdef HAVE_IF_NAMETOINDEX
mreq6.ipv6mr_interface = if_nametoindex(ifr.ifr_name);
if (mreq6.ipv6mr_interface == 0) {
coap_log(LOG_WARNING, "coap_join_mcast_group_intf: "
"cannot get interface index for '%s'\n",
ifname);
}
#else /* !HAVE_IF_NAMETOINDEX */
result = ioctl(ctx->endpoint->sock.fd, SIOCGIFINDEX, &ifr);
if (result != 0) {
coap_log(LOG_WARNING, "coap_join_mcast_group_intf: "
"cannot get interface index for '%s': %s\n",
ifname, coap_socket_strerror());
}
else {
/* Capture the IPv6 if_index for later */
mreq6.ipv6mr_interface = ifr.ifr_ifindex;
}
#endif /* !HAVE_IF_NAMETOINDEX */
#endif /* !ESPIDF_VERSION */
break;
case AF_INET:
if (done_ip4)
break;
done_ip4 = 1;
#if defined(ESPIDF_VERSION)
netif = netif_find(ifname);
if (netif)
mreq4.imr_interface.s_addr = netif_ip4_addr(netif)->addr;
else
coap_log(LOG_ERR,
"coap_join_mcast_group_intf: %s: "
"Cannot get IPv4 address: %s\n",
ifname, coap_socket_strerror());
#else /* !ESPIDF_VERSION */
/*
* Need an AF_INET socket to do this unfortunately to stop
* "Invalid argument" error if AF_INET6 socket is used for SIOCGIFADDR
*/
ip4fd = socket(AF_INET, SOCK_DGRAM, 0);
if (ip4fd == -1) {
coap_log(LOG_ERR,
"coap_join_mcast_group_intf: %s: socket: %s\n",
ifname, coap_socket_strerror());
continue;
}
memset (&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
ifr.ifr_name[IFNAMSIZ - 1] = '\000';
result = ioctl(ip4fd, SIOCGIFADDR, &ifr);
if (result != 0) {
coap_log(LOG_ERR,
"coap_join_mcast_group_intf: %s: "
"Cannot get IPv4 address: %s\n",
ifname, coap_socket_strerror());
}
else {
/* Capture the IPv4 address for later */
mreq4.imr_interface = ((struct sockaddr_in*)&ifr.ifr_addr)->sin_addr;
}
close(ip4fd);
#endif /* !ESPIDF_VERSION */
break;
default:
break;
}
}
}
#endif /* ! _WIN32 */
/* Add in mcast address(es) to appropriate interface */
for (ainfo = resmulti; ainfo != NULL; ainfo = ainfo->ai_next) {
LL_FOREACH(ctx->endpoint, endpoint) {
/* Only UDP currently supported */
if (endpoint->proto == COAP_PROTO_UDP) {
coap_address_t gaddr;
coap_address_init(&gaddr);
if (ainfo->ai_family == AF_INET6) {
if (!ifname) {
if(endpoint->bind_addr.addr.sa.sa_family == AF_INET6) {
/*
* Do it on the ifindex that the server is listening on
* (sin6_scope_id could still be 0)
*/
mreq6.ipv6mr_interface =
endpoint->bind_addr.addr.sin6.sin6_scope_id;
}
else {
mreq6.ipv6mr_interface = 0;
}
}
gaddr.addr.sin6.sin6_family = AF_INET6;
gaddr.addr.sin6.sin6_port = endpoint->bind_addr.addr.sin6.sin6_port;
gaddr.addr.sin6.sin6_addr = mreq6.ipv6mr_multiaddr =
((struct sockaddr_in6 *)ainfo->ai_addr)->sin6_addr;
result = setsockopt(endpoint->sock.fd, IPPROTO_IPV6, IPV6_JOIN_GROUP,
(char *)&mreq6, sizeof(mreq6));
}
else if (ainfo->ai_family == AF_INET) {
if (!ifname) {
if(endpoint->bind_addr.addr.sa.sa_family == AF_INET) {
/*
* Do it on the interface that the server is listening on
* (sin_addr could still be INADDR_ANY)
*/
mreq4.imr_interface = endpoint->bind_addr.addr.sin.sin_addr;
}
else {
mreq4.imr_interface.s_addr = INADDR_ANY;
}
}
gaddr.addr.sin.sin_family = AF_INET;
gaddr.addr.sin.sin_port = endpoint->bind_addr.addr.sin.sin_port;
gaddr.addr.sin.sin_addr.s_addr = mreq4.imr_multiaddr.s_addr =
((struct sockaddr_in *)ainfo->ai_addr)->sin_addr.s_addr;
result = setsockopt(endpoint->sock.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
(char *)&mreq4, sizeof(mreq4));
}
else {
continue;
}
if (result == COAP_SOCKET_ERROR) {
coap_log(LOG_ERR,
"coap_join_mcast_group_intf: %s: setsockopt: %s\n",
group_name, coap_socket_strerror());
}
else {
char addr_str[INET6_ADDRSTRLEN + 8 + 1];
addr_str[sizeof(addr_str)-1] = '\000';
if (coap_print_addr(&gaddr, (uint8_t*)addr_str,
sizeof(addr_str) - 1)) {
if (ifname)
coap_log(LOG_DEBUG, "added mcast group %s i/f %s\n", addr_str,
ifname);
else
coap_log(LOG_DEBUG, "added mcast group %s\n", addr_str);
}
mgroup_setup = 1;
}
}
}
}
if (!mgroup_setup) {
result = -1;
}
finish:
freeaddrinfo(resmulti);
return result;
}
int
coap_mcast_set_hops(coap_session_t *session, size_t hops) {
if (session && coap_is_mcast(&session->addr_info.remote)) {
switch (session->addr_info.remote.addr.sa.sa_family) {
case AF_INET:
if (setsockopt(session->sock.fd, IPPROTO_IP, IP_MULTICAST_TTL,
(const char *)&hops, sizeof(hops)) < 0) {
coap_log(LOG_INFO, "coap_mcast_set_hops: %zu: setsockopt: %s\n",
hops, coap_socket_strerror());
return 0;
}
return 1;
case AF_INET6:
if (setsockopt(session->sock.fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
(const char *)&hops, sizeof(hops)) < 0) {
coap_log(LOG_INFO, "coap_mcast_set_hops: %zu: setsockopt: %s\n",
hops, coap_socket_strerror());
return 0;
}
return 1;
default:
break;
}
}
return 0;
}
#else /* defined WITH_CONTIKI || defined WITH_LWIP */
int
coap_join_mcast_group_intf(coap_context_t *ctx COAP_UNUSED,
const char *group_name COAP_UNUSED,
const char *ifname COAP_UNUSED) {
return -1;
}
int
coap_mcast_set_hops(coap_session_t *session COAP_UNUSED,
size_t hops COAP_UNUSED) {
return 0;
}
#endif /* defined WITH_CONTIKI || defined WITH_LWIP */
#ifdef WITH_CONTIKI
/*---------------------------------------------------------------------------*/
/* CoAP message retransmission */
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(coap_retransmit_process, ev, data) {
coap_tick_t now;
coap_queue_t *nextpdu;
PROCESS_BEGIN();
coap_log(LOG_DEBUG, "Started retransmit process\n");
while (1) {
PROCESS_YIELD();
if (ev == PROCESS_EVENT_TIMER) {
if (etimer_expired(&the_coap_context.retransmit_timer)) {
nextpdu = coap_peek_next(&the_coap_context);
coap_ticks(&now);
while (nextpdu && nextpdu->t <= now) {
coap_retransmit(&the_coap_context, coap_pop_next(&the_coap_context));
nextpdu = coap_peek_next(&the_coap_context);
}
/* need to set timer to some value even if no nextpdu is available */
etimer_set(&the_coap_context.retransmit_timer,
nextpdu ? nextpdu->t - now : 0xFFFF);
}
if (etimer_expired(&the_coap_context.notify_timer)) {
coap_check_notify(&the_coap_context);
etimer_reset(&the_coap_context.notify_timer);
}
}
}
PROCESS_END();
}
/*---------------------------------------------------------------------------*/
#endif /* WITH_CONTIKI */
#ifdef WITH_LWIP
/* FIXME: retransmits that are not required any more due to incoming packages
* do *not* get cleared at the moment, the wakeup when the transmission is due
* is silently accepted. this is mainly due to the fact that the required
* checks are similar in two places in the code (when receiving ACK and RST)
* and that they cause more than one patch chunk, as it must be first checked
* whether the sendqueue item to be dropped is the next one pending, and later
* the restart function has to be called. nothing insurmountable, but it can
* also be implemented when things have stabilized, and the performance
* penality is minimal
*
* also, this completely ignores COAP_RESOURCE_CHECK_TIME.
* */
static void coap_retransmittimer_execute(void *arg) {
coap_context_t *ctx = (coap_context_t*)arg;
coap_tick_t now;
coap_tick_t elapsed;
coap_queue_t *nextinqueue;
ctx->timer_configured = 0;
coap_ticks(&now);
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 */
nextinqueue = coap_peek_next(ctx);
while (nextinqueue != NULL) {
if (nextinqueue->t > elapsed) {
nextinqueue->t -= elapsed;
break;
} else {
elapsed -= nextinqueue->t;
coap_retransmit(ctx, coap_pop_next(ctx));
nextinqueue = coap_peek_next(ctx);
}
}
ctx->sendqueue_basetime = now;
coap_retransmittimer_restart(ctx);
}
static void coap_retransmittimer_restart(coap_context_t *ctx) {
coap_tick_t now, elapsed, delay;
if (ctx->timer_configured) {
printf("clearing\n");
sys_untimeout(coap_retransmittimer_execute, (void*)ctx);
ctx->timer_configured = 0;
}
if (ctx->sendqueue != NULL) {
coap_ticks(&now);
elapsed = now - ctx->sendqueue_basetime;
if (ctx->sendqueue->t >= elapsed) {
delay = ctx->sendqueue->t - elapsed;
} else {
/* a strange situation, but not completely impossible.
*
* this happens, for example, right after
* coap_retransmittimer_execute, when a retransmission
* was *just not yet* due, and the clock ticked before
* our coap_ticks was called.
*
* not trying to retransmit anything now, as it might
* cause uncontrollable recursion; let's just try again
* with the next main loop run.
* */
delay = 0;
}
printf("scheduling for %d ticks\n", delay);
sys_timeout(delay, coap_retransmittimer_execute, (void*)ctx);
ctx->timer_configured = 1;
}
}
#endif
coap_address_init
void coap_address_init(coap_address_t *addr)
Resets the given coap_address_t object addr to its default values.
Definition: address.c:102
coap_is_mcast
int coap_is_mcast(const coap_address_t *a)
Checks if given address a denotes a multicast address.
Definition: address.c:83
coap_address_copy
COAP_STATIC_INLINE void coap_address_copy(coap_address_t *dst, const coap_address_t *src)
Definition: address.h:152
coap_internal.h
Pulls together all the internal only header files.
coap_socket_read
ssize_t coap_socket_read(coap_socket_t *sock, uint8_t *data, size_t data_len)
Definition: coap_io.c:478
coap_packet_get_memmapped
void coap_packet_get_memmapped(coap_packet_t *packet, unsigned char **address, size_t *length)
Given a packet, set msg and msg_len to an address and length of the packet's data in memory.
Definition: coap_io.c:745
coap_network_read
ssize_t coap_network_read(coap_socket_t *sock, coap_packet_t *packet)
Function interface for reading data.
Definition: coap_io.c:752
coap_network_send
ssize_t coap_network_send(coap_socket_t *sock, const coap_session_t *session, const uint8_t *data, size_t datalen)
Function interface for data transmission.
Definition: coap_io.c:571
coap_socket_strerror
const char * coap_socket_strerror(void)
Definition: coap_io.c:1502
COAP_SOCKET_ERROR
#define COAP_SOCKET_ERROR
Definition: coap_io.h:44
coap_nack_reason_t
coap_nack_reason_t
Definition: coap_io.h:64
COAP_NACK_NOT_DELIVERABLE
@ COAP_NACK_NOT_DELIVERABLE
Definition: coap_io.h:66
COAP_NACK_TOO_MANY_RETRIES
@ COAP_NACK_TOO_MANY_RETRIES
Definition: coap_io.h:65
COAP_NACK_TLS_FAILED
@ COAP_NACK_TLS_FAILED
Definition: coap_io.h:68
COAP_NACK_ICMP_ISSUE
@ COAP_NACK_ICMP_ISSUE
Definition: coap_io.h:69
COAP_NACK_RST
@ COAP_NACK_RST
Definition: coap_io.h:67
COAP_SOCKET_MULTICAST
#define COAP_SOCKET_MULTICAST
socket is used for multicast communication
Definition: coap_io_internal.h:55
COAP_SOCKET_WANT_ACCEPT
#define COAP_SOCKET_WANT_ACCEPT
non blocking server socket is waiting for accept
Definition: coap_io_internal.h:49
COAP_SOCKET_NOT_EMPTY
#define COAP_SOCKET_NOT_EMPTY
the socket is not empty
Definition: coap_io_internal.h:44
COAP_SOCKET_CAN_WRITE
#define COAP_SOCKET_CAN_WRITE
non blocking socket can now write without blocking
Definition: coap_io_internal.h:52
COAP_SOCKET_BOUND
#define COAP_SOCKET_BOUND
the socket is bound
Definition: coap_io_internal.h:45
COAP_SOCKET_WANT_READ
#define COAP_SOCKET_WANT_READ
non blocking socket is waiting for reading
Definition: coap_io_internal.h:47
COAP_SOCKET_CAN_ACCEPT
#define COAP_SOCKET_CAN_ACCEPT
non blocking server socket can now accept without blocking
Definition: coap_io_internal.h:53
COAP_SOCKET_WANT_WRITE
#define COAP_SOCKET_WANT_WRITE
non blocking socket is waiting for writing
Definition: coap_io_internal.h:48
COAP_SOCKET_CAN_CONNECT
#define COAP_SOCKET_CAN_CONNECT
non blocking client socket can now connect without blocking
Definition: coap_io_internal.h:54
coap_epoll_ctl_mod
void coap_epoll_ctl_mod(coap_socket_t *sock, uint32_t events, const char *func)
COAP_SOCKET_WANT_CONNECT
#define COAP_SOCKET_WANT_CONNECT
non blocking client socket is waiting for connect
Definition: coap_io_internal.h:50
COAP_SOCKET_CAN_READ
#define COAP_SOCKET_CAN_READ
non blocking socket can now read without blocking
Definition: coap_io_internal.h:51
COAP_SOCKET_CONNECTED
#define COAP_SOCKET_CONNECTED
the socket is connected
Definition: coap_io_internal.h:46
COAP_SOCKET_EMPTY
#define COAP_SOCKET_EMPTY
coap_socket_flags_t values
Definition: coap_io_internal.h:43
coap_dtls_context_set_spsk
int coap_dtls_context_set_spsk(coap_context_t *ctx COAP_UNUSED, coap_dtls_spsk_t *setup_data COAP_UNUSED)
Definition: coap_notls.c:58
coap_dtls_context_set_pki
int coap_dtls_context_set_pki(coap_context_t *ctx COAP_UNUSED, const coap_dtls_pki_t *setup_data COAP_UNUSED, const coap_dtls_role_t role COAP_UNUSED)
Definition: coap_notls.c:35
coap_dtls_new_context
void * coap_dtls_new_context(coap_context_t *coap_context COAP_UNUSED)
Definition: coap_notls.c:97
coap_dtls_send
int coap_dtls_send(coap_session_t *session COAP_UNUSED, const uint8_t *data COAP_UNUSED, size_t data_len COAP_UNUSED)
Definition: coap_notls.c:120
coap_dtls_new_client_session
void * coap_dtls_new_client_session(coap_session_t *session COAP_UNUSED)
Definition: coap_notls.c:109
coap_tls_read
ssize_t coap_tls_read(coap_session_t *session COAP_UNUSED, uint8_t *data COAP_UNUSED, size_t data_len COAP_UNUSED)
Definition: coap_notls.c:181
coap_dtls_receive
int coap_dtls_receive(coap_session_t *session COAP_UNUSED, const uint8_t *data COAP_UNUSED, size_t data_len COAP_UNUSED)
Definition: coap_notls.c:144
coap_tls_new_client_session
void * coap_tls_new_client_session(coap_session_t *session COAP_UNUSED, int *connected COAP_UNUSED)
Definition: coap_notls.c:163
coap_dtls_hello
int coap_dtls_hello(coap_session_t *session COAP_UNUSED, const uint8_t *data COAP_UNUSED, size_t data_len COAP_UNUSED)
Definition: coap_notls.c:152
coap_tls_write
ssize_t coap_tls_write(coap_session_t *session COAP_UNUSED, const uint8_t *data COAP_UNUSED, size_t data_len COAP_UNUSED)
Definition: coap_notls.c:174
coap_dtls_context_set_pki_root_cas
int coap_dtls_context_set_pki_root_cas(coap_context_t *ctx COAP_UNUSED, const char *ca_file COAP_UNUSED, const char *ca_path COAP_UNUSED)
Definition: coap_notls.c:43
coap_dtls_free_context
void coap_dtls_free_context(void *handle COAP_UNUSED)
Definition: coap_notls.c:102
SESSIONS_ITER_SAFE
#define SESSIONS_ITER_SAFE(e, el, rtmp)
Definition: coap_session_internal.h:288
SESSIONS_ITER
#define SESSIONS_ITER(e, el, rtmp)
Definition: coap_session_internal.h:285
coap_io_do_io
void coap_io_do_io(coap_context_t *ctx, coap_tick_t now)
Processes any outstanding read, write, accept or connect I/O as indicated in the coap_socket_t struct...
Definition: net.c:1738
coap_io_prepare_epoll
unsigned int coap_io_prepare_epoll(coap_context_t *ctx, coap_tick_t now)
Any now timed out delayed packet is transmitted, along with any packets associated with requested obs...
Definition: coap_io.c:1007
coap_io_do_epoll
void coap_io_do_epoll(coap_context_t *ctx, struct epoll_event *events, size_t nevents)
Process all the epoll events.
Definition: net.c:1799
coap_block_delete_lg_crcv
void coap_block_delete_lg_crcv(coap_session_t *session, coap_lg_crcv_t *lg_crcv)
Definition: block.c:862
coap_handle_response_get_block
int coap_handle_response_get_block(coap_context_t *context, coap_session_t *session, coap_pdu_t *sent, coap_pdu_t *rcvd, coap_recurse_t recursive)
Definition: block.c:1611
coap_check_code_lg_xmit
void coap_check_code_lg_xmit(coap_session_t *session, coap_pdu_t *response, coap_resource_t *resource, coap_string_t *query)
The function checks that the code in a newly formed lg_xmit created by coap_add_data_large_response()...
Definition: block.c:1948
coap_handle_request_send_block
int coap_handle_request_send_block(coap_session_t *session, coap_pdu_t *pdu, coap_pdu_t *response, coap_resource_t *resource, coap_string_t *query)
Definition: block.c:951
coap_handle_request_put_block
int coap_handle_request_put_block(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu, coap_pdu_t *response, coap_resource_t *resource, coap_string_t *uri_path, coap_opt_t *observe, coap_string_t *query, coap_method_handler_t h, int *added_block)
Definition: block.c:1222
coap_block_new_lg_crcv
coap_lg_crcv_t * coap_block_new_lg_crcv(coap_session_t *session, coap_pdu_t *pdu)
Definition: block.c:810
coap_handle_response_send_block
int coap_handle_response_send_block(coap_session_t *session, coap_pdu_t *rcvd)
Definition: block.c:1447
COAP_RECURSE_OK
@ COAP_RECURSE_OK
Definition: coap_block_internal.h:32
COAP_MAX_BLOCK_SZX
#define COAP_MAX_BLOCK_SZX
The largest value for the SZX component in a Block option.
Definition: block.h:29
coap_get_block
int coap_get_block(const coap_pdu_t *pdu, coap_option_num_t number, coap_block_t *block)
Initializes block from pdu.
Definition: block.c:37
coap_write_block_opt
int coap_write_block_opt(coap_block_t *block, coap_option_num_t number, coap_pdu_t *pdu, size_t data_length)
Writes a block option of type number to message pdu.
Definition: block.c:66
COAP_BLOCK_USE_LIBCOAP
#define COAP_BLOCK_USE_LIBCOAP
Definition: block.h:41
coap_delete_cache_entry
void coap_delete_cache_entry(coap_context_t *ctx, coap_cache_entry_t *cache_entry)
Remove a cache-entry from the hash list and free off all the appropriate contents apart from app_data...
Definition: coap_cache.c:220
COAP_DEFAULT_NSTART
#define COAP_DEFAULT_NSTART
The number of simultaneous outstanding interactions that a client maintains to a given server.
Definition: coap_session.h:427
COAP_DEFAULT_LEISURE
#define COAP_DEFAULT_LEISURE
The maximum number of seconds before sending back a response to a multicast request.
Definition: coap_session.h:435
coap_tick_diff_t
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:134
coap_ticks
void coap_ticks(coap_tick_t *t)
Sets t to the internal time with COAP_TICKS_PER_SECOND resolution.
coap_clock_init
void coap_clock_init(void)
Initializes the internal clock.
coap_tick_t
uint64_t coap_tick_t
This data type represents internal timer ticks with COAP_TICKS_PER_SECOND resolution.
Definition: coap_time.h:122
COAP_TICKS_PER_SECOND
#define COAP_TICKS_PER_SECOND
Use ms resolution on POSIX systems.
Definition: coap_time.h:137
coap_ticks_to_rt_us
uint64_t coap_ticks_to_rt_us(coap_tick_t t)
Helper function that converts coap ticks to POSIX wallclock time in us.
coap_check_async
coap_tick_t coap_check_async(coap_context_t *context, coap_tick_t now)
Checks if there are any pending Async requests - if so, send them off.
Definition: net.c:3199
coap_delete_all_async
void coap_delete_all_async(coap_context_t *context)
Removes and frees off all of the async entries for the given context.
Definition: async.c:139
coap_free_async
void coap_free_async(coap_session_t *session, coap_async_t *s)
Releases the memory that was allocated by coap_register_async() for the object async.
Definition: async.c:134
coap_register_async
coap_async_t * coap_register_async(coap_session_t *session, const coap_pdu_t *request, coap_tick_t delay)
Allocates a new coap_async_t object and fills its fields according to the given request.
Definition: async.c:38
coap_find_async
coap_async_t * coap_find_async(coap_session_t *session, coap_bin_const_t token)
Retrieves the object identified by token from the list of asynchronous transactions that are register...
Definition: async.c:109
coap_prng
int coap_prng(void *buf, size_t len)
Fills buf with len random bytes using the default pseudo random number generator.
Definition: coap_prng.c:87
coap_prng_init
void coap_prng_init(unsigned int seed)
Seeds the default random number generation function with the given seed.
Definition: coap_prng.c:76
coap_print_wellknown
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:171
coap_delete_all_resources
void coap_delete_all_resources(coap_context_t *context)
Deletes all resources from given context and frees their storage.
Definition: resource.c:590
RESOURCES_ITER
#define RESOURCES_ITER(r, tmp)
Definition: coap_resource_internal.h:116
coap_get_resource_from_uri_path
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:615
coap_method_handler_t
void(* coap_method_handler_t)(coap_resource_t *, coap_session_t *, const coap_pdu_t *, const coap_string_t *, coap_pdu_t *)
Definition of message handler function.
Definition: resource.h:42
COAP_PRINT_STATUS_ERROR
#define COAP_PRINT_STATUS_ERROR
Definition: resource.h:328
coap_peek_next
coap_queue_t * coap_peek_next(coap_context_t *context)
Returns the next pdu to send without removing from sendqeue.
Definition: net.c:274
coap_adjust_basetime
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:157
coap_delete_all
void coap_delete_all(coap_queue_t *queue)
Removes all items from given queue and frees the allocated storage.
Definition: net.c:251
coap_remove_from_queue
int coap_remove_from_queue(coap_queue_t **queue, coap_session_t *session, coap_mid_t id, coap_queue_t **node)
This function removes the element with given id from the list given list.
Definition: net.c:1935
coap_delete_node
int coap_delete_node(coap_queue_t *node)
Destroys specified node.
Definition: net.c:231
coap_new_node
coap_queue_t * coap_new_node(void)
Creates a new node suitable for adding to the CoAP sendqueue.
Definition: net.c:260
coap_pop_next
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:282
coap_wellknown_response
coap_pdu_t * coap_wellknown_response(coap_context_t *context, coap_session_t *session, coap_pdu_t *request)
Creates a new response for given request with the contents of .well-known/core.
Definition: net.c:2188
coap_dispatch
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:2980
coap_send_internal
coap_mid_t coap_send_internal(coap_session_t *session, coap_pdu_t *pdu)
Sends a CoAP message to given peer.
Definition: net.c:1154
coap_insert_node
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:194
coap_calc_timeout
unsigned int coap_calc_timeout(coap_session_t *session, unsigned char r)
Calculates the initial timeout based on the session CoAP transmission parameters 'ack_timeout',...
Definition: net.c:947
coap_option_check_critical
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:700
coap_retransmit
coap_mid_t coap_retransmit(coap_context_t *context, coap_queue_t *node)
Handles retransmissions of confirmable messages.
Definition: net.c:1337
coap_cancel_all_messages
void coap_cancel_all_messages(coap_context_t *context, coap_session_t *session, const uint8_t *token, size_t token_length)
Cancels all outstanding messages for session session that have the specified token.
Definition: net.c:2016
coap_wait_ack
coap_mid_t coap_wait_ack(coap_context_t *context, coap_session_t *session, coap_queue_t *node)
Definition: net.c:973
coap_cancel_session_messages
void coap_cancel_session_messages(coap_context_t *context, coap_session_t *session, coap_nack_reason_t reason)
Cancels all outstanding messages for session session.
Definition: net.c:1979
coap_handle_dgram
int coap_handle_dgram(coap_context_t *ctx, coap_session_t *session, uint8_t *msg, size_t msg_len)
Parses and interprets a CoAP datagram with context ctx.
Definition: net.c:1898
coap_send_ack
coap_mid_t coap_send_ack(coap_session_t *session, const coap_pdu_t *request)
Sends an ACK message with code 0 for the specified request to dst.
Definition: net.c:752
coap_context_set_session_timeout
void coap_context_set_session_timeout(coap_context_t *context, unsigned int session_timeout)
Set the session timeout value.
Definition: net.c:485
coap_context_set_psk2
int coap_context_set_psk2(coap_context_t *ctx, coap_dtls_spsk_t *setup_data)
Set the context's default PSK hint and/or key for a server.
Definition: net.c:408
coap_context_get_max_handshake_sessions
unsigned int coap_context_get_max_handshake_sessions(const coap_context_t *context)
Get the session timeout value.
Definition: net.c:469
coap_pong_handler_t
void(* coap_pong_handler_t)(coap_session_t *session, const coap_pdu_t *received, const coap_mid_t mid)
Received Pong handler that is used as callback in coap_context_t.
Definition: net.h:90
coap_context_get_max_idle_sessions
unsigned int coap_context_get_max_idle_sessions(const coap_context_t *context)
Get the maximum idle sessions count.
Definition: net.c:458
coap_can_exit
int coap_can_exit(coap_context_t *context)
Returns 1 if there are no messages to send or to dispatch in the context's queues.
Definition: net.c:3174
coap_response_handler_t
coap_response_t(* coap_response_handler_t)(coap_session_t *session, const coap_pdu_t *sent, const coap_pdu_t *received, const coap_mid_t mid)
Response handler that is used as callback in coap_context_t.
Definition: net.h:54
coap_register_response_handler
void coap_register_response_handler(coap_context_t *context, coap_response_handler_t handler)
Registers a new message handler that is called whenever a response is received.
Definition: net.c:3250
coap_get_app_data
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:625
coap_free_context
void coap_free_context(coap_context_t *context)
CoAP stack context must be released with coap_free_context().
Definition: net.c:631
coap_context_set_max_handshake_sessions
void coap_context_set_max_handshake_sessions(coap_context_t *context, unsigned int max_handshake_sessions)
Set the maximum number of sessions in (D)TLS handshake value.
Definition: net.c:463
coap_context_get_coap_fd
int coap_context_get_coap_fd(const coap_context_t *context)
Get the libcoap internal file descriptor for using in an application's select() or returned as an eve...
Definition: net.c:495
coap_handle_event
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:3163
coap_context_set_psk
int coap_context_set_psk(coap_context_t *ctx, const char *hint, const uint8_t *key, size_t key_len)
Set the context's default PSK hint and/or key for a server.
Definition: net.c:388
coap_mcast_set_hops
int coap_mcast_set_hops(coap_session_t *session, size_t hops)
Function interface for defining the hop count (ttl) for sending multicast traffic.
Definition: net.c:3503
coap_ping_handler_t
void(* coap_ping_handler_t)(coap_session_t *session, const coap_pdu_t *received, const coap_mid_t mid)
Received Ping handler that is used as callback in coap_context_t.
Definition: net.h:79
coap_context_set_pki_root_cas
int coap_context_set_pki_root_cas(coap_context_t *ctx, const char *ca_file, const char *ca_dir)
Set the context's default Root CA information for a client or server.
Definition: net.c:437
coap_nack_handler_t
void(* coap_nack_handler_t)(coap_session_t *session, const coap_pdu_t *sent, const coap_nack_reason_t reason, const coap_mid_t mid)
Negative Acknowedge handler that is used as callback in coap_context_t.
Definition: net.h:67
coap_send_rst
COAP_STATIC_INLINE coap_mid_t coap_send_rst(coap_session_t *session, const coap_pdu_t *request)
Sends an RST message with code 0 for the specified request to dst.
Definition: net.h:452
coap_new_context
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:505
coap_send_message_type
coap_mid_t coap_send_message_type(coap_session_t *session, const coap_pdu_t *request, coap_pdu_type_t type)
Helper function to create and send a message with type (usually ACK or RST).
Definition: net.c:920
coap_context_get_session_timeout
unsigned int coap_context_get_session_timeout(const coap_context_t *context)
Get the session timeout value.
Definition: net.c:491
coap_send_error
coap_mid_t coap_send_error(coap_session_t *session, const coap_pdu_t *request, coap_pdu_code_t code, coap_opt_filter_t *opts)
Sends an error response with code code for request request to dst.
Definition: net.c:902
coap_context_set_pki
int coap_context_set_pki(coap_context_t *ctx, const coap_dtls_pki_t *setup_data)
Set the context's default PKI information for a server.
Definition: net.c:422
coap_register_ping_handler
void coap_register_ping_handler(coap_context_t *context, coap_ping_handler_t handler)
Registers a new message handler that is called whenever a CoAP Ping message is received.
Definition: net.c:3262
coap_register_option
void coap_register_option(coap_context_t *ctx, uint16_t type)
Registers the option type type with the given context object ctx.
Definition: net.c:3274
coap_join_mcast_group_intf
int coap_join_mcast_group_intf(coap_context_t *ctx, const char *group_name, const char *ifname)
Function interface for joining a multicast group for listening for the currently defined endpoints th...
Definition: net.c:3280
coap_context_set_max_idle_sessions
void coap_context_set_max_idle_sessions(coap_context_t *context, unsigned int max_idle_sessions)
Set the maximum idle sessions count.
Definition: net.c:452
coap_new_error_response
coap_pdu_t * coap_new_error_response(const coap_pdu_t *request, coap_pdu_code_t code, coap_opt_filter_t *opts)
Creates a new ACK PDU with specified error code.
Definition: net.c:2057
coap_context_set_keepalive
void coap_context_set_keepalive(coap_context_t *context, unsigned int seconds)
Set the context keepalive timer for sessions.
Definition: net.c:447
coap_set_app_data
void coap_set_app_data(coap_context_t *ctx, void *app_data)
Stores data with the given CoAP context.
Definition: net.c:619
coap_context_get_csm_timeout
unsigned int coap_context_get_csm_timeout(const coap_context_t *context)
Get the CSM timeout value.
Definition: net.c:480
coap_register_pong_handler
void coap_register_pong_handler(coap_context_t *context, coap_pong_handler_t handler)
Registers a new message handler that is called whenever a CoAP Pong message is received.
Definition: net.c:3268
coap_send
coap_mid_t coap_send(coap_session_t *session, coap_pdu_t *pdu)
Sends a CoAP message to given peer.
Definition: net.c:1057
coap_register_nack_handler
void coap_register_nack_handler(coap_context_t *context, coap_nack_handler_t handler)
Registers a new message handler that is called whenever a confirmable message (request or response) i...
Definition: net.c:3256
coap_context_set_csm_timeout
void coap_context_set_csm_timeout(coap_context_t *context, unsigned int csm_timeout)
Set the CSM timeout value.
Definition: net.c:474
COAP_RESPONSE_FAIL
@ COAP_RESPONSE_FAIL
Response not liked - send CoAP RST packet.
Definition: net.h:39
coap_dtls_startup
void coap_dtls_startup(void)
Initialize the underlying (D)TLS Library layer.
Definition: coap_notls.c:72
coap_session_new_dtls_session
coap_session_t * coap_session_new_dtls_session(coap_session_t *session, coap_tick_t now)
Create a new DTLS session for the session.
Definition: coap_session.c:691
coap_dtls_shutdown
void coap_dtls_shutdown(void)
Close down the underlying (D)TLS Library layer.
Definition: coap_notls.c:83
COAP_DTLS_PKI_SETUP_VERSION
#define COAP_DTLS_PKI_SETUP_VERSION
Latest PKI setup version.
Definition: coap_dtls.h:239
coap_dtls_is_supported
int coap_dtls_is_supported(void)
Check whether DTLS is available.
Definition: coap_notls.c:17
COAP_DTLS_ROLE_SERVER
@ COAP_DTLS_ROLE_SERVER
Internal function invoked for server.
Definition: coap_dtls.h:33
coap_encode_var_safe
unsigned int coap_encode_var_safe(uint8_t *buf, size_t length, unsigned int val)
Encodes multiple-length byte sequences.
Definition: encode.c:40
coap_decode_var_bytes
unsigned int coap_decode_var_bytes(const uint8_t *buf, size_t len)
Decodes multiple-length byte sequences.
Definition: encode.c:31
coap_encode_var_safe8
unsigned int coap_encode_var_safe8(uint8_t *buf, size_t length, uint64_t val)
Encodes multiple-length byte sequences.
Definition: encode.c:70
COAP_EVENT_DTLS_ERROR
#define COAP_EVENT_DTLS_ERROR
Definition: coap_event.h:35
coap_event_t
unsigned int coap_event_t
Scalar type to represent different events, e.g.
Definition: coap_event.h:27
COAP_EVENT_TCP_FAILED
#define COAP_EVENT_TCP_FAILED
Definition: coap_event.h:42
COAP_EVENT_DTLS_CONNECTED
#define COAP_EVENT_DTLS_CONNECTED
Definition: coap_event.h:33
COAP_EVENT_TCP_CONNECTED
#define COAP_EVENT_TCP_CONNECTED
TCP events for COAP_PROTO_TCP and COAP_PROTO_TLS.
Definition: coap_event.h:40
coap_get_log_level
coap_log_t coap_get_log_level(void)
Get the current logging level.
Definition: coap_debug.c:63
coap_show_pdu
void coap_show_pdu(coap_log_t level, const coap_pdu_t *pdu)
Display the contents of the specified pdu.
Definition: coap_debug.c:507
coap_session_str
const char * coap_session_str(const coap_session_t *session)
Get session description.
Definition: coap_session.c:1380
coap_print_addr
size_t coap_print_addr(const coap_address_t *addr, unsigned char *buf, size_t len)
Print the address into the defined buffer.
Definition: coap_debug.c:173
coap_endpoint_str
const char * coap_endpoint_str(const coap_endpoint_t *endpoint)
Get endpoint description.
Definition: coap_session.c:1419
coap_log
#define coap_log(level,...)
Logging function.
Definition: coap_debug.h:152
LOG_ERR
@ LOG_ERR
Error.
Definition: coap_debug.h:55
LOG_INFO
@ LOG_INFO
Information.
Definition: coap_debug.h:58
LOG_ALERT
@ LOG_ALERT
Alert.
Definition: coap_debug.h:53
LOG_WARNING
@ LOG_WARNING
Warning.
Definition: coap_debug.h:56
LOG_DEBUG
@ LOG_DEBUG
Debug.
Definition: coap_debug.h:59
LOG_EMERG
@ LOG_EMERG
Emergency.
Definition: coap_debug.h:52
COAP_OBSERVE_CANCEL
#define COAP_OBSERVE_CANCEL
The value COAP_OBSERVE_CANCEL in a GET/FETCH request option COAP_OPTION_OBSERVE indicates that the ob...
Definition: subscribe.h:39
COAP_OBSERVE_ESTABLISH
#define COAP_OBSERVE_ESTABLISH
The value COAP_OBSERVE_ESTABLISH in a GET/FETCH request option COAP_OPTION_OBSERVE indicates a new ob...
Definition: subscribe.h:32
coap_option_next
coap_opt_t * coap_option_next(coap_opt_iterator_t *oi)
Updates the iterator oi to point to the next option.
Definition: option.c:148
coap_opt_length
uint32_t coap_opt_length(const coap_opt_t *opt)
Returns the length of the given option.
Definition: option.c:211
coap_check_option
coap_opt_t * coap_check_option(const coap_pdu_t *pdu, coap_option_num_t number, coap_opt_iterator_t *oi)
Retrieves the first option of number number from pdu.
Definition: option.c:198
COAP_OPT_ALL
#define COAP_OPT_ALL
Pre-defined filter that includes all options.
Definition: option.h:107
coap_option_filter_unset
int coap_option_filter_unset(coap_opt_filter_t *filter, coap_option_num_t option)
Clears the corresponding entry for number in filter.
Definition: option.c:498
coap_option_filter_clear
void coap_option_filter_clear(coap_opt_filter_t *filter)
Clears filter filter.
Definition: option.c:488
coap_opt_value
const uint8_t * coap_opt_value(const coap_opt_t *opt)
Returns a pointer to the value of the given option.
Definition: option.c:248
coap_option_iterator_init
coap_opt_iterator_t * coap_option_iterator_init(const coap_pdu_t *pdu, coap_opt_iterator_t *oi, const coap_opt_filter_t *filter)
Initializes the given option iterator oi to point to the beginning of the pdu's option list.
Definition: option.c:112
coap_option_filter_get
int coap_option_filter_get(coap_opt_filter_t *filter, coap_option_num_t option)
Checks if number is contained in filter.
Definition: option.c:503
coap_option_filter_set
int coap_option_filter_set(coap_opt_filter_t *filter, coap_option_num_t option)
Sets the corresponding entry for number in filter.
Definition: option.c:493
COAP_PDU_IS_RESPONSE
#define COAP_PDU_IS_RESPONSE(pdu)
Definition: coap_pdu_internal.h:76
coap_insert_option
size_t coap_insert_option(coap_pdu_t *pdu, coap_option_num_t number, size_t len, const uint8_t *data)
Inserts option of given number in the pdu with the appropriate data.
Definition: pdu.c:414
coap_remove_option
int coap_remove_option(coap_pdu_t *pdu, coap_option_num_t number)
Removes (first) option of given number from the pdu.
Definition: pdu.c:314
coap_update_token
int coap_update_token(coap_pdu_t *pdu, size_t len, const uint8_t *data)
Updates token in pdu with length len and data.
Definition: pdu.c:282
COAP_DROPPED_RESPONSE
#define COAP_DROPPED_RESPONSE
Indicates that a response is suppressed.
Definition: coap_pdu_internal.h:68
coap_pdu_parse_header
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:825
coap_pdu_parse_header_size
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:770
COAP_PDU_DELAYED
#define COAP_PDU_DELAYED
Definition: coap_pdu_internal.h:70
COAP_PDU_IS_EMPTY
#define COAP_PDU_IS_EMPTY(pdu)
Definition: coap_pdu_internal.h:74
COAP_DEFAULT_MAX_PDU_RX_SIZE
#define COAP_DEFAULT_MAX_PDU_RX_SIZE
Definition: coap_pdu_internal.h:60
COAP_PDU_IS_SIGNALING
#define COAP_PDU_IS_SIGNALING(pdu)
Definition: coap_pdu_internal.h:77
coap_pdu_parse_opt
int coap_pdu_parse_opt(coap_pdu_t *pdu)
Verify consistency in the given CoAP PDU structure and locate the data.
Definition: pdu.c:977
coap_update_option
size_t coap_update_option(coap_pdu_t *pdu, coap_option_num_t number, size_t len, const uint8_t *data)
Updates existing first option of given number in the pdu with the new data.
Definition: pdu.c:503
coap_pdu_encode_header
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:1127
coap_pdu_parse
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:1102
coap_pdu_parse_size
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:793
coap_pdu_resize
int coap_pdu_resize(coap_pdu_t *pdu, size_t new_size)
Dynamically grows the size of pdu to new_size.
Definition: pdu.c:207
COAP_PDU_IS_REQUEST
#define COAP_PDU_IS_REQUEST(pdu)
Definition: coap_pdu_internal.h:75
COAP_OPTION_HOP_LIMIT
#define COAP_OPTION_HOP_LIMIT
Definition: pdu.h:121
COAP_OPTION_NORESPONSE
#define COAP_OPTION_NORESPONSE
Definition: pdu.h:130
COAP_OPTION_URI_HOST
#define COAP_OPTION_URI_HOST
Definition: pdu.h:108
COAP_OPTION_IF_MATCH
#define COAP_OPTION_IF_MATCH
Definition: pdu.h:107
COAP_OPTION_BLOCK2
#define COAP_OPTION_BLOCK2
Definition: pdu.h:124
COAP_OPTION_CONTENT_FORMAT
#define COAP_OPTION_CONTENT_FORMAT
Definition: pdu.h:116
COAP_OPTION_SIZE2
#define COAP_OPTION_SIZE2
Definition: pdu.h:126
COAP_OPTION_BLOCK1
#define COAP_OPTION_BLOCK1
Definition: pdu.h:125
COAP_OPTION_PROXY_SCHEME
#define COAP_OPTION_PROXY_SCHEME
Definition: pdu.h:128
COAP_DEFAULT_PORT
#define COAP_DEFAULT_PORT
Definition: pdu.h:35
COAP_OPTION_URI_QUERY
#define COAP_OPTION_URI_QUERY
Definition: pdu.h:120
coap_delete_pdu
void coap_delete_pdu(coap_pdu_t *pdu)
Dispose of an CoAP PDU and frees associated storage.
Definition: pdu.c:142
coap_mid_t
int coap_mid_t
coap_mid_t is used to store the CoAP Message ID of a CoAP PDU.
Definition: pdu.h:231
COAP_OPTION_IF_NONE_MATCH
#define COAP_OPTION_IF_NONE_MATCH
Definition: pdu.h:110
COAP_OPTION_URI_PATH
#define COAP_OPTION_URI_PATH
Definition: pdu.h:115
COAP_RESPONSE_CODE
#define COAP_RESPONSE_CODE(N)
Definition: pdu.h:140
COAP_RESPONSE_CLASS
#define COAP_RESPONSE_CLASS(C)
Definition: pdu.h:143
coap_pdu_code_t
coap_pdu_code_t
Set of codes available for a PDU.
Definition: pdu.h:291
coap_pdu_type_t
coap_pdu_type_t
CoAP PDU message type definitions.
Definition: pdu.h:56
COAP_SIGNALING_OPTION_BLOCK_WISE_TRANSFER
#define COAP_SIGNALING_OPTION_BLOCK_WISE_TRANSFER
Definition: pdu.h:178
coap_add_token
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:258
COAP_OPTION_CONTENT_TYPE
#define COAP_OPTION_CONTENT_TYPE
Definition: pdu.h:117
coap_add_option
size_t coap_add_option(coap_pdu_t *pdu, coap_option_num_t number, size_t len, const uint8_t *data)
Adds option of given number to pdu that is passed as first parameter.
Definition: pdu.c:543
COAP_SIGNALING_OPTION_CUSTODY
#define COAP_SIGNALING_OPTION_CUSTODY
Definition: pdu.h:180
coap_add_data_after
uint8_t * coap_add_data_after(coap_pdu_t *pdu, size_t len)
Adds given data to the pdu that is passed as first parameter but does not copy it.
Definition: pdu.c:636
COAPS_DEFAULT_PORT
#define COAPS_DEFAULT_PORT
Definition: pdu.h:36
COAP_OPTION_URI_PORT
#define COAP_OPTION_URI_PORT
Definition: pdu.h:112
COAP_OPTION_ACCEPT
#define COAP_OPTION_ACCEPT
Definition: pdu.h:122
COAP_INVALID_MID
#define COAP_INVALID_MID
Indicates an invalid message id.
Definition: pdu.h:234
coap_response_phrase
const char * coap_response_phrase(unsigned char code)
Returns a human-readable response phrase for the specified CoAP response code.
Definition: pdu.c:729
COAP_OPTION_ETAG
#define COAP_OPTION_ETAG
Definition: pdu.h:109
COAP_OPTION_PROXY_URI
#define COAP_OPTION_PROXY_URI
Definition: pdu.h:127
COAP_OPTION_OBSERVE
#define COAP_OPTION_OBSERVE
Definition: pdu.h:111
COAP_DEFAULT_URI_WELLKNOWN
#define COAP_DEFAULT_URI_WELLKNOWN
well-known resources URI
Definition: pdu.h:49
COAP_MEDIATYPE_APPLICATION_LINK_FORMAT
#define COAP_MEDIATYPE_APPLICATION_LINK_FORMAT
Definition: pdu.h:190
coap_pdu_init
coap_pdu_t * coap_pdu_init(coap_pdu_type_t type, coap_pdu_code_t code, coap_mid_t mid, size_t size)
Creates a new CoAP PDU with at least enough storage space for the given size maximum message size.
Definition: pdu.c:87
COAP_SIGNALING_OPTION_MAX_MESSAGE_SIZE
#define COAP_SIGNALING_OPTION_MAX_MESSAGE_SIZE
Definition: pdu.h:177
coap_add_data
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:624
COAP_PROTO_DTLS
@ COAP_PROTO_DTLS
Definition: pdu.h:283
COAP_PROTO_UDP
@ COAP_PROTO_UDP
Definition: pdu.h:282
COAP_PROTO_NONE
@ COAP_PROTO_NONE
Definition: pdu.h:281
COAP_PROTO_TLS
@ COAP_PROTO_TLS
Definition: pdu.h:285
COAP_PROTO_TCP
@ COAP_PROTO_TCP
Definition: pdu.h:284
COAP_SIGNALING_CODE_ABORT
@ COAP_SIGNALING_CODE_ABORT
Definition: pdu.h:335
COAP_SIGNALING_CODE_CSM
@ COAP_SIGNALING_CODE_CSM
Definition: pdu.h:331
COAP_SIGNALING_CODE_PING
@ COAP_SIGNALING_CODE_PING
Definition: pdu.h:332
COAP_REQUEST_CODE_DELETE
@ COAP_REQUEST_CODE_DELETE
Definition: pdu.h:297
COAP_SIGNALING_CODE_PONG
@ COAP_SIGNALING_CODE_PONG
Definition: pdu.h:333
COAP_REQUEST_CODE_GET
@ COAP_REQUEST_CODE_GET
Definition: pdu.h:294
COAP_SIGNALING_CODE_RELEASE
@ COAP_SIGNALING_CODE_RELEASE
Definition: pdu.h:334
COAP_REQUEST_CODE_FETCH
@ COAP_REQUEST_CODE_FETCH
Definition: pdu.h:298
COAP_MESSAGE_NON
@ COAP_MESSAGE_NON
Definition: pdu.h:58
COAP_MESSAGE_ACK
@ COAP_MESSAGE_ACK
Definition: pdu.h:59
COAP_MESSAGE_CON
@ COAP_MESSAGE_CON
Definition: pdu.h:57
COAP_MESSAGE_RST
@ COAP_MESSAGE_RST
Definition: pdu.h:60
coap_endpoint_get_session
coap_session_t * coap_endpoint_get_session(coap_endpoint_t *endpoint, const coap_packet_t *packet, coap_tick_t now)
Lookup the server session for the packet received on an endpoint, or create a new one.
Definition: coap_session.c:554
coap_session_delay_pdu
ssize_t coap_session_delay_pdu(coap_session_t *session, coap_pdu_t *pdu, coap_queue_t *node)
Definition: coap_session.c:312
coap_session_send_csm
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:351
coap_new_server_session
coap_session_t * coap_new_server_session(coap_context_t *ctx, coap_endpoint_t *ep)
Creates a new server session for the specified endpoint.
Definition: coap_session.c:1106
coap_session_send
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:277
coap_session_connected
void coap_session_connected(coap_session_t *session)
Notify session that it has just connected or reconnected.
Definition: coap_session.c:399
coap_session_send_pdu
ssize_t coap_session_send_pdu(coap_session_t *session, coap_pdu_t *pdu)
Send a pdu according to the session's protocol.
Definition: net.c:766
coap_session_write
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:298
coap_free_endpoint
void coap_free_endpoint(coap_endpoint_t *ep)
Definition: coap_session.c:1324
coap_session_set_mtu
void coap_session_set_mtu(coap_session_t *session, unsigned mtu)
Set the session MTU.
Definition: coap_session.c:265
coap_session_max_pdu_size
size_t coap_session_max_pdu_size(const coap_session_t *session)
Get maximum acceptable PDU size.
Definition: coap_session.c:244
COAP_PROTO_NOT_RELIABLE
#define COAP_PROTO_NOT_RELIABLE(p)
Definition: coap_session.h:35
coap_session_reference
coap_session_t * coap_session_reference(coap_session_t *session)
Increment reference counter on a session.
Definition: coap_session.c:70
COAP_PROTO_RELIABLE
#define COAP_PROTO_RELIABLE(p)
Definition: coap_session.h:36
coap_session_release
void coap_session_release(coap_session_t *session)
Decrement reference counter on a session.
Definition: coap_session.c:76
coap_new_endpoint
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:1229
coap_session_disconnected
void coap_session_disconnected(coap_session_t *session, coap_nack_reason_t reason)
Notify session that it has failed.
Definition: coap_session.c:456
COAP_SESSION_TYPE_HELLO
@ COAP_SESSION_TYPE_HELLO
server-side ephemeral session for responding to a client hello
Definition: coap_session.h:45
COAP_SESSION_STATE_HANDSHAKE
@ COAP_SESSION_STATE_HANDSHAKE
Definition: coap_session.h:55
COAP_SESSION_STATE_CSM
@ COAP_SESSION_STATE_CSM
Definition: coap_session.h:56
COAP_SESSION_STATE_ESTABLISHED
@ COAP_SESSION_STATE_ESTABLISHED
Definition: coap_session.h:57
COAP_SESSION_STATE_NONE
@ COAP_SESSION_STATE_NONE
Definition: coap_session.h:53
COAP_SESSION_STATE_CONNECTING
@ COAP_SESSION_STATE_CONNECTING
Definition: coap_session.h:54
COAP_SET_STR
#define COAP_SET_STR(st, l, v)
Definition: str.h:45
coap_string_equal
#define coap_string_equal(string1, string2)
Compares the two strings for equality.
Definition: str.h:183
coap_delete_string
void coap_delete_string(coap_string_t *s)
Deletes the given string and releases any memory allocated.
Definition: str.c:40
coap_delete_observer
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:816
coap_add_observer
coap_subscription_t * coap_add_observer(coap_resource_t *resource, coap_session_t *session, const coap_binary_t *token, const coap_pdu_t *request)
Adds the specified peer as observer for resource.
Definition: resource.c:721
coap_check_notify
void coap_check_notify(coap_context_t *context)
Checks all known resources to see if they are dirty and then notifies subscribed observers.
Definition: resource.c:1062
coap_handle_failed_notify
void coap_handle_failed_notify(coap_context_t *context, coap_session_t *session, const coap_binary_t *token)
Handles a failed observe notify.
Definition: resource.c:1125
coap_touch_observer
void coap_touch_observer(coap_context_t *context, coap_session_t *session, const coap_binary_t *token)
Flags that data is ready to be sent to observers.
Definition: resource.c:803
coap_socket_connect_tcp1
int coap_socket_connect_tcp1(coap_socket_t *sock, const coap_address_t *local_if, const coap_address_t *server, int default_port, coap_address_t *local_addr, coap_address_t *remote_addr)
Create a new TCP socket and initiate the connection.
Definition: coap_tcp.c:39
coap_socket_connect_tcp2
int coap_socket_connect_tcp2(coap_socket_t *sock, coap_address_t *local_addr, coap_address_t *remote_addr)
Complete the TCP Connection.
Definition: coap_tcp.c:154
coap_get_uri_path
coap_string_t * coap_get_uri_path(const coap_pdu_t *request)
Extract uri_path string from request PDU.
Definition: uri.c:606
coap_get_query
coap_string_t * coap_get_query(const coap_pdu_t *request)
Extract query string from request PDU according to escape rules in 6.5.8.
Definition: uri.c:556
coap_split_proxy_uri
int coap_split_proxy_uri(const uint8_t *str_var, size_t len, coap_uri_t *uri)
Parses a given string into URI components.
Definition: uri.c:241
COAP_UNUSED
#define COAP_UNUSED
Definition: libcoap.h:55
COAP_STATIC_INLINE
#define COAP_STATIC_INLINE
Definition: libcoap.h:40
coap_malloc_type
void * coap_malloc_type(coap_memory_tag_t type, size_t size)
Allocates a chunk of size bytes and returns a pointer to the newly allocated memory.
coap_free
COAP_STATIC_INLINE void coap_free(void *object)
Wrapper function to coap_free_type() for backwards compatibility.
Definition: mem.h:105
coap_memory_init
void coap_memory_init(void)
Initializes libcoap's memory management.
COAP_NODE
@ COAP_NODE
Definition: mem.h:36
COAP_CONTEXT
@ COAP_CONTEXT
Definition: mem.h:37
coap_free_type
void coap_free_type(coap_memory_tag_t type, void *p)
Releases the memory that was allocated by coap_malloc_type().
FRAC_BITS
#define FRAC_BITS
The number of bits for the fractional part of ACK_TIMEOUT and ACK_RANDOM_FACTOR.
Definition: net.c:74
coap_send_pdu
static ssize_t coap_send_pdu(coap_session_t *session, coap_pdu_t *pdu, coap_queue_t *node)
Definition: net.c:799
token_match
COAP_STATIC_INLINE int token_match(const uint8_t *a, size_t alen, const uint8_t *b, size_t blen)
Definition: net.c:1051
respond_t
respond_t
Internal flags to control the treatment of responses (specifically in presence of the No-Response opt...
Definition: net.c:2363
RESPONSE_DROP
@ RESPONSE_DROP
Definition: net.c:2363
RESPONSE_DEFAULT
@ RESPONSE_DEFAULT
Definition: net.c:2363
RESPONSE_SEND
@ RESPONSE_SEND
Definition: net.c:2363
handle_request
static void handle_request(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu)
Definition: net.c:2483
coap_default_uri_wellknown
static coap_str_const_t coap_default_uri_wellknown
Definition: net.c:2478
coap_read_endpoint
static int coap_read_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now)
Definition: net.c:1678
get_wkc_len
COAP_STATIC_INLINE size_t get_wkc_len(coap_context_t *context, coap_opt_t *query_filter)
Quick hack to determine the size of the resource description for .well-known/core.
Definition: net.c:2170
MAX_BITS
#define MAX_BITS
The maximum number of bits for fixed point integers that are used for retransmission time calculation...
Definition: net.c:80
coap_get_session_client_psk
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:298
coap_cleanup
void coap_cleanup(void)
Definition: net.c:3242
ACK_TIMEOUT
#define ACK_TIMEOUT
creates a Qx.FRAC_BITS from session's 'ack_timeout'
Definition: net.c:95
SZX_TO_BYTES
#define SZX_TO_BYTES(SZX)
Definition: net.c:2185
coap_get_context_server_psk
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:334
coap_cancel
static int coap_cancel(coap_context_t *context, const coap_queue_t *sent)
This function cancels outstanding messages for the session and token specified in sent.
Definition: net.c:2341
coap_started
static int coap_started
Definition: net.c:3220
coap_accept_endpoint
static int coap_accept_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now)
Definition: net.c:1729
coap_get_context_server_hint
static size_t coap_get_context_server_hint(const coap_session_t *session, uint8_t *hint, size_t max_hint_len)
Definition: net.c:362
coap_write_endpoint
static int coap_write_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t now)
Definition: net.c:1721
coap_handle_dgram_for_proto
static int coap_handle_dgram_for_proto(coap_context_t *ctx, coap_session_t *session, coap_packet_t *packet)
Definition: net.c:1428
coap_write_session
static void coap_write_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now)
Definition: net.c:1484
coap_connect_session
static void coap_connect_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now)
Definition: net.c:1447
coap_free_node
COAP_STATIC_INLINE void coap_free_node(coap_queue_t *node)
Definition: net.c:105
SHR_FP
#define SHR_FP(val, frac)
no_response
static enum respond_t no_response(coap_pdu_t *request, coap_pdu_t *response, coap_session_t *session)
Definition: net.c:2411
handle_signaling
static void handle_signaling(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu)
Definition: net.c:2939
min
#define min(a, b)
Definition: net.c:67
coap_read_session
static void coap_read_session(coap_context_t *ctx, coap_session_t *session, coap_tick_t now)
Definition: net.c:1534
coap_startup
void coap_startup(void)
Definition: net.c:3222
FP1
#define FP1
ACK_RANDOM_FACTOR
#define ACK_RANDOM_FACTOR
creates a Qx.FRAC_BITS from session's 'ack_random_factor'
Definition: net.c:91
coap_malloc_node
COAP_STATIC_INLINE coap_queue_t * coap_malloc_node(void)
Definition: net.c:100
INET6_ADDRSTRLEN
#define INET6_ADDRSTRLEN
Definition: net.c:63
handle_response
static void handle_response(coap_context_t *context, coap_session_t *session, coap_pdu_t *sent, coap_pdu_t *rcvd)
Definition: net.c:2898
coap_option_num_t
uint16_t coap_option_num_t
Definition: option.h:20
coap_opt_t
uint8_t coap_opt_t
Use byte-oriented access methods here because sliding a complex struct coap_opt_t over the data buffe...
Definition: option.h:26
COAP_RESOURCE_CHECK_TIME
#define COAP_RESOURCE_CHECK_TIME
The interval in seconds to check if resources have changed.
Definition: resource.h:22
coap_addr_tuple_t::remote
coap_address_t remote
remote address and port
Definition: coap_io.h:51
coap_addr_tuple_t::local
coap_address_t local
local address and port
Definition: coap_io.h:52
coap_address_t
multi-purpose address abstraction
Definition: address.h:96
coap_address_t::sin
struct sockaddr_in sin
Definition: address.h:100
coap_address_t::sin6
struct sockaddr_in6 sin6
Definition: address.h:101
coap_address_t::sa
struct sockaddr sa
Definition: address.h:99
coap_address_t::addr
union coap_address_t::@0 addr
coap_async_t
Definition: coap_async_internal.h:33
coap_async_t::session
coap_session_t * session
transaction session
Definition: coap_async_internal.h:37
coap_async_t::pdu
coap_pdu_t * pdu
copy of request pdu
Definition: coap_async_internal.h:38
coap_async_t::delay
coap_tick_t delay
When to delay to before triggering the response 0 indicates never trigger.
Definition: coap_async_internal.h:35
coap_bin_const_t
CoAP binary data definition with const data.
Definition: str.h:58
coap_bin_const_t::length
size_t length
length of binary data
Definition: str.h:59
coap_bin_const_t::s
const uint8_t * s
read-only binary data
Definition: str.h:60
coap_binary_t
CoAP binary data definition.
Definition: str.h:50
coap_binary_t::length
size_t length
length of binary data
Definition: str.h:51
coap_binary_t::s
uint8_t * s
binary data
Definition: str.h:52
coap_block_t
Structure of Block options.
Definition: block.h:35
coap_block_t::num
unsigned int num
block number
Definition: block.h:36
coap_block_t::szx
unsigned int szx
block size
Definition: block.h:38
coap_block_t::m
unsigned int m
1 if more blocks follow, 0 otherwise
Definition: block.h:37
coap_cache_entry_t
Definition: coap_cache_internal.h:38
coap_context_t
The CoAP stack's global state is stored in a coap_context_t object.
Definition: coap_net_internal.h:45
coap_context_t::sendqueue_basetime
coap_tick_t sendqueue_basetime
The time stamp in the first element of the sendqeue is relative to sendqueue_basetime.
Definition: coap_net_internal.h:66
coap_context_t::pong_handler
coap_pong_handler_t pong_handler
Definition: coap_net_internal.h:87
coap_context_t::csm_timeout
unsigned int csm_timeout
Timeout for waiting for a CSM from the remote side.
Definition: coap_net_internal.h:127
coap_context_t::app
void * app
application-specific data
Definition: coap_net_internal.h:138
coap_context_t::async_state
coap_async_t * async_state
list of asynchronous message ids
Definition: coap_net_internal.h:60
coap_context_t::sessions
coap_session_t * sessions
client sessions
Definition: coap_net_internal.h:69
coap_context_t::nack_handler
coap_nack_handler_t nack_handler
Definition: coap_net_internal.h:85
coap_context_t::ping_timeout
unsigned int ping_timeout
Minimum inactivity time before sending a ping message.
Definition: coap_net_internal.h:124
coap_context_t::get_server_psk
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: coap_net_internal.h:104
coap_context_t::resources
coap_resource_t * resources
hash table or list of known resources
Definition: coap_net_internal.h:47
coap_context_t::network_send
ssize_t(* network_send)(coap_socket_t *sock, const coap_session_t *session, const uint8_t *data, size_t datalen)
Definition: coap_net_internal.h:95
coap_context_t::cache_ignore_options
uint16_t * cache_ignore_options
CoAP options to ignore when creating a cache-key.
Definition: coap_net_internal.h:134
coap_context_t::dtls_context
void * dtls_context
Definition: coap_net_internal.h:110
coap_context_t::known_options
coap_opt_filter_t known_options
Definition: coap_net_internal.h:46
coap_context_t::ping_handler
coap_ping_handler_t ping_handler
Definition: coap_net_internal.h:86
coap_context_t::cache_ignore_count
size_t cache_ignore_count
The number of CoAP options to ignore when creating a cache-key.
Definition: coap_net_internal.h:136
coap_context_t::max_handshake_sessions
unsigned int max_handshake_sessions
Maximum number of simultaneous negotating sessions per endpoint.
Definition: coap_net_internal.h:121
coap_context_t::sendqueue
coap_queue_t * sendqueue
Definition: coap_net_internal.h:67
coap_context_t::response_handler
coap_response_handler_t response_handler
Definition: coap_net_internal.h:84
coap_context_t::cache
coap_cache_entry_t * cache
CoAP cache-entry cache.
Definition: coap_net_internal.h:133
coap_context_t::endpoint
coap_endpoint_t * endpoint
the endpoints used for listening
Definition: coap_net_internal.h:68
coap_context_t::get_server_hint
size_t(* get_server_hint)(const coap_session_t *session, uint8_t *hint, size_t max_hint_len)
Definition: coap_net_internal.h:107
coap_context_t::handle_event
coap_event_handler_t handle_event
Callback function that is used to signal events to the application.
Definition: coap_net_internal.h:93
coap_context_t::session_timeout
unsigned int session_timeout
Number of seconds of inactivity after which an unused session will be closed.
Definition: coap_net_internal.h:115
coap_context_t::network_read
ssize_t(* network_read)(coap_socket_t *sock, coap_packet_t *packet)
Definition: coap_net_internal.h:98
coap_context_t::get_client_psk
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: coap_net_internal.h:100
coap_context_t::proxy_uri_resource
coap_resource_t * proxy_uri_resource
can be used for handling proxy URI resources
Definition: coap_net_internal.h:51
coap_context_t::spsk_setup_data
coap_dtls_spsk_t spsk_setup_data
Contains the initial PSK server setup data.
Definition: coap_net_internal.h:112
coap_context_t::unknown_resource
coap_resource_t * unknown_resource
can be used for handling unknown resources
Definition: coap_net_internal.h:49
coap_context_t::max_idle_sessions
unsigned int max_idle_sessions
Maximum number of simultaneous unused sessions per endpoint.
Definition: coap_net_internal.h:118
coap_dtls_cpsk_info_t
The structure that holds the Client PSK information.
Definition: coap_dtls.h:307
coap_dtls_cpsk_info_t::key
coap_bin_const_t key
Definition: coap_dtls.h:309
coap_dtls_cpsk_info_t::identity
coap_bin_const_t identity
Definition: coap_dtls.h:308
coap_dtls_cpsk_t::psk_info
coap_dtls_cpsk_info_t psk_info
Client PSK definition.
Definition: coap_dtls.h:367
coap_dtls_pki_t
The structure used for defining the PKI setup data to be used.
Definition: coap_dtls.h:244
coap_dtls_pki_t::version
uint8_t version
Definition: coap_dtls.h:245
coap_dtls_spsk_info_t
The structure that holds the Server Pre-Shared Key and Identity Hint information.
Definition: coap_dtls.h:374
coap_dtls_spsk_info_t::hint
coap_bin_const_t hint
Definition: coap_dtls.h:375
coap_dtls_spsk_info_t::key
coap_bin_const_t key
Definition: coap_dtls.h:376
coap_dtls_spsk_t
The structure used for defining the Server PSK setup data to be used.
Definition: coap_dtls.h:425
coap_dtls_spsk_t::psk_info
coap_dtls_spsk_info_t psk_info
Server PSK definition.
Definition: coap_dtls.h:455
coap_endpoint_t
Abstraction of virtual endpoint that can be attached to coap_context_t.
Definition: coap_session_internal.h:136
coap_endpoint_t::context
coap_context_t * context
endpoint's context
Definition: coap_session_internal.h:138
coap_endpoint_t::sessions
coap_session_t * sessions
hash table or list of active sessions
Definition: coap_session_internal.h:144
coap_endpoint_t::bind_addr
coap_address_t bind_addr
local interface address
Definition: coap_session_internal.h:143
coap_endpoint_t::sock
coap_socket_t sock
socket object for the interface, if any
Definition: coap_session_internal.h:141
coap_endpoint_t::proto
coap_proto_t proto
protocol used on this interface
Definition: coap_session_internal.h:139
coap_l_block1_t::token_length
size_t token_length
length of token
Definition: coap_block_internal.h:59
coap_l_block1_t::app_token
coap_binary_t * app_token
original PDU token
Definition: coap_block_internal.h:57
coap_l_block1_t::token
uint8_t token[8]
last used token
Definition: coap_block_internal.h:58
coap_lg_crcv_t
Structure to hold large body (many blocks) client receive information.
Definition: coap_block_internal.h:99
coap_lg_crcv_t::initial
uint8_t initial
If set, has not been used yet.
Definition: coap_block_internal.h:109
coap_lg_crcv_t::app_token
coap_binary_t * app_token
app requesting PDU token
Definition: coap_block_internal.h:113
coap_lg_crcv_t::token
uint8_t token[8]
last used token
Definition: coap_block_internal.h:116
coap_lg_crcv_t::base_token
uint8_t base_token[8]
established base PDU token
Definition: coap_block_internal.h:114
coap_lg_crcv_t::token_length
size_t token_length
length of token
Definition: coap_block_internal.h:117
coap_lg_crcv_t::base_token_length
size_t base_token_length
length of token
Definition: coap_block_internal.h:115
coap_lg_crcv_t::observe_set
uint8_t observe_set
Set if this is an observe receive PDU.
Definition: coap_block_internal.h:103
coap_lg_xmit_t
Structure to hold large body (many blocks) transmission information.
Definition: coap_block_internal.h:77
coap_lg_xmit_t::b
union coap_lg_xmit_t::@1 b
coap_lg_xmit_t::pdu
coap_pdu_t pdu
skeletal PDU
Definition: coap_block_internal.h:89
coap_lg_xmit_t::b1
coap_l_block1_t b1
Definition: coap_block_internal.h:86
coap_opt_filter_t
Definition: option.h:100
coap_opt_iterator_t
Iterator to run through PDU options.
Definition: option.h:170
coap_opt_iterator_t::number
coap_option_num_t number
decoded option number
Definition: option.h:172
coap_packet_t
Definition: coap_io_internal.h:160
coap_packet_t::addr_info
coap_addr_tuple_t addr_info
local and remote addresses
Definition: coap_io_internal.h:161
coap_packet_t::payload
unsigned char payload[COAP_RXBUFFER_SIZE]
payload
Definition: coap_io_internal.h:164
coap_pdu_t
structure for CoAP PDUs token, if any, follows the fixed size header, then options until payload mark...
Definition: coap_pdu_internal.h:94
coap_pdu_t::token
uint8_t * token
first byte of token, if any, or options
Definition: coap_pdu_internal.h:111
coap_pdu_t::max_size
size_t max_size
maximum size for token, options and payload, or zero for variable size pdu
Definition: coap_pdu_internal.h:109
coap_pdu_t::code
coap_pdu_code_t code
request method (value 1–31) or response code (value 64-255)
Definition: coap_pdu_internal.h:96
coap_pdu_t::token_length
uint8_t token_length
length of Token
Definition: coap_pdu_internal.h:103
coap_pdu_t::hdr_size
uint8_t hdr_size
actual size used for protocol-specific header
Definition: coap_pdu_internal.h:101
coap_pdu_t::data
uint8_t * data
first byte of payload, if any
Definition: coap_pdu_internal.h:112
coap_pdu_t::mid
coap_mid_t mid
message id, if any, in regular host byte order
Definition: coap_pdu_internal.h:98
coap_pdu_t::used_size
size_t used_size
used bytes of storage for token, options and payload
Definition: coap_pdu_internal.h:107
coap_pdu_t::alloc_size
size_t alloc_size
allocated storage for token, options and payload
Definition: coap_pdu_internal.h:105
coap_pdu_t::type
coap_pdu_type_t type
message type
Definition: coap_pdu_internal.h:95
coap_queue_t
Queue entry.
Definition: coap_net_internal.h:31
coap_queue_t::session
coap_session_t * session
the CoAP session
Definition: coap_net_internal.h:37
coap_queue_t::pdu
coap_pdu_t * pdu
the CoAP PDU to send
Definition: coap_net_internal.h:39
coap_queue_t::timeout
unsigned int timeout
the randomized timeout value
Definition: coap_net_internal.h:36
coap_queue_t::next
struct coap_queue_t * next
Definition: coap_net_internal.h:32
coap_queue_t::id
coap_mid_t id
CoAP message id.
Definition: coap_net_internal.h:38
coap_queue_t::t
coap_tick_t t
when to send PDU for the next time
Definition: coap_net_internal.h:33
coap_queue_t::retransmit_cnt
unsigned char retransmit_cnt
retransmission counter, will be removed when zero
Definition: coap_net_internal.h:34
coap_resource_t
Abstraction of resource that can be attached to coap_context_t.
Definition: coap_resource_internal.h:42
coap_resource_t::proxy_name_list
coap_str_const_t ** proxy_name_list
Array valid names this host is known by (proxy support)
Definition: coap_resource_internal.h:93
coap_resource_t::uri_path
coap_str_const_t * uri_path
Request URI Path for this resource.
Definition: coap_resource_internal.h:70
coap_resource_t::observe
unsigned int observe
The next value for the Observe option.
Definition: coap_resource_internal.h:78
coap_resource_t::handler
coap_method_handler_t handler[7]
Used to store handlers for the seven coap methods GET, POST, PUT, DELETE, FETCH, PATCH and IPATCH.
Definition: coap_resource_internal.h:58
coap_resource_t::is_proxy_uri
unsigned int is_proxy_uri
resource created for proxy URI handler
Definition: coap_resource_internal.h:49
coap_resource_t::is_unknown
unsigned int is_unknown
resource created for unknown handler
Definition: coap_resource_internal.h:48
coap_resource_t::observable
unsigned int observable
can be observed
Definition: coap_resource_internal.h:46
coap_resource_t::proxy_name_count
size_t proxy_name_count
Count of valid names this host is known by (proxy support)
Definition: coap_resource_internal.h:88
coap_session_t
Abstraction of virtual session that can be attached to coap_context_t (client) or coap_endpoint_t (se...
Definition: coap_session_internal.h:48
coap_session_t::last_pong
coap_tick_t last_pong
Definition: coap_session_internal.h:87
coap_session_t::lg_xmit
coap_lg_xmit_t * lg_xmit
list of large transmissions
Definition: coap_session_internal.h:73
coap_session_t::psk_key
coap_bin_const_t * psk_key
If client, this field contains the current pre-shared key for server; When this field is NULL,...
Definition: coap_session_internal.h:100
coap_session_t::endpoint
coap_endpoint_t * endpoint
session's endpoint
Definition: coap_session_internal.h:62
coap_session_t::last_rx_tx
coap_tick_t last_rx_tx
Definition: coap_session_internal.h:84
coap_session_t::sock
coap_socket_t sock
socket object for the session, if any
Definition: coap_session_internal.h:60
coap_session_t::max_retransmit
unsigned int max_retransmit
maximum re-transmit count (default 4)
Definition: coap_session_internal.h:119
coap_session_t::partial_pdu
coap_pdu_t * partial_pdu
incomplete incoming pdu
Definition: coap_session_internal.h:83
coap_session_t::psk_identity
coap_bin_const_t * psk_identity
If client, this field contains the current identity for server; When this field is NULL,...
Definition: coap_session_internal.h:91
coap_session_t::state
coap_session_state_t state
current state of relationaship with peer
Definition: coap_session_internal.h:51
coap_session_t::block_mode
uint8_t block_mode
Zero or more COAP_BLOCK_ or'd options.
Definition: coap_session_internal.h:128
coap_session_t::read_header
uint8_t read_header[8]
storage space for header of incoming message header
Definition: coap_session_internal.h:79
coap_session_t::addr_info
coap_addr_tuple_t addr_info
key: remote/local address info
Definition: coap_session_internal.h:58
coap_session_t::proto
coap_proto_t proto
protocol used
Definition: coap_session_internal.h:49
coap_session_t::psk_hint
coap_bin_const_t * psk_hint
If client, this field contains the server provided identity hint.
Definition: coap_session_internal.h:109
coap_session_t::cpsk_setup_data
coap_dtls_cpsk_t cpsk_setup_data
client provided PSK initial setup data
Definition: coap_session_internal.h:89
coap_session_t::partial_read
size_t partial_read
if > 0 indicates number of bytes already read for an incoming message
Definition: coap_session_internal.h:81
coap_session_t::tls
void * tls
security parameters
Definition: coap_session_internal.h:64
coap_session_t::csm_block_supported
uint8_t csm_block_supported
CSM TCP blocks supported.
Definition: coap_session_internal.h:68
coap_session_t::con_active
uint8_t con_active
Active CON request sent.
Definition: coap_session_internal.h:67
coap_session_t::delayqueue
coap_queue_t * delayqueue
list of delayed messages waiting to be sent
Definition: coap_session_internal.h:71
coap_session_t::last_ping_mid
coap_mid_t last_ping_mid
the last keepalive message id that was used in this session
Definition: coap_session_internal.h:69
coap_session_t::last_ping
coap_tick_t last_ping
Definition: coap_session_internal.h:86
coap_session_t::lg_crcv
coap_lg_crcv_t * lg_crcv
Client list of expected large receives.
Definition: coap_session_internal.h:74
coap_session_t::type
coap_session_type_t type
client or server side socket
Definition: coap_session_internal.h:50
coap_session_t::last_tx_rst
coap_tick_t last_tx_rst
Definition: coap_session_internal.h:85
coap_session_t::context
coap_context_t * context
session's context
Definition: coap_session_internal.h:63
coap_session_t::partial_write
size_t partial_write
if > 0 indicates number of bytes already written from the pdu at the head of sendqueue
Definition: coap_session_internal.h:76
coap_session_t::csm_tx
coap_tick_t csm_tx
Definition: coap_session_internal.h:88
coap_socket_t
Definition: coap_io_internal.h:23
coap_socket_t::session
coap_session_t * session
Definition: coap_io_internal.h:35
coap_socket_t::endpoint
coap_endpoint_t * endpoint
Definition: coap_io_internal.h:36
coap_socket_t::fd
coap_fd_t fd
Definition: coap_io_internal.h:29
coap_socket_t::flags
coap_socket_flags_t flags
Definition: coap_io_internal.h:34
coap_str_const_t
CoAP string data definition with const data.
Definition: str.h:40
coap_str_const_t::s
const uint8_t * s
read-only string data
Definition: str.h:42
coap_str_const_t::length
size_t length
length of string
Definition: str.h:41
coap_string_t
CoAP string data definition.
Definition: str.h:32
coap_string_t::s
uint8_t * s
string data
Definition: str.h:34
coap_string_t::length
size_t length
length of string
Definition: str.h:33
coap_subscription_t
Subscriber information.
Definition: coap_subscribe_internal.h:47
coap_subscription_t::session
struct coap_session_t * session
subscriber session
Definition: coap_subscribe_internal.h:49
coap_subscription_t::pdu
coap_pdu_t * pdu
cache_key to identify requester
Definition: coap_subscribe_internal.h:57
coap_uri_t
Representation of parsed URI.
Definition: uri.h:40
coap_uri_t::host
coap_str_const_t host
host part of the URI
Definition: uri.h:41