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