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