]> git.pond.sub.org Git - empserver/blob - src/server/main.c
Update copyright notice
[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 #ifdef _WIN32
137 # define XOPTS "iI:uU:"
138 #else
139 # define XOPTS
140 #endif
141     while ((op = getopt(argc, argv, "de:hpsR:v" XOPTS)) != EOF) {
142         switch (op) {
143         case 'p':
144             flags |= EMPTH_PRINT;
145             /* fall through */
146         case 'd':
147             debug = 1;
148             daemonize = 0;
149             break;
150         case 'e':
151             config_file = optarg;
152             break;
153 #if defined(_WIN32)
154         case 'I':
155             service_name = optarg;
156             /* fall through */
157         case 'i':
158             install_service_set++;
159             break;
160         case 'U':
161             service_name = optarg;
162             /* fall through */
163         case 'u':
164             remove_service_set++;
165             break;
166 #endif  /* _WIN32 */
167         case 's':
168             flags |= EMPTH_STACKCHECK;
169             break;
170         case 'R':
171             seed = strtoul(optarg, NULL, 10);
172             break;
173         case 'v':
174             printf("%s\n\n%s", version, legal);
175             return EXIT_SUCCESS;
176         case 'h':
177             print_usage(argv[0]);
178             return EXIT_SUCCESS;
179         default:
180             fprintf(stderr, "Try -h for help.\n");
181             return EXIT_FAILURE;
182         }
183     }
184
185 #if defined(_WIN32)
186     if ((debug || flags || config_file != NULL) &&
187         remove_service_set) {
188         fprintf(stderr, "Can't use -p, -s, -d or -e with either "
189             "-u or -U options\n");
190         exit(EXIT_FAILURE);
191     }
192     if ((debug || flags) && install_service_set) {
193         fprintf(stderr, "Can't use -d, -p or -s with either "
194             "-i or -I options\n");
195         exit(EXIT_FAILURE);
196     }
197     if (install_service_set && remove_service_set) {
198         fprintf(stderr, "Can't use both -u or -U and -i or -I "
199             "options\n");
200         exit(EXIT_FAILURE);
201     }
202
203     if (remove_service_set)
204         return remove_service(service_name);
205     if (install_service_set) {
206         program_name = _fullpath(NULL, argv[0], 0);
207         if (config_file != NULL)
208             config_file = _fullpath(NULL, config_file, 0);
209     }
210 #endif  /* _WIN32 */
211
212     if (emp_config(config_file) < 0)
213         exit(EXIT_FAILURE);
214     ef_init();
215     if (chdir(configdir)) {
216         fprintf(stderr, "Can't chdir to %s (%s)\n",
217                 configdir, strerror(errno));
218         exit(EXIT_FAILURE);
219     }
220     if (chdir(builtindir)) {
221         fprintf(stderr, "Can't chdir to %s (%s)\n",
222                 builtindir, strerror(errno));
223         exit(EXIT_FAILURE);
224     }
225     if (read_builtin_tables() < 0)
226         exit(EXIT_FAILURE);
227     if (chdir(configdir)) {
228         fprintf(stderr, "Can't chdir to %s (%s)\n",
229                 configdir, strerror(errno));
230         exit(EXIT_FAILURE);
231     }
232     if (read_custom_tables() < 0)
233         exit(EXIT_FAILURE);
234     if (chdir(gamedir)) {
235         fprintf(stderr, "Can't chdir to %s (%s)\n",
236                 gamedir, strerror(errno));
237         exit(EXIT_FAILURE);
238     }
239
240 #if defined(_WIN32)
241     if (install_service_set)
242         return install_service(program_name, service_name, config_file);
243 #endif  /* _WIN32 */
244
245     init_server(seed);
246
247 #if defined(_WIN32)
248     if (daemonize != 0) {
249         SERVICE_TABLE_ENTRY DispatchTable[]={
250             {"Empire Server", service_main},
251             {NULL, NULL}
252         };
253         if (StartServiceCtrlDispatcher(DispatchTable))
254             return 0;
255         else {
256             /*
257              * If it is service startup error then exit otherwise
258              * start server in the foreground
259              */
260             if (GetLastError() != ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
261                 logerror("Failed to dispatch service (%lu)",
262                          GetLastError());
263                 finish_server();
264                 exit(EXIT_FAILURE);
265             }
266         }
267     }
268     daemonize = 0;
269 #else  /* !_WIN32 */
270     if (daemonize) {
271         if (disassoc() < 0) {
272             logerror("Can't become daemon (%s)", strerror(errno));
273             exit(1);
274         }
275     }
276 #endif /* !_WIN32 */
277     start_server(flags);
278
279     for (;;) {
280         sig = empth_wait_for_signal();
281 #ifdef SIGHUP
282         if (sig == SIGHUP) {
283             /* if you make changes here, also update relo() */
284             journal_reopen();
285             update_reschedule();
286             logreopen();
287             continue;
288         }
289 #endif
290         break;
291     }
292
293     shutdwn(sig);
294     CANT_REACH();
295     finish_server();
296     return EXIT_SUCCESS;
297 }
298
299
300 /*
301  * Initialize for serving, acquire resources.
302  */
303 void
304 init_server(unsigned seed)
305 {
306     srandom(seed);
307 #if defined(_WIN32)
308     loc_NTInit();
309 #endif
310     player_init();
311     ef_init_srv();
312     io_init();
313     init_nreport();
314
315     loginit("server");
316 }
317
318 /*
319  * Start serving.
320  */
321 void
322 start_server(int flags)
323 {
324     pid_t pid;
325
326     pid = getpid();
327     create_pidfile(pidfname, pid);
328     logerror("------------------------------------------------------");
329     logerror("Empire server (pid %d) started", (int)pid);
330
331     empth_init((void **)&player, flags);
332
333     if (journal_startup() < 0)
334         exit(1);
335
336     empth_create(player_accept, 50 * 1024, flags, "AcceptPlayers", 0);
337     empth_create(player_kill_idle, 50 * 1024, flags, "KillIdle", 0);
338     empth_create(delete_lostitems, 50 * 1024, flags, "DeleteItems", 0);
339
340     market_init();
341     update_init();
342 }
343
344 /*
345  * Finish serving, release resources.
346  */
347 void
348 finish_server(void)
349 {
350     ef_fin_srv();
351 #if defined(_WIN32)
352     loc_NTTerm();
353 #endif
354     journal_shutdown();
355     remove(pidfname);
356 }
357
358 static void
359 create_pidfile(char *fname, pid_t pid)
360 {
361     FILE *pidf = fopen(fname, "w");
362     if (!pidf
363         || fprintf(pidf, "%d\n", (int)pid) < 0
364         || fclose(pidf)) {
365         logerror("Can't write PID file (%s)", strerror(errno));
366         exit(1);
367     }
368 }
369
370 void
371 shutdwn(int sig)
372 {
373     struct player *p;
374
375     logerror("Shutdown commencing (cleaning up threads.)");
376
377     play_wrlock_wanted = 1;
378     for (p = player_next(0); p != 0; p = player_next(p)) {
379         if (p->state != PS_PLAYING)
380             continue;
381         pr_flash(p, "Server shutting down...\n");
382         p->state = PS_SHUTDOWN;
383         p->aborted++;
384         if (p->command) {
385             pr_flash(p, "Shutdown aborting command\n");
386         }
387         empth_wakeup(p->proc);
388     }
389     empth_rwlock_wrlock(play_lock);
390     if (sig)
391         logerror("Server shutting down on signal %d", sig);
392     else
393         logerror("Server shutting down at deity's request");
394     finish_server();
395
396 #if defined(_WIN32)
397     if (daemonize)
398         stop_service();
399 #endif
400     exit(0);
401 }
402
403 #if defined(_WIN32)
404 static void
405 loc_NTInit(void)
406 {
407     int rc;
408     WORD wVersionRequested;
409     WSADATA wsaData;
410
411     wVersionRequested = MAKEWORD(2, 0);
412     rc = WSAStartup(wVersionRequested, &wsaData);
413     if (rc != 0) {
414         logerror("WSAStartup failed.  %d", rc);
415         exit(1);
416     }
417 }
418
419 static void
420 loc_NTTerm(void)
421 {
422     WSACleanup();
423 }
424 #endif