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