Switch over to more modern unix sharedmemory API (requested by fatbob)
[umurmur.git] / src / server.c
1 /* Copyright (C) 2009-2014, Martin Johansson <martin@fatbob.nu>
2    Copyright (C) 2005-2014, Thorvald Natvig <thorvald@natvig.com>
3
4    All rights reserved.
5
6    Redistribution and use in source and binary forms, with or without
7    modification, are permitted provided that the following conditions
8    are met:
9
10    - Redistributions of source code must retain the above copyright notice,
11      this list of conditions and the following disclaimer.
12    - Redistributions in binary form must reproduce the above copyright notice,
13      this list of conditions and the following disclaimer in the documentation
14      and/or other materials provided with the distribution.
15    - Neither the name of the Developers nor the names of its contributors may
16      be used to endorse or promote products derived from this software without
17      specific prior written permission.
18
19    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20    ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22    A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23    CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25    PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 */
31 #include <stdio.h>
32 #include <sys/time.h>
33 #include <sys/poll.h>
34 #include <netinet/tcp.h>
35 #include <sys/socket.h>
36 #include <errno.h>
37 #include <string.h>
38 #include <limits.h>
39 #include <unistd.h>
40 #include <fcntl.h>
41 #include <errno.h>
42 #include <stdlib.h>
43
44 #include "client.h"
45 #include "conf.h"
46 #include "log.h"
47 #include "timer.h"
48 #include "version.h"
49 #include "util.h"
50
51 /* globals */
52 bool_t shutdown_server;
53 extern char *bindaddr;
54 extern char *bindaddr6;
55 extern int bindport;
56 extern int bindport6;
57 int* udpsocks;
58 bool_t hasv4 = true, hasv6 = true;
59
60 const int on = 1;
61 int nofServerSocks = 4;
62
63 /* Check which IP versions are supported by the system. */
64 void checkIPversions()
65 {
66         int testsocket = -1;
67
68         testsocket = socket(PF_INET, SOCK_STREAM, 0);
69         hasv4 = (errno == EAFNOSUPPORT) ? false : true;
70         if (!(testsocket < 0)) close(testsocket);
71
72         testsocket = socket(PF_INET6, SOCK_STREAM, 0);
73         hasv6 = (errno == EAFNOSUPPORT) ? false : true;
74         if (!(testsocket < 0)) close(testsocket);
75
76         if(!hasv4)
77         {
78                 Log_info("IPv4 is not supported by this system");
79                 nofServerSocks -= 2;
80         }
81
82         if(!hasv6)
83         {
84                 Log_info("IPv6 is not supported by this system");
85                 nofServerSocks -= 2;
86         }
87
88         if(nofServerSocks == 0)
89         {
90                 Log_fatal("Neither IPv4 nor IPv6 are supported by this system");
91         }
92 }
93
94 /* Initialize the address structures for IPv4 and IPv6 */
95 struct sockaddr_storage** Server_setupAddressesAndPorts()
96 {
97         struct sockaddr_storage** addresses = calloc(2, sizeof(void*));
98
99         struct sockaddr_storage* v4address = calloc(1, sizeof(struct sockaddr_storage));
100         v4address->ss_family = AF_INET;
101         struct sockaddr_storage* v6address = calloc(1, sizeof(struct sockaddr_storage));
102         v6address->ss_family = AF_INET6;
103
104 #if defined(__NetBSD__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__APPLE__)
105         v4address->ss_len = sizeof(struct sockaddr_storage);
106         v6address->ss_len = sizeof(struct sockaddr_storage);
107 #endif
108
109         int error = 0;
110
111         error = inet_pton(AF_INET, (!bindaddr) ? ((getStrConf(BINDADDR)) ? getStrConf(BINDADDR) : "0.0.0.0")
112                 : bindaddr, &(((struct sockaddr_in*)v4address)->sin_addr));
113         if (error == 0)
114                 Log_fatal("Invalid IPv4 address supplied!");
115         else if (error == -1)
116                 Log_warn("Could not allocate IPv4 address");
117
118         error = inet_pton(AF_INET6, (!bindaddr6) ? ((getStrConf(BINDADDR6)) ? getStrConf(BINDADDR6) : "::")
119                 : bindaddr6, &(((struct sockaddr_in6*)v6address)->sin6_addr));
120         if (error == 0)
121                 Log_fatal("Invalid IPv6 address supplied!");
122         else if (error == -1)
123                 Log_warn("Could not allocate IPv6 address");
124
125         ((struct sockaddr_in*)v4address)->sin_port = htons((bindport) ? bindport : getIntConf(BINDPORT));
126         ((struct sockaddr_in6*)v6address)->sin6_port = htons((bindport6) ? bindport6 : getIntConf(BINDPORT6));
127
128         addresses[0] = v4address;
129         addresses[1] = v6address;
130
131         return addresses;
132 }
133
134 void Server_runLoop(struct pollfd* pollfds)
135 {
136         int timeout, rc, clientcount;
137
138         etimer_t janitorTimer;
139         Timer_init(&janitorTimer);
140
141         while (!shutdown_server) {
142                 struct sockaddr_storage remote;
143                 int i;
144                 
145 #ifdef USE_SHAREDMEMORY_API
146     Sharedmemory_alivetick();
147 #endif
148
149                 for(i = 0; i < nofServerSocks; i++) {
150                         pollfds[i].revents = 0;
151                 }
152
153                 clientcount = Client_getfds(&pollfds[nofServerSocks]);
154
155                 timeout = (int)(1000000LL - (int64_t)Timer_elapsed(&janitorTimer)) / 1000LL;
156                 if (timeout <= 0) {
157                         Client_janitor();
158                         Timer_restart(&janitorTimer);
159                         timeout = (int)(1000000LL - (int64_t)Timer_elapsed(&janitorTimer)) / 1000LL;
160                 }
161                 rc = poll(pollfds, clientcount + nofServerSocks, timeout);
162                 if (rc == 0) {
163                         /* Poll timed out, do maintenance */
164                         Timer_restart(&janitorTimer);
165                         Client_janitor();
166                         continue;
167                 }
168                 if (rc < 0) {
169                         if (errno == EINTR) /* signal */
170                                 continue;
171                         else
172                                 Log_fatal("poll: error %d (%s)", errno, strerror(errno));
173                 }
174
175                 /* Check for new connection */
176                 for (i = 0; i < nofServerSocks / 2; i++) {
177                         if (pollfds[i].revents) {
178                                 static int tcpfd;
179                                 static uint32_t addrlen = sizeof(struct sockaddr_storage);
180                                 tcpfd = accept(pollfds[i].fd, (struct sockaddr *)&remote, &addrlen);
181                                 fcntl(tcpfd, F_SETFL, O_NONBLOCK);
182                                 setsockopt(tcpfd, IPPROTO_TCP, TCP_NODELAY, (char *) &on, sizeof(int));
183                                 Log_debug("Connection from %s port %d\n", Util_addressToString(&remote), Util_addressToPort(&remote));
184                                 if (Client_add(tcpfd, &remote) < 0)
185                                         close(tcpfd);
186                         }
187                 }
188
189                 for (i = nofServerSocks / 2; i < nofServerSocks; i++) {
190                         if (pollfds[i].revents)
191                                 Client_read_udp(udpsocks[i - nofServerSocks / 2]);
192                 }
193
194                 for (i = 0; i < clientcount; i++) {
195                         if (pollfds[nofServerSocks + i].revents & POLLIN)
196                                 Client_read_fd(pollfds[nofServerSocks + i].fd);
197
198                         if (pollfds[nofServerSocks + i].revents & POLLOUT)
199                                 Client_write_fd(pollfds[nofServerSocks + i].fd);
200                 }
201 #ifdef USE_SHAREDMEMORY_API    
202     Sharedmemory_update();
203 #endif    
204         }
205 }
206
207 void Server_setupTCPSockets(struct sockaddr_storage* addresses[2], struct pollfd* pollfds)
208 {
209         uint8_t yes = 1;
210         int sockets[2];
211
212         if (hasv4) {
213                 /* IPv4 socket setup */
214                 sockets[0] = socket(PF_INET, SOCK_STREAM, 0);
215                 if (sockets[0] < 0)
216                         Log_fatal("socket IPv4");
217                 if (setsockopt(sockets[0], SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) != 0)
218                         Log_fatal("setsockopt IPv4: %s", strerror(errno));
219                 if (bind(sockets[0], (struct sockaddr *)addresses[0], sizeof (struct sockaddr_in)) < 0)
220                         Log_fatal("bind %s %d: %s", Util_addressToString(addresses[0]), Util_addressToPort(addresses[0]), strerror(errno));
221                 if (listen(sockets[0], 3) < 0)
222                         Log_fatal("listen IPv4");
223                 fcntl(sockets[0], F_SETFL, O_NONBLOCK);
224
225                 pollfds[0].fd = sockets[0];
226                 pollfds[0].events = POLLIN;
227         }
228
229         if (hasv6) {
230                 /* IPv6 socket setup */
231                 sockets[1] = socket(PF_INET6, SOCK_STREAM, 0);
232                 if (sockets[1] < 0)
233                         Log_fatal("socket IPv6: %s", strerror(errno));
234                 if (setsockopt(sockets[1], SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) != 0)
235                         Log_fatal("setsockopt IPv6: %s", strerror(errno));
236                 if (setsockopt(sockets[1], IPPROTO_IPV6, IPV6_V6ONLY, &yes, sizeof(int)) != 0)
237                         Log_fatal("setsockopt IPv6: %s", strerror(errno));
238                 if (bind(sockets[1], (struct sockaddr *)addresses[1], sizeof (struct sockaddr_in6)) < 0)
239                         Log_fatal("bind %s %d: %s", Util_addressToString(addresses[1]), Util_addressToPort(addresses[1]), strerror(errno));
240                 if (listen(sockets[1], 3) < 0)
241                         Log_fatal("listen IPv6");
242                 fcntl(sockets[1], F_SETFL, O_NONBLOCK);
243
244
245                 /* If  there is an IPv4 address, then IPv6 will use the second socket, otherwise it uses the first */
246                 pollfds[(hasv4) ? 1 : 0].fd = sockets[1];
247                 pollfds[(hasv4) ? 1 : 0].events = POLLIN;
248         }
249 }
250
251 void Server_setupUDPSockets(struct sockaddr_storage* addresses[2], struct pollfd* pollfds)
252 {
253         int val = 0;
254         int sockets[2] = {-1, -1};
255
256         if((udpsocks = calloc(nofServerSocks / 2, sizeof(int))) == NULL)
257                 Log_fatal("Out of memory (%s:%s)", __FILE__, __LINE__);
258
259         if (hasv4) {
260                 sockets[0] = socket(PF_INET, SOCK_DGRAM, 0);
261                 if (bind(sockets[0], (struct sockaddr *) addresses[0], sizeof (struct sockaddr_in)) < 0)
262                         Log_fatal("bind %s %d: %s", Util_addressToString(addresses[0]), Util_addressToPort(addresses[0]), strerror(errno));
263                 val = 0xe0;
264                 if (setsockopt(sockets[0], IPPROTO_IP, IP_TOS, &val, sizeof(val)) < 0)
265                         Log_warn("Server: Failed to set TOS for UDP Socket");
266                 val = 0x80;
267                 if (setsockopt(sockets[0], IPPROTO_IP, IP_TOS, &val, sizeof(val)) < 0)
268                         Log_warn("Server: Failed to set TOS for UDP Socket");
269
270                 fcntl(sockets[0], F_SETFL, O_NONBLOCK);
271                 pollfds[(hasv6) ? 2 : 1].fd = sockets[0];
272                 pollfds[(hasv6) ? 2 : 1].events = POLLIN | POLLHUP | POLLERR;
273                 udpsocks[0] = sockets[0];
274         }
275
276         if (hasv6) {
277                 sockets[1] = socket(PF_INET6, SOCK_DGRAM, 0);
278                 if (setsockopt(sockets[1], IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(int)) != 0)
279                         Log_fatal("setsockopt IPv6: %s", strerror(errno));
280                 if (bind(sockets[1], (struct sockaddr *) addresses[1], sizeof (struct sockaddr_in6)) < 0)
281                         Log_fatal("bind %s %d: %s", Util_addressToString(addresses[1]), Util_addressToPort(addresses[1]), strerror(errno));
282                 val = 0xe0;
283                 if (setsockopt(sockets[1], IPPROTO_IPV6, IPV6_TCLASS, &val, sizeof(val)) < 0)
284                         Log_warn("Server: Failed to set TOS for UDP Socket");
285                 val = 0x80;
286                 if (setsockopt(sockets[1], IPPROTO_IPV6, IPV6_TCLASS, &val, sizeof(val)) < 0)
287                         Log_warn("Server: Failed to set TOS for UDP Socket");
288
289                 fcntl(sockets[1], F_SETFL, O_NONBLOCK);
290                 pollfds[(hasv4) ? 3 : 1].fd = sockets[1];
291                 pollfds[(hasv4) ? 3 : 1].events = POLLIN | POLLHUP | POLLERR;
292                 udpsocks[(hasv4) ? 1 : 0] = sockets[1];
293         }
294
295 }
296
297 void Server_run()
298 {
299         struct pollfd *pollfds;
300
301         checkIPversions();
302
303         /* max clients + server sokets + client connecting that will be disconnected */
304         if ((pollfds = calloc((getIntConf(MAX_CLIENTS) + nofServerSocks + 1) , sizeof(struct pollfd))) == NULL)
305                 Log_fatal("out of memory");
306
307         /* Figure out bind address and port */
308         struct sockaddr_storage** addresses = Server_setupAddressesAndPorts();
309
310         /* Prepare TCP sockets */
311         Server_setupTCPSockets(addresses, pollfds);
312
313         /* Prepare UDP sockets */
314         Server_setupUDPSockets(addresses, pollfds);
315
316         Log_info("uMurmur version %s ('%s') protocol version %d.%d.%d",
317                 UMURMUR_VERSION, UMURMUR_CODENAME, PROTVER_MAJOR, PROTVER_MINOR, PROTVER_PATCH);
318         Log_info("Visit http://code.google.com/p/umurmur/");
319
320         /* Main server loop */
321         Server_runLoop(pollfds);
322
323         /* Disconnect clients and cleanup memory */
324         Client_disconnect_all();
325         free(pollfds);
326         free(addresses[0]);
327         free(addresses[1]);
328         free(addresses);
329         free(udpsocks);
330 }
331
332 void Server_shutdown()
333 {
334         shutdown_server = true;
335 }