]> git.pond.sub.org Git - empserver/blob - src/server/main.c
Comments, whitespace.
[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 static 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             /* fall through */
146         case 'i':
147             install_service_set++;
148             break;
149         case 'R':
150             service_name = optarg;
151             /* fall through */
152         case 'r':
153             remove_service_set++;
154             break;
155 #endif
156         case 's':
157             flags |= EMPTH_STACKCHECK;
158             break;
159         case 'v':
160             printf("%s\n\n%s", version, legal);
161             return EXIT_SUCCESS;
162         case 'h':
163             print_usage(argv[0]);
164             return EXIT_SUCCESS;
165         default:
166             fprintf(stderr, "Try -h for help.\n");
167             return EXIT_FAILURE;
168         }
169     }
170
171 #if defined(_WIN32)
172     if ((debug || flags || config_file != NULL) &&
173         remove_service_set) {
174         fprintf(stderr, "Can't use -p, -s, -d or -e with either "
175             "-r or -R options\n");
176         exit(EXIT_FAILURE);
177     }
178     if ((debug || flags) && install_service_set) {
179         fprintf(stderr, "Can't use -d, -p or -s with either "
180             "-i or -I options\n");
181         exit(EXIT_FAILURE);
182     }
183     if (install_service_set && remove_service_set) {
184         fprintf(stderr, "Can't use both -r or -R and -i or -I "
185             "options\n");
186         exit(EXIT_FAILURE);
187     }
188 #endif  /* _WIN32 */
189
190
191 #if defined(_WIN32)
192     if (remove_service_set)
193         return remove_service(service_name);
194     if (install_service_set) {
195         program_name = _fullpath(NULL, argv[0], 0);
196         if (config_file != NULL)
197             config_file = _fullpath(NULL, config_file, 0);
198     }
199 #endif  /* _WIN32 */
200
201     if (emp_config(config_file) < 0)
202         exit(EXIT_FAILURE);
203     ef_init();
204     if (chdir(configdir)) {
205         fprintf(stderr, "Can't chdir to %s (%s)\n",
206                 configdir, strerror(errno));
207         exit(EXIT_FAILURE);
208     }
209     if (chdir(builtindir)) {
210         fprintf(stderr, "Can't chdir to %s (%s)\n",
211                 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",
218                 configdir, strerror(errno));
219         exit(EXIT_FAILURE);
220     }
221     if (read_custom_tables() < 0)
222         exit(EXIT_FAILURE);
223     if (chdir(gamedir)) {
224         fprintf(stderr, "Can't chdir to %s (%s)\n",
225                 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[]={
239             {"Empire Server", service_main},
240             {NULL, NULL}
241         };
242         if (StartServiceCtrlDispatcher(DispatchTable))
243             return 0;
244         else {
245             /*
246              * If it is service startup error then exit otherwise
247              * start server in the foreground
248              */
249             if (GetLastError() != ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
250                 logerror("Failed to dispatch service (%lu)",
251                          GetLastError());
252                 finish_server();
253                 exit(EXIT_FAILURE);
254             }
255         }
256     }
257     daemonize = 0;
258 #else  /* !_WIN32 */
259     if (daemonize) {
260         if (disassoc() < 0) {
261             logerror("Can't become daemon (%s)", strerror(errno));
262             _exit(1);
263         }
264     }
265 #endif /* !_WIN32 */
266     start_server(flags);
267
268     empth_exit();
269
270     CANT_REACH();
271     finish_server();
272     return EXIT_SUCCESS;
273 }
274
275
276 /*
277  * Initialize for serving, acquire resources.
278  */
279 void
280 init_server(void)
281 {
282     srandom(time(NULL));
283 #if defined(_WIN32)
284     loc_NTInit();
285 #endif
286     update_policy_check();
287     shutdown_init();
288     player_init();
289     ef_init_srv();
290     io_init();
291     init_nreport();
292
293     if (opt_MOB_ACCESS) {
294         /* This fixes up mobility upon restart */
295         mobility_init();
296     }
297
298     loginit("server");
299 }
300
301 /*
302  * Start serving.
303  */
304 void
305 start_server(int flags)
306 {
307     pid_t pid;
308 #if !defined(_WIN32)
309     struct sigaction act;
310 #endif
311
312     pid = getpid();
313     create_pidfile(pidfname, pid);
314     logerror("------------------------------------------------------");
315     logerror("Empire server (pid %d) started", (int)pid);
316
317 #if !defined(_WIN32)
318     /* signal() should not be used with mit pthreads. Anyway if u
319        have a posix threads u definitly have posix signals -- Sasha */
320     act.sa_flags = 0;
321     sigemptyset(&act.sa_mask);
322     act.sa_handler = shutdwn;
323     sigaction(SIGTERM, &act, NULL);
324     sigaction(SIGINT, &act, NULL);
325     act.sa_handler = panic;
326     sigaction(SIGBUS, &act, NULL);
327     sigaction(SIGSEGV, &act, NULL);
328     sigaction(SIGILL, &act, NULL);
329     sigaction(SIGFPE, &act, NULL);
330     act.sa_handler = SIG_IGN;
331     sigaction(SIGPIPE, &act, NULL);
332 #endif /* !_WIN32 */
333
334     empth_init((void **)&player, flags);
335
336     empth_create(PP_ACCEPT, player_accept, (50 * 1024), flags,
337                  "AcceptPlayers", "Accept network connections", 0);
338     empth_create(PP_KILLIDLE, player_kill_idle, (50 * 1024), flags,
339                  "KillIdle", "Kills idle player connections", 0);
340     empth_create(PP_SCHED, update_sched, (50 * 1024), flags, "UpdateSched",
341                  "Schedules updates to occur", 0);
342     empth_create(PP_TIMESTAMP, delete_lostitems, (50 * 1024), flags,
343                  "DeleteItems", "Deletes old lost items", 0);
344     if (opt_MOB_ACCESS) {
345         /* Start the mobility access check thread */
346         empth_create(PP_TIMESTAMP, mobility_check, (50 * 1024), flags,
347                      "MobilityCheck", "Writes the timestamp file", 0);
348     }
349
350     if (opt_MARKET) {
351         empth_create(PP_TIMESTAMP, market_update, (50 * 1024), flags,
352                      "MarketUpdate", "Updates the market", 0);
353     }
354 }
355
356 /*
357  * Finish serving, release resources.
358  */
359 void
360 finish_server(void)
361 {
362     ef_fin_srv();
363 #if defined(_WIN32)
364     loc_NTTerm();
365 #endif
366     remove(pidfname);
367 }
368
369 static void
370 create_pidfile(char *fname, pid_t pid)
371 {
372     FILE *pidf = fopen(fname, "w");
373     if (!pidf
374         || fprintf(pidf, "%d\n", (int)pid) < 0
375         || fclose(pidf)) {
376         logerror("Can't write PID file (%s)", strerror(errno));
377         exit(1);
378     }
379 }
380
381 /* we're going down.  try to close the files at least */
382 #if !defined(_WIN32)
383 void
384 panic(int sig)
385 {
386     struct sigaction act;
387
388     act.sa_flags = 0;
389     sigemptyset(&act.sa_mask);
390     act.sa_handler = SIG_DFL;
391     sigaction(SIGBUS, &act, NULL);
392     sigaction(SIGSEGV, &act, NULL);
393     sigaction(SIGILL, &act, NULL);
394     sigaction(SIGFPE, &act, NULL);
395     logerror("server received fatal signal %d", sig);
396     log_last_commands();
397     ef_fin_srv();
398     if (CANT_HAPPEN(sig != SIGBUS && sig != SIGSEGV
399                     && sig != SIGILL && sig != SIGFPE))
400         _exit(1);
401     if (raise(sig))
402         _exit(1);
403 }
404 #endif /* _WIN32 */
405
406 void
407 shutdwn(int sig)
408 {
409     struct player *p;
410     time_t now;
411
412     logerror("Shutdown commencing (cleaning up threads.)");
413
414     for (p = player_next(0); p != 0; p = player_next(p)) {
415         if (p->state != PS_PLAYING)
416             continue;
417         pr_flash(p, "Server shutting down...\n");
418         p->state = PS_SHUTDOWN;
419         p->aborted++;
420         if (p->command) {
421             pr_flash(p, "Shutdown aborting command\n");
422         }
423         empth_wakeup(p->proc);
424     }
425
426     if (!sig) {
427         /* Sleep and let some cleanup happen - note this doesn't work
428            when called from a signal handler, since we may or may not
429            be in the right thread.  So we just pass by and kill 'em
430            all. */
431         time(&now);
432         empth_sleep(now + 1);
433     }
434
435     for (p = player_next(0); p != 0; p = player_next(p)) {
436         p->state = PS_KILL;
437         p->aborted++;
438         empth_terminate(p->proc);
439         p = player_delete(p);
440     }
441     if (sig)
442         logerror("Server shutting down on signal %d", sig);
443     else
444         logerror("Server shutting down at deity's request");
445     finish_server();
446
447 #if defined(_WIN32)
448     if (daemonize) {
449         stop_service();
450         return;
451     }
452 #endif
453     _exit(0);
454 }
455
456 #if defined(_WIN32)
457 static void
458 loc_NTInit(void)
459 {
460     int rc;
461     WORD wVersionRequested;
462     WSADATA wsaData;
463
464     wVersionRequested = MAKEWORD(2, 0);
465     rc = WSAStartup(wVersionRequested, &wsaData);
466     if (rc != 0) {
467         logerror("WSAStartup failed.  %d", rc);
468         _exit(1);
469     }
470 }
471
472 static void
473 loc_NTTerm(void)
474 {
475     WSACleanup();
476 }
477 #endif