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