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