diff mbox series

[v2,2/2] scripts: mkhash fail on hashing a folder

Message ID 20200717081932.3745194-2-mail@aparcar.org
State Superseded
Headers show
Series [v2,1/2] scripts: mkhash fix return code handling | expand

Commit Message

Paul Spooren July 17, 2020, 8:19 a.m. UTC
mkhash currently returns the hash of an empty input when trying to hash
a folder. This can be missleading in caseswhere e.g. an env variable is
undefined which should contain a filename. `mkhash ./path/to/$FILE`
would exit with code 0 and return a legit looking checksum.

A better behaviour would be to fail with exit code 1, which imitates the
behaviour of `md5sum` and `sha256sum`.

To avoid hashing of folders the `stat()` is checked.

Hashing empty inputs result in the following checksums:
md5: d41d8cd98f00b204e9800998ecf8427e
sha256: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855

Signed-off-by: Paul Spooren <mail@aparcar.org>
---
 scripts/mkhash.c | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)
diff mbox series

Patch

diff --git a/scripts/mkhash.c b/scripts/mkhash.c
index ea3bd60ce1..13d50176c8 100644
--- a/scripts/mkhash.c
+++ b/scripts/mkhash.c
@@ -85,6 +85,7 @@ 
 #include <stdint.h>
 #include <stdbool.h>
 #include <unistd.h>
+#include <sys/stat.h>
 
 #define ARRAY_SIZE(_n) (sizeof(_n) / sizeof((_n)[0]))
 
@@ -770,7 +771,14 @@  static int hash_file(struct hash_type *t, const char *filename, bool add_filenam
 	if (!filename || !strcmp(filename, "-")) {
 		str = t->func(stdin);
 	} else {
-		FILE *f = fopen(filename, "r");
+		struct stat path_stat;
+		stat(filename, &path_stat);
+		if (S_ISDIR(path_stat.st_mode)) {
+			fprintf(stderr, "Failed to open '%s': Is a directory\n", filename);
+			return 1;
+		}
+
+		FILE *f = fopen(filename, "r+");
 
 		if (!f) {
 			fprintf(stderr, "Failed to open '%s'\n", filename);