2 * Object oriented C module to send ICMP and ICMPv6 `echo's.
3 * Copyright (C) 2006-2014 Florian octo Forster <ff at octo.it>
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
29 # include <inttypes.h>
33 # error "You don't have the standard C99 header files installed"
34 #endif /* STDC_HEADERS */
44 #if TIME_WITH_SYS_TIME
45 # include <sys/time.h>
49 # include <sys/time.h>
56 # include <sys/socket.h>
59 # include <netinet/in.h>
62 # include <netinet/ip.h>
66 # include <netdb.h> /* NI_MAXHOST */
74 #include <sys/types.h>
81 # define NCURSES_OPAQUE 1
82 /* http://newsgroups.derkeiler.com/Archive/Rec/rec.games.roguelike.development/2010-09/msg00050.html */
83 # define _X_OPEN_SOURCE_EXTENDED
85 # if HAVE_NCURSESW_NCURSES_H
86 # include <ncursesw/ncurses.h>
91 # define OPING_GREEN 1
92 # define OPING_YELLOW 2
94 # define OPING_GREEN_HIST 4
95 # define OPING_YELLOW_HIST 5
96 # define OPING_RED_HIST 6
98 static char const * const hist_symbols_utf8[] = {
99 "▁", "▂", "▃", "▄", "▅", "▆", "▇", "█" };
100 static size_t const hist_symbols_utf8_num = sizeof (hist_symbols_utf8)
101 / sizeof (hist_symbols_utf8[0]);
103 /* scancodes for 6 levels of horizontal bars, ncurses-specific */
104 /* those are not the usual constants because those are not constant */
105 static int const hist_symbols_acs[] = {
106 115, /* ACS_S9 "⎽" */
107 114, /* ACS_S7 "⎼" */
108 113, /* ACS_S5 "─" */
109 112, /* ACS_S3 "⎻" */
112 static size_t const hist_symbols_acs_num = sizeof (hist_symbols_acs)
113 / sizeof (hist_symbols_acs[0]);
115 /* use different colors without a background for scancodes */
116 static int const hist_colors_utf8[] = {
117 OPING_GREEN_HIST, OPING_YELLOW_HIST, OPING_RED_HIST };
118 static int const hist_colors_acs[] = {
119 OPING_GREEN, OPING_YELLOW, OPING_RED };
120 /* assuming that both arrays are the same size */
121 static size_t const hist_colors_num = sizeof (hist_colors_utf8)
122 / sizeof (hist_colors_utf8[0]);
127 #ifndef _POSIX_SAVED_IDS
128 # define _POSIX_SAVED_IDS 0
131 #ifndef IPTOS_MINCOST
132 # define IPTOS_MINCOST 0x02
135 /* Remove GNU specific __attribute__ settings when using another compiler */
137 # define __attribute__(x) /**/
140 typedef struct ping_context
142 char host[NI_MAXHOST];
143 char addr[NI_MAXHOST];
151 double latency_total;
152 double latency_total_square;
159 static double opt_interval = 1.0;
160 static int opt_addrfamily = PING_DEF_AF;
161 static char *opt_srcaddr = NULL;
162 static char *opt_device = NULL;
163 static char *opt_filename = NULL;
164 static int opt_count = -1;
165 static int opt_send_ttl = 64;
166 static uint8_t opt_send_qos = 0;
167 static double opt_exit_status_threshold = 1.0;
169 static int opt_utf8 = 0;
172 static int host_num = 0;
175 static WINDOW *main_win = NULL;
178 static void sigint_handler (int signal) /* {{{ */
180 /* Make compiler happy */
184 } /* }}} void sigint_handler */
186 static ping_context_t *context_create (void) /* {{{ */
190 if ((ret = malloc (sizeof (ping_context_t))) == NULL)
193 memset (ret, '\0', sizeof (ping_context_t));
195 ret->latency_min = -1.0;
196 ret->latency_max = -1.0;
197 ret->latency_total = 0.0;
198 ret->latency_total_square = 0.0;
205 } /* }}} ping_context_t *context_create */
207 static void context_destroy (ping_context_t *context) /* {{{ */
213 if (context->window != NULL)
215 delwin (context->window);
216 context->window = NULL;
221 } /* }}} void context_destroy */
223 static double context_get_average (ping_context_t *ctx) /* {{{ */
230 if (ctx->req_rcvd < 1)
233 num_total = (double) ctx->req_rcvd;
234 return (ctx->latency_total / num_total);
235 } /* }}} double context_get_average */
237 static double context_get_stddev (ping_context_t *ctx) /* {{{ */
244 if (ctx->req_rcvd < 1)
246 else if (ctx->req_rcvd < 2)
249 num_total = (double) ctx->req_rcvd;
250 return (sqrt (((num_total * ctx->latency_total_square)
251 - (ctx->latency_total * ctx->latency_total))
252 / (num_total * (num_total - 1.0))));
253 } /* }}} double context_get_stddev */
255 static double context_get_packet_loss (const ping_context_t *ctx) /* {{{ */
260 if (ctx->req_sent < 1)
263 return (100.0 * (ctx->req_sent - ctx->req_rcvd)
264 / ((double) ctx->req_sent));
265 } /* }}} double context_get_packet_loss */
267 static int ping_initialize_contexts (pingobj_t *ping) /* {{{ */
269 pingobj_iter_t *iter;
276 for (iter = ping_iterator_get (ping);
278 iter = ping_iterator_next (iter))
280 ping_context_t *context;
283 context = context_create ();
284 context->index = index;
286 buffer_size = sizeof (context->host);
287 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
289 buffer_size = sizeof (context->addr);
290 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
292 ping_iterator_set_context (iter, (void *) context);
298 } /* }}} int ping_initialize_contexts */
300 static void usage_exit (const char *name, int status) /* {{{ */
302 fprintf (stderr, "Usage: %s [OPTIONS] "
303 "-f filename | host [host [host ...]]\n"
305 "\nAvailable options:\n"
306 " -4|-6 force the use of IPv4 or IPv6\n"
307 " -c count number of ICMP packets to send\n"
308 " -i interval interval with which to send ICMP packets\n"
309 " -t ttl time to live for each ICMP packet\n"
310 " -Q qos Quality of Service (QoS) of outgoing packets\n"
311 " Use \"-Q help\" for a list of valid options.\n"
312 " -I srcaddr source address\n"
313 " -D device outgoing interface name\n"
314 " -f filename filename to read hosts from\n"
316 " -u / -U force / disable UTF-8 output\n"
318 " -Z percent Exit with non-zero exit status if more than this percentage of\n"
319 " probes timed out. (default: never)\n"
321 "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
322 "by Florian octo Forster <octo@verplant.org>\n"
323 "for contributions see `AUTHORS'\n",
326 } /* }}} void usage_exit */
328 __attribute__((noreturn))
329 static void usage_qos_exit (const char *arg, int status) /* {{{ */
332 fprintf (stderr, "Invalid QoS argument: \"%s\"\n\n", arg);
334 fprintf (stderr, "Valid QoS arguments (option \"-Q\") are:\n"
336 " Differentiated Services (IPv4 and IPv6, RFC 2474)\n"
338 " be Best Effort (BE, default PHB).\n"
339 " ef Expedited Forwarding (EF) PHB group (RFC 3246).\n"
340 " (low delay, low loss, low jitter)\n"
341 " va Voice Admit (VA) DSCP (RFC 5865).\n"
342 " (capacity-admitted traffic)\n"
343 " af[1-4][1-3] Assured Forwarding (AF) PHB group (RFC 2597).\n"
344 " For example: \"af12\" (class 1, precedence 2)\n"
345 " cs[0-7] Class Selector (CS) PHB group (RFC 2474).\n"
346 " For example: \"cs1\" (priority traffic)\n"
348 " Type of Service (IPv4, RFC 1349, obsolete)\n"
350 " lowdelay (%#04x) minimize delay\n"
351 " throughput (%#04x) maximize throughput\n"
352 " reliability (%#04x) maximize reliability\n"
353 " mincost (%#04x) minimize monetary cost\n"
355 " Specify manually\n"
357 " 0x00 - 0xff Hexadecimal numeric specification.\n"
358 " 0 - 255 Decimal numeric specification.\n"
360 (unsigned int) IPTOS_LOWDELAY,
361 (unsigned int) IPTOS_THROUGHPUT,
362 (unsigned int) IPTOS_RELIABILITY,
363 (unsigned int) IPTOS_MINCOST);
366 } /* }}} void usage_qos_exit */
368 static int set_opt_send_qos (const char *opt) /* {{{ */
373 if (strcasecmp ("help", opt) == 0)
374 usage_qos_exit (/* arg = */ NULL, /* status = */ EXIT_SUCCESS);
375 /* DiffServ (RFC 2474): */
376 /* - Best effort (BE) */
377 else if (strcasecmp ("be", opt) == 0)
379 /* - Expedited Forwarding (EF, RFC 3246) */
380 else if (strcasecmp ("ef", opt) == 0)
381 opt_send_qos = 0xB8; /* == 0x2E << 2 */
382 /* - Voice Admit (VA, RFC 5865) */
383 else if (strcasecmp ("va", opt) == 0)
384 opt_send_qos = 0xB0; /* == 0x2D << 2 */
385 /* - Assured Forwarding (AF, RFC 2597) */
386 else if ((strncasecmp ("af", opt, strlen ("af")) == 0)
387 && (strlen (opt) == 4))
393 /* There are four classes, AF1x, AF2x, AF3x, and AF4x. */
396 else if (opt[2] == '2')
398 else if (opt[2] == '3')
400 else if (opt[2] == '4')
403 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
405 /* In each class, there are three precedences, AFx1, AFx2, and AFx3 */
408 else if (opt[3] == '2')
410 else if (opt[3] == '3')
413 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
415 dscp = (8 * class) + (2 * prec);
416 /* The lower two bits are used for Explicit Congestion Notification (ECN) */
417 opt_send_qos = dscp << 2;
419 /* - Class Selector (CS) */
420 else if ((strncasecmp ("cs", opt, strlen ("cs")) == 0)
421 && (strlen (opt) == 3))
425 if ((opt[2] < '0') || (opt[2] > '7'))
426 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
428 /* Not exactly legal by the C standard, but I don't know of any
429 * system not supporting this hack. */
430 class = ((uint8_t) opt[2]) - ((uint8_t) '0');
431 opt_send_qos = class << 5;
433 /* Type of Service (RFC 1349) */
434 else if (strcasecmp ("lowdelay", opt) == 0)
435 opt_send_qos = IPTOS_LOWDELAY;
436 else if (strcasecmp ("throughput", opt) == 0)
437 opt_send_qos = IPTOS_THROUGHPUT;
438 else if (strcasecmp ("reliability", opt) == 0)
439 opt_send_qos = IPTOS_RELIABILITY;
440 else if (strcasecmp ("mincost", opt) == 0)
441 opt_send_qos = IPTOS_MINCOST;
450 value = strtoul (opt, &endptr, /* base = */ 0);
451 if ((errno != 0) || (endptr == opt)
452 || (endptr == NULL) || (*endptr != 0)
454 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
456 opt_send_qos = (uint8_t) value;
460 } /* }}} int set_opt_send_qos */
462 static char *format_qos (uint8_t qos, char *buffer, size_t buffer_size) /* {{{ */
474 case 0x00: dscp_str = "be"; break;
475 case 0x2e: dscp_str = "ef"; break;
476 case 0x2d: dscp_str = "va"; break;
477 case 0x0a: dscp_str = "af11"; break;
478 case 0x0c: dscp_str = "af12"; break;
479 case 0x0e: dscp_str = "af13"; break;
480 case 0x12: dscp_str = "af21"; break;
481 case 0x14: dscp_str = "af22"; break;
482 case 0x16: dscp_str = "af23"; break;
483 case 0x1a: dscp_str = "af31"; break;
484 case 0x1c: dscp_str = "af32"; break;
485 case 0x1e: dscp_str = "af33"; break;
486 case 0x22: dscp_str = "af41"; break;
487 case 0x24: dscp_str = "af42"; break;
488 case 0x26: dscp_str = "af43"; break;
489 case 0x08: dscp_str = "cs1"; break;
490 case 0x10: dscp_str = "cs2"; break;
491 case 0x18: dscp_str = "cs3"; break;
492 case 0x20: dscp_str = "cs4"; break;
493 case 0x28: dscp_str = "cs5"; break;
494 case 0x30: dscp_str = "cs6"; break;
495 case 0x38: dscp_str = "cs7"; break;
496 default: dscp_str = NULL;
501 case 0x01: ecn_str = ",ecn(1)"; break;
502 case 0x02: ecn_str = ",ecn(0)"; break;
503 case 0x03: ecn_str = ",ce"; break;
504 default: ecn_str = "";
507 if (dscp_str == NULL)
508 snprintf (buffer, buffer_size, "0x%02x%s", dscp, ecn_str);
510 snprintf (buffer, buffer_size, "%s%s", dscp_str, ecn_str);
511 buffer[buffer_size - 1] = 0;
514 } /* }}} char *format_qos */
516 static int read_options (int argc, char **argv) /* {{{ */
522 optchar = getopt (argc, argv, "46c:hi:I:t:Q:f:D:Z:"
535 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
541 new_count = atoi (optarg);
543 opt_count = new_count;
545 fprintf(stderr, "Ignoring invalid count: %s\n",
552 if (opt_filename != NULL)
554 opt_filename = strdup (optarg);
561 new_interval = atof (optarg);
562 if (new_interval < 0.001)
563 fprintf (stderr, "Ignoring invalid interval: %s\n",
566 opt_interval = new_interval;
571 if (opt_srcaddr != NULL)
573 opt_srcaddr = strdup (optarg);
584 new_send_ttl = atoi (optarg);
585 if ((new_send_ttl > 0) && (new_send_ttl < 256))
586 opt_send_ttl = new_send_ttl;
588 fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
594 set_opt_send_qos (optarg);
612 tmp = strtod (optarg, &endptr);
613 if ((errno != 0) || (endptr == NULL) || (*endptr != 0) || (tmp < 0.0) || (tmp > 100.0))
615 fprintf (stderr, "Ignoring invalid -Z argument: %s\n", optarg);
616 fprintf (stderr, "The \"-Z\" option requires a numeric argument between 0 and 100.\n");
619 opt_exit_status_threshold = tmp / 100.0;
625 usage_exit (argv[0], 0);
628 usage_exit (argv[0], 1);
633 } /* }}} read_options */
635 static void time_normalize (struct timespec *ts) /* {{{ */
637 while (ts->tv_nsec < 0)
646 ts->tv_nsec += 1000000000;
649 while (ts->tv_nsec >= 1000000000)
652 ts->tv_nsec -= 1000000000;
654 } /* }}} void time_normalize */
656 static void time_calc (struct timespec *ts_dest, /* {{{ */
657 const struct timespec *ts_int,
658 const struct timeval *tv_begin,
659 const struct timeval *tv_end)
661 ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
662 ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
663 time_normalize (ts_dest);
665 /* Assure that `(begin + interval) > end'.
666 * This may seem overly complicated, but `tv_sec' is of type `time_t'
667 * which may be `unsigned. *sigh* */
668 if ((tv_end->tv_sec > ts_dest->tv_sec)
669 || ((tv_end->tv_sec == ts_dest->tv_sec)
670 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
673 ts_dest->tv_nsec = 0;
677 ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
678 ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
679 time_normalize (ts_dest);
680 } /* }}} void time_calc */
683 static _Bool has_utf8() /* {{{ */
685 # if HAVE_NCURSESW_NCURSES_H
688 /* Automatically determine */
689 if (strcasecmp ("UTF-8", nl_langinfo (CODESET)) == 0)
694 return ((_Bool) (opt_utf8 - 1));
698 } /* }}} _Bool has_utf8 */
700 static int update_prettyping_graph (ping_context_t *ctx, /* {{{ */
701 double latency, unsigned int sequence)
703 int color = OPING_RED;
704 char const *symbol = "!";
710 x_max = getmaxx (ctx->window);
711 x_pos = ((sequence - 1) % (x_max - 4)) + 2;
717 size_t symbols_num = hist_symbols_acs_num;
718 size_t colors_num = 1;
720 size_t index_symbols;
724 /* latency is in milliseconds, opt_interval is in seconds. */
725 ratio = (latency * 0.001) / opt_interval;
731 symbols_num = hist_symbols_utf8_num;
733 if (has_colors () == TRUE)
734 colors_num = hist_colors_num;
736 intensity = (size_t) (ratio * ((double) (symbols_num * colors_num)));
737 if (intensity >= (symbols_num * colors_num))
738 intensity = (symbols_num * colors_num) - 1;
740 index_symbols = intensity % symbols_num;
741 assert (index_symbols < symbols_num);
743 index_colors = intensity / symbols_num;
744 assert (index_colors < colors_num);
748 color = hist_colors_utf8[index_colors];
749 symbol = hist_symbols_utf8[index_symbols];
753 color = hist_colors_acs[index_colors];
754 symbolc = hist_symbols_acs[index_symbols] | A_ALTCHARSET;
757 else /* if (!(latency >= 0.0)) */
758 wattron (ctx->window, A_BOLD);
760 if (has_colors () == TRUE)
761 wattron (ctx->window, COLOR_PAIR(color));
764 mvwprintw (ctx->window, /* y = */ 3, /* x = */ x_pos, symbol);
766 mvwaddch (ctx->window, /* y = */ 3, /* x = */ x_pos, symbolc);
768 if (has_colors () == TRUE)
769 wattroff (ctx->window, COLOR_PAIR(color));
771 /* Use negation here to handle NaN correctly. */
772 if (!(latency >= 0.0))
773 wattroff (ctx->window, A_BOLD);
775 wprintw (ctx->window, " ");
777 } /* }}} int update_prettyping_graph */
779 static int update_stats_from_context (ping_context_t *ctx, pingobj_iter_t *iter) /* {{{ */
781 double latency = -1.0;
782 size_t buffer_len = sizeof (latency);
784 ping_iterator_get_info (iter, PING_INFO_LATENCY,
785 &latency, &buffer_len);
787 unsigned int sequence = 0;
788 buffer_len = sizeof (sequence);
789 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
790 &sequence, &buffer_len);
793 if ((ctx == NULL) || (ctx->window == NULL))
796 /* werase (ctx->window); */
798 box (ctx->window, 0, 0);
799 wattron (ctx->window, A_BOLD);
800 mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
802 wattroff (ctx->window, A_BOLD);
803 wprintw (ctx->window, "ping statistics ");
804 mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
805 "%i packets transmitted, %i received, %.2f%% packet "
807 ctx->req_sent, ctx->req_rcvd,
808 context_get_packet_loss (ctx),
810 if (ctx->req_rcvd != 0)
815 average = context_get_average (ctx);
816 deviation = context_get_stddev (ctx);
818 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
819 "rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms",
826 update_prettyping_graph (ctx, latency, sequence);
828 wrefresh (ctx->window);
831 } /* }}} int update_stats_from_context */
833 static int on_resize (pingobj_t *ping) /* {{{ */
835 pingobj_iter_t *iter;
840 getmaxyx (stdscr, height, width);
841 if ((height < 1) || (width < 1))
844 main_win_height = height - (5 * host_num);
845 wresize (main_win, main_win_height, /* width = */ width);
846 /* Allow scrolling */
847 scrollok (main_win, TRUE);
848 /* wsetscrreg (main_win, 0, main_win_height - 1); */
849 /* Allow hardware accelerated scrolling. */
850 idlok (main_win, TRUE);
853 for (iter = ping_iterator_get (ping);
855 iter = ping_iterator_next (iter))
857 ping_context_t *context;
859 context = ping_iterator_get_context (iter);
863 if (context->window != NULL)
865 delwin (context->window);
866 context->window = NULL;
868 context->window = newwin (/* height = */ 5,
870 /* y = */ main_win_height + (5 * context->index),
877 static int check_resize (pingobj_t *ping) /* {{{ */
883 int key = wgetch (stdscr);
886 else if (key == KEY_RESIZE)
891 return (on_resize (ping));
894 } /* }}} int check_resize */
896 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
898 pingobj_iter_t *iter;
906 nodelay (stdscr, TRUE);
908 getmaxyx (stdscr, height, width);
909 if ((height < 1) || (width < 1))
912 if (has_colors () == TRUE)
915 init_pair (OPING_GREEN, COLOR_GREEN, /* default = */ 0);
916 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
917 init_pair (OPING_RED, COLOR_RED, /* default = */ 0);
918 init_pair (OPING_GREEN_HIST, COLOR_GREEN, COLOR_BLACK);
919 init_pair (OPING_YELLOW_HIST, COLOR_YELLOW, COLOR_GREEN);
920 init_pair (OPING_RED_HIST, COLOR_RED, COLOR_YELLOW);
923 main_win_height = height - (5 * host_num);
924 main_win = newwin (/* height = */ main_win_height,
926 /* y = */ 0, /* x = */ 0);
927 /* Allow scrolling */
928 scrollok (main_win, TRUE);
929 /* wsetscrreg (main_win, 0, main_win_height - 1); */
930 /* Allow hardware accelerated scrolling. */
931 idlok (main_win, TRUE);
932 wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
935 for (iter = ping_iterator_get (ping);
937 iter = ping_iterator_next (iter))
939 ping_context_t *context;
941 context = ping_iterator_get_context (iter);
945 if (context->window != NULL)
947 delwin (context->window);
948 context->window = NULL;
950 context->window = newwin (/* height = */ 5,
952 /* y = */ main_win_height + (5 * context->index),
957 /* Don't know what good this does exactly, but without this code
958 * "check_resize" will be called right after startup and *somehow*
959 * this leads to display errors. If we purge all initial characters
960 * here, the problem goes away. "wgetch" is non-blocking due to
961 * "nodelay" (see above). */
962 while (wgetch (stdscr) != ERR)
964 /* eat up characters */;
968 } /* }}} int pre_loop_hook */
970 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
972 return (check_resize (ping));
973 } /* }}} int pre_sleep_hook */
975 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
977 return (check_resize (ping));
978 } /* }}} int pre_sleep_hook */
979 #else /* if !USE_NCURSES */
980 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
982 pingobj_iter_t *iter;
984 for (iter = ping_iterator_get (ping);
986 iter = ping_iterator_next (iter))
991 ctx = ping_iterator_get_context (iter);
996 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
998 printf ("PING %s (%s) %zu bytes of data.\n",
999 ctx->host, ctx->addr, buffer_size);
1003 } /* }}} int pre_loop_hook */
1005 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
1010 } /* }}} int pre_sleep_hook */
1012 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
1015 } /* }}} int post_sleep_hook */
1018 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
1019 __attribute__((unused)) int index)
1022 unsigned int sequence;
1025 char recv_qos_str[16];
1028 ping_context_t *context;
1031 buffer_len = sizeof (latency);
1032 ping_iterator_get_info (iter, PING_INFO_LATENCY,
1033 &latency, &buffer_len);
1036 buffer_len = sizeof (sequence);
1037 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
1038 &sequence, &buffer_len);
1041 buffer_len = sizeof (recv_ttl);
1042 ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
1043 &recv_ttl, &buffer_len);
1046 buffer_len = sizeof (recv_qos);
1047 ping_iterator_get_info (iter, PING_INFO_RECV_QOS,
1048 &recv_qos, &buffer_len);
1051 ping_iterator_get_info (iter, PING_INFO_DATA,
1054 context = (ping_context_t *) ping_iterator_get_context (iter);
1057 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
1059 # define HOST_PRINTF(...) printf(__VA_ARGS__)
1062 context->req_sent++;
1065 context->req_rcvd++;
1066 context->latency_total += latency;
1067 context->latency_total_square += (latency * latency);
1069 if ((context->latency_max < 0.0) || (context->latency_max < latency))
1070 context->latency_max = latency;
1071 if ((context->latency_min < 0.0) || (context->latency_min > latency))
1072 context->latency_min = latency;
1075 if (has_colors () == TRUE)
1077 int color = OPING_GREEN;
1078 double average = context_get_average (context);
1079 double stddev = context_get_stddev (context);
1081 if ((latency < (average - (2 * stddev)))
1082 || (latency > (average + (2 * stddev))))
1084 else if ((latency < (average - stddev))
1085 || (latency > (average + stddev)))
1086 color = OPING_YELLOW;
1088 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
1089 data_len, context->host, context->addr,
1091 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1092 if ((recv_qos != 0) || (opt_send_qos != 0))
1094 HOST_PRINTF ("qos=%s ",
1095 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1097 HOST_PRINTF ("time=");
1098 wattron (main_win, COLOR_PAIR(color));
1099 HOST_PRINTF ("%.2f", latency);
1100 wattroff (main_win, COLOR_PAIR(color));
1101 HOST_PRINTF (" ms\n");
1106 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
1108 context->host, context->addr,
1109 sequence, recv_ttl);
1110 if ((recv_qos != 0) || (opt_send_qos != 0))
1112 HOST_PRINTF ("qos=%s ",
1113 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1115 HOST_PRINTF ("time=%.2f ms\n", latency);
1123 if (has_colors () == TRUE)
1125 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
1126 context->host, context->addr,
1128 wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
1129 HOST_PRINTF ("timeout");
1130 wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
1136 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
1137 context->host, context->addr,
1145 update_stats_from_context (context, iter);
1146 wrefresh (main_win);
1148 } /* }}} void update_host_hook */
1150 /* Prints statistics for each host, cleans up the contexts and returns the
1151 * number of hosts which failed to return more than the fraction
1152 * opt_exit_status_threshold of pings. */
1153 static int post_loop_hook (pingobj_t *ping) /* {{{ */
1155 pingobj_iter_t *iter;
1156 int failure_count = 0;
1162 for (iter = ping_iterator_get (ping);
1164 iter = ping_iterator_next (iter))
1166 ping_context_t *context;
1168 context = ping_iterator_get_context (iter);
1170 printf ("\n--- %s ping statistics ---\n"
1171 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
1172 context->host, context->req_sent, context->req_rcvd,
1173 context_get_packet_loss (context),
1174 context->latency_total);
1177 double pct_failed = 1.0 - (((double) context->req_rcvd)
1178 / ((double) context->req_sent));
1179 if (pct_failed > opt_exit_status_threshold)
1183 if (context->req_rcvd != 0)
1188 average = context_get_average (context);
1189 deviation = context_get_stddev (context);
1191 printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
1192 context->latency_min,
1194 context->latency_max,
1198 ping_iterator_set_context (iter, NULL);
1199 context_destroy (context);
1202 return (failure_count);
1203 } /* }}} int post_loop_hook */
1205 int main (int argc, char **argv) /* {{{ */
1208 pingobj_iter_t *iter;
1210 struct sigaction sigint_action;
1212 struct timeval tv_begin;
1213 struct timeval tv_end;
1214 struct timespec ts_wait;
1215 struct timespec ts_int;
1220 #if _POSIX_SAVED_IDS
1221 uid_t saved_set_uid;
1223 /* Save the old effective user id */
1224 saved_set_uid = geteuid ();
1225 /* Set the effective user ID to the real user ID without changing the
1226 * saved set-user ID */
1227 status = seteuid (getuid ());
1230 fprintf (stderr, "Temporarily dropping privileges "
1231 "failed: %s\n", strerror (errno));
1232 exit (EXIT_FAILURE);
1236 setlocale(LC_ALL, "");
1237 optind = read_options (argc, argv);
1239 #if !_POSIX_SAVED_IDS
1240 /* Cannot temporarily drop privileges -> reject every file but "-". */
1241 if ((opt_filename != NULL)
1242 && (strcmp ("-", opt_filename) != 0)
1243 && (getuid () != geteuid ()))
1245 fprintf (stderr, "Your real and effective user IDs don't "
1246 "match. Reading from a file (option '-f')\n"
1247 "is therefore too risky. You can still read "
1248 "from STDIN using '-f -' if you like.\n"
1250 exit (EXIT_FAILURE);
1254 if ((optind >= argc) && (opt_filename == NULL)) {
1255 usage_exit (argv[0], 1);
1258 if ((ping = ping_construct ()) == NULL)
1260 fprintf (stderr, "ping_construct failed\n");
1264 if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
1266 fprintf (stderr, "Setting TTL to %i failed: %s\n",
1267 opt_send_ttl, ping_get_error (ping));
1270 if (ping_setopt (ping, PING_OPT_QOS, &opt_send_qos) != 0)
1272 fprintf (stderr, "Setting TOS to %i failed: %s\n",
1273 opt_send_qos, ping_get_error (ping));
1280 temp_nsec = modf (opt_interval, &temp_sec);
1281 ts_int.tv_sec = (time_t) temp_sec;
1282 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
1284 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
1287 if (opt_addrfamily != PING_DEF_AF)
1288 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
1290 if (opt_srcaddr != NULL)
1292 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
1294 fprintf (stderr, "Setting source address failed: %s\n",
1295 ping_get_error (ping));
1299 if (opt_device != NULL)
1301 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
1303 fprintf (stderr, "Setting device failed: %s\n",
1304 ping_get_error (ping));
1308 if (opt_filename != NULL)
1314 if (strcmp (opt_filename, "-") == 0)
1316 infile = fdopen(0, "r");
1318 infile = fopen(opt_filename, "r");
1322 fprintf (stderr, "Opening %s failed: %s\n",
1323 (strcmp (opt_filename, "-") == 0)
1324 ? "STDIN" : opt_filename,
1329 #if _POSIX_SAVED_IDS
1330 /* Regain privileges */
1331 status = seteuid (saved_set_uid);
1334 fprintf (stderr, "Temporarily re-gaining privileges "
1335 "failed: %s\n", strerror (errno));
1336 exit (EXIT_FAILURE);
1340 while (fgets(line, sizeof(line), infile))
1342 /* Strip whitespace */
1343 if (sscanf(line, "%s", host) != 1)
1346 if ((host[0] == 0) || (host[0] == '#'))
1349 if (ping_host_add(ping, host) < 0)
1351 const char *errmsg = ping_get_error (ping);
1353 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
1362 #if _POSIX_SAVED_IDS
1363 /* Drop privileges */
1364 status = seteuid (getuid ());
1367 fprintf (stderr, "Temporarily dropping privileges "
1368 "failed: %s\n", strerror (errno));
1369 exit (EXIT_FAILURE);
1376 #if _POSIX_SAVED_IDS
1377 /* Regain privileges */
1378 status = seteuid (saved_set_uid);
1381 fprintf (stderr, "Temporarily re-gaining privileges "
1382 "failed: %s\n", strerror (errno));
1383 exit (EXIT_FAILURE);
1387 for (i = optind; i < argc; i++)
1389 if (ping_host_add (ping, argv[i]) < 0)
1391 const char *errmsg = ping_get_error (ping);
1393 fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
1402 /* Permanently drop root privileges if we're setuid-root. */
1403 status = setuid (getuid ());
1406 fprintf (stderr, "Dropping privileges failed: %s\n",
1408 exit (EXIT_FAILURE);
1411 #if _POSIX_SAVED_IDS
1412 saved_set_uid = (uid_t) -1;
1415 ping_initialize_contexts (ping);
1420 memset (&sigint_action, '\0', sizeof (sigint_action));
1421 sigint_action.sa_handler = sigint_handler;
1422 if (sigaction (SIGINT, &sigint_action, NULL) < 0)
1424 perror ("sigaction");
1428 pre_loop_hook (ping);
1430 while (opt_count != 0)
1435 if (gettimeofday (&tv_begin, NULL) < 0)
1437 perror ("gettimeofday");
1441 status = ping_send (ping);
1442 if (status == -EINTR)
1446 else if (status < 0)
1448 fprintf (stderr, "ping_send failed: %s\n",
1449 ping_get_error (ping));
1454 for (iter = ping_iterator_get (ping);
1456 iter = ping_iterator_next (iter))
1458 update_host_hook (iter, index);
1462 pre_sleep_hook (ping);
1464 /* Don't sleep in the last iteration */
1468 if (gettimeofday (&tv_end, NULL) < 0)
1470 perror ("gettimeofday");
1474 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1476 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1477 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1485 perror ("nanosleep");
1490 post_sleep_hook (ping);
1494 } /* while (opt_count != 0) */
1496 /* Returns the number of failed hosts according to -Z. */
1497 status = post_loop_hook (ping);
1499 ping_destroy (ping);
1502 exit (EXIT_SUCCESS);
1509 } /* }}} int main */
1511 /* vim: set fdm=marker : */