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