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