From b9803e69d12301f238cb865b2de08802fb04eb12 Mon Sep 17 00:00:00 2001 From: Kevin Easton Date: Thu, 27 Jun 2019 17:37:35 +1000 Subject: [PATCH] Avoid reading an uninitialized byte in dgets() This was caused by an off-by-one error in the case when a line exceeded the buffer size provided to dgets(). Found with valgrind. --- source/newio.c | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/source/newio.c b/source/newio.c index 2f638c5..83845cb 100644 --- a/source/newio.c +++ b/source/newio.c @@ -349,19 +349,16 @@ int BX_dgets (char *str, int des, int buffer, int buffersize, void *ssl_fd) /* * Slurp up the data that is available into 'str'. */ - while (ioe->read_pos < ioe->write_pos) + while (ioe->read_pos < ioe->write_pos && cnt < (buffersize - 1)) { - if (((str[cnt] = ioe->buffer[ioe->read_pos++])) == '\n') - break; - cnt++; - if (cnt >= buffersize-1) + if ((str[cnt++] = ioe->buffer[ioe->read_pos++]) == '\n') break; } /* * Terminate it */ - str[cnt + 1] = 0; + str[cnt] = 0; /* * If we end in a newline, then all is well. @@ -369,8 +366,8 @@ int BX_dgets (char *str, int des, int buffer, int buffersize, void *ssl_fd) * The caller then would need to do a strlen() to get * the amount of data. */ - if (str[cnt] == '\n') - return cnt; + if (cnt > 0 && str[cnt - 1] == '\n') + return cnt - 1; else return 0; }