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