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