From f28f4109ecd87929ad20f2c37b0abd9e304f8231 Mon Sep 17 00:00:00 2001 From: Jon Shallow Date: Thu, 12 Jun 2025 17:16:55 +0100 Subject: [PATCH] coap_check_async: Fix async callback timing window Multiple threads can call coap_check_async() when one of them does a callback into application space. Only allow one thread to be scanning async_state. --- include/coap3/coap_net_internal.h | 1 + src/coap_async.c | 23 ++++++++++++----------- src/coap_net.c | 4 ++++ 3 files changed, 17 insertions(+), 11 deletions(-) diff --git a/include/coap3/coap_net_internal.h b/include/coap3/coap_net_internal.h index d1e78a55..988a7da3 100644 --- a/include/coap3/coap_net_internal.h +++ b/include/coap3/coap_net_internal.h @@ -66,6 +66,7 @@ struct coap_context_t { /** * list of asynchronous message ids */ coap_async_t *async_state; + int async_state_traversing; /**< If hte async state list is being ttaversed */ #endif /* COAP_ASYNC_SUPPORT */ /** diff --git a/src/coap_async.c b/src/coap_async.c index b0f168f0..94a9f516 100644 --- a/src/coap_async.c +++ b/src/coap_async.c @@ -179,20 +179,21 @@ coap_find_async_lkd(coap_session_t *session, coap_bin_const_t token) { } static void -coap_free_async_sub(coap_context_t *context, coap_async_t *s) { - if (s) { - LL_DELETE(context->async_state,s); - if (s->session) { - coap_session_release_lkd(s->session); +coap_free_async_sub(coap_context_t *context, coap_async_t *async) { + if (async) { + LL_DELETE(context->async_state,async); + if (async->session) { + coap_session_release_lkd(async->session); + async->session = NULL; } - if (s->pdu) { - coap_delete_pdu_lkd(s->pdu); - s->pdu = NULL; + if (async->pdu) { + coap_delete_pdu_lkd(async->pdu); + async->pdu = NULL; } - if (s->app_cb && s->app_data) { - coap_lock_callback(s->app_cb(s->app_data)); + if (async->app_cb && async->app_data) { + coap_lock_callback(async->app_cb(async->app_data)); } - coap_free_type(COAP_STRING, s); + coap_free_type(COAP_STRING, async); } } diff --git a/src/coap_net.c b/src/coap_net.c index eeeab980..177e011e 100644 --- a/src/coap_net.c +++ b/src/coap_net.c @@ -4971,6 +4971,9 @@ coap_check_async(coap_context_t *context, coap_tick_t now, coap_tick_t *tim_rem) coap_async_t *async, *tmp; int ret = 0; + if (context->async_state_traversing) + return 0; + context->async_state_traversing = 1; LL_FOREACH_SAFE(context->async_state, async, tmp) { if (async->delay != 0) { if (async->delay <= now) { @@ -4989,6 +4992,7 @@ coap_check_async(coap_context_t *context, coap_tick_t now, coap_tick_t *tim_rem) } if (tim_rem) *tim_rem = next_due; + context->async_state_traversing = 0; return ret; } #endif /* COAP_ASYNC_SUPPORT */