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) || (tmp < 0.0) || (tmp > 100.0))
553 fprintf (stderr, "Ignoring invalid -Z argument: %s\n", optarg);
554 fprintf (stderr, "The \"-Z\" option requires a numeric argument between 0 and 100.\n");
557 opt_exit_status_threshold = tmp / 100.0;
563 usage_exit (argv[0], 0);
566 usage_exit (argv[0], 1);
571 } /* }}} read_options */
573 static void time_normalize (struct timespec *ts) /* {{{ */
575 while (ts->tv_nsec < 0)
584 ts->tv_nsec += 1000000000;
587 while (ts->tv_nsec >= 1000000000)
590 ts->tv_nsec -= 1000000000;
592 } /* }}} void time_normalize */
594 static void time_calc (struct timespec *ts_dest, /* {{{ */
595 const struct timespec *ts_int,
596 const struct timeval *tv_begin,
597 const struct timeval *tv_end)
599 ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
600 ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
601 time_normalize (ts_dest);
603 /* Assure that `(begin + interval) > end'.
604 * This may seem overly complicated, but `tv_sec' is of type `time_t'
605 * which may be `unsigned. *sigh* */
606 if ((tv_end->tv_sec > ts_dest->tv_sec)
607 || ((tv_end->tv_sec == ts_dest->tv_sec)
608 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
611 ts_dest->tv_nsec = 0;
615 ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
616 ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
617 time_normalize (ts_dest);
618 } /* }}} void time_calc */
621 static int update_stats_from_context (ping_context_t *ctx) /* {{{ */
623 if ((ctx == NULL) || (ctx->window == NULL))
626 werase (ctx->window);
628 box (ctx->window, 0, 0);
629 wattron (ctx->window, A_BOLD);
630 mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
632 wattroff (ctx->window, A_BOLD);
633 wprintw (ctx->window, "ping statistics ");
634 mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
635 "%i packets transmitted, %i received, %.2f%% packet "
637 ctx->req_sent, ctx->req_rcvd,
638 context_get_packet_loss (ctx),
640 if (ctx->req_rcvd != 0)
645 average = context_get_average (ctx);
646 deviation = context_get_stddev (ctx);
648 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
649 "rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms",
656 wrefresh (ctx->window);
659 } /* }}} int update_stats_from_context */
661 static int on_resize (pingobj_t *ping) /* {{{ */
663 pingobj_iter_t *iter;
668 getmaxyx (stdscr, height, width);
669 if ((height < 1) || (width < 1))
672 main_win_height = height - (4 * host_num);
673 wresize (main_win, main_win_height, /* width = */ width);
674 /* Allow scrolling */
675 scrollok (main_win, TRUE);
676 /* wsetscrreg (main_win, 0, main_win_height - 1); */
677 /* Allow hardware accelerated scrolling. */
678 idlok (main_win, TRUE);
681 for (iter = ping_iterator_get (ping);
683 iter = ping_iterator_next (iter))
685 ping_context_t *context;
687 context = ping_iterator_get_context (iter);
691 if (context->window != NULL)
693 delwin (context->window);
694 context->window = NULL;
696 context->window = newwin (/* height = */ 4,
698 /* y = */ main_win_height + (4 * context->index),
705 static int check_resize (pingobj_t *ping) /* {{{ */
711 int key = wgetch (stdscr);
714 else if (key == KEY_RESIZE)
719 return (on_resize (ping));
722 } /* }}} int check_resize */
724 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
726 pingobj_iter_t *iter;
734 nodelay (stdscr, TRUE);
736 getmaxyx (stdscr, height, width);
737 if ((height < 1) || (width < 1))
740 if (has_colors () == TRUE)
743 init_pair (OPING_GREEN, COLOR_GREEN, /* default = */ 0);
744 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
745 init_pair (OPING_RED, COLOR_RED, /* default = */ 0);
748 main_win_height = height - (4 * host_num);
749 main_win = newwin (/* height = */ main_win_height,
751 /* y = */ 0, /* x = */ 0);
752 /* Allow scrolling */
753 scrollok (main_win, TRUE);
754 /* wsetscrreg (main_win, 0, main_win_height - 1); */
755 /* Allow hardware accelerated scrolling. */
756 idlok (main_win, TRUE);
757 wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
760 for (iter = ping_iterator_get (ping);
762 iter = ping_iterator_next (iter))
764 ping_context_t *context;
766 context = ping_iterator_get_context (iter);
770 if (context->window != NULL)
772 delwin (context->window);
773 context->window = NULL;
775 context->window = newwin (/* height = */ 4,
777 /* y = */ main_win_height + (4 * context->index),
782 /* Don't know what good this does exactly, but without this code
783 * "check_resize" will be called right after startup and *somehow*
784 * this leads to display errors. If we purge all initial characters
785 * here, the problem goes away. "wgetch" is non-blocking due to
786 * "nodelay" (see above). */
787 while (wgetch (stdscr) != ERR)
789 /* eat up characters */;
793 } /* }}} int pre_loop_hook */
795 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
797 return (check_resize (ping));
798 } /* }}} int pre_sleep_hook */
800 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
802 return (check_resize (ping));
803 } /* }}} int pre_sleep_hook */
804 #else /* if !USE_NCURSES */
805 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
807 pingobj_iter_t *iter;
809 for (iter = ping_iterator_get (ping);
811 iter = ping_iterator_next (iter))
816 ctx = ping_iterator_get_context (iter);
821 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
823 printf ("PING %s (%s) %zu bytes of data.\n",
824 ctx->host, ctx->addr, buffer_size);
828 } /* }}} int pre_loop_hook */
830 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
835 } /* }}} int pre_sleep_hook */
837 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
840 } /* }}} int post_sleep_hook */
843 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
844 __attribute__((unused)) int index)
847 unsigned int sequence;
850 char recv_qos_str[16];
853 ping_context_t *context;
856 buffer_len = sizeof (latency);
857 ping_iterator_get_info (iter, PING_INFO_LATENCY,
858 &latency, &buffer_len);
861 buffer_len = sizeof (sequence);
862 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
863 &sequence, &buffer_len);
866 buffer_len = sizeof (recv_ttl);
867 ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
868 &recv_ttl, &buffer_len);
871 buffer_len = sizeof (recv_qos);
872 ping_iterator_get_info (iter, PING_INFO_RECV_QOS,
873 &recv_qos, &buffer_len);
876 ping_iterator_get_info (iter, PING_INFO_DATA,
879 context = (ping_context_t *) ping_iterator_get_context (iter);
882 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
884 # define HOST_PRINTF(...) printf(__VA_ARGS__)
891 context->latency_total += latency;
892 context->latency_total_square += (latency * latency);
894 if ((context->latency_max < 0.0) || (context->latency_max < latency))
895 context->latency_max = latency;
896 if ((context->latency_min < 0.0) || (context->latency_min > latency))
897 context->latency_min = latency;
900 if (has_colors () == TRUE)
902 int color = OPING_GREEN;
903 double average = context_get_average (context);
904 double stddev = context_get_stddev (context);
906 if ((latency < (average - (2 * stddev)))
907 || (latency > (average + (2 * stddev))))
909 else if ((latency < (average - stddev))
910 || (latency > (average + stddev)))
911 color = OPING_YELLOW;
913 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
914 data_len, context->host, context->addr,
916 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
917 if ((recv_qos != 0) || (opt_send_qos != 0))
919 HOST_PRINTF ("qos=%s ",
920 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
922 HOST_PRINTF ("time=");
923 wattron (main_win, COLOR_PAIR(color));
924 HOST_PRINTF ("%.2f", latency);
925 wattroff (main_win, COLOR_PAIR(color));
926 HOST_PRINTF (" ms\n");
931 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
933 context->host, context->addr,
935 if ((recv_qos != 0) || (opt_send_qos != 0))
937 HOST_PRINTF ("qos=%s ",
938 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
940 HOST_PRINTF ("time=%.2f ms\n", latency);
948 if (has_colors () == TRUE)
950 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
951 context->host, context->addr,
953 wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
954 HOST_PRINTF ("timeout");
955 wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
961 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
962 context->host, context->addr,
970 update_stats_from_context (context);
973 } /* }}} void update_host_hook */
975 /* Returns the number of hosts which failed to return more than the
976 fraction opt_exit_status_threshold of pings */
977 static int post_loop_hook (pingobj_t *ping) /* {{{ */
979 pingobj_iter_t *iter;
980 int failure_count = 0;
986 for (iter = ping_iterator_get (ping);
988 iter = ping_iterator_next (iter))
990 ping_context_t *context;
992 context = ping_iterator_get_context (iter);
994 printf ("\n--- %s ping statistics ---\n"
995 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
996 context->host, context->req_sent, context->req_rcvd,
997 context_get_packet_loss (context),
998 context->latency_total);
1001 double pct_failed = 1.0 - (((double) context->req_rcvd)
1002 / ((double) context->req_sent));
1003 if (pct_failed > opt_exit_status_threshold)
1007 if (context->req_rcvd != 0)
1012 average = context_get_average (context);
1013 deviation = context_get_stddev (context);
1015 printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
1016 context->latency_min,
1018 context->latency_max,
1022 ping_iterator_set_context (iter, NULL);
1023 context_destroy (context);
1026 return (failure_count);
1027 } /* }}} int post_loop_hook */
1029 int main (int argc, char **argv) /* {{{ */
1032 pingobj_iter_t *iter;
1034 struct sigaction sigint_action;
1036 struct timeval tv_begin;
1037 struct timeval tv_end;
1038 struct timespec ts_wait;
1039 struct timespec ts_int;
1044 #if _POSIX_SAVED_IDS
1045 uid_t saved_set_uid;
1047 /* Save the old effective user id */
1048 saved_set_uid = geteuid ();
1049 /* Set the effective user ID to the real user ID without changing the
1050 * saved set-user ID */
1051 status = seteuid (getuid ());
1054 fprintf (stderr, "Temporarily dropping privileges "
1055 "failed: %s\n", strerror (errno));
1056 exit (EXIT_FAILURE);
1060 optind = read_options (argc, argv);
1062 #if !_POSIX_SAVED_IDS
1063 /* Cannot temporarily drop privileges -> reject every file but "-". */
1064 if ((opt_filename != NULL)
1065 && (strcmp ("-", opt_filename) != 0)
1066 && (getuid () != geteuid ()))
1068 fprintf (stderr, "Your real and effective user IDs don't "
1069 "match. Reading from a file (option '-f')\n"
1070 "is therefore too risky. You can still read "
1071 "from STDIN using '-f -' if you like.\n"
1073 exit (EXIT_FAILURE);
1077 if ((optind >= argc) && (opt_filename == NULL)) {
1078 usage_exit (argv[0], 1);
1081 if ((ping = ping_construct ()) == NULL)
1083 fprintf (stderr, "ping_construct failed\n");
1087 if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
1089 fprintf (stderr, "Setting TTL to %i failed: %s\n",
1090 opt_send_ttl, ping_get_error (ping));
1093 if (ping_setopt (ping, PING_OPT_QOS, &opt_send_qos) != 0)
1095 fprintf (stderr, "Setting TOS to %i failed: %s\n",
1096 opt_send_qos, ping_get_error (ping));
1103 temp_nsec = modf (opt_interval, &temp_sec);
1104 ts_int.tv_sec = (time_t) temp_sec;
1105 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
1107 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
1110 if (opt_addrfamily != PING_DEF_AF)
1111 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
1113 if (opt_srcaddr != NULL)
1115 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
1117 fprintf (stderr, "Setting source address failed: %s\n",
1118 ping_get_error (ping));
1122 if (opt_device != NULL)
1124 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
1126 fprintf (stderr, "Setting device failed: %s\n",
1127 ping_get_error (ping));
1131 if (opt_filename != NULL)
1137 if (strcmp (opt_filename, "-") == 0)
1139 infile = fdopen(0, "r");
1141 infile = fopen(opt_filename, "r");
1145 fprintf (stderr, "Opening %s failed: %s\n",
1146 (strcmp (opt_filename, "-") == 0)
1147 ? "STDIN" : opt_filename,
1152 #if _POSIX_SAVED_IDS
1153 /* Regain privileges */
1154 status = seteuid (saved_set_uid);
1157 fprintf (stderr, "Temporarily re-gaining privileges "
1158 "failed: %s\n", strerror (errno));
1159 exit (EXIT_FAILURE);
1163 while (fgets(line, sizeof(line), infile))
1165 /* Strip whitespace */
1166 if (sscanf(line, "%s", host) != 1)
1169 if ((host[0] == 0) || (host[0] == '#'))
1172 if (ping_host_add(ping, host) < 0)
1174 const char *errmsg = ping_get_error (ping);
1176 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
1185 #if _POSIX_SAVED_IDS
1186 /* Drop privileges */
1187 status = seteuid (getuid ());
1190 fprintf (stderr, "Temporarily dropping privileges "
1191 "failed: %s\n", strerror (errno));
1192 exit (EXIT_FAILURE);
1199 #if _POSIX_SAVED_IDS
1200 /* Regain privileges */
1201 status = seteuid (saved_set_uid);
1204 fprintf (stderr, "Temporarily re-gaining privileges "
1205 "failed: %s\n", strerror (errno));
1206 exit (EXIT_FAILURE);
1210 for (i = optind; i < argc; i++)
1212 if (ping_host_add (ping, argv[i]) < 0)
1214 const char *errmsg = ping_get_error (ping);
1216 fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
1225 /* Permanently drop root privileges if we're setuid-root. */
1226 status = setuid (getuid ());
1229 fprintf (stderr, "Dropping privileges failed: %s\n",
1231 exit (EXIT_FAILURE);
1234 #if _POSIX_SAVED_IDS
1235 saved_set_uid = (uid_t) -1;
1238 ping_initialize_contexts (ping);
1243 memset (&sigint_action, '\0', sizeof (sigint_action));
1244 sigint_action.sa_handler = sigint_handler;
1245 if (sigaction (SIGINT, &sigint_action, NULL) < 0)
1247 perror ("sigaction");
1251 pre_loop_hook (ping);
1253 while (opt_count != 0)
1258 if (gettimeofday (&tv_begin, NULL) < 0)
1260 perror ("gettimeofday");
1264 if (ping_send (ping) < 0)
1266 fprintf (stderr, "ping_send failed: %s\n",
1267 ping_get_error (ping));
1272 for (iter = ping_iterator_get (ping);
1274 iter = ping_iterator_next (iter))
1276 update_host_hook (iter, index);
1280 pre_sleep_hook (ping);
1282 /* Don't sleep in the last iteration */
1286 if (gettimeofday (&tv_end, NULL) < 0)
1288 perror ("gettimeofday");
1292 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1294 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1295 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1299 perror ("nanosleep");
1302 else if (opt_count == 0)
1309 post_sleep_hook (ping);
1313 } /* while (opt_count != 0) */
1315 status = post_loop_hook (ping);
1317 ping_destroy (ping);
1320 return (EXIT_FAILURE + status);
1322 return (EXIT_SUCCESS);
1323 } /* }}} int main */
1325 /* vim: set fdm=marker : */