]> git.pond.sub.org Git - empserver/blob - src/server/main.c
Fix PRNG seeding to resist guessing
[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 = 0;
147     int seed_set = 0;
148
149     oops_handler = ignore;
150
151 #ifdef _WIN32
152 # define XOPTS "iI:uU:"
153 #else
154 # define XOPTS
155 #endif
156     while ((op = getopt(argc, argv, "de:E:FhpsR:v" XOPTS)) != EOF) {
157         switch (op) {
158         case 'p':
159             flags |= EMPTH_PRINT;
160             /* fall through */
161         case 'd':
162             oops_handler = abort;
163             daemonize = 0;
164             break;
165         case 'e':
166             config_file = optarg;
167             break;
168         case 'E':
169             idx = stmtch(optarg, oops_key, 0, sizeof(*oops_key));
170             if (idx < 0) {
171                 help(argv[0], "invalid argument for -E");
172                 return EXIT_FAILURE;
173             }
174             oops_handler = oops_hndlr[idx];
175             break;
176         case 'F':
177             force_bad_state = 1;
178             break;
179 #if defined(_WIN32)
180         case 'I':
181             service_name = optarg;
182             /* fall through */
183         case 'i':
184             install_service_set++;
185             break;
186         case 'U':
187             service_name = optarg;
188             /* fall through */
189         case 'u':
190             remove_service_set++;
191             break;
192 #endif  /* _WIN32 */
193         case 's':
194             flags |= EMPTH_STACKCHECK;
195             break;
196         case 'R':
197             seed = strtoul(optarg, NULL, 10);
198             seed_set = 1;
199             break;
200         case 'v':
201             printf("%s\n\n%s", version, legal);
202             return EXIT_SUCCESS;
203         case 'h':
204             print_usage(argv[0]);
205             return EXIT_SUCCESS;
206         default:
207             help(argv[0], NULL);
208             return EXIT_FAILURE;
209         }
210     }
211
212     /* silently ignore operands for backward compatibility */
213
214 #if defined(_WIN32)
215     if ((!daemonize || flags || config_file != NULL)
216         && remove_service_set) {
217         fprintf(stderr, "Can't use -p, -s, -d or -e with either "
218             "-u or -U options\n");
219         exit(EXIT_FAILURE);
220     }
221     if ((!daemonize || flags) && install_service_set) {
222         fprintf(stderr,
223                 "Can't use -d, -p or -s with either -i or -I options\n");
224         exit(EXIT_FAILURE);
225     }
226     if (install_service_set && remove_service_set) {
227         fprintf(stderr, "Can't use both -u or -U and -i or -I options\n");
228         exit(EXIT_FAILURE);
229     }
230
231     if (remove_service_set)
232         return remove_service(service_name);
233     if (install_service_set) {
234         program_name = _fullpath(NULL, argv[0], 0);
235         if (config_file != NULL)
236             config_file = _fullpath(NULL, config_file, 0);
237     }
238 #endif  /* _WIN32 */
239
240     empfile_init();
241     if (emp_config(config_file) < 0)
242         exit(EXIT_FAILURE);
243     empfile_fixup();
244     if (read_builtin_tables() < 0)
245         exit(EXIT_FAILURE);
246     if (read_custom_tables() < 0)
247         exit(EXIT_FAILURE);
248     if (chdir(gamedir)) {
249         fprintf(stderr, "Can't chdir to %s (%s)\n",
250                 gamedir, strerror(errno));
251         exit(EXIT_FAILURE);
252     }
253
254 #if defined(_WIN32)
255     if (install_service_set)
256         return install_service(program_name, service_name, config_file);
257 #endif  /* _WIN32 */
258
259     if (!seed_set)
260         seed = pick_seed();
261     init_server(seed, force_bad_state);
262
263 #if defined(_WIN32)
264     if (daemonize != 0) {
265         SERVICE_TABLE_ENTRY DispatchTable[]={
266             {"Empire Server", service_main},
267             {NULL, NULL}
268         };
269         if (StartServiceCtrlDispatcher(DispatchTable))
270             return 0;
271         else {
272             /*
273              * If it is service startup error then exit otherwise
274              * start server in the foreground
275              */
276             if (GetLastError() != ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
277                 logerror("Failed to dispatch service (%lu)",
278                          GetLastError());
279                 finish_server();
280                 exit(EXIT_FAILURE);
281             }
282         }
283     }
284     daemonize = 0;
285 #else  /* !_WIN32 */
286     if (daemonize) {
287         if (disassoc() < 0) {
288             logerror("Can't become daemon (%s)", strerror(errno));
289             exit(1);
290         }
291     }
292 #endif /* !_WIN32 */
293     start_server(flags);
294
295     for (;;) {
296         sig = empth_wait_for_signal();
297 #ifdef SIGHUP
298         if (sig == SIGHUP) {
299             /* if you make changes here, also update relo() */
300             journal_reopen();
301             update_reschedule();
302             logreopen();
303             continue;
304         }
305 #endif
306         break;
307     }
308
309     shutdwn(sig);
310     CANT_REACH();
311     finish_server();
312     return EXIT_SUCCESS;
313 }
314
315 static void
316 ignore(void)
317 {
318 }
319
320 static void
321 crash_dump(void)
322 {
323 #ifdef _WIN32
324     logerror("Crash dump is not implemented");
325 #else
326     pid_t pid;
327     int status;
328
329     fflush(NULL);
330     pid = fork();
331     if (pid < 0) {
332         logerror("Can't fork for crash dump (%s)", strerror(errno));
333         return;
334     }
335     if (pid == 0)
336         raise(SIGABRT);         /* child */
337
338     /* parent */
339     while (waitpid(pid, &status, 0) < 0) {
340         if (errno != EINTR) {
341             logerror("Can't get crash dumping child's status (%s)",
342                      strerror(errno));
343             return;
344         }
345     }
346     run_hook(post_crash_dump_hook, "post-crash-dump");
347     logerror("Crash dump complete");
348 #endif
349 }
350
351 /*
352  * Initialize for serving, acquire resources.
353  */
354 static void
355 init_server(unsigned seed, int force_bad_state)
356 {
357     seed_prng(seed);
358 #if defined(_WIN32)
359     loc_NTInit();
360 #endif
361     player_init();
362     ef_init_srv(force_bad_state);
363     io_init();
364     init_nreport();
365
366     if (journal_startup() < 0)
367         exit(1);
368     journal_prng(seed);
369     loginit("server");
370 }
371
372 /*
373  * Start serving.
374  */
375 void
376 start_server(int flags)
377 {
378     pid_t pid;
379
380     pid = getpid();
381     create_pidfile(pidfname, pid);
382     logerror("------------------------------------------------------");
383     logerror("Empire server (pid %d) started", (int)pid);
384
385     empth_init((void **)&player, flags);
386
387     update_lock = empth_rwlock_create("Update");
388     shutdown_lock = empth_rwlock_create("Shutdown");
389     if (!update_lock || !shutdown_lock)
390         exit_nomem();
391
392     market_init();
393     update_init();
394     empth_create(player_accept, 50 * 1024, flags, "AcceptPlayers", NULL);
395 }
396
397 /*
398  * Finish serving, release resources.
399  */
400 void
401 finish_server(void)
402 {
403     ef_fin_srv();
404     journal_shutdown();
405     remove(pidfname);
406 }
407
408 static void
409 create_pidfile(char *fname, pid_t pid)
410 {
411     FILE *pidf = fopen(fname, "w");
412     if (!pidf
413         || fprintf(pidf, "%d\n", (int)pid) < 0
414         || fclose(pidf)) {
415         logerror("Can't write PID file (%s)", strerror(errno));
416         exit(1);
417     }
418 }
419
420 void
421 shutdwn(int sig)
422 {
423     struct player *p;
424     time_t now = time(NULL);
425     int i;
426
427     logerror("Shutdown commencing (cleaning up threads.)");
428
429     for (p = player_next(NULL); p; p = player_next(p)) {
430         if (p->state != PS_PLAYING)
431             continue;
432         pr_flash(p, "Server shutting down...\n");
433         io_set_eof(p->iop);
434         p->aborted = 1;
435         p->may_sleep = PLAYER_SLEEP_NEVER;
436         if (p->command) {
437             pr_flash(p, "Shutdown aborting command\n");
438         }
439         empth_wakeup(p->proc);
440     }
441
442     empth_rwlock_wrlock(shutdown_lock);
443     empth_yield();
444
445     for (i = 1; i <= 3 && player_next(NULL); i++) {
446         logerror("Waiting for player threads to terminate\n");
447         empth_sleep(now + i);
448     }
449
450     for (p = player_next(NULL); p; p = player_next(p))
451         logerror("Player %d lingers, output might be lost", p->cnum);
452
453     if (sig)
454         logerror("Server shutting down on signal %d", sig);
455     else
456         logerror("Server shutting down at deity's request");
457     finish_server();
458
459 #if defined(_WIN32)
460     if (daemonize)
461         stop_service();
462 #endif
463     exit(0);
464 }
465
466 #if defined(_WIN32)
467 static void
468 loc_NTInit(void)
469 {
470     int rc;
471
472     rc = w32_socket_init();
473     if (rc != 0) {
474         logerror("WSAStartup Failed, error code %d\n", rc);
475         exit(1);
476     }
477 }
478 #endif