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);
444 wresize (main_win, main_win_height, /* width = */ 0);
447 main_win = newwin (/* height = */ main_win_height,
449 /* y = */ 0, /* x = */ 0);
451 /* Allow scrolling */
452 scrollok (main_win, TRUE);
453 /* wsetscrreg (main_win, 0, main_win_height - 1); */
454 /* Allow hardware accelerated scrolling. */
455 idlok (main_win, TRUE);
458 for (iter = ping_iterator_get (ping);
460 iter = ping_iterator_next (iter))
462 ping_context_t *context;
464 context = ping_iterator_get_context (iter);
468 if (context->window != NULL)
470 delwin (context->window);
471 context->window = NULL;
473 context->window = newwin (/* height = */ 4,
475 /* y = */ main_win_height + (4 * context->index),
482 static int check_resize (pingobj_t *ping) /* {{{ */
488 int key = wgetch (stdscr);
491 else if (key == KEY_RESIZE)
496 return (on_resize (ping));
499 } /* }}} int check_resize */
501 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
503 pingobj_iter_t *iter;
511 nodelay (stdscr, TRUE);
513 getmaxyx (stdscr, height, width);
514 if ((height < 1) || (width < 1))
517 if (has_colors () == TRUE)
520 init_pair (OPING_GREEN, COLOR_GREEN, /* default = */ 0);
521 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
522 init_pair (OPING_RED, COLOR_RED, /* default = */ 0);
525 main_win_height = height - (4 * host_num);
526 main_win = newwin (/* height = */ main_win_height,
528 /* y = */ 0, /* x = */ 0);
529 /* Allow scrolling */
530 scrollok (main_win, TRUE);
531 /* wsetscrreg (main_win, 0, main_win_height - 1); */
532 /* Allow hardware accelerated scrolling. */
533 idlok (main_win, TRUE);
534 wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
537 for (iter = ping_iterator_get (ping);
539 iter = ping_iterator_next (iter))
541 ping_context_t *context;
543 context = ping_iterator_get_context (iter);
547 if (context->window != NULL)
549 delwin (context->window);
550 context->window = NULL;
552 context->window = newwin (/* height = */ 4,
554 /* y = */ main_win_height + (4 * context->index),
559 /* Don't know what good this does exactly, but without this code
560 * "check_resize" will be called right after startup and *somehow*
561 * this leads to display errors. If we purge all initial characters
562 * here, the problem goes away. "wgetch" is non-blocking due to
563 * "nodelay" (see above). */
564 while (wgetch (stdscr) != ERR)
566 /* eat up characters */;
570 } /* }}} int pre_loop_hook */
572 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
574 return (check_resize (ping));
575 } /* }}} int pre_sleep_hook */
577 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
579 return (check_resize (ping));
580 } /* }}} int pre_sleep_hook */
581 #else /* if !USE_NCURSES */
582 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
584 pingobj_iter_t *iter;
586 for (iter = ping_iterator_get (ping);
588 iter = ping_iterator_next (iter))
593 ctx = ping_iterator_get_context (iter);
598 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
600 printf ("PING %s (%s) %zu bytes of data.\n",
601 ctx->host, ctx->addr, buffer_size);
605 } /* }}} int pre_loop_hook */
607 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
612 } /* }}} int pre_sleep_hook */
614 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
617 } /* }}} int post_sleep_hook */
620 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
624 unsigned int sequence;
628 ping_context_t *context;
631 buffer_len = sizeof (latency);
632 ping_iterator_get_info (iter, PING_INFO_LATENCY,
633 &latency, &buffer_len);
636 buffer_len = sizeof (sequence);
637 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
638 &sequence, &buffer_len);
641 buffer_len = sizeof (recv_ttl);
642 ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
643 &recv_ttl, &buffer_len);
646 ping_iterator_get_info (iter, PING_INFO_DATA,
649 context = (ping_context_t *) ping_iterator_get_context (iter);
652 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
654 # define HOST_PRINTF(...) printf(__VA_ARGS__)
661 context->latency_total += latency;
662 context->latency_total_square += (latency * latency);
664 if ((context->latency_max < 0.0) || (context->latency_max < latency))
665 context->latency_max = latency;
666 if ((context->latency_min < 0.0) || (context->latency_min > latency))
667 context->latency_min = latency;
670 if (has_colors () == TRUE)
672 int color = OPING_GREEN;
673 double average = context_get_average (context);
674 double stddev = context_get_stddev (context);
676 if ((latency < (average - (2 * stddev)))
677 || (latency > (average + (2 * stddev))))
679 else if ((latency < (average - stddev))
680 || (latency > (average + stddev)))
681 color = OPING_YELLOW;
683 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i "
685 data_len, context->host, context->addr,
687 wattron (main_win, COLOR_PAIR(color));
688 HOST_PRINTF ("%.2f", latency);
689 wattroff (main_win, COLOR_PAIR(color));
690 HOST_PRINTF (" ms\n");
695 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i "
698 context->host, context->addr,
699 sequence, recv_ttl, latency);
707 if (has_colors () == TRUE)
709 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
710 context->host, context->addr,
712 wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
713 HOST_PRINTF ("timeout");
714 wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
720 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
721 context->host, context->addr,
729 update_stats_from_context (context);
732 } /* }}} void update_host_hook */
734 static int post_loop_hook (pingobj_t *ping) /* {{{ */
736 pingobj_iter_t *iter;
742 for (iter = ping_iterator_get (ping);
744 iter = ping_iterator_next (iter))
746 ping_context_t *context;
748 context = ping_iterator_get_context (iter);
750 printf ("\n--- %s ping statistics ---\n"
751 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
752 context->host, context->req_sent, context->req_rcvd,
753 context_get_packet_loss (context),
754 context->latency_total);
756 if (context->req_rcvd != 0)
761 average = context_get_average (context);
762 deviation = context_get_stddev (context);
764 printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
765 context->latency_min,
767 context->latency_max,
771 ping_iterator_set_context (iter, NULL);
772 context_destroy (context);
776 } /* }}} int post_loop_hook */
778 int main (int argc, char **argv) /* {{{ */
781 pingobj_iter_t *iter;
783 struct sigaction sigint_action;
785 struct timeval tv_begin;
786 struct timeval tv_end;
787 struct timespec ts_wait;
788 struct timespec ts_int;
796 /* Save the old effective user id */
797 saved_set_uid = geteuid ();
798 /* Set the effective user ID to the real user ID without changing the
799 * saved set-user ID */
800 status = seteuid (getuid ());
803 fprintf (stderr, "Temporarily dropping privileges "
804 "failed: %s\n", strerror (errno));
809 optind = read_options (argc, argv);
811 #if !_POSIX_SAVED_IDS
812 /* Cannot temporarily drop privileges -> reject every file but "-". */
813 if ((opt_filename != NULL)
814 && (strcmp ("-", opt_filename) != 0)
815 && (getuid () != geteuid ()))
817 fprintf (stderr, "Your real and effective user IDs don't "
818 "match. Reading from a file (option '-f')\n"
819 "is therefore too risky. You can still read "
820 "from STDIN using '-f -' if you like.\n"
826 if ((optind >= argc) && (opt_filename == NULL)) {
827 usage_exit (argv[0], 1);
830 if ((ping = ping_construct ()) == NULL)
832 fprintf (stderr, "ping_construct failed\n");
836 if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
838 fprintf (stderr, "Setting TTL to %i failed: %s\n",
839 opt_send_ttl, ping_get_error (ping));
846 temp_nsec = modf (opt_interval, &temp_sec);
847 ts_int.tv_sec = (time_t) temp_sec;
848 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
850 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
853 if (opt_addrfamily != PING_DEF_AF)
854 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
856 if (opt_srcaddr != NULL)
858 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
860 fprintf (stderr, "Setting source address failed: %s\n",
861 ping_get_error (ping));
865 if (opt_device != NULL)
867 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
869 fprintf (stderr, "Setting device failed: %s\n",
870 ping_get_error (ping));
874 if (opt_filename != NULL)
880 if (strcmp (opt_filename, "-") == 0)
882 infile = fdopen(0, "r");
884 infile = fopen(opt_filename, "r");
888 fprintf (stderr, "Opening %s failed: %s\n",
889 (strcmp (opt_filename, "-") == 0)
890 ? "STDIN" : opt_filename,
896 /* Regain privileges */
897 status = seteuid (saved_set_uid);
900 fprintf (stderr, "Temporarily re-gaining privileges "
901 "failed: %s\n", strerror (errno));
906 while (fgets(line, sizeof(line), infile))
908 /* Strip whitespace */
909 if (sscanf(line, "%s", host) != 1)
912 if ((host[0] == 0) || (host[0] == '#'))
915 if (ping_host_add(ping, host) < 0)
917 const char *errmsg = ping_get_error (ping);
919 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
929 /* Drop privileges */
930 status = seteuid (getuid ());
933 fprintf (stderr, "Temporarily dropping privileges "
934 "failed: %s\n", strerror (errno));
943 /* Regain privileges */
944 status = seteuid (saved_set_uid);
947 fprintf (stderr, "Temporarily re-gaining privileges "
948 "failed: %s\n", strerror (errno));
953 for (i = optind; i < argc; i++)
955 if (ping_host_add (ping, argv[i]) < 0)
957 const char *errmsg = ping_get_error (ping);
959 fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
968 /* Permanently drop root privileges if we're setuid-root. */
969 status = setuid (getuid ());
972 fprintf (stderr, "Dropping privileges failed: %s\n",
978 saved_set_uid = (uid_t) -1;
981 ping_initialize_contexts (ping);
986 memset (&sigint_action, '\0', sizeof (sigint_action));
987 sigint_action.sa_handler = sigint_handler;
988 if (sigaction (SIGINT, &sigint_action, NULL) < 0)
990 perror ("sigaction");
994 pre_loop_hook (ping);
996 while (opt_count != 0)
1001 if (gettimeofday (&tv_begin, NULL) < 0)
1003 perror ("gettimeofday");
1007 if (ping_send (ping) < 0)
1009 fprintf (stderr, "ping_send failed: %s\n",
1010 ping_get_error (ping));
1015 for (iter = ping_iterator_get (ping);
1017 iter = ping_iterator_next (iter))
1019 update_host_hook (iter, index);
1023 pre_sleep_hook (ping);
1025 /* Don't sleep in the last iteration */
1029 if (gettimeofday (&tv_end, NULL) < 0)
1031 perror ("gettimeofday");
1035 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1037 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1038 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1042 perror ("nanosleep");
1045 else if (opt_count == 0)
1052 post_sleep_hook (ping);
1056 } /* while (opt_count != 0) */
1058 post_loop_hook (ping);
1060 ping_destroy (ping);
1063 } /* }}} int main */
1065 /* vim: set fdm=marker : */