Code

Bug from code-clean (Antony Simmonds - 846311)
[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"
50 #include "netutils.h"
52 const char *progname = "check_dns";
53 const char *revision = "$Revision$";
54 const char *copyright = "2000-2003";
55 const char *email = "nagiosplug-devel@lists.sourceforge.net";
57 int process_arguments (int, char **);
58 int validate_arguments (void);
59 int error_scan (char *);
60 void print_help (void);
61 void print_usage (void);
63 #define ADDRESS_LENGTH 256
64 char query_address[ADDRESS_LENGTH] = "";
65 char dns_server[ADDRESS_LENGTH] = "";
66 char ptr_server[ADDRESS_LENGTH] = "";
67 int verbose = FALSE;
68 char expected_address[ADDRESS_LENGTH] = "";
69 int match_expected_address = FALSE;
71 int
72 main (int argc, char **argv)
73 {
74         char *command_line = NULL;
75         char input_buffer[MAX_INPUT_BUFFER];
76         char *output = NULL;
77         char *address = NULL;
78         char *temp_buffer = NULL;
79         int result = STATE_UNKNOWN;
80         double elapsed_time;
81         long microsec;
82         struct timeval tv;
83         int multi_address;
85         setlocale (LC_ALL, "");
86         bindtextdomain (PACKAGE, LOCALEDIR);
87         textdomain (PACKAGE);
89         /* Set signal handling and alarm */
90         if (signal (SIGALRM, popen_timeout_alarm_handler) == SIG_ERR) {
91                 printf (_("Cannot catch SIGALRM"));
92                 return STATE_UNKNOWN;
93         }
95         if (process_arguments (argc, argv) != OK) {
96                 print_usage ();
97                 return STATE_UNKNOWN;
98         }
100         /* get the command to run */
101         asprintf (&command_line, "%s %s %s", NSLOOKUP_COMMAND,  query_address, dns_server);
103         alarm (timeout_interval);
104         gettimeofday (&tv, NULL);
106         if (verbose)
107                 printf ("%s\n", command_line);
108         /* run the command */
109         child_process = spopen (command_line);
110         if (child_process == NULL) {
111                 printf (_("Could not open pipe: %s\n"), command_line);
112                 return STATE_UNKNOWN;
113         }
115         child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r");
116         if (child_stderr == NULL)
117                 printf (_("Could not open stderr for %s\n"), command_line);
119         /* scan stdout */
120         while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process)) {
122                 if (verbose)
123                         printf ("%s\n", input_buffer);
125                 if (strstr (input_buffer, ".in-addr.arpa")) {
126                         if ((temp_buffer = strstr (input_buffer, "name = ")))
127                                 address = strdup (temp_buffer + 7);
128                         else {
129                                 output = strdup (_("Unknown error (plugin)"));
130                                 result = STATE_WARNING;
131                         }
132                 }
134                 /* the server is responding, we just got the host name... */
135                 if (strstr (input_buffer, "Name:")) {
137                         /* get the host address */
138                         if (!fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process))
139                                 break;
141                         if (verbose)
142                                 printf ("%s\n", input_buffer);
144                         if ((temp_buffer = index (input_buffer, ':'))) {
145                                 temp_buffer++;
146                                 /* Strip leading spaces */
147                                 for (; *temp_buffer != '\0' && *temp_buffer == ' '; temp_buffer++)
148                                         /* NOOP */;
149                                 address = strdup (temp_buffer);
150                                 strip (address);
151                                 if (address==NULL || strlen(address)==0)
152                                         die (STATE_CRITICAL,
153                                                                                  _("DNS CRITICAL - '%s' returned empty host name string\n"),
154                                                                                  NSLOOKUP_COMMAND);
155                                 result = STATE_OK;
156                         }
157                         else {
158                                 output = strdup (_("Unknown error (plugin)"));
159                                 result = STATE_WARNING;
160                         }
162                         break;
163                 }
165                 result = error_scan (input_buffer);
166                 if (result != STATE_OK) {
167                         output = strdup (1 + index (input_buffer, ':'));
168                         strip (output);
169                         break;
170                 }
172         }
174         /* scan stderr */
175         while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) {
176                 if (error_scan (input_buffer) != STATE_OK) {
177                         result = max_state (result, error_scan (input_buffer));
178                         output = strdup (1 + index (input_buffer, ':'));
179                         strip (output);
180                 }
181         }
183         /* close stderr */
184         (void) fclose (child_stderr);
186         /* close stdout */
187         if (spclose (child_process)) {
188                 result = max_state (result, STATE_WARNING);
189                 if (!strcmp (output, ""))
190                         output = strdup (_("nslookup returned error status"));
191         }
193         /* If we got here, we should have an address string, 
194                  and we can segfault if we do not */
195         if (address==NULL || strlen(address)==0)
196                 die (STATE_CRITICAL,
197                                                          _("DNS CRITICAL - '%s' output parsing exited with no address\n"),
198                                                          NSLOOKUP_COMMAND);
200         /* compare to expected address */
201         if (result == STATE_OK && match_expected_address && strcmp(address, expected_address)) {
202                 result = STATE_CRITICAL;
203                 asprintf(&output, _("expected %s but got %s"), expected_address, address);
204         }
206         microsec = deltime (tv);
207         elapsed_time = (double)microsec / 1.0e6;
209         if (result == STATE_OK) {
210                 if (strchr (address, ',') == NULL)
211                         multi_address = FALSE;
212                 else
213                         multi_address = TRUE;
215                 printf (_("DNS ok - %.3f seconds response time, address%s %s|%s\n"),
216                                                 elapsed_time, (multi_address==TRUE ? "es are" : " is"), address,
217                                                 perfdata ("time", microsec, "us", FALSE, 0, FALSE, 0, TRUE, 0, FALSE, 0));
218         }
219         else if (result == STATE_WARNING)
220                 printf (_("DNS WARNING - %s\n"),
221                                                 !strcmp (output, "") ? _(" Probably a non-existent host/domain") : output);
222         else if (result == STATE_CRITICAL)
223                 printf (_("DNS CRITICAL - %s\n"),
224                                                 !strcmp (output, "") ? _(" Probably a non-existent host/domain") : output);
225         else
226                 printf (_("DNS problem - %s\n"),
227                                                 !strcmp (output, "") ? _(" Probably a non-existent host/domain") : output);
229         return result;
232 int
233 error_scan (char *input_buffer)
236         /* the DNS lookup timed out */
237         if (strstr (input_buffer,       "Note:  nslookup is deprecated and may be removed from future releases.") ||
238             strstr (input_buffer, "Consider using the `dig' or `host' programs instead.  Run nslookup with") ||
239             strstr (input_buffer, "the `-sil[ent]' option to prevent this message from appearing."))
240                 return STATE_OK;
242         /* DNS server is not running... */
243         else if (strstr (input_buffer, "No response from server"))
244                 die (STATE_CRITICAL, _("No response from name server %s\n"), dns_server);
246         /* Host name is valid, but server doesn't have records... */
247         else if (strstr (input_buffer, "No records"))
248                 die (STATE_CRITICAL, _("Name server %s has no records\n"), dns_server);
250         /* Connection was refused */
251         else if (strstr (input_buffer, "Connection refused") ||
252                  (strstr (input_buffer, "** server can't find") &&
253                   strstr (input_buffer, ": REFUSED")) ||
254                  (strstr (input_buffer, "Refused")))
255                 die (STATE_CRITICAL, _("Connection to name server %s was refused\n"), dns_server);
257         /* Host or domain name does not exist */
258         else if (strstr (input_buffer, "Non-existent") ||
259                  strstr (input_buffer, "** server can't find") ||
260                  strstr (input_buffer,"NXDOMAIN"))
261                 die (STATE_CRITICAL, _("Domain %s was not found by the server\n"), query_address);
263         /* Network is unreachable */
264         else if (strstr (input_buffer, "Network is unreachable"))
265                 die (STATE_CRITICAL, _("Network is unreachable\n"));
267         /* Internal server failure */
268         else if (strstr (input_buffer, "Server failure"))
269                 die (STATE_CRITICAL, _("Server failure for %s\n"), dns_server);
271         /* Request error or the DNS lookup timed out */
272         else if (strstr (input_buffer, "Format error") ||
273                  strstr (input_buffer, "Timed out"))
274                 return STATE_WARNING;
276         return STATE_OK;
280 /* process command-line arguments */
281 int
282 process_arguments (int argc, char **argv)
284         int c;
286         int opt_index = 0;
287         static struct option long_opts[] = {
288                 {"help", no_argument, 0, 'h'},
289                 {"version", no_argument, 0, 'V'},
290                 {"verbose", no_argument, 0, 'v'},
291                 {"timeout", required_argument, 0, 't'},
292                 {"hostname", required_argument, 0, 'H'},
293                 {"server", required_argument, 0, 's'},
294                 {"reverse-server", required_argument, 0, 'r'},
295                 {"expected-address", required_argument, 0, 'a'},
296                 {0, 0, 0, 0}
297         };
299         if (argc < 2)
300                 return ERROR;
302         for (c = 1; c < argc; c++)
303                 if (strcmp ("-to", argv[c]) == 0)
304                         strcpy (argv[c], "-t");
306         while (1) {
307                 c = getopt_long (argc, argv, "hVvt:H:s:r:a:", long_opts, &opt_index);
309                 if (c == -1 || c == EOF)
310                         break;
312                 switch (c) {
313                 case '?': /* args not parsable */
314                         printf (_("%s: Unknown argument: %s\n\n"), progname, optarg);
315                         print_usage ();
316                         exit (STATE_UNKNOWN);
317                 case 'h': /* help */
318                         print_help ();
319                         exit (STATE_OK);
320                 case 'V': /* version */
321                         print_revision (progname, revision);
322                         exit (STATE_OK);
323                 case 'v': /* version */
324                         verbose = TRUE;
325                         break;
326                 case 't': /* timeout period */
327                         timeout_interval = atoi (optarg);
328                         break;
329                 case 'H': /* hostname */
330                         if (strlen (optarg) >= ADDRESS_LENGTH)
331                                 die (STATE_UNKNOWN, _("Input buffer overflow\n"));
332                         strcpy (query_address, optarg);
333                         break;
334                 case 's': /* server name */
335                         /* TODO: this is_host check is probably unnecessary. Better to confirm nslookup
336                            response matches */
337                         if (is_host (optarg) == FALSE) {
338                                 printf (_("Invalid server name/address\n\n"));
339                                 print_usage ();
340                                 exit (STATE_UNKNOWN);
341                         }
342                         if (strlen (optarg) >= ADDRESS_LENGTH)
343                                 die (STATE_UNKNOWN, _("Input buffer overflow\n"));
344                         strcpy (dns_server, optarg);
345                         break;
346                 case 'r': /* reverse server name */
347                         /* TODO: Is this is_host necessary? */
348                         if (is_host (optarg) == FALSE) {
349                                 printf (_("Invalid host name/address\n\n"));
350                                 print_usage ();
351                                 exit (STATE_UNKNOWN);
352                         }
353                         if (strlen (optarg) >= ADDRESS_LENGTH)
354                                 die (STATE_UNKNOWN, _("Input buffer overflow\n"));
355                         strcpy (ptr_server, optarg);
356                         break;
357                 case 'a': /* expected address */
358                         if (strlen (optarg) >= ADDRESS_LENGTH)
359                                 die (STATE_UNKNOWN, _("Input buffer overflow\n"));
360                         strcpy (expected_address, optarg);
361                         match_expected_address = TRUE;
362                         break;
363                 }
364         }
366         c = optind;
367         if (strlen(query_address)==0 && c<argc) {
368                 if (strlen(argv[c])>=ADDRESS_LENGTH)
369                         die (STATE_UNKNOWN, _("Input buffer overflow\n"));
370                 strcpy (query_address, argv[c++]);
371         }
373         if (strlen(dns_server)==0 && c<argc) {
374                 /* TODO: See -s option */
375                 if (is_host(argv[c]) == FALSE) {
376                         printf (_("Invalid name/address: %s\n\n"), argv[c]);
377                         return ERROR;
378                 }
379                 if (strlen(argv[c]) >= ADDRESS_LENGTH)
380                         die (STATE_UNKNOWN, _("Input buffer overflow\n"));
381                 strcpy (dns_server, argv[c++]);
382         }
384         return validate_arguments ();
387 int
388 validate_arguments ()
390         if (query_address[0] == 0)
391                 return ERROR;
392         else
393                 return OK;
400 \f
401 void
402 print_help (void)
404         print_revision (progname, revision);
406         printf (_("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n"));
407         printf (_(COPYRIGHT), copyright, email);
409         print_usage ();
411         printf (_(UT_HELP_VRSN));
413         printf (_("\
414 -H, --hostname=HOST\n\
415    The name or address you want to query\n\
416 -s, --server=HOST\n\
417    Optional DNS server you want to use for the lookup\n\
418 -a, --expected-address=IP-ADDRESS\n\
419    Optional IP address you expect the DNS server to return\n"));
421         printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
423         printf (_("\n\
424 This plugin uses the nslookup program to obtain the IP address\n\
425 for the given host/domain query.  A optional DNS server to use may\n\
426 be specified.  If no DNS server is specified, the default server(s)\n\
427 specified in /etc/resolv.conf will be used.\n"));
429         printf (_(UT_SUPPORT));
435 void
436 print_usage (void)
438         printf (_("\
439 Usage: %s -H host [-s server] [-a expected-address] [-t timeout]\n\
440        %s --help\n\
441        %s --version\n"),
442                                         progname, progname, progname);