Set close-on-exec flag to prevent fd leakage for command execution

This commit is contained in:
Hiroki Noda 2017-12-16 09:55:06 +09:00 committed by Sönke Ludwig
parent 107f4c084f
commit b252c97012

View file

@ -25,6 +25,8 @@ version (linux) {
extern (C) int accept4(int sockfd, sockaddr *addr, socklen_t *addrlen, int flags) nothrow @nogc; extern (C) int accept4(int sockfd, sockaddr *addr, socklen_t *addrlen, int flags) nothrow @nogc;
static if (!is(typeof(SOCK_NONBLOCK))) static if (!is(typeof(SOCK_NONBLOCK)))
enum SOCK_NONBLOCK = 0x800; enum SOCK_NONBLOCK = 0x800;
static if (!is(typeof(SOCK_CLOEXEC)))
enum SOCK_CLOEXEC = 0x80000;
static if (__VERSION__ < 2077) static if (__VERSION__ < 2077)
{ {
@ -230,12 +232,13 @@ final class PosixEventDriverSockets(Loop : PosixEventLoop) : EventDriverSockets
sockaddr_storage addr; sockaddr_storage addr;
socklen_t addr_len = addr.sizeof; socklen_t addr_len = addr.sizeof;
version (linux) { version (linux) {
() @trusted { sockfd = accept4(cast(sock_t)listenfd, () @trusted { return cast(sockaddr*)&addr; } (), &addr_len, SOCK_NONBLOCK); } (); () @trusted { sockfd = accept4(cast(sock_t)listenfd, () @trusted { return cast(sockaddr*)&addr; } (), &addr_len, SOCK_NONBLOCK | SOCK_CLOEXEC); } ();
if (sockfd == -1) return; if (sockfd == -1) return;
} else { } else {
() @trusted { sockfd = accept(cast(sock_t)listenfd, () @trusted { return cast(sockaddr*)&addr; } (), &addr_len); } (); () @trusted { sockfd = accept(cast(sock_t)listenfd, () @trusted { return cast(sockaddr*)&addr; } (), &addr_len); } ();
if (sockfd == -1) return; if (sockfd == -1) return;
setSocketNonBlocking(cast(SocketFD)sockfd); setSocketNonBlocking(cast(SocketFD)sockfd);
setSocketCloseOnExec(cast(SocketFD)sockfd);
} }
auto fd = cast(StreamSocketFD)sockfd; auto fd = cast(StreamSocketFD)sockfd;
m_loop.initFD(fd, FDFlags.none); m_loop.initFD(fd, FDFlags.none);
@ -927,6 +930,13 @@ private void setSocketNonBlocking(SocketFD sockfd)
} }
} }
private void setSocketCloseOnExec(SocketFD sockfd)
@nogc nothrow {
version (Windows) {} else {
() @trusted { fcntl(cast(int)sockfd, F_SETFL, O_CLOEXEC, 1); } ();
}
}
private int getSocketError() private int getSocketError()
@nogc nothrow { @nogc nothrow {
version (Windows) return WSAGetLastError(); version (Windows) return WSAGetLastError();