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