From 73d8456dff6be06b33c5df594a3551269bbfc23b Mon Sep 17 00:00:00 2001 From: psychon Date: Tue, 1 Apr 2008 08:52:13 +0000 Subject: [PATCH] Mark all FDs as close-on-exec This marks all FDs which are valid after the function creating them returns as close-on-exec, so that processes started from ZNC (e.g. through the shell module) don't inherit a copy of all of our FDs. Csocket already does this for its FDs. git-svn-id: https://znc.svn.sourceforge.net/svnroot/znc/trunk@1004 726aef4b-f618-498e-8847-2d620e286838 --- FileUtils.cpp | 4 ++++ Utils.h | 14 +++++++++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/FileUtils.cpp b/FileUtils.cpp index 6b1998aa..73ab3e84 100644 --- a/FileUtils.cpp +++ b/FileUtils.cpp @@ -7,6 +7,7 @@ */ #include "FileUtils.h" +#include "Utils.h" #include #include #include @@ -251,6 +252,9 @@ bool CFile::Open(int iFlags, mode_t iMode) { if (m_iFD < 0) return false; + /* Make sure this FD isn't given to childs */ + SetFdCloseOnExec(m_iFD); + m_bClose = true; return true; } diff --git a/Utils.h b/Utils.h index 4a6d528e..3797761f 100644 --- a/Utils.h +++ b/Utils.h @@ -26,6 +26,15 @@ using std::vector; #define DEBUG_ONLY(f) ((void)0) #endif +static inline void SetFdCloseOnExec(int fd) +{ + int flags = fcntl(fd, F_GETFD, 0); + if (flags < 0) + return; // Ignore errors + // When we execve() a new process this fd is now automatically closed. + fcntl(fd, F_SETFD, flags | FD_CLOEXEC); +} + static const char g_HexDigits[] = "0123456789abcdef"; class CUtils { @@ -106,11 +115,14 @@ public: m_bCreated = false; if (m_fd == -1) { - // i must create the file then + // I must create the file then m_fd = open(sFile.c_str(), O_RDWR|O_CREAT, 0644); m_bCreated = true; } + // Thanks to broken POSIX, we shouldn't give this fd to anyone + SetFdCloseOnExec(m_fd); + m_pid = getpid(); // for destructor m_sFileName = sFile; }