Skip to content

Commit da101fe

Browse files
committed
src: remap invalid file descriptors using dup2
When checking for the validity of the stdio file descriptors (nodejs#875), ones which don't exist are intended to be remapped to /dev/null (and, if that doesn't work, we abort). This however doesn't work on all platforms and in all cases (e.g. /dev/null could already have been opened by the acting process and not actually be mapped to the expected file descriptor); instead, use the `dup2` syscall as a more robust solution (conforms to POSIX.1). Fixes: nodejs/help#2411 Refs: nodejs#875
1 parent 63aba56 commit da101fe

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

src/node.cc

+18-2
Original file line numberDiff line numberDiff line change
@@ -608,11 +608,27 @@ static void PlatformInit(ProcessInitializationFlags::Flags flags) {
608608
for (auto& s : stdio) {
609609
const int fd = &s - stdio;
610610
if (fstat(fd, &s.stat) == 0) continue;
611+
611612
// Anything but EBADF means something is seriously wrong. We don't
612613
// have to special-case EINTR, fstat() is not interruptible.
613614
if (errno != EBADF) ABORT();
614-
if (fd != open("/dev/null", O_RDWR)) ABORT();
615-
if (fstat(fd, &s.stat) != 0) ABORT();
615+
616+
// If EBADF (file descriptor doesn't exist), open /dev/null and duplicate
617+
// its file descriptor to the invalid file descriptor. Make sure *that*
618+
// file descriptor is valid. POSIX doesn't guarantee the next file
619+
// descriptor open(2) gives us is the lowest available number anymore in
620+
// POSIX.1-2017, which is why dup2(2) is needed.
621+
const int null_fd = open("/dev/null", O_RDWR);
622+
if (null_fd != fd) {
623+
if (dup2(null_fd, fd) < 0) {
624+
close(null_fd);
625+
ABORT();
626+
}
627+
close(null_fd);
628+
}
629+
630+
if (fstat(fd, &s.stat) == 0) continue;
631+
ABORT();
616632
}
617633
}
618634

0 commit comments

Comments
 (0)