Code

Fixed reverse lookup damaged by previous commit
[nagiosplug.git] / plugins / check_dns.c
1 /******************************************************************************
2 *
3 * Nagios check_dns plugin
4 *
5 * License: GPL
6 * Copyright (c) 1999-2006 nagios-plugins team
7 *
8 * Last Modified: $Date$
9 *
10 * Description:
11 *
12 * This file contains the check_dns plugin
13 *
14 *  LIMITATION: nslookup on Solaris 7 can return output over 2 lines, which will not 
15 *  be picked up by this plugin
16 *
17 * License Information:
18 *
19 * This program is free software; you can redistribute it and/or modify
20 * it under the terms of the GNU General Public License as published by
21 * the Free Software Foundation; either version 2 of the License, or
22 * (at your option) any later version.
23 *
24 * This program is distributed in the hope that it will be useful,
25 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
27 * GNU General Public License for more details.
28 *
29 * You should have received a copy of the GNU General Public License
30 * along with this program; if not, write to the Free Software
31 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
32 *
33 *
34 * $Id$
35 *
36 ******************************************************************************/
38 const char *progname = "check_dns";
39 const char *revision = "$Revision$";
40 const char *copyright = "2000-2006";
41 const char *email = "nagiosplug-devel@lists.sourceforge.net";
43 #include "common.h"
44 #include "utils.h"
45 #include "utils_base.h"
46 #include "netutils.h"
47 #include "runcmd.h"
49 int process_arguments (int, char **);
50 int validate_arguments (void);
51 int error_scan (char *);
52 void print_help (void);
53 void print_usage (void);
55 #define ADDRESS_LENGTH 256
56 char query_address[ADDRESS_LENGTH] = "";
57 char dns_server[ADDRESS_LENGTH] = "";
58 char ptr_server[ADDRESS_LENGTH] = "";
59 int verbose = FALSE;
60 char expected_address[ADDRESS_LENGTH] = "";
61 int match_expected_address = FALSE;
62 int expect_authority = FALSE;
63 thresholds *time_thresholds = NULL;
65 static int
66 qstrcmp(const void *p1, const void *p2)
67 {
68         /* The actual arguments to this function are "pointers to
69            pointers to char", but strcmp() arguments are "pointers
70            to char", hence the following cast plus dereference */
71         return strcmp(* (char * const *) p1, * (char * const *) p2);
72 }
75 int
76 main (int argc, char **argv)
77 {
78   char *command_line = NULL;
79   char input_buffer[MAX_INPUT_BUFFER];
80   char *address = NULL; /* comma seperated str with addrs/ptrs (sorted) */
81   char **addresses = NULL;
82   int n_addresses = 0;
83   char *msg = NULL;
84   char *temp_buffer = NULL;
85   int non_authoritative = FALSE;
86   int result = STATE_UNKNOWN;
87   double elapsed_time;
88   long microsec;
89   struct timeval tv;
90   int multi_address;
91   int parse_address = FALSE; /* This flag scans for Address: but only after Name: */
92   output chld_out, chld_err;
93   size_t i;
95   setlocale (LC_ALL, "");
96   bindtextdomain (PACKAGE, LOCALEDIR);
97   textdomain (PACKAGE);
99   /* Set signal handling and alarm */
100   if (signal (SIGALRM, popen_timeout_alarm_handler) == SIG_ERR) {
101     usage_va(_("Cannot catch SIGALRM"));
102   }
104   if (process_arguments (argc, argv) == ERROR) {
105     usage_va(_("Could not parse arguments"));
106   }
108   /* get the command to run */
109   asprintf (&command_line, "%s %s %s", NSLOOKUP_COMMAND, query_address, dns_server);
111   alarm (timeout_interval);
112   gettimeofday (&tv, NULL);
114   if (verbose)
115     printf ("%s\n", command_line);
117   /* run the command */
118   if((np_runcmd(command_line, &chld_out, &chld_err, 0)) != 0) {
119     msg = (char *)_("nslookup returned an error status");
120     result = STATE_WARNING;
121   }
123   /* scan stdout */
124   for(i = 0; i < chld_out.lines; i++) {
125     if (addresses == NULL)  
126       addresses = malloc(sizeof(*addresses)*10);
127     else if (!(n_addresses % 10))
128       addresses = realloc(addresses,sizeof(*addresses) * (n_addresses + 10));
129  
130     if (verbose)
131       puts(chld_out.line[i]);
133     if (strstr (chld_out.line[i], ".in-addr.arpa")) {
134       if ((temp_buffer = strstr (chld_out.line[i], "name = ")))
135         addresses[n_addresses++] = strdup (temp_buffer + 7);
136       else {
137         msg = (char *)_("Warning plugin error");
138         result = STATE_WARNING;
139       }
140     }
142     /* the server is responding, we just got the host name... */
143     if (strstr (chld_out.line[i], "Name:"))
144       parse_address = TRUE;
145     else if (parse_address == TRUE && (strstr (chld_out.line[i], "Address:") ||
146              strstr (chld_out.line[i], "Addresses:"))) {
147       temp_buffer = index (chld_out.line[i], ':');
148       temp_buffer++;
150       /* Strip leading spaces */
151       for (; *temp_buffer != '\0' && *temp_buffer == ' '; temp_buffer++)
152         /* NOOP */;
153       
154       strip(temp_buffer);
155       if (temp_buffer==NULL || strlen(temp_buffer)==0) {
156         die (STATE_CRITICAL,
157              _("DNS CRITICAL - '%s' returned empty host name string\n"),
158              NSLOOKUP_COMMAND);
159       }
161       addresses[n_addresses++] = strdup(temp_buffer);
162     }
163     else if (strstr (chld_out.line[i], _("Non-authoritative answer:"))) {
164       non_authoritative = TRUE;
165     }
168     result = error_scan (chld_out.line[i]);
169     if (result != STATE_OK) {
170       msg = strchr (chld_out.line[i], ':');
171       if(msg) msg++;
172       break;
173     }
174   }
176   /* scan stderr */
177   for(i = 0; i < chld_err.lines; i++) {
178     if (verbose)
179       puts(chld_err.line[i]);
181     if (error_scan (chld_err.line[i]) != STATE_OK) {
182       result = max_state (result, error_scan (chld_err.line[i]));
183       msg = strchr(input_buffer, ':');
184       if(msg) msg++;
185     }
186   }
188   if (addresses) {
189     int i,slen;
190     char *adrp;
191     qsort(addresses, n_addresses, sizeof(*addresses), qstrcmp);
192     for(i=0, slen=1; i < n_addresses; i++) {
193       slen += strlen(addresses[i])+1;
194     }
195     adrp = address = malloc(slen);
196     for(i=0; i < n_addresses; i++) {
197       if (i) *adrp++ = ',';
198       strcpy(adrp, addresses[i]);
199       adrp += strlen(addresses[i]);
200     }
201     *adrp = 0;
202   } else
203     die (STATE_CRITICAL,
204          _("DNS CRITICAL - '%s' msg parsing exited with no address\n"),
205          NSLOOKUP_COMMAND);
207   /* compare to expected address */
208   if (result == STATE_OK && match_expected_address && strcmp(address, expected_address)) {
209     result = STATE_CRITICAL;
210     asprintf(&msg, _("expected '%s' but got '%s'"), expected_address, address);
211   }
213   /* check if authoritative */
214   if (result == STATE_OK && expect_authority && non_authoritative) {
215     result = STATE_CRITICAL;
216     asprintf(&msg, _("server %s is not authoritative for %s"), dns_server, query_address);
217   }
219   microsec = deltime (tv);
220   elapsed_time = (double)microsec / 1.0e6;
222   if (result == STATE_OK) {
223     if (strchr (address, ',') == NULL)
224       multi_address = FALSE;
225     else
226       multi_address = TRUE;
228     result = get_status(elapsed_time, time_thresholds);
229     if (result == STATE_OK) {
230       printf ("DNS %s: ", _("OK"));
231     } else if (result == STATE_WARNING) {
232       printf ("DNS %s: ", _("WARNING"));
233     } else if (result == STATE_CRITICAL) {
234       printf ("DNS %s: ", _("CRITICAL"));
235     }
236     printf (ngettext("%.3f second response time", "%.3f seconds response time", elapsed_time), elapsed_time);
237     printf (_(". %s returns %s"), query_address, address);
238     printf ("|%s\n", fperfdata ("time", elapsed_time, "s", FALSE, 0, FALSE, 0, TRUE, 0, FALSE, 0));
239   }
240   else if (result == STATE_WARNING)
241     printf (_("DNS WARNING - %s\n"),
242             !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);
243   else if (result == STATE_CRITICAL)
244     printf (_("DNS CRITICAL - %s\n"),
245             !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);
246   else
247     printf (_("DNS UNKNOW - %s\n"),
248             !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);
250   return result;
255 int
256 error_scan (char *input_buffer)
259   /* the DNS lookup timed out */
260   if (strstr (input_buffer, _("Note: nslookup is deprecated and may be removed from future releases.")) ||
261       strstr (input_buffer, _("Consider using the `dig' or `host' programs instead.  Run nslookup with")) ||
262       strstr (input_buffer, _("the `-sil[ent]' option to prevent this message from appearing.")))
263     return STATE_OK;
265   /* DNS server is not running... */
266   else if (strstr (input_buffer, "No response from server"))
267     die (STATE_CRITICAL, _("No response from DNS %s\n"), dns_server);
269   /* Host name is valid, but server doesn't have records... */
270   else if (strstr (input_buffer, "No records"))
271     die (STATE_CRITICAL, _("DNS %s has no records\n"), dns_server);
273   /* Connection was refused */
274   else if (strstr (input_buffer, "Connection refused") ||
275      strstr (input_buffer, "Couldn't find server") ||
276            strstr (input_buffer, "Refused") ||
277            (strstr (input_buffer, "** server can't find") &&
278             strstr (input_buffer, ": REFUSED")))
279     die (STATE_CRITICAL, _("Connection to DNS %s was refused\n"), dns_server);
281   /* Query refused (usually by an ACL in the namserver) */ 
282   else if (strstr (input_buffer, "Query refused"))
283     die (STATE_CRITICAL, _("Query was refused by DNS server at %s\n"), dns_server);
285   /* No information (e.g. nameserver IP has two PTR records) */
286   else if (strstr (input_buffer, "No information"))
287     die (STATE_CRITICAL, _("No information returned by DNS server at %s\n"), dns_server);
289   /* Host or domain name does not exist */
290   else if (strstr (input_buffer, "Non-existent") ||
291            strstr (input_buffer, "** server can't find") ||
292      strstr (input_buffer,"NXDOMAIN"))
293     die (STATE_CRITICAL, _("Domain %s was not found by the server\n"), query_address);
295   /* Network is unreachable */
296   else if (strstr (input_buffer, "Network is unreachable"))
297     die (STATE_CRITICAL, _("Network is unreachable\n"));
299   /* Internal server failure */
300   else if (strstr (input_buffer, "Server failure"))
301     die (STATE_CRITICAL, _("DNS failure for %s\n"), dns_server);
303   /* Request error or the DNS lookup timed out */
304   else if (strstr (input_buffer, "Format error") ||
305            strstr (input_buffer, "Timed out"))
306     return STATE_WARNING;
308   return STATE_OK;
313 /* process command-line arguments */
314 int
315 process_arguments (int argc, char **argv)
317   int c;
318   char *warning = NULL;
319   char *critical = NULL;
321   int opt_index = 0;
322   static struct option long_opts[] = {
323     {"help", no_argument, 0, 'h'},
324     {"version", no_argument, 0, 'V'},
325     {"verbose", no_argument, 0, 'v'},
326     {"timeout", required_argument, 0, 't'},
327     {"hostname", required_argument, 0, 'H'},
328     {"server", required_argument, 0, 's'},
329     {"reverse-server", required_argument, 0, 'r'},
330     {"expected-address", required_argument, 0, 'a'},
331     {"expect-authority", no_argument, 0, 'A'},
332     {"warning", no_argument, 0, 'w'},
333     {"critical", no_argument, 0, 'c'},
334     {0, 0, 0, 0}
335   };
337   if (argc < 2)
338     return ERROR;
340   for (c = 1; c < argc; c++)
341     if (strcmp ("-to", argv[c]) == 0)
342       strcpy (argv[c], "-t");
344   while (1) {
345     c = getopt_long (argc, argv, "hVvAt:H:s:r:a:w:c:", long_opts, &opt_index);
347     if (c == -1 || c == EOF)
348       break;
350     switch (c) {
351     case 'h': /* help */
352       print_help ();
353       exit (STATE_OK);
354     case 'V': /* version */
355       print_revision (progname, revision);
356       exit (STATE_OK);
357     case 'v': /* version */
358       verbose = TRUE;
359       break;
360     case 't': /* timeout period */
361       timeout_interval = atoi (optarg);
362       break;
363     case 'H': /* hostname */
364       if (strlen (optarg) >= ADDRESS_LENGTH)
365         die (STATE_UNKNOWN, _("Input buffer overflow\n"));
366       strcpy (query_address, optarg);
367       break;
368     case 's': /* server name */
369       /* TODO: this host_or_die check is probably unnecessary.
370        * Better to confirm nslookup response matches */
371       host_or_die(optarg);
372       if (strlen (optarg) >= ADDRESS_LENGTH)
373         die (STATE_UNKNOWN, _("Input buffer overflow\n"));
374       strcpy (dns_server, optarg);
375       break;
376     case 'r': /* reverse server name */
377       /* TODO: Is this host_or_die necessary? */
378       host_or_die(optarg);
379       if (strlen (optarg) >= ADDRESS_LENGTH)
380         die (STATE_UNKNOWN, _("Input buffer overflow\n"));
381       strcpy (ptr_server, optarg);
382       break;
383     case 'a': /* expected address */
384       if (strlen (optarg) >= ADDRESS_LENGTH)
385         die (STATE_UNKNOWN, _("Input buffer overflow\n"));
386       strcpy (expected_address, optarg);
387       match_expected_address = TRUE;
388       break;
389     case 'A': /* expect authority */
390       expect_authority = TRUE;
391       break;
392     case 'w':
393       warning = optarg;
394       break;
395     case 'c':
396       critical = optarg;
397       break;
398     default: /* args not parsable */
399       usage5();
400     }
401   }
403   c = optind;
404   if (strlen(query_address)==0 && c<argc) {
405     if (strlen(argv[c])>=ADDRESS_LENGTH)
406       die (STATE_UNKNOWN, _("Input buffer overflow\n"));
407     strcpy (query_address, argv[c++]);
408   }
410   if (strlen(dns_server)==0 && c<argc) {
411     /* TODO: See -s option */
412     host_or_die(argv[c]);
413     if (strlen(argv[c]) >= ADDRESS_LENGTH)
414       die (STATE_UNKNOWN, _("Input buffer overflow\n"));
415     strcpy (dns_server, argv[c++]);
416   }
418   set_thresholds(&time_thresholds, warning, critical);
420   return validate_arguments ();
424 int
425 validate_arguments ()
427   if (query_address[0] == 0)
428     return ERROR;
430   return OK;
434 void
435 print_help (void)
437   print_revision (progname, revision);
439   printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
440   printf (COPYRIGHT, copyright, email);
442   printf ("%s\n", _("This plugin uses the nslookup program to obtain the IP address for the given host/domain query."));
443   printf ("%s\n", _("An optional DNS server to use may be specified."));
444   printf ("%s\n", _("If no DNS server is specified, the default server(s) specified in /etc/resolv.conf will be used."));
445   
446   printf ("\n\n");
448   print_usage ();
449   
450   printf (_(UT_HELP_VRSN));
451   
452   printf (" -H, --hostname=HOST\n");
453   printf ("    %s\n", _("The name or address you want to query"));
454   printf (" -s, --server=HOST\n");
455   printf ("    %s\n", _("Optional DNS server you want to use for the lookup"));
456   printf (" -a, --expected-address=IP-ADDRESS|HOST\n");
457   printf ("    %s\n", _("Optional IP-ADDRESS you expect the DNS server to return. HOST must end with ."));
458   printf ("    %s\n", _("Multiple addresses can be separated with commas, and need to be sorted."));
459   printf (" -A, --expect-authority\n");
460   printf ("    %s\n", _("Optionally expect the DNS server to be authoritative for the lookup"));
461   printf (" -w, --warning=seconds\n");
462   printf ("    %s\n", _("Return warning if elapsed time exceeds value. Default off"));
463   printf (" -c, --critical=seconds\n");
464   printf ("    %s\n", _("Return critical if elapsed time exceeds value. Default off"));
466   printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
467   printf (_(UT_SUPPORT));
471 void
472 print_usage (void)
474   printf (_("Usage:"));
475   printf ("%s -H host [-s server] [-a expected-address] [-A] [-t timeout] [-w warn] [-c crit]\n", progname);