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