8 #include <sys/socket.h>
11 #include "serverpool.h"
15 extern ServerPool *servers;
16 extern volatile bool hupped;
18 int create_server_socket(int port)
20 int server_sock = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP);
21 if (server_sock == -1) {
27 if (setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) == -1) {
28 perror("setsockopt(SO_REUSEADDR)");
32 // We want dual-stack sockets. (Sorry, OpenBSD and Windows XP...)
34 if (setsockopt(server_sock, IPPROTO_IPV6, IPV6_V6ONLY, &zero, sizeof(zero)) == -1) {
35 perror("setsockopt(IPV6_V6ONLY)");
39 // Set as non-blocking, so the acceptor thread can notice that we want to shut it down.
40 if (ioctl(server_sock, FIONBIO, &one) == -1) {
41 perror("ioctl(FIONBIO)");
46 memset(&addr, 0, sizeof(addr));
47 addr.sin6_family = AF_INET6;
48 addr.sin6_port = htons(port);
50 if (bind(server_sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == -1) {
55 if (listen(server_sock, 128) == -1) {
63 void *acceptor_thread_run(void *arg)
65 int server_sock = int(intptr_t(arg));
67 // Since we are non-blocking, we need to wait for the right state first.
68 // Wait up to 50 ms, then check hupped.
73 int nfds = poll(&pfd, 1, 50);
74 if (nfds == 0 || (nfds == -1 && errno == EINTR)) {
84 socklen_t addrlen = sizeof(addr);
87 int sock = accept(server_sock, reinterpret_cast<sockaddr *>(&addr), &addrlen);
88 if (sock == -1 && errno == EINTR) {
97 // Set the socket as nonblocking.
99 if (ioctl(sock, FIONBIO, &one) == -1) {
104 // Pick a server, round-robin, and hand over the socket to it.
105 servers->add_client(sock);