9 #include <sys/socket.h>
12 #include "serverpool.h"
17 extern ServerPool *servers;
18 extern volatile bool hupped;
20 int create_server_socket(int port, SocketType socket_type)
23 if (socket_type == TCP_SOCKET) {
24 server_sock = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP);
26 assert(socket_type == UDP_SOCKET);
27 server_sock = socket(PF_INET6, SOCK_DGRAM, IPPROTO_UDP);
29 if (server_sock == -1) {
35 if (setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) == -1) {
36 perror("setsockopt(SO_REUSEADDR)");
40 // We want dual-stack sockets. (Sorry, OpenBSD and Windows XP...)
42 if (setsockopt(server_sock, IPPROTO_IPV6, IPV6_V6ONLY, &zero, sizeof(zero)) == -1) {
43 perror("setsockopt(IPV6_V6ONLY)");
47 // Set as non-blocking, so the acceptor thread can notice that we want to shut it down.
48 if (ioctl(server_sock, FIONBIO, &one) == -1) {
49 perror("ioctl(FIONBIO)");
54 memset(&addr, 0, sizeof(addr));
55 addr.sin6_family = AF_INET6;
56 addr.sin6_port = htons(port);
58 if (bind(server_sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == -1) {
63 if (socket_type == TCP_SOCKET) {
64 if (listen(server_sock, 128) == -1) {
73 Acceptor::Acceptor(int server_sock, int port)
74 : server_sock(server_sock),
79 Acceptor::Acceptor(const AcceptorProto &serialized)
80 : server_sock(serialized.server_sock()),
81 port(serialized.port())
85 AcceptorProto Acceptor::serialize() const
87 AcceptorProto serialized;
88 serialized.set_server_sock(server_sock);
89 serialized.set_port(port);
93 void Acceptor::close_socket()
97 ret = close(server_sock);
98 } while (ret == -1 && errno == EINTR);
105 void Acceptor::do_work()
108 // Since we are non-blocking, we need to wait for the right state first.
109 // Wait up to 50 ms, then check hupped.
111 pfd.fd = server_sock;
114 int nfds = poll(&pfd, 1, 50);
115 if (nfds == 0 || (nfds == -1 && errno == EINTR)) {
125 socklen_t addrlen = sizeof(addr);
128 int sock = accept(server_sock, reinterpret_cast<sockaddr *>(&addr), &addrlen);
129 if (sock == -1 && errno == EINTR) {
138 // Set the socket as nonblocking.
140 if (ioctl(sock, FIONBIO, &one) == -1) {
145 // Pick a server, round-robin, and hand over the socket to it.
146 servers->add_client(sock);