From 2c93dc9c3b31eae0e7e1dae775a20d1e3dcb6dc4 Mon Sep 17 00:00:00 2001 From: Marian Buschsieweke Date: Mon, 4 Nov 2024 13:23:24 +0100 Subject: [PATCH] sys/net/nanocoap: fix coap_build_reply_header() In case no payload is added, `coap_build_reply_header()` would return `sizeof(coap_hdr_t) + token_length` regardless of the actual header length returned by `coap_build_hdr()`. These can be different if RFC 8974 extended tokens are enabled (module `nanocoap_token_ext` used): If an extended token length field is used, its size is not considered. Co-authored-by: benpicco --- sys/net/application_layer/nanocoap/nanocoap.c | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/sys/net/application_layer/nanocoap/nanocoap.c b/sys/net/application_layer/nanocoap/nanocoap.c index 06d70a918a..929ff50980 100644 --- a/sys/net/application_layer/nanocoap/nanocoap.c +++ b/sys/net/application_layer/nanocoap/nanocoap.c @@ -558,6 +558,13 @@ ssize_t coap_build_reply_header(coap_pkt_t *pkt, unsigned code, ? COAP_TYPE_ACK : COAP_TYPE_NON; + if (IS_USED(MODULE_NANOCOAP_TOKEN_EXT)) { + /* Worst case: 2 byte extended token length field. + * See https://www.rfc-editor.org/rfc/rfc8974#name-extended-token-length-tkl-f + */ + hdr_len += 2; + } + if (hdr_len > len) { return -ENOBUFS; } @@ -585,6 +592,13 @@ ssize_t coap_build_reply_header(coap_pkt_t *pkt, unsigned code, } } + if (IS_USED(MODULE_NANOCOAP_TOKEN_EXT)) { + /* we need to update the header length with the actual one, as we may + * have used less bytes for the extended token length fields as our + * worst case assumption */ + hdr_len = bufpos - (uint8_t *)buf; + } + if (payload) { if (ct >= 0) { bufpos += coap_put_option_ct(bufpos, 0, ct);