moving library related files to new folders

In preparation for changing the make buildsystem to a fully autotools
controlled system moving the core libcoap source files to a better logical
place.

All the library related header files moving to include/coap/ to get
all the public and local header files in a separate place. Also moving
the C source files of the libcoap library to the folder src/.
This commit is contained in:
Carsten Schoenert authored and Olaf Bergmann committed 2015-03-03 19:21:43 +01:00
1 parent fd86c02ac4
commit fc9b47167a
37 files changed

No files matched your search

+101
View File
@@ -0,0 +1,101 @@
/* async.c -- state management for asynchronous messages
*
* Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
*
* This file is part of the CoAP library libcoap. Please see
* README for terms of use.
*/
/**
* @file async.c
* @brief state management for asynchronous messages
*/
#ifndef WITHOUT_ASYNC
#include "coap_config.h"
#include "utlist.h"
#include "mem.h"
#include "debug.h"
#include "async.h"
coap_async_state_t *
coap_register_async(coap_context_t *context, coap_address_t *peer,
coap_pdu_t *request, unsigned char flags, void *data) {
coap_async_state_t *s;
coap_tid_t id;
coap_transaction_id(peer, request, &id);
LL_SEARCH_SCALAR(context->async_state,s,id,id);
if (s != NULL) {
/* We must return NULL here as the caller must know that he is
* responsible for releasing @p data. */
debug("asynchronous state for transaction %d already registered\n", id);
return NULL;
}
/* store information for handling the asynchronous task */
s = (coap_async_state_t *)coap_malloc(sizeof(coap_async_state_t) +
request->hdr->token_length);
if (!s) {
coap_log(LOG_CRIT, "coap_register_async: insufficient memory\n");
return NULL;
}
memset(s, 0, sizeof(coap_async_state_t) + request->hdr->token_length);
/* set COAP_ASYNC_CONFIRM according to request's type */
s->flags = flags & ~COAP_ASYNC_CONFIRM;
if (request->hdr->type == COAP_MESSAGE_CON)
s->flags |= COAP_ASYNC_CONFIRM;
s->appdata = data;
memcpy(&s->peer, peer, sizeof(coap_address_t));
if (request->hdr->token_length) {
s->tokenlen = request->hdr->token_length;
memcpy(s->token, request->hdr->token, request->hdr->token_length);
}
memcpy(&s->id, &id, sizeof(coap_tid_t));
coap_touch_async(s);
LL_PREPEND(context->async_state, s);
return s;
}
coap_async_state_t *
coap_find_async(coap_context_t *context, coap_tid_t id) {
coap_async_state_t *tmp;
LL_SEARCH_SCALAR(context->async_state,tmp,id,id);
return tmp;
}
int
coap_remove_async(coap_context_t *context, coap_tid_t id,
coap_async_state_t **s) {
coap_async_state_t *tmp = coap_find_async(context, id);
if (tmp)
LL_DELETE(context->async_state,tmp);
*s = tmp;
return tmp != NULL;
}
void
coap_free_async(coap_async_state_t *s) {
if (s && (s->flags & COAP_ASYNC_RELEASE_DATA) != 0)
coap_free(s->appdata);
coap_free(s);
}
#else
void does_not_exist(); /* make some compilers happy */
#endif /* WITHOUT_ASYNC */
+131
View File
@@ -0,0 +1,131 @@
/* block.c -- block transfer
*
* Copyright (C) 2010--2012,2015 Olaf Bergmann <bergmann@tzi.org>
*
* This file is part of the CoAP library libcoap. Please see
* README for terms of use.
*/
#include "coap_config.h"
#if defined(HAVE_ASSERT_H) && !defined(assert)
# include <assert.h>
#endif
#include "debug.h"
#include "block.h"
#if (COAP_MAX_PDU_SIZE - 6) < (1 << (COAP_MAX_BLOCK_SZX + 4))
#error "COAP_MAX_BLOCK_SZX too large"
#endif
#define min(a,b) ((a) < (b) ? (a) : (b))
#ifndef WITHOUT_BLOCK
unsigned int
coap_opt_block_num(const coap_opt_t *block_opt) {
unsigned int num = 0;
unsigned short len;
len = coap_opt_length(block_opt);
if (len == 0) {
return 0;
}
if (len > 1) {
num = coap_decode_var_bytes(COAP_OPT_VALUE(block_opt),
COAP_OPT_LENGTH(block_opt) - 1);
}
return (num << 4) | ((*COAP_OPT_BLOCK_LAST(block_opt) & 0xF0) >> 4);
}
int
coap_get_block(coap_pdu_t *pdu, unsigned short type, coap_block_t *block) {
coap_opt_iterator_t opt_iter;
coap_opt_t *option;
assert(block);
memset(block, 0, sizeof(coap_block_t));
if (pdu && (option = coap_check_option(pdu, type, &opt_iter))) {
block->szx = COAP_OPT_BLOCK_SZX(option);
if (COAP_OPT_BLOCK_MORE(option))
block->m = 1;
block->num = coap_opt_block_num(option);
return 1;
}
return 0;
}
int
coap_write_block_opt(coap_block_t *block, unsigned short type,
coap_pdu_t *pdu, size_t data_length) {
size_t start, want, avail;
unsigned char buf[3];
assert(pdu);
start = block->num << (block->szx + 4);
if (data_length <= start) {
debug("illegal block requested\n");
return -2;
}
avail = pdu->max_size - pdu->length - 4;
want = 1 << (block->szx + 4);
/* check if entire block fits in message */
if (want <= avail) {
block->m = want < data_length - start;
} else {
/* Sender has requested a block that is larger than the remaining
* space in pdu. This is ok if the remaining data fits into the pdu
* anyway. The block size needs to be adjusted only if there is more
* data left that cannot be delivered in this message. */
if (data_length - start <= avail) {
/* it's the final block and everything fits in the message */
block->m = 0;
} else {
unsigned char szx;
/* we need to decrease the block size */
if (avail < 16) { /* bad luck, this is the smallest block size */
debug("not enough space, even the smallest block does not fit");
return -3;
}
debug("decrease block size for %zu to %d\n", avail, coap_fls(avail) - 5);
szx = block->szx;
block->szx = coap_fls(avail) - 5;
block->m = 1;
block->num <<= szx - block->szx;
}
}
/* to re-encode the block option */
coap_add_option(pdu, type, coap_encode_var_bytes(buf, ((block->num << 4) |
(block->m << 3) |
block->szx)),
buf);
return 1;
}
int
coap_add_block(coap_pdu_t *pdu, unsigned int len, const unsigned char *data,
unsigned int block_num, unsigned char block_szx) {
size_t start;
start = block_num << (block_szx + 4);
if (len <= start)
return 0;
return coap_add_data(pdu,
min(len - start, (unsigned int)(1 << (block_szx + 4))),
data + start);
}
#endif /* WITHOUT_BLOCK */
+552
View File
@@ -0,0 +1,552 @@
/* coap_io.h -- Default network I/O functions for libcoap
*
* Copyright (C) 2012,2014 Olaf Bergmann <bergmann@tzi.org>
*
* This file is part of the CoAP library libcoap. Please see
* README for terms of use.
*/
#include "coap_config.h"
#ifdef HAVE_STDIO_H
# include <stdio.h>
#endif
#ifdef HAVE_SYS_SELECT_H
# include <sys/select.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
# include <sys/socket.h>
#endif
#ifdef HAVE_NETINET_IN_H
# include <netinet/in.h>
#endif
#ifdef HAVE_SYS_UIO_H
# include <sys/uio.h>
#endif
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#include <errno.h>
#ifdef WITH_CONTIKI
# include "uip.h"
#endif
#include "debug.h"
#include "mem.h"
#include "coap_io.h"
#ifdef WITH_POSIX
struct coap_packet_t {
coap_if_handle_t hnd; /**< the interface handle */
coap_address_t src; /**< the packet's source address */
coap_address_t dst; /**< the packet's destination address */
const coap_endpoint_t *interface;
int ifindex;
void *session; /**< opaque session data */
size_t length; /**< length of payload */
unsigned char payload[]; /**< payload */
};
#endif
#ifndef CUSTOM_COAP_NETWORK_ENDPOINT
#ifdef WITH_CONTIKI
static int ep_initialized = 0;
static inline struct coap_endpoint_t *
coap_malloc_contiki_endpoint() {
static struct coap_endpoint_t ep;
if (ep_initialized) {
return NULL;
} else {
ep_initialized = 1;
return &ep;
}
}
static inline void
coap_free_contiki_endpoint(struct coap_endpoint_t *ep) {
ep_initialized = 0;
}
coap_endpoint_t *
coap_new_endpoint(const coap_address_t *addr, int flags) {
struct coap_endpoint_t *ep = coap_malloc_contiki_endpoint();
if (ep) {
memset(ep, 0, sizeof(struct coap_endpoint_t));
ep->handle.conn = udp_new(NULL, 0, NULL);
if (!ep->handle.conn) {
coap_free_endpoint(ep);
return NULL;
}
coap_address_init(&ep->addr);
uip_ipaddr_copy(&ep->addr.addr, &addr->addr);
ep->addr.port = addr->port;
udp_bind((struct uip_udp_conn *)ep->handle.conn, addr->port);
}
return ep;
}
void
coap_free_endpoint(coap_endpoint_t *ep) {
if (ep) {
if (ep->handle.conn) {
uip_udp_remove((struct uip_udp_conn *)ep->handle.conn);
}
coap_free_contiki_endpoint(ep);
}
}
#else /* WITH_CONTIKI */
static inline struct coap_endpoint_t *
coap_malloc_posix_endpoint(void) {
return (struct coap_endpoint_t *)coap_malloc(sizeof(struct coap_endpoint_t));
}
static inline void
coap_free_posix_endpoint(struct coap_endpoint_t *ep) {
coap_free(ep);
}
coap_endpoint_t *
coap_new_endpoint(const coap_address_t *addr, int flags) {
int sockfd = socket(addr->addr.sa.sa_family, SOCK_DGRAM, 0);
int on = 1;
struct coap_endpoint_t *ep;
if (sockfd < 0) {
coap_log(LOG_WARNING, "coap_new_endpoint: socket");
return NULL;
}
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
coap_log(LOG_WARNING, "coap_new_endpoint: setsockopt SO_REUSEADDR");
on = 1;
switch(addr->addr.sa.sa_family) {
case AF_INET:
if (setsockopt(sockfd, IPPROTO_IP, IP_PKTINFO, &on, sizeof(on)) < 0)
coap_log(LOG_ALERT, "coap_new_endpoint: setsockopt IP_PKTINFO\n");
break;
case AF_INET6:
#ifdef IPV6_RECVPKTINFO
if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof(on)) < 0)
coap_log(LOG_ALERT, "coap_new_endpoint: setsockopt IPV6_RECVPKTINFO\n");
#else /* IPV6_RECVPKTINFO */
if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_PKTINFO, &on, sizeof(on)) < 0)
coap_log(LOG_ALERT, "coap_new_endpoint: setsockopt IPV6_PKTINFO\n");
#endif /* IPV6_RECVPKTINFO */
break;
default:
coap_log(LOG_ALERT, "coap_new_endpoint: unsupported sa_family\n");
}
if (bind(sockfd, &addr->addr.sa, addr->size) < 0) {
coap_log(LOG_WARNING, "coap_new_endpoint: bind");
close (sockfd);
return NULL;
}
ep = coap_malloc_posix_endpoint();
if (!ep) {
coap_log(LOG_WARNING, "coap_new_endpoint: malloc");
close(sockfd);
return NULL;
}
memset(ep, 0, sizeof(struct coap_endpoint_t));
ep->handle.fd = sockfd;
ep->flags = flags;
memcpy(&ep->addr, addr, sizeof(coap_address_t));
#ifndef NDEBUG
if (LOG_DEBUG <= coap_get_log_level()) {
#ifndef INET6_ADDRSTRLEN
#define INET6_ADDRSTRLEN 40
#endif
unsigned char addr_str[INET6_ADDRSTRLEN+8];
if (coap_print_addr(addr, addr_str, INET6_ADDRSTRLEN+8)) {
debug("created %sendpoint %s\n",
ep->flags & COAP_ENDPOINT_DTLS ? "DTLS " : "",
addr_str);
}
}
#endif /* NDEBUG */
return (coap_endpoint_t *)ep;
}
void
coap_free_endpoint(coap_endpoint_t *ep) {
if(ep) {
if (ep->handle.fd >= 0)
close(ep->handle.fd);
coap_free_posix_endpoint((struct coap_endpoint_t *)ep);
}
}
#endif /* WITH_CONTIKI */
#endif /* CUSTOM_COAP_NETWORK_ENDPOINT */
#ifndef CUSTOM_COAP_NETWORK_SEND
#ifdef WITH_POSIX
/* define struct in6_pktinfo and struct in_pktinfo if not available
FIXME: check with configure
*/
struct in6_pktinfo {
struct in6_addr ipi6_addr; /* src/dst IPv6 address */
unsigned int ipi6_ifindex; /* send/recv interface index */
};
struct in_pktinfo {
int ipi_ifindex;
struct in_addr ipi_spec_dst;
struct in_addr ipi_addr;
};
#endif
#ifdef __GNUC__
#define UNUSED_PARAM __attribute__ ((unused))
#else /* not a GCC */
#define UNUSED_PARAM
#endif /* GCC */
ssize_t
coap_network_send(struct coap_context_t *context UNUSED_PARAM,
const coap_endpoint_t *local_interface,
const coap_address_t *dst,
unsigned char *data,
size_t datalen) {
struct coap_endpoint_t *ep =
(struct coap_endpoint_t *)local_interface;
#ifndef WITH_CONTIKI
/* a buffer large enough to hold all protocol address types */
char buf[CMSG_LEN(sizeof(struct sockaddr_storage))];
struct msghdr mhdr;
struct iovec iov[1];
assert(local_interface);
iov[0].iov_base = data;
iov[0].iov_len = datalen;
memset(&mhdr, 0, sizeof(struct msghdr));
mhdr.msg_name = (void *)&dst->addr;
mhdr.msg_namelen = dst->size;
mhdr.msg_iov = iov;
mhdr.msg_iovlen = 1;
switch (dst->addr.sa.sa_family) {
case AF_INET6: {
struct cmsghdr *cmsg;
struct in6_pktinfo *pktinfo;
mhdr.msg_control = buf;
mhdr.msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo));
cmsg = CMSG_FIRSTHDR(&mhdr);
cmsg->cmsg_level = IPPROTO_IPV6;
cmsg->cmsg_type = IPV6_PKTINFO;
cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
pktinfo = (struct in6_pktinfo *)CMSG_DATA(cmsg);
memset(pktinfo, 0, sizeof(struct in6_pktinfo));
pktinfo->ipi6_ifindex = ep->ifindex;
memcpy(&pktinfo->ipi6_addr,
&local_interface->addr.addr.sin6.sin6_addr,
local_interface->addr.size);
break;
}
case AF_INET: {
struct cmsghdr *cmsg;
struct in_pktinfo *pktinfo;
mhdr.msg_control = buf;
mhdr.msg_controllen = CMSG_SPACE(sizeof(struct in_pktinfo));
cmsg = CMSG_FIRSTHDR(&mhdr);
cmsg->cmsg_level = SOL_IP;
cmsg->cmsg_type = IP_PKTINFO;
cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
pktinfo = (struct in_pktinfo *)CMSG_DATA(cmsg);
memset(pktinfo, 0, sizeof(struct in_pktinfo));
pktinfo->ipi_ifindex = ep->ifindex;
memcpy(&pktinfo->ipi_spec_dst,
&local_interface->addr.addr.sin.sin_addr,
local_interface->addr.size);
break;
}
default:
/* error */
coap_log(LOG_WARNING, "protocol not supported\n");
return -1;
}
return sendmsg(ep->handle.fd, &mhdr, 0);
#else /* WITH_CONTIKI */
/* FIXME: untested */
/* FIXME: is there a way to check if send was successful? */
uip_udp_packet_sendto((struct uip_udp_conn *)ep->handle.conn, data, datalen,
&dst->addr, dst->port);
return datalen;
#endif /* WITH_CONTIKI */
}
#endif /* CUSTOM_COAP_NETWORK_SEND */
#ifndef CUSTOM_COAP_NETWORK_READ
#define SIN6(A) ((struct sockaddr_in6 *)(A))
#ifdef WITH_POSIX
static coap_packet_t *
coap_malloc_packet(void) {
coap_packet_t *packet;
const size_t need = sizeof(coap_packet_t) + COAP_MAX_PDU_SIZE;
packet = (coap_packet_t *)coap_malloc(need);
if (packet) {
memset(packet, 0, need);
}
return packet;
}
void
coap_free_packet(coap_packet_t *packet) {
coap_free(packet);
}
#endif /* WITH_POSIX */
#ifdef WITH_CONTIKI
static inline coap_packet_t *
coap_malloc_packet(void) {
return (coap_packet_t *)coap_malloc_type(COAP_PACKET, 0);
}
void
coap_free_packet(coap_packet_t *packet) {
coap_free_type(COAP_PACKET, packet);
}
#endif /* WITH_CONTIKI */
static inline size_t
coap_get_max_packetlength(const coap_packet_t *packet UNUSED_PARAM) {
return COAP_MAX_PDU_SIZE;
}
void
coap_packet_populate_endpoint(coap_packet_t *packet, coap_endpoint_t *target)
{
target->handle = packet->interface->handle;
memcpy(&target->addr, &packet->dst, sizeof(target->addr));
target->ifindex = packet->ifindex;
target->flags = 0; /* FIXME */
}
void
coap_packet_copy_source(coap_packet_t *packet, coap_address_t *target)
{
memcpy(target, &packet->src, sizeof(coap_address_t));
}
void
coap_packet_get_memmapped(coap_packet_t *packet, unsigned char **address, size_t *length)
{
*address = packet->payload;
*length = packet->length;
}
/**
* Checks if a message with destination address @param dst matches the
* local interface with address @param local. This function returns @c 1
* if @param dst is a valid match, and @c 0 otherwise.
*/
static inline int
is_local_if(const coap_address_t *local, const coap_address_t *dst) {
return coap_address_isany(local) || coap_address_equals(dst, local);
}
ssize_t
coap_network_read(coap_endpoint_t *ep, coap_packet_t **packet) {
ssize_t len = -1;
#ifdef WITH_POSIX
char msg_control[CMSG_LEN(sizeof(struct sockaddr_storage))];
struct msghdr mhdr;
struct iovec iov[1];
#endif /* WITH_POSIX */
assert(ep);
assert(packet);
*packet = coap_malloc_packet();
if (!*packet) {
warn("coap_network_read: insufficient memory, drop packet\n");
return -1;
}
coap_address_init(&(*packet)->dst); /* the local interface address */
coap_address_init(&(*packet)->src); /* the remote peer */
#ifdef WITH_POSIX
iov[0].iov_base = (*packet)->payload;
iov[0].iov_len = coap_get_max_packetlength(*packet);
memset(&mhdr, 0, sizeof(struct msghdr));
mhdr.msg_name = &(*packet)->src.addr.st;
mhdr.msg_namelen = sizeof((*packet)->src.addr.st);
mhdr.msg_iov = iov;
mhdr.msg_iovlen = 1;
mhdr.msg_control = msg_control;
mhdr.msg_controllen = sizeof(msg_control);
assert(sizeof(msg_control) == CMSG_LEN(sizeof(struct sockaddr_storage)));
len = recvmsg(ep->handle.fd, &mhdr, 0);
if (len < 0) {
coap_log(LOG_WARNING, "coap_network_read: %s\n", strerror(errno));
goto error;
} else {
struct cmsghdr *cmsg;
coap_log(LOG_DEBUG, "received %d bytes on fd %d\n", (int)len, ep->handle.fd);
/* use getsockname() to get the local port */
(*packet)->dst.size = sizeof((*packet)->dst.addr);
if (getsockname(ep->handle.fd, &(*packet)->dst.addr.sa, &(*packet)->dst.size) < 0) {
coap_log(LOG_DEBUG, "cannot determine local port\n");
goto error;
}
(*packet)->length = len;
/* Walk through ancillary data records until the local interface
* is found where the data was received. */
for (cmsg = CMSG_FIRSTHDR(&mhdr); cmsg; cmsg = CMSG_NXTHDR(&mhdr, cmsg)) {
/* get the local interface for IPv6 */
if (cmsg->cmsg_level == IPPROTO_IPV6 && cmsg->cmsg_type == IPV6_PKTINFO) {
union {
unsigned char *c;
struct in6_pktinfo *p;
} u;
u.c = CMSG_DATA(cmsg);
(*packet)->ifindex = (int)(u.p->ipi6_ifindex);
memcpy(&(*packet)->dst.addr.sin6.sin6_addr,
&u.p->ipi6_addr, sizeof(struct in6_addr));
(*packet)->src.size = mhdr.msg_namelen;
assert((*packet)->src.size == sizeof(struct sockaddr_in6));
(*packet)->src.addr.sin6.sin6_family = SIN6(mhdr.msg_name)->sin6_family;
(*packet)->src.addr.sin6.sin6_addr = SIN6(mhdr.msg_name)->sin6_addr;
(*packet)->src.addr.sin6.sin6_port = SIN6(mhdr.msg_name)->sin6_port;
break;
}
/* local interface for IPv4 */
if (cmsg->cmsg_level == SOL_IP && cmsg->cmsg_type == IP_PKTINFO) {
union {
unsigned char *c;
struct in_pktinfo *p;
} u;
u.c = CMSG_DATA(cmsg);
(*packet)->ifindex = u.p->ipi_ifindex;
memcpy(&(*packet)->dst.addr.sin.sin_addr,
&u.p->ipi_addr, sizeof(struct in_addr));
(*packet)->src.size = mhdr.msg_namelen;
memcpy(&(*packet)->src.addr.st, mhdr.msg_name, (*packet)->src.size);
break;
}
}
if (!is_local_if(&ep->addr, &(*packet)->dst)) {
coap_log(LOG_DEBUG, "packet received on wrong interface, dropped\n");
goto error;
}
}
#endif /* WITH_POSIX */
#ifdef WITH_CONTIKI
/* FIXME: untested, make this work */
#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])
if(uip_newdata()) {
uip_ipaddr_copy(&(*packet)->src.addr, &UIP_IP_BUF->srcipaddr);
(*packet)->src.port = UIP_UDP_BUF->srcport;
uip_ipaddr_copy(&(*packet)->dst.addr, &UIP_IP_BUF->destipaddr);
(*packet)->dst.port = UIP_UDP_BUF->destport;
if (!is_local_if(&ep->addr, &(*packet)->dst)) {
coap_log(LOG_DEBUG, "packet received on wrong interface, dropped\n");
goto error;
}
len = uip_datalen();
if (len > coap_get_max_packetlength(*packet)) {
/* FIXME: we might want to send back a response */
warn("discarded oversized packet\n");
return -1;
}
((char *)uip_appdata)[len] = 0;
#ifndef NDEBUG
if (LOG_DEBUG <= coap_get_log_level()) {
#ifndef INET6_ADDRSTRLEN
#define INET6_ADDRSTRLEN 40
#endif
unsigned char addr_str[INET6_ADDRSTRLEN+8];
if (coap_print_addr(&(*packet)->src, addr_str, INET6_ADDRSTRLEN+8)) {
debug("received %zd bytes from %s\n", len, addr_str);
}
}
#endif /* NDEBUG */
(*packet)->length = len;
memcpy(&(*packet)->payload, uip_appdata, len);
}
#undef UIP_IP_BUF
#undef UIP_UDP_BUF
#endif /* WITH_CONTIKI */
#ifdef WITH_LWIP
#error "coap_network_read() not implemented on this platform"
#endif
(*packet)->interface = ep;
return len;
error:
coap_free_packet(*packet);
*packet = NULL;
return -1;
}
#undef SIN6
#endif /* CUSTOM_COAP_NETWORK_READ */
+334
View File
@@ -0,0 +1,334 @@
/* debug.c -- debug utilities
*
* Copyright (C) 2010--2012,2014--2015 Olaf Bergmann <bergmann@tzi.org>
*
* This file is part of the CoAP library libcoap. Please see
* README for terms of use.
*/
#include "coap_config.h"
#if defined(HAVE_STRNLEN) && defined(__GNUC__) && !defined(_GNU_SOURCE)
#define _GNU_SOURCE 1
#endif
#if defined(HAVE_ASSERT_H) && !defined(assert)
# include <assert.h>
#endif
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifdef HAVE_TIME_H
#include <time.h>
#endif
#include "debug.h"
#include "net.h"
#ifdef WITH_CONTIKI
# ifndef DEBUG
# define DEBUG DEBUG_PRINT
# endif /* DEBUG */
#include "net/ip/uip-debug.h"
#endif
static coap_log_t maxlog = LOG_WARNING; /* default maximum log level */
const char *coap_package_name(void) {
return PACKAGE_NAME;
}
const char *coap_package_version(void) {
return PACKAGE_STRING;
}
coap_log_t
coap_get_log_level(void) {
return maxlog;
}
void
coap_set_log_level(coap_log_t level) {
maxlog = level;
}
/* this array has the same order as the type log_t */
static char *loglevels[] = {
"EMRG", "ALRT", "CRIT", "ERR", "WARN", "NOTE", "INFO", "DEBG"
};
#ifdef HAVE_TIME_H
static inline size_t
print_timestamp(char *s, size_t len, coap_tick_t t) {
struct tm *tmp;
time_t now = clock_offset + (t / COAP_TICKS_PER_SECOND);
tmp = localtime(&now);
return strftime(s, len, "%b %d %H:%M:%S", tmp);
}
#else /* alternative implementation: just print the timestamp */
static inline size_t
print_timestamp(char *s, size_t len, coap_tick_t t) {
#ifdef HAVE_SNPRINTF
return snprintf(s, len, "%u.%03u",
(unsigned int)(clock_offset + (t / COAP_TICKS_PER_SECOND)),
(unsigned int)(t % COAP_TICKS_PER_SECOND));
#else /* HAVE_SNPRINTF */
/* @todo do manual conversion of timestamp */
return 0;
#endif /* HAVE_SNPRINTF */
}
#endif /* HAVE_TIME_H */
#ifndef NDEBUG
#ifndef HAVE_STRNLEN
/**
* A length-safe strlen() fake.
*
* @param s The string to count characters != 0.
* @param maxlen The maximum length of @p s.
*
* @return The length of @p s.
*/
static inline size_t
strnlen(const char *s, size_t maxlen) {
size_t n = 0;
while(*s++ && n < maxlen)
++n;
return n;
}
#endif /* HAVE_STRNLEN */
unsigned int
print_readable( const unsigned char *data, unsigned int len,
unsigned char *result, unsigned int buflen, int encode_always ) {
const unsigned char hex[] = "0123456789ABCDEF";
unsigned int cnt = 0;
assert(data || len == 0);
if (buflen == 0 || len == 0)
return 0;
while (len) {
if (!encode_always && isprint(*data)) {
if (cnt == buflen)
break;
*result++ = *data;
++cnt;
} else {
if (cnt+4 < buflen) {
*result++ = '\\';
*result++ = 'x';
*result++ = hex[(*data & 0xf0) >> 4];
*result++ = hex[*data & 0x0f];
cnt += 4;
} else
break;
}
++data; --len;
}
*result = '\0';
return cnt;
}
#ifndef min
#define min(a,b) ((a) < (b) ? (a) : (b))
#endif
size_t
coap_print_addr(const struct coap_address_t *addr, unsigned char *buf, size_t len) {
#ifdef HAVE_ARPA_INET_H
const void *addrptr = NULL;
in_port_t port;
unsigned char *p = buf;
switch (addr->addr.sa.sa_family) {
case AF_INET:
addrptr = &addr->addr.sin.sin_addr;
port = ntohs(addr->addr.sin.sin_port);
break;
case AF_INET6:
if (len < 7) /* do not proceed if buffer is even too short for [::]:0 */
return 0;
*p++ = '[';
addrptr = &addr->addr.sin6.sin6_addr;
port = ntohs(addr->addr.sin6.sin6_port);
break;
default:
memcpy(buf, "(unknown address type)", min(22, len));
return min(22, len);
}
if (inet_ntop(addr->addr.sa.sa_family, addrptr, (char *)p, len) == 0) {
perror("coap_print_addr");
return 0;
}
p += strnlen((char *)p, len);
if (addr->addr.sa.sa_family == AF_INET6) {
if (p < buf + len) {
*p++ = ']';
} else
return 0;
}
p += snprintf((char *)p, buf + len - p + 1, ":%d", port);
return buf + len - p;
#else /* HAVE_ARPA_INET_H */
# if WITH_CONTIKI
unsigned char *p = buf;
uint8_t i;
# if WITH_UIP6
const unsigned char hex[] = "0123456789ABCDEF";
if (len < 41)
return 0;
*p++ = '[';
for (i=0; i < 16; i += 2) {
if (i) {
*p++ = ':';
}
*p++ = hex[(addr->addr.u8[i] & 0xf0) >> 4];
*p++ = hex[(addr->addr.u8[i] & 0x0f)];
*p++ = hex[(addr->addr.u8[i+1] & 0xf0) >> 4];
*p++ = hex[(addr->addr.u8[i+1] & 0x0f)];
}
*p++ = ']';
# else /* WITH_UIP6 */
# warning "IPv4 network addresses will not be included in debug output"
if (len < 21)
return 0;
# endif /* WITH_UIP6 */
if (buf + len - p < 6)
return 0;
#ifdef HAVE_SNPRINTF
p += snprintf((char *)p, buf + len - p + 1, ":%d", uip_htons(addr->port));
#else /* HAVE_SNPRINTF */
/* @todo manual conversion of port number */
#endif /* HAVE_SNPRINTF */
return p - buf;
# else /* WITH_CONTIKI */
/* TODO: output addresses manually */
# warning "inet_ntop() not available, network addresses will not be included in debug output"
# endif /* WITH_CONTIKI */
return 0;
#endif
}
#ifdef WITH_CONTIKI
# define fprintf(fd, ...) PRINTF(__VA_ARGS__)
# define fflush(...)
# ifdef HAVE_VPRINTF
# define vfprintf(fd, ...) vprintf(__VA_ARGS__)
# else /* HAVE_VPRINTF */
# define vfprintf(fd, ...) PRINTF(__VA_ARGS__)
# endif /* HAVE_VPRINTF */
#endif /* WITH_CONTIKI */
void
coap_show_pdu(const coap_pdu_t *pdu) {
unsigned char buf[COAP_MAX_PDU_SIZE]; /* need some space for output creation */
int encode = 0, have_options = 0;
coap_opt_iterator_t opt_iter;
coap_opt_t *option;
fprintf(COAP_DEBUG_FD, "v:%d t:%d tkl:%d c:%d id:%u",
pdu->hdr->version, pdu->hdr->type,
pdu->hdr->token_length,
pdu->hdr->code, ntohs(pdu->hdr->id));
/* show options, if any */
coap_option_iterator_init((coap_pdu_t *)pdu, &opt_iter, COAP_OPT_ALL);
while ((option = coap_option_next(&opt_iter))) {
if (!have_options) {
have_options = 1;
fprintf(COAP_DEBUG_FD, " o: [");
} else {
fprintf(COAP_DEBUG_FD, ",");
}
if (opt_iter.type == COAP_OPTION_URI_PATH ||
opt_iter.type == COAP_OPTION_PROXY_URI ||
opt_iter.type == COAP_OPTION_URI_HOST ||
opt_iter.type == COAP_OPTION_LOCATION_PATH ||
opt_iter.type == COAP_OPTION_LOCATION_QUERY ||
opt_iter.type == COAP_OPTION_URI_PATH ||
opt_iter.type == COAP_OPTION_URI_QUERY) {
encode = 0;
} else {
encode = 1;
}
if (print_readable(COAP_OPT_VALUE(option),
COAP_OPT_LENGTH(option),
buf, sizeof(buf), encode ))
fprintf(COAP_DEBUG_FD, " %d:'%s'", opt_iter.type, buf);
}
if (have_options)
fprintf(COAP_DEBUG_FD, " ]");
if (pdu->data) {
assert(pdu->data < (unsigned char *)pdu->hdr + pdu->length);
print_readable(pdu->data,
(unsigned char *)pdu->hdr + pdu->length - pdu->data,
buf, sizeof(buf), 0 );
fprintf(COAP_DEBUG_FD, " d:%s", buf);
}
fprintf(COAP_DEBUG_FD, "\n");
fflush(COAP_DEBUG_FD);
}
#endif /* NDEBUG */
void
coap_log_impl(coap_log_t level, const char *format, ...) {
char timebuf[32];
coap_tick_t now;
va_list ap;
FILE *log_fd;
if (maxlog < level)
return;
log_fd = level <= LOG_CRIT ? COAP_ERR_FD : COAP_DEBUG_FD;
coap_ticks(&now);
if (print_timestamp(timebuf,sizeof(timebuf), now))
fprintf(log_fd, "%s ", timebuf);
if (level <= LOG_DEBUG)
fprintf(log_fd, "%s ", loglevels[level]);
va_start(ap, format);
vfprintf(log_fd, format, ap);
va_end(ap);
fflush(log_fd);
}
+48
View File
@@ -0,0 +1,48 @@
/* encode.c -- encoding and decoding of CoAP data types
*
* Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
*
* This file is part of the CoAP library libcoap. Please see
* README for terms of use.
*/
#ifndef NDEBUG
# include <stdio.h>
#endif
#include "coap_config.h"
#include "encode.h"
/* Carsten suggested this when fls() is not available: */
int coap_fls(unsigned int i) {
int n;
for (n = 0; i; n++)
i >>= 1;
return n;
}
unsigned int
coap_decode_var_bytes(unsigned char *buf,unsigned int len) {
unsigned int i, n = 0;
for (i = 0; i < len; ++i)
n = (n << 8) + buf[i];
return n;
}
unsigned int
coap_encode_var_bytes(unsigned char *buf, unsigned int val) {
unsigned int n, i;
for (n = 0, i = val; i && n < sizeof(val); ++n)
i >>= 8;
i = n;
while (i--) {
buf[i] = val & 0xff;
val >>= 8;
}
return n;
}
+29
View File
@@ -0,0 +1,29 @@
/* hashkey.c -- definition of hash key type and helper functions
*
* Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
*
* This file is part of the CoAP library libcoap. Please see
* README for terms of use.
*/
#include "hashkey.h"
/* Caution: When changing this, update COAP_DEFAULT_WKC_HASHKEY
* accordingly (see int coap_hash_path());
*/
void
coap_hash_impl(const unsigned char *s, unsigned int len, coap_key_t h) {
size_t j;
while (len--) {
j = sizeof(coap_key_t)-1;
while (j) {
h[j] = ((h[j] << 7) | (h[j-1] >> 1)) + h[j];
--j;
}
h[0] = (h[0] << 7) + h[0] + *s++;
}
}
+114
View File
@@ -0,0 +1,114 @@
/* mem.c -- CoAP memory handling
*
* Copyright (C) 2014--2015 Olaf Bergmann <bergmann@tzi.org>
*
* This file is part of the CoAP library libcoap. Please see
* README for terms of use.
*/
#include "coap_config.h"
#include "mem.h"
#include "debug.h"
#ifdef HAVE_ASSERT_H
#include <assert.h>
#else /* HAVE_ASSERT_H */
#define assert(...)
#endif /* HAVE_ASSERT_H */
#ifdef HAVE_MALLOC
#include <stdlib.h>
void
coap_memory_init(void) {
}
#ifdef __GNUC__
#define UNUSED_PARAM __attribute__((unused))
#else
#define UNUSED_PARAM
#endif /* __GNUC__ */
void *
coap_malloc_type(coap_memory_tag_t type UNUSED_PARAM, size_t size) {
return malloc(size);
}
void
coap_free_type(coap_memory_tag_t type UNUSED_PARAM, void *p) {
free(p);
}
#else /* HAVE_MALLOC */
#ifdef WITH_CONTIKI
#define COAP_MAX_STRING_SIZE 12
#define COAP_MAX_STRINGS 8
struct coap_string_t {
char data[COAP_MAX_STRING_SIZE];
};
#include "coap_config.h"
#include "net.h"
#include "pdu.h"
#include "coap_io.h"
#define COAP_MAX_PACKET_SIZE (sizeof(coap_packet_t) + COAP_MAX_PDU_SIZE)
#define COAP_MAX_PACKETS 2
typedef union {
coap_pdu_t packet; /* try to convince the compiler to word-align this structure */
char buf[COAP_MAX_PACKET_SIZE];
} coap_packetbuf_t;
MEMB(string_storage, struct coap_string_t, COAP_MAX_STRINGS);
MEMB(packet_storage, coap_packetbuf_t, COAP_MAX_PACKETS);
MEMB(node_storage, coap_queue_t, COAP_PDU_MAXCNT);
MEMB(pdu_storage, coap_pdu_t, COAP_PDU_MAXCNT);
MEMB(pdu_buf_storage, coap_packetbuf_t, COAP_PDU_MAXCNT);
static struct memb *
get_container(coap_memory_tag_t type) {
switch(type) {
case COAP_PACKET: return &packet_storage;
case COAP_NODE: return &node_storage;
case COAP_PDU: return &pdu_storage;
case COAP_PDU_BUF: return &pdu_buf_storage;
default:
return &string_storage;
}
}
void
coap_memory_init(void) {
memb_init(&string_storage);
memb_init(&packet_storage);
memb_init(&node_storage);
memb_init(&pdu_storage);
memb_init(&pdu_buf_storage);
}
void *
coap_malloc_type(coap_memory_tag_t type, size_t size) {
struct memb *container = get_container(type);
assert(container);
if (size > container->size) {
debug("coap_malloc_type: Requested memory exceeds maximum object size\n");
return NULL;
}
return memb_alloc(container);
}
void
coap_free_type(coap_memory_tag_t type, void *object) {
memb_free(get_container(type), object);
}
#endif /* WITH_CONTIKI */
#endif /* HAVE_MALLOC */
+1748
View File
File diff suppressed because it is too large. Load diff
+408
View File
@@ -0,0 +1,408 @@
/*
* option.c -- helpers for handling options in CoAP PDUs
*
* Copyright (C) 2010-2013 Olaf Bergmann <bergmann@tzi.org>
*
* This file is part of the CoAP library libcoap. Please see
* README for terms of use.
*/
#include "coap_config.h"
#if defined(HAVE_ASSERT_H) && !defined(assert)
# include <assert.h>
#endif
#include <stdio.h>
#include <string.h>
#include "option.h"
#include "debug.h"
coap_opt_t *
options_start(coap_pdu_t *pdu) {
if (pdu && pdu->hdr &&
(pdu->hdr->token + pdu->hdr->token_length
< (unsigned char *)pdu->hdr + pdu->length)) {
coap_opt_t *opt = pdu->hdr->token + pdu->hdr->token_length;
return (*opt == COAP_PAYLOAD_START) ? NULL : opt;
} else
return NULL;
}
size_t
coap_opt_parse(const coap_opt_t *opt, size_t length, coap_option_t *result) {
const coap_opt_t *opt_start = opt; /* store where parsing starts */
assert(opt); assert(result);
#define ADVANCE_OPT(o,e,step) if ((e) < step) { \
debug("cannot advance opt past end\n"); \
return 0; \
} else { \
(e) -= step; \
(o) = ((unsigned char *)(o)) + step; \
}
if (length < 1)
return 0;
result->delta = (*opt & 0xf0) >> 4;
result->length = *opt & 0x0f;
switch(result->delta) {
case 15:
if (*opt != COAP_PAYLOAD_START) {
debug("ignored reserved option delta 15\n");
}
return 0;
case 14:
/* Handle two-byte value: First, the MSB + 269 is stored as delta value.
* After that, the option pointer is advanced to the LSB which is handled
* just like case delta == 13. */
ADVANCE_OPT(opt,length,1);
result->delta = ((*opt & 0xff) << 8) + 269;
if (result->delta < 269) {
debug("delta too large\n");
return 0;
}
/* fall through */
case 13:
ADVANCE_OPT(opt,length,1);
result->delta += *opt & 0xff;
break;
default:
;
}
switch(result->length) {
case 15:
debug("found reserved option length 15\n");
return 0;
case 14:
/* Handle two-byte value: First, the MSB + 269 is stored as delta value.
* After that, the option pointer is advanced to the LSB which is handled
* just like case delta == 13. */
ADVANCE_OPT(opt,length,1);
result->length = ((*opt & 0xff) << 8) + 269;
/* fall through */
case 13:
ADVANCE_OPT(opt,length,1);
result->length += *opt & 0xff;
break;
default:
;
}
ADVANCE_OPT(opt,length,1);
/* opt now points to value, if present */
result->value = (unsigned char *)opt;
if (length < result->length) {
debug("invalid option length\n");
return 0;
}
#undef ADVANCE_OPT
return (opt + result->length) - opt_start;
}
coap_opt_iterator_t *
coap_option_iterator_init(coap_pdu_t *pdu, coap_opt_iterator_t *oi,
const coap_opt_filter_t filter) {
assert(pdu);
assert(pdu->hdr);
assert(oi);
memset(oi, 0, sizeof(coap_opt_iterator_t));
oi->next_option = (unsigned char *)pdu->hdr + sizeof(coap_hdr_t)
+ pdu->hdr->token_length;
if ((unsigned char *)pdu->hdr + pdu->length <= oi->next_option) {
oi->bad = 1;
return NULL;
}
assert((sizeof(coap_hdr_t) + pdu->hdr->token_length) <= pdu->length);
oi->length = pdu->length - (sizeof(coap_hdr_t) + pdu->hdr->token_length);
if (filter) {
memcpy(oi->filter, filter, sizeof(coap_opt_filter_t));
oi->filtered = 1;
}
return oi;
}
static inline int
opt_finished(coap_opt_iterator_t *oi) {
assert(oi);
if (oi->bad || oi->length == 0 ||
!oi->next_option || *oi->next_option == COAP_PAYLOAD_START) {
oi->bad = 1;
}
return oi->bad;
}
coap_opt_t *
coap_option_next(coap_opt_iterator_t *oi) {
coap_option_t option;
coap_opt_t *current_opt = NULL;
size_t optsize;
int b; /* to store result of coap_option_getb() */
assert(oi);
if (opt_finished(oi))
return NULL;
while (1) {
/* oi->option always points to the next option to deliver; as
* opt_finished() filters out any bad conditions, we can assume that
* oi->option is valid. */
current_opt = oi->next_option;
/* Advance internal pointer to next option, skipping any option that
* is not included in oi->filter. */
optsize = coap_opt_parse(oi->next_option, oi->length, &option);
if (optsize) {
assert(optsize <= oi->length);
oi->next_option += optsize;
oi->length -= optsize;
oi->type += option.delta;
} else { /* current option is malformed */
oi->bad = 1;
return NULL;
}
/* Exit the while loop when:
* - no filtering is done at all
* - the filter matches for the current option
* - the filter is too small for the current option number
*/
if (!oi->filtered ||
(b = coap_option_getb(oi->filter, oi->type)) > 0)
break;
else if (b < 0) { /* filter too small, cannot proceed */
oi->bad = 1;
return NULL;
}
}
return current_opt;
}
coap_opt_t *
coap_check_option(coap_pdu_t *pdu, unsigned char type,
coap_opt_iterator_t *oi) {
coap_opt_filter_t f;
coap_option_filter_clear(f);
coap_option_setb(f, type);
coap_option_iterator_init(pdu, oi, f);
return coap_option_next(oi);
}
unsigned short
coap_opt_delta(const coap_opt_t *opt) {
unsigned short n;
n = (*opt++ & 0xf0) >> 4;
switch (n) {
case 15: /* error */
warn("coap_opt_delta: illegal option delta\n");
/* This case usually should not happen, hence we do not have a
* proper way to indicate an error. */
return 0;
case 14:
/* Handle two-byte value: First, the MSB + 269 is stored as delta value.
* After that, the option pointer is advanced to the LSB which is handled
* just like case delta == 13. */
n = ((*opt++ & 0xff) << 8) + 269;
/* fall through */
case 13:
n += *opt & 0xff;
break;
default: /* n already contains the actual delta value */
;
}
return n;
}
unsigned short
coap_opt_length(const coap_opt_t *opt) {
unsigned short length;
length = *opt & 0x0f;
switch (*opt & 0xf0) {
case 0xf0:
debug("illegal option delta\n");
return 0;
case 0xe0:
++opt;
/* fall through to skip another byte */
case 0xd0:
++opt;
/* fall through to skip another byte */
default:
++opt;
}
switch (length) {
case 0x0f:
debug("illegal option length\n");
return 0;
case 0x0e:
length = (*opt++ << 8) + 269;
/* fall through */
case 0x0d:
length += *opt++;
break;
default:
;
}
return length;
}
unsigned char *
coap_opt_value(coap_opt_t *opt) {
size_t ofs = 1;
switch (*opt & 0xf0) {
case 0xf0:
debug("illegal option delta\n");
return 0;
case 0xe0:
++ofs;
/* fall through */
case 0xd0:
++ofs;
break;
default:
;
}
switch (*opt & 0x0f) {
case 0x0f:
debug("illegal option length\n");
return 0;
case 0x0e:
++ofs;
/* fall through */
case 0x0d:
++ofs;
break;
default:
;
}
return (unsigned char *)opt + ofs;
}
size_t
coap_opt_size(const coap_opt_t *opt) {
coap_option_t option;
/* we must assume that opt is encoded correctly */
return coap_opt_parse(opt, (size_t)-1, &option);
}
size_t
coap_opt_setheader(coap_opt_t *opt, size_t maxlen,
unsigned short delta, size_t length) {
size_t skip = 0;
assert(opt);
if (maxlen == 0) /* need at least one byte */
return 0;
if (delta < 13) {
opt[0] = delta << 4;
} else if (delta < 270) {
if (maxlen < 2) {
debug("insufficient space to encode option delta %d", delta);
return 0;
}
opt[0] = 0xd0;
opt[++skip] = delta - 13;
} else {
if (maxlen < 3) {
debug("insufficient space to encode option delta %d", delta);
return 0;
}
opt[0] = 0xe0;
opt[++skip] = ((delta - 269) >> 8) & 0xff;
opt[++skip] = (delta - 269) & 0xff;
}
if (length < 13) {
opt[0] |= length & 0x0f;
} else if (length < 270) {
if (maxlen < skip + 1) {
debug("insufficient space to encode option length %zu", length);
return 0;
}
opt[0] |= 0x0d;
opt[++skip] = length - 13;
} else {
if (maxlen < skip + 2) {
debug("insufficient space to encode option delta %d", delta);
return 0;
}
opt[0] |= 0x0e;
opt[++skip] = ((length - 269) >> 8) & 0xff;
opt[++skip] = (length - 269) & 0xff;
}
return skip + 1;
}
size_t
coap_opt_encode(coap_opt_t *opt, size_t maxlen, unsigned short delta,
const unsigned char *val, size_t length) {
size_t l = 1;
l = coap_opt_setheader(opt, maxlen, delta, length);
assert(l <= maxlen);
if (!l) {
debug("coap_opt_encode: cannot set option header\n");
return 0;
}
maxlen -= l;
opt += l;
if (maxlen < length) {
debug("coap_opt_encode: option too large for buffer\n");
return 0;
}
if (val) /* better be safe here */
memcpy(opt, val, length);
return l + length;
}
+425
View File
@@ -0,0 +1,425 @@
/* pdu.c -- CoAP message structure
*
* Copyright (C) 2010--2014 Olaf Bergmann <bergmann@tzi.org>
*
* This file is part of the CoAP library libcoap. Please see
* README for terms of use.
*/
#include "coap_config.h"
#if defined(HAVE_ASSERT_H) && !defined(assert)
# include <assert.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#include "debug.h"
#include "pdu.h"
#include "option.h"
#include "encode.h"
#include "mem.h"
void
coap_pdu_clear(coap_pdu_t *pdu, size_t size) {
assert(pdu);
#ifdef WITH_LWIP
/* the pdu itself is not wiped as opposed to the other implementations,
* because we have to rely on the pbuf to be set there. */
pdu->hdr = pdu->pbuf->payload;
#else
pdu->max_delta = 0;
pdu->data = NULL;
#endif
memset(pdu->hdr, 0, size);
pdu->max_size = size;
pdu->hdr->version = COAP_DEFAULT_VERSION;
/* data is NULL unless explicitly set by coap_add_data() */
pdu->length = sizeof(coap_hdr_t);
}
#ifdef WITH_LWIP
coap_pdu_t *
coap_pdu_from_pbuf(struct pbuf *pbuf)
{
if (pbuf == NULL) return NULL;
LWIP_ASSERT("Can only deal with contiguous PBUFs", pbuf->tot_len == pbuf->len);
LWIP_ASSERT("coap_read needs to receive an exclusive copy of the incoming pbuf", pbuf->ref == 1);
coap_pdu_t *result = coap_malloc_type(COAP_PDU, sizeof(coap_pdu_t));
if (!result) {
pbuf_free(pbuf);
return NULL;
}
memset(result, 0, sizeof(coap_pdu_t));
result->max_size = pbuf->tot_len;
result->length = pbuf->tot_len;
result->hdr = pbuf->payload;
result->pbuf = pbuf;
return result;
}
#endif
coap_pdu_t *
coap_pdu_init(unsigned char type, unsigned char code,
unsigned short id, size_t size) {
coap_pdu_t *pdu;
#ifdef WITH_LWIP
struct pbuf *p;
#endif
assert(size <= COAP_MAX_PDU_SIZE);
/* Size must be large enough to fit the header. */
if (size < sizeof(coap_hdr_t) || size > COAP_MAX_PDU_SIZE)
return NULL;
/* size must be large enough for hdr */
#if defined(WITH_POSIX) || defined(WITH_CONTIKI)
pdu = coap_malloc_type(COAP_PDU, sizeof(coap_pdu_t));
if (!pdu) return NULL;
pdu->hdr = coap_malloc_type(COAP_PDU_BUF, size);
if (pdu->hdr == NULL) {
coap_free_type(COAP_PDU, pdu);
pdu = NULL;
}
#endif /* WITH_POSIX or WITH_CONTIKI */
#ifdef WITH_LWIP
pdu = (coap_pdu_t*)coap_malloc_type(COAP_PDU, sizeof(coap_pdu_t));
if (!pdu) return NULL;
p = pbuf_alloc(PBUF_TRANSPORT, size, PBUF_RAM);
if (p == NULL) {
coap_free_type(COAP_PDU, pdu);
pdu = NULL;
}
#endif
if (pdu) {
#ifdef WITH_LWIP
pdu->pbuf = p;
#endif
coap_pdu_clear(pdu, size);
pdu->hdr->id = id;
pdu->hdr->type = type;
pdu->hdr->code = code;
}
return pdu;
}
coap_pdu_t *
coap_new_pdu(void) {
coap_pdu_t *pdu;
#ifndef WITH_CONTIKI
pdu = coap_pdu_init(0, 0, ntohs(COAP_INVALID_TID), COAP_MAX_PDU_SIZE);
#else /* WITH_CONTIKI */
pdu = coap_pdu_init(0, 0, uip_ntohs(COAP_INVALID_TID), COAP_MAX_PDU_SIZE);
#endif /* WITH_CONTIKI */
#ifndef NDEBUG
if (!pdu)
coap_log(LOG_CRIT, "coap_new_pdu: cannot allocate memory for new PDU\n");
#endif
return pdu;
}
void
coap_delete_pdu(coap_pdu_t *pdu) {
#if defined(WITH_POSIX) || defined(WITH_CONTIKI)
if (pdu != NULL) {
if (pdu->hdr != NULL) {
coap_free_type(COAP_PDU_BUF, pdu->hdr);
}
coap_free_type(COAP_PDU, pdu);
}
#endif
#ifdef WITH_LWIP
if (pdu != NULL) /* accepting double free as the other implementation accept that too */
pbuf_free(pdu->pbuf);
coap_free_type(COAP_PDU, pdu);
#endif
}
int
coap_add_token(coap_pdu_t *pdu, size_t len, const unsigned char *data) {
const size_t HEADERLENGTH = len + 4;
/* must allow for pdu == NULL as callers may rely on this */
if (!pdu || len > 8 || pdu->max_size < HEADERLENGTH)
return 0;
pdu->hdr->token_length = len;
if (len)
memcpy(pdu->hdr->token, data, len);
pdu->max_delta = 0;
pdu->length = HEADERLENGTH;
pdu->data = NULL;
return 1;
}
/** @FIXME de-duplicate code with coap_add_option_later */
size_t
coap_add_option(coap_pdu_t *pdu, unsigned short type, unsigned int len, const unsigned char *data) {
size_t optsize;
coap_opt_t *opt;
assert(pdu);
pdu->data = NULL;
if (type < pdu->max_delta) {
warn("coap_add_option: options are not in correct order\n");
return 0;
}
opt = (unsigned char *)pdu->hdr + pdu->length;
/* encode option and check length */
optsize = coap_opt_encode(opt, pdu->max_size - pdu->length,
type - pdu->max_delta, data, len);
if (!optsize) {
warn("coap_add_option: cannot add option\n");
/* error */
return 0;
} else {
pdu->max_delta = type;
pdu->length += optsize;
}
return optsize;
}
/** @FIXME de-duplicate code with coap_add_option */
unsigned char*
coap_add_option_later(coap_pdu_t *pdu, unsigned short type, unsigned int len) {
size_t optsize;
coap_opt_t *opt;
assert(pdu);
pdu->data = NULL;
if (type < pdu->max_delta) {
warn("coap_add_option: options are not in correct order\n");
return NULL;
}
opt = (unsigned char *)pdu->hdr + pdu->length;
/* encode option and check length */
optsize = coap_opt_encode(opt, pdu->max_size - pdu->length,
type - pdu->max_delta, NULL, len);
if (!optsize) {
warn("coap_add_option: cannot add option\n");
/* error */
return NULL;
} else {
pdu->max_delta = type;
pdu->length += optsize;
}
return ((unsigned char*)opt) + optsize - len;
}
int
coap_add_data(coap_pdu_t *pdu, unsigned int len, const unsigned char *data) {
assert(pdu);
assert(pdu->data == NULL);
if (len == 0)
return 1;
if (pdu->length + len + 1 > pdu->max_size) {
warn("coap_add_data: cannot add: data too large for PDU\n");
assert(pdu->data == NULL);
return 0;
}
pdu->data = (unsigned char *)pdu->hdr + pdu->length;
*pdu->data = COAP_PAYLOAD_START;
pdu->data++;
memcpy(pdu->data, data, len);
pdu->length += len + 1;
return 1;
}
int
coap_get_data(coap_pdu_t *pdu, size_t *len, unsigned char **data) {
assert(pdu);
assert(len);
assert(data);
if (pdu->data) {
*len = (unsigned char *)pdu->hdr + pdu->length - pdu->data;
*data = pdu->data;
} else { /* no data, clear everything */
*len = 0;
*data = NULL;
}
return *data != NULL;
}
#ifndef SHORT_ERROR_RESPONSE
typedef struct {
unsigned char code;
char *phrase;
} error_desc_t;
/* if you change anything here, make sure, that the longest string does not
* exceed COAP_ERROR_PHRASE_LENGTH. */
error_desc_t coap_error[] = {
{ COAP_RESPONSE_CODE(65), "2.01 Created" },
{ COAP_RESPONSE_CODE(66), "2.02 Deleted" },
{ COAP_RESPONSE_CODE(67), "2.03 Valid" },
{ COAP_RESPONSE_CODE(68), "2.04 Changed" },
{ COAP_RESPONSE_CODE(69), "2.05 Content" },
{ COAP_RESPONSE_CODE(400), "Bad Request" },
{ COAP_RESPONSE_CODE(401), "Unauthorized" },
{ COAP_RESPONSE_CODE(402), "Bad Option" },
{ COAP_RESPONSE_CODE(403), "Forbidden" },
{ COAP_RESPONSE_CODE(404), "Not Found" },
{ COAP_RESPONSE_CODE(405), "Method Not Allowed" },
{ COAP_RESPONSE_CODE(408), "Request Entity Incomplete" },
{ COAP_RESPONSE_CODE(413), "Request Entity Too Large" },
{ COAP_RESPONSE_CODE(415), "Unsupported Media Type" },
{ COAP_RESPONSE_CODE(500), "Internal Server Error" },
{ COAP_RESPONSE_CODE(501), "Not Implemented" },
{ COAP_RESPONSE_CODE(502), "Bad Gateway" },
{ COAP_RESPONSE_CODE(503), "Service Unavailable" },
{ COAP_RESPONSE_CODE(504), "Gateway Timeout" },
{ COAP_RESPONSE_CODE(505), "Proxying Not Supported" },
{ 0, NULL } /* end marker */
};
char *
coap_response_phrase(unsigned char code) {
int i;
for (i = 0; coap_error[i].code; ++i) {
if (coap_error[i].code == code)
return coap_error[i].phrase;
}
return NULL;
}
#endif
/**
* Advances *optp to next option if still in PDU. This function
* returns the number of bytes opt has been advanced or @c 0
* on error.
*/
static size_t
next_option_safe(coap_opt_t **optp, size_t *length) {
coap_option_t option;
size_t optsize;
assert(optp); assert(*optp);
assert(length);
optsize = coap_opt_parse(*optp, *length, &option);
if (optsize) {
assert(optsize <= *length);
*optp += optsize;
*length -= optsize;
}
return optsize;
}
int
coap_pdu_parse(unsigned char *data, size_t length, coap_pdu_t *pdu) {
coap_opt_t *opt;
assert(data);
assert(pdu);
if (pdu->max_size < length) {
debug("insufficient space to store parsed PDU\n");
return 0;
}
if (length < sizeof(coap_hdr_t)) {
debug("discarded invalid PDU\n");
}
#ifdef WITH_LWIP
LWIP_ASSERT("coap_pdu_parse with unexpected addresses", data == pdu->hdr);
LWIP_ASSERT("coap_pdu_parse with unexpected length", length == pdu->length);
#else
pdu->hdr->version = data[0] >> 6;
pdu->hdr->type = (data[0] >> 4) & 0x03;
pdu->hdr->token_length = data[0] & 0x0f;
pdu->hdr->code = data[1];
#endif
pdu->data = NULL;
/* sanity checks */
if (pdu->hdr->code == 0) {
if (length != sizeof(coap_hdr_t) || pdu->hdr->token_length) {
debug("coap_pdu_parse: empty message is not empty\n");
goto discard;
}
}
if (length < sizeof(coap_hdr_t) + pdu->hdr->token_length
|| pdu->hdr->token_length > 8) {
debug("coap_pdu_parse: invalid Token\n");
goto discard;
}
#ifndef WITH_LWIP
/* Copy message id in network byte order, so we can easily write the
* response back to the network. */
memcpy(&pdu->hdr->id, data + 2, 2);
/* append data (including the Token) to pdu structure */
memcpy(pdu->hdr + 1, data + sizeof(coap_hdr_t), length - sizeof(coap_hdr_t));
pdu->length = length;
/* Finally calculate beginning of data block and thereby check integrity
* of the PDU structure. */
#endif
/* skip header + token */
length -= (pdu->hdr->token_length + sizeof(coap_hdr_t));
opt = (unsigned char *)(pdu->hdr + 1) + pdu->hdr->token_length;
while (length && *opt != COAP_PAYLOAD_START) {
if (!next_option_safe(&opt, (size_t *)&length)) {
debug("coap_pdu_parse: drop\n");
goto discard;
}
}
/* end of packet or start marker */
if (length) {
assert(*opt == COAP_PAYLOAD_START);
opt++; length--;
if (!length) {
debug("coap_pdu_parse: message ending in payload start marker\n");
goto discard;
}
debug("set data to %p (pdu ends at %p)\n", (unsigned char *)opt,
(unsigned char *)pdu->hdr + pdu->length);
pdu->data = (unsigned char *)opt;
}
return 1;
discard:
return 0;
}
+953
View File
@@ -0,0 +1,953 @@
/* resource.c -- generic resource handling
*
* Copyright (C) 2010--2014 Olaf Bergmann <bergmann@tzi.org>
*
* This file is part of the CoAP library libcoap. Please see
* README for terms of use.
*/
#include "coap_config.h"
#include "net.h"
#include "debug.h"
#include "resource.h"
#include "subscribe.h"
#ifdef WITH_LWIP
#include "utlist.h"
/* mem.h is only needed for the string free calls for
* COAP_ATTR_FLAGS_RELEASE_NAME / COAP_ATTR_FLAGS_RELEASE_VALUE /
* COAP_RESOURCE_FLAGS_RELEASE_URI. not sure what those lines should actually
* do on lwip. */
#include "mem.h"
#include <lwip/memp.h>
#define COAP_MALLOC_TYPE(Type) \
((coap_##Type##_t *)memp_malloc(MEMP_COAP_##Type))
#define COAP_FREE_TYPE(Type, Object) memp_free(MEMP_COAP_##Type, Object)
#endif
#ifdef WITH_POSIX
#include "utlist.h"
#include "mem.h"
#define COAP_MALLOC_TYPE(Type) \
((coap_##Type##_t *)coap_malloc(sizeof(coap_##Type##_t)))
#define COAP_FREE_TYPE(Type, Object) coap_free(Object)
coap_iterator_t *
coap_iterator_init(void *storage, coap_iterator_t *ri) {
assert(storage);
assert(ri);
ri->data = storage;
ri->pos = 0;
return ri;
}
struct thing {
struct thing *next;
};
void *
coap_iterator_next(coap_iterator_t *ri) {
void *item;
assert(ri);
item = ri->data;
if (ri->data != NULL) {
ri->data = ((struct thing *)ri->data)->next;
}
return item;
}
#endif /* WITH_POSIX */
#ifdef WITH_CONTIKI
#include "mem.h"
#include "memb.h"
#define COAP_MALLOC_TYPE(Type) \
((coap_##Type##_t *)memb_alloc(&(Type##_storage)))
#define COAP_FREE_TYPE(Type, Object) memb_free(&(Type##_storage), (Object))
MEMB(resource_storage, coap_resource_t, COAP_MAX_RESOURCES);
MEMB(attribute_storage, coap_attr_t, COAP_MAX_ATTRIBUTES);
MEMB(subscription_storage, coap_subscription_t, COAP_MAX_SUBSCRIBERS);
void
coap_resources_init() {
memb_init(&resource_storage);
memb_init(&attribute_storage);
memb_init(&subscription_storage);
}
static inline coap_subscription_t *
coap_malloc_subscription() {
return memb_alloc(&subscription_storage);
}
static inline void
coap_free_subscription(coap_subscription_t *subscription) {
memb_free(&subscription_storage, subscription);
}
coap_iterator_t *
coap_iterator_init(void *storage, coap_iterator_t *ri) {
assert(storage);
assert(ri);
ri->data = storage;
ri->pos = 0;
return ri;
}
void *
coap_iterator_next(coap_iterator_t *ri) {
struct memb *m;
void *result = NULL;
assert(ri);
m = (struct memb *)ri->data;
while (!result && (ri->pos < m->num)) {
if (m->count[ri->pos]) {
result = (void *)((char *)m->mem + (ri->pos * m->size));
}
++ri->pos;
}
return result;
}
coap_iterator_t *
coap_resource_iterator_init(struct coap_resource_t *resources,
coap_iterator_t *ri) {
/* For Contiki, the resources component of coap_context_t is not used... */
return coap_iterator_init(&resource_storage, ri);
}
coap_resource_t *
coap_resource_next(coap_iterator_t *ri) {
return (coap_resource_t *)coap_iterator_next(ri);
}
#endif /* WITH_CONTIKI */
#define min(a,b) ((a) < (b) ? (a) : (b))
/* Helper functions for conditional output of character sequences into
* a given buffer. The first Offset characters are skipped.
*/
/**
* Adds Char to Buf if Offset is zero. Otherwise, Char is not written
* and Offset is decremented.
*/
#define PRINT_WITH_OFFSET(Buf,Offset,Char) \
if ((Offset) == 0) { \
(*(Buf)++) = (Char); \
} else { \
(Offset)--; \
} \
/**
* Adds Char to Buf if Offset is zero and Buf is less than Bufend.
*/
#define PRINT_COND_WITH_OFFSET(Buf,Bufend,Offset,Char,Result) { \
if ((Buf) < (Bufend)) { \
PRINT_WITH_OFFSET(Buf,Offset,Char); \
} \
(Result)++; \
}
/**
* Copies at most Length characters of Str to Buf. The first Offset
* characters are skipped. Output may be truncated to Bufend - Buf
* characters.
*/
#define COPY_COND_WITH_OFFSET(Buf,Bufend,Offset,Str,Length,Result) { \
size_t i; \
for (i = 0; i < (Length); i++) { \
PRINT_COND_WITH_OFFSET((Buf), (Bufend), (Offset), (Str)[i], (Result)); \
} \
}
int
match(const str *text, const str *pattern, int match_prefix, int match_substring) {
assert(text); assert(pattern);
if (text->length < pattern->length)
return 0;
if (match_substring) {
unsigned char *next_token = text->s;
size_t remaining_length = text->length;
while (remaining_length) {
size_t token_length;
unsigned char *token = next_token;
next_token = memchr(token, ' ', remaining_length);
if (next_token) {
token_length = next_token - token;
remaining_length -= (token_length + 1);
next_token++;
} else {
token_length = remaining_length;
remaining_length = 0;
}
if ((match_prefix || pattern->length == token_length) &&
memcmp(token, pattern->s, pattern->length) == 0)
return 1;
}
return 0;
}
return (match_prefix || pattern->length == text->length) &&
memcmp(text->s, pattern->s, pattern->length) == 0;
}
/**
* Prints the names of all known resources to @p buf. This function
* sets @p buflen to the number of bytes actually written and returns
* @c 1 on succes. On error, the value in @p buflen is undefined and
* the return value will be @c 0.
*
* @param context The context with the resource map.
* @param buf The buffer to write the result.
* @param buflen Must be initialized to the maximum length of @p buf and will be
* set to the length of the well-known response on return.
* @param offset The offset in bytes where the output shall start and is
* shifted accordingly with the characters that have been
* processed. This parameter is used to support the block
* option.
* @param query_filter A filter query according to <a href="http://tools.ietf.org/html/draft-ietf-core-link-format-11#section-4.1">Link Format</a>
*
* @return COAP_PRINT_STATUS_ERROR on error. Otherwise, the lower 28 bits are
* set to the number of bytes that have actually been written to
* @p buf. COAP_PRINT_STATUS_TRUNC is set when the output has been
* truncated.
*/
#if defined(__GNUC__) && defined(WITHOUT_QUERY_FILTER)
coap_print_status_t
print_wellknown(coap_context_t *context, unsigned char *buf, size_t *buflen,
size_t offset,
coap_opt_t *query_filter __attribute__ ((unused))) {
#else /* not a GCC */
coap_print_status_t
print_wellknown(coap_context_t *context, unsigned char *buf, size_t *buflen,
size_t offset, coap_opt_t *query_filter) {
#endif /* GCC */
coap_resource_t *r;
unsigned char *p = buf;
const unsigned char *bufend = buf + *buflen;
size_t left, written = 0;
coap_print_status_t result;
const size_t old_offset = offset;
int subsequent_resource = 0;
#ifndef COAP_RESOURCES_NOHASH
coap_resource_t *tmp;
#endif
#ifndef WITHOUT_QUERY_FILTER
str resource_param = { 0, NULL }, query_pattern = { 0, NULL };
int flags = 0; /* MATCH_SUBSTRING, MATCH_PREFIX, MATCH_URI */
#define MATCH_URI 0x01
#define MATCH_PREFIX 0x02
#define MATCH_SUBSTRING 0x04
static const str _rt_attributes[] = {
{2, (unsigned char *)"rt"},
{2, (unsigned char *)"if"},
{3, (unsigned char *)"rel"},
{0, NULL}};
#endif /* WITHOUT_QUERY_FILTER */
#ifdef WITH_CONTIKI
int i;
#endif /* WITH_CONTIKI */
#ifndef WITHOUT_QUERY_FILTER
/* split query filter, if any */
if (query_filter) {
resource_param.s = COAP_OPT_VALUE(query_filter);
while (resource_param.length < COAP_OPT_LENGTH(query_filter)
&& resource_param.s[resource_param.length] != '=')
resource_param.length++;
if (resource_param.length < COAP_OPT_LENGTH(query_filter)) {
const str *rt_attributes;
if (resource_param.length == 4 &&
memcmp(resource_param.s, "href", 4) == 0)
flags |= MATCH_URI;
for (rt_attributes = _rt_attributes; rt_attributes->s; rt_attributes++) {
if (resource_param.length == rt_attributes->length &&
memcmp(resource_param.s, rt_attributes->s, rt_attributes->length) == 0) {
flags |= MATCH_SUBSTRING;
break;
}
}
/* rest is query-pattern */
query_pattern.s =
COAP_OPT_VALUE(query_filter) + resource_param.length + 1;
assert((resource_param.length + 1) <= COAP_OPT_LENGTH(query_filter));
query_pattern.length =
COAP_OPT_LENGTH(query_filter) - (resource_param.length + 1);
if ((query_pattern.s[0] == '/') && ((flags & MATCH_URI) == MATCH_URI)) {
query_pattern.s++;
query_pattern.length--;
}
if (query_pattern.length &&
query_pattern.s[query_pattern.length-1] == '*') {
query_pattern.length--;
flags |= MATCH_PREFIX;
}
}
}
#endif /* WITHOUT_QUERY_FILTER */
#ifndef WITH_CONTIKI
#ifdef COAP_RESOURCES_NOHASH
LL_FOREACH(context->resources, r) {
#else
HASH_ITER(hh, context->resources, r, tmp) {
#endif
#else /* WITH_CONTIKI */
r = (coap_resource_t *)resource_storage.mem;
for (i = 0; i < resource_storage.num; ++i, ++r) {
if (!resource_storage.count[i])
continue;
#endif /* WITH_CONTIKI */
#ifndef WITHOUT_QUERY_FILTER
if (resource_param.length) { /* there is a query filter */
if (flags & MATCH_URI) { /* match resource URI */
if (!match(&r->uri, &query_pattern, (flags & MATCH_PREFIX) != 0, (flags & MATCH_SUBSTRING) != 0))
continue;
} else { /* match attribute */
coap_attr_t *attr;
str unquoted_val;
attr = coap_find_attr(r, resource_param.s, resource_param.length);
if (!attr) continue;
if (attr->value.s[0] == '"') { /* if attribute has a quoted value, remove double quotes */
unquoted_val.length = attr->value.length - 2;
unquoted_val.s = attr->value.s + 1;
} else {
unquoted_val = attr->value;
}
if (!(match(&unquoted_val, &query_pattern,
(flags & MATCH_PREFIX) != 0,
(flags & MATCH_SUBSTRING) != 0)))
continue;
}
}
#endif /* WITHOUT_QUERY_FILTER */
if (!subsequent_resource) { /* this is the first resource */
subsequent_resource = 1;
} else {
PRINT_COND_WITH_OFFSET(p, bufend, offset, ',', written);
}
left = bufend - p; /* calculate available space */
result = coap_print_link(r, p, &left, &offset);
if (result & COAP_PRINT_STATUS_ERROR) {
break;
}
/* coap_print_link() returns the number of characters that
* where actually written to p. Now advance to its end. */
p += COAP_PRINT_OUTPUT_LENGTH(result);
written += left;
}
*buflen = written;
result = p - buf;
if (result + old_offset - offset < *buflen) {
result |= COAP_PRINT_STATUS_TRUNC;
}
return result;
}
coap_resource_t *
coap_resource_init(const unsigned char *uri, size_t len, int flags) {
coap_resource_t *r;
#ifdef WITH_POSIX
r = (coap_resource_t *)coap_malloc(sizeof(coap_resource_t));
#endif
#ifdef WITH_LWIP
r = (coap_resource_t *)memp_malloc(MEMP_COAP_RESOURCE);
#endif
#ifdef WITH_CONTIKI
r = (coap_resource_t *)memb_alloc(&resource_storage);
#endif
if (r) {
memset(r, 0, sizeof(coap_resource_t));
#ifdef WITH_CONTIKI
LIST_STRUCT_INIT(r, link_attr);
#endif /* WITH_CONTIKI */
LIST_STRUCT_INIT(r, subscribers);
r->uri.s = (unsigned char *)uri;
r->uri.length = len;
coap_hash_path(r->uri.s, r->uri.length, r->key);
r->flags = flags;
} else {
debug("coap_resource_init: no memory left\n");
}
return r;
}
coap_attr_t *
coap_add_attr(coap_resource_t *resource,
const unsigned char *name, size_t nlen,
const unsigned char *val, size_t vlen,
int flags) {
coap_attr_t *attr;
if (!resource || !name)
return NULL;
#ifdef WITH_POSIX
attr = (coap_attr_t *)coap_malloc(sizeof(coap_attr_t));
#endif
#ifdef WITH_LWIP
attr = (coap_attr_t *)memp_malloc(MEMP_COAP_RESOURCEATTR);
#endif
#ifdef WITH_CONTIKI
attr = (coap_attr_t *)memb_alloc(&attribute_storage);
#endif
if (attr) {
attr->name.length = nlen;
attr->value.length = val ? vlen : 0;
attr->name.s = (unsigned char *)name;
attr->value.s = (unsigned char *)val;
attr->flags = flags;
/* add attribute to resource list */
#ifndef WITH_CONTIKI
LL_PREPEND(resource->link_attr, attr);
#else /* WITH_CONTIKI */
list_add(resource->link_attr, attr);
#endif /* WITH_CONTIKI */
} else {
debug("coap_add_attr: no memory left\n");
}
return attr;
}
coap_attr_t *
coap_find_attr(coap_resource_t *resource,
const unsigned char *name, size_t nlen) {
coap_attr_t *attr;
if (!resource || !name)
return NULL;
#ifndef WITH_CONTIKI
LL_FOREACH(resource->link_attr, attr) {
#else /* WITH_CONTIKI */
for (attr = list_head(resource->link_attr); attr;
attr = list_item_next(attr)) {
#endif /* WITH_CONTIKI */
if (attr->name.length == nlen &&
memcmp(attr->name.s, name, nlen) == 0)
return attr;
}
return NULL;
}
void
coap_delete_attr(coap_attr_t *attr) {
if (!attr)
return;
if (attr->flags & COAP_ATTR_FLAGS_RELEASE_NAME)
coap_free(attr->name.s);
if (attr->flags & COAP_ATTR_FLAGS_RELEASE_VALUE)
coap_free(attr->value.s);
#ifdef WITH_POSIX
coap_free(attr);
#endif
#ifdef WITH_LWIP
memp_free(MEMP_COAP_RESOURCEATTR, attr);
#endif
#ifdef WITH_CONTIKI
memb_free(&attribute_storage, attr);
#endif
}
void
coap_hash_request_uri(const coap_pdu_t *request, coap_key_t key) {
coap_opt_iterator_t opt_iter;
coap_opt_filter_t filter;
coap_opt_t *option;
memset(key, 0, sizeof(coap_key_t));
coap_option_filter_clear(filter);
coap_option_setb(filter, COAP_OPTION_URI_PATH);
coap_option_iterator_init((coap_pdu_t *)request, &opt_iter, filter);
while ((option = coap_option_next(&opt_iter)))
coap_hash(COAP_OPT_VALUE(option), COAP_OPT_LENGTH(option), key);
}
void
coap_add_resource(coap_context_t *context, coap_resource_t *resource) {
#ifndef WITH_CONTIKI
#ifdef COAP_RESOURCES_NOHASH
LL_PREPEND(context->resources, resource);
#else
HASH_ADD(hh, context->resources, key, sizeof(coap_key_t), resource);
#endif
#endif /* WITH_CONTIKI */
}
int
coap_delete_resource(coap_context_t *context, coap_key_t key) {
coap_resource_t *resource;
coap_attr_t *attr, *tmp;
#ifdef WITH_CONTIKI
coap_subscription_t *obs;
#endif
if (!context)
return 0;
resource = coap_get_resource_from_key(context, key);
if (!resource)
return 0;
#if defined(WITH_POSIX) || defined(WITH_LWIP)
#ifdef COAP_RESOURCES_NOHASH
LL_DELETE(context->resources, resource);
#else
HASH_DELETE(hh, context->resources, resource);
#endif
/* delete registered attributes */
LL_FOREACH_SAFE(resource->link_attr, attr, tmp) coap_delete_attr(attr);
if (resource->flags & COAP_RESOURCE_FLAGS_RELEASE_URI)
coap_free(resource->uri.s);
#ifdef WITH_POSIX
coap_free(resource);
#endif
#ifdef WITH_LWIP
memp_free(MEMP_COAP_RESOURCE, resource);
#endif
#else /* not (WITH_POSIX || WITH_LWIP) */
/* delete registered attributes */
while ( (attr = list_pop(resource->link_attr)) )
memb_free(&attribute_storage, attr);
/* delete subscribers */
while ( (obs = list_pop(resource->subscribers)) ) {
/* FIXME: notify observer that its subscription has been removed */
memb_free(&subscription_storage, obs);
}
memb_free(&resource_storage, resource);
#endif /* WITH_CONTIKI */
return 1;
}
coap_resource_t *
coap_get_resource_from_key(coap_context_t *context, coap_key_t key) {
#ifndef WITH_CONTIKI
coap_resource_t *resource;
#ifdef COAP_RESOURCES_NOHASH
resource = NULL;
LL_FOREACH(context->resources, resource) {
/* if you think you can outspart the compiler and speed things up by (eg by
* casting to uint32* and comparing alues), increment this counter: 1 */
if (memcmp(key, resource->key, sizeof(coap_key_t)) == 0)
return resource;
}
return NULL;
#else
HASH_FIND(hh, context->resources, key, sizeof(coap_key_t), resource);
return resource;
#endif
#else /* WITH_CONTIKI */
int i;
coap_resource_t *ptr2;
/* the search function is basically taken from memb.c */
ptr2 = (coap_resource_t *)resource_storage.mem;
for (i = 0; i < resource_storage.num; ++i) {
if (resource_storage.count[i] &&
(memcmp(ptr2->key, key, sizeof(coap_key_t)) == 0))
return (coap_resource_t *)ptr2;
++ptr2;
}
return NULL;
#endif /* WITH_CONTIKI */
}
coap_print_status_t
coap_print_link(const coap_resource_t *resource,
unsigned char *buf, size_t *len, size_t *offset) {
unsigned char *p = buf;
const unsigned char *bufend = buf + *len;
coap_attr_t *attr;
coap_print_status_t result = 0;
const size_t old_offset = *offset;
*len = 0;
PRINT_COND_WITH_OFFSET(p, bufend, *offset, '<', *len);
PRINT_COND_WITH_OFFSET(p, bufend, *offset, '/', *len);
COPY_COND_WITH_OFFSET(p, bufend, *offset,
resource->uri.s, resource->uri.length, *len);
PRINT_COND_WITH_OFFSET(p, bufend, *offset, '>', *len);
#ifndef WITH_CONTIKI
LL_FOREACH(resource->link_attr, attr) {
#else /* WITH_CONTIKI */
for (attr = list_head(resource->link_attr); attr;
attr = list_item_next(attr)) {
#endif /* WITH_CONTIKI */
PRINT_COND_WITH_OFFSET(p, bufend, *offset, ';', *len);
COPY_COND_WITH_OFFSET(p, bufend, *offset,
attr->name.s, attr->name.length, *len);
if (attr->value.s) {
PRINT_COND_WITH_OFFSET(p, bufend, *offset, '=', *len);
COPY_COND_WITH_OFFSET(p, bufend, *offset,
attr->value.s, attr->value.length, *len);
}
}
if (resource->observable) {
COPY_COND_WITH_OFFSET(p, bufend, *offset, ";obs", 4, *len);
}
result = p - buf;
if (result + old_offset - *offset < *len) {
result |= COAP_PRINT_STATUS_TRUNC;
}
return result;
}
#ifndef WITHOUT_OBSERVE
coap_subscription_t *
coap_find_observer(coap_resource_t *resource, const coap_address_t *peer,
const str *token) {
coap_subscription_t *s;
assert(resource);
assert(peer);
for (s = list_head(resource->subscribers); s; s = list_item_next(s)) {
if (coap_address_equals(&s->subscriber, peer)
&& (!token || (token->length == s->token_length
&& memcmp(token->s, s->token, token->length) == 0)))
return s;
}
return NULL;
}
coap_subscription_t *
coap_add_observer(coap_resource_t *resource,
const coap_endpoint_t *local_interface,
const coap_address_t *observer,
const str *token) {
coap_subscription_t *s;
assert(observer);
/* Check if there is already a subscription for this peer. */
s = coap_find_observer(resource, observer, token);
/* We are done if subscription was found. */
if (s)
return s;
/* s points to a different subscription, so we have to create
* another one. */
s = COAP_MALLOC_TYPE(subscription);
if (!s)
return NULL;
coap_subscription_init(s);
s->local_if = *local_interface;
memcpy(&s->subscriber, observer, sizeof(coap_address_t));
if (token && token->length) {
s->token_length = token->length;
memcpy(s->token, token->s, min(s->token_length, 8));
}
/* add subscriber to resource */
list_add(resource->subscribers, s);
return s;
}
void
coap_touch_observer(coap_context_t *context, const coap_address_t *observer,
const str *token) {
coap_resource_t *r;
coap_subscription_t *s;
#ifndef WITH_CONTIKI
#ifdef COAP_RESOURCES_NOHASH
LL_FOREACH(context->resources, r) {
#else
coap_resource_t *tmp;
HASH_ITER(hh, context->resources, r, tmp) {
#endif
s = coap_find_observer(r, observer, token);
if (s) {
s->fail_cnt = 0;
}
}
#else /* WITH_CONTIKI */
coap_iterator_t resource_iter;
if (coap_resource_iterator_init(context->resources, &resource_iter) != NULL) {
while ((r = coap_resource_next(&resource_iter))) {
s = coap_find_observer(r, observer, token);
if (s) {
s->fail_cnt = 0;
}
}
}
#endif /* WITH_CONTIKI */
}
int
coap_delete_observer(coap_resource_t *resource, const coap_address_t *observer,
const str *token) {
coap_subscription_t *s;
s = coap_find_observer(resource, observer, token);
if (s) {
list_remove(resource->subscribers, s);
COAP_FREE_TYPE(subscription,s);
}
return s != NULL;
}
static void
coap_notify_observers(coap_context_t *context, coap_resource_t *r) {
coap_method_handler_t h;
coap_subscription_t *obs;
str token;
coap_pdu_t *response;
if (r->observable && (r->dirty || r->partiallydirty)) {
r->partiallydirty = 0;
/* retrieve GET handler, prepare response */
h = r->handler[COAP_REQUEST_GET - 1];
assert(h); /* we do not allow subscriptions if no
* GET handler is defined */
for (obs = list_head(r->subscribers); obs; obs = list_item_next(obs)) {
if (r->dirty == 0 && obs->dirty == 0)
/* running this resource due to partiallydirty, but this observation's notification was already enqueued */
continue;
coap_tid_t tid = COAP_INVALID_TID;
obs->dirty = 0;
/* initialize response */
response = coap_pdu_init(COAP_MESSAGE_CON, 0, 0, COAP_MAX_PDU_SIZE);
if (!response) {
obs->dirty = 1;
r->partiallydirty = 1;
debug("coap_check_notify: pdu init failed, resource stays partially dirty\n");
continue;
}
if (!coap_add_token(response, obs->token_length, obs->token)) {
obs->dirty = 1;
r->partiallydirty = 1;
debug("coap_check_notify: cannot add token, resource stays partially dirty\n");
coap_delete_pdu(response);
continue;
}
token.length = obs->token_length;
token.s = obs->token;
response->hdr->id = coap_new_message_id(context);
if (obs->non && obs->non_cnt < COAP_OBS_MAX_NON) {
response->hdr->type = COAP_MESSAGE_NON;
} else {
response->hdr->type = COAP_MESSAGE_CON;
}
/* fill with observer-specific data */
h(context, r, &obs->local_if, &obs->subscriber, NULL, &token, response);
/* TODO: do not send response and remove observer when
* COAP_RESPONSE_CLASS(response->hdr->code) > 2
*/
if (response->hdr->type == COAP_MESSAGE_CON) {
tid = coap_send_confirmed(context, &obs->local_if, &obs->subscriber, response);
obs->non_cnt = 0;
} else {
tid = coap_send(context, &obs->local_if, &obs->subscriber, response);
obs->non_cnt++;
}
if (COAP_INVALID_TID == tid || response->hdr->type != COAP_MESSAGE_CON)
coap_delete_pdu(response);
if (COAP_INVALID_TID == tid)
{
debug("coap_check_notify: sending failed, resource stays partially dirty\n");
obs->dirty = 1;
r->partiallydirty = 1;
}
}
/* Increment value for next Observe use. */
context->observe++;
}
r->dirty = 0;
}
void
coap_check_notify(coap_context_t *context) {
coap_resource_t *r;
#ifndef WITH_CONTIKI
#ifdef COAP_RESOURCES_NOHASH
LL_FOREACH(context->resources, r) {
#else
coap_resource_t *tmp;
HASH_ITER(hh, context->resources, r, tmp) {
#endif
coap_notify_observers(context, r);
}
#else /* WITH_CONTIKI */
int i;
r = (coap_resource_t *)resource_storage.mem;
for (i = 0; i < resource_storage.num; ++i, ++r) {
if (resource_storage.count[i]) {
coap_notify_observers(context, r);
}
}
#endif /* WITH_CONTIKI */
}
/**
* Checks the failure counter for (peer, token) and removes peer from
* the list of observers for the given resource when COAP_OBS_MAX_FAIL
* is reached.
*
* @param context The CoAP context to use
* @param resource The resource to check for (peer, token)
* @param peer The observer's address
* @param token The token that has been used for subscription.
*/
static void
coap_remove_failed_observers(coap_context_t *context,
coap_resource_t *resource,
const coap_address_t *peer,
const str *token) {
coap_subscription_t *obs;
for (obs = list_head(resource->subscribers); obs;
obs = list_item_next(obs)) {
if (coap_address_equals(peer, &obs->subscriber) &&
token->length == obs->token_length &&
memcmp(token->s, obs->token, token->length) == 0) {
/* count failed notifies and remove when
* COAP_MAX_FAILED_NOTIFY is reached */
if (obs->fail_cnt < COAP_OBS_MAX_FAIL)
obs->fail_cnt++;
else {
list_remove(resource->subscribers, obs);
obs->fail_cnt = 0;
#ifndef NDEBUG
if (LOG_DEBUG <= coap_get_log_level()) {
#ifndef INET6_ADDRSTRLEN
#define INET6_ADDRSTRLEN 40
#endif
unsigned char addr[INET6_ADDRSTRLEN+8];
if (coap_print_addr(&obs->subscriber, addr, INET6_ADDRSTRLEN+8))
debug("** removed observer %s\n", addr);
}
#endif
coap_cancel_all_messages(context, &obs->subscriber,
obs->token, obs->token_length);
COAP_FREE_TYPE(subscription, obs);
}
}
break; /* break loop if observer was found */
}
}
void
coap_handle_failed_notify(coap_context_t *context,
const coap_address_t *peer,
const str *token) {
coap_resource_t *r;
#ifndef WITH_CONTIKI
#ifdef COAP_RESOURCES_NOHASH
LL_FOREACH(context->resources, r) {
#else
coap_resource_t *tmp;
HASH_ITER(hh, context->resources, r, tmp) {
#endif
coap_remove_failed_observers(context, r, peer, token);
}
#else /* WITH_CONTIKI */
int i;
r = (coap_resource_t *)resource_storage.mem;
for (i = 0; i < resource_storage.num; ++i, ++r) {
if (resource_storage.count[i]) {
coap_remove_failed_observers(context, r, peer, token);
}
}
#endif /* WITH_CONTIKI */
}
#endif /* WITHOUT_NOTIFY */
+34
View File
@@ -0,0 +1,34 @@
/* str.c -- strings to be used in the CoAP library
*
* Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
*
* This file is part of the CoAP library libcoap. Please see
* README for terms of use.
*/
#include "coap_config.h"
#include <stdio.h>
#include "debug.h"
#include "mem.h"
#include "str.h"
str *coap_new_string(size_t size) {
str *s = coap_malloc(sizeof(str) + size + 1);
if ( !s ) {
#ifndef NDEBUG
coap_log(LOG_CRIT, "coap_new_string: malloc\n");
#endif
return NULL;
}
memset(s, 0, sizeof(str));
s->s = ((unsigned char *)s) + sizeof(str);
return s;
}
void coap_delete_string(str *s) {
coap_free(s);
}
+22
View File
@@ -0,0 +1,22 @@
/* subscribe.c -- subscription handling for CoAP
* see draft-ietf-coap-observe-16
*
* Copyright (C) 2010--2013,2015 Olaf Bergmann <bergmann@tzi.org>
*
* This file is part of the CoAP library libcoap. Please see
* README for terms of use.
*/
#include "coap_config.h"
#if defined(HAVE_ASSERT_H) && !defined(assert)
# include <assert.h>
#endif
#include "subscribe.h"
void
coap_subscription_init(coap_subscription_t *s) {
assert(s);
memset(s, 0, sizeof(coap_subscription_t));
}
+528
View File
@@ -0,0 +1,528 @@
/* uri.c -- helper functions for URI treatment
*
* Copyright (C) 2010--2012 Olaf Bergmann <bergmann@tzi.org>
*
* This file is part of the CoAP library libcoap. Please see
* README for terms of use.
*/
#include "coap_config.h"
#if defined(HAVE_ASSERT_H) && !defined(assert)
# include <assert.h>
#endif
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "mem.h"
#include "debug.h"
#include "pdu.h"
#include "option.h"
#include "uri.h"
/**
* A length-safe version of strchr(). This function returns a pointer
* to the first occurrence of @p c in @p s, or @c NULL if not found.
*
* @param s The string to search for @p c.
* @param len The length of @p s.
* @param c The character to search.
*
* @return A pointer to the first occurence of @p c, or @c NULL
* if not found.
*/
static inline unsigned char *
strnchr(unsigned char *s, size_t len, unsigned char c) {
while (len && *s++ != c)
--len;
return len ? s : NULL;
}
int
coap_split_uri(unsigned char *str_var, size_t len, coap_uri_t *uri) {
unsigned char *p, *q;
int secure = 0, res = 0;
if (!str_var || !uri)
return -1;
memset(uri, 0, sizeof(coap_uri_t));
uri->port = COAP_DEFAULT_PORT;
/* search for scheme */
p = str_var;
if (*p == '/') {
q = p;
goto path;
}
q = (unsigned char *)COAP_DEFAULT_SCHEME;
while (len && *q && tolower(*p) == *q) {
++p; ++q; --len;
}
/* If q does not point to the string end marker '\0', the schema
* identifier is wrong. */
if (*q) {
res = -1;
goto error;
}
/* There might be an additional 's', indicating the secure version: */
if (len && (secure = tolower(*p) == 's')) {
++p; --len;
}
q = (unsigned char *)"://";
while (len && *q && tolower(*p) == *q) {
++p; ++q; --len;
}
if (*q) {
res = -2;
goto error;
}
/* p points to beginning of Uri-Host */
q = p;
if (len && *p == '[') { /* IPv6 address reference */
++p;
while (len && *q != ']') {
++q; --len;
}
if (!len || *q != ']' || p == q) {
res = -3;
goto error;
}
COAP_SET_STR(&uri->host, q - p, p);
++q; --len;
} else { /* IPv4 address or FQDN */
while (len && *q != ':' && *q != '/' && *q != '?') {
*q = tolower(*q);
++q;
--len;
}
if (p == q) {
res = -3;
goto error;
}
COAP_SET_STR(&uri->host, q - p, p);
}
/* check for Uri-Port */
if (len && *q == ':') {
p = ++q;
--len;
while (len && isdigit(*q)) {
++q;
--len;
}
if (p < q) { /* explicit port number given */
int uri_port = 0;
while (p < q)
uri_port = uri_port * 10 + (*p++ - '0');
uri->port = uri_port;
}
}
path: /* at this point, p must point to an absolute path */
if (!len)
goto end;
if (*q == '/') {
p = ++q;
--len;
while (len && *q != '?') {
++q;
--len;
}
if (p < q) {
COAP_SET_STR(&uri->path, q - p, p);
p = q;
}
}
/* Uri_Query */
if (len && *p == '?') {
++p;
--len;
COAP_SET_STR(&uri->query, len, p);
len = 0;
}
end:
return len ? -1 : 0;
error:
return res;
}
/**
* Calculates decimal value from hexadecimal ASCII character given in
* @p c. The caller must ensure that @p c actually represents a valid
* heaxdecimal character, e.g. with isxdigit(3).
*
* @hideinitializer
*/
#define hexchar_to_dec(c) ((c) & 0x40 ? ((c) & 0x0F) + 9 : ((c) & 0x0F))
/**
* Decodes percent-encoded characters while copying the string @p seg
* of size @p length to @p buf. The caller of this function must
* ensure that the percent-encodings are correct (i.e. the character
* '%' is always followed by two hex digits. and that @p buf provides
* sufficient space to hold the result. This function is supposed to
* be called by make_decoded_option() only.
*
* @param seg The segment to decode and copy.
* @param length Length of @p seg.
* @param buf The result buffer.
*/
void
decode_segment(const unsigned char *seg, size_t length, unsigned char *buf) {
while (length--) {
if (*seg == '%') {
*buf = (hexchar_to_dec(seg[1]) << 4) + hexchar_to_dec(seg[2]);
seg += 2; length -= 2;
} else {
*buf = *seg;
}
++buf; ++seg;
}
}
/**
* Runs through the given path (or query) segment and checks if
* percent-encodings are correct. This function returns @c -1 on error
* or the length of @p s when decoded.
*/
int
check_segment(const unsigned char *s, size_t length) {
size_t n = 0;
while (length) {
if (*s == '%') {
if (length < 2 || !(isxdigit(s[1]) && isxdigit(s[2])))
return -1;
s += 2;
length -= 2;
}
++s; ++n; --length;
}
return n;
}
/**
* Writes a coap option from given string @p s to @p buf. @p s should
* point to a (percent-encoded) path or query segment of a coap_uri_t
* object. The created option will have type @c 0, and the length
* parameter will be set according to the size of the decoded string.
* On success, this function returns the option's size, or a value
* less than zero on error. This function must be called from
* coap_split_path_impl() only.
*
* @param s The string to decode.
* @param length The size of the percent-encoded string @p s.
* @param buf The buffer to store the new coap option.
* @param buflen The maximum size of @p buf.
*
* @return The option's size, or @c -1 on error.
*
* @bug This function does not split segments that are bigger than 270
* bytes.
*/
int
make_decoded_option(const unsigned char *s, size_t length,
unsigned char *buf, size_t buflen) {
int res;
size_t written;
if (!buflen) {
debug("make_decoded_option(): buflen is 0!\n");
return -1;
}
res = check_segment(s, length);
if (res < 0)
return -1;
/* write option header using delta 0 and length res */
written = coap_opt_setheader(buf, buflen, 0, res);
assert(written <= buflen);
if (!written) /* encoding error */
return -1;
buf += written; /* advance past option type/length */
buflen -= written;
if (buflen < (size_t)res) {
debug("buffer too small for option\n");
return -1;
}
decode_segment(s, length, buf);
return written + res;
}
#ifndef min
#define min(a,b) ((a) < (b) ? (a) : (b))
#endif
typedef void (*segment_handler_t)(unsigned char *, size_t, void *);
/**
* Splits the given string into segments. You should call one of the
* macros coap_split_path() or coap_split_query() instead.
*
* @param parse_iter The iterator used for tokenizing.
* @param h A handler that is called with every token.
* @param data Opaque data that is passed to @p h when called.
*
* @return The number of characters that have been parsed from @p s.
*/
size_t
coap_split_path_impl(coap_parse_iterator_t *parse_iter,
segment_handler_t h, void *data) {
unsigned char *seg;
size_t length;
assert(parse_iter);
assert(h);
length = parse_iter->n;
while ( (seg = coap_parse_next(parse_iter)) ) {
/* any valid path segment is handled here: */
h(seg, parse_iter->segment_length, data);
}
return length - (parse_iter->n - parse_iter->segment_length);
}
struct cnt_str {
str buf;
int n;
};
void
write_option(unsigned char *s, size_t len, void *data) {
struct cnt_str *state = (struct cnt_str *)data;
int res;
assert(state);
/* skip empty segments and those that consist of only one or two dots */
if (memcmp(s, "..", min(len,2)) == 0)
return;
res = make_decoded_option(s, len, state->buf.s, state->buf.length);
if (res > 0) {
state->buf.s += res;
state->buf.length -= res;
state->n++;
}
}
int
coap_split_path(const unsigned char *s, size_t length,
unsigned char *buf, size_t *buflen) {
struct cnt_str tmp = { { *buflen, buf }, 0 };
coap_parse_iterator_t pi;
coap_parse_iterator_init((unsigned char *)s, length,
'/', (unsigned char *)"?#", 2, &pi);
coap_split_path_impl(&pi, write_option, &tmp);
*buflen = *buflen - tmp.buf.length;
return tmp.n;
}
int
coap_split_query(const unsigned char *s, size_t length,
unsigned char *buf, size_t *buflen) {
struct cnt_str tmp = { { *buflen, buf }, 0 };
coap_parse_iterator_t pi;
coap_parse_iterator_init((unsigned char *)s, length,
'&', (unsigned char *)"#", 1, &pi);
coap_split_path_impl(&pi, write_option, &tmp);
*buflen = tmp.buf.length;
return tmp.n;
}
#define URI_DATA(uriobj) ((unsigned char *)(uriobj) + sizeof(coap_uri_t))
coap_uri_t *
coap_new_uri(const unsigned char *uri, unsigned int length) {
unsigned char *result;
result = coap_malloc(length + 1 + sizeof(coap_uri_t));
if (!result)
return NULL;
memcpy(URI_DATA(result), uri, length);
URI_DATA(result)[length] = '\0'; /* make it zero-terminated */
if (coap_split_uri(URI_DATA(result), length, (coap_uri_t *)result) < 0) {
coap_free(result);
return NULL;
}
return (coap_uri_t *)result;
}
coap_uri_t *
coap_clone_uri(const coap_uri_t *uri) {
coap_uri_t *result;
if ( !uri )
return NULL;
result = (coap_uri_t *)coap_malloc( uri->query.length + uri->host.length +
uri->path.length + sizeof(coap_uri_t) + 1);
if ( !result )
return NULL;
memset( result, 0, sizeof(coap_uri_t) );
result->port = uri->port;
if ( uri->host.length ) {
result->host.s = URI_DATA(result);
result->host.length = uri->host.length;
memcpy(result->host.s, uri->host.s, uri->host.length);
}
if ( uri->path.length ) {
result->path.s = URI_DATA(result) + uri->host.length;
result->path.length = uri->path.length;
memcpy(result->path.s, uri->path.s, uri->path.length);
}
if ( uri->query.length ) {
result->query.s = URI_DATA(result) + uri->host.length + uri->path.length;
result->query.length = uri->query.length;
memcpy(result->query.s, uri->query.s, uri->query.length);
}
return result;
}
/* hash URI path segments */
/* The function signature of coap_hash() is different from
* segment_handler_t hence we use this wrapper as safe typecast. */
static inline void
hash_segment(unsigned char *s, size_t len, void *data) {
coap_hash(s, len, data);
}
int
coap_hash_path(const unsigned char *path, size_t len, coap_key_t key) {
coap_parse_iterator_t pi;
if (!path)
return 0;
memset(key, 0, sizeof(coap_key_t));
coap_parse_iterator_init((unsigned char *)path, len,
'/', (unsigned char *)"?#", 2, &pi);
coap_split_path_impl(&pi, hash_segment, key);
return 1;
}
/* iterator functions */
coap_parse_iterator_t *
coap_parse_iterator_init(unsigned char *s, size_t n,
unsigned char separator,
unsigned char *delim, size_t dlen,
coap_parse_iterator_t *pi) {
assert(pi);
assert(separator);
pi->separator = separator;
pi->delim = delim;
pi->dlen = dlen;
pi->pos = s;
pi->n = n;
pi->segment_length = 0;
return pi;
}
unsigned char *
coap_parse_next(coap_parse_iterator_t *pi) {
unsigned char *p;
if (!pi)
return NULL;
/* proceed to the next segment */
pi->n -= pi->segment_length;
pi->pos += pi->segment_length;
pi->segment_length = 0;
/* last segment? */
if (!pi->n || strnchr(pi->delim, pi->dlen, *pi->pos)) {
pi->pos = NULL;
return NULL;
}
/* skip following separator (the first segment might not have one) */
if (*pi->pos == pi->separator) {
++pi->pos;
--pi->n;
}
p = pi->pos;
while (pi->segment_length < pi->n && *p != pi->separator &&
!strnchr(pi->delim, pi->dlen, *p)) {
++p;
++pi->segment_length;
}
if (!pi->n) {
pi->pos = NULL;
pi->segment_length = 0;
}
return pi->pos;
}