From ff173047f45680b9281a476f8678be422ed1b253 Mon Sep 17 00:00:00 2001 From: peteee Date: Fri, 13 Dec 2024 00:20:44 -0500 Subject: [PATCH] file/open: check if directory Adds fstat() directory test after fopen(), which can return non-NULL when passed a directory name on Linux --- src/core/io.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/core/io.c b/src/core/io.c index adbc9385..2b8e06af 100644 --- a/src/core/io.c +++ b/src/core/io.c @@ -31,6 +31,7 @@ #ifndef JANET_WINDOWS #include +#include #include #include #endif @@ -164,6 +165,14 @@ JANET_CORE_FN(cfun_io_fopen, } FILE *f = fopen((const char *)fname, (const char *)fmode); if (f != NULL) { +#ifndef JANET_WINDOWS + struct stat st; + fstat(f->_fileno, &st); + if (S_ISDIR(st.st_mode)) { + fclose(f); + janet_panicf("cannot open directory: %s", fname); + } +#endif size_t bufsize = janet_optsize(argv, argc, 2, BUFSIZ); if (bufsize != BUFSIZ) { int result = setvbuf(f, NULL, bufsize ? _IOFBF : _IONBF, bufsize);