Capitalize "Monitoring" when it's the first word
[monitoring-plugins.git] / plugins / check_ping.c
blob60d7c7d57dfed3bc29b104c00e9a05eb5fccaa7b
1 /*****************************************************************************
2 *
3 * Monitoring check_ping plugin
4 *
5 * License: GPL
6 * Copyright (c) 2000-2007 Monitoring Plugins Development Team
7 *
8 * Description:
9 *
10 * This file contains the check_ping plugin
12 * Use the ping program to check connection statistics for a remote host.
15 * This program is free software: you can redistribute it and/or modify
16 * it under the terms of the GNU General Public License as published by
17 * the Free Software Foundation, either version 3 of the License, or
18 * (at your option) any later version.
20 * This program is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
25 * You should have received a copy of the GNU General Public License
26 * along with this program. If not, see <http://www.gnu.org/licenses/>.
29 *****************************************************************************/
31 const char *progname = "check_ping";
32 const char *copyright = "2000-2007";
33 const char *email = "devel@monitoring-plugins.org";
35 #include "common.h"
36 #include "netutils.h"
37 #include "popen.h"
38 #include "utils.h"
40 #define WARN_DUPLICATES "DUPLICATES FOUND! "
41 #define UNKNOWN_TRIP_TIME -1.0 /* -1 seconds */
43 enum {
44 UNKNOWN_PACKET_LOSS = 200, /* 200% */
45 DEFAULT_MAX_PACKETS = 5 /* default no. of ICMP ECHO packets */
48 int process_arguments (int, char **);
49 int get_threshold (char *, float *, int *);
50 int validate_arguments (void);
51 int run_ping (const char *cmd, const char *addr);
52 int error_scan (char buf[MAX_INPUT_BUFFER], const char *addr);
53 void print_usage (void);
54 void print_help (void);
56 int display_html = FALSE;
57 int wpl = UNKNOWN_PACKET_LOSS;
58 int cpl = UNKNOWN_PACKET_LOSS;
59 float wrta = UNKNOWN_TRIP_TIME;
60 float crta = UNKNOWN_TRIP_TIME;
61 char **addresses = NULL;
62 int n_addresses = 0;
63 int max_addr = 1;
64 int max_packets = -1;
65 int verbose = 0;
67 float rta = UNKNOWN_TRIP_TIME;
68 int pl = UNKNOWN_PACKET_LOSS;
70 char *warn_text;
74 int
75 main (int argc, char **argv)
77 char *cmd = NULL;
78 char *rawcmd = NULL;
79 int result = STATE_UNKNOWN;
80 int this_result = STATE_UNKNOWN;
81 int i;
83 setlocale (LC_ALL, "");
84 setlocale (LC_NUMERIC, "C");
85 bindtextdomain (PACKAGE, LOCALEDIR);
86 textdomain (PACKAGE);
88 addresses = malloc (sizeof(char*) * max_addr);
89 addresses[0] = NULL;
91 /* Parse extra opts if any */
92 argv=np_extra_opts (&argc, argv, progname);
94 if (process_arguments (argc, argv) == ERROR)
95 usage4 (_("Could not parse arguments"));
97 /* Set signal handling and alarm */
98 if (signal (SIGALRM, popen_timeout_alarm_handler) == SIG_ERR) {
99 usage4 (_("Cannot catch SIGALRM"));
102 /* If ./configure finds ping has timeout values, set plugin alarm slightly
103 * higher so that we can use response from command line ping */
104 #if defined(PING_PACKETS_FIRST) && defined(PING_HAS_TIMEOUT)
105 alarm (timeout_interval + 1);
106 #else
107 alarm (timeout_interval);
108 #endif
110 for (i = 0 ; i < n_addresses ; i++) {
112 #ifdef PING6_COMMAND
113 if (address_family != AF_INET && is_inet6_addr(addresses[i]))
114 rawcmd = strdup(PING6_COMMAND);
115 else
116 rawcmd = strdup(PING_COMMAND);
117 #else
118 rawcmd = strdup(PING_COMMAND);
119 #endif
121 /* does the host address of number of packets argument come first? */
122 #ifdef PING_PACKETS_FIRST
123 # ifdef PING_HAS_TIMEOUT
124 xasprintf (&cmd, rawcmd, timeout_interval, max_packets, addresses[i]);
125 # else
126 xasprintf (&cmd, rawcmd, max_packets, addresses[i]);
127 # endif
128 #else
129 xasprintf (&cmd, rawcmd, addresses[i], max_packets);
130 #endif
132 if (verbose >= 2)
133 printf ("CMD: %s\n", cmd);
135 /* run the command */
136 this_result = run_ping (cmd, addresses[i]);
138 if (pl == UNKNOWN_PACKET_LOSS || rta < 0.0) {
139 printf ("%s\n", cmd);
140 die (STATE_UNKNOWN,
141 _("CRITICAL - Could not interpret output from ping command\n"));
144 if (pl >= cpl || rta >= crta || rta < 0)
145 this_result = STATE_CRITICAL;
146 else if (pl >= wpl || rta >= wrta)
147 this_result = STATE_WARNING;
148 else if (pl >= 0 && rta >= 0)
149 this_result = max_state (STATE_OK, this_result);
151 if (n_addresses > 1 && this_result != STATE_UNKNOWN)
152 die (STATE_OK, "%s is alive\n", addresses[i]);
154 if (display_html == TRUE)
155 printf ("<A HREF='%s/traceroute.cgi?%s'>", CGIURL, addresses[i]);
156 if (pl == 100)
157 printf (_("PING %s - %sPacket loss = %d%%"), state_text (this_result), warn_text,
158 pl);
159 else
160 printf (_("PING %s - %sPacket loss = %d%%, RTA = %2.2f ms"),
161 state_text (this_result), warn_text, pl, rta);
162 if (display_html == TRUE)
163 printf ("</A>");
165 /* Print performance data */
166 printf("|%s", fperfdata ("rta", (double) rta, "ms",
167 wrta>0?TRUE:FALSE, wrta,
168 crta>0?TRUE:FALSE, crta,
169 TRUE, 0, FALSE, 0));
170 printf(" %s\n", perfdata ("pl", (long) pl, "%",
171 wpl>0?TRUE:FALSE, wpl,
172 cpl>0?TRUE:FALSE, cpl,
173 TRUE, 0, FALSE, 0));
175 if (verbose >= 2)
176 printf ("%f:%d%% %f:%d%%\n", wrta, wpl, crta, cpl);
178 result = max_state (result, this_result);
179 free (rawcmd);
180 free (cmd);
183 return result;
188 /* process command-line arguments */
190 process_arguments (int argc, char **argv)
192 int c = 1;
193 char *ptr;
195 int option = 0;
196 static struct option longopts[] = {
197 STD_LONG_OPTS,
198 {"packets", required_argument, 0, 'p'},
199 {"nohtml", no_argument, 0, 'n'},
200 {"link", no_argument, 0, 'L'},
201 {"use-ipv4", no_argument, 0, '4'},
202 {"use-ipv6", no_argument, 0, '6'},
203 {0, 0, 0, 0}
206 if (argc < 2)
207 return ERROR;
209 for (c = 1; c < argc; c++) {
210 if (strcmp ("-to", argv[c]) == 0)
211 strcpy (argv[c], "-t");
212 if (strcmp ("-nohtml", argv[c]) == 0)
213 strcpy (argv[c], "-n");
216 while (1) {
217 c = getopt_long (argc, argv, "VvhnL46t:c:w:H:p:", longopts, &option);
219 if (c == -1 || c == EOF)
220 break;
222 switch (c) {
223 case '?': /* usage */
224 usage5 ();
225 case 'h': /* help */
226 print_help ();
227 exit (STATE_OK);
228 break;
229 case 'V': /* version */
230 print_revision (progname, NP_VERSION);
231 exit (STATE_OK);
232 break;
233 case 't': /* timeout period */
234 timeout_interval = atoi (optarg);
235 break;
236 case 'v': /* verbose mode */
237 verbose++;
238 break;
239 case '4': /* IPv4 only */
240 address_family = AF_INET;
241 break;
242 case '6': /* IPv6 only */
243 #ifdef USE_IPV6
244 address_family = AF_INET6;
245 #else
246 usage (_("IPv6 support not available\n"));
247 #endif
248 break;
249 case 'H': /* hostname */
250 ptr=optarg;
251 while (1) {
252 n_addresses++;
253 if (n_addresses > max_addr) {
254 max_addr *= 2;
255 addresses = realloc (addresses, sizeof(char*) * max_addr);
256 if (addresses == NULL)
257 die (STATE_UNKNOWN, _("Could not realloc() addresses\n"));
259 addresses[n_addresses-1] = ptr;
260 if ((ptr = index (ptr, ','))) {
261 strcpy (ptr, "");
262 ptr += sizeof(char);
263 } else {
264 break;
267 break;
268 case 'p': /* number of packets to send */
269 if (is_intnonneg (optarg))
270 max_packets = atoi (optarg);
271 else
272 usage2 (_("<max_packets> (%s) must be a non-negative number\n"), optarg);
273 break;
274 case 'n': /* no HTML */
275 display_html = FALSE;
276 break;
277 case 'L': /* show HTML */
278 display_html = TRUE;
279 break;
280 case 'c':
281 get_threshold (optarg, &crta, &cpl);
282 break;
283 case 'w':
284 get_threshold (optarg, &wrta, &wpl);
285 break;
289 c = optind;
290 if (c == argc)
291 return validate_arguments ();
293 if (addresses[0] == NULL) {
294 if (is_host (argv[c]) == FALSE) {
295 usage2 (_("Invalid hostname/address"), argv[c]);
296 } else {
297 addresses[0] = argv[c++];
298 n_addresses++;
299 if (c == argc)
300 return validate_arguments ();
304 if (wpl == UNKNOWN_PACKET_LOSS) {
305 if (is_intpercent (argv[c]) == FALSE) {
306 printf (_("<wpl> (%s) must be an integer percentage\n"), argv[c]);
307 return ERROR;
308 } else {
309 wpl = atoi (argv[c++]);
310 if (c == argc)
311 return validate_arguments ();
315 if (cpl == UNKNOWN_PACKET_LOSS) {
316 if (is_intpercent (argv[c]) == FALSE) {
317 printf (_("<cpl> (%s) must be an integer percentage\n"), argv[c]);
318 return ERROR;
319 } else {
320 cpl = atoi (argv[c++]);
321 if (c == argc)
322 return validate_arguments ();
326 if (wrta < 0.0) {
327 if (is_negative (argv[c])) {
328 printf (_("<wrta> (%s) must be a non-negative number\n"), argv[c]);
329 return ERROR;
330 } else {
331 wrta = atof (argv[c++]);
332 if (c == argc)
333 return validate_arguments ();
337 if (crta < 0.0) {
338 if (is_negative (argv[c])) {
339 printf (_("<crta> (%s) must be a non-negative number\n"), argv[c]);
340 return ERROR;
341 } else {
342 crta = atof (argv[c++]);
343 if (c == argc)
344 return validate_arguments ();
348 if (max_packets == -1) {
349 if (is_intnonneg (argv[c])) {
350 max_packets = atoi (argv[c++]);
351 } else {
352 printf (_("<max_packets> (%s) must be a non-negative number\n"), argv[c]);
353 return ERROR;
357 return validate_arguments ();
363 get_threshold (char *arg, float *trta, int *tpl)
365 if (is_intnonneg (arg) && sscanf (arg, "%f", trta) == 1)
366 return OK;
367 else if (strpbrk (arg, ",:") && strstr (arg, "%") && sscanf (arg, "%f%*[:,]%d%%", trta, tpl) == 2)
368 return OK;
369 else if (strstr (arg, "%") && sscanf (arg, "%d%%", tpl) == 1)
370 return OK;
372 usage2 (_("%s: Warning threshold must be integer or percentage!\n\n"), arg);
373 return STATE_UNKNOWN;
379 validate_arguments ()
381 float max_seconds;
382 int i;
384 if (wrta < 0.0) {
385 printf (_("<wrta> was not set\n"));
386 return ERROR;
388 else if (crta < 0.0) {
389 printf (_("<crta> was not set\n"));
390 return ERROR;
392 else if (wpl == UNKNOWN_PACKET_LOSS) {
393 printf (_("<wpl> was not set\n"));
394 return ERROR;
396 else if (cpl == UNKNOWN_PACKET_LOSS) {
397 printf (_("<cpl> was not set\n"));
398 return ERROR;
400 else if (wrta > crta) {
401 printf (_("<wrta> (%f) cannot be larger than <crta> (%f)\n"), wrta, crta);
402 return ERROR;
404 else if (wpl > cpl) {
405 printf (_("<wpl> (%d) cannot be larger than <cpl> (%d)\n"), wpl, cpl);
406 return ERROR;
409 if (max_packets == -1)
410 max_packets = DEFAULT_MAX_PACKETS;
412 max_seconds = crta / 1000.0 * max_packets + max_packets;
413 if (max_seconds > timeout_interval)
414 timeout_interval = (int)max_seconds;
416 for (i=0; i<n_addresses; i++) {
417 if (is_host(addresses[i]) == FALSE)
418 usage2 (_("Invalid hostname/address"), addresses[i]);
421 if (n_addresses == 0) {
422 usage (_("You must specify a server address or host name"));
425 return OK;
431 run_ping (const char *cmd, const char *addr)
433 char buf[MAX_INPUT_BUFFER];
434 int result = STATE_UNKNOWN;
435 int match;
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 match = 0;
453 if((sscanf(buf,"%*d packets transmitted, %*d packets received, +%*d errors, %d%% packet loss%n",&pl,&match) && match) ||
454 (sscanf(buf,"%*d packets transmitted, %*d packets received, +%*d duplicates, %d%% packet loss%n",&pl,&match) && match) ||
455 (sscanf(buf,"%*d packets transmitted, %*d received, +%*d duplicates, %d%% packet loss%n",&pl,&match) && match) ||
456 (sscanf(buf,"%*d packets transmitted, %*d packets received, %d%% packet loss%n",&pl,&match) && match) ||
457 (sscanf(buf,"%*d packets transmitted, %*d packets received, %d%% loss, time%n",&pl,&match) && match) ||
458 (sscanf(buf,"%*d packets transmitted, %*d received, %d%% loss, time%n",&pl,&match) && match) ||
459 (sscanf(buf,"%*d packets transmitted, %*d received, %d%% packet loss, time%n",&pl,&match) && match) ||
460 (sscanf(buf,"%*d packets transmitted, %*d received, +%*d errors, %d%% packet loss%n",&pl,&match) && match) ||
461 (sscanf(buf,"%*d packets transmitted %*d received, +%*d errors, %d%% packet loss%n",&pl,&match) && match)
463 continue;
465 /* get the round trip average */
466 else
467 if((sscanf(buf,"round-trip min/avg/max = %*f/%f/%*f%n",&rta,&match) && match) ||
468 (sscanf(buf,"round-trip min/avg/max/mdev = %*f/%f/%*f/%*f%n",&rta,&match) && match) ||
469 (sscanf(buf,"round-trip min/avg/max/sdev = %*f/%f/%*f/%*f%n",&rta,&match) && match) ||
470 (sscanf(buf,"round-trip min/avg/max/stddev = %*f/%f/%*f/%*f%n",&rta,&match) && match) ||
471 (sscanf(buf,"round-trip min/avg/max/std-dev = %*f/%f/%*f/%*f%n",&rta,&match) && match) ||
472 (sscanf(buf,"round-trip (ms) min/avg/max = %*f/%f/%*f%n",&rta,&match) && match) ||
473 (sscanf(buf,"round-trip (ms) min/avg/max/stddev = %*f/%f/%*f/%*f%n",&rta,&match) && match) ||
474 (sscanf(buf,"rtt min/avg/max/mdev = %*f/%f/%*f/%*f ms%n",&rta,&match) && match))
475 continue;
478 /* this is needed because there is no rta if all packets are lost */
479 if (pl == 100)
480 rta = crta;
482 /* check stderr, setting at least WARNING if there is output here */
483 /* Add warning into warn_text */
484 while (fgets (buf, MAX_INPUT_BUFFER - 1, child_stderr)) {
485 if (! strstr(buf,"WARNING - no SO_TIMESTAMP support, falling back to SIOCGSTAMP")) {
486 if (verbose >= 3) {
487 printf("Got stderr: %s", buf);
489 if ((result=error_scan(buf, addr)) == STATE_OK) {
490 result = STATE_WARNING;
491 if (warn_text == NULL) {
492 warn_text = strdup(_("System call sent warnings to stderr "));
493 } else {
494 xasprintf(&warn_text, "%s %s", warn_text, _("System call sent warnings to stderr "));
500 (void) fclose (child_stderr);
503 spclose (child_process);
505 if (warn_text == NULL)
506 warn_text = strdup("");
508 return result;
514 error_scan (char buf[MAX_INPUT_BUFFER], const char *addr)
516 if (strstr (buf, "Network is unreachable") ||
517 strstr (buf, "Destination Net Unreachable")
519 die (STATE_CRITICAL, _("CRITICAL - Network Unreachable (%s)\n"), addr);
520 else if (strstr (buf, "Destination Host Unreachable"))
521 die (STATE_CRITICAL, _("CRITICAL - Host Unreachable (%s)\n"), addr);
522 else if (strstr (buf, "Destination Port Unreachable"))
523 die (STATE_CRITICAL, _("CRITICAL - Bogus ICMP: Port Unreachable (%s)\n"), addr);
524 else if (strstr (buf, "Destination Protocol Unreachable"))
525 die (STATE_CRITICAL, _("CRITICAL - Bogus ICMP: Protocol Unreachable (%s)\n"), addr);
526 else if (strstr (buf, "Destination Net Prohibited"))
527 die (STATE_CRITICAL, _("CRITICAL - Network Prohibited (%s)\n"), addr);
528 else if (strstr (buf, "Destination Host Prohibited"))
529 die (STATE_CRITICAL, _("CRITICAL - Host Prohibited (%s)\n"), addr);
530 else if (strstr (buf, "Packet filtered"))
531 die (STATE_CRITICAL, _("CRITICAL - Packet Filtered (%s)\n"), addr);
532 else if (strstr (buf, "unknown host" ))
533 die (STATE_CRITICAL, _("CRITICAL - Host not found (%s)\n"), addr);
534 else if (strstr (buf, "Time to live exceeded"))
535 die (STATE_CRITICAL, _("CRITICAL - Time to live exceeded (%s)\n"), addr);
536 else if (strstr (buf, "Destination unreachable: "))
537 die (STATE_CRITICAL, _("CRITICAL - Destination Unreachable (%s)\n"), addr);
539 if (strstr (buf, "(DUP!)") || strstr (buf, "DUPLICATES FOUND")) {
540 if (warn_text == NULL)
541 warn_text = strdup (_(WARN_DUPLICATES));
542 else if (! strstr (warn_text, _(WARN_DUPLICATES)) &&
543 xasprintf (&warn_text, "%s %s", warn_text, _(WARN_DUPLICATES)) == -1)
544 die (STATE_UNKNOWN, _("Unable to realloc warn_text\n"));
545 return (STATE_WARNING);
548 return (STATE_OK);
553 void
554 print_help (void)
556 print_revision (progname, NP_VERSION);
558 printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
559 printf (COPYRIGHT, copyright, email);
561 printf (_("Use ping to check connection statistics for a remote host."));
563 printf ("\n\n");
565 print_usage ();
567 printf (UT_HELP_VRSN);
568 printf (UT_EXTRA_OPTS);
570 printf (UT_IPv46);
572 printf (" %s\n", "-H, --hostname=HOST");
573 printf (" %s\n", _("host to ping"));
574 printf (" %s\n", "-w, --warning=THRESHOLD");
575 printf (" %s\n", _("warning threshold pair"));
576 printf (" %s\n", "-c, --critical=THRESHOLD");
577 printf (" %s\n", _("critical threshold pair"));
578 printf (" %s\n", "-p, --packets=INTEGER");
579 printf (" %s ", _("number of ICMP ECHO packets to send"));
580 printf (_("(Default: %d)\n"), DEFAULT_MAX_PACKETS);
581 printf (" %s\n", "-L, --link");
582 printf (" %s\n", _("show HTML in the plugin output (obsoleted by urlize)"));
584 printf (UT_TIMEOUT, DEFAULT_SOCKET_TIMEOUT);
586 printf ("\n");
587 printf ("%s\n", _("THRESHOLD is <rta>,<pl>% where <rta> is the round trip average travel"));
588 printf ("%s\n", _("time (ms) which triggers a WARNING or CRITICAL state, and <pl> is the"));
589 printf ("%s\n", _("percentage of packet loss to trigger an alarm state."));
591 printf ("\n");
592 printf ("%s\n", _("This plugin uses the ping command to probe the specified host for packet loss"));
593 printf ("%s\n", _("(percentage) and round trip average (milliseconds). It can produce HTML output"));
594 printf ("%s\n", _("linking to a traceroute CGI contributed by Ian Cass. The CGI can be found in"));
595 printf ("%s\n", _("the contrib area of the downloads section at http://www.nagios.org/"));
597 printf (UT_SUPPORT);
600 void
601 print_usage (void)
603 printf ("%s\n", _("Usage:"));
604 printf ("%s -H <host_address> -w <wrta>,<wpl>%% -c <crta>,<cpl>%%\n", progname);
605 printf (" [-p packets] [-t timeout] [-4|-6]\n");