Code

cleaning up help and usage
[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  $Id$
18  
19 ******************************************************************************/
21 const char *progname = "check_ping";
22 const char *revision = "$Revision$";
23 const char *copyright = "2000-2006";
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 = 0;
54 int max_addr = 1;
55 int max_packets = -1;
56 int verbose = 0;
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         setlocale (LC_NUMERIC, "C");
76         bindtextdomain (PACKAGE, LOCALEDIR);
77         textdomain (PACKAGE);
79         addresses = malloc (sizeof(char*) * max_addr);
80         addresses[0] = NULL;
82         if (process_arguments (argc, argv) == ERROR)
83                 usage4 (_("Could not parse arguments"));
85         /* Set signal handling and alarm */
86         if (signal (SIGALRM, popen_timeout_alarm_handler) == SIG_ERR) {
87                 usage4 (_("Cannot catch SIGALRM"));
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 >= 2)
116                         printf ("CMD: %s\n", 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                                    _("CRITICAL - 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 >= 2)
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;
162 /* process command-line arguments */
163 int
164 process_arguments (int argc, char **argv)
166         int c = 1;
167         char *ptr;
169         int option = 0;
170         static struct option longopts[] = {
171                 STD_LONG_OPTS,
172                 {"packets", required_argument, 0, 'p'},
173                 {"nohtml", no_argument, 0, 'n'},
174                 {"link", no_argument, 0, 'L'},
175                 {"use-ipv4", no_argument, 0, '4'},
176                 {"use-ipv6", no_argument, 0, '6'},
177                 {0, 0, 0, 0}
178         };
180         if (argc < 2)
181                 return ERROR;
183         for (c = 1; c < argc; c++) {
184                 if (strcmp ("-to", argv[c]) == 0)
185                         strcpy (argv[c], "-t");
186                 if (strcmp ("-nohtml", argv[c]) == 0)
187                         strcpy (argv[c], "-n");
188         }
190         while (1) {
191                 c = getopt_long (argc, argv, "VvhnL46t:c:w:H:p:", longopts, &option);
193                 if (c == -1 || c == EOF)
194                         break;
196                 switch (c) {
197                 case '?':       /* usage */
198                         usage2 (_("Unknown argument"), optarg);
199                 case 'h':       /* help */
200                         print_help ();
201                         exit (STATE_OK);
202                         break;
203                 case 'V':       /* version */
204                         print_revision (progname, revision);
205                         exit (STATE_OK);
206                         break;
207                 case 't':       /* timeout period */
208                         timeout_interval = atoi (optarg);
209                         break;
210                 case 'v':       /* verbose mode */
211                         verbose++;
212                         break;
213                 case '4':       /* IPv4 only */
214                         address_family = AF_INET;
215                         break;
216                 case '6':       /* IPv6 only */
217 #ifdef USE_IPV6
218                         address_family = AF_INET6;
219 #else
220                         usage (_("IPv6 support not available\n"));
221 #endif
222                         break;
223                 case 'H':       /* hostname */
224                         ptr=optarg;
225                         while (1) {
226                                 n_addresses++;
227                                 if (n_addresses > max_addr) {
228                                         max_addr *= 2;
229                                         addresses = realloc (addresses, sizeof(char*) * max_addr);
230                                         if (addresses == NULL)
231                                                 die (STATE_UNKNOWN, _("Could not realloc() addresses\n"));
232                                 }
233                                 addresses[n_addresses-1] = ptr;
234                                 if ((ptr = index (ptr, ','))) {
235                                         strcpy (ptr, "");
236                                         ptr += sizeof(char);
237                                 } else {
238                                         break;
239                                 }
240                         }
241                         break;
242                 case 'p':       /* number of packets to send */
243                         if (is_intnonneg (optarg))
244                                 max_packets = atoi (optarg);
245                         else
246                                 usage2 (_("<max_packets> (%s) must be a non-negative number\n"), optarg);
247                         break;
248                 case 'n':       /* no HTML */
249                         display_html = FALSE;
250                         break;
251                 case 'L':       /* show HTML */
252                         display_html = TRUE;
253                         break;
254                 case 'c':
255                         get_threshold (optarg, &crta, &cpl);
256                         break;
257                 case 'w':
258                         get_threshold (optarg, &wrta, &wpl);
259                         break;
260                 }
261         }
263         c = optind;
264         if (c == argc)
265                 return validate_arguments ();
267         if (addresses[0] == NULL) {
268                 if (is_host (argv[c]) == FALSE) {
269                         usage2 (_("Invalid hostname/address"), argv[c]);
270                 } else {
271                         addresses[0] = argv[c++];
272                         n_addresses++;
273                         if (c == argc)
274                                 return validate_arguments ();
275                 }
276         }
278         if (wpl == UNKNOWN_PACKET_LOSS) {
279                 if (is_intpercent (argv[c]) == FALSE) {
280                         printf (_("<wpl> (%s) must be an integer percentage\n"), argv[c]);
281                         return ERROR;
282                 } else {
283                         wpl = atoi (argv[c++]);
284                         if (c == argc)
285                                 return validate_arguments ();
286                 }
287         }
289         if (cpl == UNKNOWN_PACKET_LOSS) {
290                 if (is_intpercent (argv[c]) == FALSE) {
291                         printf (_("<cpl> (%s) must be an integer percentage\n"), argv[c]);
292                         return ERROR;
293                 } else {
294                         cpl = atoi (argv[c++]);
295                         if (c == argc)
296                                 return validate_arguments ();
297                 }
298         }
300         if (wrta < 0.0) {
301                 if (is_negative (argv[c])) {
302                         printf (_("<wrta> (%s) must be a non-negative number\n"), argv[c]);
303                         return ERROR;
304                 } else {
305                         wrta = atof (argv[c++]);
306                         if (c == argc)
307                                 return validate_arguments ();
308                 }
309         }
311         if (crta < 0.0) {
312                 if (is_negative (argv[c])) {
313                         printf (_("<crta> (%s) must be a non-negative number\n"), argv[c]);
314                         return ERROR;
315                 } else {
316                         crta = atof (argv[c++]);
317                         if (c == argc)
318                                 return validate_arguments ();
319                 }
320         }
322         if (max_packets == -1) {
323                 if (is_intnonneg (argv[c])) {
324                         max_packets = atoi (argv[c++]);
325                 } else {
326                         printf (_("<max_packets> (%s) must be a non-negative number\n"), argv[c]);
327                         return ERROR;
328                 }
329         }
331         return validate_arguments ();
336 int
337 get_threshold (char *arg, float *trta, int *tpl)
339         if (is_intnonneg (arg) && sscanf (arg, "%f", trta) == 1)
340                 return OK;
341         else if (strpbrk (arg, ",:") && strstr (arg, "%") && sscanf (arg, "%f%*[:,]%d%%", trta, tpl) == 2)
342                 return OK;
343         else if (strstr (arg, "%") && sscanf (arg, "%d%%", tpl) == 1) 
344                 return OK;
346         usage2 (_("%s: Warning threshold must be integer or percentage!\n\n"), arg);
347         return STATE_UNKNOWN;
352 int
353 validate_arguments ()
355         float max_seconds;
356         int i;
358         if (wrta < 0.0) {
359                 printf (_("<wrta> was not set\n"));
360                 return ERROR;
361         }
362         else if (crta < 0.0) {
363                 printf (_("<crta> was not set\n"));
364                 return ERROR;
365         }
366         else if (wpl == UNKNOWN_PACKET_LOSS) {
367                 printf (_("<wpl> was not set\n"));
368                 return ERROR;
369         }
370         else if (cpl == UNKNOWN_PACKET_LOSS) {
371                 printf (_("<cpl> was not set\n"));
372                 return ERROR;
373         }
374         else if (wrta > crta) {
375                 printf (_("<wrta> (%f) cannot be larger than <crta> (%f)\n"), wrta, crta);
376                 return ERROR;
377         }
378         else if (wpl > cpl) {
379                 printf (_("<wpl> (%d) cannot be larger than <cpl> (%d)\n"), wpl, cpl);
380                 return ERROR;
381         }
383         if (max_packets == -1)
384                 max_packets = DEFAULT_MAX_PACKETS;
386         max_seconds = crta / 1000.0 * max_packets + max_packets;
387         if (max_seconds > timeout_interval)
388                 timeout_interval = (int)max_seconds;
390         for (i=0; i<n_addresses; i++) {
391                 if (is_host(addresses[i]) == FALSE)
392                         usage2 (_("Invalid hostname/address"), addresses[i]);
393         }
395         if (n_addresses == 0) {
396                 usage (_("You must specify a server address or host name"));
397         }
399         return OK;
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, _("Could not open pipe: %s\n"), 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                 if (verbose >= 3)
420                         printf("Output: %s", buf);
422                 result = max_state (result, error_scan (buf, addr));
424                 /* get the percent loss statistics */
425                 if(sscanf(buf,"%*d packets transmitted, %*d packets received, +%*d errors, %d%% packet loss",&pl)==1 ||
426                          sscanf(buf,"%*d packets transmitted, %*d packets received, +%*d duplicates, %d%% packet loss", &pl) == 1 ||
427                          sscanf(buf,"%*d packets transmitted, %*d received, +%*d duplicates, %d%% packet loss", &pl) == 1 ||
428                          sscanf(buf,"%*d packets transmitted, %*d packets received, %d%% packet loss",&pl)==1 ||
429                          sscanf(buf,"%*d packets transmitted, %*d packets received, %d%% loss, time",&pl)==1 ||
430                          sscanf(buf,"%*d packets transmitted, %*d received, %d%% loss, time", &pl)==1 ||
431                          sscanf(buf,"%*d packets transmitted, %*d received, %d%% packet loss, time", &pl)==1 ||
432                          sscanf(buf,"%*d packets transmitted, %*d received, +%*d errors, %d%% packet loss", &pl) == 1 ||
433                          sscanf(buf,"%*d packets transmitted %*d received, +%*d errors, %d%% packet loss", &pl) == 1
434                          )
435                         continue;
437                 /* get the round trip average */
438                 else
439                         if(sscanf(buf,"round-trip min/avg/max = %*f/%f/%*f",&rta)==1 ||
440                                  sscanf(buf,"round-trip min/avg/max/mdev = %*f/%f/%*f/%*f",&rta)==1 ||
441                                  sscanf(buf,"round-trip min/avg/max/sdev = %*f/%f/%*f/%*f",&rta)==1 ||
442                                  sscanf(buf,"round-trip min/avg/max/stddev = %*f/%f/%*f/%*f",&rta)==1 ||
443                                  sscanf(buf,"round-trip min/avg/max/std-dev = %*f/%f/%*f/%*f",&rta)==1 ||
444                                  sscanf(buf,"round-trip (ms) min/avg/max = %*f/%f/%*f",&rta)==1 ||
445                                  sscanf(buf,"round-trip (ms) min/avg/max/stddev = %*f/%f/%*f/%*f",&rta)==1 ||
446                                  sscanf(buf,"rtt min/avg/max/mdev = %*f/%f/%*f/%*f ms",&rta)==1)
447                         continue;
448         }
450         /* this is needed because there is no rta if all packets are lost */
451         if (pl == 100)
452                 rta = crta;
454         /* check stderr, setting at least WARNING if there is output here */
455         /* Add warning into warn_text */
456         while (fgets (buf, MAX_INPUT_BUFFER - 1, child_stderr)) {
457                 if (! strstr(buf,"WARNING - no SO_TIMESTAMP support, falling back to SIOCGSTAMP")) {
458                         if (verbose >= 3) {
459                                 printf("Got stderr: %s", buf);
460                         }
461                         if ((result=error_scan(buf, addr)) == STATE_OK) {
462                                 result = STATE_WARNING;
463                                 if (warn_text == NULL) {
464                                         warn_text = strdup(_("System call sent warnings to stderr "));
465                                 } else {
466                                         asprintf(&warn_text, "%s %s", warn_text, _("System call sent warnings to stderr "));
467                                 }
468                         }
469                 }
470         }
472         (void) fclose (child_stderr);
475         /* close the pipe - WARNING if status is set */
476         if (spclose (child_process))
477                 result = max_state (result, STATE_WARNING);
479         if (warn_text == NULL)
480                 warn_text = strdup("");
482         return result;
487 int
488 error_scan (char buf[MAX_INPUT_BUFFER], const char *addr)
490         if (strstr (buf, "Network is unreachable"))
491                 die (STATE_CRITICAL, _("CRITICAL - Network unreachable (%s)"), addr);
492         else if (strstr (buf, "Destination Host Unreachable"))
493                 die (STATE_CRITICAL, _("CRITICAL - Host Unreachable (%s)"), addr);
494         else if (strstr (buf, "unknown host" ))
495                 die (STATE_CRITICAL, _("CRITICAL - Host not found (%s)"), addr);
496         else if (strstr (buf, "Time to live exceeded"))
497                 die (STATE_CRITICAL, _("CRITICAL - Time to live exceeded (%s)"), addr);
499         if (strstr (buf, "(DUP!)") || strstr (buf, "DUPLICATES FOUND")) {
500                 if (warn_text == NULL)
501                         warn_text = strdup (_(WARN_DUPLICATES));
502                 else if (! strstr (warn_text, _(WARN_DUPLICATES)) &&
503                          asprintf (&warn_text, "%s %s", warn_text, _(WARN_DUPLICATES)) == -1)
504                         die (STATE_UNKNOWN, _("Unable to realloc warn_text"));
505                 return (STATE_WARNING);
506         }
508         return (STATE_OK);
513 void
514 print_help (void)
516         print_revision (progname, revision);
518         printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>");
519         printf (COPYRIGHT, copyright, email);
521         printf (_("Use ping to check connection statistics for a remote host."));
523   printf ("\n\n");
525         print_usage ();
527         printf (_(UT_HELP_VRSN));
529         printf (_(UT_IPv46));
531         printf (" %s\n", "-H, --hostname=HOST");
532   printf ("    %s\n", _("host to ping"));
533   printf (" %s\n", "-w, --warning=THRESHOLD");
534   printf ("    %s\n", _("warning threshold pair"));
535   printf (" %s\n", "-c, --critical=THRESHOLD");
536   printf ("    %s\n", _("critical threshold pair"));
537   printf (" %s\n", "-p, --packets=INTEGER");
538   printf ("    %s\n", _("number of ICMP ECHO packets to send"));
539   printf (_("(Default: %d)"), DEFAULT_MAX_PACKETS);
540   printf (" %s\n", "-L, --link");
541   printf ("    %s\n", _("show HTML in the plugin output (obsoleted by urlize)"));
543         printf (_(UT_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);
545         printf ("%s\n", _("THRESHOLD is <rta>,<pl>%% where <rta> is the round trip average travel"));
546   printf ("%s\n", _("time (ms) which triggers a WARNING or CRITICAL state, and <pl> is the"));
547   printf ("%s\n", _("percentage of packet loss to trigger an alarm state."));
549   printf ("\n\n");
551         printf ("%s\n", _("This plugin uses the ping command to probe the specified host for packet loss"));
552   printf ("%s\n", _("(percentage) and round trip average (milliseconds). It can produce HTML output"));
553   printf ("%s\n", _("linking to a traceroute CGI contributed by Ian Cass. The CGI can be found in"));
554   printf ("%s\n", _("the contrib area of the downloads section at http://www.nagios.org/"));
556   printf ("\n\n");
558         printf (_(UT_SUPPORT));
561 void
562 print_usage (void)
564   printf (_("Usage:"));
565         printf ("%s -H <host_address> -w <wrta>,<wpl>%% -c <crta>,<cpl>%%\n", progname);
566   printf (" [-p packets] [-t timeout] [-L] [-4|-6]\n");