summaryrefslogtreecommitdiff
path: root/src/ip.cpp
diff options
context:
space:
mode:
authorMartin Sustrik <sustrik@250bpm.com>2012-04-13 06:32:24 +0200
committerMartin Sustrik <sustrik@250bpm.com>2012-04-14 04:59:27 +0200
commitf34f71bbd5b9b00b295aa6438dd251845547225c (patch)
treee5a84ab763991bea17a0aa66ab2c11d12c340f06 /src/ip.cpp
parent048f8816f6bea585b092b528b9da648a32a9c94c (diff)
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 <sustrik@250bpm.com>
Diffstat (limited to 'src/ip.cpp')
-rw-r--r--src/ip.cpp31
1 files changed, 21 insertions, 10 deletions
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;
}