From f34f71bbd5b9b00b295aa6438dd251845547225c Mon Sep 17 00:00:00 2001 From: Martin Sustrik Date: Fri, 13 Apr 2012 06:32:24 +0200 Subject: Set options on new sockets in systematic manner This patch consolidates the up-to-now scattered code that sets different options on newly created sockets. There are open_socket and open_tcp_socket functions that do the tuning automatically. In case the socket is not created but got from elsewhere (such as accept() call) there are tune_socket and tune_tcp_socket functions that will do the tuning. Signed-off-by: Martin Sustrik --- src/ip.cpp | 31 +++++++++++++++++++++---------- 1 file changed, 21 insertions(+), 10 deletions(-) (limited to 'src/ip.cpp') diff --git a/src/ip.cpp b/src/ip.cpp index e11ec45..a54d75e 100644 --- a/src/ip.cpp +++ b/src/ip.cpp @@ -46,24 +46,35 @@ xs::fd_t xs::open_socket (int domain_, int type_, int protocol_) #endif fd_t s = socket (domain_, type_, protocol_); - if (s == retired_fd) + if (s == retired_fd) { +#ifdef XS_HAVE_WINDOWS + wsa_error_to_errno (); +#endif return retired_fd; + } + tune_socket (s); + return s; +} - // If there's no SOCK_CLOEXEC, let's try the second best option. Note that - // race condition can cause socket not to be closed (if fork happens - // between socket creation and this point). -#if !defined XS_HAVE_SOCK_CLOEXEC && defined FD_CLOEXEC - int rc = fcntl (s, F_SETFD, FD_CLOEXEC); +void xs::tune_socket (fd_t s_) +{ + // Prevent socket to be inherited by child processes. +#if defined FD_CLOEXEC + int rc = fcntl (s_, F_SETFD, FD_CLOEXEC); errno_assert (rc != -1); #endif - - // On Windows, preventing sockets to be inherited by child processes is - // done using SetHandleInformation function. #if defined XS_HAVE_WINDOWS && defined HANDLE_FLAG_INHERIT - BOOL brc = SetHandleInformation ((HANDLE) s, HANDLE_FLAG_INHERIT, 0); + BOOL brc = SetHandleInformation ((HANDLE) s_, HANDLE_FLAG_INHERIT, 0); win_assert (brc); #endif +} +xs::fd_t xs::open_tcp_socket (int domain_, bool keepalive_) +{ + fd_t s = open_socket (domain_, SOCK_STREAM, IPPROTO_TCP); + if (s == retired_fd) + return retired_fd; + tune_tcp_socket (s, keepalive_); return s; } -- cgit v1.2.3