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) /* {{{ */
237 fprintf (stderr, "Usage: %s [OPTIONS] "
238 "-f filename | host [host [host ...]]\n"
240 "\nAvailable options:\n"
241 " -4|-6 force the use of IPv4 or IPv6\n"
242 " -c count number of ICMP packets to send\n"
243 " -i interval interval with which to send ICMP packets\n"
244 " -t ttl time to live for each ICMP packet\n"
245 " -I srcaddr source address\n"
246 " -D device outgoing interface name\n"
247 " -f filename filename to read hosts from\n"
249 "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
250 "by Florian octo Forster <octo@verplant.org>\n"
251 "for contributions see `AUTHORS'\n",
254 } /* }}} void usage_exit */
256 static int read_options (int argc, char **argv) /* {{{ */
262 optchar = getopt (argc, argv, "46c:hi:I:t:f:D:");
271 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
277 new_count = atoi (optarg);
279 opt_count = new_count;
281 fprintf(stderr, "Ignoring invalid count: %s\n",
288 if (opt_filename != NULL)
290 opt_filename = strdup (optarg);
297 new_interval = atof (optarg);
298 if (new_interval < 0.001)
299 fprintf (stderr, "Ignoring invalid interval: %s\n",
302 opt_interval = new_interval;
307 if (opt_srcaddr != NULL)
309 opt_srcaddr = strdup (optarg);
320 new_send_ttl = atoi (optarg);
321 if ((new_send_ttl > 0) && (new_send_ttl < 256))
322 opt_send_ttl = new_send_ttl;
324 fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
330 usage_exit (argv[0], 0);
333 usage_exit (argv[0], 1);
338 } /* }}} read_options */
340 static void time_normalize (struct timespec *ts) /* {{{ */
342 while (ts->tv_nsec < 0)
351 ts->tv_nsec += 1000000000;
354 while (ts->tv_nsec >= 1000000000)
357 ts->tv_nsec -= 1000000000;
359 } /* }}} void time_normalize */
361 static void time_calc (struct timespec *ts_dest, /* {{{ */
362 const struct timespec *ts_int,
363 const struct timeval *tv_begin,
364 const struct timeval *tv_end)
366 ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
367 ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
368 time_normalize (ts_dest);
370 /* Assure that `(begin + interval) > end'.
371 * This may seem overly complicated, but `tv_sec' is of type `time_t'
372 * which may be `unsigned. *sigh* */
373 if ((tv_end->tv_sec > ts_dest->tv_sec)
374 || ((tv_end->tv_sec == ts_dest->tv_sec)
375 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
378 ts_dest->tv_nsec = 0;
382 ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
383 ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
384 time_normalize (ts_dest);
385 } /* }}} void time_calc */
388 static int update_stats_from_context (ping_context_t *ctx) /* {{{ */
390 if ((ctx == NULL) || (ctx->window == NULL))
393 werase (ctx->window);
395 box (ctx->window, 0, 0);
396 wattron (ctx->window, A_BOLD);
397 mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
399 wattroff (ctx->window, A_BOLD);
400 wprintw (ctx->window, "ping statistics ");
401 mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
402 "%i packets transmitted, %i received, %.2f%% packet "
404 ctx->req_sent, ctx->req_rcvd,
405 context_get_packet_loss (ctx),
407 if (ctx->req_rcvd != 0)
412 average = context_get_average (ctx);
413 deviation = context_get_stddev (ctx);
415 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
416 "rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms",
423 wrefresh (ctx->window);
426 } /* }}} int update_stats_from_context */
428 static int on_resize (pingobj_t *ping) /* {{{ */
430 pingobj_iter_t *iter;
435 getmaxyx (stdscr, height, width);
436 if ((height < 1) || (width < 1))
439 main_win_height = height - (4 * host_num);
440 wresize (main_win, main_win_height, /* width = */ width);
441 /* Allow scrolling */
442 scrollok (main_win, TRUE);
443 /* wsetscrreg (main_win, 0, main_win_height - 1); */
444 /* Allow hardware accelerated scrolling. */
445 idlok (main_win, TRUE);
448 for (iter = ping_iterator_get (ping);
450 iter = ping_iterator_next (iter))
452 ping_context_t *context;
454 context = ping_iterator_get_context (iter);
458 if (context->window != NULL)
460 delwin (context->window);
461 context->window = NULL;
463 context->window = newwin (/* height = */ 4,
465 /* y = */ main_win_height + (4 * context->index),
472 static int check_resize (pingobj_t *ping) /* {{{ */
478 int key = wgetch (stdscr);
481 else if (key == KEY_RESIZE)
486 return (on_resize (ping));
489 } /* }}} int check_resize */
491 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
493 pingobj_iter_t *iter;
501 nodelay (stdscr, TRUE);
503 getmaxyx (stdscr, height, width);
504 if ((height < 1) || (width < 1))
507 if (has_colors () == TRUE)
510 init_pair (OPING_GREEN, COLOR_GREEN, /* default = */ 0);
511 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
512 init_pair (OPING_RED, COLOR_RED, /* default = */ 0);
515 main_win_height = height - (4 * host_num);
516 main_win = newwin (/* height = */ main_win_height,
518 /* y = */ 0, /* x = */ 0);
519 /* Allow scrolling */
520 scrollok (main_win, TRUE);
521 /* wsetscrreg (main_win, 0, main_win_height - 1); */
522 /* Allow hardware accelerated scrolling. */
523 idlok (main_win, TRUE);
524 wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
527 for (iter = ping_iterator_get (ping);
529 iter = ping_iterator_next (iter))
531 ping_context_t *context;
533 context = ping_iterator_get_context (iter);
537 if (context->window != NULL)
539 delwin (context->window);
540 context->window = NULL;
542 context->window = newwin (/* height = */ 4,
544 /* y = */ main_win_height + (4 * context->index),
549 /* Don't know what good this does exactly, but without this code
550 * "check_resize" will be called right after startup and *somehow*
551 * this leads to display errors. If we purge all initial characters
552 * here, the problem goes away. "wgetch" is non-blocking due to
553 * "nodelay" (see above). */
554 while (wgetch (stdscr) != ERR)
556 /* eat up characters */;
560 } /* }}} int pre_loop_hook */
562 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
564 return (check_resize (ping));
565 } /* }}} int pre_sleep_hook */
567 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
569 return (check_resize (ping));
570 } /* }}} int pre_sleep_hook */
571 #else /* if !USE_NCURSES */
572 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
574 pingobj_iter_t *iter;
576 for (iter = ping_iterator_get (ping);
578 iter = ping_iterator_next (iter))
583 ctx = ping_iterator_get_context (iter);
588 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
590 printf ("PING %s (%s) %zu bytes of data.\n",
591 ctx->host, ctx->addr, buffer_size);
595 } /* }}} int pre_loop_hook */
597 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
602 } /* }}} int pre_sleep_hook */
604 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
607 } /* }}} int post_sleep_hook */
610 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
614 unsigned int sequence;
618 ping_context_t *context;
621 buffer_len = sizeof (latency);
622 ping_iterator_get_info (iter, PING_INFO_LATENCY,
623 &latency, &buffer_len);
626 buffer_len = sizeof (sequence);
627 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
628 &sequence, &buffer_len);
631 buffer_len = sizeof (recv_ttl);
632 ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
633 &recv_ttl, &buffer_len);
636 ping_iterator_get_info (iter, PING_INFO_DATA,
639 context = (ping_context_t *) ping_iterator_get_context (iter);
642 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
644 # define HOST_PRINTF(...) printf(__VA_ARGS__)
651 context->latency_total += latency;
652 context->latency_total_square += (latency * latency);
654 if ((context->latency_max < 0.0) || (context->latency_max < latency))
655 context->latency_max = latency;
656 if ((context->latency_min < 0.0) || (context->latency_min > latency))
657 context->latency_min = latency;
660 if (has_colors () == TRUE)
662 int color = OPING_GREEN;
663 double average = context_get_average (context);
664 double stddev = context_get_stddev (context);
666 if ((latency < (average - (2 * stddev)))
667 || (latency > (average + (2 * stddev))))
669 else if ((latency < (average - stddev))
670 || (latency > (average + stddev)))
671 color = OPING_YELLOW;
673 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i "
675 data_len, context->host, context->addr,
677 wattron (main_win, COLOR_PAIR(color));
678 HOST_PRINTF ("%.2f", latency);
679 wattroff (main_win, COLOR_PAIR(color));
680 HOST_PRINTF (" ms\n");
685 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i "
688 context->host, context->addr,
689 sequence, recv_ttl, latency);
697 if (has_colors () == TRUE)
699 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
700 context->host, context->addr,
702 wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
703 HOST_PRINTF ("timeout");
704 wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
710 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
711 context->host, context->addr,
719 update_stats_from_context (context);
722 } /* }}} void update_host_hook */
724 static int post_loop_hook (pingobj_t *ping) /* {{{ */
726 pingobj_iter_t *iter;
732 for (iter = ping_iterator_get (ping);
734 iter = ping_iterator_next (iter))
736 ping_context_t *context;
738 context = ping_iterator_get_context (iter);
740 printf ("\n--- %s ping statistics ---\n"
741 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
742 context->host, context->req_sent, context->req_rcvd,
743 context_get_packet_loss (context),
744 context->latency_total);
746 if (context->req_rcvd != 0)
751 average = context_get_average (context);
752 deviation = context_get_stddev (context);
754 printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
755 context->latency_min,
757 context->latency_max,
761 ping_iterator_set_context (iter, NULL);
762 context_destroy (context);
766 } /* }}} int post_loop_hook */
768 int main (int argc, char **argv) /* {{{ */
771 pingobj_iter_t *iter;
773 struct sigaction sigint_action;
775 struct timeval tv_begin;
776 struct timeval tv_end;
777 struct timespec ts_wait;
778 struct timespec ts_int;
786 /* Save the old effective user id */
787 saved_set_uid = geteuid ();
788 /* Set the effective user ID to the real user ID without changing the
789 * saved set-user ID */
790 status = seteuid (getuid ());
793 fprintf (stderr, "Temporarily dropping privileges "
794 "failed: %s\n", strerror (errno));
799 optind = read_options (argc, argv);
801 #if !_POSIX_SAVED_IDS
802 /* Cannot temporarily drop privileges -> reject every file but "-". */
803 if ((opt_filename != NULL)
804 && (strcmp ("-", opt_filename) != 0)
805 && (getuid () != geteuid ()))
807 fprintf (stderr, "Your real and effective user IDs don't "
808 "match. Reading from a file (option '-f')\n"
809 "is therefore too risky. You can still read "
810 "from STDIN using '-f -' if you like.\n"
816 if ((optind >= argc) && (opt_filename == NULL)) {
817 usage_exit (argv[0], 1);
820 if ((ping = ping_construct ()) == NULL)
822 fprintf (stderr, "ping_construct failed\n");
826 if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
828 fprintf (stderr, "Setting TTL to %i failed: %s\n",
829 opt_send_ttl, ping_get_error (ping));
836 temp_nsec = modf (opt_interval, &temp_sec);
837 ts_int.tv_sec = (time_t) temp_sec;
838 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
840 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
843 if (opt_addrfamily != PING_DEF_AF)
844 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
846 if (opt_srcaddr != NULL)
848 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
850 fprintf (stderr, "Setting source address failed: %s\n",
851 ping_get_error (ping));
855 if (opt_device != NULL)
857 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
859 fprintf (stderr, "Setting device failed: %s\n",
860 ping_get_error (ping));
864 if (opt_filename != NULL)
870 if (strcmp (opt_filename, "-") == 0)
872 infile = fdopen(0, "r");
874 infile = fopen(opt_filename, "r");
878 fprintf (stderr, "Opening %s failed: %s\n",
879 (strcmp (opt_filename, "-") == 0)
880 ? "STDIN" : opt_filename,
886 /* Regain privileges */
887 status = seteuid (saved_set_uid);
890 fprintf (stderr, "Temporarily re-gaining privileges "
891 "failed: %s\n", strerror (errno));
896 while (fgets(line, sizeof(line), infile))
898 /* Strip whitespace */
899 if (sscanf(line, "%s", host) != 1)
902 if ((host[0] == 0) || (host[0] == '#'))
905 if (ping_host_add(ping, host) < 0)
907 const char *errmsg = ping_get_error (ping);
909 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
919 /* Drop privileges */
920 status = seteuid (getuid ());
923 fprintf (stderr, "Temporarily dropping privileges "
924 "failed: %s\n", strerror (errno));
933 /* Regain privileges */
934 status = seteuid (saved_set_uid);
937 fprintf (stderr, "Temporarily re-gaining privileges "
938 "failed: %s\n", strerror (errno));
943 for (i = optind; i < argc; i++)
945 if (ping_host_add (ping, argv[i]) < 0)
947 const char *errmsg = ping_get_error (ping);
949 fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
958 /* Permanently drop root privileges if we're setuid-root. */
959 status = setuid (getuid ());
962 fprintf (stderr, "Dropping privileges failed: %s\n",
968 saved_set_uid = (uid_t) -1;
971 ping_initialize_contexts (ping);
976 memset (&sigint_action, '\0', sizeof (sigint_action));
977 sigint_action.sa_handler = sigint_handler;
978 if (sigaction (SIGINT, &sigint_action, NULL) < 0)
980 perror ("sigaction");
984 pre_loop_hook (ping);
986 while (opt_count != 0)
991 if (gettimeofday (&tv_begin, NULL) < 0)
993 perror ("gettimeofday");
997 if (ping_send (ping) < 0)
999 fprintf (stderr, "ping_send failed: %s\n",
1000 ping_get_error (ping));
1005 for (iter = ping_iterator_get (ping);
1007 iter = ping_iterator_next (iter))
1009 update_host_hook (iter, index);
1013 pre_sleep_hook (ping);
1015 /* Don't sleep in the last iteration */
1019 if (gettimeofday (&tv_end, NULL) < 0)
1021 perror ("gettimeofday");
1025 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1027 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1028 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1032 perror ("nanosleep");
1035 else if (opt_count == 0)
1042 post_sleep_hook (ping);
1046 } /* while (opt_count != 0) */
1048 post_loop_hook (ping);
1050 ping_destroy (ping);
1053 } /* }}} int main */
1055 /* vim: set fdm=marker : */