Code

first revised patch failed to trap the "break" in while()
[nagiosplug.git] / plugins / check_dns.c
1 /******************************************************************************
2  *
3  * CHECK_DNS.C
4  *
5  * Program: DNS plugin for Nagios
6  * License: GPL
7  * Copyright (c) 1999 Ethan Galstad (nagios@nagios.org)
8  *
9  * Last Modified: $Date$
10  *
11  * Notes:
12  *  - Safe popen added by Karl DeBisschop 9-11-99
13  *  - expected-address parameter added by Alex Chaffee - 7 Oct 2002
14  *
15  * Command line: (see print_usage)
16  *
17  * Description:
18  *
19  * This program will use the nslookup program to obtain the IP address
20  * for a given host name.  A optional DNS server may be specified.  If
21  * no DNS server is specified, the default server(s) for the system
22  * are used.
23  *
24  * Return Values:
25  *  OK           The DNS query was successful (host IP address was returned).
26  *  WARNING      The DNS server responded, but could not fulfill the request.
27  *  CRITICAL     The DNS server is not responding or encountered an error.
28  *
29  * License Information:
30  *
31  * This program is free software; you can redistribute it and/or modify
32  * it under the terms of the GNU General Public License as published by
33  * the Free Software Foundation; either version 2 of the License, or
34  * (at your option) any later version.
35  *
36  * This program is distributed in the hope that it will be useful,
37  * but WITHOUT ANY WARRANTY; without even the implied warranty of
38  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
39  * GNU General Public License for more details.
40  *
41  * You should have received a copy of the GNU General Public License
42  * along with this program; if not, write to the Free Software
43  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
44  *
45  *****************************************************************************/
47 #include "common.h"
48 #include "popen.h"
49 #include "utils.h"
51 const char *progname = "check_dns";
52 #define REVISION "$Revision$"
53 #define COPYRIGHT "2000-2002"
55 int process_arguments (int, char **);
56 int validate_arguments (void);
57 void print_usage (void);
58 void print_help (void);
59 int error_scan (char *);
61 #define ADDRESS_LENGTH 256
62 char query_address[ADDRESS_LENGTH] = "";
63 char dns_server[ADDRESS_LENGTH] = "";
64 char ptr_server[ADDRESS_LENGTH] = "";
65 int verbose = FALSE;
66 char expected_address[ADDRESS_LENGTH] = "";
67 int match_expected_address = FALSE;
69 int
70 main (int argc, char **argv)
71 {
72         char *command_line = NULL;
73         char input_buffer[MAX_INPUT_BUFFER];
74         char *output = NULL;
75         char *address = NULL;
76         char *temp_buffer = NULL;
77         int result = STATE_UNKNOWN;
78         double elapsed_time;
79         struct timeval tv;
80         int multi_address;
82         /* Set signal handling and alarm */
83         if (signal (SIGALRM, popen_timeout_alarm_handler) == SIG_ERR) {
84                 printf ("Cannot catch SIGALRM");
85                 return STATE_UNKNOWN;
86         }
88         if (process_arguments (argc, argv) != OK) {
89                 print_usage ();
90                 return STATE_UNKNOWN;
91         }
93         /* get the command to run */
94         asprintf (&command_line, "%s %s %s", NSLOOKUP_COMMAND,  query_address, dns_server);
96         alarm (timeout_interval);
97         gettimeofday (&tv, NULL);
99         if (verbose)
100                 printf ("%s\n", command_line);
101         /* run the command */
102         child_process = spopen (command_line);
103         if (child_process == NULL) {
104                 printf ("Could not open pipe: %s\n", command_line);
105                 return STATE_UNKNOWN;
106         }
108         child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r");
109         if (child_stderr == NULL)
110                 printf ("Could not open stderr for %s\n", command_line);
112         /* scan stdout */
113         while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process)) {
115                 if (verbose)
116                         printf ("%s\n", input_buffer);
118                 if (strstr (input_buffer, ".in-addr.arpa")) {
119                         if ((temp_buffer = strstr (input_buffer, "name = ")))
120                                 address = strscpy (address, temp_buffer + 7);
121                         else {
122                                 output = strscpy (output, "Unknown error (plugin)");
123                                 result = STATE_WARNING;
124                         }
125                 }
127                 /* the server is responding, we just got the host name... */
128                 if (strstr (input_buffer, "Name:")) {
130                         /* get the host address */
131                         if (!fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process))
132                                 break;
134                         if (verbose)
135                                 printf ("%s\n", input_buffer);
137                         if ((temp_buffer = index (input_buffer, ':'))) {
138                                 temp_buffer++;
139                                 /* Strip leading spaces */
140                                 for (; *temp_buffer != '\0' && *temp_buffer == ' '; temp_buffer++)
141                                         /* NOOP */;
142                                 address = strdup (temp_buffer);
143                                 strip (address);
144                                 if (address==NULL || strlen(address)==0)
145                                         terminate (STATE_CRITICAL,
146                                                    "DNS CRITICAL - '%s' returned empty host name string\n",
147                                                    NSLOOKUP_COMMAND);
148                                 result = STATE_OK;
149                         }
150                         else {
151                                 output = strdup ("Unknown error (plugin)");
152                                 result = STATE_WARNING;
153                         }
155                         break;
156                 }
158                 result = error_scan (input_buffer);
159                 if (result != STATE_OK) {
160                         output = strscpy (output, 1 + index (input_buffer, ':'));
161                         strip (output);
162                         break;
163                 }
165         }
167         /* scan stderr */
168         while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) {
169                 if (error_scan (input_buffer) != STATE_OK) {
170                         result = max_state (result, error_scan (input_buffer));
171                         output = strscpy (output, 1 + index (input_buffer, ':'));
172                         strip (output);
173                 }
174         }
176         /* close stderr */
177         (void) fclose (child_stderr);
179         /* close stdout */
180         if (spclose (child_process)) {
181                 result = max_state (result, STATE_WARNING);
182                 if (!strcmp (output, ""))
183                         output = strscpy (output, "nslookup returned error status");
184         }
186         /* If we got here, we should have an address string, 
187            and we can segfault if we do not */
188         if (address==NULL || strlen(address)==0)
189                 terminate (STATE_CRITICAL,
190                            "DNS CRITICAL - '%s' output parsing exited with no address\n",
191                            NSLOOKUP_COMMAND);
193         /* compare to expected address */
194         if (result == STATE_OK && match_expected_address && strcmp(address, expected_address)) {
195                 result = STATE_CRITICAL;
196                 asprintf(&output, "expected %s but got %s", expected_address, address);
197         }
198         
199         elapsed_time = delta_time (tv);
201         if (result == STATE_OK) {
202                 if (strchr (address, ',') == NULL)
203                         multi_address = FALSE;
204                 else
205                         multi_address = TRUE;
207                 printf ("DNS ok - %.3f seconds response time, address%s %s|time=%.3f\n",
208                   elapsed_time, (multi_address==TRUE ? "es are" : " is"), address, elapsed_time);
209         }
210         else if (result == STATE_WARNING)
211                 printf ("DNS WARNING - %s\n",
212                         !strcmp (output, "") ? " Probably a non-existent host/domain" : output);
213         else if (result == STATE_CRITICAL)
214                 printf ("DNS CRITICAL - %s\n",
215                         !strcmp (output, "") ? " Probably a non-existent host/domain" : output);
216         else
217                 printf ("DNS problem - %s\n",
218                         !strcmp (output, "") ? " Probably a non-existent host/domain" : output);
220         return result;
223 int
224 error_scan (char *input_buffer)
227         /* the DNS lookup timed out */
228         if (strstr (input_buffer,
229              "Note:  nslookup is deprecated and may be removed from future releases.")
230             || strstr (input_buffer,
231              "Consider using the `dig' or `host' programs instead.  Run nslookup with")
232             || strstr (input_buffer,
233              "the `-sil[ent]' option to prevent this message from appearing."))
234                 return STATE_OK;
236         /* the DNS lookup timed out */
237         else if (strstr (input_buffer, "Timed out"))
238                 return STATE_WARNING;
240         /* DNS server is not running... */
241         else if (strstr (input_buffer, "No response from server"))
242                 return STATE_CRITICAL;
244         /* Host name is valid, but server doesn't have records... */
245         else if (strstr (input_buffer, "No records"))
246                 return STATE_WARNING;
248         /* Host or domain name does not exist */
249         else if (strstr (input_buffer, "Non-existent"))
250                 return STATE_CRITICAL;
251         else if (strstr (input_buffer, "** server can't find"))
252                 return STATE_CRITICAL;
253         else if(strstr(input_buffer,"NXDOMAIN")) /* 9.x */
254                 return STATE_CRITICAL;
256         /* Connection was refused */
257         else if (strstr (input_buffer, "Connection refused"))
258                 return STATE_CRITICAL;
260         /* Network is unreachable */
261         else if (strstr (input_buffer, "Network is unreachable"))
262                 return STATE_CRITICAL;
264         /* Internal server failure */
265         else if (strstr (input_buffer, "Server failure"))
266                 return STATE_CRITICAL;
268         /* DNS server refused to service request */
269         else if (strstr (input_buffer, "Refused"))
270                 return STATE_CRITICAL;
272         /* Request error */
273         else if (strstr (input_buffer, "Format error"))
274                 return STATE_WARNING;
276         else
277                 return STATE_OK;
281 /* process command-line arguments */
282 int
283 process_arguments (int argc, char **argv)
285         int c;
287         int opt_index = 0;
288         static struct option long_opts[] = {
289                 {"help", no_argument, 0, 'h'},
290                 {"version", no_argument, 0, 'V'},
291                 {"verbose", no_argument, 0, 'v'},
292                 {"timeout", required_argument, 0, 't'},
293                 {"hostname", required_argument, 0, 'H'},
294                 {"server", required_argument, 0, 's'},
295                 {"reverse-server", required_argument, 0, 'r'},
296                 {"expected-address", required_argument, 0, 'a'},
297                 {0, 0, 0, 0}
298         };
300         if (argc < 2)
301                 return ERROR;
303         for (c = 1; c < argc; c++)
304                 if (strcmp ("-to", argv[c]) == 0)
305                         strcpy (argv[c], "-t");
307         while (1) {
308                 c = getopt_long (argc, argv, "hVvt:H:s:r:a:", long_opts, &opt_index);
310                 if (c == -1 || c == EOF)
311                         break;
313                 switch (c) {
314                 case '?': /* args not parsable */
315                         printf ("%s: Unknown argument: %s\n\n", progname, optarg);
316                         print_usage ();
317                         exit (STATE_UNKNOWN);
318                 case 'h': /* help */
319                         print_help ();
320                         exit (STATE_OK);
321                 case 'V': /* version */
322                         print_revision (progname, REVISION);
323                         exit (STATE_OK);
324                 case 'v': /* version */
325                         verbose = TRUE;
326                         break;
327                 case 't': /* timeout period */
328                         timeout_interval = atoi (optarg);
329                         break;
330                 case 'H': /* hostname */
331                         if (strlen (optarg) >= ADDRESS_LENGTH)
332                                 terminate (STATE_UNKNOWN, "Input buffer overflow\n");
333                         strcpy (query_address, optarg);
334                         break;
335                 case 's': /* server name */
336                         /* TODO: this is_host check is probably unnecessary. Better to confirm nslookup
337                            response matches */
338                         if (is_host (optarg) == FALSE) {
339                                 printf ("Invalid server name/address\n\n");
340                                 print_usage ();
341                                 exit (STATE_UNKNOWN);
342                         }
343                         if (strlen (optarg) >= ADDRESS_LENGTH)
344                                 terminate (STATE_UNKNOWN, "Input buffer overflow\n");
345                         strcpy (dns_server, optarg);
346                         break;
347                 case 'r': /* reverse server name */
348                         /* TODO: Is this is_host necessary? */
349                         if (is_host (optarg) == FALSE) {
350                                 printf ("Invalid host name/address\n\n");
351                                 print_usage ();
352                                 exit (STATE_UNKNOWN);
353                         }
354                         if (strlen (optarg) >= ADDRESS_LENGTH)
355                                 terminate (STATE_UNKNOWN, "Input buffer overflow\n");
356                         strcpy (ptr_server, optarg);
357                         break;
358                 case 'a': /* expected address */
359                         if (strlen (optarg) >= ADDRESS_LENGTH)
360                                 terminate (STATE_UNKNOWN, "Input buffer overflow\n");
361                         strcpy (expected_address, optarg);
362                         match_expected_address = TRUE;
363                         break;
364                 }
365         }
367         c = optind;
368         if (strlen(query_address)==0 && c<argc) {
369                 if (strlen(argv[c])>=ADDRESS_LENGTH)
370                         terminate (STATE_UNKNOWN, "Input buffer overflow\n");
371                 strcpy (query_address, argv[c++]);
372         }
374         if (strlen(dns_server)==0 && c<argc) {
375                 /* TODO: See -s option */
376                 if (is_host(argv[c]) == FALSE) {
377                         printf ("Invalid name/address: %s\n\n", argv[c]);
378                         return ERROR;
379                 }
380                 if (strlen(argv[c]) >= ADDRESS_LENGTH)
381                         terminate (STATE_UNKNOWN, "Input buffer overflow\n");
382                 strcpy (dns_server, argv[c++]);
383         }
385         return validate_arguments ();
388 int
389 validate_arguments ()
391         if (query_address[0] == 0)
392                 return ERROR;
393         else
394                 return OK;
397 void
398 print_usage (void)
400         printf ("Usage: %s -H host [-s server] [-a expected-address] [-t timeout]\n" "       %s --help\n"
401                                         "       %s --version\n", progname, progname, progname);
404 void
405 print_help (void)
407         print_revision (progname, REVISION);
408         printf ("Copyright (c) 1999 Ethan Galstad (nagios@nagios.org)\n\n");
409         print_usage ();
410         printf
411                 ("\nOptions:\n"
412                  "-H, --hostname=HOST\n"
413                  "   The name or address you want to query\n"
414                  "-s, --server=HOST\n"
415                  "   Optional DNS server you want to use for the lookup\n"
416                  "-a, --expected-address=IP-ADDRESS\n"
417                  "   Optional IP address you expect the DNS server to return\n"
418                  "-t, --timeout=INTEGER\n"
419                  "   Seconds before connection times out (default: %d)\n"
420                  "-h, --help\n"
421                  "   Print detailed help\n"
422                  "-V, --version\n"
423                  "   Print version numbers and license information\n"
424                  "\n"
425                  "This plugin uses the nslookup program to obtain the IP address\n"
426                  "for the given host/domain query.  A optional DNS server to use may\n"
427                  "be specified.  If no DNS server is specified, the default server(s)\n"
428                  "specified in /etc/resolv.conf will be used.\n", DEFAULT_SOCKET_TIMEOUT);