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;
106 static unsigned opt_send_tos = 0;
108 static int host_num = 0;
111 static WINDOW *main_win = NULL;
114 static void sigint_handler (int signal) /* {{{ */
116 /* Make compiler happy */
120 } /* }}} void sigint_handler */
122 static ping_context_t *context_create (void) /* {{{ */
126 if ((ret = malloc (sizeof (ping_context_t))) == NULL)
129 memset (ret, '\0', sizeof (ping_context_t));
131 ret->latency_min = -1.0;
132 ret->latency_max = -1.0;
133 ret->latency_total = 0.0;
134 ret->latency_total_square = 0.0;
141 } /* }}} ping_context_t *context_create */
143 static void context_destroy (ping_context_t *context) /* {{{ */
149 if (context->window != NULL)
151 delwin (context->window);
152 context->window = NULL;
157 } /* }}} void context_destroy */
159 static double context_get_average (ping_context_t *ctx) /* {{{ */
166 if (ctx->req_rcvd < 1)
169 num_total = (double) ctx->req_rcvd;
170 return (ctx->latency_total / num_total);
171 } /* }}} double context_get_average */
173 static double context_get_stddev (ping_context_t *ctx) /* {{{ */
180 if (ctx->req_rcvd < 1)
182 else if (ctx->req_rcvd < 2)
185 num_total = (double) ctx->req_rcvd;
186 return (sqrt (((num_total * ctx->latency_total_square)
187 - (ctx->latency_total * ctx->latency_total))
188 / (num_total * (num_total - 1.0))));
189 } /* }}} double context_get_stddev */
191 static double context_get_packet_loss (const ping_context_t *ctx) /* {{{ */
196 if (ctx->req_sent < 1)
199 return (100.0 * (ctx->req_sent - ctx->req_rcvd)
200 / ((double) ctx->req_sent));
201 } /* }}} double context_get_packet_loss */
203 static int ping_initialize_contexts (pingobj_t *ping) /* {{{ */
205 pingobj_iter_t *iter;
212 for (iter = ping_iterator_get (ping);
214 iter = ping_iterator_next (iter))
216 ping_context_t *context;
219 context = context_create ();
220 context->index = index;
222 buffer_size = sizeof (context->host);
223 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
225 buffer_size = sizeof (context->addr);
226 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
228 ping_iterator_set_context (iter, (void *) context);
234 } /* }}} int ping_initialize_contexts */
236 static void usage_exit (const char *name, int status) /* {{{ */
240 name_length = (int) strlen (name);
242 fprintf (stderr, "Usage: %s [OPTIONS] "
243 "-f filename | host [host [host ...]]\n"
245 "\nAvailable options:\n"
246 " -4|-6 force the use of IPv4 or IPv6\n"
247 " -c count number of ICMP packets to send\n"
248 " -i interval interval with which to send ICMP packets\n"
249 " -t ttl time to live for each ICMP packet\n"
250 " -z tos Type-of-service/class-of-service for each ICMP packet\n"
251 " -I srcaddr source address\n"
252 " -D device outgoing interface name\n"
253 " -f filename filename to read hosts from\n"
255 "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
256 "by Florian octo Forster <octo@verplant.org>\n"
257 "for contributions see `AUTHORS'\n",
260 } /* }}} void usage_exit */
262 static int read_options (int argc, char **argv) /* {{{ */
268 optchar = getopt (argc, argv, "46c:hi:I:t:z:f:D:");
277 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
283 new_count = atoi (optarg);
285 opt_count = new_count;
287 fprintf(stderr, "Ignoring invalid count: %s\n",
294 if (opt_filename != NULL)
296 opt_filename = strdup (optarg);
303 new_interval = atof (optarg);
304 if (new_interval < 0.001)
305 fprintf (stderr, "Ignoring invalid interval: %s\n",
308 opt_interval = new_interval;
313 if (opt_srcaddr != NULL)
315 opt_srcaddr = strdup (optarg);
326 new_send_ttl = atoi (optarg);
327 if ((new_send_ttl > 0) && (new_send_ttl < 256))
328 opt_send_ttl = new_send_ttl;
330 fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
338 new_send_tos = atoi (optarg);
339 if ((new_send_tos > 0) && (new_send_tos < 256))
340 opt_send_tos = new_send_tos;
342 fprintf (stderr, "Ignoring invalid TOS argument: %s\n",
348 usage_exit (argv[0], 0);
351 usage_exit (argv[0], 1);
356 } /* }}} read_options */
358 static void time_normalize (struct timespec *ts) /* {{{ */
360 while (ts->tv_nsec < 0)
369 ts->tv_nsec += 1000000000;
372 while (ts->tv_nsec >= 1000000000)
375 ts->tv_nsec -= 1000000000;
377 } /* }}} void time_normalize */
379 static void time_calc (struct timespec *ts_dest, /* {{{ */
380 const struct timespec *ts_int,
381 const struct timeval *tv_begin,
382 const struct timeval *tv_end)
384 ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
385 ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
386 time_normalize (ts_dest);
388 /* Assure that `(begin + interval) > end'.
389 * This may seem overly complicated, but `tv_sec' is of type `time_t'
390 * which may be `unsigned. *sigh* */
391 if ((tv_end->tv_sec > ts_dest->tv_sec)
392 || ((tv_end->tv_sec == ts_dest->tv_sec)
393 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
396 ts_dest->tv_nsec = 0;
400 ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
401 ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
402 time_normalize (ts_dest);
403 } /* }}} void time_calc */
406 static int update_stats_from_context (ping_context_t *ctx) /* {{{ */
408 if ((ctx == NULL) || (ctx->window == NULL))
411 werase (ctx->window);
413 box (ctx->window, 0, 0);
414 wattron (ctx->window, A_BOLD);
415 mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
417 wattroff (ctx->window, A_BOLD);
418 wprintw (ctx->window, "ping statistics ");
419 mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
420 "%i packets transmitted, %i received, %.2f%% packet "
422 ctx->req_sent, ctx->req_rcvd,
423 context_get_packet_loss (ctx),
425 if (ctx->req_rcvd != 0)
430 average = context_get_average (ctx);
431 deviation = context_get_stddev (ctx);
433 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
434 "rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms",
441 wrefresh (ctx->window);
444 } /* }}} int update_stats_from_context */
446 static int on_resize (pingobj_t *ping) /* {{{ */
448 pingobj_iter_t *iter;
453 getmaxyx (stdscr, height, width);
454 if ((height < 1) || (width < 1))
457 main_win_height = height - (4 * host_num);
458 wresize (main_win, main_win_height, /* width = */ width);
459 /* Allow scrolling */
460 scrollok (main_win, TRUE);
461 /* wsetscrreg (main_win, 0, main_win_height - 1); */
462 /* Allow hardware accelerated scrolling. */
463 idlok (main_win, TRUE);
466 for (iter = ping_iterator_get (ping);
468 iter = ping_iterator_next (iter))
470 ping_context_t *context;
472 context = ping_iterator_get_context (iter);
476 if (context->window != NULL)
478 delwin (context->window);
479 context->window = NULL;
481 context->window = newwin (/* height = */ 4,
483 /* y = */ main_win_height + (4 * context->index),
490 static int check_resize (pingobj_t *ping) /* {{{ */
496 int key = wgetch (stdscr);
499 else if (key == KEY_RESIZE)
504 return (on_resize (ping));
507 } /* }}} int check_resize */
509 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
511 pingobj_iter_t *iter;
519 nodelay (stdscr, TRUE);
521 getmaxyx (stdscr, height, width);
522 if ((height < 1) || (width < 1))
525 if (has_colors () == TRUE)
528 init_pair (OPING_GREEN, COLOR_GREEN, /* default = */ 0);
529 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
530 init_pair (OPING_RED, COLOR_RED, /* default = */ 0);
533 main_win_height = height - (4 * host_num);
534 main_win = newwin (/* height = */ main_win_height,
536 /* y = */ 0, /* x = */ 0);
537 /* Allow scrolling */
538 scrollok (main_win, TRUE);
539 /* wsetscrreg (main_win, 0, main_win_height - 1); */
540 /* Allow hardware accelerated scrolling. */
541 idlok (main_win, TRUE);
542 wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
545 for (iter = ping_iterator_get (ping);
547 iter = ping_iterator_next (iter))
549 ping_context_t *context;
551 context = ping_iterator_get_context (iter);
555 if (context->window != NULL)
557 delwin (context->window);
558 context->window = NULL;
560 context->window = newwin (/* height = */ 4,
562 /* y = */ main_win_height + (4 * context->index),
567 /* Don't know what good this does exactly, but without this code
568 * "check_resize" will be called right after startup and *somehow*
569 * this leads to display errors. If we purge all initial characters
570 * here, the problem goes away. "wgetch" is non-blocking due to
571 * "nodelay" (see above). */
572 while (wgetch (stdscr) != ERR)
574 /* eat up characters */;
578 } /* }}} int pre_loop_hook */
580 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
582 return (check_resize (ping));
583 } /* }}} int pre_sleep_hook */
585 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
587 return (check_resize (ping));
588 } /* }}} int pre_sleep_hook */
589 #else /* if !USE_NCURSES */
590 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
592 pingobj_iter_t *iter;
594 for (iter = ping_iterator_get (ping);
596 iter = ping_iterator_next (iter))
601 ctx = ping_iterator_get_context (iter);
606 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
608 printf ("PING %s (%s) %zu bytes of data.\n",
609 ctx->host, ctx->addr, buffer_size);
613 } /* }}} int pre_loop_hook */
615 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
620 } /* }}} int pre_sleep_hook */
622 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
625 } /* }}} int post_sleep_hook */
628 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
632 unsigned int sequence;
637 ping_context_t *context;
640 buffer_len = sizeof (latency);
641 ping_iterator_get_info (iter, PING_INFO_LATENCY,
642 &latency, &buffer_len);
645 buffer_len = sizeof (sequence);
646 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
647 &sequence, &buffer_len);
650 buffer_len = sizeof (recv_ttl);
651 ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
652 &recv_ttl, &buffer_len);
655 buffer_len = sizeof (recv_tos);
656 ping_iterator_get_info (iter, PING_INFO_RECV_TOS,
657 &recv_tos, &buffer_len);
660 ping_iterator_get_info (iter, PING_INFO_DATA,
663 context = (ping_context_t *) ping_iterator_get_context (iter);
666 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
668 # define HOST_PRINTF(...) printf(__VA_ARGS__)
675 context->latency_total += latency;
676 context->latency_total_square += (latency * latency);
678 if ((context->latency_max < 0.0) || (context->latency_max < latency))
679 context->latency_max = latency;
680 if ((context->latency_min < 0.0) || (context->latency_min > latency))
681 context->latency_min = latency;
684 if (has_colors () == TRUE)
686 int color = OPING_GREEN;
687 double average = context_get_average (context);
688 double stddev = context_get_stddev (context);
690 if ((latency < (average - (2 * stddev)))
691 || (latency > (average + (2 * stddev))))
693 else if ((latency < (average - stddev))
694 || (latency > (average + stddev)))
695 color = OPING_YELLOW;
697 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i tos=%u "
699 data_len, context->host, context->addr,
700 sequence, recv_ttl, recv_tos);
701 wattron (main_win, COLOR_PAIR(color));
702 HOST_PRINTF ("%.2f", latency);
703 wattroff (main_win, COLOR_PAIR(color));
704 HOST_PRINTF (" ms\n");
709 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i tos=%u "
712 context->host, context->addr,
713 sequence, recv_ttl, recv_tos, latency);
721 if (has_colors () == TRUE)
723 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
724 context->host, context->addr,
726 wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
727 HOST_PRINTF ("timeout");
728 wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
734 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
735 context->host, context->addr,
743 update_stats_from_context (context);
746 } /* }}} void update_host_hook */
748 static int post_loop_hook (pingobj_t *ping) /* {{{ */
750 pingobj_iter_t *iter;
756 for (iter = ping_iterator_get (ping);
758 iter = ping_iterator_next (iter))
760 ping_context_t *context;
762 context = ping_iterator_get_context (iter);
764 printf ("\n--- %s ping statistics ---\n"
765 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
766 context->host, context->req_sent, context->req_rcvd,
767 context_get_packet_loss (context),
768 context->latency_total);
770 if (context->req_rcvd != 0)
775 average = context_get_average (context);
776 deviation = context_get_stddev (context);
778 printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
779 context->latency_min,
781 context->latency_max,
785 ping_iterator_set_context (iter, NULL);
786 context_destroy (context);
790 } /* }}} int post_loop_hook */
792 int main (int argc, char **argv) /* {{{ */
795 pingobj_iter_t *iter;
797 struct sigaction sigint_action;
799 struct timeval tv_begin;
800 struct timeval tv_end;
801 struct timespec ts_wait;
802 struct timespec ts_int;
810 /* Save the old effective user id */
811 saved_set_uid = geteuid ();
812 /* Set the effective user ID to the real user ID without changing the
813 * saved set-user ID */
814 status = seteuid (getuid ());
817 fprintf (stderr, "Temporarily dropping privileges "
818 "failed: %s\n", strerror (errno));
823 optind = read_options (argc, argv);
825 #if !_POSIX_SAVED_IDS
826 /* Cannot temporarily drop privileges -> reject every file but "-". */
827 if ((opt_filename != NULL)
828 && (strcmp ("-", opt_filename) != 0)
829 && (getuid () != geteuid ()))
831 fprintf (stderr, "Your real and effective user IDs don't "
832 "match. Reading from a file (option '-f')\n"
833 "is therefore too risky. You can still read "
834 "from STDIN using '-f -' if you like.\n"
840 if ((optind >= argc) && (opt_filename == NULL)) {
841 usage_exit (argv[0], 1);
844 if ((ping = ping_construct ()) == NULL)
846 fprintf (stderr, "ping_construct failed\n");
850 if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
852 fprintf (stderr, "Setting TTL to %i failed: %s\n",
853 opt_send_ttl, ping_get_error (ping));
856 if (ping_setopt (ping, PING_OPT_TOS, &opt_send_tos) != 0)
858 fprintf (stderr, "Setting TOS to %i failed: %s\n",
859 opt_send_tos, ping_get_error (ping));
866 temp_nsec = modf (opt_interval, &temp_sec);
867 ts_int.tv_sec = (time_t) temp_sec;
868 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
870 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
873 if (opt_addrfamily != PING_DEF_AF)
874 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
876 if (opt_srcaddr != NULL)
878 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
880 fprintf (stderr, "Setting source address failed: %s\n",
881 ping_get_error (ping));
885 if (opt_device != NULL)
887 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
889 fprintf (stderr, "Setting device failed: %s\n",
890 ping_get_error (ping));
894 if (opt_filename != NULL)
900 if (strcmp (opt_filename, "-") == 0)
902 infile = fdopen(0, "r");
904 infile = fopen(opt_filename, "r");
908 fprintf (stderr, "Opening %s failed: %s\n",
909 (strcmp (opt_filename, "-") == 0)
910 ? "STDIN" : opt_filename,
916 /* Regain privileges */
917 status = seteuid (saved_set_uid);
920 fprintf (stderr, "Temporarily re-gaining privileges "
921 "failed: %s\n", strerror (errno));
926 while (fgets(line, sizeof(line), infile))
928 /* Strip whitespace */
929 if (sscanf(line, "%s", host) != 1)
932 if ((host[0] == 0) || (host[0] == '#'))
935 if (ping_host_add(ping, host) < 0)
937 const char *errmsg = ping_get_error (ping);
939 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
949 /* Drop privileges */
950 status = seteuid (getuid ());
953 fprintf (stderr, "Temporarily dropping privileges "
954 "failed: %s\n", strerror (errno));
963 /* Regain privileges */
964 status = seteuid (saved_set_uid);
967 fprintf (stderr, "Temporarily re-gaining privileges "
968 "failed: %s\n", strerror (errno));
973 for (i = optind; i < argc; i++)
975 if (ping_host_add (ping, argv[i]) < 0)
977 const char *errmsg = ping_get_error (ping);
979 fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
988 /* Permanently drop root privileges if we're setuid-root. */
989 status = setuid (getuid ());
992 fprintf (stderr, "Dropping privileges failed: %s\n",
998 saved_set_uid = (uid_t) -1;
1001 ping_initialize_contexts (ping);
1006 memset (&sigint_action, '\0', sizeof (sigint_action));
1007 sigint_action.sa_handler = sigint_handler;
1008 if (sigaction (SIGINT, &sigint_action, NULL) < 0)
1010 perror ("sigaction");
1014 pre_loop_hook (ping);
1016 while (opt_count != 0)
1021 if (gettimeofday (&tv_begin, NULL) < 0)
1023 perror ("gettimeofday");
1027 if (ping_send (ping) < 0)
1029 fprintf (stderr, "ping_send failed: %s\n",
1030 ping_get_error (ping));
1035 for (iter = ping_iterator_get (ping);
1037 iter = ping_iterator_next (iter))
1039 update_host_hook (iter, index);
1043 pre_sleep_hook (ping);
1045 /* Don't sleep in the last iteration */
1049 if (gettimeofday (&tv_end, NULL) < 0)
1051 perror ("gettimeofday");
1055 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1057 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1058 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1062 perror ("nanosleep");
1065 else if (opt_count == 0)
1072 post_sleep_hook (ping);
1076 } /* while (opt_count != 0) */
1078 post_loop_hook (ping);
1080 ping_destroy (ping);
1083 } /* }}} int main */
1085 /* vim: set fdm=marker : */