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_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)." },
121 void uplink_select(char *name);
124 uplink_insert(const char *key, void *data, UNUSED_ARG(void *extra))
126 struct uplinkNode *uplink = malloc(sizeof(struct uplinkNode));
127 struct record_data *rd = data;
130 struct sockaddr_in *sin;
138 uplink->name = (char *)key;
139 uplink->host = database_get_data(rd->d.object, "address", RECDB_QSTRING);
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);
146 str = database_get_data(rd->d.object, "enabled", RECDB_QSTRING);
149 enabled = atoi(str) ? 1 : 0;
152 cManager.enabled += enabled;
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;
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))
164 sin = malloc(uplink->bind_addr_len);
166 sin->sin_family = AF_INET;
167 sin->sin_addr.s_addr = addr;
171 memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
172 uplink->bind_addr = sin;
176 uplink->bind_addr = NULL;
177 uplink->bind_addr_len = 0;
180 uplink->next = cManager.uplinks;
185 cManager.uplinks->prev = uplink;
188 cManager.uplinks = uplink;
190 /* If the configuration is being reloaded, set the current uplink
191 to the reloaded equivalent, if possible. */
194 && !irccasecmp(uplink->host, cManager.uplink->host)
195 && uplink->port == cManager.uplink->port)
197 uplink->state = cManager.uplink->state;
198 uplink->tries = cManager.uplink->tries;
199 cManager.uplink = uplink;
210 struct uplinkNode *oldUplinks = NULL, *oldUplink = NULL;
212 /* Save the old uplinks, we'll remove them later. */
213 oldUplink = cManager.uplink;
214 oldUplinks = cManager.uplinks;
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)))
220 log_module(MAIN_LOG, LOG_FATAL, "No uplinks configured; giving up.");
224 cManager.enabled = 0;
225 dict_foreach(conf_node, uplink_insert, NULL);
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. */
231 struct uplinkNode *uplink, *next;
233 oldUplinks->prev->next = NULL;
235 for(uplink = oldUplinks; uplink; uplink = next)
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)
248 irc_squit(self, "Uplinks updated; selecting new uplink.", NULL);
251 cManager.uplink = NULL;
257 uplink_find(char *name)
259 struct uplinkNode *uplink;
261 if(!cManager.enabled || !cManager.uplinks)
266 for(uplink = cManager.uplinks; uplink; uplink = uplink->next)
268 if(!strcasecmp(uplink->name, name))
278 uplink_select(char *name)
280 struct uplinkNode *start, *uplink, *next;
283 if(!cManager.enabled || !cManager.uplinks)
285 log_module(MAIN_LOG, LOG_FATAL, "No uplinks enabled; giving up.");
291 start = cManager.uplinks;
295 start = cManager.uplink->next;
298 start = cManager.uplinks;
303 for(uplink = start; uplink; uplink = next)
305 next = uplink->next ? uplink->next : cManager.uplinks;
313 /* We've wrapped around the list. */
316 sleep((cManager.cycles >> 1) * 5);
319 if(max_cycles && (cManager.cycles >= max_cycles))
321 log_module(MAIN_LOG, LOG_FATAL, "Maximum uplink list cycles exceeded; giving up.");
325 /* Give the uplink currently in 'uplink' consideration,
326 and if not selected, break on the next iteration. */
330 /* Skip bad uplinks. */
331 if(uplink->flags & UPLINK_UNAVAILABLE)
336 if(name && irccasecmp(uplink->name, name))
338 /* If we were told to connect to a specific uplink, don't stop
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.
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)
358 log_module(MAIN_LOG, LOG_FATAL, "All available uplinks exhausted; giving up.");
365 cManager.uplink = uplink;
371 struct uplinkNode *uplink = cManager.uplink;
373 if(uplink->state != DISCONNECTED)
378 if(uplink->flags & UPLINK_UNAVAILABLE)
381 uplink = cManager.uplink;
386 /* This delay could scale with the number of tries. */
390 if(!create_socket_client(uplink))
392 if(uplink->max_tries && (uplink->tries >= uplink->max_tries))
394 /* This is a bad uplink, move on. */
395 uplink->flags |= UPLINK_UNAVAILABLE;
403 uplink->state = AUTHENTICATING;
404 irc_introduce(uplink->password);
413 /* This function is called when a ping is received. Take it as
414 a sign of link health and reset the connection manager
420 void sigaction_writedb(int x)
422 #ifndef HAVE_STRSIGNAL
423 log_module(MAIN_LOG, LOG_INFO, "Signal %d -- writing databases.", x);
425 log_module(MAIN_LOG, LOG_INFO, "%s -- writing databases.", strsignal(x));
430 void sigaction_exit(int x)
432 #ifndef HAVE_STRSIGNAL
433 log_module(MAIN_LOG, LOG_INFO, "Signal %d -- exiting.", x);
435 log_module(MAIN_LOG, LOG_INFO, "%s -- exiting.", strsignal(x));
437 irc_squit(self, "Exiting on signal from console.", NULL);
441 void sigaction_wait(UNUSED_ARG(int x))
444 wait4(-1, &code, WNOHANG, NULL);
447 void sigaction_rehash(int x)
449 #ifndef HAVE_STRSIGNAL
450 log_module(MAIN_LOG, LOG_INFO, "Signal %d -- rehashing.", x);
452 log_module(MAIN_LOG, LOG_INFO, "%s -- rehashing.", strsignal(x));
457 static exit_func_t *ef_list;
458 static unsigned int ef_size = 0, ef_used = 0;
460 void reg_exit_func(exit_func_t handler)
462 if (ef_used == ef_size) {
465 ef_list = realloc(ef_list, ef_size*sizeof(exit_func_t));
468 ef_list = malloc(ef_size*sizeof(exit_func_t));
471 ef_list[ef_used++] = handler;
474 void call_exit_funcs(void)
476 unsigned int n = ef_used;
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).
488 ef_used = ef_size = 0;
492 set_policer_param(const char *param, void *data, void *extra)
494 struct record_data *rd = data;
495 const char *str = GET_RECORD_QSTRING(rd);
497 policer_params_set(extra, param, str);
508 info = conf_get_data("services/global/nick", RECDB_QSTRING);
509 if (info && (info[0] != '.'))
512 info = conf_get_data("services/nickserv/nick", RECDB_QSTRING);
513 if (info && (info[0] != '.'))
516 info = conf_get_data("services/chanserv/nick", RECDB_QSTRING);
517 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);
547 #ifdef HAVE_SYS_RESOURCE_H
550 set_item_rlimit(const char *name, void *data, void *extra)
553 struct record_data *rd = data;
557 rsrc = (int)dict_find(extra, name, &found);
559 log_module(MAIN_LOG, LOG_ERROR, "Invalid rlimit \"%s\" in rlimits section.", name);
562 if (!(str = GET_RECORD_QSTRING(rd))) {
563 log_module(MAIN_LOG, LOG_ERROR, "Missing or invalid parameter type for rlimit \"%s\".", name);
566 if (getrlimit(rsrc, &rlim) < 0) {
567 log_module(MAIN_LOG, LOG_ERROR, "Couldn't get rlimit \"%s\": errno %d: %s", name, errno, strerror(errno));
570 rlim.rlim_cur = ParseVolume(str);
571 if (setrlimit(rsrc, &rlim) < 0) {
572 log_module(MAIN_LOG, LOG_ERROR, "Couldn't set rlimit \"%s\": errno %d: %s", name, errno, strerror(errno));
583 dict_insert(values, "data", (void*)RLIMIT_DATA);
584 dict_insert(values, "stack", (void*)RLIMIT_STACK);
586 dict_insert(values, "vmem", (void*)RLIMIT_VMEM);
589 dict_insert(values, "vmem", (void*)RLIMIT_AS);
592 if ((dict = conf_get_data("rlimits", RECDB_OBJECT))) {
593 dict_foreach(dict, set_item_rlimit, values);
607 void main_shutdown(void)
609 struct uplinkNode *ul, *ul_next;
611 for (ul = cManager.uplinks; ul; ul = ul_next) {
613 if (ul->bind_addr) free(ul->bind_addr);
619 policer_params_delete(god_policer_params);
620 policer_params_delete(oper_policer_params);
621 policer_params_delete(luser_policer_params);
626 void usage(char *self) {
627 /* We can assume we have getopt_long(). */
628 printf("Usage: %s [-c config] [-r log] [-d] [-f] [-v|-h]\n"
629 "-c, --config selects a different configuration file.\n"
630 "-d, --debug enables debug mode.\n"
631 "-f, --foreground run srvx in the foreground.\n"
632 "-h, --help prints this usage message.\n"
633 "-k, --check checks the configuration file's syntax.\n"
634 "-r, --replay replay a log file (for debugging)\n"
635 "-v, --version prints this program's version.\n"
640 printf(" --------------------------------------------------\n"
641 " - "PACKAGE_STRING" ("CODENAME"), Built: " __DATE__ ", " __TIME__".\n"
642 " - Copyright (C) 2000 - 2003, srvx Development Team\n"
643 " --------------------------------------------------\n");
648 "This program is free software; you can redistribute it and/or modify\n"
649 "it under the terms of the GNU General Public License as published by\n"
650 "the Free Software Foundation; either version 2 of the License, or\n"
651 "(at your option) any later version.\n"
653 "This program is distributed in the hope that it will be useful,\n"
654 "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
655 "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
656 "GNU General Public License for more details.\n"
658 "You should have received a copy of the GNU General Public License\n"
659 "along with this program; if not, write to the Free Software\n"
660 "Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n");
663 #if WITH_MALLOC_BOEHM_GC
665 gc_warn_proc(char *msg, GC_word arg)
667 log_module(MAIN_LOG, LOG_ERROR, "GC(%p): %s", (void*)arg, msg);
671 int main(int argc, char *argv[])
682 /* set up some signal handlers */
683 memset(&sv, 0, sizeof(sv));
684 sigemptyset(&sv.sa_mask);
685 sv.sa_handler = SIG_IGN;
686 sigaction(SIGPIPE, &sv, NULL);
687 sv.sa_handler = sigaction_rehash;
688 sigaction(SIGHUP, &sv, NULL);
689 sv.sa_handler = sigaction_writedb;
690 sigaction(SIGINT, &sv, NULL);
691 sv.sa_handler = sigaction_exit;
692 sigaction(SIGQUIT, &sv, NULL);
693 sv.sa_handler = sigaction_wait;
694 sigaction(SIGCHLD, &sv, NULL);
696 if (argc > 1) { /* parse command line, if any */
698 struct option options[] =
700 {"config", 1, 0, 'c'},
701 {"debug", 0, 0, 'd'},
702 {"foreground", 0, 0, 'f'},
704 {"check", 0, 0, 'k'},
705 {"replay", 1, 0, 'r'},
706 {"version", 0, 0, 'v'},
707 {"verbose", 0, 0, 'V'},
711 while ((c = getopt_long(argc, argv, "c:kr:dfvVh", options, NULL)) != -1) {
714 services_config = optarg;
717 if (conf_read(services_config)) {
718 printf("%s appears to be a valid configuration file.\n", services_config);
720 printf("%s is an invalid configuration file.\n", services_config);
724 replay_file = fopen(optarg, "r");
726 fprintf(stderr, "Could not open %s for reading: %s (%d)\n",
727 optarg, strerror(errno), errno);
754 fprintf(stderr, "Daemon mode not supported under Cygwin.\n");
760 /* We read a line here to "prime" the replay file parser, but
761 * mostly to get the right value of "now" for when we do the
766 boot_time = time(&now);
769 log_module(MAIN_LOG, LOG_INFO, "Initializing daemon...");
770 if (!conf_read(services_config)) {
771 log_module(MAIN_LOG, LOG_FATAL, "Unable to read %s.", services_config);
775 conf_register_reload(uplink_compile);
778 /* Attempt to fork into the background if daemon mode is on. */
781 log_module(MAIN_LOG, LOG_FATAL, "Unable to fork: %s", strerror(errno));
782 } else if (pid > 0) {
783 log_module(MAIN_LOG, LOG_INFO, "Forking into the background (pid: %i)...", pid);
787 /* Close these since we should not use them from now on. */
793 if ((file_out = fopen(PID_FILE, "w")) == NULL) {
794 /* Create the main process' pid file */
795 log_module(MAIN_LOG, LOG_ERROR, "Unable to create PID file: %s", strerror(errno));
797 fprintf(file_out, "%i\n", (int)getpid());
801 services_argc = argc;
802 services_argv = argv;
804 atexit(call_exit_funcs);
805 reg_exit_func(main_shutdown);
808 MAIN_LOG = log_register_type("srvx", "file:main.log");
811 #if WITH_MALLOC_BOEHM_GC
812 GC_set_warn_proc(gc_warn_proc);
813 GC_enable_incremental();
822 conf_globals(); /* initializes the core services */
825 message_register_table(msgtab);
831 /* The first exit func to be called *should* be saxdb_write_all(). */
832 reg_exit_func(saxdb_write_all);
835 log_module(MAIN_LOG, LOG_INFO, "Beginning replay...");
838 if ((msg = dict_sanity_check(clients))) {
839 log_module(MAIN_LOG, LOG_ERROR, "Clients insanity: %s", msg);
842 if ((msg = dict_sanity_check(channels))) {
843 log_module(MAIN_LOG, LOG_ERROR, "Channels insanity: %s", msg);
846 if ((msg = dict_sanity_check(servers))) {
847 log_module(MAIN_LOG, LOG_ERROR, "Servers insanity: %s", msg);