]> git.pond.sub.org Git - empserver/blob - src/server/main.c
(main,service_main) [_WIN32]: Fix config_file for WIN32.
[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 #if defined(aix) || defined(linux)
37 #include <unistd.h>
38 #endif /* aix or linux */
39
40 #include <signal.h>
41 #if !defined(_WIN32)
42 #include <sys/ioctl.h>
43 #endif
44 #include <fcntl.h>
45 #include <stdio.h>
46 #include <string.h>
47
48 #if defined(_WIN32)
49 #include <winsock2.h>
50 #include <process.h>
51 #include "../lib/gen/getopt.h"
52 #include "service.h"
53 #endif
54
55 #include "misc.h"
56 #include "nat.h"
57 #include "file.h"
58 #include "player.h"
59 #include "empthread.h"
60 #include "plane.h"
61 #include "nuke.h"
62 #include "land.h"
63 #include "ship.h"
64 #include "sect.h"
65 #include "product.h"
66 #include "optlist.h"
67 #include "server.h"
68 #include "prototypes.h"
69
70 static void nullify_objects(void);
71 static void init_files(void);
72
73 #if defined(_WIN32)
74 static void loc_NTInit(void);
75 #endif
76
77 static int mainpid = 0;
78
79 /*
80  * Debugging?
81  * If yes, don't fork into background, don't catch certain signals,
82  * call abort() on internal error.
83  */
84 int debug = 0;
85 int daemon = 1;
86
87 static void
88 print_usage(char *program_name)
89 {
90 #if defined(_WIN32)
91     printf("Usage: %s -i -I service_name -r -R service_name -D datadir -e config_file -d\n", program_name);
92     printf("-i install service with the default name %s\n", DEFAULT_SERVICE_NAME);
93     printf("-r remove service with the default name %s\n", DEFAULT_SERVICE_NAME);
94 #else
95     printf("Usage: %s -D datadir -e config_file -d -p -s\n", program_name);
96     printf("-p print flag\n");
97     printf("-s stack check flag (include print flag)\n");
98 #endif
99     printf("-d debug mode\n");
100 }
101
102 int
103 main(int argc, char **argv)
104 {
105     int flags = 0;
106 #if defined(_WIN32)
107     int install_service_set = 0;
108     char *service_name = NULL;
109     int remove_service_set = 0;
110     int datadir_set = 0;
111 #endif
112     char *config_file = NULL;
113     int op;
114     s_char tbuf[256];
115
116     mainpid = getpid();
117
118 #if defined(_WIN32)
119     while ((op = getopt(argc, argv, "D:de:iI:rR:h")) != EOF) {
120 #else
121     while ((op = getopt(argc, argv, "D:de:psh")) != EOF) {
122 #endif
123         switch (op) {
124         case 'D':
125             datadir = optarg;
126 #if defined(_WIN32)
127             datadir_set++;
128 #endif
129             break;
130         case 'd':
131             debug++;
132             daemon = 0;
133             break;
134         case 'e':
135             config_file = optarg;
136             break;
137 #if defined(_WIN32)
138         case 'I':
139             service_name = optarg;
140             /*
141              * fall out
142              */
143         case 'i':
144             install_service_set++;
145             break;
146             break;
147         case 'R':
148             service_name = optarg;
149             /*
150              * fall out
151              */
152         case 'r':
153             remove_service_set++;
154             break;
155 #else
156         case 'p':
157             flags |= EMPTH_PRINT;
158             break;
159         case 's':
160             flags |= EMPTH_PRINT | EMPTH_STACKCHECK;
161             break;
162 #endif
163         case 'h':
164         default:
165             print_usage(argv[0]);
166             return EXIT_FAILURE;
167         }
168     }
169
170 #if defined(_WIN32)
171     if ((debug || datadir_set || config_file != NULL) &&
172         remove_service_set) {
173         logerror("Can't use -d, -D or -e with either "
174             "-r or -R options when starting the server");
175         printf("Can't use -d, -D or -e with either -r "
176             "or -R options\n");
177         exit(EXIT_FAILURE);
178     }
179     if (debug && install_service_set) {
180         logerror("Can't use -d with either "
181             "-i or -I options when starting the server");
182         printf("Can't use -d with either -i "
183             "or -I options\n");
184         exit(EXIT_FAILURE);
185     }
186     if (install_service_set && remove_service_set) {
187         logerror("Can't use both -r or -R and -i or -I options when starting "
188             "the server");
189         printf("Can't use both -r or -R and -i or -I options\n");
190         exit(EXIT_FAILURE);
191     }
192 #endif  /* _WIN32 */
193
194
195 #if defined(_WIN32)
196     if (install_service_set)
197         return install_service(argv[0], service_name, datadir_set, config_file);
198     if (remove_service_set)
199         return remove_service(service_name);
200 #endif  /* _WIN32 */
201
202     if (config_file == NULL) {
203         sprintf(tbuf, "%s/econfig", datadir);
204         config_file = tbuf;
205     }
206     emp_config(config_file);
207
208 #if defined(_WIN32)
209     if (daemon != 0) {
210         SERVICE_TABLE_ENTRY DispatchTable[]={{"Empire Server", service_main},{NULL, NULL}};
211         if (StartServiceCtrlDispatcher(DispatchTable))
212             return 0;
213         else {
214             /*
215              * If it is service startup error then exit otherwise
216              * start server in the foreground
217              */
218             if (GetLastError() != ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
219                 logerror("Failed to dispatch service (%d)", GetLastError());
220                 printf("Failed to dispatch service (%d)\n", GetLastError());
221                 exit(EXIT_FAILURE);
222             }
223         }
224     }
225     daemon = 0;
226 #endif  /* _WIN32 */
227
228     init_server(flags);
229 #ifndef _WIN32
230     if (daemon != 0 && flags == 0)
231         disassoc();
232 #endif
233     start_server(flags);
234
235 #if defined(__linux__) && defined(_EMPTH_POSIX)
236     strcpy(tbuf, argv[0]);
237     for (op = 1; op < argc; op++) {
238         strcat(tbuf, " ");
239         strcat(tbuf, argv[op]);
240     }
241     sprintf(argv[0], "%s (main pid: %d)", tbuf, getpid());
242 #endif
243
244     empth_exit();
245
246 /* We should never get here.  But, just in case... */
247     close_files();
248
249 #if defined(_WIN32)
250     loc_NTTerm();
251 #endif
252     return EXIT_SUCCESS;
253 }
254
255
256 void
257 init_server(int flags)
258 {
259 #ifdef POSIXSIGNALS
260     struct sigaction act;
261 #endif /* POSIXSIGNALS */
262
263 #if defined(_WIN32)
264     loc_NTInit();
265 #endif
266     update_policy_check();
267
268     nullify_objects();
269
270 #if !defined(_WIN32)
271     /* signal() should not be used with mit pthreads. Anyway if u
272        have a posix threads u definitly have posix signals -- Sasha */
273 #if defined (POSIXSIGNALS) || defined (_EMPTH_POSIX)
274 #ifdef SA_SIGINFO
275     act.sa_flags = SA_SIGINFO;
276 #endif
277     sigemptyset(&act.sa_mask);
278     act.sa_handler = shutdwn;
279     /* pthreads on Linux use SIGUSR1 (*shrug*) so only catch it if not on
280        a Linux box running POSIX threads -- STM */
281 #if !(defined(__linux__) && defined(_EMPTH_POSIX))
282     sigaction(SIGUSR1, &act, NULL);
283 #endif
284     sigaction(SIGTERM, &act, NULL);
285     sigaction(SIGINT, &act, NULL);
286     act.sa_handler = panic;
287     sigaction(SIGBUS, &act, NULL);
288     sigaction(SIGSEGV, &act, NULL);
289     sigaction(SIGILL, &act, NULL);
290     sigaction(SIGFPE, &act, NULL);
291     act.sa_handler = SIG_IGN;
292     sigaction(SIGPIPE, &act, NULL);
293 #else
294     if (debug == 0 && flags == 0) {
295         /* pthreads on Linux use SIGUSR1 (*shrug*) so only catch it if not on
296            a Linux box running POSIX threads -- STM */
297 #if !(defined(__linux__) && defined(_EMPTH_POSIX))
298         signal(SIGUSR1, shutdwn);
299 #endif
300         signal(SIGTERM, shutdwn);
301         signal(SIGBUS, panic);
302         signal(SIGSEGV, panic);
303         signal(SIGILL, panic);
304         signal(SIGFPE, panic);
305         signal(SIGINT, shutdwn);
306     }
307     signal(SIGPIPE, SIG_IGN);
308 #endif /* POSIXSIGNALS */
309 #endif /* _WIN32 */
310     empth_init((char **)&player, flags);
311     srand(time(NULL));
312     global_init();
313     shutdown_init();
314     player_init();
315     ef_init();
316     init_files();
317     io_init();
318     init_nreport();
319
320     if (opt_MOB_ACCESS) {
321         /* This fixes up mobility upon restart */
322         mobility_init();
323     }
324
325     loginit("server");
326     logerror("------------------------------------------------------");
327     logerror("Empire server (pid %d) started", (int)getpid());
328 }
329
330 void
331 start_server(int flags)
332 {
333     empth_create(PP_ACCEPT, player_accept, (50 * 1024), flags,
334                  "AcceptPlayers", "Accept network connections", 0);
335     empth_create(PP_KILLIDLE, player_kill_idle, (50 * 1024), flags,
336                  "KillIdle", "Kills idle player connections", 0);
337     empth_create(PP_SCHED, update_sched, (50 * 1024), flags, "UpdateSched",
338                  "Schedules updates to occur", 0);
339     empth_create(PP_TIMESTAMP, delete_lostitems, (50 * 1024), flags,
340                  "DeleteItems", "Deletes old lost items", 0);
341     if (opt_MOB_ACCESS) {
342         /* Start the mobility access check thread */
343         empth_create(PP_TIMESTAMP, mobility_check, (50 * 1024), flags,
344                      "MobilityCheck", "Writes the timestamp file", 0);
345     }
346
347     if (opt_MARKET) {
348         empth_create(PP_TIMESTAMP, market_update, (50 * 1024), flags,
349                      "MarketUpdate", "Updates the market", 0);
350     }
351 }
352
353 static void
354 init_files(void)
355 {
356     int failed = 0;
357     failed |= !ef_open(EF_NATION, O_RDWR, EFF_MEM);
358     failed |= !ef_open(EF_SECTOR, O_RDWR, EFF_MEM);
359     failed |= !ef_open(EF_SHIP, O_RDWR, EFF_MEM);
360     failed |= !ef_open(EF_PLANE, O_RDWR, EFF_MEM);
361     failed |= !ef_open(EF_LAND, O_RDWR, EFF_MEM);
362     failed |= !ef_open(EF_NEWS, O_RDWR, 0);
363     failed |= !ef_open(EF_LOAN, O_RDWR, 0);
364     failed |= !ef_open(EF_TREATY, O_RDWR, 0);
365     failed |= !ef_open(EF_NUKE, O_RDWR, EFF_MEM);
366     failed |= !ef_open(EF_POWER, O_RDWR, 0);
367     failed |= !ef_open(EF_TRADE, O_RDWR, 0);
368     failed |= !ef_open(EF_MAP, O_RDWR, EFF_MEM);
369     failed |= !ef_open(EF_BMAP, O_RDWR, EFF_MEM);
370     failed |= !ef_open(EF_COMM, O_RDWR, 0);
371     failed |= !ef_open(EF_LOST, O_RDWR, 0);
372     if (failed) {
373         logerror("Missing files, giving up");
374         exit(EXIT_FAILURE);
375     }
376 }
377
378 void
379 close_files(void)
380 {
381     ef_close(EF_NATION);
382     ef_close(EF_SECTOR);
383     ef_close(EF_SHIP);
384     ef_close(EF_PLANE);
385     ef_close(EF_LAND);
386     ef_close(EF_NEWS);
387     ef_close(EF_LOAN);
388     ef_close(EF_TREATY);
389     ef_close(EF_NUKE);
390     ef_close(EF_POWER);
391     ef_close(EF_TRADE);
392     ef_close(EF_MAP);
393     ef_close(EF_COMM);
394     ef_close(EF_BMAP);
395     ef_close(EF_LOST);
396 }
397
398 /* we're going down.  try to close the files at least */
399 #if !defined(_WIN32)
400 void
401 panic(int sig)
402 {
403 #ifdef POSIXSIGNALS
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 #else
414     signal(SIGBUS, SIG_DFL);
415     signal(SIGSEGV, SIG_DFL);
416     signal(SIGILL, SIG_DFL);
417     signal(SIGFPE, SIG_DFL);
418 #endif /* POSIXSIGNALS */
419     logerror("server received fatal signal %d", sig);
420     log_last_commands();
421     close_files();
422     if (CANT_HAPPEN(sig != SIGBUS && sig != SIGSEGV
423                     && sig != SIGILL && sig != SIGFPE))
424         _exit(1);
425     if (raise(sig))
426         _exit(1);
427 }
428 #endif /* _WIN32 */
429
430 void
431 shutdwn(int sig)
432 {
433     struct player *p;
434     time_t now;
435
436 #if defined(__linux__) && defined(_EMPTH_POSIX)
437 /* This is a hack to get around the way pthreads work on Linux.  This
438    may be useful on other platforms too where threads are turned into
439    processes. */
440     if (getpid() != mainpid) {
441         empth_t *me;
442
443         me = empth_self();
444         if (me && me->name) {
445             if (strlen(me->name) > 5) {
446                 /* Player threads are cleaned up below, so just have
447                    them return.  This should work. */
448                 if (!strncmp("Player", me->name, 6)) {
449                     return;
450                 }
451             }
452         }
453         /* Not a player thread - must be server thread, so exit */
454         empth_exit();
455         return;
456     }
457 #endif
458
459     logerror("Shutdown commencing (cleaning up threads.)");
460
461     for (p = player_next(0); p != 0; p = player_next(p)) {
462         if (p->state != PS_PLAYING)
463             continue;
464         pr_flash(p, "Server shutting down...\n");
465         p->state = PS_SHUTDOWN;
466         p->aborted++;
467         if (p->command) {
468             pr_flash(p, "Shutdown aborting command\n");
469         }
470         empth_wakeup(p->proc);
471     }
472
473     if (!sig) {
474         /* Sleep and let some cleanup happen - note this doesn't work
475            when called from a signal handler, since we may or may not
476            be in the right thread.  So we just pass by and kill 'em
477            all. */
478         time(&now);
479         empth_sleep(now + 1);
480     }
481
482     for (p = player_next(0); p != 0; p = player_next(p)) {
483         p->state = PS_KILL;
484         p->aborted++;
485         empth_terminate(p->proc);
486         p = player_delete(p);
487     }
488     if (sig)
489         logerror("Server shutting down on signal %d", sig);
490     else
491         logerror("Server shutting down at Deity's request");
492     close_files();
493     _exit(0);
494 }
495
496
497 static void
498 nullify_objects(void)
499 {
500     int i, j;
501
502     if (opt_BIG_CITY)
503         dchr[SCT_CAPIT] = bigcity_dchr;
504     if (opt_NO_LCMS)
505         dchr[SCT_LIGHT].d_cost = -1;
506     if (opt_NO_HCMS)
507         dchr[SCT_HEAVY].d_cost = -1;
508     if (opt_NO_OIL) {
509         dchr[SCT_OIL].d_cost = -1;
510         dchr[SCT_REFINE].d_cost = -1;
511     }
512     for (i = 0; i < pln_maxno; i++) {
513         if (opt_NO_HCMS)
514             plchr[i].pl_hcm = 0;
515         if (opt_NO_LCMS)
516             plchr[i].pl_lcm = 0;
517         if (opt_NO_OIL)
518             plchr[i].pl_fuel = 0;
519     }
520     for (i = 0; i < lnd_maxno; i++) {
521         if (opt_NO_HCMS)
522             lchr[i].l_hcm = 0;
523         if (opt_NO_LCMS)
524             lchr[i].l_lcm = 0;
525         /* Fix up the military values */
526         lchr[i].l_mil = lchr[i].l_item[I_MILIT];
527     }
528     for (i = 0; i < shp_maxno; i++) {
529         if (opt_NO_HCMS)
530             mchr[i].m_hcm = 0;
531         if (opt_NO_LCMS)
532             mchr[i].m_lcm = 0;
533         if (opt_NO_OIL) {
534             if (mchr[i].m_flags & M_OIL)
535                 mchr[i].m_name = 0;
536         }
537     }
538     for (i = 0; i < nuk_maxno; i++) {
539         if (opt_NO_HCMS)
540             nchr[i].n_hcm = 0;
541         if (opt_NO_LCMS)
542             nchr[i].n_lcm = 0;
543     }
544     for (i = 0; i <= SCT_MAXDEF; i++) {
545         if (opt_NO_HCMS)
546             dchr[i].d_hcms = 0;
547         if (opt_NO_LCMS)
548             dchr[i].d_lcms = 0;
549     }
550     for (i = 0; i < prd_maxno; i++) {
551         for (j = 0; j < MAXPRCON; j++) {
552             if (opt_NO_HCMS && pchr[i].p_ctype[j] == I_HCM)
553                 pchr[i].p_camt[j] = 0;
554             if (opt_NO_LCMS && pchr[i].p_ctype[j] == I_LCM)
555                 pchr[i].p_camt[j] = 0;
556             if (opt_NO_OIL && pchr[i].p_ctype[j] == I_OIL)
557                 pchr[i].p_camt[j] = 0;
558         }
559     }
560 }
561
562 #if defined(_WIN32)
563 static void
564 loc_NTInit()
565 {
566     int rc;
567     WORD wVersionRequested;
568     WSADATA wsaData;
569
570     wVersionRequested = MAKEWORD(2, 0);
571     rc = WSAStartup(wVersionRequested, &wsaData);
572     if (rc != 0) {
573         logerror("WSAStartup failed.  %d", rc);
574         _exit(1);
575     }
576 }
577 #endif
578
579 #if defined(_WIN32)
580 void
581 loc_NTTerm()
582 {
583     WSACleanup();
584 }
585 #endif