i18n fixes
[srvx.git] / src / main.c
1 /* main.c - srvx
2  * Copyright 2000-2004 srvx Development Team
3  *
4  * This file is part of srvx.
5  *
6  * srvx 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 srvx; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
19  */
20
21 #define PID_FILE "srvx.pid"
22
23 #include "conf.h"
24 #include "gline.h"
25 #include "ioset.h"
26 #include "modcmd.h"
27 #include "saxdb.h"
28 #include "sendmail.h"
29 #include "timeq.h"
30
31 #include "chanserv.h"
32 #include "global.h"
33 #include "modules.h"
34 #include "opserv.h"
35
36 #ifdef HAVE_GETOPT_H
37 #include <getopt.h>
38 #else
39 #include "getopt.h"
40 #endif
41 #ifdef HAVE_SYS_RESOURCE_H
42 #include <sys/resource.h>
43 #endif
44 #ifdef HAVE_NETINET_IN_H
45 #include <netinet/in.h>
46 #endif
47 #ifdef HAVE_SYS_SOCKET_H
48 #include <sys/socket.h>
49 #endif
50 #ifdef HAVE_SYS_WAIT_H
51 #include <sys/wait.h>
52 #endif
53
54 #ifndef SIGCHLD
55 #define SIGCHLD SIGCLD
56 #endif
57
58 extern FILE *replay_file;
59
60 time_t boot_time, burst_begin, now;
61 unsigned long burst_length;
62 struct log_type *MAIN_LOG;
63
64 int quit_services, max_cycles;
65
66 char *services_config = "srvx.conf";
67
68 char **services_argv;
69 int services_argc;
70
71 struct cManagerNode cManager;
72
73 struct policer_params *oper_policer_params, *luser_policer_params, *god_policer_params;
74
75 static const struct message_entry msgtab[] = {
76     { "MSG_NONE", "None" },
77     { "MSG_ON", "On" },
78     { "MSG_OFF", "Off" },
79     { "MSG_NEVER", "Never" },
80     { "MSG_SERVICE_IMMUNE", "$b%s$b may not be kicked, killed, banned, or deopped." },
81     { "MSG_SERVICE_PRIVILEGED", "$b%s$b is a privileged service." },
82     { "MSG_NOT_A_SERVICE", "$b%s$b is not a service bot." },
83     { "MSG_COMMAND_UNKNOWN", "$b%s$b is an unknown command." },
84     { "MSG_COMMAND_PRIVILEGED", "$b%s$b is a privileged command." },
85     { "MSG_COMMAND_DISABLED", "$b%s$b is a disabled command." },
86     { "MSG_SETTING_PRIVILEGED", "$b%s$b is a privileged setting." },
87     { "MSG_AUTHENTICATE", "You must first authenticate with $b$N$b." },
88     { "MSG_USER_AUTHENTICATE", "%s must first authenticate with $b$N$b." },
89     { "MSG_SET_EMAIL_ADDR", "You must first set your account's email address.  (Contact network staff if you cannot auth to your account.)" },
90     { "MSG_HANDLE_UNKNOWN", "Account $b%s$b has not been registered." },
91     { "MSG_NICK_UNKNOWN", "User with nick $b%s$b does not exist." },
92     { "MSG_CHANNEL_UNKNOWN", "Channel with name $b%s$b does not exist." },
93     { "MSG_SERVER_UNKNOWN", "Server with name $b%s$b does not exist or is not linked." },
94     { "MSG_MODULE_UNKNOWN", "No module has been registered with name $b%s$b." },
95     { "MSG_INVALID_MODES", "$b%s$b is an invalid set of channel modes." },
96     { "MSG_INVALID_GLINE", "Invalid G-line '%s'." },
97     { "MSG_INVALID_DURATION", "Invalid time span '%s'." },
98     { "MSG_NOT_TARGET_NAME", "You must provide the name of a channel or user." },
99     { "MSG_NOT_CHANNEL_NAME", "You must provide a valid channel name." },
100     { "MSG_INVALID_CHANNEL", "You must provide the name of a channel that exists." },
101     { "MSG_CHANNEL_ABSENT", "You aren't currently in $b%s$b." },
102     { "MSG_CHANNEL_USER_ABSENT", "$b%s$b isn't currently in $b%s$b." },
103     { "MSG_MISSING_PARAMS", "$b%s$b requires more parameters." },
104     { "MSG_DEPRECATED_COMMAND", "The $b%s$b command has been deprecated, and will be removed in the future; please use $b%s$b instead." },
105     { "MSG_OPER_SUSPENDED", "Your $b$O$b access has been suspended." },
106     { "MSG_USER_OUTRANKED", "$b%s$b outranks you (command has no effect)." },
107     { "MSG_STUPID_ACCESS_CHANGE", "Please ask someone $belse$b to demote you." },
108     { "MSG_NO_SEARCH_ACCESS", "You do not have enough access to search based on $b%s$b." },
109     { "MSG_INVALID_CRITERIA", "$b%s$b is an invalid search criteria." },
110     { "MSG_MATCH_COUNT", "Found $b%u$b matches." },
111     { "MSG_NO_MATCHES", "Nothing matched the criteria of your search." },
112     { "MSG_TOPIC_UNKNOWN", "No help on that topic." },
113     { "MSG_INVALID_BINARY", "$b%s$b is an invalid binary value." },
114     { "MSG_INTERNAL_FAILURE", "Your command could not be processed due to an internal failure." },
115     { "MSG_DB_UNKNOWN", "I do not know of a database named %s." },
116     { "MSG_DB_IS_MONDO", "Database %s is in the \"mondo\" database and cannot be written separately." },
117     { "MSG_DB_WRITE_ERROR", "Error while writing database %s." },
118     { "MSG_DB_WROTE_DB", "Wrote database %s (in "FMT_TIME_T".%06lu seconds)." },
119     { "MSG_DB_WROTE_ALL", "Wrote all databases (in "FMT_TIME_T".%06lu seconds)." },
120     { NULL, NULL }
121 };
122
123 void uplink_select(char *name);
124
125 static int
126 uplink_insert(const char *key, void *data, UNUSED_ARG(void *extra))
127 {
128     struct uplinkNode *uplink = malloc(sizeof(struct uplinkNode));
129     struct record_data *rd = data;
130     int enabled = 1;
131     char *str;
132     struct sockaddr_in *sin;
133     unsigned long addr;
134
135     if(!uplink)
136     {
137         return 0;
138     }
139
140     uplink->name = (char *)key;
141     uplink->host = database_get_data(rd->d.object, "address", RECDB_QSTRING);
142
143     str = database_get_data(rd->d.object, "port", RECDB_QSTRING);
144     uplink->port = str ? atoi(str) : 6667;
145     uplink->password = database_get_data(rd->d.object, "password", RECDB_QSTRING);
146     uplink->their_password = database_get_data(rd->d.object, "uplink_password", RECDB_QSTRING);
147
148     str = database_get_data(rd->d.object, "enabled", RECDB_QSTRING);
149     if(str)
150     {
151         enabled = atoi(str) ? 1 : 0;
152     }
153
154     cManager.enabled += enabled;
155
156     str = database_get_data(rd->d.object, "max_tries", RECDB_QSTRING);
157     uplink->max_tries = str ? atoi(str) : 3;
158     uplink->flags = enabled ? 0 : UPLINK_UNAVAILABLE;
159     uplink->state = DISCONNECTED;
160     uplink->tries = 0;
161
162     str = database_get_data(rd->d.object, "bind_address", RECDB_QSTRING);
163     uplink->bind_addr_len = sizeof(*sin);
164     if (str && getipbyname(str, &addr)) 
165     {
166         sin = calloc(1, uplink->bind_addr_len);
167         sin->sin_family = AF_INET;
168         sin->sin_addr.s_addr = addr;
169         uplink->bind_addr = sin;
170     } 
171     else 
172     {
173         uplink->bind_addr = NULL;
174         uplink->bind_addr_len = 0;
175     }
176
177     uplink->next = cManager.uplinks;
178     uplink->prev = NULL;
179
180     if(cManager.uplinks)
181     {
182         cManager.uplinks->prev = uplink;
183     }
184
185     cManager.uplinks = uplink;
186
187     /* If the configuration is being reloaded, set the current uplink
188        to the reloaded equivalent, if possible. */
189     if(cManager.uplink
190        && enabled
191        && !irccasecmp(uplink->host, cManager.uplink->host)
192        && uplink->port == cManager.uplink->port)
193     {
194         uplink->state = cManager.uplink->state;
195         uplink->tries = cManager.uplink->tries;
196         cManager.uplink = uplink;
197     }
198
199     return 0;
200 }
201
202 void
203 uplink_compile(void)
204 {
205     const char *cycles;
206     dict_t conf_node;
207     struct uplinkNode *oldUplinks = NULL, *oldUplink = NULL;
208
209     /* Save the old uplinks, we'll remove them later. */
210     oldUplink = cManager.uplink;
211     oldUplinks = cManager.uplinks;
212
213     cycles = conf_get_data("server/max_cycles", RECDB_QSTRING);
214     max_cycles = cycles ? atoi(cycles) : 30;
215     if(!(conf_node = conf_get_data("uplinks", RECDB_OBJECT)))
216     {
217         log_module(MAIN_LOG, LOG_FATAL, "No uplinks configured; giving up.");
218         exit(1);
219     }
220
221     cManager.enabled = 0;
222     dict_foreach(conf_node, uplink_insert, NULL);
223
224     /* Remove the old uplinks, if any. It doesn't matter if oldUplink (below)
225        is a reference to one of these, because it won't get dereferenced. */
226     if(oldUplinks)
227     {
228         struct uplinkNode *uplink, *next;
229
230         oldUplinks->prev->next = NULL;
231
232         for(uplink = oldUplinks; uplink; uplink = next)
233         {
234             next = uplink->next;
235             free(uplink->bind_addr);
236             free(uplink);
237         }
238     }
239
240     /* If the uplink hasn't changed, it's either NULL or pointing at
241        an uplink that was just deleted, select a new one. */
242     if(cManager.uplink == oldUplink)
243     {
244         if(oldUplink)
245         {
246             irc_squit(self, "Uplinks updated; selecting new uplink.", NULL);
247         }
248
249         cManager.uplink = NULL;
250         uplink_select(NULL);
251     }
252 }
253
254 struct uplinkNode *
255 uplink_find(char *name)
256 {
257     struct uplinkNode *uplink;
258
259     if(!cManager.enabled || !cManager.uplinks)
260     {
261         return NULL;
262     }
263
264     for(uplink = cManager.uplinks; uplink; uplink = uplink->next)
265     {
266         if(!strcasecmp(uplink->name, name))
267         {
268             return uplink;
269         }
270     }
271
272     return NULL;
273 }
274
275 void
276 uplink_select(char *name)
277 {
278     struct uplinkNode *start, *uplink, *next;
279     int stop;
280
281     if(!cManager.enabled || !cManager.uplinks)
282     {
283         log_module(MAIN_LOG, LOG_FATAL, "No uplinks enabled; giving up.");
284         exit(1);
285     }
286
287     if(!cManager.uplink)
288     {
289         start = cManager.uplinks;
290     }
291     else
292     {
293         start = cManager.uplink->next;
294         if(!start)
295         {
296             start = cManager.uplinks;
297         }
298     }
299
300     stop = 0;
301     for(uplink = start; uplink; uplink = next)
302     {
303         next = uplink->next ? uplink->next : cManager.uplinks;
304
305         if(stop)
306         {
307             uplink = NULL;
308             break;
309         }
310
311         /* We've wrapped around the list. */
312         if(next == start)
313         {
314             sleep((cManager.cycles >> 1) * 5);
315             cManager.cycles++;
316
317             if(max_cycles && (cManager.cycles >= max_cycles))
318             {
319                 log_module(MAIN_LOG, LOG_FATAL, "Maximum uplink list cycles exceeded; giving up.");
320                 exit(1);
321             }
322
323             /* Give the uplink currently in 'uplink' consideration,
324                and if not selected, break on the next iteration. */
325             stop = 1;
326         }
327
328         /* Skip bad uplinks. */
329         if(uplink->flags & UPLINK_UNAVAILABLE)
330         {
331             continue;
332         }
333
334         if(name && irccasecmp(uplink->name, name))
335         {
336             /* If we were told to connect to a specific uplink, don't stop
337                until we find it.
338             */
339             continue;
340         }
341
342         /* It would be possible to track uplink health through a variety
343            of statistics and only break on the best uplink. For now, break
344            on the first available one.
345         */
346
347         break;
348     }
349
350     if(!uplink)
351     {
352         /* We are shit outta luck if every single uplink has been passed
353            over. Use the current uplink if possible. */
354         if(!cManager.uplink || cManager.uplink->flags & UPLINK_UNAVAILABLE)
355         {
356             log_module(MAIN_LOG, LOG_FATAL, "All available uplinks exhausted; giving up.");
357             exit(1);
358         }
359
360         return;
361     }
362
363     cManager.uplink = uplink;
364 }
365
366 int
367 uplink_connect(void)
368 {
369     struct uplinkNode *uplink = cManager.uplink;
370
371     if(uplink->state != DISCONNECTED)
372     {
373         return 0;
374     }
375
376     if(uplink->flags & UPLINK_UNAVAILABLE)
377     {
378         uplink_select(NULL);
379         uplink = cManager.uplink;
380     }
381
382     if(uplink->tries)
383     {
384         /* This delay could scale with the number of tries. */
385         sleep(2);
386     }
387
388     if(!create_socket_client(uplink))
389     {
390         if(uplink->max_tries && (uplink->tries >= uplink->max_tries))
391         {
392             /* This is a bad uplink, move on. */
393             uplink->flags |= UPLINK_UNAVAILABLE;
394             uplink_select(NULL);
395         }
396
397         return 0;
398     }
399     else
400     {
401         uplink->state = AUTHENTICATING;
402         irc_introduce(uplink->password);
403     }
404
405     return 1;
406 }
407
408 void
409 received_ping(void)
410 {
411     /* This function is called when a ping is received. Take it as
412        a sign of link health and reset the connection manager
413        information. */
414
415     cManager.cycles = 0;
416 }
417
418 void sigaction_writedb(int x)
419 {
420 #ifndef HAVE_STRSIGNAL
421     log_module(MAIN_LOG, LOG_INFO, "Signal %d -- writing databases.", x);
422 #else
423     log_module(MAIN_LOG, LOG_INFO, "%s -- writing databases.", strsignal(x));
424 #endif
425     do_write_dbs = 1;
426 }
427
428 void sigaction_exit(int x)
429 {
430 #ifndef HAVE_STRSIGNAL
431     log_module(MAIN_LOG, LOG_INFO, "Signal %d -- exiting.", x);
432 #else
433     log_module(MAIN_LOG, LOG_INFO, "%s -- exiting.", strsignal(x));
434 #endif
435     irc_squit(self, "Exiting on signal from console.", NULL);
436     quit_services = 1;
437 }
438
439 void sigaction_wait(UNUSED_ARG(int x))
440 {
441     int code;
442     wait4(-1, &code, WNOHANG, NULL);
443 }
444
445 void sigaction_rehash(int x)
446 {
447 #ifndef HAVE_STRSIGNAL
448     log_module(MAIN_LOG, LOG_INFO, "Signal %d -- rehashing.", x);
449 #else
450     log_module(MAIN_LOG, LOG_INFO, "%s -- rehashing.", strsignal(x));
451 #endif
452     do_reopen = 1;
453 }
454
455 static exit_func_t *ef_list;
456 static unsigned int ef_size = 0, ef_used = 0;
457
458 void reg_exit_func(exit_func_t handler)
459 {
460     if (ef_used == ef_size) {
461         if (ef_size) {
462             ef_size <<= 1;
463             ef_list = realloc(ef_list, ef_size*sizeof(exit_func_t));
464         } else {
465             ef_size = 8;
466             ef_list = malloc(ef_size*sizeof(exit_func_t));
467         }
468     }
469     ef_list[ef_used++] = handler;
470 }
471
472 void call_exit_funcs(void)
473 {
474     unsigned int n = ef_used;
475
476     /* Call them in reverse order because we initialize logs, then
477      * nickserv, then chanserv, etc., and they register their exit
478      * funcs in that order, and there are some dependencies (for
479      * example, ChanServ requires NickServ to not have cleaned up).
480      */
481
482     while (n > 0) {
483         ef_list[--n]();
484     }
485     free(ef_list);
486     ef_used = ef_size = 0;
487 }
488
489 int
490 set_policer_param(const char *param, void *data, void *extra)
491 {
492     struct record_data *rd = data;
493     const char *str = GET_RECORD_QSTRING(rd);
494     if (str) {
495         policer_params_set(extra, param, str);
496     }
497     return 0;
498 }
499
500 static void
501 conf_globals(void)
502 {
503     const char *info;
504     dict_t dict;
505
506     info = conf_get_data("services/global/nick", RECDB_QSTRING);
507     if (info && (info[0] == '.'))
508         info = NULL;
509     init_global(info);
510
511     info = conf_get_data("services/nickserv/nick", RECDB_QSTRING);
512     if (info && (info[0] == '.'))
513         info = NULL;
514     init_nickserv(info);
515
516     info = conf_get_data("services/chanserv/nick", RECDB_QSTRING);
517     if (info && (info[0] == '.'))
518         info = NULL;
519     init_chanserv(info);
520
521     god_policer_params = policer_params_new();
522     if ((dict = conf_get_data("policers/commands-god", RECDB_OBJECT))) {
523         dict_foreach(dict, set_policer_param, god_policer_params);
524     } else {
525         policer_params_set(god_policer_params, "size", "30");
526         policer_params_set(god_policer_params, "drain-rate", "1");
527     }
528     oper_policer_params = policer_params_new();
529     if ((dict = conf_get_data("policers/commands-oper", RECDB_OBJECT))) {
530         dict_foreach(dict, set_policer_param, oper_policer_params);
531     } else {
532         policer_params_set(oper_policer_params, "size", "10");
533         policer_params_set(oper_policer_params, "drain-rate", "1");
534     }
535     luser_policer_params = policer_params_new();
536     if ((dict = conf_get_data("policers/commands-luser", RECDB_OBJECT))) {
537         dict_foreach(dict, set_policer_param, luser_policer_params);
538     } else {
539         policer_params_set(luser_policer_params, "size", "5");
540         policer_params_set(luser_policer_params, "drain-rate", "0.50");
541     }
542
543     info = conf_get_data("services/opserv/nick", RECDB_QSTRING);
544     if (info && (info[0] == '.'))
545         info = NULL;
546     init_opserv(info);
547 }
548
549 #ifdef HAVE_SYS_RESOURCE_H
550
551 static int
552 set_item_rlimit(const char *name, void *data, void *extra)
553 {
554     int rsrc, found;
555     struct record_data *rd = data;
556     struct rlimit rlim;
557     const char *str;
558
559     rsrc = (int)dict_find(extra, name, &found);
560     if (!found) {
561         log_module(MAIN_LOG, LOG_ERROR, "Invalid rlimit \"%s\" in rlimits section.", name);
562         return 0;
563     }
564     if (!(str = GET_RECORD_QSTRING(rd))) {
565         log_module(MAIN_LOG, LOG_ERROR, "Missing or invalid parameter type for rlimit \"%s\".", name);
566         return 0;
567     }
568     if (getrlimit(rsrc, &rlim) < 0) {
569         log_module(MAIN_LOG, LOG_ERROR, "Couldn't get rlimit \"%s\": errno %d: %s", name, errno, strerror(errno));
570         return 0;
571     }
572     rlim.rlim_cur = ParseVolume(str);
573     if (setrlimit(rsrc, &rlim) < 0) {
574         log_module(MAIN_LOG, LOG_ERROR, "Couldn't set rlimit \"%s\": errno %d: %s", name, errno, strerror(errno));
575     }
576     return 0;
577 }
578
579 static void
580 conf_rlimits(void)
581 {
582     dict_t dict, values;
583
584     values = dict_new();
585     dict_insert(values, "data", (void*)RLIMIT_DATA);
586     dict_insert(values, "stack", (void*)RLIMIT_STACK);
587 #ifdef RLIMIT_VMEM
588     dict_insert(values, "vmem", (void*)RLIMIT_VMEM);
589 #else
590 #ifdef RLIMIT_AS
591     dict_insert(values, "vmem", (void*)RLIMIT_AS);
592 #endif
593 #endif
594     if ((dict = conf_get_data("rlimits", RECDB_OBJECT))) {
595         dict_foreach(dict, set_item_rlimit, values);
596     }
597     dict_delete(values);
598 }
599
600 #else
601
602 static void
603 conf_rlimits(void)
604 {
605 }
606
607 #endif
608
609 void main_shutdown(void)
610 {
611     struct uplinkNode *ul, *ul_next;
612     ioset_cleanup();
613     for (ul = cManager.uplinks; ul; ul = ul_next) {
614         ul_next = ul->next;
615         free(ul->bind_addr);
616         free(ul);
617     }
618     tools_cleanup();
619     conf_close();
620     remove(PID_FILE);
621     policer_params_delete(god_policer_params);
622     policer_params_delete(oper_policer_params);
623     policer_params_delete(luser_policer_params);
624     if (replay_file)
625         fclose(replay_file);
626 }
627
628 void usage(char *self) {
629     /* We can assume we have getopt_long(). */
630     printf("Usage: %s [-c config] [-r log] [-d] [-f] [-v|-h]\n"
631            "-c, --config                    selects a different configuration file.\n"
632            "-d, --debug                     enables debug mode.\n"
633            "-f, --foreground                run srvx in the foreground.\n"
634            "-h, --help                      prints this usage message.\n"
635            "-k, --check                     checks the configuration file's syntax.\n"
636            "-r, --replay                    replay a log file (for debugging)\n"
637            "-v, --version                   prints this program's version.\n"
638            , self);
639 }
640
641 void version() {
642     printf("    --------------------------------------------------\n"
643            "    - "PACKAGE_STRING" ("CODENAME"), Built: " __DATE__ ", " __TIME__".\n"
644            "    - Copyright (C) 2000 - 2003, srvx Development Team\n"
645            "    --------------------------------------------------\n");
646 }
647
648 void license() {
649     printf("\n"
650            "This program is free software; you can redistribute it and/or modify\n"
651            "it under the terms of the GNU General Public License as published by\n"
652            "the Free Software Foundation; either version 2 of the License, or\n"
653            "(at your option) any later version.\n"
654            "\n"
655            "This program is distributed in the hope that it will be useful,\n"
656            "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
657            "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
658            "GNU General Public License for more details.\n"
659            "\n"
660            "You should have received a copy of the GNU General Public License\n"
661            "along with this program; if not, write to the Free Software\n"
662            "Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n");
663 }
664
665 #if WITH_MALLOC_BOEHM_GC
666 void
667 gc_warn_proc(char *msg, GC_word arg)
668 {
669     log_module(MAIN_LOG, LOG_ERROR, "GC(%p): %s", (void*)arg, msg);
670 }
671 #endif
672
673 int main(int argc, char *argv[])
674 {
675     int daemon, debug;
676     pid_t pid = 0;
677     FILE *file_out;
678     struct sigaction sv;
679
680     daemon = 1;
681     debug = 0;
682     tools_init();
683
684     /* set up some signal handlers */
685     memset(&sv, 0, sizeof(sv));
686     sigemptyset(&sv.sa_mask);
687     sv.sa_handler = SIG_IGN;
688     sigaction(SIGPIPE, &sv, NULL);
689     sv.sa_handler = sigaction_rehash;
690     sigaction(SIGHUP, &sv, NULL);
691     sv.sa_handler = sigaction_writedb;
692     sigaction(SIGINT, &sv, NULL);
693     sv.sa_handler = sigaction_exit;
694     sigaction(SIGQUIT, &sv, NULL);
695     sv.sa_handler = sigaction_wait;
696     sigaction(SIGCHLD, &sv, NULL);
697
698     if (argc > 1) { /* parse command line, if any */
699         int c;
700         struct option options[] =
701         {
702             {"config", 1, 0, 'c'},
703             {"debug", 0, 0, 'd'},
704             {"foreground", 0, 0, 'f'},
705             {"help", 0, 0, 'h'},
706             {"check", 0, 0, 'k'},
707             {"replay", 1, 0, 'r'},
708             {"version", 0, 0, 'v'},
709             {"verbose", 0, 0, 'V'},
710             {0, 0, 0, 0}
711         };
712
713         while ((c = getopt_long(argc, argv, "c:kr:dfvVh", options, NULL)) != -1) {
714             switch(c) {
715             case 'c':
716                 services_config = optarg;
717                 break;
718             case 'k':
719                 if (conf_read(services_config)) {
720                     printf("%s appears to be a valid configuration file.\n", services_config);
721                 } else {
722                     printf("%s is an invalid configuration file.\n", services_config);
723                 }
724                 exit(0);
725             case 'r':
726                 replay_file = fopen(optarg, "r");
727                 if (!replay_file) {
728                     fprintf(stderr, "Could not open %s for reading: %s (%d)\n",
729                             optarg, strerror(errno), errno);
730                     exit(0);
731                 }
732                 break;
733             case 'd':
734                 debug = 1;
735                 break;
736             case 'f':
737                 daemon = 0;
738                 break;
739             case 'v':
740                 version();
741                 license();
742                 exit(0);
743             case 'h':
744             default:
745                 usage(argv[0]);
746                 exit(0);
747             }
748         }
749     }
750
751     version();
752
753 #ifdef __CYGWIN__
754     if(daemon)
755     {
756         fprintf(stderr, "Daemon mode not supported under Cygwin.\n");
757         daemon = 0;
758     }
759 #endif
760
761     if (replay_file) {
762         /* We read a line here to "prime" the replay file parser, but
763          * mostly to get the right value of "now" for when we do the
764          * irc_introduce. */
765         replay_read_line();
766         boot_time = now;
767     } else {
768         boot_time = time(&now);
769     }
770
771     log_module(MAIN_LOG, LOG_INFO, "Initializing daemon...");
772     if (!conf_read(services_config)) {
773         log_module(MAIN_LOG, LOG_FATAL, "Unable to read %s.", services_config);
774         exit(0);
775     }
776
777     conf_register_reload(uplink_compile);
778
779     if (daemon) {
780         /* Attempt to fork into the background if daemon mode is on. */
781         pid = fork();
782         if (pid < 0) {
783             log_module(MAIN_LOG, LOG_FATAL, "Unable to fork: %s", strerror(errno));
784         } else if (pid > 0) {
785             log_module(MAIN_LOG, LOG_INFO, "Forking into the background (pid: %i)...", pid);
786             exit(0);
787         }
788         setsid();
789         /* Close these since we should not use them from now on. */
790         fclose(stdin);
791         fclose(stdout);
792         fclose(stderr);
793     }
794
795     if ((file_out = fopen(PID_FILE, "w")) == NULL) {
796         /* Create the main process' pid file */
797         log_module(MAIN_LOG, LOG_ERROR, "Unable to create PID file: %s", strerror(errno));
798     } else {
799         fprintf(file_out, "%i\n", (int)getpid());
800         fclose(file_out);
801     }
802
803     services_argc = argc;
804     services_argv = argv;
805
806     atexit(call_exit_funcs);
807     reg_exit_func(main_shutdown);
808
809     log_init();
810     MAIN_LOG = log_register_type("srvx", "file:main.log");
811     if (debug)
812         log_debug();
813 #if WITH_MALLOC_BOEHM_GC
814     GC_set_warn_proc(gc_warn_proc);
815     GC_enable_incremental();
816 #endif
817     timeq_init();
818     init_structs();
819     init_parse();
820     modcmd_init();
821     saxdb_init();
822     gline_init();
823     sendmail_init();
824     helpfile_init();
825     conf_globals(); /* initializes the core services */
826     conf_rlimits();
827     modules_init();
828     message_register_table(msgtab);
829     modcmd_finalize();
830     saxdb_finalize();
831     helpfile_finalize();
832     modules_finalize();
833
834     /* The first exit func to be called *should* be saxdb_write_all(). */
835     reg_exit_func(saxdb_write_all);
836     if (replay_file) {
837         char *msg;
838         log_module(MAIN_LOG, LOG_INFO, "Beginning replay...");
839         srand(now);
840         replay_event_loop();
841         if ((msg = dict_sanity_check(clients))) {
842             log_module(MAIN_LOG, LOG_ERROR, "Clients insanity: %s", msg);
843             free(msg);
844         }
845         if ((msg = dict_sanity_check(channels))) {
846             log_module(MAIN_LOG, LOG_ERROR, "Channels insanity: %s", msg);
847             free(msg);
848         }
849         if ((msg = dict_sanity_check(servers))) {
850             log_module(MAIN_LOG, LOG_ERROR, "Servers insanity: %s", msg);
851             free(msg);
852         }
853     } else {
854         srand(time(&now));
855         ioset_run();
856     }
857     return 0;
858 }