From d9039ae0ff3f7929ede576058b3ad3e9c62a47c4 Mon Sep 17 00:00:00 2001 From: "Dmitry V. Levin" Date: Sat, 20 Oct 2007 22:08:40 +0400 Subject: [PATCH] Check fgets(3) return value When fgets() function fails, contents of the buffer is undefined. That is, fgets() return value needs to be checked, to avoid undefined behavior. Signed-off-by: Dmitry V. Levin Signed-off-by: Theodore Ts'o --- debugfs/debugfs.c | 9 ++++++--- lib/ext2fs/ismounted.c | 6 ++---- misc/util.c | 4 ++-- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/debugfs/debugfs.c b/debugfs/debugfs.c index 190c4b7b..d7016153 100644 --- a/debugfs/debugfs.c +++ b/debugfs/debugfs.c @@ -789,7 +789,8 @@ static void modify_u8(char *com, const char *prompt, sprintf(buf, format, *val); printf("%30s [%s] ", prompt, buf); - fgets(buf, sizeof(buf), stdin); + if (!fgets(buf, sizeof(buf), stdin)) + return; if (buf[strlen (buf) - 1] == '\n') buf[strlen (buf) - 1] = '\0'; if (!buf[0]) @@ -810,7 +811,8 @@ static void modify_u16(char *com, const char *prompt, sprintf(buf, format, *val); printf("%30s [%s] ", prompt, buf); - fgets(buf, sizeof(buf), stdin); + if (!fgets(buf, sizeof(buf), stdin)) + return; if (buf[strlen (buf) - 1] == '\n') buf[strlen (buf) - 1] = '\0'; if (!buf[0]) @@ -831,7 +833,8 @@ static void modify_u32(char *com, const char *prompt, sprintf(buf, format, *val); printf("%30s [%s] ", prompt, buf); - fgets(buf, sizeof(buf), stdin); + if (!fgets(buf, sizeof(buf), stdin)) + return; if (buf[strlen (buf) - 1] == '\n') buf[strlen (buf) - 1] = '\0'; if (!buf[0]) diff --git a/lib/ext2fs/ismounted.c b/lib/ext2fs/ismounted.c index 24246e0e..cb563fd1 100644 --- a/lib/ext2fs/ismounted.c +++ b/lib/ext2fs/ismounted.c @@ -251,10 +251,8 @@ static int is_swap_device(const char *file) if (!(f = fopen("/proc/swaps", "r"))) return 0; /* Skip the first line */ - fgets(buf, sizeof(buf), f); - while (!feof(f)) { - if (!fgets(buf, sizeof(buf), f)) - break; + if (fgets(buf, sizeof(buf), f)) + while (fgets(buf, sizeof(buf), f)) { if ((cp = strchr(buf, ' ')) != NULL) *cp = 0; if ((cp = strchr(buf, '\t')) != NULL) diff --git a/misc/util.c b/misc/util.c index 6a4c40cf..7c99a2a2 100644 --- a/misc/util.c +++ b/misc/util.c @@ -71,8 +71,8 @@ void proceed_question(void) fflush(stderr); fputs(_("Proceed anyway? (y,n) "), stdout); buf[0] = 0; - fgets(buf, sizeof(buf), stdin); - if (strchr(short_yes, buf[0]) == 0) + if (!fgets(buf, sizeof(buf), stdin) || + strchr(short_yes, buf[0]) == 0) exit(1); }