1 /******************************************************************************
3 This program is free software; you can redistribute it and/or modify
4 it under the terms of the GNU General Public License as published by
5 the Free Software Foundation; either version 2 of the License, or
6 (at your option) any later version.
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
13 You should have received a copy of the GNU General Public License
14 along with this program; if not, write to the Free Software
15 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17 $Id$
19 ******************************************************************************/
21 const char *progname = "check_ping";
22 const char *revision = "$Revision$";
23 const char *copyright = "2000-2004";
24 const char *email = "nagiosplug-devel@lists.sourceforge.net";
26 #include "common.h"
27 #include "netutils.h"
28 #include "popen.h"
29 #include "utils.h"
31 #define WARN_DUPLICATES "DUPLICATES FOUND! "
32 #define UNKNOWN_TRIP_TIME -1.0 /* -1 seconds */
34 enum {
35 UNKNOWN_PACKET_LOSS = 200, /* 200% */
36 DEFAULT_MAX_PACKETS = 5 /* default no. of ICMP ECHO packets */
37 };
39 int process_arguments (int, char **);
40 int get_threshold (char *, float *, int *);
41 int validate_arguments (void);
42 int run_ping (const char *cmd, const char *addr);
43 int error_scan (char buf[MAX_INPUT_BUFFER], const char *addr);
44 void print_usage (void);
45 void print_help (void);
47 int display_html = FALSE;
48 int wpl = UNKNOWN_PACKET_LOSS;
49 int cpl = UNKNOWN_PACKET_LOSS;
50 float wrta = UNKNOWN_TRIP_TIME;
51 float crta = UNKNOWN_TRIP_TIME;
52 char **addresses = NULL;
53 int n_addresses;
54 int max_addr = 1;
55 int max_packets = -1;
56 int verbose = FALSE;
58 float rta = UNKNOWN_TRIP_TIME;
59 int pl = UNKNOWN_PACKET_LOSS;
61 char *warn_text;
65 int
66 main (int argc, char **argv)
67 {
68 char *cmd = NULL;
69 char *rawcmd = NULL;
70 int result = STATE_UNKNOWN;
71 int this_result = STATE_UNKNOWN;
72 int i;
74 setlocale (LC_ALL, "");
75 bindtextdomain (PACKAGE, LOCALEDIR);
76 textdomain (PACKAGE);
78 addresses = malloc (sizeof(char*) * max_addr);
79 addresses[0] = NULL;
81 if (process_arguments (argc, argv) != TRUE)
82 usage4 (_("Could not parse arguments"));
84 /* Set signal handling and alarm */
85 if (signal (SIGALRM, popen_timeout_alarm_handler) == SIG_ERR) {
86 usage4 (_("Cannot catch SIGALRM"));
87 }
89 /* handle timeouts gracefully */
90 alarm (timeout_interval);
92 for (i = 0 ; i < n_addresses ; i++) {
94 #ifdef PING6_COMMAND
95 if (is_inet6_addr(addresses[i]) && address_family != AF_INET)
96 rawcmd = strdup(PING6_COMMAND);
97 else
98 rawcmd = strdup(PING_COMMAND);
99 #else
100 rawcmd = strdup(PING_COMMAND);
101 #endif
103 /* does the host address of number of packets argument come first? */
104 #ifdef PING_PACKETS_FIRST
105 # ifdef PING_HAS_TIMEOUT
106 asprintf (&cmd, rawcmd, timeout_interval, max_packets, addresses[i]);
107 # else
108 asprintf (&cmd, rawcmd, max_packets, addresses[i]);
109 # endif
110 #else
111 asprintf (&cmd, rawcmd, addresses[i], max_packets);
112 #endif
114 if (verbose)
115 printf ("%s ==> ", cmd);
117 /* run the command */
118 this_result = run_ping (cmd, addresses[i]);
120 if (pl == UNKNOWN_PACKET_LOSS || rta < 0.0) {
121 printf ("%s\n", cmd);
122 die (STATE_UNKNOWN,
123 _("CRITICAL - Could not interpret output from ping command\n"));
124 }
126 if (pl >= cpl || rta >= crta || rta < 0)
127 this_result = STATE_CRITICAL;
128 else if (pl >= wpl || rta >= wrta)
129 this_result = STATE_WARNING;
130 else if (pl >= 0 && rta >= 0)
131 this_result = max_state (STATE_OK, this_result);
133 if (n_addresses > 1 && this_result != STATE_UNKNOWN)
134 die (STATE_OK, "%s is alive\n", addresses[i]);
136 if (display_html == TRUE)
137 printf ("<A HREF='%s/traceroute.cgi?%s'>", CGIURL, addresses[i]);
138 if (pl == 100)
139 printf (_("PING %s - %sPacket loss = %d%%"), state_text (this_result), warn_text,
140 pl);
141 else
142 printf (_("PING %s - %sPacket loss = %d%%, RTA = %2.2f ms"),
143 state_text (this_result), warn_text, pl, rta);
144 if (display_html == TRUE)
145 printf ("</A>");
146 printf ("\n");
148 if (verbose)
149 printf ("%f:%d%% %f:%d%%\n", wrta, wpl, crta, cpl);
151 result = max_state (result, this_result);
152 free (rawcmd);
153 free (cmd);
154 }
156 return result;
157 }
161 /* process command-line arguments */
162 int
163 process_arguments (int argc, char **argv)
164 {
165 int c = 1;
166 char *ptr;
168 int option = 0;
169 static struct option longopts[] = {
170 STD_LONG_OPTS,
171 {"packets", required_argument, 0, 'p'},
172 {"nohtml", no_argument, 0, 'n'},
173 {"link", no_argument, 0, 'L'},
174 {"use-ipv4", no_argument, 0, '4'},
175 {"use-ipv6", no_argument, 0, '6'},
176 {0, 0, 0, 0}
177 };
179 if (argc < 2)
180 return ERROR;
182 for (c = 1; c < argc; c++) {
183 if (strcmp ("-to", argv[c]) == 0)
184 strcpy (argv[c], "-t");
185 if (strcmp ("-nohtml", argv[c]) == 0)
186 strcpy (argv[c], "-n");
187 }
189 while (1) {
190 c = getopt_long (argc, argv, "VvhnL46t:c:w:H:p:", longopts, &option);
192 if (c == -1 || c == EOF)
193 break;
195 switch (c) {
196 case '?': /* usage */
197 printf (_("%s: Unknown argument: %s\n\n"), progname, optarg);
198 print_usage ();
199 exit (STATE_UNKNOWN);
200 case 'h': /* help */
201 print_help ();
202 exit (STATE_OK);
203 break;
204 case 'V': /* version */
205 print_revision (progname, revision);
206 exit (STATE_OK);
207 break;
208 case 't': /* timeout period */
209 timeout_interval = atoi (optarg);
210 break;
211 case 'v': /* verbose mode */
212 verbose = TRUE;
213 break;
214 case '4': /* IPv4 only */
215 address_family = AF_INET;
216 break;
217 case '6': /* IPv6 only */
218 #ifdef USE_IPV6
219 address_family = AF_INET6;
220 #else
221 usage (_("IPv6 support not available\n"));
222 #endif
223 break;
224 case 'H': /* hostname */
225 ptr=optarg;
226 while (1) {
227 n_addresses++;
228 if (n_addresses > max_addr) {
229 max_addr *= 2;
230 addresses = realloc (addresses, sizeof(char*) * max_addr);
231 if (addresses == NULL)
232 die (STATE_UNKNOWN, _("Could not realloc() addresses\n"));
233 }
234 addresses[n_addresses-1] = ptr;
235 if ((ptr = index (ptr, ','))) {
236 strcpy (ptr, "");
237 ptr += sizeof(char);
238 } else {
239 break;
240 }
241 }
242 break;
243 case 'p': /* number of packets to send */
244 if (is_intnonneg (optarg))
245 max_packets = atoi (optarg);
246 else
247 usage2 (_("<max_packets> (%s) must be a non-negative number\n"), optarg);
248 break;
249 case 'n': /* no HTML */
250 display_html = FALSE;
251 break;
252 case 'L': /* show HTML */
253 display_html = TRUE;
254 break;
255 case 'c':
256 get_threshold (optarg, &crta, &cpl);
257 break;
258 case 'w':
259 get_threshold (optarg, &wrta, &wpl);
260 break;
261 }
262 }
264 c = optind;
265 if (c == argc)
266 return validate_arguments ();
268 if (addresses[0] == NULL) {
269 if (is_host (argv[c]) == FALSE) {
270 usage2 (_("Invalid hostname/address"), argv[c]);
271 } else {
272 addresses[0] = argv[c++];
273 n_addresses++;
274 if (c == argc)
275 return validate_arguments ();
276 }
277 }
279 if (wpl == UNKNOWN_PACKET_LOSS) {
280 if (is_intpercent (argv[c]) == FALSE) {
281 printf (_("<wpl> (%s) must be an integer percentage\n"), argv[c]);
282 return ERROR;
283 } else {
284 wpl = atoi (argv[c++]);
285 if (c == argc)
286 return validate_arguments ();
287 }
288 }
290 if (cpl == UNKNOWN_PACKET_LOSS) {
291 if (is_intpercent (argv[c]) == FALSE) {
292 printf (_("<cpl> (%s) must be an integer percentage\n"), argv[c]);
293 return ERROR;
294 } else {
295 cpl = atoi (argv[c++]);
296 if (c == argc)
297 return validate_arguments ();
298 }
299 }
301 if (wrta < 0.0) {
302 if (is_negative (argv[c])) {
303 printf (_("<wrta> (%s) must be a non-negative number\n"), argv[c]);
304 return ERROR;
305 } else {
306 wrta = atof (argv[c++]);
307 if (c == argc)
308 return validate_arguments ();
309 }
310 }
312 if (crta < 0.0) {
313 if (is_negative (argv[c])) {
314 printf (_("<crta> (%s) must be a non-negative number\n"), argv[c]);
315 return ERROR;
316 } else {
317 crta = atof (argv[c++]);
318 if (c == argc)
319 return validate_arguments ();
320 }
321 }
323 if (max_packets == -1) {
324 if (is_intnonneg (argv[c])) {
325 max_packets = atoi (argv[c++]);
326 } else {
327 printf (_("<max_packets> (%s) must be a non-negative number\n"), argv[c]);
328 return ERROR;
329 }
330 }
332 return validate_arguments ();
333 }
337 int
338 get_threshold (char *arg, float *trta, int *tpl)
339 {
340 if (is_intnonneg (arg) && sscanf (arg, "%f", trta) == 1)
341 return OK;
342 else if (strpbrk (arg, ",:") && strstr (arg, "%") && sscanf (arg, "%f%*[:,]%d%%", trta, tpl) == 2)
343 return OK;
344 else if (strstr (arg, "%") && sscanf (arg, "%d%%", tpl) == 1)
345 return OK;
347 usage2 (_("%s: Warning threshold must be integer or percentage!\n\n"), arg);
348 return STATE_UNKNOWN;
349 }
353 int
354 validate_arguments ()
355 {
356 float max_seconds;
357 int i;
359 if (wrta < 0.0) {
360 printf (_("<wrta> was not set\n"));
361 return ERROR;
362 }
363 else if (crta < 0.0) {
364 printf (_("<crta> was not set\n"));
365 return ERROR;
366 }
367 else if (wpl == UNKNOWN_PACKET_LOSS) {
368 printf (_("<wpl> was not set\n"));
369 return ERROR;
370 }
371 else if (cpl == UNKNOWN_PACKET_LOSS) {
372 printf (_("<cpl> was not set\n"));
373 return ERROR;
374 }
375 else if (wrta > crta) {
376 printf (_("<wrta> (%f) cannot be larger than <crta> (%f)\n"), wrta, crta);
377 return ERROR;
378 }
379 else if (wpl > cpl) {
380 printf (_("<wpl> (%d) cannot be larger than <cpl> (%d)\n"), wpl, cpl);
381 return ERROR;
382 }
384 if (max_packets == -1)
385 max_packets = DEFAULT_MAX_PACKETS;
387 max_seconds = crta / 1000.0 * max_packets + max_packets;
388 if (max_seconds > timeout_interval)
389 timeout_interval = (int)max_seconds;
391 for (i=0; i<n_addresses; i++) {
392 if (is_host(addresses[i]) == FALSE)
393 usage2 (_("Invalid hostname/address"), addresses[i]);
394 }
396 return OK;
397 }
401 int
402 run_ping (const char *cmd, const char *addr)
403 {
404 char buf[MAX_INPUT_BUFFER];
405 int result = STATE_UNKNOWN;
407 if ((child_process = spopen (cmd)) == NULL)
408 die (STATE_UNKNOWN, _("Cannot open pipe: %s"), cmd);
410 child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r");
411 if (child_stderr == NULL)
412 printf (_("Cannot open stderr for %s\n"), cmd);
414 while (fgets (buf, MAX_INPUT_BUFFER - 1, child_process)) {
416 result = max_state (result, error_scan (buf, addr));
418 /* get the percent loss statistics */
419 if(sscanf(buf,"%*d packets transmitted, %*d packets received, +%*d errors, %d%% packet loss",&pl)==1 ||
420 sscanf(buf,"%*d packets transmitted, %*d packets received, %d%% packet loss",&pl)==1 ||
421 sscanf(buf,"%*d packets transmitted, %*d packets received, %d%% loss, time",&pl)==1 ||
422 sscanf(buf,"%*d packets transmitted, %*d received, %d%% loss, time", &pl)==1 ||
423 sscanf(buf,"%*d packets transmitted, %*d received, %d%% packet loss, time", &pl)==1 ||
424 sscanf(buf,"%*d packets transmitted, %*d received, +%*d errors, %d%% packet loss", &pl) == 1)
425 continue;
427 /* get the round trip average */
428 else
429 if(sscanf(buf,"round-trip min/avg/max = %*f/%f/%*f",&rta)==1 ||
430 sscanf(buf,"round-trip min/avg/max/mdev = %*f/%f/%*f/%*f",&rta)==1 ||
431 sscanf(buf,"round-trip min/avg/max/sdev = %*f/%f/%*f/%*f",&rta)==1 ||
432 sscanf(buf,"round-trip min/avg/max/stddev = %*f/%f/%*f/%*f",&rta)==1 ||
433 sscanf(buf,"round-trip min/avg/max/std-dev = %*f/%f/%*f/%*f",&rta)==1 ||
434 sscanf(buf,"round-trip (ms) min/avg/max = %*f/%f/%*f",&rta)==1 ||
435 sscanf(buf,"rtt min/avg/max/mdev = %*f/%f/%*f/%*f ms",&rta)==1)
436 continue;
437 }
439 /* this is needed because there is no rta if all packets are lost */
440 if (pl == 100)
441 rta = crta;
443 /* check stderr, setting at least WARNING if there is output here */
444 while (fgets (buf, MAX_INPUT_BUFFER - 1, child_stderr))
445 if (! strstr(buf,"WARNING - no SO_TIMESTAMP support, falling back to SIOCGSTAMP"))
446 result = max_state (STATE_WARNING, error_scan (buf, addr));
448 (void) fclose (child_stderr);
451 /* close the pipe - WARNING if status is set */
452 if (spclose (child_process))
453 result = max_state (result, STATE_WARNING);
455 if (warn_text == NULL)
456 warn_text = strdup("");
458 return result;
459 }
463 int
464 error_scan (char buf[MAX_INPUT_BUFFER], const char *addr)
465 {
466 if (strstr (buf, "Network is unreachable"))
467 die (STATE_CRITICAL, _("CRITICAL - Network unreachable (%s)"), addr);
468 else if (strstr (buf, "Destination Host Unreachable"))
469 die (STATE_CRITICAL, _("CRITICAL - Host Unreachable (%s)"), addr);
470 else if (strstr (buf, "unknown host" ))
471 die (STATE_CRITICAL, _("CRITICAL - Host not found (%s)"), addr);
473 if (strstr (buf, "(DUP!)") || strstr (buf, "DUPLICATES FOUND")) {
474 if (warn_text == NULL)
475 warn_text = strdup (_(WARN_DUPLICATES));
476 else if (! strstr (warn_text, _(WARN_DUPLICATES)) &&
477 asprintf (&warn_text, "%s %s", warn_text, _(WARN_DUPLICATES)) == -1)
478 die (STATE_UNKNOWN, _("Unable to realloc warn_text"));
479 return (STATE_WARNING);
480 }
482 return (STATE_OK);
483 }
487 void
488 print_help (void)
489 {
490 print_revision (progname, revision);
492 printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>");
493 printf (COPYRIGHT, copyright, email);
495 printf (_("Use ping to check connection statistics for a remote host.\n\n"));
497 print_usage ();
499 printf (_(UT_HELP_VRSN));
501 printf (_(UT_IPv46));
503 printf (_("\
504 -H, --hostname=HOST\n\
505 host to ping\n\
506 -w, --warning=THRESHOLD\n\
507 warning threshold pair\n\
508 -c, --critical=THRESHOLD\n\
509 critical threshold pair\n\
510 -p, --packets=INTEGER\n\
511 number of ICMP ECHO packets to send (Default: %d)\n\
512 -L, --link\n\
513 show HTML in the plugin output (obsoleted by urlize)\n"),
514 DEFAULT_MAX_PACKETS);
516 printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
518 printf (_("\
519 THRESHOLD is <rta>,<pl>%% where <rta> is the round trip average travel\n\
520 time (ms) which triggers a WARNING or CRITICAL state, and <pl> is the\n\
521 percentage of packet loss to trigger an alarm state.\n\n"));
523 printf (_("\
524 This plugin uses the ping command to probe the specified host for packet loss\n\
525 (percentage) and round trip average (milliseconds). It can produce HTML output\n\
526 linking to a traceroute CGI contributed by Ian Cass. The CGI can be found in\n\
527 the contrib area of the downloads section at http://www.nagios.org\n\n"));
529 printf (_(UT_SUPPORT));
530 }
532 void
533 print_usage (void)
534 {
535 printf ("Usage: %s -H <host_address> -w <wrta>,<wpl>%% -c <crta>,<cpl>%%\n\
536 [-p packets] [-t timeout] [-L] [-4|-6]\n", progname);
537 }