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