]> git.pond.sub.org Git - empserver/blob - src/server/main.c
(init_server, start_server): Move start log message to start_server(),
[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                 loc_NTTerm();
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 /*
255  * Initialize for serving, acquire resources.
256  */
257 void
258 init_server(void)
259 {
260     srandom(time(NULL));
261 #if defined(_WIN32)
262     loc_NTInit();
263 #endif
264     update_policy_check();
265     nullify_objects();
266     global_init();
267     shutdown_init();
268     player_init();
269     ef_init();
270     init_files();
271     io_init();
272     init_nreport();
273
274     if (opt_MOB_ACCESS) {
275         /* This fixes up mobility upon restart */
276         mobility_init();
277     }
278
279     loginit("server");
280 }
281
282 /*
283  * Start serving.
284  */
285 void
286 start_server(int flags)
287 {
288     struct sigaction act;
289
290     logerror("------------------------------------------------------");
291     logerror("Empire server (pid %d) started", (int)getpid());
292
293 #if !defined(_WIN32)
294     /* signal() should not be used with mit pthreads. Anyway if u
295        have a posix threads u definitly have posix signals -- Sasha */
296     sigemptyset(&act.sa_mask);
297     act.sa_handler = shutdwn;
298     sigaction(SIGTERM, &act, NULL);
299     sigaction(SIGINT, &act, NULL);
300     act.sa_handler = panic;
301     sigaction(SIGBUS, &act, NULL);
302     sigaction(SIGSEGV, &act, NULL);
303     sigaction(SIGILL, &act, NULL);
304     sigaction(SIGFPE, &act, NULL);
305     act.sa_handler = SIG_IGN;
306     sigaction(SIGPIPE, &act, NULL);
307 #endif /* !_WIN32 */
308
309     empth_init((char **)&player, flags);
310
311     empth_create(PP_ACCEPT, player_accept, (50 * 1024), flags,
312                  "AcceptPlayers", "Accept network connections", 0);
313     empth_create(PP_KILLIDLE, player_kill_idle, (50 * 1024), flags,
314                  "KillIdle", "Kills idle player connections", 0);
315     empth_create(PP_SCHED, update_sched, (50 * 1024), flags, "UpdateSched",
316                  "Schedules updates to occur", 0);
317     empth_create(PP_TIMESTAMP, delete_lostitems, (50 * 1024), flags,
318                  "DeleteItems", "Deletes old lost items", 0);
319     if (opt_MOB_ACCESS) {
320         /* Start the mobility access check thread */
321         empth_create(PP_TIMESTAMP, mobility_check, (50 * 1024), flags,
322                      "MobilityCheck", "Writes the timestamp file", 0);
323     }
324
325     if (opt_MARKET) {
326         empth_create(PP_TIMESTAMP, market_update, (50 * 1024), flags,
327                      "MarketUpdate", "Updates the market", 0);
328     }
329 }
330
331 static void
332 init_files(void)
333 {
334     int failed = 0;
335     failed |= !ef_open(EF_NATION, O_RDWR, EFF_MEM);
336     failed |= !ef_open(EF_SECTOR, O_RDWR, EFF_MEM);
337     failed |= !ef_open(EF_SHIP, O_RDWR, EFF_MEM);
338     failed |= !ef_open(EF_PLANE, O_RDWR, EFF_MEM);
339     failed |= !ef_open(EF_LAND, O_RDWR, EFF_MEM);
340     failed |= !ef_open(EF_NEWS, O_RDWR, 0);
341     failed |= !ef_open(EF_LOAN, O_RDWR, 0);
342     failed |= !ef_open(EF_TREATY, O_RDWR, 0);
343     failed |= !ef_open(EF_NUKE, O_RDWR, EFF_MEM);
344     failed |= !ef_open(EF_POWER, O_RDWR, 0);
345     failed |= !ef_open(EF_TRADE, O_RDWR, 0);
346     failed |= !ef_open(EF_MAP, O_RDWR, EFF_MEM);
347     failed |= !ef_open(EF_BMAP, O_RDWR, EFF_MEM);
348     failed |= !ef_open(EF_COMM, O_RDWR, 0);
349     failed |= !ef_open(EF_LOST, O_RDWR, 0);
350     if (failed) {
351         logerror("Missing files, giving up");
352         exit(EXIT_FAILURE);
353     }
354 }
355
356 void
357 close_files(void)
358 {
359     ef_close(EF_NATION);
360     ef_close(EF_SECTOR);
361     ef_close(EF_SHIP);
362     ef_close(EF_PLANE);
363     ef_close(EF_LAND);
364     ef_close(EF_NEWS);
365     ef_close(EF_LOAN);
366     ef_close(EF_TREATY);
367     ef_close(EF_NUKE);
368     ef_close(EF_POWER);
369     ef_close(EF_TRADE);
370     ef_close(EF_MAP);
371     ef_close(EF_COMM);
372     ef_close(EF_BMAP);
373     ef_close(EF_LOST);
374 }
375
376 /* we're going down.  try to close the files at least */
377 #if !defined(_WIN32)
378 void
379 panic(int sig)
380 {
381     struct sigaction act;
382
383     act.sa_flags = 0;
384     sigemptyset(&act.sa_mask);
385     act.sa_handler = SIG_DFL;
386     sigaction(SIGBUS, &act, NULL);
387     sigaction(SIGSEGV, &act, NULL);
388     sigaction(SIGILL, &act, NULL);
389     sigaction(SIGFPE, &act, NULL);
390     logerror("server received fatal signal %d", sig);
391     log_last_commands();
392     close_files();
393     if (CANT_HAPPEN(sig != SIGBUS && sig != SIGSEGV
394                     && sig != SIGILL && sig != SIGFPE))
395         _exit(1);
396     if (raise(sig))
397         _exit(1);
398 }
399 #endif /* _WIN32 */
400
401 void
402 shutdwn(int sig)
403 {
404     struct player *p;
405     time_t now;
406
407 #if defined(__linux__) && defined(_EMPTH_POSIX)
408 /* This is a hack to get around the way pthreads work on Linux.  This
409    may be useful on other platforms too where threads are turned into
410    processes. */
411     if (getpid() != mainpid) {
412         empth_t *me;
413
414         me = empth_self();
415         if (me && me->name) {
416             if (strlen(me->name) > 5) {
417                 /* Player threads are cleaned up below, so just have
418                    them return.  This should work. */
419                 if (!strncmp("Player", me->name, 6)) {
420                     return;
421                 }
422             }
423         }
424         /* Not a player thread - must be server thread, so exit */
425         empth_exit();
426         return;
427     }
428 #endif
429
430     logerror("Shutdown commencing (cleaning up threads.)");
431
432     for (p = player_next(0); p != 0; p = player_next(p)) {
433         if (p->state != PS_PLAYING)
434             continue;
435         pr_flash(p, "Server shutting down...\n");
436         p->state = PS_SHUTDOWN;
437         p->aborted++;
438         if (p->command) {
439             pr_flash(p, "Shutdown aborting command\n");
440         }
441         empth_wakeup(p->proc);
442     }
443
444     if (!sig) {
445         /* Sleep and let some cleanup happen - note this doesn't work
446            when called from a signal handler, since we may or may not
447            be in the right thread.  So we just pass by and kill 'em
448            all. */
449         time(&now);
450         empth_sleep(now + 1);
451     }
452
453     for (p = player_next(0); p != 0; p = player_next(p)) {
454         p->state = PS_KILL;
455         p->aborted++;
456         empth_terminate(p->proc);
457         p = player_delete(p);
458     }
459     if (sig)
460         logerror("Server shutting down on signal %d", sig);
461     else
462         logerror("Server shutting down at Deity's request");
463     close_files();
464
465 #if defined(_WIN32)
466     loc_NTTerm();
467     if (!daemonize)
468         _exit(0);
469 #else
470     _exit(0);
471 #endif
472 }
473
474
475 static void
476 nullify_objects(void)
477 {
478     int i, j;
479
480     if (opt_BIG_CITY)
481         dchr[SCT_CAPIT] = bigcity_dchr;
482     if (opt_NO_LCMS)
483         dchr[SCT_LIGHT].d_cost = -1;
484     if (opt_NO_HCMS)
485         dchr[SCT_HEAVY].d_cost = -1;
486     if (opt_NO_OIL) {
487         dchr[SCT_OIL].d_cost = -1;
488         dchr[SCT_REFINE].d_cost = -1;
489     }
490     for (i = 0; i < pln_maxno; i++) {
491         if (opt_NO_HCMS)
492             plchr[i].pl_hcm = 0;
493         if (opt_NO_LCMS)
494             plchr[i].pl_lcm = 0;
495         if (opt_NO_OIL)
496             plchr[i].pl_fuel = 0;
497     }
498     for (i = 0; i < lnd_maxno; i++) {
499         if (opt_NO_HCMS)
500             lchr[i].l_hcm = 0;
501         if (opt_NO_LCMS)
502             lchr[i].l_lcm = 0;
503         /* Fix up the military values */
504         lchr[i].l_mil = lchr[i].l_item[I_MILIT];
505     }
506     for (i = 0; i < shp_maxno; i++) {
507         if (opt_NO_HCMS)
508             mchr[i].m_hcm = 0;
509         if (opt_NO_LCMS)
510             mchr[i].m_lcm = 0;
511         if (opt_NO_OIL) {
512             if (mchr[i].m_flags & M_OIL)
513                 mchr[i].m_name = 0;
514         }
515     }
516     for (i = 0; i < nuk_maxno; i++) {
517         if (opt_NO_HCMS)
518             nchr[i].n_hcm = 0;
519         if (opt_NO_LCMS)
520             nchr[i].n_lcm = 0;
521     }
522     for (i = 0; i <= SCT_MAXDEF; i++) {
523         if (opt_NO_HCMS)
524             dchr[i].d_hcms = 0;
525         if (opt_NO_LCMS)
526             dchr[i].d_lcms = 0;
527     }
528     for (i = 0; i < prd_maxno; i++) {
529         for (j = 0; j < MAXPRCON; j++) {
530             if (opt_NO_HCMS && pchr[i].p_ctype[j] == I_HCM)
531                 pchr[i].p_camt[j] = 0;
532             if (opt_NO_LCMS && pchr[i].p_ctype[j] == I_LCM)
533                 pchr[i].p_camt[j] = 0;
534             if (opt_NO_OIL && pchr[i].p_ctype[j] == I_OIL)
535                 pchr[i].p_camt[j] = 0;
536         }
537     }
538 }
539
540 #if defined(_WIN32)
541 static void
542 loc_NTInit()
543 {
544     int rc;
545     WORD wVersionRequested;
546     WSADATA wsaData;
547
548     wVersionRequested = MAKEWORD(2, 0);
549     rc = WSAStartup(wVersionRequested, &wsaData);
550     if (rc != 0) {
551         logerror("WSAStartup failed.  %d", rc);
552         _exit(1);
553     }
554 }
555
556 void
557 loc_NTTerm()
558 {
559     WSACleanup();
560 }
561 #endif