]> git.pond.sub.org Git - empserver/blob - src/server/main.c
(config_tables, custom_tables, read_config_tables, read_custom_tables)
[empserver] / src / server / main.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2006, 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: Thread and signal initialization for Empire Server
29  * 
30  *  Known contributors to this file:
31  *     Dave Pare, 1994
32  *     Steve McClure, 1996, 1998
33  *     Doug Hay, 1998
34  */
35
36 #include <config.h>
37
38 #include <signal.h>
39 #if !defined(_WIN32)
40 #include <sys/ioctl.h>
41 #endif
42 #include <errno.h>
43 #include <stdio.h>
44 #include <string.h>
45
46 #if defined(_WIN32)
47 #define WIN32
48 #include <winsock2.h>
49 #undef NS_ALL
50 #include <process.h>
51 #include "../lib/gen/getopt.h"
52 #include "service.h"
53 #include "direct.h"
54 #endif
55
56 #include "misc.h"
57 #include "nat.h"
58 #include "file.h"
59 #include "player.h"
60 #include "empthread.h"
61 #include "plane.h"
62 #include "nuke.h"
63 #include "land.h"
64 #include "ship.h"
65 #include "sect.h"
66 #include "product.h"
67 #include "optlist.h"
68 #include "server.h"
69 #include "version.h"
70 #include "prototypes.h"
71
72 static void create_pidfile(char *, pid_t);
73
74 #if defined(_WIN32)
75 static void loc_NTInit(void);
76 static void loc_NTTerm(void);
77 #endif
78
79 static char pidfname[] = "server.pid";
80
81 /* Run as daemon?  If yes, detach from controlling terminal etc. */
82 int daemonize = 1;
83
84 static void
85 print_usage(char *program_name)
86 {
87     printf("Usage: %s [OPTION]...\n"
88            "  -d              debug mode\n"
89            "  -e CONFIG-FILE  configuration file\n"
90            "                  (default %s)\n"
91            "  -h              display this help and exit\n"
92 #ifdef _WIN32
93            "  -i              install service `%s'\n"
94            "  -I NAME         install service NAME\n"
95 #endif
96            "  -p              threading debug mode, implies -d\n"
97 #ifdef _WIN32
98            "  -r              remove service `%s'\n"
99            "  -R NAME         remove service NAME\n"
100 #endif
101            "  -s              enable stack checking\n"
102            "  -v              display version information and exit\n",
103            program_name, dflt_econfig
104 #ifdef _WIN32
105            , DEFAULT_SERVICE_NAME, DEFAULT_SERVICE_NAME
106 #endif
107         );
108 }
109
110 int
111 main(int argc, char **argv)
112 {
113     int flags = 0;
114 #if defined(_WIN32)
115     int install_service_set = 0;
116     char *program_name = NULL;
117     char *service_name = NULL;
118     int remove_service_set = 0;
119 #endif
120     char *config_file = NULL;
121     int op;
122
123 #ifdef _WIN32
124 # define XOPTS "iI:rR:"
125 #else
126 # define XOPTS
127 #endif
128     while ((op = getopt(argc, argv, "de:hpsv" XOPTS)) != EOF) {
129         switch (op) {
130         case 'p':
131             flags |= EMPTH_PRINT;
132             /* fall through */
133         case 'd':
134             debug = 1;
135             daemonize = 0;
136             break;
137         case 'e':
138             config_file = optarg;
139             break;
140 #if defined(_WIN32)
141         case 'I':
142             service_name = optarg;
143             /*
144              * fall out
145              */
146         case 'i':
147             install_service_set++;
148             break;
149         case 'R':
150             service_name = optarg;
151             /*
152              * fall out
153              */
154         case 'r':
155             remove_service_set++;
156             break;
157 #endif
158         case 's':
159             flags |= EMPTH_STACKCHECK;
160             break;
161         case 'v':
162             printf("%s\n\n%s", version, legal);
163             return EXIT_SUCCESS;
164         case 'h':
165             print_usage(argv[0]);
166             return EXIT_SUCCESS;
167         default:
168             fprintf(stderr, "Try -h for help.\n");
169             return EXIT_FAILURE;
170         }
171     }
172
173 #if defined(_WIN32)
174     if ((debug || flags || config_file != NULL) &&
175         remove_service_set) {
176         fprintf(stderr, "Can't use -p, -s, -d or -e with either "
177             "-r or -R options\n");
178         exit(EXIT_FAILURE);
179     }
180     if ((debug || flags) && install_service_set) {
181         fprintf(stderr, "Can't use -d, -p or -s with either "
182             "-i or -I options\n");
183         exit(EXIT_FAILURE);
184     }
185     if (install_service_set && remove_service_set) {
186         fprintf(stderr, "Can't use both -r or -R and -i or -I "
187             "options\n");
188         exit(EXIT_FAILURE);
189     }
190 #endif  /* _WIN32 */
191
192
193 #if defined(_WIN32)
194     if (remove_service_set)
195         return remove_service(service_name);
196     if (install_service_set) {
197         program_name = _fullpath(NULL, argv[0], 0);
198         if (config_file != NULL)
199             config_file = _fullpath(NULL, config_file, 0);
200     }
201 #endif  /* _WIN32 */
202
203     if (emp_config(config_file) < 0)
204         exit(EXIT_FAILURE);
205     ef_init();
206     if (chdir(configdir)) {
207         fprintf(stderr, "Can't chdir to %s (%s)\n", configdir, strerror(errno));
208         exit(EXIT_FAILURE);
209     }
210     if (chdir(builtindir)) {
211         fprintf(stderr, "Can't chdir to %s (%s)\n", builtindir, strerror(errno));
212         exit(EXIT_FAILURE);
213     }
214     if (read_builtin_tables() < 0)
215         exit(EXIT_FAILURE);
216     if (chdir(configdir)) {
217         fprintf(stderr, "Can't chdir to %s (%s)\n", configdir, strerror(errno));
218         exit(EXIT_FAILURE);
219     }
220     if (read_custom_tables() < 0)
221         exit(EXIT_FAILURE);
222     if (chdir(gamedir)) {
223         fprintf(stderr, "Can't chdir to %s (%s)\n", gamedir, strerror(errno));
224         exit(EXIT_FAILURE);
225     }
226
227 #if defined(_WIN32)
228     if (install_service_set)
229         return install_service(program_name, service_name, config_file);
230 #endif  /* _WIN32 */
231
232     init_server();
233
234 #if defined(_WIN32)
235     if (daemonize != 0) {
236         SERVICE_TABLE_ENTRY DispatchTable[]={{"Empire Server", service_main},{NULL, NULL}};
237         if (StartServiceCtrlDispatcher(DispatchTable))
238             return 0;
239         else {
240             /*
241              * If it is service startup error then exit otherwise
242              * start server in the foreground
243              */
244             if (GetLastError() != ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
245                 logerror("Failed to dispatch service (%lu)", GetLastError());
246                 finish_server();
247                 exit(EXIT_FAILURE);
248             }
249         }
250     }
251     daemonize = 0;
252 #else  /* !_WIN32 */
253     if (daemonize) {
254         if (disassoc() < 0) {
255             logerror("Can't become daemon (%s)", strerror(errno));
256             _exit(1);
257         }
258     }
259 #endif /* !_WIN32 */
260     start_server(flags);
261
262     empth_exit();
263
264     CANT_HAPPEN("main thread terminated");
265     finish_server();
266     return EXIT_SUCCESS;
267 }
268
269
270 /*
271  * Initialize for serving, acquire resources.
272  */
273 void
274 init_server(void)
275 {
276     srandom(time(NULL));
277 #if defined(_WIN32)
278     loc_NTInit();
279 #endif
280     update_policy_check();
281     shutdown_init();
282     player_init();
283     ef_init_srv();
284     io_init();
285     init_nreport();
286
287     if (opt_MOB_ACCESS) {
288         /* This fixes up mobility upon restart */
289         mobility_init();
290     }
291
292     loginit("server");
293 }
294
295 /*
296  * Start serving.
297  */
298 void
299 start_server(int flags)
300 {
301     pid_t pid;
302 #if !defined(_WIN32)
303     struct sigaction act;
304 #endif
305
306     pid = getpid();
307     create_pidfile(pidfname, pid);
308     logerror("------------------------------------------------------");
309     logerror("Empire server (pid %d) started", (int)pid);
310
311 #if !defined(_WIN32)
312     /* signal() should not be used with mit pthreads. Anyway if u
313        have a posix threads u definitly have posix signals -- Sasha */
314     act.sa_flags = 0;
315     sigemptyset(&act.sa_mask);
316     act.sa_handler = shutdwn;
317     sigaction(SIGTERM, &act, NULL);
318     sigaction(SIGINT, &act, NULL);
319     act.sa_handler = panic;
320     sigaction(SIGBUS, &act, NULL);
321     sigaction(SIGSEGV, &act, NULL);
322     sigaction(SIGILL, &act, NULL);
323     sigaction(SIGFPE, &act, NULL);
324     act.sa_handler = SIG_IGN;
325     sigaction(SIGPIPE, &act, NULL);
326 #endif /* !_WIN32 */
327
328     empth_init((void **)&player, flags);
329
330     empth_create(PP_ACCEPT, player_accept, (50 * 1024), flags,
331                  "AcceptPlayers", "Accept network connections", 0);
332     empth_create(PP_KILLIDLE, player_kill_idle, (50 * 1024), flags,
333                  "KillIdle", "Kills idle player connections", 0);
334     empth_create(PP_SCHED, update_sched, (50 * 1024), flags, "UpdateSched",
335                  "Schedules updates to occur", 0);
336     empth_create(PP_TIMESTAMP, delete_lostitems, (50 * 1024), flags,
337                  "DeleteItems", "Deletes old lost items", 0);
338     if (opt_MOB_ACCESS) {
339         /* Start the mobility access check thread */
340         empth_create(PP_TIMESTAMP, mobility_check, (50 * 1024), flags,
341                      "MobilityCheck", "Writes the timestamp file", 0);
342     }
343
344     if (opt_MARKET) {
345         empth_create(PP_TIMESTAMP, market_update, (50 * 1024), flags,
346                      "MarketUpdate", "Updates the market", 0);
347     }
348 }
349
350 /*
351  * Finish serving, release resources.
352  */
353 void
354 finish_server(void)
355 {
356     ef_fin_srv();
357 #if defined(_WIN32)
358     loc_NTTerm();
359 #endif
360     remove(pidfname);
361 }
362
363 static void
364 create_pidfile(char *fname, pid_t pid)
365 {
366     FILE *pidf = fopen(fname, "w");
367     if (!pidf
368         || fprintf(pidf, "%d\n", (int)pid) < 0
369         || fclose(pidf)) {
370         logerror("Can't write PID file (%s)", strerror(errno));
371         exit(1);
372     }
373 }
374
375 /* we're going down.  try to close the files at least */
376 #if !defined(_WIN32)
377 void
378 panic(int sig)
379 {
380     struct sigaction act;
381
382     act.sa_flags = 0;
383     sigemptyset(&act.sa_mask);
384     act.sa_handler = SIG_DFL;
385     sigaction(SIGBUS, &act, NULL);
386     sigaction(SIGSEGV, &act, NULL);
387     sigaction(SIGILL, &act, NULL);
388     sigaction(SIGFPE, &act, NULL);
389     logerror("server received fatal signal %d", sig);
390     log_last_commands();
391     ef_fin_srv();
392     if (CANT_HAPPEN(sig != SIGBUS && sig != SIGSEGV
393                     && sig != SIGILL && sig != SIGFPE))
394         _exit(1);
395     if (raise(sig))
396         _exit(1);
397 }
398 #endif /* _WIN32 */
399
400 void
401 shutdwn(int sig)
402 {
403     struct player *p;
404     time_t now;
405
406     logerror("Shutdown commencing (cleaning up threads.)");
407
408     for (p = player_next(0); p != 0; p = player_next(p)) {
409         if (p->state != PS_PLAYING)
410             continue;
411         pr_flash(p, "Server shutting down...\n");
412         p->state = PS_SHUTDOWN;
413         p->aborted++;
414         if (p->command) {
415             pr_flash(p, "Shutdown aborting command\n");
416         }
417         empth_wakeup(p->proc);
418     }
419
420     if (!sig) {
421         /* Sleep and let some cleanup happen - note this doesn't work
422            when called from a signal handler, since we may or may not
423            be in the right thread.  So we just pass by and kill 'em
424            all. */
425         time(&now);
426         empth_sleep(now + 1);
427     }
428
429     for (p = player_next(0); p != 0; p = player_next(p)) {
430         p->state = PS_KILL;
431         p->aborted++;
432         empth_terminate(p->proc);
433         p = player_delete(p);
434     }
435     if (sig)
436         logerror("Server shutting down on signal %d", sig);
437     else
438         logerror("Server shutting down at deity's request");
439     finish_server();
440
441 #if defined(_WIN32)
442     if (daemonize) {
443         stop_service();
444         return;
445     }
446 #endif
447     _exit(0);
448 }
449
450 #if defined(_WIN32)
451 static void
452 loc_NTInit(void)
453 {
454     int rc;
455     WORD wVersionRequested;
456     WSADATA wsaData;
457
458     wVersionRequested = MAKEWORD(2, 0);
459     rc = WSAStartup(wVersionRequested, &wsaData);
460     if (rc != 0) {
461         logerror("WSAStartup failed.  %d", rc);
462         _exit(1);
463     }
464 }
465
466 static void
467 loc_NTTerm(void)
468 {
469     WSACleanup();
470 }
471 #endif