Add support for older name resolving version libraries like openBSD
[asterisk/asterisk.git] / main / dns_core.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2015, Digium, Inc.
5  *
6  * Joshua Colp <jcolp@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 Core DNS Functionality
22  *
23  * \author Joshua Colp <jcolp@digium.com>
24  */
25
26 /*** MODULEINFO
27         <support_level>core</support_level>
28  ***/
29
30 #include "asterisk.h"
31
32 #include "asterisk/linkedlists.h"
33 #include "asterisk/astobj2.h"
34 #include "asterisk/strings.h"
35 #include "asterisk/sched.h"
36 #include "asterisk/dns_core.h"
37 #include "asterisk/dns_srv.h"
38 #include "asterisk/dns_tlsa.h"
39 #include "asterisk/dns_recurring.h"
40 #include "asterisk/dns_resolver.h"
41 #include "asterisk/dns_internal.h"
42
43 #include <netinet/in.h>
44 #include <arpa/nameser.h>
45
46 AST_RWLIST_HEAD_STATIC(resolvers, ast_dns_resolver);
47
48 static struct ast_sched_context *sched;
49
50 struct ast_sched_context *ast_dns_get_sched(void)
51 {
52         return sched;
53 }
54
55 const char *ast_dns_query_get_name(const struct ast_dns_query *query)
56 {
57         return query->name;
58 }
59
60 int ast_dns_query_get_rr_type(const struct ast_dns_query *query)
61 {
62         return query->rr_type;
63 }
64
65 int ast_dns_query_get_rr_class(const struct ast_dns_query *query)
66 {
67         return query->rr_class;
68 }
69
70 void *ast_dns_query_get_data(const struct ast_dns_query *query)
71 {
72         return query->user_data;
73 }
74
75 struct ast_dns_result *ast_dns_query_get_result(const struct ast_dns_query *query)
76 {
77         return query->result;
78 }
79
80 unsigned int ast_dns_result_get_secure(const struct ast_dns_result *result)
81 {
82         return result->secure;
83 }
84
85 unsigned int ast_dns_result_get_bogus(const struct ast_dns_result *result)
86 {
87         return result->bogus;
88 }
89
90 unsigned int ast_dns_result_get_rcode(const struct ast_dns_result *result)
91 {
92         return result->rcode;
93 }
94
95 const char *ast_dns_result_get_canonical(const struct ast_dns_result *result)
96 {
97         return result->canonical;
98 }
99
100 const struct ast_dns_record *ast_dns_result_get_records(const struct ast_dns_result *result)
101 {
102         return AST_LIST_FIRST(&result->records);
103 }
104
105 const char *ast_dns_result_get_answer(const struct ast_dns_result *result)
106 {
107         return result->answer;
108 }
109
110 int ast_dns_result_get_lowest_ttl(const struct ast_dns_result *result)
111 {
112         int ttl = 0;
113         const struct ast_dns_record *record;
114
115         if (ast_dns_result_get_rcode(result) == NXDOMAIN) {
116                 return 0;
117         }
118
119         for (record = ast_dns_result_get_records(result); record; record = ast_dns_record_get_next(record)) {
120                 if (!ttl || (ast_dns_record_get_ttl(record) && (ast_dns_record_get_ttl(record) < ttl))) {
121                         ttl = ast_dns_record_get_ttl(record);
122                 }
123         }
124
125         return ttl;
126 }
127
128 void ast_dns_result_free(struct ast_dns_result *result)
129 {
130         struct ast_dns_record *record;
131
132         if (!result) {
133                 return;
134         }
135
136         while ((record = AST_LIST_REMOVE_HEAD(&result->records, list))) {
137                 ast_free(record);
138         }
139
140         ast_free(result);
141 }
142
143 int ast_dns_record_get_rr_type(const struct ast_dns_record *record)
144 {
145         return record->rr_type;
146 }
147
148 int ast_dns_record_get_rr_class(const struct ast_dns_record *record)
149 {
150         return record->rr_class;
151 }
152
153 int ast_dns_record_get_ttl(const struct ast_dns_record *record)
154 {
155         return record->ttl;
156 }
157
158 const char *ast_dns_record_get_data(const struct ast_dns_record *record)
159 {
160         return record->data_ptr;
161 }
162
163 size_t ast_dns_record_get_data_size(const struct ast_dns_record *record)
164 {
165         return record->data_len;
166 }
167
168 const struct ast_dns_record *ast_dns_record_get_next(const struct ast_dns_record *record)
169 {
170         return AST_LIST_NEXT(record, list);
171 }
172
173 /*! \brief Destructor for an active DNS query */
174 static void dns_query_active_destroy(void *data)
175 {
176         struct ast_dns_query_active *active = data;
177
178         ao2_cleanup(active->query);
179 }
180
181 /*! \brief \brief Destructor for a DNS query */
182 static void dns_query_destroy(void *data)
183 {
184         struct ast_dns_query *query = data;
185
186         ao2_cleanup(query->user_data);
187         ao2_cleanup(query->resolver_data);
188         ast_dns_result_free(query->result);
189 }
190
191 struct ast_dns_query *dns_query_alloc(const char *name, int rr_type, int rr_class, ast_dns_resolve_callback callback, void *data)
192 {
193         struct ast_dns_query *query;
194
195         if (ast_strlen_zero(name)) {
196                 ast_log(LOG_WARNING, "Could not perform asynchronous resolution, no name provided\n");
197                 return NULL;
198         } else if (rr_type > 65536) {
199                 ast_log(LOG_WARNING, "Could not perform asynchronous resolution of '%s', resource record type '%d' exceeds maximum\n",
200                         name, rr_type);
201                 return NULL;
202         } else if (rr_type < 0) {
203                 ast_log(LOG_WARNING, "Could not perform asynchronous resolution of '%s', invalid resource record type '%d'\n",
204                         name, rr_type);
205                 return NULL;
206         } else if (rr_class > 65536) {
207                 ast_log(LOG_WARNING, "Could not perform asynchronous resolution of '%s', resource record class '%d' exceeds maximum\n",
208                         name, rr_class);
209                 return NULL;
210         } else if (rr_class < 0) {
211                 ast_log(LOG_WARNING, "Could not perform asynchronous resolution of '%s', invalid resource class '%d'\n",
212                         name, rr_class);
213                 return NULL;
214         } else if (!callback) {
215                 ast_log(LOG_WARNING, "Could not perform asynchronous resolution of '%s', no callback provided\n",
216                         name);
217                 return NULL;
218         }
219
220         query = ao2_alloc_options(sizeof(*query) + strlen(name) + 1, dns_query_destroy, AO2_ALLOC_OPT_LOCK_NOLOCK);
221         if (!query) {
222                 return NULL;
223         }
224
225         query->callback = callback;
226         query->user_data = ao2_bump(data);
227         query->rr_type = rr_type;
228         query->rr_class = rr_class;
229         strcpy(query->name, name); /* SAFE */
230
231         AST_RWLIST_RDLOCK(&resolvers);
232         query->resolver = AST_RWLIST_FIRST(&resolvers);
233         AST_RWLIST_UNLOCK(&resolvers);
234
235         if (!query->resolver) {
236                 ast_log(LOG_ERROR, "Attempted to do a DNS query for '%s' of class '%d' and type '%d' but no resolver is available\n",
237                         name, rr_class, rr_type);
238                 ao2_ref(query, -1);
239                 return NULL;
240         }
241
242         return query;
243 }
244
245 struct ast_dns_query_active *ast_dns_resolve_async(const char *name, int rr_type, int rr_class, ast_dns_resolve_callback callback, void *data)
246 {
247         struct ast_dns_query_active *active;
248
249         active = ao2_alloc_options(sizeof(*active), dns_query_active_destroy, AO2_ALLOC_OPT_LOCK_NOLOCK);
250         if (!active) {
251                 return NULL;
252         }
253
254         active->query = dns_query_alloc(name, rr_type, rr_class, callback, data);
255         if (!active->query) {
256                 ao2_ref(active, -1);
257                 return NULL;
258         }
259
260         if (active->query->resolver->resolve(active->query)) {
261                 ast_log(LOG_ERROR, "Resolver '%s' returned an error when resolving '%s' of class '%d' and type '%d'\n",
262                         active->query->resolver->name, name, rr_class, rr_type);
263                 ao2_ref(active, -1);
264                 return NULL;
265         }
266
267         return active;
268 }
269
270 int ast_dns_resolve_cancel(struct ast_dns_query_active *active)
271 {
272         return active->query->resolver->cancel(active->query);
273 }
274
275 /*! \brief Structure used for signaling back for synchronous resolution completion */
276 struct dns_synchronous_resolve {
277         /*! \brief Lock used for signaling */
278         ast_mutex_t lock;
279         /*! \brief Condition used for signaling */
280         ast_cond_t cond;
281         /*! \brief Whether the query has completed */
282         unsigned int completed;
283         /*! \brief The result from the query */
284         struct ast_dns_result *result;
285 };
286
287 /*! \brief Destructor for synchronous resolution structure */
288 static void dns_synchronous_resolve_destroy(void *data)
289 {
290         struct dns_synchronous_resolve *synchronous = data;
291
292         ast_mutex_destroy(&synchronous->lock);
293         ast_cond_destroy(&synchronous->cond);
294
295         /* This purposely does not unref result as it has been passed to the caller */
296 }
297
298 /*! \brief Callback used to implement synchronous resolution */
299 static void dns_synchronous_resolve_callback(const struct ast_dns_query *query)
300 {
301         struct dns_synchronous_resolve *synchronous = ast_dns_query_get_data(query);
302
303         synchronous->result = query->result;
304         ((struct ast_dns_query *)query)->result = NULL;
305
306         ast_mutex_lock(&synchronous->lock);
307         synchronous->completed = 1;
308         ast_cond_signal(&synchronous->cond);
309         ast_mutex_unlock(&synchronous->lock);
310 }
311
312 int ast_dns_resolve(const char *name, int rr_type, int rr_class, struct ast_dns_result **result)
313 {
314         struct dns_synchronous_resolve *synchronous;
315         struct ast_dns_query_active *active;
316
317         if (ast_strlen_zero(name)) {
318                 ast_log(LOG_WARNING, "Could not perform synchronous resolution, no name provided\n");
319                 return -1;
320         } else if (rr_type > 65536) {
321                 ast_log(LOG_WARNING, "Could not perform synchronous resolution of '%s', resource record type '%d' exceeds maximum\n",
322                         name, rr_type);
323                 return -1;
324         } else if (rr_type < 0) {
325                 ast_log(LOG_WARNING, "Could not perform synchronous resolution of '%s', invalid resource record type '%d'\n",
326                         name, rr_type);
327                 return -1;
328         } else if (rr_class > 65536) {
329                 ast_log(LOG_WARNING, "Could not perform synchronous resolution of '%s', resource record class '%d' exceeds maximum\n",
330                         name, rr_class);
331                 return -1;
332         } else if (rr_class < 0) {
333                 ast_log(LOG_WARNING, "Could not perform synchronous resolution of '%s', invalid resource class '%d'\n",
334                         name, rr_class);
335                 return -1;
336         } else if (!result) {
337                 ast_log(LOG_WARNING, "Could not perform synchronous resolution of '%s', no result pointer provided for storing results\n",
338                         name);
339                 return -1;
340         }
341
342         synchronous = ao2_alloc_options(sizeof(*synchronous), dns_synchronous_resolve_destroy, AO2_ALLOC_OPT_LOCK_NOLOCK);
343         if (!synchronous) {
344                 return -1;
345         }
346
347         ast_mutex_init(&synchronous->lock);
348         ast_cond_init(&synchronous->cond, NULL);
349
350         active = ast_dns_resolve_async(name, rr_type, rr_class, dns_synchronous_resolve_callback, synchronous);
351         if (active) {
352                 /* Wait for resolution to complete */
353                 ast_mutex_lock(&synchronous->lock);
354                 while (!synchronous->completed) {
355                         ast_cond_wait(&synchronous->cond, &synchronous->lock);
356                 }
357                 ast_mutex_unlock(&synchronous->lock);
358                 ao2_ref(active, -1);
359         }
360
361         *result = synchronous->result;
362         ao2_ref(synchronous, -1);
363
364         return *result ? 0 : -1;
365 }
366
367 int ast_dns_resolver_set_data(struct ast_dns_query *query, void *data)
368 {
369         if (query->resolver_data) {
370                 return -1;
371         }
372
373         query->resolver_data = ao2_bump(data);
374
375         return 0;
376 }
377
378 void *ast_dns_resolver_get_data(const struct ast_dns_query *query)
379 {
380         return query->resolver_data;
381 }
382
383 int ast_dns_resolver_set_result(struct ast_dns_query *query, unsigned int secure, unsigned int bogus,
384         unsigned int rcode, const char *canonical, const char *answer, size_t answer_size)
385 {
386         char *buf_ptr;
387
388         if (secure && bogus) {
389                 ast_debug(2, "Query '%p': Could not set result information, it can not be both secure and bogus\n",
390                         query);
391                 return -1;
392         }
393
394         if (ast_strlen_zero(canonical)) {
395                 ast_debug(2, "Query '%p': Could not set result information since no canonical name was provided\n",
396                         query);
397                 return -1;
398         }
399
400         if (!answer) {
401                 answer = "";
402                 answer_size = 0;
403                 ast_debug(2, "Query '%p': Assuming zero-sized answer on NULL input\n", query);
404         }
405
406         ast_dns_result_free(query->result);
407
408         query->result = ast_calloc(1, sizeof(*query->result) + strlen(canonical) + 1 + answer_size);
409         if (!query->result) {
410                 return -1;
411         }
412
413         query->result->secure = secure;
414         query->result->bogus = bogus;
415         query->result->rcode = rcode;
416
417         buf_ptr = query->result->buf;
418         strcpy(buf_ptr, canonical); /* SAFE */
419         query->result->canonical = buf_ptr;
420
421         buf_ptr += strlen(canonical) + 1;
422         memcpy(buf_ptr, answer, answer_size); /* SAFE */
423         query->result->answer = buf_ptr;
424         query->result->answer_size = answer_size;
425
426         return 0;
427 }
428
429 static struct ast_dns_record *generic_record_alloc(struct ast_dns_query *query, const char *data, const size_t size)
430 {
431         struct ast_dns_record *record;
432
433         record = ast_calloc(1, sizeof(*record) + size);
434         if (!record) {
435                 return NULL;
436         }
437
438         record->data_ptr = record->data;
439
440         return record;
441 }
442
443 typedef struct ast_dns_record *(*dns_alloc_fn)(struct ast_dns_query *query, const char *data, const size_t size);
444
445 static dns_alloc_fn dns_alloc_table [] = {
446         [T_NAPTR] = dns_naptr_alloc,
447         [T_SRV] = dns_srv_alloc,
448 };
449
450 static struct ast_dns_record *allocate_dns_record(int rr_type, struct ast_dns_query *query, const char *data, const size_t size)
451 {
452         dns_alloc_fn allocator = dns_alloc_table[rr_type] ?: generic_record_alloc;
453
454         return allocator(query, data, size);
455 }
456
457 int ast_dns_resolver_add_record(struct ast_dns_query *query, int rr_type, int rr_class, int ttl, const char *data, const size_t size)
458 {
459         struct ast_dns_record *record;
460
461         if (rr_type < 0) {
462                 ast_debug(2, "Query '%p': Could not add record, invalid resource record type '%d'\n",
463                         query, rr_type);
464                 return -1;
465         } else if (rr_type > 65536) {
466                 ast_debug(2, "Query '%p': Could not add record, resource record type '%d' exceeds maximum\n",
467                         query, rr_type);
468                 return -1;
469         } else if (rr_class < 0) {
470                 ast_debug(2, "Query '%p': Could not add record, invalid resource record class '%d'\n",
471                         query, rr_class);
472                 return -1;
473         } else if (rr_class > 65536) {
474                 ast_debug(2, "Query '%p': Could not add record, resource record class '%d' exceeds maximum\n",
475                         query, rr_class);
476                 return -1;
477         } else if (ttl < 0) {
478                 ast_debug(2, "Query '%p': Could not add record, invalid TTL '%d'\n",
479                         query, ttl);
480                 return -1;
481         } else if (!data || !size) {
482                 ast_debug(2, "Query '%p': Could not add record, no data specified\n",
483                         query);
484                 return -1;
485         } else if (!query->result) {
486                 ast_debug(2, "Query '%p': No result was set on the query, thus records can not be added\n",
487                         query);
488                 return -1;
489         }
490
491         record = allocate_dns_record(rr_type, query, data, size);
492         if (!record) {
493                 return -1;
494         }
495
496         record->rr_type = rr_type;
497         record->rr_class = rr_class;
498         record->ttl = ttl;
499         record->data_len = size;
500         memcpy(record->data_ptr, data, size);
501
502         AST_LIST_INSERT_TAIL(&query->result->records, record, list);
503
504         return 0;
505 }
506
507 typedef void (*dns_sort_fn)(struct ast_dns_result *result);
508
509 static dns_sort_fn dns_sort_table [] = {
510         [T_NAPTR] = dns_naptr_sort,
511         [T_SRV] = dns_srv_sort,
512 };
513
514 static void sort_result(int rr_type, struct ast_dns_result *result)
515 {
516         if (dns_sort_table[rr_type]) {
517                 dns_sort_table[rr_type](result);
518         }
519 }
520
521 void ast_dns_resolver_completed(struct ast_dns_query *query)
522 {
523         sort_result(ast_dns_query_get_rr_type(query), query->result);
524
525         query->callback(query);
526 }
527
528 static void dns_shutdown(void)
529 {
530         if (sched) {
531                 ast_sched_context_destroy(sched);
532                 sched = NULL;
533         }
534 }
535
536 int ast_dns_resolver_register(struct ast_dns_resolver *resolver)
537 {
538         struct ast_dns_resolver *iter;
539         int inserted = 0;
540
541         if (!resolver) {
542                 return -1;
543         } else if (ast_strlen_zero(resolver->name)) {
544                 ast_log(LOG_ERROR, "Registration of DNS resolver failed as it does not have a name\n");
545                 return -1;
546         } else if (!resolver->resolve) {
547                 ast_log(LOG_ERROR, "DNS resolver '%s' does not implement the resolve callback which is required\n",
548                         resolver->name);
549                 return -1;
550         } else if (!resolver->cancel) {
551                 ast_log(LOG_ERROR, "DNS resolver '%s' does not implement the cancel callback which is required\n",
552                         resolver->name);
553                 return -1;
554         }
555
556         AST_RWLIST_WRLOCK(&resolvers);
557
558         /* On the first registration of a resolver start a scheduler for recurring queries */
559         if (AST_LIST_EMPTY(&resolvers) && !sched) {
560                 sched = ast_sched_context_create();
561                 if (!sched) {
562                         ast_log(LOG_ERROR, "DNS resolver '%s' could not be registered: Failed to create scheduler for recurring DNS queries\n",
563                                 resolver->name);
564                         AST_RWLIST_UNLOCK(&resolvers);
565                         return -1;
566                 }
567
568                 if (ast_sched_start_thread(sched)) {
569                         ast_log(LOG_ERROR, "DNS resolver '%s' could not be registered: Failed to start thread for recurring DNS queries\n",
570                                 resolver->name);
571                         dns_shutdown();
572                         AST_RWLIST_UNLOCK(&resolvers);
573                         return -1;
574                 }
575
576                 ast_register_cleanup(dns_shutdown);
577         }
578
579         AST_LIST_TRAVERSE(&resolvers, iter, next) {
580                 if (!strcmp(iter->name, resolver->name)) {
581                         ast_log(LOG_ERROR, "A DNS resolver with the name '%s' is already registered\n", resolver->name);
582                         AST_RWLIST_UNLOCK(&resolvers);
583                         return -1;
584                 }
585         }
586
587         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&resolvers, iter, next) {
588                 if (iter->priority > resolver->priority) {
589                         AST_RWLIST_INSERT_BEFORE_CURRENT(resolver, next);
590                         inserted = 1;
591                         break;
592                 }
593         }
594         AST_RWLIST_TRAVERSE_SAFE_END;
595
596         if (!inserted) {
597                 AST_RWLIST_INSERT_TAIL(&resolvers, resolver, next);
598         }
599
600         AST_RWLIST_UNLOCK(&resolvers);
601
602         ast_verb(2, "Registered DNS resolver '%s' with priority '%d'\n", resolver->name, resolver->priority);
603
604         return 0;
605 }
606
607 void ast_dns_resolver_unregister(struct ast_dns_resolver *resolver)
608 {
609         struct ast_dns_resolver *iter;
610
611         if (!resolver) {
612                 return;
613         }
614
615         AST_RWLIST_WRLOCK(&resolvers);
616         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&resolvers, iter, next) {
617                 if (resolver == iter) {
618                         AST_RWLIST_REMOVE_CURRENT(next);
619                         break;
620                 }
621         }
622         AST_RWLIST_TRAVERSE_SAFE_END;
623         AST_RWLIST_UNLOCK(&resolvers);
624
625         ast_verb(2, "Unregistered DNS resolver '%s'\n", resolver->name);
626 }
627
628 char *dns_find_record(const char *record, size_t record_size, const char *response, size_t response_size)
629 {
630         size_t remaining_size = response_size;
631         const char *search_base = response;
632         char *record_offset;
633
634         while (1) {
635                 record_offset = memchr(search_base, record[0], remaining_size);
636
637                 ast_assert(record_offset != NULL);
638                 ast_assert(search_base + remaining_size - record_offset >= record_size);
639
640                 if (!memcmp(record_offset, record, record_size)) {
641                         return record_offset;
642                 }
643
644                 remaining_size -= record_offset - search_base;
645                 search_base = record_offset + 1;
646         }
647 }
648
649 int dns_parse_short(unsigned char *cur, uint16_t *val)
650 {
651         /* This assignment takes a big-endian 16-bit value and stores it in the
652          * machine's native byte order. Using this method allows us to avoid potential
653          * alignment issues in case the order is not on a short-addressable boundary.
654          * See http://commandcenter.blogspot.com/2012/04/byte-order-fallacy.html for
655          * more information
656          */
657         *val = (cur[1] << 0) | (cur[0] << 8);
658         return sizeof(*val);
659 }
660
661 int dns_parse_string(char *cur, uint8_t *size, char **val)
662 {
663         *size = *cur++;
664         *val = cur;
665         return *size + 1;
666 }