cmogstored 1.8.1 - use default system stack size
[cmogstored.git] / bind_listen.c
blobc5d9d593525f4b58d3e38cb49cc967ba810f5c90
1 /*
2 * Copyright (C) 2012-2020 all contributors <cmogstored-public@yhbt.net>
3 * License: GPL-3.0+ <https://www.gnu.org/licenses/gpl-3.0.txt>
4 */
5 #include "cmogstored.h"
7 /*
8 * TODO
9 * - configurable socket buffer sizes (where to put config?)
10 * - configurable listen() backlog (where to put config?)
12 * TCP_DEFER_ACCEPT is probably not worth using on Linux
13 * ref:
14 * https://bugs.launchpad.net/ubuntu/+source/apache2/+bug/134274
15 * https://labs.apnic.net/blabs/?p=57
18 static int set_tcp_opts(int fd, bool inherited)
20 int val;
21 socklen_t len = sizeof(int);
22 int rc;
24 if (!inherited) {
25 val = 1;
26 rc = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, len);
27 if (rc < 0) return rc;
30 val = 1;
31 rc = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &val, len);
32 if (rc < 0) return rc;
34 val = 1;
35 rc = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, len);
36 if (rc < 0) return rc;
38 return rc;
41 int mog_bind_listen(struct addrinfo *r)
43 /* see if we inherited the socket, first */
44 int fd = mog_inherit_get(r->ai_addr, r->ai_addrlen);
45 const int backlog = 1024;
47 if (fd >= 0 &&
48 set_tcp_opts(fd, true) == 0 &&
49 listen(fd, backlog) == 0)
50 return fd;
52 for (; r; r = r->ai_next) {
53 fd = socket(r->ai_family, r->ai_socktype, r->ai_protocol);
54 if (fd < 0)
55 continue;
58 * We'll need to unset FD_CLOEXEC in the child for upgrades
59 * Leave FD_CLOEXEC set because we fork+exec iostat(1)
60 * frequently. We can't guarantee SOCK_CLOEXEC works
61 * everywhere yet (in 2012).
63 if (mog_set_cloexec(fd, true) == 0 &&
64 set_tcp_opts(fd, false) == 0 &&
65 bind(fd, r->ai_addr, r->ai_addrlen) == 0 &&
66 listen(fd, backlog) == 0)
67 break;
69 PRESERVE_ERRNO( mog_close(fd) );
70 fd = -1;
73 return fd;