Code

New output format reported by pumuckel1980 (946857)
[nagiosplug.git] / plugins / check_ping.c
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 ******************************************************************************/
19 const char *progname = "check_ping";
20 const char *revision = "$Revision$";
21 const char *copyright = "2000-2003";
22 const char *email = "nagiosplug-devel@lists.sourceforge.net";
24 #include "common.h"
25 #include "netutils.h"
26 #include "popen.h"
27 #include "utils.h"
29 #define WARN_DUPLICATES "DUPLICATES FOUND! "
30 #define UNKNOWN_TRIP_TIME -1.0  /* -1 seconds */
32 enum {
33         UNKNOWN_PACKET_LOSS = 200,    /* 200% */
34         DEFAULT_MAX_PACKETS = 5       /* default no. of ICMP ECHO packets */
35 };
37 int process_arguments (int, char **);
38 int get_threshold (char *, float *, int *);
39 int validate_arguments (void);
40 int run_ping (const char *cmd, const char *addr);
41 int error_scan (char buf[MAX_INPUT_BUFFER], const char *addr);
42 void print_usage (void);
43 void print_help (void);
45 int display_html = FALSE;
46 int wpl = UNKNOWN_PACKET_LOSS;
47 int cpl = UNKNOWN_PACKET_LOSS;
48 float wrta = UNKNOWN_TRIP_TIME;
49 float crta = UNKNOWN_TRIP_TIME;
50 char **addresses = NULL;
51 int n_addresses;
52 int max_addr = 1;
53 int max_packets = -1;
54 int verbose = FALSE;
56 float rta = UNKNOWN_TRIP_TIME;
57 int pl = UNKNOWN_PACKET_LOSS;
59 char *warn_text;
64 \f
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) == ERROR)
82                 usage (_("Could not parse arguments"));
84         /* Set signal handling and alarm */
85         if (signal (SIGALRM, popen_timeout_alarm_handler) == SIG_ERR) {
86                 printf (_("Cannot catch SIGALRM"));
87                 return STATE_UNKNOWN;
88         }
90         /* handle timeouts gracefully */
91         alarm (timeout_interval);
93         for (i = 0 ; i < n_addresses ; i++) {
94                 
95 #ifdef PING6_COMMAND
96                 if (is_inet6_addr(addresses[i]) && address_family != AF_INET)
97                         rawcmd = strdup(PING6_COMMAND);
98                 else
99                         rawcmd = strdup(PING_COMMAND);
100 #else
101                 rawcmd = strdup(PING_COMMAND);
102 #endif
104                 /* does the host address of number of packets argument come first? */
105 #ifdef PING_PACKETS_FIRST
106 # ifdef PING_HAS_TIMEOUT
107                 asprintf (&cmd, rawcmd, timeout_interval, max_packets, addresses[i]);
108 # else
109                 asprintf (&cmd, rawcmd, max_packets, addresses[i]);
110 # endif
111 #else
112                 asprintf (&cmd, rawcmd, addresses[i], max_packets);
113 #endif
115                 if (verbose)
116                         printf ("%s ==> ", cmd);
118                 /* run the command */
119                 this_result = run_ping (cmd, addresses[i]);
121                 if (pl == UNKNOWN_PACKET_LOSS || rta < 0.0) {
122                         printf ("%s\n", cmd);
123                         die (STATE_UNKNOWN,
124                                    _("Error: Could not interpret output from ping command\n"));
125                 }
127                 if (pl >= cpl || rta >= crta || rta < 0)
128                         this_result = STATE_CRITICAL;
129                 else if (pl >= wpl || rta >= wrta)
130                         this_result = STATE_WARNING;
131                 else if (pl >= 0 && rta >= 0)
132                         this_result = max_state (STATE_OK, this_result);        
133         
134                 if (n_addresses > 1 && this_result != STATE_UNKNOWN)
135                         die (STATE_OK, "%s is alive\n", addresses[i]);
137                 if (display_html == TRUE)
138                         printf ("<A HREF='%s/traceroute.cgi?%s'>", CGIURL, addresses[i]);
139                 if (pl == 100)
140                         printf (_("PING %s - %sPacket loss = %d%%"), state_text (this_result), warn_text,
141                                                         pl);
142                 else
143                         printf (_("PING %s - %sPacket loss = %d%%, RTA = %2.2f ms"),
144                                                         state_text (this_result), warn_text, pl, rta);
145                 if (display_html == TRUE)
146                         printf ("</A>");
147                 printf ("\n");
149                 if (verbose)
150                         printf ("%f:%d%% %f:%d%%\n", wrta, wpl, crta, cpl);
152                 result = max_state (result, this_result);
153                 free (rawcmd);
154                 free (cmd);
155         }
157         return result;
164 \f
165 /* process command-line arguments */
166 int
167 process_arguments (int argc, char **argv)
169         int c = 1;
170         char *ptr;
172         int option = 0;
173         static struct option longopts[] = {
174                 STD_LONG_OPTS,
175                 {"packets", required_argument, 0, 'p'},
176                 {"nohtml", no_argument, 0, 'n'},
177                 {"link", no_argument, 0, 'L'},
178                 {"use-ipv4", no_argument, 0, '4'},
179                 {"use-ipv6", no_argument, 0, '6'},
180                 {0, 0, 0, 0}
181         };
183         if (argc < 2)
184                 return ERROR;
186         for (c = 1; c < argc; c++) {
187                 if (strcmp ("-to", argv[c]) == 0)
188                         strcpy (argv[c], "-t");
189                 if (strcmp ("-nohtml", argv[c]) == 0)
190                         strcpy (argv[c], "-n");
191         }
193         while (1) {
194                 c = getopt_long (argc, argv, "VvhnL46t:c:w:H:p:", longopts, &option);
196                 if (c == -1 || c == EOF)
197                         break;
199                 switch (c) {
200                 case '?':       /* usage */
201                         usage3 (_("Unknown argument"), optopt);
202                         break;
203                 case 'h':       /* help */
204                         print_help ();
205                         exit (STATE_OK);
206                         break;
207                 case 'V':       /* version */
208                         print_revision (progname, revision);
209                         exit (STATE_OK);
210                         break;
211                 case 't':       /* timeout period */
212                         timeout_interval = atoi (optarg);
213                         break;
214                 case 'v':       /* verbose mode */
215                         verbose = TRUE;
216                         break;
217                 case '4':       /* IPv4 only */
218                         address_family = AF_INET;
219                         break;
220                 case '6':       /* IPv6 only */
221 #ifdef USE_IPV6
222                         address_family = AF_INET6;
223 #else
224                         usage (_("IPv6 support not available\n"));
225 #endif
226                         break;
227                 case 'H':       /* hostname */
228                         ptr=optarg;
229                         while (1) {
230                                 n_addresses++;
231                                 if (n_addresses > max_addr) {
232                                         max_addr *= 2;
233                                         addresses = realloc (addresses, sizeof(char*) * max_addr);
234                                         if (addresses == NULL)
235                                                 die (STATE_UNKNOWN, _("Could not realloc() addresses\n"));
236                                 }
237                                 addresses[n_addresses-1] = ptr;
238                                 if ((ptr = index (ptr, ','))) {
239                                         strcpy (ptr, "");
240                                         ptr += sizeof(char);
241                                 } else {
242                                         break;
243                                 }
244                         }
245                         break;
246                 case 'p':       /* number of packets to send */
247                         if (is_intnonneg (optarg))
248                                 max_packets = atoi (optarg);
249                         else
250                                 usage2 (_("<max_packets> (%s) must be a non-negative number\n"), optarg);
251                         break;
252                 case 'n':       /* no HTML */
253                         display_html = FALSE;
254                         break;
255                 case 'L':       /* show HTML */
256                         display_html = TRUE;
257                         break;
258                 case 'c':
259                         get_threshold (optarg, &crta, &cpl);
260                         break;
261                 case 'w':
262                         get_threshold (optarg, &wrta, &wpl);
263                         break;
264                 }
265         }
267         c = optind;
268         if (c == argc)
269                 return validate_arguments ();
271         if (addresses[0] == NULL) {
272                 if (is_host (argv[c]) == FALSE) {
273                         printf (_("Invalid host name/address: %s\n\n"), argv[c]);
274                         return ERROR;
275                 } else {
276                         addresses[0] = argv[c++];
277                         n_addresses++;
278                         if (c == argc)
279                                 return validate_arguments ();
280                 }
281         }
283         if (wpl == UNKNOWN_PACKET_LOSS) {
284                 if (is_intpercent (argv[c]) == FALSE) {
285                         printf (_("<wpl> (%s) must be an integer percentage\n"), argv[c]);
286                         return ERROR;
287                 } else {
288                         wpl = atoi (argv[c++]);
289                         if (c == argc)
290                                 return validate_arguments ();
291                 }
292         }
294         if (cpl == UNKNOWN_PACKET_LOSS) {
295                 if (is_intpercent (argv[c]) == FALSE) {
296                         printf (_("<cpl> (%s) must be an integer percentage\n"), argv[c]);
297                         return ERROR;
298                 } else {
299                         cpl = atoi (argv[c++]);
300                         if (c == argc)
301                                 return validate_arguments ();
302                 }
303         }
305         if (wrta < 0.0) {
306                 if (is_negative (argv[c])) {
307                         printf (_("<wrta> (%s) must be a non-negative number\n"), argv[c]);
308                         return ERROR;
309                 } else {
310                         wrta = atof (argv[c++]);
311                         if (c == argc)
312                                 return validate_arguments ();
313                 }
314         }
316         if (crta < 0.0) {
317                 if (is_negative (argv[c])) {
318                         printf (_("<crta> (%s) must be a non-negative number\n"), argv[c]);
319                         return ERROR;
320                 } else {
321                         crta = atof (argv[c++]);
322                         if (c == argc)
323                                 return validate_arguments ();
324                 }
325         }
327         if (max_packets == -1) {
328                 if (is_intnonneg (argv[c])) {
329                         max_packets = atoi (argv[c++]);
330                 } else {
331                         printf (_("<max_packets> (%s) must be a non-negative number\n"), argv[c]);
332                         return ERROR;
333                 }
334         }
336         return validate_arguments ();
339 int
340 get_threshold (char *arg, float *trta, int *tpl)
342         if (is_intnonneg (arg) && sscanf (arg, "%f", trta) == 1)
343                 return OK;
344         else if (strpbrk (arg, ",:") && strstr (arg, "%") && sscanf (arg, "%f%*[:,]%d%%", trta, tpl) == 2)
345                 return OK;
346         else if (strstr (arg, "%") && sscanf (arg, "%d%%", tpl) == 1) 
347                 return OK;
349         usage2 (_("%s: Warning threshold must be integer or percentage!\n\n"), arg);
350         return STATE_UNKNOWN;
353 int
354 validate_arguments ()
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 host name/address"), addresses[i]);
394         }
396         return OK;
403 \f
404 int
405 run_ping (const char *cmd, const char *addr)
407         char buf[MAX_INPUT_BUFFER];
408         int result = STATE_UNKNOWN;
410         if ((child_process = spopen (cmd)) == NULL)
411                 die (STATE_UNKNOWN, _("Cannot open pipe: %s"), cmd);
413         child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r");
414         if (child_stderr == NULL)
415                 printf (_("Cannot open stderr for %s\n"), cmd);
417         while (fgets (buf, MAX_INPUT_BUFFER - 1, child_process)) {
419                 result = max_state (result, error_scan (buf, addr));
421                 /* get the percent loss statistics */
422                 if(sscanf(buf,"%*d packets transmitted, %*d packets received, +%*d errors, %d%% packet loss",&pl)==1 ||
423                          sscanf(buf,"%*d packets transmitted, %*d packets received, %d%% packet loss",&pl)==1   ||
424                          sscanf(buf,"%*d packets transmitted, %*d packets received, %d%% loss, time",&pl)==1 ||
425                          sscanf(buf,"%*d packets transmitted, %*d received, %d%% loss, time", &pl)==1 ||
426                          sscanf(buf,"%*d packets transmitted, %*d received, %d%% packet loss, time", &pl)==1 ||
427                    sscanf(buf,"%*d packets transmitted, %*d received, +%*d errors, %d%% packet loss", &pl) == 1)
428                         continue;
430                 /* get the round trip average */
431                 else
432                         if(sscanf(buf,"round-trip min/avg/max = %*f/%f/%*f",&rta)==1 ||
433                                  sscanf(buf,"round-trip min/avg/max/mdev = %*f/%f/%*f/%*f",&rta)==1 ||
434                                  sscanf(buf,"round-trip min/avg/max/sdev = %*f/%f/%*f/%*f",&rta)==1 ||
435                                  sscanf(buf,"round-trip min/avg/max/stddev = %*f/%f/%*f/%*f",&rta)==1 ||
436                                  sscanf(buf,"round-trip min/avg/max/std-dev = %*f/%f/%*f/%*f",&rta)==1 ||
437                                  sscanf(buf,"round-trip (ms) min/avg/max = %*f/%f/%*f",&rta)==1 ||
438                                  sscanf(buf,"rtt min/avg/max/mdev = %*f/%f/%*f/%*f ms",&rta)==1)
439                         continue;
440         }
442         /* this is needed because there is no rta if all packets are lost */
443         if (pl == 100)
444                 rta = crta;
446         /* check stderr, setting at least WARNING if there is output here */
447         while (fgets (buf, MAX_INPUT_BUFFER - 1, child_stderr))
448                 if (! strstr(buf,"Warning: no SO_TIMESTAMP support, falling back to SIOCGSTAMP"))
449                         result = max_state (STATE_WARNING, error_scan (buf, addr));
451         (void) fclose (child_stderr);
454         /* close the pipe - WARNING if status is set */
455         if (spclose (child_process))
456                 result = max_state (result, STATE_WARNING);
458         if (warn_text == NULL)
459                 warn_text = strdup("");
461         return result;
468 int
469 error_scan (char buf[MAX_INPUT_BUFFER], const char *addr)
471         if (strstr (buf, "Network is unreachable"))
472                 die (STATE_CRITICAL, _("PING CRITICAL - Network unreachable (%s)"), addr);
473         else if (strstr (buf, "Destination Host Unreachable"))
474                 die (STATE_CRITICAL, _("PING CRITICAL - Host Unreachable (%s)"), addr);
475         else if (strstr (buf, "unknown host" ))
476                 die (STATE_CRITICAL, _("PING CRITICAL - Host not found (%s)"), addr);
478         if (strstr (buf, "(DUP!)") || strstr (buf, "DUPLICATES FOUND")) {
479                 if (warn_text == NULL)
480                         warn_text = strdup (_(WARN_DUPLICATES));
481                 else if (! strstr (warn_text, _(WARN_DUPLICATES)) &&
482                          asprintf (&warn_text, "%s %s", warn_text, _(WARN_DUPLICATES)) == -1)
483                         die (STATE_UNKNOWN, _("unable to realloc warn_text"));
484                 return (STATE_WARNING);
485         }
487         return (STATE_OK);
494 \f
495 void
496 print_usage (void)
498         printf (\
499 "Usage: %s -H <host_address> -w <wrta>,<wpl>%% -c <crta>,<cpl>%%\n\
500   [-p packets] [-t timeout] [-L] [-4|-6]\n", progname);
501         printf (_(UT_HLP_VRS), progname, progname);
504 void
505 print_help (void)
507         print_revision (progname, revision);
509         printf (_("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>"));
510         printf (_(COPYRIGHT), copyright, email);
512         printf (_("Use ping to check connection statistics for a remote host.\n\n"));
514         print_usage ();
516         printf (_(UT_HELP_VRSN));
518         printf (_(UT_IPv46));
520         printf (_("\
521 -H, --hostname=HOST\n\
522    host to ping\n\
523 -w, --warning=THRESHOLD\n\
524    warning threshold pair\n\
525 -c, --critical=THRESHOLD\n\
526    critical threshold pair\n\
527 -p, --packets=INTEGER\n\
528    number of ICMP ECHO packets to send (Default: %d)\n\
529 -L, --link\n\
530    show HTML in the plugin output (obsoleted by urlize)\n"),
531                 DEFAULT_MAX_PACKETS);
533         printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
535         printf (_("\
536 THRESHOLD is <rta>,<pl>%% where <rta> is the round trip average travel\n\
537 time (ms) which triggers a WARNING or CRITICAL state, and <pl> is the\n\
538 percentage of packet loss to trigger an alarm state.\n\n"));
540         printf (_("\
541 This plugin uses the ping command to probe the specified host for packet loss\n\
542 (percentage) and round trip average (milliseconds). It can produce HTML output\n\
543 linking to a traceroute CGI contributed by Ian Cass. The CGI can be found in\n\
544 the contrib area of the downloads section at http://www.nagios.org\n\n"));
546         printf (_(UT_SUPPORT));