From a648dbb0149513885eba4ced84ca9e1e65c6caca Mon Sep 17 00:00:00 2001 From: Jens Remus Date: Tue, 31 Jul 2018 21:21:56 +0200 Subject: [PATCH] zkey: enhance file read/write error handling MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fread()/fwrite() return the unsigned count of elements read/written or a short count or zero in case of an error. Check if the number of elements read/written matches the expectation. In case of fread(), if it does not match, check if an error occurred and otherwise assume the file to be too small. In case of fwrite(), if it does not match, assume an error. Resolves Cppcheck style warnings: [zkey/pkey.c:161]: (style) Checking if unsigned variable 'count' is less than zero. [zkey/pkey.c:209]: (style) Checking if unsigned variable 'count' is less than zero. [zkey/pkey.c:299]: (style) Checking if unsigned variable 'count' is less than zero. Cc: Ingo Franzki Signed-off-by: Jens Remus Reviewed-by: Ingo Franzki Reviewed-by: Jan Höppner Signed-off-by: Jan Höppner --- zkey/pkey.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/zkey/pkey.c b/zkey/pkey.c index fe43d02e..7c6411ae 100644 --- a/zkey/pkey.c +++ b/zkey/pkey.c @@ -158,8 +158,8 @@ u8 *read_secure_key(const char *keyfile, size_t *secure_key_size, buf = util_malloc(size); count = fread(buf, 1, size, fp); - if (count <= 0) { - msg = feof(fp) ? "File is too small" : strerror(errno); + if (count != size) { + msg = ferror(fp) ? strerror(errno) : "File is too small"; warnx("File '%s': %s", keyfile, msg); free(buf); buf = NULL; @@ -206,7 +206,7 @@ int write_secure_key(const char *keyfile, const u8 *secure_key, } count = fwrite(secure_key, 1, secure_key_size, fp); - if (count <= 0) { + if (count != secure_key_size) { warnx("File '%s': %s", keyfile, strerror(errno)); fclose(fp); return -EIO; @@ -296,8 +296,8 @@ static u8 *read_clear_key(const char *keyfile, size_t keybits, bool xts, buf = util_malloc(size); count = fread(buf, 1, size, fp); - if (count <= 0) { - msg = feof(fp) ? "File is too small" : strerror(errno); + if (count != size) { + msg = ferror(fp) ? strerror(errno) : "File is too small"; warnx("File '%s': %s", keyfile, msg); free(buf); buf = NULL;