Code

add bell output on successful pings
[liboping.git] / src / oping.c
1 /**
2  * Object oriented C module to send ICMP and ICMPv6 `echo's.
3  * Copyright (C) 2006-2016  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];
171         /* Current number of entries in the history. This is a value between 0
172          * and HISTORY_SIZE_MAX. */
173         size_t history_size;
175         /* Number "received" entries in the history, i.e. non-NAN entries. */
176         size_t history_received;
178         /* Index of the next RTT to be written to history_by_time. This wraps
179          * around to 0 once the histroty has grown to HISTORY_SIZE_MAX. */
180         size_t history_index;
182         /* The last history_size RTTs sorted by value. timed out packets (NAN
183          * entries) are sorted to the back. */
184         double history_by_value[HISTORY_SIZE_MAX];
186         /* If set to true, history_by_value has to be re-calculated. */
187         _Bool history_dirty;
189 #if USE_NCURSES
190         WINDOW *window;
191 #endif
192 } ping_context_t;
194 static double  opt_interval   = 1.0;
195 static double  opt_timeout    = PING_DEF_TIMEOUT;
196 static int     opt_addrfamily = PING_DEF_AF;
197 static char   *opt_srcaddr    = NULL;
198 static char   *opt_device     = NULL;
199 static char   *opt_mark       = NULL;
200 static char   *opt_filename   = NULL;
201 static int     opt_count      = -1;
202 static int     opt_send_ttl   = 64;
203 static uint8_t opt_send_qos   = 0;
204 #define OPING_DEFAULT_PERCENTILE 95.0
205 static double  opt_percentile = -1.0;
206 static double  opt_exit_status_threshold = 1.0;
207 #if USE_NCURSES
208 static int     opt_show_graph = 1;
209 static int     opt_utf8       = 0;
210 #endif
211 static char   *opt_outfile    = NULL;
212 static int     opt_bell       = 0;
214 static int host_num  = 0;
215 static FILE *outfile = NULL;
217 #if USE_NCURSES
218 static WINDOW *main_win = NULL;
219 #endif
221 static void sigint_handler (int signal) /* {{{ */
223         /* Make compiler happy */
224         signal = 0;
225         /* Exit the loop */
226         opt_count = 0;
227 } /* }}} void sigint_handler */
229 static ping_context_t *context_create (void) /* {{{ */
231         ping_context_t *ret;
233         if ((ret = malloc (sizeof (ping_context_t))) == NULL)
234                 return (NULL);
236         memset (ret, '\0', sizeof (ping_context_t));
238         ret->latency_total = 0.0;
240 #if USE_NCURSES
241         ret->window = NULL;
242 #endif
244         return (ret);
245 } /* }}} ping_context_t *context_create */
247 static void context_destroy (ping_context_t *context) /* {{{ */
249         if (context == NULL)
250                 return;
252 #if USE_NCURSES
253         if (context->window != NULL)
254         {
255                 delwin (context->window);
256                 context->window = NULL;
257         }
258 #endif
260         free (context);
261 } /* }}} void context_destroy */
263 static int compare_double (void const *arg0, void const *arg1) /* {{{ */
265         double dbl0 = *((double *) arg0);
266         double dbl1 = *((double *) arg1);
268         if (isnan (dbl0))
269         {
270                 if (isnan (dbl1))
271                         return 0;
272                 else
273                         return 1;
274         }
275         else if (isnan (dbl1))
276                 return -1;
277         else if (dbl0 < dbl1)
278                 return -1;
279         else if (dbl0 > dbl1)
280                 return 1;
281         else
282                 return 0;
283 } /* }}} int compare_double */
285 static void clean_history (ping_context_t *ctx) /* {{{ */
287         size_t i;
289         if (!ctx->history_dirty)
290                 return;
292         /* Copy all values from by_time to by_value. */
293         memcpy (ctx->history_by_value, ctx->history_by_time,
294                         sizeof (ctx->history_by_time));
296         /* Sort all RTTs. */
297         qsort (ctx->history_by_value, ctx->history_size, sizeof
298                         (ctx->history_by_value[0]), compare_double);
300         /* Update the number of received RTTs. */
301         ctx->history_received = 0;
302         for (i = 0; i < ctx->history_size; i++)
303                 if (!isnan (ctx->history_by_value[i]))
304                         ctx->history_received++;
306         /* Mark as clean. */
307         ctx->history_dirty = 0;
308 } /* }}} void clean_history */
310 static double percentile_to_latency (ping_context_t *ctx, /* {{{ */
311                 double percentile)
313         size_t index;
315         clean_history (ctx);
317         /* Not a single packet was received successfully. */
318         if (ctx->history_received == 0)
319                 return NAN;
321         if (percentile <= 0.0)
322                 index = 0;
323         else if (percentile >= 100.0)
324                 index = ctx->history_received - 1;
325         else
326         {
327                 index = (size_t) ceil ((percentile / 100.0) * ((double) ctx->history_received));
328                 assert (index > 0);
329                 index--;
330         }
332         return (ctx->history_by_value[index]);
333 } /* }}} double percentile_to_latency */
335 #if USE_NCURSES
336 static double latency_to_ratio (ping_context_t *ctx, /* {{{ */
337                 double latency)
339         size_t low;
340         size_t high;
341         size_t index;
343         clean_history (ctx);
345         /* Not a single packet was received successfully. */
346         if (ctx->history_received == 0)
347                 return NAN;
349         low = 0;
350         high = ctx->history_received - 1;
352         if (latency < ctx->history_by_value[low])
353                 return 0.0;
354         else if (latency >= ctx->history_by_value[high])
355                 return 100.0;
357         /* Do a binary search for the latency. This will work even when the
358          * exact latency is not in the array. If the latency is in the array
359          * multiple times, "low" will be set to the index of the last
360          * occurrence. The value at index "high" will be larger than the
361          * searched for latency (assured by the above "if" block. */
362         while ((high - low) > 1)
363         {
364                 index = (high + low) / 2;
366                 if (ctx->history_by_value[index] > latency)
367                         high = index;
368                 else
369                         low = index;
370         }
372         assert (ctx->history_by_value[high] > latency);
373         assert (ctx->history_by_value[low] <= latency);
375         if (ctx->history_by_value[low] == latency)
376                 index = low;
377         else
378                 index = high;
380         return (((double) (index + 1)) / ((double) ctx->history_received));
381 } /* }}} double latency_to_ratio */
382 #endif
384 static double context_get_packet_loss (const ping_context_t *ctx) /* {{{ */
386         if (ctx == NULL)
387                 return (-1.0);
389         if (ctx->req_sent < 1)
390                 return (0.0);
392         return (100.0 * (ctx->req_sent - ctx->req_rcvd)
393                         / ((double) ctx->req_sent));
394 } /* }}} double context_get_packet_loss */
396 static int ping_initialize_contexts (pingobj_t *ping) /* {{{ */
398         pingobj_iter_t *iter;
399         int index;
401         if (ping == NULL)
402                 return (EINVAL);
404         index = 0;
405         for (iter = ping_iterator_get (ping);
406                         iter != NULL;
407                         iter = ping_iterator_next (iter))
408         {
409                 ping_context_t *context;
410                 size_t buffer_size;
412                 context = context_create ();
413                 context->index = index;
415                 buffer_size = sizeof (context->host);
416                 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
418                 buffer_size = sizeof (context->addr);
419                 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
421                 ping_iterator_set_context (iter, (void *) context);
423                 index++;
424         }
426         return (0);
427 } /* }}} int ping_initialize_contexts */
429 static void usage_exit (const char *name, int status) /* {{{ */
431         fprintf (stderr, "Usage: %s [OPTIONS] "
432                                 "-f filename | host [host [host ...]]\n"
434                         "\nAvailable options:\n"
435                         "  -4|-6        force the use of IPv4 or IPv6\n"
436                         "  -c count     number of ICMP packets to send\n"
437                         "  -i interval  interval with which to send ICMP packets\n"
438                         "  -w timeout   time to wait for replies, in seconds\n"
439                         "  -t ttl       time to live for each ICMP packet\n"
440                         "  -Q qos       Quality of Service (QoS) of outgoing packets\n"
441                         "               Use \"-Q help\" for a list of valid options.\n"
442                         "  -I srcaddr   source address\n"
443                         "  -D device    outgoing interface name\n"
444                         "  -m mark      mark to set on outgoing packets\n"
445                         "  -f filename  read hosts from <filename>\n"
446                         "  -O filename  write RTT measurements to <filename>\n"
447 #if USE_NCURSES
448                         "  -u / -U      force / disable UTF-8 output\n"
449                         "  -g graph     graph type to draw\n"
450 #endif
451                         "  -P percent   Report the n'th percentile of latency\n"
452                         "  -Z percent   Exit with non-zero exit status if more than this percentage of\n"
453                         "               probes timed out. (default: never)\n"
455                         "\noping "PACKAGE_VERSION", http://noping.cc/\n"
456                         "by Florian octo Forster <ff@octo.it>\n"
457                         "for contributions see `AUTHORS'\n",
458                         name);
459         exit (status);
460 } /* }}} void usage_exit */
462 __attribute__((noreturn))
463 static void usage_qos_exit (const char *arg, int status) /* {{{ */
465         if (arg != 0)
466                 fprintf (stderr, "Invalid QoS argument: \"%s\"\n\n", arg);
468         fprintf (stderr, "Valid QoS arguments (option \"-Q\") are:\n"
469                         "\n"
470                         "  Differentiated Services (IPv4 and IPv6, RFC 2474)\n"
471                         "\n"
472                         "    be                     Best Effort (BE, default PHB).\n"
473                         "    ef                     Expedited Forwarding (EF) PHB group (RFC 3246).\n"
474                         "                           (low delay, low loss, low jitter)\n"
475                         "    va                     Voice Admit (VA) DSCP (RFC 5865).\n"
476                         "                           (capacity-admitted traffic)\n"
477                         "    af[1-4][1-3]           Assured Forwarding (AF) PHB group (RFC 2597).\n"
478                         "                           For example: \"af12\" (class 1, precedence 2)\n"
479                         "    cs[0-7]                Class Selector (CS) PHB group (RFC 2474).\n"
480                         "                           For example: \"cs1\" (priority traffic)\n"
481                         "\n"
482                         "  Type of Service (IPv4, RFC 1349, obsolete)\n"
483                         "\n"
484                         "    lowdelay     (%#04x)    minimize delay\n"
485                         "    throughput   (%#04x)    maximize throughput\n"
486                         "    reliability  (%#04x)    maximize reliability\n"
487                         "    mincost      (%#04x)    minimize monetary cost\n"
488                         "\n"
489                         "  Specify manually\n"
490                         "\n"
491                         "    0x00 - 0xff            Hexadecimal numeric specification.\n"
492                         "       0 -  255            Decimal numeric specification.\n"
493                         "\n",
494                         (unsigned int) IPTOS_LOWDELAY,
495                         (unsigned int) IPTOS_THROUGHPUT,
496                         (unsigned int) IPTOS_RELIABILITY,
497                         (unsigned int) IPTOS_MINCOST);
499         exit (status);
500 } /* }}} void usage_qos_exit */
502 static int set_opt_send_qos (const char *opt) /* {{{ */
504         if (opt == NULL)
505                 return (EINVAL);
507         if (strcasecmp ("help", opt) == 0)
508                 usage_qos_exit (/* arg = */ NULL, /* status = */ EXIT_SUCCESS);
509         /* DiffServ (RFC 2474): */
510         /* - Best effort (BE) */
511         else if (strcasecmp ("be", opt) == 0)
512                 opt_send_qos = 0;
513         /* - Expedited Forwarding (EF, RFC 3246) */
514         else if (strcasecmp ("ef", opt) == 0)
515                 opt_send_qos = 0xB8; /* == 0x2E << 2 */
516         /* - Voice Admit (VA, RFC 5865) */
517         else if (strcasecmp ("va", opt) == 0)
518                 opt_send_qos = 0xB0; /* == 0x2D << 2 */
519         /* - Assured Forwarding (AF, RFC 2597) */
520         else if ((strncasecmp ("af", opt, strlen ("af")) == 0)
521                         && (strlen (opt) == 4))
522         {
523                 uint8_t dscp;
524                 uint8_t class = 0;
525                 uint8_t prec = 0;
527                 /* There are four classes, AF1x, AF2x, AF3x, and AF4x. */
528                 if (opt[2] == '1')
529                         class = 1;
530                 else if (opt[2] == '2')
531                         class = 2;
532                 else if (opt[2] == '3')
533                         class = 3;
534                 else if (opt[2] == '4')
535                         class = 4;
536                 else
537                         usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
539                 /* In each class, there are three precedences, AFx1, AFx2, and AFx3 */
540                 if (opt[3] == '1')
541                         prec = 1;
542                 else if (opt[3] == '2')
543                         prec = 2;
544                 else if (opt[3] == '3')
545                         prec = 3;
546                 else
547                         usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
549                 dscp = (8 * class) + (2 * prec);
550                 /* The lower two bits are used for Explicit Congestion Notification (ECN) */
551                 opt_send_qos = dscp << 2;
552         }
553         /* - Class Selector (CS) */
554         else if ((strncasecmp ("cs", opt, strlen ("cs")) == 0)
555                         && (strlen (opt) == 3))
556         {
557                 uint8_t class;
559                 if ((opt[2] < '0') || (opt[2] > '7'))
560                         usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
562                 /* Not exactly legal by the C standard, but I don't know of any
563                  * system not supporting this hack. */
564                 class = ((uint8_t) opt[2]) - ((uint8_t) '0');
565                 opt_send_qos = class << 5;
566         }
567         /* Type of Service (RFC 1349) */
568         else if (strcasecmp ("lowdelay", opt) == 0)
569                 opt_send_qos = IPTOS_LOWDELAY;
570         else if (strcasecmp ("throughput", opt) == 0)
571                 opt_send_qos = IPTOS_THROUGHPUT;
572         else if (strcasecmp ("reliability", opt) == 0)
573                 opt_send_qos = IPTOS_RELIABILITY;
574         else if (strcasecmp ("mincost", opt) == 0)
575                 opt_send_qos = IPTOS_MINCOST;
576         /* Numeric value */
577         else
578         {
579                 unsigned long value;
580                 char *endptr;
582                 errno = 0;
583                 endptr = NULL;
584                 value = strtoul (opt, &endptr, /* base = */ 0);
585                 if ((errno != 0) || (endptr == opt)
586                                 || (endptr == NULL) || (*endptr != 0)
587                                 || (value > 0xff))
588                         usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
589                 
590                 opt_send_qos = (uint8_t) value;
591         }
593         return (0);
594 } /* }}} int set_opt_send_qos */
596 static char *format_qos (uint8_t qos, char *buffer, size_t buffer_size) /* {{{ */
598         uint8_t dscp;
599         uint8_t ecn;
600         char *dscp_str;
601         char *ecn_str;
603         dscp = qos >> 2;
604         ecn = qos & 0x03;
606         switch (dscp)
607         {
608                 case 0x00: dscp_str = "be";  break;
609                 case 0x2e: dscp_str = "ef";  break;
610                 case 0x2d: dscp_str = "va";  break;
611                 case 0x0a: dscp_str = "af11"; break;
612                 case 0x0c: dscp_str = "af12"; break;
613                 case 0x0e: dscp_str = "af13"; break;
614                 case 0x12: dscp_str = "af21"; break;
615                 case 0x14: dscp_str = "af22"; break;
616                 case 0x16: dscp_str = "af23"; break;
617                 case 0x1a: dscp_str = "af31"; break;
618                 case 0x1c: dscp_str = "af32"; break;
619                 case 0x1e: dscp_str = "af33"; break;
620                 case 0x22: dscp_str = "af41"; break;
621                 case 0x24: dscp_str = "af42"; break;
622                 case 0x26: dscp_str = "af43"; break;
623                 case 0x08: dscp_str = "cs1";  break;
624                 case 0x10: dscp_str = "cs2";  break;
625                 case 0x18: dscp_str = "cs3";  break;
626                 case 0x20: dscp_str = "cs4";  break;
627                 case 0x28: dscp_str = "cs5";  break;
628                 case 0x30: dscp_str = "cs6";  break;
629                 case 0x38: dscp_str = "cs7";  break;
630                 default:   dscp_str = NULL;
631         }
633         switch (ecn)
634         {
635                 case 0x01: ecn_str = ",ecn(1)"; break;
636                 case 0x02: ecn_str = ",ecn(0)"; break;
637                 case 0x03: ecn_str = ",ce"; break;
638                 default:   ecn_str = "";
639         }
641         if (dscp_str == NULL)
642                 snprintf (buffer, buffer_size, "0x%02x%s", dscp, ecn_str);
643         else
644                 snprintf (buffer, buffer_size, "%s%s", dscp_str, ecn_str);
645         buffer[buffer_size - 1] = 0;
647         return (buffer);
648 } /* }}} char *format_qos */
650 static int read_options (int argc, char **argv) /* {{{ */
652         int optchar;
654         while (1)
655         {
656                 optchar = getopt (argc, argv, "46c:hi:I:t:Q:f:D:Z:O:P:m:w:b"
657 #if USE_NCURSES
658                                 "uUg:"
659 #endif
660                                 );
662                 if (optchar == -1)
663                         break;
665                 switch (optchar)
666                 {
667                         case '4':
668                         case '6':
669                                 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
670                                 break;
672                         case 'c':
673                                 {
674                                         int new_count;
675                                         new_count = atoi (optarg);
676                                         if (new_count > 0)
677                                         {
678                                                 opt_count = new_count;
680                                                 if ((opt_percentile < 0.0) && (opt_count < 20))
681                                                         opt_percentile = 100.0 * (opt_count - 1) / opt_count;
682                                         }
683                                         else
684                                                 fprintf(stderr, "Ignoring invalid count: %s\n",
685                                                                 optarg);
686                                 }
687                                 break;
689                         case 'f':
690                                 {
691                                         if (opt_filename != NULL)
692                                                 free (opt_filename);
693                                         opt_filename = strdup (optarg);
694                                 }
695                                 break;
697                         case 'i':
698                                 {
699                                         double new_interval;
700                                         new_interval = atof (optarg);
701                                         if (new_interval < 0.001)
702                                                 fprintf (stderr, "Ignoring invalid interval: %s\n",
703                                                                 optarg);
704                                         else
705                                                 opt_interval = new_interval;
706                                 }
707                                 break;
709                         case 'w':
710                                 {
711                                         char *endp = NULL;
712                                         double t = strtod (optarg, &endp);
713                                         if ((optarg[0] != 0) && (endp != NULL) && (*endp == 0))
714                                                 opt_timeout = t;
715                                         else
716                                                 fprintf (stderr, "Ignoring invalid timeout: %s\n",
717                                                                 optarg);
718                                 }
719                                 break;
721                         case 'I':
722                                 {
723                                         if (opt_srcaddr != NULL)
724                                                 free (opt_srcaddr);
725                                         opt_srcaddr = strdup (optarg);
726                                 }
727                                 break;
729                         case 'D':
730                                 opt_device = optarg;
731                                 break;
733                         case 'm':
734                                 opt_mark = optarg;
735                                 break;
737                         case 't':
738                         {
739                                 int new_send_ttl;
740                                 new_send_ttl = atoi (optarg);
741                                 if ((new_send_ttl > 0) && (new_send_ttl < 256))
742                                         opt_send_ttl = new_send_ttl;
743                                 else
744                                         fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
745                                                         optarg);
746                                 break;
747                         }
749                         case 'Q':
750                                 set_opt_send_qos (optarg);
751                                 break;
753                         case 'O':
754                                 {
755                                         free (opt_outfile);
756                                         opt_outfile = strdup (optarg);
757                                 }
759                         case 'P':
760                                 {
761                                         double new_percentile;
762                                         new_percentile = atof (optarg);
763                                         if (isnan (new_percentile)
764                                                         || (new_percentile < 0.1)
765                                                         || (new_percentile > 100.0))
766                                                 fprintf (stderr, "Ignoring invalid percentile: %s\n",
767                                                                 optarg);
768                                         else
769                                                 opt_percentile = new_percentile;
770                                 }
771                                 break;
773 #if USE_NCURSES
774                         case 'g':
775                                 if (strcasecmp ("none", optarg) == 0)
776                                         opt_show_graph = 0;
777                                 else if (strcasecmp ("prettyping", optarg) == 0)
778                                         opt_show_graph = 1;
779                                 else if (strcasecmp ("histogram", optarg) == 0)
780                                         opt_show_graph = 2;
781                                 else if (strcasecmp ("boxplot", optarg) == 0)
782                                         opt_show_graph = 3;
783                                 else
784                                         fprintf (stderr, "Unknown graph option: %s\n", optarg);
785                                 break;
787                         case 'u':
788                                 opt_utf8 = 2;
789                                 break;
790                         case 'U':
791                                 opt_utf8 = 1;
792                                 break;
793 #endif
794                         case 'b':
795                                 opt_bell = 1;
796                                 break;
798                         case 'Z':
799                         {
800                                 char *endptr = NULL;
801                                 double tmp;
803                                 errno = 0;
804                                 tmp = strtod (optarg, &endptr);
805                                 if ((errno != 0) || (endptr == NULL) || (*endptr != 0) || (tmp < 0.0) || (tmp > 100.0))
806                                 {
807                                         fprintf (stderr, "Ignoring invalid -Z argument: %s\n", optarg);
808                                         fprintf (stderr, "The \"-Z\" option requires a numeric argument between 0 and 100.\n");
809                                 }
810                                 else
811                                         opt_exit_status_threshold = tmp / 100.0;
813                                 break;
814                         }
816                         case 'h':
817                                 usage_exit (argv[0], 0);
818                                 break;
820                         default:
821                                 usage_exit (argv[0], 1);
822                 }
823         }
825         if (opt_percentile <= 0.0)
826                 opt_percentile = OPING_DEFAULT_PERCENTILE;
828         return (optind);
829 } /* }}} read_options */
831 static void time_normalize (struct timespec *ts) /* {{{ */
833         while (ts->tv_nsec < 0)
834         {
835                 if (ts->tv_sec == 0)
836                 {
837                         ts->tv_nsec = 0;
838                         return;
839                 }
841                 ts->tv_sec  -= 1;
842                 ts->tv_nsec += 1000000000;
843         }
845         while (ts->tv_nsec >= 1000000000)
846         {
847                 ts->tv_sec  += 1;
848                 ts->tv_nsec -= 1000000000;
849         }
850 } /* }}} void time_normalize */
852 static void time_calc (struct timespec *ts_dest, /* {{{ */
853                 const struct timespec *ts_int,
854                 const struct timeval  *tv_begin,
855                 const struct timeval  *tv_end)
857         ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
858         ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
859         time_normalize (ts_dest);
861         /* Assure that `(begin + interval) > end'.
862          * This may seem overly complicated, but `tv_sec' is of type `time_t'
863          * which may be `unsigned. *sigh* */
864         if ((tv_end->tv_sec > ts_dest->tv_sec)
865                         || ((tv_end->tv_sec == ts_dest->tv_sec)
866                                 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
867         {
868                 ts_dest->tv_sec  = 0;
869                 ts_dest->tv_nsec = 0;
870                 return;
871         }
873         ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
874         ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
875         time_normalize (ts_dest);
876 } /* }}} void time_calc */
878 #if USE_NCURSES
879 static _Bool has_utf8() /* {{{ */
881 # if HAVE_NCURSESW_NCURSES_H
882         if (!opt_utf8)
883         {
884                 /* Automatically determine */
885                 if (strcasecmp ("UTF-8", nl_langinfo (CODESET)) == 0)
886                         opt_utf8 = 2;
887                 else
888                         opt_utf8 = 1;
889         }
890         return ((_Bool) (opt_utf8 - 1));
891 # else
892         return (0);
893 # endif
894 } /* }}} _Bool has_utf8 */
896 static int update_graph_boxplot (ping_context_t *ctx) /* {{{ */
898         uint32_t *counters;
899         double *ratios;
900         size_t i;
901         size_t x_max;
902         size_t x;
904         clean_history (ctx);
906         if (ctx->history_received == 0)
907                 return (ENOENT);
909         x_max = (size_t) getmaxx (ctx->window);
910         if (x_max <= 8)
911                 return (EINVAL);
912         x_max -= 4;
914         counters = calloc (x_max, sizeof (*counters));
915         ratios = calloc (x_max, sizeof (*ratios));
917         /* Bucketize */
918         for (i = 0; i < ctx->history_received; i++)
919         {
920                 double latency = ctx->history_by_value[i] / 1000.0;
921                 size_t index = (size_t) (((double) x_max) * latency / opt_interval);
923                 if (index >= x_max)
924                         index = x_max - 1;
926                 counters[index]++;
927         }
929         /* Sum and calc ratios */
930         ratios[0] = ((double) counters[0]) / ((double) ctx->history_received);
931         for (x = 1; x < x_max; x++)
932         {
933                 counters[x] += counters[x - 1];
934                 ratios[x] = ((double) counters[x]) / ((double) ctx->history_received);
935         }
937         for (x = 0; x < x_max; x++)
938         {
939                 int symbol = ' ';
940                 _Bool reverse = 0;
942                 if (x == 0)
943                 {
944                         if (ratios[x] >= 0.5)
945                         {
946                                 symbol = BOXPLOT_MEDIAN;
947                                 reverse = 1;
948                         }
949                         else if (ratios[x] > 0.25)
950                         {
951                                 symbol = BOXPLOT_BOX;
952                                 reverse = 1;
953                         }
954                         else if (ratios[x] > 0.025)
955                                 symbol = BOXPLOT_WHISKER_BAR;
956                         else
957                                 symbol = ' '; /* NOP */
958                 }
959                 else /* (x != 0) */
960                 {
961                         if ((ratios[x - 1] < 0.5) && (ratios[x] >= 0.5))
962                         {
963                                 symbol = BOXPLOT_MEDIAN;
964                                 reverse = 1;
965                         }
966                         else if (((ratios[x] >= 0.25) && (ratios[x] <= 0.75))
967                                         || ((ratios[x - 1] < 0.75) && (ratios[x] > 0.75)))
968                         {
969                                 symbol = BOXPLOT_BOX;
970                                 reverse = 1;
971                         }
972                         else if ((ratios[x] < 0.5) && (ratios[x] >= 0.025))
973                         {
974                                 if (ratios[x - 1] < 0.025)
975                                         symbol = BOXPLOT_WHISKER_LEFT_END;
976                                 else
977                                         symbol = BOXPLOT_WHISKER_BAR;
978                         }
979                         else if ((ratios[x] > .5) && (ratios[x] < 0.975))
980                         {
981                                 symbol = BOXPLOT_WHISKER_BAR;
982                         }
983                         else if ((ratios[x] >= 0.975) && (ratios[x - 1] < 0.975))
984                                 symbol = BOXPLOT_WHISKER_RIGHT_END;
985                 }
987                 if (reverse)
988                         wattron (ctx->window, A_REVERSE);
989                 mvwaddch (ctx->window, /* y = */ 3, /* x = */ (int) (x + 2), symbol);
990                 // mvwprintw (ctx->window, /* y = */ 3, /* x = */ (int) (x + 2), symbol);
991                 if (reverse)
992                         wattroff (ctx->window, A_REVERSE);
993         }
995         free (counters);
996         free (ratios);
997         return (0);
998 } /* }}} int update_graph_boxplot */
1000 static int update_graph_prettyping (ping_context_t *ctx, /* {{{ */
1001                 double latency, unsigned int sequence)
1003         size_t x;
1004         size_t x_max;
1005         size_t history_offset;
1007         x_max = (size_t) getmaxx (ctx->window);
1008         if (x_max <= 4)
1009                 return (EINVAL);
1010         x_max -= 4;
1012         /* Determine the first index in the history we need to draw
1013          * the graph. */
1014         history_offset = 0;
1015         if (((size_t) x_max) < ctx->history_size) /* window is smaller than history */
1016         {
1017                 if (ctx->history_index > x_max)
1018                         history_offset = ctx->history_index - x_max;
1019                 else /* wrap around */
1020                         history_offset = ctx->history_index + ctx->history_size - x_max;
1021         }
1022         else /* window is larger than history */
1023         {
1024                 if (ctx->history_index != ctx->history_size) /* no longer growing. */
1025                         history_offset = ctx->history_index;
1026                 else /* start-up */
1027                         history_offset = 0;
1028         }
1030         for (x = 0; x < x_max; x++)
1031         {
1032                 size_t index;
1033                 double latency;
1035                 int color = OPING_RED;
1036                 char const *symbol = "!";
1037                 int symbolc = '!';
1039                 if (x >= ctx->history_size)
1040                 {
1041                         mvwaddch (ctx->window, /* y = */ 3, /* x = */ x + 2, ' ');
1042                         continue;
1043                 }
1045                 index = (history_offset + x) % ctx->history_size;
1046                 latency = ctx->history_by_time[index];
1048                 if (latency >= 0.0)
1049                 {
1050                         double ratio;
1052                         size_t symbols_num = hist_symbols_acs_num;
1053                         size_t colors_num = 1;
1055                         size_t index_symbols;
1056                         size_t index_colors;
1057                         size_t intensity;
1059                         /* latency is in milliseconds, opt_interval is in seconds. */
1060                         ratio = (latency * 0.001) / opt_interval;
1061                         if (ratio > 1) {
1062                                 ratio = 1.0;
1063                         }
1065                         if (has_utf8 ())
1066                                 symbols_num = hist_symbols_utf8_num;
1068                         if (has_colors () == TRUE)
1069                                 colors_num = hist_colors_num;
1071                         intensity = (size_t) (ratio * ((double) (symbols_num * colors_num)));
1072                         if (intensity >= (symbols_num * colors_num))
1073                                 intensity = (symbols_num * colors_num) - 1;
1075                         index_symbols = intensity % symbols_num;
1076                         assert (index_symbols < symbols_num);
1078                         index_colors = intensity / symbols_num;
1079                         assert (index_colors < colors_num);
1081                         if (has_utf8())
1082                         {
1083                                 color = hist_colors_utf8[index_colors];
1084                                 symbol = hist_symbols_utf8[index_symbols];
1085                         }
1086                         else
1087                         {
1088                                 color = hist_colors_acs[index_colors];
1089                                 symbolc = hist_symbols_acs[index_symbols] | A_ALTCHARSET;
1090                         }
1091                 }
1092                 else /* if (!(latency >= 0.0)) */
1093                         wattron (ctx->window, A_BOLD);
1095                 if (has_colors () == TRUE)
1096                         wattron (ctx->window, COLOR_PAIR(color));
1098                 if (has_utf8())
1099                         mvwprintw (ctx->window, /* y = */ 3, /* x = */ x + 2, symbol);
1100                 else
1101                         mvwaddch (ctx->window, /* y = */ 3, /* x = */ x + 2, symbolc);
1103                 if (has_colors () == TRUE)
1104                         wattroff (ctx->window, COLOR_PAIR(color));
1106                 /* Use negation here to handle NaN correctly. */
1107                 if (!(latency >= 0.0))
1108                         wattroff (ctx->window, A_BOLD);
1109         } /* for (x) */
1111         return (0);
1112 } /* }}} int update_graph_prettyping */
1114 static int update_graph_histogram (ping_context_t *ctx) /* {{{ */
1116         uint32_t *counters;
1117         uint32_t *accumulated;
1118         uint32_t max;
1119         size_t i;
1120         size_t x_max;
1121         size_t x;
1123         size_t symbols_num = hist_symbols_acs_num;
1125         clean_history (ctx);
1127         if (ctx->history_received == 0)
1128                 return (ENOENT);
1130         if (has_utf8 ())
1131                 symbols_num = hist_symbols_utf8_num;
1133         x_max = (size_t) getmaxx (ctx->window);
1134         if (x_max <= 4)
1135                 return (EINVAL);
1136         x_max -= 4;
1138         counters = calloc (x_max, sizeof (*counters));
1139         accumulated = calloc (x_max, sizeof (*accumulated));
1141         /* Bucketize */
1142         max = 0;
1143         for (i = 0; i < ctx->history_received; i++)
1144         {
1145                 double latency = ctx->history_by_value[i] / 1000.0;
1146                 size_t index = (size_t) (((double) x_max) * latency / opt_interval);
1148                 if (index >= x_max)
1149                         index = x_max - 1;
1151                 counters[index]++;
1152                 if (max < counters[index])
1153                         max = counters[index];
1154         }
1156         /* Sum */
1157         accumulated[0] = counters[0];
1158         for (x = 1; x < x_max; x++)
1159                 accumulated[x] = counters[x] + accumulated[x - 1];
1161         /* Calculate ratios */
1162         for (x = 0; x < x_max; x++)
1163         {
1164                 double height = ((double) counters[x]) / ((double) max);
1165                 double ratio_this = ((double) accumulated[x]) / ((double) ctx->history_received);
1166                 double ratio_prev = 0.0;
1167                 size_t index;
1168                 int color = 0;
1170                 index = (size_t) (height * ((double) symbols_num));
1171                 if (index >= symbols_num)
1172                         index = symbols_num - 1;
1174                 if (x > 0)
1175                         ratio_prev = ((double) accumulated[x - 1]) / ((double) ctx->history_received);
1177                 if (has_colors () == TRUE)
1178                 {
1179                         if ((ratio_this <= threshold_green)
1180                                         || ((ratio_prev < threshold_green)
1181                                                 && (ratio_this > threshold_green)))
1182                                 color = OPING_GREEN;
1183                         else if ((ratio_this <= threshold_yellow)
1184                                         || ((ratio_prev < threshold_yellow)
1185                                                 && (ratio_this > threshold_yellow)))
1186                                 color = OPING_YELLOW;
1187                         else
1188                                 color = OPING_RED;
1190                         wattron (ctx->window, COLOR_PAIR(color));
1191                 }
1193                 if (counters[x] == 0)
1194                         mvwaddch (ctx->window, /* y = */ 3, /* x = */ x + 2, ' ');
1195                 else if (has_utf8 ())
1196                         mvwprintw (ctx->window, /* y = */ 3, /* x = */ x + 2,
1197                                         hist_symbols_utf8[index]);
1198                 else
1199                         mvwaddch (ctx->window, /* y = */ 3, /* x = */ x + 2,
1200                                         hist_symbols_acs[index] | A_ALTCHARSET);
1202                 if (has_colors () == TRUE)
1203                         wattroff (ctx->window, COLOR_PAIR(color));
1205         }
1207         free (accumulated);
1208         return (0);
1209 } /* }}} int update_graph_histogram */
1211 static int update_stats_from_context (ping_context_t *ctx, pingobj_iter_t *iter) /* {{{ */
1213         double latency = -1.0;
1214         size_t buffer_len = sizeof (latency);
1216         ping_iterator_get_info (iter, PING_INFO_LATENCY,
1217                         &latency, &buffer_len);
1219         unsigned int sequence = 0;
1220         buffer_len = sizeof (sequence);
1221         ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
1222                         &sequence, &buffer_len);
1225         if ((ctx == NULL) || (ctx->window == NULL))
1226                 return (EINVAL);
1228         /* werase (ctx->window); */
1230         box (ctx->window, 0, 0);
1231         wattron (ctx->window, A_BOLD);
1232         mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
1233                         " %s ", ctx->host);
1234         wattroff (ctx->window, A_BOLD);
1235         wprintw (ctx->window, "ping statistics ");
1236         mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
1237                         "%i packets transmitted, %i received, %.2f%% packet "
1238                         "loss, time %.1fms",
1239                         ctx->req_sent, ctx->req_rcvd,
1240                         context_get_packet_loss (ctx),
1241                         ctx->latency_total);
1242         if (ctx->req_rcvd != 0)
1243         {
1244                 double min;
1245                 double median;
1246                 double max;
1247                 double percentile;
1249                 min = percentile_to_latency (ctx, 0.0);
1250                 median = percentile_to_latency (ctx, 50.0);
1251                 max = percentile_to_latency (ctx, 100.0);
1252                 percentile = percentile_to_latency (ctx, opt_percentile);
1254                 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
1255                                 "RTT[ms]: min = %.0f, median = %.0f, p(%.0f) = %.0f, max = %.0f  ",
1256                                 min, median, opt_percentile, percentile, max);
1257         }
1259         if (opt_show_graph == 1)
1260                 update_graph_prettyping (ctx, latency, sequence);
1261         else if (opt_show_graph == 2)
1262                 update_graph_histogram (ctx);
1263         else if (opt_show_graph == 3)
1264                 update_graph_boxplot (ctx);
1266         wrefresh (ctx->window);
1268         return (0);
1269 } /* }}} int update_stats_from_context */
1271 static int on_resize (pingobj_t *ping) /* {{{ */
1273         pingobj_iter_t *iter;
1274         int width = 0;
1275         int height = 0;
1276         int main_win_height;
1277         int box_height = (opt_show_graph == 0) ? 4 : 5;
1279         getmaxyx (stdscr, height, width);
1280         if ((height < 1) || (width < 1))
1281                 return (EINVAL);
1283         main_win_height = height - (box_height * host_num);
1284         wresize (main_win, main_win_height, /* width = */ width);
1285         /* Allow scrolling */
1286         scrollok (main_win, TRUE);
1287         /* wsetscrreg (main_win, 0, main_win_height - 1); */
1288         /* Allow hardware accelerated scrolling. */
1289         idlok (main_win, TRUE);
1290         wrefresh (main_win);
1292         for (iter = ping_iterator_get (ping);
1293                         iter != NULL;
1294                         iter = ping_iterator_next (iter))
1295         {
1296                 ping_context_t *context;
1298                 context = ping_iterator_get_context (iter);
1299                 if (context == NULL)
1300                         continue;
1302                 if (context->window != NULL)
1303                 {
1304                         delwin (context->window);
1305                         context->window = NULL;
1306                 }
1307                 context->window = newwin (/* height = */ box_height,
1308                                 /* width = */ width,
1309                                 /* y = */ main_win_height + (box_height * context->index),
1310                                 /* x = */ 0);
1311         }
1313         return (0);
1314 } /* }}} */
1316 static int check_resize (pingobj_t *ping) /* {{{ */
1318         int need_resize = 0;
1320         while (42)
1321         {
1322                 int key = wgetch (stdscr);
1323                 if (key == ERR)
1324                         break;
1325                 else if (key == KEY_RESIZE)
1326                         need_resize = 1;
1327                 else if (key == 'g')
1328                 {
1329                         if (opt_show_graph == 3)
1330                                 opt_show_graph = 1;
1331                         else if (opt_show_graph > 0)
1332                                 opt_show_graph++;
1333                 }
1334         }
1336         if (need_resize)
1337                 return (on_resize (ping));
1338         else
1339                 return (0);
1340 } /* }}} int check_resize */
1342 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
1344         pingobj_iter_t *iter;
1345         int width = 0;
1346         int height = 0;
1347         int main_win_height;
1348         int box_height = (opt_show_graph == 0) ? 4 : 5;
1350         initscr ();
1351         cbreak ();
1352         noecho ();
1353         nodelay (stdscr, TRUE);
1355         getmaxyx (stdscr, height, width);
1356         if ((height < 1) || (width < 1))
1357                 return (EINVAL);
1359         if (has_colors () == TRUE)
1360         {
1361                 start_color ();
1362                 init_pair (OPING_GREEN,  COLOR_GREEN,  /* default = */ 0);
1363                 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
1364                 init_pair (OPING_RED,    COLOR_RED,    /* default = */ 0);
1365                 init_pair (OPING_GREEN_HIST,  COLOR_GREEN,  COLOR_BLACK);
1366                 init_pair (OPING_YELLOW_HIST, COLOR_YELLOW, COLOR_GREEN);
1367                 init_pair (OPING_RED_HIST,    COLOR_RED,    COLOR_YELLOW);
1368         }
1370         main_win_height = height - (box_height * host_num);
1371         main_win = newwin (/* height = */ main_win_height,
1372                         /* width = */ width,
1373                         /* y = */ 0, /* x = */ 0);
1374         /* Allow scrolling */
1375         scrollok (main_win, TRUE);
1376         /* wsetscrreg (main_win, 0, main_win_height - 1); */
1377         /* Allow hardware accelerated scrolling. */
1378         idlok (main_win, TRUE);
1379         wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
1380         wrefresh (main_win);
1382         for (iter = ping_iterator_get (ping);
1383                         iter != NULL;
1384                         iter = ping_iterator_next (iter))
1385         {
1386                 ping_context_t *context;
1388                 context = ping_iterator_get_context (iter);
1389                 if (context == NULL)
1390                         continue;
1392                 if (context->window != NULL)
1393                 {
1394                         delwin (context->window);
1395                         context->window = NULL;
1396                 }
1397                 context->window = newwin (/* height = */ box_height,
1398                                 /* width = */ width,
1399                                 /* y = */ main_win_height + (box_height * context->index),
1400                                 /* x = */ 0);
1401         }
1404         /* Don't know what good this does exactly, but without this code
1405          * "check_resize" will be called right after startup and *somehow*
1406          * this leads to display errors. If we purge all initial characters
1407          * here, the problem goes away. "wgetch" is non-blocking due to
1408          * "nodelay" (see above). */
1409         while (wgetch (stdscr) != ERR)
1410         {
1411                 /* eat up characters */;
1412         }
1414         return (0);
1415 } /* }}} int pre_loop_hook */
1417 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
1419         return (check_resize (ping));
1420 } /* }}} int pre_sleep_hook */
1422 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
1424         return (check_resize (ping));
1425 } /* }}} int pre_sleep_hook */
1426 #else /* if !USE_NCURSES */
1427 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
1429         pingobj_iter_t *iter;
1431         for (iter = ping_iterator_get (ping);
1432                         iter != NULL;
1433                         iter = ping_iterator_next (iter))
1434         {
1435                 ping_context_t *ctx;
1436                 size_t buffer_size;
1438                 ctx = ping_iterator_get_context (iter);
1439                 if (ctx == NULL)
1440                         continue;
1442                 buffer_size = 0;
1443                 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
1445                 printf ("PING %s (%s) %zu bytes of data.\n",
1446                                 ctx->host, ctx->addr, buffer_size);
1447         }
1449         return (0);
1450 } /* }}} int pre_loop_hook */
1452 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
1454         fflush (stdout);
1456         return (0);
1457 } /* }}} int pre_sleep_hook */
1459 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
1461         return (0);
1462 } /* }}} int post_sleep_hook */
1463 #endif
1465 static void update_context (ping_context_t *ctx, double latency) /* {{{ */
1467         ctx->req_sent++;
1469         if (latency > 0.0)
1470         {
1471                 ctx->req_rcvd++;
1472                 ctx->latency_total += latency;
1473         }
1474         else
1475         {
1476                 latency = NAN;
1477         }
1479         ctx->history_by_time[ctx->history_index] = latency;
1481         ctx->history_dirty = 1;
1483         /* Update index and size. */
1484         ctx->history_index = (ctx->history_index + 1) % HISTORY_SIZE_MAX;
1485         if (ctx->history_size < HISTORY_SIZE_MAX)
1486                 ctx->history_size++;
1487 } /* }}} void update_context */
1489 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
1490                 __attribute__((unused)) int index)
1492         double          latency;
1493         unsigned int    sequence;
1494         int             recv_ttl;
1495         uint8_t         recv_qos;
1496         char            recv_qos_str[16];
1497         size_t          buffer_len;
1498         size_t          data_len;
1499         ping_context_t *context;
1501         latency = -1.0;
1502         buffer_len = sizeof (latency);
1503         ping_iterator_get_info (iter, PING_INFO_LATENCY,
1504                         &latency, &buffer_len);
1506         sequence = 0;
1507         buffer_len = sizeof (sequence);
1508         ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
1509                         &sequence, &buffer_len);
1511         recv_ttl = -1;
1512         buffer_len = sizeof (recv_ttl);
1513         ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
1514                         &recv_ttl, &buffer_len);
1516         recv_qos = 0;
1517         buffer_len = sizeof (recv_qos);
1518         ping_iterator_get_info (iter, PING_INFO_RECV_QOS,
1519                         &recv_qos, &buffer_len);
1521         data_len = 0;
1522         ping_iterator_get_info (iter, PING_INFO_DATA,
1523                         NULL, &data_len);
1525         context = (ping_context_t *) ping_iterator_get_context (iter);
1527 #if USE_NCURSES
1528 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
1529 #else
1530 # define HOST_PRINTF(...) printf(__VA_ARGS__)
1531 #endif
1533         update_context (context, latency);
1535         if (latency > 0.0)
1536         {
1537 #if USE_NCURSES
1538                 if (has_colors () == TRUE)
1539                 {
1540                         double ratio;
1541                         int color = OPING_GREEN;
1543                         ratio = latency_to_ratio (context, latency);
1544                         if (ratio < threshold_green)
1545                                 color = OPING_GREEN;
1546                         else if (ratio < threshold_yellow)
1547                                 color = OPING_YELLOW;
1548                         else
1549                                 color = OPING_RED;
1551                         HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
1552                                         data_len, context->host, context->addr,
1553                                         sequence, recv_ttl,
1554                                         format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1555                         if ((recv_qos != 0) || (opt_send_qos != 0))
1556                         {
1557                                 HOST_PRINTF ("qos=%s ",
1558                                                 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1559                         }
1560                         HOST_PRINTF ("time=");
1561                         wattron (main_win, COLOR_PAIR(color));
1562                         HOST_PRINTF ("%.2f", latency);
1563                         wattroff (main_win, COLOR_PAIR(color));
1564                         HOST_PRINTF (" ms\n");
1565                 }
1566                 else
1567                 {
1568 #endif
1569                 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
1570                                 data_len,
1571                                 context->host, context->addr,
1572                                 sequence, recv_ttl);
1573                 if ((recv_qos != 0) || (opt_send_qos != 0))
1574                 {
1575                         HOST_PRINTF ("qos=%s ",
1576                                         format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1577                 }
1578                 HOST_PRINTF ("time=%.2f ms\n", latency);
1579 #if USE_NCURSES
1580                 }
1581 #endif
1582                 if (opt_bell) {
1583 #if USE_NCURSES
1584                         beep();
1585 #else
1586                         HOST_PRINTF ("\a");
1587 #endif
1588                 }
1589         }
1590         else /* if (!(latency > 0.0)) */
1591         {
1592 #if USE_NCURSES
1593                 if (has_colors () == TRUE)
1594                 {
1595                         HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
1596                                         context->host, context->addr,
1597                                         sequence);
1598                         wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
1599                         HOST_PRINTF ("timeout");
1600                         wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
1601                         HOST_PRINTF ("\n");
1602                 }
1603                 else
1604                 {
1605 #endif
1606                 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
1607                                 context->host, context->addr,
1608                                 sequence);
1609 #if USE_NCURSES
1610                 }
1611 #endif
1612         }
1614         if (outfile != NULL)
1615         {
1616                 struct timespec ts = { 0, 0 };
1618                 if (clock_gettime (CLOCK_REALTIME, &ts) == 0)
1619                 {
1620                         double t = ((double) ts.tv_sec) + (((double) ts.tv_nsec) / 1000000000.0);
1622                         if ((sequence % 32) == 0)
1623                                 fprintf (outfile, "#time,host,latency[ms]\n");
1625                         fprintf (outfile, "%.3f,\"%s\",%.2f\n", t, context->host, latency);
1626                 }
1627         }
1629 #if USE_NCURSES
1630         update_stats_from_context (context, iter);
1631         wrefresh (main_win);
1632 #endif
1633 } /* }}} void update_host_hook */
1635 /* Prints statistics for each host, cleans up the contexts and returns the
1636  * number of hosts which failed to return more than the fraction
1637  * opt_exit_status_threshold of pings. */
1638 static int post_loop_hook (pingobj_t *ping) /* {{{ */
1640         pingobj_iter_t *iter;
1641         int failure_count = 0;
1643 #if USE_NCURSES
1644         endwin ();
1645 #endif
1647         for (iter = ping_iterator_get (ping);
1648                         iter != NULL;
1649                         iter = ping_iterator_next (iter))
1650         {
1651                 ping_context_t *context;
1653                 context = ping_iterator_get_context (iter);
1655                 printf ("\n--- %s ping statistics ---\n"
1656                                 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
1657                                 context->host, context->req_sent, context->req_rcvd,
1658                                 context_get_packet_loss (context),
1659                                 context->latency_total);
1661                 {
1662                         double pct_failed = 1.0 - (((double) context->req_rcvd)
1663                                         / ((double) context->req_sent));
1664                         if (pct_failed > opt_exit_status_threshold)
1665                                 failure_count++;
1666                 }
1668                 if (context->req_rcvd != 0)
1669                 {
1670                         double min;
1671                         double median;
1672                         double max;
1673                         double percentile;
1675                         min = percentile_to_latency (context, 0.0);
1676                         median = percentile_to_latency (context, 50.0);
1677                         max = percentile_to_latency (context, 100.0);
1678                         percentile = percentile_to_latency (context, opt_percentile);
1680                         printf ("RTT[ms]: min = %.0f, median = %.0f, p(%.0f) = %.0f, max = %.0f\n",
1681                                         min, median, opt_percentile, percentile, max);
1682                 }
1684                 ping_iterator_set_context (iter, NULL);
1685                 context_destroy (context);
1686         }
1688         return (failure_count);
1689 } /* }}} int post_loop_hook */
1691 int main (int argc, char **argv) /* {{{ */
1693         pingobj_t      *ping;
1694         pingobj_iter_t *iter;
1696         struct sigaction sigint_action;
1698         struct timeval  tv_begin;
1699         struct timeval  tv_end;
1700         struct timespec ts_wait;
1701         struct timespec ts_int;
1703         int optind;
1704         int i;
1705         int status;
1706 #if _POSIX_SAVED_IDS
1707         uid_t saved_set_uid;
1709         /* Save the old effective user id */
1710         saved_set_uid = geteuid ();
1711         /* Set the effective user ID to the real user ID without changing the
1712          * saved set-user ID */
1713         status = seteuid (getuid ());
1714         if (status != 0)
1715         {
1716                 fprintf (stderr, "Temporarily dropping privileges "
1717                                 "failed: %s\n", strerror (errno));
1718                 exit (EXIT_FAILURE);
1719         }
1720 #endif
1722         setlocale(LC_ALL, "");
1723         optind = read_options (argc, argv);
1725 #if !_POSIX_SAVED_IDS
1726         /* Cannot temporarily drop privileges -> reject every file but "-". */
1727         if ((opt_filename != NULL)
1728                         && (strcmp ("-", opt_filename) != 0)
1729                         && (getuid () != geteuid ()))
1730         {
1731                 fprintf (stderr, "Your real and effective user IDs don't "
1732                                 "match. Reading from a file (option '-f')\n"
1733                                 "is therefore too risky. You can still read "
1734                                 "from STDIN using '-f -' if you like.\n"
1735                                 "Sorry.\n");
1736                 exit (EXIT_FAILURE);
1737         }
1738 #endif
1740         if ((optind >= argc) && (opt_filename == NULL)) {
1741                 usage_exit (argv[0], 1);
1742         }
1744         if ((ping = ping_construct ()) == NULL)
1745         {
1746                 fprintf (stderr, "ping_construct failed\n");
1747                 return (1);
1748         }
1750         if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
1751         {
1752                 fprintf (stderr, "Setting TTL to %i failed: %s\n",
1753                                 opt_send_ttl, ping_get_error (ping));
1754         }
1756         if (ping_setopt (ping, PING_OPT_QOS, &opt_send_qos) != 0)
1757         {
1758                 fprintf (stderr, "Setting TOS to %i failed: %s\n",
1759                                 opt_send_qos, ping_get_error (ping));
1760         }
1762         {
1763                 double temp_sec;
1764                 double temp_nsec;
1766                 temp_nsec = modf (opt_interval, &temp_sec);
1767                 ts_int.tv_sec  = (time_t) temp_sec;
1768                 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
1770                 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
1771         }
1773         if (ping_setopt (ping, PING_OPT_TIMEOUT, (void*)(&opt_timeout)) != 0)
1774         {
1775                 fprintf (stderr, "Setting timeout failed: %s\n",
1776                                 ping_get_error (ping));
1777         }
1779         if (opt_addrfamily != PING_DEF_AF)
1780                 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
1782         if (opt_srcaddr != NULL)
1783         {
1784                 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
1785                 {
1786                         fprintf (stderr, "Setting source address failed: %s\n",
1787                                         ping_get_error (ping));
1788                 }
1789         }
1791         if (opt_device != NULL)
1792         {
1793                 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
1794                 {
1795                         fprintf (stderr, "Setting device failed: %s\n",
1796                                         ping_get_error (ping));
1797                 }
1798         }
1800         if (opt_mark != NULL)
1801         {
1802                 char *endp = NULL;
1803                 int mark = (int) strtol (opt_mark, &endp, /* base = */ 0);
1804                 if ((opt_mark[0] != 0) && (endp != NULL) && (*endp == 0))
1805                 {
1806                         if (ping_setopt(ping, PING_OPT_MARK, (void*)(&mark)) != 0)
1807                         {
1808                                 fprintf (stderr, "Setting mark failed: %s\n",
1809                                         ping_get_error (ping));
1810                         }
1811                 }
1812                 else
1813                 {
1814                         fprintf(stderr, "Ignoring invalid mark: %s\n", optarg);
1815                 }
1816         }
1818         if (opt_filename != NULL)
1819         {
1820                 FILE *infile;
1821                 char line[256];
1822                 char host[256];
1824                 if (strcmp (opt_filename, "-") == 0)
1825                         /* Open STDIN */
1826                         infile = fdopen(0, "r");
1827                 else
1828                         infile = fopen(opt_filename, "r");
1830                 if (infile == NULL)
1831                 {
1832                         fprintf (stderr, "Opening %s failed: %s\n",
1833                                         (strcmp (opt_filename, "-") == 0)
1834                                         ? "STDIN" : opt_filename,
1835                                         strerror(errno));
1836                         return (1);
1837                 }
1839 #if _POSIX_SAVED_IDS
1840                 /* Regain privileges */
1841                 status = seteuid (saved_set_uid);
1842                 if (status != 0)
1843                 {
1844                         fprintf (stderr, "Temporarily re-gaining privileges "
1845                                         "failed: %s\n", strerror (errno));
1846                         exit (EXIT_FAILURE);
1847                 }
1848 #endif
1850                 while (fgets(line, sizeof(line), infile))
1851                 {
1852                         /* Strip whitespace */
1853                         if (sscanf(line, "%s", host) != 1)
1854                                 continue;
1856                         if ((host[0] == 0) || (host[0] == '#'))
1857                                 continue;
1859                         if (ping_host_add(ping, host) < 0)
1860                         {
1861                                 const char *errmsg = ping_get_error (ping);
1863                                 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
1864                                 continue;
1865                         }
1866                         else
1867                         {
1868                                 host_num++;
1869                         }
1870                 }
1872 #if _POSIX_SAVED_IDS
1873                 /* Drop privileges */
1874                 status = seteuid (getuid ());
1875                 if (status != 0)
1876                 {
1877                         fprintf (stderr, "Temporarily dropping privileges "
1878                                         "failed: %s\n", strerror (errno));
1879                         exit (EXIT_FAILURE);
1880                 }
1881 #endif
1883                 fclose(infile);
1884         }
1886 #if _POSIX_SAVED_IDS
1887         /* Regain privileges */
1888         status = seteuid (saved_set_uid);
1889         if (status != 0)
1890         {
1891                 fprintf (stderr, "Temporarily re-gaining privileges "
1892                                 "failed: %s\n", strerror (errno));
1893                 exit (EXIT_FAILURE);
1894         }
1895 #endif
1897         for (i = optind; i < argc; i++)
1898         {
1899                 if (ping_host_add (ping, argv[i]) < 0)
1900                 {
1901                         const char *errmsg = ping_get_error (ping);
1903                         fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
1904                         continue;
1905                 }
1906                 else
1907                 {
1908                         host_num++;
1909                 }
1910         }
1912         /* Permanently drop root privileges if we're setuid-root. */
1913         status = setuid (getuid ());
1914         if (status != 0)
1915         {
1916                 fprintf (stderr, "Dropping privileges failed: %s\n",
1917                                 strerror (errno));
1918                 exit (EXIT_FAILURE);
1919         }
1921         if (host_num == 0)
1922                 exit (EXIT_FAILURE);
1924 #if _POSIX_SAVED_IDS
1925         saved_set_uid = (uid_t) -1;
1926 #endif
1928         if (opt_outfile != NULL)
1929         {
1930                 outfile = fopen (opt_outfile, "a");
1931                 if (outfile == NULL)
1932                 {
1933                         fprintf (stderr, "opening \"%s\" failed: %s\n",
1934                                  opt_outfile, strerror (errno));
1935                         exit (EXIT_FAILURE);
1936                 }
1937         }
1939         ping_initialize_contexts (ping);
1941         if (i == 0)
1942                 return (1);
1944         memset (&sigint_action, '\0', sizeof (sigint_action));
1945         sigint_action.sa_handler = sigint_handler;
1946         if (sigaction (SIGINT, &sigint_action, NULL) < 0)
1947         {
1948                 perror ("sigaction");
1949                 return (1);
1950         }
1952         pre_loop_hook (ping);
1954         while (opt_count != 0)
1955         {
1956                 int index;
1957                 int status;
1959                 if (gettimeofday (&tv_begin, NULL) < 0)
1960                 {
1961                         perror ("gettimeofday");
1962                         return (1);
1963                 }
1965                 status = ping_send (ping);
1966                 if (status == -EINTR)
1967                 {
1968                         continue;
1969                 }
1970                 else if (status < 0)
1971                 {
1972                         fprintf (stderr, "ping_send failed: %s\n",
1973                                         ping_get_error (ping));
1974                         return (1);
1975                 }
1977                 index = 0;
1978                 for (iter = ping_iterator_get (ping);
1979                                 iter != NULL;
1980                                 iter = ping_iterator_next (iter))
1981                 {
1982                         update_host_hook (iter, index);
1983                         index++;
1984                 }
1986                 pre_sleep_hook (ping);
1988                 /* Don't sleep in the last iteration */
1989                 if (opt_count == 1)
1990                         break;
1992                 if (gettimeofday (&tv_end, NULL) < 0)
1993                 {
1994                         perror ("gettimeofday");
1995                         return (1);
1996                 }
1998                 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
2000                 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
2001                 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
2002                 {
2003                         if (errno == EINTR)
2004                         {
2005                                 continue;
2006                         }
2007                         else
2008                         {
2009                                 perror ("nanosleep");
2010                                 break;
2011                         }
2012                 }
2014                 post_sleep_hook (ping);
2016                 if (opt_count > 0)
2017                         opt_count--;
2018         } /* while (opt_count != 0) */
2020         /* Returns the number of failed hosts according to -Z. */
2021         status = post_loop_hook (ping);
2023         ping_destroy (ping);
2025         if (outfile != NULL)
2026         {
2027                 fclose (outfile);
2028                 outfile = NULL;
2029         }
2031         if (status == 0)
2032                 exit (EXIT_SUCCESS);
2033         else
2034         {
2035                 if (status > 255)
2036                         status = 255;
2037                 exit (status);
2038         }
2039 } /* }}} int main */
2041 /* vim: set fdm=marker : */