]> git.pond.sub.org Git - empserver/blob - src/server/main.c
(main): Rev. 1.43 broke option -D. Its meaning in presence of -e is
[empserver] / src / server / main.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2004, 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 <signal.h>
37 #if !defined(_WIN32)
38 #include <sys/ioctl.h>
39 #endif
40 #include <errno.h>
41 #include <fcntl.h>
42 #include <stdio.h>
43 #include <string.h>
44
45 #if defined(_WIN32)
46 #include <winsock2.h>
47 #undef NS_ALL
48 #include <process.h>
49 #include "../lib/gen/getopt.h"
50 #include "service.h"
51 #include "direct.h"
52 #endif
53
54 #include "misc.h"
55 #include "nat.h"
56 #include "file.h"
57 #include "player.h"
58 #include "empthread.h"
59 #include "plane.h"
60 #include "nuke.h"
61 #include "land.h"
62 #include "ship.h"
63 #include "sect.h"
64 #include "product.h"
65 #include "optlist.h"
66 #include "server.h"
67 #include "version.h"
68 #include "prototypes.h"
69
70 static void nullify_objects(void);
71 static void init_files(void);
72 static void close_files(void);
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 /* Debugging?  If yes call abort() on internal error.  */
83 int debug = 0;
84 /* Run as daemon?  If yes, detach from controlling terminal etc. */
85 int daemonize = 1;
86
87 static void
88 print_usage(char *program_name)
89 {
90     printf("Usage: %s [OPTION]...\n"
91            "  -d              debug mode\n"
92            "  -e CONFIG-FILE  configuration file\n"
93            "                  (default %s)\n"
94            "  -h              display this help and exit\n"
95 #ifdef _WIN32
96            "  -i              install service `%s'\n"
97            "  -I NAME         install service NAME\n"
98 #endif
99            "  -p              threading debug mode, implies -d\n"
100 #ifdef _WIN32
101            "  -r              remove service `%s'\n"
102            "  -R NAME         remove service NAME\n"
103 #endif
104            "  -s              enable stack checking\n"
105            "  -v              display version information and exit\n"
106            program_name, dflt_econfig
107 #ifdef _WIN32
108            , DEFAULT_SERVICE_NAME, DEFAULT_SERVICE_NAME
109 #endif
110         );
111 }
112
113 int
114 main(int argc, char **argv)
115 {
116     int flags = 0;
117 #if defined(_WIN32)
118     int install_service_set = 0;
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("Wolfpack Empire %d.%d.%d\n",
165                    EMP_VERS_MAJOR, EMP_VERS_MINOR, EMP_VERS_PATCH);
166             return EXIT_SUCCESS;
167         case 'h':
168             print_usage(argv[0]);
169             return EXIT_SUCCESS;
170         default:
171             fprintf(stderr, "Try -h for help.\n");
172             return EXIT_FAILURE;
173         }
174     }
175
176 #if defined(_WIN32)
177     if ((debug || flags || config_file != NULL) &&
178         remove_service_set) {
179         fprintf(stderr, "Can't use -p, -s, -d or -e with either "
180             "-r or -R options\n");
181         exit(EXIT_FAILURE);
182     }
183     if ((debug || flags) && install_service_set) {
184         fprintf(stderr, "Can't use -d, -p or -s with either "
185             "-i or -I options\n");
186         exit(EXIT_FAILURE);
187     }
188     if (install_service_set && remove_service_set) {
189         fprintf(stderr, "Can't use both -r or -R and -i or -I "
190             "options\n");
191         exit(EXIT_FAILURE);
192     }
193 #endif  /* _WIN32 */
194
195
196 #if defined(_WIN32)
197     if (remove_service_set)
198         return remove_service(service_name);
199 #endif  /* _WIN32 */
200
201     if (emp_config(config_file) < 0)
202         exit(EXIT_FAILURE);
203     if (chdir(datadir)) {
204         fprintf(stderr, "Can't chdir to %s (%s)\n", datadir, strerror(errno));
205         exit(EXIT_FAILURE);
206     }
207
208 #if defined(_WIN32)
209     if (install_service_set)
210         return install_service(argv[0], service_name, config_file);
211 #endif  /* _WIN32 */
212
213     init_server();
214
215 #if defined(_WIN32)
216     if (daemonize != 0) {
217         SERVICE_TABLE_ENTRY DispatchTable[]={{"Empire Server", service_main},{NULL, NULL}};
218         if (StartServiceCtrlDispatcher(DispatchTable))
219             return 0;
220         else {
221             /*
222              * If it is service startup error then exit otherwise
223              * start server in the foreground
224              */
225             if (GetLastError() != ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
226                 logerror("Failed to dispatch service (%d)", GetLastError());
227                 finish_server();
228                 exit(EXIT_FAILURE);
229             }
230         }
231     }
232     daemonize = 0;
233 #else  /* !_WIN32 */
234     if (daemonize)
235         disassoc();
236 #endif /* !_WIN32 */
237     start_server(flags);
238
239     empth_exit();
240
241     CANT_HAPPEN("main thread terminated");
242     finish_server();
243     return EXIT_SUCCESS;
244 }
245
246
247 /*
248  * Initialize for serving, acquire resources.
249  */
250 void
251 init_server(void)
252 {
253     srandom(time(NULL));
254 #if defined(_WIN32)
255     loc_NTInit();
256 #endif
257     update_policy_check();
258     nullify_objects();
259     global_init();
260     shutdown_init();
261     player_init();
262     ef_init();
263     init_files();
264     io_init();
265     init_nreport();
266
267     if (opt_MOB_ACCESS) {
268         /* This fixes up mobility upon restart */
269         mobility_init();
270     }
271
272     loginit("server");
273 }
274
275 /*
276  * Start serving.
277  */
278 void
279 start_server(int flags)
280 {
281     pid_t pid;
282 #if !defined(_WIN32)
283     struct sigaction act;
284 #endif
285
286     pid = getpid();
287     create_pidfile(pidfname, pid);
288     logerror("------------------------------------------------------");
289     logerror("Empire server (pid %d) started", (int)pid);
290
291 #if !defined(_WIN32)
292     /* signal() should not be used with mit pthreads. Anyway if u
293        have a posix threads u definitly have posix signals -- Sasha */
294     sigemptyset(&act.sa_mask);
295     act.sa_handler = shutdwn;
296     sigaction(SIGTERM, &act, NULL);
297     sigaction(SIGINT, &act, NULL);
298     act.sa_handler = panic;
299     sigaction(SIGBUS, &act, NULL);
300     sigaction(SIGSEGV, &act, NULL);
301     sigaction(SIGILL, &act, NULL);
302     sigaction(SIGFPE, &act, NULL);
303     act.sa_handler = SIG_IGN;
304     sigaction(SIGPIPE, &act, NULL);
305 #endif /* !_WIN32 */
306
307     empth_init((char **)&player, flags);
308
309     empth_create(PP_ACCEPT, player_accept, (50 * 1024), flags,
310                  "AcceptPlayers", "Accept network connections", 0);
311     empth_create(PP_KILLIDLE, player_kill_idle, (50 * 1024), flags,
312                  "KillIdle", "Kills idle player connections", 0);
313     empth_create(PP_SCHED, update_sched, (50 * 1024), flags, "UpdateSched",
314                  "Schedules updates to occur", 0);
315     empth_create(PP_TIMESTAMP, delete_lostitems, (50 * 1024), flags,
316                  "DeleteItems", "Deletes old lost items", 0);
317     if (opt_MOB_ACCESS) {
318         /* Start the mobility access check thread */
319         empth_create(PP_TIMESTAMP, mobility_check, (50 * 1024), flags,
320                      "MobilityCheck", "Writes the timestamp file", 0);
321     }
322
323     if (opt_MARKET) {
324         empth_create(PP_TIMESTAMP, market_update, (50 * 1024), flags,
325                      "MarketUpdate", "Updates the market", 0);
326     }
327 }
328
329 /*
330  * Finish serving, release resources.
331  */
332 void
333 finish_server(void)
334 {
335     close_files();
336 #if defined(_WIN32)
337     loc_NTTerm();
338 #endif
339     remove(pidfname);
340 }
341
342 static void
343 create_pidfile(char *fname, pid_t pid)
344 {
345     FILE *pidf = fopen(fname, "w");
346     if (!pidf
347         || fprintf(pidf, "%d\n", pid) < 0
348         || fclose(pidf)) {
349         logerror("Can't write PID file (%s)", strerror(errno));
350         exit(1);
351     }
352 }
353
354 static void
355 init_files(void)
356 {
357     int failed = 0;
358     failed |= !ef_open(EF_NATION, O_RDWR, EFF_MEM);
359     failed |= !ef_open(EF_SECTOR, O_RDWR, EFF_MEM);
360     failed |= !ef_open(EF_SHIP, O_RDWR, EFF_MEM);
361     failed |= !ef_open(EF_PLANE, O_RDWR, EFF_MEM);
362     failed |= !ef_open(EF_LAND, O_RDWR, EFF_MEM);
363     failed |= !ef_open(EF_NEWS, O_RDWR, 0);
364     failed |= !ef_open(EF_LOAN, O_RDWR, 0);
365     failed |= !ef_open(EF_TREATY, O_RDWR, 0);
366     failed |= !ef_open(EF_NUKE, O_RDWR, EFF_MEM);
367     failed |= !ef_open(EF_POWER, O_RDWR, 0);
368     failed |= !ef_open(EF_TRADE, O_RDWR, 0);
369     failed |= !ef_open(EF_MAP, O_RDWR, EFF_MEM);
370     failed |= !ef_open(EF_BMAP, O_RDWR, EFF_MEM);
371     failed |= !ef_open(EF_COMM, O_RDWR, 0);
372     failed |= !ef_open(EF_LOST, O_RDWR, 0);
373     if (failed) {
374         logerror("Missing files, giving up");
375         exit(EXIT_FAILURE);
376     }
377 }
378
379 static void
380 close_files(void)
381 {
382     ef_close(EF_NATION);
383     ef_close(EF_SECTOR);
384     ef_close(EF_SHIP);
385     ef_close(EF_PLANE);
386     ef_close(EF_LAND);
387     ef_close(EF_NEWS);
388     ef_close(EF_LOAN);
389     ef_close(EF_TREATY);
390     ef_close(EF_NUKE);
391     ef_close(EF_POWER);
392     ef_close(EF_TRADE);
393     ef_close(EF_MAP);
394     ef_close(EF_COMM);
395     ef_close(EF_BMAP);
396     ef_close(EF_LOST);
397 }
398
399 /* we're going down.  try to close the files at least */
400 #if !defined(_WIN32)
401 void
402 panic(int sig)
403 {
404     struct sigaction act;
405
406     act.sa_flags = 0;
407     sigemptyset(&act.sa_mask);
408     act.sa_handler = SIG_DFL;
409     sigaction(SIGBUS, &act, NULL);
410     sigaction(SIGSEGV, &act, NULL);
411     sigaction(SIGILL, &act, NULL);
412     sigaction(SIGFPE, &act, NULL);
413     logerror("server received fatal signal %d", sig);
414     log_last_commands();
415     close_files();
416     if (CANT_HAPPEN(sig != SIGBUS && sig != SIGSEGV
417                     && sig != SIGILL && sig != SIGFPE))
418         _exit(1);
419     if (raise(sig))
420         _exit(1);
421 }
422 #endif /* _WIN32 */
423
424 void
425 shutdwn(int sig)
426 {
427     struct player *p;
428     time_t now;
429
430     logerror("Shutdown commencing (cleaning up threads.)");
431
432     for (p = player_next(0); p != 0; p = player_next(p)) {
433         if (p->state != PS_PLAYING)
434             continue;
435         pr_flash(p, "Server shutting down...\n");
436         p->state = PS_SHUTDOWN;
437         p->aborted++;
438         if (p->command) {
439             pr_flash(p, "Shutdown aborting command\n");
440         }
441         empth_wakeup(p->proc);
442     }
443
444     if (!sig) {
445         /* Sleep and let some cleanup happen - note this doesn't work
446            when called from a signal handler, since we may or may not
447            be in the right thread.  So we just pass by and kill 'em
448            all. */
449         time(&now);
450         empth_sleep(now + 1);
451     }
452
453     for (p = player_next(0); p != 0; p = player_next(p)) {
454         p->state = PS_KILL;
455         p->aborted++;
456         empth_terminate(p->proc);
457         p = player_delete(p);
458     }
459     if (sig)
460         logerror("Server shutting down on signal %d", sig);
461     else
462         logerror("Server shutting down at deity's request");
463     finish_server();
464
465 #if defined(_WIN32)
466     if (daemonize) {
467         stop_service();
468         return;
469     }
470 #endif
471     _exit(0);
472 }
473
474
475 static void
476 nullify_objects(void)
477 {
478     int i, j;
479
480     if (opt_BIG_CITY)
481         dchr[SCT_CAPIT] = bigcity_dchr;
482     if (opt_NO_LCMS)
483         dchr[SCT_LIGHT].d_cost = -1;
484     if (opt_NO_HCMS)
485         dchr[SCT_HEAVY].d_cost = -1;
486     if (opt_NO_OIL) {
487         dchr[SCT_OIL].d_cost = -1;
488         dchr[SCT_REFINE].d_cost = -1;
489     }
490     for (i = 0; i < pln_maxno; i++) {
491         if (opt_NO_HCMS)
492             plchr[i].pl_hcm = 0;
493         if (opt_NO_LCMS)
494             plchr[i].pl_lcm = 0;
495         if (opt_NO_OIL)
496             plchr[i].pl_fuel = 0;
497     }
498     for (i = 0; i < lnd_maxno; i++) {
499         if (opt_NO_HCMS)
500             lchr[i].l_hcm = 0;
501         if (opt_NO_LCMS)
502             lchr[i].l_lcm = 0;
503         /* Fix up the military values */
504         lchr[i].l_mil = lchr[i].l_item[I_MILIT];
505     }
506     for (i = 0; i < shp_maxno; i++) {
507         if (opt_NO_HCMS)
508             mchr[i].m_hcm = 0;
509         if (opt_NO_LCMS)
510             mchr[i].m_lcm = 0;
511         if (opt_NO_OIL) {
512             if (mchr[i].m_flags & M_OIL)
513                 mchr[i].m_name = 0;
514         }
515     }
516     for (i = 0; i < nuk_maxno; i++) {
517         if (opt_NO_HCMS)
518             nchr[i].n_hcm = 0;
519         if (opt_NO_LCMS)
520             nchr[i].n_lcm = 0;
521     }
522     for (i = 0; i <= SCT_MAXDEF; i++) {
523         if (opt_NO_HCMS)
524             dchr[i].d_hcms = 0;
525         if (opt_NO_LCMS)
526             dchr[i].d_lcms = 0;
527     }
528     for (i = 0; i < prd_maxno; i++) {
529         for (j = 0; j < MAXPRCON; j++) {
530             if (opt_NO_HCMS && pchr[i].p_ctype[j] == I_HCM)
531                 pchr[i].p_camt[j] = 0;
532             if (opt_NO_LCMS && pchr[i].p_ctype[j] == I_LCM)
533                 pchr[i].p_camt[j] = 0;
534             if (opt_NO_OIL && pchr[i].p_ctype[j] == I_OIL)
535                 pchr[i].p_camt[j] = 0;
536         }
537     }
538 }
539
540 #if defined(_WIN32)
541 static void
542 loc_NTInit(void)
543 {
544     int rc;
545     WORD wVersionRequested;
546     WSADATA wsaData;
547
548     wVersionRequested = MAKEWORD(2, 0);
549     rc = WSAStartup(wVersionRequested, &wsaData);
550     if (rc != 0) {
551         logerror("WSAStartup failed.  %d", rc);
552         _exit(1);
553     }
554 }
555
556 static void
557 loc_NTTerm(void)
558 {
559     WSACleanup();
560 }
561 #endif