Code

fix a variety of compiler warnings about qualifier discards and other pedantic stuff
[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 void
58 print_usage (void)
59 {
60         printf (_("\
61 Usage: %s -H host [-s server] [-a expected-address] [-t timeout]\n\
62        %s --help\n\
63        %s --version\n"),
64                                         progname, progname, progname);
65 }
67 void
68 print_help (void)
69 {
70         print_revision (progname, revision);
72         printf (_(COPYRIGHT), copyright, email);
74         print_usage ();
76         printf (_(UT_HELP_VRSN));
78         printf (_("\
79 -H, --hostname=HOST\n\
80    The name or address you want to query\n\
81 -s, --server=HOST\n\
82    Optional DNS server you want to use for the lookup\n\
83 -a, --expected-address=IP-ADDRESS\n\
84    Optional IP address you expect the DNS server to return\n"));
86         printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
88         printf (_("\n\
89 This plugin uses the nslookup program to obtain the IP address\n\
90 for the given host/domain query.  A optional DNS server to use may\n\
91 be specified.  If no DNS server is specified, the default server(s)\n\
92 specified in /etc/resolv.conf will be used.\n"));
93 }
95 int process_arguments (int, char **);
96 int validate_arguments (void);
97 int error_scan (char *);
99 #define ADDRESS_LENGTH 256
100 char query_address[ADDRESS_LENGTH] = "";
101 char dns_server[ADDRESS_LENGTH] = "";
102 char ptr_server[ADDRESS_LENGTH] = "";
103 int verbose = FALSE;
104 char expected_address[ADDRESS_LENGTH] = "";
105 int match_expected_address = FALSE;
107 int
108 main (int argc, char **argv)
110         char *command_line = NULL;
111         char input_buffer[MAX_INPUT_BUFFER];
112         char *output = NULL;
113         char *address = NULL;
114         char *temp_buffer = NULL;
115         int result = STATE_UNKNOWN;
116         double elapsed_time;
117         struct timeval tv;
118         int multi_address;
120         /* Set signal handling and alarm */
121         if (signal (SIGALRM, popen_timeout_alarm_handler) == SIG_ERR) {
122                 printf (_("Cannot catch SIGALRM"));
123                 return STATE_UNKNOWN;
124         }
126         if (process_arguments (argc, argv) != OK) {
127                 print_usage ();
128                 return STATE_UNKNOWN;
129         }
131         /* get the command to run */
132         asprintf (&command_line, "%s %s %s", NSLOOKUP_COMMAND,  query_address, dns_server);
134         alarm (timeout_interval);
135         gettimeofday (&tv, NULL);
137         if (verbose)
138                 printf ("%s\n", command_line);
139         /* run the command */
140         child_process = spopen (command_line);
141         if (child_process == NULL) {
142                 printf (_("Could not open pipe: %s\n"), command_line);
143                 return STATE_UNKNOWN;
144         }
146         child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r");
147         if (child_stderr == NULL)
148                 printf (_("Could not open stderr for %s\n"), command_line);
150         /* scan stdout */
151         while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process)) {
153                 if (verbose)
154                         printf ("%s\n", input_buffer);
156                 if (strstr (input_buffer, ".in-addr.arpa")) {
157                         if ((temp_buffer = strstr (input_buffer, "name = ")))
158                                 address = strdup (temp_buffer + 7);
159                         else {
160                                 output = strdup (_("Unknown error (plugin)"));
161                                 result = STATE_WARNING;
162                         }
163                 }
165                 /* the server is responding, we just got the host name... */
166                 if (strstr (input_buffer, "Name:")) {
168                         /* get the host address */
169                         if (!fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process))
170                                 break;
172                         if (verbose)
173                                 printf ("%s\n", input_buffer);
175                         if ((temp_buffer = index (input_buffer, ':'))) {
176                                 temp_buffer++;
177                                 /* Strip leading spaces */
178                                 for (; *temp_buffer != '\0' && *temp_buffer == ' '; temp_buffer++)
179                                         /* NOOP */;
180                                 address = strdup (temp_buffer);
181                                 strip (address);
182                                 if (address==NULL || strlen(address)==0)
183                                         die (STATE_CRITICAL,
184                                                                                  _("DNS CRITICAL - '%s' returned empty host name string\n"),
185                                                                                  NSLOOKUP_COMMAND);
186                                 result = STATE_OK;
187                         }
188                         else {
189                                 output = strdup (_("Unknown error (plugin)"));
190                                 result = STATE_WARNING;
191                         }
193                         break;
194                 }
196                 result = error_scan (input_buffer);
197                 if (result != STATE_OK) {
198                         output = strdup (1 + index (input_buffer, ':'));
199                         strip (output);
200                         break;
201                 }
203         }
205         /* scan stderr */
206         while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) {
207                 if (error_scan (input_buffer) != STATE_OK) {
208                         result = max_state (result, error_scan (input_buffer));
209                         output = strdup (1 + index (input_buffer, ':'));
210                         strip (output);
211                 }
212         }
214         /* close stderr */
215         (void) fclose (child_stderr);
217         /* close stdout */
218         if (spclose (child_process)) {
219                 result = max_state (result, STATE_WARNING);
220                 if (!strcmp (output, ""))
221                         output = strdup (_("nslookup returned error status"));
222         }
224         /* If we got here, we should have an address string, 
225                  and we can segfault if we do not */
226         if (address==NULL || strlen(address)==0)
227                 die (STATE_CRITICAL,
228                                                          _("DNS CRITICAL - '%s' output parsing exited with no address\n"),
229                                                          NSLOOKUP_COMMAND);
231         /* compare to expected address */
232         if (result == STATE_OK && match_expected_address && strcmp(address, expected_address)) {
233                 result = STATE_CRITICAL;
234                 asprintf(&output, _("expected %s but got %s"), expected_address, address);
235         }
236         
237         elapsed_time = delta_time (tv);
239         if (result == STATE_OK) {
240                 if (strchr (address, ',') == NULL)
241                         multi_address = FALSE;
242                 else
243                         multi_address = TRUE;
245                 printf (_("DNS ok - %.3f seconds response time, address%s %s|time=%.3f\n"),
246                                                 elapsed_time, (multi_address==TRUE ? "es are" : " is"), address, elapsed_time);
247         }
248         else if (result == STATE_WARNING)
249                 printf (_("DNS WARNING - %s\n"),
250                                                 !strcmp (output, "") ? _(" Probably a non-existent host/domain") : output);
251         else if (result == STATE_CRITICAL)
252                 printf (_("DNS CRITICAL - %s\n"),
253                                                 !strcmp (output, "") ? _(" Probably a non-existent host/domain") : output);
254         else
255                 printf (_("DNS problem - %s\n"),
256                                                 !strcmp (output, "") ? _(" Probably a non-existent host/domain") : output);
258         return result;
261 int
262 error_scan (char *input_buffer)
265         /* the DNS lookup timed out */
266         if (strstr (input_buffer,       "Note:  nslookup is deprecated and may be removed from future releases.") ||
267             strstr (input_buffer, "Consider using the `dig' or `host' programs instead.  Run nslookup with") ||
268             strstr (input_buffer, "the `-sil[ent]' option to prevent this message from appearing."))
269                 return STATE_OK;
271         /* DNS server is not running... */
272         else if (strstr (input_buffer, "No response from server"))
273                 die (STATE_CRITICAL, _("No response from name server %s\n"), dns_server);
275         /* Host name is valid, but server doesn't have records... */
276         else if (strstr (input_buffer, "No records"))
277                 die (STATE_CRITICAL, _("Name server %s has no records\n"), dns_server);
279         /* Connection was refused */
280         else if (strstr (input_buffer, "Connection refused") ||
281                  (strstr (input_buffer, "** server can't find") &&
282                   strstr (input_buffer, ": REFUSED")) ||
283                  (strstr (input_buffer, "Refused")))
284                 die (STATE_CRITICAL, _("Connection to name server %s was refused\n"), dns_server);
286         /* Host or domain name does not exist */
287         else if (strstr (input_buffer, "Non-existent") ||
288                  strstr (input_buffer, "** server can't find") ||
289                  strstr (input_buffer,"NXDOMAIN"))
290                 die (STATE_CRITICAL, _("Domain %s was not found by the server\n"), query_address);
292         /* Network is unreachable */
293         else if (strstr (input_buffer, "Network is unreachable"))
294                 die (STATE_CRITICAL, _("Network is unreachable\n"));
296         /* Internal server failure */
297         else if (strstr (input_buffer, "Server failure"))
298                 die (STATE_CRITICAL, _("Server failure for %s\n"), dns_server);
300         /* Request error or the DNS lookup timed out */
301         else if (strstr (input_buffer, "Format error") ||
302                  strstr (input_buffer, "Timed out"))
303                 return STATE_WARNING;
305         return STATE_OK;
309 /* process command-line arguments */
310 int
311 process_arguments (int argc, char **argv)
313         int c;
315         int opt_index = 0;
316         static struct option long_opts[] = {
317                 {"help", no_argument, 0, 'h'},
318                 {"version", no_argument, 0, 'V'},
319                 {"verbose", no_argument, 0, 'v'},
320                 {"timeout", required_argument, 0, 't'},
321                 {"hostname", required_argument, 0, 'H'},
322                 {"server", required_argument, 0, 's'},
323                 {"reverse-server", required_argument, 0, 'r'},
324                 {"expected-address", required_argument, 0, 'a'},
325                 {0, 0, 0, 0}
326         };
328         if (argc < 2)
329                 return ERROR;
331         for (c = 1; c < argc; c++)
332                 if (strcmp ("-to", argv[c]) == 0)
333                         strcpy (argv[c], "-t");
335         while (1) {
336                 c = getopt_long (argc, argv, "hVvt:H:s:r:a:", long_opts, &opt_index);
338                 if (c == -1 || c == EOF)
339                         break;
341                 switch (c) {
342                 case '?': /* args not parsable */
343                         printf (_("%s: Unknown argument: %s\n\n"), progname, optarg);
344                         print_usage ();
345                         exit (STATE_UNKNOWN);
346                 case 'h': /* help */
347                         print_help ();
348                         exit (STATE_OK);
349                 case 'V': /* version */
350                         print_revision (progname, revision);
351                         exit (STATE_OK);
352                 case 'v': /* version */
353                         verbose = TRUE;
354                         break;
355                 case 't': /* timeout period */
356                         timeout_interval = atoi (optarg);
357                         break;
358                 case 'H': /* hostname */
359                         if (strlen (optarg) >= ADDRESS_LENGTH)
360                                 die (STATE_UNKNOWN, _("Input buffer overflow\n"));
361                         strcpy (query_address, optarg);
362                         break;
363                 case 's': /* server name */
364                         /* TODO: this is_host check is probably unnecessary. Better to confirm nslookup
365                            response matches */
366                         if (is_host (optarg) == FALSE) {
367                                 printf (_("Invalid server name/address\n\n"));
368                                 print_usage ();
369                                 exit (STATE_UNKNOWN);
370                         }
371                         if (strlen (optarg) >= ADDRESS_LENGTH)
372                                 die (STATE_UNKNOWN, _("Input buffer overflow\n"));
373                         strcpy (dns_server, optarg);
374                         break;
375                 case 'r': /* reverse server name */
376                         /* TODO: Is this is_host necessary? */
377                         if (is_host (optarg) == FALSE) {
378                                 printf (_("Invalid host name/address\n\n"));
379                                 print_usage ();
380                                 exit (STATE_UNKNOWN);
381                         }
382                         if (strlen (optarg) >= ADDRESS_LENGTH)
383                                 die (STATE_UNKNOWN, _("Input buffer overflow\n"));
384                         strcpy (ptr_server, optarg);
385                         break;
386                 case 'a': /* expected address */
387                         if (strlen (optarg) >= ADDRESS_LENGTH)
388                                 die (STATE_UNKNOWN, _("Input buffer overflow\n"));
389                         strcpy (expected_address, optarg);
390                         match_expected_address = TRUE;
391                         break;
392                 }
393         }
395         c = optind;
396         if (strlen(query_address)==0 && c<argc) {
397                 if (strlen(argv[c])>=ADDRESS_LENGTH)
398                         die (STATE_UNKNOWN, _("Input buffer overflow\n"));
399                 strcpy (query_address, argv[c++]);
400         }
402         if (strlen(dns_server)==0 && c<argc) {
403                 /* TODO: See -s option */
404                 if (is_host(argv[c]) == FALSE) {
405                         printf (_("Invalid name/address: %s\n\n"), argv[c]);
406                         return ERROR;
407                 }
408                 if (strlen(argv[c]) >= ADDRESS_LENGTH)
409                         die (STATE_UNKNOWN, _("Input buffer overflow\n"));
410                 strcpy (dns_server, argv[c++]);
411         }
413         return validate_arguments ();
416 int
417 validate_arguments ()
419         if (query_address[0] == 0)
420                 return ERROR;
421         else
422                 return OK;