Code

cce437904d856ff01571b1ffede9c41362a33f84
[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         }
1273         if (need_resize)
1274                 return (on_resize (ping));
1275         else
1276                 return (0);
1277 } /* }}} int check_resize */
1279 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
1281         pingobj_iter_t *iter;
1282         int width = 0;
1283         int height = 0;
1284         int main_win_height;
1285         int box_height = (opt_show_graph == 0) ? 4 : 5;
1287         initscr ();
1288         cbreak ();
1289         noecho ();
1290         nodelay (stdscr, TRUE);
1292         getmaxyx (stdscr, height, width);
1293         if ((height < 1) || (width < 1))
1294                 return (EINVAL);
1296         if (has_colors () == TRUE)
1297         {
1298                 start_color ();
1299                 init_pair (OPING_GREEN,  COLOR_GREEN,  /* default = */ 0);
1300                 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
1301                 init_pair (OPING_RED,    COLOR_RED,    /* default = */ 0);
1302                 init_pair (OPING_GREEN_HIST,  COLOR_GREEN,  COLOR_BLACK);
1303                 init_pair (OPING_YELLOW_HIST, COLOR_YELLOW, COLOR_GREEN);
1304                 init_pair (OPING_RED_HIST,    COLOR_RED,    COLOR_YELLOW);
1305         }
1307         main_win_height = height - (box_height * host_num);
1308         main_win = newwin (/* height = */ main_win_height,
1309                         /* width = */ width,
1310                         /* y = */ 0, /* x = */ 0);
1311         /* Allow scrolling */
1312         scrollok (main_win, TRUE);
1313         /* wsetscrreg (main_win, 0, main_win_height - 1); */
1314         /* Allow hardware accelerated scrolling. */
1315         idlok (main_win, TRUE);
1316         wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
1317         wrefresh (main_win);
1319         for (iter = ping_iterator_get (ping);
1320                         iter != NULL;
1321                         iter = ping_iterator_next (iter))
1322         {
1323                 ping_context_t *context;
1325                 context = ping_iterator_get_context (iter);
1326                 if (context == NULL)
1327                         continue;
1329                 if (context->window != NULL)
1330                 {
1331                         delwin (context->window);
1332                         context->window = NULL;
1333                 }
1334                 context->window = newwin (/* height = */ box_height,
1335                                 /* width = */ width,
1336                                 /* y = */ main_win_height + (box_height * context->index),
1337                                 /* x = */ 0);
1338         }
1341         /* Don't know what good this does exactly, but without this code
1342          * "check_resize" will be called right after startup and *somehow*
1343          * this leads to display errors. If we purge all initial characters
1344          * here, the problem goes away. "wgetch" is non-blocking due to
1345          * "nodelay" (see above). */
1346         while (wgetch (stdscr) != ERR)
1347         {
1348                 /* eat up characters */;
1349         }
1351         return (0);
1352 } /* }}} int pre_loop_hook */
1354 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
1356         return (check_resize (ping));
1357 } /* }}} int pre_sleep_hook */
1359 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
1361         return (check_resize (ping));
1362 } /* }}} int pre_sleep_hook */
1363 #else /* if !USE_NCURSES */
1364 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
1366         pingobj_iter_t *iter;
1368         for (iter = ping_iterator_get (ping);
1369                         iter != NULL;
1370                         iter = ping_iterator_next (iter))
1371         {
1372                 ping_context_t *ctx;
1373                 size_t buffer_size;
1375                 ctx = ping_iterator_get_context (iter);
1376                 if (ctx == NULL)
1377                         continue;
1379                 buffer_size = 0;
1380                 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
1382                 printf ("PING %s (%s) %zu bytes of data.\n",
1383                                 ctx->host, ctx->addr, buffer_size);
1384         }
1386         return (0);
1387 } /* }}} int pre_loop_hook */
1389 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
1391         fflush (stdout);
1393         return (0);
1394 } /* }}} int pre_sleep_hook */
1396 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
1398         return (0);
1399 } /* }}} int post_sleep_hook */
1400 #endif
1402 static void update_context (ping_context_t *ctx, double latency) /* {{{ */
1404         ctx->req_sent++;
1406         if (latency > 0.0)
1407         {
1408                 ctx->req_rcvd++;
1409                 ctx->latency_total += latency;
1410         }
1411         else
1412         {
1413                 latency = NAN;
1414         }
1416         ctx->history_by_time[ctx->history_index] = latency;
1418         ctx->history_dirty = 1;
1420         /* Update index and size. */
1421         ctx->history_index = (ctx->history_index + 1) % HISTORY_SIZE_MAX;
1422         if (ctx->history_size < HISTORY_SIZE_MAX)
1423                 ctx->history_size++;
1424 } /* }}} void update_context */
1426 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
1427                 __attribute__((unused)) int index)
1429         double          latency;
1430         unsigned int    sequence;
1431         int             recv_ttl;
1432         uint8_t         recv_qos;
1433         char            recv_qos_str[16];
1434         size_t          buffer_len;
1435         size_t          data_len;
1436         ping_context_t *context;
1438         latency = -1.0;
1439         buffer_len = sizeof (latency);
1440         ping_iterator_get_info (iter, PING_INFO_LATENCY,
1441                         &latency, &buffer_len);
1443         sequence = 0;
1444         buffer_len = sizeof (sequence);
1445         ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
1446                         &sequence, &buffer_len);
1448         recv_ttl = -1;
1449         buffer_len = sizeof (recv_ttl);
1450         ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
1451                         &recv_ttl, &buffer_len);
1453         recv_qos = 0;
1454         buffer_len = sizeof (recv_qos);
1455         ping_iterator_get_info (iter, PING_INFO_RECV_QOS,
1456                         &recv_qos, &buffer_len);
1458         data_len = 0;
1459         ping_iterator_get_info (iter, PING_INFO_DATA,
1460                         NULL, &data_len);
1462         context = (ping_context_t *) ping_iterator_get_context (iter);
1464 #if USE_NCURSES
1465 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
1466 #else
1467 # define HOST_PRINTF(...) printf(__VA_ARGS__)
1468 #endif
1470         update_context (context, latency);
1472         if (latency > 0.0)
1473         {
1474 #if USE_NCURSES
1475                 if (has_colors () == TRUE)
1476                 {
1477                         double percentile;
1478                         int color = OPING_GREEN;
1480                         percentile = latency_to_percentile (context, latency);
1481                         if (percentile < (100.0 * threshold_green))
1482                                 color = OPING_GREEN;
1483                         else if (percentile < (100.0 * threshold_yellow))
1484                                 color = OPING_YELLOW;
1485                         else
1486                                 color = OPING_RED;
1488 #if 0
1489                         if ((ratio_this <= threshold_green)
1490                                         || ((ratio_prev < threshold_green)
1491                                                 && (ratio_this > threshold_green)))
1492                                 color = OPING_GREEN;
1493                         else if ((ratio_this <= threshold_yellow)
1494                                         || ((ratio_prev < threshold_yellow)
1495                                                 && (ratio_this > threshold_yellow)))
1496                                 color = OPING_YELLOW;
1497                         else
1498                                 color = OPING_RED;
1499 #endif
1501                         HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
1502                                         data_len, context->host, context->addr,
1503                                         sequence, recv_ttl,
1504                                         format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1505                         if ((recv_qos != 0) || (opt_send_qos != 0))
1506                         {
1507                                 HOST_PRINTF ("qos=%s ",
1508                                                 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1509                         }
1510                         HOST_PRINTF ("time=");
1511                         wattron (main_win, COLOR_PAIR(color));
1512                         HOST_PRINTF ("%.2f", latency);
1513                         wattroff (main_win, COLOR_PAIR(color));
1514                         HOST_PRINTF (" ms\n");
1515                 }
1516                 else
1517                 {
1518 #endif
1519                 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
1520                                 data_len,
1521                                 context->host, context->addr,
1522                                 sequence, recv_ttl);
1523                 if ((recv_qos != 0) || (opt_send_qos != 0))
1524                 {
1525                         HOST_PRINTF ("qos=%s ",
1526                                         format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1527                 }
1528                 HOST_PRINTF ("time=%.2f ms\n", latency);
1529 #if USE_NCURSES
1530                 }
1531 #endif
1532         }
1533         else /* if (!(latency > 0.0)) */
1534         {
1535 #if USE_NCURSES
1536                 if (has_colors () == TRUE)
1537                 {
1538                         HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
1539                                         context->host, context->addr,
1540                                         sequence);
1541                         wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
1542                         HOST_PRINTF ("timeout");
1543                         wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
1544                         HOST_PRINTF ("\n");
1545                 }
1546                 else
1547                 {
1548 #endif
1549                 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
1550                                 context->host, context->addr,
1551                                 sequence);
1552 #if USE_NCURSES
1553                 }
1554 #endif
1555         }
1557 #if USE_NCURSES
1558         update_stats_from_context (context, iter);
1559         wrefresh (main_win);
1560 #endif
1561 } /* }}} void update_host_hook */
1563 /* Prints statistics for each host, cleans up the contexts and returns the
1564  * number of hosts which failed to return more than the fraction
1565  * opt_exit_status_threshold of pings. */
1566 static int post_loop_hook (pingobj_t *ping) /* {{{ */
1568         pingobj_iter_t *iter;
1569         int failure_count = 0;
1571 #if USE_NCURSES
1572         endwin ();
1573 #endif
1575         for (iter = ping_iterator_get (ping);
1576                         iter != NULL;
1577                         iter = ping_iterator_next (iter))
1578         {
1579                 ping_context_t *context;
1581                 context = ping_iterator_get_context (iter);
1583                 printf ("\n--- %s ping statistics ---\n"
1584                                 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
1585                                 context->host, context->req_sent, context->req_rcvd,
1586                                 context_get_packet_loss (context),
1587                                 context->latency_total);
1589                 {
1590                         double pct_failed = 1.0 - (((double) context->req_rcvd)
1591                                         / ((double) context->req_sent));
1592                         if (pct_failed > opt_exit_status_threshold)
1593                                 failure_count++;
1594                 }
1596                 if (context->req_rcvd != 0)
1597                 {
1598                         double min;
1599                         double median;
1600                         double max;
1601                         double percentile;
1603                         min = percentile_to_latency (context, 0.0);
1604                         median = percentile_to_latency (context, 50.0);
1605                         max = percentile_to_latency (context, 100.0);
1606                         percentile = percentile_to_latency (context, opt_percentile);
1608                         printf ("RTT[ms]: min = %.0f, median = %.0f, p(%.0f) = %.0f, max = %.0f\n",
1609                                         min, median, opt_percentile, percentile, max);
1610                 }
1612                 ping_iterator_set_context (iter, NULL);
1613                 context_destroy (context);
1614         }
1616         return (failure_count);
1617 } /* }}} int post_loop_hook */
1619 int main (int argc, char **argv) /* {{{ */
1621         pingobj_t      *ping;
1622         pingobj_iter_t *iter;
1624         struct sigaction sigint_action;
1626         struct timeval  tv_begin;
1627         struct timeval  tv_end;
1628         struct timespec ts_wait;
1629         struct timespec ts_int;
1631         int optind;
1632         int i;
1633         int status;
1634 #if _POSIX_SAVED_IDS
1635         uid_t saved_set_uid;
1637         /* Save the old effective user id */
1638         saved_set_uid = geteuid ();
1639         /* Set the effective user ID to the real user ID without changing the
1640          * saved set-user ID */
1641         status = seteuid (getuid ());
1642         if (status != 0)
1643         {
1644                 fprintf (stderr, "Temporarily dropping privileges "
1645                                 "failed: %s\n", strerror (errno));
1646                 exit (EXIT_FAILURE);
1647         }
1648 #endif
1650         setlocale(LC_ALL, "");
1651         optind = read_options (argc, argv);
1653 #if !_POSIX_SAVED_IDS
1654         /* Cannot temporarily drop privileges -> reject every file but "-". */
1655         if ((opt_filename != NULL)
1656                         && (strcmp ("-", opt_filename) != 0)
1657                         && (getuid () != geteuid ()))
1658         {
1659                 fprintf (stderr, "Your real and effective user IDs don't "
1660                                 "match. Reading from a file (option '-f')\n"
1661                                 "is therefore too risky. You can still read "
1662                                 "from STDIN using '-f -' if you like.\n"
1663                                 "Sorry.\n");
1664                 exit (EXIT_FAILURE);
1665         }
1666 #endif
1668         if ((optind >= argc) && (opt_filename == NULL)) {
1669                 usage_exit (argv[0], 1);
1670         }
1672         if ((ping = ping_construct ()) == NULL)
1673         {
1674                 fprintf (stderr, "ping_construct failed\n");
1675                 return (1);
1676         }
1678         if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
1679         {
1680                 fprintf (stderr, "Setting TTL to %i failed: %s\n",
1681                                 opt_send_ttl, ping_get_error (ping));
1682         }
1684         if (ping_setopt (ping, PING_OPT_QOS, &opt_send_qos) != 0)
1685         {
1686                 fprintf (stderr, "Setting TOS to %i failed: %s\n",
1687                                 opt_send_qos, ping_get_error (ping));
1688         }
1690         {
1691                 double temp_sec;
1692                 double temp_nsec;
1694                 temp_nsec = modf (opt_interval, &temp_sec);
1695                 ts_int.tv_sec  = (time_t) temp_sec;
1696                 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
1698                 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
1699         }
1701         if (opt_addrfamily != PING_DEF_AF)
1702                 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
1704         if (opt_srcaddr != NULL)
1705         {
1706                 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
1707                 {
1708                         fprintf (stderr, "Setting source address failed: %s\n",
1709                                         ping_get_error (ping));
1710                 }
1711         }
1713         if (opt_device != NULL)
1714         {
1715                 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
1716                 {
1717                         fprintf (stderr, "Setting device failed: %s\n",
1718                                         ping_get_error (ping));
1719                 }
1720         }
1722         if (opt_filename != NULL)
1723         {
1724                 FILE *infile;
1725                 char line[256];
1726                 char host[256];
1728                 if (strcmp (opt_filename, "-") == 0)
1729                         /* Open STDIN */
1730                         infile = fdopen(0, "r");
1731                 else
1732                         infile = fopen(opt_filename, "r");
1734                 if (infile == NULL)
1735                 {
1736                         fprintf (stderr, "Opening %s failed: %s\n",
1737                                         (strcmp (opt_filename, "-") == 0)
1738                                         ? "STDIN" : opt_filename,
1739                                         strerror(errno));
1740                         return (1);
1741                 }
1743 #if _POSIX_SAVED_IDS
1744                 /* Regain privileges */
1745                 status = seteuid (saved_set_uid);
1746                 if (status != 0)
1747                 {
1748                         fprintf (stderr, "Temporarily re-gaining privileges "
1749                                         "failed: %s\n", strerror (errno));
1750                         exit (EXIT_FAILURE);
1751                 }
1752 #endif
1754                 while (fgets(line, sizeof(line), infile))
1755                 {
1756                         /* Strip whitespace */
1757                         if (sscanf(line, "%s", host) != 1)
1758                                 continue;
1760                         if ((host[0] == 0) || (host[0] == '#'))
1761                                 continue;
1763                         if (ping_host_add(ping, host) < 0)
1764                         {
1765                                 const char *errmsg = ping_get_error (ping);
1767                                 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
1768                                 continue;
1769                         }
1770                         else
1771                         {
1772                                 host_num++;
1773                         }
1774                 }
1776 #if _POSIX_SAVED_IDS
1777                 /* Drop privileges */
1778                 status = seteuid (getuid ());
1779                 if (status != 0)
1780                 {
1781                         fprintf (stderr, "Temporarily dropping privileges "
1782                                         "failed: %s\n", strerror (errno));
1783                         exit (EXIT_FAILURE);
1784                 }
1785 #endif
1787                 fclose(infile);
1788         }
1790 #if _POSIX_SAVED_IDS
1791         /* Regain privileges */
1792         status = seteuid (saved_set_uid);
1793         if (status != 0)
1794         {
1795                 fprintf (stderr, "Temporarily re-gaining privileges "
1796                                 "failed: %s\n", strerror (errno));
1797                 exit (EXIT_FAILURE);
1798         }
1799 #endif
1801         for (i = optind; i < argc; i++)
1802         {
1803                 if (ping_host_add (ping, argv[i]) < 0)
1804                 {
1805                         const char *errmsg = ping_get_error (ping);
1807                         fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
1808                         continue;
1809                 }
1810                 else
1811                 {
1812                         host_num++;
1813                 }
1814         }
1816         /* Permanently drop root privileges if we're setuid-root. */
1817         status = setuid (getuid ());
1818         if (status != 0)
1819         {
1820                 fprintf (stderr, "Dropping privileges failed: %s\n",
1821                                 strerror (errno));
1822                 exit (EXIT_FAILURE);
1823         }
1825         if (host_num == 0)
1826                 exit (EXIT_FAILURE);
1828 #if _POSIX_SAVED_IDS
1829         saved_set_uid = (uid_t) -1;
1830 #endif
1832         ping_initialize_contexts (ping);
1834         if (i == 0)
1835                 return (1);
1837         memset (&sigint_action, '\0', sizeof (sigint_action));
1838         sigint_action.sa_handler = sigint_handler;
1839         if (sigaction (SIGINT, &sigint_action, NULL) < 0)
1840         {
1841                 perror ("sigaction");
1842                 return (1);
1843         }
1845         pre_loop_hook (ping);
1847         while (opt_count != 0)
1848         {
1849                 int index;
1850                 int status;
1852                 if (gettimeofday (&tv_begin, NULL) < 0)
1853                 {
1854                         perror ("gettimeofday");
1855                         return (1);
1856                 }
1858                 status = ping_send (ping);
1859                 if (status == -EINTR)
1860                 {
1861                         continue;
1862                 }
1863                 else if (status < 0)
1864                 {
1865                         fprintf (stderr, "ping_send failed: %s\n",
1866                                         ping_get_error (ping));
1867                         return (1);
1868                 }
1870                 index = 0;
1871                 for (iter = ping_iterator_get (ping);
1872                                 iter != NULL;
1873                                 iter = ping_iterator_next (iter))
1874                 {
1875                         update_host_hook (iter, index);
1876                         index++;
1877                 }
1879                 pre_sleep_hook (ping);
1881                 /* Don't sleep in the last iteration */
1882                 if (opt_count == 1)
1883                         break;
1885                 if (gettimeofday (&tv_end, NULL) < 0)
1886                 {
1887                         perror ("gettimeofday");
1888                         return (1);
1889                 }
1891                 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1893                 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1894                 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1895                 {
1896                         if (errno == EINTR)
1897                         {
1898                                 continue;
1899                         }
1900                         else
1901                         {
1902                                 perror ("nanosleep");
1903                                 break;
1904                         }
1905                 }
1907                 post_sleep_hook (ping);
1909                 if (opt_count > 0)
1910                         opt_count--;
1911         } /* while (opt_count != 0) */
1913         /* Returns the number of failed hosts according to -Z. */
1914         status = post_loop_hook (ping);
1916         ping_destroy (ping);
1918         if (status == 0)
1919                 exit (EXIT_SUCCESS);
1920         else
1921         {
1922                 if (status > 255)
1923                         status = 255;
1924                 exit (status);
1925         }
1926 } /* }}} int main */
1928 /* vim: set fdm=marker : */