]> git.pond.sub.org Git - empserver/blob - src/server/main.c
(shutdown_init): Has no effect, remove.
[empserver] / src / server / main.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2006, 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_close();
271             journal_open();
272             continue;
273         }
274 #endif
275         break;
276     }
277
278     shutdwn(sig);
279     CANT_REACH();
280     finish_server();
281     return EXIT_SUCCESS;
282 }
283
284
285 /*
286  * Initialize for serving, acquire resources.
287  */
288 void
289 init_server(void)
290 {
291     srandom(time(NULL));
292 #if defined(_WIN32)
293     loc_NTInit();
294 #endif
295     update_policy_check();
296     player_init();
297     ef_init_srv();
298     io_init();
299     init_nreport();
300
301     if (opt_MOB_ACCESS) {
302         /* This fixes up mobility upon restart */
303         mobility_init();
304     }
305
306     loginit("server");
307 }
308
309 /*
310  * Start serving.
311  */
312 void
313 start_server(int flags)
314 {
315     pid_t pid;
316
317     pid = getpid();
318     create_pidfile(pidfname, pid);
319     logerror("------------------------------------------------------");
320     logerror("Empire server (pid %d) started", (int)pid);
321
322     empth_init((void **)&player, flags);
323
324     empth_create(PP_ACCEPT, player_accept, (50 * 1024), flags,
325                  "AcceptPlayers", "Accept network connections", 0);
326     empth_create(PP_KILLIDLE, player_kill_idle, (50 * 1024), flags,
327                  "KillIdle", "Kills idle player connections", 0);
328     empth_create(PP_SCHED, update_sched, (50 * 1024), flags, "UpdateSched",
329                  "Schedules updates to occur", 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     if (opt_MARKET) {
339         empth_create(PP_TIMESTAMP, market_update, (50 * 1024), flags,
340                      "MarketUpdate", "Updates the market", 0);
341     }
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     remove(pidfname);
355 }
356
357 static void
358 create_pidfile(char *fname, pid_t pid)
359 {
360     FILE *pidf = fopen(fname, "w");
361     if (!pidf
362         || fprintf(pidf, "%d\n", (int)pid) < 0
363         || fclose(pidf)) {
364         logerror("Can't write PID file (%s)", strerror(errno));
365         exit(1);
366     }
367 }
368
369 void
370 shutdwn(int sig)
371 {
372     struct player *p;
373     time_t now;
374
375     logerror("Shutdown commencing (cleaning up threads.)");
376
377     for (p = player_next(0); p != 0; p = player_next(p)) {
378         if (p->state != PS_PLAYING)
379             continue;
380         pr_flash(p, "Server shutting down...\n");
381         p->state = PS_SHUTDOWN;
382         p->aborted++;
383         if (p->command) {
384             pr_flash(p, "Shutdown aborting command\n");
385         }
386         empth_wakeup(p->proc);
387     }
388
389     time(&now);
390     empth_sleep(now + 1);
391
392     for (p = player_next(0); p != 0; p = player_next(p)) {
393         p->state = PS_KILL;
394         p->aborted++;
395         empth_terminate(p->proc);
396         p = player_delete(p);
397     }
398     if (sig)
399         logerror("Server shutting down on signal %d", sig);
400     else
401         logerror("Server shutting down at deity's request");
402     finish_server();
403
404 #if defined(_WIN32)
405     if (daemonize)
406         stop_service();
407 #endif
408     exit(0);
409 }
410
411 #if defined(_WIN32)
412 static void
413 loc_NTInit(void)
414 {
415     int rc;
416     WORD wVersionRequested;
417     WSADATA wsaData;
418
419     wVersionRequested = MAKEWORD(2, 0);
420     rc = WSAStartup(wVersionRequested, &wsaData);
421     if (rc != 0) {
422         logerror("WSAStartup failed.  %d", rc);
423         exit(1);
424     }
425 }
426
427 static void
428 loc_NTTerm(void)
429 {
430     WSACleanup();
431 }
432 #endif