Code

6563e10372367e08e8cd3793d7253349000843af
[nagiosplug.git] / plugins / check_dns.c
1 /******************************************************************************
3  This program is free software; you can redistribute it and/or modify
4  it under the terms of the GNU General Public License as published by
5  the Free Software Foundation; either version 2 of the License, or
6  (at your option) any later version.
8  This program is distributed in the hope that it will be useful,
9  but WITHOUT ANY WARRANTY; without even the implied warranty of
10  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11  GNU General Public License for more details.
13  You should have received a copy of the GNU General Public License
14  along with this program; if not, write to the Free Software
15  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17  LIMITATION: nslookup on Solaris 7 can return output over 2 lines, which will not 
18  be picked up by this plugin
19  
20  $Id$
22 ******************************************************************************/
24 const char *progname = "check_dns";
25 const char *revision = "$Revision$";
26 const char *copyright = "2000-2005";
27 const char *email = "nagiosplug-devel@lists.sourceforge.net";
29 #include "common.h"
30 #include "utils.h"
31 #include "utils_base.h"
32 #include "netutils.h"
33 #include "runcmd.h"
35 int process_arguments (int, char **);
36 int validate_arguments (void);
37 int error_scan (char *);
38 void print_help (void);
39 void print_usage (void);
41 #define ADDRESS_LENGTH 256
42 char query_address[ADDRESS_LENGTH] = "";
43 char dns_server[ADDRESS_LENGTH] = "";
44 char ptr_server[ADDRESS_LENGTH] = "";
45 int verbose = FALSE;
46 char expected_address[ADDRESS_LENGTH] = "";
47 int match_expected_address = FALSE;
48 int expect_authority = FALSE;
49 thresholds *time_thresholds = NULL;
51 int
52 main (int argc, char **argv)
53 {
54   char *command_line = NULL;
55   char input_buffer[MAX_INPUT_BUFFER];
56   char *address = NULL;
57   char *msg = NULL;
58   char *temp_buffer = NULL;
59   int non_authoritative = FALSE;
60   int result = STATE_UNKNOWN;
61   double elapsed_time;
62   long microsec;
63   struct timeval tv;
64   int multi_address;
65   int parse_address = FALSE; /* This flag scans for Address: but only after Name: */
66   output chld_out, chld_err;
67   size_t i;
69   setlocale (LC_ALL, "");
70   bindtextdomain (PACKAGE, LOCALEDIR);
71   textdomain (PACKAGE);
73   /* Set signal handling and alarm */
74   if (signal (SIGALRM, popen_timeout_alarm_handler) == SIG_ERR) {
75     usage_va(_("Cannot catch SIGALRM"));
76   }
78   if (process_arguments (argc, argv) == ERROR) {
79     usage_va(_("Could not parse arguments"));
80   }
82   /* get the command to run */
83   asprintf (&command_line, "%s %s %s", NSLOOKUP_COMMAND, query_address, dns_server);
85   alarm (timeout_interval);
86   gettimeofday (&tv, NULL);
88   if (verbose)
89     printf ("%s\n", command_line);
91   /* run the command */
92   if((np_runcmd(command_line, &chld_out, &chld_err, 0)) != 0) {
93     msg = (char *)_("nslookup returned an error status");
94     result = STATE_WARNING;
95   }
97   /* scan stdout */
98   for(i = 0; i < chld_out.lines; i++) {
99     if (verbose)
100       puts(chld_out.line[i]);
102     if (strstr (chld_out.line[i], ".in-addr.arpa")) {
103       if ((temp_buffer = strstr (chld_out.line[i], "name = ")))
104         address = strdup (temp_buffer + 7);
105       else {
106         msg = (char *)_("Warning plugin error");
107         result = STATE_WARNING;
108       }
109     }
111     /* the server is responding, we just got the host name... */
112     if (strstr (chld_out.line[i], "Name:"))
113       parse_address = TRUE;
114     else if (parse_address == TRUE && (strstr (chld_out.line[i], "Address:") ||
115              strstr (chld_out.line[i], "Addresses:"))) {
116       temp_buffer = index (chld_out.line[i], ':');
117       temp_buffer++;
119       /* Strip leading spaces */
120       for (; *temp_buffer != '\0' && *temp_buffer == ' '; temp_buffer++)
121         /* NOOP */;
122       
123       strip(temp_buffer);
124       if (temp_buffer==NULL || strlen(temp_buffer)==0) {
125         die (STATE_CRITICAL,
126              _("DNS CRITICAL - '%s' returned empty host name string\n"),
127              NSLOOKUP_COMMAND);
128       }
130       if (address == NULL)
131         address = strdup (temp_buffer);
132       else
133         asprintf(&address, "%s,%s", address, temp_buffer);
134     }
136     else if (strstr (chld_out.line[i], _("Non-authoritative answer:"))) {
137       non_authoritative = TRUE;
138     }
140     result = error_scan (chld_out.line[i]);
141     if (result != STATE_OK) {
142       msg = strchr (chld_out.line[i], ':');
143       if(msg) msg++;
144       break;
145     }
146   }
148   /* scan stderr */
149   for(i = 0; i < chld_err.lines; i++) {
150     if (verbose)
151       puts(chld_err.line[i]);
153     if (error_scan (chld_err.line[i]) != STATE_OK) {
154       result = max_state (result, error_scan (chld_err.line[i]));
155       msg = strchr(input_buffer, ':');
156       if(msg) msg++;
157     }
158   }
160   /* If we got here, we should have an address string,
161    * and we can segfault if we do not */
162   if (address==NULL || strlen(address)==0)
163     die (STATE_CRITICAL,
164          _("DNS CRITICAL - '%s' msg parsing exited with no address\n"),
165          NSLOOKUP_COMMAND);
167   /* compare to expected address */
168   if (result == STATE_OK && match_expected_address && strcmp(address, expected_address)) {
169     result = STATE_CRITICAL;
170     asprintf(&msg, _("expected '%s' but got '%s'"), expected_address, address);
171   }
173   /* check if authoritative */
174   if (result == STATE_OK && expect_authority && non_authoritative) {
175     result = STATE_CRITICAL;
176     asprintf(&msg, _("server %s is not authoritative for %s"), dns_server, query_address);
177   }
179   microsec = deltime (tv);
180   elapsed_time = (double)microsec / 1.0e6;
182   if (result == STATE_OK) {
183     if (strchr (address, ',') == NULL)
184       multi_address = FALSE;
185     else
186       multi_address = TRUE;
188     result = get_status(elapsed_time, time_thresholds);
189     if (result == STATE_OK) {
190       printf ("DNS %s: ", _("OK"));
191     } else if (result == STATE_WARNING) {
192       printf ("DNS %s: ", _("WARNING"));
193     } else if (result == STATE_CRITICAL) {
194       printf ("DNS %s: ", _("CRITICAL"));
195     }
196     printf (ngettext("%.3f second response time", "%.3f seconds response time", elapsed_time), elapsed_time);
197     printf (_(". %s returns %s"), query_address, address);
198     printf ("|%s\n", fperfdata ("time", elapsed_time, "s", FALSE, 0, FALSE, 0, TRUE, 0, FALSE, 0));
199   }
200   else if (result == STATE_WARNING)
201     printf (_("DNS WARNING - %s\n"),
202             !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);
203   else if (result == STATE_CRITICAL)
204     printf (_("DNS CRITICAL - %s\n"),
205             !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);
206   else
207     printf (_("DNS UNKNOW - %s\n"),
208             !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);
210   return result;
215 int
216 error_scan (char *input_buffer)
219   /* the DNS lookup timed out */
220   if (strstr (input_buffer, _("Note: nslookup is deprecated and may be removed from future releases.")) ||
221       strstr (input_buffer, _("Consider using the `dig' or `host' programs instead.  Run nslookup with")) ||
222       strstr (input_buffer, _("the `-sil[ent]' option to prevent this message from appearing.")))
223     return STATE_OK;
225   /* DNS server is not running... */
226   else if (strstr (input_buffer, "No response from server"))
227     die (STATE_CRITICAL, _("No response from DNS %s\n"), dns_server);
229   /* Host name is valid, but server doesn't have records... */
230   else if (strstr (input_buffer, "No records"))
231     die (STATE_CRITICAL, _("DNS %s has no records\n"), dns_server);
233   /* Connection was refused */
234   else if (strstr (input_buffer, "Connection refused") ||
235      strstr (input_buffer, "Couldn't find server") ||
236            strstr (input_buffer, "Refused") ||
237            (strstr (input_buffer, "** server can't find") &&
238             strstr (input_buffer, ": REFUSED")))
239     die (STATE_CRITICAL, _("Connection to DNS %s was refused\n"), dns_server);
241   /* Query refused (usually by an ACL in the namserver) */ 
242   else if (strstr (input_buffer, "Query refused"))
243     die (STATE_CRITICAL, _("Query was refused by DNS server at %s\n"), dns_server);
245   /* No information (e.g. nameserver IP has two PTR records) */
246   else if (strstr (input_buffer, "No information"))
247     die (STATE_CRITICAL, _("No information returned by DNS server at %s\n"), dns_server);
249   /* Host or domain name does not exist */
250   else if (strstr (input_buffer, "Non-existent") ||
251            strstr (input_buffer, "** server can't find") ||
252      strstr (input_buffer,"NXDOMAIN"))
253     die (STATE_CRITICAL, _("Domain %s was not found by the server\n"), query_address);
255   /* Network is unreachable */
256   else if (strstr (input_buffer, "Network is unreachable"))
257     die (STATE_CRITICAL, _("Network is unreachable\n"));
259   /* Internal server failure */
260   else if (strstr (input_buffer, "Server failure"))
261     die (STATE_CRITICAL, _("DNS failure for %s\n"), dns_server);
263   /* Request error or the DNS lookup timed out */
264   else if (strstr (input_buffer, "Format error") ||
265            strstr (input_buffer, "Timed out"))
266     return STATE_WARNING;
268   return STATE_OK;
273 /* process command-line arguments */
274 int
275 process_arguments (int argc, char **argv)
277   int c;
278   char *warning = NULL;
279   char *critical = NULL;
281   int opt_index = 0;
282   static struct option long_opts[] = {
283     {"help", no_argument, 0, 'h'},
284     {"version", no_argument, 0, 'V'},
285     {"verbose", no_argument, 0, 'v'},
286     {"timeout", required_argument, 0, 't'},
287     {"hostname", required_argument, 0, 'H'},
288     {"server", required_argument, 0, 's'},
289     {"reverse-server", required_argument, 0, 'r'},
290     {"expected-address", required_argument, 0, 'a'},
291     {"expect-authority", no_argument, 0, 'A'},
292     {"warning", no_argument, 0, 'w'},
293     {"critical", no_argument, 0, 'c'},
294     {0, 0, 0, 0}
295   };
297   if (argc < 2)
298     return ERROR;
300   for (c = 1; c < argc; c++)
301     if (strcmp ("-to", argv[c]) == 0)
302       strcpy (argv[c], "-t");
304   while (1) {
305     c = getopt_long (argc, argv, "hVvAt:H:s:r:a:w:c:", long_opts, &opt_index);
307     if (c == -1 || c == EOF)
308       break;
310     switch (c) {
311     case 'h': /* help */
312       print_help ();
313       exit (STATE_OK);
314     case 'V': /* version */
315       print_revision (progname, revision);
316       exit (STATE_OK);
317     case 'v': /* version */
318       verbose = TRUE;
319       break;
320     case 't': /* timeout period */
321       timeout_interval = atoi (optarg);
322       break;
323     case 'H': /* hostname */
324       if (strlen (optarg) >= ADDRESS_LENGTH)
325         die (STATE_UNKNOWN, _("Input buffer overflow\n"));
326       strcpy (query_address, optarg);
327       break;
328     case 's': /* server name */
329       /* TODO: this host_or_die check is probably unnecessary.
330        * Better to confirm nslookup response matches */
331       host_or_die(optarg);
332       if (strlen (optarg) >= ADDRESS_LENGTH)
333         die (STATE_UNKNOWN, _("Input buffer overflow\n"));
334       strcpy (dns_server, optarg);
335       break;
336     case 'r': /* reverse server name */
337       /* TODO: Is this host_or_die necessary? */
338       host_or_die(optarg);
339       if (strlen (optarg) >= ADDRESS_LENGTH)
340         die (STATE_UNKNOWN, _("Input buffer overflow\n"));
341       strcpy (ptr_server, optarg);
342       break;
343     case 'a': /* expected address */
344       if (strlen (optarg) >= ADDRESS_LENGTH)
345         die (STATE_UNKNOWN, _("Input buffer overflow\n"));
346       strcpy (expected_address, optarg);
347       match_expected_address = TRUE;
348       break;
349     case 'A': /* expect authority */
350       expect_authority = TRUE;
351       break;
352     case 'w':
353       warning = optarg;
354       break;
355     case 'c':
356       critical = optarg;
357       break;
358     default: /* args not parsable */
359       usage_va(_("Unknown argument - %s"), optarg);
360     }
361   }
363   c = optind;
364   if (strlen(query_address)==0 && c<argc) {
365     if (strlen(argv[c])>=ADDRESS_LENGTH)
366       die (STATE_UNKNOWN, _("Input buffer overflow\n"));
367     strcpy (query_address, argv[c++]);
368   }
370   if (strlen(dns_server)==0 && c<argc) {
371     /* TODO: See -s option */
372     host_or_die(argv[c]);
373     if (strlen(argv[c]) >= ADDRESS_LENGTH)
374       die (STATE_UNKNOWN, _("Input buffer overflow\n"));
375     strcpy (dns_server, argv[c++]);
376   }
378   set_thresholds(&time_thresholds, warning, critical);
380   return validate_arguments ();
384 int
385 validate_arguments ()
387   if (query_address[0] == 0)
388     return ERROR;
390   return OK;
394 void
395 print_help (void)
397   print_revision (progname, revision);
399   printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
400   printf (COPYRIGHT, copyright, email);
402   printf ("%s\n", _("This plugin uses the nslookup program to obtain the IP address for the given host/domain query."));
403   printf ("%s\n", _("An optional DNS server to use may be specified."));
404   printf ("%s\n", _("If no DNS server is specified, the default server(s) specified in /etc/resolv.conf will be used."));
405   
406   printf ("\n\n");
408   print_usage ();
409   
410   printf (_(UT_HELP_VRSN));
411   
412   printf (" -H, --hostname=HOST\n");
413   printf ("    %s\n", _("The name or address you want to query"));
414   printf (" -s, --server=HOST\n");
415   printf ("    %s\n", _("Optional DNS server you want to use for the lookup"));
416   printf (" -a, --expected-address=IP-ADDRESS|HOST\n");
417   printf ("    %s\n", _("Optional IP-ADDRESS you expect the DNS server to return. HOST must end with ."));
418   printf (" -A, --expect-authority\n");
419   printf ("    %s\n", _("Optionally expect the DNS server to be authoritative for the lookup"));
420   printf (" -w, --warning=seconds\n");
421   printf ("    %s\n", _("Return warning if elapsed time exceeds value. Default off"));
422   printf (" -c, --critical=seconds\n");
423   printf ("    %s\n", _("Return critical if elapsed time exceeds value. Default off"));
425   printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
426   printf (_(UT_SUPPORT));
430 void
431 print_usage (void)
433   printf (_("Usage:"));
434   printf ("%s -H host [-s server] [-a expected-address] [-A] [-t timeout] [-w warn] [-c crit]\n", progname);