From c8da4315943af77ba4daa54bfefb9734b355c63f Mon Sep 17 00:00:00 2001 From: Olaf Bergmann Date: Fri, 30 Aug 2019 16:55:23 +0200 Subject: [PATCH] coap_debug.c: Fix format truncation warning When COAP_DEBUG_BUF_SIZE is smaller than the buffer size for holding temporary strings in coap_show_pdu(), the compiler will emit a warning as snprintf() truncates the output string. Moreover, this will result in a missing terminating zero. This fix adjusts the temporary buffer size if COAP_DEBUG_BUF_SIZE is very small (i.e., on Contiki), and sets the last character in outbuf to \000 when necessary. --- src/coap_debug.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/coap_debug.c b/src/coap_debug.c index 2e01a7e6..91fa4085 100644 --- a/src/coap_debug.c +++ b/src/coap_debug.c @@ -466,10 +466,10 @@ void coap_show_pdu(coap_log_t level, const coap_pdu_t *pdu) { #if COAP_CONSTRAINED_STACK static coap_mutex_t static_show_pdu_mutex = COAP_MUTEX_INITIALIZER; - static unsigned char buf[1024]; /* need some space for output creation */ + static unsigned char buf[min(COAP_DEBUG_BUF_SIZE, 1024)]; /* need some space for output creation */ static char outbuf[COAP_DEBUG_BUF_SIZE]; #else /* ! COAP_CONSTRAINED_STACK */ - unsigned char buf[1024]; /* need some space for output creation */ + unsigned char buf[min(COAP_DEBUG_BUF_SIZE, 1024)]; /* need some space for output creation */ char outbuf[COAP_DEBUG_BUF_SIZE]; #endif /* ! COAP_CONSTRAINED_STACK */ size_t buf_len = 0; /* takes the number of bytes written to buf */ @@ -652,8 +652,11 @@ coap_show_pdu(coap_log_t level, const coap_pdu_t *pdu) { snprintf(&outbuf[outbuflen], sizeof(outbuf)-outbuflen, ">>"); } else { if (print_readable(data, data_len, buf, sizeof(buf), 0)) { + size_t max_length; outbuflen = strlen(outbuf); - snprintf(&outbuf[outbuflen], sizeof(outbuf)-outbuflen, "'%s'", buf); + max_length = sizeof(outbuf)-outbuflen; + if (snprintf(&outbuf[outbuflen], max_length, "'%s'", buf) >= (int)max_length) + outbuf[sizeof(outbuf)-1] = '\000'; } } }