Back to index

nagios-plugins  1.4.16
check_dns.c
Go to the documentation of this file.
00001 /*****************************************************************************
00002 * 
00003 * Nagios check_dns plugin
00004 * 
00005 * License: GPL
00006 * Copyright (c) 2000-2008 Nagios Plugins Development Team
00007 * 
00008 * Description:
00009 * 
00010 * This file contains the check_dns plugin
00011 * 
00012 * LIMITATION: nslookup on Solaris 7 can return output over 2 lines, which
00013 * will not be picked up by this plugin
00014 * 
00015 * 
00016 * This program is free software: you can redistribute it and/or modify
00017 * it under the terms of the GNU General Public License as published by
00018 * the Free Software Foundation, either version 3 of the License, or
00019 * (at your option) any later version.
00020 * 
00021 * This program is distributed in the hope that it will be useful,
00022 * but WITHOUT ANY WARRANTY; without even the implied warranty of
00023 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00024 * GNU General Public License for more details.
00025 * 
00026 * You should have received a copy of the GNU General Public License
00027 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
00028 * 
00029 * 
00030 *****************************************************************************/
00031 
00032 const char *progname = "check_dns";
00033 const char *copyright = "2000-2008";
00034 const char *email = "nagiosplug-devel@lists.sourceforge.net";
00035 
00036 #include "common.h"
00037 #include "utils.h"
00038 #include "utils_base.h"
00039 #include "netutils.h"
00040 #include "runcmd.h"
00041 
00042 int process_arguments (int, char **);
00043 int validate_arguments (void);
00044 int error_scan (char *);
00045 void print_help (void);
00046 void print_usage (void);
00047 
00048 #define ADDRESS_LENGTH 256
00049 char query_address[ADDRESS_LENGTH] = "";
00050 char dns_server[ADDRESS_LENGTH] = "";
00051 char ptr_server[ADDRESS_LENGTH] = "";
00052 int verbose = FALSE;
00053 char **expected_address = NULL;
00054 int expected_address_cnt = 0;
00055 
00056 int expect_authority = FALSE;
00057 thresholds *time_thresholds = NULL;
00058 
00059 static int
00060 qstrcmp(const void *p1, const void *p2)
00061 {
00062        /* The actual arguments to this function are "pointers to
00063           pointers to char", but strcmp() arguments are "pointers
00064           to char", hence the following cast plus dereference */
00065        return strcmp(* (char * const *) p1, * (char * const *) p2);
00066 }
00067 
00068 
00069 int
00070 main (int argc, char **argv)
00071 {
00072   char *command_line = NULL;
00073   char input_buffer[MAX_INPUT_BUFFER];
00074   char *address = NULL; /* comma seperated str with addrs/ptrs (sorted) */
00075   char **addresses = NULL;
00076   int n_addresses = 0;
00077   char *msg = NULL;
00078   char *temp_buffer = NULL;
00079   int non_authoritative = FALSE;
00080   int result = STATE_UNKNOWN;
00081   double elapsed_time;
00082   long microsec;
00083   struct timeval tv;
00084   int multi_address;
00085   int parse_address = FALSE; /* This flag scans for Address: but only after Name: */
00086   output chld_out, chld_err;
00087   size_t i;
00088 
00089   setlocale (LC_ALL, "");
00090   bindtextdomain (PACKAGE, LOCALEDIR);
00091   textdomain (PACKAGE);
00092 
00093   /* Set signal handling and alarm */
00094   if (signal (SIGALRM, popen_timeout_alarm_handler) == SIG_ERR) {
00095     usage_va(_("Cannot catch SIGALRM"));
00096   }
00097 
00098   /* Parse extra opts if any */
00099   argv=np_extra_opts (&argc, argv, progname);
00100 
00101   if (process_arguments (argc, argv) == ERROR) {
00102     usage_va(_("Could not parse arguments"));
00103   }
00104 
00105   /* get the command to run */
00106   asprintf (&command_line, "%s %s %s", NSLOOKUP_COMMAND, query_address, dns_server);
00107 
00108   alarm (timeout_interval);
00109   gettimeofday (&tv, NULL);
00110 
00111   if (verbose)
00112     printf ("%s\n", command_line);
00113 
00114   /* run the command */
00115   if((np_runcmd(command_line, &chld_out, &chld_err, 0)) != 0) {
00116     msg = (char *)_("nslookup returned an error status");
00117     result = STATE_WARNING;
00118   }
00119 
00120   /* scan stdout */
00121   for(i = 0; i < chld_out.lines; i++) {
00122     if (addresses == NULL)
00123       addresses = malloc(sizeof(*addresses)*10);
00124     else if (!(n_addresses % 10))
00125       addresses = realloc(addresses,sizeof(*addresses) * (n_addresses + 10));
00126 
00127     if (verbose)
00128       puts(chld_out.line[i]);
00129 
00130     if (strstr (chld_out.line[i], ".in-addr.arpa")) {
00131       if ((temp_buffer = strstr (chld_out.line[i], "name = ")))
00132         addresses[n_addresses++] = strdup (temp_buffer + 7);
00133       else {
00134         msg = (char *)_("Warning plugin error");
00135         result = STATE_WARNING;
00136       }
00137     }
00138 
00139     /* the server is responding, we just got the host name... */
00140     if (strstr (chld_out.line[i], "Name:"))
00141       parse_address = TRUE;
00142     else if (parse_address == TRUE && (strstr (chld_out.line[i], "Address:") ||
00143              strstr (chld_out.line[i], "Addresses:"))) {
00144       temp_buffer = index (chld_out.line[i], ':');
00145       temp_buffer++;
00146 
00147       /* Strip leading spaces */
00148       for (; *temp_buffer != '\0' && *temp_buffer == ' '; temp_buffer++)
00149         /* NOOP */;
00150 
00151       strip(temp_buffer);
00152       if (temp_buffer==NULL || strlen(temp_buffer)==0) {
00153         die (STATE_CRITICAL,
00154              _("DNS CRITICAL - '%s' returned empty host name string\n"),
00155              NSLOOKUP_COMMAND);
00156       }
00157 
00158       addresses[n_addresses++] = strdup(temp_buffer);
00159     }
00160     else if (strstr (chld_out.line[i], _("Non-authoritative answer:"))) {
00161       non_authoritative = TRUE;
00162     }
00163 
00164 
00165     result = error_scan (chld_out.line[i]);
00166     if (result != STATE_OK) {
00167       msg = strchr (chld_out.line[i], ':');
00168       if(msg) msg++;
00169       break;
00170     }
00171   }
00172 
00173   /* scan stderr */
00174   for(i = 0; i < chld_err.lines; i++) {
00175     if (verbose)
00176       puts(chld_err.line[i]);
00177 
00178     if (error_scan (chld_err.line[i]) != STATE_OK) {
00179       result = max_state (result, error_scan (chld_err.line[i]));
00180       msg = strchr(input_buffer, ':');
00181       if(msg) msg++;
00182     }
00183   }
00184 
00185   if (addresses) {
00186     int i,slen;
00187     char *adrp;
00188     qsort(addresses, n_addresses, sizeof(*addresses), qstrcmp);
00189     for(i=0, slen=1; i < n_addresses; i++) {
00190       slen += strlen(addresses[i])+1;
00191     }
00192     adrp = address = malloc(slen);
00193     for(i=0; i < n_addresses; i++) {
00194       if (i) *adrp++ = ',';
00195       strcpy(adrp, addresses[i]);
00196       adrp += strlen(addresses[i]);
00197     }
00198     *adrp = 0;
00199   } else
00200     die (STATE_CRITICAL,
00201          _("DNS CRITICAL - '%s' msg parsing exited with no address\n"),
00202          NSLOOKUP_COMMAND);
00203 
00204   /* compare to expected address */
00205   if (result == STATE_OK && expected_address_cnt > 0) {
00206     result = STATE_CRITICAL;
00207     temp_buffer = "";
00208     for (i=0; i<expected_address_cnt; i++) {
00209       /* check if we get a match and prepare an error string */
00210       if (strcmp(address, expected_address[i]) == 0) result = STATE_OK;
00211       asprintf(&temp_buffer, "%s%s; ", temp_buffer, expected_address[i]);
00212     }
00213     if (result == STATE_CRITICAL) {
00214       /* Strip off last semicolon... */
00215       temp_buffer[strlen(temp_buffer)-2] = '\0';
00216       asprintf(&msg, _("expected '%s' but got '%s'"), temp_buffer, address);
00217     }
00218   }
00219 
00220   /* check if authoritative */
00221   if (result == STATE_OK && expect_authority && non_authoritative) {
00222     result = STATE_CRITICAL;
00223     asprintf(&msg, _("server %s is not authoritative for %s"), dns_server, query_address);
00224   }
00225 
00226   microsec = deltime (tv);
00227   elapsed_time = (double)microsec / 1.0e6;
00228 
00229   if (result == STATE_OK) {
00230     if (strchr (address, ',') == NULL)
00231       multi_address = FALSE;
00232     else
00233       multi_address = TRUE;
00234 
00235     result = get_status(elapsed_time, time_thresholds);
00236     if (result == STATE_OK) {
00237       printf ("DNS %s: ", _("OK"));
00238     } else if (result == STATE_WARNING) {
00239       printf ("DNS %s: ", _("WARNING"));
00240     } else if (result == STATE_CRITICAL) {
00241       printf ("DNS %s: ", _("CRITICAL"));
00242     }
00243     printf (ngettext("%.3f second response time", "%.3f seconds response time", elapsed_time), elapsed_time);
00244     printf (_(". %s returns %s"), query_address, address);
00245     printf ("|%s\n", fperfdata ("time", elapsed_time, "s", FALSE, 0, FALSE, 0, TRUE, 0, FALSE, 0));
00246   }
00247   else if (result == STATE_WARNING)
00248     printf (_("DNS WARNING - %s\n"),
00249             !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);
00250   else if (result == STATE_CRITICAL)
00251     printf (_("DNS CRITICAL - %s\n"),
00252             !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);
00253   else
00254     printf (_("DNS UNKNOWN - %s\n"),
00255             !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);
00256 
00257   return result;
00258 }
00259 
00260 
00261 
00262 int
00263 error_scan (char *input_buffer)
00264 {
00265 
00266   /* the DNS lookup timed out */
00267   if (strstr (input_buffer, _("Note: nslookup is deprecated and may be removed from future releases.")) ||
00268       strstr (input_buffer, _("Consider using the `dig' or `host' programs instead.  Run nslookup with")) ||
00269       strstr (input_buffer, _("the `-sil[ent]' option to prevent this message from appearing.")))
00270     return STATE_OK;
00271 
00272   /* DNS server is not running... */
00273   else if (strstr (input_buffer, "No response from server"))
00274     die (STATE_CRITICAL, _("No response from DNS %s\n"), dns_server);
00275 
00276   /* Host name is valid, but server doesn't have records... */
00277   else if (strstr (input_buffer, "No records"))
00278     die (STATE_CRITICAL, _("DNS %s has no records\n"), dns_server);
00279 
00280   /* Connection was refused */
00281   else if (strstr (input_buffer, "Connection refused") ||
00282      strstr (input_buffer, "Couldn't find server") ||
00283            strstr (input_buffer, "Refused") ||
00284            (strstr (input_buffer, "** server can't find") &&
00285             strstr (input_buffer, ": REFUSED")))
00286     die (STATE_CRITICAL, _("Connection to DNS %s was refused\n"), dns_server);
00287 
00288   /* Query refused (usually by an ACL in the namserver) */
00289   else if (strstr (input_buffer, "Query refused"))
00290     die (STATE_CRITICAL, _("Query was refused by DNS server at %s\n"), dns_server);
00291 
00292   /* No information (e.g. nameserver IP has two PTR records) */
00293   else if (strstr (input_buffer, "No information"))
00294     die (STATE_CRITICAL, _("No information returned by DNS server at %s\n"), dns_server);
00295 
00296   /* Host or domain name does not exist */
00297   else if (strstr (input_buffer, "Non-existent") ||
00298            strstr (input_buffer, "** server can't find") ||
00299      strstr (input_buffer,"NXDOMAIN"))
00300     die (STATE_CRITICAL, _("Domain %s was not found by the server\n"), query_address);
00301 
00302   /* Network is unreachable */
00303   else if (strstr (input_buffer, "Network is unreachable"))
00304     die (STATE_CRITICAL, _("Network is unreachable\n"));
00305 
00306   /* Internal server failure */
00307   else if (strstr (input_buffer, "Server failure"))
00308     die (STATE_CRITICAL, _("DNS failure for %s\n"), dns_server);
00309 
00310   /* Request error or the DNS lookup timed out */
00311   else if (strstr (input_buffer, "Format error") ||
00312            strstr (input_buffer, "Timed out"))
00313     return STATE_WARNING;
00314 
00315   return STATE_OK;
00316 
00317 }
00318 
00319 
00320 /* process command-line arguments */
00321 int
00322 process_arguments (int argc, char **argv)
00323 {
00324   int c;
00325   char *warning = NULL;
00326   char *critical = NULL;
00327 
00328   int opt_index = 0;
00329   static struct option long_opts[] = {
00330     {"help", no_argument, 0, 'h'},
00331     {"version", no_argument, 0, 'V'},
00332     {"verbose", no_argument, 0, 'v'},
00333     {"timeout", required_argument, 0, 't'},
00334     {"hostname", required_argument, 0, 'H'},
00335     {"server", required_argument, 0, 's'},
00336     {"reverse-server", required_argument, 0, 'r'},
00337     {"expected-address", required_argument, 0, 'a'},
00338     {"expect-authority", no_argument, 0, 'A'},
00339     {"warning", required_argument, 0, 'w'},
00340     {"critical", required_argument, 0, 'c'},
00341     {0, 0, 0, 0}
00342   };
00343 
00344   if (argc < 2)
00345     return ERROR;
00346 
00347   for (c = 1; c < argc; c++)
00348     if (strcmp ("-to", argv[c]) == 0)
00349       strcpy (argv[c], "-t");
00350 
00351   while (1) {
00352     c = getopt_long (argc, argv, "hVvAt:H:s:r:a:w:c:", long_opts, &opt_index);
00353 
00354     if (c == -1 || c == EOF)
00355       break;
00356 
00357     switch (c) {
00358     case 'h': /* help */
00359       print_help ();
00360       exit (STATE_OK);
00361     case 'V': /* version */
00362       print_revision (progname, NP_VERSION);
00363       exit (STATE_OK);
00364     case 'v': /* version */
00365       verbose = TRUE;
00366       break;
00367     case 't': /* timeout period */
00368       timeout_interval = atoi (optarg);
00369       break;
00370     case 'H': /* hostname */
00371       if (strlen (optarg) >= ADDRESS_LENGTH)
00372         die (STATE_UNKNOWN, _("Input buffer overflow\n"));
00373       strcpy (query_address, optarg);
00374       break;
00375     case 's': /* server name */
00376       /* TODO: this host_or_die check is probably unnecessary.
00377        * Better to confirm nslookup response matches */
00378       host_or_die(optarg);
00379       if (strlen (optarg) >= ADDRESS_LENGTH)
00380         die (STATE_UNKNOWN, _("Input buffer overflow\n"));
00381       strcpy (dns_server, optarg);
00382       break;
00383     case 'r': /* reverse server name */
00384       /* TODO: Is this host_or_die necessary? */
00385       host_or_die(optarg);
00386       if (strlen (optarg) >= ADDRESS_LENGTH)
00387         die (STATE_UNKNOWN, _("Input buffer overflow\n"));
00388       strcpy (ptr_server, optarg);
00389       break;
00390     case 'a': /* expected address */
00391       if (strlen (optarg) >= ADDRESS_LENGTH)
00392         die (STATE_UNKNOWN, _("Input buffer overflow\n"));
00393       expected_address = (char **)realloc(expected_address, (expected_address_cnt+1) * sizeof(char**));
00394       expected_address[expected_address_cnt] = strdup(optarg);
00395       expected_address_cnt++;
00396       break;
00397     case 'A': /* expect authority */
00398       expect_authority = TRUE;
00399       break;
00400     case 'w':
00401       warning = optarg;
00402       break;
00403     case 'c':
00404       critical = optarg;
00405       break;
00406     default: /* args not parsable */
00407       usage5();
00408     }
00409   }
00410 
00411   c = optind;
00412   if (strlen(query_address)==0 && c<argc) {
00413     if (strlen(argv[c])>=ADDRESS_LENGTH)
00414       die (STATE_UNKNOWN, _("Input buffer overflow\n"));
00415     strcpy (query_address, argv[c++]);
00416   }
00417 
00418   if (strlen(dns_server)==0 && c<argc) {
00419     /* TODO: See -s option */
00420     host_or_die(argv[c]);
00421     if (strlen(argv[c]) >= ADDRESS_LENGTH)
00422       die (STATE_UNKNOWN, _("Input buffer overflow\n"));
00423     strcpy (dns_server, argv[c++]);
00424   }
00425 
00426   set_thresholds(&time_thresholds, warning, critical);
00427 
00428   return validate_arguments ();
00429 }
00430 
00431 
00432 int
00433 validate_arguments ()
00434 {
00435   if (query_address[0] == 0)
00436     return ERROR;
00437 
00438   return OK;
00439 }
00440 
00441 
00442 void
00443 print_help (void)
00444 {
00445   print_revision (progname, NP_VERSION);
00446 
00447   printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
00448   printf (COPYRIGHT, copyright, email);
00449 
00450   printf ("%s\n", _("This plugin uses the nslookup program to obtain the IP address for the given host/domain query."));
00451   printf ("%s\n", _("An optional DNS server to use may be specified."));
00452   printf ("%s\n", _("If no DNS server is specified, the default server(s) specified in /etc/resolv.conf will be used."));
00453 
00454   printf ("\n\n");
00455 
00456   print_usage ();
00457 
00458   printf (UT_HELP_VRSN);
00459   printf (UT_EXTRA_OPTS);
00460 
00461   printf (" -H, --hostname=HOST\n");
00462   printf ("    %s\n", _("The name or address you want to query"));
00463   printf (" -s, --server=HOST\n");
00464   printf ("    %s\n", _("Optional DNS server you want to use for the lookup"));
00465   printf (" -a, --expected-address=IP-ADDRESS|HOST\n");
00466   printf ("    %s\n", _("Optional IP-ADDRESS you expect the DNS server to return. HOST must end with"));
00467   printf ("    %s\n", _("a dot (.). This option can be repeated multiple times (Returns OK if any"));
00468   printf ("    %s\n", _("value match). If multiple addresses are returned at once, you have to match"));
00469   printf ("    %s\n", _("the whole string of addresses separated with commas (sorted alphabetically)."));
00470   printf (" -A, --expect-authority\n");
00471   printf ("    %s\n", _("Optionally expect the DNS server to be authoritative for the lookup"));
00472   printf (" -w, --warning=seconds\n");
00473   printf ("    %s\n", _("Return warning if elapsed time exceeds value. Default off"));
00474   printf (" -c, --critical=seconds\n");
00475   printf ("    %s\n", _("Return critical if elapsed time exceeds value. Default off"));
00476 
00477   printf (UT_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
00478 
00479   printf (UT_SUPPORT);
00480 }
00481 
00482 
00483 void
00484 print_usage (void)
00485 {
00486   printf ("%s\n", _("Usage:"));
00487   printf ("%s -H host [-s server] [-a expected-address] [-A] [-t timeout] [-w warn] [-c crit]\n", progname);
00488 }