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