Code

src/oping.c: Switch graphs when pressing "g".
[liboping.git] / src / oping.c
1 /**
2  * Object oriented C module to send ICMP and ICMPv6 `echo's.
3  * Copyright (C) 2006-2014  Florian octo Forster <ff at octo.it>
4  *
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
8  * applicable.
9  *
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.
14  *
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
18  */
20 #if HAVE_CONFIG_H
21 # include <config.h>
22 #endif
24 #if STDC_HEADERS
25 # include <stdlib.h>
26 # include <stdio.h>
27 # include <string.h>
28 # include <stdint.h>
29 # include <inttypes.h>
30 # include <errno.h>
31 # include <assert.h>
32 #else
33 # error "You don't have the standard C99 header files installed"
34 #endif /* STDC_HEADERS */
36 #if HAVE_UNISTD_H
37 # include <unistd.h>
38 #endif
40 #if HAVE_MATH_H
41 # include <math.h>
42 #endif
44 #if TIME_WITH_SYS_TIME
45 # include <sys/time.h>
46 # include <time.h>
47 #else
48 # if HAVE_SYS_TIME_H
49 #  include <sys/time.h>
50 # else
51 #  include <time.h>
52 # endif
53 #endif
55 #if HAVE_SYS_SOCKET_H
56 # include <sys/socket.h>
57 #endif
58 #if HAVE_NETINET_IN_H
59 # include <netinet/in.h>
60 #endif
61 #if HAVE_NETINET_IP_H
62 # include <netinet/ip.h>
63 #endif
65 #if HAVE_NETDB_H
66 # include <netdb.h> /* NI_MAXHOST */
67 #endif
69 #if HAVE_SIGNAL_H
70 # include <signal.h>
71 #endif
73 #if HAVE_SYS_TYPES_H
74 #include <sys/types.h>
75 #endif
77 #include <locale.h>
78 #include <langinfo.h>
80 #if USE_NCURSES
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>
87 # elif HAVE_NCURSES_H
88 #  include <ncurses.h>
89 # endif
91 # define OPING_GREEN 1
92 # define OPING_YELLOW 2
93 # define OPING_RED 3
94 # define OPING_GREEN_HIST 4
95 # define OPING_YELLOW_HIST 5
96 # define OPING_RED_HIST 6
98 double const threshold_green = 0.8;
99 double const threshold_yellow = 0.95;
101 static char const * const hist_symbols_utf8[] = {
102         "▁", "▂", "▃", "▄", "▅", "▆", "▇", "█" };
103 static size_t const hist_symbols_utf8_num = sizeof (hist_symbols_utf8)
104         / sizeof (hist_symbols_utf8[0]);
106 /* scancodes for 6 levels of horizontal bars, ncurses-specific */
107 /* those are not the usual constants because those are not constant */
108 static int const hist_symbols_acs[] = {
109         115, /* ACS_S9 "⎽" */
110         114, /* ACS_S7 "⎼" */
111         113, /* ACS_S5 "─" */
112         112, /* ACS_S3 "⎻" */
113         111  /* ACS_S1 "⎺" */
114 };
115 static size_t const hist_symbols_acs_num = sizeof (hist_symbols_acs)
116         / sizeof (hist_symbols_acs[0]);
118 /* use different colors without a background for scancodes */
119 static int const hist_colors_utf8[] = {
120         OPING_GREEN_HIST, OPING_YELLOW_HIST, OPING_RED_HIST };
121 static int const hist_colors_acs[] = {
122         OPING_GREEN, OPING_YELLOW, OPING_RED };
123 /* assuming that both arrays are the same size */
124 static size_t const hist_colors_num = sizeof (hist_colors_utf8)
125         / sizeof (hist_colors_utf8[0]);
126 #endif
128 /* "─" */
129 #define BOXPLOT_WHISKER_BAR       (113 | A_ALTCHARSET)
130 /* "├" */
131 #define BOXPLOT_WHISKER_LEFT_END  (116 | A_ALTCHARSET)
132 /* "┤" */
133 #define BOXPLOT_WHISKER_RIGHT_END (117 | A_ALTCHARSET)
134 /* Inverted */
135 #define BOXPLOT_BOX               ' '
136 /* "│", inverted */
137 #define BOXPLOT_MEDIAN            (120 | A_ALTCHARSET)
139 #include "oping.h"
141 #ifndef _POSIX_SAVED_IDS
142 # define _POSIX_SAVED_IDS 0
143 #endif
145 #ifndef IPTOS_MINCOST
146 # define IPTOS_MINCOST 0x02
147 #endif
149 /* Remove GNU specific __attribute__ settings when using another compiler */
150 #if !__GNUC__
151 # define __attribute__(x) /**/
152 #endif
154 typedef struct ping_context
156         char host[NI_MAXHOST];
157         char addr[NI_MAXHOST];
159         int index;
160         int req_sent;
161         int req_rcvd;
163         double latency_total;
165 #ifndef HISTORY_SIZE_MAX
166 # define HISTORY_SIZE_MAX 900
167 #endif
168         /* The last n RTTs in the order they were sent. */
169         double history_by_time[HISTORY_SIZE_MAX];
170         /* Current size of the history. This is a value between 0 and
171          * HISTORY_SIZE_MAX. */
172         size_t history_size;
173         /* Index of the next RTT to be written to history_by_time. This wraps
174          * around to 0 once the histroty has grown to HISTORY_SIZE_MAX. */
175         size_t history_index;
176         /* Number received replies, i.e. non-NAN entries. */
177         size_t history_received;
178         /* The last n RTTs sorted by value. timed out packets are sorted to the
179          * back. */
180         double history_by_value[HISTORY_SIZE_MAX];
181         /* If set to true, history_by_value has to be re-calculated. */
182         _Bool history_dirty;
184 #if USE_NCURSES
185         WINDOW *window;
186 #endif
187 } ping_context_t;
189 static double  opt_interval   = 1.0;
190 static int     opt_addrfamily = PING_DEF_AF;
191 static char   *opt_srcaddr    = NULL;
192 static char   *opt_device     = NULL;
193 static char   *opt_filename   = NULL;
194 static int     opt_count      = -1;
195 static int     opt_send_ttl   = 64;
196 static uint8_t opt_send_qos   = 0;
197 #define OPING_DEFAULT_PERCENTILE 95.0
198 static double  opt_percentile = -1.0;
199 static double  opt_exit_status_threshold = 1.0;
200 #if USE_NCURSES
201 static int     opt_show_graph = 1;
202 static int     opt_utf8       = 0;
203 #endif
205 static int host_num = 0;
207 #if USE_NCURSES
208 static WINDOW *main_win = NULL;
209 #endif
211 static void sigint_handler (int signal) /* {{{ */
213         /* Make compiler happy */
214         signal = 0;
215         /* Exit the loop */
216         opt_count = 0;
217 } /* }}} void sigint_handler */
219 static ping_context_t *context_create (void) /* {{{ */
221         ping_context_t *ret;
223         if ((ret = malloc (sizeof (ping_context_t))) == NULL)
224                 return (NULL);
226         memset (ret, '\0', sizeof (ping_context_t));
228         ret->latency_total = 0.0;
230 #if USE_NCURSES
231         ret->window = NULL;
232 #endif
234         return (ret);
235 } /* }}} ping_context_t *context_create */
237 static void context_destroy (ping_context_t *context) /* {{{ */
239         if (context == NULL)
240                 return;
242 #if USE_NCURSES
243         if (context->window != NULL)
244         {
245                 delwin (context->window);
246                 context->window = NULL;
247         }
248 #endif
250         free (context);
251 } /* }}} void context_destroy */
253 static int compare_double (void const *arg0, void const *arg1) /* {{{ */
255         double dbl0 = *((double *) arg0);
256         double dbl1 = *((double *) arg1);
258         if (isnan (dbl0))
259         {
260                 if (isnan (dbl1))
261                         return 0;
262                 else
263                         return 1;
264         }
265         else if (isnan (dbl1))
266                 return -1;
267         else if (dbl0 < dbl1)
268                 return -1;
269         else if (dbl0 > dbl1)
270                 return 1;
271         else
272                 return 0;
273 } /* }}} int compare_double */
275 static void clean_history (ping_context_t *ctx) /* {{{ */
277         size_t i;
279         if (!ctx->history_dirty)
280                 return;
282         /* Copy all values from by_time to by_value. */
283         memcpy (ctx->history_by_value, ctx->history_by_time,
284                         sizeof (ctx->history_by_time));
285         /* Sort all RTTs. */
286         qsort (ctx->history_by_value, ctx->history_size, sizeof
287                         (ctx->history_by_value[0]), compare_double);
289         ctx->history_received = 0;
290         for (i = 0; i < ctx->history_size; i++)
291                 if (!isnan (ctx->history_by_value[i]))
292                         ctx->history_received++;
294         /* Mark as clean. */
295         ctx->history_dirty = 0;
296 } /* }}} void clean_history */
298 static double percentile_to_latency (ping_context_t *ctx, /* {{{ */
299                 double percentile)
301         size_t index;
303         clean_history (ctx);
305         if (ctx->history_received == 0)
306                 return NAN;
308         if (percentile <= 0.0)
309                 index = 0;
310         else if (percentile >= 100.0)
311                 index = ctx->history_received - 1;
312         else
313         {
314                 index = (size_t) ceil ((percentile / 100.0) * ((double) ctx->history_received));
315                 assert (index > 0);
316                 index--;
317         }
319         return (ctx->history_by_value[index]);
320 } /* }}} double percentile_to_latency */
322 #if USE_NCURSES
323 static double latency_to_percentile (ping_context_t *ctx, /* {{{ */
324                 double latency)
326         size_t low;
327         size_t high;
328         size_t index;
330         clean_history (ctx);
332         if (ctx->history_received == 0)
333                 return NAN;
335         low = 0;
336         high = ctx->history_received - 1;
338         if (latency < ctx->history_by_value[low])
339                 return 0.0;
340         else if (latency >= ctx->history_by_value[high])
341                 return 100.0;
343         while ((high - low) > 1)
344         {
345                 index = (high + low) / 2;
347                 if (ctx->history_by_value[index] > latency)
348                         high = index;
349                 else
350                         low = index;
351         }
353         assert (ctx->history_by_value[high] > latency);
354         assert (ctx->history_by_value[low] <= latency);
356         if (ctx->history_by_value[low] == latency)
357                 index = low;
358         else
359                 index = high;
361         return (100.0 * ((double) (index + 1)) / ((double) ctx->history_received));
362 } /* }}} double latency_to_percentile */
363 #endif
365 static double context_get_packet_loss (const ping_context_t *ctx) /* {{{ */
367         if (ctx == NULL)
368                 return (-1.0);
370         if (ctx->req_sent < 1)
371                 return (0.0);
373         return (100.0 * (ctx->req_sent - ctx->req_rcvd)
374                         / ((double) ctx->req_sent));
375 } /* }}} double context_get_packet_loss */
377 static int ping_initialize_contexts (pingobj_t *ping) /* {{{ */
379         pingobj_iter_t *iter;
380         int index;
382         if (ping == NULL)
383                 return (EINVAL);
385         index = 0;
386         for (iter = ping_iterator_get (ping);
387                         iter != NULL;
388                         iter = ping_iterator_next (iter))
389         {
390                 ping_context_t *context;
391                 size_t buffer_size;
393                 context = context_create ();
394                 context->index = index;
396                 buffer_size = sizeof (context->host);
397                 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
399                 buffer_size = sizeof (context->addr);
400                 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
402                 ping_iterator_set_context (iter, (void *) context);
404                 index++;
405         }
407         return (0);
408 } /* }}} int ping_initialize_contexts */
410 static void usage_exit (const char *name, int status) /* {{{ */
412         fprintf (stderr, "Usage: %s [OPTIONS] "
413                                 "-f filename | host [host [host ...]]\n"
415                         "\nAvailable options:\n"
416                         "  -4|-6        force the use of IPv4 or IPv6\n"
417                         "  -c count     number of ICMP packets to send\n"
418                         "  -i interval  interval with which to send ICMP packets\n"
419                         "  -t ttl       time to live for each ICMP packet\n"
420                         "  -Q qos       Quality of Service (QoS) of outgoing packets\n"
421                         "               Use \"-Q help\" for a list of valid options.\n"
422                         "  -I srcaddr   source address\n"
423                         "  -D device    outgoing interface name\n"
424                         "  -f filename  filename to read hosts from\n"
425 #if USE_NCURSES
426                         "  -u / -U      force / disable UTF-8 output\n"
427                         "  -g graph     graph type to draw\n"
428 #endif
429                         "  -P percent   Report the n'th percentile of latency\n"
430                         "  -Z percent   Exit with non-zero exit status if more than this percentage of\n"
431                         "               probes timed out. (default: never)\n"
433                         "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
434                         "by Florian octo Forster <octo@verplant.org>\n"
435                         "for contributions see `AUTHORS'\n",
436                         name);
437         exit (status);
438 } /* }}} void usage_exit */
440 __attribute__((noreturn))
441 static void usage_qos_exit (const char *arg, int status) /* {{{ */
443         if (arg != 0)
444                 fprintf (stderr, "Invalid QoS argument: \"%s\"\n\n", arg);
446         fprintf (stderr, "Valid QoS arguments (option \"-Q\") are:\n"
447                         "\n"
448                         "  Differentiated Services (IPv4 and IPv6, RFC 2474)\n"
449                         "\n"
450                         "    be                     Best Effort (BE, default PHB).\n"
451                         "    ef                     Expedited Forwarding (EF) PHB group (RFC 3246).\n"
452                         "                           (low delay, low loss, low jitter)\n"
453                         "    va                     Voice Admit (VA) DSCP (RFC 5865).\n"
454                         "                           (capacity-admitted traffic)\n"
455                         "    af[1-4][1-3]           Assured Forwarding (AF) PHB group (RFC 2597).\n"
456                         "                           For example: \"af12\" (class 1, precedence 2)\n"
457                         "    cs[0-7]                Class Selector (CS) PHB group (RFC 2474).\n"
458                         "                           For example: \"cs1\" (priority traffic)\n"
459                         "\n"
460                         "  Type of Service (IPv4, RFC 1349, obsolete)\n"
461                         "\n"
462                         "    lowdelay     (%#04x)    minimize delay\n"
463                         "    throughput   (%#04x)    maximize throughput\n"
464                         "    reliability  (%#04x)    maximize reliability\n"
465                         "    mincost      (%#04x)    minimize monetary cost\n"
466                         "\n"
467                         "  Specify manually\n"
468                         "\n"
469                         "    0x00 - 0xff            Hexadecimal numeric specification.\n"
470                         "       0 -  255            Decimal numeric specification.\n"
471                         "\n",
472                         (unsigned int) IPTOS_LOWDELAY,
473                         (unsigned int) IPTOS_THROUGHPUT,
474                         (unsigned int) IPTOS_RELIABILITY,
475                         (unsigned int) IPTOS_MINCOST);
477         exit (status);
478 } /* }}} void usage_qos_exit */
480 static int set_opt_send_qos (const char *opt) /* {{{ */
482         if (opt == NULL)
483                 return (EINVAL);
485         if (strcasecmp ("help", opt) == 0)
486                 usage_qos_exit (/* arg = */ NULL, /* status = */ EXIT_SUCCESS);
487         /* DiffServ (RFC 2474): */
488         /* - Best effort (BE) */
489         else if (strcasecmp ("be", opt) == 0)
490                 opt_send_qos = 0;
491         /* - Expedited Forwarding (EF, RFC 3246) */
492         else if (strcasecmp ("ef", opt) == 0)
493                 opt_send_qos = 0xB8; /* == 0x2E << 2 */
494         /* - Voice Admit (VA, RFC 5865) */
495         else if (strcasecmp ("va", opt) == 0)
496                 opt_send_qos = 0xB0; /* == 0x2D << 2 */
497         /* - Assured Forwarding (AF, RFC 2597) */
498         else if ((strncasecmp ("af", opt, strlen ("af")) == 0)
499                         && (strlen (opt) == 4))
500         {
501                 uint8_t dscp;
502                 uint8_t class = 0;
503                 uint8_t prec = 0;
505                 /* There are four classes, AF1x, AF2x, AF3x, and AF4x. */
506                 if (opt[2] == '1')
507                         class = 1;
508                 else if (opt[2] == '2')
509                         class = 2;
510                 else if (opt[2] == '3')
511                         class = 3;
512                 else if (opt[2] == '4')
513                         class = 4;
514                 else
515                         usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
517                 /* In each class, there are three precedences, AFx1, AFx2, and AFx3 */
518                 if (opt[3] == '1')
519                         prec = 1;
520                 else if (opt[3] == '2')
521                         prec = 2;
522                 else if (opt[3] == '3')
523                         prec = 3;
524                 else
525                         usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
527                 dscp = (8 * class) + (2 * prec);
528                 /* The lower two bits are used for Explicit Congestion Notification (ECN) */
529                 opt_send_qos = dscp << 2;
530         }
531         /* - Class Selector (CS) */
532         else if ((strncasecmp ("cs", opt, strlen ("cs")) == 0)
533                         && (strlen (opt) == 3))
534         {
535                 uint8_t class;
537                 if ((opt[2] < '0') || (opt[2] > '7'))
538                         usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
540                 /* Not exactly legal by the C standard, but I don't know of any
541                  * system not supporting this hack. */
542                 class = ((uint8_t) opt[2]) - ((uint8_t) '0');
543                 opt_send_qos = class << 5;
544         }
545         /* Type of Service (RFC 1349) */
546         else if (strcasecmp ("lowdelay", opt) == 0)
547                 opt_send_qos = IPTOS_LOWDELAY;
548         else if (strcasecmp ("throughput", opt) == 0)
549                 opt_send_qos = IPTOS_THROUGHPUT;
550         else if (strcasecmp ("reliability", opt) == 0)
551                 opt_send_qos = IPTOS_RELIABILITY;
552         else if (strcasecmp ("mincost", opt) == 0)
553                 opt_send_qos = IPTOS_MINCOST;
554         /* Numeric value */
555         else
556         {
557                 unsigned long value;
558                 char *endptr;
560                 errno = 0;
561                 endptr = NULL;
562                 value = strtoul (opt, &endptr, /* base = */ 0);
563                 if ((errno != 0) || (endptr == opt)
564                                 || (endptr == NULL) || (*endptr != 0)
565                                 || (value > 0xff))
566                         usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
567                 
568                 opt_send_qos = (uint8_t) value;
569         }
571         return (0);
572 } /* }}} int set_opt_send_qos */
574 static char *format_qos (uint8_t qos, char *buffer, size_t buffer_size) /* {{{ */
576         uint8_t dscp;
577         uint8_t ecn;
578         char *dscp_str;
579         char *ecn_str;
581         dscp = qos >> 2;
582         ecn = qos & 0x03;
584         switch (dscp)
585         {
586                 case 0x00: dscp_str = "be";  break;
587                 case 0x2e: dscp_str = "ef";  break;
588                 case 0x2d: dscp_str = "va";  break;
589                 case 0x0a: dscp_str = "af11"; break;
590                 case 0x0c: dscp_str = "af12"; break;
591                 case 0x0e: dscp_str = "af13"; break;
592                 case 0x12: dscp_str = "af21"; break;
593                 case 0x14: dscp_str = "af22"; break;
594                 case 0x16: dscp_str = "af23"; break;
595                 case 0x1a: dscp_str = "af31"; break;
596                 case 0x1c: dscp_str = "af32"; break;
597                 case 0x1e: dscp_str = "af33"; break;
598                 case 0x22: dscp_str = "af41"; break;
599                 case 0x24: dscp_str = "af42"; break;
600                 case 0x26: dscp_str = "af43"; break;
601                 case 0x08: dscp_str = "cs1";  break;
602                 case 0x10: dscp_str = "cs2";  break;
603                 case 0x18: dscp_str = "cs3";  break;
604                 case 0x20: dscp_str = "cs4";  break;
605                 case 0x28: dscp_str = "cs5";  break;
606                 case 0x30: dscp_str = "cs6";  break;
607                 case 0x38: dscp_str = "cs7";  break;
608                 default:   dscp_str = NULL;
609         }
611         switch (ecn)
612         {
613                 case 0x01: ecn_str = ",ecn(1)"; break;
614                 case 0x02: ecn_str = ",ecn(0)"; break;
615                 case 0x03: ecn_str = ",ce"; break;
616                 default:   ecn_str = "";
617         }
619         if (dscp_str == NULL)
620                 snprintf (buffer, buffer_size, "0x%02x%s", dscp, ecn_str);
621         else
622                 snprintf (buffer, buffer_size, "%s%s", dscp_str, ecn_str);
623         buffer[buffer_size - 1] = 0;
625         return (buffer);
626 } /* }}} char *format_qos */
628 static int read_options (int argc, char **argv) /* {{{ */
630         int optchar;
632         while (1)
633         {
634                 optchar = getopt (argc, argv, "46c:hi:I:t:Q:f:D:Z:P:"
635 #if USE_NCURSES
636                                 "uUg:"
637 #endif
638                                 );
640                 if (optchar == -1)
641                         break;
643                 switch (optchar)
644                 {
645                         case '4':
646                         case '6':
647                                 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
648                                 break;
650                         case 'c':
651                                 {
652                                         int new_count;
653                                         new_count = atoi (optarg);
654                                         if (new_count > 0)
655                                         {
656                                                 opt_count = new_count;
658                                                 if ((opt_percentile < 0.0) && (opt_count < 20))
659                                                         opt_percentile = 100.0 * (opt_count - 1) / opt_count;
660                                         }
661                                         else
662                                                 fprintf(stderr, "Ignoring invalid count: %s\n",
663                                                                 optarg);
664                                 }
665                                 break;
667                         case 'f':
668                                 {
669                                         if (opt_filename != NULL)
670                                                 free (opt_filename);
671                                         opt_filename = strdup (optarg);
672                                 }
673                                 break;
675                         case 'i':
676                                 {
677                                         double new_interval;
678                                         new_interval = atof (optarg);
679                                         if (new_interval < 0.001)
680                                                 fprintf (stderr, "Ignoring invalid interval: %s\n",
681                                                                 optarg);
682                                         else
683                                                 opt_interval = new_interval;
684                                 }
685                                 break;
687                         case 'I':
688                                 {
689                                         if (opt_srcaddr != NULL)
690                                                 free (opt_srcaddr);
691                                         opt_srcaddr = strdup (optarg);
692                                 }
693                                 break;
695                         case 'D':
696                                 opt_device = optarg;
697                                 break;
699                         case 't':
700                         {
701                                 int new_send_ttl;
702                                 new_send_ttl = atoi (optarg);
703                                 if ((new_send_ttl > 0) && (new_send_ttl < 256))
704                                         opt_send_ttl = new_send_ttl;
705                                 else
706                                         fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
707                                                         optarg);
708                                 break;
709                         }
711                         case 'Q':
712                                 set_opt_send_qos (optarg);
713                                 break;
715                         case 'P':
716                                 {
717                                         double new_percentile;
718                                         new_percentile = atof (optarg);
719                                         if (isnan (new_percentile)
720                                                         || (new_percentile < 0.1)
721                                                         || (new_percentile > 100.0))
722                                                 fprintf (stderr, "Ignoring invalid percentile: %s\n",
723                                                                 optarg);
724                                         else
725                                                 opt_percentile = new_percentile;
726                                 }
727                                 break;
729 #if USE_NCURSES
730                         case 'g':
731                                 if (strcasecmp ("none", optarg) == 0)
732                                         opt_show_graph = 0;
733                                 else if (strcasecmp ("prettyping", optarg) == 0)
734                                         opt_show_graph = 1;
735                                 else if (strcasecmp ("boxplot", optarg) == 0)
736                                         opt_show_graph = 2;
737                                 else if (strcasecmp ("histogram", optarg) == 0)
738                                         opt_show_graph = 3;
739                                 else
740                                         fprintf (stderr, "Unknown graph option: %s\n", optarg);
741                                 break;
743                         case 'u':
744                                 opt_utf8 = 2;
745                                 break;
746                         case 'U':
747                                 opt_utf8 = 1;
748                                 break;
749 #endif
751                         case 'Z':
752                         {
753                                 char *endptr = NULL;
754                                 double tmp;
756                                 errno = 0;
757                                 tmp = strtod (optarg, &endptr);
758                                 if ((errno != 0) || (endptr == NULL) || (*endptr != 0) || (tmp < 0.0) || (tmp > 100.0))
759                                 {
760                                         fprintf (stderr, "Ignoring invalid -Z argument: %s\n", optarg);
761                                         fprintf (stderr, "The \"-Z\" option requires a numeric argument between 0 and 100.\n");
762                                 }
763                                 else
764                                         opt_exit_status_threshold = tmp / 100.0;
766                                 break;
767                         }
769                         case 'h':
770                                 usage_exit (argv[0], 0);
771                                 break;
773                         default:
774                                 usage_exit (argv[0], 1);
775                 }
776         }
778         if (opt_percentile <= 0.0)
779                 opt_percentile = OPING_DEFAULT_PERCENTILE;
781         return (optind);
782 } /* }}} read_options */
784 static void time_normalize (struct timespec *ts) /* {{{ */
786         while (ts->tv_nsec < 0)
787         {
788                 if (ts->tv_sec == 0)
789                 {
790                         ts->tv_nsec = 0;
791                         return;
792                 }
794                 ts->tv_sec  -= 1;
795                 ts->tv_nsec += 1000000000;
796         }
798         while (ts->tv_nsec >= 1000000000)
799         {
800                 ts->tv_sec  += 1;
801                 ts->tv_nsec -= 1000000000;
802         }
803 } /* }}} void time_normalize */
805 static void time_calc (struct timespec *ts_dest, /* {{{ */
806                 const struct timespec *ts_int,
807                 const struct timeval  *tv_begin,
808                 const struct timeval  *tv_end)
810         ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
811         ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
812         time_normalize (ts_dest);
814         /* Assure that `(begin + interval) > end'.
815          * This may seem overly complicated, but `tv_sec' is of type `time_t'
816          * which may be `unsigned. *sigh* */
817         if ((tv_end->tv_sec > ts_dest->tv_sec)
818                         || ((tv_end->tv_sec == ts_dest->tv_sec)
819                                 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
820         {
821                 ts_dest->tv_sec  = 0;
822                 ts_dest->tv_nsec = 0;
823                 return;
824         }
826         ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
827         ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
828         time_normalize (ts_dest);
829 } /* }}} void time_calc */
831 #if USE_NCURSES
832 static _Bool has_utf8() /* {{{ */
834 # if HAVE_NCURSESW_NCURSES_H
835         if (!opt_utf8)
836         {
837                 /* Automatically determine */
838                 if (strcasecmp ("UTF-8", nl_langinfo (CODESET)) == 0)
839                         opt_utf8 = 2;
840                 else
841                         opt_utf8 = 1;
842         }
843         return ((_Bool) (opt_utf8 - 1));
844 # else
845         return (0);
846 # endif
847 } /* }}} _Bool has_utf8 */
849 static int update_graph_boxplot (ping_context_t *ctx) /* {{{ */
851         uint32_t *counters;
852         double *ratios;
853         size_t i;
854         size_t x_max;
855         size_t x;
857         clean_history (ctx);
859         if (ctx->history_received == 0)
860                 return (ENOENT);
862         x_max = (size_t) getmaxx (ctx->window);
863         if (x_max <= 8)
864                 return (EINVAL);
865         x_max -= 4;
867         counters = calloc (x_max, sizeof (*counters));
868         ratios = calloc (x_max, sizeof (*ratios));
870         /* Bucketize */
871         for (i = 0; i < ctx->history_received; i++)
872         {
873                 double latency = ctx->history_by_value[i] / 1000.0;
874                 size_t index = (size_t) (((double) x_max) * latency / opt_interval);
876                 if (index >= x_max)
877                         index = x_max - 1;
879                 counters[index]++;
880         }
882         /* Sum and calc ratios */
883         ratios[0] = ((double) counters[0]) / ((double) ctx->history_received);
884         for (x = 1; x < x_max; x++)
885         {
886                 counters[x] += counters[x - 1];
887                 ratios[x] = ((double) counters[x]) / ((double) ctx->history_received);
888         }
890         for (x = 0; x < x_max; x++)
891         {
892                 int symbol = ' ';
893                 _Bool reverse = 0;
895                 if (x == 0)
896                 {
897                         if (ratios[x] >= 0.5)
898                         {
899                                 symbol = BOXPLOT_MEDIAN;
900                                 reverse = 1;
901                         }
902                         else if (ratios[x] > 0.25)
903                         {
904                                 symbol = BOXPLOT_BOX;
905                                 reverse = 1;
906                         }
907                         else if (ratios[x] > 0.025)
908                                 symbol = BOXPLOT_WHISKER_BAR;
909                         else
910                                 symbol = ' '; /* NOP */
911                 }
912                 else /* (x != 0) */
913                 {
914                         if ((ratios[x - 1] < 0.5) && (ratios[x] >= 0.5))
915                         {
916                                 symbol = BOXPLOT_MEDIAN;
917                                 reverse = 1;
918                         }
919                         else if (((ratios[x] >= 0.25) && (ratios[x] <= 0.75))
920                                         || ((ratios[x - 1] < 0.75) && (ratios[x] > 0.75)))
921                         {
922                                 symbol = BOXPLOT_BOX;
923                                 reverse = 1;
924                         }
925                         else if ((ratios[x] < 0.5) && (ratios[x] >= 0.025))
926                         {
927                                 if (ratios[x - 1] < 0.025)
928                                         symbol = BOXPLOT_WHISKER_LEFT_END;
929                                 else
930                                         symbol = BOXPLOT_WHISKER_BAR;
931                         }
932                         else if ((ratios[x] > .5) && (ratios[x] < 0.975))
933                         {
934                                 symbol = BOXPLOT_WHISKER_BAR;
935                         }
936                         else if ((ratios[x] >= 0.975) && (ratios[x - 1] < 0.975))
937                                 symbol = BOXPLOT_WHISKER_RIGHT_END;
938                 }
940                 if (reverse)
941                         wattron (ctx->window, A_REVERSE);
942                 mvwaddch (ctx->window, /* y = */ 3, /* x = */ (int) (x + 2), symbol);
943                 // mvwprintw (ctx->window, /* y = */ 3, /* x = */ (int) (x + 2), symbol);
944                 if (reverse)
945                         wattroff (ctx->window, A_REVERSE);
946         }
948         free (counters);
949         free (ratios);
950         return (0);
951 } /* }}} int update_graph_boxplot */
953 static int update_graph_prettyping (ping_context_t *ctx, /* {{{ */
954                 double latency, unsigned int sequence)
956         size_t x;
957         size_t x_max;
958         size_t history_offset;
960         x_max = (size_t) getmaxx (ctx->window);
961         if (x_max <= 4)
962                 return (EINVAL);
963         x_max -= 4;
965         history_offset = 0;
966         if (((size_t) x_max) < ctx->history_size)
967         {
968                 if (ctx->history_index > x_max)
969                         history_offset = ctx->history_index - x_max;
970                 else /* wrap around */
971                         history_offset = ctx->history_index + x_max - ctx->history_size;
972         }
974         for (x = 0; x < x_max; x++)
975         {
976                 size_t index;
977                 double latency;
979                 int color = OPING_RED;
980                 char const *symbol = "!";
981                 int symbolc = '!';
983                 if (x >= ctx->history_size)
984                 {
985                         mvwaddch (ctx->window, /* y = */ 3, /* x = */ x + 2, ' ');
986                         continue;
987                 }
989                 index = (history_offset + x) % ctx->history_size;
990                 latency = ctx->history_by_time[index];
992                 if (latency >= 0.0)
993                 {
994                         double ratio;
996                         size_t symbols_num = hist_symbols_acs_num;
997                         size_t colors_num = 1;
999                         size_t index_symbols;
1000                         size_t index_colors;
1001                         size_t intensity;
1003                         /* latency is in milliseconds, opt_interval is in seconds. */
1004                         ratio = (latency * 0.001) / opt_interval;
1005                         if (ratio > 1) {
1006                                 ratio = 1.0;
1007                         }
1009                         if (has_utf8 ())
1010                                 symbols_num = hist_symbols_utf8_num;
1012                         if (has_colors () == TRUE)
1013                                 colors_num = hist_colors_num;
1015                         intensity = (size_t) (ratio * ((double) (symbols_num * colors_num)));
1016                         if (intensity >= (symbols_num * colors_num))
1017                                 intensity = (symbols_num * colors_num) - 1;
1019                         index_symbols = intensity % symbols_num;
1020                         assert (index_symbols < symbols_num);
1022                         index_colors = intensity / symbols_num;
1023                         assert (index_colors < colors_num);
1025                         if (has_utf8())
1026                         {
1027                                 color = hist_colors_utf8[index_colors];
1028                                 symbol = hist_symbols_utf8[index_symbols];
1029                         }
1030                         else
1031                         {
1032                                 color = hist_colors_acs[index_colors];
1033                                 symbolc = hist_symbols_acs[index_symbols] | A_ALTCHARSET;
1034                         }
1035                 }
1036                 else /* if (!(latency >= 0.0)) */
1037                         wattron (ctx->window, A_BOLD);
1039                 if (has_colors () == TRUE)
1040                         wattron (ctx->window, COLOR_PAIR(color));
1042                 if (has_utf8())
1043                         mvwprintw (ctx->window, /* y = */ 3, /* x = */ x + 2, symbol);
1044                 else
1045                         mvwaddch (ctx->window, /* y = */ 3, /* x = */ x + 2, symbolc);
1047                 if (has_colors () == TRUE)
1048                         wattroff (ctx->window, COLOR_PAIR(color));
1050                 /* Use negation here to handle NaN correctly. */
1051                 if (!(latency >= 0.0))
1052                         wattroff (ctx->window, A_BOLD);
1053         } /* for (x) */
1055         return (0);
1056 } /* }}} int update_graph_prettyping */
1058 static int update_graph_histogram (ping_context_t *ctx) /* {{{ */
1060         uint32_t *counters;
1061         uint32_t *accumulated;
1062         uint32_t max;
1063         size_t i;
1064         size_t x_max;
1065         size_t x;
1067         size_t symbols_num = hist_symbols_acs_num;
1069         clean_history (ctx);
1071         if (ctx->history_received == 0)
1072                 return (ENOENT);
1074         if (has_utf8 ())
1075                 symbols_num = hist_symbols_utf8_num;
1077         x_max = (size_t) getmaxx (ctx->window);
1078         if (x_max <= 4)
1079                 return (EINVAL);
1080         x_max -= 4;
1082         counters = calloc (x_max, sizeof (*counters));
1083         accumulated = calloc (x_max, sizeof (*accumulated));
1085         /* Bucketize */
1086         max = 0;
1087         for (i = 0; i < ctx->history_received; i++)
1088         {
1089                 double latency = ctx->history_by_value[i] / 1000.0;
1090                 size_t index = (size_t) (((double) x_max) * latency / opt_interval);
1092                 if (index >= x_max)
1093                         index = x_max - 1;
1095                 counters[index]++;
1096                 if (max < counters[index])
1097                         max = counters[index];
1098         }
1100         /* Sum */
1101         accumulated[0] = counters[0];
1102         for (x = 1; x < x_max; x++)
1103                 accumulated[x] = counters[x] + accumulated[x - 1];
1105         /* Calculate ratios */
1106         for (x = 0; x < x_max; x++)
1107         {
1108                 double height = ((double) counters[x]) / ((double) max);
1109                 double ratio_this = ((double) accumulated[x]) / ((double) ctx->history_received);
1110                 double ratio_prev = 0.0;
1111                 size_t index;
1112                 int color = 0;
1114                 index = (size_t) (height * ((double) symbols_num));
1115                 if (index >= symbols_num)
1116                         index = symbols_num - 1;
1118                 if (x > 0)
1119                         ratio_prev = ((double) accumulated[x - 1]) / ((double) ctx->history_received);
1121                 if (has_colors () == TRUE)
1122                 {
1123                         if ((ratio_this <= threshold_green)
1124                                         || ((ratio_prev < threshold_green)
1125                                                 && (ratio_this > threshold_green)))
1126                                 color = OPING_GREEN;
1127                         else if ((ratio_this <= threshold_yellow)
1128                                         || ((ratio_prev < threshold_yellow)
1129                                                 && (ratio_this > threshold_yellow)))
1130                                 color = OPING_YELLOW;
1131                         else
1132                                 color = OPING_RED;
1134                         wattron (ctx->window, COLOR_PAIR(color));
1135                 }
1137                 if (counters[x] == 0)
1138                         mvwaddch (ctx->window, /* y = */ 3, /* x = */ x + 2, ' ');
1139                 else if (has_utf8 ())
1140                         mvwprintw (ctx->window, /* y = */ 3, /* x = */ x + 2,
1141                                         hist_symbols_utf8[index]);
1142                 else
1143                         mvwaddch (ctx->window, /* y = */ 3, /* x = */ x + 2,
1144                                         hist_symbols_acs[index] | A_ALTCHARSET);
1146                 if (has_colors () == TRUE)
1147                         wattroff (ctx->window, COLOR_PAIR(color));
1149         }
1151         free (accumulated);
1152         return (0);
1153 } /* }}} int update_graph_histogram */
1155 static int update_stats_from_context (ping_context_t *ctx, pingobj_iter_t *iter) /* {{{ */
1157         double latency = -1.0;
1158         size_t buffer_len = sizeof (latency);
1160         ping_iterator_get_info (iter, PING_INFO_LATENCY,
1161                         &latency, &buffer_len);
1163         unsigned int sequence = 0;
1164         buffer_len = sizeof (sequence);
1165         ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
1166                         &sequence, &buffer_len);
1169         if ((ctx == NULL) || (ctx->window == NULL))
1170                 return (EINVAL);
1172         /* werase (ctx->window); */
1174         box (ctx->window, 0, 0);
1175         wattron (ctx->window, A_BOLD);
1176         mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
1177                         " %s ", ctx->host);
1178         wattroff (ctx->window, A_BOLD);
1179         wprintw (ctx->window, "ping statistics ");
1180         mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
1181                         "%i packets transmitted, %i received, %.2f%% packet "
1182                         "loss, time %.1fms",
1183                         ctx->req_sent, ctx->req_rcvd,
1184                         context_get_packet_loss (ctx),
1185                         ctx->latency_total);
1186         if (ctx->req_rcvd != 0)
1187         {
1188                 double min;
1189                 double median;
1190                 double max;
1191                 double percentile;
1193                 min = percentile_to_latency (ctx, 0.0);
1194                 median = percentile_to_latency (ctx, 50.0);
1195                 max = percentile_to_latency (ctx, 100.0);
1196                 percentile = percentile_to_latency (ctx, opt_percentile);
1198                 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
1199                                 "RTT[ms]: min = %.0f, median = %.0f, p(%.0f) = %.0f, max = %.0f",
1200                                 min, median, opt_percentile, percentile, max);
1201         }
1203         if (opt_show_graph == 1)
1204                 update_graph_prettyping (ctx, latency, sequence);
1205         else if (opt_show_graph == 2)
1206                 update_graph_boxplot (ctx);
1207         else if (opt_show_graph == 3)
1208                 update_graph_histogram (ctx);
1210         wrefresh (ctx->window);
1212         return (0);
1213 } /* }}} int update_stats_from_context */
1215 static int on_resize (pingobj_t *ping) /* {{{ */
1217         pingobj_iter_t *iter;
1218         int width = 0;
1219         int height = 0;
1220         int main_win_height;
1221         int box_height = (opt_show_graph == 0) ? 4 : 5;
1223         getmaxyx (stdscr, height, width);
1224         if ((height < 1) || (width < 1))
1225                 return (EINVAL);
1227         main_win_height = height - (box_height * host_num);
1228         wresize (main_win, main_win_height, /* width = */ width);
1229         /* Allow scrolling */
1230         scrollok (main_win, TRUE);
1231         /* wsetscrreg (main_win, 0, main_win_height - 1); */
1232         /* Allow hardware accelerated scrolling. */
1233         idlok (main_win, TRUE);
1234         wrefresh (main_win);
1236         for (iter = ping_iterator_get (ping);
1237                         iter != NULL;
1238                         iter = ping_iterator_next (iter))
1239         {
1240                 ping_context_t *context;
1242                 context = ping_iterator_get_context (iter);
1243                 if (context == NULL)
1244                         continue;
1246                 if (context->window != NULL)
1247                 {
1248                         delwin (context->window);
1249                         context->window = NULL;
1250                 }
1251                 context->window = newwin (/* height = */ box_height,
1252                                 /* width = */ width,
1253                                 /* y = */ main_win_height + (box_height * context->index),
1254                                 /* x = */ 0);
1255         }
1257         return (0);
1258 } /* }}} */
1260 static int check_resize (pingobj_t *ping) /* {{{ */
1262         int need_resize = 0;
1264         while (42)
1265         {
1266                 int key = wgetch (stdscr);
1267                 if (key == ERR)
1268                         break;
1269                 else if (key == KEY_RESIZE)
1270                         need_resize = 1;
1271                 else if (key == 'g')
1272                 {
1273                         if (opt_show_graph == 3)
1274                                 opt_show_graph = 1;
1275                         else if (opt_show_graph > 0)
1276                                 opt_show_graph++;
1277                 }
1278         }
1280         if (need_resize)
1281                 return (on_resize (ping));
1282         else
1283                 return (0);
1284 } /* }}} int check_resize */
1286 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
1288         pingobj_iter_t *iter;
1289         int width = 0;
1290         int height = 0;
1291         int main_win_height;
1292         int box_height = (opt_show_graph == 0) ? 4 : 5;
1294         initscr ();
1295         cbreak ();
1296         noecho ();
1297         nodelay (stdscr, TRUE);
1299         getmaxyx (stdscr, height, width);
1300         if ((height < 1) || (width < 1))
1301                 return (EINVAL);
1303         if (has_colors () == TRUE)
1304         {
1305                 start_color ();
1306                 init_pair (OPING_GREEN,  COLOR_GREEN,  /* default = */ 0);
1307                 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
1308                 init_pair (OPING_RED,    COLOR_RED,    /* default = */ 0);
1309                 init_pair (OPING_GREEN_HIST,  COLOR_GREEN,  COLOR_BLACK);
1310                 init_pair (OPING_YELLOW_HIST, COLOR_YELLOW, COLOR_GREEN);
1311                 init_pair (OPING_RED_HIST,    COLOR_RED,    COLOR_YELLOW);
1312         }
1314         main_win_height = height - (box_height * host_num);
1315         main_win = newwin (/* height = */ main_win_height,
1316                         /* width = */ width,
1317                         /* y = */ 0, /* x = */ 0);
1318         /* Allow scrolling */
1319         scrollok (main_win, TRUE);
1320         /* wsetscrreg (main_win, 0, main_win_height - 1); */
1321         /* Allow hardware accelerated scrolling. */
1322         idlok (main_win, TRUE);
1323         wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
1324         wrefresh (main_win);
1326         for (iter = ping_iterator_get (ping);
1327                         iter != NULL;
1328                         iter = ping_iterator_next (iter))
1329         {
1330                 ping_context_t *context;
1332                 context = ping_iterator_get_context (iter);
1333                 if (context == NULL)
1334                         continue;
1336                 if (context->window != NULL)
1337                 {
1338                         delwin (context->window);
1339                         context->window = NULL;
1340                 }
1341                 context->window = newwin (/* height = */ box_height,
1342                                 /* width = */ width,
1343                                 /* y = */ main_win_height + (box_height * context->index),
1344                                 /* x = */ 0);
1345         }
1348         /* Don't know what good this does exactly, but without this code
1349          * "check_resize" will be called right after startup and *somehow*
1350          * this leads to display errors. If we purge all initial characters
1351          * here, the problem goes away. "wgetch" is non-blocking due to
1352          * "nodelay" (see above). */
1353         while (wgetch (stdscr) != ERR)
1354         {
1355                 /* eat up characters */;
1356         }
1358         return (0);
1359 } /* }}} int pre_loop_hook */
1361 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
1363         return (check_resize (ping));
1364 } /* }}} int pre_sleep_hook */
1366 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
1368         return (check_resize (ping));
1369 } /* }}} int pre_sleep_hook */
1370 #else /* if !USE_NCURSES */
1371 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
1373         pingobj_iter_t *iter;
1375         for (iter = ping_iterator_get (ping);
1376                         iter != NULL;
1377                         iter = ping_iterator_next (iter))
1378         {
1379                 ping_context_t *ctx;
1380                 size_t buffer_size;
1382                 ctx = ping_iterator_get_context (iter);
1383                 if (ctx == NULL)
1384                         continue;
1386                 buffer_size = 0;
1387                 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
1389                 printf ("PING %s (%s) %zu bytes of data.\n",
1390                                 ctx->host, ctx->addr, buffer_size);
1391         }
1393         return (0);
1394 } /* }}} int pre_loop_hook */
1396 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
1398         fflush (stdout);
1400         return (0);
1401 } /* }}} int pre_sleep_hook */
1403 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
1405         return (0);
1406 } /* }}} int post_sleep_hook */
1407 #endif
1409 static void update_context (ping_context_t *ctx, double latency) /* {{{ */
1411         ctx->req_sent++;
1413         if (latency > 0.0)
1414         {
1415                 ctx->req_rcvd++;
1416                 ctx->latency_total += latency;
1417         }
1418         else
1419         {
1420                 latency = NAN;
1421         }
1423         ctx->history_by_time[ctx->history_index] = latency;
1425         ctx->history_dirty = 1;
1427         /* Update index and size. */
1428         ctx->history_index = (ctx->history_index + 1) % HISTORY_SIZE_MAX;
1429         if (ctx->history_size < HISTORY_SIZE_MAX)
1430                 ctx->history_size++;
1431 } /* }}} void update_context */
1433 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
1434                 __attribute__((unused)) int index)
1436         double          latency;
1437         unsigned int    sequence;
1438         int             recv_ttl;
1439         uint8_t         recv_qos;
1440         char            recv_qos_str[16];
1441         size_t          buffer_len;
1442         size_t          data_len;
1443         ping_context_t *context;
1445         latency = -1.0;
1446         buffer_len = sizeof (latency);
1447         ping_iterator_get_info (iter, PING_INFO_LATENCY,
1448                         &latency, &buffer_len);
1450         sequence = 0;
1451         buffer_len = sizeof (sequence);
1452         ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
1453                         &sequence, &buffer_len);
1455         recv_ttl = -1;
1456         buffer_len = sizeof (recv_ttl);
1457         ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
1458                         &recv_ttl, &buffer_len);
1460         recv_qos = 0;
1461         buffer_len = sizeof (recv_qos);
1462         ping_iterator_get_info (iter, PING_INFO_RECV_QOS,
1463                         &recv_qos, &buffer_len);
1465         data_len = 0;
1466         ping_iterator_get_info (iter, PING_INFO_DATA,
1467                         NULL, &data_len);
1469         context = (ping_context_t *) ping_iterator_get_context (iter);
1471 #if USE_NCURSES
1472 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
1473 #else
1474 # define HOST_PRINTF(...) printf(__VA_ARGS__)
1475 #endif
1477         update_context (context, latency);
1479         if (latency > 0.0)
1480         {
1481 #if USE_NCURSES
1482                 if (has_colors () == TRUE)
1483                 {
1484                         double percentile;
1485                         int color = OPING_GREEN;
1487                         percentile = latency_to_percentile (context, latency);
1488                         if (percentile < (100.0 * threshold_green))
1489                                 color = OPING_GREEN;
1490                         else if (percentile < (100.0 * threshold_yellow))
1491                                 color = OPING_YELLOW;
1492                         else
1493                                 color = OPING_RED;
1495 #if 0
1496                         if ((ratio_this <= threshold_green)
1497                                         || ((ratio_prev < threshold_green)
1498                                                 && (ratio_this > threshold_green)))
1499                                 color = OPING_GREEN;
1500                         else if ((ratio_this <= threshold_yellow)
1501                                         || ((ratio_prev < threshold_yellow)
1502                                                 && (ratio_this > threshold_yellow)))
1503                                 color = OPING_YELLOW;
1504                         else
1505                                 color = OPING_RED;
1506 #endif
1508                         HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
1509                                         data_len, context->host, context->addr,
1510                                         sequence, recv_ttl,
1511                                         format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1512                         if ((recv_qos != 0) || (opt_send_qos != 0))
1513                         {
1514                                 HOST_PRINTF ("qos=%s ",
1515                                                 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1516                         }
1517                         HOST_PRINTF ("time=");
1518                         wattron (main_win, COLOR_PAIR(color));
1519                         HOST_PRINTF ("%.2f", latency);
1520                         wattroff (main_win, COLOR_PAIR(color));
1521                         HOST_PRINTF (" ms\n");
1522                 }
1523                 else
1524                 {
1525 #endif
1526                 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
1527                                 data_len,
1528                                 context->host, context->addr,
1529                                 sequence, recv_ttl);
1530                 if ((recv_qos != 0) || (opt_send_qos != 0))
1531                 {
1532                         HOST_PRINTF ("qos=%s ",
1533                                         format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1534                 }
1535                 HOST_PRINTF ("time=%.2f ms\n", latency);
1536 #if USE_NCURSES
1537                 }
1538 #endif
1539         }
1540         else /* if (!(latency > 0.0)) */
1541         {
1542 #if USE_NCURSES
1543                 if (has_colors () == TRUE)
1544                 {
1545                         HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
1546                                         context->host, context->addr,
1547                                         sequence);
1548                         wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
1549                         HOST_PRINTF ("timeout");
1550                         wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
1551                         HOST_PRINTF ("\n");
1552                 }
1553                 else
1554                 {
1555 #endif
1556                 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
1557                                 context->host, context->addr,
1558                                 sequence);
1559 #if USE_NCURSES
1560                 }
1561 #endif
1562         }
1564 #if USE_NCURSES
1565         update_stats_from_context (context, iter);
1566         wrefresh (main_win);
1567 #endif
1568 } /* }}} void update_host_hook */
1570 /* Prints statistics for each host, cleans up the contexts and returns the
1571  * number of hosts which failed to return more than the fraction
1572  * opt_exit_status_threshold of pings. */
1573 static int post_loop_hook (pingobj_t *ping) /* {{{ */
1575         pingobj_iter_t *iter;
1576         int failure_count = 0;
1578 #if USE_NCURSES
1579         endwin ();
1580 #endif
1582         for (iter = ping_iterator_get (ping);
1583                         iter != NULL;
1584                         iter = ping_iterator_next (iter))
1585         {
1586                 ping_context_t *context;
1588                 context = ping_iterator_get_context (iter);
1590                 printf ("\n--- %s ping statistics ---\n"
1591                                 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
1592                                 context->host, context->req_sent, context->req_rcvd,
1593                                 context_get_packet_loss (context),
1594                                 context->latency_total);
1596                 {
1597                         double pct_failed = 1.0 - (((double) context->req_rcvd)
1598                                         / ((double) context->req_sent));
1599                         if (pct_failed > opt_exit_status_threshold)
1600                                 failure_count++;
1601                 }
1603                 if (context->req_rcvd != 0)
1604                 {
1605                         double min;
1606                         double median;
1607                         double max;
1608                         double percentile;
1610                         min = percentile_to_latency (context, 0.0);
1611                         median = percentile_to_latency (context, 50.0);
1612                         max = percentile_to_latency (context, 100.0);
1613                         percentile = percentile_to_latency (context, opt_percentile);
1615                         printf ("RTT[ms]: min = %.0f, median = %.0f, p(%.0f) = %.0f, max = %.0f\n",
1616                                         min, median, opt_percentile, percentile, max);
1617                 }
1619                 ping_iterator_set_context (iter, NULL);
1620                 context_destroy (context);
1621         }
1623         return (failure_count);
1624 } /* }}} int post_loop_hook */
1626 int main (int argc, char **argv) /* {{{ */
1628         pingobj_t      *ping;
1629         pingobj_iter_t *iter;
1631         struct sigaction sigint_action;
1633         struct timeval  tv_begin;
1634         struct timeval  tv_end;
1635         struct timespec ts_wait;
1636         struct timespec ts_int;
1638         int optind;
1639         int i;
1640         int status;
1641 #if _POSIX_SAVED_IDS
1642         uid_t saved_set_uid;
1644         /* Save the old effective user id */
1645         saved_set_uid = geteuid ();
1646         /* Set the effective user ID to the real user ID without changing the
1647          * saved set-user ID */
1648         status = seteuid (getuid ());
1649         if (status != 0)
1650         {
1651                 fprintf (stderr, "Temporarily dropping privileges "
1652                                 "failed: %s\n", strerror (errno));
1653                 exit (EXIT_FAILURE);
1654         }
1655 #endif
1657         setlocale(LC_ALL, "");
1658         optind = read_options (argc, argv);
1660 #if !_POSIX_SAVED_IDS
1661         /* Cannot temporarily drop privileges -> reject every file but "-". */
1662         if ((opt_filename != NULL)
1663                         && (strcmp ("-", opt_filename) != 0)
1664                         && (getuid () != geteuid ()))
1665         {
1666                 fprintf (stderr, "Your real and effective user IDs don't "
1667                                 "match. Reading from a file (option '-f')\n"
1668                                 "is therefore too risky. You can still read "
1669                                 "from STDIN using '-f -' if you like.\n"
1670                                 "Sorry.\n");
1671                 exit (EXIT_FAILURE);
1672         }
1673 #endif
1675         if ((optind >= argc) && (opt_filename == NULL)) {
1676                 usage_exit (argv[0], 1);
1677         }
1679         if ((ping = ping_construct ()) == NULL)
1680         {
1681                 fprintf (stderr, "ping_construct failed\n");
1682                 return (1);
1683         }
1685         if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
1686         {
1687                 fprintf (stderr, "Setting TTL to %i failed: %s\n",
1688                                 opt_send_ttl, ping_get_error (ping));
1689         }
1691         if (ping_setopt (ping, PING_OPT_QOS, &opt_send_qos) != 0)
1692         {
1693                 fprintf (stderr, "Setting TOS to %i failed: %s\n",
1694                                 opt_send_qos, ping_get_error (ping));
1695         }
1697         {
1698                 double temp_sec;
1699                 double temp_nsec;
1701                 temp_nsec = modf (opt_interval, &temp_sec);
1702                 ts_int.tv_sec  = (time_t) temp_sec;
1703                 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
1705                 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
1706         }
1708         if (opt_addrfamily != PING_DEF_AF)
1709                 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
1711         if (opt_srcaddr != NULL)
1712         {
1713                 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
1714                 {
1715                         fprintf (stderr, "Setting source address failed: %s\n",
1716                                         ping_get_error (ping));
1717                 }
1718         }
1720         if (opt_device != NULL)
1721         {
1722                 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
1723                 {
1724                         fprintf (stderr, "Setting device failed: %s\n",
1725                                         ping_get_error (ping));
1726                 }
1727         }
1729         if (opt_filename != NULL)
1730         {
1731                 FILE *infile;
1732                 char line[256];
1733                 char host[256];
1735                 if (strcmp (opt_filename, "-") == 0)
1736                         /* Open STDIN */
1737                         infile = fdopen(0, "r");
1738                 else
1739                         infile = fopen(opt_filename, "r");
1741                 if (infile == NULL)
1742                 {
1743                         fprintf (stderr, "Opening %s failed: %s\n",
1744                                         (strcmp (opt_filename, "-") == 0)
1745                                         ? "STDIN" : opt_filename,
1746                                         strerror(errno));
1747                         return (1);
1748                 }
1750 #if _POSIX_SAVED_IDS
1751                 /* Regain privileges */
1752                 status = seteuid (saved_set_uid);
1753                 if (status != 0)
1754                 {
1755                         fprintf (stderr, "Temporarily re-gaining privileges "
1756                                         "failed: %s\n", strerror (errno));
1757                         exit (EXIT_FAILURE);
1758                 }
1759 #endif
1761                 while (fgets(line, sizeof(line), infile))
1762                 {
1763                         /* Strip whitespace */
1764                         if (sscanf(line, "%s", host) != 1)
1765                                 continue;
1767                         if ((host[0] == 0) || (host[0] == '#'))
1768                                 continue;
1770                         if (ping_host_add(ping, host) < 0)
1771                         {
1772                                 const char *errmsg = ping_get_error (ping);
1774                                 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
1775                                 continue;
1776                         }
1777                         else
1778                         {
1779                                 host_num++;
1780                         }
1781                 }
1783 #if _POSIX_SAVED_IDS
1784                 /* Drop privileges */
1785                 status = seteuid (getuid ());
1786                 if (status != 0)
1787                 {
1788                         fprintf (stderr, "Temporarily dropping privileges "
1789                                         "failed: %s\n", strerror (errno));
1790                         exit (EXIT_FAILURE);
1791                 }
1792 #endif
1794                 fclose(infile);
1795         }
1797 #if _POSIX_SAVED_IDS
1798         /* Regain privileges */
1799         status = seteuid (saved_set_uid);
1800         if (status != 0)
1801         {
1802                 fprintf (stderr, "Temporarily re-gaining privileges "
1803                                 "failed: %s\n", strerror (errno));
1804                 exit (EXIT_FAILURE);
1805         }
1806 #endif
1808         for (i = optind; i < argc; i++)
1809         {
1810                 if (ping_host_add (ping, argv[i]) < 0)
1811                 {
1812                         const char *errmsg = ping_get_error (ping);
1814                         fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
1815                         continue;
1816                 }
1817                 else
1818                 {
1819                         host_num++;
1820                 }
1821         }
1823         /* Permanently drop root privileges if we're setuid-root. */
1824         status = setuid (getuid ());
1825         if (status != 0)
1826         {
1827                 fprintf (stderr, "Dropping privileges failed: %s\n",
1828                                 strerror (errno));
1829                 exit (EXIT_FAILURE);
1830         }
1832         if (host_num == 0)
1833                 exit (EXIT_FAILURE);
1835 #if _POSIX_SAVED_IDS
1836         saved_set_uid = (uid_t) -1;
1837 #endif
1839         ping_initialize_contexts (ping);
1841         if (i == 0)
1842                 return (1);
1844         memset (&sigint_action, '\0', sizeof (sigint_action));
1845         sigint_action.sa_handler = sigint_handler;
1846         if (sigaction (SIGINT, &sigint_action, NULL) < 0)
1847         {
1848                 perror ("sigaction");
1849                 return (1);
1850         }
1852         pre_loop_hook (ping);
1854         while (opt_count != 0)
1855         {
1856                 int index;
1857                 int status;
1859                 if (gettimeofday (&tv_begin, NULL) < 0)
1860                 {
1861                         perror ("gettimeofday");
1862                         return (1);
1863                 }
1865                 status = ping_send (ping);
1866                 if (status == -EINTR)
1867                 {
1868                         continue;
1869                 }
1870                 else if (status < 0)
1871                 {
1872                         fprintf (stderr, "ping_send failed: %s\n",
1873                                         ping_get_error (ping));
1874                         return (1);
1875                 }
1877                 index = 0;
1878                 for (iter = ping_iterator_get (ping);
1879                                 iter != NULL;
1880                                 iter = ping_iterator_next (iter))
1881                 {
1882                         update_host_hook (iter, index);
1883                         index++;
1884                 }
1886                 pre_sleep_hook (ping);
1888                 /* Don't sleep in the last iteration */
1889                 if (opt_count == 1)
1890                         break;
1892                 if (gettimeofday (&tv_end, NULL) < 0)
1893                 {
1894                         perror ("gettimeofday");
1895                         return (1);
1896                 }
1898                 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1900                 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1901                 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1902                 {
1903                         if (errno == EINTR)
1904                         {
1905                                 continue;
1906                         }
1907                         else
1908                         {
1909                                 perror ("nanosleep");
1910                                 break;
1911                         }
1912                 }
1914                 post_sleep_hook (ping);
1916                 if (opt_count > 0)
1917                         opt_count--;
1918         } /* while (opt_count != 0) */
1920         /* Returns the number of failed hosts according to -Z. */
1921         status = post_loop_hook (ping);
1923         ping_destroy (ping);
1925         if (status == 0)
1926                 exit (EXIT_SUCCESS);
1927         else
1928         {
1929                 if (status > 255)
1930                         status = 255;
1931                 exit (status);
1932         }
1933 } /* }}} int main */
1935 /* vim: set fdm=marker : */