From a141e442b0300e306ddf4a5b1b358a20584b39ed Mon Sep 17 00:00:00 2001 From: Jon Shallow Date: Wed, 29 Nov 2023 12:14:10 +0000 Subject: [PATCH] coap_block.c: Handle incorrect SZX changes for Block2 --- src/coap_block.c | 47 ++++++++++++++++++++++++++++++----------------- 1 file changed, 30 insertions(+), 17 deletions(-) diff --git a/src/coap_block.c b/src/coap_block.c index 5fe6544f..2e4b6b9a 100644 --- a/src/coap_block.c +++ b/src/coap_block.c @@ -2366,24 +2366,30 @@ coap_handle_request_send_block(coap_session_t *session, 1 << (block.szx + 4), block.num, block.m); } if (block.bert == 0 && block.szx != p->blk_size) { - if ((p->offset + chunk) % ((size_t)1 << (block.szx + 4)) == 0) { - /* - * Recompute the block number of the previous packet given - * the new block size - */ - block.num = (uint32_t)(((p->offset + chunk) >> (block.szx + 4)) - 1); - p->blk_size = block.szx; - chunk = (size_t)1 << (p->blk_size + 4); - p->offset = block.num * chunk; - coap_log_debug("new Block size is %u, block number %u completed\n", - 1 << (block.szx + 4), block.num); + if (block.num == 0) { + if ((p->offset + chunk) % ((size_t)1 << (block.szx + 4)) == 0) { + /* + * Recompute the block number of the previous packet given + * the new block size + */ + block.num = (uint32_t)(((p->offset + chunk) >> (block.szx + 4)) - 1); + p->blk_size = block.szx; + chunk = (size_t)1 << (p->blk_size + 4); + p->offset = block.num * chunk; + coap_log_debug("new Block size is %u, block number %u completed\n", + 1 << (block.szx + 4), block.num); + } else { + coap_log_debug("ignoring request to increase Block size, " + "next block is not aligned on requested block size " + "boundary. (%zu x %u mod %u = %zu (which is not 0)\n", + p->offset/chunk + 1, (1 << (p->blk_size + 4)), + (1 << (block.szx + 4)), + (p->offset + chunk) % ((size_t)1 << (block.szx + 4))); + } } else { - coap_log_debug("ignoring request to increase Block size, " - "next block is not aligned on requested block size " - "boundary. (%zu x %u mod %u = %zu (which is not 0)\n", - p->offset/chunk + 1, (1 << (p->blk_size + 4)), - (1 << (block.szx + 4)), - (p->offset + chunk) % ((size_t)1 << (block.szx + 4))); + coap_log_debug("ignoring request to change Block size from %u to %u\n", + (1 << (p->blk_size + 4)), (1 << (block.szx + 4))); + block.szx = block.aszx = p->blk_size; } } } @@ -3546,6 +3552,13 @@ coap_handle_response_get_block(coap_context_t *context, block.chunk_size, length); length = block.chunk_size; } + if (block.m && length != block.chunk_size) { + coap_log_warn("block: Undersized packet - expected %"PRIu32", got %zu\n", + block.chunk_size, length); + /* Unclear how to properly handle this */ + rcvd->code = COAP_RESPONSE_CODE(402); + goto expire_lg_crcv; + } /* Possibility that Size2 not sent, or is too small */ chunk = (size_t)1 << (block.szx + 4); offset = block.num * chunk;