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>
66 # define NCURSES_OPAQUE 1
69 # define OPING_GREEN 1
70 # define OPING_YELLOW 2
76 #ifndef _POSIX_SAVED_IDS
77 # define _POSIX_SAVED_IDS 0
80 typedef struct ping_context
82 char host[NI_MAXHOST];
83 char addr[NI_MAXHOST];
92 double latency_total_square;
99 static double opt_interval = 1.0;
100 static int opt_addrfamily = PING_DEF_AF;
101 static char *opt_srcaddr = NULL;
102 static char *opt_device = NULL;
103 static char *opt_filename = NULL;
104 static int opt_count = -1;
105 static int opt_send_ttl = 64;
107 static int host_num = 0;
110 static WINDOW *main_win = NULL;
113 static void sigint_handler (int signal) /* {{{ */
115 /* Make compiler happy */
119 } /* }}} void sigint_handler */
121 static ping_context_t *context_create (void) /* {{{ */
125 if ((ret = malloc (sizeof (ping_context_t))) == NULL)
128 memset (ret, '\0', sizeof (ping_context_t));
130 ret->latency_min = -1.0;
131 ret->latency_max = -1.0;
132 ret->latency_total = 0.0;
133 ret->latency_total_square = 0.0;
140 } /* }}} ping_context_t *context_create */
142 static void context_destroy (ping_context_t *context) /* {{{ */
148 if (context->window != NULL)
150 delwin (context->window);
151 context->window = NULL;
156 } /* }}} void context_destroy */
158 static double context_get_average (ping_context_t *ctx) /* {{{ */
165 if (ctx->req_rcvd < 1)
168 num_total = (double) ctx->req_rcvd;
169 return (ctx->latency_total / num_total);
170 } /* }}} double context_get_average */
172 static double context_get_stddev (ping_context_t *ctx) /* {{{ */
179 if (ctx->req_rcvd < 1)
181 else if (ctx->req_rcvd < 2)
184 num_total = (double) ctx->req_rcvd;
185 return (sqrt (((num_total * ctx->latency_total_square)
186 - (ctx->latency_total * ctx->latency_total))
187 / (num_total * (num_total - 1.0))));
188 } /* }}} double context_get_stddev */
190 static double context_get_packet_loss (const ping_context_t *ctx) /* {{{ */
195 if (ctx->req_sent < 1)
198 return (100.0 * (ctx->req_sent - ctx->req_rcvd)
199 / ((double) ctx->req_sent));
200 } /* }}} double context_get_packet_loss */
202 static int ping_initialize_contexts (pingobj_t *ping) /* {{{ */
204 pingobj_iter_t *iter;
211 for (iter = ping_iterator_get (ping);
213 iter = ping_iterator_next (iter))
215 ping_context_t *context;
218 context = context_create ();
219 context->index = index;
221 buffer_size = sizeof (context->host);
222 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
224 buffer_size = sizeof (context->addr);
225 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
227 ping_iterator_set_context (iter, (void *) context);
233 } /* }}} int ping_initialize_contexts */
235 static void usage_exit (const char *name, int status) /* {{{ */
239 name_length = (int) strlen (name);
241 fprintf (stderr, "Usage: %s [OPTIONS] "
242 "-f filename | host [host [host ...]]\n"
244 "\nAvailable options:\n"
245 " -4|-6 force the use of IPv4 or IPv6\n"
246 " -c count number of ICMP packets to send\n"
247 " -i interval interval with which to send ICMP packets\n"
248 " -t ttl time to live for each ICMP packet\n"
249 " -I srcaddr source address\n"
250 " -D device outgoing interface name\n"
251 " -f filename filename to read hosts from\n"
253 "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
254 "by Florian octo Forster <octo@verplant.org>\n"
255 "for contributions see `AUTHORS'\n",
258 } /* }}} void usage_exit */
260 static int read_options (int argc, char **argv) /* {{{ */
266 optchar = getopt (argc, argv, "46c:hi:I:t:f:D:");
275 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
281 new_count = atoi (optarg);
283 opt_count = new_count;
285 fprintf(stderr, "Ignoring invalid count: %s\n",
292 if (opt_filename != NULL)
294 opt_filename = strdup (optarg);
301 new_interval = atof (optarg);
302 if (new_interval < 0.001)
303 fprintf (stderr, "Ignoring invalid interval: %s\n",
306 opt_interval = new_interval;
311 if (opt_srcaddr != NULL)
313 opt_srcaddr = strdup (optarg);
324 new_send_ttl = atoi (optarg);
325 if ((new_send_ttl > 0) && (new_send_ttl < 256))
326 opt_send_ttl = new_send_ttl;
328 fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
334 usage_exit (argv[0], 0);
337 usage_exit (argv[0], 1);
342 } /* }}} read_options */
344 static void time_normalize (struct timespec *ts) /* {{{ */
346 while (ts->tv_nsec < 0)
355 ts->tv_nsec += 1000000000;
358 while (ts->tv_nsec >= 1000000000)
361 ts->tv_nsec -= 1000000000;
363 } /* }}} void time_normalize */
365 static void time_calc (struct timespec *ts_dest, /* {{{ */
366 const struct timespec *ts_int,
367 const struct timeval *tv_begin,
368 const struct timeval *tv_end)
370 ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
371 ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
372 time_normalize (ts_dest);
374 /* Assure that `(begin + interval) > end'.
375 * This may seem overly complicated, but `tv_sec' is of type `time_t'
376 * which may be `unsigned. *sigh* */
377 if ((tv_end->tv_sec > ts_dest->tv_sec)
378 || ((tv_end->tv_sec == ts_dest->tv_sec)
379 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
382 ts_dest->tv_nsec = 0;
386 ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
387 ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
388 time_normalize (ts_dest);
389 } /* }}} void time_calc */
392 static int update_stats_from_context (ping_context_t *ctx) /* {{{ */
394 if ((ctx == NULL) || (ctx->window == NULL))
397 werase (ctx->window);
399 box (ctx->window, 0, 0);
400 wattron (ctx->window, A_BOLD);
401 mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
403 wattroff (ctx->window, A_BOLD);
404 wprintw (ctx->window, "ping statistics ");
405 mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
406 "%i packets transmitted, %i received, %.2f%% packet "
408 ctx->req_sent, ctx->req_rcvd,
409 context_get_packet_loss (ctx),
411 if (ctx->req_rcvd != 0)
416 average = context_get_average (ctx);
417 deviation = context_get_stddev (ctx);
419 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
420 "rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms",
427 wrefresh (ctx->window);
430 } /* }}} int update_stats_from_context */
432 static int on_resize (pingobj_t *ping) /* {{{ */
434 pingobj_iter_t *iter;
439 getmaxyx (stdscr, height, width);
440 if ((height < 1) || (width < 1))
443 main_win_height = height - (4 * host_num);
444 wresize (main_win, main_win_height, /* width = */ width);
445 /* Allow scrolling */
446 scrollok (main_win, TRUE);
447 /* wsetscrreg (main_win, 0, main_win_height - 1); */
448 /* Allow hardware accelerated scrolling. */
449 idlok (main_win, TRUE);
452 for (iter = ping_iterator_get (ping);
454 iter = ping_iterator_next (iter))
456 ping_context_t *context;
458 context = ping_iterator_get_context (iter);
462 if (context->window != NULL)
464 delwin (context->window);
465 context->window = NULL;
467 context->window = newwin (/* height = */ 4,
469 /* y = */ main_win_height + (4 * context->index),
476 static int check_resize (pingobj_t *ping) /* {{{ */
482 int key = wgetch (stdscr);
485 else if (key == KEY_RESIZE)
490 return (on_resize (ping));
493 } /* }}} int check_resize */
495 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
497 pingobj_iter_t *iter;
505 nodelay (stdscr, TRUE);
507 getmaxyx (stdscr, height, width);
508 if ((height < 1) || (width < 1))
511 if (has_colors () == TRUE)
514 init_pair (OPING_GREEN, COLOR_GREEN, /* default = */ 0);
515 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
516 init_pair (OPING_RED, COLOR_RED, /* default = */ 0);
519 main_win_height = height - (4 * host_num);
520 main_win = newwin (/* height = */ main_win_height,
522 /* y = */ 0, /* x = */ 0);
523 /* Allow scrolling */
524 scrollok (main_win, TRUE);
525 /* wsetscrreg (main_win, 0, main_win_height - 1); */
526 /* Allow hardware accelerated scrolling. */
527 idlok (main_win, TRUE);
528 wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
531 for (iter = ping_iterator_get (ping);
533 iter = ping_iterator_next (iter))
535 ping_context_t *context;
537 context = ping_iterator_get_context (iter);
541 if (context->window != NULL)
543 delwin (context->window);
544 context->window = NULL;
546 context->window = newwin (/* height = */ 4,
548 /* y = */ main_win_height + (4 * context->index),
553 /* Don't know what good this does exactly, but without this code
554 * "check_resize" will be called right after startup and *somehow*
555 * this leads to display errors. If we purge all initial characters
556 * here, the problem goes away. "wgetch" is non-blocking due to
557 * "nodelay" (see above). */
558 while (wgetch (stdscr) != ERR)
560 /* eat up characters */;
564 } /* }}} int pre_loop_hook */
566 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
568 return (check_resize (ping));
569 } /* }}} int pre_sleep_hook */
571 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
573 return (check_resize (ping));
574 } /* }}} int pre_sleep_hook */
575 #else /* if !USE_NCURSES */
576 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
578 pingobj_iter_t *iter;
580 for (iter = ping_iterator_get (ping);
582 iter = ping_iterator_next (iter))
587 ctx = ping_iterator_get_context (iter);
592 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
594 printf ("PING %s (%s) %zu bytes of data.\n",
595 ctx->host, ctx->addr, buffer_size);
599 } /* }}} int pre_loop_hook */
601 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
606 } /* }}} int pre_sleep_hook */
608 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
611 } /* }}} int post_sleep_hook */
614 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
618 unsigned int sequence;
622 ping_context_t *context;
625 buffer_len = sizeof (latency);
626 ping_iterator_get_info (iter, PING_INFO_LATENCY,
627 &latency, &buffer_len);
630 buffer_len = sizeof (sequence);
631 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
632 &sequence, &buffer_len);
635 buffer_len = sizeof (recv_ttl);
636 ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
637 &recv_ttl, &buffer_len);
640 ping_iterator_get_info (iter, PING_INFO_DATA,
643 context = (ping_context_t *) ping_iterator_get_context (iter);
646 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
648 # define HOST_PRINTF(...) printf(__VA_ARGS__)
655 context->latency_total += latency;
656 context->latency_total_square += (latency * latency);
658 if ((context->latency_max < 0.0) || (context->latency_max < latency))
659 context->latency_max = latency;
660 if ((context->latency_min < 0.0) || (context->latency_min > latency))
661 context->latency_min = latency;
664 if (has_colors () == TRUE)
666 int color = OPING_GREEN;
667 double average = context_get_average (context);
668 double stddev = context_get_stddev (context);
670 if ((latency < (average - (2 * stddev)))
671 || (latency > (average + (2 * stddev))))
673 else if ((latency < (average - stddev))
674 || (latency > (average + stddev)))
675 color = OPING_YELLOW;
677 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i "
679 data_len, context->host, context->addr,
681 wattron (main_win, COLOR_PAIR(color));
682 HOST_PRINTF ("%.2f", latency);
683 wattroff (main_win, COLOR_PAIR(color));
684 HOST_PRINTF (" ms\n");
689 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i "
692 context->host, context->addr,
693 sequence, recv_ttl, latency);
701 if (has_colors () == TRUE)
703 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
704 context->host, context->addr,
706 wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
707 HOST_PRINTF ("timeout");
708 wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
714 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
715 context->host, context->addr,
723 update_stats_from_context (context);
726 } /* }}} void update_host_hook */
728 static int post_loop_hook (pingobj_t *ping) /* {{{ */
730 pingobj_iter_t *iter;
736 for (iter = ping_iterator_get (ping);
738 iter = ping_iterator_next (iter))
740 ping_context_t *context;
742 context = ping_iterator_get_context (iter);
744 printf ("\n--- %s ping statistics ---\n"
745 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
746 context->host, context->req_sent, context->req_rcvd,
747 context_get_packet_loss (context),
748 context->latency_total);
750 if (context->req_rcvd != 0)
755 average = context_get_average (context);
756 deviation = context_get_stddev (context);
758 printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
759 context->latency_min,
761 context->latency_max,
765 ping_iterator_set_context (iter, NULL);
766 context_destroy (context);
770 } /* }}} int post_loop_hook */
772 int main (int argc, char **argv) /* {{{ */
775 pingobj_iter_t *iter;
777 struct sigaction sigint_action;
779 struct timeval tv_begin;
780 struct timeval tv_end;
781 struct timespec ts_wait;
782 struct timespec ts_int;
790 /* Save the old effective user id */
791 saved_set_uid = geteuid ();
792 /* Set the effective user ID to the real user ID without changing the
793 * saved set-user ID */
794 status = seteuid (getuid ());
797 fprintf (stderr, "Temporarily dropping privileges "
798 "failed: %s\n", strerror (errno));
803 optind = read_options (argc, argv);
805 #if !_POSIX_SAVED_IDS
806 /* Cannot temporarily drop privileges -> reject every file but "-". */
807 if ((opt_filename != NULL)
808 && (strcmp ("-", opt_filename) != 0)
809 && (getuid () != geteuid ()))
811 fprintf (stderr, "Your real and effective user IDs don't "
812 "match. Reading from a file (option '-f')\n"
813 "is therefore too risky. You can still read "
814 "from STDIN using '-f -' if you like.\n"
820 if ((optind >= argc) && (opt_filename == NULL)) {
821 usage_exit (argv[0], 1);
824 if ((ping = ping_construct ()) == NULL)
826 fprintf (stderr, "ping_construct failed\n");
830 if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
832 fprintf (stderr, "Setting TTL to %i failed: %s\n",
833 opt_send_ttl, ping_get_error (ping));
840 temp_nsec = modf (opt_interval, &temp_sec);
841 ts_int.tv_sec = (time_t) temp_sec;
842 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
844 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
847 if (opt_addrfamily != PING_DEF_AF)
848 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
850 if (opt_srcaddr != NULL)
852 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
854 fprintf (stderr, "Setting source address failed: %s\n",
855 ping_get_error (ping));
859 if (opt_device != NULL)
861 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
863 fprintf (stderr, "Setting device failed: %s\n",
864 ping_get_error (ping));
868 if (opt_filename != NULL)
874 if (strcmp (opt_filename, "-") == 0)
876 infile = fdopen(0, "r");
878 infile = fopen(opt_filename, "r");
882 fprintf (stderr, "Opening %s failed: %s\n",
883 (strcmp (opt_filename, "-") == 0)
884 ? "STDIN" : opt_filename,
890 /* Regain privileges */
891 status = seteuid (saved_set_uid);
894 fprintf (stderr, "Temporarily re-gaining privileges "
895 "failed: %s\n", strerror (errno));
900 while (fgets(line, sizeof(line), infile))
902 /* Strip whitespace */
903 if (sscanf(line, "%s", host) != 1)
906 if ((host[0] == 0) || (host[0] == '#'))
909 if (ping_host_add(ping, host) < 0)
911 const char *errmsg = ping_get_error (ping);
913 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
923 /* Drop privileges */
924 status = seteuid (getuid ());
927 fprintf (stderr, "Temporarily dropping privileges "
928 "failed: %s\n", strerror (errno));
937 /* Regain privileges */
938 status = seteuid (saved_set_uid);
941 fprintf (stderr, "Temporarily re-gaining privileges "
942 "failed: %s\n", strerror (errno));
947 for (i = optind; i < argc; i++)
949 if (ping_host_add (ping, argv[i]) < 0)
951 const char *errmsg = ping_get_error (ping);
953 fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
962 /* Permanently drop root privileges if we're setuid-root. */
963 status = setuid (getuid ());
966 fprintf (stderr, "Dropping privileges failed: %s\n",
972 saved_set_uid = (uid_t) -1;
975 ping_initialize_contexts (ping);
980 memset (&sigint_action, '\0', sizeof (sigint_action));
981 sigint_action.sa_handler = sigint_handler;
982 if (sigaction (SIGINT, &sigint_action, NULL) < 0)
984 perror ("sigaction");
988 pre_loop_hook (ping);
990 while (opt_count != 0)
995 if (gettimeofday (&tv_begin, NULL) < 0)
997 perror ("gettimeofday");
1001 if (ping_send (ping) < 0)
1003 fprintf (stderr, "ping_send failed: %s\n",
1004 ping_get_error (ping));
1009 for (iter = ping_iterator_get (ping);
1011 iter = ping_iterator_next (iter))
1013 update_host_hook (iter, index);
1017 pre_sleep_hook (ping);
1019 /* Don't sleep in the last iteration */
1023 if (gettimeofday (&tv_end, NULL) < 0)
1025 perror ("gettimeofday");
1029 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1031 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1032 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1036 perror ("nanosleep");
1039 else if (opt_count == 0)
1046 post_sleep_hook (ping);
1050 } /* while (opt_count != 0) */
1052 post_loop_hook (ping);
1054 ping_destroy (ping);
1057 } /* }}} int main */
1059 /* vim: set fdm=marker : */