2 * Object oriented C module to send ICMP and ICMPv6 `echo's.
3 * Copyright (C) 2006-2016 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 defined HAVE_NCURSESW_CURSES_H
86 # include <ncursesw/curses.h>
87 #elif defined HAVE_NCURSESW_H
88 # include <ncursesw.h>
89 #elif defined HAVE_NCURSES_CURSES_H
90 # include <ncurses/curses.h>
91 #elif defined HAVE_NCURSES_H
94 # error "SysV or X/Open-compatible Curses header file required"
97 # define OPING_GREEN 1
98 # define OPING_YELLOW 2
100 # define OPING_GREEN_HIST 4
101 # define OPING_YELLOW_HIST 5
102 # define OPING_RED_HIST 6
104 double const threshold_green = 0.8;
105 double const threshold_yellow = 0.95;
107 static char const * const hist_symbols_utf8[] = {
108 "▁", "▂", "▃", "▄", "▅", "▆", "▇", "█" };
109 static size_t const hist_symbols_utf8_num = sizeof (hist_symbols_utf8)
110 / sizeof (hist_symbols_utf8[0]);
112 /* scancodes for 6 levels of horizontal bars, ncurses-specific */
113 /* those are not the usual constants because those are not constant */
114 static int const hist_symbols_acs[] = {
115 115, /* ACS_S9 "⎽" */
116 114, /* ACS_S7 "⎼" */
117 113, /* ACS_S5 "─" */
118 112, /* ACS_S3 "⎻" */
121 static size_t const hist_symbols_acs_num = sizeof (hist_symbols_acs)
122 / sizeof (hist_symbols_acs[0]);
124 /* use different colors without a background for scancodes */
125 static int const hist_colors_utf8[] = {
126 OPING_GREEN_HIST, OPING_YELLOW_HIST, OPING_RED_HIST };
127 static int const hist_colors_acs[] = {
128 OPING_GREEN, OPING_YELLOW, OPING_RED };
129 /* assuming that both arrays are the same size */
130 static size_t const hist_colors_num = sizeof (hist_colors_utf8)
131 / sizeof (hist_colors_utf8[0]);
135 #define BOXPLOT_WHISKER_BAR (113 | A_ALTCHARSET)
137 #define BOXPLOT_WHISKER_LEFT_END (116 | A_ALTCHARSET)
139 #define BOXPLOT_WHISKER_RIGHT_END (117 | A_ALTCHARSET)
141 #define BOXPLOT_BOX ' '
143 #define BOXPLOT_MEDIAN (120 | A_ALTCHARSET)
147 #ifndef _POSIX_SAVED_IDS
148 # define _POSIX_SAVED_IDS 0
151 #ifndef IPTOS_MINCOST
152 # define IPTOS_MINCOST 0x02
155 /* Remove GNU specific __attribute__ settings when using another compiler */
157 # define __attribute__(x) /**/
160 typedef struct ping_context
162 char host[NI_MAXHOST];
163 char addr[NI_MAXHOST];
169 double latency_total;
171 #ifndef HISTORY_SIZE_MAX
172 # define HISTORY_SIZE_MAX 900
174 /* The last n RTTs in the order they were sent. */
175 double history_by_time[HISTORY_SIZE_MAX];
177 /* Current number of entries in the history. This is a value between 0
178 * and HISTORY_SIZE_MAX. */
181 /* Total number of reponses received. */
182 size_t history_received;
184 /* Index of the next RTT to be written to history_by_time. This wraps
185 * around to 0 once the histroty has grown to HISTORY_SIZE_MAX. */
186 size_t history_index;
188 /* The last history_size RTTs sorted by value. timed out packets (NAN
189 * entries) are sorted to the back. */
190 double history_by_value[HISTORY_SIZE_MAX];
192 /* If set to true, history_by_value has to be re-calculated. */
200 static double opt_interval = 1.0;
201 static double opt_timeout = PING_DEF_TIMEOUT;
202 static int opt_addrfamily = PING_DEF_AF;
203 static char *opt_srcaddr = NULL;
204 static char *opt_device = NULL;
205 static char *opt_mark = NULL;
206 static char *opt_filename = NULL;
207 static int opt_count = -1;
208 static int opt_send_ttl = 64;
209 static uint8_t opt_send_qos = 0;
210 #define OPING_DEFAULT_PERCENTILE 95.0
211 static double opt_percentile = -1.0;
212 static double opt_exit_status_threshold = 1.0;
214 static int opt_show_graph = 1;
215 static int opt_utf8 = 0;
217 static char *opt_outfile = NULL;
218 static int opt_bell = 0;
220 static int host_num = 0;
221 static FILE *outfile = NULL;
224 static WINDOW *main_win = NULL;
227 static void sigint_handler (int signal) /* {{{ */
229 /* Make compiler happy */
233 } /* }}} void sigint_handler */
235 static ping_context_t *context_create () /* {{{ */
237 ping_context_t *ctx = calloc (1, sizeof (*ctx));
246 } /* }}} ping_context_t *context_create */
248 static void context_destroy (ping_context_t *context) /* {{{ */
254 if (context->window != NULL)
256 delwin (context->window);
257 context->window = NULL;
262 } /* }}} void context_destroy */
264 static int compare_double (void const *arg0, void const *arg1) /* {{{ */
266 double dbl0 = *((double *) arg0);
267 double dbl1 = *((double *) arg1);
276 else if (isnan (dbl1))
278 else if (dbl0 < dbl1)
280 else if (dbl0 > dbl1)
284 } /* }}} int compare_double */
286 static void clean_history (ping_context_t *ctx) /* {{{ */
290 if (!ctx->history_dirty)
293 /* Copy all values from by_time to by_value. */
294 memcpy (ctx->history_by_value, ctx->history_by_time,
295 sizeof (ctx->history_by_time));
297 /* Remove impossible values caused by adding a new host */
298 for (i = 0; i < ctx->history_size; i++)
299 if (ctx->history_by_value[i] < 0)
300 ctx->history_by_value[i] = NAN;
303 qsort (ctx->history_by_value, ctx->history_size, sizeof
304 (ctx->history_by_value[0]), compare_double);
306 /* Update the number of received RTTs. */
307 ctx->history_received = 0;
308 for (i = 0; i < ctx->history_size; i++)
309 if (!isnan (ctx->history_by_value[i]))
310 ctx->history_received++;
313 ctx->history_dirty = 0;
314 } /* }}} void clean_history */
316 static double percentile_to_latency (ping_context_t *ctx, /* {{{ */
323 /* Not a single packet was received successfully. */
324 if (ctx->history_received == 0)
327 if (percentile <= 0.0)
329 else if (percentile >= 100.0)
330 index = ctx->history_received - 1;
333 index = (size_t) ceil ((percentile / 100.0) * ((double) ctx->history_received));
338 return (ctx->history_by_value[index]);
339 } /* }}} double percentile_to_latency */
342 static double latency_to_ratio (ping_context_t *ctx, /* {{{ */
351 /* Not a single packet was received successfully. */
352 if (ctx->history_received == 0)
356 high = ctx->history_received - 1;
358 if (latency < ctx->history_by_value[low])
360 else if (latency >= ctx->history_by_value[high])
363 /* Do a binary search for the latency. This will work even when the
364 * exact latency is not in the array. If the latency is in the array
365 * multiple times, "low" will be set to the index of the last
366 * occurrence. The value at index "high" will be larger than the
367 * searched for latency (assured by the above "if" block. */
368 while ((high - low) > 1)
370 index = (high + low) / 2;
372 if (ctx->history_by_value[index] > latency)
378 assert (ctx->history_by_value[high] > latency);
379 assert (ctx->history_by_value[low] <= latency);
381 if (ctx->history_by_value[low] == latency)
386 return (((double) (index + 1)) / ((double) ctx->history_received));
387 } /* }}} double latency_to_ratio */
390 static double context_get_packet_loss (const ping_context_t *ctx) /* {{{ */
395 if (ctx->req_sent < 1)
398 return (100.0 * (ctx->req_sent - ctx->req_rcvd)
399 / ((double) ctx->req_sent));
400 } /* }}} double context_get_packet_loss */
402 static int ping_initialize_contexts (pingobj_t *ping) /* {{{ */
404 pingobj_iter_t *iter;
406 size_t history_size = 0;
412 for (iter = ping_iterator_get (ping);
414 iter = ping_iterator_next (iter))
416 ping_context_t *context;
420 context = ping_iterator_get_context(iter);
422 /* if this is a previously existing host, do not recreate it */
425 history_size = context->history_size;
426 context->index = index++;
430 context = context_create ();
431 context->index = index;
433 /* start new hosts at the same graph point as old hosts */
434 context->history_size = history_size;
435 context->history_index = history_size;
436 for (i = 0; i < history_size; i++)
437 context->history_by_time[i] = -1;
439 buffer_size = sizeof (context->host);
440 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
442 buffer_size = sizeof (context->addr);
443 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
445 ping_iterator_set_context (iter, (void *) context);
451 } /* }}} int ping_initialize_contexts */
453 static void usage_exit (const char *name, int status) /* {{{ */
455 fprintf (stderr, "Usage: %s [OPTIONS] "
456 "-f filename | host [host [host ...]]\n"
458 "\nAvailable options:\n"
459 " -4|-6 force the use of IPv4 or IPv6\n"
460 " -c count number of ICMP packets to send\n"
461 " -i interval interval with which to send ICMP packets\n"
462 " -w timeout time to wait for replies, in seconds\n"
463 " -t ttl time to live for each ICMP packet\n"
464 " -Q qos Quality of Service (QoS) of outgoing packets\n"
465 " Use \"-Q help\" for a list of valid options.\n"
466 " -I srcaddr source address\n"
467 " -D device outgoing interface name\n"
468 " -m mark mark to set on outgoing packets\n"
469 " -f filename read hosts from <filename>\n"
470 " -O filename write RTT measurements to <filename>\n"
472 " -u / -U force / disable UTF-8 output\n"
473 " -g graph graph type to draw\n"
475 " -P percent Report the n'th percentile of latency\n"
476 " -Z percent Exit with non-zero exit status if more than this percentage of\n"
477 " probes timed out. (default: never)\n"
479 "\noping "PACKAGE_VERSION", http://noping.cc/\n"
480 "by Florian octo Forster <ff@octo.it>\n"
481 "for contributions see `AUTHORS'\n",
484 } /* }}} void usage_exit */
486 __attribute__((noreturn))
487 static void usage_qos_exit (const char *arg, int status) /* {{{ */
490 fprintf (stderr, "Invalid QoS argument: \"%s\"\n\n", arg);
492 fprintf (stderr, "Valid QoS arguments (option \"-Q\") are:\n"
494 " Differentiated Services (IPv4 and IPv6, RFC 2474)\n"
496 " be Best Effort (BE, default PHB).\n"
497 " ef Expedited Forwarding (EF) PHB group (RFC 3246).\n"
498 " (low delay, low loss, low jitter)\n"
499 " va Voice Admit (VA) DSCP (RFC 5865).\n"
500 " (capacity-admitted traffic)\n"
501 " af[1-4][1-3] Assured Forwarding (AF) PHB group (RFC 2597).\n"
502 " For example: \"af12\" (class 1, precedence 2)\n"
503 " cs[0-7] Class Selector (CS) PHB group (RFC 2474).\n"
504 " For example: \"cs1\" (priority traffic)\n"
506 " Type of Service (IPv4, RFC 1349, obsolete)\n"
508 " lowdelay (%#04x) minimize delay\n"
509 " throughput (%#04x) maximize throughput\n"
510 " reliability (%#04x) maximize reliability\n"
511 " mincost (%#04x) minimize monetary cost\n"
513 " Specify manually\n"
515 " 0x00 - 0xff Hexadecimal numeric specification.\n"
516 " 0 - 255 Decimal numeric specification.\n"
518 (unsigned int) IPTOS_LOWDELAY,
519 (unsigned int) IPTOS_THROUGHPUT,
520 (unsigned int) IPTOS_RELIABILITY,
521 (unsigned int) IPTOS_MINCOST);
524 } /* }}} void usage_qos_exit */
526 static int set_opt_send_qos (const char *opt) /* {{{ */
531 if (strcasecmp ("help", opt) == 0)
532 usage_qos_exit (/* arg = */ NULL, /* status = */ EXIT_SUCCESS);
533 /* DiffServ (RFC 2474): */
534 /* - Best effort (BE) */
535 else if (strcasecmp ("be", opt) == 0)
537 /* - Expedited Forwarding (EF, RFC 3246) */
538 else if (strcasecmp ("ef", opt) == 0)
539 opt_send_qos = 0xB8; /* == 0x2E << 2 */
540 /* - Voice Admit (VA, RFC 5865) */
541 else if (strcasecmp ("va", opt) == 0)
542 opt_send_qos = 0xB0; /* == 0x2D << 2 */
543 /* - Assured Forwarding (AF, RFC 2597) */
544 else if ((strncasecmp ("af", opt, strlen ("af")) == 0)
545 && (strlen (opt) == 4))
551 /* There are four classes, AF1x, AF2x, AF3x, and AF4x. */
554 else if (opt[2] == '2')
556 else if (opt[2] == '3')
558 else if (opt[2] == '4')
561 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
563 /* In each class, there are three precedences, AFx1, AFx2, and AFx3 */
566 else if (opt[3] == '2')
568 else if (opt[3] == '3')
571 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
573 dscp = (8 * class) + (2 * prec);
574 /* The lower two bits are used for Explicit Congestion Notification (ECN) */
575 opt_send_qos = dscp << 2;
577 /* - Class Selector (CS) */
578 else if ((strncasecmp ("cs", opt, strlen ("cs")) == 0)
579 && (strlen (opt) == 3))
583 if ((opt[2] < '0') || (opt[2] > '7'))
584 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
586 /* Not exactly legal by the C standard, but I don't know of any
587 * system not supporting this hack. */
588 class = ((uint8_t) opt[2]) - ((uint8_t) '0');
589 opt_send_qos = class << 5;
591 /* Type of Service (RFC 1349) */
592 else if (strcasecmp ("lowdelay", opt) == 0)
593 opt_send_qos = IPTOS_LOWDELAY;
594 else if (strcasecmp ("throughput", opt) == 0)
595 opt_send_qos = IPTOS_THROUGHPUT;
596 else if (strcasecmp ("reliability", opt) == 0)
597 opt_send_qos = IPTOS_RELIABILITY;
598 else if (strcasecmp ("mincost", opt) == 0)
599 opt_send_qos = IPTOS_MINCOST;
608 value = strtoul (opt, &endptr, /* base = */ 0);
609 if ((errno != 0) || (endptr == opt)
610 || (endptr == NULL) || (*endptr != 0)
612 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
614 opt_send_qos = (uint8_t) value;
618 } /* }}} int set_opt_send_qos */
620 static char *format_qos (uint8_t qos, char *buffer, size_t buffer_size) /* {{{ */
632 case 0x00: dscp_str = "be"; break;
633 case 0x2e: dscp_str = "ef"; break;
634 case 0x2d: dscp_str = "va"; break;
635 case 0x0a: dscp_str = "af11"; break;
636 case 0x0c: dscp_str = "af12"; break;
637 case 0x0e: dscp_str = "af13"; break;
638 case 0x12: dscp_str = "af21"; break;
639 case 0x14: dscp_str = "af22"; break;
640 case 0x16: dscp_str = "af23"; break;
641 case 0x1a: dscp_str = "af31"; break;
642 case 0x1c: dscp_str = "af32"; break;
643 case 0x1e: dscp_str = "af33"; break;
644 case 0x22: dscp_str = "af41"; break;
645 case 0x24: dscp_str = "af42"; break;
646 case 0x26: dscp_str = "af43"; break;
647 case 0x08: dscp_str = "cs1"; break;
648 case 0x10: dscp_str = "cs2"; break;
649 case 0x18: dscp_str = "cs3"; break;
650 case 0x20: dscp_str = "cs4"; break;
651 case 0x28: dscp_str = "cs5"; break;
652 case 0x30: dscp_str = "cs6"; break;
653 case 0x38: dscp_str = "cs7"; break;
654 default: dscp_str = NULL;
659 case 0x01: ecn_str = ",ecn(1)"; break;
660 case 0x02: ecn_str = ",ecn(0)"; break;
661 case 0x03: ecn_str = ",ce"; break;
662 default: ecn_str = "";
665 if (dscp_str == NULL)
666 snprintf (buffer, buffer_size, "0x%02x%s", dscp, ecn_str);
668 snprintf (buffer, buffer_size, "%s%s", dscp_str, ecn_str);
669 buffer[buffer_size - 1] = 0;
672 } /* }}} char *format_qos */
674 static int read_options (int argc, char **argv) /* {{{ */
680 optchar = getopt (argc, argv, "46c:hi:I:t:Q:f:D:Z:O:P:m:w:b"
693 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
699 new_count = atoi (optarg);
702 opt_count = new_count;
704 if ((opt_percentile < 0.0) && (opt_count < 20))
705 opt_percentile = 100.0 * (opt_count - 1) / opt_count;
708 fprintf(stderr, "Ignoring invalid count: %s\n",
715 if (opt_filename != NULL)
717 opt_filename = strdup (optarg);
724 new_interval = atof (optarg);
725 if (new_interval < 0.001)
726 fprintf (stderr, "Ignoring invalid interval: %s\n",
729 opt_interval = new_interval;
736 double t = strtod (optarg, &endp);
737 if ((optarg[0] != 0) && (endp != NULL) && (*endp == 0))
740 fprintf (stderr, "Ignoring invalid timeout: %s\n",
747 if (opt_srcaddr != NULL)
749 opt_srcaddr = strdup (optarg);
764 new_send_ttl = atoi (optarg);
765 if ((new_send_ttl > 0) && (new_send_ttl < 256))
766 opt_send_ttl = new_send_ttl;
768 fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
774 set_opt_send_qos (optarg);
780 opt_outfile = strdup (optarg);
786 double new_percentile;
787 new_percentile = atof (optarg);
788 if (isnan (new_percentile)
789 || (new_percentile < 0.1)
790 || (new_percentile > 100.0))
791 fprintf (stderr, "Ignoring invalid percentile: %s\n",
794 opt_percentile = new_percentile;
800 if (strcasecmp ("none", optarg) == 0)
802 else if (strcasecmp ("prettyping", optarg) == 0)
804 else if (strcasecmp ("histogram", optarg) == 0)
806 else if (strcasecmp ("boxplot", optarg) == 0)
809 fprintf (stderr, "Unknown graph option: %s\n", optarg);
829 tmp = strtod (optarg, &endptr);
830 if ((errno != 0) || (endptr == NULL) || (*endptr != 0) || (tmp < 0.0) || (tmp > 100.0))
832 fprintf (stderr, "Ignoring invalid -Z argument: %s\n", optarg);
833 fprintf (stderr, "The \"-Z\" option requires a numeric argument between 0 and 100.\n");
836 opt_exit_status_threshold = tmp / 100.0;
842 usage_exit (argv[0], 0);
846 usage_exit (argv[0], 1);
850 if (opt_percentile <= 0.0)
851 opt_percentile = OPING_DEFAULT_PERCENTILE;
854 } /* }}} read_options */
856 static void time_normalize (struct timespec *ts) /* {{{ */
858 while (ts->tv_nsec < 0)
867 ts->tv_nsec += 1000000000;
870 while (ts->tv_nsec >= 1000000000)
873 ts->tv_nsec -= 1000000000;
875 } /* }}} void time_normalize */
877 static void time_calc (struct timespec *ts_dest, /* {{{ */
878 const struct timespec *ts_int,
879 const struct timeval *tv_begin,
880 const struct timeval *tv_end)
882 ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
883 ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
884 time_normalize (ts_dest);
886 /* Assure that `(begin + interval) > end'.
887 * This may seem overly complicated, but `tv_sec' is of type `time_t'
888 * which may be `unsigned. *sigh* */
889 if ((tv_end->tv_sec > ts_dest->tv_sec)
890 || ((tv_end->tv_sec == ts_dest->tv_sec)
891 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
894 ts_dest->tv_nsec = 0;
898 ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
899 ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
900 time_normalize (ts_dest);
901 } /* }}} void time_calc */
904 static _Bool has_utf8() /* {{{ */
906 # if HAVE_NCURSESW_NCURSES_H
909 /* Automatically determine */
910 if (strcasecmp ("UTF-8", nl_langinfo (CODESET)) == 0)
915 return ((_Bool) (opt_utf8 - 1));
919 } /* }}} _Bool has_utf8 */
921 static int update_graph_boxplot (ping_context_t *ctx) /* {{{ */
931 if (ctx->history_received == 0)
934 x_max = (size_t) getmaxx (ctx->window);
939 counters = calloc (x_max, sizeof (*counters));
940 ratios = calloc (x_max, sizeof (*ratios));
943 for (i = 0; i < ctx->history_received; i++)
945 double latency = ctx->history_by_value[i] / 1000.0;
946 size_t index = (size_t) (((double) x_max) * latency / opt_interval);
954 /* Sum and calc ratios */
955 ratios[0] = ((double) counters[0]) / ((double) ctx->history_received);
956 for (x = 1; x < x_max; x++)
958 counters[x] += counters[x - 1];
959 ratios[x] = ((double) counters[x]) / ((double) ctx->history_received);
962 for (x = 0; x < x_max; x++)
969 if (ratios[x] >= 0.5)
971 symbol = BOXPLOT_MEDIAN;
974 else if (ratios[x] > 0.25)
976 symbol = BOXPLOT_BOX;
979 else if (ratios[x] > 0.025)
980 symbol = BOXPLOT_WHISKER_BAR;
982 symbol = ' '; /* NOP */
986 if ((ratios[x - 1] < 0.5) && (ratios[x] >= 0.5))
988 symbol = BOXPLOT_MEDIAN;
991 else if (((ratios[x] >= 0.25) && (ratios[x] <= 0.75))
992 || ((ratios[x - 1] < 0.75) && (ratios[x] > 0.75)))
994 symbol = BOXPLOT_BOX;
997 else if ((ratios[x] < 0.5) && (ratios[x] >= 0.025))
999 if (ratios[x - 1] < 0.025)
1000 symbol = BOXPLOT_WHISKER_LEFT_END;
1002 symbol = BOXPLOT_WHISKER_BAR;
1004 else if ((ratios[x] > .5) && (ratios[x] < 0.975))
1006 symbol = BOXPLOT_WHISKER_BAR;
1008 else if ((ratios[x] >= 0.975) && (ratios[x - 1] < 0.975))
1009 symbol = BOXPLOT_WHISKER_RIGHT_END;
1013 wattron (ctx->window, A_REVERSE);
1014 mvwaddch (ctx->window, /* y = */ 3, /* x = */ (int) (x + 2), symbol);
1015 // mvwprintw (ctx->window, /* y = */ 3, /* x = */ (int) (x + 2), symbol);
1017 wattroff (ctx->window, A_REVERSE);
1023 } /* }}} int update_graph_boxplot */
1025 static int update_graph_prettyping (ping_context_t *ctx, /* {{{ */
1030 size_t history_offset;
1032 x_max = (size_t) getmaxx (ctx->window);
1037 /* Determine the first index in the history we need to draw
1040 if (((size_t) x_max) < ctx->history_size) /* window is smaller than history */
1042 if (ctx->history_index > x_max)
1043 history_offset = ctx->history_index - x_max;
1044 else /* wrap around */
1045 history_offset = ctx->history_index + ctx->history_size - x_max;
1047 else /* window is larger than history */
1049 if (ctx->history_index != ctx->history_size) /* no longer growing. */
1050 history_offset = ctx->history_index;
1055 for (x = 0; x < x_max; x++)
1060 int color = OPING_RED;
1061 char const *symbol = "!";
1064 if (x >= ctx->history_size)
1066 mvwaddch (ctx->window, /* y = */ 3, /* x = */ x + 2, ' ');
1070 index = (history_offset + x) % ctx->history_size;
1071 latency = ctx->history_by_time[index];
1081 size_t symbols_num = hist_symbols_acs_num;
1082 size_t colors_num = 1;
1084 size_t index_symbols;
1085 size_t index_colors;
1088 /* latency is in milliseconds, opt_interval is in seconds. */
1089 ratio = (latency * 0.001) / opt_interval;
1095 symbols_num = hist_symbols_utf8_num;
1097 if (has_colors () == TRUE)
1098 colors_num = hist_colors_num;
1100 intensity = (size_t) (ratio * ((double) (symbols_num * colors_num)));
1101 if (intensity >= (symbols_num * colors_num))
1102 intensity = (symbols_num * colors_num) - 1;
1104 index_symbols = intensity % symbols_num;
1105 assert (index_symbols < symbols_num);
1107 index_colors = intensity / symbols_num;
1108 assert (index_colors < colors_num);
1112 color = hist_colors_utf8[index_colors];
1113 symbol = hist_symbols_utf8[index_symbols];
1117 color = hist_colors_acs[index_colors];
1118 symbolc = hist_symbols_acs[index_symbols] | A_ALTCHARSET;
1121 else /* if (!(latency >= 0.0)) */
1122 wattron (ctx->window, A_BOLD);
1124 if (has_colors () == TRUE)
1125 wattron (ctx->window, COLOR_PAIR(color));
1128 mvwprintw (ctx->window, /* y = */ 3, /* x = */ x + 2, symbol);
1130 mvwaddch (ctx->window, /* y = */ 3, /* x = */ x + 2, symbolc);
1132 if (has_colors () == TRUE)
1133 wattroff (ctx->window, COLOR_PAIR(color));
1135 /* Use negation here to handle NaN correctly. */
1136 if (!(latency >= 0.0))
1137 wattroff (ctx->window, A_BOLD);
1141 } /* }}} int update_graph_prettyping */
1143 static int update_graph_histogram (ping_context_t *ctx) /* {{{ */
1146 uint32_t *accumulated;
1152 size_t symbols_num = hist_symbols_acs_num;
1154 clean_history (ctx);
1156 if (ctx->history_received == 0)
1160 symbols_num = hist_symbols_utf8_num;
1162 x_max = (size_t) getmaxx (ctx->window);
1167 counters = calloc (x_max, sizeof (*counters));
1168 accumulated = calloc (x_max, sizeof (*accumulated));
1172 for (i = 0; i < ctx->history_received; i++)
1174 double latency = ctx->history_by_value[i] / 1000.0;
1175 size_t index = (size_t) (((double) x_max) * latency / opt_interval);
1181 if (max < counters[index])
1182 max = counters[index];
1186 accumulated[0] = counters[0];
1187 for (x = 1; x < x_max; x++)
1188 accumulated[x] = counters[x] + accumulated[x - 1];
1190 /* Calculate ratios */
1191 for (x = 0; x < x_max; x++)
1193 double height = ((double) counters[x]) / ((double) max);
1194 double ratio_this = ((double) accumulated[x]) / ((double) ctx->history_received);
1195 double ratio_prev = 0.0;
1199 index = (size_t) (height * ((double) symbols_num));
1200 if (index >= symbols_num)
1201 index = symbols_num - 1;
1204 ratio_prev = ((double) accumulated[x - 1]) / ((double) ctx->history_received);
1206 if (has_colors () == TRUE)
1208 if ((ratio_this <= threshold_green)
1209 || ((ratio_prev < threshold_green)
1210 && (ratio_this > threshold_green)))
1211 color = OPING_GREEN;
1212 else if ((ratio_this <= threshold_yellow)
1213 || ((ratio_prev < threshold_yellow)
1214 && (ratio_this > threshold_yellow)))
1215 color = OPING_YELLOW;
1219 wattron (ctx->window, COLOR_PAIR(color));
1222 if (counters[x] == 0)
1223 mvwaddch (ctx->window, /* y = */ 3, /* x = */ x + 2, ' ');
1224 else if (has_utf8 ())
1225 mvwprintw (ctx->window, /* y = */ 3, /* x = */ x + 2,
1226 hist_symbols_utf8[index]);
1228 mvwaddch (ctx->window, /* y = */ 3, /* x = */ x + 2,
1229 hist_symbols_acs[index] | A_ALTCHARSET);
1231 if (has_colors () == TRUE)
1232 wattroff (ctx->window, COLOR_PAIR(color));
1238 } /* }}} int update_graph_histogram */
1240 static int update_stats_from_context (ping_context_t *ctx, pingobj_iter_t *iter) /* {{{ */
1242 double latency = -1.0;
1243 size_t buffer_len = sizeof (latency);
1245 ping_iterator_get_info (iter, PING_INFO_LATENCY,
1246 &latency, &buffer_len);
1248 if ((ctx == NULL) || (ctx->window == NULL))
1251 /* werase (ctx->window); */
1253 box (ctx->window, 0, 0);
1254 wattron (ctx->window, A_BOLD);
1255 mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
1257 wattroff (ctx->window, A_BOLD);
1258 wprintw (ctx->window, "ping statistics ");
1259 mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
1260 "%i packets transmitted, %i received, %.2f%% packet "
1261 "loss, time %.1fms",
1262 ctx->req_sent, ctx->req_rcvd,
1263 context_get_packet_loss (ctx),
1264 ctx->latency_total);
1265 if (ctx->req_rcvd != 0)
1272 min = percentile_to_latency (ctx, 0.0);
1273 median = percentile_to_latency (ctx, 50.0);
1274 max = percentile_to_latency (ctx, 100.0);
1275 percentile = percentile_to_latency (ctx, opt_percentile);
1277 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
1278 "RTT[ms]: min = %.0f, median = %.0f, p(%.0f) = %.0f, max = %.0f ",
1279 min, median, opt_percentile, percentile, max);
1282 if (opt_show_graph == 1)
1283 update_graph_prettyping (ctx, latency);
1284 else if (opt_show_graph == 2)
1285 update_graph_histogram (ctx);
1286 else if (opt_show_graph == 3)
1287 update_graph_boxplot (ctx);
1289 wrefresh (ctx->window);
1292 } /* }}} int update_stats_from_context */
1294 static int on_resize (pingobj_t *ping) /* {{{ */
1296 pingobj_iter_t *iter;
1299 int main_win_height;
1300 int box_height = (opt_show_graph == 0) ? 4 : 5;
1302 getmaxyx (stdscr, height, width);
1303 if ((height < 1) || (width < 1))
1306 main_win_height = height - (box_height * host_num);
1307 wresize (main_win, main_win_height, /* width = */ width);
1308 /* Allow scrolling */
1309 scrollok (main_win, TRUE);
1310 /* wsetscrreg (main_win, 0, main_win_height - 1); */
1311 /* Allow hardware accelerated scrolling. */
1312 idlok (main_win, TRUE);
1313 wrefresh (main_win);
1315 for (iter = ping_iterator_get (ping);
1317 iter = ping_iterator_next (iter))
1319 ping_context_t *context;
1321 context = ping_iterator_get_context (iter);
1322 if (context == NULL)
1325 if (context->window != NULL)
1327 werase (context->window);
1328 wrefresh (context->window);
1329 delwin (context->window);
1330 context->window = NULL;
1332 context->window = newwin (/* height = */ box_height,
1333 /* width = */ width,
1334 /* y = */ main_win_height + (box_height * context->index),
1341 static int check_resize (pingobj_t *ping) /* {{{ */
1343 int need_resize = 0;
1347 int key = wgetch (stdscr);
1350 else if (key == KEY_RESIZE)
1352 else if (key == 'g')
1354 if (opt_show_graph == 3)
1356 else if (opt_show_graph > 0)
1359 else if (key == 'a')
1361 char host[NI_MAXHOST];
1363 wprintw (main_win, "New Host: ");
1365 wgetnstr (main_win, host, sizeof (host));
1368 if (ping_host_add(ping, host) < 0)
1370 const char *errmsg = ping_get_error (ping);
1372 wprintw (main_win, "Adding host `%s' failed: %s\n", host, errmsg);
1376 /* FIXME - scroll main_win correctly so that old
1377 * data is still visible */
1379 host_num = ping_iterator_count(ping);
1380 ping_initialize_contexts(ping);
1386 return (on_resize (ping));
1389 } /* }}} int check_resize */
1391 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
1393 pingobj_iter_t *iter;
1396 int main_win_height;
1397 int box_height = (opt_show_graph == 0) ? 4 : 5;
1402 nodelay (stdscr, TRUE);
1404 getmaxyx (stdscr, height, width);
1405 if ((height < 1) || (width < 1))
1408 if (has_colors () == TRUE)
1411 use_default_colors ();
1412 init_pair (OPING_GREEN, COLOR_GREEN, /* default = */ -1);
1413 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ -1);
1414 init_pair (OPING_RED, COLOR_RED, /* default = */ -1);
1415 init_pair (OPING_GREEN_HIST, COLOR_GREEN, -1);
1416 init_pair (OPING_YELLOW_HIST, COLOR_YELLOW, COLOR_GREEN);
1417 init_pair (OPING_RED_HIST, COLOR_RED, COLOR_YELLOW);
1420 main_win_height = height - (box_height * host_num);
1421 main_win = newwin (/* height = */ main_win_height,
1422 /* width = */ width,
1423 /* y = */ 0, /* x = */ 0);
1424 /* Allow scrolling */
1425 scrollok (main_win, TRUE);
1426 /* wsetscrreg (main_win, 0, main_win_height - 1); */
1427 /* Allow hardware accelerated scrolling. */
1428 idlok (main_win, TRUE);
1429 wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
1430 wrefresh (main_win);
1432 for (iter = ping_iterator_get (ping);
1434 iter = ping_iterator_next (iter))
1436 ping_context_t *context;
1438 context = ping_iterator_get_context (iter);
1439 if (context == NULL)
1442 if (context->window != NULL)
1444 delwin (context->window);
1445 context->window = NULL;
1447 context->window = newwin (/* height = */ box_height,
1448 /* width = */ width,
1449 /* y = */ main_win_height + (box_height * context->index),
1454 /* Don't know what good this does exactly, but without this code
1455 * "check_resize" will be called right after startup and *somehow*
1456 * this leads to display errors. If we purge all initial characters
1457 * here, the problem goes away. "wgetch" is non-blocking due to
1458 * "nodelay" (see above). */
1459 while (wgetch (stdscr) != ERR)
1461 /* eat up characters */;
1465 } /* }}} int pre_loop_hook */
1467 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
1469 return (check_resize (ping));
1470 } /* }}} int pre_sleep_hook */
1472 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
1474 return (check_resize (ping));
1475 } /* }}} int pre_sleep_hook */
1476 #else /* if !USE_NCURSES */
1477 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
1479 pingobj_iter_t *iter;
1481 for (iter = ping_iterator_get (ping);
1483 iter = ping_iterator_next (iter))
1485 ping_context_t *ctx;
1488 ctx = ping_iterator_get_context (iter);
1493 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
1495 printf ("PING %s (%s) %zu bytes of data.\n",
1496 ctx->host, ctx->addr, buffer_size);
1500 } /* }}} int pre_loop_hook */
1502 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
1507 } /* }}} int pre_sleep_hook */
1509 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
1512 } /* }}} int post_sleep_hook */
1515 static void update_context (ping_context_t *ctx, double latency) /* {{{ */
1522 ctx->latency_total += latency;
1529 ctx->history_by_time[ctx->history_index] = latency;
1531 ctx->history_dirty = 1;
1533 /* Update index and size. */
1534 ctx->history_index = (ctx->history_index + 1) % HISTORY_SIZE_MAX;
1535 if (ctx->history_size < HISTORY_SIZE_MAX)
1536 ctx->history_size++;
1537 } /* }}} void update_context */
1539 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
1540 __attribute__((unused)) int index)
1543 unsigned int sequence;
1546 char recv_qos_str[16];
1549 ping_context_t *context;
1552 buffer_len = sizeof (latency);
1553 ping_iterator_get_info (iter, PING_INFO_LATENCY,
1554 &latency, &buffer_len);
1557 buffer_len = sizeof (sequence);
1558 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
1559 &sequence, &buffer_len);
1562 buffer_len = sizeof (recv_ttl);
1563 ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
1564 &recv_ttl, &buffer_len);
1567 buffer_len = sizeof (recv_qos);
1568 ping_iterator_get_info (iter, PING_INFO_RECV_QOS,
1569 &recv_qos, &buffer_len);
1572 ping_iterator_get_info (iter, PING_INFO_DATA,
1575 context = (ping_context_t *) ping_iterator_get_context (iter);
1578 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
1580 # define HOST_PRINTF(...) printf(__VA_ARGS__)
1583 update_context (context, latency);
1588 if (has_colors () == TRUE)
1591 int color = OPING_GREEN;
1593 ratio = latency_to_ratio (context, latency);
1594 if (ratio < threshold_green)
1595 color = OPING_GREEN;
1596 else if (ratio < threshold_yellow)
1597 color = OPING_YELLOW;
1601 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
1602 data_len, context->host, context->addr,
1604 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1605 if ((recv_qos != 0) || (opt_send_qos != 0))
1607 HOST_PRINTF ("qos=%s ",
1608 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1610 HOST_PRINTF ("time=");
1611 wattron (main_win, COLOR_PAIR(color));
1612 HOST_PRINTF ("%.2f", latency);
1613 wattroff (main_win, COLOR_PAIR(color));
1614 HOST_PRINTF (" ms\n");
1619 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
1621 context->host, context->addr,
1622 sequence, recv_ttl);
1623 if ((recv_qos != 0) || (opt_send_qos != 0))
1625 HOST_PRINTF ("qos=%s ",
1626 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1628 HOST_PRINTF ("time=%.2f ms\n", latency);
1640 else /* if (!(latency > 0.0)) */
1643 if (has_colors () == TRUE)
1645 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
1646 context->host, context->addr,
1648 wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
1649 HOST_PRINTF ("timeout");
1650 wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
1656 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
1657 context->host, context->addr,
1664 if (outfile != NULL)
1666 struct timeval tv = {0};
1667 if (gettimeofday (&tv, NULL) == 0)
1669 double t = ((double) tv.tv_sec) + (((double) tv.tv_usec) / 1000000.0);
1671 if ((sequence % 32) == 0)
1672 fprintf (outfile, "#time,host,latency[ms]\n");
1674 fprintf (outfile, "%.3f,\"%s\",%.2f\n", t, context->host, latency);
1679 update_stats_from_context (context, iter);
1680 wrefresh (main_win);
1682 } /* }}} void update_host_hook */
1684 /* Prints statistics for each host, cleans up the contexts and returns the
1685 * number of hosts which failed to return more than the fraction
1686 * opt_exit_status_threshold of pings. */
1687 static int post_loop_hook (pingobj_t *ping) /* {{{ */
1689 pingobj_iter_t *iter;
1690 int failure_count = 0;
1696 for (iter = ping_iterator_get (ping);
1698 iter = ping_iterator_next (iter))
1700 ping_context_t *context;
1702 context = ping_iterator_get_context (iter);
1704 printf ("\n--- %s ping statistics ---\n"
1705 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
1706 context->host, context->req_sent, context->req_rcvd,
1707 context_get_packet_loss (context),
1708 context->latency_total);
1711 double pct_failed = 1.0 - (((double) context->req_rcvd)
1712 / ((double) context->req_sent));
1713 if (pct_failed > opt_exit_status_threshold)
1717 if (context->req_rcvd != 0)
1724 min = percentile_to_latency (context, 0.0);
1725 median = percentile_to_latency (context, 50.0);
1726 max = percentile_to_latency (context, 100.0);
1727 percentile = percentile_to_latency (context, opt_percentile);
1729 printf ("RTT[ms]: min = %.0f, median = %.0f, p(%.0f) = %.0f, max = %.0f\n",
1730 min, median, opt_percentile, percentile, max);
1733 ping_iterator_set_context (iter, NULL);
1734 context_destroy (context);
1737 return (failure_count);
1738 } /* }}} int post_loop_hook */
1740 int main (int argc, char **argv) /* {{{ */
1743 pingobj_iter_t *iter;
1745 struct sigaction sigint_action;
1747 struct timeval tv_begin;
1748 struct timeval tv_end;
1749 struct timespec ts_wait;
1750 struct timespec ts_int;
1755 #if _POSIX_SAVED_IDS
1756 uid_t saved_set_uid;
1758 /* Save the old effective user id */
1759 saved_set_uid = geteuid ();
1760 /* Set the effective user ID to the real user ID without changing the
1761 * saved set-user ID */
1762 status = seteuid (getuid ());
1765 fprintf (stderr, "Temporarily dropping privileges "
1766 "failed: %s\n", strerror (errno));
1767 exit (EXIT_FAILURE);
1771 setlocale(LC_ALL, "");
1772 optind = read_options (argc, argv);
1774 #if !_POSIX_SAVED_IDS
1775 /* Cannot temporarily drop privileges -> reject every file but "-". */
1776 if ((opt_filename != NULL)
1777 && (strcmp ("-", opt_filename) != 0)
1778 && (getuid () != geteuid ()))
1780 fprintf (stderr, "Your real and effective user IDs don't "
1781 "match. Reading from a file (option '-f')\n"
1782 "is therefore too risky. You can still read "
1783 "from STDIN using '-f -' if you like.\n"
1785 exit (EXIT_FAILURE);
1789 if ((optind >= argc) && (opt_filename == NULL)) {
1790 usage_exit (argv[0], 1);
1793 if ((ping = ping_construct ()) == NULL)
1795 fprintf (stderr, "ping_construct failed\n");
1799 if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
1801 fprintf (stderr, "Setting TTL to %i failed: %s\n",
1802 opt_send_ttl, ping_get_error (ping));
1805 if (ping_setopt (ping, PING_OPT_QOS, &opt_send_qos) != 0)
1807 fprintf (stderr, "Setting TOS to %i failed: %s\n",
1808 opt_send_qos, ping_get_error (ping));
1815 temp_nsec = modf (opt_interval, &temp_sec);
1816 ts_int.tv_sec = (time_t) temp_sec;
1817 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
1819 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
1822 if (ping_setopt (ping, PING_OPT_TIMEOUT, (void*)(&opt_timeout)) != 0)
1824 fprintf (stderr, "Setting timeout failed: %s\n",
1825 ping_get_error (ping));
1828 if (opt_addrfamily != PING_DEF_AF)
1829 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
1831 if (opt_srcaddr != NULL)
1833 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
1835 fprintf (stderr, "Setting source address failed: %s\n",
1836 ping_get_error (ping));
1840 if (opt_device != NULL)
1842 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
1844 fprintf (stderr, "Setting device failed: %s\n",
1845 ping_get_error (ping));
1849 if (opt_mark != NULL)
1852 int mark = (int) strtol (opt_mark, &endp, /* base = */ 0);
1853 if ((opt_mark[0] != 0) && (endp != NULL) && (*endp == 0))
1855 if (ping_setopt(ping, PING_OPT_MARK, (void*)(&mark)) != 0)
1857 fprintf (stderr, "Setting mark failed: %s\n",
1858 ping_get_error (ping));
1863 fprintf(stderr, "Ignoring invalid mark: %s\n", optarg);
1867 if (opt_filename != NULL)
1873 if (strcmp (opt_filename, "-") == 0)
1875 infile = fdopen(0, "r");
1877 infile = fopen(opt_filename, "r");
1881 fprintf (stderr, "Opening %s failed: %s\n",
1882 (strcmp (opt_filename, "-") == 0)
1883 ? "STDIN" : opt_filename,
1888 #if _POSIX_SAVED_IDS
1889 /* Regain privileges */
1890 status = seteuid (saved_set_uid);
1893 fprintf (stderr, "Temporarily re-gaining privileges "
1894 "failed: %s\n", strerror (errno));
1895 exit (EXIT_FAILURE);
1899 while (fgets(line, sizeof(line), infile))
1901 /* Strip whitespace */
1902 if (sscanf(line, "%s", host) != 1)
1905 if ((host[0] == 0) || (host[0] == '#'))
1908 if (ping_host_add(ping, host) < 0)
1910 const char *errmsg = ping_get_error (ping);
1912 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
1921 #if _POSIX_SAVED_IDS
1922 /* Drop privileges */
1923 status = seteuid (getuid ());
1926 fprintf (stderr, "Temporarily dropping privileges "
1927 "failed: %s\n", strerror (errno));
1928 exit (EXIT_FAILURE);
1935 #if _POSIX_SAVED_IDS
1936 /* Regain privileges */
1937 status = seteuid (saved_set_uid);
1940 fprintf (stderr, "Temporarily re-gaining privileges "
1941 "failed: %s\n", strerror (errno));
1942 exit (EXIT_FAILURE);
1946 for (i = optind; i < argc; i++)
1948 if (ping_host_add (ping, argv[i]) < 0)
1950 const char *errmsg = ping_get_error (ping);
1952 fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
1961 /* Permanently drop root privileges if we're setuid-root. */
1962 status = setuid (getuid ());
1965 fprintf (stderr, "Dropping privileges failed: %s\n",
1967 exit (EXIT_FAILURE);
1971 exit (EXIT_FAILURE);
1973 #if _POSIX_SAVED_IDS
1974 saved_set_uid = (uid_t) -1;
1977 if (opt_outfile != NULL)
1979 outfile = fopen (opt_outfile, "a");
1980 if (outfile == NULL)
1982 fprintf (stderr, "opening \"%s\" failed: %s\n",
1983 opt_outfile, strerror (errno));
1984 exit (EXIT_FAILURE);
1988 ping_initialize_contexts (ping);
1993 memset (&sigint_action, '\0', sizeof (sigint_action));
1994 sigint_action.sa_handler = sigint_handler;
1995 if (sigaction (SIGINT, &sigint_action, NULL) < 0)
1997 perror ("sigaction");
2001 pre_loop_hook (ping);
2003 while (opt_count != 0)
2008 if (gettimeofday (&tv_begin, NULL) < 0)
2010 perror ("gettimeofday");
2014 status = ping_send (ping);
2015 if (status == -EINTR)
2019 else if (status < 0)
2021 fprintf (stderr, "ping_send failed: %s\n",
2022 ping_get_error (ping));
2027 for (iter = ping_iterator_get (ping);
2029 iter = ping_iterator_next (iter))
2031 update_host_hook (iter, index);
2035 pre_sleep_hook (ping);
2037 /* Don't sleep in the last iteration */
2041 if (gettimeofday (&tv_end, NULL) < 0)
2043 perror ("gettimeofday");
2047 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
2049 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
2050 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
2058 perror ("nanosleep");
2063 post_sleep_hook (ping);
2067 } /* while (opt_count != 0) */
2069 /* Returns the number of failed hosts according to -Z. */
2070 status = post_loop_hook (ping);
2072 ping_destroy (ping);
2074 if (outfile != NULL)
2081 exit (EXIT_SUCCESS);
2088 } /* }}} int main */
2090 /* vim: set fdm=marker : */