Initial import (again)
[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 = malloc(uplink->bind_addr_len);
165         sin->sin_port = 0;
166         sin->sin_family = AF_INET;
167         sin->sin_addr.s_addr = addr;
168 #ifdef HAVE_SIN_LEN
169         sin->sin_len = 0;
170 #endif
171         memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
172         uplink->bind_addr = sin;
173     } 
174     else 
175     {
176         uplink->bind_addr = NULL;
177         uplink->bind_addr_len = 0;
178     }
179
180     uplink->next = cManager.uplinks;
181     uplink->prev = NULL;
182
183     if(cManager.uplinks)
184     {
185         cManager.uplinks->prev = uplink;
186     }
187
188     cManager.uplinks = uplink;
189
190     /* If the configuration is being reloaded, set the current uplink
191        to the reloaded equivalent, if possible. */
192     if(cManager.uplink
193        && enabled
194        && !irccasecmp(uplink->host, cManager.uplink->host)
195        && uplink->port == cManager.uplink->port)
196     {
197         uplink->state = cManager.uplink->state;
198         uplink->tries = cManager.uplink->tries;
199         cManager.uplink = uplink;
200     }
201
202     return 0;
203 }
204
205 void
206 uplink_compile(void)
207 {
208     const char *cycles;
209     dict_t conf_node;
210     struct uplinkNode *oldUplinks = NULL, *oldUplink = NULL;
211
212     /* Save the old uplinks, we'll remove them later. */
213     oldUplink = cManager.uplink;
214     oldUplinks = cManager.uplinks;
215
216     cycles = conf_get_data("server/max_cycles", RECDB_QSTRING);
217     max_cycles = cycles ? atoi(cycles) : 30;
218     if(!(conf_node = conf_get_data("uplinks", RECDB_OBJECT)))
219     {
220         log_module(MAIN_LOG, LOG_FATAL, "No uplinks configured; giving up.");
221         exit(1);
222     }
223
224     cManager.enabled = 0;
225     dict_foreach(conf_node, uplink_insert, NULL);
226
227     /* Remove the old uplinks, if any. It doesn't matter if oldUplink (below)
228        is a reference to one of these, because it won't get dereferenced. */
229     if(oldUplinks)
230     {
231         struct uplinkNode *uplink, *next;
232
233         oldUplinks->prev->next = NULL;
234
235         for(uplink = oldUplinks; uplink; uplink = next)
236         {
237             next = uplink->next;
238             free(uplink);
239         }
240     }
241
242     /* If the uplink hasn't changed, it's either NULL or pointing at
243        an uplink that was just deleted, select a new one. */
244     if(cManager.uplink == oldUplink)
245     {
246         if(oldUplink)
247         {
248             irc_squit(self, "Uplinks updated; selecting new uplink.", NULL);
249         }
250
251         cManager.uplink = NULL;
252         uplink_select(NULL);
253     }
254 }
255
256 struct uplinkNode *
257 uplink_find(char *name)
258 {
259     struct uplinkNode *uplink;
260
261     if(!cManager.enabled || !cManager.uplinks)
262     {
263         return NULL;
264     }
265
266     for(uplink = cManager.uplinks; uplink; uplink = uplink->next)
267     {
268         if(!strcasecmp(uplink->name, name))
269         {
270             return uplink;
271         }
272     }
273
274     return NULL;
275 }
276
277 void
278 uplink_select(char *name)
279 {
280     struct uplinkNode *start, *uplink, *next;
281     int stop;
282
283     if(!cManager.enabled || !cManager.uplinks)
284     {
285         log_module(MAIN_LOG, LOG_FATAL, "No uplinks enabled; giving up.");
286         exit(1);
287     }
288
289     if(!cManager.uplink)
290     {
291         start = cManager.uplinks;
292     }
293     else
294     {
295         start = cManager.uplink->next;
296         if(!start)
297         {
298             start = cManager.uplinks;
299         }
300     }
301
302     stop = 0;
303     for(uplink = start; uplink; uplink = next)
304     {
305         next = uplink->next ? uplink->next : cManager.uplinks;
306
307         if(stop)
308         {
309             uplink = NULL;
310             break;
311         }
312
313         /* We've wrapped around the list. */
314         if(next == start)
315         {
316             sleep((cManager.cycles >> 1) * 5);
317             cManager.cycles++;
318
319             if(max_cycles && (cManager.cycles >= max_cycles))
320             {
321                 log_module(MAIN_LOG, LOG_FATAL, "Maximum uplink list cycles exceeded; giving up.");
322                 exit(1);
323             }
324
325             /* Give the uplink currently in 'uplink' consideration,
326                and if not selected, break on the next iteration. */
327             stop = 1;
328         }
329
330         /* Skip bad uplinks. */
331         if(uplink->flags & UPLINK_UNAVAILABLE)
332         {
333             continue;
334         }
335
336         if(name && irccasecmp(uplink->name, name))
337         {
338             /* If we were told to connect to a specific uplink, don't stop
339                until we find it.
340             */
341             continue;
342         }
343
344         /* It would be possible to track uplink health through a variety
345            of statistics and only break on the best uplink. For now, break
346            on the first available one.
347         */
348
349         break;
350     }
351
352     if(!uplink)
353     {
354         /* We are shit outta luck if every single uplink has been passed
355            over. Use the current uplink if possible. */
356         if(!cManager.uplink || cManager.uplink->flags & UPLINK_UNAVAILABLE)
357         {
358             log_module(MAIN_LOG, LOG_FATAL, "All available uplinks exhausted; giving up.");
359             exit(1);
360         }
361
362         return;
363     }
364
365     cManager.uplink = uplink;
366 }
367
368 int
369 uplink_connect(void)
370 {
371     struct uplinkNode *uplink = cManager.uplink;
372
373     if(uplink->state != DISCONNECTED)
374     {
375         return 0;
376     }
377
378     if(uplink->flags & UPLINK_UNAVAILABLE)
379     {
380         uplink_select(NULL);
381         uplink = cManager.uplink;
382     }
383
384     if(uplink->tries)
385     {
386         /* This delay could scale with the number of tries. */
387         sleep(2);
388     }
389
390     if(!create_socket_client(uplink))
391     {
392         if(uplink->max_tries && (uplink->tries >= uplink->max_tries))
393         {
394             /* This is a bad uplink, move on. */
395             uplink->flags |= UPLINK_UNAVAILABLE;
396             uplink_select(NULL);
397         }
398
399         return 0;
400     }
401     else
402     {
403         uplink->state = AUTHENTICATING;
404         irc_introduce(uplink->password);
405     }
406
407     return 1;
408 }
409
410 void
411 received_ping(void)
412 {
413     /* This function is called when a ping is received. Take it as
414        a sign of link health and reset the connection manager
415        information. */
416
417     cManager.cycles = 0;
418 }
419
420 void sigaction_writedb(int x)
421 {
422 #ifndef HAVE_STRSIGNAL
423     log_module(MAIN_LOG, LOG_INFO, "Signal %d -- writing databases.", x);
424 #else
425     log_module(MAIN_LOG, LOG_INFO, "%s -- writing databases.", strsignal(x));
426 #endif
427     do_write_dbs = 1;
428 }
429
430 void sigaction_exit(int x)
431 {
432 #ifndef HAVE_STRSIGNAL
433     log_module(MAIN_LOG, LOG_INFO, "Signal %d -- exiting.", x);
434 #else
435     log_module(MAIN_LOG, LOG_INFO, "%s -- exiting.", strsignal(x));
436 #endif
437     irc_squit(self, "Exiting on signal from console.", NULL);
438     quit_services = 1;
439 }
440
441 void sigaction_wait(UNUSED_ARG(int x))
442 {
443     int code;
444     wait4(-1, &code, WNOHANG, NULL);
445 }
446
447 void sigaction_rehash(int x)
448 {
449 #ifndef HAVE_STRSIGNAL
450     log_module(MAIN_LOG, LOG_INFO, "Signal %d -- rehashing.", x);
451 #else
452     log_module(MAIN_LOG, LOG_INFO, "%s -- rehashing.", strsignal(x));
453 #endif
454     do_reopen = 1;
455 }
456
457 static exit_func_t *ef_list;
458 static unsigned int ef_size = 0, ef_used = 0;
459
460 void reg_exit_func(exit_func_t handler)
461 {
462     if (ef_used == ef_size) {
463         if (ef_size) {
464             ef_size <<= 1;
465             ef_list = realloc(ef_list, ef_size*sizeof(exit_func_t));
466         } else {
467             ef_size = 8;
468             ef_list = malloc(ef_size*sizeof(exit_func_t));
469         }
470     }
471     ef_list[ef_used++] = handler;
472 }
473
474 void call_exit_funcs(void)
475 {
476     unsigned int n = ef_used;
477
478     /* Call them in reverse order because we initialize logs, then
479      * nickserv, then chanserv, etc., and they register their exit
480      * funcs in that order, and there are some dependencies (for
481      * example, ChanServ requires NickServ to not have cleaned up).
482      */
483
484     while (n > 0) {
485         ef_list[--n]();
486     }
487     free(ef_list);
488     ef_used = ef_size = 0;
489 }
490
491 int
492 set_policer_param(const char *param, void *data, void *extra)
493 {
494     struct record_data *rd = data;
495     const char *str = GET_RECORD_QSTRING(rd);
496     if (str) {
497         policer_params_set(extra, param, str);
498     }
499     return 0;
500 }
501
502 static void
503 conf_globals(void)
504 {
505     const char *info;
506     dict_t dict;
507
508     info = conf_get_data("services/global/nick", RECDB_QSTRING);
509     if (info && (info[0] != '.'))
510         init_global(info);
511
512     info = conf_get_data("services/nickserv/nick", RECDB_QSTRING);
513     if (info && (info[0] != '.'))
514         init_nickserv(info);
515
516     info = conf_get_data("services/chanserv/nick", RECDB_QSTRING);
517     if (info && (info[0] != '.'))
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)
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         if (ul->bind_addr) 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 }