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