2 * Object oriented C module to send ICMP and ICMPv6 `echo's.
3 * Copyright (C) 2006-2010 Florian octo Forster <octo at verplant.org>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; only version 2 of the License is
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
31 # error "You don't have the standard C99 header files installed"
32 #endif /* STDC_HEADERS */
42 #if TIME_WITH_SYS_TIME
43 # include <sys/time.h>
47 # include <sys/time.h>
54 # include <netdb.h> /* NI_MAXHOST */
62 #include <sys/types.h>
68 # define OPING_GREEN 1
69 # define OPING_YELLOW 2
75 #ifndef _POSIX_SAVED_IDS
76 # define _POSIX_SAVED_IDS 0
79 typedef struct ping_context
81 char host[NI_MAXHOST];
82 char addr[NI_MAXHOST];
91 double latency_total_square;
98 static double opt_interval = 1.0;
99 static int opt_addrfamily = PING_DEF_AF;
100 static char *opt_srcaddr = NULL;
101 static char *opt_device = NULL;
102 static char *opt_filename = NULL;
103 static int opt_count = -1;
104 static int opt_send_ttl = 64;
106 static int host_num = 0;
109 static WINDOW *main_win = NULL;
112 static void sigint_handler (int signal) /* {{{ */
114 /* Make compiler happy */
118 } /* }}} void sigint_handler */
120 static ping_context_t *context_create (void) /* {{{ */
124 if ((ret = malloc (sizeof (ping_context_t))) == NULL)
127 memset (ret, '\0', sizeof (ping_context_t));
129 ret->latency_min = -1.0;
130 ret->latency_max = -1.0;
131 ret->latency_total = 0.0;
132 ret->latency_total_square = 0.0;
139 } /* }}} ping_context_t *context_create */
141 static void context_destroy (ping_context_t *context) /* {{{ */
147 if (context->window != NULL)
149 delwin (context->window);
150 context->window = NULL;
155 } /* }}} void context_destroy */
157 static double context_get_average (ping_context_t *ctx) /* {{{ */
164 if (ctx->req_rcvd < 1)
167 num_total = (double) ctx->req_rcvd;
168 return (ctx->latency_total / num_total);
169 } /* }}} double context_get_average */
171 static double context_get_stddev (ping_context_t *ctx) /* {{{ */
178 if (ctx->req_rcvd < 1)
180 else if (ctx->req_rcvd < 2)
183 num_total = (double) ctx->req_rcvd;
184 return (sqrt (((num_total * ctx->latency_total_square)
185 - (ctx->latency_total * ctx->latency_total))
186 / (num_total * (num_total - 1.0))));
187 } /* }}} double context_get_stddev */
189 static double context_get_packet_loss (const ping_context_t *ctx) /* {{{ */
194 if (ctx->req_sent < 1)
197 return (100.0 * (ctx->req_sent - ctx->req_rcvd)
198 / ((double) ctx->req_sent));
199 } /* }}} double context_get_packet_loss */
201 static int ping_initialize_contexts (pingobj_t *ping) /* {{{ */
203 pingobj_iter_t *iter;
210 for (iter = ping_iterator_get (ping);
212 iter = ping_iterator_next (iter))
214 ping_context_t *context;
217 context = context_create ();
218 context->index = index;
220 buffer_size = sizeof (context->host);
221 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
223 buffer_size = sizeof (context->addr);
224 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
226 ping_iterator_set_context (iter, (void *) context);
232 } /* }}} int ping_initialize_contexts */
234 static void usage_exit (const char *name, int status) /* {{{ */
238 name_length = (int) strlen (name);
240 fprintf (stderr, "Usage: %s [OPTIONS] "
241 "-f filename | host [host [host ...]]\n"
243 "\nAvailable options:\n"
244 " -4|-6 force the use of IPv4 or IPv6\n"
245 " -c count number of ICMP packets to send\n"
246 " -i interval interval with which to send ICMP packets\n"
247 " -t ttl time to live for each ICMP packet\n"
248 " -I srcaddr source address\n"
249 " -D device outgoing interface name\n"
250 " -f filename filename to read hosts from\n"
252 "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
253 "by Florian octo Forster <octo@verplant.org>\n"
254 "for contributions see `AUTHORS'\n",
257 } /* }}} void usage_exit */
259 static int read_options (int argc, char **argv) /* {{{ */
265 optchar = getopt (argc, argv, "46c:hi:I:t:f:D:");
274 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
280 new_count = atoi (optarg);
282 opt_count = new_count;
284 fprintf(stderr, "Ignoring invalid count: %s\n",
291 if (opt_filename != NULL)
293 opt_filename = strdup (optarg);
300 new_interval = atof (optarg);
301 if (new_interval < 0.001)
302 fprintf (stderr, "Ignoring invalid interval: %s\n",
305 opt_interval = new_interval;
310 if (opt_srcaddr != NULL)
312 opt_srcaddr = strdup (optarg);
323 new_send_ttl = atoi (optarg);
324 if ((new_send_ttl > 0) && (new_send_ttl < 256))
325 opt_send_ttl = new_send_ttl;
327 fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
333 usage_exit (argv[0], 0);
336 usage_exit (argv[0], 1);
341 } /* }}} read_options */
343 static void time_normalize (struct timespec *ts) /* {{{ */
345 while (ts->tv_nsec < 0)
354 ts->tv_nsec += 1000000000;
357 while (ts->tv_nsec >= 1000000000)
360 ts->tv_nsec -= 1000000000;
362 } /* }}} void time_normalize */
364 static void time_calc (struct timespec *ts_dest, /* {{{ */
365 const struct timespec *ts_int,
366 const struct timeval *tv_begin,
367 const struct timeval *tv_end)
369 ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
370 ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
371 time_normalize (ts_dest);
373 /* Assure that `(begin + interval) > end'.
374 * This may seem overly complicated, but `tv_sec' is of type `time_t'
375 * which may be `unsigned. *sigh* */
376 if ((tv_end->tv_sec > ts_dest->tv_sec)
377 || ((tv_end->tv_sec == ts_dest->tv_sec)
378 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
381 ts_dest->tv_nsec = 0;
385 ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
386 ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
387 time_normalize (ts_dest);
388 } /* }}} void time_calc */
391 static int update_stats_from_context (ping_context_t *ctx) /* {{{ */
393 if ((ctx == NULL) || (ctx->window == NULL))
396 werase (ctx->window);
398 box (ctx->window, 0, 0);
399 wattron (ctx->window, A_BOLD);
400 mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
402 wattroff (ctx->window, A_BOLD);
403 wprintw (ctx->window, "ping statistics ");
404 mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
405 "%i packets transmitted, %i received, %.2f%% packet "
407 ctx->req_sent, ctx->req_rcvd,
408 context_get_packet_loss (ctx),
410 if (ctx->req_rcvd != 0)
415 average = context_get_average (ctx);
416 deviation = context_get_stddev (ctx);
418 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
419 "rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms",
426 wrefresh (ctx->window);
429 } /* }}} int update_stats_from_context */
431 static int on_resize (pingobj_t *ping) /* {{{ */
433 pingobj_iter_t *iter;
438 getmaxyx (stdscr, height, width);
439 if ((height < 1) || (width < 1))
442 main_win_height = height - (4 * host_num);
443 wresize (main_win, main_win_height, /* width = */ width);
444 /* Allow scrolling */
445 scrollok (main_win, TRUE);
446 /* wsetscrreg (main_win, 0, main_win_height - 1); */
447 /* Allow hardware accelerated scrolling. */
448 idlok (main_win, TRUE);
451 for (iter = ping_iterator_get (ping);
453 iter = ping_iterator_next (iter))
455 ping_context_t *context;
457 context = ping_iterator_get_context (iter);
461 if (context->window != NULL)
463 delwin (context->window);
464 context->window = NULL;
466 context->window = newwin (/* height = */ 4,
468 /* y = */ main_win_height + (4 * context->index),
475 static int check_resize (pingobj_t *ping) /* {{{ */
481 int key = wgetch (stdscr);
484 else if (key == KEY_RESIZE)
489 return (on_resize (ping));
492 } /* }}} int check_resize */
494 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
496 pingobj_iter_t *iter;
504 nodelay (stdscr, TRUE);
506 getmaxyx (stdscr, height, width);
507 if ((height < 1) || (width < 1))
510 if (has_colors () == TRUE)
513 init_pair (OPING_GREEN, COLOR_GREEN, /* default = */ 0);
514 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
515 init_pair (OPING_RED, COLOR_RED, /* default = */ 0);
518 main_win_height = height - (4 * host_num);
519 main_win = newwin (/* height = */ main_win_height,
521 /* y = */ 0, /* x = */ 0);
522 /* Allow scrolling */
523 scrollok (main_win, TRUE);
524 /* wsetscrreg (main_win, 0, main_win_height - 1); */
525 /* Allow hardware accelerated scrolling. */
526 idlok (main_win, TRUE);
527 wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
530 for (iter = ping_iterator_get (ping);
532 iter = ping_iterator_next (iter))
534 ping_context_t *context;
536 context = ping_iterator_get_context (iter);
540 if (context->window != NULL)
542 delwin (context->window);
543 context->window = NULL;
545 context->window = newwin (/* height = */ 4,
547 /* y = */ main_win_height + (4 * context->index),
552 /* Don't know what good this does exactly, but without this code
553 * "check_resize" will be called right after startup and *somehow*
554 * this leads to display errors. If we purge all initial characters
555 * here, the problem goes away. "wgetch" is non-blocking due to
556 * "nodelay" (see above). */
557 while (wgetch (stdscr) != ERR)
559 /* eat up characters */;
563 } /* }}} int pre_loop_hook */
565 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
567 return (check_resize (ping));
568 } /* }}} int pre_sleep_hook */
570 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
572 return (check_resize (ping));
573 } /* }}} int pre_sleep_hook */
574 #else /* if !USE_NCURSES */
575 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
577 pingobj_iter_t *iter;
579 for (iter = ping_iterator_get (ping);
581 iter = ping_iterator_next (iter))
586 ctx = ping_iterator_get_context (iter);
591 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
593 printf ("PING %s (%s) %zu bytes of data.\n",
594 ctx->host, ctx->addr, buffer_size);
598 } /* }}} int pre_loop_hook */
600 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
605 } /* }}} int pre_sleep_hook */
607 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
610 } /* }}} int post_sleep_hook */
613 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
617 unsigned int sequence;
621 ping_context_t *context;
624 buffer_len = sizeof (latency);
625 ping_iterator_get_info (iter, PING_INFO_LATENCY,
626 &latency, &buffer_len);
629 buffer_len = sizeof (sequence);
630 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
631 &sequence, &buffer_len);
634 buffer_len = sizeof (recv_ttl);
635 ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
636 &recv_ttl, &buffer_len);
639 ping_iterator_get_info (iter, PING_INFO_DATA,
642 context = (ping_context_t *) ping_iterator_get_context (iter);
645 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
647 # define HOST_PRINTF(...) printf(__VA_ARGS__)
654 context->latency_total += latency;
655 context->latency_total_square += (latency * latency);
657 if ((context->latency_max < 0.0) || (context->latency_max < latency))
658 context->latency_max = latency;
659 if ((context->latency_min < 0.0) || (context->latency_min > latency))
660 context->latency_min = latency;
663 if (has_colors () == TRUE)
665 int color = OPING_GREEN;
666 double average = context_get_average (context);
667 double stddev = context_get_stddev (context);
669 if ((latency < (average - (2 * stddev)))
670 || (latency > (average + (2 * stddev))))
672 else if ((latency < (average - stddev))
673 || (latency > (average + stddev)))
674 color = OPING_YELLOW;
676 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i "
678 data_len, context->host, context->addr,
680 wattron (main_win, COLOR_PAIR(color));
681 HOST_PRINTF ("%.2f", latency);
682 wattroff (main_win, COLOR_PAIR(color));
683 HOST_PRINTF (" ms\n");
688 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i "
691 context->host, context->addr,
692 sequence, recv_ttl, latency);
700 if (has_colors () == TRUE)
702 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
703 context->host, context->addr,
705 wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
706 HOST_PRINTF ("timeout");
707 wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
713 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
714 context->host, context->addr,
722 update_stats_from_context (context);
725 } /* }}} void update_host_hook */
727 static int post_loop_hook (pingobj_t *ping) /* {{{ */
729 pingobj_iter_t *iter;
735 for (iter = ping_iterator_get (ping);
737 iter = ping_iterator_next (iter))
739 ping_context_t *context;
741 context = ping_iterator_get_context (iter);
743 printf ("\n--- %s ping statistics ---\n"
744 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
745 context->host, context->req_sent, context->req_rcvd,
746 context_get_packet_loss (context),
747 context->latency_total);
749 if (context->req_rcvd != 0)
754 average = context_get_average (context);
755 deviation = context_get_stddev (context);
757 printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
758 context->latency_min,
760 context->latency_max,
764 ping_iterator_set_context (iter, NULL);
765 context_destroy (context);
769 } /* }}} int post_loop_hook */
771 int main (int argc, char **argv) /* {{{ */
774 pingobj_iter_t *iter;
776 struct sigaction sigint_action;
778 struct timeval tv_begin;
779 struct timeval tv_end;
780 struct timespec ts_wait;
781 struct timespec ts_int;
789 /* Save the old effective user id */
790 saved_set_uid = geteuid ();
791 /* Set the effective user ID to the real user ID without changing the
792 * saved set-user ID */
793 status = seteuid (getuid ());
796 fprintf (stderr, "Temporarily dropping privileges "
797 "failed: %s\n", strerror (errno));
802 optind = read_options (argc, argv);
804 #if !_POSIX_SAVED_IDS
805 /* Cannot temporarily drop privileges -> reject every file but "-". */
806 if ((opt_filename != NULL)
807 && (strcmp ("-", opt_filename) != 0)
808 && (getuid () != geteuid ()))
810 fprintf (stderr, "Your real and effective user IDs don't "
811 "match. Reading from a file (option '-f')\n"
812 "is therefore too risky. You can still read "
813 "from STDIN using '-f -' if you like.\n"
819 if ((optind >= argc) && (opt_filename == NULL)) {
820 usage_exit (argv[0], 1);
823 if ((ping = ping_construct ()) == NULL)
825 fprintf (stderr, "ping_construct failed\n");
829 if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
831 fprintf (stderr, "Setting TTL to %i failed: %s\n",
832 opt_send_ttl, ping_get_error (ping));
839 temp_nsec = modf (opt_interval, &temp_sec);
840 ts_int.tv_sec = (time_t) temp_sec;
841 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
843 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
846 if (opt_addrfamily != PING_DEF_AF)
847 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
849 if (opt_srcaddr != NULL)
851 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
853 fprintf (stderr, "Setting source address failed: %s\n",
854 ping_get_error (ping));
858 if (opt_device != NULL)
860 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
862 fprintf (stderr, "Setting device failed: %s\n",
863 ping_get_error (ping));
867 if (opt_filename != NULL)
873 if (strcmp (opt_filename, "-") == 0)
875 infile = fdopen(0, "r");
877 infile = fopen(opt_filename, "r");
881 fprintf (stderr, "Opening %s failed: %s\n",
882 (strcmp (opt_filename, "-") == 0)
883 ? "STDIN" : opt_filename,
889 /* Regain privileges */
890 status = seteuid (saved_set_uid);
893 fprintf (stderr, "Temporarily re-gaining privileges "
894 "failed: %s\n", strerror (errno));
899 while (fgets(line, sizeof(line), infile))
901 /* Strip whitespace */
902 if (sscanf(line, "%s", host) != 1)
905 if ((host[0] == 0) || (host[0] == '#'))
908 if (ping_host_add(ping, host) < 0)
910 const char *errmsg = ping_get_error (ping);
912 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
922 /* Drop privileges */
923 status = seteuid (getuid ());
926 fprintf (stderr, "Temporarily dropping privileges "
927 "failed: %s\n", strerror (errno));
936 /* Regain privileges */
937 status = seteuid (saved_set_uid);
940 fprintf (stderr, "Temporarily re-gaining privileges "
941 "failed: %s\n", strerror (errno));
946 for (i = optind; i < argc; i++)
948 if (ping_host_add (ping, argv[i]) < 0)
950 const char *errmsg = ping_get_error (ping);
952 fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
961 /* Permanently drop root privileges if we're setuid-root. */
962 status = setuid (getuid ());
965 fprintf (stderr, "Dropping privileges failed: %s\n",
971 saved_set_uid = (uid_t) -1;
974 ping_initialize_contexts (ping);
979 memset (&sigint_action, '\0', sizeof (sigint_action));
980 sigint_action.sa_handler = sigint_handler;
981 if (sigaction (SIGINT, &sigint_action, NULL) < 0)
983 perror ("sigaction");
987 pre_loop_hook (ping);
989 while (opt_count != 0)
994 if (gettimeofday (&tv_begin, NULL) < 0)
996 perror ("gettimeofday");
1000 if (ping_send (ping) < 0)
1002 fprintf (stderr, "ping_send failed: %s\n",
1003 ping_get_error (ping));
1008 for (iter = ping_iterator_get (ping);
1010 iter = ping_iterator_next (iter))
1012 update_host_hook (iter, index);
1016 pre_sleep_hook (ping);
1018 /* Don't sleep in the last iteration */
1022 if (gettimeofday (&tv_end, NULL) < 0)
1024 perror ("gettimeofday");
1028 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1030 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1031 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1035 perror ("nanosleep");
1038 else if (opt_count == 0)
1045 post_sleep_hook (ping);
1049 } /* while (opt_count != 0) */
1051 post_loop_hook (ping);
1053 ping_destroy (ping);
1056 } /* }}} int main */
1058 /* vim: set fdm=marker : */