From 469357b8244e6a8204fb285406ab0c42a0874a2a Mon Sep 17 00:00:00 2001 From: Jon Shallow Date: Fri, 24 Aug 2018 16:36:39 +0100 Subject: [PATCH] BLOCK option support in coap-server hashkey.[ch] files restored (now prefixed with coap_) LWIP and Contiki builds now include these files block.[ch]: New function coap_add_data_blocked_response() to simplify GET responses and handle adding in BLOCK2 options as appropriate. Needs coap_hash() to generate ETag option. net.c: Determine if Block2 is in use, and add to coap_add_observer(). resource.[ch]: Include Block2 request in coap_add_observer(). subscribe.h: Include Block2 definition in coap_subscriber_t for using during observe responses. pdu.h: Update comment. coap-client.c: No longer causes duplicate calls to coap_show_pdu() (one in library, one in coap-client for the same PDU). If a block'ed response received and observing, now observing continues. (Fixes #166). Send Observe Cancel with Block2 option if -b defined coap-server.c: Replaced all option setting, data addition etc. with new coap_add_data_blocked_response() function in the GET handlers. (Fixes #246 Issue 2). Support PUT with BLOCK1. (Fixes #246 Issue 1). Add in -N option to send observe responses as non-confirmable. Handle small wait_ms values correctly (after being decremented) for testing whether observe should be triggered or not. Refresh time every second by making COAP_RESOURCE_CHECK_TIME 1 Manuals: Add in new function coap_add_data_blocked_response() Update coap_observe with coap_delete_observer(s) functions Correct example typo and use new function in hnd_get_time(). Add in -N option to coap-server(5) Be more specific about COAP_RESOURCE_FLAGS_NOTIFY_NON and COAP_RESOURCE_FLAGS_NOTIFY_CON usage for observe. Files: Makefile.am Makefile.libcoap examples/client.c examples/coap-server.c examples/lwip/Makefile include/coap/block.h include/coap/coap_hashkey.h include/coap/pdu.h include/coap/resource.h include/coap/subscribe.h libcoap-2.map libcoap-2.sym man/Makefile.am man/coap-server.txt.in man/coap_handler.txt.in man/coap_observe.txt.in man/coap_pdu_setup.txt.in man/coap_resource.txt.in src/block.c src/coap_hashkey.c src/net.c src/resource.c --- Makefile.am | 2 + Makefile.libcoap | 2 +- examples/client.c | 28 ++++- examples/coap-server.c | 231 ++++++++++++++++++++++++------------ examples/lwip/Makefile | 2 +- include/coap/block.h | 34 ++++++ include/coap/coap_hashkey.h | 59 +++++++++ include/coap/pdu.h | 5 +- include/coap/resource.h | 6 +- include/coap/subscribe.h | 3 + libcoap-2.map | 2 + libcoap-2.sym | 2 + man/Makefile.am | 1 + man/coap-server.txt.in | 8 +- man/coap_handler.txt.in | 57 +++++---- man/coap_observe.txt.in | 128 ++++++++++++++------ man/coap_pdu_setup.txt.in | 74 ++++++------ man/coap_resource.txt.in | 14 ++- src/block.c | 144 ++++++++++++++++++++-- src/coap_hashkey.c | 26 ++++ src/net.c | 10 +- src/resource.c | 20 +++- 22 files changed, 656 insertions(+), 202 deletions(-) create mode 100644 include/coap/coap_hashkey.h create mode 100644 src/coap_hashkey.c diff --git a/Makefile.am b/Makefile.am index e735b7c0..9315de91 100644 --- a/Makefile.am +++ b/Makefile.am @@ -70,6 +70,7 @@ libcoap_@LIBCOAP_NAME_SUFFIX@_la_SOURCES = \ src/async.c \ src/block.c \ src/coap_event.c \ + src/coap_hashkey.c \ src/coap_io.c \ src/coap_notls.c \ src/coap_openssl.c \ @@ -100,6 +101,7 @@ libcoap_include_HEADERS = \ $(top_builddir)/include/coap/coap.h \ $(top_srcdir)/include/coap/coap_dtls.h \ $(top_srcdir)/include/coap/coap_event.h \ + $(top_srcdir)/include/coap/coap_hashkey.h \ $(top_srcdir)/include/coap/coap_io.h \ $(top_srcdir)/include/coap/coap_session.h \ $(top_srcdir)/include/coap/coap_time.h \ diff --git a/Makefile.libcoap b/Makefile.libcoap index c1e8191f..00e6929f 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 str.c option.c async.c block.c mem.c coap_io.c coap_session.c coap_notls.c +libcoap_src = pdu.c net.c 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 libcoap_dir := $(filter %libcoap,$(APPDS)) vpath %c $(libcoap_dir)/src diff --git a/examples/client.c b/examples/client.c index 9f842660..c2311298 100644 --- a/examples/client.c +++ b/examples/client.c @@ -217,7 +217,18 @@ clear_obs(coap_context_t *ctx, coap_session_t *session) { } } - coap_show_pdu(LOG_INFO, pdu); + if (flags & FLAGS_BLOCK) { + block.num = 0; + block.m = 0; + coap_add_option(pdu, + COAP_OPTION_BLOCK2, + coap_encode_var_safe(buf, sizeof(buf), (block.num << 4 | block.m << 3 | block.szx)), + buf); + } + + if (coap_get_log_level() < LOG_DEBUG) + coap_show_pdu(LOG_INFO, pdu); + tid = coap_send(session, pdu); @@ -304,7 +315,8 @@ message_handler(struct coap_context_t *ctx, #ifndef NDEBUG coap_log(LOG_DEBUG, "** process incoming %d.%02d response:\n", (received->code >> 5), received->code & 0x1F); - coap_show_pdu(LOG_INFO, received); + if (coap_get_log_level() < LOG_DEBUG) + coap_show_pdu(LOG_INFO, received); #endif /* check if this is a response to our original request */ @@ -344,6 +356,11 @@ message_handler(struct coap_context_t *ctx, if (coap_get_data(received, &len, &databuf)) append_to_output(databuf, len); + if (coap_opt_block_num(block_opt) == 0) { + /* See if observe is set in first response */ + ready = coap_check_option(received, + COAP_OPTION_OBSERVE, &opt_iter) == NULL; + } if(COAP_OPT_BLOCK_MORE(block_opt)) { /* more bit is set */ coap_log(LOG_DEBUG, "found the M bit, block size is %u, block nr. %u\n", @@ -390,6 +407,7 @@ message_handler(struct coap_context_t *ctx, return; } } + return; } else { /* no Block2 option */ block_opt = coap_check_option(received, COAP_OPTION_BLOCK1, &opt_iter); @@ -459,7 +477,8 @@ message_handler(struct coap_context_t *ctx, payload.s, block.num, block.szx); - coap_show_pdu(LOG_WARNING, pdu); + if (coap_get_log_level() < LOG_DEBUG) + coap_show_pdu(LOG_INFO, pdu); tid = coap_send(session, pdu); @@ -1358,7 +1377,8 @@ main(int argc, char **argv) { #ifndef NDEBUG coap_log(LOG_DEBUG, "sending CoAP request:\n"); - coap_show_pdu(LOG_INFO, pdu); + if (coap_get_log_level() < LOG_DEBUG) + coap_show_pdu(LOG_INFO, pdu); #endif coap_send(session, pdu); diff --git a/examples/coap-server.c b/examples/coap-server.c index d58f6347..9d86e0a3 100644 --- a/examples/coap-server.c +++ b/examples/coap-server.c @@ -33,9 +33,10 @@ #include #endif -#include +/* Need to refresh time once per sec */ +#define COAP_RESOURCE_CHECK_TIME 1 -#define COAP_RESOURCE_CHECK_TIME 2 +#include #ifndef min #define min(a,b) ((a) < (b) ? (a) : (b)) @@ -50,6 +51,8 @@ static time_t my_clock_base = 0; struct coap_resource_t *time_resource = NULL; +static int resource_flags = COAP_RESOURCE_FLAGS_NOTIFY_CON; + static char *cert_file = NULL; /* Combined certificate and private key in PEM */ static char *ca_file = NULL; /* CA for cert_file - for cert checking in PEM */ static char *root_ca_file = NULL; /* List of trusted Root CAs in PEM */ @@ -83,27 +86,17 @@ handle_sigint(int signum UNUSED_PARAM) { static void hnd_get_index(coap_context_t *ctx UNUSED_PARAM, - struct coap_resource_t *resource UNUSED_PARAM, - coap_session_t *session UNUSED_PARAM, - coap_pdu_t *request UNUSED_PARAM, - coap_binary_t *token UNUSED_PARAM, + struct 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) { - unsigned char buf[3]; - response->code = COAP_RESPONSE_CODE(205); - - coap_add_option(response, - COAP_OPTION_CONTENT_TYPE, - coap_encode_var_safe(buf, sizeof(buf), - COAP_MEDIATYPE_TEXT_PLAIN), - buf); - - coap_add_option(response, - COAP_OPTION_MAXAGE, - coap_encode_var_safe(buf, sizeof(buf), 0x2ffff), buf); - - coap_add_data(response, strlen(INDEX), (const uint8_t *)INDEX); + coap_add_data_blocked_response(resource, session, request, response, token, + COAP_MEDIATYPE_TEXT_PLAIN, 0x2ffff, + strlen(INDEX), + (const uint8_t *)INDEX); } static void @@ -123,28 +116,6 @@ hnd_get_time(coap_context_t *ctx UNUSED_PARAM, /* FIXME: return time, e.g. in human-readable by default and ticks * when query ?ticks is given. */ - /* if my_clock_base was deleted, we pretend to have no such resource */ - response->code = - my_clock_base ? COAP_RESPONSE_CODE(205) : COAP_RESPONSE_CODE(404); - - if (coap_find_observer(resource, session, token)) { - coap_add_option(response, - COAP_OPTION_OBSERVE, - coap_encode_var_safe(buf, sizeof(buf), resource->observe), - buf); - } - - if (my_clock_base) - coap_add_option(response, - COAP_OPTION_CONTENT_FORMAT, - coap_encode_var_safe(buf, sizeof(buf), - COAP_MEDIATYPE_TEXT_PLAIN), - buf); - - coap_add_option(response, - COAP_OPTION_MAXAGE, - coap_encode_var_safe(buf, sizeof(buf), 0x01), buf); - if (my_clock_base) { /* calculate current time */ @@ -155,7 +126,6 @@ hnd_get_time(coap_context_t *ctx UNUSED_PARAM, && coap_string_equal(query, coap_make_str_const("ticks"))) { /* output ticks */ len = snprintf((char *)buf, sizeof(buf), "%u", (unsigned int)now); - coap_add_data(response, len, buf); } else { /* output human-readable time */ struct tm *tmp; @@ -163,12 +133,20 @@ hnd_get_time(coap_context_t *ctx UNUSED_PARAM, if (!tmp) { /* If 'now' is not valid */ response->code = COAP_RESPONSE_CODE(404); + return; } else { len = strftime((char *)buf, sizeof(buf), "%b %d %H:%M:%S", tmp); - coap_add_data(response, len, buf); } } + coap_add_data_blocked_response(resource, session, request, response, token, + COAP_MEDIATYPE_TEXT_PLAIN, 1, + len, + buf); + } + else { + /* if my_clock_base was deleted, we pretend to have no such resource */ + response->code = COAP_RESPONSE_CODE(404); } } @@ -310,13 +288,16 @@ check_async(coap_context_t *ctx, } #endif /* WITHOUT_ASYNC */ -typedef struct dynamic_resource { +typedef struct dynamic_resource_t { coap_string_t *uri_path; coap_string_t *value; -} dynamic_resource; + coap_resource_t *resource; + int created; + uint16_t media_type; +} dynamic_resource_t; static int dynamic_count = 0; -static dynamic_resource *dynamic_entry = NULL; +static dynamic_resource_t *dynamic_entry = NULL; /* * Regular DELETE handler - used by resources created by the @@ -371,14 +352,14 @@ static void hnd_get(coap_context_t *ctx UNUSED_PARAM, coap_resource_t *resource, coap_session_t *session, - coap_pdu_t *request UNUSED_PARAM, + coap_pdu_t *request, coap_binary_t *token, coap_string_t *query UNUSED_PARAM, coap_pdu_t *response ) { coap_str_const_t *uri_path; - uint8_t buf[4]; int i; + dynamic_resource_t *resource_entry = NULL; /* * request will be NULL if an Observe triggered request, so the uri_path, @@ -402,13 +383,13 @@ hnd_get(coap_context_t *ctx UNUSED_PARAM, return; } - if (coap_find_observer(resource, session, token)) { - coap_add_option(response, COAP_OPTION_OBSERVE, coap_encode_var_safe(buf, sizeof (buf), resource->observe), buf); - } - if (dynamic_entry[i].value) { - coap_add_data (response, dynamic_entry[i].value->length, dynamic_entry[i].value->s); - } - response->code = COAP_RESPONSE_CODE (205); + resource_entry = &dynamic_entry[i]; + + coap_add_data_blocked_response(resource, session, request, response, token, + resource_entry->media_type, -1, + resource_entry->value->length, + resource_entry->value->s); + return; } /* @@ -418,7 +399,7 @@ hnd_get(coap_context_t *ctx UNUSED_PARAM, static void hnd_put(coap_context_t *ctx UNUSED_PARAM, - coap_resource_t *resource UNUSED_PARAM, + coap_resource_t *resource, coap_session_t *session UNUSED_PARAM, coap_pdu_t *request, coap_binary_t *token UNUSED_PARAM, @@ -429,6 +410,11 @@ hnd_put(coap_context_t *ctx UNUSED_PARAM, int i; size_t size; uint8_t *data; + coap_block_t block1; + dynamic_resource_t *resource_entry = NULL; + unsigned char buf[4]; + coap_opt_iterator_t opt_iter; + coap_opt_t *option; /* get the uri_path */ uri_path = coap_get_uri_path(request); @@ -437,6 +423,9 @@ hnd_put(coap_context_t *ctx UNUSED_PARAM, return; } + /* + * Locate the correct dynamic block for this request + */ for (i = 0; i < dynamic_count; i++) { if (coap_string_equal(uri_path, dynamic_entry[i].uri_path)) { break; @@ -444,6 +433,7 @@ hnd_put(coap_context_t *ctx UNUSED_PARAM, } if (i == dynamic_count) { if (dynamic_count >= support_dynamic) { + /* Should have been caught in hnd_unknown_put() */ response->code = COAP_RESPONSE_CODE(406); return; } @@ -452,7 +442,17 @@ hnd_put(coap_context_t *ctx UNUSED_PARAM, 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) { + dynamic_entry[i].media_type = + coap_decode_var_bytes (coap_opt_value (option), coap_opt_length (option)); + } + else { + dynamic_entry[i].media_type = COAP_MEDIATYPE_TEXT_PLAIN; + } + } else { dynamic_count--; @@ -463,17 +463,69 @@ 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; } - if (dynamic_entry[i].value) { - coap_delete_string(dynamic_entry[i].value); - dynamic_entry[i].value = NULL; - } + resource_entry = &dynamic_entry[i]; - if (coap_get_data(request, &size, &data) && (size > 0)) { - dynamic_entry[i].value = coap_new_string(size); - memcpy (dynamic_entry[i].value->s, data, size); - dynamic_entry[i].value->length = size; + 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; + } + } + else if (offset != + (resource_entry->value ? resource_entry->value->length : 0)) { + /* Upload is not sequential */ + response->code = COAP_RESPONSE_CODE(408); + return; + } + 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); + } + } + if (block1.m) { + response->code = COAP_RESPONSE_CODE(231); + } + else if (resource_entry->created) { + response->code = COAP_RESPONSE_CODE(201); + } + 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 (resource_entry->value) { + coap_delete_string(resource_entry->value); + resource_entry->value = NULL; + } + resource_entry->value = coap_new_string(size); + memcpy (resource_entry->value->s, data, size); + resource_entry->value->length = size; + } + else { + /* Not a BLOCK1 and no data */ + if (resource_entry->value) { + coap_delete_string(resource_entry->value); + resource_entry->value = NULL; + } } } @@ -483,7 +535,7 @@ hnd_put(coap_context_t *ctx UNUSED_PARAM, static void hnd_unknown_put(coap_context_t *ctx, - coap_resource_t *resource, + coap_resource_t *resource UNUSED_PARAM, coap_session_t *session, coap_pdu_t *request, coap_binary_t *token, @@ -500,12 +552,17 @@ hnd_unknown_put(coap_context_t *ctx, return; } + if (dynamic_count >= support_dynamic) { + response->code = COAP_RESPONSE_CODE(406); + return; + } + /* * Create a resource to handle the new URI * uri_path will get deleted when the resource is removed */ r = coap_resource_init((coap_str_const_t*)uri_path, - COAP_RESOURCE_FLAGS_RELEASE_URI | COAP_RESOURCE_FLAGS_NOTIFY_NON); + COAP_RESOURCE_FLAGS_RELEASE_URI | resource_flags); coap_add_attr(r, coap_make_str_const("title"), coap_make_str_const("\"Dynamic\""), 0); coap_register_handler(r, COAP_REQUEST_PUT, hnd_put); coap_register_handler(r, COAP_REQUEST_DELETE, hnd_delete); @@ -515,7 +572,7 @@ hnd_unknown_put(coap_context_t *ctx, coap_add_resource(ctx, r); /* Do the PUT for this first call */ - hnd_put(ctx, resource, session, request, token, query, response); + hnd_put(ctx, r, session, request, token, query, response); return; } @@ -534,7 +591,7 @@ init_resources(coap_context_t *ctx) { /* store clock base to use in /time */ my_clock_base = clock_offset; - r = coap_resource_init(coap_make_str_const("time"), COAP_RESOURCE_FLAGS_NOTIFY_CON); + r = coap_resource_init(coap_make_str_const("time"), resource_flags); coap_register_handler(r, COAP_REQUEST_GET, hnd_get_time); coap_register_handler(r, COAP_REQUEST_PUT, hnd_put_time); coap_register_handler(r, COAP_REQUEST_DELETE, hnd_delete_time); @@ -639,7 +696,8 @@ usage( const char *program, const char *version) { fprintf( stderr, "%s v%s -- a small CoAP implementation\n" "(c) 2010,2011,2015 Olaf Bergmann \n\n" "Usage: %s [-A address] [-g group] [-p port] [-l loss] [-c certfile]\n" - "\t\t[-C cafile] [-R root_cafile] [-k key] [-h hint] [-v num] [-d max]\n\n" + "\t\t[-C cafile] [-R root_cafile] [-k key] [-h hint] [-N]\n" + "\t\t[-v num] [-d max]\n\n" "\t-A address\tInterface address to bind to\n" "\t-g group\tJoin the given multicast group\n" "\t-p port\t\tListen on specified port\n" @@ -665,6 +723,9 @@ usage( const char *program, const char *version) { "\t \t\tto be available. This cannot be empty if defined.\n" "\t \t\tNote that both -c and -k need to be defined\n" "\t \t\tfor both PSK and PKI to be concurrently supported\n" + "\t-N \t\tMake \"observe\" responses NON-confirmable. Even if set\n" + "\t \t\tevery fifth response will still be sent as a confirmable\n" + "\t \t\tresponse (RFC 7641 requirement)\n" "\t-l list\t\tFail to send some datagrams specified by a comma separated\n" "\t \t\tlist of numbers or number ranges (for debugging only)\n" "\t-l loss%%\tRandomly fail to send datagrams with the specified\n" @@ -844,7 +905,7 @@ main(int argc, char **argv) { clock_offset = time(NULL); - while ((opt = getopt(argc, argv, "A:d:c:C:g:h:k:l:p:R:v:")) != -1) { + while ((opt = getopt(argc, argv, "A:d:c:C:g:h:k:l:Np:R:v:")) != -1) { switch (opt) { case 'A' : strncpy(addr_str, optarg, NI_MAXHOST-1); @@ -883,6 +944,9 @@ main(int argc, char **argv) { exit(1); } break; + case 'N': + resource_flags = COAP_RESOURCE_FLAGS_NOTIFY_NON; + break; case 'p' : strncpy(port_str, optarg, NI_MAXSERV-1); port_str[NI_MAXSERV - 1] = '\0'; @@ -921,15 +985,32 @@ main(int argc, char **argv) { int result = coap_run_once( ctx, wait_ms ); if ( result < 0 ) { break; - } else if ( (unsigned)result < wait_ms ) { + } else if ( result && (unsigned)result < wait_ms ) { + /* decrement if there is a result wait time returned */ wait_ms -= result; } else { + /* + * result == 0, or result >= wait_ms + * (wait_ms could have decremented to a small value, below + * the granularity of the timer in coap_run_once() and hence + * result == 0) + */ time_t t_now = time(NULL); - if (time_resource && (t_last != t_now)) { + if (t_last != t_now) { + /* Happens once per second */ + int i; t_last = t_now; - coap_resource_notify_observers(time_resource, NULL); + if (time_resource) { + coap_resource_notify_observers(time_resource, NULL); + } + for (i = 0; i < dynamic_count; i++) { + coap_resource_notify_observers(dynamic_entry[i].resource, NULL); + } + } + if (result) { + /* result must have been >= wait_ms, so reset wait_ms */ + wait_ms = COAP_RESOURCE_CHECK_TIME * 1000; } - wait_ms = COAP_RESOURCE_CHECK_TIME * 1000; } #ifndef WITHOUT_ASYNC diff --git a/examples/lwip/Makefile b/examples/lwip/Makefile index 54faa142..39abb0de 100644 --- a/examples/lwip/Makefile +++ b/examples/lwip/Makefile @@ -39,7 +39,7 @@ CFLAGS += -I$(top_srcdir)/include/coap vpath %.c $(top_srcdir)/src -COAPOBJS = net.o 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 +COAPOBJS = net.o 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 CFLAGS += -g3 -Wall -Wextra -pedantic -O0 -fpack-struct # not sorted out yet diff --git a/include/coap/block.h b/include/coap/block.h index c8d82dd9..4c4bcde2 100644 --- a/include/coap/block.h +++ b/include/coap/block.h @@ -14,8 +14,12 @@ #include "option.h" #include "pdu.h" +struct coap_resource_t; +struct coap_session_t; + /** * @defgroup block Block Transfer + * API functions for handling PDUs using CoAP BLOCK options * @{ */ @@ -133,6 +137,36 @@ int coap_add_block(coap_pdu_t *pdu, const uint8_t *data, unsigned int block_num, unsigned char block_szx); + +/** + * Adds the @p data to the @p response pdu. If blocks are + * required, then the appropriate block will be added and + * consequently sent. + * Used by a GET request handler. + * + * @param resource The resource the data is associated with. + * @param session The coap session. + * @param request The requesting pdu. + * @param response The response pdu. + * @param token The token taken from the (original) requesting pdu. + * @param media_type The format of the data. + * @param maxage The maxmimum life of the data. If @c -1, then there + * is no maxage. + * @param length The total length of the data. + * @param data The data to transmit. + * + */ +void +coap_add_data_blocked_response(struct coap_resource_t *resource, + struct coap_session_t *session, + coap_pdu_t *request, + coap_pdu_t *response, + const coap_binary_t *token, + uint16_t media_type, + int maxage, + size_t length, + const uint8_t* data); + /**@}*/ #endif /* _COAP_BLOCK_H_ */ diff --git a/include/coap/coap_hashkey.h b/include/coap/coap_hashkey.h new file mode 100644 index 00000000..9466a575 --- /dev/null +++ b/include/coap/coap_hashkey.h @@ -0,0 +1,59 @@ +/* + * coap_hashkey.h -- definition of hash key type and helper functions + * + * Copyright (C) 2010-2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see README for terms + * of use. + */ + +/** + * @file coap_hashkey.h + * @brief definition of hash key type and helper functions + */ + +#ifndef _COAP_HASHKEY_H_ +#define _COAP_HASHKEY_H_ + +#include "libcoap.h" +#include "uthash.h" +#include "str.h" + +typedef unsigned char coap_key_t[4]; + +#ifndef coap_hash +/** + * Calculates a fast hash over the given string @p s of length @p len and stores + * the result into @p h. Depending on the exact implementation, this function + * cannot be used as one-way function to check message integrity or simlar. + * + * @param s The string used for hash calculation. + * @param len The length of @p s. + * @param h The result buffer to store the calculated hash key. + */ +void coap_hash_impl(const unsigned char *s, unsigned int len, coap_key_t h); + +#define coap_hash(String,Length,Result) \ + coap_hash_impl((String),(Length),(Result)) + +/* This is used to control the pre-set hash-keys for resources. */ +#define __COAP_DEFAULT_HASH +#else +#undef __COAP_DEFAULT_HASH +#endif /* coap_hash */ + +/** + * Calls coap_hash() with given @c str object as parameter. + * + * @param Str Must contain a pointer to a coap string object. + * @param H A coap_key_t object to store the result. + * + * @hideinitializer + */ +#define coap_str_hash(Str,H) { \ + assert(Str); \ + memset((H), 0, sizeof(coap_key_t)); \ + coap_hash((Str)->s, (Str)->length, (H)); \ + } + +#endif /* _COAP_HASHKEY_H_ */ diff --git a/include/coap/pdu.h b/include/coap/pdu.h index a581abb5..771a766a 100644 --- a/include/coap/pdu.h +++ b/include/coap/pdu.h @@ -84,7 +84,10 @@ struct coap_session_t; #define COAP_REQUEST_PATCH 6 /* RFC 8132 */ #define COAP_REQUEST_IPATCH 7 /* RFC 8132 */ -/* CoAP option types (be sure to update check_critical when adding options */ +/* + * CoAP option types (be sure to update coap_option_check_critical() when + * adding options + */ #define COAP_OPTION_IF_MATCH 1 /* C, opaque, 0-8 B, (none) */ #define COAP_OPTION_URI_HOST 3 /* C, String, 1-255 B, destination address */ diff --git a/include/coap/resource.h b/include/coap/resource.h index d58cf6c1..96906348 100644 --- a/include/coap/resource.h +++ b/include/coap/resource.h @@ -368,13 +368,17 @@ coap_resource_t *coap_get_resource_from_uri_path(coap_context_t *context, * @param token The token that identifies this subscription. * @param query The query string, if any. subscription will take ownership of the string. + * @param has_block2 If Option Block2 defined. + * @param block2 Contents of Block2 if Block 2 defined. * @return A pointer to the added/updated subscription * information or @c NULL on error. */ coap_subscription_t *coap_add_observer(coap_resource_t *resource, coap_session_t *session, const coap_binary_t *token, - coap_string_t *query); + coap_string_t *query, + int has_block2, + coap_block_t block2); /** * Returns a subscription object for given @p peer. diff --git a/include/coap/subscribe.h b/include/coap/subscribe.h index 321b73ed..75891739 100644 --- a/include/coap/subscribe.h +++ b/include/coap/subscribe.h @@ -14,6 +14,7 @@ #include "address.h" #include "coap_io.h" +#include "block.h" /** * @defgroup observe Resource observation @@ -61,6 +62,8 @@ typedef struct coap_subscription_t { unsigned int dirty:1; /**< set if the notification temporarily could not be * sent (in that case, the resource's partially * dirty flag is set too) */ + unsigned int has_block2:1; /**< GET request had Block2 definition */ + coap_block_t block2; /**< GET request Block2 definition */ size_t token_length; /**< actual length of token */ unsigned char token[8]; /**< token used for subscription */ coap_string_t *query; /**< query string used for subscription, if any */ diff --git a/libcoap-2.map b/libcoap-2.map index e2037eec..3ce7adb3 100644 --- a/libcoap-2.map +++ b/libcoap-2.map @@ -4,6 +4,7 @@ global: coap_add_block; coap_add_data; coap_add_data_after; + coap_add_data_blocked_response; coap_add_observer; coap_add_option; coap_add_option_later; @@ -69,6 +70,7 @@ global: coap_handle_dgram; coap_handle_event; coap_handle_failed_notify; + coap_hash_impl; coap_insert_node; coap_insert_optlist; coap_is_mcast; diff --git a/libcoap-2.sym b/libcoap-2.sym index 08182336..15918eda 100644 --- a/libcoap-2.sym +++ b/libcoap-2.sym @@ -2,6 +2,7 @@ coap_add_attr coap_add_block coap_add_data coap_add_data_after +coap_add_data_blocked_response coap_add_observer coap_add_option coap_add_option_later @@ -67,6 +68,7 @@ coap_get_uri_path coap_handle_dgram coap_handle_event coap_handle_failed_notify +coap_hash_impl coap_insert_node coap_insert_optlist coap_is_mcast diff --git a/man/Makefile.am b/man/Makefile.am index 4c3e438f..f4695434 100644 --- a/man/Makefile.am +++ b/man/Makefile.am @@ -55,6 +55,7 @@ man7_MANS = $(MAN7) # We are limited to 10 names, but synopsis can cover more install-man: install-man3 install-man5 install-man7 @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_bytes.3 @echo ".so man3/coap_pdu_setup.3" > coap_split_path.3 @echo ".so man3/coap_pdu_setup.3" > coap_split_query.3 diff --git a/man/coap-server.txt.in b/man/coap-server.txt.in index 8ec60ad5..edf8ba11 100644 --- a/man/coap-server.txt.in +++ b/man/coap-server.txt.in @@ -16,7 +16,7 @@ SYNOPSIS -------- *coap-server* [*-A* addr] [*-g* group] [*-p* port] [*-l* loss] [*-k* key] [*-h* hint] [*-c* certfile] [*-C* cafile] - [*-R* root_cafile] [*-v* num] [-d max] + [*-R* root_cafile] [-N] [*-v* num] [-d max] DESCRIPTION ----------- @@ -67,6 +67,12 @@ OPTIONS Pre-shared key hint to use for inbound connections. The default is 'CoAP'. This cannot be empty if defined. +*-N* :: + Send NON-confirmable message for \"observe\" responses. If option *-N* is + not specified, a confirmable response will be sent. Even if set, every + fifth response will still be sent as a confirmable response + (RFC 7641 requirement). + *-l* list:: Fail to send some datagrams specified by a comma separated list of numbers or number ranges (debugging only). diff --git a/man/coap_handler.txt.in b/man/coap_handler.txt.in index 2b945631..d2e57d29 100644 --- a/man/coap_handler.txt.in +++ b/man/coap_handler.txt.in @@ -168,51 +168,56 @@ EXAMPLES #include void -hnd_get_time(coap_context_t *ctx, coap_resource_t *resource, -coap_session_t *session, coap_pdu_t *request, coap_string_t *token, +hnd_get_time(coap_context_t *context, coap_resource_t *resource, +coap_session_t *session, coap_pdu_t *request, coap_string_t *token, coap_string_t *query, coap_pdu_t *response) { unsigned char buf[40]; size_t len; time_t now; - coap_tick_t t; - /* Define what the response ode is going to be */ - response->code = COAP_RESPONSE_CODE(205); + /* ... Additional analysis code for resource, request pdu etc. ... */ - /* If the resource is being Observed, return with Observe set */ - if (coap_find_observer(resource, session, token)) { - coap_add_option(response, - COAP_OPTION_OBSERVE, - coap_encode_var_safe(buf, sizeof(buf), resource->observe), - buf); - } + /* After analysis, generate a suitable response */ - /* Response is in plain text format */ - coap_add_option(response, - COAP_OPTION_CONTENT_FORMAT, - coap_encode_var_safe(buf, sizeof (buf), - COAP_MEDIATYPE_TEXT_PLAIN), - buf); - - /* Report on how long this response is valid for */ - coap_add_option(response, - COAP_OPTION_MAXAGE, - coap_encode_var_safe(buf, sizeof(buf), 0x01), buf); + /* Note that token, if set, is already in the response pdu */ now = time(NULL); if (query != NULL && coap_string_equal(query, coap_make_str_const("secs"))) { /* Output secs since Jan 1 1970 */ len = snprintf((char *)buf, sizeof(buf), "%lu", now); - coap_add_data(response, len, buf); - } else { + } + else { /* Output human-readable time */ struct tm *tmp; tmp = gmtime(&now); + if (!tmp) { + /* If 'now' is not valid */ + response->code = COAP_RESPONSE_CODE(404); + return; + } len = strftime((char *)buf, sizeof(buf), "%b %d %H:%M:%S", tmp); - coap_add_data(response, len, buf); } + /* + * Invoke coap_add_data_blocked_response() to do all the hard work. + * + * Define the format - COAP_MEDIATYPE_TEXT_PLAIN - to add in + * Define how long this response is valid for (secs) - 1 - to add in. + * + * OBSERVE Option added internally if needed within the function + * BLOCK2 Option added internally if output too large + * ETAG Option added internally + */ + coap_add_data_blocked_response(resource, session, request, response, token, + COAP_MEDIATYPE_TEXT_PLAIN, 1, + len, + buf); + + /* + * As resource->code has been updated in coap_add_data_blocked_response(), + * the response pdu will be transmitted by the underlying library. + */ } -- diff --git a/man/coap_observe.txt.in b/man/coap_observe.txt.in index 638fc770..f6c81942 100644 --- a/man/coap_observe.txt.in +++ b/man/coap_observe.txt.in @@ -11,7 +11,8 @@ coap_observe(3) NAME ---- coap_observe, coap_resource_set_get_observable, coap_resource_notify_observers, -coap_resource_get_uri_path, coap_find_observer - Work with CoAP observe +coap_resource_get_uri_path, coap_find_observer, coap_delete_observer, +coap_delete_observers - work with CoAP observe SYNOPSIS -------- @@ -28,6 +29,11 @@ const const_string_t *_query_);* *coap_subscription_t *coap_find_observer(coap_resource_t *_resource_, coap_session_t *_session_, const const_string_t *_token_);* +*int coap_delete_observer(coap_resource_t *_resource_, coap_session_t *_session_, +const coap_binary_t *_token_);* + +*void coap_delete_observers(coap_context_t *_context_, coap_session_t *_session_);* + Link with *-lcoap-@LIBCOAP_API_VERSION@*, *-lcoap-@LIBCOAP_API_VERSION@-openssl* or *-lcoap-@LIBCOAP_API_VERSION@-tinydtls* depending on your (D)TLS library type. @@ -46,23 +52,30 @@ to request in a GET request that it wants to observe this resource by the use of the COAP_OPTION_OBSERVE Option with a value of COAP_OBSERVE_ESTABLISH. Optionally, the client can specify query options for the resource. +To remove the "observe" subscription, the client has to issue a GET request +with the COAP_OPTION_OBSERVE Option with a value of COAP_OBSERVE_CANCEL. +Alternatively, the server can remove a subscription by calling +*coap_delete_observer*() or *coap_delete_observers*(), but this does not +notify the client that the subscription has been removed. + The underlying library adds in and removes "subscribers" to the resource as appropriate in the server side logic. Within the server application, it needs to determine that there is a change of state of the resource under observation, and then cause the CoAP library -layer to initiate a "fake GET request" so that an unsolicited GET response +layer to initiate a "fake GET request" so that an observe GET response gets sent back to all the clients that are observing the resource. The appropriate GET handler within the server application is called to fill in the -response packet with the appropriate information. +response packet with the appropriate information. This "fake GET request" is +triggered by a call to *coap_resource_notify_observers*(). -The call to coap_write() in the main server application i/o loop will do all -the necessary processing of sending any outstanding "fake GET requests". +The call to *coap_run_once*() in the main server application i/o loop will do +all the necessary processing of sending any outstanding "fake GET requests". Whenever the server sends a copy of the state of the "observed" resource to the client, it will use the same token used by the client when the client -requested the "observe". The client will receive this unsolicited response -in the handler defined by coap_register_response_handler(). It is the +requested the "observe". The client will receive this observe response +in the handler defined by *coap_register_response_handler*(3). It is the responsibility of the client application to match the supplied token and update the appropriate internal information. @@ -72,12 +85,22 @@ observable status of the _resource_ by the setting of _mode_. If _mode_ is _resource_ is no longer observable. *NOTE:* It is not possible for the Unknown Resource, created by -coap_resource_unknown_init(), to be observable as the Uri-Path is not known +*coap_resource_unknown_init*(3), to be observable as the Uri-Path is not known when libcoap creates a "fake GET request". The Unknown Resource PUT handler must create a new resource and mark the resource as "observable" if a specific resource needs to be observable. The application must then manage the deleteion of the resource at the appropriate time. +*NOTE:* The type (confirmable or non-confirmable) of the triggered observe +GET response is determined not by the initial GET request, but independently +by the server as per RFC 7641 3.5. Transmission. This is controlled by the +flags (one of COAP_RESOURCE_FLAGS_NOTIFY_NON or COAP_RESOURCE_FLAGS_NOTIFY_CON) +used when creating the resource using *coap_resource_init*(3). +Furthermore, the server must send at least one "observe" response as +confirmable, when generally sending non-confirmable, every 24 hours. +libcoap handles this by sending every fifth (COAP_OBS_MAX_NON) response as a +confirmable response for detection that the client is still responding. + The *coap_resource_notify_observers*() function needs to be called whenever the server application determines that there has been a change to the state of _resource_, possibly only matching a specific _query_ if _query_ is not NULL. @@ -89,6 +112,12 @@ The *coap_find_observer*() function is used to check whether the current GET request as determined from _resource_, _session_ and _token_ is currently being observed or not. +The *coap_delete_observer*() function deletes the specific observer associated +with _resource_, _session_ and has _token_. + +The *coap_delete_observers*() function is used to delete all observers +associated with the _session_ that is a part of the _context_. + RETURN VALUES ------------- The *coap_resource_get_uri_path*() function returns the uri_path or NULL if @@ -100,6 +129,8 @@ was a failure. The *coap_resource_set_get_observable*() function return 0 on failure, 1 on success. +The *coap_delete_observer*() function return 0 on failure, 1 on success. + EXAMPLES -------- *Simple Time Server* @@ -117,7 +148,7 @@ static int check_if_time_resource_has_changed(coap_resource_t *resource) { /* specific GET "time" handler, called from hnd_get_generic() */ static void -hnd_get_time(coap_context_t *ctx, coap_resource_t *resource, +hnd_get_time(coap_context_t *context, coap_resource_t *resource, coap_session_t *session, coap_pdu_t *request, coap_string_t *token, coap_string_t *query, coap_pdu_t *response) { @@ -125,42 +156,48 @@ coap_string_t *query, coap_pdu_t *response) { size_t len; time_t now; - /* Define what the response code is going to be */ - response->code = COAP_RESPONSE_CODE(205); + /* ... Additional analysis code for resource, request pdu etc. ... */ - /* If the resource is being Observed, return with Observe set */ - if (coap_find_observer(resource, session, token)) { - coap_add_option(response, - COAP_OPTION_OBSERVE, - coap_encode_var_safe(buf, sizeof(buf), resource->observe), - buf); - } + /* After analysis, generate a suitable response */ - /* Response is in plain text format */ - coap_add_option(response, - COAP_OPTION_CONTENT_FORMAT, - coap_encode_var_safe(buf, sizeof(buf), - COAP_MEDIATYPE_TEXT_PLAIN), - buf); - - /* Report on how long this response is valid for */ - coap_add_option(response, - COAP_OPTION_MAXAGE, - coap_encode_var_safe(buf, sizeof(buf), 0x01), buf); + /* Note that token, if set, is already in the response pdu */ now = time(NULL); if (query != NULL && coap_string_equal(query, coap_make_str_const("secs"))) { /* Output secs since Jan 1 1970 */ len = snprintf((char *)buf, sizeof(buf), "%lu", now); - coap_add_data(response, len, buf); - } else { + } + else { /* Output human-readable time */ struct tm *tmp; tmp = gmtime(&now); + if (!tmp) { + /* If 'now' is not valid */ + response->code = COAP_RESPONSE_CODE(404); + return; + } len = strftime((char *)buf, sizeof(buf), "%b %d %H:%M:%S", tmp); - coap_add_data(response, len, buf); } + /* + * Invoke coap_add_data_blocked_response() to do all the hard work. + * + * Define the format - COAP_MEDIATYPE_TEXT_PLAIN - to add in + * Define how long this response is valid for (secs) - 1 - to add in. + * + * OBSERVE Option added internally if needed within the function + * BLOCK2 Option added internally if output too large + * ETAG Option added internally + */ + coap_add_data_blocked_response(resource, session, request, response, token, + COAP_MEDIATYPE_TEXT_PLAIN, 1, + len, + buf); + + /* + * As resource->code has been updated in coap_add_data_blocked_response(), + * the response pdu will be transmitted by the underlying library. + */ } @@ -214,7 +251,6 @@ init_resources(coap_context_t *ctx) } - int main(int argc, char *argv[]){ coap_context_t *ctx = NULL; @@ -239,16 +275,32 @@ int main(int argc, char *argv[]){ wait_ms = COAP_RESOURCE_CHECK_TIME * 1000; while (1) { - int result = coap_run_once(ctx, wait_ms); + int result = coap_run_once( ctx, wait_ms ); if ( result < 0 ) { break; - } else if ((unsigned)result < wait_ms) { + } else if ( result && (unsigned)result < wait_ms ) { + /* decrement if there is a result wait time returned */ wait_ms -= result; } else { - if (check_if_time_resource_has_changed(time_resource)) { - coap_resource_notify_observers(time_resource, NULL); + /* + * result == 0, or result >= wait_ms + * (wait_ms could have decremented to a small value, below + * the granularity of the timer in coap_run_once() and hence + * result == 0) + */ + time_t t_now = time(NULL); + if (t_last != t_now) { + /* Happens once per second */ + int i; + t_last = t_now; + if (time_resource) { + coap_resource_notify_observers(time_resource, NULL); + } + } + if (result) { + /* result must have been >= wait_ms, so reset wait_ms */ + wait_ms = COAP_RESOURCE_CHECK_TIME * 1000; } - wait_ms = COAP_RESOURCE_CHECK_TIME * 1000; } } exit(0); diff --git a/man/coap_pdu_setup.txt.in b/man/coap_pdu_setup.txt.in index 19749c81..e41d6d70 100644 --- a/man/coap_pdu_setup.txt.in +++ b/man/coap_pdu_setup.txt.in @@ -39,6 +39,11 @@ const uint8_t *_data_);* *int coap_add_data(coap_pdu_t *_pdu_, size_t _length_, const uint8_t *_data_);* +*void coap_add_data_blocked_response(coap_resource_t *_resource_, +coap_session_t *_session_, coap_pdu_t *_request_, coap_pdu_t *_response_, +const coap_binary_t *_token_, uint16_t _media_type_, int _maxage_, +size_t _length_, const uint8_t* _data_); + *unsigned int coap_encode_var_safe(uint8_t *_buffer_, size_t _size_, unsigned int _value_);* @@ -143,6 +148,7 @@ The following is the current list of options with their numeric value #define COAP_OPTION_LOCATION_QUERY 20 /* String, 0-255 B */ #define COAP_OPTION_BLOCK2 23 /* uint, 0-3 B */ #define COAP_OPTION_BLOCK1 27 /* uint, 0-3 B */ +#define COAP_OPTION_SIZE2 28 /* uint, 0-4 B */ #define COAP_OPTION_PROXY_URI 35 /* String, 1-1034 B */ #define COAP_OPTION_PROXY_SCHEME 39 /* String, 1-255 B */ #define COAP_OPTION_SIZE1 60 /* uint, 0-4 B */ @@ -170,10 +176,19 @@ with _data_ of length _length_ to the PDU _pdu_. It is critical that options are added to the _pdu_ with _number_ either being the same or greater than the previous option _number_ that was added. -The *coap_add_data*() function added in the specified payload _data_ of length +The *coap_add_data*() function adds in the specified payload _data_ of length _length_ to the PDU _pdu_. Adding the payload data must be done after any token or options are added. This function must only be called once per _pdu_. +The *coap_add_data_blocked_response*() function added in the specified payload +_data_ of length _length_ to the PDU _pdu_. It also adds in the appropriate +CoAP options to handle Block-Wise transfer. This function is usually used for +a server's GET response. The _resource_, _session_, _request_, _response_ +and _token_ are the same parameters for the registered GET resource handler. +The _media_type_ is for the format of the _data_ and _maxage_ defines the +lifetime of the response. If set to -1, then the MAXAGE option does not get +included. This function must only be called once per _pdu_. + The *coap_encode_var_safe*() function encodes _value_ into _buffer_ which has a size of _size_ in bytes. Normally, the _buffer_ size should be at least the sizeof(int) bytes unless you definitely know less space is required. @@ -318,59 +333,48 @@ coap_string_t *query, coap_pdu_t *response) { unsigned char buf[40]; size_t len; time_t now; - coap_tick_t t; /* ... Additional analysis code for resource, request pdu etc. ... */ /* After analysis, generate a suitable response */ - /* Define what the response code is going to be */ - response->code = COAP_RESPONSE_CODE(205); - /* Note that token, if set, is already in the response pdu */ - /* - * Note that the following coap_add_option MUST be defined with numerically - * incrementing COAP_OPTION_ options - */ - - /* If the resource is being Observed, return with Observe set */ - if (coap_find_observer(resource, session, token)) { - coap_add_option(response, - COAP_OPTION_OBSERVE, - coap_encode_var_safe(buf, sizeof(buf), resource->observe), - buf); - } - - /* Response is in plain text format */ - coap_add_option(response, - COAP_OPTION_CONTENT_FORMAT, - coap_encode_var_safe(buf, sizeof(buf), - COAP_MEDIATYPE_TEXT_PLAIN), - buf); - - /* Report on how long this response is valid for (1 second in this case)*/ - coap_add_option(response, - COAP_OPTION_MAXAGE, - coap_encode_var_safe(buf, sizeof(buf), 0x01), buf); - now = time(NULL); if (query != NULL && coap_string_equal(query, coap_make_str_const("secs"))) { /* Output secs since Jan 1 1970 */ len = snprintf((char *)buf, sizeof(buf), "%lu", now); - coap_add_data(response, len, buf); - } else { + } + else { /* Output human-readable time */ struct tm *tmp; tmp = gmtime(&now); + if (!tmp) { + /* If 'now' is not valid */ + response->code = COAP_RESPONSE_CODE(404); + return; + } len = strftime((char *)buf, sizeof(buf), "%b %d %H:%M:%S", tmp); - coap_add_data(response, len, buf); } + /* + * Invoke coap_add_data_blocked_response() to do all the hard work. + * + * Define the format - COAP_MEDIATYPE_TEXT_PLAIN - to add in + * Define how long this response is valid for (secs) - 1 - to add in. + * + * OBSERVE Option added internally if needed within the function + * BLOCK2 Option added internally if output too large + * ETAG Option added internally + */ + coap_add_data_blocked_response(resource, session, request, response, token, + COAP_MEDIATYPE_TEXT_PLAIN, 1, + len, + buf); /* - * As resource->code has been updated, the response pdu will be transmitted - * by the underlying library + * As resource->code has been updated in coap_add_data_blocked_response(), + * the response pdu will be transmitted by the underlying library. */ } diff --git a/man/coap_resource.txt.in b/man/coap_resource.txt.in index 6eca5820..ea760ae7 100644 --- a/man/coap_resource.txt.in +++ b/man/coap_resource.txt.in @@ -69,17 +69,20 @@ resource with GET handler must be created by the unknown resource callback handle matching the URI which then can be Observable. The *coap_resource_init*() function returns a newly created _resource_ of -type _coap_resource_t_ *. _uri_path_ specifies the uri string path to match +type _coap_resource_t_ * . _uri_path_ specifies the uri string path to match against. _flags_ is used to define whether the -_resource_ is of type Confirmable Message or Non-Confirmable Message. +_resource_ is of type Confirmable Message or Non-Confirmable Message for +any "observe" responses. See *coap_observe*(3). _flags_ can be one of the following definitions or'ed together. [horizontal] *COAP_RESOURCE_FLAGS_NOTIFY_NON*:: -Set the notification message type to non-confirmable. +Set the notification message type to non-confirmable for any trigggered +"observe" responses. //- *COAP_RESOURCE_FLAGS_NOTIFY_CON*:: -Set the notification message type to confirmable. +Set the notification message type to confirmable for any trigggered +"observe" responses. //- *COAP_RESOURCE_FLAGS_RELEASE_URI*:: Free off the coap_str_const_t for _uri_path_ when the _resource_ is deleted. @@ -150,6 +153,7 @@ coap_string_t *query, coap_pdu_t *response) { coap_encode_var_safe(buf, sizeof(buf), 0x2ffff), buf); coap_add_data(response, strlen(INDEX), (const uint8_t *)INDEX); + } void @@ -329,7 +333,7 @@ coap_string_t *query, coap_pdu_t *response) { coap_add_resource(ctx, r); /* Do the PUT for this first call */ - hnd_put(ctx, resource, session, request, token, query, response); + hnd_put(ctx, r, session, request, token, query, response); return; diff --git a/src/block.c b/src/block.c index 83cbf700..585ff8a8 100644 --- a/src/block.c +++ b/src/block.c @@ -15,6 +15,8 @@ #include "libcoap.h" #include "debug.h" #include "block.h" +#include "resource.h" +#include "coap_hashkey.h" #ifndef min #define min(a,b) ((a) < (b) ? (a) : (b)) @@ -34,7 +36,7 @@ coap_opt_block_num(const coap_opt_t *block_opt) { if (len > 1) { num = coap_decode_var_bytes(coap_opt_value(block_opt), - coap_opt_length(block_opt) - 1); + coap_opt_length(block_opt) - 1); } return (num << 4) | ((*COAP_OPT_BLOCK_LAST(block_opt) & 0xF0) >> 4); @@ -70,7 +72,7 @@ coap_get_block(coap_pdu_t *pdu, uint16_t type, coap_block_t *block) { int coap_write_block_opt(coap_block_t *block, uint16_t type, - coap_pdu_t *pdu, size_t data_length) { + coap_pdu_t *pdu, size_t data_length) { size_t start, want, avail; unsigned char buf[4]; @@ -104,7 +106,7 @@ coap_write_block_opt(coap_block_t *block, uint16_t type, int newBlockSize; /* we need to decrease the block size */ - if (avail < 16) { /* bad luck, this is the smallest block size */ + if (avail < 16) { /* bad luck, this is the smallest block size */ debug("not enough space, even the smallest block does not fit"); return -3; } @@ -120,16 +122,16 @@ coap_write_block_opt(coap_block_t *block, uint16_t type, /* to re-encode the block option */ coap_add_option(pdu, type, coap_encode_var_safe(buf, sizeof(buf), ((block->num << 4) | - (block->m << 3) | - block->szx)), - buf); + (block->m << 3) | + block->szx)), + buf); return 1; } int coap_add_block(coap_pdu_t *pdu, unsigned int len, const uint8_t *data, - unsigned int block_num, unsigned char block_szx) { + unsigned int block_num, unsigned char block_szx) { unsigned int start; start = block_num << (block_szx + 4); @@ -137,7 +139,131 @@ coap_add_block(coap_pdu_t *pdu, unsigned int len, const uint8_t *data, return 0; return coap_add_data(pdu, - min(len - start, (1U << (block_szx + 4))), - data + start); + min(len - start, (1U << (block_szx + 4))), + data + start); } + +/* + * Note that the COAP_OPTION_ have to be added in the correct order + */ +void +coap_add_data_blocked_response(coap_resource_t *resource, + coap_session_t *session, + coap_pdu_t *request, + coap_pdu_t *response, + const coap_binary_t *token, + uint16_t media_type, + int maxage, + size_t length, + const uint8_t* data +) { + coap_key_t etag; + unsigned char buf[4]; + coap_block_t block2 = { 0, 0, 0 }; + int block2_requested = 0; + coap_subscription_t *subscription = coap_find_observer(resource, session, token); + + /* + * Need to check that a valid block is getting asked for so that the + * correct options are put into the PDU. + */ + if (request) { + if (coap_get_block(request, COAP_OPTION_BLOCK2, &block2)) { + block2_requested = 1; + if (length <= (block2.num << (block2.szx + 4))) { + coap_log(LOG_DEBUG, "Illegal block requested (%d > last = %ld)\n", + block2.num, + length >> (block2.szx + 4)); + response->code = COAP_RESPONSE_CODE(400); + goto error; + } + } + } + else if (subscription && subscription->has_block2) { + block2 = subscription->block2; + block2.num = 0; + block2_requested = 1; + } + response->code = COAP_RESPONSE_CODE(205); + + /* add etag for the resource */ + memset(etag, 0, sizeof(etag)); + coap_hash(data, length, etag); + coap_add_option(response, COAP_OPTION_ETAG, sizeof(etag), etag); + + if ((block2.num == 0) && subscription) { + coap_add_option(response, COAP_OPTION_OBSERVE, + coap_encode_var_safe(buf, sizeof (buf), + resource->observe), + buf); + } + + coap_add_option(response, COAP_OPTION_CONTENT_TYPE, + coap_encode_var_safe(buf, sizeof(buf), + media_type), + buf); + + if (maxage >= 0) { + coap_add_option(response, + COAP_OPTION_MAXAGE, + coap_encode_var_safe(buf, sizeof(buf), maxage), buf); + } + + if (block2_requested) { + int res; + + res = coap_write_block_opt(&block2, COAP_OPTION_BLOCK2, response, + length); + + switch (res) { + case -2: /* illegal block (caught above) */ + response->code = COAP_RESPONSE_CODE(400); + goto error; + case -1: /* should really not happen */ + assert(0); + /* fall through if assert is a no-op */ + case -3: /* cannot handle request */ + response->code = COAP_RESPONSE_CODE(500); + goto error; + default: /* everything is good */ + ; + } + + coap_add_option(response, + COAP_OPTION_SIZE2, + coap_encode_var_safe(buf, sizeof(buf), length), + buf); + + coap_add_block(response, length, data, + block2.num, block2.szx); + return; + } + + /* + * BLOCK2 not requested + */ + if (!coap_add_data(response, length, data)) { + /* set initial block size, will be lowered by + * coap_write_block_opt) automatically */ + block2.num = 0; + block2.szx = 6; + coap_write_block_opt(&block2, COAP_OPTION_BLOCK2, response, + length); + + coap_add_option(response, + COAP_OPTION_SIZE2, + coap_encode_var_safe(buf, sizeof(buf), length), + buf); + + coap_add_block(response, length, data, + block2.num, block2.szx); + } + return; + +error: + coap_add_data(response, + strlen(coap_response_phrase(response->code)), + (const unsigned char *)coap_response_phrase(response->code)); +} + #endif /* WITHOUT_BLOCK */ diff --git a/src/coap_hashkey.c b/src/coap_hashkey.c new file mode 100644 index 00000000..da93ff12 --- /dev/null +++ b/src/coap_hashkey.c @@ -0,0 +1,26 @@ +/* coap_hashkey.c -- definition of hash key type and helper functions + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include "coap_hashkey.h" + +void +coap_hash_impl(const unsigned char *s, unsigned int len, coap_key_t h) { + size_t j; + + while (len--) { + j = sizeof(coap_key_t)-1; + + while (j) { + h[j] = ((h[j] << 7) | (h[j-1] >> 1)) + h[j]; + --j; + } + + h[0] = (h[0] << 7) + h[0] + *s++; + } +} + diff --git a/src/net.c b/src/net.c index e1b6ca0e..cb6e4cc3 100644 --- a/src/net.c +++ b/src/net.c @@ -1986,15 +1986,18 @@ handle_request(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu if ((observe_action & COAP_OBSERVE_CANCEL) == 0) { coap_subscription_t *subscription; + coap_block_t block2; + int has_block2 = 0; - coap_log(LOG_DEBUG, "create new subscription\n"); - subscription = coap_add_observer(resource, session, &token, query); + if (coap_get_block(pdu, COAP_OPTION_BLOCK2, &block2)) { + has_block2 = 1; + } + subscription = coap_add_observer(resource, session, &token, query, has_block2, block2); owns_query = 0; if (subscription) { coap_touch_observer(context, session, &token); } } else { - coap_log(LOG_DEBUG, "removed observer\n"); coap_delete_observer(resource, session, &token); } } @@ -2008,7 +2011,6 @@ handle_request(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu respond = no_response(pdu, response); if (respond != RESPONSE_DROP) { if (observe && (COAP_RESPONSE_CLASS(response->code) > 2)) { - coap_log(LOG_DEBUG, "removed observer\n"); coap_delete_observer(resource, session, &token); } diff --git a/src/resource.c b/src/resource.c index a6f8a6eb..cc76d50d 100644 --- a/src/resource.c +++ b/src/resource.c @@ -6,6 +6,7 @@ * README for terms of use. */ +#include #include "coap_config.h" #include "coap.h" #include "debug.h" @@ -622,7 +623,9 @@ coap_subscription_t * coap_add_observer(coap_resource_t *resource, coap_session_t *session, const coap_binary_t *token, - coap_string_t *query) { + coap_string_t *query, + int has_block2, + coap_block_t block2) { coap_subscription_t *s; assert( session ); @@ -672,9 +675,14 @@ coap_add_observer(coap_resource_t *resource, s->query = query; + s->has_block2 = has_block2; + s->block2 = block2; + /* add subscriber to resource */ LL_PREPEND(resource->subscribers, s); + coap_log(LOG_DEBUG, "create new subscription\n"); + return s; } @@ -706,6 +714,16 @@ coap_delete_observer(coap_resource_t *resource, coap_session_t *session, COAP_FREE_TYPE(subscription,s); } + if (s) { + char outbuf[2*s->token_length+1]; + unsigned int i; + for (i = 0; i < s->token_length; i++) { + snprintf(&outbuf[2*i], 3, + "%02x", s->token[i]); + } + coap_log(LOG_DEBUG, "removed observer tid %s\n", outbuf); + } + return s != NULL; }