]> git.pond.sub.org Git - empserver/blob - src/server/main.c
(shutdwn): Rev. 1.51 broke the Linux pthread hack. It is unclear what
[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 static void close_files(void);
72 static void create_pidfile(char *, pid_t);
73
74 #if defined(_WIN32)
75 static void loc_NTInit(void);
76 static void loc_NTTerm(void);
77 #endif
78
79 static char pidfname[] = "server.pid";
80
81 /* Debugging?  If yes call abort() on internal error.  */
82 int debug = 0;
83 /* Run as daemon?  If yes, detach from controlling terminal etc. */
84 int daemonize = 1;
85
86 static void
87 print_usage(char *program_name)
88 {
89 #if defined(_WIN32)
90     printf("Usage: %s -i -I service_name -r -R service_name -D datadir -e config_file -d -p\n",
91         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
95 #else
96     printf("Usage: %s -D datadir -e config_file -d -p -s\n", program_name);
97     printf("-s stack check flag (include print flag)\n");
98 #endif
99     printf("-p print flag\n");
100     printf("-d debug mode\n");
101 }
102
103 int
104 main(int argc, char **argv)
105 {
106     int flags = 0;
107 #if defined(_WIN32)
108     int install_service_set = 0;
109     char *service_name = NULL;
110     int remove_service_set = 0;
111     int datadir_set = 0;
112 #endif
113     char *config_file = NULL;
114     int op;
115
116 #if defined(_WIN32)
117     while ((op = getopt(argc, argv, "D:de:iI:rR:hp")) != 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         case 'p':
136             flags |= EMPTH_PRINT;
137             daemonize = 0;
138             break;
139 #if defined(_WIN32)
140         case 'I':
141             service_name = optarg;
142             /*
143              * fall out
144              */
145         case 'i':
146             install_service_set++;
147             break;
148             break;
149         case 'R':
150             service_name = optarg;
151             /*
152              * fall out
153              */
154         case 'r':
155             remove_service_set++;
156             break;
157 #else
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                 finish_server();
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     empth_exit();
234
235     CANT_HAPPEN("main thread terminated");
236     finish_server();
237     return EXIT_SUCCESS;
238 }
239
240
241 /*
242  * Initialize for serving, acquire resources.
243  */
244 void
245 init_server(void)
246 {
247     srandom(time(NULL));
248 #if defined(_WIN32)
249     loc_NTInit();
250 #endif
251     update_policy_check();
252     nullify_objects();
253     global_init();
254     shutdown_init();
255     player_init();
256     ef_init();
257     init_files();
258     io_init();
259     init_nreport();
260
261     if (opt_MOB_ACCESS) {
262         /* This fixes up mobility upon restart */
263         mobility_init();
264     }
265
266     loginit("server");
267 }
268
269 /*
270  * Start serving.
271  */
272 void
273 start_server(int flags)
274 {
275     pid_t pid;
276 #if !defined(_WIN32)
277     struct sigaction act;
278 #endif
279
280     pid = getpid();
281     create_pidfile(pidfname, pid);
282     logerror("------------------------------------------------------");
283     logerror("Empire server (pid %d) started", (int)pid);
284
285 #if !defined(_WIN32)
286     /* signal() should not be used with mit pthreads. Anyway if u
287        have a posix threads u definitly have posix signals -- Sasha */
288     sigemptyset(&act.sa_mask);
289     act.sa_handler = shutdwn;
290     sigaction(SIGTERM, &act, NULL);
291     sigaction(SIGINT, &act, NULL);
292     act.sa_handler = panic;
293     sigaction(SIGBUS, &act, NULL);
294     sigaction(SIGSEGV, &act, NULL);
295     sigaction(SIGILL, &act, NULL);
296     sigaction(SIGFPE, &act, NULL);
297     act.sa_handler = SIG_IGN;
298     sigaction(SIGPIPE, &act, NULL);
299 #endif /* !_WIN32 */
300
301     empth_init((char **)&player, flags);
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 /*
324  * Finish serving, release resources.
325  */
326 void
327 finish_server(void)
328 {
329     close_files();
330 #if defined(_WIN32)
331     loc_NTTerm();
332 #endif
333     remove(pidfname);
334 }
335
336 static void
337 create_pidfile(char *fname, pid_t pid)
338 {
339     FILE *pidf = fopen(fname, "w");
340     if (!pidf
341         || fprintf(pidf, "%d\n", pid) < 0
342         || fclose(pidf)) {
343         logerror("Can't write PID file (%s)", strerror(errno));
344         exit(1);
345     }
346 }
347
348 static void
349 init_files(void)
350 {
351     int failed = 0;
352     failed |= !ef_open(EF_NATION, O_RDWR, EFF_MEM);
353     failed |= !ef_open(EF_SECTOR, O_RDWR, EFF_MEM);
354     failed |= !ef_open(EF_SHIP, O_RDWR, EFF_MEM);
355     failed |= !ef_open(EF_PLANE, O_RDWR, EFF_MEM);
356     failed |= !ef_open(EF_LAND, O_RDWR, EFF_MEM);
357     failed |= !ef_open(EF_NEWS, O_RDWR, 0);
358     failed |= !ef_open(EF_LOAN, O_RDWR, 0);
359     failed |= !ef_open(EF_TREATY, O_RDWR, 0);
360     failed |= !ef_open(EF_NUKE, O_RDWR, EFF_MEM);
361     failed |= !ef_open(EF_POWER, O_RDWR, 0);
362     failed |= !ef_open(EF_TRADE, O_RDWR, 0);
363     failed |= !ef_open(EF_MAP, O_RDWR, EFF_MEM);
364     failed |= !ef_open(EF_BMAP, O_RDWR, EFF_MEM);
365     failed |= !ef_open(EF_COMM, O_RDWR, 0);
366     failed |= !ef_open(EF_LOST, O_RDWR, 0);
367     if (failed) {
368         logerror("Missing files, giving up");
369         exit(EXIT_FAILURE);
370     }
371 }
372
373 static void
374 close_files(void)
375 {
376     ef_close(EF_NATION);
377     ef_close(EF_SECTOR);
378     ef_close(EF_SHIP);
379     ef_close(EF_PLANE);
380     ef_close(EF_LAND);
381     ef_close(EF_NEWS);
382     ef_close(EF_LOAN);
383     ef_close(EF_TREATY);
384     ef_close(EF_NUKE);
385     ef_close(EF_POWER);
386     ef_close(EF_TRADE);
387     ef_close(EF_MAP);
388     ef_close(EF_COMM);
389     ef_close(EF_BMAP);
390     ef_close(EF_LOST);
391 }
392
393 /* we're going down.  try to close the files at least */
394 #if !defined(_WIN32)
395 void
396 panic(int sig)
397 {
398     struct sigaction act;
399
400     act.sa_flags = 0;
401     sigemptyset(&act.sa_mask);
402     act.sa_handler = SIG_DFL;
403     sigaction(SIGBUS, &act, NULL);
404     sigaction(SIGSEGV, &act, NULL);
405     sigaction(SIGILL, &act, NULL);
406     sigaction(SIGFPE, &act, NULL);
407     logerror("server received fatal signal %d", sig);
408     log_last_commands();
409     close_files();
410     if (CANT_HAPPEN(sig != SIGBUS && sig != SIGSEGV
411                     && sig != SIGILL && sig != SIGFPE))
412         _exit(1);
413     if (raise(sig))
414         _exit(1);
415 }
416 #endif /* _WIN32 */
417
418 void
419 shutdwn(int sig)
420 {
421     struct player *p;
422     time_t now;
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     finish_server();
458
459 #if defined(_WIN32)
460     if (daemonize) {
461         stop_service();
462         return;
463     }
464 #endif
465     _exit(0);
466 }
467
468
469 static void
470 nullify_objects(void)
471 {
472     int i, j;
473
474     if (opt_BIG_CITY)
475         dchr[SCT_CAPIT] = bigcity_dchr;
476     if (opt_NO_LCMS)
477         dchr[SCT_LIGHT].d_cost = -1;
478     if (opt_NO_HCMS)
479         dchr[SCT_HEAVY].d_cost = -1;
480     if (opt_NO_OIL) {
481         dchr[SCT_OIL].d_cost = -1;
482         dchr[SCT_REFINE].d_cost = -1;
483     }
484     for (i = 0; i < pln_maxno; i++) {
485         if (opt_NO_HCMS)
486             plchr[i].pl_hcm = 0;
487         if (opt_NO_LCMS)
488             plchr[i].pl_lcm = 0;
489         if (opt_NO_OIL)
490             plchr[i].pl_fuel = 0;
491     }
492     for (i = 0; i < lnd_maxno; i++) {
493         if (opt_NO_HCMS)
494             lchr[i].l_hcm = 0;
495         if (opt_NO_LCMS)
496             lchr[i].l_lcm = 0;
497         /* Fix up the military values */
498         lchr[i].l_mil = lchr[i].l_item[I_MILIT];
499     }
500     for (i = 0; i < shp_maxno; i++) {
501         if (opt_NO_HCMS)
502             mchr[i].m_hcm = 0;
503         if (opt_NO_LCMS)
504             mchr[i].m_lcm = 0;
505         if (opt_NO_OIL) {
506             if (mchr[i].m_flags & M_OIL)
507                 mchr[i].m_name = 0;
508         }
509     }
510     for (i = 0; i < nuk_maxno; i++) {
511         if (opt_NO_HCMS)
512             nchr[i].n_hcm = 0;
513         if (opt_NO_LCMS)
514             nchr[i].n_lcm = 0;
515     }
516     for (i = 0; i <= SCT_MAXDEF; i++) {
517         if (opt_NO_HCMS)
518             dchr[i].d_hcms = 0;
519         if (opt_NO_LCMS)
520             dchr[i].d_lcms = 0;
521     }
522     for (i = 0; i < prd_maxno; i++) {
523         for (j = 0; j < MAXPRCON; j++) {
524             if (opt_NO_HCMS && pchr[i].p_ctype[j] == I_HCM)
525                 pchr[i].p_camt[j] = 0;
526             if (opt_NO_LCMS && pchr[i].p_ctype[j] == I_LCM)
527                 pchr[i].p_camt[j] = 0;
528             if (opt_NO_OIL && pchr[i].p_ctype[j] == I_OIL)
529                 pchr[i].p_camt[j] = 0;
530         }
531     }
532 }
533
534 #if defined(_WIN32)
535 static void
536 loc_NTInit(void)
537 {
538     int rc;
539     WORD wVersionRequested;
540     WSADATA wsaData;
541
542     wVersionRequested = MAKEWORD(2, 0);
543     rc = WSAStartup(wVersionRequested, &wsaData);
544     if (rc != 0) {
545         logerror("WSAStartup failed.  %d", rc);
546         _exit(1);
547     }
548 }
549
550 static void
551 loc_NTTerm(void)
552 {
553     WSACleanup();
554 }
555 #endif