Subject: Eliminate toctou by using fstat and always opening with non-blocking i/o Origin: FILE5_34-17-g54bec4a0 Upstream-Author: Christos Zoulas Date: Wed Aug 1 10:07:00 2018 +0000 Found by coverity. --- a/src/file.h +++ b/src/file.h @@ -597,6 +597,9 @@ #ifndef O_BINARY #define O_BINARY 0 #endif +#ifndef O_NONBLOCK +#define O_NONBLOCK 0 +#endif #ifndef __cplusplus #if defined(__GNUC__) && (__GNUC__ >= 3) --- a/src/magic.c +++ b/src/magic.c @@ -442,18 +442,12 @@ else pos = lseek(fd, (off_t)0, SEEK_CUR); } else { - int flags = O_RDONLY|O_BINARY; - int okstat = stat(inname, &sb) == 0; - - if (okstat && S_ISFIFO(sb.st_mode)) { -#ifdef O_NONBLOCK - flags |= O_NONBLOCK; -#endif - ispipe = 1; - } - + int flags = O_RDONLY|O_BINARY|O_NONBLOCK; errno = 0; if ((fd = open(inname, flags)) < 0) { + int okstat = fstat(fd, &sb) == 0; + if (okstat && S_ISFIFO(sb.st_mode)) + ispipe = 1; #ifdef WIN32 /* * Can't stat, can't open. It may have been opened in