From dc1ca3c0015c13308f49c0332378e86ab15956e5 Mon Sep 17 00:00:00 2001 From: Jon Shallow Date: Wed, 7 Apr 2021 10:55:20 +0100 Subject: [PATCH 1/2] coap_async_state_t: Obfuscate coap_async_state_t for applications Move coap_async_state_t to coap_async_internal.h and rename to coap_async_t as it no longer has any state. Refactor the async logic to simplify usage and provide libcoap based delay functionality support for request/response traffic such as multicast. Let libcoap decide when the delayed response is to be sent. Move internal async based function definitions to coap_async_internal.h. Replace most references to "struct coap_async_state_t" with "coap_async_t". Provide new functions to allow applications to access parts of coap_async_t as appropriate. Update examples to use these new access functions where appropriate. Add in new man page. --- Makefile.am | 2 + configure.ac | 1 + examples/coap-server.c | 130 +++++++------------- examples/etsi_iot_01.c | 130 ++++++-------------- include/coap2/async.h | 137 ++++++++------------- include/coap2/coap_async_internal.h | 65 ++++++++++ include/coap2/coap_forward_decls.h | 7 ++ include/coap2/coap_internal.h | 1 + include/coap2/coap_net_internal.h | 2 +- libcoap-2.map | 4 +- libcoap-2.sym | 4 +- man/Makefile.am | 3 +- man/coap_async.txt.in | 180 ++++++++++++++++++++++++++++ src/async.c | 108 ++++++++++------- src/coap_io.c | 24 +++- src/net.c | 39 ++++++ 16 files changed, 516 insertions(+), 321 deletions(-) create mode 100644 include/coap2/coap_async_internal.h create mode 100644 man/coap_async.txt.in diff --git a/Makefile.am b/Makefile.am index e0165469..8e2e4b61 100644 --- a/Makefile.am +++ b/Makefile.am @@ -28,6 +28,7 @@ EXTRA_DIST = \ include/coap$(LIBCOAP_API_VERSION)/coap_internal.h \ include/coap$(LIBCOAP_API_VERSION)/coap_riot.h \ include/coap$(LIBCOAP_API_VERSION)/coap_asn1_internal.h \ + include/coap$(LIBCOAP_API_VERSION)/coap_async_internal.h \ include/coap$(LIBCOAP_API_VERSION)/coap_block_internal.h \ include/coap$(LIBCOAP_API_VERSION)/coap_cache_internal.h \ include/coap$(LIBCOAP_API_VERSION)/coap_net_internal.h \ @@ -164,6 +165,7 @@ libcoap_@LIBCOAP_NAME_SUFFIX@_la_LDFLAGS = \ ## libcoap-$(LIBCOAP_API_VERSION).{map,sym} for the linker. CTAGS_IGNORE=-I " \ coap_delete_all_async \ +coap_delete_all \ coap_dtls_context_check_keys_enabled \ coap_dtls_context_set_pki \ coap_dtls_context_set_pki_root_cas \ diff --git a/configure.ac b/configure.ac index a3ff617e..f9ee93c5 100644 --- a/configure.ac +++ b/configure.ac @@ -820,6 +820,7 @@ examples/Makefile include/coap$LIBCOAP_API_VERSION/coap.h include/coap$LIBCOAP_API_VERSION/coap.h.windows man/coap.txt +man/coap_async.txt man/coap_attribute.txt man/coap_block.txt man/coap_cache.txt diff --git a/examples/coap-server.c b/examples/coap-server.c index cc0bdb6e..adc8594a 100644 --- a/examples/coap-server.c +++ b/examples/coap-server.c @@ -146,18 +146,6 @@ typedef struct valid_pki_snis_t { static valid_pki_snis_t valid_pki_snis = {0, NULL}; -#ifndef WITHOUT_ASYNC -/* This variable is used to mimic long-running tasks that require - * asynchronous responses. */ -static coap_async_state_t *async = NULL; - -/* A typedef for transfering a value in a void pointer */ -typedef union { - unsigned int val; - void *ptr; -} async_data_t; -#endif /* WITHOUT_ASYNC */ - typedef struct transient_value_t { coap_binary_t *value; size_t ref_cnt; @@ -363,89 +351,63 @@ hnd_delete_time(coap_context_t *ctx COAP_UNUSED, } #ifndef WITHOUT_ASYNC +/* + * This logic is used to test out that the client correctly handles a + * "separate" response (empty ACK followed by data response at a later stage). + */ static void -hnd_get_async(coap_context_t *ctx, - coap_resource_t *resource COAP_UNUSED, +hnd_get_async(coap_context_t *context, + coap_resource_t *resource, coap_session_t *session, coap_pdu_t *request, - coap_binary_t *token COAP_UNUSED, - coap_string_t *query COAP_UNUSED, + coap_binary_t *token, + coap_string_t *query, coap_pdu_t *response) { unsigned long delay = 5; size_t size; - - if (async) { - if (async->id != request->mid) { - coap_opt_filter_t f; - coap_option_filter_clear(&f); - response->code = COAP_RESPONSE_CODE_SERVICE_UNAVAILABLE; - } - return; - } - - if (query) { - const uint8_t *p = query->s; - - delay = 0; - for (size = query->length; size; --size, ++p) - delay = delay * 10 + (*p - '0'); - } + coap_async_t *async; /* - * This is so we can use a local variable to hold the remaining time. - * The alternative is to malloc the variable and set COAP_ASYNC_RELEASE_DATA - * in the flags parameter in the call to coap_register_async() and handle - * the required time as appropriate in check_async() below. + * See if this is the initial, or delayed request */ - async_data_t data; - data.val = COAP_TICKS_PER_SECOND * delay; - async = coap_register_async(ctx, - session, - request, - COAP_ASYNC_SEPARATE | COAP_ASYNC_CONFIRM, - data.ptr); -} + async = coap_find_async(context, session, request->mid); + if (!async) { + /* Set up an async request to trigger delay in the future */ + if (query) { + const uint8_t *p = query->s; -static void -check_async(coap_context_t *ctx, - coap_tick_t now) { - coap_pdu_t *response; - coap_async_state_t *tmp; - async_data_t data; - - size_t size = 13; - - if (!async) - return; - - data.ptr = async->appdata; - if (now < async->created + data.val) - return; - - response = coap_pdu_init(async->flags & COAP_ASYNC_CONFIRM - ? COAP_MESSAGE_CON - : COAP_MESSAGE_NON, - COAP_RESPONSE_CODE_CONTENT, 0, size); - if (!response) { - coap_log(LOG_DEBUG, "check_async: insufficient memory, we'll try later\n"); - data.val = data.val + 15 * COAP_TICKS_PER_SECOND; - async->appdata = data.ptr; + delay = 0; + for (size = query->length; size; --size, ++p) + delay = delay * 10 + (*p - '0'); + if (delay == 0) { + coap_log(LOG_INFO, "async: delay of 0 not supported\n"); + response->code = COAP_RESPONSE_CODE_BAD_REQUEST; + return; + } + } + async = coap_register_async(context, + session, + request, + COAP_TICKS_PER_SECOND * delay); + if (async == NULL) { + response->code = COAP_RESPONSE_CODE_SERVICE_UNAVAILABLE; + return; + } + /* + * Not setting response code will cause empty ACK to be sent + * if Confirmable + */ return; } + /* async set up, so this is the delayed request */ - response->mid = coap_new_message_id(async->session); + /* Send back the appropriate data */ + coap_add_data_large_response(resource, session, request, response, token, + query, COAP_MEDIATYPE_TEXT_PLAIN, -1, 0, 4, + (const uint8_t *)"done", NULL, NULL); + response->code = COAP_RESPONSE_CODE_CONTENT; - if (async->tokenlen) - coap_add_token(response, async->tokenlen, async->token); - - coap_add_data(response, 4, (const uint8_t *)"done"); - - if (coap_send_large(async->session, response) == COAP_INVALID_MID) { - coap_log(LOG_DEBUG, "check_async: cannot send response for message\n"); - } - coap_remove_async(ctx, async->session, async->id, &tmp); - coap_free_async(async); - async = NULL; + /* async is automatically removed by libcoap on return from this handler */ } #endif /* WITHOUT_ASYNC */ @@ -2900,12 +2862,6 @@ main(int argc, char **argv) { if (next_sec_ms && next_sec_ms < wait_ms) wait_ms = next_sec_ms; } - -#ifndef WITHOUT_ASYNC - /* check if we have to send asynchronous responses */ - coap_ticks( &now ); - check_async(ctx, now); -#endif /* WITHOUT_ASYNC */ } coap_free(ca_mem); diff --git a/examples/etsi_iot_01.c b/examples/etsi_iot_01.c index d1e0f16b..6200d894 100644 --- a/examples/etsi_iot_01.c +++ b/examples/etsi_iot_01.c @@ -44,16 +44,6 @@ typedef struct { unsigned char data[]; /* the actual contents */ } coap_payload_t; -/* This variable is used to mimic long-running tasks that require - * asynchronous responses. */ -static coap_async_state_t *async = NULL; - -/* A typedef for transfering a value in a void pointer */ -typedef union { - unsigned int val; - void *ptr; -} async_data_t; - /* SIGINT handler: set quit to 1 for graceful termination */ static void handle_sigint(int signum COAP_UNUSED) { @@ -369,92 +359,52 @@ hnd_get_separate(coap_context_t *ctx, coap_opt_t *option; coap_opt_filter_t f; unsigned long delay = 5; + coap_async_t *async; - if (async) { - if (async->id != request->mid) { - coap_option_filter_clear(&f); + async = coap_find_async(ctx, session, request->mid); + if (!async) { + /* Set up an async request to trigger delay in the future */ + + /* search for option delay in query list */ + coap_option_filter_clear(&f); + coap_option_filter_set(&f, COAP_OPTION_URI_QUERY); + + coap_option_iterator_init(request, &opt_iter, &f); + + while ((option = coap_option_next(&opt_iter))) { + if (strncmp("delay=", (const char *)coap_opt_value(option), 6) == 0) { + unsigned int i; + unsigned long d = 0; + + for (i = 6; i < coap_opt_length(option); ++i) + d = d * 10 + coap_opt_value(option)[i] - '0'; + + /* don't allow delay to be less than COAP_RESOURCE_CHECK_TIME*/ + delay = d < COAP_RESOURCE_CHECK_TIME_SEC + ? COAP_RESOURCE_CHECK_TIME_SEC + : d; + coap_log(LOG_DEBUG, "set delay to %lu\n", delay); + break; + } + } + async = coap_register_async(ctx, + session, + request, + COAP_TICKS_PER_SECOND * delay); + if (async == NULL) { response->code = COAP_RESPONSE_CODE_SERVICE_UNAVAILABLE; + return; } + /* Not setting response code will cause empty ACK to be sent + if Confirmable */ return; } - /* search for option delay in query list */ - coap_option_filter_clear(&f); - coap_option_filter_set(&f, COAP_OPTION_URI_QUERY); - - coap_option_iterator_init(request, &opt_iter, &f); - - while ((option = coap_option_next(&opt_iter))) { - if (strncmp("delay=", (const char *)coap_opt_value(option), 6) == 0) { - unsigned int i; - unsigned long d = 0; - - for (i = 6; i < coap_opt_length(option); ++i) - d = d * 10 + coap_opt_value(option)[i] - '0'; - - /* don't allow delay to be less than COAP_RESOURCE_CHECK_TIME*/ - delay = d < COAP_RESOURCE_CHECK_TIME_SEC - ? COAP_RESOURCE_CHECK_TIME_SEC - : d; - coap_log(LOG_DEBUG, "set delay to %lu\n", delay); - break; - } - } - - /* - * This is so we can use a local variable to hold the remaining time. - * The alternative is to malloc the variable and set COAP_ASYNC_RELEASE_DATA - * in the flags parameter in the call to coap_register_async() and handle - * the required time as appropriate in check_async() below. - */ - async_data_t data; - data.val = COAP_TICKS_PER_SECOND * delay; - - async = coap_register_async(ctx, session, request, COAP_ASYNC_SEPARATE, - data.ptr); -} - -static void -check_async(coap_context_t *ctx, - coap_tick_t now) { - coap_pdu_t *response; - coap_async_state_t *tmp; - async_data_t data; - - size_t size = 8; - - if (!async) - return; - - data.ptr = async->appdata; - if (now < async->created + data.val) - return; - - response = coap_pdu_init(async->flags & COAP_ASYNC_CONFIRM - ? COAP_MESSAGE_CON - : COAP_MESSAGE_NON, - COAP_RESPONSE_CODE_CONTENT, 0, size); - if (!response) { - coap_log(LOG_DEBUG, "check_async: insufficient memory, we'll try later\n"); - async->appdata = - (void *)((unsigned long)async->appdata + 15 * COAP_TICKS_PER_SECOND); - return; - } - - response->mid = coap_new_message_id(async->session); - - if (async->tokenlen) - coap_add_token(response, async->tokenlen, async->token); - + /* This is the delayed response. Send back the appropriate data */ coap_add_data(response, 4, (const uint8_t *)"done"); + response->code = COAP_RESPONSE_CODE_CONTENT; - if (coap_send(async->session, response) == COAP_INVALID_MID) { - coap_log(LOG_DEBUG, "check_async: cannot send response for mid=0x%x\n", - response->mid); - } - coap_remove_async(ctx, async->session, async->id, &tmp); - coap_free_async(async); - async = NULL; + /* async is automatically removed by libcoap */ } static coap_payload_t * @@ -636,7 +586,6 @@ int main(int argc, char **argv) { coap_context_t *ctx; int result; - coap_tick_t now; char addr_str[NI_MAXHOST] = "::"; char port_str[NI_MAXSERV] = "5683"; int opt; @@ -685,9 +634,6 @@ main(int argc, char **argv) { if ( result >= 0 ) { /* coap_check_resource_list( ctx ); */ } - /* check if we have to send asynchronous responses */ - coap_ticks(&now); - check_async(ctx, now); } coap_free_context( ctx ); diff --git a/include/coap2/async.h b/include/coap2/async.h index 57f6be3d..b2940136 100644 --- a/include/coap2/async.h +++ b/include/coap2/async.h @@ -22,135 +22,96 @@ /** * @defgroup coap_async Asynchronous Messaging * @{ - * Structure for managing asynchronous state of CoAP resources. A - * coap_context_t object holds a list of coap_async_state_t objects that can be - * used to generate a separate response in case a result of an operation cannot - * be delivered in time. + * API functions for Async "separate" messages. + * A coap_context_t object holds a list of coap_async_t objects that can + * be used to generate a separate response in the case a result of a request + * cannot be delivered immediately. */ -typedef struct coap_async_state_t { - unsigned char flags; /**< holds the flags to control behaviour */ - - /** - * Holds the internal time when the object was registered with a - * resource. This field will be updated whenever - * coap_register_async() is called for a specific resource. - */ - coap_tick_t created; - - /** - * This field can be used to register opaque application data with the - * asynchronous state object. - */ - void *appdata; - coap_session_t *session; /**< transaction session */ - coap_mid_t id; /**< message id */ - struct coap_async_state_t *next; /**< internally used for linking */ - size_t tokenlen; /**< length of the token */ - uint8_t token[8]; /**< the token to use in a response */ -} coap_async_state_t; - -/* Definitions for Async Status Flags These flags can be used to control the - * behaviour of asynchronous response generation. - */ -#define COAP_ASYNC_CONFIRM 0x01 /**< send confirmable response */ -#define COAP_ASYNC_SEPARATE 0x02 /**< send separate response */ - -/** release application data on destruction */ -#define COAP_ASYNC_RELEASE_DATA 0x08 /** - * Allocates a new coap_async_state_t object and fills its fields according to - * the given @p request. The @p flags are used to control generation of empty - * ACK responses to stop retransmissions and to release registered @p data when - * the resource is deleted by coap_free_async(). This function returns a pointer - * to the registered coap_async_t object or @c NULL on error. Note that this - * function will return @c NULL in case that an object with the same identifier - * is already registered. + * Allocates a new coap_async_t object and fills its fields according to + * the given @p request. This function returns a pointer to the registered + * coap_async_t object or @c NULL on error. Note that this function will + * return @c NULL in case that an object with the same identifier is already + * registered. + * + * When the delay expires, a copy of the @p request will get sent to the + * appropriate request handler. * * @param context The context to use. * @param session The session that is used for asynchronous transmissions. * @param request The request that is handled asynchronously. - * @param flags Flags to control state management. - * @param data Opaque application data to register. Note that the - * storage occupied by @p data is released on destruction - * only if flag COAP_ASYNC_RELEASE_DATA is set. + * @param delay The amount of time to delay before sending response, 0 means + * wait forever. * - * @return A pointer to the registered coap_async_state_t object or @c + * @return A pointer to the registered coap_async_t object or @c * NULL in case of an error. */ -coap_async_state_t * +coap_async_t * coap_register_async(coap_context_t *context, coap_session_t *session, coap_pdu_t *request, - unsigned char flags, - void *data); + coap_tick_t delay); /** - * Removes the state object identified by @p id from @p context. The removed - * object is returned in @p s, if found. Otherwise, @p s is undefined. This - * function returns @c 1 if the object was removed, @c 0 otherwise. Note that - * the storage allocated for the stored object is not released by this - * functions. You will have to call coap_free_async() to do so. + * Update the delay timeout, so changing when the registered @p async triggers. * - * @param context The context where the async object is registered. - * @param session The session that is used for asynchronous transmissions. - * @param id The identifier of the asynchronous transaction. - * @param s Will be set to the object identified by @p id after removal. + * When the new delay expires, a copy of the original request will get sent to + * the appropriate request handler. * - * @return @c 1 if object was removed and @p s updated, or @c 0 if no - * object was found with the given id. @p s is valid only if the - * return value is @c 1. + * @param async The object to update. + * @param delay The amount of time to delay before sending response, 0 means + * wait forever. */ -int coap_remove_async(coap_context_t *context, - coap_session_t *session, - coap_mid_t id, - coap_async_state_t **s); +void +coap_async_set_delay(coap_async_t *async, coap_tick_t delay); /** * Releases the memory that was allocated by coap_async_state_init() for the - * object @p s. The registered application data will be released automatically - * if COAP_ASYNC_RELEASE_DATA is set. + * object @p async. * - * @param state The object to delete. + * @param context The context to use. + * @param async The object to delete. */ void -coap_free_async(coap_async_state_t *state); +coap_free_async(coap_context_t *context, coap_async_t *async); /** - * Retrieves the object identified by @p id from the list of asynchronous + * Retrieves the object identified by @p mid from the list of asynchronous * transactions that are registered with @p context. This function returns a * pointer to that object or @c NULL if not found. * * @param context The context where the asynchronous objects are registered * with. - * @param session The session that is used for asynchronous transmissions. - * @param id The id of the object to retrieve. + * @param session The session that is used for asynchronous transmissions. + * @param mid The mid of the object to retrieve. * - * @return A pointer to the object identified by @p id or @c NULL if + * @return A pointer to the object identified by @p mid or @c NULL if * not found. */ -coap_async_state_t *coap_find_async(coap_context_t *context, coap_session_t *session, coap_mid_t id); +coap_async_t *coap_find_async(coap_context_t *context, + coap_session_t *session, coap_mid_t mid); /** - * Updates the time stamp of @p s. + * Set the application data pointer held in @p async. This overwrites any + * existing data pointer. * - * @param s The state object to update. + * @param async The async state object. + * @param app_data The pointer to the data. */ -COAP_STATIC_INLINE void -coap_touch_async(coap_async_state_t *s) { coap_ticks(&s->created); } +void coap_async_set_app_data(coap_async_t *async, void *app_data); + +/** + * Gets the application data pointer held in @p async. + * + * @param async The async state object. + * + * @return The applicaton data pointer. + */ +void *coap_async_get_app_data(const coap_async_t *async); /** @} */ -/** - * Removes and frees off all of the async entries for the given context. - * - * Internal function. - * - * @param context The context to remove all async entries from. - */ -void -coap_delete_all_async(coap_context_t *context); - #endif /* WITHOUT_ASYNC */ #endif /* COAP_ASYNC_H_ */ diff --git a/include/coap2/coap_async_internal.h b/include/coap2/coap_async_internal.h new file mode 100644 index 00000000..49584d0b --- /dev/null +++ b/include/coap2/coap_async_internal.h @@ -0,0 +1,65 @@ +/* + * coap_async_internal.h -- state management for asynchronous messages + * + * Copyright (C) 2010-2021 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see README for terms + * of use. + */ + +/** + * @file coap_async_internal.h + * @brief CoAP async internal information + */ + +#ifndef COAP_ASYNC_INTERNAL_H_ +#define COAP_ASYNC_INTERNAL_H_ + +#include "coap2/net.h" + +#ifndef WITHOUT_ASYNC + +/** + * @defgroup coap_async_internal Asynchronous Messaging (Internal) + * @{ + * CoAP Async Structures, Enums and Functions that are not exposed to + * applications. + * A coap_context_t object holds a list of coap_async_t objects that can be + * used to generate a separate response in the case a result of a request cannot + * be delivered immediately. + */ +struct coap_async_t { + struct coap_async_t *next; /**< internally used for linking */ + coap_tick_t delay; /**< When to delay to before triggering the response + 0 indicates never trigger */ + coap_session_t *session; /**< transaction session */ + coap_pdu_t *pdu; /**< copy of request pdu */ + void* appdata; /** User definable data pointer */ +}; + +/** + * Checks if there are any pending Async requests - if so, send them off. + * Otherewise return the time remaining for the next Async to be triggered + * or 0 if nothing to do. + * + * @param context The current context. + * @param now The current time in ticks. + * + * @return The tick time before the next Async needs to go, else 0 if + * nothing to do. + */ +coap_tick_t coap_check_async(coap_context_t *context, coap_tick_t now); + +/** + * Removes and frees off all of the async entries for the given context. + * + * @param context The context to remove all async entries from. + */ +void +coap_delete_all_async(coap_context_t *context); + +/** @} */ + +#endif /* WITHOUT_ASYNC */ + +#endif /* COAP_ASYNC_INTERNAL_H_ */ diff --git a/include/coap2/coap_forward_decls.h b/include/coap2/coap_forward_decls.h index ad95a7a4..db18ddca 100644 --- a/include/coap2/coap_forward_decls.h +++ b/include/coap2/coap_forward_decls.h @@ -40,6 +40,13 @@ typedef struct coap_pdu_t coap_pdu_t; * typedef all the opaque structures that are defined in coap_*_internal.h */ +/* ************* coap_async_internal.h ***************** */ + +/** + * Async Entry information. + */ +typedef struct coap_async_t coap_async_t; + /* ************* coap_cache_internal.h ***************** */ /* diff --git a/include/coap2/coap_internal.h b/include/coap2/coap_internal.h index 89c43406..25ead77f 100644 --- a/include/coap2/coap_internal.h +++ b/include/coap2/coap_internal.h @@ -47,6 +47,7 @@ /* Specifically defined internal .h files */ #include "coap_asn1_internal.h" +#include "coap_async_internal.h" #include "coap_block_internal.h" #include "coap_cache_internal.h" #include "coap_net_internal.h" diff --git a/include/coap2/coap_net_internal.h b/include/coap2/coap_net_internal.h index b18891f3..4de36d6b 100644 --- a/include/coap2/coap_net_internal.h +++ b/include/coap2/coap_net_internal.h @@ -55,7 +55,7 @@ struct coap_context_t { #ifndef WITHOUT_ASYNC /** * list of asynchronous message ids */ - struct coap_async_state_t *async_state; + coap_async_t *async_state; #endif /* WITHOUT_ASYNC */ /** diff --git a/libcoap-2.map b/libcoap-2.map index 71cdded5..917a11a5 100644 --- a/libcoap-2.map +++ b/libcoap-2.map @@ -15,6 +15,9 @@ global: coap_address_init; coap_address_set_port; coap_add_token; + coap_async_get_app_data; + coap_async_set_app_data; + coap_async_set_delay; coap_attr_get_value; coap_block_build_body; coap_cache_derive_key; @@ -157,7 +160,6 @@ global: coap_register_ping_handler; coap_register_pong_handler; coap_register_response_handler; - coap_remove_async; coap_resize_binary; coap_resource_get_uri_path; coap_resource_get_userdata; diff --git a/libcoap-2.sym b/libcoap-2.sym index a50dedbd..24c44d5d 100644 --- a/libcoap-2.sym +++ b/libcoap-2.sym @@ -13,6 +13,9 @@ coap_address_get_port coap_address_init coap_address_set_port coap_add_token +coap_async_get_app_data +coap_async_set_app_data +coap_async_set_delay coap_attr_get_value coap_block_build_body coap_cache_derive_key @@ -155,7 +158,6 @@ coap_register_option coap_register_ping_handler coap_register_pong_handler coap_register_response_handler -coap_remove_async coap_resize_binary coap_resource_get_uri_path coap_resource_get_userdata diff --git a/man/Makefile.am b/man/Makefile.am index ade349ea..34580653 100644 --- a/man/Makefile.am +++ b/man/Makefile.am @@ -18,7 +18,8 @@ if BUILD_MANPAGES # building the manpages -TXT3 = coap_attribute.txt \ +TXT3 = coap_async.txt \ + coap_attribute.txt \ coap_block.txt \ coap_cache.txt \ coap_context.txt \ diff --git a/man/coap_async.txt.in b/man/coap_async.txt.in new file mode 100644 index 00000000..3e10f38f --- /dev/null +++ b/man/coap_async.txt.in @@ -0,0 +1,180 @@ +// -*- mode:doc; -*- +// vim: set syntax=asciidoc,tw=0: + +coap_async(3) +============= +:doctype: manpage +:man source: coap_async +:man version: @PACKAGE_VERSION@ +:man manual: libcoap Manual + +NAME +---- +coap_async, +coap_register_async, +coap_async_set_delay, +coap_find_async, +coap_free_async, +coap_async_set_app_data, +coap_async_get_app_data +- Work with CoAP async support + +SYNOPSIS +-------- +*#include * + +*coap_async_t *coap_register_async(coap_context_t *_context_, +coap_session_t *_session_, coap_pdu_t *_request_, coap_tick_t _delay_);* + +*void coap_async_set_delay(coap_async_t *_async_, coap_tick_t _delay_);* + +*void coap_free_async(coap_context_t *_context_, coap_async_t *_async_);* + +*coap_async_t *coap_find_async(coap_context_t *_context_, +coap_session_t *_session_, coap_mid_t _mid_);* + +*void coap_async_set_app_data(coap_async_t *_async_, void *_app_data_);* + +*void *coap_async_get_app_data(const coap_async_t *_async_);* + +For specific (D)TLS library support, link with +*-lcoap-@LIBCOAP_API_VERSION@-notls*, *-lcoap-@LIBCOAP_API_VERSION@-gnutls*, +*-lcoap-@LIBCOAP_API_VERSION@-openssl*, *-lcoap-@LIBCOAP_API_VERSION@-mbedtls* +or *-lcoap-@LIBCOAP_API_VERSION@-tinydtls*. Otherwise, link with +*-lcoap-@LIBCOAP_API_VERSION@* to get the default (D)TLS library support. + +DESCRIPTION +----------- +CoAP server responses can be piggybacked (RFC7252 5.2.1) or separate +(RFC7252 5.2.2). + +For piggybacked responses, the response packet contains both the status and +any data. + +For separate responses, there is an initial empty ACK response (Confirmable +only - to stop the client re-transmitting the request) followed at a later time +by the packet containing the status and any data. + +Usually responses are piggybacked, but this man page focuses on separate +(async) support. + +The *coap_register_async*() function is used to set up an asynchronous delayed +request for the _request_ PDU associated with the _context_ and _session_. The +application request handler will get called with a copy of _request_ after +_delay_ ticks which will then cause a response to be sent. If _delay_ is 0, +then the application request handler will not get called. + +The coap_async_set_delay*() function is used to update the reamining _delay_ +before the application request handler is called for the _async_ definition. If +_delay_ is set to 0, then the application request handler will not get called. + +The *coap_free_async*() function is used to delete an _async_ definition. + +The *coap_find_async*() function is used to determine if there is an async +definition based on the _context_, _session_ and message id _mid_. + +The *coap_async_set_app_data*() function is used to add in user defined +_app_data_ to the _async_ definition. It is the responsibility of the +application to release this data if appropriate. + +The *coap_async_get_app_data*() function is used to retrieve any defines +application data from the _async_ definition. + +RETURN VALUES +------------- + +*coap_register_async*() and *coap_find_async*() return a pointer to an async +definition or NULL if there is an error. + +*coap_async_get_app_data*() returns a pointer to the user defined data. + +EXAMPLES +-------- +*CoAP Server Non-Encrypted Setup* + +[source, c] +---- +#include + +/* + * This example is used to demonstrate how to set up and use a "separate" + * response (empty ACK followed by data response at a later stage). + */ +static void +hnd_get_with_delay(coap_context_t *context, + coap_resource_t *resource, + coap_session_t *session, + coap_pdu_t *request, + coap_binary_t *token, + coap_string_t *query, + coap_pdu_t *response) { + unsigned long delay = 5; + size_t size; + coap_async_t *async; + + /* + * See if this is the initial, or delayed request + */ + async = coap_find_async(context, session, request->mid); + if (!async) { + /* Set up an async request to trigger delay in the future */ + if (query) { + const uint8_t *p = query->s; + + delay = 0; + for (size = query->length; size; --size, ++p) + delay = delay * 10 + (*p - '0'); + if (delay == 0) { + coap_log(LOG_INFO, "async: delay of 0 not supported\n"); + response->code = COAP_RESPONSE_CODE_BAD_REQUEST; + return; + } + } + async = coap_register_async(context, + session, + request, + COAP_TICKS_PER_SECOND * delay); + if (async == NULL) { + response->code = COAP_RESPONSE_CODE_SERVICE_UNAVAILABLE; + return; + } + /* + * Not setting response code will cause empty ACK to be sent + * if Confirmable + */ + return; + } + /* async set up, so this is the delayed request */ + + /* Send back the appropriate data */ + coap_add_data_large_response(resource, session, request, response, token, + query, COAP_MEDIATYPE_TEXT_PLAIN, -1, 0, 4, + (const uint8_t *)"done", NULL, NULL); + response->code = COAP_RESPONSE_CODE_CONTENT; + + /* async is automatically removed by libcoap on return from this handler */ +} + +---- + +SEE ALSO +-------- +*coap_handler*(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/src/async.c b/src/async.c index 3cf13ac8..8b83b32f 100644 --- a/src/async.c +++ b/src/async.c @@ -26,80 +26,90 @@ } \ } while(0) -coap_async_state_t * +coap_async_t * coap_register_async(coap_context_t *context, coap_session_t *session, - coap_pdu_t *request, unsigned char flags, void *data) { - coap_async_state_t *s; - coap_mid_t id = request->mid; + coap_pdu_t *request, coap_tick_t delay) { + coap_async_t *s; + coap_mid_t mid = request->mid; + size_t len; + uint8_t *data; - SEARCH_PAIR(context->async_state,s,session,session,id,id); + if (!COAP_PDU_IS_REQUEST(request)) + return NULL; + + SEARCH_PAIR(context->async_state,s,session,session,pdu->mid,mid); if (s != NULL) { - /* We must return NULL here as the caller must know that he is - * responsible for releasing @p data. */ coap_log(LOG_DEBUG, - "asynchronous state for mid=0x%x already registered\n", id); + "asynchronous state for mid=0x%x already registered\n", mid); return NULL; } /* store information for handling the asynchronous task */ - s = (coap_async_state_t *)coap_malloc(sizeof(coap_async_state_t)); + s = (coap_async_t *)coap_malloc(sizeof(coap_async_t)); if (!s) { coap_log(LOG_CRIT, "coap_register_async: insufficient memory\n"); return NULL; } - memset(s, 0, sizeof(coap_async_state_t)); + memset(s, 0, sizeof(coap_async_t)); - /* set COAP_ASYNC_CONFIRM according to request's type */ - s->flags = flags & ~COAP_ASYNC_CONFIRM; - if (request->type == COAP_MESSAGE_CON) - s->flags |= COAP_ASYNC_CONFIRM; + s->pdu = coap_pdu_duplicate(request, session, request->token_length, + request->token, NULL); + if (s->pdu == NULL) { + coap_free_async(context, s); + coap_log(LOG_CRIT, "coap_register_async: insufficient memory\n"); + return NULL; + } + s->pdu->mid = mid; /* coap_pdu_duplicate() created one */ - s->appdata = data; - s->session = coap_session_reference( session ); - s->id = id; - - if (request->token_length) { - /* A token can be up to 8 bytes */ - s->tokenlen = (request->token_length > 8) ? 8 : request->token_length; - memcpy(s->token, request->token, s->tokenlen); + if (coap_get_data(request, &len, &data)) { + coap_add_data(s->pdu, len, data); } - coap_touch_async(s); + s->session = coap_session_reference( session ); + + if (delay) { + coap_ticks(&s->delay); + s->delay += delay; + } LL_PREPEND(context->async_state, s); return s; } -coap_async_state_t * -coap_find_async(coap_context_t *context, coap_session_t *session, coap_mid_t id) { - coap_async_state_t *tmp; - SEARCH_PAIR(context->async_state,tmp,session,session,id,id); +void +coap_async_set_delay(coap_async_t *async, coap_tick_t delay) { + assert(async != NULL); + + if (delay) { + coap_ticks(&async->delay); + async->delay += delay; + } + else + async->delay = 0; +} + + +coap_async_t * +coap_find_async(coap_context_t *context, coap_session_t *session, + coap_mid_t mid) { + coap_async_t *tmp; + SEARCH_PAIR(context->async_state,tmp,session,session,pdu->mid,mid); return tmp; } -int -coap_remove_async(coap_context_t *context, coap_session_t *session, - coap_mid_t id, coap_async_state_t **s) { - coap_async_state_t *tmp = coap_find_async(context, session, id); - - if (tmp) - LL_DELETE(context->async_state,tmp); - - *s = tmp; - return tmp != NULL; -} - void -coap_free_async(coap_async_state_t *s) { +coap_free_async(coap_context_t *context, coap_async_t *s) { if (s) { + LL_DELETE(context->async_state,s); if (s->session) { coap_session_release(s->session); } - if ((s->flags & COAP_ASYNC_RELEASE_DATA) != 0) { - coap_free(s->appdata); + if (s->pdu) { + coap_delete_pdu(s->pdu); + s->pdu = NULL; } coap_free(s); } @@ -107,14 +117,24 @@ coap_free_async(coap_async_state_t *s) { void coap_delete_all_async(coap_context_t *context) { - coap_async_state_t *astate, *tmp; + coap_async_t *astate, *tmp; LL_FOREACH_SAFE(context->async_state, astate, tmp) { - coap_free_async(astate); + coap_free_async(context, astate); } context->async_state = NULL; } +void +coap_async_set_app_data(coap_async_t *async, void *app_data) { + async->appdata = app_data; +} + +void * +coap_async_get_app_data(const coap_async_t *async) { + return async->appdata; +} + #else void does_not_exist(void); /* make some compilers happy */ #endif /* WITHOUT_ASYNC */ diff --git a/src/coap_io.c b/src/coap_io.c index 46202e5e..803fef38 100644 --- a/src/coap_io.c +++ b/src/coap_io.c @@ -1065,6 +1065,7 @@ coap_io_prepare_io(coap_context_t *ctx, coap_session_t *s, *rtmp; coap_tick_t session_timeout; coap_tick_t timeout = 0; + coap_tick_t s_timeout; #ifdef COAP_EPOLL_SUPPORT (void)sockets; (void)max_sockets; @@ -1080,6 +1081,15 @@ coap_io_prepare_io(coap_context_t *ctx, else session_timeout = COAP_DEFAULT_SESSION_TIMEOUT * COAP_TICKS_PER_SECOND; +#ifndef WITHOUT_ASYNC + /* Check to see if we need to send off any Async requests */ + s_timeout = coap_check_async(ctx, now); + if (s_timeout) { + if (timeout == 0 || s_timeout < timeout) + timeout = s_timeout; + } +#endif /* WITHOUT_ASYNC */ + LL_FOREACH(ctx->endpoint, ep) { #ifndef COAP_EPOLL_SUPPORT if (ep->sock.flags & (COAP_SOCKET_WANT_READ | COAP_SOCKET_WANT_WRITE | COAP_SOCKET_WANT_ACCEPT)) { @@ -1095,13 +1105,12 @@ coap_io_prepare_io(coap_context_t *ctx, coap_session_free(s); } else { if (s->type == COAP_SESSION_TYPE_SERVER && s->ref == 0 && s->delayqueue == NULL) { - coap_tick_t s_timeout = (s->last_rx_tx + session_timeout) - now; + s_timeout = (s->last_rx_tx + session_timeout) - now; if (timeout == 0 || s_timeout < timeout) timeout = s_timeout; } /* Check if any server large receives have timed out */ if (s->lg_srcv) { - coap_tick_t s_timeout; s_timeout = coap_block_check_lg_srcv_timeouts(s, now); if (timeout == 0 || s_timeout < timeout) timeout = s_timeout; @@ -1121,7 +1130,6 @@ coap_io_prepare_io(coap_context_t *ctx, && s->state == COAP_SESSION_STATE_ESTABLISHED && ctx->ping_timeout > 0 ) { - coap_tick_t s_timeout; if (s->last_rx_tx + ctx->ping_timeout * COAP_TICKS_PER_SECOND <= now) { if ((s->last_ping > 0 && s->last_pong < s->last_ping) || ((s->last_ping_mid = coap_session_send_ping(s)) == COAP_INVALID_MID)) @@ -1146,7 +1154,6 @@ coap_io_prepare_io(coap_context_t *ctx, && s->state == COAP_SESSION_STATE_CSM && ctx->csm_timeout > 0 ) { - coap_tick_t s_timeout; if (s->csm_tx == 0) { s->csm_tx = now; } else if (s->csm_tx + ctx->csm_timeout * COAP_TICKS_PER_SECOND <= now) { @@ -1163,7 +1170,6 @@ coap_io_prepare_io(coap_context_t *ctx, /* Check if any client large receives have timed out */ if (s->lg_crcv) { - coap_tick_t s_timeout; s_timeout = coap_block_check_lg_crcv_timeouts(s, now); if (timeout == 0 || s_timeout < timeout) timeout = s_timeout; @@ -1438,9 +1444,15 @@ 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); +#endif /* COAP_EPOLL_SUPPORT */ coap_expire_cache_entries(ctx); coap_ticks(&now); -#endif /* COAP_EPOLL_SUPPORT */ +#ifndef WITHOUT_ASYNC + /* Check to see if we need to send off any Async requests as delay might + have been updated */ + coap_check_async(ctx, now); + coap_ticks(&now); +#endif /* WITHOUT_ASYNC */ #if COAP_CONSTRAINED_STACK coap_mutex_unlock(&static_mutex); diff --git a/src/net.c b/src/net.c index 43368306..df60bcbd 100644 --- a/src/net.c +++ b/src/net.c @@ -2492,6 +2492,23 @@ handle_request(coap_context_t *context, coap_session_t *session, coap_pdu_t *pdu int skip_hop_limit_check = 0; int resp; +#ifndef WITHOUT_ASYNC + /* Need to check for duplicate request in case of network issues */ + if (!COAP_PROTO_RELIABLE(session->proto) && pdu->type == COAP_MESSAGE_CON) { + coap_async_t *async = coap_find_async(context, session, pdu->mid); + + if (async) { + coap_tick_t now; + + coap_ticks(&now); + if (async->delay == 0 || async->delay > now) { + /* re-transmit missing ACK */ + coap_send_ack(session, pdu); + } + } + } +#endif /* WITHOUT_ASYNC */ + coap_option_filter_clear(&opt_filter); opt = coap_check_option(pdu, COAP_OPTION_PROXY_SCHEME, &opt_iter); if (opt) @@ -3144,6 +3161,28 @@ coap_can_exit(coap_context_t *context) { } return 1; } +#ifndef WITHOUT_ASYNC +coap_tick_t +coap_check_async(coap_context_t *context, coap_tick_t now) { + coap_tick_t next_due = 0; + coap_async_t *async, *tmp; + + LL_FOREACH_SAFE(context->async_state, async, tmp) { + if (async->delay <= now) { + /* Send off the request to the application */ + handle_request(context, async->session, async->pdu); + + /* Remove this async entry as it has now fired */ + coap_free_async(context, async); + } + else { + if (next_due == 0 || next_due > async->delay - now) + next_due = async->delay - now; + } + } + return next_due; +} +#endif /* WITHOUT_ASYNC */ static int coap_started = 0; From db2b7de91b76b1b1dfc240f9c5838b374ed2e4d4 Mon Sep 17 00:00:00 2001 From: Jon Shallow Date: Fri, 16 Apr 2021 16:09:17 +0100 Subject: [PATCH 2/2] Update --- man/coap_async.txt.in | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/man/coap_async.txt.in b/man/coap_async.txt.in index 3e10f38f..0737766a 100644 --- a/man/coap_async.txt.in +++ b/man/coap_async.txt.in @@ -64,10 +64,14 @@ application request handler will get called with a copy of _request_ after _delay_ ticks which will then cause a response to be sent. If _delay_ is 0, then the application request handler will not get called. -The coap_async_set_delay*() function is used to update the reamining _delay_ +The *coap_async_set_delay*() function is used to update the remaining _delay_ before the application request handler is called for the _async_ definition. If _delay_ is set to 0, then the application request handler will not get called. +An example of usage here is *coap_register_async*() sets _delay_ to 0, and +then when the response is ready at an indeterminate point in the future, +*coap_async_set_delay*() is called setting _delay_ to 1. + The *coap_free_async*() function is used to delete an _async_ definition. The *coap_find_async*() function is used to determine if there is an async