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