]> git.pond.sub.org Git - empserver/blob - src/server/main.c
20d1a264570518109291a1e2af92a8994f1673d4
[empserver] / src / server / main.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2008, 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 files README, COPYING and CREDITS in the root of the source
23  *  tree for related information and legal notices.  It is expected
24  *  that future projects/authors will amend these files as needed.
25  *
26  *  ---
27  *
28  *  main.c: Empire Server main, startup and shutdown
29  * 
30  *  Known contributors to this file:
31  *     Dave Pare, 1994
32  *     Steve McClure, 1996, 1998
33  *     Doug Hay, 1998
34  *     Ron Koenderink, 2004-2005
35  *     Markus Armbruster, 2005-2007
36  */
37
38 #include <config.h>
39
40 #include <errno.h>
41 #include <signal.h>
42 #include <stdio.h>
43
44 #if defined(_WIN32)
45 #include <winsock2.h>
46 #undef NS_ALL
47 #include <process.h>
48 #include "service.h"
49 #endif
50 #include <unistd.h>
51
52 #include "empio.h"
53 #include "empthread.h"
54 #include "file.h"
55 #include "journal.h"
56 #include "land.h"
57 #include "misc.h"
58 #include "nat.h"
59 #include "nuke.h"
60 #include "optlist.h"
61 #include "plane.h"
62 #include "player.h"
63 #include "product.h"
64 #include "prototypes.h"
65 #include "sect.h"
66 #include "server.h"
67 #include "ship.h"
68 #include "version.h"
69
70 static void create_pidfile(char *, pid_t);
71
72 #if defined(_WIN32)
73 static void loc_NTInit(void);
74 static void loc_NTTerm(void);
75 #endif
76
77 /*
78  * Lock to synchronize player threads with update and shutdown.
79  * Update and shutdown takes it exclusive, commands take it shared.
80  */
81 empth_rwlock_t *play_lock;
82
83 /*
84  * Is a thread attempting to take an exclusive play_lock?
85  * Threads holding a shared play_lock must not sleep while this is
86  * true.
87  */
88 int play_wrlock_wanted;
89
90 static char pidfname[] = "server.pid";
91
92 /* Run as daemon?  If yes, detach from controlling terminal etc. */
93 static int daemonize = 1;
94
95 static void
96 print_usage(char *program_name)
97 {
98     printf("Usage: %s [OPTION]...\n"
99            "  -d              debug mode\n"
100            "  -e CONFIG-FILE  configuration file\n"
101            "                  (default %s)\n"
102            "  -h              display this help and exit\n"
103 #ifdef _WIN32
104            "  -i              install service `%s'\n"
105            "  -I NAME         install service NAME\n"
106 #endif
107            "  -p              threading debug mode, implies -d\n"
108 #ifdef _WIN32
109            "  -u              uninstall service `%s'\n"
110            "  -U NAME         uninstall service NAME\n"
111 #endif
112            "  -s              enable stack checking\n"
113            "  -R RANDOM-SEED  random seed\n"
114            "  -v              display version information and exit\n",
115            program_name, dflt_econfig
116 #ifdef _WIN32
117            , DEFAULT_SERVICE_NAME, DEFAULT_SERVICE_NAME
118 #endif
119         );
120 }
121
122 int
123 main(int argc, char **argv)
124 {
125     int flags = 0;
126 #if defined(_WIN32)
127     int install_service_set = 0;
128     char *program_name = NULL;
129     char *service_name = NULL;
130     int remove_service_set = 0;
131 #endif
132     char *config_file = NULL;
133     int op, sig;
134     unsigned seed = time(NULL);
135
136     debug = 0;
137
138 #ifdef _WIN32
139 # define XOPTS "iI:uU:"
140 #else
141 # define XOPTS
142 #endif
143     while ((op = getopt(argc, argv, "de:hpsR:v" XOPTS)) != EOF) {
144         switch (op) {
145         case 'p':
146             flags |= EMPTH_PRINT;
147             /* fall through */
148         case 'd':
149             debug = 1;
150             daemonize = 0;
151             break;
152         case 'e':
153             config_file = optarg;
154             break;
155 #if defined(_WIN32)
156         case 'I':
157             service_name = optarg;
158             /* fall through */
159         case 'i':
160             install_service_set++;
161             break;
162         case 'U':
163             service_name = optarg;
164             /* fall through */
165         case 'u':
166             remove_service_set++;
167             break;
168 #endif  /* _WIN32 */
169         case 's':
170             flags |= EMPTH_STACKCHECK;
171             break;
172         case 'R':
173             seed = strtoul(optarg, NULL, 10);
174             break;
175         case 'v':
176             printf("%s\n\n%s", version, legal);
177             return EXIT_SUCCESS;
178         case 'h':
179             print_usage(argv[0]);
180             return EXIT_SUCCESS;
181         default:
182             fprintf(stderr, "Try -h for help.\n");
183             return EXIT_FAILURE;
184         }
185     }
186
187 #if defined(_WIN32)
188     if ((debug || flags || config_file != NULL) &&
189         remove_service_set) {
190         fprintf(stderr, "Can't use -p, -s, -d or -e with either "
191             "-u or -U options\n");
192         exit(EXIT_FAILURE);
193     }
194     if ((debug || flags) && install_service_set) {
195         fprintf(stderr, "Can't use -d, -p or -s with either "
196             "-i or -I options\n");
197         exit(EXIT_FAILURE);
198     }
199     if (install_service_set && remove_service_set) {
200         fprintf(stderr, "Can't use both -u or -U and -i or -I "
201             "options\n");
202         exit(EXIT_FAILURE);
203     }
204
205     if (remove_service_set)
206         return remove_service(service_name);
207     if (install_service_set) {
208         program_name = _fullpath(NULL, argv[0], 0);
209         if (config_file != NULL)
210             config_file = _fullpath(NULL, config_file, 0);
211     }
212 #endif  /* _WIN32 */
213
214     if (emp_config(config_file) < 0)
215         exit(EXIT_FAILURE);
216     ef_init();
217     if (chdir(configdir)) {
218         fprintf(stderr, "Can't chdir to %s (%s)\n",
219                 configdir, strerror(errno));
220         exit(EXIT_FAILURE);
221     }
222     if (chdir(builtindir)) {
223         fprintf(stderr, "Can't chdir to %s (%s)\n",
224                 builtindir, strerror(errno));
225         exit(EXIT_FAILURE);
226     }
227     if (read_builtin_tables() < 0)
228         exit(EXIT_FAILURE);
229     if (chdir(configdir)) {
230         fprintf(stderr, "Can't chdir to %s (%s)\n",
231                 configdir, strerror(errno));
232         exit(EXIT_FAILURE);
233     }
234     if (read_custom_tables() < 0)
235         exit(EXIT_FAILURE);
236     if (chdir(gamedir)) {
237         fprintf(stderr, "Can't chdir to %s (%s)\n",
238                 gamedir, strerror(errno));
239         exit(EXIT_FAILURE);
240     }
241
242 #if defined(_WIN32)
243     if (install_service_set)
244         return install_service(program_name, service_name, config_file);
245 #endif  /* _WIN32 */
246
247     init_server(seed);
248
249 #if defined(_WIN32)
250     if (daemonize != 0) {
251         SERVICE_TABLE_ENTRY DispatchTable[]={
252             {"Empire Server", service_main},
253             {NULL, NULL}
254         };
255         if (StartServiceCtrlDispatcher(DispatchTable))
256             return 0;
257         else {
258             /*
259              * If it is service startup error then exit otherwise
260              * start server in the foreground
261              */
262             if (GetLastError() != ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
263                 logerror("Failed to dispatch service (%lu)",
264                          GetLastError());
265                 finish_server();
266                 exit(EXIT_FAILURE);
267             }
268         }
269     }
270     daemonize = 0;
271 #else  /* !_WIN32 */
272     if (daemonize) {
273         if (disassoc() < 0) {
274             logerror("Can't become daemon (%s)", strerror(errno));
275             exit(1);
276         }
277     }
278 #endif /* !_WIN32 */
279     start_server(flags);
280
281     for (;;) {
282         sig = empth_wait_for_signal();
283 #ifdef SIGHUP
284         if (sig == SIGHUP) {
285             /* if you make changes here, also update relo() */
286             journal_reopen();
287             update_reschedule();
288             logreopen();
289             continue;
290         }
291 #endif
292         break;
293     }
294
295     shutdwn(sig);
296     CANT_REACH();
297     finish_server();
298     return EXIT_SUCCESS;
299 }
300
301
302 /*
303  * Initialize for serving, acquire resources.
304  */
305 void
306 init_server(unsigned seed)
307 {
308     srandom(seed);
309 #if defined(_WIN32)
310     loc_NTInit();
311 #endif
312     player_init();
313     ef_init_srv();
314     io_init();
315     init_nreport();
316
317     loginit("server");
318 }
319
320 /*
321  * Start serving.
322  */
323 void
324 start_server(int flags)
325 {
326     pid_t pid;
327
328     pid = getpid();
329     create_pidfile(pidfname, pid);
330     logerror("------------------------------------------------------");
331     logerror("Empire server (pid %d) started", (int)pid);
332
333     empth_init((void **)&player, flags);
334
335     if (journal_startup() < 0)
336         exit(1);
337
338     empth_create(player_accept, 50 * 1024, flags, "AcceptPlayers", 0);
339     empth_create(player_kill_idle, 50 * 1024, flags, "KillIdle", 0);
340     empth_create(delete_lostitems, 50 * 1024, flags, "DeleteItems", 0);
341
342     market_init();
343     update_init();
344 }
345
346 /*
347  * Finish serving, release resources.
348  */
349 void
350 finish_server(void)
351 {
352     ef_fin_srv();
353 #if defined(_WIN32)
354     loc_NTTerm();
355 #endif
356     journal_shutdown();
357     remove(pidfname);
358 }
359
360 static void
361 create_pidfile(char *fname, pid_t pid)
362 {
363     FILE *pidf = fopen(fname, "w");
364     if (!pidf
365         || fprintf(pidf, "%d\n", (int)pid) < 0
366         || fclose(pidf)) {
367         logerror("Can't write PID file (%s)", strerror(errno));
368         exit(1);
369     }
370 }
371
372 void
373 shutdwn(int sig)
374 {
375     struct player *p;
376
377     logerror("Shutdown commencing (cleaning up threads.)");
378
379     play_wrlock_wanted = 1;
380     for (p = player_next(0); p != 0; p = player_next(p)) {
381         if (p->state != PS_PLAYING)
382             continue;
383         pr_flash(p, "Server shutting down...\n");
384         p->state = PS_SHUTDOWN;
385         p->aborted++;
386         if (p->command) {
387             pr_flash(p, "Shutdown aborting command\n");
388         }
389         empth_wakeup(p->proc);
390     }
391     empth_rwlock_wrlock(play_lock);
392     if (sig)
393         logerror("Server shutting down on signal %d", sig);
394     else
395         logerror("Server shutting down at deity's request");
396     finish_server();
397
398 #if defined(_WIN32)
399     if (daemonize)
400         stop_service();
401 #endif
402     exit(0);
403 }
404
405 #if defined(_WIN32)
406 static void
407 loc_NTInit(void)
408 {
409     int rc;
410     WORD wVersionRequested;
411     WSADATA wsaData;
412
413     wVersionRequested = MAKEWORD(2, 0);
414     rc = WSAStartup(wVersionRequested, &wsaData);
415     if (rc != 0) {
416         logerror("WSAStartup failed.  %d", rc);
417         exit(1);
418     }
419 }
420
421 static void
422 loc_NTTerm(void)
423 {
424     WSACleanup();
425 }
426 #endif