]> git.pond.sub.org Git - empserver/blob - src/server/main.c
(init_server, ef_load, xundump): Add ability to customize game
[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 <signal.h>
37 #if !defined(_WIN32)
38 #include <sys/ioctl.h>
39 #endif
40 #include <errno.h>
41 #include <stdio.h>
42 #include <string.h>
43
44 #if defined(_WIN32)
45 #define 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 /* Run as daemon?  If yes, detach from controlling terminal etc. */
83 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             /*
145              * fall out
146              */
147         case 'i':
148             install_service_set++;
149             break;
150         case 'R':
151             service_name = optarg;
152             /*
153              * fall out
154              */
155         case 'r':
156             remove_service_set++;
157             break;
158 #endif
159         case 's':
160             flags |= EMPTH_STACKCHECK;
161             break;
162         case 'v':
163             printf("Wolfpack Empire %d.%d.%d\n",
164                    EMP_VERS_MAJOR, EMP_VERS_MINOR, EMP_VERS_PATCH);
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     if (chdir(datadir)) {
208         fprintf(stderr, "Can't chdir to %s (%s)\n", datadir, strerror(errno));
209         exit(EXIT_FAILURE);
210     }
211
212 #if defined(_WIN32)
213     if (install_service_set)
214         return install_service(program_name, service_name, config_file);
215 #endif  /* _WIN32 */
216
217     init_server();
218
219 #if defined(_WIN32)
220     if (daemonize != 0) {
221         SERVICE_TABLE_ENTRY DispatchTable[]={{"Empire Server", service_main},{NULL, NULL}};
222         if (StartServiceCtrlDispatcher(DispatchTable))
223             return 0;
224         else {
225             /*
226              * If it is service startup error then exit otherwise
227              * start server in the foreground
228              */
229             if (GetLastError() != ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
230                 logerror("Failed to dispatch service (%d)", GetLastError());
231                 finish_server();
232                 exit(EXIT_FAILURE);
233             }
234         }
235     }
236     daemonize = 0;
237 #else  /* !_WIN32 */
238     if (daemonize) {
239         if (disassoc() < 0) {
240             logerror("Can't become daemon (%s)", strerror(errno));
241             _exit(1);
242         }
243     }
244 #endif /* !_WIN32 */
245     start_server(flags);
246
247     empth_exit();
248
249     CANT_HAPPEN("main thread terminated");
250     finish_server();
251     return EXIT_SUCCESS;
252 }
253
254
255 /*
256  * Initialize for serving, acquire resources.
257  */
258 void
259 init_server(void)
260 {
261     srandom(time(NULL));
262 #if defined(_WIN32)
263     loc_NTInit();
264 #endif
265     update_policy_check();
266     if (ef_load() < 0)
267         exit(EXIT_FAILURE);
268     nullify_objects();
269     global_init();
270     shutdown_init();
271     player_init();
272     ef_init_srv();
273     init_files();
274     io_init();
275     init_nreport();
276
277     if (opt_MOB_ACCESS) {
278         /* This fixes up mobility upon restart */
279         mobility_init();
280     }
281
282     loginit("server");
283 }
284
285 /*
286  * Start serving.
287  */
288 void
289 start_server(int flags)
290 {
291     pid_t pid;
292 #if !defined(_WIN32)
293     struct sigaction act;
294 #endif
295
296     pid = getpid();
297     create_pidfile(pidfname, pid);
298     logerror("------------------------------------------------------");
299     logerror("Empire server (pid %d) started", (int)pid);
300
301 #if !defined(_WIN32)
302     /* signal() should not be used with mit pthreads. Anyway if u
303        have a posix threads u definitly have posix signals -- Sasha */
304     act.sa_flags = 0;
305     sigemptyset(&act.sa_mask);
306     act.sa_handler = shutdwn;
307     sigaction(SIGTERM, &act, NULL);
308     sigaction(SIGINT, &act, NULL);
309     act.sa_handler = panic;
310     sigaction(SIGBUS, &act, NULL);
311     sigaction(SIGSEGV, &act, NULL);
312     sigaction(SIGILL, &act, NULL);
313     sigaction(SIGFPE, &act, NULL);
314     act.sa_handler = SIG_IGN;
315     sigaction(SIGPIPE, &act, NULL);
316 #endif /* !_WIN32 */
317
318     empth_init((void **)&player, flags);
319
320     empth_create(PP_ACCEPT, player_accept, (50 * 1024), flags,
321                  "AcceptPlayers", "Accept network connections", 0);
322     empth_create(PP_KILLIDLE, player_kill_idle, (50 * 1024), flags,
323                  "KillIdle", "Kills idle player connections", 0);
324     empth_create(PP_SCHED, update_sched, (50 * 1024), flags, "UpdateSched",
325                  "Schedules updates to occur", 0);
326     empth_create(PP_TIMESTAMP, delete_lostitems, (50 * 1024), flags,
327                  "DeleteItems", "Deletes old lost items", 0);
328     if (opt_MOB_ACCESS) {
329         /* Start the mobility access check thread */
330         empth_create(PP_TIMESTAMP, mobility_check, (50 * 1024), flags,
331                      "MobilityCheck", "Writes the timestamp file", 0);
332     }
333
334     if (opt_MARKET) {
335         empth_create(PP_TIMESTAMP, market_update, (50 * 1024), flags,
336                      "MarketUpdate", "Updates the market", 0);
337     }
338 }
339
340 /*
341  * Finish serving, release resources.
342  */
343 void
344 finish_server(void)
345 {
346     close_files();
347 #if defined(_WIN32)
348     loc_NTTerm();
349 #endif
350     remove(pidfname);
351 }
352
353 static void
354 create_pidfile(char *fname, pid_t pid)
355 {
356     FILE *pidf = fopen(fname, "w");
357     if (!pidf
358         || fprintf(pidf, "%d\n", (int)pid) < 0
359         || fclose(pidf)) {
360         logerror("Can't write PID file (%s)", strerror(errno));
361         exit(1);
362     }
363 }
364
365 static void
366 init_files(void)
367 {
368     int failed = 0;
369     failed |= !ef_open(EF_NATION, EFF_MEM);
370     failed |= !ef_open(EF_SECTOR, EFF_MEM);
371     failed |= !ef_open(EF_SHIP, EFF_MEM);
372     failed |= !ef_open(EF_PLANE, EFF_MEM);
373     failed |= !ef_open(EF_LAND, EFF_MEM);
374     failed |= !ef_open(EF_NEWS, 0);
375     failed |= !ef_open(EF_LOAN, 0);
376     failed |= !ef_open(EF_TREATY, 0);
377     failed |= !ef_open(EF_NUKE, EFF_MEM);
378     failed |= !ef_open(EF_POWER, 0);
379     failed |= !ef_open(EF_TRADE, 0);
380     failed |= !ef_open(EF_MAP, EFF_MEM);
381     failed |= !ef_open(EF_BMAP, EFF_MEM);
382     failed |= !ef_open(EF_COMM, 0);
383     failed |= !ef_open(EF_LOST, 0);
384     if (failed) {
385         logerror("Missing files, giving up");
386         exit(EXIT_FAILURE);
387     }
388 }
389
390 static void
391 close_files(void)
392 {
393     ef_close(EF_NATION);
394     ef_close(EF_SECTOR);
395     ef_close(EF_SHIP);
396     ef_close(EF_PLANE);
397     ef_close(EF_LAND);
398     ef_close(EF_NEWS);
399     ef_close(EF_LOAN);
400     ef_close(EF_TREATY);
401     ef_close(EF_NUKE);
402     ef_close(EF_POWER);
403     ef_close(EF_TRADE);
404     ef_close(EF_MAP);
405     ef_close(EF_COMM);
406     ef_close(EF_BMAP);
407     ef_close(EF_LOST);
408 }
409
410 /* we're going down.  try to close the files at least */
411 #if !defined(_WIN32)
412 void
413 panic(int sig)
414 {
415     struct sigaction act;
416
417     act.sa_flags = 0;
418     sigemptyset(&act.sa_mask);
419     act.sa_handler = SIG_DFL;
420     sigaction(SIGBUS, &act, NULL);
421     sigaction(SIGSEGV, &act, NULL);
422     sigaction(SIGILL, &act, NULL);
423     sigaction(SIGFPE, &act, NULL);
424     logerror("server received fatal signal %d", sig);
425     log_last_commands();
426     close_files();
427     if (CANT_HAPPEN(sig != SIGBUS && sig != SIGSEGV
428                     && sig != SIGILL && sig != SIGFPE))
429         _exit(1);
430     if (raise(sig))
431         _exit(1);
432 }
433 #endif /* _WIN32 */
434
435 void
436 shutdwn(int sig)
437 {
438     struct player *p;
439     time_t now;
440
441     logerror("Shutdown commencing (cleaning up threads.)");
442
443     for (p = player_next(0); p != 0; p = player_next(p)) {
444         if (p->state != PS_PLAYING)
445             continue;
446         pr_flash(p, "Server shutting down...\n");
447         p->state = PS_SHUTDOWN;
448         p->aborted++;
449         if (p->command) {
450             pr_flash(p, "Shutdown aborting command\n");
451         }
452         empth_wakeup(p->proc);
453     }
454
455     if (!sig) {
456         /* Sleep and let some cleanup happen - note this doesn't work
457            when called from a signal handler, since we may or may not
458            be in the right thread.  So we just pass by and kill 'em
459            all. */
460         time(&now);
461         empth_sleep(now + 1);
462     }
463
464     for (p = player_next(0); p != 0; p = player_next(p)) {
465         p->state = PS_KILL;
466         p->aborted++;
467         empth_terminate(p->proc);
468         p = player_delete(p);
469     }
470     if (sig)
471         logerror("Server shutting down on signal %d", sig);
472     else
473         logerror("Server shutting down at deity's request");
474     finish_server();
475
476 #if defined(_WIN32)
477     if (daemonize) {
478         stop_service();
479         return;
480     }
481 #endif
482     _exit(0);
483 }
484
485
486 static void
487 nullify_objects(void)
488 {
489     int i, j;
490
491     if (opt_BIG_CITY)
492         dchr[SCT_CAPIT] = bigcity_dchr;
493     if (opt_NO_LCMS)
494         dchr[SCT_LIGHT].d_cost = -1;
495     if (opt_NO_HCMS)
496         dchr[SCT_HEAVY].d_cost = -1;
497     if (opt_NO_OIL) {
498         dchr[SCT_OIL].d_cost = -1;
499         dchr[SCT_REFINE].d_cost = -1;
500     }
501     for (i = 0; plchr[i].pl_name; i++) {
502         if (opt_NO_HCMS)
503             plchr[i].pl_hcm = 0;
504         if (opt_NO_LCMS)
505             plchr[i].pl_lcm = 0;
506         if (opt_NO_OIL)
507             plchr[i].pl_fuel = 0;
508     }
509     for (i = 0; lchr[i].l_name; i++) {
510         if (opt_NO_HCMS)
511             lchr[i].l_hcm = 0;
512         if (opt_NO_LCMS)
513             lchr[i].l_lcm = 0;
514         /* Fix up the military values */
515         lchr[i].l_mil = lchr[i].l_item[I_MILIT];
516     }
517     for (i = 0; mchr[i].m_name; i++) {
518         if (opt_NO_HCMS)
519             mchr[i].m_hcm = 0;
520         if (opt_NO_LCMS)
521             mchr[i].m_lcm = 0;
522         if (opt_NO_OIL)
523             mchr[i].m_flags &= ~M_OIL;
524     }
525     for (i = 0; nchr[i].n_name; i++) {
526         if (opt_NO_HCMS)
527             nchr[i].n_hcm = 0;
528         if (opt_NO_LCMS)
529             nchr[i].n_lcm = 0;
530     }
531     for (i = 0; i <= SCT_MAXDEF; i++) {
532         if (opt_NO_HCMS)
533             dchr[i].d_hcms = 0;
534         if (opt_NO_LCMS)
535             dchr[i].d_lcms = 0;
536     }
537     for (i = 0; pchr[i].p_name; i++) {
538         for (j = 0; j < MAXPRCON; j++) {
539             if (opt_NO_HCMS && pchr[i].p_ctype[j] == I_HCM)
540                 pchr[i].p_camt[j] = 0;
541             if (opt_NO_LCMS && pchr[i].p_ctype[j] == I_LCM)
542                 pchr[i].p_camt[j] = 0;
543             if (opt_NO_OIL && pchr[i].p_ctype[j] == I_OIL)
544                 pchr[i].p_camt[j] = 0;
545         }
546     }
547     for (i = 0; intrchr[i].in_name; i++) {
548         if (opt_NO_HCMS)
549             intrchr[i].in_hcms = 0;
550         if (opt_NO_LCMS)
551             intrchr[i].in_lcms = 0;
552     }
553 }
554
555 #if defined(_WIN32)
556 static void
557 loc_NTInit(void)
558 {
559     int rc;
560     WORD wVersionRequested;
561     WSADATA wsaData;
562
563     wVersionRequested = MAKEWORD(2, 0);
564     rc = WSAStartup(wVersionRequested, &wsaData);
565     if (rc != 0) {
566         logerror("WSAStartup failed.  %d", rc);
567         _exit(1);
568     }
569 }
570
571 static void
572 loc_NTTerm(void)
573 {
574     WSACleanup();
575 }
576 #endif