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