]> git.pond.sub.org Git - empserver/blob - src/server/main.c
(create_pidfile): Silence compiler warning on printing pid_t with %d.
[empserver] / src / server / main.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2005, 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 #define WIN32
47 #include <winsock2.h>
48 #undef NS_ALL
49 #include <process.h>
50 #include "../lib/gen/getopt.h"
51 #include "service.h"
52 #include "direct.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 "server.h"
68 #include "version.h"
69 #include "prototypes.h"
70
71 static void nullify_objects(void);
72 static void init_files(void);
73 static void close_files(void);
74 static void create_pidfile(char *, pid_t);
75
76 #if defined(_WIN32)
77 static void loc_NTInit(void);
78 static void loc_NTTerm(void);
79 #endif
80
81 static char pidfname[] = "server.pid";
82
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     printf("Usage: %s [OPTION]...\n"
90            "  -d              debug mode\n"
91            "  -e CONFIG-FILE  configuration file\n"
92            "                  (default %s)\n"
93            "  -h              display this help and exit\n"
94 #ifdef _WIN32
95            "  -i              install service `%s'\n"
96            "  -I NAME         install service NAME\n"
97 #endif
98            "  -p              threading debug mode, implies -d\n"
99 #ifdef _WIN32
100            "  -r              remove service `%s'\n"
101            "  -R NAME         remove service NAME\n"
102 #endif
103            "  -s              enable stack checking\n"
104            "  -v              display version information and exit\n",
105            program_name, dflt_econfig
106 #ifdef _WIN32
107            , DEFAULT_SERVICE_NAME, DEFAULT_SERVICE_NAME
108 #endif
109         );
110 }
111
112 int
113 main(int argc, char **argv)
114 {
115     int flags = 0;
116 #if defined(_WIN32)
117     int install_service_set = 0;
118     char *program_name = NULL;
119     char *service_name = NULL;
120     int remove_service_set = 0;
121 #endif
122     char *config_file = NULL;
123     int op;
124
125 #ifdef _WIN32
126 # define XOPTS "iI:rR:"
127 #else
128 # define XOPTS
129 #endif
130     while ((op = getopt(argc, argv, "de:hpsv" XOPTS)) != EOF) {
131         switch (op) {
132         case 'p':
133             flags |= EMPTH_PRINT;
134             /* fall through */
135         case 'd':
136             debug = 1;
137             daemonize = 0;
138             break;
139         case 'e':
140             config_file = optarg;
141             break;
142 #if defined(_WIN32)
143         case 'I':
144             service_name = optarg;
145             /*
146              * fall out
147              */
148         case 'i':
149             install_service_set++;
150             break;
151         case 'R':
152             service_name = optarg;
153             /*
154              * fall out
155              */
156         case 'r':
157             remove_service_set++;
158             break;
159 #endif
160         case 's':
161             flags |= EMPTH_STACKCHECK;
162             break;
163         case 'v':
164             printf("Wolfpack Empire %d.%d.%d\n",
165                    EMP_VERS_MAJOR, EMP_VERS_MINOR, EMP_VERS_PATCH);
166             return EXIT_SUCCESS;
167         case 'h':
168             print_usage(argv[0]);
169             return EXIT_SUCCESS;
170         default:
171             fprintf(stderr, "Try -h for help.\n");
172             return EXIT_FAILURE;
173         }
174     }
175
176 #if defined(_WIN32)
177     if ((debug || flags || config_file != NULL) &&
178         remove_service_set) {
179         fprintf(stderr, "Can't use -p, -s, -d or -e with either "
180             "-r or -R options\n");
181         exit(EXIT_FAILURE);
182     }
183     if ((debug || flags) && install_service_set) {
184         fprintf(stderr, "Can't use -d, -p or -s with either "
185             "-i or -I options\n");
186         exit(EXIT_FAILURE);
187     }
188     if (install_service_set && remove_service_set) {
189         fprintf(stderr, "Can't use both -r or -R and -i or -I "
190             "options\n");
191         exit(EXIT_FAILURE);
192     }
193 #endif  /* _WIN32 */
194
195
196 #if defined(_WIN32)
197     if (remove_service_set)
198         return remove_service(service_name);
199     if (install_service_set) {
200         program_name = _fullpath(NULL, argv[0], 0);
201         if (config_file != NULL)
202             config_file = _fullpath(NULL, config_file, 0);
203     }
204 #endif  /* _WIN32 */
205
206     if (emp_config(config_file) < 0)
207         exit(EXIT_FAILURE);
208     if (chdir(datadir)) {
209         fprintf(stderr, "Can't chdir to %s (%s)\n", datadir, strerror(errno));
210         exit(EXIT_FAILURE);
211     }
212
213 #if defined(_WIN32)
214     if (install_service_set)
215         return install_service(program_name, service_name, config_file);
216 #endif  /* _WIN32 */
217
218     init_server();
219
220 #if defined(_WIN32)
221     if (daemonize != 0) {
222         SERVICE_TABLE_ENTRY DispatchTable[]={{"Empire Server", service_main},{NULL, NULL}};
223         if (StartServiceCtrlDispatcher(DispatchTable))
224             return 0;
225         else {
226             /*
227              * If it is service startup error then exit otherwise
228              * start server in the foreground
229              */
230             if (GetLastError() != ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
231                 logerror("Failed to dispatch service (%d)", GetLastError());
232                 finish_server();
233                 exit(EXIT_FAILURE);
234             }
235         }
236     }
237     daemonize = 0;
238 #else  /* !_WIN32 */
239     if (daemonize)
240         disassoc();
241 #endif /* !_WIN32 */
242     start_server(flags);
243
244     empth_exit();
245
246     CANT_HAPPEN("main thread terminated");
247     finish_server();
248     return EXIT_SUCCESS;
249 }
250
251
252 /*
253  * Initialize for serving, acquire resources.
254  */
255 void
256 init_server(void)
257 {
258     srandom(time(NULL));
259 #if defined(_WIN32)
260     loc_NTInit();
261 #endif
262     update_policy_check();
263     nullify_objects();
264     global_init();
265     shutdown_init();
266     player_init();
267     ef_init();
268     init_files();
269     io_init();
270     init_nreport();
271
272     if (opt_MOB_ACCESS) {
273         /* This fixes up mobility upon restart */
274         mobility_init();
275     }
276
277     loginit("server");
278 }
279
280 /*
281  * Start serving.
282  */
283 void
284 start_server(int flags)
285 {
286     pid_t pid;
287 #if !defined(_WIN32)
288     struct sigaction act;
289 #endif
290
291     pid = getpid();
292     create_pidfile(pidfname, pid);
293     logerror("------------------------------------------------------");
294     logerror("Empire server (pid %d) started", (int)pid);
295
296 #if !defined(_WIN32)
297     /* signal() should not be used with mit pthreads. Anyway if u
298        have a posix threads u definitly have posix signals -- Sasha */
299     sigemptyset(&act.sa_mask);
300     act.sa_handler = shutdwn;
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 #endif /* !_WIN32 */
311
312     empth_init((void **)&player, flags);
313
314     empth_create(PP_ACCEPT, player_accept, (50 * 1024), flags,
315                  "AcceptPlayers", "Accept network connections", 0);
316     empth_create(PP_KILLIDLE, player_kill_idle, (50 * 1024), flags,
317                  "KillIdle", "Kills idle player connections", 0);
318     empth_create(PP_SCHED, update_sched, (50 * 1024), flags, "UpdateSched",
319                  "Schedules updates to occur", 0);
320     empth_create(PP_TIMESTAMP, delete_lostitems, (50 * 1024), flags,
321                  "DeleteItems", "Deletes old lost items", 0);
322     if (opt_MOB_ACCESS) {
323         /* Start the mobility access check thread */
324         empth_create(PP_TIMESTAMP, mobility_check, (50 * 1024), flags,
325                      "MobilityCheck", "Writes the timestamp file", 0);
326     }
327
328     if (opt_MARKET) {
329         empth_create(PP_TIMESTAMP, market_update, (50 * 1024), flags,
330                      "MarketUpdate", "Updates the market", 0);
331     }
332 }
333
334 /*
335  * Finish serving, release resources.
336  */
337 void
338 finish_server(void)
339 {
340     close_files();
341 #if defined(_WIN32)
342     loc_NTTerm();
343 #endif
344     remove(pidfname);
345 }
346
347 static void
348 create_pidfile(char *fname, pid_t pid)
349 {
350     FILE *pidf = fopen(fname, "w");
351     if (!pidf
352         || fprintf(pidf, "%d\n", (int)pid) < 0
353         || fclose(pidf)) {
354         logerror("Can't write PID file (%s)", strerror(errno));
355         exit(1);
356     }
357 }
358
359 static void
360 init_files(void)
361 {
362     int failed = 0;
363     failed |= !ef_open(EF_NATION, O_RDWR, EFF_MEM);
364     failed |= !ef_open(EF_SECTOR, O_RDWR, EFF_MEM);
365     failed |= !ef_open(EF_SHIP, O_RDWR, EFF_MEM);
366     failed |= !ef_open(EF_PLANE, O_RDWR, EFF_MEM);
367     failed |= !ef_open(EF_LAND, O_RDWR, EFF_MEM);
368     failed |= !ef_open(EF_NEWS, O_RDWR, 0);
369     failed |= !ef_open(EF_LOAN, O_RDWR, 0);
370     failed |= !ef_open(EF_TREATY, O_RDWR, 0);
371     failed |= !ef_open(EF_NUKE, O_RDWR, EFF_MEM);
372     failed |= !ef_open(EF_POWER, O_RDWR, 0);
373     failed |= !ef_open(EF_TRADE, O_RDWR, 0);
374     failed |= !ef_open(EF_MAP, O_RDWR, EFF_MEM);
375     failed |= !ef_open(EF_BMAP, O_RDWR, EFF_MEM);
376     failed |= !ef_open(EF_COMM, O_RDWR, 0);
377     failed |= !ef_open(EF_LOST, O_RDWR, 0);
378     if (failed) {
379         logerror("Missing files, giving up");
380         exit(EXIT_FAILURE);
381     }
382 }
383
384 static void
385 close_files(void)
386 {
387     ef_close(EF_NATION);
388     ef_close(EF_SECTOR);
389     ef_close(EF_SHIP);
390     ef_close(EF_PLANE);
391     ef_close(EF_LAND);
392     ef_close(EF_NEWS);
393     ef_close(EF_LOAN);
394     ef_close(EF_TREATY);
395     ef_close(EF_NUKE);
396     ef_close(EF_POWER);
397     ef_close(EF_TRADE);
398     ef_close(EF_MAP);
399     ef_close(EF_COMM);
400     ef_close(EF_BMAP);
401     ef_close(EF_LOST);
402 }
403
404 /* we're going down.  try to close the files at least */
405 #if !defined(_WIN32)
406 void
407 panic(int sig)
408 {
409     struct sigaction act;
410
411     act.sa_flags = 0;
412     sigemptyset(&act.sa_mask);
413     act.sa_handler = SIG_DFL;
414     sigaction(SIGBUS, &act, NULL);
415     sigaction(SIGSEGV, &act, NULL);
416     sigaction(SIGILL, &act, NULL);
417     sigaction(SIGFPE, &act, NULL);
418     logerror("server received fatal signal %d", sig);
419     log_last_commands();
420     close_files();
421     if (CANT_HAPPEN(sig != SIGBUS && sig != SIGSEGV
422                     && sig != SIGILL && sig != SIGFPE))
423         _exit(1);
424     if (raise(sig))
425         _exit(1);
426 }
427 #endif /* _WIN32 */
428
429 void
430 shutdwn(int sig)
431 {
432     struct player *p;
433     time_t now;
434
435     logerror("Shutdown commencing (cleaning up threads.)");
436
437     for (p = player_next(0); p != 0; p = player_next(p)) {
438         if (p->state != PS_PLAYING)
439             continue;
440         pr_flash(p, "Server shutting down...\n");
441         p->state = PS_SHUTDOWN;
442         p->aborted++;
443         if (p->command) {
444             pr_flash(p, "Shutdown aborting command\n");
445         }
446         empth_wakeup(p->proc);
447     }
448
449     if (!sig) {
450         /* Sleep and let some cleanup happen - note this doesn't work
451            when called from a signal handler, since we may or may not
452            be in the right thread.  So we just pass by and kill 'em
453            all. */
454         time(&now);
455         empth_sleep(now + 1);
456     }
457
458     for (p = player_next(0); p != 0; p = player_next(p)) {
459         p->state = PS_KILL;
460         p->aborted++;
461         empth_terminate(p->proc);
462         p = player_delete(p);
463     }
464     if (sig)
465         logerror("Server shutting down on signal %d", sig);
466     else
467         logerror("Server shutting down at deity's request");
468     finish_server();
469
470 #if defined(_WIN32)
471     if (daemonize) {
472         stop_service();
473         return;
474     }
475 #endif
476     _exit(0);
477 }
478
479
480 static void
481 nullify_objects(void)
482 {
483     int i, j;
484
485     if (opt_BIG_CITY)
486         dchr[SCT_CAPIT] = bigcity_dchr;
487     if (opt_NO_LCMS)
488         dchr[SCT_LIGHT].d_cost = -1;
489     if (opt_NO_HCMS)
490         dchr[SCT_HEAVY].d_cost = -1;
491     if (opt_NO_OIL) {
492         dchr[SCT_OIL].d_cost = -1;
493         dchr[SCT_REFINE].d_cost = -1;
494     }
495     for (i = 0; i < pln_maxno; i++) {
496         if (opt_NO_HCMS)
497             plchr[i].pl_hcm = 0;
498         if (opt_NO_LCMS)
499             plchr[i].pl_lcm = 0;
500         if (opt_NO_OIL)
501             plchr[i].pl_fuel = 0;
502     }
503     for (i = 0; i < lnd_maxno; i++) {
504         if (opt_NO_HCMS)
505             lchr[i].l_hcm = 0;
506         if (opt_NO_LCMS)
507             lchr[i].l_lcm = 0;
508         /* Fix up the military values */
509         lchr[i].l_mil = lchr[i].l_item[I_MILIT];
510     }
511     for (i = 0; i < shp_maxno; i++) {
512         if (opt_NO_HCMS)
513             mchr[i].m_hcm = 0;
514         if (opt_NO_LCMS)
515             mchr[i].m_lcm = 0;
516         if (opt_NO_OIL) {
517             if (mchr[i].m_flags & M_OIL)
518                 mchr[i].m_name = 0;
519         }
520     }
521     for (i = 0; i < nuk_maxno; i++) {
522         if (opt_NO_HCMS)
523             nchr[i].n_hcm = 0;
524         if (opt_NO_LCMS)
525             nchr[i].n_lcm = 0;
526     }
527     for (i = 0; i <= SCT_MAXDEF; i++) {
528         if (opt_NO_HCMS)
529             dchr[i].d_hcms = 0;
530         if (opt_NO_LCMS)
531             dchr[i].d_lcms = 0;
532     }
533     for (i = 0; i < prd_maxno; i++) {
534         for (j = 0; j < MAXPRCON; j++) {
535             if (opt_NO_HCMS && pchr[i].p_ctype[j] == I_HCM)
536                 pchr[i].p_camt[j] = 0;
537             if (opt_NO_LCMS && pchr[i].p_ctype[j] == I_LCM)
538                 pchr[i].p_camt[j] = 0;
539             if (opt_NO_OIL && pchr[i].p_ctype[j] == I_OIL)
540                 pchr[i].p_camt[j] = 0;
541         }
542     }
543 }
544
545 #if defined(_WIN32)
546 static void
547 loc_NTInit(void)
548 {
549     int rc;
550     WORD wVersionRequested;
551     WSADATA wsaData;
552
553     wVersionRequested = MAKEWORD(2, 0);
554     rc = WSAStartup(wVersionRequested, &wsaData);
555     if (rc != 0) {
556         logerror("WSAStartup failed.  %d", rc);
557         _exit(1);
558     }
559 }
560
561 static void
562 loc_NTTerm(void)
563 {
564     WSACleanup();
565 }
566 #endif