diff --git a/Makefile.am b/Makefile.am index 05e07b09..2365f1b3 100644 --- a/Makefile.am +++ b/Makefile.am @@ -63,6 +63,7 @@ libcoap_@LIBCOAP_API_VERSION@_la_SOURCES = \ src/option.c \ src/pdu.c \ src/resource.c \ + src/session.c \ src/str.c \ src/subscribe.c \ src/uri.c @@ -92,6 +93,7 @@ libcoap_include_HEADERS = \ $(top_srcdir)/include/coap/pdu.h \ $(top_srcdir)/include/coap/prng.h \ $(top_srcdir)/include/coap/resource.h \ + $(top_srcdir)/include/coap/session.h \ $(top_srcdir)/include/coap/str.h \ $(top_srcdir)/include/coap/subscribe.h \ $(top_srcdir)/include/coap/uri.h \ diff --git a/Makefile.libcoap b/Makefile.libcoap index 122e0faa..eed7054e 100644 --- a/Makefile.libcoap +++ b/Makefile.libcoap @@ -1,4 +1,4 @@ -libcoap_src = pdu.c net.c debug.c encode.c uri.c subscribe.c resource.c hashkey.c str.c option.c async.c block.c mem.c coap_io.c +libcoap_src = pdu.c net.c debug.c encode.c uri.c subscribe.c resource.c hashkey.c str.c option.c async.c block.c mem.c coap_io.c session.c libcoap_dir := $(filter %libcoap,$(APPDS)) vpath %c $(libcoap_dir)/src diff --git a/coap_config.h.windows b/coap_config.h.windows index ee3216a4..7255b030 100644 --- a/coap_config.h.windows +++ b/coap_config.h.windows @@ -64,6 +64,8 @@ #define snprintf _snprintf #endif +#define HAVE_OPENSSL 1 + /* Define to the address where bug reports for this package should be sent. */ #define PACKAGE_BUGREPORT "libcoap-developers@lists.sourceforge.net" diff --git a/examples/client.c b/examples/client.c index 7bd58d09..038c1750 100644 --- a/examples/client.c +++ b/examples/client.c @@ -248,16 +248,10 @@ clear_obs(coap_context_t *ctx, coap_session_t *session) { coap_show_pdu(pdu); - if (pdu->hdr->type == COAP_MESSAGE_CON) - tid = coap_send_confirmed(session, pdu); - else - tid = coap_send(session, pdu); + tid = coap_send(session, pdu); - if (tid == COAP_INVALID_TID) { + if (tid == COAP_INVALID_TID) debug("clear_obs: error sending new request"); - coap_delete_pdu(pdu); - } else if (pdu->hdr->type != COAP_MESSAGE_CON) - coap_delete_pdu(pdu); return tid; error: @@ -414,19 +408,13 @@ message_handler(struct coap_context_t *ctx, ((coap_opt_block_num(block_opt) + 1) << 4) | COAP_OPT_BLOCK_SZX(block_opt)), buf); - if (pdu->hdr->type == COAP_MESSAGE_CON) - tid = coap_send_confirmed(session, pdu); - else - tid = coap_send(session, pdu); + tid = coap_send(session, pdu); if (tid == COAP_INVALID_TID) { debug("message_handler: error sending new request"); - coap_delete_pdu(pdu); } else { wait_ms = wait_seconds * 1000; wait_ms_reset = 1; - if (pdu->hdr->type != COAP_MESSAGE_CON) - coap_delete_pdu(pdu); } return; @@ -501,19 +489,14 @@ message_handler(struct coap_context_t *ctx, block.num, block.szx); coap_show_pdu(pdu); - if (pdu->hdr->type == COAP_MESSAGE_CON) - tid = coap_send_confirmed(session, pdu); - else - tid = coap_send(session, pdu); + + tid = coap_send(session, pdu); if (tid == COAP_INVALID_TID) { debug("message_handler: error sending new request"); - coap_delete_pdu(pdu); } else { wait_ms = wait_seconds * 1000; wait_ms_reset = 1; - if (pdu->hdr->type != COAP_MESSAGE_CON) - coap_delete_pdu(pdu); } return; @@ -541,10 +524,8 @@ message_handler(struct coap_context_t *ctx, } /* finally send new request, if needed */ - if (pdu && coap_send(session, pdu) == COAP_INVALID_TID) { + if (pdu && coap_send(session, pdu) == COAP_INVALID_TID) debug("message_handler: error sending response"); - } - coap_delete_pdu(pdu); /* our job is done, we can exit at any time */ ready = coap_check_option(received, COAP_OPTION_SUBSCRIPTION, &opt_iter) == NULL; @@ -1061,10 +1042,9 @@ get_session( const char *local_port, coap_proto_t proto, coap_address_t *dst, - const uint8_t *identity, - size_t identity_len, + const char *identity, const uint8_t *key, - size_t key_len + unsigned key_len ) { coap_session_t *session = NULL; @@ -1092,7 +1072,7 @@ get_session( bind_addr.size = rp->ai_addrlen; memcpy( &bind_addr.addr, rp->ai_addr, rp->ai_addrlen ); if ( identity && key && proto == COAP_PROTO_DTLS ) - session = coap_new_client_session_psk( ctx, &bind_addr, dst, proto, identity, identity_len, key, key_len ); + session = coap_new_client_session_psk( ctx, &bind_addr, dst, proto, identity, key, key_len ); else session = coap_new_client_session( ctx, &bind_addr, dst, proto ); if ( session ) @@ -1102,7 +1082,7 @@ get_session( freeaddrinfo( result ); } else { if ( identity && key && proto == COAP_PROTO_DTLS ) - session = coap_new_client_session_psk( ctx, NULL, dst, proto, identity, identity_len, key, key_len ); + session = coap_new_client_session_psk( ctx, NULL, dst, proto, identity, key, key_len ); else session = coap_new_client_session( ctx, NULL, dst, proto ); } @@ -1125,7 +1105,7 @@ main(int argc, char **argv) { int opt, res; coap_log_t log_level = LOG_WARNING; coap_tid_t tid = COAP_INVALID_TID; - unsigned char user[MAX_USER], key[MAX_KEY]; + unsigned char user[MAX_USER + 1], key[MAX_KEY]; ssize_t user_length = 0, key_length = 0; int create_uri_opts = 1; @@ -1197,6 +1177,8 @@ main(int argc, char **argv) { break; case 'u' : user_length = cmdline_read_user(optarg, user, MAX_USER); + if ( user_length >= 0 ) + user[user_length] = 0; break; case 'U' : create_uri_opts = 0; @@ -1258,8 +1240,8 @@ main(int argc, char **argv) { node_str[0] ? node_str : NULL, port_str, coap_uri_scheme_is_secure( &uri ) ? COAP_PROTO_DTLS : COAP_PROTO_UDP, &dst, - user_length > 0 ? user : NULL, (size_t)user_length, - key_length > 0 ? key : NULL, (size_t)key_length + user_length > 0 ? (const char *)user : NULL, + key_length > 0 ? key : NULL, (unsigned)key_length ); if ( !session ) { @@ -1314,13 +1296,7 @@ main(int argc, char **argv) { } #endif - if (pdu->hdr->type == COAP_MESSAGE_CON) - tid = coap_send_confirmed(session, pdu); - else - tid = coap_send(session, pdu); - - if (pdu->hdr->type != COAP_MESSAGE_CON || tid == COAP_INVALID_TID) - coap_delete_pdu(pdu); + tid = coap_send(session, pdu); wait_ms = wait_seconds * 1000; debug("timeout is set to %u seconds\n", wait_seconds); @@ -1329,16 +1305,7 @@ main(int argc, char **argv) { result = coap_run_once( ctx, wait_ms == 0 ? obs_ms : obs_ms == 0 ? wait_ms : min( wait_ms, obs_ms ) ); - if ( result < 0 ) { /* error */ -#ifdef _WIN32 - 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 ); - fprintf( stderr, "select: %s\n", szErrorMsg ); - LocalFree( szErrorMsg ); -#else - perror("select"); -#endif - } else { + if ( result >= 0 ) { if ( wait_ms > 0 && !wait_ms_reset ) { if ( (unsigned)result >= wait_ms ) { info( "timeout\n" ); @@ -1367,12 +1334,12 @@ main(int argc, char **argv) { result = 0; finish: - close_output(); coap_delete_list(optlist); coap_session_release( session ); coap_free_context( ctx ); coap_cleanup(); + close_output(); return result; } diff --git a/examples/coap-rd.c b/examples/coap-rd.c index f810b454..92c0e903 100644 --- a/examples/coap-rd.c +++ b/examples/coap-rd.c @@ -194,7 +194,6 @@ hnd_put_resource(coap_context_t *ctx UNUSED_PARAM, debug("hnd_get_rd: cannot send response for message %d\n", request->hdr->id); } - coap_delete_pdu(response); #endif } @@ -658,15 +657,8 @@ join(coap_context_t *ctx, char *group_name) { result = setsockopt(ctx->endpoint->sock.fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, (char *)&mreq, sizeof(mreq) ); - if ( result < 0 ) { -#ifdef _WIN32 - 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 ); - fprintf( stderr, "join: setsockopt: %s\n", szErrorMsg ); - LocalFree( szErrorMsg ); -#else - perror("join: setsockopt"); -#endif + if ( result == COAP_SOCKET_ERROR ) { + fprintf( stderr, "join: setsockopt: %s\n", coap_socket_strerror() ); } } else { result = -1; @@ -725,19 +717,8 @@ main(int argc, char **argv) { while ( !quit ) { result = coap_run_once( ctx, COAP_RESOURCE_CHECK_TIME * 1000 ); - - if ( result < 0 ) { /* error */ -#ifdef _WIN32 - 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 ); - fprintf( stderr, "select: %s\n", szErrorMsg ); - LocalFree( szErrorMsg ); -#else - if (errno != EINTR) - perror("select"); -#endif - } else { - /* coap_check_resource_list( ctx ); */ + if ( result >= 0 ) { + /* coap_check_resource_list( ctx ); */ } } diff --git a/examples/coap-server.c b/examples/coap-server.c index f38c1eb5..70114db5 100644 --- a/examples/coap-server.c +++ b/examples/coap-server.c @@ -278,7 +278,6 @@ check_async(coap_context_t *ctx, debug("check_async: cannot send response for message %d\n", ntohs(response->hdr->id)); } - coap_delete_pdu(response); coap_remove_async(ctx, async->session, async->id, &tmp); coap_free_async(async); async = NULL; @@ -324,19 +323,9 @@ init_resources(coap_context_t *ctx) { static void fill_keystore(coap_context_t *ctx) { - /* - coap_keystore_item_t *psk; - static unsigned char user[] = "Client_identity"; - size_t user_length = sizeof(user) - 1; - static unsigned char key[] = "secretPSK"; - size_t key_length = sizeof(key) - 1; - - psk = coap_keystore_new_psk(NULL, 0, user, user_length, - key, key_length, 0); - if (!psk || !coap_keystore_store_item(ctx->keystore, psk, NULL)) { - coap_log(LOG_WARNING, "cannot store key\n"); - } - */ + static uint8_t key[] = "secretPSK"; + size_t key_len = sizeof( key ) - 1; + coap_context_set_psk( ctx, "CoAP", key, key_len ); } static void @@ -472,15 +461,8 @@ join(coap_context_t *ctx, char *group_name){ if (ctx->endpoint) { result = setsockopt(ctx->endpoint->sock.fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, (char *)&mreq, sizeof(mreq)); - if (result < 0) { -#ifdef _WIN32 - 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 ); - fprintf( stderr, "join: setsockopt: %s\n", szErrorMsg ); - LocalFree( szErrorMsg ); -#else - perror("join: setsockopt"); -#endif + if ( result == COAP_SOCKET_ERROR ) { + fprintf( stderr, "join: setsockopt: %s\n", coap_socket_strerror() ); } } else { result = -1; diff --git a/examples/etsi_iot_01.c b/examples/etsi_iot_01.c index ec2df7bf..153163fb 100644 --- a/examples/etsi_iot_01.c +++ b/examples/etsi_iot_01.c @@ -488,7 +488,6 @@ check_async(coap_context_t *ctx, coap_tick_t now) { debug("check_async: cannot send response for message %d\n", ntohs(response->hdr->id)); } - coap_delete_pdu(response); coap_remove_async(ctx, async->id, &tmp); coap_free_async(async); diff --git a/examples/tiny.c b/examples/tiny.c index 86cef841..b309ce45 100644 --- a/examples/tiny.c +++ b/examples/tiny.c @@ -135,7 +135,6 @@ main(int argc, char **argv) { return -1; coap_send( ctx, (struct sockaddr *)&dst, sizeof(dst), pdu ); - coap_delete_pdu(pdu); tv.tv_sec = 5; tv.tv_usec = 0; diff --git a/include/coap/coap_dtls.h b/include/coap/coap_dtls.h index 28397dcb..22150a3d 100644 --- a/include/coap/coap_dtls.h +++ b/include/coap/coap_dtls.h @@ -11,6 +11,7 @@ #define _COAP_DTLS_H_ #include "net.h" +#include "session.h" #include "pdu.h" /** @@ -27,7 +28,6 @@ #define COAP_DTLS_MAX_PACKET_SIZE COAP_MAX_PDU_SIZE struct coap_dtls_context_t; -struct coap_dtls_session_t; /** Returns 1 if support for DTLS is enabled, or 0 otherwise. */ int coap_dtls_is_supported(void); @@ -45,32 +45,72 @@ int coap_dtls_get_log_level(void); * @param coap_context The CoAP context where the DTLS object shall be used. * @return A DTLS context object or NULL on error; */ -struct coap_dtls_context_t *coap_dtls_new_context(struct coap_context_t *coap_context); +struct coap_dtls_context_t * +coap_dtls_new_context( coap_context_t *coap_context ); /** Releases the storage allocated for @p dtls_context. */ -void coap_dtls_free_context(struct coap_dtls_context_t *dtls_context); +void coap_dtls_free_context( struct coap_dtls_context_t *dtls_context ); -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); +/** + * Create a new client-side session. This should send a HELLO to the server. + * + * @param session The CoAP session + * @return Opaque handle to underlying TLS library object containing security parameters for the session. +*/ +void *coap_dtls_new_client_session( coap_session_t *session ); -void coap_dtls_free_session(struct coap_dtls_context_t *dtls_context, - struct coap_dtls_session_t *session); +/** +* Create a new server-side session. +* Called after coap_dtls_hello() has returned 1, signalling that a validated HELLO was received from a client. +* This should send a HELLO to the server. +* +* @param session The CoAP session +* @return Opaque handle to underlying TLS library object containing security parameters for the session. +*/ +void *coap_dtls_new_server_session( coap_session_t *session ); -struct coap_dtls_session_t * -coap_dtls_get_session(struct coap_context_t *coap_context, - const coap_endpoint_t *local_interface, - const coap_address_t *dst); +/** + * Terminates the DTLS session (may send an ALERT if necessary) then frees the underlying TLS library object containing security parameters for the session. + * + * @param session The CoAP session + */ +void coap_dtls_free_session( coap_session_t *session ); -int coap_dtls_send(struct coap_context_t *coap_context, - struct coap_dtls_session_t *session, - const coap_pdu_t *pdu); +/** +* Send data to a DTLS peer. +* +* @param session The CoAP session +* @param pdu The CoAP PDU +* @return 0 if this would be blocking, -1 if there is an error or the number of cleartext bytes sent +*/ +int coap_dtls_send( coap_session_t *session, + const uint8_t *data, + size_t data_len ); -int coap_dtls_handle_message(struct coap_context_t *coap_context, - coap_session_t *session, - const uint8_t *data, - size_t data_len); +/** +* Handling incoming data from a DTLS peer. +* +* @param session The CoAP session +* @param data Encrypted datagram +* @param data_len Encrypted datagram size +* @return result of coap_handle_message on the decrypted CoAP PDU or -1 for error. +*/ +int coap_dtls_receive( coap_session_t *session, + const uint8_t *data, + size_t data_len); + +/** +* Handling client HELLO messages from a new candiate peer. +* Note that session->tls is empty. +* +* @param session The CoAP session +* @param data Encrypted datagram +* @param data_len Encrypted datagram size +* @return 0 if a cookie verification message has been sent, 1 if the HELLO contains a valid cookie and a server session should be created, -1 if the message is invalid. +*/ +int coap_dtls_hello( coap_session_t *session, + const uint8_t *data, + size_t data_len ); /** @} */ diff --git a/include/coap/coap_io.h b/include/coap/coap_io.h index 5cab3c43..1199d48a 100644 --- a/include/coap/coap_io.h +++ b/include/coap/coap_io.h @@ -36,6 +36,9 @@ typedef struct coap_session_t coap_session_t; struct coap_context_t; typedef struct coap_context_t coap_context_t; +struct coap_pdu_t; +typedef struct coap_pdu_t coap_pdu_t; + typedef uint16_t coap_socket_flags_t; typedef struct coap_socket_t { @@ -61,132 +64,36 @@ typedef struct coap_socket_t { #define COAP_SOCKET_HAS_DATA 0x0100 /**< non blocking socket can now read without blocking */ #define COAP_SOCKET_CAN_WRITE 0x0200 /**< non blocking socket can now write without blocking */ -typedef uint8_t coap_proto_t; - /** - * coap_proto_t values - */ -#define COAP_PROTO_NONE 0 -#define COAP_PROTO_UDP 1 -#define COAP_PROTO_DTLS 2 +struct coap_endpoint_t *coap_malloc_endpoint( void ); +void coap_mfree_endpoint( struct coap_endpoint_t *ep ); -typedef uint8_t coap_session_type_t; -/** -* coap_session_type_t values -*/ -#define COAP_SESSION_TYPE_CLIENT 1 -#define COAP_SESSION_TYPE_SERVER 2 +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 ); -typedef uint8_t coap_session_state_t; -/** -* coap_session_state_t values -*/ -#define COAP_SESSION_STATE_NONE 0 -#define COAP_SESSION_STATE_CONNECTING 1 -#define COAP_SESSION_STATE_HANDSHAKE 2 -#define COAP_SESSION_STATE_ESTABLISHED 3 +int +coap_socket_bind_udp( coap_socket_t *sock, + const coap_address_t *listen_addr, + coap_address_t *bound_addr ); -/** - * Abstraction of virtual endpoint that can be attached to coap_context_t. The - * tuple (handle, addr) must uniquely identify this endpoint. - */ -typedef struct coap_endpoint_t { - struct coap_endpoint_t *next; - coap_context_t *context; /**< endpoint's context */ - coap_proto_t proto; /**< protocol used on this interface */ - coap_socket_t sock; /**< socket object for the interface, if any */ - coap_address_t bind_addr; /**< local interface address */ - coap_session_t *sessions; /**< list of active sessions */ -} coap_endpoint_t; +void coap_socket_close( coap_socket_t *sock ); -/** - * Create a new endpoint for communicating with peers. - * - * @param context The coap context that will own the new endpoint - * @param listen_addr Address the endpoint will listen for incoming requests on or originate outgoing requests from. Use NULL to specify that no incoming request will be accepted and use a random endpoint. - * @param proto Protocol used on this endpoint -*/ +ssize_t +coap_socket_send( coap_socket_t *sock, coap_session_t *session, + const uint8_t *data, size_t data_len ); -coap_endpoint_t *coap_new_endpoint( coap_context_t *context, const coap_address_t *listen_addr, coap_proto_t proto ); -typedef struct coap_session_t { - struct coap_session_t *next; - coap_proto_t proto; /**< protocol used */ - coap_session_type_t type; /**< client or server side socket */ - coap_session_state_t state; /**< current state of relationaship with peer */ - int ref; /**< reference count from queues */ - coap_address_t local_addr; /**< local address and port */ - coap_address_t remote_addr; /**< remote address and port */ - int ifindex; /**< interface index */ - coap_socket_t sock; /**< socket object for the session, if any */ - coap_endpoint_t *endpoint; /**< session's endpoint */ - coap_context_t *context; /**< session's context */ - void *tls; /**< security parameters */ -} coap_session_t; +#ifdef WITH_LWIP +ssize_t +coap_socket_send_pdu( coap_socket_t *sock, coap_session_t *session, + coap_pdu_t *pdu ); +#endif -/** - * Increment reference counter on a session. - * - * @param session The CoAP session. - * @return same as session -*/ -coap_session_t *coap_session_reference( coap_session_t *session ); - -/** -* Decrement reference counter on a session. -* -* @param session The CoAP session. -*/ -void coap_session_release( coap_session_t *session ); - -/** - * Lookup the server session for the packet received on an endpoint, or create - * a new one. - * - * @param endpoint Active endpoint the packet was received on. - * @param packet Received packet. - * @return The CoAP session. -*/ -coap_session_t *coap_endpoint_get_session( coap_endpoint_t *endpoint, const coap_packet_t *packet ); - -/** - * Creates a new client session to the designated server. - * @param ctx The CoAP context. - * @param local_if Address of local interface. It is recommended to use NULL to let the operating system choose a suitable local interface. If an address is specified, the port number should be zero, which means that a free port is automatically selected. - * @param server The server's address. If the port number is zero, the default port for the protocol will be used. - * @param proto Protocol. - * - * @return A new CoAP session or NULL if failed. Call coap_session_release to free. - */ -coap_session_t *coap_new_client_session( - coap_context_t *ctx, - coap_address_t *local_if, - coap_address_t *server, - coap_proto_t proto -); - -/** -* Creates a new client session to the designated server with PSK credentials -* @param ctx The CoAP context. -* @param local_if Address of local interface. It is recommended to use NULL to let the operating system choose a suitable local interface. If an address is specified, the port number should be zero, which means that a free port is automatically selected. -* @param server The server's address. If the port number is zero, the default port for the protocol will be used. -* @param identity PSK client identity -* @param identity_len Length PSK client identity -* @param key PSK shared key -* @param key_len PSK shared key length -* @param proto Protocol. -* -* @return A new CoAP session or NULL if failed. Call coap_session_release to free. -*/ -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 -); +const char *coap_socket_strerror(); /** * Function interface for data transmission. This function returns the number of @@ -200,7 +107,7 @@ coap_session_t *coap_new_client_session_psk( * @return The number of bytes written on success, or a value * less than zero on error. */ -ssize_t coap_network_send( coap_socket_t *sock, const coap_session_t *session, uint8_t *data, size_t datalen ); +ssize_t coap_network_send( coap_socket_t *sock, const coap_session_t *session, const uint8_t *data, size_t datalen ); /** * Function interface for reading data. This function returns the number of @@ -245,21 +152,7 @@ void coap_packet_set_addr( coap_packet_t *packet, const coap_address_t *src, struct pbuf *coap_packet_extract_pbuf(coap_packet_t *packet); #endif -#ifdef WITH_CONTIKI -/* - * This is only included in coap_io.h instead of .c in order to be available for - * sizeof in mem.c. - */ -struct coap_packet_t { - coap_address_t src; /**< the packet's source address */ - coap_address_t dst; /**< the packet's destination address */ - int ifindex; - size_t length; /**< length of payload */ - unsigned char payload[]; /**< payload */ -}; -#endif - -#ifdef WITH_LWIP +#if defined(WITH_LWIP) /* * This is only included in coap_io.h instead of .c in order to be available for * sizeof in lwippools.h. @@ -273,6 +166,14 @@ struct coap_packet_t { const coap_endpoint_t *local_interface; uint16_t srcport; }; +#else +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 #endif /* _COAP_IO_H_ */ diff --git a/include/coap/net.h b/include/coap/net.h index 7ccf5b76..0faadf62 100644 --- a/include/coap/net.h +++ b/include/coap/net.h @@ -29,6 +29,7 @@ #include "option.h" #include "pdu.h" #include "prng.h" +#include "session.h" struct coap_queue_t; @@ -126,11 +127,18 @@ typedef struct coap_context_t { */ coap_event_handler_t handle_event; - ssize_t (*network_send)(coap_socket_t *sock, const coap_session_t *session, uint8_t *data, size_t datalen); + ssize_t (*network_send)(coap_socket_t *sock, const coap_session_t *session, const uint8_t *data, size_t datalen); ssize_t (*network_read)(coap_socket_t *sock, coap_packet_t **packet); + unsigned (*get_client_psk)( const coap_session_t *session, const char *hint, char *identity, unsigned max_identity_len, uint8_t *psk, unsigned max_psk_len ); + unsigned (*get_server_psk)( const coap_session_t *session, const char *identity, uint8_t *psk, unsigned max_psk_len ); + int (*get_server_hint)( const coap_session_t *session, char *hint, unsigned max_hint_len ); + struct coap_dtls_context_t *dtls_context; + char *psk_hint; + uint8_t *psk_key; + unsigned psk_key_len; void *app; /**< application-specific data */ } coap_context_t; @@ -180,6 +188,18 @@ coap_queue_t *coap_pop_next( coap_context_t *context ); */ coap_context_t *coap_new_context(const coap_address_t *listen_addr); +/** + * Set the context's default server PSK hint and/or key. + * These global defaults are used only no PSK callback is specified. + * + * @param hint The default PSK server hint sent to a client. If NULL, PSK authentication is disabled. Empty string is a valid hint. + * @param key The default PSK key. If NULL, PSK authentication will fail. + * @param key_len The default PSK key's lenght. If 0, PSK authentication will fail. + */ + +void coap_context_set_psk( coap_context_t *ctx, const char *hint, + const uint8_t *key, unsigned key_len ); + /** * Returns a new message id and updates @p context->message_id accordingly. The * message id is returned in network byte order to make it easier to read in @@ -221,22 +241,6 @@ void coap_set_app_data(coap_context_t *context, void *data); */ void *coap_get_app_data(coap_context_t *context); -/** - * Sends a confirmed CoAP message to given destination. The memory that is - * allocated by pdu will not be released by coap_send_confirmed(). The caller - * must release the memory. - * - * @param context The CoAP context to use. - * @param local_interface The local network interface where the outbound - * packet is sent. - * @param dst The address to send to. - * @param pdu The CoAP PDU to send. - * - * @return The message id of the sent message or @c - * COAP_INVALID_TID on error. - */ -coap_tid_t coap_send_confirmed(coap_session_t *session, coap_pdu_t *pdu); - /** * Creates a new ACK PDU with specified error @p code. The options specified by * the filter expression @p opts will be copied from the original request @@ -258,19 +262,6 @@ coap_pdu_t *coap_new_error_response(coap_pdu_t *request, unsigned char code, coap_opt_filter_t opts); -/** - * Sends a non-confirmed CoAP message to given destination. The memory that is - * allocated by pdu will not be released by coap_send(). - * The caller must release the memory. - * - * @param session The CoAP session. - * @param pdu The CoAP PDU to send. - * - * @return The message id of the sent message or @c - * COAP_INVALID_TID on error. - */ -coap_tid_t coap_send(coap_session_t *session, coap_pdu_t *pdu); - /** * Sends an error response with code @p code for request @p request to @p dst. * @p opts will be passed to coap_new_error_response() to copy marked options @@ -334,6 +325,19 @@ coap_send_rst(coap_session_t *session, coap_pdu_t *request) { return coap_send_message_type(session, request, COAP_MESSAGE_RST); } +/** +* Sends a CoAP message to given peer. The memory that is +* allocated by pdu will be released by coap_send(). +* The caller must not use the pdu after calling coap_send(). +* +* @param session The CoAP session. +* @param pdu The CoAP PDU to send. +* +* @return The message id of the sent message or @c +* COAP_INVALID_TID on error. +*/ +coap_tid_t coap_send( coap_session_t *session, coap_pdu_t *pdu ); + /** * Handles retransmissions of confirmable messages */ @@ -421,6 +425,10 @@ coap_remove_transaction(coap_queue_t **queue, coap_session_t *session, coap_tid_ return 1; } +coap_tid_t +coap_wait_ack( coap_context_t *context, coap_session_t *session, + coap_pdu_t *pdu, int retransmit_cnt ); + /** * Retrieves transaction from the queue. * @@ -500,7 +508,7 @@ int coap_option_check_critical(coap_context_t *ctx, /** * Creates a new response for given @p request with the contents of @c * .well-known/core. The result is NULL on error or a newly allocated PDU that - * must be released by coap_delete_pdu(). + * must be either sent with coap_sent() or released by coap_delete_pdu(). * * @param context The current coap context to use. * @param request The request for @c .well-known/core . diff --git a/include/coap/pdu.h b/include/coap/pdu.h index 72368955..697e6e65 100644 --- a/include/coap/pdu.h +++ b/include/coap/pdu.h @@ -175,6 +175,8 @@ typedef int coap_tid_t; */ #define COAP_DROPPED_RESPONSE -2 +#define COAP_PDU_DELAYED -3 + #if defined(_MSC_VER) #include #pragma pack( push, 1 ) @@ -241,7 +243,7 @@ typedef struct { * Header structure for CoAP PDUs */ -typedef struct { +typedef struct coap_pdu_t { size_t max_size; /**< allocated storage for options and data */ coap_hdr_t *hdr; /**< Address of the first byte of the CoAP message. * This may or may not equal (coap_hdr_t*)(pdu+1) @@ -291,7 +293,8 @@ coap_pdu_t * coap_pdu_from_pbuf(struct pbuf *pbuf); * Creates a new CoAP PDU of given @p size (must be large enough to hold the * basic CoAP message header (coap_hdr_t). The function returns a pointer to the * node coap_pdu_t object on success, or @c NULL on error. The storage allocated - * for the result must be released with coap_delete_pdu(). + * for the result must be released with coap_delete_pdu() if coap_send() is not + * called. * * @param type The type of the PDU (one of COAP_MESSAGE_CON, COAP_MESSAGE_NON, * COAP_MESSAGE_ACK, COAP_MESSAGE_RST). @@ -318,13 +321,21 @@ void coap_pdu_clear(coap_pdu_t *pdu, size_t size); /** * Creates a new CoAP PDU. * The object is created on the heap and must be released using - * coap_delete_pdu(); + * coap_delete_pdu() unless coap_send() is called in which case + * coap_send() will take care of calling coap_delete_pdu(). * * @deprecated This function allocates the maximum storage for each * PDU. Use coap_pdu_init() instead. */ coap_pdu_t *coap_new_pdu(void); +/** + * Dispose of an CoAP PDU and frees associated storage. + * Not that in general you should not call this function directly. + * When a PDU is sent with coap_send(), coap_delete_pdu() will be + * called automatically for you. + */ + void coap_delete_pdu(coap_pdu_t *); /** diff --git a/include/coap/session.h b/include/coap/session.h new file mode 100644 index 00000000..002fc405 --- /dev/null +++ b/include/coap/session.h @@ -0,0 +1,210 @@ +/* session.h -- Session management for libcoap +* +* Copyright (C) 2017 Jean-Claue Michelou +* +* This file is part of the CoAP library libcoap. Please see +* README for terms of use. +*/ + +#ifndef _SESSION_H_ +#define _SESSION_H_ + + +#include "coap_io.h" +#include "pdu.h" + +struct coap_endpoint_t; +typedef struct coap_endpoint_t coap_endpoint_t; + +typedef uint8_t coap_proto_t; +/** +* coap_proto_t values +*/ +#define COAP_PROTO_NONE 0 +#define COAP_PROTO_UDP 1 +#define COAP_PROTO_DTLS 2 + +typedef uint8_t coap_session_type_t; +/** + * coap_session_type_t values + */ +#define COAP_SESSION_TYPE_CLIENT 1 /**< client-side */ +#define COAP_SESSION_TYPE_SERVER 2 /**< server-side */ +#define COAP_SESSION_TYPE_HELLO 3 /**< server-side ephemeral session for responding to a client hello */ + +typedef uint8_t coap_session_state_t; +/** + * coap_session_state_t values + */ +#define COAP_SESSION_STATE_NONE 0 +#define COAP_SESSION_STATE_CONNECTING 1 +#define COAP_SESSION_STATE_HANDSHAKE 2 +#define COAP_SESSION_STATE_ESTABLISHED 3 + +typedef struct coap_pdu_queue_t { + struct coap_pdu_queue_t *next; + coap_pdu_t *pdu; + int retransmit_cnt; +} coap_pdu_queue_t; + +typedef struct coap_session_t { + struct coap_session_t *next; + coap_proto_t proto; /**< protocol used */ + coap_session_type_t type; /**< client or server side socket */ + coap_session_state_t state; /**< current state of relationaship with peer */ + int ref; /**< reference count from queues */ + coap_address_t local_addr; /**< local address and port */ + coap_address_t remote_addr; /**< remote address and port */ + int ifindex; /**< interface index */ + coap_socket_t sock; /**< socket object for the session, if any */ + coap_endpoint_t *endpoint; /**< session's endpoint */ + coap_context_t *context; /**< session's context */ + void *tls; /**< security parameters */ + coap_pdu_queue_t *sendqueue; /**< list of messages waiting to be sent */ + char *psk_identity; + uint8_t *psk_key; + unsigned psk_key_len; +} coap_session_t; + +/** +* Increment reference counter on a session. +* +* @param session The CoAP session. +* @return same as session +*/ +coap_session_t *coap_session_reference( coap_session_t *session ); + +/** +* Decrement reference counter on a session. +* Note that the session may be deleted as a result and should not be used +* after this call. +* +* @param session The CoAP session. +*/ +void coap_session_release( coap_session_t *session ); + +/** +* Notify session that it has failed connecting or has been disconnected. +* +* @param session The CoAP session. +*/ +void coap_session_disconnected( coap_session_t *session ); + +/** +* Notify session that it has just connected or reconnected. +* +* @param session The CoAP session. +*/ +void coap_session_connected( coap_session_t *session ); + +/** +* Creates a new client session to the designated server. +* @param ctx The CoAP context. +* @param local_if Address of local interface. It is recommended to use NULL to let the operating system choose a suitable local interface. If an address is specified, the port number should be zero, which means that a free port is automatically selected. +* @param server The server's address. If the port number is zero, the default port for the protocol will be used. +* @param proto Protocol. +* +* @return A new CoAP session or NULL if failed. Call coap_session_release to free. +*/ +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 +); + +/** +* Creates a new client session to the designated server with PSK credentials +* @param ctx The CoAP context. +* @param local_if Address of local interface. It is recommended to use NULL to let the operating system choose a suitable local interface. If an address is specified, the port number should be zero, which means that a free port is automatically selected. +* @param server The server's address. If the port number is zero, the default port for the protocol will be used. +* @param identity PSK client identity +* @param identity_len Length PSK client identity +* @param key PSK shared key +* @param key_len PSK shared key length +* @param proto Protocol. +* +* @return A new CoAP session or NULL if failed. Call coap_session_release to free. +*/ +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, + unsigned key_len +); + +/** +* Function interface for data transmission. This function returns the number of +* bytes that have been transmitted, or a value less than zero on error. +* +* @param session Session to send data on. +* @param data The data to send. +* @param datalen The actual length of @p data. +* +* @return The number of bytes written on success, or a value +* less than zero on error. +*/ +ssize_t coap_session_send( coap_session_t *session, + const uint8_t *data, size_t datalen ); + +/** + * Get session description. + * + * @param session The CoAP session. + * @return description string + */ +const char *coap_session_str( const coap_session_t *session ); + +ssize_t +coap_session_delay_pdu( coap_session_t *session, coap_pdu_t *pdu, int retransmit_cnt ); + +/** +* Abstraction of virtual endpoint that can be attached to coap_context_t. The +* tuple (handle, addr) must uniquely identify this endpoint. +*/ +typedef struct coap_endpoint_t { + struct coap_endpoint_t *next; + coap_context_t *context; /**< endpoint's context */ + coap_proto_t proto; /**< protocol used on this interface */ + coap_socket_t sock; /**< socket object for the interface, if any */ + coap_address_t bind_addr; /**< local interface address */ + coap_session_t *sessions; /**< list of active sessions */ + coap_session_t hello; /**< special session of DTLS hello messages */ +} coap_endpoint_t; + +/** +* Create a new endpoint for communicating with peers. +* +* @param context The coap context that will own the new endpoint +* @param listen_addr Address the endpoint will listen for incoming requests on or originate outgoing requests from. Use NULL to specify that no incoming request will be accepted and use a random endpoint. +* @param proto Protocol used on this endpoint +*/ + +coap_endpoint_t *coap_new_endpoint( coap_context_t *context, const coap_address_t *listen_addr, coap_proto_t proto ); + +void coap_free_endpoint( coap_endpoint_t *ep ); + +/** +* Get endpoint description. +* +* @param session The CoAP endpoint. +* @return description string +*/ +const char *coap_endpoint_str( const coap_endpoint_t *endpoint ); + +/** +* Lookup the server session for the packet received on an endpoint, or create +* a new one. +* +* @param endpoint Active endpoint the packet was received on. +* @param packet Received packet. +* @return The CoAP session. +*/ +coap_session_t *coap_endpoint_get_session( coap_endpoint_t *endpoint, const coap_packet_t *packet ); + +coap_session_t *coap_endpoint_new_dtls_session( coap_endpoint_t *endpoint, const coap_packet_t *packet ); + +#endif /* _SESSION_H */ diff --git a/libcoap-1.map b/libcoap-1.map index 76f6ca64..4a54a537 100644 --- a/libcoap-1.map +++ b/libcoap-1.map @@ -18,6 +18,7 @@ global: coap_clear_event_handler; coap_clock_init; coap_clone_uri; + coap_context_set_psk; coap_decode_var_bytes; coap_delete_all; coap_delete_all_resources; @@ -28,15 +29,8 @@ global: coap_delete_resource; coap_delete_string; coap_dispatch; - coap_dtls_free_context; - coap_dtls_free_session; coap_dtls_get_log_level; - coap_dtls_get_session; - coap_dtls_handle_message; coap_dtls_is_supported; - coap_dtls_new_context; - coap_dtls_new_session; - coap_dtls_send; coap_dtls_set_log_level; coap_encode_var_bytes; coap_find_async; @@ -111,12 +105,12 @@ global: coap_run_once; coap_send; coap_send_ack; - coap_send_confirmed; coap_send_error; coap_send_message_type; coap_session_release; coap_set_event_handler; coap_set_log_level; + coap_socket_strerror; coap_show_pdu; coap_split_path; coap_split_query; diff --git a/libcoap-1.sym b/libcoap-1.sym index 8e24c05c..57b5ae02 100644 --- a/libcoap-1.sym +++ b/libcoap-1.sym @@ -16,6 +16,7 @@ coap_cleanup coap_clear_event_handler coap_clock_init coap_clone_uri +coap_context_set_psk coap_decode_var_bytes coap_delete_all coap_delete_all_resources @@ -26,15 +27,8 @@ coap_delete_pdu coap_delete_resource coap_delete_string coap_dispatch -coap_dtls_free_context -coap_dtls_free_session coap_dtls_get_log_level -coap_dtls_get_session -coap_dtls_handle_message coap_dtls_is_supported -coap_dtls_new_context -coap_dtls_new_session -coap_dtls_send coap_dtls_set_log_level coap_encode_var_bytes coap_find_async @@ -109,13 +103,13 @@ coap_retransmit coap_run_once coap_send coap_send_ack -coap_send_confirmed coap_send_error coap_send_message_type coap_session_release coap_set_event_handler coap_set_log_level coap_show_pdu +coap_socket_strerror coap_split_path coap_split_query coap_split_uri diff --git a/src/coap_io.c b/src/coap_io.c index 2e8e0071..2c9d25d6 100644 --- a/src/coap_io.c +++ b/src/coap_io.c @@ -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 */ diff --git a/src/coap_notls.c b/src/coap_notls.c new file mode 100644 index 00000000..a9f0633f --- /dev/null +++ b/src/coap_notls.c @@ -0,0 +1,85 @@ +/* +* coap_notls.c -- Stub Datagram Transport Layer Support for libcoap +* +* Copyright (C) 2016 Olaf Bergmann +* +* 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 */ diff --git a/src/coap_openssl.c b/src/coap_openssl.c new file mode 100644 index 00000000..739ac6cf --- /dev/null +++ b/src/coap_openssl.c @@ -0,0 +1,572 @@ +/* +* coap_tinydtls.c -- Datagram Transport Layer Support for libcoap with openssl +* +* Copyright (C) 2017 Jean-Claude Michelou +* +* 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 +#include +#include +#include + +/* 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 */ diff --git a/src/coap_dtls.c b/src/coap_tinydtls.c similarity index 89% rename from src/coap_dtls.c rename to src/coap_tinydtls.c index 94448227..ad83215d 100644 --- a/src/coap_dtls.c +++ b/src/coap_tinydtls.c @@ -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 * @@ -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 #include @@ -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 diff --git a/src/net.c b/src/net.c index a4477a11..97cfd450 100644 --- a/src/net.c +++ b/src/net.c @@ -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; } diff --git a/src/resource.c b/src/resource.c index e8dbf85f..cc327adb 100644 --- a/src/resource.c +++ b/src/resource.c @@ -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"); diff --git a/src/session.c b/src/session.c new file mode 100644 index 00000000..85b32751 --- /dev/null +++ b/src/session.c @@ -0,0 +1,453 @@ +/* session.c -- Session management for libcoap +* +* Copyright (C) 2017 Jean-Claue Michelou +* +* 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 + +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_ */ diff --git a/win32/libcoap.vcxproj b/win32/libcoap.vcxproj index 1ba05501..7d908fd4 100644 --- a/win32/libcoap.vcxproj +++ b/win32/libcoap.vcxproj @@ -38,10 +38,12 @@ - + + + @@ -50,6 +52,7 @@ + @@ -75,6 +78,7 @@ + @@ -337,6 +341,7 @@ copy /Y ..\include\coap\coap.h.windows ..\include\coap\coap.h Windows true $(IntDir)$(TargetName).def + kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;libcryptod.lib;libssld.lib;%(AdditionalDependencies) copy /Y ..\coap_config.h.windows ..\coap_config.h @@ -463,6 +468,7 @@ copy /Y ..\include\coap\coap.h.windows ..\include\coap\coap.h true true $(IntDir)$(TargetName).def + kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;libcrypto.lib;libssl.lib;%(AdditionalDependencies) copy /Y ..\coap_config.h.windows ..\coap_config.h diff --git a/win32/libcoap.vcxproj.filters b/win32/libcoap.vcxproj.filters index 85b276c0..651071d5 100644 --- a/win32/libcoap.vcxproj.filters +++ b/win32/libcoap.vcxproj.filters @@ -63,10 +63,19 @@ Source Files - + Source Files - + + Source Files + + + Source Files + + + Source Files + + Source Files @@ -146,6 +155,9 @@ Header Files + + Header Files +