]> git.pond.sub.org Git - empserver/blob - src/server/main.c
Give init_server() internal linkage
[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-2010
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);
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 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     /* silently ignore operands for backward compatibility */
204
205 #if defined(_WIN32)
206     if ((!daemonize || flags || config_file != NULL)
207         && remove_service_set) {
208         fprintf(stderr, "Can't use -p, -s, -d or -e with either "
209             "-u or -U options\n");
210         exit(EXIT_FAILURE);
211     }
212     if ((!daemonize || flags) && install_service_set) {
213         fprintf(stderr,
214                 "Can't use -d, -p or -s with either -i or -I options\n");
215         exit(EXIT_FAILURE);
216     }
217     if (install_service_set && remove_service_set) {
218         fprintf(stderr, "Can't use both -u or -U and -i or -I options\n");
219         exit(EXIT_FAILURE);
220     }
221
222     if (remove_service_set)
223         return remove_service(service_name);
224     if (install_service_set) {
225         program_name = _fullpath(NULL, argv[0], 0);
226         if (config_file != NULL)
227             config_file = _fullpath(NULL, config_file, 0);
228     }
229 #endif  /* _WIN32 */
230
231     empfile_init();
232     if (emp_config(config_file) < 0)
233         exit(EXIT_FAILURE);
234     empfile_fixup();
235     if (read_builtin_tables() < 0)
236         exit(EXIT_FAILURE);
237     if (read_custom_tables() < 0)
238         exit(EXIT_FAILURE);
239     if (chdir(gamedir)) {
240         fprintf(stderr, "Can't chdir to %s (%s)\n",
241                 gamedir, strerror(errno));
242         exit(EXIT_FAILURE);
243     }
244
245 #if defined(_WIN32)
246     if (install_service_set)
247         return install_service(program_name, service_name, config_file);
248 #endif  /* _WIN32 */
249
250     init_server(seed);
251
252 #if defined(_WIN32)
253     if (daemonize != 0) {
254         SERVICE_TABLE_ENTRY DispatchTable[]={
255             {"Empire Server", service_main},
256             {NULL, NULL}
257         };
258         if (StartServiceCtrlDispatcher(DispatchTable))
259             return 0;
260         else {
261             /*
262              * If it is service startup error then exit otherwise
263              * start server in the foreground
264              */
265             if (GetLastError() != ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
266                 logerror("Failed to dispatch service (%lu)",
267                          GetLastError());
268                 finish_server();
269                 exit(EXIT_FAILURE);
270             }
271         }
272     }
273     daemonize = 0;
274 #else  /* !_WIN32 */
275     if (daemonize) {
276         if (disassoc() < 0) {
277             logerror("Can't become daemon (%s)", strerror(errno));
278             exit(1);
279         }
280     }
281 #endif /* !_WIN32 */
282     start_server(flags);
283     journal_prng(seed);
284
285     for (;;) {
286         sig = empth_wait_for_signal();
287 #ifdef SIGHUP
288         if (sig == SIGHUP) {
289             /* if you make changes here, also update relo() */
290             journal_reopen();
291             update_reschedule();
292             logreopen();
293             continue;
294         }
295 #endif
296         break;
297     }
298
299     shutdwn(sig);
300     CANT_REACH();
301     finish_server();
302     return EXIT_SUCCESS;
303 }
304
305 static void
306 ignore(void)
307 {
308 }
309
310 static void
311 crash_dump(void)
312 {
313 #ifdef _WIN32
314     logerror("Crash dump is not implemented");
315 #else
316     pid_t pid;
317     int status;
318
319     fflush(NULL);
320     pid = fork();
321     if (pid < 0) {
322         logerror("Can't fork for crash dump (%s)", strerror(errno));
323         return;
324     }
325     if (pid == 0)
326         raise(SIGABRT);         /* child */
327
328     /* parent */
329     while (waitpid(pid, &status, 0) < 0) {
330         if (errno != EINTR) {
331             logerror("Can't get crash dumping child's status (%s)",
332                      strerror(errno));
333             return;
334         }
335     }
336     run_hook(post_crash_dump_hook, "post-crash-dump");
337     logerror("Crash dump complete");
338 #endif
339 }
340
341 /*
342  * Initialize for serving, acquire resources.
343  */
344 static void
345 init_server(unsigned seed)
346 {
347     srandom(seed);
348 #if defined(_WIN32)
349     loc_NTInit();
350 #endif
351     player_init();
352     ef_init_srv();
353     io_init();
354     init_nreport();
355
356     loginit("server");
357 }
358
359 /*
360  * Start serving.
361  */
362 void
363 start_server(int flags)
364 {
365     pid_t pid;
366
367     pid = getpid();
368     create_pidfile(pidfname, pid);
369     logerror("------------------------------------------------------");
370     logerror("Empire server (pid %d) started", (int)pid);
371
372     empth_init((void **)&player, flags);
373
374     if (journal_startup() < 0)
375         exit(1);
376
377     market_init();
378     update_init();
379     empth_create(player_accept, 50 * 1024, flags, "AcceptPlayers", NULL);
380 }
381
382 /*
383  * Finish serving, release resources.
384  */
385 void
386 finish_server(void)
387 {
388     ef_fin_srv();
389     journal_shutdown();
390     remove(pidfname);
391 }
392
393 static void
394 create_pidfile(char *fname, pid_t pid)
395 {
396     FILE *pidf = fopen(fname, "w");
397     if (!pidf
398         || fprintf(pidf, "%d\n", (int)pid) < 0
399         || fclose(pidf)) {
400         logerror("Can't write PID file (%s)", strerror(errno));
401         exit(1);
402     }
403 }
404
405 void
406 shutdwn(int sig)
407 {
408     struct player *p;
409     time_t now;
410     int i, queues_drained;
411
412     logerror("Shutdown commencing (cleaning up threads.)");
413
414     for (p = player_next(NULL); p; p = player_next(p)) {
415         if (p->state != PS_PLAYING)
416             continue;
417         pr_flash(p, "Server shutting down...\n");
418         p->state = PS_SHUTDOWN;
419         p->may_sleep = PLAYER_SLEEP_NEVER;
420         p->aborted++;
421         if (p->command) {
422             pr_flash(p, "Shutdown aborting command\n");
423         }
424         empth_wakeup(p->proc);
425     }
426     empth_rwlock_wrlock(play_lock);
427
428     now = time(NULL);
429     empth_yield();
430     for (i = 1; i <= 3; i++) {
431         queues_drained = 1;
432         for (p = player_next(NULL); p; p = player_next(p)) {
433             if (io_outputwaiting(p->iop))
434                 queues_drained = 0;
435         }
436         if (queues_drained)
437             break;
438         logerror("Waiting for player output to drain\n");
439         empth_sleep(now + i);
440     }
441
442     for (p = player_next(NULL); p; p = player_next(p)) {
443         if (io_outputwaiting(p->iop))
444             logerror("Output for player %d lost", p->cnum);
445     }
446
447     if (sig)
448         logerror("Server shutting down on signal %d", sig);
449     else
450         logerror("Server shutting down at deity's request");
451     finish_server();
452
453 #if defined(_WIN32)
454     if (daemonize)
455         stop_service();
456 #endif
457     exit(0);
458 }
459
460 #if defined(_WIN32)
461 static void
462 loc_NTInit(void)
463 {
464     int rc;
465
466     rc = w32_socket_init();
467     if (rc != 0) {
468         logerror("WSAStartup Failed, error code %d\n", rc);
469         exit(1);
470     }
471 }
472 #endif