From 0eac97542d4700478389f00c6c34198348f050df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20H=C3=B6ppner?= Date: Wed, 23 Apr 2025 12:35:51 +0200 Subject: [PATCH] libutil/util_file: Handle over-read in util_file_read_fd() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In certain situations util_file_read_fd_buf() might return a larger buffer than printable characters were read (e.g. a file was padded with zeros). This can lead to util_file_read_fd() returning NULL with a freed buffer even though a certain amount of printable characters were read. This behaviour causes a regression introduced with commit 9efd1df31d9b ("ipl_tools: Refactor read helper using util_file_read_text_file()") in ipl_tools were the scp_data sysfs attribute is padded with 0 to fit an 8 byte alignment required by the architecture. Fix this by comparing the size read with the actual string length and use the smaller value for further processing. Fixes: 9efd1df31d9b ("ipl_tools: Refactor read helper using util_file_read_text_file()") Tested-by: Jan Polensky Reviewed-by: Jan Polensky Signed-off-by: Jan Höppner --- libutil/util_file.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/libutil/util_file.c b/libutil/util_file.c index 706c3675..9bba5579 100644 --- a/libutil/util_file.c +++ b/libutil/util_file.c @@ -616,6 +616,10 @@ char *util_file_read_fd(FILE *fd, int chomp) if (util_file_read_fd_buf(fd, (void **) &buffer, &done)) return NULL; + /* Prevent over-read if buffer is larger than amount of read characters */ + if (buffer) + done = MIN(done, strnlen(buffer, done)); + /* Check if this is a text file at all (required to filter out * binary sysfs attributes). */