]> git.pond.sub.org Git - empserver/blob - src/server/main.c
Switch PRNG from BSD random() to Mersenne Twister
[empserver] / src / server / main.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2013, Dave Pare, Jeff Bailey, Thomas Ruschak,
4  *                Ken Stevens, Steve McClure, Markus Armbruster
5  *
6  *  Empire is free software: you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation, either version 3 of the License, or
9  *  (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, see <http://www.gnu.org/licenses/>.
18  *
19  *  ---
20  *
21  *  See files README, COPYING and CREDITS in the root of the source
22  *  tree for related information and legal notices.  It is expected
23  *  that future projects/authors will amend these files as needed.
24  *
25  *  ---
26  *
27  *  main.c: Empire Server main, startup and shutdown
28  *
29  *  Known contributors to this file:
30  *     Dave Pare, 1994
31  *     Steve McClure, 1996, 1998
32  *     Doug Hay, 1998
33  *     Ron Koenderink, 2004-2009
34  *     Markus Armbruster, 2005-2012
35  */
36
37 #include <config.h>
38
39 #include <errno.h>
40 #include <signal.h>
41 #include <stdio.h>
42 #ifndef _WIN32
43 #include <sys/wait.h>
44 #endif
45 #include <unistd.h>
46
47 #if defined(_WIN32)
48 #include <process.h>
49 #include "service.h"
50 #include "sys/socket.h"
51 #endif
52
53 #include "chance.h"
54 #include "empio.h"
55 #include "empthread.h"
56 #include "file.h"
57 #include "journal.h"
58 #include "match.h"
59 #include "misc.h"
60 #include "optlist.h"
61 #include "plane.h"
62 #include "player.h"
63 #include "product.h"
64 #include "prototypes.h"
65 #include "sect.h"
66 #include "server.h"
67 #include "version.h"
68
69 static void ignore(void);
70 static void crash_dump(void);
71 static void init_server(unsigned, int);
72 static void create_pidfile(char *, pid_t);
73
74 #if defined(_WIN32)
75 static void loc_NTInit(void);
76 #endif
77
78 /*
79  * Lock to synchronize player threads with update.
80  * Update holds it exclusive, commands hold it shared.
81  */
82 empth_rwlock_t *update_lock;
83 /*
84  * Lock to synchronize player threads with shutdown.
85  * Shutdown holds it exclusive, player threads in state PS_PLAYING
86  * hold it shared.
87  */
88 empth_rwlock_t *shutdown_lock;
89
90 static char pidfname[] = "server.pid";
91
92 /* Run as daemon?  If yes, detach from controlling terminal etc. */
93 static int daemonize = 1;
94
95 static void
96 help(char *program_name, char *complaint)
97 {
98     if (complaint)
99         fprintf(stderr, "%s: %s\n", program_name, complaint);
100     fprintf(stderr, "Try -h for help.\n");
101 }
102
103 static void
104 print_usage(char *program_name)
105 {
106     printf("Usage: %s [OPTION]...\n"
107            "  -d              debug mode, implies -E abort\n"
108            "  -e CONFIG-FILE  configuration file\n"
109            "                  (default %s)\n"
110            "  -E ACTION       what to do on oops: abort, crash-dump, nothing (default)\n"
111 #ifdef _WIN32
112            "  -i              install service `%s'\n"
113            "  -I NAME         install service NAME\n"
114 #endif
115            "  -p              threading debug mode, implies -d\n"
116 #ifdef _WIN32
117            "  -u              uninstall service `%s'\n"
118            "  -U NAME         uninstall service NAME\n"
119 #endif
120            "  -s              enable stack checking\n"
121            "  -R RANDOM-SEED  random seed\n"
122            "  -h              display this help and exit\n"
123            "  -v              display version information and exit\n",
124            program_name, dflt_econfig
125 #ifdef _WIN32
126            , DEFAULT_SERVICE_NAME, DEFAULT_SERVICE_NAME
127 #endif
128         );
129 }
130
131 int
132 main(int argc, char **argv)
133 {
134     static char *oops_key[] = { "abort", "crash-dump", "nothing", NULL };
135     static void (*oops_hndlr[])(void) = { abort, crash_dump, ignore };
136     int flags = 0;
137 #if defined(_WIN32)
138     int install_service_set = 0;
139     char *program_name = NULL;
140     char *service_name = NULL;
141     int remove_service_set = 0;
142 #endif
143     char *config_file = NULL;
144     int force_bad_state = 0;
145     int op, idx, sig;
146     unsigned seed = time(NULL);
147
148     oops_handler = ignore;
149
150 #ifdef _WIN32
151 # define XOPTS "iI:uU:"
152 #else
153 # define XOPTS
154 #endif
155     while ((op = getopt(argc, argv, "de:E:FhpsR:v" XOPTS)) != EOF) {
156         switch (op) {
157         case 'p':
158             flags |= EMPTH_PRINT;
159             /* fall through */
160         case 'd':
161             oops_handler = abort;
162             daemonize = 0;
163             break;
164         case 'e':
165             config_file = optarg;
166             break;
167         case 'E':
168             idx = stmtch(optarg, oops_key, 0, sizeof(*oops_key));
169             if (idx < 0) {
170                 help(argv[0], "invalid argument for -E");
171                 return EXIT_FAILURE;
172             }
173             oops_handler = oops_hndlr[idx];
174             break;
175         case 'F':
176             force_bad_state = 1;
177             break;
178 #if defined(_WIN32)
179         case 'I':
180             service_name = optarg;
181             /* fall through */
182         case 'i':
183             install_service_set++;
184             break;
185         case 'U':
186             service_name = optarg;
187             /* fall through */
188         case 'u':
189             remove_service_set++;
190             break;
191 #endif  /* _WIN32 */
192         case 's':
193             flags |= EMPTH_STACKCHECK;
194             break;
195         case 'R':
196             seed = strtoul(optarg, NULL, 10);
197             break;
198         case 'v':
199             printf("%s\n\n%s", version, legal);
200             return EXIT_SUCCESS;
201         case 'h':
202             print_usage(argv[0]);
203             return EXIT_SUCCESS;
204         default:
205             help(argv[0], NULL);
206             return EXIT_FAILURE;
207         }
208     }
209
210     /* silently ignore operands for backward compatibility */
211
212 #if defined(_WIN32)
213     if ((!daemonize || flags || config_file != NULL)
214         && remove_service_set) {
215         fprintf(stderr, "Can't use -p, -s, -d or -e with either "
216             "-u or -U options\n");
217         exit(EXIT_FAILURE);
218     }
219     if ((!daemonize || flags) && install_service_set) {
220         fprintf(stderr,
221                 "Can't use -d, -p or -s with either -i or -I options\n");
222         exit(EXIT_FAILURE);
223     }
224     if (install_service_set && remove_service_set) {
225         fprintf(stderr, "Can't use both -u or -U and -i or -I options\n");
226         exit(EXIT_FAILURE);
227     }
228
229     if (remove_service_set)
230         return remove_service(service_name);
231     if (install_service_set) {
232         program_name = _fullpath(NULL, argv[0], 0);
233         if (config_file != NULL)
234             config_file = _fullpath(NULL, config_file, 0);
235     }
236 #endif  /* _WIN32 */
237
238     empfile_init();
239     if (emp_config(config_file) < 0)
240         exit(EXIT_FAILURE);
241     empfile_fixup();
242     if (read_builtin_tables() < 0)
243         exit(EXIT_FAILURE);
244     if (read_custom_tables() < 0)
245         exit(EXIT_FAILURE);
246     if (chdir(gamedir)) {
247         fprintf(stderr, "Can't chdir to %s (%s)\n",
248                 gamedir, strerror(errno));
249         exit(EXIT_FAILURE);
250     }
251
252 #if defined(_WIN32)
253     if (install_service_set)
254         return install_service(program_name, service_name, config_file);
255 #endif  /* _WIN32 */
256
257     init_server(seed, force_bad_state);
258
259 #if defined(_WIN32)
260     if (daemonize != 0) {
261         SERVICE_TABLE_ENTRY DispatchTable[]={
262             {"Empire Server", service_main},
263             {NULL, NULL}
264         };
265         if (StartServiceCtrlDispatcher(DispatchTable))
266             return 0;
267         else {
268             /*
269              * If it is service startup error then exit otherwise
270              * start server in the foreground
271              */
272             if (GetLastError() != ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
273                 logerror("Failed to dispatch service (%lu)",
274                          GetLastError());
275                 finish_server();
276                 exit(EXIT_FAILURE);
277             }
278         }
279     }
280     daemonize = 0;
281 #else  /* !_WIN32 */
282     if (daemonize) {
283         if (disassoc() < 0) {
284             logerror("Can't become daemon (%s)", strerror(errno));
285             exit(1);
286         }
287     }
288 #endif /* !_WIN32 */
289     start_server(flags);
290
291     for (;;) {
292         sig = empth_wait_for_signal();
293 #ifdef SIGHUP
294         if (sig == SIGHUP) {
295             /* if you make changes here, also update relo() */
296             journal_reopen();
297             update_reschedule();
298             logreopen();
299             continue;
300         }
301 #endif
302         break;
303     }
304
305     shutdwn(sig);
306     CANT_REACH();
307     finish_server();
308     return EXIT_SUCCESS;
309 }
310
311 static void
312 ignore(void)
313 {
314 }
315
316 static void
317 crash_dump(void)
318 {
319 #ifdef _WIN32
320     logerror("Crash dump is not implemented");
321 #else
322     pid_t pid;
323     int status;
324
325     fflush(NULL);
326     pid = fork();
327     if (pid < 0) {
328         logerror("Can't fork for crash dump (%s)", strerror(errno));
329         return;
330     }
331     if (pid == 0)
332         raise(SIGABRT);         /* child */
333
334     /* parent */
335     while (waitpid(pid, &status, 0) < 0) {
336         if (errno != EINTR) {
337             logerror("Can't get crash dumping child's status (%s)",
338                      strerror(errno));
339             return;
340         }
341     }
342     run_hook(post_crash_dump_hook, "post-crash-dump");
343     logerror("Crash dump complete");
344 #endif
345 }
346
347 /*
348  * Initialize for serving, acquire resources.
349  */
350 static void
351 init_server(unsigned seed, int force_bad_state)
352 {
353     seed_prng(seed);
354 #if defined(_WIN32)
355     loc_NTInit();
356 #endif
357     player_init();
358     ef_init_srv(force_bad_state);
359     io_init();
360     init_nreport();
361
362     if (journal_startup() < 0)
363         exit(1);
364     journal_prng(seed);
365     loginit("server");
366 }
367
368 /*
369  * Start serving.
370  */
371 void
372 start_server(int flags)
373 {
374     pid_t pid;
375
376     pid = getpid();
377     create_pidfile(pidfname, pid);
378     logerror("------------------------------------------------------");
379     logerror("Empire server (pid %d) started", (int)pid);
380
381     empth_init((void **)&player, flags);
382
383     update_lock = empth_rwlock_create("Update");
384     shutdown_lock = empth_rwlock_create("Shutdown");
385     if (!update_lock || !shutdown_lock)
386         exit_nomem();
387
388     market_init();
389     update_init();
390     empth_create(player_accept, 50 * 1024, flags, "AcceptPlayers", NULL);
391 }
392
393 /*
394  * Finish serving, release resources.
395  */
396 void
397 finish_server(void)
398 {
399     ef_fin_srv();
400     journal_shutdown();
401     remove(pidfname);
402 }
403
404 static void
405 create_pidfile(char *fname, pid_t pid)
406 {
407     FILE *pidf = fopen(fname, "w");
408     if (!pidf
409         || fprintf(pidf, "%d\n", (int)pid) < 0
410         || fclose(pidf)) {
411         logerror("Can't write PID file (%s)", strerror(errno));
412         exit(1);
413     }
414 }
415
416 void
417 shutdwn(int sig)
418 {
419     struct player *p;
420     time_t now = time(NULL);
421     int i;
422
423     logerror("Shutdown commencing (cleaning up threads.)");
424
425     for (p = player_next(NULL); p; p = player_next(p)) {
426         if (p->state != PS_PLAYING)
427             continue;
428         pr_flash(p, "Server shutting down...\n");
429         io_set_eof(p->iop);
430         p->aborted = 1;
431         p->may_sleep = PLAYER_SLEEP_NEVER;
432         if (p->command) {
433             pr_flash(p, "Shutdown aborting command\n");
434         }
435         empth_wakeup(p->proc);
436     }
437
438     empth_rwlock_wrlock(shutdown_lock);
439     empth_yield();
440
441     for (i = 1; i <= 3 && player_next(NULL); i++) {
442         logerror("Waiting for player threads to terminate\n");
443         empth_sleep(now + i);
444     }
445
446     for (p = player_next(NULL); p; p = player_next(p))
447         logerror("Player %d lingers, output might be lost", p->cnum);
448
449     if (sig)
450         logerror("Server shutting down on signal %d", sig);
451     else
452         logerror("Server shutting down at deity's request");
453     finish_server();
454
455 #if defined(_WIN32)
456     if (daemonize)
457         stop_service();
458 #endif
459     exit(0);
460 }
461
462 #if defined(_WIN32)
463 static void
464 loc_NTInit(void)
465 {
466     int rc;
467
468     rc = w32_socket_init();
469     if (rc != 0) {
470         logerror("WSAStartup Failed, error code %d\n", rc);
471         exit(1);
472     }
473 }
474 #endif