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