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 if (process_arguments (argc, argv) == ERROR) {
103 usage_va(_("Could not parse arguments"));
104 }
106 /* get the command to run */
107 asprintf (&command_line, "%s %s %s", NSLOOKUP_COMMAND, query_address, dns_server);
109 alarm (timeout_interval);
110 gettimeofday (&tv, NULL);
112 if (verbose)
113 printf ("%s\n", command_line);
115 /* run the command */
116 if((np_runcmd(command_line, &chld_out, &chld_err, 0)) != 0) {
117 msg = (char *)_("nslookup returned an error status");
118 result = STATE_WARNING;
119 }
121 /* scan stdout */
122 for(i = 0; i < chld_out.lines; i++) {
123 if (addresses == NULL)
124 addresses = malloc(sizeof(*addresses)*10);
125 else if (!(n_addresses % 10))
126 addresses = realloc(addresses,sizeof(*addresses) * (n_addresses + 10));
128 if (verbose)
129 puts(chld_out.line[i]);
131 if (strstr (chld_out.line[i], ".in-addr.arpa")) {
132 if ((temp_buffer = strstr (chld_out.line[i], "name = ")))
133 addresses[n_addresses++] = strdup (temp_buffer + 7);
134 else {
135 msg = (char *)_("Warning plugin error");
136 result = STATE_WARNING;
137 }
138 }
140 /* the server is responding, we just got the host name... */
141 if (strstr (chld_out.line[i], "Name:"))
142 parse_address = TRUE;
143 else if (parse_address == TRUE && (strstr (chld_out.line[i], "Address:") ||
144 strstr (chld_out.line[i], "Addresses:"))) {
145 temp_buffer = index (chld_out.line[i], ':');
146 temp_buffer++;
148 /* Strip leading spaces */
149 for (; *temp_buffer != '\0' && *temp_buffer == ' '; temp_buffer++)
150 /* NOOP */;
152 strip(temp_buffer);
153 if (temp_buffer==NULL || strlen(temp_buffer)==0) {
154 die (STATE_CRITICAL,
155 _("DNS CRITICAL - '%s' returned empty host name string\n"),
156 NSLOOKUP_COMMAND);
157 }
159 addresses[n_addresses++] = strdup(temp_buffer);
160 }
161 else if (strstr (chld_out.line[i], _("Non-authoritative answer:"))) {
162 non_authoritative = TRUE;
163 }
166 result = error_scan (chld_out.line[i]);
167 if (result != STATE_OK) {
168 msg = strchr (chld_out.line[i], ':');
169 if(msg) msg++;
170 break;
171 }
172 }
174 /* scan stderr */
175 for(i = 0; i < chld_err.lines; i++) {
176 if (verbose)
177 puts(chld_err.line[i]);
179 if (error_scan (chld_err.line[i]) != STATE_OK) {
180 result = max_state (result, error_scan (chld_err.line[i]));
181 msg = strchr(input_buffer, ':');
182 if(msg) msg++;
183 }
184 }
186 if (addresses) {
187 int i,slen;
188 char *adrp;
189 qsort(addresses, n_addresses, sizeof(*addresses), qstrcmp);
190 for(i=0, slen=1; i < n_addresses; i++) {
191 slen += strlen(addresses[i])+1;
192 }
193 adrp = address = malloc(slen);
194 for(i=0; i < n_addresses; i++) {
195 if (i) *adrp++ = ',';
196 strcpy(adrp, addresses[i]);
197 adrp += strlen(addresses[i]);
198 }
199 *adrp = 0;
200 } else
201 die (STATE_CRITICAL,
202 _("DNS CRITICAL - '%s' msg parsing exited with no address\n"),
203 NSLOOKUP_COMMAND);
205 /* compare to expected address */
206 if (result == STATE_OK && expected_address_cnt > 0) {
207 result = STATE_CRITICAL;
208 temp_buffer = "";
209 for (i=0; i<expected_address_cnt; i++) {
210 /* check if we get a match and prepare an error string */
211 if (strcmp(address, expected_address[i]) == 0) result = STATE_OK;
212 asprintf(&temp_buffer, "%s%s; ", temp_buffer, expected_address[i]);
213 }
214 if (result == STATE_CRITICAL) {
215 /* Strip off last semicolon... */
216 temp_buffer[strlen(temp_buffer)-2] = '\0';
217 asprintf(&msg, _("expected '%s' but got '%s'"), temp_buffer, address);
218 }
219 }
221 /* check if authoritative */
222 if (result == STATE_OK && expect_authority && non_authoritative) {
223 result = STATE_CRITICAL;
224 asprintf(&msg, _("server %s is not authoritative for %s"), dns_server, query_address);
225 }
227 microsec = deltime (tv);
228 elapsed_time = (double)microsec / 1.0e6;
230 if (result == STATE_OK) {
231 if (strchr (address, ',') == NULL)
232 multi_address = FALSE;
233 else
234 multi_address = TRUE;
236 result = get_status(elapsed_time, time_thresholds);
237 if (result == STATE_OK) {
238 printf ("DNS %s: ", _("OK"));
239 } else if (result == STATE_WARNING) {
240 printf ("DNS %s: ", _("WARNING"));
241 } else if (result == STATE_CRITICAL) {
242 printf ("DNS %s: ", _("CRITICAL"));
243 }
244 printf (ngettext("%.3f second response time", "%.3f seconds response time", elapsed_time), elapsed_time);
245 printf (_(". %s returns %s"), query_address, address);
246 printf ("|%s\n", fperfdata ("time", elapsed_time, "s", FALSE, 0, FALSE, 0, TRUE, 0, FALSE, 0));
247 }
248 else if (result == STATE_WARNING)
249 printf (_("DNS WARNING - %s\n"),
250 !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);
251 else if (result == STATE_CRITICAL)
252 printf (_("DNS CRITICAL - %s\n"),
253 !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);
254 else
255 printf (_("DNS UNKNOW - %s\n"),
256 !strcmp (msg, "") ? _(" Probably a non-existent host/domain") : msg);
258 return result;
259 }
263 int
264 error_scan (char *input_buffer)
265 {
267 /* the DNS lookup timed out */
268 if (strstr (input_buffer, _("Note: nslookup is deprecated and may be removed from future releases.")) ||
269 strstr (input_buffer, _("Consider using the `dig' or `host' programs instead. Run nslookup with")) ||
270 strstr (input_buffer, _("the `-sil[ent]' option to prevent this message from appearing.")))
271 return STATE_OK;
273 /* DNS server is not running... */
274 else if (strstr (input_buffer, "No response from server"))
275 die (STATE_CRITICAL, _("No response from DNS %s\n"), dns_server);
277 /* Host name is valid, but server doesn't have records... */
278 else if (strstr (input_buffer, "No records"))
279 die (STATE_CRITICAL, _("DNS %s has no records\n"), dns_server);
281 /* Connection was refused */
282 else if (strstr (input_buffer, "Connection refused") ||
283 strstr (input_buffer, "Couldn't find server") ||
284 strstr (input_buffer, "Refused") ||
285 (strstr (input_buffer, "** server can't find") &&
286 strstr (input_buffer, ": REFUSED")))
287 die (STATE_CRITICAL, _("Connection to DNS %s was refused\n"), dns_server);
289 /* Query refused (usually by an ACL in the namserver) */
290 else if (strstr (input_buffer, "Query refused"))
291 die (STATE_CRITICAL, _("Query was refused by DNS server at %s\n"), dns_server);
293 /* No information (e.g. nameserver IP has two PTR records) */
294 else if (strstr (input_buffer, "No information"))
295 die (STATE_CRITICAL, _("No information returned by DNS server at %s\n"), dns_server);
297 /* Host or domain name does not exist */
298 else if (strstr (input_buffer, "Non-existent") ||
299 strstr (input_buffer, "** server can't find") ||
300 strstr (input_buffer,"NXDOMAIN"))
301 die (STATE_CRITICAL, _("Domain %s was not found by the server\n"), query_address);
303 /* Network is unreachable */
304 else if (strstr (input_buffer, "Network is unreachable"))
305 die (STATE_CRITICAL, _("Network is unreachable\n"));
307 /* Internal server failure */
308 else if (strstr (input_buffer, "Server failure"))
309 die (STATE_CRITICAL, _("DNS failure for %s\n"), dns_server);
311 /* Request error or the DNS lookup timed out */
312 else if (strstr (input_buffer, "Format error") ||
313 strstr (input_buffer, "Timed out"))
314 return STATE_WARNING;
316 return STATE_OK;
318 }
321 /* process command-line arguments */
322 int
323 process_arguments (int argc, char **argv)
324 {
325 int c;
326 char *warning = NULL;
327 char *critical = NULL;
329 int opt_index = 0;
330 static struct option long_opts[] = {
331 {"help", no_argument, 0, 'h'},
332 {"version", no_argument, 0, 'V'},
333 {"verbose", no_argument, 0, 'v'},
334 {"timeout", required_argument, 0, 't'},
335 {"hostname", required_argument, 0, 'H'},
336 {"server", required_argument, 0, 's'},
337 {"reverse-server", required_argument, 0, 'r'},
338 {"expected-address", required_argument, 0, 'a'},
339 {"expect-authority", no_argument, 0, 'A'},
340 {"warning", no_argument, 0, 'w'},
341 {"critical", no_argument, 0, 'c'},
342 {0, 0, 0, 0}
343 };
345 if (argc < 2)
346 return ERROR;
348 for (c = 1; c < argc; c++)
349 if (strcmp ("-to", argv[c]) == 0)
350 strcpy (argv[c], "-t");
352 while (1) {
353 c = getopt_long (argc, argv, "hVvAt:H:s:r:a:w:c:", long_opts, &opt_index);
355 if (c == -1 || c == EOF)
356 break;
358 switch (c) {
359 case 'h': /* help */
360 print_help ();
361 exit (STATE_OK);
362 case 'V': /* version */
363 print_revision (progname, revision);
364 exit (STATE_OK);
365 case 'v': /* version */
366 verbose = TRUE;
367 break;
368 case 't': /* timeout period */
369 timeout_interval = atoi (optarg);
370 break;
371 case 'H': /* hostname */
372 if (strlen (optarg) >= ADDRESS_LENGTH)
373 die (STATE_UNKNOWN, _("Input buffer overflow\n"));
374 strcpy (query_address, optarg);
375 break;
376 case 's': /* server name */
377 /* TODO: this host_or_die check is probably unnecessary.
378 * Better to confirm nslookup response matches */
379 host_or_die(optarg);
380 if (strlen (optarg) >= ADDRESS_LENGTH)
381 die (STATE_UNKNOWN, _("Input buffer overflow\n"));
382 strcpy (dns_server, optarg);
383 break;
384 case 'r': /* reverse server name */
385 /* TODO: Is this host_or_die necessary? */
386 host_or_die(optarg);
387 if (strlen (optarg) >= ADDRESS_LENGTH)
388 die (STATE_UNKNOWN, _("Input buffer overflow\n"));
389 strcpy (ptr_server, optarg);
390 break;
391 case 'a': /* expected address */
392 if (strlen (optarg) >= ADDRESS_LENGTH)
393 die (STATE_UNKNOWN, _("Input buffer overflow\n"));
394 expected_address = (char **)realloc(expected_address, (expected_address_cnt+1) * sizeof(char**));
395 expected_address[expected_address_cnt] = strdup(optarg);
396 expected_address_cnt++;
397 break;
398 case 'A': /* expect authority */
399 expect_authority = TRUE;
400 break;
401 case 'w':
402 warning = optarg;
403 break;
404 case 'c':
405 critical = optarg;
406 break;
407 default: /* args not parsable */
408 usage5();
409 }
410 }
412 c = optind;
413 if (strlen(query_address)==0 && c<argc) {
414 if (strlen(argv[c])>=ADDRESS_LENGTH)
415 die (STATE_UNKNOWN, _("Input buffer overflow\n"));
416 strcpy (query_address, argv[c++]);
417 }
419 if (strlen(dns_server)==0 && c<argc) {
420 /* TODO: See -s option */
421 host_or_die(argv[c]);
422 if (strlen(argv[c]) >= ADDRESS_LENGTH)
423 die (STATE_UNKNOWN, _("Input buffer overflow\n"));
424 strcpy (dns_server, argv[c++]);
425 }
427 set_thresholds(&time_thresholds, warning, critical);
429 return validate_arguments ();
430 }
433 int
434 validate_arguments ()
435 {
436 if (query_address[0] == 0)
437 return ERROR;
439 return OK;
440 }
443 void
444 print_help (void)
445 {
446 print_revision (progname, revision);
448 printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
449 printf (COPYRIGHT, copyright, email);
451 printf ("%s\n", _("This plugin uses the nslookup program to obtain the IP address for the given host/domain query."));
452 printf ("%s\n", _("An optional DNS server to use may be specified."));
453 printf ("%s\n", _("If no DNS server is specified, the default server(s) specified in /etc/resolv.conf will be used."));
455 printf ("\n\n");
457 print_usage ();
459 printf (_(UT_HELP_VRSN));
461 printf (" -H, --hostname=HOST\n");
462 printf (" %s\n", _("The name or address you want to query"));
463 printf (" -s, --server=HOST\n");
464 printf (" %s\n", _("Optional DNS server you want to use for the lookup"));
465 printf (" -a, --expected-address=IP-ADDRESS|HOST\n");
466 printf (" %s\n", _("Optional IP-ADDRESS you expect the DNS server to return. HOST must end with"));
467 printf (" %s\n", _("a dot (.). This option can be repeated multiple times (Returns OK if any"));
468 printf (" %s\n", _("value match). If multiple addressesare returned at once, you have to match"));
469 printf (" %s\n", _("the whole string of addresses separated with commas (sorted alphabetically)."));
470 printf (" -A, --expect-authority\n");
471 printf (" %s\n", _("Optionally expect the DNS server to be authoritative for the lookup"));
472 printf (" -w, --warning=seconds\n");
473 printf (" %s\n", _("Return warning if elapsed time exceeds value. Default off"));
474 printf (" -c, --critical=seconds\n");
475 printf (" %s\n", _("Return critical if elapsed time exceeds value. Default off"));
477 printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
478 printf (_(UT_SUPPORT));
479 }
482 void
483 print_usage (void)
484 {
485 printf (_("Usage:"));
486 printf ("%s -H host [-s server] [-a expected-address] [-A] [-t timeout] [-w warn] [-c crit]\n", progname);
487 }