Cleanup dnsmgr on exit.
[asterisk/asterisk.git] / main / dnsmgr.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2005-2006, Kevin P. Fleming
5  *
6  * Kevin P. Fleming <kpfleming@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Background DNS update manager
22  *
23  * \author Kevin P. Fleming <kpfleming@digium.com>
24  *
25  * \bug There is a minor race condition.  In the event that an IP address
26  * of a dnsmgr managed host changes, there is the potential for the consumer
27  * of that address to access the in_addr data at the same time that the dnsmgr
28  * thread is in the middle of updating it to the new address.
29  */
30
31
32 /*! \li \ref dnsmgr.c uses the configuration file \ref dnsmgr.conf
33  * \addtogroup configuration_file Configuration Files
34  */
35
36 /*!
37  * \page dnsmgr.conf dnsmgr.conf
38  * \verbinclude dnsmgr.conf.sample
39  */
40
41
42 /*** MODULEINFO
43         <support_level>core</support_level>
44  ***/
45
46 #include "asterisk.h"
47
48 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
49
50 #include "asterisk/_private.h"
51 #include <regex.h>
52 #include <signal.h>
53
54 #include "asterisk/dnsmgr.h"
55 #include "asterisk/linkedlists.h"
56 #include "asterisk/utils.h"
57 #include "asterisk/config.h"
58 #include "asterisk/sched.h"
59 #include "asterisk/cli.h"
60 #include "asterisk/manager.h"
61 #include "asterisk/acl.h"
62
63 static struct ast_sched_context *sched;
64 static int refresh_sched = -1;
65 static pthread_t refresh_thread = AST_PTHREADT_NULL;
66
67 struct ast_dnsmgr_entry {
68         /*! where we will store the resulting IP address and port number */
69         struct ast_sockaddr *result;
70         /*! SRV record to lookup, if provided. Composed of service, protocol, and domain name: _Service._Proto.Name */
71         char *service;
72         /*! Address family to filter DNS responses. */
73         unsigned int family;
74         /*! Set to 1 if the entry changes */
75         unsigned int changed:1;
76         /*! Data to pass back to update_func */
77         void *data;
78         /*! The callback function to execute on address update */
79         dns_update_func update_func;
80         ast_mutex_t lock;
81         AST_RWLIST_ENTRY(ast_dnsmgr_entry) list;
82         /*! just 1 here, but we use calloc to allocate the correct size */
83         char name[1];
84 };
85
86 static AST_RWLIST_HEAD_STATIC(entry_list, ast_dnsmgr_entry);
87
88 AST_MUTEX_DEFINE_STATIC(refresh_lock);
89
90 #define REFRESH_DEFAULT 300
91
92 static int enabled;
93 static int refresh_interval;
94
95 struct refresh_info {
96         struct entry_list *entries;
97         int verbose;
98         unsigned int regex_present:1;
99         regex_t filter;
100 };
101
102 static struct refresh_info master_refresh_info = {
103         .entries = &entry_list,
104         .verbose = 0,
105 };
106
107 struct ast_dnsmgr_entry *ast_dnsmgr_get_family(const char *name, struct ast_sockaddr *result, const char *service, unsigned int family)
108 {
109         struct ast_dnsmgr_entry *entry;
110         int total_size = sizeof(*entry) + strlen(name) + (service ? strlen(service) + 1 : 0);
111
112         if (!result || ast_strlen_zero(name) || !(entry = ast_calloc(1, total_size))) {
113                 return NULL;
114         }
115
116         entry->result = result;
117         ast_mutex_init(&entry->lock);
118         strcpy(entry->name, name);
119         if (service) {
120                 entry->service = ((char *) entry) + sizeof(*entry) + strlen(name);
121                 strcpy(entry->service, service);
122         }
123         entry->family = family;
124
125         AST_RWLIST_WRLOCK(&entry_list);
126         AST_RWLIST_INSERT_HEAD(&entry_list, entry, list);
127         AST_RWLIST_UNLOCK(&entry_list);
128
129         return entry;
130 }
131
132 struct ast_dnsmgr_entry *ast_dnsmgr_get(const char *name, struct ast_sockaddr *result, const char *service)
133 {
134         return ast_dnsmgr_get_family(name, result, service, 0);
135 }
136
137 void ast_dnsmgr_release(struct ast_dnsmgr_entry *entry)
138 {
139         if (!entry) {
140                 return;
141         }
142
143         AST_RWLIST_WRLOCK(&entry_list);
144         AST_RWLIST_REMOVE(&entry_list, entry, list);
145         AST_RWLIST_UNLOCK(&entry_list);
146         ast_debug(6, "removing dns manager for '%s'\n", entry->name);
147
148         ast_mutex_destroy(&entry->lock);
149         ast_free(entry);
150 }
151
152 static int internal_dnsmgr_lookup(const char *name, struct ast_sockaddr *result, struct ast_dnsmgr_entry **dnsmgr, const char *service, dns_update_func func, void *data)
153 {
154         unsigned int family;
155
156         if (ast_strlen_zero(name) || !result || !dnsmgr) {
157                 return -1;
158         }
159
160         if (*dnsmgr && !strcasecmp((*dnsmgr)->name, name)) {
161                 return 0;
162         }
163
164         /* Lookup address family filter. */
165         family = result->ss.ss_family;
166
167         /*
168          * If it's actually an IP address and not a name, there's no
169          * need for a managed lookup.
170          */
171         if (ast_sockaddr_parse(result, name, PARSE_PORT_FORBID)) {
172                 return 0;
173         }
174
175         ast_debug(6, "doing dnsmgr_lookup for '%s'\n", name);
176
177         /* do a lookup now but add a manager so it will automagically get updated in the background */
178         ast_get_ip_or_srv(result, name, service);
179
180         /* if dnsmgr is not enable don't bother adding an entry */
181         if (!enabled) {
182                 return 0;
183         }
184
185         ast_debug(6, "adding dns manager for '%s'\n", name);
186         *dnsmgr = ast_dnsmgr_get_family(name, result, service, family);
187         (*dnsmgr)->update_func = func;
188         (*dnsmgr)->data = data;
189         return !*dnsmgr;
190 }
191
192 int ast_dnsmgr_lookup(const char *name, struct ast_sockaddr *result, struct ast_dnsmgr_entry **dnsmgr, const char *service)
193 {
194         return internal_dnsmgr_lookup(name, result, dnsmgr, service, NULL, NULL);
195 }
196
197 int ast_dnsmgr_lookup_cb(const char *name, struct ast_sockaddr *result, struct ast_dnsmgr_entry **dnsmgr, const char *service, dns_update_func func, void *data)
198 {
199         return internal_dnsmgr_lookup(name, result, dnsmgr, service, func, data);
200 }
201
202 /*
203  * Refresh a dnsmgr entry
204  */
205 static int dnsmgr_refresh(struct ast_dnsmgr_entry *entry, int verbose)
206 {
207         struct ast_sockaddr tmp = { .len = 0, };
208         int changed = 0;
209
210         ast_mutex_lock(&entry->lock);
211
212         ast_debug(6, "refreshing '%s'\n", entry->name);
213
214         tmp.ss.ss_family = entry->family;
215         if (!ast_get_ip_or_srv(&tmp, entry->name, entry->service)) {
216                 if (!ast_sockaddr_port(&tmp)) {
217                         ast_sockaddr_set_port(&tmp, ast_sockaddr_port(entry->result));
218                 }
219                 if (ast_sockaddr_cmp(&tmp, entry->result)) {
220                         const char *old_addr = ast_strdupa(ast_sockaddr_stringify(entry->result));
221                         const char *new_addr = ast_strdupa(ast_sockaddr_stringify(&tmp));
222
223                         if (entry->update_func) {
224                                 entry->update_func(entry->result, &tmp, entry->data);
225                         } else {
226                                 ast_log(LOG_NOTICE, "dnssrv: host '%s' changed from %s to %s\n",
227                                                 entry->name, old_addr, new_addr);
228
229                                 ast_sockaddr_copy(entry->result, &tmp);
230                                 changed = entry->changed = 1;
231                         }
232                 }
233         }
234
235         ast_mutex_unlock(&entry->lock);
236
237         return changed;
238 }
239
240 int ast_dnsmgr_refresh(struct ast_dnsmgr_entry *entry)
241 {
242         return dnsmgr_refresh(entry, 0);
243 }
244
245 /*
246  * Check if dnsmgr entry has changed from since last call to this function
247  */
248 int ast_dnsmgr_changed(struct ast_dnsmgr_entry *entry)
249 {
250         int changed;
251
252         ast_mutex_lock(&entry->lock);
253
254         changed = entry->changed;
255         entry->changed = 0;
256
257         ast_mutex_unlock(&entry->lock);
258
259         return changed;
260 }
261
262 static void *do_refresh(void *data)
263 {
264         for (;;) {
265                 pthread_testcancel();
266                 usleep((ast_sched_wait(sched)*1000));
267                 pthread_testcancel();
268                 ast_sched_runq(sched);
269         }
270         return NULL;
271 }
272
273 static int refresh_list(const void *data)
274 {
275         struct refresh_info *info = (struct refresh_info *)data;
276         struct ast_dnsmgr_entry *entry;
277
278         /* if a refresh or reload is already in progress, exit now */
279         if (ast_mutex_trylock(&refresh_lock)) {
280                 if (info->verbose) {
281                         ast_log(LOG_WARNING, "DNS Manager refresh already in progress.\n");
282                 }
283                 return -1;
284         }
285
286         ast_debug(6, "Refreshing DNS lookups.\n");
287         AST_RWLIST_RDLOCK(info->entries);
288         AST_RWLIST_TRAVERSE(info->entries, entry, list) {
289                 if (info->regex_present && regexec(&info->filter, entry->name, 0, NULL, 0)) {
290                         continue;
291                 }
292
293                 dnsmgr_refresh(entry, info->verbose);
294         }
295         AST_RWLIST_UNLOCK(info->entries);
296
297         ast_mutex_unlock(&refresh_lock);
298
299         /* automatically reschedule based on the interval */
300         return refresh_interval * 1000;
301 }
302
303 void dnsmgr_start_refresh(void)
304 {
305         if (refresh_sched > -1) {
306                 AST_SCHED_DEL(sched, refresh_sched);
307                 refresh_sched = ast_sched_add_variable(sched, 100, refresh_list, &master_refresh_info, 1);
308         }
309 }
310
311 static int do_reload(int loading);
312
313 static char *handle_cli_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
314 {
315         switch (cmd) {
316         case CLI_INIT:
317                 e->command = "dnsmgr reload";
318                 e->usage =
319                         "Usage: dnsmgr reload\n"
320                         "       Reloads the DNS manager configuration.\n";
321                 return NULL;
322         case CLI_GENERATE:
323                 return NULL;
324         }
325         if (a->argc > 2) {
326                 return CLI_SHOWUSAGE;
327         }
328
329         do_reload(0);
330         return CLI_SUCCESS;
331 }
332
333 static char *handle_cli_refresh(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
334 {
335         struct refresh_info info = {
336                 .entries = &entry_list,
337                 .verbose = 1,
338         };
339         switch (cmd) {
340         case CLI_INIT:
341                 e->command = "dnsmgr refresh";
342                 e->usage =
343                         "Usage: dnsmgr refresh [pattern]\n"
344                         "       Peforms an immediate refresh of the managed DNS entries.\n"
345                         "       Optional regular expression pattern is used to filter the entries to refresh.\n";
346                 return NULL;
347         case CLI_GENERATE:
348                 return NULL;
349         }
350
351         if (!enabled) {
352                 ast_cli(a->fd, "DNS Manager is disabled.\n");
353                 return 0;
354         }
355
356         if (a->argc > 3) {
357                 return CLI_SHOWUSAGE;
358         }
359
360         if (a->argc == 3) {
361                 if (regcomp(&info.filter, a->argv[2], REG_EXTENDED | REG_NOSUB)) {
362                         return CLI_SHOWUSAGE;
363                 } else {
364                         info.regex_present = 1;
365                 }
366         }
367
368         refresh_list(&info);
369
370         if (info.regex_present) {
371                 regfree(&info.filter);
372         }
373
374         return CLI_SUCCESS;
375 }
376
377 static char *handle_cli_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
378 {
379         int count = 0;
380         struct ast_dnsmgr_entry *entry;
381         switch (cmd) {
382         case CLI_INIT:
383                 e->command = "dnsmgr status";
384                 e->usage =
385                         "Usage: dnsmgr status\n"
386                         "       Displays the DNS manager status.\n";
387                 return NULL;
388         case CLI_GENERATE:
389                 return NULL;
390         }
391
392         if (a->argc > 2) {
393                 return CLI_SHOWUSAGE;
394         }
395
396         ast_cli(a->fd, "DNS Manager: %s\n", enabled ? "enabled" : "disabled");
397         ast_cli(a->fd, "Refresh Interval: %d seconds\n", refresh_interval);
398         AST_RWLIST_RDLOCK(&entry_list);
399         AST_RWLIST_TRAVERSE(&entry_list, entry, list)
400                 count++;
401         AST_RWLIST_UNLOCK(&entry_list);
402         ast_cli(a->fd, "Number of entries: %d\n", count);
403
404         return CLI_SUCCESS;
405 }
406
407 static struct ast_cli_entry cli_reload = AST_CLI_DEFINE(handle_cli_reload, "Reloads the DNS manager configuration");
408 static struct ast_cli_entry cli_refresh = AST_CLI_DEFINE(handle_cli_refresh, "Performs an immediate refresh");
409 static struct ast_cli_entry cli_status = AST_CLI_DEFINE(handle_cli_status, "Display the DNS manager status");
410
411 static void dnsmgr_shutdown(void)
412 {
413         ast_cli_unregister(&cli_reload);
414         ast_cli_unregister(&cli_status);
415         ast_cli_unregister(&cli_refresh);
416
417         /* Destroy refresh thread. */
418         ast_mutex_lock(&refresh_lock);
419         if (refresh_thread != AST_PTHREADT_NULL) {
420                 /* wake up the thread so it will exit */
421                 pthread_cancel(refresh_thread);
422                 pthread_kill(refresh_thread, SIGURG);
423                 pthread_join(refresh_thread, NULL);
424                 refresh_thread = AST_PTHREADT_NULL;
425         }
426         ast_mutex_unlock(&refresh_lock);
427
428         ast_sched_context_destroy(sched);
429 }
430
431 int dnsmgr_init(void)
432 {
433         if (!(sched = ast_sched_context_create())) {
434                 ast_log(LOG_ERROR, "Unable to create schedule context.\n");
435                 return -1;
436         }
437         ast_cli_register(&cli_reload);
438         ast_cli_register(&cli_status);
439         ast_cli_register(&cli_refresh);
440
441         ast_register_atexit(dnsmgr_shutdown);
442
443         return do_reload(1);
444 }
445
446 int dnsmgr_reload(void)
447 {
448         return do_reload(0);
449 }
450
451 static int do_reload(int loading)
452 {
453         struct ast_config *config;
454         struct ast_variable *v;
455         struct ast_flags config_flags = { loading ? 0 : CONFIG_FLAG_FILEUNCHANGED };
456         int interval;
457         int was_enabled;
458
459         if ((config = ast_config_load2("dnsmgr.conf", "dnsmgr", config_flags)) == CONFIG_STATUS_FILEUNCHANGED) {
460                 return 0;
461         }
462
463         /* ensure that no refresh cycles run while the reload is in progress */
464         ast_mutex_lock(&refresh_lock);
465
466         /* reset defaults in preparation for reading config file */
467         refresh_interval = REFRESH_DEFAULT;
468         was_enabled = enabled;
469         enabled = 0;
470
471         if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
472                 ast_mutex_unlock(&refresh_lock);
473                 return 0;
474         }
475
476         AST_SCHED_DEL(sched, refresh_sched);
477
478         for (v = ast_variable_browse(config, "general"); v; v = v->next) {
479                 if (!strcasecmp(v->name, "enable")) {
480                         enabled = ast_true(v->value);
481                 } else if (!strcasecmp(v->name, "refreshinterval")) {
482                         if (sscanf(v->value, "%30d", &interval) < 1) {
483                                 ast_log(LOG_WARNING, "Unable to convert '%s' to a numeric value.\n", v->value);
484                         } else if (interval < 0) {
485                                 ast_log(LOG_WARNING, "Invalid refresh interval '%d' specified, using default\n", interval);
486                         } else {
487                                 refresh_interval = interval;
488                         }
489                 }
490         }
491         ast_config_destroy(config);
492
493         if (enabled && refresh_interval) {
494                 ast_log(LOG_NOTICE, "Managed DNS entries will be refreshed every %d seconds.\n", refresh_interval);
495         }
496
497         /* if this reload enabled the manager, create the background thread
498            if it does not exist */
499         if (enabled) {
500                 if (!was_enabled && (refresh_thread == AST_PTHREADT_NULL)) {
501                         if (ast_pthread_create_background(&refresh_thread, NULL, do_refresh, NULL) < 0) {
502                                 ast_log(LOG_ERROR, "Unable to start refresh thread.\n");
503                         }
504                 }
505                 /* make a background refresh happen right away */
506                 refresh_sched = ast_sched_add_variable(sched, 100, refresh_list, &master_refresh_info, 1);
507         /* if this reload disabled the manager and there is a background thread, kill it */
508         } else if (!enabled && was_enabled && (refresh_thread != AST_PTHREADT_NULL)) {
509                 /* wake up the thread so it will exit */
510                 pthread_cancel(refresh_thread);
511                 pthread_kill(refresh_thread, SIGURG);
512                 pthread_join(refresh_thread, NULL);
513                 refresh_thread = AST_PTHREADT_NULL;
514         }
515
516         ast_mutex_unlock(&refresh_lock);
517         manager_event(EVENT_FLAG_SYSTEM, "Reload", "Module: DNSmgr\r\nStatus: %s\r/nMessage: DNSmgr reload Requested\r\n", enabled ? "Enabled" : "Disabled");
518
519         return 0;
520 }