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