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