Added session management with simpler DTLS lib API.

Added DTLS support with OpenSSL.
This commit is contained in:
jcmichelou committed 2017-06-18 20:09:47 +02:00
1 parent 5b1a8f67bf
commit 8353417afb
24 files changed
+1979 -876

No files matched your search

+176 -315
View File
@@ -66,25 +66,15 @@
#else
# error "Need IPV6_PKTINFO or IPV6_RECVPKTINFO to request ancillary data from OS."
#endif /* IPV6_RECVPKTINFO */
struct coap_packet_t {
coap_address_t src; /**< the packet's source address */
coap_address_t dst; /**< the packet's destination address */
int ifindex; /**< the interface index */
size_t length; /**< length of payload */
unsigned char payload[]; /**< payload */
};
#endif
void coap_free_endpoint( coap_endpoint_t *ep );
#ifndef CUSTOM_COAP_NETWORK_ENDPOINT
#ifdef WITH_CONTIKI
static int ep_initialized = 0;
COAP_STATIC_INLINE struct coap_endpoint_t *
coap_malloc_contiki_endpoint() {
struct coap_endpoint_t *
coap_malloc_endpoint() {
static struct coap_endpoint_t ep;
if (ep_initialized) {
@@ -95,335 +85,178 @@ coap_malloc_contiki_endpoint() {
}
}
COAP_STATIC_INLINE void
coap_free_contiki_endpoint(struct coap_endpoint_t *ep) {
void
coap_mfree_endpoint(struct coap_endpoint_t *ep) {
ep_initialized = 0;
}
coap_endpoint_t *
coap_new_endpoint( coap_context_t *context, const coap_address_t *listen_addr, coap_proto_t proto ) {
int
coap_socket_bind_udp( coap_socket_t *sock,
const coap_address_t *listen_addr,
coap_address_t *bound_addr )
{
sock->conn = udp_new( NULL, 0, NULL );
if ( proto == COAP_PROTO_DTLS ) {
coap_log( LOG_CRIT, "coap_new_endpoint: DTLS not supported\n" );
return NULL;
if ( !sock->conn ) {
coap_log( LOG_WARNING, "coap_socket_bind_udp" );
return 0;
}
struct coap_endpoint_t *ep = coap_malloc_contiki_endpoint();
coap_address_init( &bound_addr );
uip_ipaddr_copy( &bound_addr->addr, &listen_addr->addr );
bound_addr->addr.port = listen_addr->addr.port;
udp_bind( (struct uip_udp_conn *)sock->conn, bound_addr->port );
return 1;
}
if (ep) {
memset(ep, 0, sizeof(struct coap_endpoint_t));
ep->sock.handle.conn = udp_new(NULL, 0, NULL);
int
coap_socket_connect_udp( 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 )
{
return 0;
}
if (!ep->sock.handle.conn) {
coap_free_endpoint(ep);
return NULL;
}
void coap_socket_close( coap_socket_t *sock ) {
if ( sock->conn )
uip_udp_remove( (struct uip_udp_conn *)sock->conn );
}
coap_address_init(&ep->addr);
uip_ipaddr_copy(&ep->addr.addr, &listen_addr->addr);
ep->addr.port = listen_addr->port;
udp_bind((struct uip_udp_conn *)ep->sock.handle.conn, listen_addr->port);
LL_PREPEND( context->endpoint, endpoint );
}
return ep;
#else
struct coap_endpoint_t *
coap_malloc_endpoint( void ) {
return ( struct coap_endpoint_t * )coap_malloc( sizeof( struct coap_endpoint_t ) );
}
void
coap_free_endpoint(coap_endpoint_t *ep) {
if (ep) {
if (ep->sock.handle.conn) {
uip_udp_remove((struct uip_udp_conn *)ep->handle.conn);
}
coap_free_contiki_endpoint(ep);
}
coap_mfree_endpoint( struct coap_endpoint_t *ep ) {
coap_free( ep );
}
#else /* WITH_CONTIKI */
COAP_STATIC_INLINE struct coap_endpoint_t *
coap_malloc_posix_endpoint(void) {
return (struct coap_endpoint_t *)coap_malloc(sizeof(struct coap_endpoint_t));
}
COAP_STATIC_INLINE void
coap_free_posix_endpoint(struct coap_endpoint_t *ep) {
coap_free(ep);
}
coap_endpoint_t *
coap_new_endpoint( coap_context_t *context, const coap_address_t *listen_addr, coap_proto_t proto ) {
coap_fd_t sockfd;
int
coap_socket_bind_udp( coap_socket_t *sock,
const coap_address_t *listen_addr,
coap_address_t *bound_addr ) {
int on = 1, off = 0;
struct coap_endpoint_t *ep = NULL;
assert( context );
assert( listen_addr );
assert( proto != COAP_PROTO_NONE );
if ( proto == COAP_PROTO_DTLS && !coap_dtls_is_supported() ) {
coap_log(LOG_CRIT, "coap_new_endpoint: DTLS not supported\n");
return NULL;
sock->fd = socket( listen_addr->addr.sa.sa_family, SOCK_DGRAM, 0 );
if ( sock->fd == COAP_INVALID_SOCKET ) {
coap_log( LOG_WARNING, "coap_socket_bind_udp: socket" );
goto error;
}
sockfd = socket( listen_addr->addr.sa.sa_family, SOCK_DGRAM, 0 );
if (sockfd == COAP_INVALID_SOCKET) {
coap_log(LOG_WARNING, "coap_new_endpoint: socket");
return NULL;
}
if ( setsockopt( sock->fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T( &on ), sizeof( on ) ) == COAP_SOCKET_ERROR )
coap_log( LOG_WARNING, "coap_socket_bind_udp: setsockopt SO_REUSEADDR" );
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof(on)) == COAP_SOCKET_ERROR)
coap_log(LOG_WARNING, "coap_new_endpoint: setsockopt SO_REUSEADDR");
switch( listen_addr->addr.sa.sa_family ) {
switch ( listen_addr->addr.sa.sa_family ) {
case AF_INET:
if (setsockopt(sockfd, IPPROTO_IP, GEN_IP_PKTINFO, OPTVAL_T(&on), sizeof(on)) == COAP_SOCKET_ERROR)
coap_log(LOG_ALERT, "coap_new_endpoint: setsockopt IP_PKTINFO\n");
if ( setsockopt( sock->fd, IPPROTO_IP, GEN_IP_PKTINFO, OPTVAL_T( &on ), sizeof( on ) ) == COAP_SOCKET_ERROR )
coap_log( LOG_ALERT, "coap_socket_bind_udp: setsockopt IP_PKTINFO\n" );
break;
case AF_INET6:
/* Configure the socket as dual-stacked */
if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY, OPTVAL_T(&off), sizeof(off)) == COAP_SOCKET_ERROR)
coap_log(LOG_ALERT, "coap_new_endpoint: setsockopt IPV6_V6ONLY\n");
if (setsockopt(sockfd, IPPROTO_IPV6, GEN_IPV6_PKTINFO, OPTVAL_T(&on), sizeof(on)) == COAP_SOCKET_ERROR)
coap_log(LOG_ALERT, "coap_new_endpoint: setsockopt IPV6_PKTINFO\n");
setsockopt(sockfd, IPPROTO_IP, GEN_IP_PKTINFO, OPTVAL_T(&on), sizeof(on)); /* ignore error, because the likely cause is that IPv4 is disabled at the os level */
break;
if ( setsockopt( sock->fd, IPPROTO_IPV6, IPV6_V6ONLY, OPTVAL_T( &off ), sizeof( off ) ) == COAP_SOCKET_ERROR )
coap_log( LOG_ALERT, "coap_socket_bind_udp: setsockopt IPV6_V6ONLY\n" );
if ( setsockopt( sock->fd, IPPROTO_IPV6, GEN_IPV6_PKTINFO, OPTVAL_T( &on ), sizeof( on ) ) == COAP_SOCKET_ERROR )
coap_log( LOG_ALERT, "coap_socket_bind_udp: setsockopt IPV6_PKTINFO\n" );
setsockopt( sock->fd, IPPROTO_IP, GEN_IP_PKTINFO, OPTVAL_T( &on ), sizeof( on ) ); /* ignore error, because the likely cause is that IPv4 is disabled at the os level */
break;
default:
coap_log(LOG_ALERT, "coap_new_endpoint: unsupported sa_family\n");
coap_log( LOG_ALERT, "coap_socket_bind_udp: unsupported sa_family\n" );
}
if ( bind( sockfd, &listen_addr->addr.sa, listen_addr->size ) == COAP_SOCKET_ERROR) {
coap_log(LOG_WARNING, "coap_new_endpoint: bind");
if ( bind( sock->fd, &listen_addr->addr.sa, listen_addr->size ) == COAP_SOCKET_ERROR ) {
coap_log( LOG_WARNING, "coap_socket_bind_udp: bind" );
goto error;
}
ep = coap_malloc_posix_endpoint();
if (!ep) {
coap_log(LOG_WARNING, "coap_new_endpoint: malloc");
bound_addr->size = ( socklen_t )sizeof( *bound_addr );
if ( getsockname( sock->fd, &bound_addr->addr.sa, &bound_addr->size ) < 0 ) {
coap_log( LOG_WARNING, "coap_socket_bind_udp: cannot determine local address" );
goto error;
}
memset(ep, 0, sizeof(struct coap_endpoint_t));
ep->context = context;
ep->proto = proto;
ep->sock.fd = sockfd;
ep->sock.flags = COAP_SOCKET_NOT_EMPTY | COAP_SOCKET_BOUND | COAP_SOCKET_WANT_DATA;
ep->bind_addr.size = (socklen_t)sizeof( ep->bind_addr );
if (getsockname(sockfd, &ep->bind_addr.addr.sa, &ep->bind_addr.size) < 0) {
coap_log(LOG_WARNING, "coap_new_endpoint: cannot determine local address");
goto error;
}
return 1;
#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(&ep->bind_addr, addr_str, INET6_ADDRSTRLEN+8)) {
debug("created %s endpoint %s\n",
ep->proto == COAP_PROTO_DTLS ? "DTLS " : "UDP",
addr_str);
}
}
#endif /* NDEBUG */
LL_PREPEND( context->endpoint, ep );
return ep;
error:
coap_closesocket(sockfd);
coap_free_posix_endpoint(ep);
return NULL;
error:
coap_socket_close( sock );
return 0;
}
void
coap_free_endpoint(coap_endpoint_t *ep) {
if (ep) {
coap_session_t *session;
if (ep->sock.flags != COAP_SOCKET_EMPTY && ep->sock.fd != COAP_INVALID_SOCKET)
coap_closesocket(ep->sock.fd);
LL_FOREACH( ep->sessions, session ) {
assert( session->ref == 0 );
if ( session->ref == 0 ) {
if ( session->sock.flags != COAP_SOCKET_EMPTY && session->sock.fd != COAP_INVALID_SOCKET )
coap_closesocket( session->sock.fd );
}
}
coap_free_posix_endpoint(ep);
}
}
static coap_session_t *
coap_make_session( coap_proto_t proto, coap_session_type_t type, const coap_address_t *local, const coap_address_t *remote, int ifindex, coap_context_t *context, coap_endpoint_t *endpoint ) {
coap_session_t *session = (coap_session_t*)coap_malloc( sizeof( coap_session_t ) );
if ( !session )
return NULL;
memset( session, 0, sizeof( *session ) );
session->proto = proto;
session->type = type;
if ( local )
coap_address_copy( &session->local_addr, local );
else
coap_address_init( &session->local_addr );
if ( remote )
coap_address_copy( &session->remote_addr, remote );
else
coap_address_init( &session->remote_addr );
session->ifindex = ifindex;
session->context = context;
session->endpoint = endpoint;
return session;
}
static void
coap_free_session( coap_session_t *session ) {
if ( !session )
return;
assert( session->ref == 0 );
if ( session->ref )
return;
if ( session->sock.flags != COAP_SOCKET_EMPTY && session->sock.fd != COAP_INVALID_SOCKET )
coap_closesocket( session->sock.fd );
if ( session->endpoint )
LL_DELETE( session->endpoint->sessions, session );
else if ( session->context )
LL_DELETE( session->context->sessions, session );
coap_free( session );
}
coap_session_t *
coap_session_reference( coap_session_t *session ) {
++session->ref;
return session;
}
void
coap_session_release( coap_session_t *session ) {
if ( session ) {
assert( session->ref > 0 );
if ( session->ref > 0 )
--session->ref;
if ( session->ref == 0 && session->type == COAP_SESSION_TYPE_CLIENT )
coap_free_session( session );
}
}
coap_session_t *
coap_endpoint_get_session( coap_endpoint_t *endpoint, const coap_packet_t *packet ) {
coap_session_t *session = NULL;
LL_FOREACH( endpoint->sessions, session ) {
if ( session->ifindex == packet->ifindex && coap_address_equals( &session->local_addr, &packet->dst ) && coap_address_equals( &session->remote_addr, &packet->src ) )
return session;
}
session = coap_make_session( endpoint->proto, COAP_SESSION_TYPE_SERVER, &packet->dst, &packet->src, packet->ifindex, endpoint->context, endpoint );
int
coap_socket_connect_udp( 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 )
{
int on = 1, off = 0;
coap_address_t connect_addr;
coap_address_copy( &connect_addr, server );
if ( endpoint->proto == COAP_PROTO_UDP )
session->state = COAP_SESSION_STATE_ESTABLISHED;
LL_PREPEND( endpoint->sessions, session );
return session;
}
coap_session_t *coap_new_client_session(
coap_context_t *ctx,
coap_address_t *local_if,
coap_address_t *server,
coap_proto_t proto
) {
coap_session_t *session = NULL;
int on = 1, off = 0;
assert( server );
assert( proto != COAP_PROTO_NONE );
coap_fd_t sockfd = socket( server->addr.sa.sa_family, SOCK_DGRAM, 0 );
if ( sockfd == COAP_INVALID_SOCKET ) {
coap_log( LOG_WARNING, "coap_new_session: socket" );
return NULL;
sock->fd = socket( connect_addr.addr.sa.sa_family, SOCK_DGRAM, 0 );
if ( sock->fd == COAP_INVALID_SOCKET ) {
coap_log( LOG_WARNING, "coap_socket_connect_udp: socket" );
goto error;
}
switch ( server->addr.sa.sa_family ) {
switch ( connect_addr.addr.sa.sa_family ) {
case AF_INET:
if ( server->addr.sin.sin_port == 0 )
server->addr.sin.sin_port = htons( proto == COAP_PROTO_DTLS ? COAPS_DEFAULT_PORT : COAP_DEFAULT_PORT );
if ( connect_addr.addr.sin.sin_port == 0 )
connect_addr.addr.sin.sin_port = htons( default_port );
break;
case AF_INET6:
if ( server->addr.sin6.sin6_port == 0 )
server->addr.sin6.sin6_port = htons( proto == COAP_PROTO_DTLS ? COAPS_DEFAULT_PORT : COAP_DEFAULT_PORT );
if ( connect_addr.addr.sin6.sin6_port == 0 )
connect_addr.addr.sin6.sin6_port = htons( default_port );
/* Configure the socket as dual-stacked */
if ( setsockopt( sockfd, IPPROTO_IPV6, IPV6_V6ONLY, OPTVAL_T( &off ), sizeof( off ) ) == COAP_SOCKET_ERROR )
coap_log( LOG_ALERT, "coap_new_session: setsockopt IPV6_V6ONLY\n" );
if ( setsockopt( sock->fd, IPPROTO_IPV6, IPV6_V6ONLY, OPTVAL_T( &off ), sizeof( off ) ) == COAP_SOCKET_ERROR )
coap_log( LOG_WARNING, "coap_socket_connect_udp: setsockopt IPV6_V6ONLY\n" );
break;
default:
coap_log( LOG_ALERT, "coap_new_session: unsupported sa_family\n" );
coap_log( LOG_ALERT, "coap_socket_connect_udp: unsupported sa_family\n" );
}
if ( local_if ) {
if ( setsockopt( sockfd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T( &on ), sizeof( on ) ) == COAP_SOCKET_ERROR )
coap_log( LOG_WARNING, "coap_new_session: setsockopt SO_REUSEADDR" );
if ( bind( sockfd, &local_if->addr.sa, local_if->size ) == COAP_SOCKET_ERROR ) {
coap_log( LOG_WARNING, "coap_new_session: bind" );
if ( setsockopt( sock->fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T( &on ), sizeof( on ) ) == COAP_SOCKET_ERROR )
coap_log( LOG_WARNING, "coap_socket_connect_udp: setsockopt SO_REUSEADDR" );
if ( bind( sock->fd, &local_if->addr.sa, local_if->size ) == COAP_SOCKET_ERROR ) {
coap_log( LOG_WARNING, "coap_socket_connect_udp: bind" );
goto error;
}
}
if ( connect( sockfd, &server->addr.sa, server->size ) == COAP_SOCKET_ERROR ) {
coap_log( LOG_WARNING, "coap_new_session: connect" );
if ( connect( sock->fd, &connect_addr.addr.sa, connect_addr.size ) == COAP_SOCKET_ERROR ) {
coap_log( LOG_WARNING, "coap_socket_connect_udp: connect" );
goto error;
}
session = coap_make_session( proto, COAP_SESSION_TYPE_CLIENT, local_if, server, 0, ctx, NULL );
if ( !session )
goto error;
if ( getsockname( sockfd, &session->local_addr.addr.sa, &session->local_addr.size ) == COAP_SOCKET_ERROR ) {
if ( getsockname( sock->fd, &local_addr->addr.sa, &local_addr->size ) == COAP_SOCKET_ERROR ) {
coap_log( LOG_WARNING, "coap_new_session: getsockname" );
}
if ( getpeername( sockfd, &session->remote_addr.addr.sa, &session->remote_addr.size ) == COAP_SOCKET_ERROR ) {
if ( getpeername( sock->fd, &remote_addr->addr.sa, &remote_addr->size ) == COAP_SOCKET_ERROR ) {
coap_log( LOG_WARNING, "coap_new_session: getpeername" );
}
session->ref = 1;
session->sock.fd = sockfd;
session->sock.flags = COAP_SOCKET_NOT_EMPTY | COAP_SOCKET_CONNECTED | COAP_SOCKET_WANT_DATA;
if ( local_if )
session->sock.flags |= COAP_SOCKET_BOUND;
if ( proto == COAP_PROTO_UDP )
session->state = COAP_SESSION_STATE_ESTABLISHED;
LL_PREPEND( ctx->sessions, session );
return session;
return 1;
error:
if ( session )
coap_free_session( session );
else if ( sockfd != COAP_INVALID_SOCKET )
coap_closesocket( sockfd );
return NULL;
coap_socket_close( sock );
return 0;
}
coap_session_t *coap_new_client_session_psk(
coap_context_t *ctx,
coap_address_t *local_if,
coap_address_t *server,
coap_proto_t proto,
const uint8_t *identity,
size_t identity_len,
const uint8_t *key,
size_t key_len
) {
coap_session_t *session = coap_new_client_session( ctx, local_if, server, proto );
return session;
void coap_socket_close( coap_socket_t *sock ) {
if ( sock->fd != COAP_INVALID_SOCKET )
coap_closesocket( sock->fd );
}
#endif /* WITH_CONTIKI */
#endif /* CUSTOM_COAP_NETWORK_ENDPOINT */
#ifndef CUSTOM_COAP_NETWORK_SEND
#endif /* WITH_CONTIKI */
#if (!defined(WITH_CONTIKI) && !defined(WITH_LWIP)) != ( defined(HAVE_NETINET_IN_H) || defined(HAVE_WS2TCPIP_H) )
/* define struct in6_pktinfo and struct in_pktinfo if not available
@@ -475,29 +308,29 @@ static __declspec( thread ) LPFN_WSARECVMSG lpWSARecvMsg = NULL;
#endif
ssize_t
coap_network_send( coap_socket_t *sock, const coap_session_t *session, uint8_t *data, size_t datalen ) {
ssize_t r = 0;
coap_network_send( coap_socket_t *sock, const coap_session_t *session, const uint8_t *data, size_t datalen ) {
ssize_t bytes_written = 0;
if ( sock->flags & COAP_SOCKET_CONNECTED ) {
#ifdef _WIN32
r = send( sock->fd, (const char *)data, (int)datalen, 0 );
bytes_written = send( sock->fd, (const char *)data, (int)datalen, 0 );
#else
r = send( sock->fd, data, datalen, 0 );
bytes_written = send( sock->fd, data, datalen, 0 );
#endif
return r;
} else {
#ifndef WITH_CONTIKI
/* a buffer large enough to hold all packet info types, ipv6 is the largest */
char buf[CMSG_SPACE( sizeof( struct in6_pktinfo ) )];
#ifdef _WIN32
DWORD dwNumberOfBytesSent = 0;
int r;
#endif
struct msghdr mhdr;
struct iovec iov[1];
assert( session );
iov[0].iov_base = data;
iov[0].iov_base = (uint8_t*)data;
iov[0].iov_len = (iov_len_t)datalen;
memset( &mhdr, 0, sizeof( struct msghdr ) );
@@ -570,34 +403,35 @@ coap_network_send( coap_socket_t *sock, const coap_session_t *session, uint8_t *
default:
/* error */
coap_log( LOG_WARNING, "protocol not supported\n" );
return -1;
bytes_written = -1;
}
#ifdef _WIN32
r = WSASendMsg( sock->fd, &mhdr, 0 /*dwFlags*/, &dwNumberOfBytesSent, NULL /*lpOverlapped*/, NULL /*lpCompletionRoutine*/ );
if ( r == 0 )
return (ssize_t)dwNumberOfBytesSent;
bytes_written = (ssize_t)dwNumberOfBytesSent;
else
return -1;
bytes_written = -1;
#else
return sendmsg( sock->fd, &mhdr, 0 );
bytes_written = sendmsg( sock->fd, &mhdr, 0 );
#endif
#else /* WITH_CONTIKI */
/* FIXME: untested */
/* FIXME: is there a way to check if send was successful? */
(void)datalen;
(void)data;
uip_udp_packet_sendto( ( struct uip_udp_conn * )sock->handle.conn, data, datalen,
uip_udp_packet_sendto( ( struct uip_udp_conn * )sock->conn, data, datalen,
&session->remote_addr.addr, session->remote_addr.port );
return datalen;
bytes_written = datalen;
#endif /* WITH_CONTIKI */
}
if ( bytes_written < 0 )
coap_log( LOG_CRIT, "coap_network_send: %s\n", coap_socket_strerror() );
return bytes_written;
}
#endif /* CUSTOM_COAP_NETWORK_SEND */
#ifndef CUSTOM_COAP_NETWORK_READ
#define SIN6(A) ((struct sockaddr_in6 *)(A))
#if !defined(WITH_CONTIKI) && !defined(WITH_LWIP)
@@ -716,28 +550,18 @@ coap_network_read(coap_socket_t *sock, coap_packet_t **packet) {
}
}
r = lpWSARecvMsg( sock->fd, &mhdr, &dwNumberOfBytesRecvd, NULL /* LPWSAOVERLAPPED */, NULL /* LPWSAOVERLAPPED_COMPLETION_ROUTINE */ );
if ( r == 0 ) {
if ( r == 0 )
len = (ssize_t)dwNumberOfBytesRecvd;
} else {
char *szErrorMsg = NULL;
FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, (DWORD)WSAGetLastError(), MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), (LPSTR)&szErrorMsg, 0, NULL );
coap_log( LOG_WARNING, "coap_network_read: %s\n", szErrorMsg );
LocalFree( szErrorMsg );
len = -1;
}
#else
len = recvmsg( socket->fd, &mhdr, 0 );
if ( len < 0 )
coap_log( LOG_WARNING, "coap_network_read: %s\n", strerror( errno ) );
#endif
if ( len < 0 ) {
coap_log( LOG_WARNING, "coap_network_read: %s\n", coap_socket_strerror() );
goto error;
} else {
struct cmsghdr *cmsg;
coap_log( LOG_DEBUG, "received %d bytes on fd %d\n", (int)len, (int)sock->fd );
( *packet )->src.size = mhdr.msg_namelen;
/* use getsockname() to get the local port */
@@ -909,21 +733,16 @@ coap_run_once( coap_context_t *ctx, unsigned int timeout_ms ) {
if ( result < 0 ) { /* error */
#ifdef _WIN32
char *szErrorMsg = NULL;
int err = WSAGetLastError();
if ( err == WSAEINVAL ) { /* May happen because of ICMP */
if ( WSAGetLastError() == WSAEINVAL ) { /* May happen because of ICMP */
coap_tick_t past = now;
coap_ticks( &now );
return (int)( ( ( now - past ) * 1000 ) / COAP_TICKS_PER_SECOND );
}
FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, (DWORD)err, MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), (LPSTR)&szErrorMsg, 0, NULL );
coap_log( LOG_DEBUG, szErrorMsg );
LocalFree( szErrorMsg );
} else {
#else
if ( errno != EINTR ) {
coap_log( LOG_DEBUG, strerror( errno ) );
}
#endif
coap_log( LOG_DEBUG, coap_socket_strerror() );
}
return -1;
} else if ( result > 0 ) { /* read from socket */
coap_tick_t past = now;
@@ -962,7 +781,49 @@ int coap_run_once( coap_context_t *ctx, unsigned int timeout_ms ) {
}
#endif
#ifdef _WIN32
const char *coap_socket_strerror() {
static char szError[256];
if ( FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, (DWORD)WSAGetLastError(), MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), (LPSTR)szError, ( DWORD )sizeof( szError ), NULL ) == 0 )
strcpy( szError, "Unknown error" );
return szError;
}
#else
const char *coap_socket_strerrror() {
return strerror( errno );
}
#endif
#if defined(WITH_LWIP)
ssize_t
coap_socket_send_pdu( coap_socket_t *sock, coap_session_t *session,
coap_pdu_t *pdu ) {
/* FIXME: we can't check this here with the existing infrastructure, but we
* should actually check that the pdu is not held by anyone but us. the
* respective pbuf is already exclusively owned by the pdu. */
pbuf_realloc( pdu->pbuf, pdu->length );
udp_sendto( sock->pcb, pdu->pbuf, &session->remote_addr.addr,
session->remote_addr.port );
return pdu->length;
}
ssize_t
coap_socket_send( coap_socket_t *sock, coap_session_t *session,
/* Not implemented, use coap_socket_send_pdu instead */
return -1;
}
#else /* defined(WITH_LWIP) */
ssize_t
coap_socket_send( coap_socket_t *sock, coap_session_t *session,
const uint8_t *data, size_t data_len )
{
return session->context->network_send( sock, session, data, data_len );
}
#endif /* defined(WITH_LWIP) */
#undef SIN6
#endif /* CUSTOM_COAP_NETWORK_READ */
+85
View File
@@ -0,0 +1,85 @@
/*
* coap_notls.c -- Stub Datagram Transport Layer Support for libcoap
*
* Copyright (C) 2016 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_LIBTINYDTLS) && !defined(HAVE_OPENSSL)
#include "coap_dtls.h"
#ifdef __GNUC__
#define UNUSED __attribute__((unused))
#else /* __GNUC__ */
#define UNUSED
#endif /* __GNUC__ */
int
coap_dtls_is_supported( void ) {
return 0;
}
static int dtls_log_level = 0;
void
coap_dtls_set_log_level( int level ) {
dtls_log_level = level;
}
int
coap_dtls_get_log_level( void ) {
return dtls_log_level;
}
struct coap_dtls_context_t *
coap_dtls_new_context( struct coap_context_t *coap_context UNUSED ) {
return NULL;
}
void
coap_dtls_free_context( struct coap_dtls_context_t *dtls_context ) {
}
struct coap_dtls_session_t *
coap_dtls_get_session( struct coap_context_t *coap_context UNUSED,
const coap_endpoint_t *local_interface UNUSED,
const coap_address_t *dst UNUSED ) {
return NULL;
}
int
coap_dtls_send( struct coap_context_t *coap_context,
struct coap_dtls_session_t *session,
const coap_pdu_t *pdu ) {
return -1;
}
struct coap_dtls_session_t *
coap_dtls_new_session( struct coap_dtls_context_t *dtls_context,
const coap_endpoint_t *local_interface,
const coap_address_t *remote ) {
return NULL;
}
struct coap_dtls_session_t;
void
coap_dtls_free_session( struct coap_dtls_context_t *dtls_context,
struct coap_dtls_session_t *session ) {
}
int
coap_dtls_handle_message( struct coap_context_t *coap_context UNUSED,
coap_session_t *session UNUSED,
const unsigned char *data UNUSED,
size_t data_len UNUSED ) {
return -1;
}
#undef UNUSED
#endif /* !HAVE_LIBTINYDTLS && !HAVE_OPENSSL */
+572
View File
@@ -0,0 +1,572 @@
/*
* coap_tinydtls.c -- Datagram Transport Layer Support for libcoap with openssl
*
* Copyright (C) 2017 Jean-Claude Michelou <jcm@spinetix.com>
*
* This file is part of the CoAP library libcoap. Please see README for terms
* of use.
*/
#include "coap_config.h"
#ifdef HAVE_OPENSSL
#include "coap_dtls.h"
#include "mem.h"
#include "debug.h"
#include "prng.h"
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/hmac.h>
/* This structure encapsulates the OpenSSL context object. */
typedef struct coap_dtls_context_t {
SSL_CTX *ctx;
SSL *ssl; /* OpenSSL object for listening to connection requests */
HMAC_CTX *cookie_hmac;
BIO_METHOD *meth;
BIO_ADDR *bio_addr;
} coap_dtls_context_t;
int coap_dtls_is_supported( void ) {
return 1;
}
static int dtls_log_level = 0;
void coap_dtls_set_log_level( int level ) {
level = dtls_log_level;
}
int coap_dtls_get_log_level( void ) {
return dtls_log_level;
}
typedef struct coap_ssl_st {
coap_session_t *session;
const void *pdu;
unsigned pdu_len;
unsigned mtu;
unsigned peekmode;
} coap_ssl_data;
static int coap_dgram_create( BIO *a ) {
coap_ssl_data *data = NULL;
data = malloc( sizeof( coap_ssl_data ) );
if ( data == NULL )
return 0;
BIO_set_init( a, 1 );
BIO_set_data( a, data );
memset( data, 0x00, sizeof( coap_ssl_data ) );
data->mtu = 1280 - 40 - 8;
return 1;
}
static int coap_dgram_destroy( BIO *a ) {
coap_ssl_data *data;
if ( a == NULL )
return 0;
data = (coap_ssl_data *)BIO_get_data( a );
if ( data != NULL )
free( data );
return 1;
}
static int coap_dgram_read( BIO *a, char *out, int outl ) {
int ret = 0;
coap_ssl_data *data = (coap_ssl_data *)BIO_get_data( a );
if ( out != NULL ) {
if ( data != NULL && data->pdu_len > 0 ) {
if ( outl < (int)data->pdu_len ) {
memcpy( out, data->pdu, outl );
ret = outl;
} else {
memcpy( out, data->pdu, data->pdu_len );
ret = (int)data->pdu_len;
}
if ( !data->peekmode ) {
data->pdu_len = 0;
data->pdu = NULL;
}
} else {
ret = -1;
}
BIO_clear_retry_flags( a );
if ( ret < 0 )
BIO_set_retry_read( a );
}
return ret;
}
static int coap_dgram_write( BIO *a, const char *in, int inl ) {
int ret = 0;
coap_ssl_data *data = (coap_ssl_data *)BIO_get_data( a );
if ( data->session ) {
ret = (int)coap_session_send( data->session, (unsigned char*)in, (size_t)inl );
BIO_clear_retry_flags( a );
if ( ret <= 0 )
BIO_set_retry_write( a );
} else {
BIO_clear_retry_flags( a );
ret = -1;
}
return ret;
}
static int coap_dgram_puts( BIO *a, const char *str ) {
return coap_dgram_write( a, str, (int)strlen( str ) );
}
static const uint8_t in6_v4mapped[12] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff };
static long dgram_get_mtu_overhead( const coap_ssl_data *data ) {
if ( data->session && data->session->remote_addr.addr.sa.sa_family == AF_INET6 && memcmp( &data->session->remote_addr.addr.sin6.sin6_addr, in6_v4mapped, sizeof( in6_v4mapped ) ) != 0 )
return 48;
return 28;
}
static long coap_dgram_ctrl( BIO *a, int cmd, long num, void *ptr ) {
long ret = 1;
struct sockaddr *to = NULL;
coap_ssl_data *data = BIO_get_data( a );
switch ( cmd ) {
case BIO_CTRL_GET_CLOSE:
ret = BIO_get_shutdown( a );
break;
case BIO_CTRL_SET_CLOSE:
BIO_set_shutdown( a, (int)num );
break;
ret = 0;
break;
case BIO_CTRL_DGRAM_QUERY_MTU:
case BIO_CTRL_DGRAM_GET_FALLBACK_MTU:
ret = -dgram_get_mtu_overhead( data );
if ( data->session && data->session->remote_addr.addr.sa.sa_family == AF_INET6 && memcmp( &data->session->remote_addr.addr.sin6.sin6_addr, in6_v4mapped, sizeof( in6_v4mapped ) ) != 0 )
ret += 1280;
else
ret += 576;
break;
case BIO_CTRL_DGRAM_GET_MTU:
return (long)data->mtu;
case BIO_CTRL_DGRAM_SET_MTU:
data->mtu = (unsigned)num;
ret = num;
break;
case BIO_CTRL_DGRAM_GET_MTU_OVERHEAD:
ret = dgram_get_mtu_overhead( data );
break;
case BIO_CTRL_DGRAM_SET_PEEK_MODE:
data->peekmode = (unsigned)num;
break;
case BIO_CTRL_DGRAM_CONNECT:
case BIO_C_SET_FD:
case BIO_C_GET_FD:
case BIO_CTRL_DGRAM_SET_DONT_FRAG:
ret = -1;
break;
case BIO_CTRL_DUP:
case BIO_CTRL_FLUSH:
case BIO_CTRL_DGRAM_MTU_DISCOVER:
case BIO_CTRL_DGRAM_SET_CONNECTED:
case BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT:
ret = 1;
break;
case BIO_CTRL_RESET:
case BIO_C_FILE_SEEK:
case BIO_C_FILE_TELL:
case BIO_CTRL_INFO:
case BIO_CTRL_PENDING:
case BIO_CTRL_WPENDING:
case BIO_CTRL_DGRAM_GET_PEER:
case BIO_CTRL_DGRAM_SET_PEER:
case BIO_CTRL_DGRAM_SET_RECV_TIMEOUT:
case BIO_CTRL_DGRAM_GET_RECV_TIMEOUT:
case BIO_CTRL_DGRAM_SET_SEND_TIMEOUT:
case BIO_CTRL_DGRAM_GET_SEND_TIMEOUT:
case BIO_CTRL_DGRAM_GET_SEND_TIMER_EXP:
case BIO_CTRL_DGRAM_GET_RECV_TIMER_EXP:
case BIO_CTRL_DGRAM_MTU_EXCEEDED:
default:
ret = 0;
break;
}
return ret;
}
static int coap_dtls_verify_cert( int ok, X509_STORE_CTX *ctx ) {
if ( dtls_log_level <= LOG_WARNING )
coap_log( LOG_WARNING, "cannot accept DTLS connection with certificate.\n" );
return 0; /* For now, trust no one */
}
static int coap_dtls_generate_cookie( SSL *ssl, unsigned char *cookie, unsigned int *cookie_len ) {
coap_dtls_context_t *dtls = (coap_dtls_context_t *)SSL_CTX_get_app_data( SSL_get_SSL_CTX( ssl ) );
coap_ssl_data *data = (coap_ssl_data*)BIO_get_data( SSL_get_rbio( ssl ) );
int r = HMAC_Init_ex( dtls->cookie_hmac, NULL, 0, NULL, NULL );
r &= HMAC_Update( dtls->cookie_hmac, (const uint8_t*)&data->session->local_addr.addr, (size_t)data->session->local_addr.size );
r &= HMAC_Update( dtls->cookie_hmac, (const uint8_t*)&data->session->remote_addr.addr, (size_t)data->session->remote_addr.size );
r &= HMAC_Final( dtls->cookie_hmac, cookie, cookie_len );
return r;
}
static int coap_dtls_verify_cookie( SSL *ssl, const unsigned char *cookie, unsigned int cookie_len ) {
uint8_t hmac[32];
unsigned len = 32;
if ( coap_dtls_generate_cookie( ssl, hmac, &len ) && cookie_len == len && memcmp( cookie, hmac, len ) == 0 )
return 1;
else
return 0;
}
static unsigned coap_dtls_psk_client_callback( SSL *ssl, const char *hint, char *identity, unsigned int max_identity_len, unsigned char *buf, unsigned max_len ) {
coap_ssl_data *data = (coap_ssl_data*)BIO_get_data( SSL_get_rbio( ssl ) );
if ( !hint )
hint = "";
if ( dtls_log_level <= LOG_DEBUG )
coap_log( LOG_DEBUG, "got psk_identity_hint: '%s'\n", hint );
if ( data->session == NULL || data->session->context == NULL || data->session->context->get_client_psk == NULL )
return 0;
return data->session->context->get_client_psk( data->session, hint, identity, max_identity_len, buf, max_len );
}
static unsigned coap_dtls_psk_server_callback( SSL *ssl, const char *identity, unsigned char *buf, unsigned max_len ) {
coap_ssl_data *data = (coap_ssl_data*)BIO_get_data( SSL_get_rbio( ssl ) );
if ( dtls_log_level <= LOG_DEBUG )
coap_log( LOG_DEBUG, "got psk_identity: '%s'\n", identity );
if ( data->session == NULL || data->session->context == NULL || data->session->context->get_server_psk == NULL )
return 0;
return data->session->context->get_server_psk( data->session, identity, buf, max_len );
}
static void coap_dtls_info_callback( const SSL *ssl, int where, int ret ) {
const char *str;
int w = where &~ SSL_ST_MASK;
if ( w & SSL_ST_CONNECT )
str = "SSL_connect";
else if ( w & SSL_ST_ACCEPT )
str = "SSL_accept";
else
str = "undefined";
if ( where & SSL_CB_LOOP ) {
if ( dtls_log_level <= LOG_INFO )
coap_log( LOG_INFO, "%s:%s\n", str, SSL_state_string_long( ssl ) );
} else if ( where & SSL_CB_ALERT ) {
str = ( where & SSL_CB_READ ) ? "read" : "write";
if ( dtls_log_level <= LOG_WARNING )
coap_log( LOG_WARNING, "SSL3 alert %s:%s:%s\n", str, SSL_alert_type_string_long( ret ), SSL_alert_desc_string_long( ret ) );
} else if ( where & SSL_CB_EXIT ) {
if ( ret == 0 ) {
if ( dtls_log_level <= LOG_WARNING ) {
long e;
coap_log( LOG_WARNING, "%s:failed in %s\n", str, SSL_state_string_long( ssl ) );
while ( ( e = ERR_get_error() ) )
coap_log( LOG_WARNING, " %s at %s:%s\n", ERR_reason_error_string( e ), ERR_lib_error_string( e ), ERR_func_error_string( e ) );
}
} else if ( ret < 0 ) {
if ( dtls_log_level <= LOG_WARNING ) {
int err = SSL_get_error( ssl, ret );
if ( err != SSL_ERROR_WANT_READ && err != SSL_ERROR_WANT_WRITE && err != SSL_ERROR_WANT_CONNECT && err != SSL_ERROR_WANT_ACCEPT && err != SSL_ERROR_WANT_X509_LOOKUP ) {
long e;
coap_log( LOG_WARNING, "%s:error in %s\n", str, SSL_state_string_long( ssl ) );
while ( ( e = ERR_get_error() ) )
coap_log( LOG_WARNING, " %s at %s:%s\n", ERR_reason_error_string( e ), ERR_lib_error_string( e ), ERR_func_error_string( e ) );
}
}
}
}
if ( where == SSL_CB_HANDSHAKE_START && SSL_get_state( ssl ) == TLS_ST_OK ) {
coap_session_t *session = (coap_session_t *)SSL_get_app_data( ssl );
if ( session && session->context )
coap_handle_event( session->context, COAP_EVENT_DTLS_RENEGOTIATE, session );
}
}
static int ssl_library_loaded = 0;
struct coap_dtls_context_t *coap_dtls_new_context( struct coap_context_t *coap_context ) {
struct coap_dtls_context_t *context;
if ( !ssl_library_loaded ) {
SSL_load_error_strings();
SSL_library_init();
ssl_library_loaded = 1;
}
context = ( struct coap_dtls_context_t * )coap_malloc( sizeof( struct coap_dtls_context_t ) );
if ( context ) {
BIO *bio;
uint8_t cookie_secret[32];
memset( context, 0, sizeof( struct coap_dtls_context_t ) );
context->ctx = SSL_CTX_new( DTLSv1_2_method() );
if ( !context->ctx )
goto error;
SSL_CTX_set_app_data( context->ctx, context );
SSL_CTX_set_read_ahead( context->ctx, 1 );
SSL_CTX_set_cipher_list( context->ctx, "TLSv1.2:TLSv1.0" );
if ( !RAND_bytes( cookie_secret, ( int )sizeof( cookie_secret ) ) ) {
if ( dtls_log_level <= LOG_WARNING )
coap_log( LOG_WARNING, "Insufficient entropy for random cookie generation" );
prng( cookie_secret, sizeof( cookie_secret ) );
}
context->cookie_hmac = HMAC_CTX_new();
if ( !HMAC_Init_ex( context->cookie_hmac, cookie_secret, ( int )sizeof( cookie_secret ), EVP_sha256(), NULL ) )
goto error;
/*SSL_CTX_set_verify( context->ctx, SSL_VERIFY_PEER, coap_dtls_verify_cert );*/
SSL_CTX_set_cookie_generate_cb( context->ctx, coap_dtls_generate_cookie );
SSL_CTX_set_cookie_verify_cb( context->ctx, coap_dtls_verify_cookie );
SSL_CTX_set_info_callback( context->ctx, coap_dtls_info_callback );
SSL_CTX_set_psk_client_callback( context->ctx, coap_dtls_psk_client_callback );
SSL_CTX_set_psk_server_callback( context->ctx, coap_dtls_psk_server_callback );
SSL_CTX_use_psk_identity_hint( context->ctx, "" );
context->meth = BIO_meth_new( BIO_TYPE_DGRAM, "coapdgram" );
if ( !context->meth )
goto error;
context->bio_addr = BIO_ADDR_new();
if ( !context->bio_addr )
goto error;
BIO_meth_set_write( context->meth, coap_dgram_write );
BIO_meth_set_read( context->meth, coap_dgram_read );
BIO_meth_set_puts( context->meth, coap_dgram_puts );
BIO_meth_set_ctrl( context->meth, coap_dgram_ctrl );
BIO_meth_set_create( context->meth, coap_dgram_create );
BIO_meth_set_destroy( context->meth, coap_dgram_destroy );
context->ssl = SSL_new( context->ctx );
if ( !context->ssl )
goto error;
bio = BIO_new( context->meth );
if ( !bio )
goto error;
SSL_set_bio( context->ssl, bio, bio );
SSL_set_app_data( context->ssl, NULL );
SSL_set_options( context->ssl, SSL_OP_COOKIE_EXCHANGE );
}
return context;
error:
coap_dtls_free_context( context );
return NULL;
}
void coap_dtls_free_context( struct coap_dtls_context_t *context ) {
if ( context->ssl )
SSL_free( context->ssl );
if ( context->ctx )
SSL_CTX_free( context->ctx );
if ( context->cookie_hmac )
HMAC_CTX_free( context->cookie_hmac );
if ( context->meth )
BIO_meth_free( context->meth );
if ( context->bio_addr )
BIO_ADDR_free( context->bio_addr );
coap_free( context );
}
void * coap_dtls_new_server_session( coap_session_t *session ) {
BIO *nbio = NULL;
SSL *nssl = NULL, *ssl = NULL;
coap_ssl_data *data;
coap_dtls_context_t *dtls = session->context->dtls_context;
int r;
nssl = SSL_new( dtls->ctx );
if ( !nssl )
goto error;
nbio = BIO_new( dtls->meth );
if ( !nbio )
goto error;
SSL_set_bio( nssl, nbio, nbio );
SSL_set_app_data( nssl, NULL );
SSL_set_options( nssl, SSL_OP_COOKIE_EXCHANGE );
ssl = dtls->ssl;
dtls->ssl = nssl;
nssl = NULL;
SSL_set_app_data( ssl, session );
data = (coap_ssl_data*)BIO_get_data( SSL_get_rbio( ssl ) );
data->session = session;
if ( session->context->get_server_hint ) {
char hint[128] = "";
if ( session->context->get_server_hint( session, hint, sizeof( hint ) ) )
SSL_use_psk_identity_hint( ssl, hint );
}
r = SSL_accept( ssl );
if ( r == -1 ) {
int err = SSL_get_error( ssl, r );
if ( err != SSL_ERROR_WANT_READ && err != SSL_ERROR_WANT_WRITE )
r = 0;
}
if ( r == 0 ) {
SSL_free( ssl );
return NULL;
}
return ssl;
error:
if ( nssl )
SSL_free( nssl );
return NULL;
}
void *coap_dtls_new_client_session( coap_session_t *session ) {
BIO *bio = NULL;
SSL *ssl = NULL;
coap_ssl_data *data;
int r;
coap_dtls_context_t *dtls = session->context->dtls_context;
ssl = SSL_new( dtls->ctx );
if ( !ssl )
goto error;
bio = BIO_new( dtls->meth );
if ( !bio )
goto error;
data = (coap_ssl_data *)BIO_get_data( bio );
data->session = session;
SSL_set_bio( ssl, bio, bio );
SSL_set_app_data( ssl, session );
SSL_set_options( ssl, SSL_OP_COOKIE_EXCHANGE );
r = SSL_connect( ssl );
if ( r == -1 ) {
int ret = SSL_get_error( ssl, r );
if ( ret != SSL_ERROR_WANT_READ && ret != SSL_ERROR_WANT_WRITE )
r = 0;
}
if ( r == 0 )
goto error;
return ssl;
error:
if ( ssl )
SSL_free( ssl );
return NULL;
}
void coap_dtls_free_session( coap_session_t *session ) {
SSL *ssl = (SSL *)session->tls;
if ( ssl ) {
if ( !( SSL_get_shutdown( ssl ) & SSL_SENT_SHUTDOWN ) )
SSL_shutdown( ssl );
SSL_free( ssl );
}
}
int coap_dtls_send( coap_session_t *session,
const uint8_t *data, size_t data_len )
{
int r;
SSL *ssl = (SSL *)session->tls;
assert( ssl != NULL );
r = SSL_write( ssl, data, (int)data_len );
if ( r <= 0 ) {
int err = SSL_get_error( ssl, r );
if ( err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE ) {
r = 0;
} else {
if ( dtls_log_level <= LOG_WARNING )
coap_log( LOG_WARNING, "coap_dtls_send: cannot send PDU\n" );
if ( r == SSL_ERROR_ZERO_RETURN ) {
coap_handle_event( session->context, COAP_EVENT_DTLS_CLOSED, session );
coap_session_disconnected( session );
} else {
coap_handle_event( session->context, COAP_EVENT_DTLS_ERROR, session );
}
r = -1;
}
}
return r;
}
int coap_dtls_hello( coap_session_t *session,
const uint8_t *data, size_t data_len )
{
struct coap_dtls_context_t *ctx = session->context->dtls_context;
coap_ssl_data *ssl_data;
int r;
ssl_data = (coap_ssl_data*)BIO_get_data( SSL_get_rbio( ctx->ssl ) );
ssl_data->session = session;
ssl_data->pdu = data;
ssl_data->pdu_len = (unsigned)data_len;
r = DTLSv1_listen( ctx->ssl, ctx->bio_addr );
if ( r <= 0 ) {
int err = SSL_get_error( ctx->ssl, r );
if ( err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE ) {
/* Got a ClientHello, sent-out a VerifyRequest */
r = 0;
}
} else {
/* Got a valid answer to a VerifyRequest */
r = 1;
}
return r;
}
int coap_dtls_receive( coap_session_t *session,
const uint8_t *data, size_t data_len )
{
coap_ssl_data *ssl_data;
SSL *ssl = (SSL *)session->tls;
int r;
assert( ssl != NULL );
int in_init = SSL_in_init( ssl );
uint8_t pdu[COAP_MAX_PDU_SIZE];
ssl_data = (coap_ssl_data*)BIO_get_data( SSL_get_rbio( ssl ) );
ssl_data->pdu = data;
ssl_data->pdu_len = (unsigned)data_len;
r = SSL_read( ssl, pdu, COAP_MAX_PDU_SIZE );
if ( r > 0 ) {
return coap_handle_message( session->context, session, pdu, (size_t)r );
} else {
int err = SSL_get_error( ssl, r );
if ( err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE ) {
if ( in_init && SSL_is_init_finished( ssl ) ) {
coap_handle_event( session->context, COAP_EVENT_DTLS_CONNECTED, session );
coap_session_connected( session );
}
r = 0;
} else if ( err == SSL_ERROR_ZERO_RETURN ) {
/* Got a close notify alert from the remote side */
SSL_shutdown( ssl );
coap_handle_event( session->context, COAP_EVENT_DTLS_CLOSED, session );
coap_session_disconnected( session );
r = -1;
} else {
coap_handle_event( session->context, COAP_EVENT_DTLS_ERROR, session );
r = -1;
}
}
return r;
}
#endif /* HAVE_OPENSSL */
+4 -73
View File
@@ -1,5 +1,5 @@
/*
* coap_dtls.c -- Datagram Transport Layer Support for libcoap
* coap_tinydtls.c -- Datagram Transport Layer Support for libcoap with tinydtls
*
* Copyright (C) 2016 Olaf Bergmann <bergmann@tzi.org>
*
@@ -8,20 +8,15 @@
*/
#include "coap_config.h"
#ifdef HAVE_LIBTINYDTLS
#include "address.h"
#include "debug.h"
#include "mem.h"
#include "coap_dtls.h"
#include "utlist.h"
#ifdef __GNUC__
#define UNUSED __attribute__((unused))
#else /* __GNUC__ */
#define UNUSED
#endif /* __GNUC__ */
#ifdef HAVE_LIBTINYDTLS
#include <tinydtls.h>
#include <dtls.h>
@@ -500,68 +495,4 @@ coap_dtls_handle_message(struct coap_context_t *coap_context,
return -1;
}
#else /* HAVE_LIBTINYDTLS */
int
coap_dtls_is_supported(void) {
return 0;
}
static int dtls_log_level = 0;
void
coap_dtls_set_log_level(int level) {
dtls_log_level = level;
}
int
coap_dtls_get_log_level(void) {
return dtls_log_level;
}
struct coap_dtls_context_t *
coap_dtls_new_context(struct coap_context_t *coap_context UNUSED) {
return NULL;
}
void
coap_dtls_free_context(struct coap_dtls_context_t *dtls_context) {
}
struct coap_dtls_session_t *
coap_dtls_get_session(struct coap_context_t *coap_context UNUSED,
const coap_endpoint_t *local_interface UNUSED,
const coap_address_t *dst UNUSED) {
return NULL;
}
int
coap_dtls_send(struct coap_context_t *coap_context,
struct coap_dtls_session_t *session,
const coap_pdu_t *pdu) {
return -1;
}
struct coap_dtls_session_t *
coap_dtls_new_session(struct coap_dtls_context_t *dtls_context,
const coap_endpoint_t *local_interface,
const coap_address_t *remote) {
return NULL;
}
struct coap_dtls_session_t;
void
coap_dtls_free_session(struct coap_dtls_context_t *dtls_context,
struct coap_dtls_session_t *session) {}
int
coap_dtls_handle_message(struct coap_context_t *coap_context UNUSED,
coap_session_t *session UNUSED,
const unsigned char *data UNUSED,
size_t data_len UNUSED) {
return -1;
}
#endif /* HAVE_LIBTINYDTLS */
#undef UNUSED
+271 -176
View File
@@ -342,6 +342,94 @@ is_wkc(coap_key_t k) {
}
#endif
static unsigned
coap_get_session_client_psk(
const coap_session_t *session,
const char *hint,
char *identity, unsigned max_identity_len,
uint8_t *psk, unsigned max_psk_len
) {
if ( session->psk_identity && session->psk_key && session->psk_key_len > 0 ) {
unsigned identity_len = (unsigned)strlen( session->psk_identity ) + 1;
if ( identity_len <= max_identity_len && session->psk_key_len <= max_psk_len ) {
memcpy( identity, session->psk_identity, identity_len );
memcpy( psk, session->psk_key, session->psk_key_len );
return session->psk_key_len;
}
} else if ( session->context && session->context->psk_key && session->context->psk_key_len > 0 ) {
if ( session->context->psk_key_len <= max_psk_len ) {
identity[0] = 0;
memcpy( psk, session->context->psk_key, session->context->psk_key_len );
return session->context->psk_key_len;
}
}
return 0;
}
static unsigned
coap_get_context_server_psk(
const coap_session_t *session,
const char *identity,
uint8_t *psk, unsigned max_psk_len
) {
const coap_context_t *ctx = session->context;
if ( ctx && ctx->psk_key && ctx->psk_key_len > 0 && ctx->psk_key_len <= max_psk_len ) {
memcpy( psk, ctx->psk_key, ctx->psk_key_len );
return ctx->psk_key_len;
}
return 0;
}
static int
coap_get_context_server_hint(
const coap_session_t *session,
char *hint, unsigned max_hint_len
) {
const coap_context_t *ctx = session->context;
if ( ctx && ctx->psk_hint ) {
unsigned hint_len = (unsigned)strlen( ctx->psk_hint ) + 1;
if ( hint_len <= max_hint_len )
memcpy( hint, ctx->psk_hint, hint_len );
return 1;
}
return 0;
}
void coap_context_set_psk( coap_context_t *ctx, const char *hint,
const uint8_t *key, unsigned key_len ) {
if ( ctx->psk_hint )
coap_free( ctx->psk_hint );
if ( hint ) {
size_t hint_len = strlen( hint ) + 1;
ctx->psk_hint = (char*)coap_malloc( hint_len );
if ( ctx->psk_hint )
memcpy( ctx->psk_hint, hint, hint_len );
else
coap_log( LOG_ERR, "No memory to store PSK hint" );
} else {
ctx->psk_hint = NULL;
}
if ( ctx->psk_key )
coap_free( ctx->psk_key );
if ( key && key_len > 0 ) {
ctx->psk_key = (uint8_t *)coap_malloc( key_len );
if ( ctx->psk_key ) {
memcpy( ctx->psk_key, key, key_len );
ctx->psk_key_len = key_len;
} else {
coap_log( LOG_ERR, "No memory to store PSK key" );
ctx->psk_key_len = 0;
}
} else {
ctx->psk_key = NULL;
ctx->psk_key_len = 0;
}
}
coap_context_t *
coap_new_context(
const coap_address_t *listen_addr) {
@@ -406,6 +494,10 @@ coap_new_context(
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);
@@ -460,6 +552,12 @@ coap_free_context(coap_context_t *context) {
coap_free_endpoint(ep);
}
if ( context->psk_hint )
coap_free( context->psk_hint );
if ( context->psk_key )
coap_free( context->psk_key );
#ifndef WITH_CONTIKI
coap_free_type(COAP_CONTEXT, context);
#endif/* not WITH_CONTIKI */
@@ -529,107 +627,60 @@ coap_send_ack(coap_session_t *session, coap_pdu_t *request) {
if (request && request->hdr->type == COAP_MESSAGE_CON) {
response = coap_pdu_init(COAP_MESSAGE_ACK, 0, request->hdr->id,
sizeof(coap_pdu_t));
if (response) {
if (response)
result = coap_send(session, response);
coap_delete_pdu(response);
}
}
return result;
}
#if !defined(WITH_LWIP)
static coap_tid_t
coap_send_impl(coap_session_t *session, coap_pdu_t *pdu) {
static ssize_t
coap_send_pdu( coap_session_t *session, coap_pdu_t *pdu, int retransmit_cnt ) {
ssize_t bytes_written;
coap_tid_t id = COAP_INVALID_TID;
if ( !session || !pdu )
return id;
#ifdef 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 );
#else
/* Do not send error responses for requests that were received via
* IP multicast.
* FIXME: If No-Response option indicates interest, these responses
* must not be dropped. */
if (coap_is_mcast(&session->local_addr) &&
COAP_RESPONSE_CLASS(pdu->hdr->code) > 2) {
* IP multicast.
* FIXME: If No-Response option indicates interest, these responses
* must not be dropped. */
if ( coap_is_mcast( &session->local_addr ) &&
COAP_RESPONSE_CLASS( pdu->hdr->code ) > 2 ) {
return COAP_DROPPED_RESPONSE;
}
/* Pass to DTLS module for sending if local_interface is for secure
* communication. */
if (session->proto == COAP_PROTO_DTLS) {
struct coap_dtls_session_t *dtls_session = (struct coap_dtls_session_t *)session->tls;
if (dtls_session == NULL) {
coap_log(LOG_WARNING, "coap_send: no DTLS session available\n");
goto finish;
} else {
bytes_written = coap_dtls_send(session->context, dtls_session, pdu);
/* If coap_dtls_send() has returned a negative value we need to
* output a custom error message. Otherwise, we end this branch
* to create a valid transaction id. */
if (bytes_written < 0) {
coap_log(LOG_WARNING, "coap_send: error sending data over DTLS\n");
goto finish;
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, retransmit_cnt );
}
}
} else {
coap_socket_t *sock = &session->sock;
if ( sock->flags == COAP_SOCKET_EMPTY ) {
assert( session->endpoint != NULL );
sock = &session->endpoint->sock;
}
bytes_written = session->context->network_send(sock, session, (uint8_t*)pdu->hdr, pdu->length);
return -1;
}
if (bytes_written >= 0) {
id = ntohs( pdu->hdr->id );
} else {
#if defined(HAVE_WINSOCK2_H)
char *szErrorMsg = NULL;
FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, (DWORD)WSAGetLastError(), MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), (LPSTR)&szErrorMsg, 0, NULL );
coap_log(LOG_CRIT, "coap_send_impl: %s\n", szErrorMsg);
LocalFree( szErrorMsg );
#else
coap_log(LOG_CRIT, "coap_send_impl: %s\n", strerror(errno));
#endif
}
if ( session->state != COAP_SESSION_STATE_ESTABLISHED )
return coap_session_delay_pdu( session, pdu, retransmit_cnt );
finish:
return id;
}
#else /* !defined(WITH_LWIP) */
coap_tid_t
coap_send_impl(coap_session_t *session, coap_pdu_t *pdu) {
coap_tid_t id = COAP_INVALID_TID;
coap_socket_t *sock;
/* Pass to DTLS module for sending if local_interface is for secure
* communication. */
if ( session->proto == COAP_PROTO_DTLS )
bytes_written = coap_dtls_send( session, (const uint8_t*)pdu->hdr, pdu->length );
else
bytes_written = coap_session_send( session, (const uint8_t*)pdu->hdr, pdu->length );
if ( !session || !pdu ) {
return id;
}
#endif /* WITH_LWIP */
/* FIXME: we can't check this here with the existing infrastructure, but we
* should actually check that the pdu is not held by anyone but us. the
* respective pbuf is already exclusively owned by the pdu. */
pbuf_realloc(pdu->pbuf, pdu->length);
coap_transaction_id(&session->remote_addr, pdu, &id);
sock = &session->sock;
if ( sock->flags == COAP_SOCKET_EMPTY )
sock = &session->endpoint->sock;
udp_sendto(sock->pcb, pdu->pbuf,
&session->remote_addr.addr, session->remote_addr.port);
return id;
}
#endif /* !defined(WITH_LWIP) */
coap_tid_t
coap_send(coap_session_t *session, coap_pdu_t *pdu) {
return coap_send_impl(session, pdu);
return bytes_written;
}
coap_tid_t
@@ -644,10 +695,8 @@ coap_send_error(coap_session_t *session,
assert(session);
response = coap_new_error_response(request, code, opts);
if (response) {
if (response)
result = coap_send(session, response);
coap_delete_pdu(response);
}
return result;
}
@@ -659,10 +708,8 @@ coap_send_message_type(coap_session_t *session, coap_pdu_t *request, unsigned ch
if (request) {
response = coap_pdu_init(type, 0, request->hdr->id, sizeof(coap_pdu_t));
if (response) {
if (response)
result = coap_send(session, response);
coap_delete_pdu(response);
}
}
return result;
}
@@ -705,73 +752,95 @@ calc_timeout(unsigned char r) {
}
coap_tid_t
coap_send_confirmed( coap_session_t *session, coap_pdu_t *pdu) {
coap_queue_t *node;
coap_wait_ack( coap_context_t *context, coap_session_t *session,
coap_pdu_t *pdu, int retransmit_cnt )
{
coap_tick_t now;
unsigned char r;
node = coap_new_node();
if (!node) {
debug("coap_send_confirmed: insufficient memory\n");
coap_queue_t *node = coap_new_node();
if ( !node ) {
debug( "coap_wait_ack: insufficient memory\n" );
return COAP_INVALID_TID;
}
node->id = coap_send_impl(session, pdu);
if (COAP_INVALID_TID == node->id) {
debug("coap_send_confirmed: error sending pdu\n");
coap_free_node(node);
return COAP_INVALID_TID;
}
prng((unsigned char *)&r,sizeof(r));
node->id = ntohs( pdu->hdr->id );
node->retransmit_cnt = retransmit_cnt;
prng( (unsigned char *)&r, sizeof( r ) );
/* add timeout in range [ACK_TIMEOUT...ACK_TIMEOUT * ACK_RANDOM_FACTOR] */
node->timeout = calc_timeout(r);
node->timeout = calc_timeout( r ) << retransmit_cnt;
node->session = coap_session_reference( session );
node->pdu = pdu;
/* 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 (session->context->sendqueue == NULL) {
* 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;
session->context->sendqueue_basetime = now;
context->sendqueue_basetime = now;
} else {
/* make node->t relative to context->sendqueue_basetime */
node->t = (now - session->context->sendqueue_basetime) + node->timeout;
node->t = ( now - context->sendqueue_basetime ) + node->timeout;
}
coap_insert_node(&session->context->sendqueue, node);
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);
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 */
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);
/* 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 */
debug( "** %s tid=%d added to retransmit queue (%us)\n",
coap_session_str( node->session ), node->id,
(unsigned)( node->t / COAP_TICKS_PER_SECOND ) );
return node->id;
}
coap_tid_t
coap_send( coap_session_t *session, coap_pdu_t *pdu ) {
ssize_t bytes_written = coap_send_pdu( session, pdu, 0 );
if ( bytes_written == COAP_PDU_DELAYED )
return ntohs( pdu->hdr->id );
if ( bytes_written < 0 ) {
coap_delete_pdu( pdu );
return (coap_tid_t)bytes_written;
}
if ( pdu->hdr->type != COAP_MESSAGE_CON ) {
coap_tid_t id = ntohs( pdu->hdr->id );
coap_delete_pdu( pdu );
return id;
}
return coap_wait_ack( session->context, session, pdu, 0 );
}
coap_tid_t
coap_retransmit(coap_context_t *context, coap_queue_t *node) {
if (!context || !node)
@@ -779,6 +848,8 @@ coap_retransmit(coap_context_t *context, coap_queue_t *node) {
/* re-initialize timeout when maximum number of retransmissions are not reached yet */
if (node->retransmit_cnt < COAP_DEFAULT_MAX_RETRANSMIT) {
ssize_t bytes_written;
node->retransmit_cnt++;
node->t = node->timeout << node->retransmit_cnt;
coap_insert_node(&context->sendqueue, node);
@@ -787,17 +858,32 @@ coap_retransmit(coap_context_t *context, coap_queue_t *node) {
coap_retransmittimer_restart(context);
#endif
debug("** retransmission #%d of transaction %d\n",
node->retransmit_cnt, ntohs(node->pdu->hdr->id));
debug( "** %s tid=%d: retransmission #%d\n",
coap_session_str( node->session ), node->id, node->retransmit_cnt );
bytes_written = coap_send_pdu( node->session, node->pdu, node->retransmit_cnt );
if ( bytes_written == COAP_PDU_DELAYED ) {
/* PDU was not retransmitted immediately because a new handshake is
in progress. Must be remove from the retransmit list as it now
belongs to the delayed list of the session. */
coap_tid_t id = node->id;
node->pdu = NULL;
coap_remove_transaction( &context->sendqueue, node->session, node->id );
return id;
}
if ( bytes_written < 0 )
return (int)bytes_written;
node->id = coap_send_impl(node->session, node->pdu);
return node->id;
}
/* no more retransmissions, remove node from system */
#ifndef WITH_CONTIKI
debug("** removed transaction %d\n", ntohl(node->id));
debug( "** %s tid=%d: give up after %d attempts\n",
coap_session_str( node->session ), node->id, node->retransmit_cnt );
#endif
#ifndef WITHOUT_OBSERVE
@@ -837,7 +923,10 @@ coap_handle_message_for_proto( coap_context_t *ctx, coap_session_t *session, coa
coap_packet_get_memmapped( packet, &data, &data_len );
if ( session->proto == COAP_PROTO_DTLS ) {
result = coap_dtls_handle_message( ctx, session, data, data_len );
if ( session->type == COAP_SESSION_TYPE_HELLO )
result = coap_dtls_hello( session, data, data_len );
else
result = coap_dtls_receive( session, data, data_len );
} else if ( session->proto == COAP_PROTO_UDP ) {
result = coap_handle_message( ctx, session, data, data_len );
}
@@ -856,8 +945,9 @@ coap_read_session( coap_context_t *ctx, coap_session_t *session ) {
bytes_read = ctx->network_read( &session->sock, &packet );
if ( bytes_read < 0 ) {
warn( "coap_read: recv" );
warn( "* %s: read error\n", coap_session_str( session ) );
} else if ( bytes_read > 0 ) {
debug( "* %s: received %zd bytes\n", coap_session_str( session ), bytes_read );
coap_packet_set_addr( packet, &session->remote_addr, &session->local_addr );
result = coap_handle_message_for_proto( ctx, session, packet );
}
@@ -876,11 +966,15 @@ coap_read_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint) {
bytes_read = ctx->network_read(&endpoint->sock, &packet);
if ( bytes_read < 0 ) {
warn("coap_read: recvfrom");
warn( "* %s: read failed\n", coap_endpoint_str( endpoint ) );
} else if ( bytes_read > 0 ) {
coap_session_t *session = coap_endpoint_get_session( endpoint, packet );
if ( session )
if ( session ) {
debug( "* %s: received %zd bytes\n", coap_session_str( session ), bytes_read );
result = coap_handle_message_for_proto( ctx, session, packet );
if ( endpoint->proto == COAP_PROTO_DTLS && session->type == COAP_SESSION_TYPE_HELLO && result == 1 )
coap_endpoint_new_dtls_session( endpoint, packet );
}
}
coap_free_packet(packet);
@@ -1000,7 +1094,7 @@ coap_remove_from_queue(coap_queue_t **queue, coap_session_t *session, coap_tid_t
}
(*node)->next = NULL;
/* coap_delete_node( q ); */
debug("*** removed transaction %u\n", id);
debug( "** %s tid=%d: removed\n", coap_session_str( session ), id );
return 1;
}
@@ -1019,7 +1113,7 @@ coap_remove_from_queue(coap_queue_t **queue, coap_session_t *session, coap_tid_t
q->next = NULL;
*node = q;
/* coap_delete_node( q ); */
debug("*** removed transaction %u\n", id);
debug( "** %s tid=%d: removed\n", coap_session_str( session ), id );
return 1;
}
@@ -1046,7 +1140,7 @@ coap_cancel_all_messages(coap_context_t *context, coap_session_t *session,
context->sendqueue->pdu->hdr->token_length)) {
q = context->sendqueue;
context->sendqueue = q->next;
debug("**** removed transaction %d\n", ntohs(q->pdu->hdr->id));
debug( "** %s tid=%d: removed\n", coap_session_str( session ), q->id );
coap_delete_node(q);
}
@@ -1062,7 +1156,7 @@ coap_cancel_all_messages(coap_context_t *context, coap_session_t *session,
token_match(token, token_length,
q->pdu->hdr->token, q->pdu->hdr->token_length)) {
p->next = q->next;
debug("**** removed transaction %d\n", ntohs(q->pdu->hdr->id));
debug( "** %s tid=%d: removed\n", coap_session_str( session ), q->id );
coap_delete_node(q);
q = p->next;
} else {
@@ -1473,12 +1567,13 @@ handle_request(coap_context_t *context, coap_queue_t *node) {
opt_filter);
}
if (response
&& (no_response(node->pdu, response) != RESPONSE_DROP)
&& (coap_send(node->session, response) == COAP_INVALID_TID)) {
warn("cannot send response for transaction %u\n", node->id);
if (response && (no_response(node->pdu, response) != RESPONSE_DROP)) {
if ( coap_send( node->session, response ) == COAP_INVALID_TID )
warn( "cannot send response for transaction %u\n", node->id );
} else {
coap_delete_pdu( response );
}
coap_delete_pdu(response);
response = NULL;
return;
@@ -1532,35 +1627,37 @@ handle_request(coap_context_t *context, coap_queue_t *node) {
h(context, resource, node->session, node->pdu, &token, response);
respond = no_response(node->pdu, response);
if (respond != RESPONSE_DROP) {
if (observe && (COAP_RESPONSE_CLASS(response->hdr->code) > 2)) {
coap_log(LOG_DEBUG, "removed observer\n");
coap_delete_observer(resource, node->session, &token);
}
if ( respond != RESPONSE_DROP ) {
if ( observe && ( COAP_RESPONSE_CLASS( response->hdr->code ) > 2 ) ) {
coap_log( LOG_DEBUG, "removed observer\n" );
coap_delete_observer( resource, node->session, &token );
}
/* 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->hdr->type == COAP_MESSAGE_ACK)
&& (response->hdr->code == 0)) {
/* Remove token from otherwise-empty acknowledgment PDU */
response->hdr->token_length = 0;
response->length = sizeof(coap_hdr_t);
}
/* 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->hdr->type == COAP_MESSAGE_ACK )
&& ( response->hdr->code == 0 ) ) {
/* Remove token from otherwise-empty acknowledgment PDU */
response->hdr->token_length = 0;
response->length = sizeof( coap_hdr_t );
}
if ((respond == RESPONSE_SEND)
|| /* RESPOND_DEFAULT */
(response->hdr->type != COAP_MESSAGE_NON ||
(response->hdr->code >= 64
&& !coap_mcast_interface(&node->local_if)))) {
if ( ( respond == RESPONSE_SEND )
|| /* RESPOND_DEFAULT */
( response->hdr->type != COAP_MESSAGE_NON ||
( response->hdr->code >= 64
&& !coap_mcast_interface( &node->local_if ) ) ) ) {
if (coap_send(node->session, response) == COAP_INVALID_TID) {
debug("cannot send response for message %d\n", node->pdu->hdr->id);
}
if ( coap_send( node->session, response ) == COAP_INVALID_TID )
debug( "cannot send response for message %d\n", node->pdu->hdr->id );
} else {
coap_delete_pdu(response);
}
} else {
coap_delete_pdu(response);
}
}
coap_delete_pdu(response);
response = NULL;
} else {
warn("cannot generate response\r\n");
@@ -1575,11 +1672,11 @@ handle_request(coap_context_t *context, coap_queue_t *node) {
opt_filter);
if (response && (no_response(node->pdu, response) != RESPONSE_DROP)) {
if (coap_send(node->session, response) == COAP_INVALID_TID) {
debug("cannot send response for transaction %u\n", node->id);
}
if (coap_send(node->session, response) == COAP_INVALID_TID)
debug("cannot send response for transaction %d\n", node->id);
} else {
coap_delete_pdu( response );
}
coap_delete_pdu(response);
response = NULL;
}
@@ -1674,14 +1771,12 @@ coap_dispatch(coap_context_t *context, coap_queue_t *rcvd) {
response =
coap_new_error_response(rcvd->pdu, COAP_RESPONSE_CODE(402), opt_filter);
if (!response)
warn("coap_dispatch: cannot create error response\n");
else {
if (coap_send(rcvd->session, response) == COAP_INVALID_TID) {
if ( !response ) {
warn( "coap_dispatch: cannot create error response\n" );
} else {
if (coap_send(rcvd->session, response) == COAP_INVALID_TID)
warn("coap_dispatch: error sending response\n");
}
coap_delete_pdu(response);
}
}
goto cleanup;
}
+2 -4
View File
@@ -679,15 +679,13 @@ coap_notify_observers(coap_context_t *context, coap_resource_t *r) {
* COAP_RESPONSE_CLASS(response->hdr->code) > 2
*/
if (response->hdr->type == COAP_MESSAGE_CON) {
tid = coap_send_confirmed(obs->session, response);
obs->non_cnt = 0;
} else {
tid = coap_send(obs->session, response);
obs->non_cnt++;
}
if (COAP_INVALID_TID == tid || response->hdr->type != COAP_MESSAGE_CON)
coap_delete_pdu(response);
tid = coap_send( obs->session, response );
if (COAP_INVALID_TID == tid)
{
debug("coap_check_notify: sending failed, resource stays partially dirty\n");
+453
View File
@@ -0,0 +1,453 @@
/* session.c -- Session management for libcoap
*
* Copyright (C) 2017 Jean-Claue Michelou <jcm@spinetix.com>
*
* This file is part of the CoAP library libcoap. Please see
* README for terms of use.
*/
#ifndef _COAP_SESSION_H_
#define _COAP_SESSION_H_
#include "coap_config.h"
#include "coap_io.h"
#include "coap_dtls.h"
#include "session.h"
#include "net.h"
#include "debug.h"
#include "mem.h"
#include "utlist.h"
#include <stdio.h>
static void coap_free_session( coap_session_t *session );
coap_session_t *
coap_session_reference( coap_session_t *session ) {
++session->ref;
return session;
}
void
coap_session_release( coap_session_t *session ) {
if ( session ) {
assert( session->ref > 0 );
if ( session->ref > 0 )
--session->ref;
if ( session->ref == 0 && session->type == COAP_SESSION_TYPE_CLIENT )
coap_free_session( session );
}
}
static coap_session_t *
coap_make_session( coap_proto_t proto, coap_session_type_t type, const coap_address_t *local, const coap_address_t *remote, int ifindex, coap_context_t *context, coap_endpoint_t *endpoint ) {
coap_session_t *session = (coap_session_t*)coap_malloc( sizeof( coap_session_t ) );
if ( !session )
return NULL;
memset( session, 0, sizeof( *session ) );
session->proto = proto;
session->type = type;
if ( local )
coap_address_copy( &session->local_addr, local );
else
coap_address_init( &session->local_addr );
if ( remote )
coap_address_copy( &session->remote_addr, remote );
else
coap_address_init( &session->remote_addr );
session->ifindex = ifindex;
session->context = context;
session->endpoint = endpoint;
return session;
}
static void
coap_free_session( coap_session_t *session ) {
coap_pdu_queue_t *q, *tmp;
if ( !session )
return;
assert( session->ref == 0 );
if ( session->ref )
return;
if ( session->proto == COAP_PROTO_DTLS )
coap_dtls_free_session( session );
if ( session->sock.flags != COAP_SOCKET_EMPTY && session->sock.fd != COAP_INVALID_SOCKET )
coap_closesocket( session->sock.fd );
if ( session->endpoint ) {
if ( session->endpoint->sessions )
LL_DELETE( session->endpoint->sessions, session );
} else if ( session->context ) {
if ( session->context->sessions )
LL_DELETE( session->context->sessions, session );
}
if ( session->psk_identity )
coap_free( session->psk_identity );
if ( session->psk_key )
coap_free( session->psk_key );
LL_FOREACH_SAFE( session->sendqueue, q, tmp ) {
if ( q->pdu )
coap_delete_pdu( q->pdu );
coap_free( q );
}
debug( "*** %s: session closed\n", coap_session_str( session ) );
coap_free( session );
}
ssize_t coap_session_send( coap_session_t *session, const uint8_t *data, size_t datalen ) {
ssize_t bytes_written;
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( sock, session, data, datalen );
if ( bytes_written == datalen )
debug( "* %s: sent %zd bytes\n", coap_session_str( session ), datalen );
else
debug( "* %s: failed to send %zd bytes\n", coap_session_str( session ), datalen );
return bytes_written;
}
ssize_t
coap_session_delay_pdu( coap_session_t *session, coap_pdu_t *pdu, int retransmit_cnt ) {
coap_pdu_queue_t *q = (coap_pdu_queue_t*)coap_malloc( sizeof( coap_pdu_queue_t ) );
if ( q == NULL )
return COAP_INVALID_TID;
q->next = NULL;
q->pdu = pdu;
q->retransmit_cnt = retransmit_cnt;
LL_APPEND( session->sendqueue, q );
debug( "** %s tid=%d: delayed\n", coap_session_str( session ), (int)ntohs(q->pdu->hdr->id) );
return COAP_PDU_DELAYED;
}
void coap_session_connected( coap_session_t *session ) {
debug( "*** %s: session connected\n", coap_session_str( session ) );
session->state = COAP_SESSION_STATE_ESTABLISHED;
while ( session->sendqueue && session->state == COAP_SESSION_STATE_ESTABLISHED ) {
ssize_t bytes_written;
coap_pdu_queue_t *q = session->sendqueue;
session->sendqueue = q->next;
debug( "** %s tid=%d: transmitted after delay\n", coap_session_str( session ), (int)ntohs( q->pdu->hdr->id ) );
if ( session->proto == COAP_PROTO_DTLS )
bytes_written = coap_dtls_send( session, (const uint8_t*)q->pdu->hdr, q->pdu->length );
else
bytes_written = coap_session_send( session, (const uint8_t*)q->pdu->hdr, q->pdu->length );
if ( bytes_written > 0 && q->pdu->hdr->type == COAP_MESSAGE_CON ) {
if ( coap_wait_ack( session->context, session, q->pdu, q->retransmit_cnt ) >= 0 )
q->pdu = NULL;
}
if ( q->pdu )
coap_delete_pdu( q->pdu );
coap_free( q );
if ( bytes_written < 0 )
break;
}
}
void coap_session_disconnected( coap_session_t *session ) {
debug( "*** %s: session disconnected\n", coap_session_str( session ) );
session->state = COAP_SESSION_STATE_NONE;
while ( session->sendqueue ) {
coap_pdu_queue_t *q = session->sendqueue;
session->sendqueue = q->next;
debug( "** %s tid=%d: not transmitted after delay\n", coap_session_str( session ), (int)ntohs( q->pdu->hdr->id ) );
if ( q->pdu->hdr->type == COAP_MESSAGE_CON ) {
if ( coap_wait_ack( session->context, session, q->pdu, q->retransmit_cnt ) >= 0 )
q->pdu = NULL;
}
if ( q->pdu )
coap_delete_pdu( q->pdu );
coap_free( q );
}
}
coap_session_t *
coap_endpoint_get_session( coap_endpoint_t *endpoint, const coap_packet_t *packet ) {
coap_session_t *session = NULL;
LL_FOREACH( endpoint->sessions, session ) {
if ( session->ifindex == packet->ifindex && coap_address_equals( &session->local_addr, &packet->dst ) && coap_address_equals( &session->remote_addr, &packet->src ) )
return session;
}
if ( endpoint->proto == COAP_PROTO_DTLS ) {
session = &endpoint->hello;
coap_address_copy( &session->local_addr, &packet->dst );
coap_address_copy( &session->remote_addr, &packet->src );
session->ifindex = packet->ifindex;
} else {
session = coap_make_session( endpoint->proto, COAP_SESSION_TYPE_SERVER, &packet->dst, &packet->src, packet->ifindex, endpoint->context, endpoint );
if ( session ) {
if ( endpoint->proto == COAP_PROTO_UDP )
session->state = COAP_SESSION_STATE_ESTABLISHED;
LL_PREPEND( endpoint->sessions, session );
debug( "*** %s: new incoming session\n", coap_session_str( session ) );
}
}
return session;
}
coap_session_t *
coap_endpoint_new_dtls_session( coap_endpoint_t *endpoint,
const coap_packet_t *packet )
{
coap_session_t *session = coap_make_session( COAP_PROTO_DTLS, COAP_SESSION_TYPE_SERVER, &packet->dst, &packet->src, packet->ifindex, endpoint->context, endpoint );
if ( session ) {
session->state = COAP_SESSION_STATE_HANDSHAKE;
session->tls = coap_dtls_new_server_session( session );
if ( session->tls ) {
session->state = COAP_SESSION_STATE_HANDSHAKE;
LL_PREPEND( endpoint->sessions, session );
debug( "*** %s: new incoming session\n", coap_session_str( session ) );
} else {
coap_free_session( session );
}
}
return session;
}
static coap_session_t *
coap_session_create_client(
coap_context_t *ctx,
const coap_address_t *local_if,
const coap_address_t *server,
coap_proto_t proto
) {
coap_session_t *session = NULL;
int on = 1, off = 0;
assert( server );
assert( proto != COAP_PROTO_NONE );
session = coap_make_session( proto, COAP_SESSION_TYPE_CLIENT, local_if, server, 0, ctx, NULL );
if ( !session )
goto error;
if ( !coap_socket_connect_udp( &session->sock, local_if, server,
proto == COAP_PROTO_DTLS ? COAPS_DEFAULT_PORT : COAP_DEFAULT_PORT,
&session->local_addr, &session->remote_addr
)
) {
goto error;
}
session->ref = 1;
session->sock.flags = COAP_SOCKET_NOT_EMPTY | COAP_SOCKET_CONNECTED | COAP_SOCKET_WANT_DATA;
if ( local_if )
session->sock.flags |= COAP_SOCKET_BOUND;
LL_PREPEND( ctx->sessions, session );
return session;
error:
if ( session )
coap_free_session( session );
return NULL;
}
static coap_session_t *
coap_session_connect( coap_session_t *session ) {
if ( session->proto == COAP_PROTO_UDP ) {
session->state = COAP_SESSION_STATE_ESTABLISHED;
} else if ( session->proto == COAP_PROTO_DTLS ) {
session->tls = coap_dtls_new_client_session( session );
if ( session->tls ) {
session->state = COAP_SESSION_STATE_HANDSHAKE;
} else {
coap_free_session( session );
return NULL;
}
}
return session;
}
coap_session_t *coap_new_client_session(
coap_context_t *ctx,
const coap_address_t *local_if,
const coap_address_t *server,
coap_proto_t proto
) {
coap_session_t *session = coap_session_create_client( ctx, local_if, server, proto );
if ( session ) {
debug( "*** %s: new outgoing session\n", coap_session_str( session ) );
session = coap_session_connect( session );
}
return session;
}
coap_session_t *coap_new_client_session_psk(
coap_context_t *ctx,
const coap_address_t *local_if,
const coap_address_t *server,
coap_proto_t proto,
const char *identity,
const uint8_t *key,
size_t key_len
) {
coap_session_t *session = coap_session_create_client( ctx, local_if, server, proto );
if ( !session )
return NULL;
if ( identity ) {
unsigned identity_len = (unsigned)strlen( identity ) + 1;
session->psk_identity = (char*)coap_malloc( identity_len );
if ( session->psk_identity ) {
memcpy( session->psk_identity, identity, identity_len );
} else {
coap_log( LOG_WARNING, "Cannot store session PSK identity" );
}
}
if ( key && key_len > 0 ) {
session->psk_key = (uint8_t*)coap_malloc( key_len );
if ( session->psk_key ) {
memcpy( session->psk_key, key, key_len );
session->psk_key_len = key_len;
} else {
coap_log( LOG_WARNING, "Cannot store session PSK key" );
}
}
debug( "*** %s: new outgoing session\n", coap_session_str( session ) );
return coap_session_connect( session );
}
coap_endpoint_t *
coap_new_endpoint( coap_context_t *context, const coap_address_t *listen_addr, coap_proto_t proto ) {
int on = 1, off = 0;
struct coap_endpoint_t *ep = NULL;
assert( context );
assert( listen_addr );
assert( proto != COAP_PROTO_NONE );
if ( proto == COAP_PROTO_DTLS && !coap_dtls_is_supported() ) {
coap_log( LOG_CRIT, "coap_new_endpoint: DTLS not supported\n" );
goto error;
}
ep = coap_malloc_endpoint();
if ( !ep ) {
coap_log( LOG_WARNING, "coap_new_endpoint: malloc" );
goto error;
}
memset( ep, 0, sizeof( struct coap_endpoint_t ) );
ep->context = context;
ep->proto = proto;
if ( !coap_socket_bind_udp( &ep->sock, listen_addr, &ep->bind_addr ) )
goto error;
#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( &ep->bind_addr, addr_str, INET6_ADDRSTRLEN + 8 ) ) {
debug( "created %s endpoint %s\n",
ep->proto == COAP_PROTO_DTLS ? "DTLS " : "UDP",
addr_str );
}
}
#endif /* NDEBUG */
ep->sock.flags = COAP_SOCKET_NOT_EMPTY | COAP_SOCKET_BOUND | COAP_SOCKET_WANT_DATA;
if ( proto == COAP_PROTO_DTLS ) {
ep->hello.proto = proto;
ep->hello.type = COAP_SESSION_TYPE_HELLO;
ep->hello.context = context;
ep->hello.endpoint = ep;
}
LL_PREPEND( context->endpoint, ep );
return ep;
error:
coap_free_endpoint( ep );
return NULL;
}
void
coap_free_endpoint( coap_endpoint_t *ep ) {
if ( ep ) {
coap_session_t *session;
if ( ep->sock.flags != COAP_SOCKET_EMPTY )
coap_socket_close( &ep->sock );
LL_FOREACH( ep->sessions, session ) {
assert( session->ref == 0 );
if ( session->ref == 0 ) {
if ( session->sock.flags != COAP_SOCKET_EMPTY )
coap_socket_close( &session->sock );
}
}
coap_mfree_endpoint( ep );
}
}
const char *coap_session_str( const coap_session_t *session ) {
static char szSession[256];
char *p = szSession, *end = szSession + sizeof( szSession );
if ( coap_print_addr( &session->local_addr, (unsigned char*)p, end - p ) > 0 )
p += strlen( p );
if ( p + 6 < end ) {
strcpy( p, " <-> " );
p += 5;
}
if ( p + 1 < end ) {
if ( coap_print_addr( &session->remote_addr, (unsigned char*)p, end - p ) > 0 )
p += strlen( p );
}
if ( session->ifindex > 0 && p + 1 < end )
p += snprintf( p, end - p, " (if%d)", session->ifindex );
if ( p + 6 < end ) {
if ( session->proto == COAP_PROTO_UDP ) {
strcpy( p, " UDP" );
p += 4;
} else if ( session->proto == COAP_PROTO_DTLS ) {
strcpy( p, " DTLS" );
p += 5;
} else {
strcpy( p, " NONE" );
p += 5;
}
}
return szSession;
}
const char *coap_endpoint_str( const coap_endpoint_t *endpoint ) {
static char szEndpoint[128];
char *p = szEndpoint, *end = szEndpoint + sizeof( szEndpoint );
if ( coap_print_addr( &endpoint->bind_addr, (unsigned char*)p, end - p ) > 0 )
p += strlen( p );
if ( p + 6 < end ) {
if ( endpoint->proto == COAP_PROTO_UDP ) {
strcpy( p, " UDP" );
p += 4;
} else if ( endpoint->proto == COAP_PROTO_DTLS ) {
strcpy( p, " DTLS" );
p += 5;
} else {
strcpy( p, " NONE" );
p += 5;
}
}
return szEndpoint;
}
#endif /* _COAP_SESSION_H_ */