3 #include <netinet/in.h>
8 #include <sys/socket.h>
13 #include "serverpool.h"
19 extern ServerPool *servers;
21 int create_server_socket(int port, SocketType socket_type)
24 if (socket_type == TCP_SOCKET) {
25 server_sock = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP);
27 assert(socket_type == UDP_SOCKET);
28 server_sock = socket(PF_INET6, SOCK_DGRAM, IPPROTO_UDP);
30 if (server_sock == -1) {
36 if (setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) == -1) {
37 log_perror("setsockopt(SO_REUSEADDR)");
41 // We want dual-stack sockets. (Sorry, OpenBSD and Windows XP...)
43 if (setsockopt(server_sock, IPPROTO_IPV6, IPV6_V6ONLY, &zero, sizeof(zero)) == -1) {
44 log_perror("setsockopt(IPV6_V6ONLY)");
48 // Set as non-blocking, so the acceptor thread can notice that we want to shut it down.
49 if (ioctl(server_sock, FIONBIO, &one) == -1) {
50 log_perror("ioctl(FIONBIO)");
55 memset(&addr, 0, sizeof(addr));
56 addr.sin6_family = AF_INET6;
57 addr.sin6_port = htons(port);
59 if (bind(server_sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == -1) {
64 if (socket_type == TCP_SOCKET) {
65 if (listen(server_sock, 128) == -1) {
74 Acceptor::Acceptor(int server_sock, int port)
75 : server_sock(server_sock),
80 Acceptor::Acceptor(const AcceptorProto &serialized)
81 : server_sock(serialized.server_sock()),
82 port(serialized.port())
86 AcceptorProto Acceptor::serialize() const
88 AcceptorProto serialized;
89 serialized.set_server_sock(server_sock);
90 serialized.set_port(port);
94 void Acceptor::close_socket()
96 safe_close(server_sock);
99 void Acceptor::do_work()
101 while (!should_stop()) {
102 if (!wait_for_activity(server_sock, POLLIN, NULL)) {
107 socklen_t addrlen = sizeof(addr);
110 int sock = accept(server_sock, reinterpret_cast<sockaddr *>(&addr), &addrlen);
111 if (sock == -1 && errno == EINTR) {
115 log_perror("accept");
120 // Set the socket as nonblocking.
122 if (ioctl(sock, FIONBIO, &one) == -1) {
123 log_perror("FIONBIO");
127 // Pick a server, round-robin, and hand over the socket to it.
128 servers->add_client(sock);