]> git.pond.sub.org Git - empserver/blob - src/server/main.c
(ef_open_srv, start_server): Journal must not be written before
[empserver] / src / server / main.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2007, 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-2006
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 #define WIN32
46 #include <winsock2.h>
47 #undef NS_ALL
48 #include <process.h>
49 #include <direct.h>
50 #include "service.h"
51 #include "../lib/gen/getopt.h"
52 #else
53 #include <sys/types.h>
54 #include <unistd.h>
55 #endif
56
57 #include "empio.h"
58 #include "empthread.h"
59 #include "file.h"
60 #include "journal.h"
61 #include "land.h"
62 #include "misc.h"
63 #include "nat.h"
64 #include "nuke.h"
65 #include "optlist.h"
66 #include "plane.h"
67 #include "player.h"
68 #include "product.h"
69 #include "prototypes.h"
70 #include "sect.h"
71 #include "server.h"
72 #include "ship.h"
73 #include "version.h"
74
75 static void create_pidfile(char *, pid_t);
76
77 #if defined(_WIN32)
78 static void loc_NTInit(void);
79 static void loc_NTTerm(void);
80 #endif
81
82 static char pidfname[] = "server.pid";
83
84 /* Run as daemon?  If yes, detach from controlling terminal etc. */
85 static int daemonize = 1;
86
87 static void
88 print_usage(char *program_name)
89 {
90     printf("Usage: %s [OPTION]...\n"
91            "  -d              debug mode\n"
92            "  -e CONFIG-FILE  configuration file\n"
93            "                  (default %s)\n"
94            "  -h              display this help and exit\n"
95 #ifdef _WIN32
96            "  -i              install service `%s'\n"
97            "  -I NAME         install service NAME\n"
98 #endif
99            "  -p              threading debug mode, implies -d\n"
100 #ifdef _WIN32
101            "  -r              remove service `%s'\n"
102            "  -R NAME         remove service NAME\n"
103 #endif
104            "  -s              enable stack checking\n"
105            "  -v              display version information and exit\n",
106            program_name, dflt_econfig
107 #ifdef _WIN32
108            , DEFAULT_SERVICE_NAME, DEFAULT_SERVICE_NAME
109 #endif
110         );
111 }
112
113 int
114 main(int argc, char **argv)
115 {
116     int flags = 0;
117 #if defined(_WIN32)
118     int install_service_set = 0;
119     char *program_name = NULL;
120     char *service_name = NULL;
121     int remove_service_set = 0;
122 #endif
123     char *config_file = NULL;
124     int op, sig;
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             /* fall through */
147         case 'i':
148             install_service_set++;
149             break;
150         case 'R':
151             service_name = optarg;
152             /* fall through */
153         case 'r':
154             remove_service_set++;
155             break;
156 #endif  /* _WIN32 */
157         case 's':
158             flags |= EMPTH_STACKCHECK;
159             break;
160         case 'v':
161             printf("%s\n\n%s", version, legal);
162             return EXIT_SUCCESS;
163         case 'h':
164             print_usage(argv[0]);
165             return EXIT_SUCCESS;
166         default:
167             fprintf(stderr, "Try -h for help.\n");
168             return EXIT_FAILURE;
169         }
170     }
171
172 #if defined(_WIN32)
173     if ((debug || flags || config_file != NULL) &&
174         remove_service_set) {
175         fprintf(stderr, "Can't use -p, -s, -d or -e with either "
176             "-r or -R options\n");
177         exit(EXIT_FAILURE);
178     }
179     if ((debug || flags) && install_service_set) {
180         fprintf(stderr, "Can't use -d, -p or -s with either "
181             "-i or -I options\n");
182         exit(EXIT_FAILURE);
183     }
184     if (install_service_set && remove_service_set) {
185         fprintf(stderr, "Can't use both -r or -R and -i or -I "
186             "options\n");
187         exit(EXIT_FAILURE);
188     }
189
190     if (remove_service_set)
191         return remove_service(service_name);
192     if (install_service_set) {
193         program_name = _fullpath(NULL, argv[0], 0);
194         if (config_file != NULL)
195             config_file = _fullpath(NULL, config_file, 0);
196     }
197 #endif  /* _WIN32 */
198
199     if (emp_config(config_file) < 0)
200         exit(EXIT_FAILURE);
201     ef_init();
202     if (chdir(configdir)) {
203         fprintf(stderr, "Can't chdir to %s (%s)\n",
204                 configdir, strerror(errno));
205         exit(EXIT_FAILURE);
206     }
207     if (chdir(builtindir)) {
208         fprintf(stderr, "Can't chdir to %s (%s)\n",
209                 builtindir, strerror(errno));
210         exit(EXIT_FAILURE);
211     }
212     if (read_builtin_tables() < 0)
213         exit(EXIT_FAILURE);
214     if (chdir(configdir)) {
215         fprintf(stderr, "Can't chdir to %s (%s)\n",
216                 configdir, strerror(errno));
217         exit(EXIT_FAILURE);
218     }
219     if (read_custom_tables() < 0)
220         exit(EXIT_FAILURE);
221     if (chdir(gamedir)) {
222         fprintf(stderr, "Can't chdir to %s (%s)\n",
223                 gamedir, strerror(errno));
224         exit(EXIT_FAILURE);
225     }
226
227 #if defined(_WIN32)
228     if (install_service_set)
229         return install_service(program_name, service_name, config_file);
230 #endif  /* _WIN32 */
231
232     init_server();
233
234 #if defined(_WIN32)
235     if (daemonize != 0) {
236         SERVICE_TABLE_ENTRY DispatchTable[]={
237             {"Empire Server", service_main},
238             {NULL, NULL}
239         };
240         if (StartServiceCtrlDispatcher(DispatchTable))
241             return 0;
242         else {
243             /*
244              * If it is service startup error then exit otherwise
245              * start server in the foreground
246              */
247             if (GetLastError() != ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
248                 logerror("Failed to dispatch service (%lu)",
249                          GetLastError());
250                 finish_server();
251                 exit(EXIT_FAILURE);
252             }
253         }
254     }
255     daemonize = 0;
256 #else  /* !_WIN32 */
257     if (daemonize) {
258         if (disassoc() < 0) {
259             logerror("Can't become daemon (%s)", strerror(errno));
260             exit(1);
261         }
262     }
263 #endif /* !_WIN32 */
264     start_server(flags);
265
266     for (;;) {
267         sig = empth_wait_for_signal();
268 #ifdef SIGHUP
269         if (sig == SIGHUP) {
270             journal_reopen();
271             continue;
272         }
273 #endif
274         break;
275     }
276
277     shutdwn(sig);
278     CANT_REACH();
279     finish_server();
280     return EXIT_SUCCESS;
281 }
282
283
284 /*
285  * Initialize for serving, acquire resources.
286  */
287 void
288 init_server(void)
289 {
290     srandom(time(NULL));
291 #if defined(_WIN32)
292     loc_NTInit();
293 #endif
294     update_policy_check();
295     player_init();
296     ef_init_srv();
297     io_init();
298     init_nreport();
299
300     if (opt_MOB_ACCESS) {
301         /* This fixes up mobility upon restart */
302         mobility_init();
303     }
304
305     loginit("server");
306 }
307
308 /*
309  * Start serving.
310  */
311 void
312 start_server(int flags)
313 {
314     pid_t pid;
315
316     pid = getpid();
317     create_pidfile(pidfname, pid);
318     logerror("------------------------------------------------------");
319     logerror("Empire server (pid %d) started", (int)pid);
320
321     empth_init((void **)&player, flags);
322
323     if (journal_startup() < 0)
324         exit(1);
325
326     empth_create(PP_ACCEPT, player_accept, (50 * 1024), flags,
327                  "AcceptPlayers", "Accept network connections", 0);
328     empth_create(PP_KILLIDLE, player_kill_idle, (50 * 1024), flags,
329                  "KillIdle", "Kills idle player connections", 0);
330     empth_create(PP_TIMESTAMP, delete_lostitems, (50 * 1024), flags,
331                  "DeleteItems", "Deletes old lost items", 0);
332     if (opt_MOB_ACCESS) {
333         /* Start the mobility access check thread */
334         empth_create(PP_TIMESTAMP, mobility_check, (50 * 1024), flags,
335                      "MobilityCheck", "Writes the timestamp file", 0);
336     }
337
338     market_init();
339     update_init();
340 }
341
342 /*
343  * Finish serving, release resources.
344  */
345 void
346 finish_server(void)
347 {
348     ef_fin_srv();
349 #if defined(_WIN32)
350     loc_NTTerm();
351 #endif
352     journal_shutdown();
353     remove(pidfname);
354 }
355
356 static void
357 create_pidfile(char *fname, pid_t pid)
358 {
359     FILE *pidf = fopen(fname, "w");
360     if (!pidf
361         || fprintf(pidf, "%d\n", (int)pid) < 0
362         || fclose(pidf)) {
363         logerror("Can't write PID file (%s)", strerror(errno));
364         exit(1);
365     }
366 }
367
368 void
369 shutdwn(int sig)
370 {
371     struct player *p;
372
373     logerror("Shutdown commencing (cleaning up threads.)");
374
375     for (p = player_next(0); p != 0; p = player_next(p)) {
376         if (p->state != PS_PLAYING)
377             continue;
378         pr_flash(p, "Server shutting down...\n");
379         p->state = PS_SHUTDOWN;
380         p->aborted++;
381         if (p->command) {
382             pr_flash(p, "Shutdown aborting command\n");
383         }
384         empth_wakeup(p->proc);
385     }
386     empth_rwlock_wrlock(update_lock);
387     /* rely on player_kill_idle() for killing hung player threads */
388     if (sig)
389         logerror("Server shutting down on signal %d", sig);
390     else
391         logerror("Server shutting down at deity's request");
392     finish_server();
393
394 #if defined(_WIN32)
395     if (daemonize)
396         stop_service();
397 #endif
398     exit(0);
399 }
400
401 #if defined(_WIN32)
402 static void
403 loc_NTInit(void)
404 {
405     int rc;
406     WORD wVersionRequested;
407     WSADATA wsaData;
408
409     wVersionRequested = MAKEWORD(2, 0);
410     rc = WSAStartup(wVersionRequested, &wsaData);
411     if (rc != 0) {
412         logerror("WSAStartup failed.  %d", rc);
413         exit(1);
414     }
415 }
416
417 static void
418 loc_NTTerm(void)
419 {
420     WSACleanup();
421 }
422 #endif