2 * Copyright 2000-2004 srvx Development Team
4 * This file is part of srvx.
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.
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.
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.
21 #define PID_FILE "srvx.pid"
41 #ifdef HAVE_SYS_RESOURCE_H
42 #include <sys/resource.h>
44 #ifdef HAVE_NETINET_IN_H
45 #include <netinet/in.h>
47 #ifdef HAVE_SYS_SOCKET_H
48 #include <sys/socket.h>
50 #ifdef HAVE_SYS_WAIT_H
55 #define SIGCHLD SIGCLD
58 extern FILE *replay_file;
60 time_t boot_time, burst_begin, now;
61 unsigned long burst_length;
62 struct log_type *MAIN_LOG;
64 int quit_services, max_cycles;
66 char *services_config = "srvx.conf";
71 struct cManagerNode cManager;
73 struct policer_params *oper_policer_params, *luser_policer_params, *god_policer_params;
75 static const struct message_entry msgtab[] = {
76 { "MSG_NONE", "None" },
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" },
137 void uplink_select(char *name);
140 uplink_insert(const char *key, void *data, UNUSED_ARG(void *extra))
142 struct uplinkNode *uplink = malloc(sizeof(struct uplinkNode));
143 struct record_data *rd = data;
146 struct sockaddr_in *sin;
154 uplink->name = (char *)key;
155 uplink->host = database_get_data(rd->d.object, "address", RECDB_QSTRING);
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);
162 str = database_get_data(rd->d.object, "enabled", RECDB_QSTRING);
165 enabled = atoi(str) ? 1 : 0;
168 cManager.enabled += enabled;
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;
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))
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;
187 uplink->bind_addr = NULL;
188 uplink->bind_addr_len = 0;
191 uplink->next = cManager.uplinks;
196 cManager.uplinks->prev = uplink;
199 cManager.uplinks = uplink;
201 /* If the configuration is being reloaded, set the current uplink
202 to the reloaded equivalent, if possible. */
205 && !irccasecmp(uplink->host, cManager.uplink->host)
206 && uplink->port == cManager.uplink->port)
208 uplink->state = cManager.uplink->state;
209 uplink->tries = cManager.uplink->tries;
210 cManager.uplink = uplink;
221 struct uplinkNode *oldUplinks = NULL, *oldUplink = NULL;
223 /* Save the old uplinks, we'll remove them later. */
224 oldUplink = cManager.uplink;
225 oldUplinks = cManager.uplinks;
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)))
231 log_module(MAIN_LOG, LOG_FATAL, "No uplinks configured; giving up.");
235 cManager.enabled = 0;
236 dict_foreach(conf_node, uplink_insert, NULL);
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. */
242 struct uplinkNode *uplink, *next;
244 oldUplinks->prev->next = NULL;
246 for(uplink = oldUplinks; uplink; uplink = next)
249 free(uplink->bind_addr);
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)
260 irc_squit(self, "Uplinks updated; selecting new uplink.", NULL);
263 cManager.uplink = NULL;
269 uplink_find(char *name)
271 struct uplinkNode *uplink;
273 if(!cManager.enabled || !cManager.uplinks)
278 for(uplink = cManager.uplinks; uplink; uplink = uplink->next)
280 if(!strcasecmp(uplink->name, name))
290 uplink_select(char *name)
292 struct uplinkNode *start, *uplink, *next;
295 if(!cManager.enabled || !cManager.uplinks)
297 log_module(MAIN_LOG, LOG_FATAL, "No uplinks enabled; giving up.");
303 start = cManager.uplinks;
307 start = cManager.uplink->next;
310 start = cManager.uplinks;
315 for(uplink = start; uplink; uplink = next)
317 next = uplink->next ? uplink->next : cManager.uplinks;
325 /* We've wrapped around the list. */
328 sleep((cManager.cycles >> 1) * 5);
331 if(max_cycles && (cManager.cycles >= max_cycles))
333 log_module(MAIN_LOG, LOG_FATAL, "Maximum uplink list cycles exceeded; giving up.");
337 /* Give the uplink currently in 'uplink' consideration,
338 and if not selected, break on the next iteration. */
342 /* Skip bad uplinks. */
343 if(uplink->flags & UPLINK_UNAVAILABLE)
348 if(name && irccasecmp(uplink->name, name))
350 /* If we were told to connect to a specific uplink, don't stop
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.
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)
370 log_module(MAIN_LOG, LOG_FATAL, "All available uplinks exhausted; giving up.");
377 cManager.uplink = uplink;
383 struct uplinkNode *uplink = cManager.uplink;
385 if(uplink->state != DISCONNECTED)
390 if(uplink->flags & UPLINK_UNAVAILABLE)
393 uplink = cManager.uplink;
398 /* This delay could scale with the number of tries. */
402 if(!create_socket_client(uplink))
404 if(uplink->max_tries && (uplink->tries >= uplink->max_tries))
406 /* This is a bad uplink, move on. */
407 uplink->flags |= UPLINK_UNAVAILABLE;
415 uplink->state = AUTHENTICATING;
416 irc_introduce(uplink->password);
425 /* This function is called when a ping is received. Take it as
426 a sign of link health and reset the connection manager
432 void sigaction_writedb(int x)
434 #ifndef HAVE_STRSIGNAL
435 log_module(MAIN_LOG, LOG_INFO, "Signal %d -- writing databases.", x);
437 log_module(MAIN_LOG, LOG_INFO, "%s -- writing databases.", strsignal(x));
442 void sigaction_exit(int x)
444 #ifndef HAVE_STRSIGNAL
445 log_module(MAIN_LOG, LOG_INFO, "Signal %d -- exiting.", x);
447 log_module(MAIN_LOG, LOG_INFO, "%s -- exiting.", strsignal(x));
449 irc_squit(self, "Exiting on signal from console.", NULL);
453 void sigaction_wait(UNUSED_ARG(int x))
456 wait4(-1, &code, WNOHANG, NULL);
459 void sigaction_rehash(int x)
461 #ifndef HAVE_STRSIGNAL
462 log_module(MAIN_LOG, LOG_INFO, "Signal %d -- rehashing.", x);
464 log_module(MAIN_LOG, LOG_INFO, "%s -- rehashing.", strsignal(x));
469 static exit_func_t *ef_list;
470 static unsigned int ef_size = 0, ef_used = 0;
472 void reg_exit_func(exit_func_t handler)
474 if (ef_used == ef_size) {
477 ef_list = realloc(ef_list, ef_size*sizeof(exit_func_t));
480 ef_list = malloc(ef_size*sizeof(exit_func_t));
483 ef_list[ef_used++] = handler;
486 void call_exit_funcs(void)
488 unsigned int n = ef_used;
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).
500 ef_used = ef_size = 0;
504 set_policer_param(const char *param, void *data, void *extra)
506 struct record_data *rd = data;
507 const char *str = GET_RECORD_QSTRING(rd);
509 policer_params_set(extra, param, str);
520 info = conf_get_data("services/global/nick", RECDB_QSTRING);
521 if (info && (info[0] == '.'))
525 info = conf_get_data("services/nickserv/nick", RECDB_QSTRING);
526 if (info && (info[0] == '.'))
530 info = conf_get_data("services/chanserv/nick", RECDB_QSTRING);
531 if (info && (info[0] == '.'))
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);
539 policer_params_set(god_policer_params, "size", "30");
540 policer_params_set(god_policer_params, "drain-rate", "1");
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);
546 policer_params_set(oper_policer_params, "size", "10");
547 policer_params_set(oper_policer_params, "drain-rate", "1");
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);
553 policer_params_set(luser_policer_params, "size", "5");
554 policer_params_set(luser_policer_params, "drain-rate", "0.50");
557 info = conf_get_data("services/opserv/nick", RECDB_QSTRING);
558 if (info && (info[0] == '.'))
563 #ifdef HAVE_SYS_RESOURCE_H
566 set_item_rlimit(const char *name, void *data, void *extra)
570 struct record_data *rd = data;
574 rsrc = (long)dict_find(extra, name, &found);
576 log_module(MAIN_LOG, LOG_ERROR, "Invalid rlimit \"%s\" in rlimits section.", name);
579 if (!(str = GET_RECORD_QSTRING(rd))) {
580 log_module(MAIN_LOG, LOG_ERROR, "Missing or invalid parameter type for rlimit \"%s\".", name);
583 if (getrlimit(rsrc, &rlim) < 0) {
584 log_module(MAIN_LOG, LOG_ERROR, "Couldn't get rlimit \"%s\": errno %d: %s", name, errno, strerror(errno));
587 rlim.rlim_cur = ParseVolume(str);
588 if (setrlimit(rsrc, &rlim) < 0) {
589 log_module(MAIN_LOG, LOG_ERROR, "Couldn't set rlimit \"%s\": errno %d: %s", name, errno, strerror(errno));
600 dict_insert(values, "data", (void*)RLIMIT_DATA);
601 dict_insert(values, "stack", (void*)RLIMIT_STACK);
603 dict_insert(values, "vmem", (void*)RLIMIT_VMEM);
606 dict_insert(values, "vmem", (void*)RLIMIT_AS);
609 if ((dict = conf_get_data("rlimits", RECDB_OBJECT))) {
610 dict_foreach(dict, set_item_rlimit, values);
624 void main_shutdown(void)
626 struct uplinkNode *ul, *ul_next;
628 for (ul = cManager.uplinks; ul; ul = ul_next) {
636 policer_params_delete(god_policer_params);
637 policer_params_delete(oper_policer_params);
638 policer_params_delete(luser_policer_params);
643 void usage(char *self) {
644 /* We can assume we have getopt_long(). */
645 printf("Usage: %s [-c config] [-r log] [-d] [-f] [-v|-h]\n"
646 "-c, --config selects a different configuration file.\n"
647 "-d, --debug enables debug mode.\n"
648 "-f, --foreground run srvx in the foreground.\n"
649 "-h, --help prints this usage message.\n"
650 "-k, --check checks the configuration file's syntax.\n"
651 "-r, --replay replay a log file (for debugging)\n"
652 "-v, --version prints this program's version.\n"
657 printf(" --------------------------------------------------\n"
658 " - "PACKAGE_STRING" ("CODENAME"), Built: " __DATE__ ", " __TIME__".\n"
659 " - Copyright (C) 2000 - 2005, srvx Development Team\n"
660 " --------------------------------------------------\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"
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"
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");
680 #if WITH_MALLOC_BOEHM_GC
682 gc_warn_proc(char *msg, GC_word arg)
684 log_module(MAIN_LOG, LOG_ERROR, "GC(%p): %s", (void*)arg, msg);
688 int main(int argc, char *argv[])
695 #if WITH_MALLOC_BOEHM_GC
697 GC_set_warn_proc(gc_warn_proc);
698 GC_enable_incremental();
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);
719 if (argc > 1) { /* parse command line, if any */
721 struct option options[] =
723 {"config", 1, 0, 'c'},
724 {"debug", 0, 0, 'd'},
725 {"foreground", 0, 0, 'f'},
727 {"check", 0, 0, 'k'},
728 {"replay", 1, 0, 'r'},
729 {"version", 0, 0, 'v'},
730 {"verbose", 0, 0, 'V'},
734 while ((c = getopt_long(argc, argv, "c:kr:dfvVh", options, NULL)) != -1) {
737 services_config = optarg;
740 if (conf_read(services_config)) {
741 printf("%s appears to be a valid configuration file.\n", services_config);
743 printf("%s is an invalid configuration file.\n", services_config);
747 replay_file = fopen(optarg, "r");
749 fprintf(stderr, "Could not open %s for reading: %s (%d)\n",
750 optarg, strerror(errno), errno);
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
781 boot_time = time(&now);
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);
790 conf_register_reload(uplink_compile);
793 /* Attempt to fork into the background if daemon mode is on. */
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);
802 /* Close these since we should not use them from now on. */
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));
812 fprintf(file_out, "%i\n", (int)getpid());
816 services_argc = argc;
817 services_argv = argv;
819 atexit(call_exit_funcs);
820 reg_exit_func(main_shutdown);
823 MAIN_LOG = log_register_type("srvx", "file:main.log");
834 conf_globals(); /* initializes the core services */
837 message_register_table(msgtab);
843 /* The first exit func to be called *should* be saxdb_write_all(). */
844 reg_exit_func(saxdb_write_all);
847 log_module(MAIN_LOG, LOG_INFO, "Beginning replay...");
850 if ((msg = dict_sanity_check(clients))) {
851 log_module(MAIN_LOG, LOG_ERROR, "Clients insanity: %s", msg);
854 if ((msg = dict_sanity_check(channels))) {
855 log_module(MAIN_LOG, LOG_ERROR, "Channels insanity: %s", msg);
858 if ((msg = dict_sanity_check(servers))) {
859 log_module(MAIN_LOG, LOG_ERROR, "Servers insanity: %s", msg);