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