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