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];
90 double latency_total_square;
97 static double opt_interval = 1.0;
98 static int opt_addrfamily = PING_DEF_AF;
99 static char *opt_srcaddr = NULL;
100 static char *opt_device = NULL;
101 static char *opt_filename = NULL;
102 static int opt_count = -1;
103 static int opt_send_ttl = 64;
106 static WINDOW *main_win = NULL;
109 static void sigint_handler (int signal) /* {{{ */
111 /* Make compiler happy */
115 } /* }}} void sigint_handler */
117 static ping_context_t *context_create (void)
121 if ((ret = malloc (sizeof (ping_context_t))) == NULL)
124 memset (ret, '\0', sizeof (ping_context_t));
126 ret->latency_min = -1.0;
127 ret->latency_max = -1.0;
128 ret->latency_total = 0.0;
129 ret->latency_total_square = 0.0;
138 static void context_destroy (ping_context_t *context)
144 if (context->window != NULL)
146 delwin (context->window);
147 context->window = NULL;
154 static double context_get_average (ping_context_t *ctx) /* {{{ */
161 if (ctx->req_rcvd < 1)
164 num_total = (double) ctx->req_rcvd;
165 return (ctx->latency_total / num_total);
166 } /* }}} double context_get_average */
168 static double context_get_stddev (ping_context_t *ctx) /* {{{ */
175 if (ctx->req_rcvd < 1)
177 else if (ctx->req_rcvd < 2)
180 num_total = (double) ctx->req_rcvd;
181 return (sqrt (((num_total * ctx->latency_total_square)
182 - (ctx->latency_total * ctx->latency_total))
183 / (num_total * (num_total - 1.0))));
184 } /* }}} double context_get_stddev */
186 static double context_get_packet_loss (const ping_context_t *ctx) /* {{{ */
191 if (ctx->req_sent < 1)
194 return (100.0 * (ctx->req_sent - ctx->req_rcvd)
195 / ((double) ctx->req_sent));
196 } /* }}} double context_get_packet_loss */
198 static void usage_exit (const char *name, int status)
202 name_length = (int) strlen (name);
204 fprintf (stderr, "Usage: %s [OPTIONS] "
205 "-f filename | host [host [host ...]]\n"
207 "\nAvailable options:\n"
208 " -4|-6 force the use of IPv4 or IPv6\n"
209 " -c count number of ICMP packets to send\n"
210 " -i interval interval with which to send ICMP packets\n"
211 " -t ttl time to live for each ICMP packet\n"
212 " -I srcaddr source address\n"
213 " -D device outgoing interface name\n"
214 " -f filename filename to read hosts from\n"
216 "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
217 "by Florian octo Forster <octo@verplant.org>\n"
218 "for contributions see `AUTHORS'\n",
223 static int read_options (int argc, char **argv) /* {{{ */
229 optchar = getopt (argc, argv, "46c:hi:I:t:f:D:");
238 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
244 new_count = atoi (optarg);
246 opt_count = new_count;
248 fprintf(stderr, "Ignoring invalid count: %s\n",
255 if (opt_filename != NULL)
257 opt_filename = strdup (optarg);
264 new_interval = atof (optarg);
265 if (new_interval < 0.001)
266 fprintf (stderr, "Ignoring invalid interval: %s\n",
269 opt_interval = new_interval;
274 if (opt_srcaddr != NULL)
276 opt_srcaddr = strdup (optarg);
287 new_send_ttl = atoi (optarg);
288 if ((new_send_ttl > 0) && (new_send_ttl < 256))
289 opt_send_ttl = new_send_ttl;
291 fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
297 usage_exit (argv[0], 0);
300 usage_exit (argv[0], 1);
305 } /* }}} read_options */
307 static void time_normalize (struct timespec *ts) /* {{{ */
309 while (ts->tv_nsec < 0)
318 ts->tv_nsec += 1000000000;
321 while (ts->tv_nsec >= 1000000000)
324 ts->tv_nsec -= 1000000000;
326 } /* }}} void time_normalize */
328 static void time_calc (struct timespec *ts_dest, /* {{{ */
329 const struct timespec *ts_int,
330 const struct timeval *tv_begin,
331 const struct timeval *tv_end)
333 ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
334 ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
335 time_normalize (ts_dest);
337 /* Assure that `(begin + interval) > end'.
338 * This may seem overly complicated, but `tv_sec' is of type `time_t'
339 * which may be `unsigned. *sigh* */
340 if ((tv_end->tv_sec > ts_dest->tv_sec)
341 || ((tv_end->tv_sec == ts_dest->tv_sec)
342 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
345 ts_dest->tv_nsec = 0;
349 ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
350 ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
351 time_normalize (ts_dest);
352 } /* }}} void time_calc */
355 static int context_window_repaint (ping_context_t *ctx, /* {{{ */
361 if (ctx->window == NULL)
363 ctx->window = newwin (/* height = */ 4, /* width = */ 0,
364 /* start y = */ 4 * index, /* start x = */ 0);
366 else /* if (ctx->window != NULL) */
368 werase (ctx->window);
371 box (ctx->window, 0, 0);
372 wattron (ctx->window, A_BOLD);
373 mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
375 wattroff (ctx->window, A_BOLD);
376 wprintw (ctx->window, "ping statistics ");
377 mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
378 "%i packets transmitted, %i received, %.2f%% packet "
380 ctx->req_sent, ctx->req_rcvd,
381 context_get_packet_loss (ctx),
383 if (ctx->req_rcvd != 0)
388 average = context_get_average (ctx);
389 deviation = context_get_stddev (ctx);
391 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
392 "rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms",
399 wrefresh (ctx->window);
402 } /* }}} int context_window_repaint */
404 static int resize_windows (pingobj_t *ping) /* {{{ */
407 pingobj_iter_t *iter;
414 int key = wgetch (stdscr);
417 else if (key == KEY_RESIZE)
424 getmaxyx (stdscr, height, width);
425 if ((height < 1) || (width < 1))
429 for (iter = ping_iterator_get (ping);
431 iter = ping_iterator_next (iter))
433 ping_context_t *ctx = ping_iterator_get_context (iter);
435 if (ctx->window == NULL)
441 wresize (ctx->window, 4, width);
442 context_window_repaint (ctx, index);
447 if (main_win != NULL)
449 wresize (main_win, height - (4 * index), width);
450 /* touchwin (main_win); */
451 /* wrefresh (main_win); */
452 clearok (main_win, TRUE);
456 } /* }}} int resize_windows */
459 static void print_host (pingobj_iter_t *iter, /* {{{ */
463 unsigned int sequence;
467 ping_context_t *context;
470 buffer_len = sizeof (latency);
471 ping_iterator_get_info (iter, PING_INFO_LATENCY,
472 &latency, &buffer_len);
475 buffer_len = sizeof (sequence);
476 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
477 &sequence, &buffer_len);
480 buffer_len = sizeof (recv_ttl);
481 ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
482 &recv_ttl, &buffer_len);
485 ping_iterator_get_info (iter, PING_INFO_DATA,
488 context = (ping_context_t *) ping_iterator_get_context (iter);
491 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
493 # define HOST_PRINTF(...) printf(__VA_ARGS__)
500 context->latency_total += latency;
501 context->latency_total_square += (latency * latency);
503 if ((context->latency_max < 0.0) || (context->latency_max < latency))
504 context->latency_max = latency;
505 if ((context->latency_min < 0.0) || (context->latency_min > latency))
506 context->latency_min = latency;
509 if (has_colors () == TRUE)
511 int color = OPING_GREEN;
512 double average = context_get_average (context);
513 double stddev = context_get_stddev (context);
515 if ((latency < (average - (2 * stddev)))
516 || (latency > (average + (2 * stddev))))
518 else if ((latency < (average - stddev))
519 || (latency > (average + stddev)))
520 color = OPING_YELLOW;
522 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i "
524 data_len, context->host, context->addr,
526 wattron (main_win, COLOR_PAIR(color));
527 HOST_PRINTF ("%.2f", latency);
528 wattroff (main_win, COLOR_PAIR(color));
529 HOST_PRINTF (" ms\n");
534 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i "
537 context->host, context->addr,
538 sequence, recv_ttl, latency);
546 if (has_colors () == TRUE)
548 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
549 context->host, context->addr,
551 wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
552 HOST_PRINTF ("timeout");
553 wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
559 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
560 context->host, context->addr,
568 context_window_repaint (context, index);
571 } /* }}} void print_host */
573 static int print_header (pingobj_t *ping) /* {{{ */
575 pingobj_iter_t *iter;
582 nodelay (stdscr, TRUE);
584 if (has_colors () == TRUE)
587 init_pair (OPING_GREEN, COLOR_GREEN, /* default = */ 0);
588 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
589 init_pair (OPING_RED, COLOR_RED, /* default = */ 0);
594 for (iter = ping_iterator_get (ping);
596 iter = ping_iterator_next (iter))
598 ping_context_t *context;
601 context = context_create ();
603 buffer_size = sizeof (context->host);
604 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
606 buffer_size = sizeof (context->addr);
607 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
610 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
613 context_window_repaint (context, index);
614 #else /* !USE_NCURSES */
615 printf ("PING %s (%s) %zu bytes of data.\n",
616 context->host, context->addr, buffer_size);
619 ping_iterator_set_context (iter, (void *) context);
625 main_win = newwin (/* height = */ 0, /* width = */ 0,
626 /* y = */ 4 * index, /* x = */ 0);
627 /* Allow scrolling */
628 scrollok (main_win, TRUE);
629 /* Allow hardware accelerated scrolling. */
630 idlok (main_win, TRUE);
632 /* Don't know what good this does exactly, but without this code
633 * "resize_windows" will be called right after startup and *somehow*
634 * this leads to display errors. If we purge all initial characters
635 * here, the problem goes away. "wgetch" is non-blocking due to
636 * "nodelay" (see above). */
637 while (wgetch (stdscr) != ERR)
639 /* eat up characters */;
644 } /* }}} int print_header */
646 static int print_footer (pingobj_t *ping) /* {{{ */
648 pingobj_iter_t *iter;
654 for (iter = ping_iterator_get (ping);
656 iter = ping_iterator_next (iter))
658 ping_context_t *context;
660 context = ping_iterator_get_context (iter);
662 printf ("\n--- %s ping statistics ---\n"
663 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
664 context->host, context->req_sent, context->req_rcvd,
665 context_get_packet_loss (context),
666 context->latency_total);
668 if (context->req_rcvd != 0)
673 average = context_get_average (context);
674 deviation = context_get_stddev (context);
676 printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
677 context->latency_min,
679 context->latency_max,
683 ping_iterator_set_context (iter, NULL);
684 context_destroy (context);
688 } /* }}} int print_footer */
690 int main (int argc, char **argv) /* {{{ */
693 pingobj_iter_t *iter;
695 struct sigaction sigint_action;
697 struct timeval tv_begin;
698 struct timeval tv_end;
699 struct timespec ts_wait;
700 struct timespec ts_int;
708 /* Save the old effective user id */
709 saved_set_uid = geteuid ();
710 /* Set the effective user ID to the real user ID without changing the
711 * saved set-user ID */
712 status = seteuid (getuid ());
715 fprintf (stderr, "Temporarily dropping privileges "
716 "failed: %s\n", strerror (errno));
721 optind = read_options (argc, argv);
723 #if !_POSIX_SAVED_IDS
724 /* Cannot temporarily drop privileges -> reject every file but "-". */
725 if ((opt_filename != NULL)
726 && (strcmp ("-", opt_filename) != 0)
727 && (getuid () != geteuid ()))
729 fprintf (stderr, "Your real and effective user IDs don't "
730 "match. Reading from a file (option '-f')\n"
731 "is therefore too risky. You can still read "
732 "from STDIN using '-f -' if you like.\n"
738 if ((optind >= argc) && (opt_filename == NULL)) {
739 usage_exit (argv[0], 1);
742 if ((ping = ping_construct ()) == NULL)
744 fprintf (stderr, "ping_construct failed\n");
748 if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
750 fprintf (stderr, "Setting TTL to %i failed: %s\n",
751 opt_send_ttl, ping_get_error (ping));
758 temp_nsec = modf (opt_interval, &temp_sec);
759 ts_int.tv_sec = (time_t) temp_sec;
760 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
762 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
765 if (opt_addrfamily != PING_DEF_AF)
766 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
768 if (opt_srcaddr != NULL)
770 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
772 fprintf (stderr, "Setting source address failed: %s\n",
773 ping_get_error (ping));
777 if (opt_device != NULL)
779 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
781 fprintf (stderr, "Setting device failed: %s\n",
782 ping_get_error (ping));
786 if (opt_filename != NULL)
792 if (strcmp (opt_filename, "-") == 0)
794 infile = fdopen(0, "r");
796 infile = fopen(opt_filename, "r");
800 fprintf (stderr, "Opening %s failed: %s\n",
801 (strcmp (opt_filename, "-") == 0)
802 ? "STDIN" : opt_filename,
808 /* Regain privileges */
809 status = seteuid (saved_set_uid);
812 fprintf (stderr, "Temporarily re-gaining privileges "
813 "failed: %s\n", strerror (errno));
818 while (fgets(line, sizeof(line), infile))
820 /* Strip whitespace */
821 if (sscanf(line, "%s", host) != 1)
824 if ((host[0] == 0) || (host[0] == '#'))
827 if (ping_host_add(ping, host) < 0)
829 const char *errmsg = ping_get_error (ping);
831 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
837 /* Drop privileges */
838 status = seteuid (getuid ());
841 fprintf (stderr, "Temporarily dropping privileges "
842 "failed: %s\n", strerror (errno));
851 /* Regain privileges */
852 status = seteuid (saved_set_uid);
855 fprintf (stderr, "Temporarily re-gaining privileges "
856 "failed: %s\n", strerror (errno));
861 for (i = optind; i < argc; i++)
863 if (ping_host_add (ping, argv[i]) < 0)
865 const char *errmsg = ping_get_error (ping);
867 fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
872 /* Permanently drop root privileges if we're setuid-root. */
873 status = setuid (getuid ());
876 fprintf (stderr, "Dropping privileges failed: %s\n",
882 saved_set_uid = (uid_t) -1;
890 memset (&sigint_action, '\0', sizeof (sigint_action));
891 sigint_action.sa_handler = sigint_handler;
892 if (sigaction (SIGINT, &sigint_action, NULL) < 0)
894 perror ("sigaction");
898 while (opt_count != 0)
903 if (gettimeofday (&tv_begin, NULL) < 0)
905 perror ("gettimeofday");
909 if (ping_send (ping) < 0)
911 fprintf (stderr, "ping_send failed: %s\n",
912 ping_get_error (ping));
917 for (iter = ping_iterator_get (ping);
919 iter = ping_iterator_next (iter))
921 print_host (iter, index);
928 /* Don't sleep in the last iteration */
932 if (gettimeofday (&tv_end, NULL) < 0)
934 perror ("gettimeofday");
938 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
940 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
941 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
945 perror ("nanosleep");
948 else if (opt_count == 0)
955 resize_windows (ping);
960 resize_windows (ping);
965 } /* while (opt_count != 0) */
974 /* vim: set fdm=marker : */