Merge branch 'master' of ssh://tonvoon@nagiosplug.git.sourceforge.net/gitroot/nagiosp...
[monitoring-plugins.git] / plugins / check_ping.c
blobecdd61835e7508b09f3747440d4f19a72f9104f7
1 /*****************************************************************************
2 *
3 * Nagios check_ping plugin
4 *
5 * License: GPL
6 * Copyright (c) 2000-2007 Nagios 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 = "nagiosplug-devel@lists.sourceforge.net";
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 asprintf (&cmd, rawcmd, timeout_interval, max_packets, addresses[i]);
125 # else
126 asprintf (&cmd, rawcmd, max_packets, addresses[i]);
127 # endif
128 #else
129 asprintf (&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;
436 if ((child_process = spopen (cmd)) == NULL)
437 die (STATE_UNKNOWN, _("Could not open pipe: %s\n"), cmd);
439 child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r");
440 if (child_stderr == NULL)
441 printf (_("Cannot open stderr for %s\n"), cmd);
443 while (fgets (buf, MAX_INPUT_BUFFER - 1, child_process)) {
445 if (verbose >= 3)
446 printf("Output: %s", buf);
448 result = max_state (result, error_scan (buf, addr));
450 /* get the percent loss statistics */
451 if(sscanf(buf,"%*d packets transmitted, %*d packets received, +%*d errors, %d%% packet loss",&pl)==1 ||
452 sscanf(buf,"%*d packets transmitted, %*d packets received, +%*d duplicates, %d%% packet loss", &pl) == 1 ||
453 sscanf(buf,"%*d packets transmitted, %*d received, +%*d duplicates, %d%% packet loss", &pl) == 1 ||
454 sscanf(buf,"%*d packets transmitted, %*d packets received, %d%% packet loss",&pl)==1 ||
455 sscanf(buf,"%*d packets transmitted, %*d packets received, %d%% loss, time",&pl)==1 ||
456 sscanf(buf,"%*d packets transmitted, %*d received, %d%% loss, time", &pl)==1 ||
457 sscanf(buf,"%*d packets transmitted, %*d received, %d%% packet loss, time", &pl)==1 ||
458 sscanf(buf,"%*d packets transmitted, %*d received, +%*d errors, %d%% packet loss", &pl) == 1 ||
459 sscanf(buf,"%*d packets transmitted %*d received, +%*d errors, %d%% packet loss", &pl) == 1
461 continue;
463 /* get the round trip average */
464 else
465 if(sscanf(buf,"round-trip min/avg/max = %*f/%f/%*f",&rta)==1 ||
466 sscanf(buf,"round-trip min/avg/max/mdev = %*f/%f/%*f/%*f",&rta)==1 ||
467 sscanf(buf,"round-trip min/avg/max/sdev = %*f/%f/%*f/%*f",&rta)==1 ||
468 sscanf(buf,"round-trip min/avg/max/stddev = %*f/%f/%*f/%*f",&rta)==1 ||
469 sscanf(buf,"round-trip min/avg/max/std-dev = %*f/%f/%*f/%*f",&rta)==1 ||
470 sscanf(buf,"round-trip (ms) min/avg/max = %*f/%f/%*f",&rta)==1 ||
471 sscanf(buf,"round-trip (ms) min/avg/max/stddev = %*f/%f/%*f/%*f",&rta)==1 ||
472 sscanf(buf,"rtt min/avg/max/mdev = %*f/%f/%*f/%*f ms",&rta)==1)
473 continue;
476 /* this is needed because there is no rta if all packets are lost */
477 if (pl == 100)
478 rta = crta;
480 /* check stderr, setting at least WARNING if there is output here */
481 /* Add warning into warn_text */
482 while (fgets (buf, MAX_INPUT_BUFFER - 1, child_stderr)) {
483 if (! strstr(buf,"WARNING - no SO_TIMESTAMP support, falling back to SIOCGSTAMP")) {
484 if (verbose >= 3) {
485 printf("Got stderr: %s", buf);
487 if ((result=error_scan(buf, addr)) == STATE_OK) {
488 result = STATE_WARNING;
489 if (warn_text == NULL) {
490 warn_text = strdup(_("System call sent warnings to stderr "));
491 } else {
492 asprintf(&warn_text, "%s %s", warn_text, _("System call sent warnings to stderr "));
498 (void) fclose (child_stderr);
501 /* close the pipe - WARNING if status is set */
502 if (spclose (child_process))
503 result = max_state (result, STATE_WARNING);
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)"), addr);
520 else if (strstr (buf, "Destination Host Unreachable"))
521 die (STATE_CRITICAL, _("CRITICAL - Host Unreachable (%s)"), addr);
522 else if (strstr (buf, "Destination Port Unreachable"))
523 die (STATE_CRITICAL, _("CRITICAL - Bogus ICMP: Port Unreachable (%s)"), addr);
524 else if (strstr (buf, "Destination Protocol Unreachable"))
525 die (STATE_CRITICAL, _("CRITICAL - Bogus ICMP: Protocol Unreachable (%s)"), addr);
526 else if (strstr (buf, "Destination Net Prohibited"))
527 die (STATE_CRITICAL, _("CRITICAL - Network Prohibited (%s)"), addr);
528 else if (strstr (buf, "Destination Host Prohibited"))
529 die (STATE_CRITICAL, _("CRITICAL - Host Prohibited (%s)"), addr);
530 else if (strstr (buf, "Packet filtered"))
531 die (STATE_CRITICAL, _("CRITICAL - Packet Filtered (%s)"), addr);
532 else if (strstr (buf, "unknown host" ))
533 die (STATE_CRITICAL, _("CRITICAL - Host not found (%s)"), addr);
534 else if (strstr (buf, "Time to live exceeded"))
535 die (STATE_CRITICAL, _("CRITICAL - Time to live exceeded (%s)"), addr);
537 if (strstr (buf, "(DUP!)") || strstr (buf, "DUPLICATES FOUND")) {
538 if (warn_text == NULL)
539 warn_text = strdup (_(WARN_DUPLICATES));
540 else if (! strstr (warn_text, _(WARN_DUPLICATES)) &&
541 asprintf (&warn_text, "%s %s", warn_text, _(WARN_DUPLICATES)) == -1)
542 die (STATE_UNKNOWN, _("Unable to realloc warn_text"));
543 return (STATE_WARNING);
546 return (STATE_OK);
551 void
552 print_help (void)
554 print_revision (progname, NP_VERSION);
556 printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n");
557 printf (COPYRIGHT, copyright, email);
559 printf (_("Use ping to check connection statistics for a remote host."));
561 printf ("\n\n");
563 print_usage ();
565 printf (UT_HELP_VRSN);
566 printf (UT_EXTRA_OPTS);
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);
598 void
599 print_usage (void)
601 printf ("%s\n", _("Usage:"));
602 printf ("%s -H <host_address> -w <wrta>,<wpl>%% -c <crta>,<cpl>%%\n", progname);
603 printf (" [-p packets] [-t timeout] [-4|-6]\n");