38b95be5105c8eff505b1bc66381014287c988bf
[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         info = NULL;
511     init_global(info);
512
513     info = conf_get_data("services/nickserv/nick", RECDB_QSTRING);
514     if (info && (info[0] == '.'))
515         info = NULL;
516     init_nickserv(info);
517
518     info = conf_get_data("services/chanserv/nick", RECDB_QSTRING);
519     if (info && (info[0] == '.'))
520         info = NULL;
521     init_chanserv(info);
522
523     god_policer_params = policer_params_new();
524     if ((dict = conf_get_data("policers/commands-god", RECDB_OBJECT))) {
525         dict_foreach(dict, set_policer_param, god_policer_params);
526     } else {
527         policer_params_set(god_policer_params, "size", "30");
528         policer_params_set(god_policer_params, "drain-rate", "1");
529     }
530     oper_policer_params = policer_params_new();
531     if ((dict = conf_get_data("policers/commands-oper", RECDB_OBJECT))) {
532         dict_foreach(dict, set_policer_param, oper_policer_params);
533     } else {
534         policer_params_set(oper_policer_params, "size", "10");
535         policer_params_set(oper_policer_params, "drain-rate", "1");
536     }
537     luser_policer_params = policer_params_new();
538     if ((dict = conf_get_data("policers/commands-luser", RECDB_OBJECT))) {
539         dict_foreach(dict, set_policer_param, luser_policer_params);
540     } else {
541         policer_params_set(luser_policer_params, "size", "5");
542         policer_params_set(luser_policer_params, "drain-rate", "0.50");
543     }
544
545     info = conf_get_data("services/opserv/nick", RECDB_QSTRING);
546     if (info && (info[0] == '.'))
547         info = NULL;
548     init_opserv(info);
549 }
550
551 #ifdef HAVE_SYS_RESOURCE_H
552
553 static int
554 set_item_rlimit(const char *name, void *data, void *extra)
555 {
556     int rsrc, found;
557     struct record_data *rd = data;
558     struct rlimit rlim;
559     const char *str;
560
561     rsrc = (int)dict_find(extra, name, &found);
562     if (!found) {
563         log_module(MAIN_LOG, LOG_ERROR, "Invalid rlimit \"%s\" in rlimits section.", name);
564         return 0;
565     }
566     if (!(str = GET_RECORD_QSTRING(rd))) {
567         log_module(MAIN_LOG, LOG_ERROR, "Missing or invalid parameter type for rlimit \"%s\".", name);
568         return 0;
569     }
570     if (getrlimit(rsrc, &rlim) < 0) {
571         log_module(MAIN_LOG, LOG_ERROR, "Couldn't get rlimit \"%s\": errno %d: %s", name, errno, strerror(errno));
572         return 0;
573     }
574     rlim.rlim_cur = ParseVolume(str);
575     if (setrlimit(rsrc, &rlim) < 0) {
576         log_module(MAIN_LOG, LOG_ERROR, "Couldn't set rlimit \"%s\": errno %d: %s", name, errno, strerror(errno));
577     }
578     return 0;
579 }
580
581 static void
582 conf_rlimits(void)
583 {
584     dict_t dict, values;
585
586     values = dict_new();
587     dict_insert(values, "data", (void*)RLIMIT_DATA);
588     dict_insert(values, "stack", (void*)RLIMIT_STACK);
589 #ifdef RLIMIT_VMEM
590     dict_insert(values, "vmem", (void*)RLIMIT_VMEM);
591 #else
592 #ifdef RLIMIT_AS
593     dict_insert(values, "vmem", (void*)RLIMIT_AS);
594 #endif
595 #endif
596     if ((dict = conf_get_data("rlimits", RECDB_OBJECT))) {
597         dict_foreach(dict, set_item_rlimit, values);
598     }
599     dict_delete(values);
600 }
601
602 #else
603
604 static void
605 conf_rlimits(void)
606 {
607 }
608
609 #endif
610
611 void main_shutdown(void)
612 {
613     struct uplinkNode *ul, *ul_next;
614     ioset_cleanup();
615     for (ul = cManager.uplinks; ul; ul = ul_next) {
616         ul_next = ul->next;
617         if (ul->bind_addr) free(ul->bind_addr);
618         free(ul);
619     }
620     tools_cleanup();
621     conf_close();
622     remove(PID_FILE);
623     policer_params_delete(god_policer_params);
624     policer_params_delete(oper_policer_params);
625     policer_params_delete(luser_policer_params);
626     if (replay_file)
627         fclose(replay_file);
628 }
629
630 void usage(char *self) {
631     /* We can assume we have getopt_long(). */
632     printf("Usage: %s [-c config] [-r log] [-d] [-f] [-v|-h]\n"
633            "-c, --config                    selects a different configuration file.\n"
634            "-d, --debug                     enables debug mode.\n"
635            "-f, --foreground                run srvx in the foreground.\n"
636            "-h, --help                      prints this usage message.\n"
637            "-k, --check                     checks the configuration file's syntax.\n"
638            "-r, --replay                    replay a log file (for debugging)\n"
639            "-v, --version                   prints this program's version.\n"
640            , self);
641 }
642
643 void version() {
644     printf("    --------------------------------------------------\n"
645            "    - "PACKAGE_STRING" ("CODENAME"), Built: " __DATE__ ", " __TIME__".\n"
646            "    - Copyright (C) 2000 - 2003, srvx Development Team\n"
647            "    --------------------------------------------------\n");
648 }
649
650 void license() {
651     printf("\n"
652            "This program is free software; you can redistribute it and/or modify\n"
653            "it under the terms of the GNU General Public License as published by\n"
654            "the Free Software Foundation; either version 2 of the License, or\n"
655            "(at your option) any later version.\n"
656            "\n"
657            "This program is distributed in the hope that it will be useful,\n"
658            "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
659            "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
660            "GNU General Public License for more details.\n"
661            "\n"
662            "You should have received a copy of the GNU General Public License\n"
663            "along with this program; if not, write to the Free Software\n"
664            "Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n");
665 }
666
667 #if WITH_MALLOC_BOEHM_GC
668 void
669 gc_warn_proc(char *msg, GC_word arg)
670 {
671     log_module(MAIN_LOG, LOG_ERROR, "GC(%p): %s", (void*)arg, msg);
672 }
673 #endif
674
675 int main(int argc, char *argv[])
676 {
677     int daemon, debug;
678     pid_t pid = 0;
679     FILE *file_out;
680     struct sigaction sv;
681
682     daemon = 1;
683     debug = 0;
684     tools_init();
685
686     /* set up some signal handlers */
687     memset(&sv, 0, sizeof(sv));
688     sigemptyset(&sv.sa_mask);
689     sv.sa_handler = SIG_IGN;
690     sigaction(SIGPIPE, &sv, NULL);
691     sv.sa_handler = sigaction_rehash;
692     sigaction(SIGHUP, &sv, NULL);
693     sv.sa_handler = sigaction_writedb;
694     sigaction(SIGINT, &sv, NULL);
695     sv.sa_handler = sigaction_exit;
696     sigaction(SIGQUIT, &sv, NULL);
697     sv.sa_handler = sigaction_wait;
698     sigaction(SIGCHLD, &sv, NULL);
699
700     if (argc > 1) { /* parse command line, if any */
701         int c;
702         struct option options[] =
703         {
704             {"config", 1, 0, 'c'},
705             {"debug", 0, 0, 'd'},
706             {"foreground", 0, 0, 'f'},
707             {"help", 0, 0, 'h'},
708             {"check", 0, 0, 'k'},
709             {"replay", 1, 0, 'r'},
710             {"version", 0, 0, 'v'},
711             {"verbose", 0, 0, 'V'},
712             {0, 0, 0, 0}
713         };
714
715         while ((c = getopt_long(argc, argv, "c:kr:dfvVh", options, NULL)) != -1) {
716             switch(c) {
717             case 'c':
718                 services_config = optarg;
719                 break;
720             case 'k':
721                 if (conf_read(services_config)) {
722                     printf("%s appears to be a valid configuration file.\n", services_config);
723                 } else {
724                     printf("%s is an invalid configuration file.\n", services_config);
725                 }
726                 exit(0);
727             case 'r':
728                 replay_file = fopen(optarg, "r");
729                 if (!replay_file) {
730                     fprintf(stderr, "Could not open %s for reading: %s (%d)\n",
731                             optarg, strerror(errno), errno);
732                     exit(0);
733                 }
734                 break;
735             case 'd':
736                 debug = 1;
737                 break;
738             case 'f':
739                 daemon = 0;
740                 break;
741             case 'v':
742                 version();
743                 license();
744                 exit(0);
745             case 'h':
746             default:
747                 usage(argv[0]);
748                 exit(0);
749             }
750         }
751     }
752
753     version();
754
755 #ifdef __CYGWIN__
756     if(daemon)
757     {
758         fprintf(stderr, "Daemon mode not supported under Cygwin.\n");
759         daemon = 0;
760     }
761 #endif
762
763     if (replay_file) {
764         /* We read a line here to "prime" the replay file parser, but
765          * mostly to get the right value of "now" for when we do the
766          * irc_introduce. */
767         replay_read_line();
768         boot_time = now;
769     } else {
770         boot_time = time(&now);
771     }
772
773     log_module(MAIN_LOG, LOG_INFO, "Initializing daemon...");
774     if (!conf_read(services_config)) {
775         log_module(MAIN_LOG, LOG_FATAL, "Unable to read %s.", services_config);
776         exit(0);
777     }
778
779     conf_register_reload(uplink_compile);
780
781     if (daemon) {
782         /* Attempt to fork into the background if daemon mode is on. */
783         pid = fork();
784         if (pid < 0) {
785             log_module(MAIN_LOG, LOG_FATAL, "Unable to fork: %s", strerror(errno));
786         } else if (pid > 0) {
787             log_module(MAIN_LOG, LOG_INFO, "Forking into the background (pid: %i)...", pid);
788             exit(0);
789         }
790         setsid();
791         /* Close these since we should not use them from now on. */
792         fclose(stdin);
793         fclose(stdout);
794         fclose(stderr);
795     }
796
797     if ((file_out = fopen(PID_FILE, "w")) == NULL) {
798         /* Create the main process' pid file */
799         log_module(MAIN_LOG, LOG_ERROR, "Unable to create PID file: %s", strerror(errno));
800     } else {
801         fprintf(file_out, "%i\n", (int)getpid());
802         fclose(file_out);
803     }
804
805     services_argc = argc;
806     services_argv = argv;
807
808     atexit(call_exit_funcs);
809     reg_exit_func(main_shutdown);
810
811     log_init();
812     MAIN_LOG = log_register_type("srvx", "file:main.log");
813     if (debug)
814         log_debug();
815 #if WITH_MALLOC_BOEHM_GC
816     GC_set_warn_proc(gc_warn_proc);
817     GC_enable_incremental();
818 #endif
819     timeq_init();
820     init_structs();
821     init_parse();
822     modcmd_init();
823     saxdb_init();
824     gline_init();
825     sendmail_init();
826     conf_globals(); /* initializes the core services */
827     conf_rlimits();
828     modules_init();
829     message_register_table(msgtab);
830     modcmd_finalize();
831     helpfile_finalize();
832     saxdb_finalize();
833     modules_finalize();
834
835     /* The first exit func to be called *should* be saxdb_write_all(). */
836     reg_exit_func(saxdb_write_all);
837     if (replay_file) {
838         char *msg;
839         log_module(MAIN_LOG, LOG_INFO, "Beginning replay...");
840         srand(now);
841         replay_event_loop();
842         if ((msg = dict_sanity_check(clients))) {
843             log_module(MAIN_LOG, LOG_ERROR, "Clients insanity: %s", msg);
844             free(msg);
845         }
846         if ((msg = dict_sanity_check(channels))) {
847             log_module(MAIN_LOG, LOG_ERROR, "Channels insanity: %s", msg);
848             free(msg);
849         }
850         if ((msg = dict_sanity_check(servers))) {
851             log_module(MAIN_LOG, LOG_ERROR, "Servers insanity: %s", msg);
852             free(msg);
853         }
854     } else {
855         srand(time(&now));
856         ioset_run();
857     }
858     return 0;
859 }