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