From 1a349d5cb47a9747d31cd3c581ca40705a0f86f1 Mon Sep 17 00:00:00 2001 From: Jon Shallow Date: Mon, 27 Apr 2020 09:54:46 +0100 Subject: [PATCH] coap_cache: Add in Cache Key and Cache Entry support This updates the initial work done for adding in cache support include/coap2/coap_cache.h: (new) include/coap2/coap_cache_internal.h: (new) src/coap_cache.c: (new) New files to support cache support. CMakeLists.txt: Makefile.amMakefile.am: Makefile.libcoap: configure.ac: examples/lwip/Makefile: include/coap2/coap.h.in: include/coap2/coap.h.windows: win32/libcoap.vcxproj: win32/libcoap.vcxproj.filters: Add in the new files. examples/client.c: Fix valgrind reported memory leak. examples/coap-server.c: Add in new example_data resource that uses the new caching logic. Update hnd_put() to use the new cache logic for BLOCK1 PUTs. include/coap2/coap_forward_decls.h: include/coap2/coap_internal.h: include/coap2/coap_session.h: include/coap2/net.h: Add in new cache support. libcoap-2.map: libcoap-2.sym: Include the new functions. man/Makefile.am: man/coap.txt.in: man/coap_cache.txt.in: (new) Update documentation. src/coap_io.c: Idle timeout cache entries. src/coap_session.c: Delete cache entry when session is deleted. src/net.c: Delete cache entries when context is freed off. src/coap_gnutls.c: src/coap_mbedtls.c: src/coap_notls.c: src/coap_openssl.c: src/coap_tinydtls.c: Add in SHA256 digest support. --- CMakeLists.txt | 10 + Makefile.am | 2 +- Makefile.libcoap | 2 +- configure.ac | 1 + examples/client.c | 1 + examples/coap-server.c | 353 ++++++++++++++++++++++--- examples/lwip/Makefile | 2 +- include/coap2/coap.h.windows | 1 + include/coap2/coap_cache.h | 185 ++++++++++--- include/coap2/coap_cache_internal.h | 108 ++++++++ include/coap2/coap_forward_decls.h | 11 +- include/coap2/coap_internal.h | 3 +- include/coap2/coap_session.h | 103 +++++++- include/coap2/mem.h | 4 +- include/coap2/net.h | 4 +- libcoap-2.map | 10 + libcoap-2.sym | 10 + man/Makefile.am | 3 + man/coap.txt.in | 11 +- man/coap_cache.txt.in | 385 ++++++++++++++++++++++++++++ man/coap_string.txt.in | 18 +- src/coap_cache.c | 274 +++++++++++++++----- src/coap_gnutls.c | 34 +++ src/coap_io.c | 1 + src/coap_mbedtls.c | 36 +++ src/coap_notls.c | 45 ++++ src/coap_openssl.c | 31 +++ src/coap_session.c | 7 + src/coap_tinydtls.c | 34 +++ src/net.c | 8 +- win32/libcoap.vcxproj | 3 + win32/libcoap.vcxproj.filters | 9 + 32 files changed, 1526 insertions(+), 183 deletions(-) create mode 100644 include/coap2/coap_cache_internal.h create mode 100644 man/coap_cache.txt.in diff --git a/CMakeLists.txt b/CMakeLists.txt index 08e35d2b..efb5d776 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -389,8 +389,17 @@ configure_file(${CMAKE_CURRENT_LIST_DIR}/include/coap2/coap_config.h.in target_sources( ${COAP_LIBRARY_NAME} PRIVATE ${CMAKE_CURRENT_LIST_DIR}/src/address.c + ${CMAKE_CURRENT_LIST_DIR}/src/net.c + ${CMAKE_CURRENT_LIST_DIR}/src/coap_debug.c + ${CMAKE_CURRENT_LIST_DIR}/src/encode.c + ${CMAKE_CURRENT_LIST_DIR}/src/uri.c + ${CMAKE_CURRENT_LIST_DIR}/src/subscribe.c + ${CMAKE_CURRENT_LIST_DIR}/src/resource.c + ${CMAKE_CURRENT_LIST_DIR}/src/str.c + ${CMAKE_CURRENT_LIST_DIR}/src/option.c ${CMAKE_CURRENT_LIST_DIR}/src/async.c ${CMAKE_CURRENT_LIST_DIR}/src/block.c + ${CMAKE_CURRENT_LIST_DIR}/src/coap_cache.c ${CMAKE_CURRENT_LIST_DIR}/src/coap_debug.c ${CMAKE_CURRENT_LIST_DIR}/src/coap_event.c ${CMAKE_CURRENT_LIST_DIR}/src/coap_hashkey.c @@ -419,6 +428,7 @@ target_sources( ${CMAKE_CURRENT_LIST_DIR}/include/coap2/async.h ${CMAKE_CURRENT_LIST_DIR}/include/coap2/bits.h ${CMAKE_CURRENT_LIST_DIR}/include/coap2/block.h + ${CMAKE_CURRENT_LIST_DIR}/include/coap2/coap_cache.h ${CMAKE_CURRENT_LIST_DIR}/include/coap2/coap_debug.h ${CMAKE_CURRENT_LIST_DIR}/include/coap2/coap_dtls.h ${CMAKE_CURRENT_LIST_DIR}/include/coap2/coap_event.h diff --git a/Makefile.am b/Makefile.am index ed239967..51ebde83 100644 --- a/Makefile.am +++ b/Makefile.am @@ -24,6 +24,7 @@ EXTRA_DIST = \ examples/getopt.c \ include/coap$(LIBCOAP_API_VERSION)/coap_internal.h \ include/coap$(LIBCOAP_API_VERSION)/coap_riot.h \ + include/coap$(LIBCOAP_API_VERSION)/coap_cache_internal.h \ include/coap$(LIBCOAP_API_VERSION)/coap_session_internal.h \ include/coap$(LIBCOAP_API_VERSION)/coap_subscribe_internal.h \ include/coap$(LIBCOAP_API_VERSION)/coap_tcp_internal.h \ @@ -91,7 +92,6 @@ libcoap_@LIBCOAP_NAME_SUFFIX@_la_SOURCES = \ src/coap_tinydtls.c \ src/encode.c \ src/mem.c \ - src/murmur3.c \ src/net.c \ src/option.c \ src/pdu.c \ diff --git a/Makefile.libcoap b/Makefile.libcoap index 1035c64b..9275f794 100644 --- a/Makefile.libcoap +++ b/Makefile.libcoap @@ -1,4 +1,4 @@ -libcoap_src = pdu.c net.c coap_debug.c encode.c uri.c subscribe.c resource.c str.c option.c async.c block.c mem.c coap_io.c coap_session.c coap_notls.c coap_hashkey.c address.c coap_tcp.c +libcoap_src = pdu.c net.c coap_cache.c coap_debug.c encode.c uri.c subscribe.c resource.c str.c option.c async.c block.c mem.c coap_io.c coap_session.c coap_notls.c coap_hashkey.c address.c coap_tcp.c libcoap_dir := $(filter %libcoap,$(APPDS)) vpath %c $(libcoap_dir)/src diff --git a/configure.ac b/configure.ac index d56de5d5..4cf5d63e 100644 --- a/configure.ac +++ b/configure.ac @@ -788,6 +788,7 @@ examples/Makefile include/coap2/coap.h man/coap.txt man/coap_attribute.txt +man/coap_cache.txt man/coap_context.txt man/coap_encryption.txt man/coap_handler.txt diff --git a/examples/client.c b/examples/client.c index b90df987..dd10b0d4 100644 --- a/examples/client.c +++ b/examples/client.c @@ -1858,6 +1858,7 @@ main(int argc, char **argv) { if (valid_ihs.count) free(valid_ihs.ih_list); coap_delete_optlist(optlist); + if (payload.s) coap_free(payload.s); coap_session_release( session ); coap_free_context( ctx ); coap_cleanup(); diff --git a/examples/coap-server.c b/examples/coap-server.c index 1c9d114d..cfc77fc6 100644 --- a/examples/coap-server.c +++ b/examples/coap-server.c @@ -66,6 +66,9 @@ static time_t my_clock_base = 0; struct coap_resource_t *time_resource = NULL; +static coap_binary_t *example_data_ptr = NULL; +static int example_data_media_type = COAP_MEDIATYPE_TEXT_PLAIN; + static int resource_flags = COAP_RESOURCE_FLAGS_NOTIFY_CON; /* @@ -377,9 +380,200 @@ check_async(coap_context_t *ctx, } #endif /* WITHOUT_ASYNC */ +/* + * Large Data GET handler + */ + +static void +hnd_get_example_data(coap_context_t *ctx UNUSED_PARAM, + coap_resource_t *resource, + coap_session_t *session, + coap_pdu_t *request, + coap_binary_t *token, + coap_string_t *query UNUSED_PARAM, + coap_pdu_t *response +) { + if (!example_data_ptr) { + /* Initialise for the first time */ + int i; + example_data_ptr = coap_new_binary(1500); + if (example_data_ptr) { + example_data_ptr->length = 1500; + for (i = 0; i < 1500; i++) { + if ((i % 10) == 0) { + example_data_ptr->s[i] = 'a' + (i/10) % 26; + } + else { + example_data_ptr->s[i] = '0' + i%10; + } + } + } + } + coap_add_data_blocked_response(resource, session, request, response, token, + example_data_media_type, -1, + example_data_ptr ? example_data_ptr->length : 0, + example_data_ptr ? example_data_ptr->s : NULL); +} + +static void +cache_free_app_data(void *data) { + coap_binary_t *bdata = (coap_binary_t*)data; + coap_delete_binary(bdata); +} + +/* + * Large Data PUT handler + */ + +static void +hnd_put_example_data(coap_context_t *ctx UNUSED_PARAM, + coap_resource_t *resource, + coap_session_t *session, + coap_pdu_t *request, + coap_binary_t *token UNUSED_PARAM, + coap_string_t *query UNUSED_PARAM, + coap_pdu_t *response +) { + size_t size; + uint8_t *data; + coap_block_t block1; + unsigned char buf[6]; /* space to hold encoded/decoded uints */ + coap_opt_iterator_t opt_iter; + coap_opt_t *option; + + if (coap_get_block(request, COAP_OPTION_BLOCK1, &block1)) { + /* handle BLOCK1 */ + coap_cache_entry_t *cache_entry = coap_cache_get_by_pdu(session, + request, + COAP_CACHE_IS_SESSION_BASED); + size_t offset = block1.num << (block1.szx + 4); + coap_binary_t *data_so_far; + + if (!cache_entry && block1.num == 0) { + cache_entry = coap_new_cache_entry(session, request, + COAP_CACHE_NOT_RECORD_PDU, + COAP_CACHE_IS_SESSION_BASED, 0); + } + if (!cache_entry) { + if (block1.num == 0) { + coap_log(LOG_WARNING, "Unable to create a new cache entry\n"); + } + else { + coap_log(LOG_WARNING, + "No cache entry available for the non-first BLOCK1\n"); + } + response->code = COAP_RESPONSE_CODE(500); + return; + } + + data_so_far = coap_cache_get_app_data(cache_entry); + if (offset == 0) { + if (data_so_far) { + coap_delete_binary(data_so_far); + data_so_far = NULL; + } + } + else if (offset > + (data_so_far ? data_so_far->length : 0)) { + /* Upload is not sequential - block missing */ + response->code = COAP_RESPONSE_CODE(408); + return; + } + else if (offset < + (data_so_far ? data_so_far->length : 0)) { + /* Upload is not sequential - block duplicated */ + goto just_respond; + } + + if (coap_get_data(request, &size, &data) && (size > 0)) { + if (!data_so_far) { + data_so_far = coap_new_binary(size); + if (data_so_far) + memcpy(data_so_far->s, data, size); + } + else { + /* Add in new block to end of current data */ + data_so_far = coap_resize_binary(data_so_far, offset + size); + if (data_so_far) + memcpy(&data_so_far->s[offset], data, size); + } + } + else if (!block1.m && block1.num == 0) { + /* Empty first and only block */ + if (data_so_far) { + coap_delete_binary(example_data_ptr); + } + data_so_far = coap_new_binary(0); + } + + if (!block1.m) { + /* all the data in - now update the resource */ + coap_delete_binary(example_data_ptr); + example_data_ptr = data_so_far; + coap_cache_set_app_data(cache_entry, NULL, NULL); + if ((option = coap_check_option(request, COAP_OPTION_CONTENT_FORMAT, + &opt_iter)) != NULL) { + example_data_media_type = + coap_decode_var_bytes (coap_opt_value (option), + coap_opt_length (option)); + } + else { + example_data_media_type = COAP_MEDIATYPE_TEXT_PLAIN; + } + coap_resource_notify_observers(resource, NULL); + } + else { + /* save the updated data for the next block */ + coap_cache_set_app_data(cache_entry,data_so_far, cache_free_app_data); + } + +just_respond: + if (block1.m) { + response->code = COAP_RESPONSE_CODE(231); + } + else { + response->code = COAP_RESPONSE_CODE(204); + } + coap_add_option(response, + COAP_OPTION_BLOCK1, + coap_encode_var_safe(buf, sizeof(buf), + ((block1.num << 4) | + (block1.m << 3) | + block1.szx)), + buf); + } + else if (coap_get_data(request, &size, &data) && (size > 0)) { + /* Not a BLOCK1 with data */ + if (example_data_ptr) { + coap_delete_binary(example_data_ptr); + } + example_data_ptr = coap_new_binary(size); + if (example_data_ptr) + memcpy (example_data_ptr->s, data, size); + if ((option = coap_check_option(request, COAP_OPTION_CONTENT_FORMAT, + &opt_iter)) != NULL) { + example_data_media_type = coap_decode_var_bytes (coap_opt_value (option), + coap_opt_length (option)); + } + else { + example_data_media_type = COAP_MEDIATYPE_TEXT_PLAIN; + } + response->code = COAP_RESPONSE_CODE(204); + coap_resource_notify_observers(resource, NULL); + } + else { + /* Not a BLOCK1 and no data */ + if (example_data_ptr) { + coap_delete_binary(example_data_ptr); + } + example_data_ptr = coap_new_binary(0); + response->code = COAP_RESPONSE_CODE(204); + } +} + typedef struct dynamic_resource_t { coap_string_t *uri_path; - coap_string_t *value; + coap_binary_t *value; coap_resource_t *resource; int created; uint16_t media_type; @@ -397,10 +591,10 @@ static void hnd_delete(coap_context_t *ctx, coap_resource_t *resource, coap_session_t *session UNUSED_PARAM, - coap_pdu_t *request UNUSED_PARAM, + coap_pdu_t *request, coap_binary_t *token UNUSED_PARAM, coap_string_t *query UNUSED_PARAM, - coap_pdu_t *response UNUSED_PARAM + coap_pdu_t *response ) { int i; coap_string_t *uri_path; @@ -415,7 +609,7 @@ hnd_delete(coap_context_t *ctx, for (i = 0; i < dynamic_count; i++) { if (coap_string_equal(uri_path, dynamic_entry[i].uri_path)) { /* Dynamic entry no longer required - delete it */ - coap_delete_string(dynamic_entry[i].value); + coap_delete_binary(dynamic_entry[i].value); if (dynamic_count-i > 1) { memmove (&dynamic_entry[i], &dynamic_entry[i+1], @@ -449,7 +643,7 @@ hnd_get(coap_context_t *ctx UNUSED_PARAM, coap_str_const_t *uri_path; int i; dynamic_resource_t *resource_entry = NULL; - coap_str_const_t value = { 0, NULL }; + coap_bin_const_t value = { 0, NULL }; /* * request will be NULL if an Observe triggered request, so the uri_path, * if needed, must be abstracted from the resource. @@ -492,7 +686,7 @@ hnd_get(coap_context_t *ctx UNUSED_PARAM, static void hnd_put(coap_context_t *ctx UNUSED_PARAM, coap_resource_t *resource, - coap_session_t *session UNUSED_PARAM, + coap_session_t *session, coap_pdu_t *request, coap_binary_t *token UNUSED_PARAM, coap_string_t *query UNUSED_PARAM, @@ -531,16 +725,19 @@ hnd_put(coap_context_t *ctx UNUSED_PARAM, return; } dynamic_count++; - dynamic_entry = realloc (dynamic_entry, dynamic_count * sizeof(dynamic_entry[0])); + dynamic_entry = realloc (dynamic_entry, + dynamic_count * sizeof(dynamic_entry[0])); if (dynamic_entry) { dynamic_entry[i].uri_path = uri_path; dynamic_entry[i].value = NULL; dynamic_entry[i].resource = resource; dynamic_entry[i].created = 1; response->code = COAP_RESPONSE_CODE(201); - if ((option = coap_check_option(request, COAP_OPTION_CONTENT_TYPE, &opt_iter)) != NULL) { + if ((option = coap_check_option(request, COAP_OPTION_CONTENT_FORMAT, + &opt_iter)) != NULL) { dynamic_entry[i].media_type = - coap_decode_var_bytes (coap_opt_value (option), coap_opt_length (option)); + coap_decode_var_bytes (coap_opt_value (option), + coap_opt_length (option)); } else { dynamic_entry[i].media_type = COAP_MEDIATYPE_TEXT_PLAIN; @@ -566,49 +763,87 @@ hnd_put(coap_context_t *ctx UNUSED_PARAM, /* Need to do this as coap_get_uri_path() created it */ coap_delete_string(uri_path); response->code = COAP_RESPONSE_CODE(204); - dynamic_entry[i].created = 0; - coap_resource_notify_observers(dynamic_entry[i].resource, NULL); } resource_entry = &dynamic_entry[i]; if (coap_get_block(request, COAP_OPTION_BLOCK1, &block1)) { /* handle BLOCK1 */ - if (coap_get_data(request, &size, &data) && (size > 0)) { - size_t offset = block1.num << (block1.szx + 4); - coap_string_t *value = resource_entry->value; - if (offset == 0) { - if (value) { - coap_delete_string(value); - value = NULL; - } + coap_cache_entry_t *cache_entry = coap_cache_get_by_pdu(session, + request, + COAP_CACHE_IS_SESSION_BASED); + size_t offset = block1.num << (block1.szx + 4); + coap_binary_t *data_so_far; + + if (!cache_entry && block1.num == 0) { + cache_entry = coap_new_cache_entry(session, request, + COAP_CACHE_NOT_RECORD_PDU, + COAP_CACHE_IS_SESSION_BASED, 0); + } + if (!cache_entry) { + if ( block1.num == 0) { + coap_log(LOG_WARNING, "Unable to create a new cache entry\n"); } - else if (offset > - (resource_entry->value ? resource_entry->value->length : 0)) { - /* Upload is not sequential - block missing */ - response->code = COAP_RESPONSE_CODE(408); - return; + else { + coap_log(LOG_WARNING, + "No cache entry available for the non-first BLOCK1\n"); } - else if (offset < - (resource_entry->value ? resource_entry->value->length : 0)) { - /* Upload is not sequential - block duplicated */ - goto just_respond; - } - /* Add in new block to end of current data */ - resource_entry->value = coap_new_string(offset + size); - memcpy (&resource_entry->value->s[offset], data, size); - resource_entry->value->length = offset + size; - if (value) { - memcpy (resource_entry->value->s, value->s, value->length); - coap_delete_string(value); + response->code = COAP_RESPONSE_CODE(500); + return; + } + + data_so_far = coap_cache_get_app_data(cache_entry); + if (offset == 0) { + if (data_so_far) { + coap_delete_binary(data_so_far); + data_so_far = NULL; } } + else if (offset > + (data_so_far ? data_so_far->length : 0)) { + /* Upload is not sequential - block missing */ + response->code = COAP_RESPONSE_CODE(408); + return; + } + else if (offset < + (data_so_far ? data_so_far->length : 0)) { + /* Upload is not sequential - block duplicated */ + goto just_respond; + } + + if (coap_get_data(request, &size, &data) && (size > 0)) { + if (!data_so_far) { + data_so_far = coap_new_binary(size); + if (data_so_far) + memcpy(data_so_far->s, data, size); + } + else { + /* Add in new block to end of current data */ + data_so_far = coap_resize_binary(data_so_far, offset + size); + if (data_so_far) + memcpy(&data_so_far->s[offset], data, size); + } + } + + if (!block1.m) { + /* all the data in - now update the resource */ + coap_delete_binary(resource_entry->value); + resource_entry->value = data_so_far; + coap_cache_set_app_data(cache_entry, NULL, NULL); + coap_resource_notify_observers(resource_entry->resource, NULL); + } + else { + /* save the updated data for the next block */ + coap_cache_set_app_data(cache_entry, data_so_far, cache_free_app_data); + } + just_respond: if (block1.m) { response->code = COAP_RESPONSE_CODE(231); } else if (resource_entry->created) { response->code = COAP_RESPONSE_CODE(201); + resource_entry->created = 0; } else { response->code = COAP_RESPONSE_CODE(204); @@ -624,19 +859,29 @@ just_respond: else if (coap_get_data(request, &size, &data) && (size > 0)) { /* Not a BLOCK1 with data */ if (resource_entry->value) { - coap_delete_string(resource_entry->value); - resource_entry->value = NULL; + coap_delete_binary(resource_entry->value); } - resource_entry->value = coap_new_string(size); - memcpy (resource_entry->value->s, data, size); - resource_entry->value->length = size; + resource_entry->value = coap_new_binary(size); + if (resource_entry->value) + memcpy (resource_entry->value->s, data, size); + if ((option = coap_check_option(request, COAP_OPTION_CONTENT_FORMAT, + &opt_iter)) != NULL) { + resource_entry->media_type = coap_decode_var_bytes (coap_opt_value (option), + coap_opt_length (option)); + } + else { + resource_entry->media_type = COAP_MEDIATYPE_TEXT_PLAIN; + } + coap_resource_notify_observers(resource_entry->resource, NULL); + resource_entry->created = 0; } else { /* Not a BLOCK1 and no data */ if (resource_entry->value) { - coap_delete_string(resource_entry->value); + coap_delete_binary(resource_entry->value); resource_entry->value = NULL; } + resource_entry->created = 0; } } @@ -727,6 +972,14 @@ init_resources(coap_context_t *ctx) { coap_add_attr(r, coap_make_str_const("ct"), coap_make_str_const("0"), 0); coap_add_resource(ctx, r); #endif /* WITHOUT_ASYNC */ + r = coap_resource_init(coap_make_str_const("example_data"), 0); + coap_register_handler(r, COAP_REQUEST_GET, hnd_get_example_data); + coap_register_handler(r, COAP_REQUEST_PUT, hnd_put_example_data); + coap_resource_set_get_observable(r, 1); + + coap_add_attr(r, coap_make_str_const("ct"), coap_make_str_const("0"), 0); + coap_add_attr(r, coap_make_str_const("title"), coap_make_str_const("\"Example Data\""), 0); + coap_add_resource(ctx, r); } static int @@ -1371,6 +1624,12 @@ main(int argc, char **argv) { fd_set m_readfds; int nfds = 0; size_t i; + uint16_t cache_ignore_options[] = { COAP_OPTION_BLOCK1, + COAP_OPTION_BLOCK2, + /* See https://tools.ietf.org/html/rfc7959#section-2.10 */ + COAP_OPTION_MAXAGE, + /* See https://tools.ietf.org/html/rfc7959#section-2.10 */ + COAP_OPTION_IF_NONE_MATCH }; #ifndef _WIN32 struct sigaction sa; #endif @@ -1475,6 +1734,9 @@ main(int argc, char **argv) { init_resources(ctx); + /* Define the options to ignore when setting up cache-keys */ + coap_cache_ignore_options(ctx, cache_ignore_options, + sizeof(cache_ignore_options)/sizeof(cache_ignore_options[0])); /* join multicast group if requested at command line */ if (group) coap_join_mcast_group(ctx, group); @@ -1614,6 +1876,13 @@ main(int argc, char **argv) { if (valid_pki_snis.count) free(valid_pki_snis.pki_sni_list); + for (i = 0; i < (size_t)dynamic_count; i++) { + coap_delete_string(dynamic_entry[i].uri_path); + coap_delete_binary(dynamic_entry[i].value); + } + if (dynamic_entry) free(dynamic_entry); + if (example_data_ptr) coap_delete_binary(example_data_ptr); + coap_free_context(ctx); coap_cleanup(); diff --git a/examples/lwip/Makefile b/examples/lwip/Makefile index 5664d808..ff9cc830 100644 --- a/examples/lwip/Makefile +++ b/examples/lwip/Makefile @@ -39,7 +39,7 @@ CFLAGS += -I$(top_srcdir)/include/coap2 vpath %.c $(top_srcdir)/src -COAPOBJS = net.o coap_debug.o option.o resource.o pdu.o encode.o subscribe.o coap_io_lwip.o block.o uri.o str.o coap_session.o coap_notls.o coap_hashkey.o address.o coap_tcp.o async.o +COAPOBJS = net.o coap_cache.o coap_debug.o option.o resource.o pdu.o encode.o subscribe.o coap_io_lwip.o block.o uri.o str.o coap_session.o coap_notls.o coap_hashkey.o address.o coap_tcp.o async.o CFLAGS += -g3 -Wall -Wextra -pedantic -O0 -fpack-struct # not sorted out yet diff --git a/include/coap2/coap.h.windows b/include/coap2/coap.h.windows index 1ecd6cf4..0c20d600 100644 --- a/include/coap2/coap.h.windows +++ b/include/coap2/coap.h.windows @@ -37,6 +37,7 @@ extern "C" { #include "async.h" #include "bits.h" #include "block.h" +#include "coap_cache.h" #include "coap_debug.h" #include "coap_dtls.h" #include "coap_event.h" diff --git a/include/coap2/coap_cache.h b/include/coap2/coap_cache.h index eb3b2ee4..01fd3722 100644 --- a/include/coap2/coap_cache.h +++ b/include/coap2/coap_cache.h @@ -8,82 +8,183 @@ /** * @file coap_cache.h - * @brief Provides a simple request storage for CoAP requests + * @brief Provides a simple cache request storage for CoAP requests */ #ifndef COAP_CACHE_H_ #define COAP_CACHE_H_ -#include - #include "coap_forward_decls.h" -typedef enum { - COAP_CACHE_INVALID=-1, - COAP_CACHE_MAXKEY=INT_MAX -} coap_cache_key_t; +/** + * Callback to free off the app data when the cache-entry is + * being deleted / freed off. + * + * @param data The app data to be freed off. + */ +typedef void (*coap_cache_app_data_free_callback_t)(void *data); + +typedef enum coap_cache_session_based_t { + COAP_CACHE_NOT_SESSION_BASED, + COAP_CACHE_IS_SESSION_BASED +} coap_cache_session_based_t; + +typedef enum coap_cache_record_pdu_t { + COAP_CACHE_NOT_RECORD_PDU, + COAP_CACHE_RECORD_PDU +} coap_cache_record_pdu_t; /** - * Calculates a cache key for the given CoAP PDU. See + * Calculates a cache-key for the given CoAP PDU. See * https://tools.ietf.org/html/rfc7252#section-5.6 * for an explanation of CoAP cache keys. * - * @param pdu The CoAP PDU for which a cache key is to be - * calculated. + * Specific CoAP options can be removed from the cache-key. Examples of + * this are the BLOCK1 and BLOCK2 options - which make no real sense including + * them in a client or server environment, but should be included in a proxy + * caching environment where things are cached on a per block basis. + * This is done globally by calling the coap_cache_ignore_options() + * function. * - * @return The calculcated cache key. + * NOTE: The returned cache-key needs to be freed off by the caller by + * calling coap_cache_delete_key(). + * + * @param session The session to add into cache-key if @p session_based + * is set. + * @param pdu The CoAP PDU for which a cache-key is to be + * calculated. + * @param session_based COAP_CACHE_IS_SESSION_BASED if session based + * cache-key, else COAP_CACHE_NOT_SESSION_BASED. + * + * @return The returned cache-key or @c NULL if failure. */ -coap_cache_key_t coap_cache_key(const coap_pdu_t *pdu); +coap_cache_key_t *coap_cache_derive_key(const coap_session_t *session, + const coap_pdu_t *pdu, + coap_cache_session_based_t session_based); /** - * Marks a request for permanent storage. The request may be retrieved - * through its cache-key. + * Delete the cache-key. * - * @param ctx The context to use. - * @param request The request to be stored. - * - * @return The cache key that corresponds to the newly stored - * request or @c COAP_CACHE_INVALID if the request could - * not be stored. + * @param cache_key The cache-key to delete. */ -coap_cache_key_t coap_cache_mark_request(coap_context_t *ctx, - const coap_pdu_t *request); +void coap_delete_cache_key(coap_cache_key_t *cache_key); /** - * Clears a mark from a request. + * Define the CoAP options that are not to be included when calculating + * the cache-key. Options that are defined as Non-Cache and the Observe + * option are always ignored. * - * @param ctx The context to use. - * @param cache_key The cache key for the request which can be - * unmarked. + * @param context The context to save the ignored options information in. + * @param options The array of options to ignore. + * @param count The number of options to ignore. Use 0 to reset the + * options matching. + * + * @return @return @c 1 if successful, else @c 0. */ -void coap_cache_unmark_request(coap_context_t *ctx, - coap_cache_key_t cache_key); +int coap_cache_ignore_options(coap_context_t *context, + const uint16_t *options, size_t count); /** - * Searches for a cache entry identified by @p cache_key. This - * function returns the corresponding cache entry or @c NULL + * Create a new cache-entry hash keyed by cache-key derived from the PDU. + * + * If @p session_based is set, then this cache-entry will get deleted when + * the session is freed off. + * If @p record_pdu is set, then the copied PDU will get freed off when + * this cache-entry is deleted. + * + * The cache-entry is maintained on a context hash list. + * + * @param session The session to use to derive the context from. + * @param pdu The pdu to use to generate the cache-key. + * @param record_pdu COAP_CACHE_RECORD_PDU if to take a copy of the PDU for + * later use, else COAP_CACHE_NOT_RECORD_PDU. + * @param session_based COAP_CACHE_IS_SESSION_BASED if to associate this + * cache-entry with the the session (which is embedded + * in the cache-entry), else COAP_CACHE_NOT_SESSION_BASED. + * @param idle_time Idle time in seconds before cache-entry is expired. + * If set to 0, it does not expire (but will get + * deleted if the session is deleted and it is session_based). + * + * @return The returned cache-key or @c NULL if failure. + */ +coap_cache_entry_t *coap_new_cache_entry(coap_session_t *session, + const coap_pdu_t *pdu, + coap_cache_record_pdu_t record_pdu, + coap_cache_session_based_t session_based, + unsigned int idle_time); + +/** + * Remove a cache-entry from the hash list and free off all the appropriate + * contents apart from app_data. + * + * @param context The context to use. + * @param cache_entry The cache-entry to remove. + */ +void coap_delete_cache_entry(coap_context_t *context, + coap_cache_entry_t *cache_entry); + +/** + * Searches for a cache-entry identified by @p cache_key. This + * function returns the corresponding cache-entry or @c NULL * if not found. * - * @param ctx The context to use. - * @param cache_key The cache key to look up. + * @param context The context to use. + * @param cache_key The cache-key to get the hashed coap-entry. * - * @return The cache entry for @p cache_key or @c NULL if not found. + * @return The cache-entry for @p cache_key or @c NULL if not found. */ -struct coap_cache_entry_t *coap_cache_lookup_key(coap_context_t *ctx, - coap_cache_key_t cache_key); +coap_cache_entry_t *coap_cache_get_by_key(coap_context_t *context, + const coap_cache_key_t *cache_key); /** - * Searches for a cache entry corresponding to @p request. This - * function returns the corresponding cache entry or @c NULL if not + * Searches for a cache-entry corresponding to @p pdu. This + * function returns the corresponding cache-entry or @c NULL if not * found. * - * @param ctx The context to use. - * @param request The CoAP request to search for. + * @param session The session to use. + * @param pdu The CoAP request to search for. + * @param session_based COAP_CACHE_IS_SESSION_BASED if session based + * cache-key to be used, else COAP_CACHE_NOT_SESSION_BASED. * - * @return The cache entry for @p request or @c NULL if not found. + * @return The cache-entry for @p request or @c NULL if not found. */ -struct coap_cache_entry_t *coap_cache_lookup_request(coap_context_t *ctx, - const coap_pdu_t *request); +coap_cache_entry_t *coap_cache_get_by_pdu(coap_session_t *session, + const coap_pdu_t *pdu, + coap_cache_session_based_t session_based); +/** + * Returns the PDU information stored in the @p coap_cache entry. + * + * @param cache_entry The CoAP cache entry. + * + * @return The PDU information stored in the cache_entry or NULL + * if the PDU was not initially copied. + */ +const coap_pdu_t *coap_cache_get_pdu(const coap_cache_entry_t *cache_entry); + +/** + * Stores @p data with the given cache entry. This function + * overwrites any value that has previously been stored with @p + * cache_entry. + * + * @param cache_entry The CoAP cache entry. + * @param data The data pointer to store with wih the cache entry. Note that + * this data must be valid during the lifetime of @p cache_entry. + * @param callback The callback to call to free off this data when the + * cache-entry is deleted, or @c NULL if not required. + */ +void coap_cache_set_app_data(coap_cache_entry_t *cache_entry, void *data, + coap_cache_app_data_free_callback_t callback); + +/** + * Returns any application-specific data that has been stored with @p + * cache_entry using the function coap_cache_set_app_data(). This function will + * return @c NULL if no data has been stored. + * + * @param cache_entry The CoAP cache entry. + * + * @return The data pointer previously stored or @c NULL if no data stored. + */ +void *coap_cache_get_app_data(const coap_cache_entry_t *cache_entry); #endif /* COAP_CACHE_H */ diff --git a/include/coap2/coap_cache_internal.h b/include/coap2/coap_cache_internal.h new file mode 100644 index 00000000..91f6f0f5 --- /dev/null +++ b/include/coap2/coap_cache_internal.h @@ -0,0 +1,108 @@ +/* + * coap_cache_internal.h -- Cache functions for libcoap + * + * Copyright (C) 2019--2020 Olaf Bergmann and others + * + * This file is part of the CoAP library libcoap. Please see README for terms + * of use. + */ + +/** + * @file coap_cache_internal.h + * @brief COAP cache internal information + */ + +#ifndef COAP_CACHE_INTERNAL_H_ +#define COAP_CACHE_INTERNAL_H_ + +#include "coap_io.h" + +/** + * @defgroup cache Cache Support (Internal) + * API functions for CoAP Caching + * @{ + */ + +/* Holds a digest in binary typically sha256 except for notls */ +typedef struct coap_digest_t { + uint8_t key[32]; +} coap_digest_t; + +struct coap_cache_key_t { + uint8_t key[32]; +}; + +struct coap_cache_entry_t { + UT_hash_handle hh; + coap_cache_key_t *cache_key; + coap_session_t *session; + coap_pdu_t *pdu; + void* app_data; + coap_tick_t expire_ticks; + unsigned int idle_timeout; + coap_cache_app_data_free_callback_t callback; +}; + +/** + * Expire coap_cache_entry_t entries + * + * Internal function. + * + * @param context The context holding the coap-entries to exire + */ +void coap_expire_cache_entries(coap_context_t *context); + +typedef void coap_digest_ctx_t; + +/** + * Initialize a coap_digest + * + * Internal function. + * + * @return The digest context or @c NULL if failure. + */ +coap_digest_ctx_t *coap_digest_setup(void); + +/** + * Free off coap_digest_ctx_t. Always done by + * coap_digest_final() + * + * Internal function. + * + * @param digest_ctx The coap_digest context. + */ +void coap_digest_free(coap_digest_ctx_t *digest_ctx); + +/** + * Update the coap_digest information with the next chunk of data + * + * Internal function. + * + * @param digest_ctx The coap_digest context. + * @param data Pointer to data. + * @param data_len Number of bytes. + * + * @return @c 1 success, @c 0 failure. + */ +int coap_digest_update(coap_digest_ctx_t *digest_ctx, + const uint8_t *data, + size_t data_len + ); + +/** + * Finalize the coap_digest information into the provided + * @p digest_buffer. + * + * Internal function. + * + * @param digest_ctx The coap_digest context. + * @param digest_buffer Pointer to digest buffer to update + * + * @return @c 1 success, @c 0 failure. + */ +int coap_digest_final(coap_digest_ctx_t *digest_ctx, + coap_digest_t *digest_buffer); + +/** @} */ + +#endif /* COAP_CACHE_INTERNAL_H_ */ diff --git a/include/coap2/coap_forward_decls.h b/include/coap2/coap_forward_decls.h index e99c6b42..541d129d 100644 --- a/include/coap2/coap_forward_decls.h +++ b/include/coap2/coap_forward_decls.h @@ -21,6 +21,8 @@ * so that applications (using coap.h) as well as libcoap builds * can reference them (and makes .h file dependencies a lot simpler). */ +struct coap_cache_entry_t; +struct coap_cache_key_t; struct coap_context_t; struct coap_dtls_pki_t; struct coap_endpoint_t; @@ -28,12 +30,17 @@ struct coap_queue_t; struct coap_session_t; struct coap_string_t; struct coap_subscription_t; -struct coap_cache_entry_t; /* - * typedef all the structures that are defined in coap_*_internal.h + * typedef all the opaque structures that are defined in coap_*_internal.h */ +/* ************* coap_cache_internal.h ***************** */ + +/** Cache Entry information */ +typedef struct coap_cache_entry_t coap_cache_entry_t; +typedef struct coap_cache_key_t coap_cache_key_t; + /* ************* coap_session_internal.h ***************** */ /** diff --git a/include/coap2/coap_internal.h b/include/coap2/coap_internal.h index 727e5462..b1821168 100644 --- a/include/coap2/coap_internal.h +++ b/include/coap2/coap_internal.h @@ -2,7 +2,7 @@ * coap_internal.h -- Structures, Enums & Functions that are not exposed to * application programming * - * Copyright (C) 2019 Jon Shallow + * Copyright (C) 2019-2020 Jon Shallow * * This file is part of the CoAP library libcoap. Please see README for terms * of use. @@ -46,6 +46,7 @@ #include "coap_mutex.h" /* Specifically defined internal .h files */ +#include "coap_cache_internal.h" #include "coap_session_internal.h" #include "coap_subscribe_internal.h" #include "coap_tcp_internal.h" diff --git a/include/coap2/coap_session.h b/include/coap2/coap_session.h index afb37bef..01041388 100644 --- a/include/coap2/coap_session.h +++ b/include/coap2/coap_session.h @@ -447,29 +447,104 @@ void coap_session_mfree(coap_session_t *session); * Number of seconds when to expect an ACK or a response to an * outstanding CON message. * RFC 7252, Section 4.8 Default value of ACK_TIMEOUT is 2 + * + * Configurable using coap_session_set_ack_timeout() */ #define COAP_DEFAULT_ACK_TIMEOUT ((coap_fixed_point_t){2,0}) - /** - * A factor that is used to randomize the wait time before a message - * is retransmitted to prevent synchronization effects. - * RFC 7252, Section 4.8 Default value of ACK_RANDOM_FACTOR is 1.5 - */ + /** + * A factor that is used to randomize the wait time before a message + * is retransmitted to prevent synchronization effects. + * RFC 7252, Section 4.8 Default value of ACK_RANDOM_FACTOR is 1.5 + * + * Configurable using coap_session_set_ack_random_factor() + */ #define COAP_DEFAULT_ACK_RANDOM_FACTOR ((coap_fixed_point_t){1,500}) - /** - * Number of message retransmissions before message sending is stopped - * RFC 7252, Section 4.8 Default value of MAX_RETRANSMIT is 4 - */ + /** + * Number of message retransmissions before message sending is stopped + * RFC 7252, Section 4.8 Default value of MAX_RETRANSMIT is 4 + * + * Configurable using coap_session_set_max_retransmit() + */ #define COAP_DEFAULT_MAX_RETRANSMIT 4 - /** - * The number of simultaneous outstanding interactions that a client - * maintains to a given server. - * RFC 7252, Section 4.8 Default value of NSTART is 1 - */ + /** + * The number of simultaneous outstanding interactions that a client + * maintains to a given server. + * RFC 7252, Section 4.8 Default value of NSTART is 1 + */ #define COAP_DEFAULT_NSTART 1 + /** + * The MAX_TRANSMIT_SPAN definition for the session (s). + * + * RFC 7252, Section 4.8.2 Calculation of MAX_TRAMSMIT_SPAN + * ACK_TIMEOUT * ((2 ** (MAX_RETRANSMIT)) - 1) * ACK_RANDOM_FACTOR + */ +#define COAP_MAX_TRANSMIT_SPAN(s) \ + ((s->ack_timeout.integer_part * 1000 + s->ack_timeout.fractional_part) * \ + ((1 << (s->max_retransmit)) -1) * \ + (s->ack_random_factor.integer_part * 1000 + \ + s->ack_random_factor.fractional_part) \ + / 1000000) + + /** + * The MAX_TRANSMIT_WAIT definition for the session (s). + * + * RFC 7252, Section 4.8.2 Calculation of MAX_TRAMSMIT_WAIT + * ACK_TIMEOUT * ((2 ** (MAX_RETRANSMIT + 1)) - 1) * ACK_RANDOM_FACTOR + */ +#define COAP_MAX_TRANSMIT_WAIT(s) \ + ((s->ack_timeout.integer_part * 1000 + s->ack_timeout.fractional_part) * \ + ((1 << (s->max_retransmit + 1)) -1) * \ + (s->ack_random_factor.integer_part * 1000 + \ + s->ack_random_factor.fractional_part) \ + / 1000000) + + /** + * The MAX_LATENCY definition. + * RFC 7252, Section 4.8.2 MAX_LATENCY is 100. + */ +#define COAP_MAX_LATENCY 100 + + /** + * The PROCESSING_DELAY definition for the session (s). + * + * RFC 7252, Section 4.8.2 Calculation of PROCESSING_DELAY + * PROCESSING_DELAY set to ACK_TIMEOUT + */ +#define COAP_PROCESSING_DELAY(s) \ + ((s->ack_timeout.integer_part * 1000 + s->ack_timeout.fractional_part + 500) \ + / 1000) + + /** + * The MAX_RTT definition for the session (s). + * + * RFC 7252, Section 4.8.2 Calculation of MAX_RTT + * (2 * MAX_LATENCY) + PROCESSING_DELAY + */ +#define COAP_MAX_RTT(s) \ + ((2 * COAP_MAX_LATENCY) + COAP_PROCESSING_DELAY(s)) + + /** + * The EXCHANGE_LIFETIME definition for the session (s). + * + * RFC 7252, Section 4.8.2 Calculation of EXCHANGE_LIFETIME + * MAX_TRANSMIT_SPAN + (2 * MAX_LATENCY) + PROCESSING_DELAY + */ +#define COAP_EXCHANGE_LIFETIME(s) \ + (COAP_MAX_TRANSMIT_SPAN(s) + (2 * COAP_MAX_LATENCY) + COAP_PROCESSING_DELAY(s)) + + /** + * The NON_LIFETIME definition for the session (s). + * + * RFC 7252, Section 4.8.2 Calculation of NON_LIFETIME + * MAX_TRANSMIT_SPAN + MAX_LATENCY + */ +#define COAP_NON_LIFETIME(s) \ + (COAP_MAX_TRANSMIT_SPAN(s) + COAP_MAX_LATENCY) + /** @} */ /** diff --git a/include/coap2/mem.h b/include/coap2/mem.h index f8f58c98..fd29215b 100644 --- a/include/coap2/mem.h +++ b/include/coap2/mem.h @@ -62,9 +62,9 @@ typedef enum { void *coap_malloc_type(coap_memory_tag_t type, size_t size); /** - * Reallocates a chunk of @p p bytes created by coap_malloc_type() or + * Reallocates a chunk @p p of bytes created by coap_malloc_type() or * coap_realloc_type() and returns a pointer to the newly allocated memory of - * @p size.. + * @p size. * The @p type is used to select the appropriate storage * container on constrained devices. The storage allocated by coap_malloc_type() * coap_realloc_type() must be released with coap_free_type(). diff --git a/include/coap2/net.h b/include/coap2/net.h index 7a32475f..af434b4e 100644 --- a/include/coap2/net.h +++ b/include/coap2/net.h @@ -209,7 +209,9 @@ typedef struct coap_context_t { unsigned int csm_timeout; /**< Timeout for waiting for a CSM from the remote side. 0 means disabled. */ int observe_pending; /**< Observe response pending */ - struct coap_cache_entry_t *cache; /**< CoAP message cache */ + coap_cache_entry_t *cache; /**< CoAP cache-entry cache */ + uint16_t *cache_ignore_options; /**< CoAP options to ignore when creating a cache-key */ + size_t cache_ignore_count; /**< The number of CoAP options to ignore when creating a cache-key */ void *app; /**< application-specific data */ #ifdef COAP_EPOLL_SUPPORT int epfd; /**< External FD for epoll */ diff --git a/libcoap-2.map b/libcoap-2.map index cef0dbcb..b89fb84d 100644 --- a/libcoap-2.map +++ b/libcoap-2.map @@ -16,6 +16,13 @@ global: coap_address_set_port; coap_add_token; coap_adjust_basetime; + coap_cache_derive_key; + coap_cache_get_app_data; + coap_cache_get_by_key; + coap_cache_get_by_pdu; + coap_cache_get_pdu; + coap_cache_ignore_options; + coap_cache_set_app_data; coap_calc_timeout; coap_cancel_all_messages; coap_cancel_session_messages; @@ -39,6 +46,8 @@ global: coap_delete_attr; coap_delete_binary; coap_delete_bin_const; + coap_delete_cache_entry; + coap_delete_cache_key; coap_delete_node; coap_delete_observer; coap_delete_observers; @@ -97,6 +106,7 @@ global: coap_network_send; coap_new_binary; coap_new_bin_const; + coap_new_cache_entry; coap_new_client_session; coap_new_client_session_pki; coap_new_client_session_psk; diff --git a/libcoap-2.sym b/libcoap-2.sym index 6b728af3..7c2ec99e 100644 --- a/libcoap-2.sym +++ b/libcoap-2.sym @@ -14,6 +14,13 @@ coap_address_init coap_address_set_port coap_add_token coap_adjust_basetime +coap_cache_derive_key +coap_cache_get_app_data +coap_cache_get_by_key +coap_cache_get_by_pdu +coap_cache_get_pdu +coap_cache_ignore_options +coap_cache_set_app_data coap_calc_timeout coap_cancel_all_messages coap_cancel_session_messages @@ -37,6 +44,8 @@ coap_decode_var_bytes8 coap_delete_attr coap_delete_binary coap_delete_bin_const +coap_delete_cache_entry +coap_delete_cache_key coap_delete_node coap_delete_observer coap_delete_observers @@ -95,6 +104,7 @@ coap_network_read coap_network_send coap_new_binary coap_new_bin_const +coap_new_cache_entry coap_new_client_session coap_new_client_session_pki coap_new_client_session_psk diff --git a/man/Makefile.am b/man/Makefile.am index 9f4d895a..ef521897 100644 --- a/man/Makefile.am +++ b/man/Makefile.am @@ -19,6 +19,7 @@ if BUILD_MANPAGES # building the manpages TXT3 = coap_attribute.txt \ + coap_cache.txt \ coap_context.txt \ coap_encryption.txt \ coap_handler.txt \ @@ -78,6 +79,8 @@ A2X_EXTRA_PAGES = @DOLLAR_SIGN@(shell for fil in $(TXT3) ; do sed -ne '/^NAME/,/ # Then all the alternative names as well as the extras defined below need # to be cleaned up in a 'make unistall'. install-man: install-man3 install-man5 install-man7 + @echo ".so man3/coap_cache.3" > coap_cache_get_app_data.3 + @echo ".so man3/coap_cache.3" > coap_cache_set_app_data.3 @echo ".so man3/coap_context.3" > coap_context_set_pki_root_cas.3 @echo ".so man3/coap_pdu_setup.3" > coap_add_data_blocked_response.3 @echo ".so man3/coap_pdu_setup.3" > coap_encode_var_safe.3 diff --git a/man/coap.txt.in b/man/coap.txt.in index cfdcd451..fd9cda8d 100644 --- a/man/coap.txt.in +++ b/man/coap.txt.in @@ -38,10 +38,10 @@ examples directory. SEE ALSO -------- -*coap_attribute*(3), *coap_context*(3), *coap_encryption*(3), *coap_handler*(3), -*coap_io*(3), *coap_keepalive*(3), *coap_logging*(3), *coap_observe*(3), -*coap_pdu_setup*(3), *coap_recovery*(3), *coap_resource*(3), *coap_session*(3), -*coap_string*(3) and *coap_tls_library*(3) +*coap_attribute*(3), *coap_cache*(3,) *coap_context*(3), *coap_encryption*(3), +*coap_handler*(3), *coap_io*(3), *coap_keepalive*(3), *coap_logging*(3), +*coap_observe*(3), *coap_pdu_setup*(3), *coap_recovery*(3), *coap_resource*(3), +*coap_session*(3), *coap_string*(3) and *coap_tls_library*(3) For example executables, see *coap-client*(5), *coap-rd*(5) and *coap-server*(5) @@ -68,7 +68,8 @@ for further information. BUGS ---- Please report bugs on the mailing list for libcoap: -libcoap-developers@lists.sourceforge.net +libcoap-developers@lists.sourceforge.net or raise an issue on GitHub at +https://github.com/obgm/libcoap/issues AUTHORS ------- diff --git a/man/coap_cache.txt.in b/man/coap_cache.txt.in new file mode 100644 index 00000000..72ebd58e --- /dev/null +++ b/man/coap_cache.txt.in @@ -0,0 +1,385 @@ +// -*- mode:doc; -*- +// vim: set syntax=asciidoc,tw=0: + +coap_cache(3) +============= +:doctype: manpage +:man source: coap_cache +:man version: @PACKAGE_VERSION@ +:man manual: libcoap Manual + +NAME +---- +coap_cache, +coap_cache_derive_key, +coap_cache_delete_key, +coap_cache_ignore_options, +coap_new_cache_entry, +coap_delete_cache_entry, +coap_cache_get_by_key, +coap_cache_get_by_pdu, +coap_cache_get_pdu, +coap_cache_set_app_data, +coap_cache_get_app_data +- cache functions + +SYNOPSIS +-------- +*#include * + +*coap_cache_key_t *coap_cache_derive_key(const coap_session_t *_session_, +const coap_pdu_t *_pdu_, coap_cache_session_based_t _session_based_);* + +*void coap_delete_cache_key(coap_cache_key_t *_cache_key_);* + +*int coap_cache_ignore_options(coap_context_t *_context_, +const uint16_t *_options_, size_t _count_);* + +*coap_cache_entry_t *coap_new_cache_entry(coap_session_t *_session_, +const coap_pdu_t *_pdu_, coap_cache_record_pdu_t _record_pdu_, +coap_cache_session_based_t _session_based_, unsigned int _idle_timeout_);* + +*void coap_delete_cache_entry(coap_context_t *_context_, +coap_cache_entry_t *_cache_entry_);* + +*coap_cache_entry_t *coap_cache_get_by_key(coap_context_t *_context_, +const coap_cache_key_t *_cache_key_);* + +*coap_cache_entry_t *coap_cache_get_by_pdu(coap_session_t *_session_, +const coap_pdu_t *_pdu_, coap_cache_session_based_t _session_based_);* + +*const coap_pdu_t *coap_cache_get_pdu(const coap_cache_entry_t *_cache_entry_);* + +*void coap_cache_set_app_data(coap_cache_entry_t *_cache_entry_, void *_data_, +coap_cache_app_data_free_callback_t _callback_);* + +*void *coap_cache_get_app_data(const coap_cache_entry_t *_cache_entry_);* + +Link with *-lcoap-@LIBCOAP_API_VERSION@*, *-lcoap-@LIBCOAP_API_VERSION@-gnutls*, +*-lcoap-@LIBCOAP_API_VERSION@-openssl*, *-lcoap-@LIBCOAP_API_VERSION@-mbedtls* +or *-lcoap-@LIBCOAP_API_VERSION@-tinydtls* depending on your (D)TLS library +type. + +DESCRIPTION +----------- + +The CoAP Cache provides support for two opaque objects that can be used for +tracking requests and responses. + +The first is the ability to derive a Cache Key from the cacheable parts of a +CoAP PDU as defined in +https://tools.ietf.org/html/rfc7252#section-5.6 updated by +https://tools.ietf.org/html/rfc7641#section-2 and +https://tools.ietf.org/html/rfc8132#section-2 . + +The Cache Key is a SHA256 digest if libcoap was built with TLS support, +otherwise it uses the coap_hash() function, using the information abstracted +from the PDU and (optionally) the CoAP session. + +This Cache Key can then be used to match against incoming PDUs and then +appropriate action logic can take place. + +There is support for excluding specific CoAP options from the Cache Key. +Examples could be to exclude CoAP BLOCK1 and BLOCK2 Options for the client or +server for ease of tracking a large PUT or GET response, but to not exclude +these CoAP options in a proxy where it makes sense to cache the individual +blocks. + +The second is providing Cache Entries (which can be looked up by PDU and hence +by Cache Key) which hold additional information to make information tracking +simpler. These Cache Entries are automatically deleted when a session closes +or a context is deleted. These Cache Entries are maintained on a hashed list +for speed of lookup. + +The following enums are defined. + +[source, c] +---- +typedef enum coap_cache_session_based_t { + COAP_CACHE_NOT_SESSION_BASED, + COAP_CACHE_IS_SESSION_BASED +} coap_cache_session_based_t; + +typedef enum coap_cache_record_pdu_t { + COAP_CACHE_NOT_RECORD_PDU, + COAP_CACHE_RECORD_PDU +} coap_cache_record_pdu_t; +---- + +The *coap_cache_derive_key*() function abstracts all the non NoCacheKey CoAP +options, ignores the CoAP Observer option and includes a FETCH body from _pdu_. +If _session_based_ is COAP_CACHE_IS_SESSION_BASED, then _session_ is also +included. CoAP options can be specifically ignored by the use of +*coap_cache_ignore_options*(). A digest is then built from all of the +information and returned. NULL is returned on error. + +The *coap_delete_cache_key*() function deletes the _cache_key_ that was +returned from a *coap_cache_derive_key*() call. + +The *coap_cache_ignore_options*() function is used to store in _context_ a +list of _count_ options held in _options_. The specified _options_ will not +be included in the data used for the *coap_cache_derive_key*() function. + +The *coap_new_cache_entry*() function will create a new Cache Entry based on +the Cache Key derived from the _pdu_, _session_based_ and _session_. If +_record_pdu_ is COAP_CACHE_RECORD_PDU, then a copy of the _pdu_ is stored in +the Cache Entry for subsequent retrieval. The Cache Entry can also store +application specific data (*coap_cache_set_app_data*() and +*coap_cache_get_app_data*()). _idle_timeout_ in seconds defines the length of +time not being used before it gets deleted. If _idle_timeout_ is set to +0, then the Cache Entry will not get idle expired. The created Cache +Entry is returned, or NULL on error. + +The *coap_delete_cache_entry*() function can be used to delete the Cache Entry +_cache_entry_. This will remove the Cache Entry from the hash lookup list and +free off any internally held data. If the Cache Entry is session based, then +it will automatically get deleted when the session is freed off or when the +idle timeout expires. + +The *coap_cache_get_by_key*() function will locate the Cache Entry held in the +_context_ environment that has Cache Key _cache_key_. Returns NULL if the +Cache Key was not found. + +The *coap_cache_get_by_pdu*() function will locate the Cache Entry held in the +_context_ environment that has a Cache Key derived from the _pdu_ and +whether _session_based_ or not. + +The *coap_cache_get_pdu*() function returns the PDU that was stored with the +Cache Entry when it was created with *coap_new_cache_entry*() and _record_pdu_ +was set. If a PDU was not initially stored, NULL is returned. + +*NOTE:* A copy of the returned PDU must be taken for using in sending a CoAP +packet. + +The *coap_cache_set_app_data*() function is used to asssociate _data_ with the +_cache_entry_. If _callback_ is not NULL, it points to a function to free off +_data_ when the _cache_entry_ is deleted. If any data has been previously +stored in the _cache_entry_, the pointer to the old data will get overwritten, +but the old data will not get freed off. + +The _callback_ handler function prototype is defined as: +[source, c] +---- +typedef void (*coap_cache_app_data_free_callback_t)(void *data); +---- +where _data_ is passed into the callback function whenever the Cache Entry is +deleted. + +The *coap_cache_get_app_data*() function is used to get the previously stored +_data_ in the _cache_entry_. + +RETURN VALUES +------------- +*coap_cache_derive_key*() function returns a newly created Cache Key or +NULL if there is a creation failure. + +*coap_cache_ignore_options*() function returs 1 if success, 0 on failure. + +*coap_new_cache_entry*(), *coap_cache_get_by_key*() and +*coap_cache_get_by_pdu*() functions return the Cache Entry or NULL if there +is a failure. + +*coap_cache_get_pdu*() function the PDU that is held within the Cache Entry or +NULL if there is no PDU available. + +EXAMPLES +-------- +*PUT Handler supporting BLOCK1* + +[source, c] +---- +#include + +static coap_binary_t *example_data_ptr = NULL; +static int example_data_media_type = COAP_MEDIATYPE_TEXT_PLAIN; + +static void +cache_free_app_data(void *data) { + coap_binary_t *bdata = (coap_binary_t*)data; + coap_delete_binary(bdata); +} + +/* + * Large Data PUT handler + */ + +static void +hnd_put_example_data(coap_context_t *ctx, + coap_resource_t *resource, + coap_session_t *session, + coap_pdu_t *request, + coap_binary_t *token, + coap_string_t *query, + coap_pdu_t *response +) { + size_t size; + uint8_t *data; + coap_block_t block1; + unsigned char buf[6]; /* space to hold encoded/decoded uints */ + coap_opt_iterator_t opt_iter; + coap_opt_t *option; + (void)ctx; + (void)token; + (void)query; + + if (coap_get_block(request, COAP_OPTION_BLOCK1, &block1)) { + /* handle BLOCK1 */ + coap_cache_entry_t *cache_entry = coap_cache_get_by_pdu(session, + request, + COAP_CACHE_IS_SESSION_BASED); + size_t offset = block1.num << (block1.szx + 4); + coap_binary_t *data_so_far; + + if (!cache_entry && block1.num == 0) { + /* + * Set idle_timeout parameter to COAP_MAX_TRANSMIT_WAIT if you want + * early removal on transmission failure. -1 means only delete when + * the session is deleted as session_based is set here. + */ + cache_entry = coap_new_cache_entry(session, request, + COAP_CACHE_NOT_RECORD_PDU, + COAP_CACHE_IS_SESSION_BASED, 0); + } + if (!cache_entry) { + if (block1.num == 0) { + coap_log(LOG_WARNING, "Unable to create a new cache entry\n"); + } + else { + coap_log(LOG_WARNING, + "No cache entry available for the non-first BLOCK1\n"); + } + response->code = COAP_RESPONSE_CODE(500); + return; + } + + data_so_far = coap_cache_get_app_data(cache_entry); + if (offset == 0) { + if (data_so_far) { + coap_delete_binary(data_so_far); + data_so_far = NULL; + } + } + else if (offset > + (data_so_far ? data_so_far->length : 0)) { + /* Upload is not sequential - block missing */ + response->code = COAP_RESPONSE_CODE(408); + return; + } + else if (offset < + (data_so_far ? data_so_far->length : 0)) { + /* Upload is not sequential - block duplicated */ + goto just_respond; + } + + if (coap_get_data(request, &size, &data) && (size > 0)) { + if (!data_so_far) { + data_so_far = coap_new_binary(size); + memcpy(data_so_far->s, data, size); + } + else { + /* Add in new block to end of current data */ + data_so_far = coap_resize_binary(data_so_far, offset + size); + memcpy(&data_so_far->s[offset], data, size); + } + } + + if (!block1.m) { + /* all the data in - now update the resource */ + coap_delete_binary(example_data_ptr); + example_data_ptr = data_so_far; + coap_cache_set_app_data(cache_entry, NULL, NULL); + if ((option = coap_check_option(request, COAP_OPTION_CONTENT_FORMAT, + &opt_iter)) != NULL) { + example_data_media_type = + coap_decode_var_bytes (coap_opt_value (option), + coap_opt_length (option)); + } + else { + example_data_media_type = COAP_MEDIATYPE_TEXT_PLAIN; + } + coap_resource_notify_observers(resource, NULL); + } + else { + /* save the updated data for the next block */ + coap_cache_set_app_data(cache_entry,data_so_far, cache_free_app_data); + } + +just_respond: + if (block1.m) { + response->code = COAP_RESPONSE_CODE(231); + } + else { + response->code = COAP_RESPONSE_CODE(204); + } + coap_add_option(response, + COAP_OPTION_BLOCK1, + coap_encode_var_safe(buf, sizeof(buf), + ((block1.num << 4) | + (block1.m << 3) | + block1.szx)), + buf); + } + else if (coap_get_data(request, &size, &data) && (size > 0)) { + /* Not a BLOCK1 with data */ + if (example_data_ptr) { + coap_delete_binary(example_data_ptr); + } + example_data_ptr = coap_new_binary(size); + memcpy (example_data_ptr->s, data, size); + if ((option = coap_check_option(request, COAP_OPTION_CONTENT_FORMAT, + &opt_iter)) != NULL) { + example_data_media_type = coap_decode_var_bytes (coap_opt_value (option), + coap_opt_length (option)); + } + else { + example_data_media_type = COAP_MEDIATYPE_TEXT_PLAIN; + } + coap_resource_notify_observers(resource, NULL); + } + else { + /* Not a BLOCK1 and no data */ + if (example_data_ptr) { + coap_delete_binary(example_data_ptr); + example_data_ptr = NULL; + } + } +} + +int main(int argc, char* argv[]){ + coap_context_t *ctx = NULL; /* Set up as normal */ + /* ... */ + uint16_t cache_ignore_options[] = { COAP_OPTION_BLOCK1, + COAP_OPTION_BLOCK2 }; + + /* Remove (void) definition if variable is used */ + (void)argc; + (void)argv; + + /* ... */ + + /** Define the options to ignore when setting up cache-keys */ + coap_cache_ignore_options(ctx, cache_ignore_options, + sizeof(cache_ignore_options)/sizeof(cache_ignore_options[0])); + + /* ... */ + +} +---- + +SEE ALSO +-------- +*coap_pdu_setup*(3), *coap_resource*(3) and *coap_string*(3) + +FURTHER INFORMATION +------------------- +See "RFC7252: The Constrained Application Protocol (CoAP)" for further +information. + +BUGS +---- +Please report bugs on the mailing list for libcoap: +libcoap-developers@lists.sourceforge.net or raise an issue on GitHub at +https://github.com/obgm/libcoap/issues + +AUTHORS +------- +The libcoap project diff --git a/man/coap_string.txt.in b/man/coap_string.txt.in index 803013a0..525e7d67 100644 --- a/man/coap_string.txt.in +++ b/man/coap_string.txt.in @@ -10,10 +10,20 @@ coap_string(3) NAME ---- -coap_string, coap_new_string, coap_delete_string, coap_new_str_const, -coap_delete_str_const, coap_new_binary, coap_delete_binary, coap_resize_binary, -coap_new_bin_const, coap_delete_bin_const, coap_make_str_const, -coap_string_equal, coap_binary_equal - string functions +coap_string, +coap_new_string, +coap_delete_string, +coap_new_str_const, +coap_delete_str_const, +coap_new_binary, +coap_delete_binary, +coap_resize_binary, +coap_new_bin_const, +coap_delete_bin_const, +coap_make_str_const, +coap_string_equal, +coap_binary_equal +- string functions SYNOPSIS -------- diff --git a/src/coap_cache.c b/src/coap_cache.c index 6f1cc120..2d01f03c 100644 --- a/src/coap_cache.c +++ b/src/coap_cache.c @@ -8,34 +8,90 @@ #include "coap_internal.h" -#include "murmur3.h" - /* Determines if the given option_type denotes an option type that can * be used as CacheKey. Options that can be cache keys are not Unsafe * and not marked explicitly as NoCacheKey. */ static int -is_cache_key(uint16_t option_type) { - const uint16_t unsafe = 0x02; - const uint16_t no_cache_key = 0x04; +is_cache_key(const coap_context_t *ctx, uint16_t option_type) { + int nocachekey = (option_type & 0x1e) == 0x1c; + size_t i; - return (option_type & (unsafe | no_cache_key)) == 0; -} - -coap_cache_key_t -coap_cache_key(const coap_pdu_t *pdu) { - coap_opt_t *option; - coap_opt_iterator_t opt_iter; - murmur3_context_t mctx; - - if (!coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL)) { - return COAP_CACHE_INVALID; + /* + * https://tools.ietf.org/html/rfc7641#section-2 Observe is not a + * part of the cache-key. + */ + if (option_type == COAP_OPTION_OBSERVE) { + nocachekey = 1; } - murmur3_32_init(&mctx); + /* Check for option user has defined as not part of cache-key */ + for (i = 0; i < ctx->cache_ignore_count; i++) { + if (ctx->cache_ignore_options[i] == option_type) { + nocachekey = 1; + break; + } + } + return nocachekey == 0; +} + +int +coap_cache_ignore_options(coap_context_t *ctx, + const uint16_t *options, + size_t count) { + if (ctx->cache_ignore_options) { + coap_free(ctx->cache_ignore_options); + } + if (count) { + assert(options); + ctx->cache_ignore_options = coap_malloc(count * sizeof(options[0])); + if (ctx->cache_ignore_options) { + memcpy(ctx->cache_ignore_options, options, count * sizeof(options[0])); + ctx->cache_ignore_count = count; + } + else { + coap_log(LOG_WARNING, "Unable to create cache_ignore_options\n"); + return 0; + } + } + else { + ctx->cache_ignore_options = NULL; + ctx->cache_ignore_count = count; + } + return 1; +} + +coap_cache_key_t * +coap_cache_derive_key(const coap_session_t *session, + const coap_pdu_t *pdu, + coap_cache_session_based_t session_based) { + coap_opt_t *option; + coap_opt_iterator_t opt_iter; + coap_digest_ctx_t *dctx; + coap_digest_t digest; + coap_cache_key_t *cache_key; + + if (!coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL)) { + return NULL; + } + + dctx = coap_digest_setup(); + if (!dctx) + return NULL; + + if (session_based == COAP_CACHE_IS_SESSION_BASED) { + /* Include the session ptr */ + if (!coap_digest_update(dctx, (const uint8_t*)session, sizeof(session))) { + coap_digest_free(dctx); + return NULL; + } + } while ((option = coap_option_next(&opt_iter))) { - if (is_cache_key(opt_iter.type)) { - murmur3_32_update(&mctx, option, coap_opt_size(option)); + if (is_cache_key(session->context, opt_iter.type)) { + if (!coap_digest_update(dctx, option, coap_opt_size(option))) { + coap_digest_free(dctx); + return NULL; + } } } @@ -45,66 +101,152 @@ coap_cache_key(const coap_pdu_t *pdu) { size_t len; uint8_t *data; if (coap_get_data(pdu, &len, &data)) { - murmur3_32_update(&mctx, option, coap_opt_size(option)); + if (!coap_digest_update(dctx, data, len)) { + coap_digest_free(dctx); + return NULL; + } } } - return murmur3_32_finalize(&mctx); + if (!coap_digest_final(dctx, &digest)) { + /* coap_digest_final() is guaranteed to free off dctx no matter what */ + return NULL; + } + cache_key = coap_malloc_type(COAP_CACHE_KEY, sizeof(coap_cache_key_t)); + if (cache_key) { + memcpy(cache_key->key, digest.key, sizeof(cache_key->key)); + } + return cache_key; } -typedef struct coap_cache_entry_t { - UT_hash_handle hh; - const coap_pdu_t *pdu; - coap_cache_key_t cache_key; -} coap_cache_entry_t; - -/** - * Marks a request for permanent storage. The request may be retrieved - * through its cache-key. - * - * @param ctx The context to use. - * @param request The request to be stored. - * - * @return The cache key that corresponds to the newly stored - * request or @c COAP_CACHE_INVALID if the request could - * not be stored. - */ -coap_cache_key_t -coap_cache_mark_request(coap_context_t *ctx, const coap_pdu_t *request) { - coap_cache_entry_t *entry = coap_malloc(sizeof(coap_cache_entry_t)); - if (!entry) { - return COAP_CACHE_INVALID; - } - - entry->pdu = request; - entry->cache_key = coap_cache_key(request); - HASH_ADD(hh, ctx->cache, cache_key, sizeof(coap_cache_key_t), entry); - return entry->cache_key; +void +coap_delete_cache_key(coap_cache_key_t *cache_key) { + coap_free_type(COAP_CACHE_KEY, cache_key); } coap_cache_entry_t * -coap_cache_lookup_key(coap_context_t *ctx, coap_cache_key_t key) { - coap_cache_entry_t *entry = NULL; - if (key != COAP_CACHE_INVALID) { - HASH_FIND(hh, ctx->cache, &key, sizeof(coap_cache_key_t), entry); +coap_new_cache_entry(coap_session_t *session, const coap_pdu_t *pdu, + coap_cache_record_pdu_t record_pdu, + coap_cache_session_based_t session_based, + unsigned int idle_timeout) { + coap_cache_entry_t *entry = coap_malloc_type(COAP_CACHE_ENTRY, + sizeof(coap_cache_entry_t)); + if (!entry) { + return NULL; } + + memset(entry, 0, sizeof(coap_cache_entry_t)); + if (session_based == COAP_CACHE_IS_SESSION_BASED) { + entry->session = session; + } + if (record_pdu == COAP_CACHE_RECORD_PDU) { + entry->pdu = coap_pdu_init(pdu->type, pdu->code, pdu->tid, pdu->alloc_size); + if (entry->pdu) { + coap_pdu_resize(entry->pdu, pdu->alloc_size); + /* Need to get the appropriate data across */ + memcpy(entry->pdu, pdu, offsetof(coap_pdu_t, token)); + memcpy(entry->pdu->token, pdu->token, pdu->used_size); + /* And adjust all the pointers etc. */ + entry->pdu->data = entry->pdu->token + (pdu->data - pdu->token); + } + } + entry->cache_key = coap_cache_derive_key(session, pdu, session_based); + if (!entry->cache_key) { + coap_free_type(COAP_CACHE_ENTRY, entry); + return NULL; + } + entry->idle_timeout = idle_timeout; + if (idle_timeout > 0) { + coap_ticks(&entry->expire_ticks); + entry->expire_ticks += idle_timeout * COAP_TICKS_PER_SECOND; + } + + HASH_ADD(hh, session->context->cache, cache_key[0], sizeof(coap_cache_key_t), entry); return entry; } coap_cache_entry_t * -coap_cache_lookup_request(coap_context_t *ctx, const coap_pdu_t *request) { - return coap_cache_lookup_key(ctx, coap_cache_key(request)); +coap_cache_get_by_key(coap_context_t *ctx, const coap_cache_key_t *cache_key) { + coap_cache_entry_t *cache_entry = NULL; + + assert(cache_key); + if (cache_key) { + HASH_FIND(hh, ctx->cache, cache_key, sizeof(coap_cache_key_t), cache_entry); + } + if (cache_entry && cache_entry->idle_timeout > 0) { + coap_ticks(&cache_entry->expire_ticks); + cache_entry->expire_ticks += cache_entry->idle_timeout * COAP_TICKS_PER_SECOND; + } + return cache_entry; } -/** - * Clears a mark from a request. - * - * @param ctx The context to use. - * @param cache_key The cache key for the request which can be - * unmarked. - */ -void -coap_cache_unmark_request(coap_context_t *ctx, coap_cache_key_t cache_key) { - (void)ctx; - (void)cache_key; +coap_cache_entry_t * +coap_cache_get_by_pdu(coap_session_t *session, + const coap_pdu_t *request, + coap_cache_session_based_t session_based) { + coap_cache_key_t *cache_key = coap_cache_derive_key(session, request, session_based); + coap_cache_entry_t *cache_entry; + + if (!cache_key) + return NULL; + + cache_entry = coap_cache_get_by_key(session->context, cache_key); + coap_delete_cache_key(cache_key); + if (cache_entry && cache_entry->idle_timeout > 0) { + coap_ticks(&cache_entry->expire_ticks); + cache_entry->expire_ticks += cache_entry->idle_timeout * COAP_TICKS_PER_SECOND; + } + return cache_entry; } + +void +coap_delete_cache_entry(coap_context_t *ctx, coap_cache_entry_t *cache_entry) { + + assert(cache_entry); + + if (cache_entry) { + HASH_DELETE(hh, ctx->cache, cache_entry); + } + if (cache_entry->pdu) { + coap_delete_pdu(cache_entry->pdu); + } + coap_delete_cache_key(cache_entry->cache_key); + if (cache_entry->callback && cache_entry->app_data) { + cache_entry->callback(cache_entry->app_data); + } + coap_free_type(COAP_CACHE_ENTRY, cache_entry); +} + +const coap_pdu_t * +coap_cache_get_pdu(const coap_cache_entry_t *cache_entry) { + return cache_entry->pdu; +} + +void +coap_cache_set_app_data(coap_cache_entry_t *cache_entry, + void *data, + coap_cache_app_data_free_callback_t callback) { + cache_entry->app_data = data; + cache_entry->callback = callback; +} + +void * +coap_cache_get_app_data(const coap_cache_entry_t *cache_entry) { + return cache_entry->app_data; +} + +void +coap_expire_cache_entries(coap_context_t *ctx) { + coap_tick_t now; + coap_cache_entry_t *cp, *ctmp; + + coap_ticks(&now); + HASH_ITER(hh, ctx->cache, cp, ctmp) { + if (cp->idle_timeout > 0) { + if (cp->expire_ticks <= now) { + coap_delete_cache_entry(ctx, cp); + } + } + } +} + diff --git a/src/coap_gnutls.c b/src/coap_gnutls.c index 94b6b408..fbfa9a8c 100644 --- a/src/coap_gnutls.c +++ b/src/coap_gnutls.c @@ -53,6 +53,7 @@ #include #include #include +#include #include #ifdef __GNUC__ @@ -2349,6 +2350,39 @@ ssize_t coap_tls_read(coap_session_t *c_session, } #endif /* !COAP_DISABLE_TCP */ +coap_digest_ctx_t * +coap_digest_setup(void) { + gnutls_hash_hd_t digest_ctx; + + if (gnutls_hash_init(&digest_ctx, GNUTLS_DIG_SHA256)) { + return NULL; + } + return digest_ctx; +} + +void +coap_digest_free(coap_digest_ctx_t *digest_ctx) { + gnutls_hash_deinit(digest_ctx, NULL); +} + +int +coap_digest_update(coap_digest_ctx_t *digest_ctx, + const uint8_t *data, + size_t data_len) { + int ret = gnutls_hash(digest_ctx, data, data_len); + + return ret == 0; +} + +int +coap_digest_final(coap_digest_ctx_t *digest_ctx, + coap_digest_t *digest_buffer) { + gnutls_hash_output(digest_ctx, (uint8_t*)digest_buffer); + + coap_digest_free(digest_ctx); + return 1; +} + #else /* !HAVE_LIBGNUTLS */ #ifdef __clang__ diff --git a/src/coap_io.c b/src/coap_io.c index 229ae36e..58c8759c 100644 --- a/src/coap_io.c +++ b/src/coap_io.c @@ -1397,6 +1397,7 @@ coap_io_process_with_fds(coap_context_t *ctx, uint32_t timeout_ms, /* Keep retrying until less than COAP_MAX_EPOLL_EVENTS are returned */ } while (nfds == COAP_MAX_EPOLL_EVENTS); + coap_expire_cache_entries(ctx); coap_ticks(&now); #endif /* COAP_EPOLL_SUPPORT */ diff --git a/src/coap_mbedtls.c b/src/coap_mbedtls.c index add025ef..d35c4707 100644 --- a/src/coap_mbedtls.c +++ b/src/coap_mbedtls.c @@ -48,6 +48,7 @@ #include #include #include +#include #if defined(ESPIDF_VERSION) && defined(CONFIG_MBEDTLS_DEBUG) #include #endif /* ESPIDF_VERSION && CONFIG_MBEDTLS_DEBUG */ @@ -1837,6 +1838,41 @@ coap_tls_version_t * coap_get_tls_library_version(void) return &version; } +coap_digest_ctx_t * +coap_digest_setup(void) { + mbedtls_sha256_context *digest_ctx = mbedtls_malloc(sizeof(mbedtls_sha256_context)); + + if (digest_ctx) { + mbedtls_sha256_init(digest_ctx); + mbedtls_sha256_starts_ret(digest_ctx, 0); + } + return digest_ctx; +} + +void +coap_digest_free(coap_digest_ctx_t *digest_ctx) { + mbedtls_sha256_free(digest_ctx); + mbedtls_free(digest_ctx); +} + +int +coap_digest_update(coap_digest_ctx_t *digest_ctx, + const uint8_t *data, + size_t data_len) { + int ret = mbedtls_sha256_update_ret(digest_ctx, data, data_len); + + return ret == 0; +} + +int +coap_digest_final(coap_digest_ctx_t *digest_ctx, + coap_digest_t *digest_buffer) { + int ret = mbedtls_sha256_finish_ret(digest_ctx, (uint8_t*)digest_buffer); + + coap_digest_free(digest_ctx); + return ret == 0; +} + #else /* !HAVE_MBEDTLS */ #ifdef __clang__ diff --git a/src/coap_notls.c b/src/coap_notls.c index 3c8eb47e..b8210641 100644 --- a/src/coap_notls.c +++ b/src/coap_notls.c @@ -181,6 +181,51 @@ ssize_t coap_tls_read(coap_session_t *session UNUSED, return -1; } +typedef struct coap_local_hash_t { + size_t ofs; + coap_key_t key[8]; /* 32 bytes in total */ +} coap_local_hash_t; + +coap_digest_ctx_t * +coap_digest_setup(void) { + coap_key_t *digest_ctx = coap_malloc(sizeof(coap_local_hash_t)); + + if (digest_ctx) { + memset(digest_ctx, 0, sizeof(coap_local_hash_t)); + } + + return digest_ctx; +} + +void +coap_digest_free(coap_digest_ctx_t *digest_ctx) { + coap_free(digest_ctx); +} + +int +coap_digest_update(coap_digest_ctx_t *digest_ctx, + const uint8_t *data, + size_t data_len) { + coap_local_hash_t *local = (coap_local_hash_t*)digest_ctx; + + coap_hash(data, data_len, local->key[local->ofs]); + + local->ofs = (local->ofs + 1) % 7; + return 1; +} + +int +coap_digest_final(coap_digest_ctx_t *digest_ctx, + coap_digest_t *digest_buffer) { + coap_local_hash_t *local = (coap_local_hash_t*)digest_ctx; + + memcpy(digest_buffer, local->key, sizeof(coap_digest_t)); + + coap_digest_free(digest_ctx); + return 1; +} + + #undef UNUSED #else /* !HAVE_LIBTINYDTLS && !HAVE_OPENSSL && !HAVE_LIBGNUTLS */ diff --git a/src/coap_openssl.c b/src/coap_openssl.c index 4e5de588..05a83047 100644 --- a/src/coap_openssl.c +++ b/src/coap_openssl.c @@ -3331,6 +3331,37 @@ ssize_t coap_tls_read(coap_session_t *session, } #endif /* !COAP_DISABLE_TCP */ +coap_digest_ctx_t * +coap_digest_setup(void) { + SHA256_CTX *digest_ctx = OPENSSL_malloc(sizeof(SHA256_CTX)); + + if (digest_ctx) { + SHA256_Init(digest_ctx); + } + return digest_ctx; +} + +void +coap_digest_free(coap_digest_ctx_t *digest_ctx) { + OPENSSL_free(digest_ctx); +} + +int +coap_digest_update(coap_digest_ctx_t *digest_ctx, + const uint8_t *data, + size_t data_len) { + return SHA256_Update(digest_ctx, data, data_len); +} + +int +coap_digest_final(coap_digest_ctx_t *digest_ctx, + coap_digest_t *digest_buffer) { + int ret = SHA256_Final((uint8_t*)digest_buffer, digest_ctx); + + coap_digest_free(digest_ctx); + return ret; +} + #else /* !HAVE_OPENSSL */ #ifdef __clang__ diff --git a/src/coap_session.c b/src/coap_session.c index a5bfcf7d..27b85447 100644 --- a/src/coap_session.c +++ b/src/coap_session.c @@ -155,6 +155,7 @@ coap_make_session(coap_proto_t proto, coap_session_type_t type, void coap_session_mfree(coap_session_t *session) { coap_queue_t *q, *tmp; + coap_cache_entry_t *cp, *ctmp; if (session->partial_pdu) coap_delete_pdu(session->partial_pdu); @@ -173,6 +174,12 @@ void coap_session_mfree(coap_session_t *session) { if (session->psk_hint) coap_free(session->psk_hint); + HASH_ITER(hh, session->context->cache, cp, ctmp) { + /* cp->session is NULL if not session based */ + if (cp->session == session) { + coap_delete_cache_entry(session->context, cp); + } + } LL_FOREACH_SAFE(session->delayqueue, q, tmp) { if (q->pdu->type==COAP_MESSAGE_CON && session->context && session->context->nack_handler) session->context->nack_handler(session->context, session, q->pdu, session->proto == COAP_PROTO_DTLS ? COAP_NACK_TLS_FAILED : COAP_NACK_NOT_DELIVERABLE, q->id); diff --git a/src/coap_tinydtls.c b/src/coap_tinydtls.c index a66da60a..0558d709 100644 --- a/src/coap_tinydtls.c +++ b/src/coap_tinydtls.c @@ -636,6 +636,40 @@ ssize_t coap_tls_read(coap_session_t *session UNUSED, } #endif /* !COAP_DISABLE_TCP */ +coap_digest_ctx_t * +coap_digest_setup(void) { + dtls_sha256_ctx *digest_ctx = coap_malloc(sizeof(dtls_sha256_ctx)); + + if (digest_ctx) { + dtls_sha256_init(digest_ctx); + } + + return digest_ctx; +} + +void +coap_digest_free(coap_digest_ctx_t *digest_ctx) { + coap_free(digest_ctx); +} + +int +coap_digest_update(coap_digest_ctx_t *digest_ctx, + const uint8_t *data, + size_t data_len) { + dtls_sha256_update(digest_ctx, data, data_len); + + return 1; +} + +int +coap_digest_final(coap_digest_ctx_t *digest_ctx, + coap_digest_t *digest_buffer) { + dtls_sha256_final((uint8_t*)digest_buffer, digest_ctx); + + coap_digest_free(digest_ctx); + return 1; +} + #undef UNUSED #else /* !HAVE_LIBTINYDTLS */ diff --git a/src/net.c b/src/net.c index 061c7569..59f731f4 100644 --- a/src/net.c +++ b/src/net.c @@ -583,6 +583,7 @@ void coap_free_context(coap_context_t *context) { coap_endpoint_t *ep, *tmp; coap_session_t *sp, *rtmp; + coap_cache_entry_t *cp, *ctmp; if (!context) return; @@ -599,6 +600,12 @@ coap_free_context(coap_context_t *context) { #ifndef WITHOUT_ASYNC coap_delete_all_async(context); #endif /* WITHOUT_ASYNC */ + HASH_ITER(hh, context->cache, cp, ctmp) { + coap_delete_cache_entry(context, cp); + } + if (context->cache_ignore_count) { + coap_free(context->cache_ignore_options); + } LL_FOREACH_SAFE(context->endpoint, ep, tmp) { coap_free_endpoint(ep); @@ -610,7 +617,6 @@ coap_free_context(coap_context_t *context) { if (context->dtls_context) coap_dtls_free_context(context->dtls_context); - #ifdef COAP_EPOLL_SUPPORT if (context->eptimerfd != -1) { int ret; diff --git a/win32/libcoap.vcxproj b/win32/libcoap.vcxproj index 63c8300c..a2e50413 100644 --- a/win32/libcoap.vcxproj +++ b/win32/libcoap.vcxproj @@ -38,6 +38,7 @@ + @@ -67,6 +68,8 @@ + + diff --git a/win32/libcoap.vcxproj.filters b/win32/libcoap.vcxproj.filters index 1fdcd196..44ac1d18 100644 --- a/win32/libcoap.vcxproj.filters +++ b/win32/libcoap.vcxproj.filters @@ -24,6 +24,9 @@ Source Files + + Source Files + Source Files @@ -107,6 +110,12 @@ Header Files + + Header Files + + + Header Files + Header Files