]> git.pond.sub.org Git - empserver/blob - src/server/main.c
(empth_init_signals): Don't catch SIGINT and SIGTERM.
[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: 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
36  */
37
38 #include <config.h>
39
40 #if !defined(_WIN32)
41 #include <sys/ioctl.h>
42 #endif
43 #include <errno.h>
44 #include <stdio.h>
45 #include <string.h>
46
47 #if defined(_WIN32)
48 #define WIN32
49 #include <winsock2.h>
50 #undef NS_ALL
51 #include <process.h>
52 #include "../lib/gen/getopt.h"
53 #include "service.h"
54 #include "direct.h"
55 #endif
56
57 #include "misc.h"
58 #include "nat.h"
59 #include "file.h"
60 #include "player.h"
61 #include "empthread.h"
62 #include "plane.h"
63 #include "nuke.h"
64 #include "land.h"
65 #include "ship.h"
66 #include "sect.h"
67 #include "product.h"
68 #include "optlist.h"
69 #include "server.h"
70 #include "version.h"
71 #include "prototypes.h"
72
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 static char pidfname[] = "server.pid";
81
82 /* Run as daemon?  If yes, detach from controlling terminal etc. */
83 static int daemonize = 1;
84
85 static void
86 print_usage(char *program_name)
87 {
88     printf("Usage: %s [OPTION]...\n"
89            "  -d              debug mode\n"
90            "  -e CONFIG-FILE  configuration file\n"
91            "                  (default %s)\n"
92            "  -h              display this help and exit\n"
93 #ifdef _WIN32
94            "  -i              install service `%s'\n"
95            "  -I NAME         install service NAME\n"
96 #endif
97            "  -p              threading debug mode, implies -d\n"
98 #ifdef _WIN32
99            "  -r              remove service `%s'\n"
100            "  -R NAME         remove service NAME\n"
101 #endif
102            "  -s              enable stack checking\n"
103            "  -v              display version information and exit\n",
104            program_name, dflt_econfig
105 #ifdef _WIN32
106            , DEFAULT_SERVICE_NAME, DEFAULT_SERVICE_NAME
107 #endif
108         );
109 }
110
111 int
112 main(int argc, char **argv)
113 {
114     int flags = 0;
115 #if defined(_WIN32)
116     int install_service_set = 0;
117     char *program_name = NULL;
118     char *service_name = NULL;
119     int remove_service_set = 0;
120 #endif
121     char *config_file = NULL;
122     int op;
123
124 #ifdef _WIN32
125 # define XOPTS "iI:rR:"
126 #else
127 # define XOPTS
128 #endif
129     while ((op = getopt(argc, argv, "de:hpsv" XOPTS)) != EOF) {
130         switch (op) {
131         case 'p':
132             flags |= EMPTH_PRINT;
133             /* fall through */
134         case 'd':
135             debug = 1;
136             daemonize = 0;
137             break;
138         case 'e':
139             config_file = optarg;
140             break;
141 #if defined(_WIN32)
142         case 'I':
143             service_name = optarg;
144             /* fall through */
145         case 'i':
146             install_service_set++;
147             break;
148         case 'R':
149             service_name = optarg;
150             /* fall through */
151         case 'r':
152             remove_service_set++;
153             break;
154 #endif  /* _WIN32 */
155         case 's':
156             flags |= EMPTH_STACKCHECK;
157             break;
158         case 'v':
159             printf("%s\n\n%s", version, legal);
160             return EXIT_SUCCESS;
161         case 'h':
162             print_usage(argv[0]);
163             return EXIT_SUCCESS;
164         default:
165             fprintf(stderr, "Try -h for help.\n");
166             return EXIT_FAILURE;
167         }
168     }
169
170 #if defined(_WIN32)
171     if ((debug || flags || config_file != NULL) &&
172         remove_service_set) {
173         fprintf(stderr, "Can't use -p, -s, -d or -e with either "
174             "-r or -R options\n");
175         exit(EXIT_FAILURE);
176     }
177     if ((debug || flags) && install_service_set) {
178         fprintf(stderr, "Can't use -d, -p or -s with either "
179             "-i or -I options\n");
180         exit(EXIT_FAILURE);
181     }
182     if (install_service_set && remove_service_set) {
183         fprintf(stderr, "Can't use both -r or -R and -i or -I "
184             "options\n");
185         exit(EXIT_FAILURE);
186     }
187
188     if (remove_service_set)
189         return remove_service(service_name);
190     if (install_service_set) {
191         program_name = _fullpath(NULL, argv[0], 0);
192         if (config_file != NULL)
193             config_file = _fullpath(NULL, config_file, 0);
194     }
195 #endif  /* _WIN32 */
196
197     if (emp_config(config_file) < 0)
198         exit(EXIT_FAILURE);
199     ef_init();
200     if (chdir(configdir)) {
201         fprintf(stderr, "Can't chdir to %s (%s)\n",
202                 configdir, strerror(errno));
203         exit(EXIT_FAILURE);
204     }
205     if (chdir(builtindir)) {
206         fprintf(stderr, "Can't chdir to %s (%s)\n",
207                 builtindir, strerror(errno));
208         exit(EXIT_FAILURE);
209     }
210     if (read_builtin_tables() < 0)
211         exit(EXIT_FAILURE);
212     if (chdir(configdir)) {
213         fprintf(stderr, "Can't chdir to %s (%s)\n",
214                 configdir, strerror(errno));
215         exit(EXIT_FAILURE);
216     }
217     if (read_custom_tables() < 0)
218         exit(EXIT_FAILURE);
219     if (chdir(gamedir)) {
220         fprintf(stderr, "Can't chdir to %s (%s)\n",
221                 gamedir, strerror(errno));
222         exit(EXIT_FAILURE);
223     }
224
225 #if defined(_WIN32)
226     if (install_service_set)
227         return install_service(program_name, service_name, config_file);
228 #endif  /* _WIN32 */
229
230     init_server();
231
232 #if defined(_WIN32)
233     if (daemonize != 0) {
234         SERVICE_TABLE_ENTRY DispatchTable[]={
235             {"Empire Server", service_main},
236             {NULL, NULL}
237         };
238         if (StartServiceCtrlDispatcher(DispatchTable))
239             return 0;
240         else {
241             /*
242              * If it is service startup error then exit otherwise
243              * start server in the foreground
244              */
245             if (GetLastError() != ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
246                 logerror("Failed to dispatch service (%lu)",
247                          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     shutdwn(empth_wait_for_shutdown());
265
266     CANT_REACH();
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
305     pid = getpid();
306     create_pidfile(pidfname, pid);
307     logerror("------------------------------------------------------");
308     logerror("Empire server (pid %d) started", (int)pid);
309
310     empth_init((void **)&player, flags);
311
312     empth_create(PP_ACCEPT, player_accept, (50 * 1024), flags,
313                  "AcceptPlayers", "Accept network connections", 0);
314     empth_create(PP_KILLIDLE, player_kill_idle, (50 * 1024), flags,
315                  "KillIdle", "Kills idle player connections", 0);
316     empth_create(PP_SCHED, update_sched, (50 * 1024), flags, "UpdateSched",
317                  "Schedules updates to occur", 0);
318     empth_create(PP_TIMESTAMP, delete_lostitems, (50 * 1024), flags,
319                  "DeleteItems", "Deletes old lost items", 0);
320     if (opt_MOB_ACCESS) {
321         /* Start the mobility access check thread */
322         empth_create(PP_TIMESTAMP, mobility_check, (50 * 1024), flags,
323                      "MobilityCheck", "Writes the timestamp file", 0);
324     }
325
326     if (opt_MARKET) {
327         empth_create(PP_TIMESTAMP, market_update, (50 * 1024), flags,
328                      "MarketUpdate", "Updates the market", 0);
329     }
330 }
331
332 /*
333  * Finish serving, release resources.
334  */
335 void
336 finish_server(void)
337 {
338     ef_fin_srv();
339 #if defined(_WIN32)
340     loc_NTTerm();
341 #endif
342     remove(pidfname);
343 }
344
345 static void
346 create_pidfile(char *fname, pid_t pid)
347 {
348     FILE *pidf = fopen(fname, "w");
349     if (!pidf
350         || fprintf(pidf, "%d\n", (int)pid) < 0
351         || fclose(pidf)) {
352         logerror("Can't write PID file (%s)", strerror(errno));
353         exit(1);
354     }
355 }
356
357 void
358 shutdwn(int sig)
359 {
360     struct player *p;
361     time_t now;
362
363     logerror("Shutdown commencing (cleaning up threads.)");
364
365     for (p = player_next(0); p != 0; p = player_next(p)) {
366         if (p->state != PS_PLAYING)
367             continue;
368         pr_flash(p, "Server shutting down...\n");
369         p->state = PS_SHUTDOWN;
370         p->aborted++;
371         if (p->command) {
372             pr_flash(p, "Shutdown aborting command\n");
373         }
374         empth_wakeup(p->proc);
375     }
376
377     if (!sig) {
378         /* Sleep and let some cleanup happen - note this doesn't work
379            when called from a signal handler, since we may or may not
380            be in the right thread.  So we just pass by and kill 'em
381            all. */
382         time(&now);
383         empth_sleep(now + 1);
384     }
385
386     for (p = player_next(0); p != 0; p = player_next(p)) {
387         p->state = PS_KILL;
388         p->aborted++;
389         empth_terminate(p->proc);
390         p = player_delete(p);
391     }
392     if (sig)
393         logerror("Server shutting down on signal %d", sig);
394     else
395         logerror("Server shutting down at deity's request");
396     finish_server();
397
398 #if defined(_WIN32)
399     if (daemonize) {
400         stop_service();
401         return;
402     }
403 #endif
404     _exit(0);
405 }
406
407 #if defined(_WIN32)
408 static void
409 loc_NTInit(void)
410 {
411     int rc;
412     WORD wVersionRequested;
413     WSADATA wsaData;
414
415     wVersionRequested = MAKEWORD(2, 0);
416     rc = WSAStartup(wVersionRequested, &wsaData);
417     if (rc != 0) {
418         logerror("WSAStartup failed.  %d", rc);
419         _exit(1);
420     }
421 }
422
423 static void
424 loc_NTTerm(void)
425 {
426     WSACleanup();
427 }
428 #endif