Bump version to 1.7.0; Update ChangeLog.
[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  */
19
20 #if HAVE_CONFIG_H
21 # include <config.h>
22 #endif
23
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 */
35
36 #if HAVE_UNISTD_H
37 # include <unistd.h>
38 #endif
39
40 #if HAVE_MATH_H
41 # include <math.h>
42 #endif
43
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
54
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
64
65 #if HAVE_NETDB_H
66 # include <netdb.h> /* NI_MAXHOST */
67 #endif
68
69 #if HAVE_SIGNAL_H
70 # include <signal.h>
71 #endif
72
73 #if HAVE_SYS_TYPES_H
74 #include <sys/types.h>
75 #endif
76
77 #include <locale.h>
78 #include <langinfo.h>
79
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
84
85 # if HAVE_NCURSESW_NCURSES_H
86 #  include <ncursesw/ncurses.h>
87 # elif HAVE_NCURSES_H
88 #  include <ncurses.h>
89 # endif
90
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
97
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]);
102
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]);
114
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
124
125 #include "oping.h"
126
127 #ifndef _POSIX_SAVED_IDS
128 # define _POSIX_SAVED_IDS 0
129 #endif
130
131 #ifndef IPTOS_MINCOST
132 # define IPTOS_MINCOST 0x02
133 #endif
134
135 /* Remove GNU specific __attribute__ settings when using another compiler */
136 #if !__GNUC__
137 # define __attribute__(x) /**/
138 #endif
139
140 typedef struct ping_context
141 {
142         char host[NI_MAXHOST];
143         char addr[NI_MAXHOST];
144
145         int index;
146         int req_sent;
147         int req_rcvd;
148
149         double latency_min;
150         double latency_max;
151         double latency_total;
152         double latency_total_square;
153
154 #if USE_NCURSES
155         WINDOW *window;
156 #endif
157 } ping_context_t;
158
159 static double  opt_interval   = 1.0;
160 static int     opt_addrfamily = PING_DEF_AF;
161 static char   *opt_srcaddr    = NULL;
162 static char   *opt_device     = NULL;
163 static char   *opt_filename   = NULL;
164 static int     opt_count      = -1;
165 static int     opt_send_ttl   = 64;
166 static uint8_t opt_send_qos   = 0;
167 static double  opt_exit_status_threshold = 1.0;
168 #if USE_NCURSES
169 static int     opt_utf8       = 0;
170 #endif
171
172 static int host_num = 0;
173
174 #if USE_NCURSES
175 static WINDOW *main_win = NULL;
176 #endif
177
178 static void sigint_handler (int signal) /* {{{ */
179 {
180         /* Make compiler happy */
181         signal = 0;
182         /* Exit the loop */
183         opt_count = 0;
184 } /* }}} void sigint_handler */
185
186 static ping_context_t *context_create (void) /* {{{ */
187 {
188         ping_context_t *ret;
189
190         if ((ret = malloc (sizeof (ping_context_t))) == NULL)
191                 return (NULL);
192
193         memset (ret, '\0', sizeof (ping_context_t));
194
195         ret->latency_min   = -1.0;
196         ret->latency_max   = -1.0;
197         ret->latency_total = 0.0;
198         ret->latency_total_square = 0.0;
199
200 #if USE_NCURSES
201         ret->window = NULL;
202 #endif
203
204         return (ret);
205 } /* }}} ping_context_t *context_create */
206
207 static void context_destroy (ping_context_t *context) /* {{{ */
208 {
209         if (context == NULL)
210                 return;
211
212 #if USE_NCURSES
213         if (context->window != NULL)
214         {
215                 delwin (context->window);
216                 context->window = NULL;
217         }
218 #endif
219
220         free (context);
221 } /* }}} void context_destroy */
222
223 static double context_get_average (ping_context_t *ctx) /* {{{ */
224 {
225         double num_total;
226
227         if (ctx == NULL)
228                 return (-1.0);
229
230         if (ctx->req_rcvd < 1)
231                 return (-0.0);
232
233         num_total = (double) ctx->req_rcvd;
234         return (ctx->latency_total / num_total);
235 } /* }}} double context_get_average */
236
237 static double context_get_stddev (ping_context_t *ctx) /* {{{ */
238 {
239         double num_total;
240
241         if (ctx == NULL)
242                 return (-1.0);
243
244         if (ctx->req_rcvd < 1)
245                 return (-0.0);
246         else if (ctx->req_rcvd < 2)
247                 return (0.0);
248
249         num_total = (double) ctx->req_rcvd;
250         return (sqrt (((num_total * ctx->latency_total_square)
251                                         - (ctx->latency_total * ctx->latency_total))
252                                 / (num_total * (num_total - 1.0))));
253 } /* }}} double context_get_stddev */
254
255 static double context_get_packet_loss (const ping_context_t *ctx) /* {{{ */
256 {
257         if (ctx == NULL)
258                 return (-1.0);
259
260         if (ctx->req_sent < 1)
261                 return (0.0);
262
263         return (100.0 * (ctx->req_sent - ctx->req_rcvd)
264                         / ((double) ctx->req_sent));
265 } /* }}} double context_get_packet_loss */
266
267 static int ping_initialize_contexts (pingobj_t *ping) /* {{{ */
268 {
269         pingobj_iter_t *iter;
270         int index;
271
272         if (ping == NULL)
273                 return (EINVAL);
274
275         index = 0;
276         for (iter = ping_iterator_get (ping);
277                         iter != NULL;
278                         iter = ping_iterator_next (iter))
279         {
280                 ping_context_t *context;
281                 size_t buffer_size;
282
283                 context = context_create ();
284                 context->index = index;
285
286                 buffer_size = sizeof (context->host);
287                 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
288
289                 buffer_size = sizeof (context->addr);
290                 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
291
292                 ping_iterator_set_context (iter, (void *) context);
293
294                 index++;
295         }
296
297         return (0);
298 } /* }}} int ping_initialize_contexts */
299
300 static void usage_exit (const char *name, int status) /* {{{ */
301 {
302         fprintf (stderr, "Usage: %s [OPTIONS] "
303                                 "-f filename | host [host [host ...]]\n"
304
305                         "\nAvailable options:\n"
306                         "  -4|-6        force the use of IPv4 or IPv6\n"
307                         "  -c count     number of ICMP packets to send\n"
308                         "  -i interval  interval with which to send ICMP packets\n"
309                         "  -t ttl       time to live for each ICMP packet\n"
310                         "  -Q qos       Quality of Service (QoS) of outgoing packets\n"
311                         "               Use \"-Q help\" for a list of valid options.\n"
312                         "  -I srcaddr   source address\n"
313                         "  -D device    outgoing interface name\n"
314                         "  -f filename  filename to read hosts from\n"
315 #if USE_NCURSES
316                         "  -u / -U      force / disable UTF-8 output\n"
317 #endif
318                         "  -Z percent   Exit with non-zero exit status if more than this percentage of\n"
319                         "               probes timed out. (default: never)\n"
320
321                         "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
322                         "by Florian octo Forster <octo@verplant.org>\n"
323                         "for contributions see `AUTHORS'\n",
324                         name);
325         exit (status);
326 } /* }}} void usage_exit */
327
328 __attribute__((noreturn))
329 static void usage_qos_exit (const char *arg, int status) /* {{{ */
330 {
331         if (arg != 0)
332                 fprintf (stderr, "Invalid QoS argument: \"%s\"\n\n", arg);
333
334         fprintf (stderr, "Valid QoS arguments (option \"-Q\") are:\n"
335                         "\n"
336                         "  Differentiated Services (IPv4 and IPv6, RFC 2474)\n"
337                         "\n"
338                         "    be                     Best Effort (BE, default PHB).\n"
339                         "    ef                     Expedited Forwarding (EF) PHB group (RFC 3246).\n"
340                         "                           (low delay, low loss, low jitter)\n"
341                         "    va                     Voice Admit (VA) DSCP (RFC 5865).\n"
342                         "                           (capacity-admitted traffic)\n"
343                         "    af[1-4][1-3]           Assured Forwarding (AF) PHB group (RFC 2597).\n"
344                         "                           For example: \"af12\" (class 1, precedence 2)\n"
345                         "    cs[0-7]                Class Selector (CS) PHB group (RFC 2474).\n"
346                         "                           For example: \"cs1\" (priority traffic)\n"
347                         "\n"
348                         "  Type of Service (IPv4, RFC 1349, obsolete)\n"
349                         "\n"
350                         "    lowdelay     (%#04x)    minimize delay\n"
351                         "    throughput   (%#04x)    maximize throughput\n"
352                         "    reliability  (%#04x)    maximize reliability\n"
353                         "    mincost      (%#04x)    minimize monetary cost\n"
354                         "\n"
355                         "  Specify manually\n"
356                         "\n"
357                         "    0x00 - 0xff            Hexadecimal numeric specification.\n"
358                         "       0 -  255            Decimal numeric specification.\n"
359                         "\n",
360                         (unsigned int) IPTOS_LOWDELAY,
361                         (unsigned int) IPTOS_THROUGHPUT,
362                         (unsigned int) IPTOS_RELIABILITY,
363                         (unsigned int) IPTOS_MINCOST);
364
365         exit (status);
366 } /* }}} void usage_qos_exit */
367
368 static int set_opt_send_qos (const char *opt) /* {{{ */
369 {
370         if (opt == NULL)
371                 return (EINVAL);
372
373         if (strcasecmp ("help", opt) == 0)
374                 usage_qos_exit (/* arg = */ NULL, /* status = */ EXIT_SUCCESS);
375         /* DiffServ (RFC 2474): */
376         /* - Best effort (BE) */
377         else if (strcasecmp ("be", opt) == 0)
378                 opt_send_qos = 0;
379         /* - Expedited Forwarding (EF, RFC 3246) */
380         else if (strcasecmp ("ef", opt) == 0)
381                 opt_send_qos = 0xB8; /* == 0x2E << 2 */
382         /* - Voice Admit (VA, RFC 5865) */
383         else if (strcasecmp ("va", opt) == 0)
384                 opt_send_qos = 0xB0; /* == 0x2D << 2 */
385         /* - Assured Forwarding (AF, RFC 2597) */
386         else if ((strncasecmp ("af", opt, strlen ("af")) == 0)
387                         && (strlen (opt) == 4))
388         {
389                 uint8_t dscp;
390                 uint8_t class = 0;
391                 uint8_t prec = 0;
392
393                 /* There are four classes, AF1x, AF2x, AF3x, and AF4x. */
394                 if (opt[2] == '1')
395                         class = 1;
396                 else if (opt[2] == '2')
397                         class = 2;
398                 else if (opt[2] == '3')
399                         class = 3;
400                 else if (opt[2] == '4')
401                         class = 4;
402                 else
403                         usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
404
405                 /* In each class, there are three precedences, AFx1, AFx2, and AFx3 */
406                 if (opt[3] == '1')
407                         prec = 1;
408                 else if (opt[3] == '2')
409                         prec = 2;
410                 else if (opt[3] == '3')
411                         prec = 3;
412                 else
413                         usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
414
415                 dscp = (8 * class) + (2 * prec);
416                 /* The lower two bits are used for Explicit Congestion Notification (ECN) */
417                 opt_send_qos = dscp << 2;
418         }
419         /* - Class Selector (CS) */
420         else if ((strncasecmp ("cs", opt, strlen ("cs")) == 0)
421                         && (strlen (opt) == 3))
422         {
423                 uint8_t class;
424
425                 if ((opt[2] < '0') || (opt[2] > '7'))
426                         usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
427
428                 /* Not exactly legal by the C standard, but I don't know of any
429                  * system not supporting this hack. */
430                 class = ((uint8_t) opt[2]) - ((uint8_t) '0');
431                 opt_send_qos = class << 5;
432         }
433         /* Type of Service (RFC 1349) */
434         else if (strcasecmp ("lowdelay", opt) == 0)
435                 opt_send_qos = IPTOS_LOWDELAY;
436         else if (strcasecmp ("throughput", opt) == 0)
437                 opt_send_qos = IPTOS_THROUGHPUT;
438         else if (strcasecmp ("reliability", opt) == 0)
439                 opt_send_qos = IPTOS_RELIABILITY;
440         else if (strcasecmp ("mincost", opt) == 0)
441                 opt_send_qos = IPTOS_MINCOST;
442         /* Numeric value */
443         else
444         {
445                 unsigned long value;
446                 char *endptr;
447
448                 errno = 0;
449                 endptr = NULL;
450                 value = strtoul (opt, &endptr, /* base = */ 0);
451                 if ((errno != 0) || (endptr == opt)
452                                 || (endptr == NULL) || (*endptr != 0)
453                                 || (value > 0xff))
454                         usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
455                 
456                 opt_send_qos = (uint8_t) value;
457         }
458
459         return (0);
460 } /* }}} int set_opt_send_qos */
461
462 static char *format_qos (uint8_t qos, char *buffer, size_t buffer_size) /* {{{ */
463 {
464         uint8_t dscp;
465         uint8_t ecn;
466         char *dscp_str;
467         char *ecn_str;
468
469         dscp = qos >> 2;
470         ecn = qos & 0x03;
471
472         switch (dscp)
473         {
474                 case 0x00: dscp_str = "be";  break;
475                 case 0x2e: dscp_str = "ef";  break;
476                 case 0x2d: dscp_str = "va";  break;
477                 case 0x0a: dscp_str = "af11"; break;
478                 case 0x0c: dscp_str = "af12"; break;
479                 case 0x0e: dscp_str = "af13"; break;
480                 case 0x12: dscp_str = "af21"; break;
481                 case 0x14: dscp_str = "af22"; break;
482                 case 0x16: dscp_str = "af23"; break;
483                 case 0x1a: dscp_str = "af31"; break;
484                 case 0x1c: dscp_str = "af32"; break;
485                 case 0x1e: dscp_str = "af33"; break;
486                 case 0x22: dscp_str = "af41"; break;
487                 case 0x24: dscp_str = "af42"; break;
488                 case 0x26: dscp_str = "af43"; break;
489                 case 0x08: dscp_str = "cs1";  break;
490                 case 0x10: dscp_str = "cs2";  break;
491                 case 0x18: dscp_str = "cs3";  break;
492                 case 0x20: dscp_str = "cs4";  break;
493                 case 0x28: dscp_str = "cs5";  break;
494                 case 0x30: dscp_str = "cs6";  break;
495                 case 0x38: dscp_str = "cs7";  break;
496                 default:   dscp_str = NULL;
497         }
498
499         switch (ecn)
500         {
501                 case 0x01: ecn_str = ",ecn(1)"; break;
502                 case 0x02: ecn_str = ",ecn(0)"; break;
503                 case 0x03: ecn_str = ",ce"; break;
504                 default:   ecn_str = "";
505         }
506
507         if (dscp_str == NULL)
508                 snprintf (buffer, buffer_size, "0x%02x%s", dscp, ecn_str);
509         else
510                 snprintf (buffer, buffer_size, "%s%s", dscp_str, ecn_str);
511         buffer[buffer_size - 1] = 0;
512
513         return (buffer);
514 } /* }}} char *format_qos */
515
516 static int read_options (int argc, char **argv) /* {{{ */
517 {
518         int optchar;
519
520         while (1)
521         {
522                 optchar = getopt (argc, argv, "46c:hi:I:t:Q:f:D:Z:"
523 #if USE_NCURSES
524                                 "uU"
525 #endif
526                                 );
527
528                 if (optchar == -1)
529                         break;
530
531                 switch (optchar)
532                 {
533                         case '4':
534                         case '6':
535                                 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
536                                 break;
537
538                         case 'c':
539                                 {
540                                         int new_count;
541                                         new_count = atoi (optarg);
542                                         if (new_count > 0)
543                                                 opt_count = new_count;
544                                         else
545                                                 fprintf(stderr, "Ignoring invalid count: %s\n",
546                                                                 optarg);
547                                 }
548                                 break;
549
550                         case 'f':
551                                 {
552                                         if (opt_filename != NULL)
553                                                 free (opt_filename);
554                                         opt_filename = strdup (optarg);
555                                 }
556                                 break;
557
558                         case 'i':
559                                 {
560                                         double new_interval;
561                                         new_interval = atof (optarg);
562                                         if (new_interval < 0.001)
563                                                 fprintf (stderr, "Ignoring invalid interval: %s\n",
564                                                                 optarg);
565                                         else
566                                                 opt_interval = new_interval;
567                                 }
568                                 break;
569                         case 'I':
570                                 {
571                                         if (opt_srcaddr != NULL)
572                                                 free (opt_srcaddr);
573                                         opt_srcaddr = strdup (optarg);
574                                 }
575                                 break;
576
577                         case 'D':
578                                 opt_device = optarg;
579                                 break;
580
581                         case 't':
582                         {
583                                 int new_send_ttl;
584                                 new_send_ttl = atoi (optarg);
585                                 if ((new_send_ttl > 0) && (new_send_ttl < 256))
586                                         opt_send_ttl = new_send_ttl;
587                                 else
588                                         fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
589                                                         optarg);
590                                 break;
591                         }
592
593                         case 'Q':
594                                 set_opt_send_qos (optarg);
595                                 break;
596
597 #if USE_NCURSES
598                         case 'u':
599                                 opt_utf8 = 2;
600                                 break;
601                         case 'U':
602                                 opt_utf8 = 1;
603                                 break;
604 #endif
605
606                         case 'Z':
607                         {
608                                 char *endptr = NULL;
609                                 double tmp;
610
611                                 errno = 0;
612                                 tmp = strtod (optarg, &endptr);
613                                 if ((errno != 0) || (endptr == NULL) || (*endptr != 0) || (tmp < 0.0) || (tmp > 100.0))
614                                 {
615                                         fprintf (stderr, "Ignoring invalid -Z argument: %s\n", optarg);
616                                         fprintf (stderr, "The \"-Z\" option requires a numeric argument between 0 and 100.\n");
617                                 }
618                                 else
619                                         opt_exit_status_threshold = tmp / 100.0;
620
621                                 break;
622                         }
623
624                         case 'h':
625                                 usage_exit (argv[0], 0);
626                                 break;
627                         default:
628                                 usage_exit (argv[0], 1);
629                 }
630         }
631
632         return (optind);
633 } /* }}} read_options */
634
635 static void time_normalize (struct timespec *ts) /* {{{ */
636 {
637         while (ts->tv_nsec < 0)
638         {
639                 if (ts->tv_sec == 0)
640                 {
641                         ts->tv_nsec = 0;
642                         return;
643                 }
644
645                 ts->tv_sec  -= 1;
646                 ts->tv_nsec += 1000000000;
647         }
648
649         while (ts->tv_nsec >= 1000000000)
650         {
651                 ts->tv_sec  += 1;
652                 ts->tv_nsec -= 1000000000;
653         }
654 } /* }}} void time_normalize */
655
656 static void time_calc (struct timespec *ts_dest, /* {{{ */
657                 const struct timespec *ts_int,
658                 const struct timeval  *tv_begin,
659                 const struct timeval  *tv_end)
660 {
661         ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
662         ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
663         time_normalize (ts_dest);
664
665         /* Assure that `(begin + interval) > end'.
666          * This may seem overly complicated, but `tv_sec' is of type `time_t'
667          * which may be `unsigned. *sigh* */
668         if ((tv_end->tv_sec > ts_dest->tv_sec)
669                         || ((tv_end->tv_sec == ts_dest->tv_sec)
670                                 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
671         {
672                 ts_dest->tv_sec  = 0;
673                 ts_dest->tv_nsec = 0;
674                 return;
675         }
676
677         ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
678         ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
679         time_normalize (ts_dest);
680 } /* }}} void time_calc */
681
682 #if USE_NCURSES
683 static _Bool has_utf8() /* {{{ */
684 {
685 # if HAVE_NCURSESW_NCURSES_H
686         if (!opt_utf8)
687         {
688                 /* Automatically determine */
689                 if (strcasecmp ("UTF-8", nl_langinfo (CODESET)) == 0)
690                         opt_utf8 = 2;
691                 else
692                         opt_utf8 = 1;
693         }
694         return ((_Bool) (opt_utf8 - 1));
695 # else
696         return (0);
697 # endif
698 } /* }}} _Bool has_utf8 */
699
700 static int update_prettyping_graph (ping_context_t *ctx, /* {{{ */
701                 double latency, unsigned int sequence)
702 {
703         int color = OPING_RED;
704         char const *symbol = "!";
705         int symbolc = '!';
706
707         int x_max;
708         int x_pos;
709
710         x_max = getmaxx (ctx->window);
711         x_pos = ((sequence - 1) % (x_max - 4)) + 2;
712
713         if (latency >= 0.0)
714         {
715                 double ratio;
716
717                 size_t symbols_num = hist_symbols_acs_num;
718                 size_t colors_num = 1;
719
720                 size_t index_symbols;
721                 size_t index_colors;
722                 size_t intensity;
723
724                 /* latency is in milliseconds, opt_interval is in seconds. */
725                 ratio = (latency * 0.001) / opt_interval;
726                 if (ratio > 1) {
727                         ratio = 1.0;
728                 }
729
730                 if (has_utf8 ())
731                         symbols_num = hist_symbols_utf8_num;
732
733                 if (has_colors () == TRUE)
734                         colors_num = hist_colors_num;
735
736                 intensity = (size_t) (ratio * ((double) (symbols_num * colors_num)));
737                 if (intensity >= (symbols_num * colors_num))
738                         intensity = (symbols_num * colors_num) - 1;
739
740                 index_symbols = intensity % symbols_num;
741                 assert (index_symbols < symbols_num);
742
743                 index_colors = intensity / symbols_num;
744                 assert (index_colors < colors_num);
745
746                 if (has_utf8())
747                 {
748                         color = hist_colors_utf8[index_colors];
749                         symbol = hist_symbols_utf8[index_symbols];
750                 }
751                 else
752                 {
753                         color = hist_colors_acs[index_colors];
754                         symbolc = hist_symbols_acs[index_symbols] | A_ALTCHARSET;
755                 }
756         }
757         else /* if (!(latency >= 0.0)) */
758                 wattron (ctx->window, A_BOLD);
759
760         if (has_colors () == TRUE)
761                 wattron (ctx->window, COLOR_PAIR(color));
762
763         if (has_utf8())
764                 mvwprintw (ctx->window, /* y = */ 3, /* x = */ x_pos, symbol);
765         else
766                 mvwaddch (ctx->window, /* y = */ 3, /* x = */ x_pos, symbolc);
767
768         if (has_colors () == TRUE)
769                 wattroff (ctx->window, COLOR_PAIR(color));
770
771         /* Use negation here to handle NaN correctly. */
772         if (!(latency >= 0.0))
773                 wattroff (ctx->window, A_BOLD);
774
775         wprintw (ctx->window, " ");
776         return (0);
777 } /* }}} int update_prettyping_graph */
778
779 static int update_stats_from_context (ping_context_t *ctx, pingobj_iter_t *iter) /* {{{ */
780 {
781         double latency = -1.0;
782         size_t buffer_len = sizeof (latency);
783
784         ping_iterator_get_info (iter, PING_INFO_LATENCY,
785                         &latency, &buffer_len);
786
787         unsigned int sequence = 0;
788         buffer_len = sizeof (sequence);
789         ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
790                         &sequence, &buffer_len);
791
792
793         if ((ctx == NULL) || (ctx->window == NULL))
794                 return (EINVAL);
795
796         /* werase (ctx->window); */
797
798         box (ctx->window, 0, 0);
799         wattron (ctx->window, A_BOLD);
800         mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
801                         " %s ", ctx->host);
802         wattroff (ctx->window, A_BOLD);
803         wprintw (ctx->window, "ping statistics ");
804         mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
805                         "%i packets transmitted, %i received, %.2f%% packet "
806                         "loss, time %.1fms",
807                         ctx->req_sent, ctx->req_rcvd,
808                         context_get_packet_loss (ctx),
809                         ctx->latency_total);
810         if (ctx->req_rcvd != 0)
811         {
812                 double average;
813                 double deviation;
814
815                 average = context_get_average (ctx);
816                 deviation = context_get_stddev (ctx);
817
818                 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
819                                 "rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms",
820                                 ctx->latency_min,
821                                 average,
822                                 ctx->latency_max,
823                                 deviation);
824         }
825
826         update_prettyping_graph (ctx, latency, sequence);
827
828         wrefresh (ctx->window);
829
830         return (0);
831 } /* }}} int update_stats_from_context */
832
833 static int on_resize (pingobj_t *ping) /* {{{ */
834 {
835         pingobj_iter_t *iter;
836         int width = 0;
837         int height = 0;
838         int main_win_height;
839
840         getmaxyx (stdscr, height, width);
841         if ((height < 1) || (width < 1))
842                 return (EINVAL);
843
844         main_win_height = height - (5 * host_num);
845         wresize (main_win, main_win_height, /* width = */ width);
846         /* Allow scrolling */
847         scrollok (main_win, TRUE);
848         /* wsetscrreg (main_win, 0, main_win_height - 1); */
849         /* Allow hardware accelerated scrolling. */
850         idlok (main_win, TRUE);
851         wrefresh (main_win);
852
853         for (iter = ping_iterator_get (ping);
854                         iter != NULL;
855                         iter = ping_iterator_next (iter))
856         {
857                 ping_context_t *context;
858
859                 context = ping_iterator_get_context (iter);
860                 if (context == NULL)
861                         continue;
862
863                 if (context->window != NULL)
864                 {
865                         delwin (context->window);
866                         context->window = NULL;
867                 }
868                 context->window = newwin (/* height = */ 5,
869                                 /* width = */ width,
870                                 /* y = */ main_win_height + (5 * context->index),
871                                 /* x = */ 0);
872         }
873
874         return (0);
875 } /* }}} */
876
877 static int check_resize (pingobj_t *ping) /* {{{ */
878 {
879         int need_resize = 0;
880
881         while (42)
882         {
883                 int key = wgetch (stdscr);
884                 if (key == ERR)
885                         break;
886                 else if (key == KEY_RESIZE)
887                         need_resize = 1;
888         }
889
890         if (need_resize)
891                 return (on_resize (ping));
892         else
893                 return (0);
894 } /* }}} int check_resize */
895
896 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
897 {
898         pingobj_iter_t *iter;
899         int width = 0;
900         int height = 0;
901         int main_win_height;
902
903         initscr ();
904         cbreak ();
905         noecho ();
906         nodelay (stdscr, TRUE);
907
908         getmaxyx (stdscr, height, width);
909         if ((height < 1) || (width < 1))
910                 return (EINVAL);
911
912         if (has_colors () == TRUE)
913         {
914                 start_color ();
915                 init_pair (OPING_GREEN,  COLOR_GREEN,  /* default = */ 0);
916                 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
917                 init_pair (OPING_RED,    COLOR_RED,    /* default = */ 0);
918                 init_pair (OPING_GREEN_HIST,  COLOR_GREEN,  COLOR_BLACK);
919                 init_pair (OPING_YELLOW_HIST, COLOR_YELLOW, COLOR_GREEN);
920                 init_pair (OPING_RED_HIST,    COLOR_RED,    COLOR_YELLOW);
921         }
922
923         main_win_height = height - (5 * host_num);
924         main_win = newwin (/* height = */ main_win_height,
925                         /* width = */ width,
926                         /* y = */ 0, /* x = */ 0);
927         /* Allow scrolling */
928         scrollok (main_win, TRUE);
929         /* wsetscrreg (main_win, 0, main_win_height - 1); */
930         /* Allow hardware accelerated scrolling. */
931         idlok (main_win, TRUE);
932         wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
933         wrefresh (main_win);
934
935         for (iter = ping_iterator_get (ping);
936                         iter != NULL;
937                         iter = ping_iterator_next (iter))
938         {
939                 ping_context_t *context;
940
941                 context = ping_iterator_get_context (iter);
942                 if (context == NULL)
943                         continue;
944
945                 if (context->window != NULL)
946                 {
947                         delwin (context->window);
948                         context->window = NULL;
949                 }
950                 context->window = newwin (/* height = */ 5,
951                                 /* width = */ width,
952                                 /* y = */ main_win_height + (5 * context->index),
953                                 /* x = */ 0);
954         }
955
956
957         /* Don't know what good this does exactly, but without this code
958          * "check_resize" will be called right after startup and *somehow*
959          * this leads to display errors. If we purge all initial characters
960          * here, the problem goes away. "wgetch" is non-blocking due to
961          * "nodelay" (see above). */
962         while (wgetch (stdscr) != ERR)
963         {
964                 /* eat up characters */;
965         }
966
967         return (0);
968 } /* }}} int pre_loop_hook */
969
970 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
971 {
972         return (check_resize (ping));
973 } /* }}} int pre_sleep_hook */
974
975 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
976 {
977         return (check_resize (ping));
978 } /* }}} int pre_sleep_hook */
979 #else /* if !USE_NCURSES */
980 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
981 {
982         pingobj_iter_t *iter;
983
984         for (iter = ping_iterator_get (ping);
985                         iter != NULL;
986                         iter = ping_iterator_next (iter))
987         {
988                 ping_context_t *ctx;
989                 size_t buffer_size;
990
991                 ctx = ping_iterator_get_context (iter);
992                 if (ctx == NULL)
993                         continue;
994
995                 buffer_size = 0;
996                 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
997
998                 printf ("PING %s (%s) %zu bytes of data.\n",
999                                 ctx->host, ctx->addr, buffer_size);
1000         }
1001
1002         return (0);
1003 } /* }}} int pre_loop_hook */
1004
1005 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
1006 {
1007         fflush (stdout);
1008
1009         return (0);
1010 } /* }}} int pre_sleep_hook */
1011
1012 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
1013 {
1014         return (0);
1015 } /* }}} int post_sleep_hook */
1016 #endif
1017
1018 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
1019                 __attribute__((unused)) int index)
1020 {
1021         double          latency;
1022         unsigned int    sequence;
1023         int             recv_ttl;
1024         uint8_t         recv_qos;
1025         char            recv_qos_str[16];
1026         size_t          buffer_len;
1027         size_t          data_len;
1028         ping_context_t *context;
1029
1030         latency = -1.0;
1031         buffer_len = sizeof (latency);
1032         ping_iterator_get_info (iter, PING_INFO_LATENCY,
1033                         &latency, &buffer_len);
1034
1035         sequence = 0;
1036         buffer_len = sizeof (sequence);
1037         ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
1038                         &sequence, &buffer_len);
1039
1040         recv_ttl = -1;
1041         buffer_len = sizeof (recv_ttl);
1042         ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
1043                         &recv_ttl, &buffer_len);
1044
1045         recv_qos = 0;
1046         buffer_len = sizeof (recv_qos);
1047         ping_iterator_get_info (iter, PING_INFO_RECV_QOS,
1048                         &recv_qos, &buffer_len);
1049
1050         data_len = 0;
1051         ping_iterator_get_info (iter, PING_INFO_DATA,
1052                         NULL, &data_len);
1053
1054         context = (ping_context_t *) ping_iterator_get_context (iter);
1055
1056 #if USE_NCURSES
1057 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
1058 #else
1059 # define HOST_PRINTF(...) printf(__VA_ARGS__)
1060 #endif
1061
1062         context->req_sent++;
1063         if (latency > 0.0)
1064         {
1065                 context->req_rcvd++;
1066                 context->latency_total += latency;
1067                 context->latency_total_square += (latency * latency);
1068
1069                 if ((context->latency_max < 0.0) || (context->latency_max < latency))
1070                         context->latency_max = latency;
1071                 if ((context->latency_min < 0.0) || (context->latency_min > latency))
1072                         context->latency_min = latency;
1073
1074 #if USE_NCURSES
1075                 if (has_colors () == TRUE)
1076                 {
1077                         int color = OPING_GREEN;
1078                         double average = context_get_average (context);
1079                         double stddev = context_get_stddev (context);
1080
1081                         if ((latency < (average - (2 * stddev)))
1082                                         || (latency > (average + (2 * stddev))))
1083                                 color = OPING_RED;
1084                         else if ((latency < (average - stddev))
1085                                         || (latency > (average + stddev)))
1086                                 color = OPING_YELLOW;
1087
1088                         HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
1089                                         data_len, context->host, context->addr,
1090                                         sequence, recv_ttl,
1091                                         format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1092                         if ((recv_qos != 0) || (opt_send_qos != 0))
1093                         {
1094                                 HOST_PRINTF ("qos=%s ",
1095                                                 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1096                         }
1097                         HOST_PRINTF ("time=");
1098                         wattron (main_win, COLOR_PAIR(color));
1099                         HOST_PRINTF ("%.2f", latency);
1100                         wattroff (main_win, COLOR_PAIR(color));
1101                         HOST_PRINTF (" ms\n");
1102                 }
1103                 else
1104                 {
1105 #endif
1106                 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
1107                                 data_len,
1108                                 context->host, context->addr,
1109                                 sequence, recv_ttl);
1110                 if ((recv_qos != 0) || (opt_send_qos != 0))
1111                 {
1112                         HOST_PRINTF ("qos=%s ",
1113                                         format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1114                 }
1115                 HOST_PRINTF ("time=%.2f ms\n", latency);
1116 #if USE_NCURSES
1117                 }
1118 #endif
1119         }
1120         else
1121         {
1122 #if USE_NCURSES
1123                 if (has_colors () == TRUE)
1124                 {
1125                         HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
1126                                         context->host, context->addr,
1127                                         sequence);
1128                         wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
1129                         HOST_PRINTF ("timeout");
1130                         wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
1131                         HOST_PRINTF ("\n");
1132                 }
1133                 else
1134                 {
1135 #endif
1136                 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
1137                                 context->host, context->addr,
1138                                 sequence);
1139 #if USE_NCURSES
1140                 }
1141 #endif
1142         }
1143
1144 #if USE_NCURSES
1145         update_stats_from_context (context, iter);
1146         wrefresh (main_win);
1147 #endif
1148 } /* }}} void update_host_hook */
1149
1150 /* Prints statistics for each host, cleans up the contexts and returns the
1151  * number of hosts which failed to return more than the fraction
1152  * opt_exit_status_threshold of pings. */
1153 static int post_loop_hook (pingobj_t *ping) /* {{{ */
1154 {
1155         pingobj_iter_t *iter;
1156         int failure_count = 0;
1157
1158 #if USE_NCURSES
1159         endwin ();
1160 #endif
1161
1162         for (iter = ping_iterator_get (ping);
1163                         iter != NULL;
1164                         iter = ping_iterator_next (iter))
1165         {
1166                 ping_context_t *context;
1167
1168                 context = ping_iterator_get_context (iter);
1169
1170                 printf ("\n--- %s ping statistics ---\n"
1171                                 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
1172                                 context->host, context->req_sent, context->req_rcvd,
1173                                 context_get_packet_loss (context),
1174                                 context->latency_total);
1175
1176                 {
1177                         double pct_failed = 1.0 - (((double) context->req_rcvd)
1178                                         / ((double) context->req_sent));
1179                         if (pct_failed > opt_exit_status_threshold)
1180                                 failure_count++;
1181                 }
1182
1183                 if (context->req_rcvd != 0)
1184                 {
1185                         double average;
1186                         double deviation;
1187
1188                         average = context_get_average (context);
1189                         deviation = context_get_stddev (context);
1190
1191                         printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
1192                                         context->latency_min,
1193                                         average,
1194                                         context->latency_max,
1195                                         deviation);
1196                 }
1197
1198                 ping_iterator_set_context (iter, NULL);
1199                 context_destroy (context);
1200         }
1201
1202         return (failure_count);
1203 } /* }}} int post_loop_hook */
1204
1205 int main (int argc, char **argv) /* {{{ */
1206 {
1207         pingobj_t      *ping;
1208         pingobj_iter_t *iter;
1209
1210         struct sigaction sigint_action;
1211
1212         struct timeval  tv_begin;
1213         struct timeval  tv_end;
1214         struct timespec ts_wait;
1215         struct timespec ts_int;
1216
1217         int optind;
1218         int i;
1219         int status;
1220 #if _POSIX_SAVED_IDS
1221         uid_t saved_set_uid;
1222
1223         /* Save the old effective user id */
1224         saved_set_uid = geteuid ();
1225         /* Set the effective user ID to the real user ID without changing the
1226          * saved set-user ID */
1227         status = seteuid (getuid ());
1228         if (status != 0)
1229         {
1230                 fprintf (stderr, "Temporarily dropping privileges "
1231                                 "failed: %s\n", strerror (errno));
1232                 exit (EXIT_FAILURE);
1233         }
1234 #endif
1235
1236         setlocale(LC_ALL, "");
1237         optind = read_options (argc, argv);
1238
1239 #if !_POSIX_SAVED_IDS
1240         /* Cannot temporarily drop privileges -> reject every file but "-". */
1241         if ((opt_filename != NULL)
1242                         && (strcmp ("-", opt_filename) != 0)
1243                         && (getuid () != geteuid ()))
1244         {
1245                 fprintf (stderr, "Your real and effective user IDs don't "
1246                                 "match. Reading from a file (option '-f')\n"
1247                                 "is therefore too risky. You can still read "
1248                                 "from STDIN using '-f -' if you like.\n"
1249                                 "Sorry.\n");
1250                 exit (EXIT_FAILURE);
1251         }
1252 #endif
1253
1254         if ((optind >= argc) && (opt_filename == NULL)) {
1255                 usage_exit (argv[0], 1);
1256         }
1257
1258         if ((ping = ping_construct ()) == NULL)
1259         {
1260                 fprintf (stderr, "ping_construct failed\n");
1261                 return (1);
1262         }
1263
1264         if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
1265         {
1266                 fprintf (stderr, "Setting TTL to %i failed: %s\n",
1267                                 opt_send_ttl, ping_get_error (ping));
1268         }
1269
1270         if (ping_setopt (ping, PING_OPT_QOS, &opt_send_qos) != 0)
1271         {
1272                 fprintf (stderr, "Setting TOS to %i failed: %s\n",
1273                                 opt_send_qos, ping_get_error (ping));
1274         }
1275
1276         {
1277                 double temp_sec;
1278                 double temp_nsec;
1279
1280                 temp_nsec = modf (opt_interval, &temp_sec);
1281                 ts_int.tv_sec  = (time_t) temp_sec;
1282                 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
1283
1284                 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
1285         }
1286
1287         if (opt_addrfamily != PING_DEF_AF)
1288                 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
1289
1290         if (opt_srcaddr != NULL)
1291         {
1292                 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
1293                 {
1294                         fprintf (stderr, "Setting source address failed: %s\n",
1295                                         ping_get_error (ping));
1296                 }
1297         }
1298
1299         if (opt_device != NULL)
1300         {
1301                 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
1302                 {
1303                         fprintf (stderr, "Setting device failed: %s\n",
1304                                         ping_get_error (ping));
1305                 }
1306         }
1307
1308         if (opt_filename != NULL)
1309         {
1310                 FILE *infile;
1311                 char line[256];
1312                 char host[256];
1313
1314                 if (strcmp (opt_filename, "-") == 0)
1315                         /* Open STDIN */
1316                         infile = fdopen(0, "r");
1317                 else
1318                         infile = fopen(opt_filename, "r");
1319
1320                 if (infile == NULL)
1321                 {
1322                         fprintf (stderr, "Opening %s failed: %s\n",
1323                                         (strcmp (opt_filename, "-") == 0)
1324                                         ? "STDIN" : opt_filename,
1325                                         strerror(errno));
1326                         return (1);
1327                 }
1328
1329 #if _POSIX_SAVED_IDS
1330                 /* Regain privileges */
1331                 status = seteuid (saved_set_uid);
1332                 if (status != 0)
1333                 {
1334                         fprintf (stderr, "Temporarily re-gaining privileges "
1335                                         "failed: %s\n", strerror (errno));
1336                         exit (EXIT_FAILURE);
1337                 }
1338 #endif
1339
1340                 while (fgets(line, sizeof(line), infile))
1341                 {
1342                         /* Strip whitespace */
1343                         if (sscanf(line, "%s", host) != 1)
1344                                 continue;
1345
1346                         if ((host[0] == 0) || (host[0] == '#'))
1347                                 continue;
1348
1349                         if (ping_host_add(ping, host) < 0)
1350                         {
1351                                 const char *errmsg = ping_get_error (ping);
1352
1353                                 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
1354                                 continue;
1355                         }
1356                         else
1357                         {
1358                                 host_num++;
1359                         }
1360                 }
1361
1362 #if _POSIX_SAVED_IDS
1363                 /* Drop privileges */
1364                 status = seteuid (getuid ());
1365                 if (status != 0)
1366                 {
1367                         fprintf (stderr, "Temporarily dropping privileges "
1368                                         "failed: %s\n", strerror (errno));
1369                         exit (EXIT_FAILURE);
1370                 }
1371 #endif
1372
1373                 fclose(infile);
1374         }
1375
1376 #if _POSIX_SAVED_IDS
1377         /* Regain privileges */
1378         status = seteuid (saved_set_uid);
1379         if (status != 0)
1380         {
1381                 fprintf (stderr, "Temporarily re-gaining privileges "
1382                                 "failed: %s\n", strerror (errno));
1383                 exit (EXIT_FAILURE);
1384         }
1385 #endif
1386
1387         for (i = optind; i < argc; i++)
1388         {
1389                 if (ping_host_add (ping, argv[i]) < 0)
1390                 {
1391                         const char *errmsg = ping_get_error (ping);
1392
1393                         fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
1394                         continue;
1395                 }
1396                 else
1397                 {
1398                         host_num++;
1399                 }
1400         }
1401
1402         /* Permanently drop root privileges if we're setuid-root. */
1403         status = setuid (getuid ());
1404         if (status != 0)
1405         {
1406                 fprintf (stderr, "Dropping privileges failed: %s\n",
1407                                 strerror (errno));
1408                 exit (EXIT_FAILURE);
1409         }
1410
1411 #if _POSIX_SAVED_IDS
1412         saved_set_uid = (uid_t) -1;
1413 #endif
1414
1415         ping_initialize_contexts (ping);
1416
1417         if (i == 0)
1418                 return (1);
1419
1420         memset (&sigint_action, '\0', sizeof (sigint_action));
1421         sigint_action.sa_handler = sigint_handler;
1422         if (sigaction (SIGINT, &sigint_action, NULL) < 0)
1423         {
1424                 perror ("sigaction");
1425                 return (1);
1426         }
1427
1428         pre_loop_hook (ping);
1429
1430         while (opt_count != 0)
1431         {
1432                 int index;
1433                 int status;
1434
1435                 if (gettimeofday (&tv_begin, NULL) < 0)
1436                 {
1437                         perror ("gettimeofday");
1438                         return (1);
1439                 }
1440
1441                 status = ping_send (ping);
1442                 if (status == -EINTR)
1443                 {
1444                         continue;
1445                 }
1446                 else if (status < 0)
1447                 {
1448                         fprintf (stderr, "ping_send failed: %s\n",
1449                                         ping_get_error (ping));
1450                         return (1);
1451                 }
1452
1453                 index = 0;
1454                 for (iter = ping_iterator_get (ping);
1455                                 iter != NULL;
1456                                 iter = ping_iterator_next (iter))
1457                 {
1458                         update_host_hook (iter, index);
1459                         index++;
1460                 }
1461
1462                 pre_sleep_hook (ping);
1463
1464                 /* Don't sleep in the last iteration */
1465                 if (opt_count == 1)
1466                         break;
1467
1468                 if (gettimeofday (&tv_end, NULL) < 0)
1469                 {
1470                         perror ("gettimeofday");
1471                         return (1);
1472                 }
1473
1474                 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1475
1476                 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1477                 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1478                 {
1479                         if (errno == EINTR)
1480                         {
1481                                 continue;
1482                         }
1483                         else
1484                         {
1485                                 perror ("nanosleep");
1486                                 break;
1487                         }
1488                 }
1489
1490                 post_sleep_hook (ping);
1491
1492                 if (opt_count > 0)
1493                         opt_count--;
1494         } /* while (opt_count != 0) */
1495
1496         /* Returns the number of failed hosts according to -Z. */
1497         status = post_loop_hook (ping);
1498
1499         ping_destroy (ping);
1500
1501         if (status == 0)
1502                 exit (EXIT_SUCCESS);
1503         else
1504         {
1505                 if (status > 255)
1506                         status = 255;
1507                 exit (status);
1508         }
1509 } /* }}} int main */
1510
1511 /* vim: set fdm=marker : */