2 * Object oriented C module to send ICMP and ICMPv6 `echo's.
3 * Copyright (C) 2006-2011 Florian octo Forster <ff at octo.it>
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
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.
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
29 # include <inttypes.h>
33 # error "You don't have the standard C99 header files installed"
34 #endif /* STDC_HEADERS */
44 #if TIME_WITH_SYS_TIME
45 # include <sys/time.h>
49 # include <sys/time.h>
56 # include <sys/socket.h>
59 # include <netinet/in.h>
62 # include <netinet/ip.h>
66 # include <netdb.h> /* NI_MAXHOST */
74 #include <sys/types.h>
78 # define NCURSES_OPAQUE 1
81 # define OPING_GREEN 1
82 # define OPING_YELLOW 2
88 #ifndef _POSIX_SAVED_IDS
89 # define _POSIX_SAVED_IDS 0
92 /* Remove GNU specific __attribute__ settings when using another compiler */
94 # define __attribute__(x) /**/
97 typedef struct ping_context
99 char host[NI_MAXHOST];
100 char addr[NI_MAXHOST];
108 double latency_total;
109 double latency_total_square;
116 static double opt_interval = 1.0;
117 static int opt_addrfamily = PING_DEF_AF;
118 static char *opt_srcaddr = NULL;
119 static char *opt_device = NULL;
120 static char *opt_filename = NULL;
121 static int opt_count = -1;
122 static int opt_send_ttl = 64;
123 static uint8_t opt_send_qos = 0;
124 static double opt_exit_status_threshold = 1.0;
126 static int host_num = 0;
129 static WINDOW *main_win = NULL;
132 static void sigint_handler (int signal) /* {{{ */
134 /* Make compiler happy */
138 } /* }}} void sigint_handler */
140 static ping_context_t *context_create (void) /* {{{ */
144 if ((ret = malloc (sizeof (ping_context_t))) == NULL)
147 memset (ret, '\0', sizeof (ping_context_t));
149 ret->latency_min = -1.0;
150 ret->latency_max = -1.0;
151 ret->latency_total = 0.0;
152 ret->latency_total_square = 0.0;
159 } /* }}} ping_context_t *context_create */
161 static void context_destroy (ping_context_t *context) /* {{{ */
167 if (context->window != NULL)
169 delwin (context->window);
170 context->window = NULL;
175 } /* }}} void context_destroy */
177 static double context_get_average (ping_context_t *ctx) /* {{{ */
184 if (ctx->req_rcvd < 1)
187 num_total = (double) ctx->req_rcvd;
188 return (ctx->latency_total / num_total);
189 } /* }}} double context_get_average */
191 static double context_get_stddev (ping_context_t *ctx) /* {{{ */
198 if (ctx->req_rcvd < 1)
200 else if (ctx->req_rcvd < 2)
203 num_total = (double) ctx->req_rcvd;
204 return (sqrt (((num_total * ctx->latency_total_square)
205 - (ctx->latency_total * ctx->latency_total))
206 / (num_total * (num_total - 1.0))));
207 } /* }}} double context_get_stddev */
209 static double context_get_packet_loss (const ping_context_t *ctx) /* {{{ */
214 if (ctx->req_sent < 1)
217 return (100.0 * (ctx->req_sent - ctx->req_rcvd)
218 / ((double) ctx->req_sent));
219 } /* }}} double context_get_packet_loss */
221 static int ping_initialize_contexts (pingobj_t *ping) /* {{{ */
223 pingobj_iter_t *iter;
230 for (iter = ping_iterator_get (ping);
232 iter = ping_iterator_next (iter))
234 ping_context_t *context;
237 context = context_create ();
238 context->index = index;
240 buffer_size = sizeof (context->host);
241 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
243 buffer_size = sizeof (context->addr);
244 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
246 ping_iterator_set_context (iter, (void *) context);
252 } /* }}} int ping_initialize_contexts */
254 static void usage_exit (const char *name, int status) /* {{{ */
256 fprintf (stderr, "Usage: %s [OPTIONS] "
257 "-f filename | host [host [host ...]]\n"
259 "\nAvailable options:\n"
260 " -4|-6 force the use of IPv4 or IPv6\n"
261 " -c count number of ICMP packets to send\n"
262 " -i interval interval with which to send ICMP packets\n"
263 " -t ttl time to live for each ICMP packet\n"
264 " -Q qos Quality of Service (QoS) of outgoing packets\n"
265 " Use \"-Q help\" for a list of valid options.\n"
266 " -I srcaddr source address\n"
267 " -D device outgoing interface name\n"
268 " -f filename filename to read hosts from\n"
269 " -Z percent Exit with non-zero exit status if more than this percentage of\n"
270 " probes timed out. (default: never)\n"
272 "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
273 "by Florian octo Forster <octo@verplant.org>\n"
274 "for contributions see `AUTHORS'\n",
277 } /* }}} void usage_exit */
279 __attribute__((noreturn))
280 static void usage_qos_exit (const char *arg, int status) /* {{{ */
283 fprintf (stderr, "Invalid QoS argument: \"%s\"\n\n", arg);
285 fprintf (stderr, "Valid QoS arguments (option \"-Q\") are:\n"
287 " Differentiated Services (IPv4 and IPv6, RFC 2474)\n"
289 " be Best Effort (BE, default PHB).\n"
290 " ef Expedited Forwarding (EF) PHB group (RFC 3246).\n"
291 " (low delay, low loss, low jitter)\n"
292 " va Voice Admit (VA) DSCP (RFC 5865).\n"
293 " (capacity-admitted traffic)\n"
294 " af[1-4][1-3] Assured Forwarding (AF) PHB group (RFC 2597).\n"
295 " For example: \"af12\" (class 1, precedence 2)\n"
296 " cs[0-7] Class Selector (CS) PHB group (RFC 2474).\n"
297 " For example: \"cs1\" (priority traffic)\n"
299 " Type of Service (IPv4, RFC 1349, obsolete)\n"
301 " lowdelay (%#04x) minimize delay\n"
302 " throughput (%#04x) maximize throughput\n"
303 " reliability (%#04x) maximize reliability\n"
304 " mincost (%#04x) minimize monetary cost\n"
306 " Specify manually\n"
308 " 0x00 - 0xff Hexadecimal numeric specification.\n"
309 " 0 - 255 Decimal numeric specification.\n"
311 (unsigned int) IPTOS_LOWDELAY,
312 (unsigned int) IPTOS_THROUGHPUT,
313 (unsigned int) IPTOS_RELIABILITY,
314 (unsigned int) IPTOS_MINCOST);
317 } /* }}} void usage_qos_exit */
319 static int set_opt_send_qos (const char *opt) /* {{{ */
324 if (strcasecmp ("help", opt) == 0)
325 usage_qos_exit (/* arg = */ NULL, /* status = */ EXIT_SUCCESS);
326 /* DiffServ (RFC 2474): */
327 /* - Best effort (BE) */
328 else if (strcasecmp ("be", opt) == 0)
330 /* - Expedited Forwarding (EF, RFC 3246) */
331 else if (strcasecmp ("ef", opt) == 0)
332 opt_send_qos = 0xB8; /* == 0x2E << 2 */
333 /* - Voice Admit (VA, RFC 5865) */
334 else if (strcasecmp ("va", opt) == 0)
335 opt_send_qos = 0xB0; /* == 0x2D << 2 */
336 /* - Assured Forwarding (AF, RFC 2597) */
337 else if ((strncasecmp ("af", opt, strlen ("af")) == 0)
338 && (strlen (opt) == 4))
344 /* There are four classes, AF1x, AF2x, AF3x, and AF4x. */
347 else if (opt[2] == '2')
349 else if (opt[2] == '3')
351 else if (opt[2] == '4')
354 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
356 /* In each class, there are three precedences, AFx1, AFx2, and AFx3 */
359 else if (opt[3] == '2')
361 else if (opt[3] == '3')
364 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
366 dscp = (8 * class) + (2 * prec);
367 /* The lower two bits are used for Explicit Congestion Notification (ECN) */
368 opt_send_qos = dscp << 2;
370 /* - Class Selector (CS) */
371 else if ((strncasecmp ("cs", opt, strlen ("cs")) == 0)
372 && (strlen (opt) == 3))
376 if ((opt[2] < '0') || (opt[2] > '7'))
377 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
379 /* Not exactly legal by the C standard, but I don't know of any
380 * system not supporting this hack. */
381 class = ((uint8_t) opt[2]) - ((uint8_t) '0');
382 opt_send_qos = class << 5;
384 /* Type of Service (RFC 1349) */
385 else if (strcasecmp ("lowdelay", opt) == 0)
386 opt_send_qos = IPTOS_LOWDELAY;
387 else if (strcasecmp ("throughput", opt) == 0)
388 opt_send_qos = IPTOS_THROUGHPUT;
389 else if (strcasecmp ("reliability", opt) == 0)
390 opt_send_qos = IPTOS_RELIABILITY;
391 else if (strcasecmp ("mincost", opt) == 0)
392 opt_send_qos = IPTOS_MINCOST;
401 value = strtoul (opt, &endptr, /* base = */ 0);
402 if ((errno != 0) || (endptr == opt)
403 || (endptr == NULL) || (*endptr != 0)
405 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
407 opt_send_qos = (uint8_t) value;
411 } /* }}} int set_opt_send_qos */
413 static char *format_qos (uint8_t qos, char *buffer, size_t buffer_size) /* {{{ */
425 case 0x00: dscp_str = "be"; break;
426 case 0x2e: dscp_str = "ef"; break;
427 case 0x2d: dscp_str = "va"; break;
428 case 0x0a: dscp_str = "af11"; break;
429 case 0x0c: dscp_str = "af12"; break;
430 case 0x0e: dscp_str = "af13"; break;
431 case 0x12: dscp_str = "af21"; break;
432 case 0x14: dscp_str = "af22"; break;
433 case 0x16: dscp_str = "af23"; break;
434 case 0x1a: dscp_str = "af31"; break;
435 case 0x1c: dscp_str = "af32"; break;
436 case 0x1e: dscp_str = "af33"; break;
437 case 0x22: dscp_str = "af41"; break;
438 case 0x24: dscp_str = "af42"; break;
439 case 0x26: dscp_str = "af43"; break;
440 case 0x08: dscp_str = "cs1"; break;
441 case 0x10: dscp_str = "cs2"; break;
442 case 0x18: dscp_str = "cs3"; break;
443 case 0x20: dscp_str = "cs4"; break;
444 case 0x28: dscp_str = "cs5"; break;
445 case 0x30: dscp_str = "cs6"; break;
446 case 0x38: dscp_str = "cs7"; break;
447 default: dscp_str = NULL;
452 case 0x01: ecn_str = ",ecn(1)"; break;
453 case 0x02: ecn_str = ",ecn(0)"; break;
454 case 0x03: ecn_str = ",ce"; break;
455 default: ecn_str = "";
458 if (dscp_str == NULL)
459 snprintf (buffer, buffer_size, "0x%02x%s", dscp, ecn_str);
461 snprintf (buffer, buffer_size, "%s%s", dscp_str, ecn_str);
462 buffer[buffer_size - 1] = 0;
465 } /* }}} char *format_qos */
467 static int read_options (int argc, char **argv) /* {{{ */
473 optchar = getopt (argc, argv, "46c:hi:I:t:Q:f:D:Z:");
482 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
488 new_count = atoi (optarg);
490 opt_count = new_count;
492 fprintf(stderr, "Ignoring invalid count: %s\n",
499 if (opt_filename != NULL)
501 opt_filename = strdup (optarg);
508 new_interval = atof (optarg);
509 if (new_interval < 0.001)
510 fprintf (stderr, "Ignoring invalid interval: %s\n",
513 opt_interval = new_interval;
518 if (opt_srcaddr != NULL)
520 opt_srcaddr = strdup (optarg);
531 new_send_ttl = atoi (optarg);
532 if ((new_send_ttl > 0) && (new_send_ttl < 256))
533 opt_send_ttl = new_send_ttl;
535 fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
541 set_opt_send_qos (optarg);
550 tmp = strtod (optarg, &endptr);
551 if ((errno != 0) || (endptr == NULL) || (*endptr != 0))
552 fprintf (stderr, "The \"-Z\" option requires a numeric argument.\n");
553 else if ((tmp >= 0.0) && (tmp <= 100.0))
554 opt_exit_status_threshold = tmp / 100.0;
556 fprintf (stderr, "The argument of the \"-Z\" option must be between 0 and 100.\n");
562 usage_exit (argv[0], 0);
565 usage_exit (argv[0], 1);
570 } /* }}} read_options */
572 static void time_normalize (struct timespec *ts) /* {{{ */
574 while (ts->tv_nsec < 0)
583 ts->tv_nsec += 1000000000;
586 while (ts->tv_nsec >= 1000000000)
589 ts->tv_nsec -= 1000000000;
591 } /* }}} void time_normalize */
593 static void time_calc (struct timespec *ts_dest, /* {{{ */
594 const struct timespec *ts_int,
595 const struct timeval *tv_begin,
596 const struct timeval *tv_end)
598 ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
599 ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
600 time_normalize (ts_dest);
602 /* Assure that `(begin + interval) > end'.
603 * This may seem overly complicated, but `tv_sec' is of type `time_t'
604 * which may be `unsigned. *sigh* */
605 if ((tv_end->tv_sec > ts_dest->tv_sec)
606 || ((tv_end->tv_sec == ts_dest->tv_sec)
607 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
610 ts_dest->tv_nsec = 0;
614 ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
615 ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
616 time_normalize (ts_dest);
617 } /* }}} void time_calc */
620 static int update_stats_from_context (ping_context_t *ctx) /* {{{ */
622 if ((ctx == NULL) || (ctx->window == NULL))
625 werase (ctx->window);
627 box (ctx->window, 0, 0);
628 wattron (ctx->window, A_BOLD);
629 mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
631 wattroff (ctx->window, A_BOLD);
632 wprintw (ctx->window, "ping statistics ");
633 mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
634 "%i packets transmitted, %i received, %.2f%% packet "
636 ctx->req_sent, ctx->req_rcvd,
637 context_get_packet_loss (ctx),
639 if (ctx->req_rcvd != 0)
644 average = context_get_average (ctx);
645 deviation = context_get_stddev (ctx);
647 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
648 "rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms",
655 wrefresh (ctx->window);
658 } /* }}} int update_stats_from_context */
660 static int on_resize (pingobj_t *ping) /* {{{ */
662 pingobj_iter_t *iter;
667 getmaxyx (stdscr, height, width);
668 if ((height < 1) || (width < 1))
671 main_win_height = height - (4 * host_num);
672 wresize (main_win, main_win_height, /* width = */ width);
673 /* Allow scrolling */
674 scrollok (main_win, TRUE);
675 /* wsetscrreg (main_win, 0, main_win_height - 1); */
676 /* Allow hardware accelerated scrolling. */
677 idlok (main_win, TRUE);
680 for (iter = ping_iterator_get (ping);
682 iter = ping_iterator_next (iter))
684 ping_context_t *context;
686 context = ping_iterator_get_context (iter);
690 if (context->window != NULL)
692 delwin (context->window);
693 context->window = NULL;
695 context->window = newwin (/* height = */ 4,
697 /* y = */ main_win_height + (4 * context->index),
704 static int check_resize (pingobj_t *ping) /* {{{ */
710 int key = wgetch (stdscr);
713 else if (key == KEY_RESIZE)
718 return (on_resize (ping));
721 } /* }}} int check_resize */
723 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
725 pingobj_iter_t *iter;
733 nodelay (stdscr, TRUE);
735 getmaxyx (stdscr, height, width);
736 if ((height < 1) || (width < 1))
739 if (has_colors () == TRUE)
742 init_pair (OPING_GREEN, COLOR_GREEN, /* default = */ 0);
743 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
744 init_pair (OPING_RED, COLOR_RED, /* default = */ 0);
747 main_win_height = height - (4 * host_num);
748 main_win = newwin (/* height = */ main_win_height,
750 /* y = */ 0, /* x = */ 0);
751 /* Allow scrolling */
752 scrollok (main_win, TRUE);
753 /* wsetscrreg (main_win, 0, main_win_height - 1); */
754 /* Allow hardware accelerated scrolling. */
755 idlok (main_win, TRUE);
756 wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
759 for (iter = ping_iterator_get (ping);
761 iter = ping_iterator_next (iter))
763 ping_context_t *context;
765 context = ping_iterator_get_context (iter);
769 if (context->window != NULL)
771 delwin (context->window);
772 context->window = NULL;
774 context->window = newwin (/* height = */ 4,
776 /* y = */ main_win_height + (4 * context->index),
781 /* Don't know what good this does exactly, but without this code
782 * "check_resize" will be called right after startup and *somehow*
783 * this leads to display errors. If we purge all initial characters
784 * here, the problem goes away. "wgetch" is non-blocking due to
785 * "nodelay" (see above). */
786 while (wgetch (stdscr) != ERR)
788 /* eat up characters */;
792 } /* }}} int pre_loop_hook */
794 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
796 return (check_resize (ping));
797 } /* }}} int pre_sleep_hook */
799 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
801 return (check_resize (ping));
802 } /* }}} int pre_sleep_hook */
803 #else /* if !USE_NCURSES */
804 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
806 pingobj_iter_t *iter;
808 for (iter = ping_iterator_get (ping);
810 iter = ping_iterator_next (iter))
815 ctx = ping_iterator_get_context (iter);
820 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
822 printf ("PING %s (%s) %zu bytes of data.\n",
823 ctx->host, ctx->addr, buffer_size);
827 } /* }}} int pre_loop_hook */
829 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
834 } /* }}} int pre_sleep_hook */
836 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
839 } /* }}} int post_sleep_hook */
842 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
843 __attribute__((unused)) int index)
846 unsigned int sequence;
849 char recv_qos_str[16];
852 ping_context_t *context;
855 buffer_len = sizeof (latency);
856 ping_iterator_get_info (iter, PING_INFO_LATENCY,
857 &latency, &buffer_len);
860 buffer_len = sizeof (sequence);
861 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
862 &sequence, &buffer_len);
865 buffer_len = sizeof (recv_ttl);
866 ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
867 &recv_ttl, &buffer_len);
870 buffer_len = sizeof (recv_qos);
871 ping_iterator_get_info (iter, PING_INFO_RECV_QOS,
872 &recv_qos, &buffer_len);
875 ping_iterator_get_info (iter, PING_INFO_DATA,
878 context = (ping_context_t *) ping_iterator_get_context (iter);
881 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
883 # define HOST_PRINTF(...) printf(__VA_ARGS__)
890 context->latency_total += latency;
891 context->latency_total_square += (latency * latency);
893 if ((context->latency_max < 0.0) || (context->latency_max < latency))
894 context->latency_max = latency;
895 if ((context->latency_min < 0.0) || (context->latency_min > latency))
896 context->latency_min = latency;
899 if (has_colors () == TRUE)
901 int color = OPING_GREEN;
902 double average = context_get_average (context);
903 double stddev = context_get_stddev (context);
905 if ((latency < (average - (2 * stddev)))
906 || (latency > (average + (2 * stddev))))
908 else if ((latency < (average - stddev))
909 || (latency > (average + stddev)))
910 color = OPING_YELLOW;
912 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
913 data_len, context->host, context->addr,
915 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
916 if ((recv_qos != 0) || (opt_send_qos != 0))
918 HOST_PRINTF ("qos=%s ",
919 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
921 HOST_PRINTF ("time=");
922 wattron (main_win, COLOR_PAIR(color));
923 HOST_PRINTF ("%.2f", latency);
924 wattroff (main_win, COLOR_PAIR(color));
925 HOST_PRINTF (" ms\n");
930 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
932 context->host, context->addr,
934 if ((recv_qos != 0) || (opt_send_qos != 0))
936 HOST_PRINTF ("qos=%s ",
937 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
939 HOST_PRINTF ("time=%.2f ms\n", latency);
947 if (has_colors () == TRUE)
949 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
950 context->host, context->addr,
952 wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
953 HOST_PRINTF ("timeout");
954 wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
960 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
961 context->host, context->addr,
969 update_stats_from_context (context);
972 } /* }}} void update_host_hook */
974 /* returns the number of significant failures: sum over hosts of
975 unreturned packets exceeding 50% of the number sent, rounding up. */
976 static int post_loop_hook (pingobj_t *ping) /* {{{ */
978 pingobj_iter_t *iter;
979 /* failures to report: sum over hosts of number of failed
981 int failure_count = 0;
987 for (iter = ping_iterator_get (ping);
989 iter = ping_iterator_next (iter))
991 ping_context_t *context;
993 context = ping_iterator_get_context (iter);
995 printf ("\n--- %s ping statistics ---\n"
996 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
997 context->host, context->req_sent, context->req_rcvd,
998 context_get_packet_loss (context),
999 context->latency_total);
1002 double pct_failed = 1.0 - (((double) context->req_rcvd)
1003 / ((double) context->req_sent));
1004 if (pct_failed > opt_exit_status_threshold)
1008 if (context->req_rcvd != 0)
1013 average = context_get_average (context);
1014 deviation = context_get_stddev (context);
1016 printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
1017 context->latency_min,
1019 context->latency_max,
1023 ping_iterator_set_context (iter, NULL);
1024 context_destroy (context);
1027 return (failure_count);
1028 } /* }}} int post_loop_hook */
1030 int main (int argc, char **argv) /* {{{ */
1033 pingobj_iter_t *iter;
1035 struct sigaction sigint_action;
1037 struct timeval tv_begin;
1038 struct timeval tv_end;
1039 struct timespec ts_wait;
1040 struct timespec ts_int;
1045 #if _POSIX_SAVED_IDS
1046 uid_t saved_set_uid;
1048 /* Save the old effective user id */
1049 saved_set_uid = geteuid ();
1050 /* Set the effective user ID to the real user ID without changing the
1051 * saved set-user ID */
1052 status = seteuid (getuid ());
1055 fprintf (stderr, "Temporarily dropping privileges "
1056 "failed: %s\n", strerror (errno));
1057 exit (EXIT_FAILURE);
1061 optind = read_options (argc, argv);
1063 #if !_POSIX_SAVED_IDS
1064 /* Cannot temporarily drop privileges -> reject every file but "-". */
1065 if ((opt_filename != NULL)
1066 && (strcmp ("-", opt_filename) != 0)
1067 && (getuid () != geteuid ()))
1069 fprintf (stderr, "Your real and effective user IDs don't "
1070 "match. Reading from a file (option '-f')\n"
1071 "is therefore too risky. You can still read "
1072 "from STDIN using '-f -' if you like.\n"
1074 exit (EXIT_FAILURE);
1078 if ((optind >= argc) && (opt_filename == NULL)) {
1079 usage_exit (argv[0], 1);
1082 if ((ping = ping_construct ()) == NULL)
1084 fprintf (stderr, "ping_construct failed\n");
1088 if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
1090 fprintf (stderr, "Setting TTL to %i failed: %s\n",
1091 opt_send_ttl, ping_get_error (ping));
1094 if (ping_setopt (ping, PING_OPT_QOS, &opt_send_qos) != 0)
1096 fprintf (stderr, "Setting TOS to %i failed: %s\n",
1097 opt_send_qos, ping_get_error (ping));
1104 temp_nsec = modf (opt_interval, &temp_sec);
1105 ts_int.tv_sec = (time_t) temp_sec;
1106 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
1108 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
1111 if (opt_addrfamily != PING_DEF_AF)
1112 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
1114 if (opt_srcaddr != NULL)
1116 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
1118 fprintf (stderr, "Setting source address failed: %s\n",
1119 ping_get_error (ping));
1123 if (opt_device != NULL)
1125 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
1127 fprintf (stderr, "Setting device failed: %s\n",
1128 ping_get_error (ping));
1132 if (opt_filename != NULL)
1138 if (strcmp (opt_filename, "-") == 0)
1140 infile = fdopen(0, "r");
1142 infile = fopen(opt_filename, "r");
1146 fprintf (stderr, "Opening %s failed: %s\n",
1147 (strcmp (opt_filename, "-") == 0)
1148 ? "STDIN" : opt_filename,
1153 #if _POSIX_SAVED_IDS
1154 /* Regain privileges */
1155 status = seteuid (saved_set_uid);
1158 fprintf (stderr, "Temporarily re-gaining privileges "
1159 "failed: %s\n", strerror (errno));
1160 exit (EXIT_FAILURE);
1164 while (fgets(line, sizeof(line), infile))
1166 /* Strip whitespace */
1167 if (sscanf(line, "%s", host) != 1)
1170 if ((host[0] == 0) || (host[0] == '#'))
1173 if (ping_host_add(ping, host) < 0)
1175 const char *errmsg = ping_get_error (ping);
1177 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
1186 #if _POSIX_SAVED_IDS
1187 /* Drop privileges */
1188 status = seteuid (getuid ());
1191 fprintf (stderr, "Temporarily dropping privileges "
1192 "failed: %s\n", strerror (errno));
1193 exit (EXIT_FAILURE);
1200 #if _POSIX_SAVED_IDS
1201 /* Regain privileges */
1202 status = seteuid (saved_set_uid);
1205 fprintf (stderr, "Temporarily re-gaining privileges "
1206 "failed: %s\n", strerror (errno));
1207 exit (EXIT_FAILURE);
1211 for (i = optind; i < argc; i++)
1213 if (ping_host_add (ping, argv[i]) < 0)
1215 const char *errmsg = ping_get_error (ping);
1217 fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
1226 /* Permanently drop root privileges if we're setuid-root. */
1227 status = setuid (getuid ());
1230 fprintf (stderr, "Dropping privileges failed: %s\n",
1232 exit (EXIT_FAILURE);
1235 #if _POSIX_SAVED_IDS
1236 saved_set_uid = (uid_t) -1;
1239 ping_initialize_contexts (ping);
1244 memset (&sigint_action, '\0', sizeof (sigint_action));
1245 sigint_action.sa_handler = sigint_handler;
1246 if (sigaction (SIGINT, &sigint_action, NULL) < 0)
1248 perror ("sigaction");
1252 pre_loop_hook (ping);
1254 while (opt_count != 0)
1259 if (gettimeofday (&tv_begin, NULL) < 0)
1261 perror ("gettimeofday");
1265 if (ping_send (ping) < 0)
1267 fprintf (stderr, "ping_send failed: %s\n",
1268 ping_get_error (ping));
1273 for (iter = ping_iterator_get (ping);
1275 iter = ping_iterator_next (iter))
1277 update_host_hook (iter, index);
1281 pre_sleep_hook (ping);
1283 /* Don't sleep in the last iteration */
1287 if (gettimeofday (&tv_end, NULL) < 0)
1289 perror ("gettimeofday");
1293 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1295 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1296 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1300 perror ("nanosleep");
1303 else if (opt_count == 0)
1310 post_sleep_hook (ping);
1314 } /* while (opt_count != 0) */
1316 status = post_loop_hook (ping);
1318 ping_destroy (ping);
1321 return (EXIT_FAILURE + status);
1323 return (EXIT_SUCCESS);
1324 } /* }}} int main */
1326 /* vim: set fdm=marker : */