root/src/modules/dns.c

Revision f91ddca09660d8415b1bcdd88b20946e82b0ef62, 24.2 kB (checked in by Theo Schlossnagle <jesus@omniti.com>, 6 years ago)

propagate the cause for causal checks into all of the calls

  • Property mode set to 100644
Line 
1 /*
2  * Copyright (c) 2007, OmniTI Computer Consulting, Inc.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are
7  * met:
8  *
9  *     * Redistributions of source code must retain the above copyright
10  *       notice, this list of conditions and the following disclaimer.
11  *     * Redistributions in binary form must reproduce the above
12  *       copyright notice, this list of conditions and the following
13  *       disclaimer in the documentation and/or other materials provided
14  *       with the distribution.
15  *     * Neither the name OmniTI Computer Consulting, Inc. nor the names
16  *       of its contributors may be used to endorse or promote products
17  *       derived from this software without specific prior written
18  *       permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  */
32
33 #include "noit_defines.h"
34
35 #include <stdio.h>
36 #include <unistd.h>
37 #include <netdb.h>
38 #include <errno.h>
39 #include <assert.h>
40 #include <netinet/in.h>
41 #include <arpa/inet.h>
42
43 #include "noit_module.h"
44 #include "noit_check.h"
45 #include "noit_check_tools.h"
46 #include "utils/noit_log.h"
47 #include "utils/noit_atomic.h"
48 #include "udns/udns.h"
49
50 #define MAX_RR 256
51
52 static void eventer_dns_utm_fn(struct dns_ctx *, int, void *);
53 static int dns_eventer_callback(eventer_t, int, void *, struct timeval *);
54
55 static noit_log_stream_t nlerr = NULL;
56 static noit_log_stream_t nldeb = NULL;
57
58 static noit_hash_table dns_rtypes = NOIT_HASH_EMPTY;
59 static noit_hash_table dns_ctypes = NOIT_HASH_EMPTY;
60
61 static noit_hash_table dns_ctx_store = NOIT_HASH_EMPTY;
62 static pthread_mutex_t dns_ctx_store_lock;
63 typedef struct dns_ctx_handle {
64   char *ns;
65   struct dns_ctx *ctx;
66   noit_atomic32_t refcnt;
67   eventer_t e; /* evetner handling UDP traffic */
68   eventer_t timeout; /* the timeout managed by libudns */
69 } dns_ctx_handle_t;
70
71 static int cstring_cmp(const void *a, const void *b) {
72   return strcmp(*((const char **)a), *((const char **)b));
73 }
74
75 static dns_ctx_handle_t *default_ctx_handle = NULL;
76 static void dns_ctx_handle_free(void *vh) {
77   dns_ctx_handle_t *h = vh;
78   assert(h->timeout == NULL);
79   free(h->ns);
80   dns_close(h->ctx);
81   dns_free(h->ctx);
82 }
83 static dns_ctx_handle_t *dns_ctx_alloc(const char *ns) {
84   void *vh;
85   dns_ctx_handle_t *h = NULL;
86   pthread_mutex_lock(&dns_ctx_store_lock);
87   if(ns == NULL && default_ctx_handle != NULL) {
88     /* special case -- default context */
89     h = default_ctx_handle;
90     noit_atomic_inc32(&h->refcnt);
91     goto bail;
92   }
93   if(ns &&
94      noit_hash_retrieve(&dns_ctx_store, ns, strlen(ns), &vh)) {
95     h = (dns_ctx_handle_t *)vh;
96     noit_atomic_inc32(&h->refcnt);
97   }
98   else {
99     int failed = 0;
100     h = calloc(1, sizeof(*h));
101     h->ns = ns ? strdup(ns) : NULL;
102     h->ctx = dns_new(NULL);
103     if(dns_init(h->ctx, 0) != 0) failed++;
104     if(ns) {
105       if(dns_add_serv(h->ctx, NULL) < 0) failed++;
106       if(dns_add_serv(h->ctx, ns) < 0) failed++;
107     }
108     if(dns_open(h->ctx) < 0) failed++;
109     if(failed) {
110       noitL(nlerr, "dns_open failed\n");
111       free(h->ns);
112       free(h);
113       h = NULL;
114       goto bail;
115     }
116     dns_set_tmcbck(h->ctx, eventer_dns_utm_fn, h);
117     h->e = eventer_alloc();
118     h->e->mask = EVENTER_READ | EVENTER_EXCEPTION;
119     h->e->closure = h;
120     h->e->callback = dns_eventer_callback;
121     h->e->fd = dns_sock(h->ctx);
122     eventer_add(h->e);
123     h->refcnt = 1;
124     if(!ns)
125       default_ctx_handle = h;
126     else
127       noit_hash_store(&dns_ctx_store, h->ns, strlen(h->ns), h);
128   }
129  bail:
130   pthread_mutex_unlock(&dns_ctx_store_lock);
131   return h;
132 }
133 static void dns_ctx_release(dns_ctx_handle_t *h) {
134   if(h->ns == NULL) {
135     /* Special case for the default */
136     noit_atomic_dec32(&h->refcnt);
137     return;
138   }
139   pthread_mutex_lock(&dns_ctx_store_lock);
140   if(noit_atomic_dec32(&h->refcnt) == 0) {
141     /* I was the last one */
142     assert(noit_hash_delete(&dns_ctx_store, h->ns, strlen(h->ns),
143                             NULL, dns_ctx_handle_free));
144   }
145   pthread_mutex_unlock(&dns_ctx_store_lock);
146 }
147
148 static noit_hash_table active_events = NOIT_HASH_EMPTY;
149 static pthread_mutex_t active_events_lock;
150
151 typedef struct dns_check_info {
152   stats_t current;
153   int timed_out;
154   noit_module_t *self;
155   noit_check_t *check;
156   eventer_t timeout_event;
157   dns_ctx_handle_t *h;
158   char *error;
159   int nrr;
160   int sort;
161
162   /* These make up the query itself */
163   unsigned char dn[DNS_MAXDN];
164   enum dns_class query_ctype;
165   enum dns_type query_rtype;
166 } dns_check_info_t;
167
168 static int __isactive_ci(struct dns_check_info *ci) {
169   void *u;
170   int exists = 0;
171   pthread_mutex_lock(&active_events_lock);
172   if(noit_hash_retrieve(&active_events, (void *)&ci, sizeof(ci), &u))
173     exists = 1;
174   pthread_mutex_unlock(&active_events_lock);
175   return exists;
176 }
177 static void __activate_ci(struct dns_check_info *ci) {
178   struct dns_check_info **holder;
179   holder = calloc(1, sizeof(*holder));
180   *holder = ci;
181   pthread_mutex_lock(&active_events_lock);
182   assert(noit_hash_store(&active_events, (void *)holder, sizeof(*holder), ci));
183   pthread_mutex_unlock(&active_events_lock);
184 }
185 static void __deactivate_ci(struct dns_check_info *ci) {
186   pthread_mutex_lock(&active_events_lock);
187   assert(noit_hash_delete(&active_events, (void *)&ci, sizeof(ci), free, NULL));
188   pthread_mutex_unlock(&active_events_lock);
189 }
190
191 static void dns_check_log_results(struct dns_check_info *ci) {
192   struct timeval duration;
193   double rtt;
194
195   gettimeofday(&ci->current.whence, NULL);
196   sub_timeval(ci->current.whence, ci->check->last_fire_time, &duration);
197   rtt = duration.tv_sec * 1000.0 + duration.tv_usec / 1000.0;
198   ci->current.duration = rtt;
199
200   ci->current.state = (ci->error || ci->nrr == 0) ? NP_BAD : NP_GOOD;
201   ci->current.available = ci->timed_out ? NP_UNAVAILABLE : NP_AVAILABLE;
202   if(ci->error) {
203     ci->current.status = strdup(ci->error);
204   }
205   else if(!ci->current.status) {
206     char buff[48];
207     snprintf(buff, sizeof(buff), "%d %s",
208              ci->nrr, ci->nrr == 1 ? "record" : "records");
209     ci->current.status = strdup(buff);
210     noit_stats_set_metric(&ci->current, "rtt", METRIC_DOUBLE,
211                           ci->timed_out ? NULL : &rtt);
212   }
213
214   noit_check_set_stats(ci->self, ci->check, &ci->current);
215   if(ci->error) free(ci->error);
216   if(ci->current.status) free(ci->current.status);
217   ci->error = NULL;
218   memset(&ci->current, 0, sizeof(ci->current));
219 }
220
221 static int dns_interpolate_inaddr_arpa(char *buff, int len, const char *ip) {
222   const char *b, *e;
223   char *o;
224   unsigned char dn[DNS_MAXDN];
225   int il;
226   struct {
227     struct in_addr addr;
228     struct in6_addr addr6;
229   } a;
230   /* This function takes a dot delimited string as input and
231    * reverses the parts split on dot.
232    */
233   if (dns_pton(AF_INET, ip, &a.addr) > 0) {
234     dns_a4todn(&a.addr, 0, dn, sizeof(dn));
235     dns_dntop(dn,buff,len);
236     return strlen(buff);
237   }
238   else if (dns_pton(AF_INET6, ip, &a.addr6) > 0) {
239     dns_a6todn(&a.addr6, 0, dn, sizeof(dn));
240     dns_dntop(dn,buff,len);
241     return strlen(buff);
242   }
243
244   o = buff;
245   il = strlen(ip);
246   if(len <= il) {
247     /* not enough room for ip and '\0' */
248     if(len > 0) buff[0] = '\0';
249     return 0;
250   }
251   e = ip + il;
252   b = e - 1;
253   while(b >= ip) {
254     const char *term;
255     while(b >= ip && *b != '.') b--;  /* Rewind to previous part */
256     term = b + 1; /* term is one ahead, we went past it */
257     if(term != e) memcpy(o, term, e - term); /* no sense in copying nothing */
258     o += e - term; /* advance the term length */
259     e = b;
260     b = e - 1;
261     if(e >= ip) *o++ = '.'; /* we must be at . */
262   }
263   *o = '\0';
264   assert((o - buff) == il);
265   return o - buff;
266 }
267 static int dns_interpolate_reverse_ip(char *buff, int len, const char *ip) {
268 #define IN4ADDRARPA_LEN 13 // strlen(".in-addr.arpa");
269 #define IN6ADDRARPA_LEN 9 // strlen(".ip6.arpa");
270   dns_interpolate_inaddr_arpa(buff,len,ip);
271   if(len > IN4ADDRARPA_LEN &&
272      !strcmp(buff+len-IN4ADDRARPA_LEN, ".in-addr.arpa"))
273     buff[len-IN4ADDRARPA_LEN] = '\0';
274   else if((len > IN6ADDRARPA_LEN) &&
275           !strcmp(buff+len-IN6ADDRARPA_LEN, ".ip6.arpa"))
276     buff[len-IN6ADDRARPA_LEN] = '\0';
277   return strlen(buff);
278 }
279
280 static int dns_module_init(noit_module_t *self) {
281   const struct dns_nameval *nv;
282   struct dns_ctx *pctx;
283   int i;
284   pthread_mutex_init(&dns_ctx_store_lock, NULL);
285   pthread_mutex_init(&active_events_lock, NULL);
286   /* HASH the rr types */
287   for(i=0, nv = dns_type_index(i); nv->name; nv = dns_type_index(++i))
288     noit_hash_store(&dns_rtypes,
289                     nv->name, strlen(nv->name),
290                     (void *)nv);
291   /* HASH the class types */
292   for(i=0, nv = dns_class_index(i); nv->name; nv = dns_class_index(++i))
293     noit_hash_store(&dns_ctypes,
294                     nv->name, strlen(nv->name),
295                     (void *)nv);
296
297   noit_check_interpolate_register_oper_fn("inaddrarpa",
298                                           dns_interpolate_inaddr_arpa);
299   noit_check_interpolate_register_oper_fn("reverseip",
300                                           dns_interpolate_reverse_ip);
301
302   if (dns_init(NULL, 0) < 0 || (pctx = dns_new(NULL)) == NULL) {
303     noitL(nlerr, "Unable to initialize dns subsystem\n");
304     return -1;
305   }
306   dns_free(pctx);
307   if(dns_ctx_alloc(NULL) == NULL) {
308     noitL(nlerr, "Error setting up default dns resolver context.\n");
309     return -1;
310   }
311   return 0;
312 }
313
314 static void dns_check_cleanup(noit_module_t *self, noit_check_t *check) {
315 }
316
317 static int dns_eventer_callback(eventer_t e, int mask, void *closure,
318                                 struct timeval *now) {
319   dns_ctx_handle_t *h = closure;
320   dns_ioevent(h->ctx, now->tv_sec);
321   return EVENTER_READ | EVENTER_EXCEPTION;
322 }
323
324 static int dns_check_timeout(eventer_t e, int mask, void *closure,
325                              struct timeval *now) {
326   struct dns_check_info *ci;
327   ci = closure;
328   ci->timeout_event = NULL;
329   ci->check->flags &= ~NP_RUNNING;
330   dns_check_log_results(ci);
331   __deactivate_ci(ci);
332   return 0;
333 }
334
335 static int dns_invoke_timeouts(eventer_t e, int mask, void *closure,
336                                struct timeval *now) {
337   dns_ctx_handle_t *h = closure;
338   dns_timeouts(h->ctx, 0, now->tv_sec);
339   return 0;
340 }
341 static void eventer_dns_utm_fn(struct dns_ctx *ctx, int timeout, void *data) {
342   dns_ctx_handle_t *h = data;
343   eventer_t e = NULL, newe = NULL;
344   if(ctx == NULL) e = eventer_remove(h->timeout);
345   else {
346     assert(h->ctx == ctx);
347     if(timeout < 0) e = eventer_remove(h->timeout);
348     else {
349       newe = eventer_alloc();
350       newe->mask = EVENTER_TIMER;
351       newe->callback = dns_invoke_timeouts;
352       newe->closure = h;
353       gettimeofday(&newe->whence, NULL);
354       newe->whence.tv_sec += timeout;
355     }
356   }
357   if(e) eventer_free(e);
358   if(newe) eventer_add(newe);
359   h->timeout = newe;
360 }
361
362 static char *encode_txt(char *dst, const unsigned char *src, int len) {
363   int i;
364   for(i=0; i<len; i++) {
365     if(src[i] >= 127 || src[i] <= 31) {
366       snprintf(dst, 4, "\\%02x", src[i]);
367       dst += 3;
368     }
369     else if(src[i] == '\\') {
370       *dst++ = '\\';
371       *dst++ = '\\';
372     }
373     else {
374       *dst++ = (char)src[i];
375     }
376   }
377   *dst = '\0';
378   return dst;
379 }
380
381 static void decode_rr(struct dns_check_info *ci, struct dns_parse *p,
382                       struct dns_rr *rr, char **output) {
383   char buff[DNS_MAXDN], *txt_str = buff, *c;
384   u_int32_t ttl, vu;
385   int32_t vs;
386   int totalsize;
387   const unsigned char *pkt = p->dnsp_pkt;
388   const unsigned char *end = p->dnsp_end;
389   const unsigned char *dptr = rr->dnsrr_dptr;
390   const unsigned char *dend = rr->dnsrr_dend;
391   unsigned char *dn = rr->dnsrr_dn;
392   const unsigned char *tmp;
393
394   /* Not interested unless it is the answer to my exact question */
395   if (!dns_dnequal(ci->dn, dn)) return;
396
397   if (!p->dnsp_rrl && !rr->dnsrr_dn[0] && rr->dnsrr_typ == DNS_T_OPT) {
398     /* We don't handle EDNS0 OPT records */
399     goto decode_err;
400   }
401   noitL(nldeb, "%s. %u %s %s\n", dns_dntosp(dn), rr->dnsrr_ttl,
402         dns_classname(rr->dnsrr_cls),
403         dns_typename(rr->dnsrr_typ));
404
405   ttl = rr->dnsrr_ttl;
406   noit_stats_set_metric(&ci->current, "ttl", METRIC_UINT32, &ttl);
407
408   switch(rr->dnsrr_typ) {
409    case DNS_T_A:
410     if (rr->dnsrr_dsz != 4) goto decode_err;
411     snprintf(buff, sizeof(buff), "%d.%d.%d.%d",
412              dptr[0], dptr[1], dptr[2], dptr[3]);
413     break;
414
415    case DNS_T_AAAA:
416     if (rr->dnsrr_dsz != 16) goto decode_err;
417     inet_ntop(AF_INET6, dptr, buff, sizeof(buff));
418     break;
419
420    case DNS_T_TXT:
421     totalsize = 0;
422     for(tmp = dptr; tmp < dend; totalsize += *tmp, tmp += *tmp + 1)
423       if(tmp + *tmp + 1 > dend) goto decode_err;
424     /* worst case: every character escaped + '\0' */
425     txt_str = alloca(totalsize * 3 + 1);
426     if(!txt_str) goto decode_err;
427     c = txt_str;
428     for(tmp = dptr; tmp < dend; tmp += *tmp + 1)
429       c = encode_txt(c, tmp+1, *tmp);
430     break;
431
432    case DNS_T_MX:
433     snprintf(buff, sizeof(buff), "%d ", dns_get16(dptr));
434     tmp = dptr + 2;
435     if(dns_getdn(pkt, &tmp, end, dn, DNS_MAXDN) <= 0 || tmp != dend)
436       goto decode_err;
437     dns_dntop(dn, buff + strlen(buff), sizeof(buff) - strlen(buff));
438     break;
439
440    case DNS_T_SOA:
441      if(dns_getdn(pkt, &dptr, end, dn, DNS_MAXDN) <= 0) goto decode_err;
442      dns_dntop(dn, buff, sizeof(buff));
443      noit_stats_set_metric(&ci->current, "name-server", METRIC_STRING, buff);
444      if(dns_getdn(pkt, &dptr, end, dn, DNS_MAXDN) <= 0) goto decode_err;
445      dns_dntop(dn, buff, sizeof(buff));
446      noit_stats_set_metric(&ci->current, "email-addr", METRIC_STRING, buff);
447      if(dptr + 5 * sizeof(u_int32_t) != dend) goto decode_err;
448      vu = dns_get32(dptr); dptr += sizeof(u_int32_t);
449      noit_stats_set_metric(&ci->current, "serial", METRIC_UINT32, &vu);
450      /* the serial is what we elect to store as the "answer" as text...
451       * because it rarely changes and that seems the most interesting thing
452       * to track change-log-style.
453       */
454      snprintf(buff, sizeof(buff), "%u", vu);
455      vs = dns_get32(dptr); dptr += sizeof(int32_t);
456      noit_stats_set_metric(&ci->current, "refresh", METRIC_UINT32, &vs);
457      vs = dns_get32(dptr); dptr += sizeof(int32_t);
458      noit_stats_set_metric(&ci->current, "retry", METRIC_UINT32, &vs);
459      vs = dns_get32(dptr); dptr += sizeof(int32_t);
460      noit_stats_set_metric(&ci->current, "expiry", METRIC_UINT32, &vs);
461      vs = dns_get32(dptr); dptr += sizeof(int32_t);
462      noit_stats_set_metric(&ci->current, "minimum", METRIC_UINT32, &vs);
463      break;
464
465    case DNS_T_CNAME:
466    case DNS_T_PTR:
467    case DNS_T_NS:
468    case DNS_T_MB:
469    case DNS_T_MD:
470    case DNS_T_MF:
471    case DNS_T_MG:
472    case DNS_T_MR:
473     if(dns_getdn(pkt, &dptr, end, dn, DNS_MAXDN) <= 0) goto decode_err;
474     dns_dntop(dn, buff, sizeof(buff));
475     break;
476
477    default:
478     break;
479   }
480   if(*output) {
481     int newlen = strlen(*output) + strlen(", ") + strlen(buff) + 1;
482     char *newstr;
483     newstr = malloc(newlen);
484     snprintf(newstr, newlen, "%s, %s", *output, buff);
485     free(*output);
486     *output = newstr;
487   }
488   else
489     *output = strdup(txt_str);
490   ci->nrr++;
491   return;
492
493  decode_err:
494   ci->error = strdup("RR decode error");
495   return;
496 }
497
498 static void dns_cb(struct dns_ctx *ctx, void *result, void *data) {
499   int r = dns_status(ctx);
500   int len, i;
501   struct dns_check_info *ci = data;
502   struct dns_parse p;
503   struct dns_rr rr;
504   unsigned nrr;
505   unsigned char dn[DNS_MAXDN];
506   const unsigned char *pkt, *cur, *end;
507   char *result_str[MAX_RR] = { NULL };
508   char *result_combined = NULL;
509
510   /* If out ci isn't active, we must have timed out already */
511   if(!__isactive_ci(ci)) {
512     if(result) free(result);
513     return;
514   }
515
516   ci->timed_out = 0;
517   /* If we don't have a result, explode */
518   if (!result) {
519     ci->error = strdup(dns_strerror(r));
520     goto cleanup;
521   }
522
523   /* Process the packet */
524   pkt = result; end = pkt + r; cur = dns_payload(pkt);
525   dns_getdn(pkt, &cur, end, dn, sizeof(dn));
526   dns_initparse(&p, NULL, pkt, cur, end);
527   p.dnsp_qcls = 0;
528   p.dnsp_qtyp = 0;
529   nrr = 0;
530
531   while((r = dns_nextrr(&p, &rr)) > 0) {
532     if (!dns_dnequal(dn, rr.dnsrr_dn)) continue;
533     if ((ci->query_ctype == DNS_C_ANY || ci->query_ctype == rr.dnsrr_cls) &&
534         (ci->query_rtype == DNS_T_ANY || ci->query_rtype == rr.dnsrr_typ))
535       ++nrr;
536     else if (rr.dnsrr_typ == DNS_T_CNAME && !nrr) {
537       if (dns_getdn(pkt, &rr.dnsrr_dptr, end,
538                     p.dnsp_dnbuf, sizeof(p.dnsp_dnbuf)) <= 0 ||
539           rr.dnsrr_dptr != rr.dnsrr_dend) {
540         ci->error = strdup("protocol error");
541         break;
542       }
543       else {
544         int32_t on = 1;
545         /* This actually updates what we're looking for */
546         dns_dntodn(p.dnsp_dnbuf, ci->dn, sizeof(dn));
547         noit_stats_set_metric(&ci->current, "cname", METRIC_INT32, &on);
548
549         /* Now follow the leader */
550         noitL(nldeb, "%s. CNAME %s.\n", dns_dntosp(dn),
551               dns_dntosp(p.dnsp_dnbuf));
552         dns_dntodn(p.dnsp_dnbuf, dn, sizeof(dn));
553         noitL(nldeb, " ---> '%s'\n", dns_dntosp(dn));
554       }
555     }
556   }
557   if (!r && !nrr) {
558     ci->error = strdup("no data");
559   }
560
561   dns_rewind(&p, NULL);
562   p.dnsp_qtyp = ci->query_rtype == DNS_T_ANY ? 0 : ci->query_rtype;
563   p.dnsp_qcls = ci->query_ctype == DNS_C_ANY ? 0 : ci->query_ctype;
564   while(dns_nextrr(&p, &rr) && ci->nrr < MAX_RR)
565     decode_rr(ci, &p, &rr, &result_str[ci->nrr]);
566   if(ci->sort)
567     qsort(result_str, ci->nrr, sizeof(*result_str), cstring_cmp);
568   /* calculate the length and allocate on the stack */
569   len = 0;
570   for(i=0; i<ci->nrr; i++) len += strlen(result_str[i]) + 2;
571   result_combined = alloca(len);
572   result_combined[0] = '\0';
573   /* string it together */
574   len = 0;
575   for(i=0; i<ci->nrr; i++) {
576     int slen;
577     if(i) { memcpy(result_combined + len, ", ", 2); len += 2; }
578     slen = strlen(result_str[i]);
579     memcpy(result_combined + len, result_str[i], slen);
580     len += slen;
581     result_combined[len] = '\0';
582     free(result_str[i]); /* free as we go */
583   }
584   noit_stats_set_metric(&ci->current, "answer", METRIC_STRING, result_combined);
585
586  cleanup:
587   if(result) free(result);
588   if(ci->timeout_event) {
589     eventer_t e = eventer_remove(ci->timeout_event);
590     ci->timeout_event = NULL;
591     if(e) eventer_free(e);
592   }
593   ci->check->flags &= ~NP_RUNNING;
594   dns_check_log_results(ci);
595   __deactivate_ci(ci);
596 }
597
598 static int dns_check_send(noit_module_t *self, noit_check_t *check,
599                           noit_check_t *cause) {
600   void *vnv_pair = NULL;
601   struct dns_nameval *nv_pair;
602   eventer_t newe;
603   struct timeval p_int, now;
604   struct dns_check_info *ci = check->closure;
605   const char *config_val;
606   const char *rtype = NULL;
607   const char *nameserver = NULL;
608   const char *want_sort = NULL;
609   const char *ctype = "IN";
610   const char *query = NULL;
611   char interpolated_nameserver[1024];
612   char interpolated_query[1024];
613   noit_hash_table check_attrs_hash = NOIT_HASH_EMPTY;
614
615   gettimeofday(&now, NULL);
616   memcpy(&check->last_fire_time, &now, sizeof(now));
617   ci->current.state = NP_BAD;
618   ci->current.available = NP_UNAVAILABLE;
619   ci->timed_out = 1;
620   ci->nrr = 0;
621   ci->sort = 1;
622
623   if(!strcmp(check->name, "in-addr.arpa") ||
624      (strlen(check->name) >= sizeof("::in-addr.arpa") - 1 &&
625       !strcmp(check->name + strlen(check->name) - sizeof("::in-addr.arpa") + 1,
626               "::in-addr.arpa"))) {
627     /* in-addr.arpa defaults:
628      *   nameserver to NULL
629      *   rtype to PTR
630      *   query to %[:inaddrarpa:target]
631      */
632     nameserver = NULL;
633     rtype = "PTR";
634     query = "%[:inaddrarpa:target_ip]";
635   }
636   else {
637     nameserver = "%[target_ip]";
638     rtype = "A";
639     query = "%[name]";
640   }
641 #define CONFIG_OVERRIDE(a) \
642   if(noit_hash_retr_str(check->config, #a, strlen(#a), \
643                         &config_val) && \
644      strlen(config_val) > 0) \
645     a = config_val
646   CONFIG_OVERRIDE(ctype);
647   CONFIG_OVERRIDE(nameserver);
648   CONFIG_OVERRIDE(rtype);
649   CONFIG_OVERRIDE(query);
650   CONFIG_OVERRIDE(want_sort);
651   if(nameserver && !strcmp(nameserver, "default")) nameserver = NULL;
652   if(want_sort && strcasecmp(want_sort, "on") && strcasecmp(want_sort, "true"))
653     ci->sort = 0;
654
655   noit_check_make_attrs(check, &check_attrs_hash);
656
657   if(nameserver) {
658     noit_check_interpolate(interpolated_nameserver,
659                            sizeof(interpolated_nameserver),
660                            nameserver,
661                            &check_attrs_hash, check->config);
662     nameserver = interpolated_nameserver;
663   }
664   if(query) {
665     noit_check_interpolate(interpolated_query,
666                            sizeof(interpolated_query),
667                            query,
668                            &check_attrs_hash, check->config);
669     query = interpolated_query;
670   }
671   noit_hash_destroy(&check_attrs_hash, NULL, NULL);
672
673   check->flags |= NP_RUNNING;
674   noitL(nldeb, "dns_check_send(%p,%s,%s,%s,%s,%s)\n",
675         self, check->target, nameserver ? nameserver : "default",
676         query ? query : "null", ctype, rtype);
677
678   __activate_ci(ci);
679   /* If this ci has a handle and it isn't the one we need,
680    * we should release it
681    */
682   if(ci->h &&
683      ((ci->h->ns == NULL && nameserver != NULL) ||
684       (ci->h->ns != NULL && nameserver == NULL) ||
685       (ci->h->ns && strcmp(ci->h->ns, nameserver)))) {
686     dns_ctx_release(ci->h);
687     ci->h = NULL;
688   }
689   /* use the cached one, unless we don't have one */
690   if(!ci->h) ci->h = dns_ctx_alloc(nameserver);
691   if(!ci->h) ci->error = strdup("bad nameserver");
692
693   /* Lookup out class */
694   if(!noit_hash_retrieve(&dns_ctypes, ctype, strlen(ctype),
695                          &vnv_pair)) {
696     if(ci->error) free(ci->error);
697     ci->error = strdup("bad class");
698   }
699   else {
700     nv_pair = (struct dns_nameval *)vnv_pair;
701     ci->query_ctype = nv_pair->val;
702   }
703   /* Lookup out rr type */
704   if(!noit_hash_retrieve(&dns_rtypes, rtype, strlen(rtype),
705                          &vnv_pair)) {
706     if(ci->error) free(ci->error);
707     ci->error = strdup("bad rr type");
708   }
709   else {
710     nv_pair = (struct dns_nameval *)vnv_pair;
711     ci->query_rtype = nv_pair->val;
712   }
713
714   if(!ci->error) {
715     /* Submit the query */
716     int abs;
717     if(!dns_ptodn(query, strlen(query), ci->dn, sizeof(ci->dn), &abs) ||
718        !dns_submit_dn(ci->h->ctx, ci->dn, ci->query_ctype, ci->query_rtype,
719                       abs | DNS_NOSRCH, NULL, dns_cb, ci)) {
720       ci->error = strdup("submission error");
721     }
722     else {
723       dns_timeouts(ci->h->ctx, -1, now.tv_sec);
724     }
725   }
726
727   /* we could have completed by now... if so, we've nothing to do */
728
729   if(!__isactive_ci(ci)) return 0;
730
731   if(ci->error) {
732     /* Errors here are easy, fail and avoid scheduling a timeout */
733     ci->check->flags &= ~NP_RUNNING;
734     dns_check_log_results(ci);
735     __deactivate_ci(ci);
736     return 0;
737   }
738
739   newe = eventer_alloc();
740   newe->mask = EVENTER_TIMER;
741   gettimeofday(&now, NULL);
742   p_int.tv_sec = check->timeout / 1000;
743   p_int.tv_usec = (check->timeout % 1000) * 1000;
744   add_timeval(now, p_int, &newe->whence);
745   newe->closure = ci;
746   newe->callback = dns_check_timeout;
747   ci->timeout_event = newe;
748   eventer_add(newe);
749
750   return 0;
751 }
752
753 static int dns_initiate_check(noit_module_t *self, noit_check_t *check,
754                               int once, noit_check_t *cause) {
755   struct dns_check_info *ci;
756   if(!check->closure)
757     check->closure = calloc(1, sizeof(struct dns_check_info));
758   ci = check->closure;
759   ci->check = check;
760   ci->self = self;
761   INITIATE_CHECK(dns_check_send, self, check, cause);
762   return 0;
763 }
764
765 static int dns_config(noit_module_t *self, noit_hash_table *options) {
766   return 0;
767 }
768
769 static int dns_onload(noit_image_t *self) {
770   nlerr = noit_log_stream_find("error/dns");
771   nldeb = noit_log_stream_find("debug/dns");
772   if(!nlerr) nlerr = noit_stderr;
773   if(!nldeb) nldeb = noit_debug;
774   eventer_name_callback("dns/dns_eventer_callback", dns_eventer_callback);
775   eventer_name_callback("dns/dns_check_timeout", dns_check_timeout);
776   eventer_name_callback("dns/dns_invoke_timeouts", dns_invoke_timeouts);
777   return 0;
778 }
779
780 #include "dns.xmlh"
781 noit_module_t dns = {
782   {
783     NOIT_MODULE_MAGIC,
784     NOIT_MODULE_ABI_VERSION,
785     "dns",
786     "DNS RR checker",
787     dns_xml_description,
788     dns_onload
789   },
790   dns_config,
791   dns_module_init,
792   dns_initiate_check,
793   dns_check_cleanup
794 };
795
Note: See TracBrowser for help on using the browser.