Code

The "-e" option now accepts a comma-delimited list of expected status
[nagiosplug.git] / plugins / check_dns.c
1 /*****************************************************************************
2
3 * Nagios check_dns plugin
4
5 * License: GPL
6 * Copyright (c) 2000-2008 Nagios Plugins Development 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
15 * will not be picked up by this plugin
16
17
18 * This program is free software: you can redistribute it and/or modify
19 * it under the terms of the GNU General Public License as published by
20 * the Free Software Foundation, either version 3 of the License, or
21 * (at your option) any later version.
22
23 * This program is distributed in the hope that it will be useful,
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
26 * GNU General Public License for more details.
27
28 * You should have received a copy of the GNU General Public License
29 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
30
31 * $Id$
32
33 *****************************************************************************/
35 const char *progname = "check_dns";
36 const char *revision = "$Revision$";
37 const char *copyright = "2000-2008";
38 const char *email = "nagiosplug-devel@lists.sourceforge.net";
40 #include "common.h"
41 #include "utils.h"
42 #include "utils_base.h"
43 #include "netutils.h"
44 #include "runcmd.h"
46 int process_arguments (int, char **);
47 int validate_arguments (void);
48 int error_scan (char *);
49 void print_help (void);
50 void print_usage (void);
52 #define ADDRESS_LENGTH 256
53 char query_address[ADDRESS_LENGTH] = "";
54 char dns_server[ADDRESS_LENGTH] = "";
55 char ptr_server[ADDRESS_LENGTH] = "";
56 int verbose = FALSE;
57 char **expected_address = NULL;
58 int expected_address_cnt = 0;
60 int expect_authority = FALSE;
61 thresholds *time_thresholds = NULL;
63 static int
64 qstrcmp(const void *p1, const void *p2)
65 {
66         /* The actual arguments to this function are "pointers to
67            pointers to char", but strcmp() arguments are "pointers
68            to char", hence the following cast plus dereference */
69         return strcmp(* (char * const *) p1, * (char * const *) p2);
70 }
73 int
74 main (int argc, char **argv)
75 {
76   char *command_line = NULL;
77   char input_buffer[MAX_INPUT_BUFFER];
78   char *address = NULL; /* comma seperated str with addrs/ptrs (sorted) */
79   char **addresses = NULL;
80   int n_addresses = 0;
81   char *msg = NULL;
82   char *temp_buffer = NULL;
83   int non_authoritative = FALSE;
84   int result = STATE_UNKNOWN;
85   double elapsed_time;
86   long microsec;
87   struct timeval tv;
88   int multi_address;
89   int parse_address = FALSE; /* This flag scans for Address: but only after Name: */
90   output chld_out, chld_err;
91   size_t i;
93   setlocale (LC_ALL, "");
94   bindtextdomain (PACKAGE, LOCALEDIR);
95   textdomain (PACKAGE);
97   /* Set signal handling and alarm */
98   if (signal (SIGALRM, popen_timeout_alarm_handler) == SIG_ERR) {
99     usage_va(_("Cannot catch SIGALRM"));
100   }
102   /* Parse extra opts if any */
103   argv=np_extra_opts (&argc, argv, progname);
105   if (process_arguments (argc, argv) == ERROR) {
106     usage_va(_("Could not parse arguments"));
107   }
109   /* get the command to run */
110   asprintf (&command_line, "%s %s %s", NSLOOKUP_COMMAND, query_address, dns_server);
112   alarm (timeout_interval);
113   gettimeofday (&tv, NULL);
115   if (verbose)
116     printf ("%s\n", command_line);
118   /* run the command */
119   if((np_runcmd(command_line, &chld_out, &chld_err, 0)) != 0) {
120     msg = (char *)_("nslookup returned an error status");
121     result = STATE_WARNING;
122   }
124   /* scan stdout */
125   for(i = 0; i < chld_out.lines; i++) {
126     if (addresses == NULL)  
127       addresses = malloc(sizeof(*addresses)*10);
128     else if (!(n_addresses % 10))
129       addresses = realloc(addresses,sizeof(*addresses) * (n_addresses + 10));
131     if (verbose)
132       puts(chld_out.line[i]);
134     if (strstr (chld_out.line[i], ".in-addr.arpa")) {
135       if ((temp_buffer = strstr (chld_out.line[i], "name = ")))
136         addresses[n_addresses++] = strdup (temp_buffer + 7);
137       else {
138         msg = (char *)_("Warning plugin error");
139         result = STATE_WARNING;
140       }
141     }
143     /* the server is responding, we just got the host name... */
144     if (strstr (chld_out.line[i], "Name:"))
145       parse_address = TRUE;
146     else if (parse_address == TRUE && (strstr (chld_out.line[i], "Address:") ||
147              strstr (chld_out.line[i], "Addresses:"))) {
148       temp_buffer = index (chld_out.line[i], ':');
149       temp_buffer++;
151       /* Strip leading spaces */
152       for (; *temp_buffer != '\0' && *temp_buffer == ' '; temp_buffer++)
153         /* NOOP */;
155       strip(temp_buffer);
156       if (temp_buffer==NULL || strlen(temp_buffer)==0) {
157         die (STATE_CRITICAL,
158              _("DNS CRITICAL - '%s' returned empty host name string\n"),
159              NSLOOKUP_COMMAND);
160       }
162       addresses[n_addresses++] = strdup(temp_buffer);
163     }
164     else if (strstr (chld_out.line[i], _("Non-authoritative answer:"))) {
165       non_authoritative = TRUE;
166     }
169     result = error_scan (chld_out.line[i]);
170     if (result != STATE_OK) {
171       msg = strchr (chld_out.line[i], ':');
172       if(msg) msg++;
173       break;
174     }
175   }
177   /* scan stderr */
178   for(i = 0; i < chld_err.lines; i++) {
179     if (verbose)
180       puts(chld_err.line[i]);
182     if (error_scan (chld_err.line[i]) != STATE_OK) {
183       result = max_state (result, error_scan (chld_err.line[i]));
184       msg = strchr(input_buffer, ':');
185       if(msg) msg++;
186     }
187   }
189   if (addresses) {
190     int i,slen;
191     char *adrp;
192     qsort(addresses, n_addresses, sizeof(*addresses), qstrcmp);
193     for(i=0, slen=1; i < n_addresses; i++) {
194       slen += strlen(addresses[i])+1;
195     }
196     adrp = address = malloc(slen);
197     for(i=0; i < n_addresses; i++) {
198       if (i) *adrp++ = ',';
199       strcpy(adrp, addresses[i]);
200       adrp += strlen(addresses[i]);
201     }
202     *adrp = 0;
203   } else
204     die (STATE_CRITICAL,
205          _("DNS CRITICAL - '%s' msg parsing exited with no address\n"),
206          NSLOOKUP_COMMAND);
208   /* compare to expected address */
209   if (result == STATE_OK && expected_address_cnt > 0) {
210     result = STATE_CRITICAL;
211     temp_buffer = "";
212     for (i=0; i<expected_address_cnt; i++) {
213       /* check if we get a match and prepare an error string */
214       if (strcmp(address, expected_address[i]) == 0) result = STATE_OK;
215       asprintf(&temp_buffer, "%s%s; ", temp_buffer, expected_address[i]);
216     }
217     if (result == STATE_CRITICAL) {
218       /* Strip off last semicolon... */
219       temp_buffer[strlen(temp_buffer)-2] = '\0';
220       asprintf(&msg, _("expected '%s' but got '%s'"), temp_buffer, address);
221     }
222   }
224   /* check if authoritative */
225   if (result == STATE_OK && expect_authority && non_authoritative) {
226     result = STATE_CRITICAL;
227     asprintf(&msg, _("server %s is not authoritative for %s"), dns_server, query_address);
228   }
230   microsec = deltime (tv);
231   elapsed_time = (double)microsec / 1.0e6;
233   if (result == STATE_OK) {
234     if (strchr (address, ',') == NULL)
235       multi_address = FALSE;
236     else
237       multi_address = TRUE;
239     result = get_status(elapsed_time, time_thresholds);
240     if (result == STATE_OK) {
241       printf ("DNS %s: ", _("OK"));
242     } else if (result == STATE_WARNING) {
243       printf ("DNS %s: ", _("WARNING"));
244     } else if (result == STATE_CRITICAL) {
245       printf ("DNS %s: ", _("CRITICAL"));
246     }
247     printf (ngettext("%.3f second response time", "%.3f seconds response time", elapsed_time), elapsed_time);
248     printf (_(". %s returns %s"), query_address, address);
249     printf ("|%s\n", fperfdata ("time", elapsed_time, "s", FALSE, 0, FALSE, 0, TRUE, 0, FALSE, 0));
250   }
251   else if (result == STATE_WARNING)
252     printf (_("DNS WARNING - %s\n"),
253             !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);
254   else if (result == STATE_CRITICAL)
255     printf (_("DNS CRITICAL - %s\n"),
256             !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);
257   else
258     printf (_("DNS UNKNOW - %s\n"),
259             !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);
261   return result;
266 int
267 error_scan (char *input_buffer)
270   /* the DNS lookup timed out */
271   if (strstr (input_buffer, _("Note: nslookup is deprecated and may be removed from future releases.")) ||
272       strstr (input_buffer, _("Consider using the `dig' or `host' programs instead.  Run nslookup with")) ||
273       strstr (input_buffer, _("the `-sil[ent]' option to prevent this message from appearing.")))
274     return STATE_OK;
276   /* DNS server is not running... */
277   else if (strstr (input_buffer, "No response from server"))
278     die (STATE_CRITICAL, _("No response from DNS %s\n"), dns_server);
280   /* Host name is valid, but server doesn't have records... */
281   else if (strstr (input_buffer, "No records"))
282     die (STATE_CRITICAL, _("DNS %s has no records\n"), dns_server);
284   /* Connection was refused */
285   else if (strstr (input_buffer, "Connection refused") ||
286      strstr (input_buffer, "Couldn't find server") ||
287            strstr (input_buffer, "Refused") ||
288            (strstr (input_buffer, "** server can't find") &&
289             strstr (input_buffer, ": REFUSED")))
290     die (STATE_CRITICAL, _("Connection to DNS %s was refused\n"), dns_server);
292   /* Query refused (usually by an ACL in the namserver) */ 
293   else if (strstr (input_buffer, "Query refused"))
294     die (STATE_CRITICAL, _("Query was refused by DNS server at %s\n"), dns_server);
296   /* No information (e.g. nameserver IP has two PTR records) */
297   else if (strstr (input_buffer, "No information"))
298     die (STATE_CRITICAL, _("No information returned by DNS server at %s\n"), dns_server);
300   /* Host or domain name does not exist */
301   else if (strstr (input_buffer, "Non-existent") ||
302            strstr (input_buffer, "** server can't find") ||
303      strstr (input_buffer,"NXDOMAIN"))
304     die (STATE_CRITICAL, _("Domain %s was not found by the server\n"), query_address);
306   /* Network is unreachable */
307   else if (strstr (input_buffer, "Network is unreachable"))
308     die (STATE_CRITICAL, _("Network is unreachable\n"));
310   /* Internal server failure */
311   else if (strstr (input_buffer, "Server failure"))
312     die (STATE_CRITICAL, _("DNS failure for %s\n"), dns_server);
314   /* Request error or the DNS lookup timed out */
315   else if (strstr (input_buffer, "Format error") ||
316            strstr (input_buffer, "Timed out"))
317     return STATE_WARNING;
319   return STATE_OK;
324 /* process command-line arguments */
325 int
326 process_arguments (int argc, char **argv)
328   int c;
329   char *warning = NULL;
330   char *critical = NULL;
332   int opt_index = 0;
333   static struct option long_opts[] = {
334     {"help", no_argument, 0, 'h'},
335     {"version", no_argument, 0, 'V'},
336     {"verbose", no_argument, 0, 'v'},
337     {"timeout", required_argument, 0, 't'},
338     {"hostname", required_argument, 0, 'H'},
339     {"server", required_argument, 0, 's'},
340     {"reverse-server", required_argument, 0, 'r'},
341     {"expected-address", required_argument, 0, 'a'},
342     {"expect-authority", no_argument, 0, 'A'},
343     {"warning", no_argument, 0, 'w'},
344     {"critical", no_argument, 0, 'c'},
345     {0, 0, 0, 0}
346   };
348   if (argc < 2)
349     return ERROR;
351   for (c = 1; c < argc; c++)
352     if (strcmp ("-to", argv[c]) == 0)
353       strcpy (argv[c], "-t");
355   while (1) {
356     c = getopt_long (argc, argv, "hVvAt:H:s:r:a:w:c:", long_opts, &opt_index);
358     if (c == -1 || c == EOF)
359       break;
361     switch (c) {
362     case 'h': /* help */
363       print_help ();
364       exit (STATE_OK);
365     case 'V': /* version */
366       print_revision (progname, revision);
367       exit (STATE_OK);
368     case 'v': /* version */
369       verbose = TRUE;
370       break;
371     case 't': /* timeout period */
372       timeout_interval = atoi (optarg);
373       break;
374     case 'H': /* hostname */
375       if (strlen (optarg) >= ADDRESS_LENGTH)
376         die (STATE_UNKNOWN, _("Input buffer overflow\n"));
377       strcpy (query_address, optarg);
378       break;
379     case 's': /* server name */
380       /* TODO: this host_or_die check is probably unnecessary.
381        * Better to confirm nslookup response matches */
382       host_or_die(optarg);
383       if (strlen (optarg) >= ADDRESS_LENGTH)
384         die (STATE_UNKNOWN, _("Input buffer overflow\n"));
385       strcpy (dns_server, optarg);
386       break;
387     case 'r': /* reverse server name */
388       /* TODO: Is this host_or_die necessary? */
389       host_or_die(optarg);
390       if (strlen (optarg) >= ADDRESS_LENGTH)
391         die (STATE_UNKNOWN, _("Input buffer overflow\n"));
392       strcpy (ptr_server, optarg);
393       break;
394     case 'a': /* expected address */
395       if (strlen (optarg) >= ADDRESS_LENGTH)
396         die (STATE_UNKNOWN, _("Input buffer overflow\n"));
397       expected_address = (char **)realloc(expected_address, (expected_address_cnt+1) * sizeof(char**));
398       expected_address[expected_address_cnt] = strdup(optarg);
399       expected_address_cnt++;
400       break;
401     case 'A': /* expect authority */
402       expect_authority = TRUE;
403       break;
404     case 'w':
405       warning = optarg;
406       break;
407     case 'c':
408       critical = optarg;
409       break;
410     default: /* args not parsable */
411       usage5();
412     }
413   }
415   c = optind;
416   if (strlen(query_address)==0 && c<argc) {
417     if (strlen(argv[c])>=ADDRESS_LENGTH)
418       die (STATE_UNKNOWN, _("Input buffer overflow\n"));
419     strcpy (query_address, argv[c++]);
420   }
422   if (strlen(dns_server)==0 && c<argc) {
423     /* TODO: See -s option */
424     host_or_die(argv[c]);
425     if (strlen(argv[c]) >= ADDRESS_LENGTH)
426       die (STATE_UNKNOWN, _("Input buffer overflow\n"));
427     strcpy (dns_server, argv[c++]);
428   }
430   set_thresholds(&time_thresholds, warning, critical);
432   return validate_arguments ();
436 int
437 validate_arguments ()
439   if (query_address[0] == 0)
440     return ERROR;
442   return OK;
446 void
447 print_help (void)
449   print_revision (progname, revision);
451   printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
452   printf (COPYRIGHT, copyright, email);
454   printf ("%s\n", _("This plugin uses the nslookup program to obtain the IP address for the given host/domain query."));
455   printf ("%s\n", _("An optional DNS server to use may be specified."));
456   printf ("%s\n", _("If no DNS server is specified, the default server(s) specified in /etc/resolv.conf will be used."));
458   printf ("\n\n");
460   print_usage ();
462   printf (_(UT_HELP_VRSN));
463   printf (_(UT_EXTRA_OPTS));
465   printf (" -H, --hostname=HOST\n");
466   printf ("    %s\n", _("The name or address you want to query"));
467   printf (" -s, --server=HOST\n");
468   printf ("    %s\n", _("Optional DNS server you want to use for the lookup"));
469   printf (" -a, --expected-address=IP-ADDRESS|HOST\n");
470   printf ("    %s\n", _("Optional IP-ADDRESS you expect the DNS server to return. HOST must end with"));
471   printf ("    %s\n", _("a dot (.). This option can be repeated multiple times (Returns OK if any"));
472   printf ("    %s\n", _("value match). If multiple addresses are returned at once, you have to match"));
473   printf ("    %s\n", _("the whole string of addresses separated with commas (sorted alphabetically)."));
474   printf (" -A, --expect-authority\n");
475   printf ("    %s\n", _("Optionally expect the DNS server to be authoritative for the lookup"));
476   printf (" -w, --warning=seconds\n");
477   printf ("    %s\n", _("Return warning if elapsed time exceeds value. Default off"));
478   printf (" -c, --critical=seconds\n");
479   printf ("    %s\n", _("Return critical if elapsed time exceeds value. Default off"));
481   printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
483 #ifdef NP_EXTRA_OPTS
484   printf ("\n");
485   printf ("%s\n", _("Notes:"));
486   printf (_(UT_EXTRA_OPTS_NOTES));
487 #endif
489   printf (_(UT_SUPPORT));
493 void
494 print_usage (void)
496   printf (_("Usage:"));
497   printf ("%s -H host [-s server] [-a expected-address] [-A] [-t timeout] [-w warn] [-c crit]\n", progname);