Uplink exhaustion should be a non-fatal error, since we exit afterwards.
[srvx.git] / src / main-common.c
1 extern FILE *replay_file;
2
3 time_t boot_time, burst_begin, now;
4 unsigned long burst_length;
5 struct log_type *MAIN_LOG;
6
7 int quit_services;
8 int max_cycles;
9
10 char *services_config = "srvx.conf";
11
12 char **services_argv;
13 int services_argc;
14
15 struct cManagerNode cManager;
16
17 struct policer_params *oper_policer_params, *luser_policer_params, *god_policer_params;
18
19 static const struct message_entry msgtab[] = {
20     { "MSG_NONE", "None" },
21     { "MSG_ON", "On" },
22     { "MSG_OFF", "Off" },
23     { "MSG_NEVER", "Never" },
24     { "MSG_SERVICE_IMMUNE", "$b%s$b may not be kicked, killed, banned, or deopped." },
25     { "MSG_SERVICE_PRIVILEGED", "$b%s$b is a privileged service." },
26     { "MSG_NOT_A_SERVICE", "$b%s$b is not a service bot." },
27     { "MSG_COMMAND_UNKNOWN", "$b%s$b is an unknown command." },
28     { "MSG_COMMAND_PRIVILEGED", "$b%s$b is a privileged command." },
29     { "MSG_COMMAND_DISABLED", "$b%s$b is a disabled command." },
30     { "MSG_SETTING_PRIVILEGED", "$b%s$b is a privileged setting." },
31     { "MSG_AUTHENTICATE", "You must first authenticate with $b$N$b." },
32     { "MSG_USER_AUTHENTICATE", "%s must first authenticate with $b$N$b." },
33     { "MSG_SET_EMAIL_ADDR", "You must first set your account's email address.  (Contact network staff if you cannot auth to your account.)" },
34     { "MSG_HANDLE_UNKNOWN", "Account $b%s$b has not been registered." },
35     { "MSG_NICK_UNKNOWN", "User with nick $b%s$b does not exist." },
36     { "MSG_CHANNEL_UNKNOWN", "Channel with name $b%s$b does not exist." },
37     { "MSG_SERVER_UNKNOWN", "Server with name $b%s$b does not exist or is not linked." },
38     { "MSG_MODULE_UNKNOWN", "No module has been registered with name $b%s$b." },
39     { "MSG_INVALID_MODES", "$b%s$b is an invalid set of channel modes." },
40     { "MSG_INVALID_GLINE", "Invalid G-line '%s'." },
41     { "MSG_INVALID_DURATION", "Invalid time span '%s'." },
42     { "MSG_NOT_TARGET_NAME", "You must provide the name of a channel or user." },
43     { "MSG_NOT_CHANNEL_NAME", "You must provide a valid channel name." },
44     { "MSG_INVALID_CHANNEL", "You must provide the name of a channel that exists." },
45     { "MSG_CHANNEL_ABSENT", "You aren't currently in $b%s$b." },
46     { "MSG_CHANNEL_USER_ABSENT", "$b%s$b isn't currently in $b%s$b." },
47     { "MSG_MISSING_PARAMS", "$b%s$b requires more parameters." },
48     { "MSG_DEPRECATED_COMMAND", "The $b%s$b command has been deprecated, and will be removed in the future; please use $b%s$b instead." },
49     { "MSG_OPER_SUSPENDED", "Your $b$O$b access has been suspended." },
50     { "MSG_USER_OUTRANKED", "$b%s$b outranks you (command has no effect)." },
51     { "MSG_STUPID_ACCESS_CHANGE", "Please ask someone $belse$b to demote you." },
52     { "MSG_NO_SEARCH_ACCESS", "You do not have enough access to search based on $b%s$b." },
53     { "MSG_INVALID_CRITERIA", "$b%s$b is an invalid search criteria." },
54     { "MSG_MATCH_COUNT", "Found $b%u$b matches." },
55     { "MSG_NO_MATCHES", "Nothing matched the criteria of your search." },
56     { "MSG_TOPIC_UNKNOWN", "No help on that topic." },
57     { "MSG_INVALID_BINARY", "$b%s$b is an invalid binary value." },
58     { "MSG_INTERNAL_FAILURE", "Your command could not be processed due to an internal failure." },
59     { "MSG_DB_UNKNOWN", "I do not know of a database named %s." },
60     { "MSG_DB_IS_MONDO", "Database %s is in the \"mondo\" database and cannot be written separately." },
61     { "MSG_DB_WRITE_ERROR", "Error while writing database %s." },
62     { "MSG_DB_WROTE_DB", "Wrote database %s (in "FMT_TIME_T".%06lu seconds)." },
63     { "MSG_DB_WROTE_ALL", "Wrote all databases (in "FMT_TIME_T".%06lu seconds)." },
64     { "MSG_AND", "and" },
65     { "MSG_0_SECONDS", "0 seconds" },
66     { "MSG_YEAR", "year" },
67     { "MSG_YEARS", "years" },
68     { "MSG_WEEK", "week" },
69     { "MSG_WEEKS", "weeks" },
70     { "MSG_DAY", "day" },
71     { "MSG_DAYS", "days" },
72     { "MSG_HOUR", "hour" },
73     { "MSG_HOURS", "hours" },
74     { "MSG_MINUTE", "minute" },
75     { "MSG_MINUTES", "minutes" },
76     { "MSG_SECOND", "second" },
77     { "MSG_SECONDS", "seconds" },
78     { NULL, NULL }
79 };
80
81 void uplink_select(char *name);
82
83 static int
84 uplink_insert(const char *key, void *data, UNUSED_ARG(void *extra))
85 {
86     struct uplinkNode *uplink = malloc(sizeof(struct uplinkNode));
87     struct record_data *rd = data;
88     struct addrinfo hints, *ai;
89     int enabled = 1;
90     char *str;
91
92     if(!uplink)
93     {
94         return 0;
95     }
96
97     uplink->name = (char *)key;
98     uplink->host = database_get_data(rd->d.object, "address", RECDB_QSTRING);
99
100     str = database_get_data(rd->d.object, "port", RECDB_QSTRING);
101     uplink->port = str ? atoi(str) : 6667;
102     uplink->password = database_get_data(rd->d.object, "password", RECDB_QSTRING);
103     uplink->their_password = database_get_data(rd->d.object, "uplink_password", RECDB_QSTRING);
104
105     str = database_get_data(rd->d.object, "enabled", RECDB_QSTRING);
106     if(str)
107     {
108         enabled = atoi(str) ? 1 : 0;
109     }
110
111     cManager.enabled += enabled;
112
113     str = database_get_data(rd->d.object, "max_tries", RECDB_QSTRING);
114     uplink->max_tries = str ? atoi(str) : 3;
115     uplink->flags = enabled ? 0 : UPLINK_UNAVAILABLE;
116     uplink->state = DISCONNECTED;
117     uplink->tries = 0;
118
119     str = database_get_data(rd->d.object, "bind_address", RECDB_QSTRING);
120     memset(&hints, 0, sizeof(hints));
121     hints.ai_flags = AI_PASSIVE;
122     hints.ai_socktype = SOCK_STREAM;
123     if (!getaddrinfo(str, NULL, &hints, &ai))
124     {
125         uplink->bind_addr_len = ai->ai_addrlen;
126         uplink->bind_addr = calloc(1, ai->ai_addrlen);
127         memcpy(uplink->bind_addr, ai->ai_addr, ai->ai_addrlen);
128         freeaddrinfo(ai);
129     }
130     else
131     {
132         uplink->bind_addr = NULL;
133         uplink->bind_addr_len = 0;
134     }
135
136     uplink->next = cManager.uplinks;
137     uplink->prev = NULL;
138
139     if(cManager.uplinks)
140     {
141         cManager.uplinks->prev = uplink;
142     }
143
144     cManager.uplinks = uplink;
145
146     /* If the configuration is being reloaded, set the current uplink
147        to the reloaded equivalent, if possible. */
148     if(cManager.uplink
149        && enabled
150        && !irccasecmp(uplink->host, cManager.uplink->host)
151        && uplink->port == cManager.uplink->port)
152     {
153         uplink->state = cManager.uplink->state;
154         uplink->tries = cManager.uplink->tries;
155         cManager.uplink = uplink;
156     }
157
158     return 0;
159 }
160
161 void
162 uplink_compile(void)
163 {
164     const char *cycles;
165     dict_t conf_node;
166     struct uplinkNode *oldUplinks = NULL, *oldUplink = NULL;
167
168     /* Save the old uplinks, we'll remove them later. */
169     oldUplink = cManager.uplink;
170     oldUplinks = cManager.uplinks;
171
172     cycles = conf_get_data("server/max_cycles", RECDB_QSTRING);
173     max_cycles = cycles ? atoi(cycles) : 30;
174     if(!(conf_node = conf_get_data("uplinks", RECDB_OBJECT)))
175     {
176         log_module(MAIN_LOG, LOG_FATAL, "No uplinks configured; giving up.");
177         exit(1);
178     }
179
180     cManager.enabled = 0;
181     dict_foreach(conf_node, uplink_insert, NULL);
182
183     /* Remove the old uplinks, if any. It doesn't matter if oldUplink (below)
184        is a reference to one of these, because it won't get dereferenced. */
185     if(oldUplinks)
186     {
187         struct uplinkNode *uplink, *next;
188
189         oldUplinks->prev->next = NULL;
190
191         for(uplink = oldUplinks; uplink; uplink = next)
192         {
193             next = uplink->next;
194             free(uplink->bind_addr);
195             free(uplink);
196         }
197     }
198
199     /* If the uplink hasn't changed, it's either NULL or pointing at
200        an uplink that was just deleted, select a new one. */
201     if(cManager.uplink == oldUplink)
202     {
203         if(oldUplink)
204         {
205             irc_squit(self, "Uplinks updated; selecting new uplink.", NULL);
206         }
207
208         cManager.uplink = NULL;
209         uplink_select(NULL);
210     }
211 }
212
213 struct uplinkNode *
214 uplink_find(char *name)
215 {
216     struct uplinkNode *uplink;
217
218     if(!cManager.enabled || !cManager.uplinks)
219     {
220         return NULL;
221     }
222
223     for(uplink = cManager.uplinks; uplink; uplink = uplink->next)
224     {
225         if(!strcasecmp(uplink->name, name))
226         {
227             return uplink;
228         }
229     }
230
231     return NULL;
232 }
233
234 void
235 uplink_select(char *name)
236 {
237     struct uplinkNode *start, *uplink, *next;
238     int stop;
239
240     if(!cManager.enabled || !cManager.uplinks)
241     {
242         log_module(MAIN_LOG, LOG_FATAL, "No uplinks enabled; giving up.");
243         exit(1);
244     }
245
246     if(!cManager.uplink)
247     {
248         start = cManager.uplinks;
249     }
250     else
251     {
252         start = cManager.uplink->next;
253         if(!start)
254         {
255             start = cManager.uplinks;
256         }
257     }
258
259     stop = 0;
260     for(uplink = start; uplink; uplink = next)
261     {
262         next = uplink->next ? uplink->next : cManager.uplinks;
263
264         if(stop)
265         {
266             uplink = NULL;
267             break;
268         }
269
270         /* We've wrapped around the list. */
271         if(next == start)
272         {
273             sleep((cManager.cycles >> 1) * 5);
274             cManager.cycles++;
275
276             if(max_cycles && (cManager.cycles >= max_cycles))
277             {
278                 log_module(MAIN_LOG, LOG_ERROR, "Maximum uplink list cycles exceeded; giving up.");
279                 exit(1);
280             }
281
282             /* Give the uplink currently in 'uplink' consideration,
283                and if not selected, break on the next iteration. */
284             stop = 1;
285         }
286
287         /* Skip bad uplinks. */
288         if(uplink->flags & UPLINK_UNAVAILABLE)
289         {
290             continue;
291         }
292
293         if(name && irccasecmp(uplink->name, name))
294         {
295             /* If we were told to connect to a specific uplink, don't stop
296                until we find it.
297             */
298             continue;
299         }
300
301         /* It would be possible to track uplink health through a variety
302            of statistics and only break on the best uplink. For now, break
303            on the first available one.
304         */
305
306         break;
307     }
308
309     if(!uplink)
310     {
311         /* We are shit outta luck if every single uplink has been passed
312            over. Use the current uplink if possible. */
313         if(!cManager.uplink || cManager.uplink->flags & UPLINK_UNAVAILABLE)
314         {
315             log_module(MAIN_LOG, LOG_ERROR, "All available uplinks exhausted; giving up.");
316             exit(1);
317         }
318
319         return;
320     }
321
322     cManager.uplink = uplink;
323 }
324
325 int
326 uplink_connect(void)
327 {
328     struct uplinkNode *uplink = cManager.uplink;
329
330     if(uplink->state != DISCONNECTED)
331     {
332         return 0;
333     }
334
335     if(uplink->flags & UPLINK_UNAVAILABLE)
336     {
337         uplink_select(NULL);
338         uplink = cManager.uplink;
339     }
340
341     if(uplink->tries)
342     {
343         /* This delay could scale with the number of tries. */
344         sleep(2);
345     }
346
347     if(!create_socket_client(uplink))
348     {
349         if(uplink->max_tries && (uplink->tries >= uplink->max_tries))
350         {
351             /* This is a bad uplink, move on. */
352             uplink->flags |= UPLINK_UNAVAILABLE;
353             uplink_select(NULL);
354         }
355
356         return 0;
357     }
358     else
359     {
360         uplink->state = AUTHENTICATING;
361         irc_introduce(uplink->password);
362     }
363
364     return 1;
365 }
366
367 void
368 received_ping(void)
369 {
370     /* This function is called when a ping is received. Take it as
371        a sign of link health and reset the connection manager
372        information. */
373
374     cManager.cycles = 0;
375 }
376
377 static exit_func_t *ef_list;
378 static unsigned int ef_size = 0, ef_used = 0;
379
380 void reg_exit_func(exit_func_t handler)
381 {
382     if (ef_used == ef_size) {
383         if (ef_size) {
384             ef_size <<= 1;
385             ef_list = realloc(ef_list, ef_size*sizeof(exit_func_t));
386         } else {
387             ef_size = 8;
388             ef_list = malloc(ef_size*sizeof(exit_func_t));
389         }
390     }
391     ef_list[ef_used++] = handler;
392 }
393
394 void call_exit_funcs(void)
395 {
396     unsigned int n = ef_used;
397
398     /* Call them in reverse order because we initialize logs, then
399      * nickserv, then chanserv, etc., and they register their exit
400      * funcs in that order, and there are some dependencies (for
401      * example, ChanServ requires NickServ to not have cleaned up).
402      */
403
404     while (n > 0) {
405         ef_list[--n]();
406     }
407     free(ef_list);
408     ef_used = ef_size = 0;
409 }
410
411 int
412 set_policer_param(const char *param, void *data, void *extra)
413 {
414     struct record_data *rd = data;
415     const char *str = GET_RECORD_QSTRING(rd);
416     if (str) {
417         policer_params_set(extra, param, str);
418     }
419     return 0;
420 }
421
422 static void
423 conf_globals(void)
424 {
425     const char *info;
426     dict_t dict;
427
428     info = conf_get_data("services/global/nick", RECDB_QSTRING);
429     if (info && (info[0] == '.'))
430         info = NULL;
431     init_global(info);
432
433     info = conf_get_data("services/nickserv/nick", RECDB_QSTRING);
434     if (info && (info[0] == '.'))
435         info = NULL;
436     init_nickserv(info);
437
438     info = conf_get_data("services/chanserv/nick", RECDB_QSTRING);
439     if (info && (info[0] == '.'))
440         info = NULL;
441     init_chanserv(info);
442
443     god_policer_params = policer_params_new();
444     if ((dict = conf_get_data("policers/commands-god", RECDB_OBJECT))) {
445         dict_foreach(dict, set_policer_param, god_policer_params);
446     } else {
447         policer_params_set(god_policer_params, "size", "30");
448         policer_params_set(god_policer_params, "drain-rate", "1");
449     }
450     oper_policer_params = policer_params_new();
451     if ((dict = conf_get_data("policers/commands-oper", RECDB_OBJECT))) {
452         dict_foreach(dict, set_policer_param, oper_policer_params);
453     } else {
454         policer_params_set(oper_policer_params, "size", "10");
455         policer_params_set(oper_policer_params, "drain-rate", "1");
456     }
457     luser_policer_params = policer_params_new();
458     if ((dict = conf_get_data("policers/commands-luser", RECDB_OBJECT))) {
459         dict_foreach(dict, set_policer_param, luser_policer_params);
460     } else {
461         policer_params_set(luser_policer_params, "size", "5");
462         policer_params_set(luser_policer_params, "drain-rate", "0.50");
463     }
464
465     info = conf_get_data("services/opserv/nick", RECDB_QSTRING);
466     if (info && (info[0] == '.'))
467         info = NULL;
468     init_opserv(info);
469 }
470
471 #ifdef HAVE_SYS_RESOURCE_H
472
473 static int
474 set_item_rlimit(const char *name, void *data, void *extra)
475 {
476     long rsrc;
477     int found;
478     struct record_data *rd = data;
479     struct rlimit rlim;
480     const char *str;
481
482     rsrc = (long)dict_find(extra, name, &found);
483     if (!found) {
484         log_module(MAIN_LOG, LOG_ERROR, "Invalid rlimit \"%s\" in rlimits section.", name);
485         return 0;
486     }
487     if (!(str = GET_RECORD_QSTRING(rd))) {
488         log_module(MAIN_LOG, LOG_ERROR, "Missing or invalid parameter type for rlimit \"%s\".", name);
489         return 0;
490     }
491     if (getrlimit(rsrc, &rlim) < 0) {
492         log_module(MAIN_LOG, LOG_ERROR, "Couldn't get rlimit \"%s\": errno %d: %s", name, errno, strerror(errno));
493         return 0;
494     }
495     rlim.rlim_cur = ParseVolume(str);
496     if (setrlimit(rsrc, &rlim) < 0) {
497         log_module(MAIN_LOG, LOG_ERROR, "Couldn't set rlimit \"%s\": errno %d: %s", name, errno, strerror(errno));
498     }
499     return 0;
500 }
501
502 static void
503 conf_rlimits(void)
504 {
505     dict_t dict, values;
506
507     values = dict_new();
508     dict_insert(values, "data", (void*)RLIMIT_DATA);
509     dict_insert(values, "stack", (void*)RLIMIT_STACK);
510 #ifdef RLIMIT_VMEM
511     dict_insert(values, "vmem", (void*)RLIMIT_VMEM);
512 #else
513 #ifdef RLIMIT_AS
514     dict_insert(values, "vmem", (void*)RLIMIT_AS);
515 #endif
516 #endif
517     if ((dict = conf_get_data("rlimits", RECDB_OBJECT))) {
518         dict_foreach(dict, set_item_rlimit, values);
519     }
520     dict_delete(values);
521 }
522
523 #else
524
525 static void
526 conf_rlimits(void)
527 {
528 }
529
530 #endif
531
532 static void
533 usage(char *self)
534 {
535     /* We can assume we have getopt_long(). */
536     printf("Usage: %s [-c config] [-r log] [-d] [-f] [-v|-h]\n"
537            " -c, --config         selects a different configuration file.\n"
538            " -d, --debug          enables debug mode.\n"
539            " -f, --foreground     run srvx in the foreground.\n"
540            " -h, --help           prints this usage message.\n"
541            " -k, --check          checks the configuration file's syntax.\n"
542            " -r, --replay         replay a log file (for debugging).\n"
543            " -v, --version        prints this program's version.\n"
544            , self);
545 }
546
547 static void
548 version()
549 {
550     printf("    --------------------------------------------------\n"
551            "    - "PACKAGE_STRING" ("CODENAME"), Built: " __DATE__ ", " __TIME__".\n"
552            "    - Copyright (C) 2000 - 2005, srvx Development Team\n"
553            "    --------------------------------------------------\n");
554 }
555
556 static void
557 license()
558 {
559     printf("\n"
560            "This program is free software; you can redistribute it and/or modify\n"
561            "it under the terms of the GNU General Public License as published by\n"
562            "the Free Software Foundation; either version 2 of the License, or\n"
563            "(at your option) any later version.\n"
564            "\n"
565            "This program is distributed in the hope that it will be useful,\n"
566            "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
567            "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
568            "GNU General Public License for more details.\n"
569            "\n"
570            "You should have received a copy of the GNU General Public License\n"
571            "along with this program; if not, write to the Free Software\n"
572            "Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n");
573 }
574
575 void main_shutdown(void)
576 {
577     struct uplinkNode *ul, *ul_next;
578     ioset_cleanup();
579     for (ul = cManager.uplinks; ul; ul = ul_next) {
580         ul_next = ul->next;
581         free(ul->bind_addr);
582         free(ul);
583     }
584     tools_cleanup();
585     conf_close();
586 #if defined(PID_FILE)
587     remove(PID_FILE);
588 #endif
589     policer_params_delete(god_policer_params);
590     policer_params_delete(oper_policer_params);
591     policer_params_delete(luser_policer_params);
592     if (replay_file)
593         fclose(replay_file);
594 }