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_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)." },
124 void uplink_select(char *name);
127 uplink_insert(const char *key, void *data, UNUSED_ARG(void *extra))
129 struct uplinkNode *uplink = malloc(sizeof(struct uplinkNode));
130 struct record_data *rd = data;
133 struct sockaddr_in *sin;
141 uplink->name = (char *)key;
142 uplink->host = database_get_data(rd->d.object, "address", RECDB_QSTRING);
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);
149 str = database_get_data(rd->d.object, "enabled", RECDB_QSTRING);
152 enabled = atoi(str) ? 1 : 0;
155 cManager.enabled += enabled;
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;
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))
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;
174 uplink->bind_addr = NULL;
175 uplink->bind_addr_len = 0;
178 uplink->next = cManager.uplinks;
183 cManager.uplinks->prev = uplink;
186 cManager.uplinks = uplink;
188 /* If the configuration is being reloaded, set the current uplink
189 to the reloaded equivalent, if possible. */
192 && !irccasecmp(uplink->host, cManager.uplink->host)
193 && uplink->port == cManager.uplink->port)
195 uplink->state = cManager.uplink->state;
196 uplink->tries = cManager.uplink->tries;
197 cManager.uplink = uplink;
208 struct uplinkNode *oldUplinks = NULL, *oldUplink = NULL;
210 /* Save the old uplinks, we'll remove them later. */
211 oldUplink = cManager.uplink;
212 oldUplinks = cManager.uplinks;
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)))
218 log_module(MAIN_LOG, LOG_FATAL, "No uplinks configured; giving up.");
222 cManager.enabled = 0;
223 dict_foreach(conf_node, uplink_insert, NULL);
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. */
229 struct uplinkNode *uplink, *next;
231 oldUplinks->prev->next = NULL;
233 for(uplink = oldUplinks; uplink; uplink = next)
236 free(uplink->bind_addr);
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)
247 irc_squit(self, "Uplinks updated; selecting new uplink.", NULL);
250 cManager.uplink = NULL;
256 uplink_find(char *name)
258 struct uplinkNode *uplink;
260 if(!cManager.enabled || !cManager.uplinks)
265 for(uplink = cManager.uplinks; uplink; uplink = uplink->next)
267 if(!strcasecmp(uplink->name, name))
277 uplink_select(char *name)
279 struct uplinkNode *start, *uplink, *next;
282 if(!cManager.enabled || !cManager.uplinks)
284 log_module(MAIN_LOG, LOG_FATAL, "No uplinks enabled; giving up.");
290 start = cManager.uplinks;
294 start = cManager.uplink->next;
297 start = cManager.uplinks;
302 for(uplink = start; uplink; uplink = next)
304 next = uplink->next ? uplink->next : cManager.uplinks;
312 /* We've wrapped around the list. */
315 sleep((cManager.cycles >> 1) * 5);
318 if(max_cycles && (cManager.cycles >= max_cycles))
320 log_module(MAIN_LOG, LOG_FATAL, "Maximum uplink list cycles exceeded; giving up.");
324 /* Give the uplink currently in 'uplink' consideration,
325 and if not selected, break on the next iteration. */
329 /* Skip bad uplinks. */
330 if(uplink->flags & UPLINK_UNAVAILABLE)
335 if(name && irccasecmp(uplink->name, name))
337 /* If we were told to connect to a specific uplink, don't stop
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.
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)
357 log_module(MAIN_LOG, LOG_FATAL, "All available uplinks exhausted; giving up.");
364 cManager.uplink = uplink;
370 struct uplinkNode *uplink = cManager.uplink;
372 if(uplink->state != DISCONNECTED)
377 if(uplink->flags & UPLINK_UNAVAILABLE)
380 uplink = cManager.uplink;
385 /* This delay could scale with the number of tries. */
389 if(!create_socket_client(uplink))
391 if(uplink->max_tries && (uplink->tries >= uplink->max_tries))
393 /* This is a bad uplink, move on. */
394 uplink->flags |= UPLINK_UNAVAILABLE;
402 uplink->state = AUTHENTICATING;
403 irc_introduce(uplink->password);
412 /* This function is called when a ping is received. Take it as
413 a sign of link health and reset the connection manager
419 void sigaction_writedb(int x)
421 #ifndef HAVE_STRSIGNAL
422 log_module(MAIN_LOG, LOG_INFO, "Signal %d -- writing databases.", x);
424 log_module(MAIN_LOG, LOG_INFO, "%s -- writing databases.", strsignal(x));
429 void sigaction_exit(int x)
431 #ifndef HAVE_STRSIGNAL
432 log_module(MAIN_LOG, LOG_INFO, "Signal %d -- exiting.", x);
434 log_module(MAIN_LOG, LOG_INFO, "%s -- exiting.", strsignal(x));
436 irc_squit(self, "Exiting on signal from console.", NULL);
440 void sigaction_wait(UNUSED_ARG(int x))
443 wait4(-1, &code, WNOHANG, NULL);
446 void sigaction_rehash(int x)
448 #ifndef HAVE_STRSIGNAL
449 log_module(MAIN_LOG, LOG_INFO, "Signal %d -- rehashing.", x);
451 log_module(MAIN_LOG, LOG_INFO, "%s -- rehashing.", strsignal(x));
456 static exit_func_t *ef_list;
457 static unsigned int ef_size = 0, ef_used = 0;
459 void reg_exit_func(exit_func_t handler)
461 if (ef_used == ef_size) {
464 ef_list = realloc(ef_list, ef_size*sizeof(exit_func_t));
467 ef_list = malloc(ef_size*sizeof(exit_func_t));
470 ef_list[ef_used++] = handler;
473 void call_exit_funcs(void)
475 unsigned int n = ef_used;
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).
487 ef_used = ef_size = 0;
491 set_policer_param(const char *param, void *data, void *extra)
493 struct record_data *rd = data;
494 const char *str = GET_RECORD_QSTRING(rd);
496 policer_params_set(extra, param, str);
507 info = conf_get_data("services/global/nick", RECDB_QSTRING);
508 if (info && (info[0] == '.'))
512 info = conf_get_data("services/nickserv/nick", RECDB_QSTRING);
513 if (info && (info[0] == '.'))
517 info = conf_get_data("services/chanserv/nick", RECDB_QSTRING);
518 if (info && (info[0] == '.'))
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);
526 policer_params_set(god_policer_params, "size", "30");
527 policer_params_set(god_policer_params, "drain-rate", "1");
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);
533 policer_params_set(oper_policer_params, "size", "10");
534 policer_params_set(oper_policer_params, "drain-rate", "1");
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);
540 policer_params_set(luser_policer_params, "size", "5");
541 policer_params_set(luser_policer_params, "drain-rate", "0.50");
544 info = conf_get_data("services/opserv/nick", RECDB_QSTRING);
545 if (info && (info[0] == '.'))
550 #ifdef HAVE_SYS_RESOURCE_H
553 set_item_rlimit(const char *name, void *data, void *extra)
556 struct record_data *rd = data;
560 rsrc = (int)dict_find(extra, name, &found);
562 log_module(MAIN_LOG, LOG_ERROR, "Invalid rlimit \"%s\" in rlimits section.", name);
565 if (!(str = GET_RECORD_QSTRING(rd))) {
566 log_module(MAIN_LOG, LOG_ERROR, "Missing or invalid parameter type for rlimit \"%s\".", name);
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));
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));
586 dict_insert(values, "data", (void*)RLIMIT_DATA);
587 dict_insert(values, "stack", (void*)RLIMIT_STACK);
589 dict_insert(values, "vmem", (void*)RLIMIT_VMEM);
592 dict_insert(values, "vmem", (void*)RLIMIT_AS);
595 if ((dict = conf_get_data("rlimits", RECDB_OBJECT))) {
596 dict_foreach(dict, set_item_rlimit, values);
610 void main_shutdown(void)
612 struct uplinkNode *ul, *ul_next;
614 for (ul = cManager.uplinks; ul; ul = ul_next) {
622 policer_params_delete(god_policer_params);
623 policer_params_delete(oper_policer_params);
624 policer_params_delete(luser_policer_params);
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"
643 printf(" --------------------------------------------------\n"
644 " - "PACKAGE_STRING" ("CODENAME"), Built: " __DATE__ ", " __TIME__".\n"
645 " - Copyright (C) 2000 - 2003, srvx Development Team\n"
646 " --------------------------------------------------\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"
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"
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");
666 #if WITH_MALLOC_BOEHM_GC
668 gc_warn_proc(char *msg, GC_word arg)
670 log_module(MAIN_LOG, LOG_ERROR, "GC(%p): %s", (void*)arg, msg);
674 int main(int argc, char *argv[])
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);
699 if (argc > 1) { /* parse command line, if any */
701 struct option options[] =
703 {"config", 1, 0, 'c'},
704 {"debug", 0, 0, 'd'},
705 {"foreground", 0, 0, 'f'},
707 {"check", 0, 0, 'k'},
708 {"replay", 1, 0, 'r'},
709 {"version", 0, 0, 'v'},
710 {"verbose", 0, 0, 'V'},
714 while ((c = getopt_long(argc, argv, "c:kr:dfvVh", options, NULL)) != -1) {
717 services_config = optarg;
720 if (conf_read(services_config)) {
721 printf("%s appears to be a valid configuration file.\n", services_config);
723 printf("%s is an invalid configuration file.\n", services_config);
727 replay_file = fopen(optarg, "r");
729 fprintf(stderr, "Could not open %s for reading: %s (%d)\n",
730 optarg, strerror(errno), errno);
757 fprintf(stderr, "Daemon mode not supported under Cygwin.\n");
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
769 boot_time = time(&now);
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);
778 conf_register_reload(uplink_compile);
781 /* Attempt to fork into the background if daemon mode is on. */
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);
790 /* Close these since we should not use them from now on. */
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));
800 fprintf(file_out, "%i\n", (int)getpid());
804 services_argc = argc;
805 services_argv = argv;
807 atexit(call_exit_funcs);
808 reg_exit_func(main_shutdown);
811 MAIN_LOG = log_register_type("srvx", "file:main.log");
814 #if WITH_MALLOC_BOEHM_GC
815 GC_set_warn_proc(gc_warn_proc);
816 GC_enable_incremental();
826 conf_globals(); /* initializes the core services */
829 message_register_table(msgtab);
834 /* The first exit func to be called *should* be saxdb_write_all(). */
835 reg_exit_func(saxdb_write_all);
838 log_module(MAIN_LOG, LOG_INFO, "Beginning replay...");
841 if ((msg = dict_sanity_check(clients))) {
842 log_module(MAIN_LOG, LOG_ERROR, "Clients insanity: %s", msg);
845 if ((msg = dict_sanity_check(channels))) {
846 log_module(MAIN_LOG, LOG_ERROR, "Channels insanity: %s", msg);
849 if ((msg = dict_sanity_check(servers))) {
850 log_module(MAIN_LOG, LOG_ERROR, "Servers insanity: %s", msg);