Debian Codegraph @

src/bnetd/server.cpp

raw symbols SCIP
1 /*
2 * Copyright (C) 1998,1999 Mark Baysinger ([email protected])
3 * Copyright (C) 1998,1999,2000,2001 Ross Combs ([email protected])
4 * Copyright (C) 2000,2001 Marco Ziech ([email protected])
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19 */
20 #include "common/setup_before.h"
21 #define SERVER_INTERNAL_ACCESS
22 #include "server.h"
23
24 #include <cctype>
25 #include <cerrno>
26 #include <cstring>
27 #include <cstdio>
28
29 #ifdef DO_POSIXSIG
30 # include <signal.h>
31 #endif
32 #ifdef HAVE_SYS_TIME_H
33 # include <sys/time.h>
34 #endif
35 #include "compat/strerror.h"
36 #include "compat/psock.h"
37 #include "common/fdwatch.h"
38 #include "common/addr.h"
39 #include "common/eventlog.h"
40 #include "common/xalloc.h"
41 #include "common/packet.h"
42 #include "common/hexdump.h"
43 #include "common/network.h"
44 #include "common/list.h"
45 #include "common/trans.h"
46 #ifdef WIN32
47 # include "win32/service.h"
48 # include "windows.h"
49 #endif
50 #include "common/util.h"
51
52 #include "prefs.h"
53 #include "connection.h"
54 #include "ipban.h"
55 #include "timer.h"
56 #include "handle_bnet.h"
57 #include "handle_bot.h"
58 #include "handle_telnet.h"
59 #include "handle_file.h"
60 #include "handle_init.h"
61 #include "handle_d2cs.h"
62 #include "handle_irc_common.h"
63 #include "handle_udp.h"
64 #include "handle_apireg.h"
65 #include "handle_wol_gameres.h"
66 #include "anongame.h"
67 #include "clan.h"
68 #include "attrlayer.h"
69 #include "account.h"
70 #include "message.h"
71 #include "game.h"
72 #include "cmdline.h"
73 #include "tracker.h"
74 #include "ladder.h"
75 #include "output.h"
76 #include "channel.h"
77 #include "realm.h"
78 #include "autoupdate.h"
79 #include "news.h"
80 #include "versioncheck.h"
81 #include "helpfile.h"
82 #include "adbanner.h"
83 #include "command_groups.h"
84 #include "alias_command.h"
85 #include "tournament.h"
86 #include "icons.h"
87 #include "anongame_infos.h"
88 #include "topic.h"
89 #include "i18n.h"
90
91 #ifdef HAVE_ARPA_INET_H
92 # include <arpa/inet.h>
93 #endif
94 #ifdef HAVE_WS2TCPIP_H
95 # include <Ws2tcpip.h>
96 #endif
97
98 #include "common/setup_after.h"
99
100 #ifdef WITH_LUA
101 #include "luainterface.h"
102 #endif
103
104 extern std::FILE * hexstrm; /* from main.c */
105 extern int g_ServiceStatus;
106
107 namespace pvpgn
108 {
109
110 namespace bnetd
111 {
112
113 #ifdef DO_POSIXSIG
114 static void quit_sig_handle(int unused);
115 static void restart_sig_handle(int unused);
116 static void save_sig_handle(int unused);
117 #ifdef HAVE_SETITIMER
118 static void timer_sig_handle(int unused);
119 #endif
120 #endif
121
122
123 time_t now;
124 static std::time_t starttime;
125 static std::time_t curr_exittime;
126 static volatile std::time_t sigexittime = 0;
127 static volatile int do_restart = 0;
128 static volatile int do_save = 0;
129 static volatile int got_epipe = 0;
130 static char const * server_hostname = NULL;
131
132 extern void server_quit_delay(int delay)
133 {
134 /* getting negative delay is ok too because it will force immediate
135 * shutdown */
136 if (delay)
137 sigexittime = std::time(NULL) + delay;
138 else
139 sigexittime = 0;
140 }
141
142
143 extern void server_quit_wraper(void)
144 {
145 if (sigexittime)
146 sigexittime -= prefs_get_shutdown_decr();
147 else
148 sigexittime = std::time(NULL) + (std::time_t)prefs_get_shutdown_delay();
149 }
150
151 extern void server_restart_wraper(int mode){
152 do_restart = mode;
153 }
154
155 extern void server_save_wraper(void){
156 do_save = 1;
157 }
158
159 #ifdef DO_POSIXSIG
160 static void quit_sig_handle(int unused)
161 {
162 server_quit_wraper();
163 }
164
165
166 static void restart_sig_handle(int unused)
167 {
168 do_restart = 1;
169 }
170
171
172 static void save_sig_handle(int unused)
173 {
174 do_save = 1;
175 }
176
177 static void pipe_sig_handle(int unused)
178 {
179 got_epipe = 1;
180 }
181
182 #ifdef HAVE_SETITIMER
183 static void timer_sig_handle(int unused)
184 {
185 std::time(&now);
186 }
187 #endif
188
189 static void forced_quit_sig_handle(int unused)
190 {
191 server_quit_delay(-1); /* programs shutdown 1 second before now */
192 }
193 #endif
194
195
196 extern unsigned int server_get_uptime(void)
197 {
198 return (unsigned int)std::difftime(std::time(NULL), starttime);
199 }
200
201
202 extern unsigned int server_get_starttime(void)
203 {
204 return (unsigned int)starttime;
205 }
206
207
208 static char const * laddr_type_get_str(t_laddr_type laddr_type)
209 {
210 switch (laddr_type)
211 {
212 case laddr_type_bnet:
213 return "bnet";
214 case laddr_type_w3route:
215 return "w3route";
216 case laddr_type_irc:
217 return "irc";
218 case laddr_type_wolv1:
219 return "wolv1";
220 case laddr_type_wolv2:
221 return "wolv2";
222 case laddr_type_apireg:
223 return "apireg";
224 case laddr_type_wgameres:
225 return "wgameres";
226 case laddr_type_telnet:
227 return "telnet";
228 default:
229 return "UNKNOWN";
230 }
231 }
232
233
234 static int handle_accept(void *data, t_fdwatch_type rw);
235 static int handle_tcp(void *data, t_fdwatch_type rw);
236 static int handle_udp(void *data, t_fdwatch_type rw);
237
238
239 static int sd_accept(t_addr const * curr_laddr, t_laddr_info const * laddr_info, int ssocket, int usocket)
240 {
241 char tempa[32];
242 int csocket;
243 struct sockaddr_in caddr;
244 psock_t_socklen caddr_len;
245 unsigned int raddr;
246 unsigned short rport;
247
248 if (!addr_get_addr_str(curr_laddr, tempa, sizeof(tempa)))
249 std::strcpy(tempa, "x.x.x.x:x");
250
251 /* accept the connection */
252 std::memset(&caddr, 0, sizeof(caddr)); /* not sure if this is needed... modern systems are ok anyway */
253 caddr_len = sizeof(caddr);
254 if ((csocket = psock_accept(ssocket, (struct sockaddr *)&caddr, &caddr_len)) < 0)
255 {
256 /* BSD, POSIX error for aborted connections, SYSV often uses EAGAIN or EPROTO */
257 if (
258 #ifdef PSOCK_EWOULDBLOCK
259 psock_errno() == PSOCK_EWOULDBLOCK ||
260 #endif
261 #ifdef PSOCK_ECONNABORTED
262 psock_errno() == PSOCK_ECONNABORTED ||
263 #endif
264 #ifdef PSOCK_EPROTO
265 psock_errno() == PSOCK_EPROTO ||
266 #endif
267 0)
268 eventlog(eventlog_level_error, __FUNCTION__, "client aborted connection on {} (psock_accept: {})", tempa, pstrerror(psock_errno()));
269 else /* EAGAIN can mean out of resources _or_ connection aborted :( */
270 if (
271 #ifdef PSOCK_EINTR
272 psock_errno() != PSOCK_EINTR &&
273 #endif
274 1)
275 eventlog(eventlog_level_error, __FUNCTION__, "could not accept new connection on {} (psock_accept: {})", tempa, pstrerror(psock_errno()));
276 return -1;
277 }
278
279 /* dont accept new connections while shutting down */
280 if (curr_exittime) {
281 psock_shutdown(csocket, PSOCK_SHUT_RDWR);
282 psock_close(csocket);
283 return 0;
284 }
285
286 char addrstr[INET_ADDRSTRLEN] = { 0 };
287 if (ipbanlist_check(inet_ntop(AF_INET, &(caddr.sin_addr), addrstr, sizeof(addrstr))) != 0)
288 {
289 eventlog(eventlog_level_info, __FUNCTION__, "[{}] connection from banned address {} denied (closing connection)", csocket, addrstr);
290 psock_close(csocket);
291 return -1;
292 }
293
294 eventlog(eventlog_level_info, __FUNCTION__, "[{}] accepted connection from {} on {}", csocket, addr_num_to_addr_str(ntohl(caddr.sin_addr.s_addr), ntohs(caddr.sin_port)), tempa);
295
296 if (prefs_get_use_keepalive())
297 {
298 int val = 1;
299
300 if (psock_setsockopt(csocket, PSOCK_SOL_SOCKET, PSOCK_SO_KEEPALIVE, &val, (psock_t_socklen)sizeof(val)) < 0)
301 eventlog(eventlog_level_error, __FUNCTION__, "[{}] could not set socket option SO_KEEPALIVE (psock_setsockopt: {})", csocket, pstrerror(psock_errno()));
302 /* not a fatal error */
303 }
304
305 {
306 struct sockaddr_in rsaddr;
307 psock_t_socklen rlen;
308
309 std::memset(&rsaddr, 0, sizeof(rsaddr)); /* not sure if this is needed... modern systems are ok anyway */
310 rlen = sizeof(rsaddr);
311 if (psock_getsockname(csocket, (struct sockaddr *)&rsaddr, &rlen) < 0)
312 {
313 eventlog(eventlog_level_error, __FUNCTION__, "[{}] unable to determine real local port (psock_getsockname: {})", csocket, pstrerror(psock_errno()));
314 /* not a fatal error */
315 raddr = addr_get_ip(curr_laddr);
316 rport = addr_get_port(curr_laddr);
317 }
318 else
319 {
320 if (rsaddr.sin_family != PSOCK_AF_INET)
321 {
322 eventlog(eventlog_level_error, __FUNCTION__, "local address returned with bad address family {}", (int)rsaddr.sin_family);
323 /* not a fatal error */
324 raddr = addr_get_ip(curr_laddr);
325 rport = addr_get_port(curr_laddr);
326 }
327 else
328 {
329 raddr = ntohl(rsaddr.sin_addr.s_addr);
330 rport = ntohs(rsaddr.sin_port);
331 }
332 }
333 }
334
335 if (psock_ctl(csocket, PSOCK_NONBLOCK) < 0)
336 {
337 eventlog(eventlog_level_error, __FUNCTION__, "[{}] could not set TCP socket to non-blocking mode (closing connection) (psock_ctl: {})", csocket, pstrerror(psock_errno()));
338 psock_close(csocket);
339 return -1;
340 }
341
342 {
343 t_connection * c;
344
345 if (!(c = conn_create(csocket, usocket, raddr, rport, addr_get_ip(curr_laddr), addr_get_port(curr_laddr), ntohl(caddr.sin_addr.s_addr), ntohs(caddr.sin_port))))
346 {
347 eventlog(eventlog_level_error, __FUNCTION__, "[{}] unable to create new connection (closing connection)", csocket);
348 psock_close(csocket);
349 return -1;
350 }
351
352 if (conn_add_fdwatch(c, handle_tcp) < 0) {
353 eventlog(eventlog_level_error, __FUNCTION__, "[{}] unable to add socket to fdwatch pool (max connections?)", csocket);
354 conn_set_state(c, conn_state_destroy);
355 return -1;
356 }
357
358 eventlog(eventlog_level_debug, __FUNCTION__, "[{}] client connected to a {} listening address", csocket, laddr_type_get_str(laddr_info->type));
359 switch (laddr_info->type)
360 {
361 case laddr_type_irc:
362 case laddr_type_wolv1:
363 case laddr_type_wolv2:
364 conn_set_class(c, conn_class_ircinit);
365 conn_set_state(c, conn_state_connected);
366 break;
367 case laddr_type_apireg:
368 conn_set_class(c, conn_class_apireg);
369 conn_set_state(c, conn_state_connected);
370 break;
371 case laddr_type_wgameres:
372 conn_set_class(c, conn_class_wgameres);
373 conn_set_state(c, conn_state_connected);
374 break;
375 case laddr_type_w3route:
376 conn_set_class(c, conn_class_w3route);
377 conn_set_state(c, conn_state_connected);
378 break;
379 case laddr_type_telnet:
380 conn_set_class(c, conn_class_telnet);
381 conn_set_state(c, conn_state_connected);
382 break;
383 case laddr_type_bnet:
384 { /* add a timer to close stale connections */
385 int delay;
386 t_timer_data data;
387
388 data.p = NULL;
389 delay = prefs_get_initkill_timer();
390 if (delay) timerlist_add_timer(c, std::time(NULL) + delay, conn_shutdown, data);
391 }
392 default:
393 /* We have to wait for an initial "magic" byte on bnet connections to
394 * tell us exactly what connection class we are dealing with.
395 */
396 break;
397 }
398 }
399
400 return 0;
401 }
402
403
404 static int sd_udpinput(t_addr * const curr_laddr, t_laddr_info const * laddr_info, int ssocket, int usocket)
405 {
406 int err;
407 psock_t_socklen errlen;
408 t_packet * upacket;
409
410 err = 0;
411 errlen = sizeof(err);
412 if (psock_getsockopt(usocket, PSOCK_SOL_SOCKET, PSOCK_SO_ERROR, &err, &errlen) < 0)
413 {
414 eventlog(eventlog_level_error, __FUNCTION__, "[{}] unable to read socket error (psock_getsockopt: {})", usocket, pstrerror(psock_errno()));
415 return -1;
416 }
417 if (errlen && err) /* if it was an error, there is no packet to read */
418 {
419 eventlog(eventlog_level_error, __FUNCTION__, "[{}] async UDP socket error notification (psock_getsockopt: {})", usocket, pstrerror(err));
420 return -1;
421 }
422 if (!(upacket = packet_create(packet_class_udp)))
423 {
424 eventlog(eventlog_level_error, __FUNCTION__, "could not allocate raw packet for input");
425 return -1;
426 }
427
428 {
429 struct sockaddr_in fromaddr;
430 psock_t_socklen fromlen;
431 int len;
432
433 fromlen = sizeof(fromaddr);
434 if ((len = psock_recvfrom(usocket, packet_get_raw_data_build(upacket, 0), MAX_PACKET_SIZE, 0, (struct sockaddr *)&fromaddr, &fromlen)) < 0)
435 {
436 if (
437 #ifdef PSOCK_EINTR
438 psock_errno() != PSOCK_EINTR &&
439 #endif
440 #ifdef PSOCK_EAGAIN
441 psock_errno() != PSOCK_EAGAIN &&
442 #endif
443 #ifdef PSOCK_EWOULDBLOCK
444 psock_errno() != PSOCK_EWOULDBLOCK &&
445 #endif
446 #ifdef PSOCK_ECONNRESET
447 psock_errno() != PSOCK_ECONNRESET && /* this is a win2k/winxp issue
448 * their socket implementation returns this value
449 * although it shouldn't
450 */
451 #endif
452 1)
453 eventlog(eventlog_level_error, __FUNCTION__, "could not recv UDP datagram (psock_recvfrom: {})", pstrerror(psock_errno()));
454 packet_del_ref(upacket);
455 return -1;
456 }
457
458 if (fromaddr.sin_family != PSOCK_AF_INET)
459 {
460 eventlog(eventlog_level_error, __FUNCTION__, "got UDP datagram with bad address family {}", (int)fromaddr.sin_family);
461 packet_del_ref(upacket);
462 return -1;
463 }
464
465 packet_set_size(upacket, len);
466
467 if (hexstrm)
468 {
469 char tempa[32];
470
471 if (!addr_get_addr_str(curr_laddr, tempa, sizeof(tempa)))
472 std::strcpy(tempa, "x.x.x.x:x");
473 std::fprintf(hexstrm, "%d: recv class=%s[0x%02x] type=%s[0x%04x] from=%s to=%s length=%u\n",
474 usocket,
475 packet_get_class_str(upacket), (unsigned int)packet_get_class(upacket),
476 packet_get_type_str(upacket, packet_dir_from_client), packet_get_type(upacket),
477 addr_num_to_addr_str(ntohl(fromaddr.sin_addr.s_addr), ntohs(fromaddr.sin_port)),
478 tempa,
479 packet_get_size(upacket));
480 hexdump(hexstrm, packet_get_raw_data(upacket, 0), packet_get_size(upacket));
481 }
482
483 handle_udp_packet(usocket, ntohl(fromaddr.sin_addr.s_addr), ntohs(fromaddr.sin_port), upacket);
484 packet_del_ref(upacket);
485 }
486
487 return 0;
488 }
489
490
491 static int sd_tcpinput(t_connection * c)
492 {
493 unsigned int currsize;
494 t_packet * packet;
495 int csocket = conn_get_socket(c);
496 bool skip;
497
498 currsize = conn_get_in_size(c);
499
500 if (!conn_get_in_queue(c))
501 {
502 switch (conn_get_class(c))
503 {
504 case conn_class_init:
505 if (!(packet = packet_create(packet_class_init)))
506 {
507 eventlog(eventlog_level_error, __FUNCTION__, "could not allocate init packet for input");
508 return -1;
509 }
510 break;
511 case conn_class_d2cs_bnetd:
512 if (!(packet = packet_create(packet_class_d2cs_bnetd)))
513 {
514 eventlog(eventlog_level_error, __FUNCTION__, "could not allocate d2cs_bnetd packet");
515 return -1;
516 }
517 break;
518 case conn_class_bnet:
519 if (!(packet = packet_create(packet_class_bnet)))
520 {
521 eventlog(eventlog_level_error, __FUNCTION__, "could not allocate bnet packet for input");
522 return -1;
523 }
524 break;
525 case conn_class_file:
526 switch (conn_get_state(c)) {
527 case conn_state_pending_raw:
528 if (!(packet = packet_create(packet_class_raw)))
529 {
530 eventlog(eventlog_level_error, __FUNCTION__, "could not allocate raw packet for input");
531 return -1;
532 }
533 packet_set_size(packet, sizeof(t_client_file_req3));
534 break;
535 default:
536 if (!(packet = packet_create(packet_class_file)))
537 {
538 eventlog(eventlog_level_error, __FUNCTION__, "could not allocate file packet for input");
539 return -1;
540 }
541 break;
542 }
543 break;
544 case conn_class_bot:
545 case conn_class_ircinit:
546 case conn_class_irc:
547 case conn_class_wol:
548 case conn_class_wserv:
549 case conn_class_apireg:
550 case conn_class_wladder:
551 case conn_class_telnet:
552 if (!(packet = packet_create(packet_class_raw)))
553 {
554 eventlog(eventlog_level_error, __FUNCTION__, "could not allocate raw packet for input");
555 return -1;
556 }
557 packet_set_size(packet, 1); /* start by only reading one char */
558 break;
559 case conn_class_w3route:
560 if (!(packet = packet_create(packet_class_w3route)))
561 {
562 eventlog(eventlog_level_error, __FUNCTION__, "could not allocate w3route packet for input");
563 return -1;
564 }
565 break;
566 case conn_class_wgameres:
567 if (!(packet = packet_create(packet_class_wolgameres)))
568 {
569 eventlog(eventlog_level_error, __FUNCTION__, "could not allocate wolgameres packet for input");
570 return -1;
571 }
572 break;
573 default:
574 eventlog(eventlog_level_error, __FUNCTION__, "[{}] connection has bad class (closing connection)", conn_get_socket(c));
575 conn_close_read(c);
576 return -2;
577 }
578 conn_put_in_queue(c, packet);
579 currsize = 0;
580 }
581
582 packet = conn_get_in_queue(c);
583 switch (net_recv_packet(csocket, packet, &currsize))
584 {
585 case -1:
586 eventlog(eventlog_level_debug, __FUNCTION__, "[{}] read returned -1 (closing connection)", conn_get_socket(c));
587 conn_close_read(c);
588 return -2;
589
590 case 0: /* still working on it */
591 /* eventlog(eventlog_level_debug,__FUNCTION__,"[{}] still reading \"{}\" packet ({} of {} bytes so far)",conn_get_socket(c),packet_get_class_str(packet),conn_get_in_size(c),packet_get_size(packet)); */
592 conn_set_in_size(c, currsize);
593 break;
594
595 case 1: /* done reading */
596 switch (conn_get_class(c))
597 {
598 case conn_class_bot:
599 case conn_class_telnet:
600 if (currsize < MAX_PACKET_SIZE) /* if we overflow, we can't wait for the end of the line.
601 handle_*_packet() should take care of it */
602 {
603 char const * const temp = (char const * const)packet_get_raw_data_const(packet, 0);
604
605 if ((temp[currsize - 1] == '\003') || (temp[currsize - 1] == '\004')) {
606 /* we have to ignore these special characters, since
607 * some bots even send them after login (eg. UltimateBot)
608 */
609 currsize--;
610 skip = true;
611 break;
612 }
613
614 if (temp[currsize - 1] != '\r' && temp[currsize - 1] != '\n')
615 {
616 conn_set_in_size(c, currsize);
617 packet_set_size(packet, currsize + 1);
618 skip = true;
619 break; /* no end of line, get another char */
620 }
621 }
622 skip = false;
623 break;
624
625 case conn_class_ircinit:
626 case conn_class_irc:
627 case conn_class_wol:
628 case conn_class_wserv:
629 case conn_class_wladder:
630 if (currsize < MAX_PACKET_SIZE)
631 /* if we overflow, we can't wait for the end of the line.
632 handle_*_packet() should take care of it */
633 {
634 char const * const temp = (char const * const)packet_get_raw_data_const(packet, 0);
635
636 if ((temp[currsize - 1] == '\r') || (temp[currsize - 1] == '\0')) {
637 /* kindly ignore \r and NUL ... */
638 currsize--;
639 skip = true;
640 break;
641 }
642
643 if (temp[currsize - 1] != '\n')
644 {
645 conn_set_in_size(c, currsize);
646 packet_set_size(packet, currsize + 1);
647 skip = true;
648 break; /* no end of line, get another char */
649 }
650 }
651 skip = false;
652 break;
653
654 default:
655 skip = false;
656 }
657
658 if (!skip) {
659 conn_put_in_queue(c, NULL);
660
661 if (hexstrm)
662 {
663 std::fprintf(hexstrm, "%d: recv class=%s[0x%02x] type=%s[0x%04x] length=%u\n",
664 csocket,
665 packet_get_class_str(packet), (unsigned int)packet_get_class(packet),
666 packet_get_type_str(packet, packet_dir_from_client), packet_get_type(packet),
667 packet_get_size(packet));
668 hexdump(hexstrm, packet_get_raw_data_const(packet, 0), packet_get_size(packet));
669 }
670
671 if (conn_get_class(c) == conn_class_bot ||
672 conn_get_class(c) == conn_class_telnet) /* NUL terminate the line to make life easier */
673 {
674 char * const temp = (char*)packet_get_raw_data(packet, 0);
675
676 if (temp[currsize - 1] == '\r' || temp[currsize - 1] == '\n')
677 temp[currsize - 1] = '\0'; /* have to do it here instead of above so everything
678 is intact for the hexdump */
679 }
680
681 {
682 int ret;
683
684 switch (conn_get_class(c))
685 {
686 case conn_class_init:
687 ret = handle_init_packet(c, packet);
688 break;
689 case conn_class_bnet:
690 ret = handle_bnet_packet(c, packet);
691 break;
692 case conn_class_d2cs_bnetd:
693 ret = handle_d2cs_packet(c, packet);
694 break;
695 case conn_class_bot:
696 ret = handle_bot_packet(c, packet);
697 break;
698 case conn_class_telnet:
699 ret = handle_telnet_packet(c, packet);
700 break;
701 case conn_class_file:
702 ret = handle_file_packet(c, packet);
703 break;
704 case conn_class_ircinit:
705 case conn_class_irc:
706 case conn_class_wol:
707 case conn_class_wserv:
708 case conn_class_wladder:
709 ret = handle_irc_common_packet(c, packet);
710 break;
711 case conn_class_apireg:
712 ret = handle_apireg_packet(c, packet);
713 break;
714 case conn_class_w3route:
715 ret = handle_w3route_packet(c, packet);
716 break;
717 case conn_class_wgameres:
718 ret = handle_wol_gameres_packet(c, packet);
719 break;
720 default:
721 eventlog(eventlog_level_error, __FUNCTION__, "[{}] bad packet class {} (closing connection)", conn_get_socket(c), (int)packet_get_class(packet));
722 ret = -1;
723 }
724 packet_del_ref(packet);
725 if (ret < 0)
726 {
727 conn_close_read(c);
728 return -2;
729 }
730 }
731
732 conn_set_in_size(c, 0);
733 }
734 }
735
736 return 0;
737 }
738
739
740 static int sd_tcpoutput(t_connection * c)
741 {
742 unsigned int currsize;
743 unsigned int totsize;
744 t_packet * packet;
745 int csocket = conn_get_socket(c);
746
747 totsize = 0;
748 for (;;)
749 {
750 currsize = conn_get_out_size(c);
751
752 if ((packet = conn_peek_outqueue(c)) == NULL)
753 return -2;
754
755 switch (net_send_packet(csocket, packet, &currsize)) /* avoid warning */
756 {
757 case -1:
758 /* marking connection as "destroyed", memory will be freed later */
759 conn_clear_outqueue(c);
760 conn_set_state(c, conn_state_destroy);
761 return -2;
762
763 case 0: /* still working on it */
764 conn_set_out_size(c, currsize);
765 return 0; /* bail out */
766
767 case 1: /* done sending */
768 if (hexstrm)
769 {
770 std::fprintf(hexstrm, "%d: send class=%s[0x%02x] type=%s[0x%04x] length=%u\n",
771 csocket,
772 packet_get_class_str(packet), (unsigned int)packet_get_class(packet),
773 packet_get_type_str(packet, packet_dir_from_server), packet_get_type(packet),
774 packet_get_size(packet));
775 hexdump(hexstrm, packet_get_raw_data(packet, 0), packet_get_size(packet));
776 }
777
778 packet = conn_pull_outqueue(c);
779 packet_del_ref(packet);
780 conn_set_out_size(c, 0);
781
782 /* stop at about BNETD_MAX_OUTBURST (or until out of packets or EWOULDBLOCK) */
783 if (totsize > BNETD_MAX_OUTBURST || !conn_peek_outqueue(c))
784 return 0;
785 totsize += currsize;
786 break;
787 }
788 }
789
790 /* not reached */
791 }
792
793 void server_check_and_fix_hostname(char const * sname)
794 {
795 int ok = 1;
796 char * tn = (char *)sname;
797 char * sn = (char *)sname;
798
799 if (!std::isalnum((int)*sn))
800 {
801 eventlog(eventlog_level_error, __FUNCTION__, "hostname contains invalid first symbol (must be alphanumeric)");
802 *tn = 'a';
803 }
804 tn++;
805 sn++;
806
807 for (; *sn != '\0'; sn++)
808 {
809 if (std::isalnum((int)*sn) || *sn == '-' || *sn == '.')
810 {
811 *tn = *sn;
812 tn++;
813 }
814 else
815 ok = 0;
816 }
817 *tn = '\0';
818
819 if (!ok)
820 eventlog(eventlog_level_error, __FUNCTION__, "hostname contains invalid symbol(s) (must be alphanumeric, '-' or '.') - skipped those symbols");
821 }
822
823 extern void server_set_hostname(void)
824 {
825 char temp[250];
826 char const * hn;
827 #ifdef HAVE_GETHOSTBYNAME
828 struct hostent * hp;
829 #endif
830
831 if (server_hostname) {
832 xfree((void *)server_hostname); /* avoid warning */
833 server_hostname = NULL;
834 }
835
836 hn = prefs_get_hostname();
837 if ((!hn) || (hn[0] == '\0')) {
838 if (gethostname(temp, sizeof(temp)) < 0) {
839 #ifdef WIN32
840 std::sprintf(temp, "localhost");
841 #else
842 eventlog(eventlog_level_error, __FUNCTION__, "could not get hostname: {}", pstrerror(errno));
843 return;
844 #endif
845 }
846 #ifdef HAVE_GETHOSTBYNAME
847 hp = gethostbyname(temp);
848 if (!hp || !hp->h_name) {
849 #endif
850 server_hostname = xstrdup(temp);
851 #ifdef HAVE_GETHOSTBYNAME
852 }
853 else {
854 int i = 0;
855
856 if (std::strchr(hp->h_name, '.'))
857 /* Default name is already a FQDN */
858 server_hostname = xstrdup(hp->h_name);
859 /* ... if not we have to examine the aliases */
860 while (!server_hostname && hp->h_aliases && hp->h_aliases[i]) {
861 if (std::strchr(hp->h_aliases[i], '.'))
862 server_hostname = xstrdup(hp->h_aliases[i]);
863 i++;
864 }
865 if (!server_hostname)
866 /* Fall back to default name which might not be a FQDN */
867 server_hostname = xstrdup(hp->h_name);
868 }
869 #endif
870 }
871 else {
872 server_hostname = xstrdup(hn);
873 }
874 server_check_and_fix_hostname(server_hostname);
875 eventlog(eventlog_level_info, __FUNCTION__, "set hostname to \"{}\"", server_hostname);
876 }
877
878 extern char const * server_get_hostname(void)
879 {
880 if (!server_hostname)
881 return "(null)"; /* avoid crashes */
882 else
883 return server_hostname;
884 }
885
886
887 extern void server_clear_hostname(void)
888 {
889 if (server_hostname) {
890 xfree((void *)server_hostname); /* avoid warning */
891 server_hostname = NULL;
892 }
893 }
894
895
896 static int handle_accept(void *data, t_fdwatch_type rw)
897 {
898 t_laddr_info *laddr_info = (t_laddr_info*)addr_get_data((t_addr *)data).p;
899
900 return sd_accept((t_addr *)data, laddr_info, laddr_info->ssocket, laddr_info->usocket);
901 }
902
903
904 static int handle_udp(void *data, t_fdwatch_type rw)
905 {
906 t_laddr_info *laddr_info = (t_laddr_info*)addr_get_data((t_addr *)data).p;
907
908 return sd_udpinput((t_addr *)data, laddr_info, laddr_info->ssocket, laddr_info->usocket);
909 }
910
911
912 static int handle_tcp(void *data, t_fdwatch_type rw)
913 {
914 switch (rw) {
915 case fdwatch_type_read: return sd_tcpinput((t_connection *)data);
916 case fdwatch_type_write: return sd_tcpoutput((t_connection *)data);
917 default:
918 return -1;
919 }
920 }
921
922
923 static int _setup_add_addrs(t_addrlist **pladdrs, const char *str, unsigned int defaddr, unsigned short defport, t_laddr_type type)
924 {
925 t_addr * curr_laddr;
926 t_addr_data laddr_data;
927 t_laddr_info * laddr_info;
928 t_elem const * acurr;
929
930 if (*pladdrs == NULL) {
931 *pladdrs = addrlist_create(str, defaddr, defport);
932 if (*pladdrs == NULL) return -1;
933 }
934 else if (addrlist_append(*pladdrs, str, defaddr, defport)) return -1;
935
936 /* Mark all these laddrs for being classic Battle.net service */
937 LIST_TRAVERSE_CONST(*pladdrs, acurr)
938 {
939 curr_laddr = (t_addr*)elem_get_data(acurr);
940 if (addr_get_data(curr_laddr).p)
941 continue;
942 laddr_info = (t_laddr_info*)xmalloc(sizeof(t_laddr_info));
943 laddr_info->usocket = -1;
944 laddr_info->ssocket = -1;
945 laddr_info->type = type;
946 laddr_data.p = laddr_info;
947 if (addr_set_data(curr_laddr, laddr_data) < 0)
948 {
949 eventlog(eventlog_level_error, __FUNCTION__, "could not set address data");
950 if (laddr_info->usocket != -1)
951 {
952 psock_close(laddr_info->usocket);
953 laddr_info->usocket = -1;
954 }
955 if (laddr_info->ssocket != -1)
956 {
957 psock_close(laddr_info->ssocket);
958 laddr_info->ssocket = -1;
959 }
960 return -1;
961 }
962 }
963
964 return 0;
965 }
966
967 static int _set_reuseaddr(int sock)
968 {
969 int val = 1;
970
971 return psock_setsockopt(sock, PSOCK_SOL_SOCKET, PSOCK_SO_REUSEADDR, &val, (psock_t_socklen)sizeof(int));
972 }
973
974 static int _bind_socket(int sock, unsigned addr, short port)
975 {
976 struct sockaddr_in saddr;
977
978 std::memset(&saddr, 0, sizeof(saddr));
979 saddr.sin_family = PSOCK_AF_INET;
980 saddr.sin_port = htons(port);
981 saddr.sin_addr.s_addr = htonl(addr);
982 return psock_bind(sock, (struct sockaddr *)&saddr, (psock_t_socklen)sizeof(saddr));
983 }
984
985 static int _setup_listensock(t_addrlist *laddrs)
986 {
987 t_addr * curr_laddr;
988 t_laddr_info * laddr_info;
989 t_elem const * acurr;
990 char tempa[32];
991 int fidx;
992
993 LIST_TRAVERSE_CONST(laddrs, acurr)
994 {
995 curr_laddr = (t_addr*)elem_get_data(acurr);
996 if (!(laddr_info = (t_laddr_info*)addr_get_data(curr_laddr).p))
997 {
998 eventlog(eventlog_level_error, __FUNCTION__, "NULL address info");
999 goto err;
1000 }
1001
1002 if (!addr_get_addr_str(curr_laddr, tempa, sizeof(tempa)))
1003 std::strcpy(tempa, "x.x.x.x:x");
1004
1005 laddr_info->ssocket = psock_socket(PSOCK_PF_INET, PSOCK_SOCK_STREAM, PSOCK_IPPROTO_TCP);
1006 if (laddr_info->ssocket < 0)
1007 {
1008 eventlog(eventlog_level_error, __FUNCTION__, "could not create a {} listening socket (psock_socket: {})", laddr_type_get_str(laddr_info->type), pstrerror(psock_errno()));
1009 goto err;
1010 }
1011
1012 if (_set_reuseaddr(laddr_info->ssocket) < 0)
1013 eventlog(eventlog_level_error, __FUNCTION__, "could not set option SO_REUSEADDR on {} socket {} (psock_setsockopt: {})", laddr_type_get_str(laddr_info->type), laddr_info->ssocket, pstrerror(psock_errno()));
1014 /* not a fatal error... */
1015
1016 if (_bind_socket(laddr_info->ssocket, addr_get_ip(curr_laddr), addr_get_port(curr_laddr)) < 0) {
1017 eventlog(eventlog_level_error, __FUNCTION__, "could not bind {} socket to address {} TCP (psock_bind: {})", laddr_type_get_str(laddr_info->type), tempa, pstrerror(psock_errno()));
1018 goto errsock;
1019 }
1020
1021 /* tell socket to listen for connections */
1022 if (psock_listen(laddr_info->ssocket, LISTEN_QUEUE) < 0) {
1023 eventlog(eventlog_level_error, __FUNCTION__, "could not set {} socket {} to listen (psock_listen: {})", laddr_type_get_str(laddr_info->type), laddr_info->ssocket, pstrerror(psock_errno()));
1024 goto errsock;
1025 }
1026
1027 if (psock_ctl(laddr_info->ssocket, PSOCK_NONBLOCK) < 0)
1028 eventlog(eventlog_level_error, __FUNCTION__, "could not set {} TCP listen socket to non-blocking mode (psock_ctl: {})", laddr_type_get_str(laddr_info->type), pstrerror(psock_errno()));
1029
1030 /* index not stored persisently because we dont need to refer to it later */
1031 fidx = fdwatch_add_fd(laddr_info->ssocket, fdwatch_type_read, handle_accept, curr_laddr);
1032 if (fidx < 0) {
1033 eventlog(eventlog_level_error, __FUNCTION__, "could not add listening socket {} to fdwatch pool (max sockets?)", laddr_info->ssocket);
1034 goto errsock;
1035 }
1036
1037 eventlog(eventlog_level_info, __FUNCTION__, "listening for {} connections on {} TCP", laddr_type_get_str(laddr_info->type), tempa);
1038
1039 if (laddr_info->type == laddr_type_bnet)
1040 {
1041 laddr_info->usocket = psock_socket(PSOCK_PF_INET, PSOCK_SOCK_DGRAM, PSOCK_IPPROTO_UDP);
1042 if (laddr_info->usocket < 0)
1043 {
1044 eventlog(eventlog_level_error, __FUNCTION__, "could not create UDP socket (psock_socket: {})", pstrerror(psock_errno()));
1045 goto errfdw;
1046 }
1047
1048 if (_set_reuseaddr(laddr_info->usocket) < 0)
1049 eventlog(eventlog_level_error, __FUNCTION__, "could not set option SO_REUSEADDR on {} socket {} (psock_setsockopt: {})", laddr_type_get_str(laddr_info->type), laddr_info->usocket, pstrerror(psock_errno()));
1050 /* not a fatal error... */
1051
1052 if (_bind_socket(laddr_info->usocket, addr_get_ip(curr_laddr), addr_get_port(curr_laddr)) < 0) {
1053 eventlog(eventlog_level_error, __FUNCTION__, "could not bind {} socket to address {} UDP (psock_bind: {})", laddr_type_get_str(laddr_info->type), tempa, pstrerror(psock_errno()));
1054 goto errusock;
1055 }
1056
1057 if (psock_ctl(laddr_info->usocket, PSOCK_NONBLOCK) < 0)
1058 eventlog(eventlog_level_error, __FUNCTION__, "could not set {} UDP socket to non-blocking mode (psock_ctl: {})", laddr_type_get_str(laddr_info->type), pstrerror(psock_errno()));
1059
1060 /* index ignored because we never need it after this */
1061 if (fdwatch_add_fd(laddr_info->usocket, fdwatch_type_read, handle_udp, curr_laddr) < 0) {
1062 eventlog(eventlog_level_error, __FUNCTION__, "could not add listening socket {} to fdwatch pool (max sockets?)", laddr_info->usocket);
1063 goto errusock;
1064 }
1065 }
1066 }
1067
1068 return 0;
1069
1070 errusock:
1071 psock_close(laddr_info->usocket);
1072 laddr_info->usocket = -1;
1073
1074 errfdw:
1075 fdwatch_del_fd(fidx);
1076
1077 errsock:
1078 psock_close(laddr_info->ssocket);
1079 laddr_info->ssocket = -1;
1080
1081 err:
1082 return -1;
1083 }
1084
1085 #ifdef DO_POSIXSIG
1086 static sigset_t block_set;
1087 static sigset_t save_set;
1088
1089 static int _setup_posixsig(void)
1090 {
1091 if (sigemptyset(&save_set) < 0)
1092 {
1093 eventlog(eventlog_level_error, __FUNCTION__, "could not initialize std::signal set (sigemptyset: {})", pstrerror(errno));
1094 return -1;
1095 }
1096 if (sigemptyset(&block_set) < 0)
1097 {
1098 eventlog(eventlog_level_error, __FUNCTION__, "could not initialize std::signal set (sigemptyset: {})", pstrerror(errno));
1099 return -1;
1100 }
1101 if (sigaddset(&block_set, SIGINT) < 0)
1102 {
1103 eventlog(eventlog_level_error, __FUNCTION__, "could not add std::signal to set (sigemptyset: {})", pstrerror(errno));
1104 return -1;
1105 }
1106 if (sigaddset(&block_set, SIGHUP) < 0)
1107 {
1108 eventlog(eventlog_level_error, __FUNCTION__, "could not add std::signal to set (sigemptyset: {})", pstrerror(errno));
1109 return -1;
1110 }
1111 if (sigaddset(&block_set, SIGTERM) < 0)
1112 {
1113 eventlog(eventlog_level_error, __FUNCTION__, "could not add std::signal to set (sigemptyset: {})", pstrerror(errno));
1114 return -1;
1115 }
1116 if (sigaddset(&block_set, SIGUSR1) < 0)
1117 {
1118 eventlog(eventlog_level_error, __FUNCTION__, "could not add std::signal to set (sigemptyset: {})", pstrerror(errno));
1119 return -1;
1120 }
1121 if (sigaddset(&block_set, SIGUSR2) < 0)
1122 {
1123 eventlog(eventlog_level_error, __FUNCTION__, "could not add std::signal to set (sigemptyset: {})", pstrerror(errno));
1124 return -1;
1125 }
1126 if (sigaddset(&block_set, SIGALRM) < 0)
1127 {
1128 eventlog(eventlog_level_error, __FUNCTION__, "could not add std::signal to set (sigemptyset: {})", pstrerror(errno));
1129 return -1;
1130 }
1131
1132 {
1133 struct sigaction quit_action;
1134 struct sigaction restart_action;
1135 struct sigaction save_action;
1136 struct sigaction pipe_action;
1137 #ifdef HAVE_SETITIMER
1138 struct sigaction timer_action;
1139 #endif
1140 struct sigaction forced_quit_action;
1141
1142 quit_action.sa_handler = quit_sig_handle;
1143 if (sigemptyset(&quit_action.sa_mask) < 0)
1144 eventlog(eventlog_level_error, __FUNCTION__, "could not initialize std::signal set (sigemptyset: {})", pstrerror(errno));
1145 quit_action.sa_flags = SA_RESTART;
1146
1147 restart_action.sa_handler = restart_sig_handle;
1148 if (sigemptyset(&restart_action.sa_mask) < 0)
1149 eventlog(eventlog_level_error, __FUNCTION__, "could not initialize std::signal set (sigemptyset: {})", pstrerror(errno));
1150 restart_action.sa_flags = SA_RESTART;
1151
1152 save_action.sa_handler = save_sig_handle;
1153 if (sigemptyset(&save_action.sa_mask) < 0)
1154 eventlog(eventlog_level_error, __FUNCTION__, "could not initialize std::signal set (sigemptyset: {})", pstrerror(errno));
1155 save_action.sa_flags = SA_RESTART;
1156
1157 pipe_action.sa_handler = pipe_sig_handle;
1158 if (sigemptyset(&pipe_action.sa_mask) < 0)
1159 eventlog(eventlog_level_error, __FUNCTION__, "could not initialize std::signal set (sigemptyset: {})", pstrerror(errno));
1160 pipe_action.sa_flags = SA_RESTART;
1161 #ifdef HAVE_SETITIMER
1162 timer_action.sa_handler = timer_sig_handle;
1163 if (sigemptyset(&timer_action.sa_mask) < 0)
1164 eventlog(eventlog_level_error, __FUNCTION__, "could not initialize std::signal set (sigemptyset: {})", pstrerror(errno));
1165 timer_action.sa_flags = SA_RESTART;
1166 #endif /* HAVE_SETITIMER */
1167 forced_quit_action.sa_handler = forced_quit_sig_handle;
1168 if (sigemptyset(&forced_quit_action.sa_mask) < 0)
1169 eventlog(eventlog_level_error, __FUNCTION__, "could not initialize std::signal set (sigemptyset: {})", pstrerror(errno));
1170 forced_quit_action.sa_flags = SA_RESTART;
1171
1172 if (sigaction(SIGINT, &quit_action, NULL) < 0) /* control-c */
1173 eventlog(eventlog_level_error, __FUNCTION__, "could not set SIGINT std::signal handler (sigaction: {})", pstrerror(errno));
1174 if (sigaction(SIGHUP, &restart_action, NULL) < 0)
1175 eventlog(eventlog_level_error, __FUNCTION__, "could not set SIGHUP std::signal handler (sigaction: {})", pstrerror(errno));
1176 if (sigaction(SIGTERM, &quit_action, NULL) < 0)
1177 eventlog(eventlog_level_error, __FUNCTION__, "could not set SIGTERM std::signal handler (sigaction: {})", pstrerror(errno));
1178 if (sigaction(SIGUSR1, &save_action, NULL) < 0)
1179 eventlog(eventlog_level_error, __FUNCTION__, "could not set SIGUSR1 std::signal handler (sigaction: {})", pstrerror(errno));
1180 if (sigaction(SIGPIPE, &pipe_action, NULL) < 0)
1181 eventlog(eventlog_level_error, __FUNCTION__, "could not set SIGPIPE std::signal handler (sigaction: {})", pstrerror(errno));
1182 #ifdef HAVE_SETITIMER
1183 /* setup asynchronus timestamp update timer */
1184 if (sigaction(SIGALRM, &timer_action, NULL) < 0)
1185 eventlog(eventlog_level_error, __FUNCTION__, "could not set SIGALRM std::signal handler (sigaction: {})", pstrerror(errno));
1186
1187 {
1188 struct itimerval it;
1189
1190 it.it_interval.tv_sec = BNETD_JIFFIES / 1000;
1191 it.it_interval.tv_usec = BNETD_JIFFIES % 1000;
1192 it.it_value.tv_sec = BNETD_JIFFIES / 1000;
1193 it.it_value.tv_usec = BNETD_JIFFIES % 1000;
1194
1195 if (setitimer(ITIMER_REAL, &it, NULL)) {
1196 eventlog(eventlog_level_fatal, __FUNCTION__, "failed to set timers (setitimer(): {})", pstrerror(errno));
1197 return -1;
1198 }
1199 }
1200 #endif
1201 if (sigaction(SIGQUIT, &forced_quit_action, NULL) < 0) /* immediate shutdown */
1202 eventlog(eventlog_level_error, __FUNCTION__, "could not set SIGQUIT std::signal handler (sigaction: {})", pstrerror(errno));
1203 }
1204
1205 return 0;
1206 }
1207 #endif
1208
1209 #ifdef WIN32
1210 # ifndef WIN32_GUI
1211 BOOL CtrlHandler(DWORD fdwCtrlType)
1212 {
1213 switch (fdwCtrlType)
1214 {
1215 // Handle the CTRL-C signal.
1216 case CTRL_C_EVENT:
1217 server_quit_wraper();
1218 return(TRUE);
1219
1220 // CTRL-CLOSE: confirm that the user wants to exit.
1221 server_quit_wraper();
1222 return(TRUE);
1223
1224 // Pass other signals to the next handler.
1225 case CTRL_BREAK_EVENT:
1226 server_quit_wraper();
1227 return FALSE;
1228
1229 case CTRL_LOGOFF_EVENT:
1230 server_quit_wraper();
1231 return FALSE;
1232
1233 case CTRL_SHUTDOWN_EVENT:
1234 server_quit_wraper();
1235 return FALSE;
1236
1237 default:
1238 return FALSE;
1239 }
1240 }
1241 # endif
1242 #endif
1243
1244 static std::time_t prev_exittime;
1245
1246 static void _server_mainloop(t_addrlist *laddrs)
1247 {
1248 std::time_t next_savetime, track_time;
1249 std::time_t war3_ladder_updatetime;
1250 std::time_t output_updatetime;
1251 std::time_t prev_time = 0;
1252
1253 starttime = std::time(NULL);
1254 track_time = starttime - prefs_get_track();
1255 next_savetime = starttime + prefs_get_user_sync_timer();
1256 war3_ladder_updatetime = starttime - prefs_get_war3_ladder_update_secs();
1257 output_updatetime = starttime - prefs_get_output_update_secs();
1258
1259 for (;;)
1260 {
1261 #ifdef WIN32
1262 if (g_ServiceStatus == 0) server_quit_wraper();
1263
1264 while (g_ServiceStatus == 2) Sleep(1000);
1265 #endif
1266
1267 #ifdef DO_POSIXSIG
1268 if (sigprocmask(SIG_SETMASK, &save_set, NULL) < 0)
1269 eventlog(eventlog_level_error, __FUNCTION__, "could not unblock signals");
1270 /* receive signals here */
1271 if (sigprocmask(SIG_SETMASK, &block_set, NULL) < 0)
1272 eventlog(eventlog_level_error, __FUNCTION__, "could not block signals");
1273 #endif
1274 if (got_epipe)
1275 {
1276 got_epipe = 0;
1277 eventlog(eventlog_level_info, __FUNCTION__, "handled SIGPIPE");
1278 }
1279
1280 #if !defined(DO_POSIXSIG) || !defined(HAVE_SETITIMER)
1281 /* if no DO_POSIXSIG or no HAVE_SETITIMER so we must read timestamp each loop */
1282 std::time(&now);
1283 #endif
1284 curr_exittime = sigexittime;
1285 if (curr_exittime && (curr_exittime <= now || connlist_login_get_length() < 1))
1286 {
1287 eventlog(eventlog_level_info, __FUNCTION__, "the server is shutting down ({} connections left)", connlist_get_length());
1288 clanlist_save();
1289 /* no need for accountlist_save() when using "force" */
1290 accountlist_save(FS_FORCE | FS_ALL);
1291 accountlist_flush(FS_FORCE | FS_ALL);
1292 break;
1293 }
1294 if (prev_exittime != curr_exittime)
1295 {
1296 t_message * message;
1297 char const * tstr;
1298
1299 if (curr_exittime != 0)
1300 {
1301 char text[29 + 256 + 2 + 32 + 24 + 1]; /* "The ... in " + std::time + " (" num + " connection ...)." + NUL */
1302
1303 tstr = seconds_to_timestr(curr_exittime - now);
1304 std::sprintf(text, "The server will shut down in %s (%d connections remaining).", tstr, connlist_get_length());
1305 if ((message = message_create(message_type_error, NULL, text)))
1306 {
1307 message_send_all(message);
1308 message_destroy(message);
1309 }
1310 eventlog(eventlog_level_info, __FUNCTION__, "the server will shut down in {} ({} connections remaining)", tstr, connlist_get_length());
1311 }
1312 else
1313 {
1314 if ((message = message_create(message_type_error, NULL, "Server shutdown has been canceled.")))
1315 {
1316 message_send_all(message);
1317 message_destroy(message);
1318 }
1319 eventlog(eventlog_level_info, __FUNCTION__, "server shutdown canceled");
1320 }
1321 }
1322 prev_exittime = curr_exittime;
1323
1324 if (next_savetime <= now) {
1325 /* do this stuff in usersync periods */
1326 clanlist_save();
1327 gamelist_check_voidgame();
1328 ladders.save();
1329 next_savetime += prefs_get_user_sync_timer();
1330 }
1331 accountlist_save(FS_NONE);
1332 accountlist_flush(FS_NONE);
1333
1334 if (prefs_get_track() && track_time + (std::time_t)prefs_get_track() <= now)
1335 {
1336 track_time = now;
1337 tracker_send_report(laddrs);
1338 }
1339
1340 if (prefs_get_war3_ladder_update_secs() && war3_ladder_updatetime + (std::time_t)prefs_get_war3_ladder_update_secs() <= now)
1341 {
1342 war3_ladder_updatetime = now;
1343 ladders.status();
1344 }
1345
1346 if (prefs_get_output_update_secs() && output_updatetime + (std::time_t)prefs_get_output_update_secs() <= now)
1347 {
1348 output_updatetime = now;
1349 output_write_to_file();
1350 }
1351
1352
1353 if (do_save)
1354 {
1355 eventlog(eventlog_level_info, __FUNCTION__, "saving accounts due to std::signal");
1356 clanlist_save();
1357
1358 do_save = 0;
1359 }
1360
1361 if (do_restart)
1362 {
1363 if (do_restart == restart_mode_all)
1364 {
1365 eventlog(eventlog_level_info, __FUNCTION__, "reading configuration files");
1366 if (cmdline_get_preffile())
1367 {
1368 if (prefs_load(cmdline_get_preffile()) < 0)
1369 eventlog(eventlog_level_error, __FUNCTION__, "could not parse configuration file");
1370 }
1371 else
1372 if (prefs_load(BNETD_DEFAULT_CONF_FILE) < 0)
1373 eventlog(eventlog_level_error, __FUNCTION__, "using default configuration");
1374
1375 if (eventlog_open(prefs_get_logfile()) < 0)
1376 eventlog(eventlog_level_error, __FUNCTION__, "could not use the file \"{}\" for the eventlog", prefs_get_logfile());
1377
1378 /* FIXME: load new network settings */
1379
1380 /* reload server name */
1381 server_set_hostname();
1382
1383 attrlayer_load_default();
1384 }
1385
1386 if (do_restart == restart_mode_all || do_restart == restart_mode_i18n)
1387 {
1388 i18n_reload();
1389 }
1390
1391 if (do_restart == restart_mode_all || do_restart == restart_mode_channels)
1392 {
1393 channellist_reload();
1394 }
1395
1396 if (do_restart == restart_mode_all || do_restart == restart_mode_realms)
1397 {
1398 if (realmlist_reload(prefs_get_realmfile()) < 0)
1399 eventlog(eventlog_level_error, __FUNCTION__, "could not reload realm list");
1400 }
1401
1402 if (do_restart == restart_mode_all || do_restart == restart_mode_autoupdate)
1403 {
1404 autoupdate_unload();
1405 if (autoupdate_load(prefs_get_mpqfile()) < 0)
1406 eventlog(eventlog_level_error, __FUNCTION__, "could not load autoupdate list");
1407 }
1408
1409 if (do_restart == restart_mode_all || do_restart == restart_mode_news)
1410 {
1411 news_unload();
1412 if (news_load(prefs_get_newsfile()) < 0)
1413 eventlog(eventlog_level_error, __FUNCTION__, "could not load news list");
1414 }
1415
1416 if (do_restart == restart_mode_all || do_restart == restart_mode_versioncheck)
1417 {
1418 unload_versioncheck_conf();
1419 if (!load_versioncheck_conf(prefs_get_versioncheck_file()))
1420 {
1421 eventlog(eventlog_level_error, __FUNCTION__, "could not load versioncheck list");
1422 }
1423 }
1424
1425 if (do_restart == restart_mode_all || do_restart == restart_mode_ipbans)
1426 {
1427 if (ipbanlist_destroy() < 0)
1428 eventlog(eventlog_level_error, __FUNCTION__, "could not unload old IP ban list");
1429 ipbanlist_create();
1430 if (ipbanlist_load(prefs_get_ipbanfile()) < 0)
1431 eventlog(eventlog_level_error, __FUNCTION__, "could not load new IP ban list");
1432 }
1433
1434 if (do_restart == restart_mode_all || do_restart == restart_mode_helpfile)
1435 {
1436 helpfile_unload();
1437 if (helpfile_init(prefs_get_helpfile()) < 0)
1438 eventlog(eventlog_level_error, __FUNCTION__, "could not load the helpfile");
1439 }
1440
1441 if (do_restart == restart_mode_all || do_restart == restart_mode_banners)
1442 {
1443 try
1444 {
1445 if (AdBannerList.is_loaded())
1446 {
1447 AdBannerList.unload();
1448 }
1449
1450 AdBannerList.load(prefs_get_adfile());
1451 }
1452 catch (const std::exception& e)
1453 {
1454 eventlog(eventlog_level_error, __FUNCTION__, "{}", e.what());
1455 }
1456 }
1457
1458 if (do_restart == restart_mode_all || do_restart == restart_mode_tracker)
1459 {
1460 if (prefs_get_track())
1461 tracker_set_servers(prefs_get_trackserv_addrs());
1462 }
1463
1464 if (do_restart == restart_mode_all || do_restart == restart_mode_commandgroups)
1465 {
1466 if (command_groups_reload(prefs_get_command_groups_file()) < 0)
1467 eventlog(eventlog_level_error, __FUNCTION__, "could not load new command_groups list");
1468 }
1469
1470 if (do_restart == restart_mode_all || do_restart == restart_mode_aliasfile)
1471 {
1472 aliasfile_unload();
1473 aliasfile_load(prefs_get_aliasfile());
1474 }
1475
1476 if (do_restart == restart_mode_all || do_restart == restart_mode_transfile)
1477 {
1478 if (trans_reload(prefs_get_transfile(), TRANS_BNETD) < 0)
1479 eventlog(eventlog_level_error, __FUNCTION__, "could not reload trans list");
1480 }
1481
1482 if (do_restart == restart_mode_all || do_restart == restart_mode_tournament)
1483 {
1484 tournament_reload(prefs_get_tournament_file());
1485 }
1486
1487 if (do_restart == restart_mode_all || do_restart == restart_mode_icons)
1488 {
1489 customicons_unload();
1490 customicons_load(prefs_get_customicons_file());
1491 }
1492
1493 if (do_restart == restart_mode_all || do_restart == restart_mode_anongame)
1494 {
1495 anongame_infos_unload();
1496 anongame_infos_load(prefs_get_anongame_infos_file());
1497 }
1498
1499 #ifdef WITH_LUA
1500 if (do_restart == restart_mode_all || do_restart == restart_mode_lua)
1501 {
1502 lua_handle_server(luaevent_server_rehash);
1503
1504 lua_unload();
1505 lua_load(prefs_get_scriptdir());
1506 }
1507 #endif
1508
1509 eventlog(eventlog_level_info, __FUNCTION__, "done reconfiguring");
1510
1511 do_restart = 0;
1512 }
1513
1514 /* only check timers once a second */
1515 if (now > prev_time)
1516 {
1517 prev_time = now;
1518 timerlist_check_timers(now);
1519 #ifdef WITH_LUA
1520 lua_handle_server(luaevent_server_mainloop);
1521 #endif
1522 }
1523
1524 /* no need to populate the fdwatch structures as they are populated on the fly
1525 * by sd_accept, conn_push_outqueue, conn_pull_outqueue, conn_destory */
1526
1527 /* find which sockets need servicing */
1528 switch (fdwatch(BNETD_POLL_INTERVAL))
1529 {
1530 case -1: /* error */
1531 if (
1532 #ifdef PSOCK_EINTR
1533 psock_errno() != PSOCK_EINTR &&
1534 #endif
1535 1)
1536 eventlog(eventlog_level_error, __FUNCTION__, "fdwatch() failed (errno: {})", pstrerror(psock_errno()));
1537 case 0: /* timeout... no sockets need checking */
1538 continue;
1539 }
1540
1541 /* cycle through the ready sockets and handle them */
1542 fdwatch_handle();
1543
1544 /* reap dead connections */
1545 connlist_reap();
1546
1547 }
1548 }
1549
1550
1551 static void _shutdown_conns(void)
1552 {
1553 t_elem *ccurr;
1554 t_connection *c;
1555
1556 LIST_TRAVERSE(connlist(), ccurr)
1557 {
1558 c = (t_connection *)elem_get_data(ccurr);
1559 conn_destroy(c, &ccurr, DESTROY_FROM_CONNLIST);
1560 }
1561 }
1562
1563
1564 static void _shutdown_addrs(t_addrlist *laddrs)
1565 {
1566 t_addr * curr_laddr;
1567 t_laddr_info * laddr_info;
1568 t_elem const * acurr;
1569
1570 LIST_TRAVERSE_CONST(laddrs, acurr)
1571 {
1572 curr_laddr = (t_addr*)elem_get_data(acurr);
1573 if ((laddr_info = (t_laddr_info*)addr_get_data(curr_laddr).p))
1574 {
1575 if (laddr_info->usocket != -1)
1576 psock_close(laddr_info->usocket);
1577 if (laddr_info->ssocket != -1)
1578 psock_close(laddr_info->ssocket);
1579 xfree(laddr_info);
1580 }
1581 }
1582 addrlist_destroy(laddrs);
1583 }
1584
1585 extern int server_process(void)
1586 {
1587 t_addrlist * laddrs;
1588
1589 laddrs = NULL;
1590 /* Start with the Battle.net address list */
1591 if (_setup_add_addrs(&laddrs, prefs_get_bnetdserv_addrs(), INADDR_ANY, BNETD_SERV_PORT, laddr_type_bnet))
1592 {
1593 eventlog(eventlog_level_error, __FUNCTION__, "could not create {} server address list from \"{}\"", laddr_type_get_str(laddr_type_bnet), prefs_get_bnetdserv_addrs());
1594 return -1;
1595 }
1596
1597 /* Append list of addresses to listen for IRC connections */
1598 if (_setup_add_addrs(&laddrs, prefs_get_irc_addrs(), INADDR_ANY, BNETD_IRC_PORT, laddr_type_irc))
1599 {
1600 eventlog(eventlog_level_error, __FUNCTION__, "could not create {} server address list from \"{}\"", laddr_type_get_str(laddr_type_irc), prefs_get_irc_addrs());
1601 _shutdown_addrs(laddrs);
1602 return -1;
1603 }
1604
1605 /* Append list of addresses to listen for WOLv1 connections */
1606 if (_setup_add_addrs(&laddrs, prefs_get_wolv1_addrs(), INADDR_ANY, BNETD_WOLV1_PORT, laddr_type_wolv1))
1607 {
1608 eventlog(eventlog_level_error, __FUNCTION__, "could not create {} server address list from \"{}\"", laddr_type_get_str(laddr_type_wolv1), prefs_get_wolv1_addrs());
1609 _shutdown_addrs(laddrs);
1610 return -1;
1611 }
1612
1613 /* Append list of addresses to listen for WOLv2 connections */
1614 if (_setup_add_addrs(&laddrs, prefs_get_wolv2_addrs(), INADDR_ANY, BNETD_WOLV2_PORT, laddr_type_wolv2))
1615 {
1616 eventlog(eventlog_level_error, __FUNCTION__, "could not create {} server address list from \"{}\"", laddr_type_get_str(laddr_type_wolv2), prefs_get_wolv2_addrs());
1617 _shutdown_addrs(laddrs);
1618 return -1;
1619 }
1620
1621 /* Append list of addresses to listen for APIREGISER connections */
1622 if (_setup_add_addrs(&laddrs, prefs_get_apireg_addrs(), INADDR_ANY, BNETD_APIREG_PORT, laddr_type_apireg))
1623 {
1624 eventlog(eventlog_level_error, __FUNCTION__, "could not create {} server address list from \"{}\"", laddr_type_get_str(laddr_type_apireg), prefs_get_apireg_addrs());
1625 _shutdown_addrs(laddrs);
1626 return -1;
1627 }
1628
1629 /* Append list of addresses to listen for WGAMERES connections */
1630 if (_setup_add_addrs(&laddrs, prefs_get_wgameres_addrs(), INADDR_ANY, BNETD_WGAMERES_PORT, laddr_type_wgameres))
1631 {
1632 eventlog(eventlog_level_error, __FUNCTION__, "could not create {} server address list from \"{}\"", laddr_type_get_str(laddr_type_wgameres), prefs_get_wgameres_addrs());
1633 _shutdown_addrs(laddrs);
1634 return -1;
1635 }
1636
1637 /* Append list of addresses to listen for W3ROUTE connections */
1638 if (_setup_add_addrs(&laddrs, prefs_get_w3route_addr(), INADDR_ANY, BNETD_W3ROUTE_PORT, laddr_type_w3route))
1639 {
1640 eventlog(eventlog_level_error, __FUNCTION__, "could not create {} server address list from \"{}\"", laddr_type_get_str(laddr_type_w3route), prefs_get_w3route_addr());
1641 _shutdown_addrs(laddrs);
1642 return -1;
1643 }
1644
1645 /* Append list of addresses to listen for telnet connections */
1646 if (_setup_add_addrs(&laddrs, prefs_get_telnet_addrs(), INADDR_ANY, BNETD_TELNET_PORT, laddr_type_telnet))
1647 {
1648 eventlog(eventlog_level_error, __FUNCTION__, "could not create {} server address list from \"{}\"", laddr_type_get_str(laddr_type_telnet), prefs_get_telnet_addrs());
1649 _shutdown_addrs(laddrs);
1650 return -1;
1651 }
1652
1653 if (_setup_listensock(laddrs)) {
1654 _shutdown_addrs(laddrs);
1655 return -1;
1656 }
1657
1658 /* setup std::signal handlers */
1659 prev_exittime = sigexittime;
1660 #ifdef DO_POSIXSIG
1661 _setup_posixsig();
1662 #endif
1663
1664 #ifdef WIN32
1665 # ifndef WIN32_GUI
1666 SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE);
1667 # endif
1668 #endif
1669
1670 _server_mainloop(laddrs);
1671
1672 #ifdef WIN32
1673 # ifndef WIN32_GUI
1674 SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, FALSE);
1675 # endif
1676 #endif
1677
1678
1679 /* cleanup for server shutdown */
1680 _shutdown_conns();
1681 _shutdown_addrs(laddrs);
1682
1683 return 0;
1684 }
1685
1686 }
1687
1688 }