1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2021, 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-2017
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 "player.h"
62 #include "prototypes.h"
63 #include "server.h"
64 #include "version.h"
65 
66 static void ignore(void);
67 static void crash_dump(void);
68 static void init_server(unsigned, int);
69 static void create_pidfile(char *, pid_t);
70 
71 #if defined(_WIN32)
72 static void loc_NTInit(void);
73 #endif
74 
75 /*
76  * Lock to synchronize player threads with update.
77  * Update holds it exclusive, commands hold it shared.
78  */
79 empth_rwlock_t *update_lock;
80 /*
81  * Lock to synchronize player threads with shutdown.
82  * Shutdown holds it exclusive, player threads in state PS_PLAYING
83  * hold it shared.
84  */
85 empth_rwlock_t *shutdown_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
help(char * program_name,char * complaint)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
print_usage(char * program_name)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
main(int argc,char ** argv)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 = 0;
144     int seed_set = 0;
145 
146     oops_handler = ignore;
147 
148 #ifdef _WIN32
149 # define XOPTS "iI:uU:"
150 #else
151 # define XOPTS
152 #endif
153     while ((op = getopt(argc, argv, "de:E:FhpsR:v" XOPTS)) != EOF) {
154 	switch (op) {
155 	case 'p':
156 	    flags |= EMPTH_PRINT;
157 	    /* fall through */
158 	case 'd':
159 	    oops_handler = abort;
160 	    daemonize = 0;
161 	    break;
162 	case 'e':
163 	    config_file = optarg;
164 	    break;
165 	case 'E':
166 	    idx = stmtch(optarg, oops_key, 0, sizeof(*oops_key));
167 	    if (idx < 0) {
168 		help(argv[0], "invalid argument for -E");
169 		return EXIT_FAILURE;
170 	    }
171 	    oops_handler = oops_hndlr[idx];
172 	    break;
173 	case 'F':
174 	    force_bad_state = 1;
175 	    break;
176 #if defined(_WIN32)
177 	case 'I':
178 	    service_name = optarg;
179 	    /* fall through */
180 	case 'i':
181 	    install_service_set++;
182 	    break;
183 	case 'U':
184 	    service_name = optarg;
185 	    /* fall through */
186 	case 'u':
187 	    remove_service_set++;
188 	    break;
189 #endif	/* _WIN32 */
190 	case 's':
191 	    flags |= EMPTH_STACKCHECK;
192 	    break;
193 	case 'R':
194 	    seed = strtoul(optarg, NULL, 10);
195 	    seed_set = 1;
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     if (!seed_set)
257 	seed = pick_seed();
258     init_server(seed, force_bad_state);
259 
260 #if defined(_WIN32)
261     if (daemonize != 0) {
262 	SERVICE_TABLE_ENTRY DispatchTable[]={
263 	    {"Empire Server", service_main},
264 	    {NULL, NULL}
265 	};
266 	if (StartServiceCtrlDispatcher(DispatchTable))
267 	    return 0;
268 	else {
269 	    /*
270 	     * If it is service startup error then exit otherwise
271 	     * start server in the foreground
272 	     */
273 	    if (GetLastError() != ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
274 		logerror("Failed to dispatch service (%lu)",
275 			 GetLastError());
276 		finish_server();
277 		exit(EXIT_FAILURE);
278 	    }
279 	}
280     }
281     daemonize = 0;
282 #else  /* !_WIN32 */
283     if (daemonize) {
284 	if (disassoc() < 0) {
285 	    logerror("Can't become daemon (%s)", strerror(errno));
286 	    exit(1);
287 	}
288     }
289 #endif /* !_WIN32 */
290     start_server(flags);
291 
292     for (;;) {
293 	sig = empth_wait_for_signal();
294 #ifdef SIGHUP
295 	if (sig == SIGHUP) {
296 	    /* if you make changes here, also update relo() */
297 	    journal_reopen();
298 	    update_reschedule();
299 	    logreopen();
300 	    continue;
301 	}
302 #endif
303 	break;
304     }
305 
306     shutdwn(sig);
307     CANT_REACH();
308     finish_server();
309     return EXIT_SUCCESS;
310 }
311 
312 static void
ignore(void)313 ignore(void)
314 {
315 }
316 
317 static void
crash_dump(void)318 crash_dump(void)
319 {
320 #ifdef _WIN32
321     logerror("Crash dump is not implemented");
322 #else
323     pid_t pid;
324     int status;
325 
326     fflush(NULL);
327     pid = fork();
328     if (pid < 0) {
329 	logerror("Can't fork for crash dump (%s)", strerror(errno));
330 	return;
331     }
332     if (pid == 0)
333 	raise(SIGABRT);		/* child */
334 
335     /* parent */
336     while (waitpid(pid, &status, 0) < 0) {
337 	if (errno != EINTR) {
338 	    logerror("Can't get crash dumping child's status (%s)",
339 		     strerror(errno));
340 	    return;
341 	}
342     }
343     run_hook(post_crash_dump_hook, "post-crash-dump");
344     logerror("Crash dump complete");
345 #endif
346 }
347 
348 /*
349  * Initialize for serving, acquire resources.
350  */
351 static void
init_server(unsigned seed,int force_bad_state)352 init_server(unsigned seed, int force_bad_state)
353 {
354     seed_prng(seed);
355 #if defined(_WIN32)
356     loc_NTInit();
357 #endif
358     player_init();
359     ef_init_srv(force_bad_state);
360     io_init();
361     init_nreport();
362 
363     if (journal_startup() < 0)
364 	exit(1);
365     journal_prng(seed);
366     loginit("server");
367 }
368 
369 /*
370  * Start serving.
371  */
372 void
start_server(int flags)373 start_server(int flags)
374 {
375     pid_t pid;
376 
377     pid = getpid();
378     create_pidfile(pidfname, pid);
379     logerror("------------------------------------------------------");
380     logerror("Empire server (pid %d) started", (int)pid);
381     if (running_test_suite)
382 	logerror("Configured for testing");
383     else if (strstr(version, "UNKNOWN-"))
384 	logerror("Warning: version number unknown");
385 
386     empth_init((void **)&player, flags);
387 
388     update_lock = empth_rwlock_create("Update");
389     shutdown_lock = empth_rwlock_create("Shutdown");
390     if (!update_lock || !shutdown_lock)
391 	exit_nomem();
392 
393     market_init();
394     update_init();
395     empth_create(player_accept, 65536, flags, "AcceptPlayers", NULL);
396 }
397 
398 /*
399  * Finish serving, release resources.
400  */
401 void
finish_server(void)402 finish_server(void)
403 {
404     ef_fin_srv();
405     journal_shutdown();
406     remove(pidfname);
407 }
408 
409 static void
create_pidfile(char * fname,pid_t pid)410 create_pidfile(char *fname, pid_t pid)
411 {
412     FILE *pidf = fopen(fname, "w");
413     if (!pidf
414 	|| fprintf(pidf, "%d\n", (int)pid) < 0
415 	|| fclose(pidf)) {
416 	logerror("Can't write PID file (%s)", strerror(errno));
417 	exit(1);
418     }
419 }
420 
421 void
shutdwn(int sig)422 shutdwn(int sig)
423 {
424     struct player *p;
425     time_t now = time(NULL);
426     int i;
427 
428     logerror("Shutdown commencing (cleaning up threads.)");
429 
430     for (p = player_next(NULL); p; p = player_next(p)) {
431 	if (p->state != PS_PLAYING)
432 	    continue;
433 	pr_flash(p, "Server shutting down...\n");
434 	io_set_eof(p->iop);
435 	p->aborted = 1;
436 	p->may_sleep = PLAYER_SLEEP_NEVER;
437 	if (p->command) {
438 	    pr_flash(p, "Shutdown aborting command\n");
439 	}
440 	empth_wakeup(p->proc);
441     }
442 
443     empth_rwlock_wrlock(shutdown_lock);
444     empth_yield();
445 
446     for (i = 1; i <= 3 && player_next(NULL); i++) {
447 	logerror("Waiting for player threads to terminate\n");
448 	empth_sleep(now + i);
449     }
450 
451     for (p = player_next(NULL); p; p = player_next(p))
452 	logerror("Player %d lingers, output might be lost", p->cnum);
453 
454     if (sig)
455 	logerror("Server shutting down on signal %d", sig);
456     else
457 	logerror("Server shutting down at deity's request");
458     finish_server();
459 
460 #if defined(_WIN32)
461     if (daemonize)
462 	stop_service();
463 #endif
464     exit(0);
465 }
466 
467 #if defined(_WIN32)
468 static void
loc_NTInit(void)469 loc_NTInit(void)
470 {
471     int rc;
472 
473     rc = w32_socket_init();
474     if (rc != 0) {
475 	logerror("WSAStartup Failed, error code %d\n", rc);
476 	exit(1);
477     }
478 }
479 #endif
480