Code

Initial implementation of a box plot.
[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 static char const * const hist_symbols_utf8[] = {
99         "▁", "▂", "▃", "▄", "▅", "▆", "▇", "█" };
100 static size_t const hist_symbols_utf8_num = sizeof (hist_symbols_utf8)
101         / sizeof (hist_symbols_utf8[0]);
103 /* scancodes for 6 levels of horizontal bars, ncurses-specific */
104 /* those are not the usual constants because those are not constant */
105 static int const hist_symbols_acs[] = {
106         115, /* ACS_S9 "⎽" */
107         114, /* ACS_S7 "⎼" */
108         113, /* ACS_S5 "─" */
109         112, /* ACS_S3 "⎻" */
110         111  /* ACS_S1 "⎺" */
111 };
112 static size_t const hist_symbols_acs_num = sizeof (hist_symbols_acs)
113         / sizeof (hist_symbols_acs[0]);
115 /* use different colors without a background for scancodes */
116 static int const hist_colors_utf8[] = {
117         OPING_GREEN_HIST, OPING_YELLOW_HIST, OPING_RED_HIST };
118 static int const hist_colors_acs[] = {
119         OPING_GREEN, OPING_YELLOW, OPING_RED };
120 /* assuming that both arrays are the same size */
121 static size_t const hist_colors_num = sizeof (hist_colors_utf8)
122         / sizeof (hist_colors_utf8[0]);
123 #endif
125 /* "─" */
126 #define BOXPLOT_WHISKER_BAR (113 | A_ALTCHARSET)
127 /* "├" */
128 #define BOXPLOT_WHISKER_LEFT_END (116 | A_ALTCHARSET)
129 /* "┤" */
130 #define BOXPLOT_WHISKER_RIGHT_END (117 | A_ALTCHARSET)
131 #define BOXPLOT_BOX ' '
132 /* "│" */
133 #define BOXPLOT_MEDIAN (120 | A_ALTCHARSET)
135 #include "oping.h"
137 #ifndef _POSIX_SAVED_IDS
138 # define _POSIX_SAVED_IDS 0
139 #endif
141 #ifndef IPTOS_MINCOST
142 # define IPTOS_MINCOST 0x02
143 #endif
145 /* Remove GNU specific __attribute__ settings when using another compiler */
146 #if !__GNUC__
147 # define __attribute__(x) /**/
148 #endif
150 typedef struct ping_context
152         char host[NI_MAXHOST];
153         char addr[NI_MAXHOST];
155         int index;
156         int req_sent;
157         int req_rcvd;
159         double latency_min;
160         double latency_max;
161         double latency_total;
162         double latency_total_square;
164 /* 1000 + one "infinity" bucket. */
165 #define OPING_HISTOGRAM_BUCKETS 1001
166         uint32_t *latency_histogram;
167         size_t latency_histogram_size;
169 #if USE_NCURSES
170         WINDOW *window;
171 #endif
172 } ping_context_t;
174 static double  opt_interval   = 1.0;
175 static int     opt_addrfamily = PING_DEF_AF;
176 static char   *opt_srcaddr    = NULL;
177 static char   *opt_device     = NULL;
178 static char   *opt_filename   = NULL;
179 static int     opt_count      = -1;
180 static int     opt_send_ttl   = 64;
181 static uint8_t opt_send_qos   = 0;
182 #define OPING_DEFAULT_PERCENTILE 95.0
183 static double  opt_percentile = -1.0;
184 static double  opt_exit_status_threshold = 1.0;
185 #if USE_NCURSES
186 static int     opt_utf8       = 0;
187 #endif
189 static int host_num = 0;
191 #if USE_NCURSES
192 static WINDOW *main_win = NULL;
193 #endif
195 static void sigint_handler (int signal) /* {{{ */
197         /* Make compiler happy */
198         signal = 0;
199         /* Exit the loop */
200         opt_count = 0;
201 } /* }}} void sigint_handler */
203 static ping_context_t *context_create (void) /* {{{ */
205         ping_context_t *ret;
207         if ((ret = malloc (sizeof (ping_context_t))) == NULL)
208                 return (NULL);
210         memset (ret, '\0', sizeof (ping_context_t));
212         ret->latency_min   = -1.0;
213         ret->latency_max   = -1.0;
214         ret->latency_total = 0.0;
215         ret->latency_total_square = 0.0;
217         ret->latency_histogram_size = (size_t) OPING_HISTOGRAM_BUCKETS;
218         ret->latency_histogram = calloc (ret->latency_histogram_size,
219                         sizeof (*ret->latency_histogram));
221 #if USE_NCURSES
222         ret->window = NULL;
223 #endif
225         return (ret);
226 } /* }}} ping_context_t *context_create */
228 static void context_destroy (ping_context_t *context) /* {{{ */
230         if (context == NULL)
231                 return;
233 #if USE_NCURSES
234         if (context->window != NULL)
235         {
236                 delwin (context->window);
237                 context->window = NULL;
238         }
239 #endif
241         free (context->latency_histogram);
242         context->latency_histogram = NULL;
244         free (context);
245 } /* }}} void context_destroy */
247 static double context_get_average (ping_context_t *ctx) /* {{{ */
249         double num_total;
251         if (ctx == NULL)
252                 return (-1.0);
254         if (ctx->req_rcvd < 1)
255                 return (-0.0);
257         num_total = (double) ctx->req_rcvd;
258         return (ctx->latency_total / num_total);
259 } /* }}} double context_get_average */
261 static double context_get_percentile (ping_context_t *ctx, /* {{{ */
262                 double percentile)
264         double threshold = percentile / 100.0;
265         uint32_t accumulated[ctx->latency_histogram_size];
266         double ratios[ctx->latency_histogram_size];
267         double index_to_ms_factor;
268         uint32_t num;
269         size_t i;
271         if (ctx->latency_histogram == NULL)
272                 return (NAN);
274         accumulated[0] = ctx->latency_histogram[0];
275         for (i = 1; i < ctx->latency_histogram_size; i++)
276                 accumulated[i] = accumulated[i - 1]
277                         + ctx->latency_histogram[i];
278         num = accumulated[ctx->latency_histogram_size - 1];
280         for (i = 0; i < ctx->latency_histogram_size; i++)
281         {
282                 ratios[i] = ((double) accumulated[i]) / ((double) num);
283                 if (ratios[i] >= threshold)
284                         break;
285         }
287         if (i >= ctx->latency_histogram_size)
288                 return (NAN);
289         else if (i == (ctx->latency_histogram_size - 1))
290                 return (INFINITY);
292         index_to_ms_factor = (1000.0 * opt_interval) / (ctx->latency_histogram_size - 1);
294         /* Multiply with i+1, because we're interested in the _upper_ bound of
295          * each bucket. */
296         return (index_to_ms_factor * ((double) (i + 1)));
297 } /* }}} double context_get_percentile */
299 static double context_get_stddev (ping_context_t *ctx) /* {{{ */
301         double num_total;
303         if (ctx == NULL)
304                 return (-1.0);
306         if (ctx->req_rcvd < 1)
307                 return (-0.0);
308         else if (ctx->req_rcvd < 2)
309                 return (0.0);
311         num_total = (double) ctx->req_rcvd;
312         return (sqrt (((num_total * ctx->latency_total_square)
313                                         - (ctx->latency_total * ctx->latency_total))
314                                 / (num_total * (num_total - 1.0))));
315 } /* }}} double context_get_stddev */
317 static double context_get_packet_loss (const ping_context_t *ctx) /* {{{ */
319         if (ctx == NULL)
320                 return (-1.0);
322         if (ctx->req_sent < 1)
323                 return (0.0);
325         return (100.0 * (ctx->req_sent - ctx->req_rcvd)
326                         / ((double) ctx->req_sent));
327 } /* }}} double context_get_packet_loss */
329 static int ping_initialize_contexts (pingobj_t *ping) /* {{{ */
331         pingobj_iter_t *iter;
332         int index;
334         if (ping == NULL)
335                 return (EINVAL);
337         index = 0;
338         for (iter = ping_iterator_get (ping);
339                         iter != NULL;
340                         iter = ping_iterator_next (iter))
341         {
342                 ping_context_t *context;
343                 size_t buffer_size;
345                 context = context_create ();
346                 context->index = index;
348                 buffer_size = sizeof (context->host);
349                 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
351                 buffer_size = sizeof (context->addr);
352                 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
354                 ping_iterator_set_context (iter, (void *) context);
356                 index++;
357         }
359         return (0);
360 } /* }}} int ping_initialize_contexts */
362 static void usage_exit (const char *name, int status) /* {{{ */
364         fprintf (stderr, "Usage: %s [OPTIONS] "
365                                 "-f filename | host [host [host ...]]\n"
367                         "\nAvailable options:\n"
368                         "  -4|-6        force the use of IPv4 or IPv6\n"
369                         "  -c count     number of ICMP packets to send\n"
370                         "  -i interval  interval with which to send ICMP packets\n"
371                         "  -t ttl       time to live for each ICMP packet\n"
372                         "  -Q qos       Quality of Service (QoS) of outgoing packets\n"
373                         "               Use \"-Q help\" for a list of valid options.\n"
374                         "  -I srcaddr   source address\n"
375                         "  -D device    outgoing interface name\n"
376                         "  -f filename  filename to read hosts from\n"
377 #if USE_NCURSES
378                         "  -u / -U      force / disable UTF-8 output\n"
379 #endif
380                         "  -P percent   Report the n'th percentile of latency\n"
381                         "  -Z percent   Exit with non-zero exit status if more than this percentage of\n"
382                         "               probes timed out. (default: never)\n"
384                         "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
385                         "by Florian octo Forster <octo@verplant.org>\n"
386                         "for contributions see `AUTHORS'\n",
387                         name);
388         exit (status);
389 } /* }}} void usage_exit */
391 __attribute__((noreturn))
392 static void usage_qos_exit (const char *arg, int status) /* {{{ */
394         if (arg != 0)
395                 fprintf (stderr, "Invalid QoS argument: \"%s\"\n\n", arg);
397         fprintf (stderr, "Valid QoS arguments (option \"-Q\") are:\n"
398                         "\n"
399                         "  Differentiated Services (IPv4 and IPv6, RFC 2474)\n"
400                         "\n"
401                         "    be                     Best Effort (BE, default PHB).\n"
402                         "    ef                     Expedited Forwarding (EF) PHB group (RFC 3246).\n"
403                         "                           (low delay, low loss, low jitter)\n"
404                         "    va                     Voice Admit (VA) DSCP (RFC 5865).\n"
405                         "                           (capacity-admitted traffic)\n"
406                         "    af[1-4][1-3]           Assured Forwarding (AF) PHB group (RFC 2597).\n"
407                         "                           For example: \"af12\" (class 1, precedence 2)\n"
408                         "    cs[0-7]                Class Selector (CS) PHB group (RFC 2474).\n"
409                         "                           For example: \"cs1\" (priority traffic)\n"
410                         "\n"
411                         "  Type of Service (IPv4, RFC 1349, obsolete)\n"
412                         "\n"
413                         "    lowdelay     (%#04x)    minimize delay\n"
414                         "    throughput   (%#04x)    maximize throughput\n"
415                         "    reliability  (%#04x)    maximize reliability\n"
416                         "    mincost      (%#04x)    minimize monetary cost\n"
417                         "\n"
418                         "  Specify manually\n"
419                         "\n"
420                         "    0x00 - 0xff            Hexadecimal numeric specification.\n"
421                         "       0 -  255            Decimal numeric specification.\n"
422                         "\n",
423                         (unsigned int) IPTOS_LOWDELAY,
424                         (unsigned int) IPTOS_THROUGHPUT,
425                         (unsigned int) IPTOS_RELIABILITY,
426                         (unsigned int) IPTOS_MINCOST);
428         exit (status);
429 } /* }}} void usage_qos_exit */
431 static int set_opt_send_qos (const char *opt) /* {{{ */
433         if (opt == NULL)
434                 return (EINVAL);
436         if (strcasecmp ("help", opt) == 0)
437                 usage_qos_exit (/* arg = */ NULL, /* status = */ EXIT_SUCCESS);
438         /* DiffServ (RFC 2474): */
439         /* - Best effort (BE) */
440         else if (strcasecmp ("be", opt) == 0)
441                 opt_send_qos = 0;
442         /* - Expedited Forwarding (EF, RFC 3246) */
443         else if (strcasecmp ("ef", opt) == 0)
444                 opt_send_qos = 0xB8; /* == 0x2E << 2 */
445         /* - Voice Admit (VA, RFC 5865) */
446         else if (strcasecmp ("va", opt) == 0)
447                 opt_send_qos = 0xB0; /* == 0x2D << 2 */
448         /* - Assured Forwarding (AF, RFC 2597) */
449         else if ((strncasecmp ("af", opt, strlen ("af")) == 0)
450                         && (strlen (opt) == 4))
451         {
452                 uint8_t dscp;
453                 uint8_t class = 0;
454                 uint8_t prec = 0;
456                 /* There are four classes, AF1x, AF2x, AF3x, and AF4x. */
457                 if (opt[2] == '1')
458                         class = 1;
459                 else if (opt[2] == '2')
460                         class = 2;
461                 else if (opt[2] == '3')
462                         class = 3;
463                 else if (opt[2] == '4')
464                         class = 4;
465                 else
466                         usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
468                 /* In each class, there are three precedences, AFx1, AFx2, and AFx3 */
469                 if (opt[3] == '1')
470                         prec = 1;
471                 else if (opt[3] == '2')
472                         prec = 2;
473                 else if (opt[3] == '3')
474                         prec = 3;
475                 else
476                         usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
478                 dscp = (8 * class) + (2 * prec);
479                 /* The lower two bits are used for Explicit Congestion Notification (ECN) */
480                 opt_send_qos = dscp << 2;
481         }
482         /* - Class Selector (CS) */
483         else if ((strncasecmp ("cs", opt, strlen ("cs")) == 0)
484                         && (strlen (opt) == 3))
485         {
486                 uint8_t class;
488                 if ((opt[2] < '0') || (opt[2] > '7'))
489                         usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
491                 /* Not exactly legal by the C standard, but I don't know of any
492                  * system not supporting this hack. */
493                 class = ((uint8_t) opt[2]) - ((uint8_t) '0');
494                 opt_send_qos = class << 5;
495         }
496         /* Type of Service (RFC 1349) */
497         else if (strcasecmp ("lowdelay", opt) == 0)
498                 opt_send_qos = IPTOS_LOWDELAY;
499         else if (strcasecmp ("throughput", opt) == 0)
500                 opt_send_qos = IPTOS_THROUGHPUT;
501         else if (strcasecmp ("reliability", opt) == 0)
502                 opt_send_qos = IPTOS_RELIABILITY;
503         else if (strcasecmp ("mincost", opt) == 0)
504                 opt_send_qos = IPTOS_MINCOST;
505         /* Numeric value */
506         else
507         {
508                 unsigned long value;
509                 char *endptr;
511                 errno = 0;
512                 endptr = NULL;
513                 value = strtoul (opt, &endptr, /* base = */ 0);
514                 if ((errno != 0) || (endptr == opt)
515                                 || (endptr == NULL) || (*endptr != 0)
516                                 || (value > 0xff))
517                         usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
518                 
519                 opt_send_qos = (uint8_t) value;
520         }
522         return (0);
523 } /* }}} int set_opt_send_qos */
525 static char *format_qos (uint8_t qos, char *buffer, size_t buffer_size) /* {{{ */
527         uint8_t dscp;
528         uint8_t ecn;
529         char *dscp_str;
530         char *ecn_str;
532         dscp = qos >> 2;
533         ecn = qos & 0x03;
535         switch (dscp)
536         {
537                 case 0x00: dscp_str = "be";  break;
538                 case 0x2e: dscp_str = "ef";  break;
539                 case 0x2d: dscp_str = "va";  break;
540                 case 0x0a: dscp_str = "af11"; break;
541                 case 0x0c: dscp_str = "af12"; break;
542                 case 0x0e: dscp_str = "af13"; break;
543                 case 0x12: dscp_str = "af21"; break;
544                 case 0x14: dscp_str = "af22"; break;
545                 case 0x16: dscp_str = "af23"; break;
546                 case 0x1a: dscp_str = "af31"; break;
547                 case 0x1c: dscp_str = "af32"; break;
548                 case 0x1e: dscp_str = "af33"; break;
549                 case 0x22: dscp_str = "af41"; break;
550                 case 0x24: dscp_str = "af42"; break;
551                 case 0x26: dscp_str = "af43"; break;
552                 case 0x08: dscp_str = "cs1";  break;
553                 case 0x10: dscp_str = "cs2";  break;
554                 case 0x18: dscp_str = "cs3";  break;
555                 case 0x20: dscp_str = "cs4";  break;
556                 case 0x28: dscp_str = "cs5";  break;
557                 case 0x30: dscp_str = "cs6";  break;
558                 case 0x38: dscp_str = "cs7";  break;
559                 default:   dscp_str = NULL;
560         }
562         switch (ecn)
563         {
564                 case 0x01: ecn_str = ",ecn(1)"; break;
565                 case 0x02: ecn_str = ",ecn(0)"; break;
566                 case 0x03: ecn_str = ",ce"; break;
567                 default:   ecn_str = "";
568         }
570         if (dscp_str == NULL)
571                 snprintf (buffer, buffer_size, "0x%02x%s", dscp, ecn_str);
572         else
573                 snprintf (buffer, buffer_size, "%s%s", dscp_str, ecn_str);
574         buffer[buffer_size - 1] = 0;
576         return (buffer);
577 } /* }}} char *format_qos */
579 static int read_options (int argc, char **argv) /* {{{ */
581         int optchar;
583         while (1)
584         {
585                 optchar = getopt (argc, argv, "46c:hi:I:t:Q:f:D:Z:P:"
586 #if USE_NCURSES
587                                 "uU"
588 #endif
589                                 );
591                 if (optchar == -1)
592                         break;
594                 switch (optchar)
595                 {
596                         case '4':
597                         case '6':
598                                 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
599                                 break;
601                         case 'c':
602                                 {
603                                         int new_count;
604                                         new_count = atoi (optarg);
605                                         if (new_count > 0)
606                                         {
607                                                 opt_count = new_count;
609                                                 if ((opt_percentile < 0.0) && (opt_count < 20))
610                                                         opt_percentile = 100.0 * (opt_count - 1) / opt_count;
611                                         }
612                                         else
613                                                 fprintf(stderr, "Ignoring invalid count: %s\n",
614                                                                 optarg);
615                                 }
616                                 break;
618                         case 'f':
619                                 {
620                                         if (opt_filename != NULL)
621                                                 free (opt_filename);
622                                         opt_filename = strdup (optarg);
623                                 }
624                                 break;
626                         case 'i':
627                                 {
628                                         double new_interval;
629                                         new_interval = atof (optarg);
630                                         if (new_interval < 0.001)
631                                                 fprintf (stderr, "Ignoring invalid interval: %s\n",
632                                                                 optarg);
633                                         else
634                                                 opt_interval = new_interval;
635                                 }
636                                 break;
638                         case 'I':
639                                 {
640                                         if (opt_srcaddr != NULL)
641                                                 free (opt_srcaddr);
642                                         opt_srcaddr = strdup (optarg);
643                                 }
644                                 break;
646                         case 'D':
647                                 opt_device = optarg;
648                                 break;
650                         case 't':
651                         {
652                                 int new_send_ttl;
653                                 new_send_ttl = atoi (optarg);
654                                 if ((new_send_ttl > 0) && (new_send_ttl < 256))
655                                         opt_send_ttl = new_send_ttl;
656                                 else
657                                         fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
658                                                         optarg);
659                                 break;
660                         }
662                         case 'Q':
663                                 set_opt_send_qos (optarg);
664                                 break;
666                         case 'P':
667                                 {
668                                         double new_percentile;
669                                         new_percentile = atof (optarg);
670                                         if (isnan (new_percentile)
671                                                         || (new_percentile < 0.1)
672                                                         || (new_percentile > 100.0))
673                                                 fprintf (stderr, "Ignoring invalid percentile: %s\n",
674                                                                 optarg);
675                                         else
676                                                 opt_percentile = new_percentile;
677                                 }
678                                 break;
680 #if USE_NCURSES
681                         case 'u':
682                                 opt_utf8 = 2;
683                                 break;
684                         case 'U':
685                                 opt_utf8 = 1;
686                                 break;
687 #endif
689                         case 'Z':
690                         {
691                                 char *endptr = NULL;
692                                 double tmp;
694                                 errno = 0;
695                                 tmp = strtod (optarg, &endptr);
696                                 if ((errno != 0) || (endptr == NULL) || (*endptr != 0) || (tmp < 0.0) || (tmp > 100.0))
697                                 {
698                                         fprintf (stderr, "Ignoring invalid -Z argument: %s\n", optarg);
699                                         fprintf (stderr, "The \"-Z\" option requires a numeric argument between 0 and 100.\n");
700                                 }
701                                 else
702                                         opt_exit_status_threshold = tmp / 100.0;
704                                 break;
705                         }
707                         case 'h':
708                                 usage_exit (argv[0], 0);
709                                 break;
710                         default:
711                                 usage_exit (argv[0], 1);
712                 }
713         }
715         if (opt_percentile <= 0.0)
716                 opt_percentile = OPING_DEFAULT_PERCENTILE;
718         return (optind);
719 } /* }}} read_options */
721 static void time_normalize (struct timespec *ts) /* {{{ */
723         while (ts->tv_nsec < 0)
724         {
725                 if (ts->tv_sec == 0)
726                 {
727                         ts->tv_nsec = 0;
728                         return;
729                 }
731                 ts->tv_sec  -= 1;
732                 ts->tv_nsec += 1000000000;
733         }
735         while (ts->tv_nsec >= 1000000000)
736         {
737                 ts->tv_sec  += 1;
738                 ts->tv_nsec -= 1000000000;
739         }
740 } /* }}} void time_normalize */
742 static void time_calc (struct timespec *ts_dest, /* {{{ */
743                 const struct timespec *ts_int,
744                 const struct timeval  *tv_begin,
745                 const struct timeval  *tv_end)
747         ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
748         ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
749         time_normalize (ts_dest);
751         /* Assure that `(begin + interval) > end'.
752          * This may seem overly complicated, but `tv_sec' is of type `time_t'
753          * which may be `unsigned. *sigh* */
754         if ((tv_end->tv_sec > ts_dest->tv_sec)
755                         || ((tv_end->tv_sec == ts_dest->tv_sec)
756                                 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
757         {
758                 ts_dest->tv_sec  = 0;
759                 ts_dest->tv_nsec = 0;
760                 return;
761         }
763         ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
764         ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
765         time_normalize (ts_dest);
766 } /* }}} void time_calc */
768 #if USE_NCURSES
769 static _Bool has_utf8() /* {{{ */
771 # if HAVE_NCURSESW_NCURSES_H
772         if (!opt_utf8)
773         {
774                 /* Automatically determine */
775                 if (strcasecmp ("UTF-8", nl_langinfo (CODESET)) == 0)
776                         opt_utf8 = 2;
777                 else
778                         opt_utf8 = 1;
779         }
780         return ((_Bool) (opt_utf8 - 1));
781 # else
782         return (0);
783 # endif
784 } /* }}} _Bool has_utf8 */
786 static int update_boxplot (ping_context_t *ctx) /* {{{ */
788         uint32_t *accumulated;
789         double *ratios;
790         uint32_t num;
791         size_t i;
792         size_t x_max;
793         size_t x;
795         x_max = (size_t) getmaxx (ctx->window);
796         if (x_max <= 4)
797                 return (EINVAL);
798         x_max -= 4;
800         accumulated = calloc (x_max, sizeof (*accumulated));
801         ratios = calloc (x_max, sizeof (*ratios));
803         /* Downsample */
804         for (i = 0; i < ctx->latency_histogram_size; i++)
805         {
806                 x = i * x_max / ctx->latency_histogram_size;
807                 accumulated[x] += ctx->latency_histogram[i];
808         }
810         /* Sum */
811         for (x = 1; x < x_max; x++)
812                 accumulated[x] += accumulated[x - 1];
814         num = accumulated[x_max - 1];
816         /* Calculate ratios */
817         for (x = 0; x < x_max; x++)
818                 ratios[x] = ((double) accumulated[x]) / ((double) num);
820         for (x = 0; x < x_max; x++)
821         {
822                 int symbol = ' ';
823                 _Bool reverse = 0;
825                 if (x == 0)
826                 {
827                         if (ratios[x] >= 0.5)
828                         {
829                                 symbol = BOXPLOT_MEDIAN;
830                                 reverse = 1;
831                         }
832                         else if (ratios[x] > 0.25)
833                         {
834                                 symbol = BOXPLOT_BOX;
835                                 reverse = 1;
836                         }
837                         else if (ratios[x] > 0.025)
838                                 symbol = BOXPLOT_WHISKER_BAR;
839                         else
840                                 symbol = ' '; /* NOP */
841                 }
842                 else /* (x != 0) */
843                 {
844                         if ((ratios[x - 1] < 0.5) && (ratios[x] >= 0.5))
845                         {
846                                 symbol = BOXPLOT_MEDIAN;
847                                 reverse = 1;
848                         }
849                         else if (((ratios[x] >= 0.25) && (ratios[x] <= 0.75))
850                                         || ((ratios[x - 1] < 0.75) && (ratios[x] > 0.75)))
851                         {
852                                 symbol = BOXPLOT_BOX;
853                                 reverse = 1;
854                         }
855                         else if ((ratios[x] < 0.5) && (ratios[x] >= 0.025))
856                         {
857                                 if (ratios[x - 1] < 0.025)
858                                         symbol = BOXPLOT_WHISKER_LEFT_END;
859                                 else
860                                         symbol = BOXPLOT_WHISKER_BAR;
861                         }
862                         else if ((ratios[x] > .5) && (ratios[x] < 0.975))
863                         {
864                                 symbol = BOXPLOT_WHISKER_BAR;
865                         }
866                         else if ((ratios[x] >= 0.975) && (ratios[x - 1] < 0.975))
867                                 symbol = BOXPLOT_WHISKER_RIGHT_END;
868                 }
870                 if (reverse)
871                         wattron (ctx->window, A_REVERSE);
872                 mvwaddch (ctx->window, /* y = */ 3, /* x = */ (int) (x + 2), symbol);
873                 // mvwprintw (ctx->window, /* y = */ 3, /* x = */ (int) (x + 2), symbol);
874                 if (reverse)
875                         wattroff (ctx->window, A_REVERSE);
876         }
878         free (ratios);
879         free (accumulated);
880         return (0);
881 } /* }}} int update_boxplot */
883 static int update_prettyping_graph (ping_context_t *ctx, /* {{{ */
884                 double latency, unsigned int sequence)
886         int color = OPING_RED;
887         char const *symbol = "!";
888         int symbolc = '!';
890         int x_max;
891         int x_pos;
893         x_max = getmaxx (ctx->window);
894         x_pos = ((sequence - 1) % (x_max - 4)) + 2;
896         if (latency >= 0.0)
897         {
898                 double ratio;
900                 size_t symbols_num = hist_symbols_acs_num;
901                 size_t colors_num = 1;
903                 size_t index_symbols;
904                 size_t index_colors;
905                 size_t intensity;
907                 /* latency is in milliseconds, opt_interval is in seconds. */
908                 ratio = (latency * 0.001) / opt_interval;
909                 if (ratio > 1) {
910                         ratio = 1.0;
911                 }
913                 if (has_utf8 ())
914                         symbols_num = hist_symbols_utf8_num;
916                 if (has_colors () == TRUE)
917                         colors_num = hist_colors_num;
919                 intensity = (size_t) (ratio * ((double) (symbols_num * colors_num)));
920                 if (intensity >= (symbols_num * colors_num))
921                         intensity = (symbols_num * colors_num) - 1;
923                 index_symbols = intensity % symbols_num;
924                 assert (index_symbols < symbols_num);
926                 index_colors = intensity / symbols_num;
927                 assert (index_colors < colors_num);
929                 if (has_utf8())
930                 {
931                         color = hist_colors_utf8[index_colors];
932                         symbol = hist_symbols_utf8[index_symbols];
933                 }
934                 else
935                 {
936                         color = hist_colors_acs[index_colors];
937                         symbolc = hist_symbols_acs[index_symbols] | A_ALTCHARSET;
938                 }
939         }
940         else /* if (!(latency >= 0.0)) */
941                 wattron (ctx->window, A_BOLD);
943         if (has_colors () == TRUE)
944                 wattron (ctx->window, COLOR_PAIR(color));
946         if (has_utf8())
947                 mvwprintw (ctx->window, /* y = */ 3, /* x = */ x_pos, symbol);
948         else
949                 mvwaddch (ctx->window, /* y = */ 3, /* x = */ x_pos, symbolc);
951         if (has_colors () == TRUE)
952                 wattroff (ctx->window, COLOR_PAIR(color));
954         /* Use negation here to handle NaN correctly. */
955         if (!(latency >= 0.0))
956                 wattroff (ctx->window, A_BOLD);
958         wprintw (ctx->window, " ");
959         return (0);
960 } /* }}} int update_prettyping_graph */
962 static int update_stats_from_context (ping_context_t *ctx, pingobj_iter_t *iter) /* {{{ */
964         double latency = -1.0;
965         size_t buffer_len = sizeof (latency);
967         ping_iterator_get_info (iter, PING_INFO_LATENCY,
968                         &latency, &buffer_len);
970         unsigned int sequence = 0;
971         buffer_len = sizeof (sequence);
972         ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
973                         &sequence, &buffer_len);
976         if ((ctx == NULL) || (ctx->window == NULL))
977                 return (EINVAL);
979         /* werase (ctx->window); */
981         box (ctx->window, 0, 0);
982         wattron (ctx->window, A_BOLD);
983         mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
984                         " %s ", ctx->host);
985         wattroff (ctx->window, A_BOLD);
986         wprintw (ctx->window, "ping statistics ");
987         mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
988                         "%i packets transmitted, %i received, %.2f%% packet "
989                         "loss, time %.1fms",
990                         ctx->req_sent, ctx->req_rcvd,
991                         context_get_packet_loss (ctx),
992                         ctx->latency_total);
993         if (ctx->req_rcvd != 0)
994         {
995                 double average;
996                 double deviation;
997                 double percentile;
999                 average = context_get_average (ctx);
1000                 deviation = context_get_stddev (ctx);
1001                 percentile = context_get_percentile (ctx, opt_percentile);
1003                 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
1004                                 "rtt min/avg/%.0f%%/max/sdev = "
1005                                 "%.3f/%.3f/%.0f/%.3f/%.3f ms\n",
1006                                 opt_percentile,
1007                                 ctx->latency_min,
1008                                 average,
1009                                 percentile,
1010                                 ctx->latency_max,
1011                                 deviation);
1012         }
1014         update_prettyping_graph (ctx, latency, sequence);
1016         wrefresh (ctx->window);
1018         return (0);
1019 } /* }}} int update_stats_from_context */
1021 static int on_resize (pingobj_t *ping) /* {{{ */
1023         pingobj_iter_t *iter;
1024         int width = 0;
1025         int height = 0;
1026         int main_win_height;
1028         getmaxyx (stdscr, height, width);
1029         if ((height < 1) || (width < 1))
1030                 return (EINVAL);
1032         main_win_height = height - (5 * host_num);
1033         wresize (main_win, main_win_height, /* width = */ width);
1034         /* Allow scrolling */
1035         scrollok (main_win, TRUE);
1036         /* wsetscrreg (main_win, 0, main_win_height - 1); */
1037         /* Allow hardware accelerated scrolling. */
1038         idlok (main_win, TRUE);
1039         wrefresh (main_win);
1041         for (iter = ping_iterator_get (ping);
1042                         iter != NULL;
1043                         iter = ping_iterator_next (iter))
1044         {
1045                 ping_context_t *context;
1047                 context = ping_iterator_get_context (iter);
1048                 if (context == NULL)
1049                         continue;
1051                 if (context->window != NULL)
1052                 {
1053                         delwin (context->window);
1054                         context->window = NULL;
1055                 }
1056                 context->window = newwin (/* height = */ 5,
1057                                 /* width = */ width,
1058                                 /* y = */ main_win_height + (5 * context->index),
1059                                 /* x = */ 0);
1060         }
1062         return (0);
1063 } /* }}} */
1065 static int check_resize (pingobj_t *ping) /* {{{ */
1067         int need_resize = 0;
1069         while (42)
1070         {
1071                 int key = wgetch (stdscr);
1072                 if (key == ERR)
1073                         break;
1074                 else if (key == KEY_RESIZE)
1075                         need_resize = 1;
1076         }
1078         if (need_resize)
1079                 return (on_resize (ping));
1080         else
1081                 return (0);
1082 } /* }}} int check_resize */
1084 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
1086         pingobj_iter_t *iter;
1087         int width = 0;
1088         int height = 0;
1089         int main_win_height;
1091         initscr ();
1092         cbreak ();
1093         noecho ();
1094         nodelay (stdscr, TRUE);
1096         getmaxyx (stdscr, height, width);
1097         if ((height < 1) || (width < 1))
1098                 return (EINVAL);
1100         if (has_colors () == TRUE)
1101         {
1102                 start_color ();
1103                 init_pair (OPING_GREEN,  COLOR_GREEN,  /* default = */ 0);
1104                 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
1105                 init_pair (OPING_RED,    COLOR_RED,    /* default = */ 0);
1106                 init_pair (OPING_GREEN_HIST,  COLOR_GREEN,  COLOR_BLACK);
1107                 init_pair (OPING_YELLOW_HIST, COLOR_YELLOW, COLOR_GREEN);
1108                 init_pair (OPING_RED_HIST,    COLOR_RED,    COLOR_YELLOW);
1109         }
1111         main_win_height = height - (5 * host_num);
1112         main_win = newwin (/* height = */ main_win_height,
1113                         /* width = */ width,
1114                         /* y = */ 0, /* x = */ 0);
1115         /* Allow scrolling */
1116         scrollok (main_win, TRUE);
1117         /* wsetscrreg (main_win, 0, main_win_height - 1); */
1118         /* Allow hardware accelerated scrolling. */
1119         idlok (main_win, TRUE);
1120         wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
1121         wrefresh (main_win);
1123         for (iter = ping_iterator_get (ping);
1124                         iter != NULL;
1125                         iter = ping_iterator_next (iter))
1126         {
1127                 ping_context_t *context;
1129                 context = ping_iterator_get_context (iter);
1130                 if (context == NULL)
1131                         continue;
1133                 if (context->window != NULL)
1134                 {
1135                         delwin (context->window);
1136                         context->window = NULL;
1137                 }
1138                 context->window = newwin (/* height = */ 5,
1139                                 /* width = */ width,
1140                                 /* y = */ main_win_height + (5 * context->index),
1141                                 /* x = */ 0);
1142         }
1145         /* Don't know what good this does exactly, but without this code
1146          * "check_resize" will be called right after startup and *somehow*
1147          * this leads to display errors. If we purge all initial characters
1148          * here, the problem goes away. "wgetch" is non-blocking due to
1149          * "nodelay" (see above). */
1150         while (wgetch (stdscr) != ERR)
1151         {
1152                 /* eat up characters */;
1153         }
1155         return (0);
1156 } /* }}} int pre_loop_hook */
1158 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
1160         return (check_resize (ping));
1161 } /* }}} int pre_sleep_hook */
1163 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
1165         return (check_resize (ping));
1166 } /* }}} int pre_sleep_hook */
1167 #else /* if !USE_NCURSES */
1168 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
1170         pingobj_iter_t *iter;
1172         for (iter = ping_iterator_get (ping);
1173                         iter != NULL;
1174                         iter = ping_iterator_next (iter))
1175         {
1176                 ping_context_t *ctx;
1177                 size_t buffer_size;
1179                 ctx = ping_iterator_get_context (iter);
1180                 if (ctx == NULL)
1181                         continue;
1183                 buffer_size = 0;
1184                 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
1186                 printf ("PING %s (%s) %zu bytes of data.\n",
1187                                 ctx->host, ctx->addr, buffer_size);
1188         }
1190         return (0);
1191 } /* }}} int pre_loop_hook */
1193 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
1195         fflush (stdout);
1197         return (0);
1198 } /* }}} int pre_sleep_hook */
1200 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
1202         return (0);
1203 } /* }}} int post_sleep_hook */
1204 #endif
1206 static void update_context (ping_context_t *context, double latency) /* {{{ */
1208         size_t bucket;
1210         context->req_rcvd++;
1211         context->latency_total += latency;
1212         context->latency_total_square += (latency * latency);
1214         if ((context->latency_max < 0.0) || (context->latency_max < latency))
1215                 context->latency_max = latency;
1216         if ((context->latency_min < 0.0) || (context->latency_min > latency))
1217                 context->latency_min = latency;
1219         if (context->latency_histogram == NULL)
1220                 return;
1222         /* latency is in ms, opt_interval is in s. */
1223         bucket = (size_t) ((latency * (context->latency_histogram_size - 1))
1224                         / (1000.0 * opt_interval));
1225         if (bucket >= context->latency_histogram_size)
1226                 bucket = context->latency_histogram_size - 1;
1227         context->latency_histogram[bucket]++;
1228 } /* }}} void update_context */
1230 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
1231                 __attribute__((unused)) int index)
1233         double          latency;
1234         unsigned int    sequence;
1235         int             recv_ttl;
1236         uint8_t         recv_qos;
1237         char            recv_qos_str[16];
1238         size_t          buffer_len;
1239         size_t          data_len;
1240         ping_context_t *context;
1242         latency = -1.0;
1243         buffer_len = sizeof (latency);
1244         ping_iterator_get_info (iter, PING_INFO_LATENCY,
1245                         &latency, &buffer_len);
1247         sequence = 0;
1248         buffer_len = sizeof (sequence);
1249         ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
1250                         &sequence, &buffer_len);
1252         recv_ttl = -1;
1253         buffer_len = sizeof (recv_ttl);
1254         ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
1255                         &recv_ttl, &buffer_len);
1257         recv_qos = 0;
1258         buffer_len = sizeof (recv_qos);
1259         ping_iterator_get_info (iter, PING_INFO_RECV_QOS,
1260                         &recv_qos, &buffer_len);
1262         data_len = 0;
1263         ping_iterator_get_info (iter, PING_INFO_DATA,
1264                         NULL, &data_len);
1266         context = (ping_context_t *) ping_iterator_get_context (iter);
1268 #if USE_NCURSES
1269 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
1270 #else
1271 # define HOST_PRINTF(...) printf(__VA_ARGS__)
1272 #endif
1274         context->req_sent++;
1275         if (latency > 0.0)
1276         {
1277                 update_context (context, latency);
1279 #if USE_NCURSES
1280                 if (has_colors () == TRUE)
1281                 {
1282                         int color = OPING_GREEN;
1283                         double average = context_get_average (context);
1284                         double stddev = context_get_stddev (context);
1286                         if ((latency < (average - (2 * stddev)))
1287                                         || (latency > (average + (2 * stddev))))
1288                                 color = OPING_RED;
1289                         else if ((latency < (average - stddev))
1290                                         || (latency > (average + stddev)))
1291                                 color = OPING_YELLOW;
1293                         HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
1294                                         data_len, context->host, context->addr,
1295                                         sequence, recv_ttl,
1296                                         format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1297                         if ((recv_qos != 0) || (opt_send_qos != 0))
1298                         {
1299                                 HOST_PRINTF ("qos=%s ",
1300                                                 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1301                         }
1302                         HOST_PRINTF ("time=");
1303                         wattron (main_win, COLOR_PAIR(color));
1304                         HOST_PRINTF ("%.2f", latency);
1305                         wattroff (main_win, COLOR_PAIR(color));
1306                         HOST_PRINTF (" ms\n");
1307                 }
1308                 else
1309                 {
1310 #endif
1311                 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
1312                                 data_len,
1313                                 context->host, context->addr,
1314                                 sequence, recv_ttl);
1315                 if ((recv_qos != 0) || (opt_send_qos != 0))
1316                 {
1317                         HOST_PRINTF ("qos=%s ",
1318                                         format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1319                 }
1320                 HOST_PRINTF ("time=%.2f ms\n", latency);
1321 #if USE_NCURSES
1322                 }
1323 #endif
1324         }
1325         else
1326         {
1327 #if USE_NCURSES
1328                 if (has_colors () == TRUE)
1329                 {
1330                         HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
1331                                         context->host, context->addr,
1332                                         sequence);
1333                         wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
1334                         HOST_PRINTF ("timeout");
1335                         wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
1336                         HOST_PRINTF ("\n");
1337                 }
1338                 else
1339                 {
1340 #endif
1341                 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
1342                                 context->host, context->addr,
1343                                 sequence);
1344 #if USE_NCURSES
1345                 }
1346 #endif
1347         }
1349 #if USE_NCURSES
1350         update_stats_from_context (context, iter);
1351         wrefresh (main_win);
1352 #endif
1353 } /* }}} void update_host_hook */
1355 /* Prints statistics for each host, cleans up the contexts and returns the
1356  * number of hosts which failed to return more than the fraction
1357  * opt_exit_status_threshold of pings. */
1358 static int post_loop_hook (pingobj_t *ping) /* {{{ */
1360         pingobj_iter_t *iter;
1361         int failure_count = 0;
1363 #if USE_NCURSES
1364         endwin ();
1365 #endif
1367         for (iter = ping_iterator_get (ping);
1368                         iter != NULL;
1369                         iter = ping_iterator_next (iter))
1370         {
1371                 ping_context_t *context;
1373                 context = ping_iterator_get_context (iter);
1375                 printf ("\n--- %s ping statistics ---\n"
1376                                 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
1377                                 context->host, context->req_sent, context->req_rcvd,
1378                                 context_get_packet_loss (context),
1379                                 context->latency_total);
1381                 {
1382                         double pct_failed = 1.0 - (((double) context->req_rcvd)
1383                                         / ((double) context->req_sent));
1384                         if (pct_failed > opt_exit_status_threshold)
1385                                 failure_count++;
1386                 }
1388                 if (context->req_rcvd != 0)
1389                 {
1390                         double average;
1391                         double deviation;
1392                         double percentile;
1394                         average = context_get_average (context);
1395                         deviation = context_get_stddev (context);
1396                         percentile = context_get_percentile (context, opt_percentile);
1398                         printf ("rtt min/avg/%.0f%%/max/sdev = "
1399                                         "%.3f/%.3f/%.0f/%.3f/%.3f ms\n",
1400                                         opt_percentile,
1401                                         context->latency_min,
1402                                         average,
1403                                         percentile,
1404                                         context->latency_max,
1405                                         deviation);
1406                 }
1408                 ping_iterator_set_context (iter, NULL);
1409                 context_destroy (context);
1410         }
1412         return (failure_count);
1413 } /* }}} int post_loop_hook */
1415 int main (int argc, char **argv) /* {{{ */
1417         pingobj_t      *ping;
1418         pingobj_iter_t *iter;
1420         struct sigaction sigint_action;
1422         struct timeval  tv_begin;
1423         struct timeval  tv_end;
1424         struct timespec ts_wait;
1425         struct timespec ts_int;
1427         int optind;
1428         int i;
1429         int status;
1430 #if _POSIX_SAVED_IDS
1431         uid_t saved_set_uid;
1433         /* Save the old effective user id */
1434         saved_set_uid = geteuid ();
1435         /* Set the effective user ID to the real user ID without changing the
1436          * saved set-user ID */
1437         status = seteuid (getuid ());
1438         if (status != 0)
1439         {
1440                 fprintf (stderr, "Temporarily dropping privileges "
1441                                 "failed: %s\n", strerror (errno));
1442                 exit (EXIT_FAILURE);
1443         }
1444 #endif
1446         setlocale(LC_ALL, "");
1447         optind = read_options (argc, argv);
1449 #if !_POSIX_SAVED_IDS
1450         /* Cannot temporarily drop privileges -> reject every file but "-". */
1451         if ((opt_filename != NULL)
1452                         && (strcmp ("-", opt_filename) != 0)
1453                         && (getuid () != geteuid ()))
1454         {
1455                 fprintf (stderr, "Your real and effective user IDs don't "
1456                                 "match. Reading from a file (option '-f')\n"
1457                                 "is therefore too risky. You can still read "
1458                                 "from STDIN using '-f -' if you like.\n"
1459                                 "Sorry.\n");
1460                 exit (EXIT_FAILURE);
1461         }
1462 #endif
1464         if ((optind >= argc) && (opt_filename == NULL)) {
1465                 usage_exit (argv[0], 1);
1466         }
1468         if ((ping = ping_construct ()) == NULL)
1469         {
1470                 fprintf (stderr, "ping_construct failed\n");
1471                 return (1);
1472         }
1474         if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
1475         {
1476                 fprintf (stderr, "Setting TTL to %i failed: %s\n",
1477                                 opt_send_ttl, ping_get_error (ping));
1478         }
1480         if (ping_setopt (ping, PING_OPT_QOS, &opt_send_qos) != 0)
1481         {
1482                 fprintf (stderr, "Setting TOS to %i failed: %s\n",
1483                                 opt_send_qos, ping_get_error (ping));
1484         }
1486         {
1487                 double temp_sec;
1488                 double temp_nsec;
1490                 temp_nsec = modf (opt_interval, &temp_sec);
1491                 ts_int.tv_sec  = (time_t) temp_sec;
1492                 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
1494                 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
1495         }
1497         if (opt_addrfamily != PING_DEF_AF)
1498                 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
1500         if (opt_srcaddr != NULL)
1501         {
1502                 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
1503                 {
1504                         fprintf (stderr, "Setting source address failed: %s\n",
1505                                         ping_get_error (ping));
1506                 }
1507         }
1509         if (opt_device != NULL)
1510         {
1511                 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
1512                 {
1513                         fprintf (stderr, "Setting device failed: %s\n",
1514                                         ping_get_error (ping));
1515                 }
1516         }
1518         if (opt_filename != NULL)
1519         {
1520                 FILE *infile;
1521                 char line[256];
1522                 char host[256];
1524                 if (strcmp (opt_filename, "-") == 0)
1525                         /* Open STDIN */
1526                         infile = fdopen(0, "r");
1527                 else
1528                         infile = fopen(opt_filename, "r");
1530                 if (infile == NULL)
1531                 {
1532                         fprintf (stderr, "Opening %s failed: %s\n",
1533                                         (strcmp (opt_filename, "-") == 0)
1534                                         ? "STDIN" : opt_filename,
1535                                         strerror(errno));
1536                         return (1);
1537                 }
1539 #if _POSIX_SAVED_IDS
1540                 /* Regain privileges */
1541                 status = seteuid (saved_set_uid);
1542                 if (status != 0)
1543                 {
1544                         fprintf (stderr, "Temporarily re-gaining privileges "
1545                                         "failed: %s\n", strerror (errno));
1546                         exit (EXIT_FAILURE);
1547                 }
1548 #endif
1550                 while (fgets(line, sizeof(line), infile))
1551                 {
1552                         /* Strip whitespace */
1553                         if (sscanf(line, "%s", host) != 1)
1554                                 continue;
1556                         if ((host[0] == 0) || (host[0] == '#'))
1557                                 continue;
1559                         if (ping_host_add(ping, host) < 0)
1560                         {
1561                                 const char *errmsg = ping_get_error (ping);
1563                                 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
1564                                 continue;
1565                         }
1566                         else
1567                         {
1568                                 host_num++;
1569                         }
1570                 }
1572 #if _POSIX_SAVED_IDS
1573                 /* Drop privileges */
1574                 status = seteuid (getuid ());
1575                 if (status != 0)
1576                 {
1577                         fprintf (stderr, "Temporarily dropping privileges "
1578                                         "failed: %s\n", strerror (errno));
1579                         exit (EXIT_FAILURE);
1580                 }
1581 #endif
1583                 fclose(infile);
1584         }
1586 #if _POSIX_SAVED_IDS
1587         /* Regain privileges */
1588         status = seteuid (saved_set_uid);
1589         if (status != 0)
1590         {
1591                 fprintf (stderr, "Temporarily re-gaining privileges "
1592                                 "failed: %s\n", strerror (errno));
1593                 exit (EXIT_FAILURE);
1594         }
1595 #endif
1597         for (i = optind; i < argc; i++)
1598         {
1599                 if (ping_host_add (ping, argv[i]) < 0)
1600                 {
1601                         const char *errmsg = ping_get_error (ping);
1603                         fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
1604                         continue;
1605                 }
1606                 else
1607                 {
1608                         host_num++;
1609                 }
1610         }
1612         /* Permanently drop root privileges if we're setuid-root. */
1613         status = setuid (getuid ());
1614         if (status != 0)
1615         {
1616                 fprintf (stderr, "Dropping privileges failed: %s\n",
1617                                 strerror (errno));
1618                 exit (EXIT_FAILURE);
1619         }
1621 #if _POSIX_SAVED_IDS
1622         saved_set_uid = (uid_t) -1;
1623 #endif
1625         ping_initialize_contexts (ping);
1627         if (i == 0)
1628                 return (1);
1630         memset (&sigint_action, '\0', sizeof (sigint_action));
1631         sigint_action.sa_handler = sigint_handler;
1632         if (sigaction (SIGINT, &sigint_action, NULL) < 0)
1633         {
1634                 perror ("sigaction");
1635                 return (1);
1636         }
1638         pre_loop_hook (ping);
1640         while (opt_count != 0)
1641         {
1642                 int index;
1643                 int status;
1645                 if (gettimeofday (&tv_begin, NULL) < 0)
1646                 {
1647                         perror ("gettimeofday");
1648                         return (1);
1649                 }
1651                 status = ping_send (ping);
1652                 if (status == -EINTR)
1653                 {
1654                         continue;
1655                 }
1656                 else if (status < 0)
1657                 {
1658                         fprintf (stderr, "ping_send failed: %s\n",
1659                                         ping_get_error (ping));
1660                         return (1);
1661                 }
1663                 index = 0;
1664                 for (iter = ping_iterator_get (ping);
1665                                 iter != NULL;
1666                                 iter = ping_iterator_next (iter))
1667                 {
1668                         update_host_hook (iter, index);
1669                         index++;
1670                 }
1672                 pre_sleep_hook (ping);
1674                 /* Don't sleep in the last iteration */
1675                 if (opt_count == 1)
1676                         break;
1678                 if (gettimeofday (&tv_end, NULL) < 0)
1679                 {
1680                         perror ("gettimeofday");
1681                         return (1);
1682                 }
1684                 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1686                 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1687                 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1688                 {
1689                         if (errno == EINTR)
1690                         {
1691                                 continue;
1692                         }
1693                         else
1694                         {
1695                                 perror ("nanosleep");
1696                                 break;
1697                         }
1698                 }
1700                 post_sleep_hook (ping);
1702                 if (opt_count > 0)
1703                         opt_count--;
1704         } /* while (opt_count != 0) */
1706         /* Returns the number of failed hosts according to -Z. */
1707         status = post_loop_hook (ping);
1709         ping_destroy (ping);
1711         if (status == 0)
1712                 exit (EXIT_SUCCESS);
1713         else
1714         {
1715                 if (status > 255)
1716                         status = 255;
1717                 exit (status);
1718         }
1719 } /* }}} int main */
1721 /* vim: set fdm=marker : */