2 * Copyright 2000-2004 srvx Development Team
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.
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.
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.
19 #define PID_FILE "srvx.pid"
39 #ifdef HAVE_SYS_RESOURCE_H
40 #include <sys/resource.h>
42 #ifdef HAVE_NETINET_IN_H
43 #include <netinet/in.h>
45 #ifdef HAVE_SYS_SOCKET_H
46 #include <sys/socket.h>
48 #ifdef HAVE_SYS_WAIT_H
53 #define SIGCHLD SIGCLD
56 extern FILE *replay_file;
58 time_t boot_time, burst_begin, now;
59 unsigned long burst_length;
60 struct log_type *MAIN_LOG;
62 int quit_services, max_cycles;
64 char *services_config = "srvx.conf";
69 struct cManagerNode cManager;
71 struct policer_params *oper_policer_params, *luser_policer_params, *god_policer_params;
73 static const struct message_entry msgtab[] = {
74 { "MSG_NONE", "None" },
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_TARGET_NAME", "You must provide the name of a channel or user." },
98 { "MSG_NOT_CHANNEL_NAME", "You must provide a valid channel name." },
99 { "MSG_INVALID_CHANNEL", "You must provide the name of a channel that exists." },
100 { "MSG_CHANNEL_ABSENT", "You aren't currently in $b%s$b." },
101 { "MSG_CHANNEL_USER_ABSENT", "$b%s$b isn't currently in $b%s$b." },
102 { "MSG_MISSING_PARAMS", "$b%s$b requires more parameters." },
103 { "MSG_DEPRECATED_COMMAND", "The $b%s$b command has been deprecated, and will be removed in the future; please use $b%s$b instead." },
104 { "MSG_OPER_SUSPENDED", "Your $b$O$b access has been suspended." },
105 { "MSG_USER_OUTRANKED", "$b%s$b outranks you (command has no effect)." },
106 { "MSG_STUPID_ACCESS_CHANGE", "Please ask someone $belse$b to demote you." },
107 { "MSG_NO_SEARCH_ACCESS", "You do not have enough access to search based on $b%s$b." },
108 { "MSG_INVALID_CRITERIA", "$b%s$b is an invalid search criteria." },
109 { "MSG_MATCH_COUNT", "Found $b%u$b matches." },
110 { "MSG_NO_MATCHES", "Nothing matched the criteria of your search." },
111 { "MSG_TOPIC_UNKNOWN", "No help on that topic." },
112 { "MSG_INVALID_BINARY", "$b%s$b is an invalid binary value." },
113 { "MSG_INTERNAL_FAILURE", "Your command could not be processed due to an internal failure." },
114 { "MSG_DB_UNKNOWN", "I do not know of a database named %s." },
115 { "MSG_DB_IS_MONDO", "Database %s is in the \"mondo\" database and cannot be written separately." },
116 { "MSG_DB_WRITE_ERROR", "Error while writing database %s." },
117 { "MSG_DB_WROTE_DB", "Wrote database %s (in "FMT_TIME_T".%06lu seconds)." },
118 { "MSG_DB_WROTE_ALL", "Wrote all databases (in "FMT_TIME_T".%06lu seconds)." },
122 void uplink_select(char *name);
125 uplink_insert(const char *key, void *data, UNUSED_ARG(void *extra))
127 struct uplinkNode *uplink = malloc(sizeof(struct uplinkNode));
128 struct record_data *rd = data;
131 struct sockaddr_in *sin;
139 uplink->name = (char *)key;
140 uplink->host = database_get_data(rd->d.object, "address", RECDB_QSTRING);
142 str = database_get_data(rd->d.object, "port", RECDB_QSTRING);
143 uplink->port = str ? atoi(str) : 6667;
144 uplink->password = database_get_data(rd->d.object, "password", RECDB_QSTRING);
145 uplink->their_password = database_get_data(rd->d.object, "uplink_password", RECDB_QSTRING);
147 str = database_get_data(rd->d.object, "enabled", RECDB_QSTRING);
150 enabled = atoi(str) ? 1 : 0;
153 cManager.enabled += enabled;
155 str = database_get_data(rd->d.object, "max_tries", RECDB_QSTRING);
156 uplink->max_tries = str ? atoi(str) : 3;
157 uplink->flags = enabled ? 0 : UPLINK_UNAVAILABLE;
158 uplink->state = DISCONNECTED;
161 str = database_get_data(rd->d.object, "bind_address", RECDB_QSTRING);
162 uplink->bind_addr_len = sizeof(*sin);
163 if (str && getipbyname(str, &addr))
165 sin = calloc(1, uplink->bind_addr_len);
166 sin->sin_family = AF_INET;
167 sin->sin_addr.s_addr = addr;
168 uplink->bind_addr = sin;
172 uplink->bind_addr = NULL;
173 uplink->bind_addr_len = 0;
176 uplink->next = cManager.uplinks;
181 cManager.uplinks->prev = uplink;
184 cManager.uplinks = uplink;
186 /* If the configuration is being reloaded, set the current uplink
187 to the reloaded equivalent, if possible. */
190 && !irccasecmp(uplink->host, cManager.uplink->host)
191 && uplink->port == cManager.uplink->port)
193 uplink->state = cManager.uplink->state;
194 uplink->tries = cManager.uplink->tries;
195 cManager.uplink = uplink;
206 struct uplinkNode *oldUplinks = NULL, *oldUplink = NULL;
208 /* Save the old uplinks, we'll remove them later. */
209 oldUplink = cManager.uplink;
210 oldUplinks = cManager.uplinks;
212 cycles = conf_get_data("server/max_cycles", RECDB_QSTRING);
213 max_cycles = cycles ? atoi(cycles) : 30;
214 if(!(conf_node = conf_get_data("uplinks", RECDB_OBJECT)))
216 log_module(MAIN_LOG, LOG_FATAL, "No uplinks configured; giving up.");
220 cManager.enabled = 0;
221 dict_foreach(conf_node, uplink_insert, NULL);
223 /* Remove the old uplinks, if any. It doesn't matter if oldUplink (below)
224 is a reference to one of these, because it won't get dereferenced. */
227 struct uplinkNode *uplink, *next;
229 oldUplinks->prev->next = NULL;
231 for(uplink = oldUplinks; uplink; uplink = next)
234 free(uplink->bind_addr);
239 /* If the uplink hasn't changed, it's either NULL or pointing at
240 an uplink that was just deleted, select a new one. */
241 if(cManager.uplink == oldUplink)
245 irc_squit(self, "Uplinks updated; selecting new uplink.", NULL);
248 cManager.uplink = NULL;
254 uplink_find(char *name)
256 struct uplinkNode *uplink;
258 if(!cManager.enabled || !cManager.uplinks)
263 for(uplink = cManager.uplinks; uplink; uplink = uplink->next)
265 if(!strcasecmp(uplink->name, name))
275 uplink_select(char *name)
277 struct uplinkNode *start, *uplink, *next;
280 if(!cManager.enabled || !cManager.uplinks)
282 log_module(MAIN_LOG, LOG_FATAL, "No uplinks enabled; giving up.");
288 start = cManager.uplinks;
292 start = cManager.uplink->next;
295 start = cManager.uplinks;
300 for(uplink = start; uplink; uplink = next)
302 next = uplink->next ? uplink->next : cManager.uplinks;
310 /* We've wrapped around the list. */
313 sleep((cManager.cycles >> 1) * 5);
316 if(max_cycles && (cManager.cycles >= max_cycles))
318 log_module(MAIN_LOG, LOG_FATAL, "Maximum uplink list cycles exceeded; giving up.");
322 /* Give the uplink currently in 'uplink' consideration,
323 and if not selected, break on the next iteration. */
327 /* Skip bad uplinks. */
328 if(uplink->flags & UPLINK_UNAVAILABLE)
333 if(name && irccasecmp(uplink->name, name))
335 /* If we were told to connect to a specific uplink, don't stop
341 /* It would be possible to track uplink health through a variety
342 of statistics and only break on the best uplink. For now, break
343 on the first available one.
351 /* We are shit outta luck if every single uplink has been passed
352 over. Use the current uplink if possible. */
353 if(!cManager.uplink || cManager.uplink->flags & UPLINK_UNAVAILABLE)
355 log_module(MAIN_LOG, LOG_FATAL, "All available uplinks exhausted; giving up.");
362 cManager.uplink = uplink;
368 struct uplinkNode *uplink = cManager.uplink;
370 if(uplink->state != DISCONNECTED)
375 if(uplink->flags & UPLINK_UNAVAILABLE)
378 uplink = cManager.uplink;
383 /* This delay could scale with the number of tries. */
387 if(!create_socket_client(uplink))
389 if(uplink->max_tries && (uplink->tries >= uplink->max_tries))
391 /* This is a bad uplink, move on. */
392 uplink->flags |= UPLINK_UNAVAILABLE;
400 uplink->state = AUTHENTICATING;
401 irc_introduce(uplink->password);
410 /* This function is called when a ping is received. Take it as
411 a sign of link health and reset the connection manager
417 void sigaction_writedb(int x)
419 #ifndef HAVE_STRSIGNAL
420 log_module(MAIN_LOG, LOG_INFO, "Signal %d -- writing databases.", x);
422 log_module(MAIN_LOG, LOG_INFO, "%s -- writing databases.", strsignal(x));
427 void sigaction_exit(int x)
429 #ifndef HAVE_STRSIGNAL
430 log_module(MAIN_LOG, LOG_INFO, "Signal %d -- exiting.", x);
432 log_module(MAIN_LOG, LOG_INFO, "%s -- exiting.", strsignal(x));
434 irc_squit(self, "Exiting on signal from console.", NULL);
438 void sigaction_wait(UNUSED_ARG(int x))
441 wait4(-1, &code, WNOHANG, NULL);
444 void sigaction_rehash(int x)
446 #ifndef HAVE_STRSIGNAL
447 log_module(MAIN_LOG, LOG_INFO, "Signal %d -- rehashing.", x);
449 log_module(MAIN_LOG, LOG_INFO, "%s -- rehashing.", strsignal(x));
454 static exit_func_t *ef_list;
455 static unsigned int ef_size = 0, ef_used = 0;
457 void reg_exit_func(exit_func_t handler)
459 if (ef_used == ef_size) {
462 ef_list = realloc(ef_list, ef_size*sizeof(exit_func_t));
465 ef_list = malloc(ef_size*sizeof(exit_func_t));
468 ef_list[ef_used++] = handler;
471 void call_exit_funcs(void)
473 unsigned int n = ef_used;
475 /* Call them in reverse order because we initialize logs, then
476 * nickserv, then chanserv, etc., and they register their exit
477 * funcs in that order, and there are some dependencies (for
478 * example, ChanServ requires NickServ to not have cleaned up).
485 ef_used = ef_size = 0;
489 set_policer_param(const char *param, void *data, void *extra)
491 struct record_data *rd = data;
492 const char *str = GET_RECORD_QSTRING(rd);
494 policer_params_set(extra, param, str);
505 info = conf_get_data("services/global/nick", RECDB_QSTRING);
506 if (info && (info[0] == '.'))
510 info = conf_get_data("services/nickserv/nick", RECDB_QSTRING);
511 if (info && (info[0] == '.'))
515 info = conf_get_data("services/chanserv/nick", RECDB_QSTRING);
516 if (info && (info[0] == '.'))
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);
524 policer_params_set(god_policer_params, "size", "30");
525 policer_params_set(god_policer_params, "drain-rate", "1");
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);
531 policer_params_set(oper_policer_params, "size", "10");
532 policer_params_set(oper_policer_params, "drain-rate", "1");
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);
538 policer_params_set(luser_policer_params, "size", "5");
539 policer_params_set(luser_policer_params, "drain-rate", "0.50");
542 info = conf_get_data("services/opserv/nick", RECDB_QSTRING);
543 if (info && (info[0] == '.'))
548 #ifdef HAVE_SYS_RESOURCE_H
551 set_item_rlimit(const char *name, void *data, void *extra)
554 struct record_data *rd = data;
558 rsrc = (int)dict_find(extra, name, &found);
560 log_module(MAIN_LOG, LOG_ERROR, "Invalid rlimit \"%s\" in rlimits section.", name);
563 if (!(str = GET_RECORD_QSTRING(rd))) {
564 log_module(MAIN_LOG, LOG_ERROR, "Missing or invalid parameter type for rlimit \"%s\".", name);
567 if (getrlimit(rsrc, &rlim) < 0) {
568 log_module(MAIN_LOG, LOG_ERROR, "Couldn't get rlimit \"%s\": errno %d: %s", name, errno, strerror(errno));
571 rlim.rlim_cur = ParseVolume(str);
572 if (setrlimit(rsrc, &rlim) < 0) {
573 log_module(MAIN_LOG, LOG_ERROR, "Couldn't set rlimit \"%s\": errno %d: %s", name, errno, strerror(errno));
584 dict_insert(values, "data", (void*)RLIMIT_DATA);
585 dict_insert(values, "stack", (void*)RLIMIT_STACK);
587 dict_insert(values, "vmem", (void*)RLIMIT_VMEM);
590 dict_insert(values, "vmem", (void*)RLIMIT_AS);
593 if ((dict = conf_get_data("rlimits", RECDB_OBJECT))) {
594 dict_foreach(dict, set_item_rlimit, values);
608 void main_shutdown(void)
610 struct uplinkNode *ul, *ul_next;
612 for (ul = cManager.uplinks; ul; ul = ul_next) {
620 policer_params_delete(god_policer_params);
621 policer_params_delete(oper_policer_params);
622 policer_params_delete(luser_policer_params);
627 void usage(char *self) {
628 /* We can assume we have getopt_long(). */
629 printf("Usage: %s [-c config] [-r log] [-d] [-f] [-v|-h]\n"
630 "-c, --config selects a different configuration file.\n"
631 "-d, --debug enables debug mode.\n"
632 "-f, --foreground run srvx in the foreground.\n"
633 "-h, --help prints this usage message.\n"
634 "-k, --check checks the configuration file's syntax.\n"
635 "-r, --replay replay a log file (for debugging)\n"
636 "-v, --version prints this program's version.\n"
641 printf(" --------------------------------------------------\n"
642 " - "PACKAGE_STRING" ("CODENAME"), Built: " __DATE__ ", " __TIME__".\n"
643 " - Copyright (C) 2000 - 2003, srvx Development Team\n"
644 " --------------------------------------------------\n");
649 "This program is free software; you can redistribute it and/or modify\n"
650 "it under the terms of the GNU General Public License as published by\n"
651 "the Free Software Foundation; either version 2 of the License, or\n"
652 "(at your option) any later version.\n"
654 "This program is distributed in the hope that it will be useful,\n"
655 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
656 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
657 "GNU General Public License for more details.\n"
659 "You should have received a copy of the GNU General Public License\n"
660 "along with this program; if not, write to the Free Software\n"
661 "Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n");
664 #if WITH_MALLOC_BOEHM_GC
666 gc_warn_proc(char *msg, GC_word arg)
668 log_module(MAIN_LOG, LOG_ERROR, "GC(%p): %s", (void*)arg, msg);
672 int main(int argc, char *argv[])
683 /* set up some signal handlers */
684 memset(&sv, 0, sizeof(sv));
685 sigemptyset(&sv.sa_mask);
686 sv.sa_handler = SIG_IGN;
687 sigaction(SIGPIPE, &sv, NULL);
688 sv.sa_handler = sigaction_rehash;
689 sigaction(SIGHUP, &sv, NULL);
690 sv.sa_handler = sigaction_writedb;
691 sigaction(SIGINT, &sv, NULL);
692 sv.sa_handler = sigaction_exit;
693 sigaction(SIGQUIT, &sv, NULL);
694 sv.sa_handler = sigaction_wait;
695 sigaction(SIGCHLD, &sv, NULL);
697 if (argc > 1) { /* parse command line, if any */
699 struct option options[] =
701 {"config", 1, 0, 'c'},
702 {"debug", 0, 0, 'd'},
703 {"foreground", 0, 0, 'f'},
705 {"check", 0, 0, 'k'},
706 {"replay", 1, 0, 'r'},
707 {"version", 0, 0, 'v'},
708 {"verbose", 0, 0, 'V'},
712 while ((c = getopt_long(argc, argv, "c:kr:dfvVh", options, NULL)) != -1) {
715 services_config = optarg;
718 if (conf_read(services_config)) {
719 printf("%s appears to be a valid configuration file.\n", services_config);
721 printf("%s is an invalid configuration file.\n", services_config);
725 replay_file = fopen(optarg, "r");
727 fprintf(stderr, "Could not open %s for reading: %s (%d)\n",
728 optarg, strerror(errno), errno);
755 fprintf(stderr, "Daemon mode not supported under Cygwin.\n");
761 /* We read a line here to "prime" the replay file parser, but
762 * mostly to get the right value of "now" for when we do the
767 boot_time = time(&now);
770 log_module(MAIN_LOG, LOG_INFO, "Initializing daemon...");
771 if (!conf_read(services_config)) {
772 log_module(MAIN_LOG, LOG_FATAL, "Unable to read %s.", services_config);
776 conf_register_reload(uplink_compile);
779 /* Attempt to fork into the background if daemon mode is on. */
782 log_module(MAIN_LOG, LOG_FATAL, "Unable to fork: %s", strerror(errno));
783 } else if (pid > 0) {
784 log_module(MAIN_LOG, LOG_INFO, "Forking into the background (pid: %i)...", pid);
788 /* Close these since we should not use them from now on. */
794 if ((file_out = fopen(PID_FILE, "w")) == NULL) {
795 /* Create the main process' pid file */
796 log_module(MAIN_LOG, LOG_ERROR, "Unable to create PID file: %s", strerror(errno));
798 fprintf(file_out, "%i\n", (int)getpid());
802 services_argc = argc;
803 services_argv = argv;
805 atexit(call_exit_funcs);
806 reg_exit_func(main_shutdown);
809 MAIN_LOG = log_register_type("srvx", "file:main.log");
812 #if WITH_MALLOC_BOEHM_GC
813 GC_set_warn_proc(gc_warn_proc);
814 GC_enable_incremental();
823 conf_globals(); /* initializes the core services */
826 message_register_table(msgtab);
832 /* The first exit func to be called *should* be saxdb_write_all(). */
833 reg_exit_func(saxdb_write_all);
836 log_module(MAIN_LOG, LOG_INFO, "Beginning replay...");
839 if ((msg = dict_sanity_check(clients))) {
840 log_module(MAIN_LOG, LOG_ERROR, "Clients insanity: %s", msg);
843 if ((msg = dict_sanity_check(channels))) {
844 log_module(MAIN_LOG, LOG_ERROR, "Channels insanity: %s", msg);
847 if ((msg = dict_sanity_check(servers))) {
848 log_module(MAIN_LOG, LOG_ERROR, "Servers insanity: %s", msg);