9 #include <sys/socket.h>
12 #include "serverpool.h"
16 extern ServerPool *servers;
17 extern volatile bool hupped;
19 int create_server_socket(int port)
21 int server_sock = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP);
22 if (server_sock == -1) {
28 if (setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) == -1) {
29 perror("setsockopt(SO_REUSEADDR)");
33 // We want dual-stack sockets. (Sorry, OpenBSD and Windows XP...)
35 if (setsockopt(server_sock, IPPROTO_IPV6, IPV6_V6ONLY, &zero, sizeof(zero)) == -1) {
36 perror("setsockopt(IPV6_V6ONLY)");
40 // Set as non-blocking, so the acceptor thread can notice that we want to shut it down.
41 if (ioctl(server_sock, FIONBIO, &one) == -1) {
42 perror("ioctl(FIONBIO)");
47 memset(&addr, 0, sizeof(addr));
48 addr.sin6_family = AF_INET6;
49 addr.sin6_port = htons(port);
51 if (bind(server_sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == -1) {
56 if (listen(server_sock, 128) == -1) {
64 AcceptorThread::AcceptorThread(int server_sock)
65 : server_sock(server_sock)
69 void AcceptorThread::do_work()
72 // Since we are non-blocking, we need to wait for the right state first.
73 // Wait up to 50 ms, then check hupped.
78 int nfds = poll(&pfd, 1, 50);
79 if (nfds == 0 || (nfds == -1 && errno == EINTR)) {
89 socklen_t addrlen = sizeof(addr);
92 int sock = accept(server_sock, reinterpret_cast<sockaddr *>(&addr), &addrlen);
93 if (sock == -1 && errno == EINTR) {
102 // Set the socket as nonblocking.
104 if (ioctl(sock, FIONBIO, &one) == -1) {
109 // Pick a server, round-robin, and hand over the socket to it.
110 servers->add_client(sock);