]> git.sesse.net Git - cubemap/blobdiff - acceptor.cpp
Set close-on-exec on all file descriptors we open.
[cubemap] / acceptor.cpp
index b3cd3c1bd92824d27840ef52a04b95bed22e5c62..8bc16ed846d8f23870779682ffd7118486259e2a 100644 (file)
@@ -1,5 +1,6 @@
 #include <assert.h>
 #include <errno.h>
+#include <fcntl.h>
 #include <netinet/in.h>
 #include <netinet/tcp.h>
 #include <poll.h>
@@ -24,10 +25,10 @@ int create_server_socket(const sockaddr_in6 &addr, SocketType socket_type)
        // NOTE: We set as non-blocking, so the acceptor thread can notice that we want to shut it down.
        int server_sock;
        if (socket_type == TCP_SOCKET) {
-               server_sock = socket(PF_INET6, SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP);
+               server_sock = socket(PF_INET6, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, IPPROTO_TCP);
        } else {
                assert(socket_type == UDP_SOCKET);
-               server_sock = socket(PF_INET6, SOCK_DGRAM | SOCK_NONBLOCK, IPPROTO_UDP);
+               server_sock = socket(PF_INET6, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, IPPROTO_UDP);
        }
        if (server_sock == -1) {
                log_perror("socket");
@@ -101,10 +102,17 @@ Acceptor::Acceptor(const AcceptorProto &serialized)
          certificate_chain(serialized.certificate_chain()),
          private_key(serialized.private_key())
 {
+       // Set back the close-on-exec flag for the socket.
+       // (This can't leak into a child, since we haven't been started yet.)
+       fcntl(server_sock, F_SETFD, 1);
 }
 
 AcceptorProto Acceptor::serialize() const
 {
+       // Unset the close-on-exec flag for the socket.
+       // (This can't leak into a child, since there's only one thread left.)
+       fcntl(server_sock, F_SETFD, 0);
+
        char buf[INET6_ADDRSTRLEN];
        inet_ntop(addr.sin6_family, &addr.sin6_addr, buf, sizeof(buf));
 
@@ -133,7 +141,7 @@ void Acceptor::do_work()
                socklen_t addrlen = sizeof(addr);
 
                // Get a new socket, and set it as nonblocking.
-               int sock = accept4(server_sock, reinterpret_cast<sockaddr *>(&addr), &addrlen, SOCK_NONBLOCK);
+               int sock = accept4(server_sock, reinterpret_cast<sockaddr *>(&addr), &addrlen, SOCK_NONBLOCK | SOCK_CLOEXEC);
                if (sock == -1 && errno == EINTR) {
                        continue;
                }