1 /*****************************************************************************
2 *
3 * Nagios check_ping plugin
4 *
5 * License: GPL
6 * Copyright (c) 2000-2007 Nagios Plugins Development Team
7 *
8 * Last Modified: $Date$
9 *
10 * Description:
11 *
12 * This file contains the check_ping plugin
13 *
14 * Use the ping program to check connection statistics for a remote host.
15 *
16 *
17 * This program is free software: you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation, either version 3 of the License, or
20 * (at your option) any later version.
21 *
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
26 *
27 * You should have received a copy of the GNU General Public License
28 * along with this program. If not, see <http://www.gnu.org/licenses/>.
29 *
30 * $Id$
31 *
32 *****************************************************************************/
34 const char *progname = "check_ping";
35 const char *revision = "$Revision$";
36 const char *copyright = "2000-2007";
37 const char *email = "nagiosplug-devel@lists.sourceforge.net";
39 #include "common.h"
40 #include "netutils.h"
41 #include "popen.h"
42 #include "utils.h"
44 #define WARN_DUPLICATES "DUPLICATES FOUND! "
45 #define UNKNOWN_TRIP_TIME -1.0 /* -1 seconds */
47 enum {
48 UNKNOWN_PACKET_LOSS = 200, /* 200% */
49 DEFAULT_MAX_PACKETS = 5 /* default no. of ICMP ECHO packets */
50 };
52 int process_arguments (int, char **);
53 int get_threshold (char *, float *, int *);
54 int validate_arguments (void);
55 int run_ping (const char *cmd, const char *addr);
56 int error_scan (char buf[MAX_INPUT_BUFFER], const char *addr);
57 void print_usage (void);
58 void print_help (void);
60 int display_html = FALSE;
61 int wpl = UNKNOWN_PACKET_LOSS;
62 int cpl = UNKNOWN_PACKET_LOSS;
63 float wrta = UNKNOWN_TRIP_TIME;
64 float crta = UNKNOWN_TRIP_TIME;
65 char **addresses = NULL;
66 int n_addresses = 0;
67 int max_addr = 1;
68 int max_packets = -1;
69 int verbose = 0;
71 float rta = UNKNOWN_TRIP_TIME;
72 int pl = UNKNOWN_PACKET_LOSS;
74 char *warn_text;
78 int
79 main (int argc, char **argv)
80 {
81 char *cmd = NULL;
82 char *rawcmd = NULL;
83 int result = STATE_UNKNOWN;
84 int this_result = STATE_UNKNOWN;
85 int i;
87 setlocale (LC_ALL, "");
88 setlocale (LC_NUMERIC, "C");
89 bindtextdomain (PACKAGE, LOCALEDIR);
90 textdomain (PACKAGE);
92 addresses = malloc (sizeof(char*) * max_addr);
93 addresses[0] = NULL;
95 if (process_arguments (argc, argv) == ERROR)
96 usage4 (_("Could not parse arguments"));
98 /* Set signal handling and alarm */
99 if (signal (SIGALRM, popen_timeout_alarm_handler) == SIG_ERR) {
100 usage4 (_("Cannot catch SIGALRM"));
101 }
103 /* If ./configure finds ping has timeout values, set plugin alarm slightly
104 * higher so that we can use response from command line ping */
105 #if defined(PING_PACKETS_FIRST) && defined(PING_HAS_TIMEOUT)
106 alarm (timeout_interval + 1);
107 #else
108 alarm (timeout_interval);
109 #endif
111 for (i = 0 ; i < n_addresses ; i++) {
113 #ifdef PING6_COMMAND
114 if (address_family != AF_INET && is_inet6_addr(addresses[i]))
115 rawcmd = strdup(PING6_COMMAND);
116 else
117 rawcmd = strdup(PING_COMMAND);
118 #else
119 rawcmd = strdup(PING_COMMAND);
120 #endif
122 /* does the host address of number of packets argument come first? */
123 #ifdef PING_PACKETS_FIRST
124 # ifdef PING_HAS_TIMEOUT
125 asprintf (&cmd, rawcmd, timeout_interval, max_packets, addresses[i]);
126 # else
127 asprintf (&cmd, rawcmd, max_packets, addresses[i]);
128 # endif
129 #else
130 asprintf (&cmd, rawcmd, addresses[i], max_packets);
131 #endif
133 if (verbose >= 2)
134 printf ("CMD: %s\n", cmd);
136 /* run the command */
137 this_result = run_ping (cmd, addresses[i]);
139 if (pl == UNKNOWN_PACKET_LOSS || rta < 0.0) {
140 printf ("%s\n", cmd);
141 die (STATE_UNKNOWN,
142 _("CRITICAL - Could not interpret output from ping command\n"));
143 }
145 if (pl >= cpl || rta >= crta || rta < 0)
146 this_result = STATE_CRITICAL;
147 else if (pl >= wpl || rta >= wrta)
148 this_result = STATE_WARNING;
149 else if (pl >= 0 && rta >= 0)
150 this_result = max_state (STATE_OK, this_result);
152 if (n_addresses > 1 && this_result != STATE_UNKNOWN)
153 die (STATE_OK, "%s is alive\n", addresses[i]);
155 if (display_html == TRUE)
156 printf ("<A HREF='%s/traceroute.cgi?%s'>", CGIURL, addresses[i]);
157 if (pl == 100)
158 printf (_("PING %s - %sPacket loss = %d%%"), state_text (this_result), warn_text,
159 pl);
160 else
161 printf (_("PING %s - %sPacket loss = %d%%, RTA = %2.2f ms"),
162 state_text (this_result), warn_text, pl, rta);
163 if (display_html == TRUE)
164 printf ("</A>");
166 /* Print performance data */
167 printf("|%s", fperfdata ("rta", (double) rta, "ms",
168 wrta>0?TRUE:FALSE, wrta,
169 crta>0?TRUE:FALSE, crta,
170 TRUE, 0, FALSE, 0));
171 printf(" %s\n", perfdata ("pl", (long) pl, "%",
172 wpl>0?TRUE:FALSE, wpl,
173 cpl>0?TRUE:FALSE, cpl,
174 TRUE, 0, FALSE, 0));
176 if (verbose >= 2)
177 printf ("%f:%d%% %f:%d%%\n", wrta, wpl, crta, cpl);
179 result = max_state (result, this_result);
180 free (rawcmd);
181 free (cmd);
182 }
184 return result;
185 }
189 /* process command-line arguments */
190 int
191 process_arguments (int argc, char **argv)
192 {
193 int c = 1;
194 char *ptr;
196 int option = 0;
197 static struct option longopts[] = {
198 STD_LONG_OPTS,
199 {"packets", required_argument, 0, 'p'},
200 {"nohtml", no_argument, 0, 'n'},
201 {"link", no_argument, 0, 'L'},
202 {"use-ipv4", no_argument, 0, '4'},
203 {"use-ipv6", no_argument, 0, '6'},
204 {0, 0, 0, 0}
205 };
207 if (argc < 2)
208 return ERROR;
210 for (c = 1; c < argc; c++) {
211 if (strcmp ("-to", argv[c]) == 0)
212 strcpy (argv[c], "-t");
213 if (strcmp ("-nohtml", argv[c]) == 0)
214 strcpy (argv[c], "-n");
215 }
217 while (1) {
218 c = getopt_long (argc, argv, "VvhnL46t:c:w:H:p:", longopts, &option);
220 if (c == -1 || c == EOF)
221 break;
223 switch (c) {
224 case '?': /* usage */
225 usage5 ();
226 case 'h': /* help */
227 print_help ();
228 exit (STATE_OK);
229 break;
230 case 'V': /* version */
231 print_revision (progname, revision);
232 exit (STATE_OK);
233 break;
234 case 't': /* timeout period */
235 timeout_interval = atoi (optarg);
236 break;
237 case 'v': /* verbose mode */
238 verbose++;
239 break;
240 case '4': /* IPv4 only */
241 address_family = AF_INET;
242 break;
243 case '6': /* IPv6 only */
244 #ifdef USE_IPV6
245 address_family = AF_INET6;
246 #else
247 usage (_("IPv6 support not available\n"));
248 #endif
249 break;
250 case 'H': /* hostname */
251 ptr=optarg;
252 while (1) {
253 n_addresses++;
254 if (n_addresses > max_addr) {
255 max_addr *= 2;
256 addresses = realloc (addresses, sizeof(char*) * max_addr);
257 if (addresses == NULL)
258 die (STATE_UNKNOWN, _("Could not realloc() addresses\n"));
259 }
260 addresses[n_addresses-1] = ptr;
261 if ((ptr = index (ptr, ','))) {
262 strcpy (ptr, "");
263 ptr += sizeof(char);
264 } else {
265 break;
266 }
267 }
268 break;
269 case 'p': /* number of packets to send */
270 if (is_intnonneg (optarg))
271 max_packets = atoi (optarg);
272 else
273 usage2 (_("<max_packets> (%s) must be a non-negative number\n"), optarg);
274 break;
275 case 'n': /* no HTML */
276 display_html = FALSE;
277 break;
278 case 'L': /* show HTML */
279 display_html = TRUE;
280 break;
281 case 'c':
282 get_threshold (optarg, &crta, &cpl);
283 break;
284 case 'w':
285 get_threshold (optarg, &wrta, &wpl);
286 break;
287 }
288 }
290 c = optind;
291 if (c == argc)
292 return validate_arguments ();
294 if (addresses[0] == NULL) {
295 if (is_host (argv[c]) == FALSE) {
296 usage2 (_("Invalid hostname/address"), argv[c]);
297 } else {
298 addresses[0] = argv[c++];
299 n_addresses++;
300 if (c == argc)
301 return validate_arguments ();
302 }
303 }
305 if (wpl == UNKNOWN_PACKET_LOSS) {
306 if (is_intpercent (argv[c]) == FALSE) {
307 printf (_("<wpl> (%s) must be an integer percentage\n"), argv[c]);
308 return ERROR;
309 } else {
310 wpl = atoi (argv[c++]);
311 if (c == argc)
312 return validate_arguments ();
313 }
314 }
316 if (cpl == UNKNOWN_PACKET_LOSS) {
317 if (is_intpercent (argv[c]) == FALSE) {
318 printf (_("<cpl> (%s) must be an integer percentage\n"), argv[c]);
319 return ERROR;
320 } else {
321 cpl = atoi (argv[c++]);
322 if (c == argc)
323 return validate_arguments ();
324 }
325 }
327 if (wrta < 0.0) {
328 if (is_negative (argv[c])) {
329 printf (_("<wrta> (%s) must be a non-negative number\n"), argv[c]);
330 return ERROR;
331 } else {
332 wrta = atof (argv[c++]);
333 if (c == argc)
334 return validate_arguments ();
335 }
336 }
338 if (crta < 0.0) {
339 if (is_negative (argv[c])) {
340 printf (_("<crta> (%s) must be a non-negative number\n"), argv[c]);
341 return ERROR;
342 } else {
343 crta = atof (argv[c++]);
344 if (c == argc)
345 return validate_arguments ();
346 }
347 }
349 if (max_packets == -1) {
350 if (is_intnonneg (argv[c])) {
351 max_packets = atoi (argv[c++]);
352 } else {
353 printf (_("<max_packets> (%s) must be a non-negative number\n"), argv[c]);
354 return ERROR;
355 }
356 }
358 return validate_arguments ();
359 }
363 int
364 get_threshold (char *arg, float *trta, int *tpl)
365 {
366 if (is_intnonneg (arg) && sscanf (arg, "%f", trta) == 1)
367 return OK;
368 else if (strpbrk (arg, ",:") && strstr (arg, "%") && sscanf (arg, "%f%*[:,]%d%%", trta, tpl) == 2)
369 return OK;
370 else if (strstr (arg, "%") && sscanf (arg, "%d%%", tpl) == 1)
371 return OK;
373 usage2 (_("%s: Warning threshold must be integer or percentage!\n\n"), arg);
374 return STATE_UNKNOWN;
375 }
379 int
380 validate_arguments ()
381 {
382 float max_seconds;
383 int i;
385 if (wrta < 0.0) {
386 printf (_("<wrta> was not set\n"));
387 return ERROR;
388 }
389 else if (crta < 0.0) {
390 printf (_("<crta> was not set\n"));
391 return ERROR;
392 }
393 else if (wpl == UNKNOWN_PACKET_LOSS) {
394 printf (_("<wpl> was not set\n"));
395 return ERROR;
396 }
397 else if (cpl == UNKNOWN_PACKET_LOSS) {
398 printf (_("<cpl> was not set\n"));
399 return ERROR;
400 }
401 else if (wrta > crta) {
402 printf (_("<wrta> (%f) cannot be larger than <crta> (%f)\n"), wrta, crta);
403 return ERROR;
404 }
405 else if (wpl > cpl) {
406 printf (_("<wpl> (%d) cannot be larger than <cpl> (%d)\n"), wpl, cpl);
407 return ERROR;
408 }
410 if (max_packets == -1)
411 max_packets = DEFAULT_MAX_PACKETS;
413 max_seconds = crta / 1000.0 * max_packets + max_packets;
414 if (max_seconds > timeout_interval)
415 timeout_interval = (int)max_seconds;
417 for (i=0; i<n_addresses; i++) {
418 if (is_host(addresses[i]) == FALSE)
419 usage2 (_("Invalid hostname/address"), addresses[i]);
420 }
422 if (n_addresses == 0) {
423 usage (_("You must specify a server address or host name"));
424 }
426 return OK;
427 }
431 int
432 run_ping (const char *cmd, const char *addr)
433 {
434 char buf[MAX_INPUT_BUFFER];
435 int result = STATE_UNKNOWN;
437 if ((child_process = spopen (cmd)) == NULL)
438 die (STATE_UNKNOWN, _("Could not open pipe: %s\n"), cmd);
440 child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r");
441 if (child_stderr == NULL)
442 printf (_("Cannot open stderr for %s\n"), cmd);
444 while (fgets (buf, MAX_INPUT_BUFFER - 1, child_process)) {
446 if (verbose >= 3)
447 printf("Output: %s", buf);
449 result = max_state (result, error_scan (buf, addr));
451 /* get the percent loss statistics */
452 if(sscanf(buf,"%*d packets transmitted, %*d packets received, +%*d errors, %d%% packet loss",&pl)==1 ||
453 sscanf(buf,"%*d packets transmitted, %*d packets received, +%*d duplicates, %d%% packet loss", &pl) == 1 ||
454 sscanf(buf,"%*d packets transmitted, %*d received, +%*d duplicates, %d%% packet loss", &pl) == 1 ||
455 sscanf(buf,"%*d packets transmitted, %*d packets received, %d%% packet loss",&pl)==1 ||
456 sscanf(buf,"%*d packets transmitted, %*d packets received, %d%% loss, time",&pl)==1 ||
457 sscanf(buf,"%*d packets transmitted, %*d received, %d%% loss, time", &pl)==1 ||
458 sscanf(buf,"%*d packets transmitted, %*d received, %d%% packet loss, time", &pl)==1 ||
459 sscanf(buf,"%*d packets transmitted, %*d received, +%*d errors, %d%% packet loss", &pl) == 1 ||
460 sscanf(buf,"%*d packets transmitted %*d received, +%*d errors, %d%% packet loss", &pl) == 1
461 )
462 continue;
464 /* get the round trip average */
465 else
466 if(sscanf(buf,"round-trip min/avg/max = %*f/%f/%*f",&rta)==1 ||
467 sscanf(buf,"round-trip min/avg/max/mdev = %*f/%f/%*f/%*f",&rta)==1 ||
468 sscanf(buf,"round-trip min/avg/max/sdev = %*f/%f/%*f/%*f",&rta)==1 ||
469 sscanf(buf,"round-trip min/avg/max/stddev = %*f/%f/%*f/%*f",&rta)==1 ||
470 sscanf(buf,"round-trip min/avg/max/std-dev = %*f/%f/%*f/%*f",&rta)==1 ||
471 sscanf(buf,"round-trip (ms) min/avg/max = %*f/%f/%*f",&rta)==1 ||
472 sscanf(buf,"round-trip (ms) min/avg/max/stddev = %*f/%f/%*f/%*f",&rta)==1 ||
473 sscanf(buf,"rtt min/avg/max/mdev = %*f/%f/%*f/%*f ms",&rta)==1)
474 continue;
475 }
477 /* this is needed because there is no rta if all packets are lost */
478 if (pl == 100)
479 rta = crta;
481 /* check stderr, setting at least WARNING if there is output here */
482 /* Add warning into warn_text */
483 while (fgets (buf, MAX_INPUT_BUFFER - 1, child_stderr)) {
484 if (! strstr(buf,"WARNING - no SO_TIMESTAMP support, falling back to SIOCGSTAMP")) {
485 if (verbose >= 3) {
486 printf("Got stderr: %s", buf);
487 }
488 if ((result=error_scan(buf, addr)) == STATE_OK) {
489 result = STATE_WARNING;
490 if (warn_text == NULL) {
491 warn_text = strdup(_("System call sent warnings to stderr "));
492 } else {
493 asprintf(&warn_text, "%s %s", warn_text, _("System call sent warnings to stderr "));
494 }
495 }
496 }
497 }
499 (void) fclose (child_stderr);
502 /* close the pipe - WARNING if status is set */
503 if (spclose (child_process))
504 result = max_state (result, STATE_WARNING);
506 if (warn_text == NULL)
507 warn_text = strdup("");
509 return result;
510 }
514 int
515 error_scan (char buf[MAX_INPUT_BUFFER], const char *addr)
516 {
517 if (strstr (buf, "Network is unreachable") ||
518 strstr (buf, "Destination Net Unreachable")
519 )
520 die (STATE_CRITICAL, _("CRITICAL - Network Unreachable (%s)"), addr);
521 else if (strstr (buf, "Destination Host Unreachable"))
522 die (STATE_CRITICAL, _("CRITICAL - Host Unreachable (%s)"), addr);
523 else if (strstr (buf, "Destination Port Unreachable"))
524 die (STATE_CRITICAL, _("CRITICAL - Bogus ICMP: Port Unreachable (%s)"), addr);
525 else if (strstr (buf, "Destination Protocol Unreachable"))
526 die (STATE_CRITICAL, _("CRITICAL - Bogus ICMP: Protocol Unreachable (%s)"), addr);
527 else if (strstr (buf, "Destination Net Prohibited"))
528 die (STATE_CRITICAL, _("CRITICAL - Network Prohibited (%s)"), addr);
529 else if (strstr (buf, "Destination Host Prohibited"))
530 die (STATE_CRITICAL, _("CRITICAL - Host Prohibited (%s)"), addr);
531 else if (strstr (buf, "Packet filtered"))
532 die (STATE_CRITICAL, _("CRITICAL - Packet Filtered (%s)"), addr);
533 else if (strstr (buf, "unknown host" ))
534 die (STATE_CRITICAL, _("CRITICAL - Host not found (%s)"), addr);
535 else if (strstr (buf, "Time to live exceeded"))
536 die (STATE_CRITICAL, _("CRITICAL - Time to live exceeded (%s)"), addr);
538 if (strstr (buf, "(DUP!)") || strstr (buf, "DUPLICATES FOUND")) {
539 if (warn_text == NULL)
540 warn_text = strdup (_(WARN_DUPLICATES));
541 else if (! strstr (warn_text, _(WARN_DUPLICATES)) &&
542 asprintf (&warn_text, "%s %s", warn_text, _(WARN_DUPLICATES)) == -1)
543 die (STATE_UNKNOWN, _("Unable to realloc warn_text"));
544 return (STATE_WARNING);
545 }
547 return (STATE_OK);
548 }
552 void
553 print_help (void)
554 {
555 print_revision (progname, revision);
557 printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
558 printf (COPYRIGHT, copyright, email);
560 printf (_("Use ping to check connection statistics for a remote host."));
562 printf ("\n\n");
564 print_usage ();
566 printf (_(UT_HELP_VRSN));
568 printf (_(UT_IPv46));
570 printf (" %s\n", "-H, --hostname=HOST");
571 printf (" %s\n", _("host to ping"));
572 printf (" %s\n", "-w, --warning=THRESHOLD");
573 printf (" %s\n", _("warning threshold pair"));
574 printf (" %s\n", "-c, --critical=THRESHOLD");
575 printf (" %s\n", _("critical threshold pair"));
576 printf (" %s\n", "-p, --packets=INTEGER");
577 printf (" %s ", _("number of ICMP ECHO packets to send"));
578 printf (_("(Default: %d)\n"), DEFAULT_MAX_PACKETS);
579 printf (" %s\n", "-L, --link");
580 printf (" %s\n", _("show HTML in the plugin output (obsoleted by urlize)"));
582 printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
584 printf ("\n");
585 printf ("%s\n", _("THRESHOLD is <rta>,<pl>% where <rta> is the round trip average travel"));
586 printf ("%s\n", _("time (ms) which triggers a WARNING or CRITICAL state, and <pl> is the"));
587 printf ("%s\n", _("percentage of packet loss to trigger an alarm state."));
589 printf ("\n");
590 printf ("%s\n", _("This plugin uses the ping command to probe the specified host for packet loss"));
591 printf ("%s\n", _("(percentage) and round trip average (milliseconds). It can produce HTML output"));
592 printf ("%s\n", _("linking to a traceroute CGI contributed by Ian Cass. The CGI can be found in"));
593 printf ("%s\n", _("the contrib area of the downloads section at http://www.nagios.org/"));
595 printf (_(UT_SUPPORT));
596 }
598 void
599 print_usage (void)
600 {
601 printf (_("Usage:"));
602 printf ("%s -H <host_address> -w <wrta>,<wpl>%% -c <crta>,<cpl>%%\n", progname);
603 printf (" [-p packets] [-t timeout] [-4|-6]\n");
604 }