1 /**
2 * Object oriented C module to send ICMP and ICMPv6 `echo's.
3 * Copyright (C) 2006-2010 Florian octo Forster <octo at verplant.org>
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 #if USE_NCURSES
78 # define NCURSES_OPAQUE 1
79 # include <ncurses.h>
81 # define OPING_GREEN 1
82 # define OPING_YELLOW 2
83 # define OPING_RED 3
84 #endif
86 #include "oping.h"
88 #ifndef _POSIX_SAVED_IDS
89 # define _POSIX_SAVED_IDS 0
90 #endif
92 typedef struct ping_context
93 {
94 char host[NI_MAXHOST];
95 char addr[NI_MAXHOST];
97 int index;
98 int req_sent;
99 int req_rcvd;
101 double latency_min;
102 double latency_max;
103 double latency_total;
104 double latency_total_square;
106 #if USE_NCURSES
107 WINDOW *window;
108 #endif
109 } ping_context_t;
111 static double opt_interval = 1.0;
112 static int opt_addrfamily = PING_DEF_AF;
113 static char *opt_srcaddr = NULL;
114 static char *opt_device = NULL;
115 static char *opt_filename = NULL;
116 static int opt_count = -1;
117 static int opt_send_ttl = 64;
118 static uint8_t opt_send_qos = 0;
120 static int host_num = 0;
122 #if USE_NCURSES
123 static WINDOW *main_win = NULL;
124 #endif
126 static void sigint_handler (int signal) /* {{{ */
127 {
128 /* Make compiler happy */
129 signal = 0;
130 /* Exit the loop */
131 opt_count = 0;
132 } /* }}} void sigint_handler */
134 static ping_context_t *context_create (void) /* {{{ */
135 {
136 ping_context_t *ret;
138 if ((ret = malloc (sizeof (ping_context_t))) == NULL)
139 return (NULL);
141 memset (ret, '\0', sizeof (ping_context_t));
143 ret->latency_min = -1.0;
144 ret->latency_max = -1.0;
145 ret->latency_total = 0.0;
146 ret->latency_total_square = 0.0;
148 #if USE_NCURSES
149 ret->window = NULL;
150 #endif
152 return (ret);
153 } /* }}} ping_context_t *context_create */
155 static void context_destroy (ping_context_t *context) /* {{{ */
156 {
157 if (context == NULL)
158 return;
160 #if USE_NCURSES
161 if (context->window != NULL)
162 {
163 delwin (context->window);
164 context->window = NULL;
165 }
166 #endif
168 free (context);
169 } /* }}} void context_destroy */
171 static double context_get_average (ping_context_t *ctx) /* {{{ */
172 {
173 double num_total;
175 if (ctx == NULL)
176 return (-1.0);
178 if (ctx->req_rcvd < 1)
179 return (-0.0);
181 num_total = (double) ctx->req_rcvd;
182 return (ctx->latency_total / num_total);
183 } /* }}} double context_get_average */
185 static double context_get_stddev (ping_context_t *ctx) /* {{{ */
186 {
187 double num_total;
189 if (ctx == NULL)
190 return (-1.0);
192 if (ctx->req_rcvd < 1)
193 return (-0.0);
194 else if (ctx->req_rcvd < 2)
195 return (0.0);
197 num_total = (double) ctx->req_rcvd;
198 return (sqrt (((num_total * ctx->latency_total_square)
199 - (ctx->latency_total * ctx->latency_total))
200 / (num_total * (num_total - 1.0))));
201 } /* }}} double context_get_stddev */
203 static double context_get_packet_loss (const ping_context_t *ctx) /* {{{ */
204 {
205 if (ctx == NULL)
206 return (-1.0);
208 if (ctx->req_sent < 1)
209 return (0.0);
211 return (100.0 * (ctx->req_sent - ctx->req_rcvd)
212 / ((double) ctx->req_sent));
213 } /* }}} double context_get_packet_loss */
215 static int ping_initialize_contexts (pingobj_t *ping) /* {{{ */
216 {
217 pingobj_iter_t *iter;
218 int index;
220 if (ping == NULL)
221 return (EINVAL);
223 index = 0;
224 for (iter = ping_iterator_get (ping);
225 iter != NULL;
226 iter = ping_iterator_next (iter))
227 {
228 ping_context_t *context;
229 size_t buffer_size;
231 context = context_create ();
232 context->index = index;
234 buffer_size = sizeof (context->host);
235 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
237 buffer_size = sizeof (context->addr);
238 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
240 ping_iterator_set_context (iter, (void *) context);
242 index++;
243 }
245 return (0);
246 } /* }}} int ping_initialize_contexts */
248 static void usage_exit (const char *name, int status) /* {{{ */
249 {
250 int name_length;
252 name_length = (int) strlen (name);
254 fprintf (stderr, "Usage: %s [OPTIONS] "
255 "-f filename | host [host [host ...]]\n"
257 "\nAvailable options:\n"
258 " -4|-6 force the use of IPv4 or IPv6\n"
259 " -c count number of ICMP packets to send\n"
260 " -i interval interval with which to send ICMP packets\n"
261 " -t ttl time to live for each ICMP packet\n"
262 " -Q qos Quality of Service (QoS) of outgoing packets\n"
263 " Use \"-Q help\" for a list of valid options.\n"
264 " -I srcaddr source address\n"
265 " -D device outgoing interface name\n"
266 " -f filename filename to read hosts from\n"
268 "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
269 "by Florian octo Forster <octo@verplant.org>\n"
270 "for contributions see `AUTHORS'\n",
271 name);
272 exit (status);
273 } /* }}} void usage_exit */
275 static void usage_tos_exit (const char *arg, int status) /* {{{ */
276 {
277 if (arg != 0)
278 fprintf (stderr, "Invalid QoS argument: \"%s\"\n\n", arg);
280 fprintf (stderr, "Valid QoS arguments (option \"-Q\") are:\n"
281 "\n"
282 " Differentiated Services (IPv4 and IPv6, RFC 2474)\n"
283 "\n"
284 " ef Expedited Forwarding (EF) PHB group (RFC 3246).\n"
285 " (low delay, low loss, low jitter)\n"
286 " af[1-4][1-3] Assured Forwarding (AF) PHB group (RFC 2597).\n"
287 " For example: \"af12\" (class 1, precedence 2)\n"
288 "\n"
289 " Type of Service (IPv4, RFC 1349, obsolete)\n"
290 "\n"
291 " lowdelay (%#04x) minimize delay\n"
292 " throughput (%#04x) maximize throughput\n"
293 " reliability (%#04x) maximize reliability\n"
294 " mincost (%#04x) minimize monetary cost\n"
295 "\n"
296 " Specify manually\n"
297 "\n"
298 " 0x00 - 0xff Hexadecimal numeric specification.\n"
299 " 0 - 255 Decimal numeric specification.\n"
300 "\n",
301 (unsigned int) IPTOS_LOWDELAY,
302 (unsigned int) IPTOS_THROUGHPUT,
303 (unsigned int) IPTOS_RELIABILITY,
304 (unsigned int) IPTOS_MINCOST);
306 exit (status);
307 } /* }}} void usage_tos_exit */
309 static int set_opt_send_qos (const char *opt) /* {{{ */
310 {
311 if (opt == NULL)
312 return (EINVAL);
314 if (strcasecmp ("help", opt) == 0)
315 usage_tos_exit (/* arg = */ NULL, /* status = */ EXIT_SUCCESS);
316 /* Type of Service (RFC 1349) */
317 else if (strcasecmp ("lowdelay", opt) == 0)
318 opt_send_qos = IPTOS_LOWDELAY;
319 else if (strcasecmp ("throughput", opt) == 0)
320 opt_send_qos = IPTOS_THROUGHPUT;
321 else if (strcasecmp ("reliability", opt) == 0)
322 opt_send_qos = IPTOS_RELIABILITY;
323 else if (strcasecmp ("mincost", opt) == 0)
324 opt_send_qos = IPTOS_MINCOST;
325 /* DiffServ (RFC 2474): */
326 /* * Expedited Forwarding (EF, RFC 3246) */
327 else if (strcasecmp ("ef", opt) == 0)
328 opt_send_qos = 0xB8; /* == 0x2E << 2 */
329 /* Assured Forwarding (AF, RFC 2597) */
330 else if (strncasecmp ("af", opt, strlen ("af")) == 0)
331 {
332 uint8_t dscp;
333 uint8_t class;
334 uint8_t prec;
336 /* There are four classes, AF1x, AF2x, AF3x, and AF4x. */
337 if (opt[2] == '1')
338 class = 1;
339 else if (opt[2] == '2')
340 class = 2;
341 else if (opt[2] == '3')
342 class = 3;
343 else if (opt[2] == '4')
344 class = 4;
345 else
346 usage_tos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
348 /* In each class, there are three precedences, AFx1, AFx2, and AFx3 */
349 if (opt[3] == '1')
350 prec = 1;
351 else if (opt[3] == '2')
352 prec = 2;
353 else if (opt[3] == '3')
354 prec = 3;
355 else
356 usage_tos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
358 dscp = (8 * class) + (2 * prec);
359 /* The lower two bits are used for Explicit Congestion Notification (ECN) */
360 opt_send_qos = dscp << 2;
361 }
362 else
363 {
364 unsigned long value;
365 char *endptr;
367 errno = 0;
368 endptr = NULL;
369 value = strtoul (opt, &endptr, /* base = */ 0);
370 if ((errno != 0) || (endptr == opt)
371 || (endptr == NULL) || (*endptr != 0)
372 || (value > 0xff))
373 usage_tos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
375 opt_send_qos = (uint8_t) value;
376 }
378 return (0);
379 } /* }}} int set_opt_send_qos */
381 static int read_options (int argc, char **argv) /* {{{ */
382 {
383 int optchar;
385 while (1)
386 {
387 optchar = getopt (argc, argv, "46c:hi:I:t:Q:f:D:");
389 if (optchar == -1)
390 break;
392 switch (optchar)
393 {
394 case '4':
395 case '6':
396 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
397 break;
399 case 'c':
400 {
401 int new_count;
402 new_count = atoi (optarg);
403 if (new_count > 0)
404 opt_count = new_count;
405 else
406 fprintf(stderr, "Ignoring invalid count: %s\n",
407 optarg);
408 }
409 break;
411 case 'f':
412 {
413 if (opt_filename != NULL)
414 free (opt_filename);
415 opt_filename = strdup (optarg);
416 }
417 break;
419 case 'i':
420 {
421 double new_interval;
422 new_interval = atof (optarg);
423 if (new_interval < 0.001)
424 fprintf (stderr, "Ignoring invalid interval: %s\n",
425 optarg);
426 else
427 opt_interval = new_interval;
428 }
429 break;
430 case 'I':
431 {
432 if (opt_srcaddr != NULL)
433 free (opt_srcaddr);
434 opt_srcaddr = strdup (optarg);
435 }
436 break;
438 case 'D':
439 opt_device = optarg;
440 break;
442 case 't':
443 {
444 int new_send_ttl;
445 new_send_ttl = atoi (optarg);
446 if ((new_send_ttl > 0) && (new_send_ttl < 256))
447 opt_send_ttl = new_send_ttl;
448 else
449 fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
450 optarg);
451 break;
452 }
454 case 'Q':
455 set_opt_send_qos (optarg);
456 break;
458 case 'h':
459 usage_exit (argv[0], 0);
460 break;
461 default:
462 usage_exit (argv[0], 1);
463 }
464 }
466 return (optind);
467 } /* }}} read_options */
469 static void time_normalize (struct timespec *ts) /* {{{ */
470 {
471 while (ts->tv_nsec < 0)
472 {
473 if (ts->tv_sec == 0)
474 {
475 ts->tv_nsec = 0;
476 return;
477 }
479 ts->tv_sec -= 1;
480 ts->tv_nsec += 1000000000;
481 }
483 while (ts->tv_nsec >= 1000000000)
484 {
485 ts->tv_sec += 1;
486 ts->tv_nsec -= 1000000000;
487 }
488 } /* }}} void time_normalize */
490 static void time_calc (struct timespec *ts_dest, /* {{{ */
491 const struct timespec *ts_int,
492 const struct timeval *tv_begin,
493 const struct timeval *tv_end)
494 {
495 ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
496 ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
497 time_normalize (ts_dest);
499 /* Assure that `(begin + interval) > end'.
500 * This may seem overly complicated, but `tv_sec' is of type `time_t'
501 * which may be `unsigned. *sigh* */
502 if ((tv_end->tv_sec > ts_dest->tv_sec)
503 || ((tv_end->tv_sec == ts_dest->tv_sec)
504 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
505 {
506 ts_dest->tv_sec = 0;
507 ts_dest->tv_nsec = 0;
508 return;
509 }
511 ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
512 ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
513 time_normalize (ts_dest);
514 } /* }}} void time_calc */
516 #if USE_NCURSES
517 static int update_stats_from_context (ping_context_t *ctx) /* {{{ */
518 {
519 if ((ctx == NULL) || (ctx->window == NULL))
520 return (EINVAL);
522 werase (ctx->window);
524 box (ctx->window, 0, 0);
525 wattron (ctx->window, A_BOLD);
526 mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
527 " %s ", ctx->host);
528 wattroff (ctx->window, A_BOLD);
529 wprintw (ctx->window, "ping statistics ");
530 mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
531 "%i packets transmitted, %i received, %.2f%% packet "
532 "loss, time %.1fms",
533 ctx->req_sent, ctx->req_rcvd,
534 context_get_packet_loss (ctx),
535 ctx->latency_total);
536 if (ctx->req_rcvd != 0)
537 {
538 double average;
539 double deviation;
541 average = context_get_average (ctx);
542 deviation = context_get_stddev (ctx);
544 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
545 "rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms",
546 ctx->latency_min,
547 average,
548 ctx->latency_max,
549 deviation);
550 }
552 wrefresh (ctx->window);
554 return (0);
555 } /* }}} int update_stats_from_context */
557 static int on_resize (pingobj_t *ping) /* {{{ */
558 {
559 pingobj_iter_t *iter;
560 int width = 0;
561 int height = 0;
562 int main_win_height;
564 getmaxyx (stdscr, height, width);
565 if ((height < 1) || (width < 1))
566 return (EINVAL);
568 main_win_height = height - (4 * host_num);
569 wresize (main_win, main_win_height, /* width = */ width);
570 /* Allow scrolling */
571 scrollok (main_win, TRUE);
572 /* wsetscrreg (main_win, 0, main_win_height - 1); */
573 /* Allow hardware accelerated scrolling. */
574 idlok (main_win, TRUE);
575 wrefresh (main_win);
577 for (iter = ping_iterator_get (ping);
578 iter != NULL;
579 iter = ping_iterator_next (iter))
580 {
581 ping_context_t *context;
583 context = ping_iterator_get_context (iter);
584 if (context == NULL)
585 continue;
587 if (context->window != NULL)
588 {
589 delwin (context->window);
590 context->window = NULL;
591 }
592 context->window = newwin (/* height = */ 4,
593 /* width = */ 0,
594 /* y = */ main_win_height + (4 * context->index),
595 /* x = */ 0);
596 }
598 return (0);
599 } /* }}} */
601 static int check_resize (pingobj_t *ping) /* {{{ */
602 {
603 int need_resize = 0;
605 while (42)
606 {
607 int key = wgetch (stdscr);
608 if (key == ERR)
609 break;
610 else if (key == KEY_RESIZE)
611 need_resize = 1;
612 }
614 if (need_resize)
615 return (on_resize (ping));
616 else
617 return (0);
618 } /* }}} int check_resize */
620 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
621 {
622 pingobj_iter_t *iter;
623 int width = 0;
624 int height = 0;
625 int main_win_height;
627 initscr ();
628 cbreak ();
629 noecho ();
630 nodelay (stdscr, TRUE);
632 getmaxyx (stdscr, height, width);
633 if ((height < 1) || (width < 1))
634 return (EINVAL);
636 if (has_colors () == TRUE)
637 {
638 start_color ();
639 init_pair (OPING_GREEN, COLOR_GREEN, /* default = */ 0);
640 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
641 init_pair (OPING_RED, COLOR_RED, /* default = */ 0);
642 }
644 main_win_height = height - (4 * host_num);
645 main_win = newwin (/* height = */ main_win_height,
646 /* width = */ 0,
647 /* y = */ 0, /* x = */ 0);
648 /* Allow scrolling */
649 scrollok (main_win, TRUE);
650 /* wsetscrreg (main_win, 0, main_win_height - 1); */
651 /* Allow hardware accelerated scrolling. */
652 idlok (main_win, TRUE);
653 wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
654 wrefresh (main_win);
656 for (iter = ping_iterator_get (ping);
657 iter != NULL;
658 iter = ping_iterator_next (iter))
659 {
660 ping_context_t *context;
662 context = ping_iterator_get_context (iter);
663 if (context == NULL)
664 continue;
666 if (context->window != NULL)
667 {
668 delwin (context->window);
669 context->window = NULL;
670 }
671 context->window = newwin (/* height = */ 4,
672 /* width = */ 0,
673 /* y = */ main_win_height + (4 * context->index),
674 /* x = */ 0);
675 }
678 /* Don't know what good this does exactly, but without this code
679 * "check_resize" will be called right after startup and *somehow*
680 * this leads to display errors. If we purge all initial characters
681 * here, the problem goes away. "wgetch" is non-blocking due to
682 * "nodelay" (see above). */
683 while (wgetch (stdscr) != ERR)
684 {
685 /* eat up characters */;
686 }
688 return (0);
689 } /* }}} int pre_loop_hook */
691 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
692 {
693 return (check_resize (ping));
694 } /* }}} int pre_sleep_hook */
696 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
697 {
698 return (check_resize (ping));
699 } /* }}} int pre_sleep_hook */
700 #else /* if !USE_NCURSES */
701 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
702 {
703 pingobj_iter_t *iter;
705 for (iter = ping_iterator_get (ping);
706 iter != NULL;
707 iter = ping_iterator_next (iter))
708 {
709 ping_context_t *ctx;
710 size_t buffer_size;
712 ctx = ping_iterator_get_context (iter);
713 if (ctx == NULL)
714 continue;
716 buffer_size = 0;
717 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
719 printf ("PING %s (%s) %zu bytes of data.\n",
720 ctx->host, ctx->addr, buffer_size);
721 }
723 return (0);
724 } /* }}} int pre_loop_hook */
726 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
727 {
728 fflush (stdout);
730 return (0);
731 } /* }}} int pre_sleep_hook */
733 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
734 {
735 return (0);
736 } /* }}} int post_sleep_hook */
737 #endif
739 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
740 int index)
741 {
742 double latency;
743 unsigned int sequence;
744 int recv_ttl;
745 uint8_t recv_tos;
746 size_t buffer_len;
747 size_t data_len;
748 ping_context_t *context;
750 latency = -1.0;
751 buffer_len = sizeof (latency);
752 ping_iterator_get_info (iter, PING_INFO_LATENCY,
753 &latency, &buffer_len);
755 sequence = 0;
756 buffer_len = sizeof (sequence);
757 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
758 &sequence, &buffer_len);
760 recv_ttl = -1;
761 buffer_len = sizeof (recv_ttl);
762 ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
763 &recv_ttl, &buffer_len);
765 recv_tos = 0;
766 buffer_len = sizeof (recv_tos);
767 ping_iterator_get_info (iter, PING_INFO_RECV_TOS,
768 &recv_tos, &buffer_len);
770 data_len = 0;
771 ping_iterator_get_info (iter, PING_INFO_DATA,
772 NULL, &data_len);
774 context = (ping_context_t *) ping_iterator_get_context (iter);
776 #if USE_NCURSES
777 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
778 #else
779 # define HOST_PRINTF(...) printf(__VA_ARGS__)
780 #endif
782 context->req_sent++;
783 if (latency > 0.0)
784 {
785 context->req_rcvd++;
786 context->latency_total += latency;
787 context->latency_total_square += (latency * latency);
789 if ((context->latency_max < 0.0) || (context->latency_max < latency))
790 context->latency_max = latency;
791 if ((context->latency_min < 0.0) || (context->latency_min > latency))
792 context->latency_min = latency;
794 #if USE_NCURSES
795 if (has_colors () == TRUE)
796 {
797 int color = OPING_GREEN;
798 double average = context_get_average (context);
799 double stddev = context_get_stddev (context);
801 if ((latency < (average - (2 * stddev)))
802 || (latency > (average + (2 * stddev))))
803 color = OPING_RED;
804 else if ((latency < (average - stddev))
805 || (latency > (average + stddev)))
806 color = OPING_YELLOW;
808 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i tos=0x%02"PRIx8
809 " time=",
810 data_len, context->host, context->addr,
811 sequence, recv_ttl, recv_tos);
812 wattron (main_win, COLOR_PAIR(color));
813 HOST_PRINTF ("%.2f", latency);
814 wattroff (main_win, COLOR_PAIR(color));
815 HOST_PRINTF (" ms\n");
816 }
817 else
818 {
819 #endif
820 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i tos=0x%02"PRIx8
821 " time=%.2f ms\n",
822 data_len,
823 context->host, context->addr,
824 sequence, recv_ttl, recv_tos, latency);
825 #if USE_NCURSES
826 }
827 #endif
828 }
829 else
830 {
831 #if USE_NCURSES
832 if (has_colors () == TRUE)
833 {
834 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
835 context->host, context->addr,
836 sequence);
837 wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
838 HOST_PRINTF ("timeout");
839 wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
840 HOST_PRINTF ("\n");
841 }
842 else
843 {
844 #endif
845 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
846 context->host, context->addr,
847 sequence);
848 #if USE_NCURSES
849 }
850 #endif
851 }
853 #if USE_NCURSES
854 update_stats_from_context (context);
855 wrefresh (main_win);
856 #endif
857 } /* }}} void update_host_hook */
859 static int post_loop_hook (pingobj_t *ping) /* {{{ */
860 {
861 pingobj_iter_t *iter;
863 #if USE_NCURSES
864 endwin ();
865 #endif
867 for (iter = ping_iterator_get (ping);
868 iter != NULL;
869 iter = ping_iterator_next (iter))
870 {
871 ping_context_t *context;
873 context = ping_iterator_get_context (iter);
875 printf ("\n--- %s ping statistics ---\n"
876 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
877 context->host, context->req_sent, context->req_rcvd,
878 context_get_packet_loss (context),
879 context->latency_total);
881 if (context->req_rcvd != 0)
882 {
883 double average;
884 double deviation;
886 average = context_get_average (context);
887 deviation = context_get_stddev (context);
889 printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
890 context->latency_min,
891 average,
892 context->latency_max,
893 deviation);
894 }
896 ping_iterator_set_context (iter, NULL);
897 context_destroy (context);
898 }
900 return (0);
901 } /* }}} int post_loop_hook */
903 int main (int argc, char **argv) /* {{{ */
904 {
905 pingobj_t *ping;
906 pingobj_iter_t *iter;
908 struct sigaction sigint_action;
910 struct timeval tv_begin;
911 struct timeval tv_end;
912 struct timespec ts_wait;
913 struct timespec ts_int;
915 int optind;
916 int i;
917 int status;
918 #if _POSIX_SAVED_IDS
919 uid_t saved_set_uid;
921 /* Save the old effective user id */
922 saved_set_uid = geteuid ();
923 /* Set the effective user ID to the real user ID without changing the
924 * saved set-user ID */
925 status = seteuid (getuid ());
926 if (status != 0)
927 {
928 fprintf (stderr, "Temporarily dropping privileges "
929 "failed: %s\n", strerror (errno));
930 exit (EXIT_FAILURE);
931 }
932 #endif
934 optind = read_options (argc, argv);
936 #if !_POSIX_SAVED_IDS
937 /* Cannot temporarily drop privileges -> reject every file but "-". */
938 if ((opt_filename != NULL)
939 && (strcmp ("-", opt_filename) != 0)
940 && (getuid () != geteuid ()))
941 {
942 fprintf (stderr, "Your real and effective user IDs don't "
943 "match. Reading from a file (option '-f')\n"
944 "is therefore too risky. You can still read "
945 "from STDIN using '-f -' if you like.\n"
946 "Sorry.\n");
947 exit (EXIT_FAILURE);
948 }
949 #endif
951 if ((optind >= argc) && (opt_filename == NULL)) {
952 usage_exit (argv[0], 1);
953 }
955 if ((ping = ping_construct ()) == NULL)
956 {
957 fprintf (stderr, "ping_construct failed\n");
958 return (1);
959 }
961 if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
962 {
963 fprintf (stderr, "Setting TTL to %i failed: %s\n",
964 opt_send_ttl, ping_get_error (ping));
965 }
967 if (ping_setopt (ping, PING_OPT_TOS, &opt_send_qos) != 0)
968 {
969 fprintf (stderr, "Setting TOS to %i failed: %s\n",
970 opt_send_qos, ping_get_error (ping));
971 }
973 {
974 double temp_sec;
975 double temp_nsec;
977 temp_nsec = modf (opt_interval, &temp_sec);
978 ts_int.tv_sec = (time_t) temp_sec;
979 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
981 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
982 }
984 if (opt_addrfamily != PING_DEF_AF)
985 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
987 if (opt_srcaddr != NULL)
988 {
989 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
990 {
991 fprintf (stderr, "Setting source address failed: %s\n",
992 ping_get_error (ping));
993 }
994 }
996 if (opt_device != NULL)
997 {
998 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
999 {
1000 fprintf (stderr, "Setting device failed: %s\n",
1001 ping_get_error (ping));
1002 }
1003 }
1005 if (opt_filename != NULL)
1006 {
1007 FILE *infile;
1008 char line[256];
1009 char host[256];
1011 if (strcmp (opt_filename, "-") == 0)
1012 /* Open STDIN */
1013 infile = fdopen(0, "r");
1014 else
1015 infile = fopen(opt_filename, "r");
1017 if (infile == NULL)
1018 {
1019 fprintf (stderr, "Opening %s failed: %s\n",
1020 (strcmp (opt_filename, "-") == 0)
1021 ? "STDIN" : opt_filename,
1022 strerror(errno));
1023 return (1);
1024 }
1026 #if _POSIX_SAVED_IDS
1027 /* Regain privileges */
1028 status = seteuid (saved_set_uid);
1029 if (status != 0)
1030 {
1031 fprintf (stderr, "Temporarily re-gaining privileges "
1032 "failed: %s\n", strerror (errno));
1033 exit (EXIT_FAILURE);
1034 }
1035 #endif
1037 while (fgets(line, sizeof(line), infile))
1038 {
1039 /* Strip whitespace */
1040 if (sscanf(line, "%s", host) != 1)
1041 continue;
1043 if ((host[0] == 0) || (host[0] == '#'))
1044 continue;
1046 if (ping_host_add(ping, host) < 0)
1047 {
1048 const char *errmsg = ping_get_error (ping);
1050 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
1051 continue;
1052 }
1053 else
1054 {
1055 host_num++;
1056 }
1057 }
1059 #if _POSIX_SAVED_IDS
1060 /* Drop privileges */
1061 status = seteuid (getuid ());
1062 if (status != 0)
1063 {
1064 fprintf (stderr, "Temporarily dropping privileges "
1065 "failed: %s\n", strerror (errno));
1066 exit (EXIT_FAILURE);
1067 }
1068 #endif
1070 fclose(infile);
1071 }
1073 #if _POSIX_SAVED_IDS
1074 /* Regain privileges */
1075 status = seteuid (saved_set_uid);
1076 if (status != 0)
1077 {
1078 fprintf (stderr, "Temporarily re-gaining privileges "
1079 "failed: %s\n", strerror (errno));
1080 exit (EXIT_FAILURE);
1081 }
1082 #endif
1084 for (i = optind; i < argc; i++)
1085 {
1086 if (ping_host_add (ping, argv[i]) < 0)
1087 {
1088 const char *errmsg = ping_get_error (ping);
1090 fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
1091 continue;
1092 }
1093 else
1094 {
1095 host_num++;
1096 }
1097 }
1099 /* Permanently drop root privileges if we're setuid-root. */
1100 status = setuid (getuid ());
1101 if (status != 0)
1102 {
1103 fprintf (stderr, "Dropping privileges failed: %s\n",
1104 strerror (errno));
1105 exit (EXIT_FAILURE);
1106 }
1108 #if _POSIX_SAVED_IDS
1109 saved_set_uid = (uid_t) -1;
1110 #endif
1112 ping_initialize_contexts (ping);
1114 if (i == 0)
1115 return (1);
1117 memset (&sigint_action, '\0', sizeof (sigint_action));
1118 sigint_action.sa_handler = sigint_handler;
1119 if (sigaction (SIGINT, &sigint_action, NULL) < 0)
1120 {
1121 perror ("sigaction");
1122 return (1);
1123 }
1125 pre_loop_hook (ping);
1127 while (opt_count != 0)
1128 {
1129 int index;
1130 int status;
1132 if (gettimeofday (&tv_begin, NULL) < 0)
1133 {
1134 perror ("gettimeofday");
1135 return (1);
1136 }
1138 if (ping_send (ping) < 0)
1139 {
1140 fprintf (stderr, "ping_send failed: %s\n",
1141 ping_get_error (ping));
1142 return (1);
1143 }
1145 index = 0;
1146 for (iter = ping_iterator_get (ping);
1147 iter != NULL;
1148 iter = ping_iterator_next (iter))
1149 {
1150 update_host_hook (iter, index);
1151 index++;
1152 }
1154 pre_sleep_hook (ping);
1156 /* Don't sleep in the last iteration */
1157 if (opt_count == 1)
1158 break;
1160 if (gettimeofday (&tv_end, NULL) < 0)
1161 {
1162 perror ("gettimeofday");
1163 return (1);
1164 }
1166 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1168 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1169 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1170 {
1171 if (errno != EINTR)
1172 {
1173 perror ("nanosleep");
1174 break;
1175 }
1176 else if (opt_count == 0)
1177 {
1178 /* sigint */
1179 break;
1180 }
1181 }
1183 post_sleep_hook (ping);
1185 if (opt_count > 0)
1186 opt_count--;
1187 } /* while (opt_count != 0) */
1189 post_loop_hook (ping);
1191 ping_destroy (ping);
1193 return (0);
1194 } /* }}} int main */
1196 /* vim: set fdm=marker : */