check_ping.c 14 KB

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