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_qos_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 " be Best Effort (BE, default PHB).\n"
285 " ef Expedited Forwarding (EF) PHB group (RFC 3246).\n"
286 " (low delay, low loss, low jitter)\n"
287 " af[1-4][1-3] Assured Forwarding (AF) PHB group (RFC 2597).\n"
288 " For example: \"af12\" (class 1, precedence 2)\n"
289 " cs[0-7] Class Selector (CS) PHB group (RFC 2474).\n"
290 " For example: \"cs1\" (priority traffic)\n"
291 "\n"
292 " Type of Service (IPv4, RFC 1349, obsolete)\n"
293 "\n"
294 " lowdelay (%#04x) minimize delay\n"
295 " throughput (%#04x) maximize throughput\n"
296 " reliability (%#04x) maximize reliability\n"
297 " mincost (%#04x) minimize monetary cost\n"
298 "\n"
299 " Specify manually\n"
300 "\n"
301 " 0x00 - 0xff Hexadecimal numeric specification.\n"
302 " 0 - 255 Decimal numeric specification.\n"
303 "\n",
304 (unsigned int) IPTOS_LOWDELAY,
305 (unsigned int) IPTOS_THROUGHPUT,
306 (unsigned int) IPTOS_RELIABILITY,
307 (unsigned int) IPTOS_MINCOST);
309 exit (status);
310 } /* }}} void usage_qos_exit */
312 static int set_opt_send_qos (const char *opt) /* {{{ */
313 {
314 if (opt == NULL)
315 return (EINVAL);
317 if (strcasecmp ("help", opt) == 0)
318 usage_qos_exit (/* arg = */ NULL, /* status = */ EXIT_SUCCESS);
319 /* DiffServ (RFC 2474): */
320 /* - Best effort (BE) */
321 else if (strcasecmp ("be", opt) == 0)
322 opt_send_qos = 0;
323 /* - Expedited Forwarding (EF, RFC 3246) */
324 else if (strcasecmp ("ef", opt) == 0)
325 opt_send_qos = 0xB8; /* == 0x2E << 2 */
326 /* - Assured Forwarding (AF, RFC 2597) */
327 else if ((strncasecmp ("af", opt, strlen ("af")) == 0)
328 && (strlen (opt) == 4))
329 {
330 uint8_t dscp;
331 uint8_t class;
332 uint8_t prec;
334 /* There are four classes, AF1x, AF2x, AF3x, and AF4x. */
335 if (opt[2] == '1')
336 class = 1;
337 else if (opt[2] == '2')
338 class = 2;
339 else if (opt[2] == '3')
340 class = 3;
341 else if (opt[2] == '4')
342 class = 4;
343 else
344 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
346 /* In each class, there are three precedences, AFx1, AFx2, and AFx3 */
347 if (opt[3] == '1')
348 prec = 1;
349 else if (opt[3] == '2')
350 prec = 2;
351 else if (opt[3] == '3')
352 prec = 3;
353 else
354 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
356 dscp = (8 * class) + (2 * prec);
357 /* The lower two bits are used for Explicit Congestion Notification (ECN) */
358 opt_send_qos = dscp << 2;
359 }
360 /* - Class Selector (CS) */
361 else if ((strncasecmp ("cs", opt, strlen ("cs")) == 0)
362 && (strlen (opt) == 3))
363 {
364 uint8_t class;
366 if ((opt[2] < '0') || (opt[2] > '7'))
367 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
369 /* Not exactly legal by the C standard, but I don't know of any
370 * system not supporting this hack. */
371 class = ((uint8_t) opt[2]) - ((uint8_t) '0');
372 opt_send_qos = class << 5;
373 }
374 /* Type of Service (RFC 1349) */
375 else if (strcasecmp ("lowdelay", opt) == 0)
376 opt_send_qos = IPTOS_LOWDELAY;
377 else if (strcasecmp ("throughput", opt) == 0)
378 opt_send_qos = IPTOS_THROUGHPUT;
379 else if (strcasecmp ("reliability", opt) == 0)
380 opt_send_qos = IPTOS_RELIABILITY;
381 else if (strcasecmp ("mincost", opt) == 0)
382 opt_send_qos = IPTOS_MINCOST;
383 /* Numeric value */
384 else
385 {
386 unsigned long value;
387 char *endptr;
389 errno = 0;
390 endptr = NULL;
391 value = strtoul (opt, &endptr, /* base = */ 0);
392 if ((errno != 0) || (endptr == opt)
393 || (endptr == NULL) || (*endptr != 0)
394 || (value > 0xff))
395 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
397 opt_send_qos = (uint8_t) value;
398 }
400 return (0);
401 } /* }}} int set_opt_send_qos */
403 static char *format_qos (uint8_t qos, char *buffer, size_t buffer_size) /* {{{ */
404 {
405 uint8_t dscp;
406 uint8_t ecn;
407 char *dscp_str;
408 char *ecn_str;
410 dscp = qos >> 2;
411 ecn = qos & 0x03;
413 switch (dscp)
414 {
415 case 0x00: dscp_str = "be"; break;
416 case 0x2e: dscp_str = "ef"; break;
417 case 0x0a: dscp_str = "af11"; break;
418 case 0x0c: dscp_str = "af12"; break;
419 case 0x0e: dscp_str = "af13"; break;
420 case 0x12: dscp_str = "af21"; break;
421 case 0x14: dscp_str = "af22"; break;
422 case 0x16: dscp_str = "af23"; break;
423 case 0x1a: dscp_str = "af31"; break;
424 case 0x1c: dscp_str = "af32"; break;
425 case 0x1e: dscp_str = "af33"; break;
426 case 0x22: dscp_str = "af41"; break;
427 case 0x24: dscp_str = "af42"; break;
428 case 0x26: dscp_str = "af43"; break;
429 case 0x08: dscp_str = "cs1"; break;
430 case 0x10: dscp_str = "cs2"; break;
431 case 0x18: dscp_str = "cs3"; break;
432 case 0x20: dscp_str = "cs4"; break;
433 case 0x28: dscp_str = "cs5"; break;
434 case 0x30: dscp_str = "cs6"; break;
435 case 0x38: dscp_str = "cs7"; break;
436 default: dscp_str = NULL;
437 }
439 switch (ecn)
440 {
441 case 0x01: ecn_str = ",ecn(1)"; break;
442 case 0x02: ecn_str = ",ecn(0)"; break;
443 case 0x03: ecn_str = ",ce"; break;
444 default: ecn_str = "";
445 }
447 if (dscp_str == NULL)
448 snprintf (buffer, buffer_size, "0x%02x%s", dscp, ecn_str);
449 else
450 snprintf (buffer, buffer_size, "%s%s", dscp_str, ecn_str);
451 buffer[buffer_size - 1] = 0;
453 return (buffer);
454 } /* }}} char *format_qos */
456 static int read_options (int argc, char **argv) /* {{{ */
457 {
458 int optchar;
460 while (1)
461 {
462 optchar = getopt (argc, argv, "46c:hi:I:t:Q:f:D:");
464 if (optchar == -1)
465 break;
467 switch (optchar)
468 {
469 case '4':
470 case '6':
471 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
472 break;
474 case 'c':
475 {
476 int new_count;
477 new_count = atoi (optarg);
478 if (new_count > 0)
479 opt_count = new_count;
480 else
481 fprintf(stderr, "Ignoring invalid count: %s\n",
482 optarg);
483 }
484 break;
486 case 'f':
487 {
488 if (opt_filename != NULL)
489 free (opt_filename);
490 opt_filename = strdup (optarg);
491 }
492 break;
494 case 'i':
495 {
496 double new_interval;
497 new_interval = atof (optarg);
498 if (new_interval < 0.001)
499 fprintf (stderr, "Ignoring invalid interval: %s\n",
500 optarg);
501 else
502 opt_interval = new_interval;
503 }
504 break;
505 case 'I':
506 {
507 if (opt_srcaddr != NULL)
508 free (opt_srcaddr);
509 opt_srcaddr = strdup (optarg);
510 }
511 break;
513 case 'D':
514 opt_device = optarg;
515 break;
517 case 't':
518 {
519 int new_send_ttl;
520 new_send_ttl = atoi (optarg);
521 if ((new_send_ttl > 0) && (new_send_ttl < 256))
522 opt_send_ttl = new_send_ttl;
523 else
524 fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
525 optarg);
526 break;
527 }
529 case 'Q':
530 set_opt_send_qos (optarg);
531 break;
533 case 'h':
534 usage_exit (argv[0], 0);
535 break;
536 default:
537 usage_exit (argv[0], 1);
538 }
539 }
541 return (optind);
542 } /* }}} read_options */
544 static void time_normalize (struct timespec *ts) /* {{{ */
545 {
546 while (ts->tv_nsec < 0)
547 {
548 if (ts->tv_sec == 0)
549 {
550 ts->tv_nsec = 0;
551 return;
552 }
554 ts->tv_sec -= 1;
555 ts->tv_nsec += 1000000000;
556 }
558 while (ts->tv_nsec >= 1000000000)
559 {
560 ts->tv_sec += 1;
561 ts->tv_nsec -= 1000000000;
562 }
563 } /* }}} void time_normalize */
565 static void time_calc (struct timespec *ts_dest, /* {{{ */
566 const struct timespec *ts_int,
567 const struct timeval *tv_begin,
568 const struct timeval *tv_end)
569 {
570 ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
571 ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
572 time_normalize (ts_dest);
574 /* Assure that `(begin + interval) > end'.
575 * This may seem overly complicated, but `tv_sec' is of type `time_t'
576 * which may be `unsigned. *sigh* */
577 if ((tv_end->tv_sec > ts_dest->tv_sec)
578 || ((tv_end->tv_sec == ts_dest->tv_sec)
579 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
580 {
581 ts_dest->tv_sec = 0;
582 ts_dest->tv_nsec = 0;
583 return;
584 }
586 ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
587 ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
588 time_normalize (ts_dest);
589 } /* }}} void time_calc */
591 #if USE_NCURSES
592 static int update_stats_from_context (ping_context_t *ctx) /* {{{ */
593 {
594 if ((ctx == NULL) || (ctx->window == NULL))
595 return (EINVAL);
597 werase (ctx->window);
599 box (ctx->window, 0, 0);
600 wattron (ctx->window, A_BOLD);
601 mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
602 " %s ", ctx->host);
603 wattroff (ctx->window, A_BOLD);
604 wprintw (ctx->window, "ping statistics ");
605 mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
606 "%i packets transmitted, %i received, %.2f%% packet "
607 "loss, time %.1fms",
608 ctx->req_sent, ctx->req_rcvd,
609 context_get_packet_loss (ctx),
610 ctx->latency_total);
611 if (ctx->req_rcvd != 0)
612 {
613 double average;
614 double deviation;
616 average = context_get_average (ctx);
617 deviation = context_get_stddev (ctx);
619 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
620 "rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms",
621 ctx->latency_min,
622 average,
623 ctx->latency_max,
624 deviation);
625 }
627 wrefresh (ctx->window);
629 return (0);
630 } /* }}} int update_stats_from_context */
632 static int on_resize (pingobj_t *ping) /* {{{ */
633 {
634 pingobj_iter_t *iter;
635 int width = 0;
636 int height = 0;
637 int main_win_height;
639 getmaxyx (stdscr, height, width);
640 if ((height < 1) || (width < 1))
641 return (EINVAL);
643 main_win_height = height - (4 * host_num);
644 wresize (main_win, main_win_height, /* width = */ width);
645 /* Allow scrolling */
646 scrollok (main_win, TRUE);
647 /* wsetscrreg (main_win, 0, main_win_height - 1); */
648 /* Allow hardware accelerated scrolling. */
649 idlok (main_win, TRUE);
650 wrefresh (main_win);
652 for (iter = ping_iterator_get (ping);
653 iter != NULL;
654 iter = ping_iterator_next (iter))
655 {
656 ping_context_t *context;
658 context = ping_iterator_get_context (iter);
659 if (context == NULL)
660 continue;
662 if (context->window != NULL)
663 {
664 delwin (context->window);
665 context->window = NULL;
666 }
667 context->window = newwin (/* height = */ 4,
668 /* width = */ 0,
669 /* y = */ main_win_height + (4 * context->index),
670 /* x = */ 0);
671 }
673 return (0);
674 } /* }}} */
676 static int check_resize (pingobj_t *ping) /* {{{ */
677 {
678 int need_resize = 0;
680 while (42)
681 {
682 int key = wgetch (stdscr);
683 if (key == ERR)
684 break;
685 else if (key == KEY_RESIZE)
686 need_resize = 1;
687 }
689 if (need_resize)
690 return (on_resize (ping));
691 else
692 return (0);
693 } /* }}} int check_resize */
695 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
696 {
697 pingobj_iter_t *iter;
698 int width = 0;
699 int height = 0;
700 int main_win_height;
702 initscr ();
703 cbreak ();
704 noecho ();
705 nodelay (stdscr, TRUE);
707 getmaxyx (stdscr, height, width);
708 if ((height < 1) || (width < 1))
709 return (EINVAL);
711 if (has_colors () == TRUE)
712 {
713 start_color ();
714 init_pair (OPING_GREEN, COLOR_GREEN, /* default = */ 0);
715 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
716 init_pair (OPING_RED, COLOR_RED, /* default = */ 0);
717 }
719 main_win_height = height - (4 * host_num);
720 main_win = newwin (/* height = */ main_win_height,
721 /* width = */ 0,
722 /* y = */ 0, /* x = */ 0);
723 /* Allow scrolling */
724 scrollok (main_win, TRUE);
725 /* wsetscrreg (main_win, 0, main_win_height - 1); */
726 /* Allow hardware accelerated scrolling. */
727 idlok (main_win, TRUE);
728 wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
729 wrefresh (main_win);
731 for (iter = ping_iterator_get (ping);
732 iter != NULL;
733 iter = ping_iterator_next (iter))
734 {
735 ping_context_t *context;
737 context = ping_iterator_get_context (iter);
738 if (context == NULL)
739 continue;
741 if (context->window != NULL)
742 {
743 delwin (context->window);
744 context->window = NULL;
745 }
746 context->window = newwin (/* height = */ 4,
747 /* width = */ 0,
748 /* y = */ main_win_height + (4 * context->index),
749 /* x = */ 0);
750 }
753 /* Don't know what good this does exactly, but without this code
754 * "check_resize" will be called right after startup and *somehow*
755 * this leads to display errors. If we purge all initial characters
756 * here, the problem goes away. "wgetch" is non-blocking due to
757 * "nodelay" (see above). */
758 while (wgetch (stdscr) != ERR)
759 {
760 /* eat up characters */;
761 }
763 return (0);
764 } /* }}} int pre_loop_hook */
766 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
767 {
768 return (check_resize (ping));
769 } /* }}} int pre_sleep_hook */
771 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
772 {
773 return (check_resize (ping));
774 } /* }}} int pre_sleep_hook */
775 #else /* if !USE_NCURSES */
776 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
777 {
778 pingobj_iter_t *iter;
780 for (iter = ping_iterator_get (ping);
781 iter != NULL;
782 iter = ping_iterator_next (iter))
783 {
784 ping_context_t *ctx;
785 size_t buffer_size;
787 ctx = ping_iterator_get_context (iter);
788 if (ctx == NULL)
789 continue;
791 buffer_size = 0;
792 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
794 printf ("PING %s (%s) %zu bytes of data.\n",
795 ctx->host, ctx->addr, buffer_size);
796 }
798 return (0);
799 } /* }}} int pre_loop_hook */
801 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
802 {
803 fflush (stdout);
805 return (0);
806 } /* }}} int pre_sleep_hook */
808 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
809 {
810 return (0);
811 } /* }}} int post_sleep_hook */
812 #endif
814 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
815 int index)
816 {
817 double latency;
818 unsigned int sequence;
819 int recv_ttl;
820 uint8_t recv_qos;
821 char recv_qos_str[16];
822 size_t buffer_len;
823 size_t data_len;
824 ping_context_t *context;
826 latency = -1.0;
827 buffer_len = sizeof (latency);
828 ping_iterator_get_info (iter, PING_INFO_LATENCY,
829 &latency, &buffer_len);
831 sequence = 0;
832 buffer_len = sizeof (sequence);
833 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
834 &sequence, &buffer_len);
836 recv_ttl = -1;
837 buffer_len = sizeof (recv_ttl);
838 ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
839 &recv_ttl, &buffer_len);
841 recv_qos = 0;
842 buffer_len = sizeof (recv_qos);
843 ping_iterator_get_info (iter, PING_INFO_RECV_QOS,
844 &recv_qos, &buffer_len);
846 data_len = 0;
847 ping_iterator_get_info (iter, PING_INFO_DATA,
848 NULL, &data_len);
850 context = (ping_context_t *) ping_iterator_get_context (iter);
852 #if USE_NCURSES
853 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
854 #else
855 # define HOST_PRINTF(...) printf(__VA_ARGS__)
856 #endif
858 context->req_sent++;
859 if (latency > 0.0)
860 {
861 context->req_rcvd++;
862 context->latency_total += latency;
863 context->latency_total_square += (latency * latency);
865 if ((context->latency_max < 0.0) || (context->latency_max < latency))
866 context->latency_max = latency;
867 if ((context->latency_min < 0.0) || (context->latency_min > latency))
868 context->latency_min = latency;
870 #if USE_NCURSES
871 if (has_colors () == TRUE)
872 {
873 int color = OPING_GREEN;
874 double average = context_get_average (context);
875 double stddev = context_get_stddev (context);
877 if ((latency < (average - (2 * stddev)))
878 || (latency > (average + (2 * stddev))))
879 color = OPING_RED;
880 else if ((latency < (average - stddev))
881 || (latency > (average + stddev)))
882 color = OPING_YELLOW;
884 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
885 data_len, context->host, context->addr,
886 sequence, recv_ttl,
887 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
888 if ((recv_qos != 0) || (opt_send_qos != 0))
889 {
890 HOST_PRINTF ("qos=%s ",
891 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
892 }
893 HOST_PRINTF ("time=");
894 wattron (main_win, COLOR_PAIR(color));
895 HOST_PRINTF ("%.2f", latency);
896 wattroff (main_win, COLOR_PAIR(color));
897 HOST_PRINTF (" ms\n");
898 }
899 else
900 {
901 #endif
902 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
903 data_len,
904 context->host, context->addr,
905 sequence, recv_ttl);
906 if ((recv_qos != 0) || (opt_send_qos != 0))
907 {
908 HOST_PRINTF ("qos=%s ",
909 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
910 }
911 HOST_PRINTF ("time=%.2f ms\n", latency);
912 #if USE_NCURSES
913 }
914 #endif
915 }
916 else
917 {
918 #if USE_NCURSES
919 if (has_colors () == TRUE)
920 {
921 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
922 context->host, context->addr,
923 sequence);
924 wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
925 HOST_PRINTF ("timeout");
926 wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
927 HOST_PRINTF ("\n");
928 }
929 else
930 {
931 #endif
932 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
933 context->host, context->addr,
934 sequence);
935 #if USE_NCURSES
936 }
937 #endif
938 }
940 #if USE_NCURSES
941 update_stats_from_context (context);
942 wrefresh (main_win);
943 #endif
944 } /* }}} void update_host_hook */
946 static int post_loop_hook (pingobj_t *ping) /* {{{ */
947 {
948 pingobj_iter_t *iter;
950 #if USE_NCURSES
951 endwin ();
952 #endif
954 for (iter = ping_iterator_get (ping);
955 iter != NULL;
956 iter = ping_iterator_next (iter))
957 {
958 ping_context_t *context;
960 context = ping_iterator_get_context (iter);
962 printf ("\n--- %s ping statistics ---\n"
963 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
964 context->host, context->req_sent, context->req_rcvd,
965 context_get_packet_loss (context),
966 context->latency_total);
968 if (context->req_rcvd != 0)
969 {
970 double average;
971 double deviation;
973 average = context_get_average (context);
974 deviation = context_get_stddev (context);
976 printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
977 context->latency_min,
978 average,
979 context->latency_max,
980 deviation);
981 }
983 ping_iterator_set_context (iter, NULL);
984 context_destroy (context);
985 }
987 return (0);
988 } /* }}} int post_loop_hook */
990 int main (int argc, char **argv) /* {{{ */
991 {
992 pingobj_t *ping;
993 pingobj_iter_t *iter;
995 struct sigaction sigint_action;
997 struct timeval tv_begin;
998 struct timeval tv_end;
999 struct timespec ts_wait;
1000 struct timespec ts_int;
1002 int optind;
1003 int i;
1004 int status;
1005 #if _POSIX_SAVED_IDS
1006 uid_t saved_set_uid;
1008 /* Save the old effective user id */
1009 saved_set_uid = geteuid ();
1010 /* Set the effective user ID to the real user ID without changing the
1011 * saved set-user ID */
1012 status = seteuid (getuid ());
1013 if (status != 0)
1014 {
1015 fprintf (stderr, "Temporarily dropping privileges "
1016 "failed: %s\n", strerror (errno));
1017 exit (EXIT_FAILURE);
1018 }
1019 #endif
1021 optind = read_options (argc, argv);
1023 #if !_POSIX_SAVED_IDS
1024 /* Cannot temporarily drop privileges -> reject every file but "-". */
1025 if ((opt_filename != NULL)
1026 && (strcmp ("-", opt_filename) != 0)
1027 && (getuid () != geteuid ()))
1028 {
1029 fprintf (stderr, "Your real and effective user IDs don't "
1030 "match. Reading from a file (option '-f')\n"
1031 "is therefore too risky. You can still read "
1032 "from STDIN using '-f -' if you like.\n"
1033 "Sorry.\n");
1034 exit (EXIT_FAILURE);
1035 }
1036 #endif
1038 if ((optind >= argc) && (opt_filename == NULL)) {
1039 usage_exit (argv[0], 1);
1040 }
1042 if ((ping = ping_construct ()) == NULL)
1043 {
1044 fprintf (stderr, "ping_construct failed\n");
1045 return (1);
1046 }
1048 if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
1049 {
1050 fprintf (stderr, "Setting TTL to %i failed: %s\n",
1051 opt_send_ttl, ping_get_error (ping));
1052 }
1054 if (ping_setopt (ping, PING_OPT_QOS, &opt_send_qos) != 0)
1055 {
1056 fprintf (stderr, "Setting TOS to %i failed: %s\n",
1057 opt_send_qos, ping_get_error (ping));
1058 }
1060 {
1061 double temp_sec;
1062 double temp_nsec;
1064 temp_nsec = modf (opt_interval, &temp_sec);
1065 ts_int.tv_sec = (time_t) temp_sec;
1066 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
1068 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
1069 }
1071 if (opt_addrfamily != PING_DEF_AF)
1072 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
1074 if (opt_srcaddr != NULL)
1075 {
1076 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
1077 {
1078 fprintf (stderr, "Setting source address failed: %s\n",
1079 ping_get_error (ping));
1080 }
1081 }
1083 if (opt_device != NULL)
1084 {
1085 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
1086 {
1087 fprintf (stderr, "Setting device failed: %s\n",
1088 ping_get_error (ping));
1089 }
1090 }
1092 if (opt_filename != NULL)
1093 {
1094 FILE *infile;
1095 char line[256];
1096 char host[256];
1098 if (strcmp (opt_filename, "-") == 0)
1099 /* Open STDIN */
1100 infile = fdopen(0, "r");
1101 else
1102 infile = fopen(opt_filename, "r");
1104 if (infile == NULL)
1105 {
1106 fprintf (stderr, "Opening %s failed: %s\n",
1107 (strcmp (opt_filename, "-") == 0)
1108 ? "STDIN" : opt_filename,
1109 strerror(errno));
1110 return (1);
1111 }
1113 #if _POSIX_SAVED_IDS
1114 /* Regain privileges */
1115 status = seteuid (saved_set_uid);
1116 if (status != 0)
1117 {
1118 fprintf (stderr, "Temporarily re-gaining privileges "
1119 "failed: %s\n", strerror (errno));
1120 exit (EXIT_FAILURE);
1121 }
1122 #endif
1124 while (fgets(line, sizeof(line), infile))
1125 {
1126 /* Strip whitespace */
1127 if (sscanf(line, "%s", host) != 1)
1128 continue;
1130 if ((host[0] == 0) || (host[0] == '#'))
1131 continue;
1133 if (ping_host_add(ping, host) < 0)
1134 {
1135 const char *errmsg = ping_get_error (ping);
1137 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
1138 continue;
1139 }
1140 else
1141 {
1142 host_num++;
1143 }
1144 }
1146 #if _POSIX_SAVED_IDS
1147 /* Drop privileges */
1148 status = seteuid (getuid ());
1149 if (status != 0)
1150 {
1151 fprintf (stderr, "Temporarily dropping privileges "
1152 "failed: %s\n", strerror (errno));
1153 exit (EXIT_FAILURE);
1154 }
1155 #endif
1157 fclose(infile);
1158 }
1160 #if _POSIX_SAVED_IDS
1161 /* Regain privileges */
1162 status = seteuid (saved_set_uid);
1163 if (status != 0)
1164 {
1165 fprintf (stderr, "Temporarily re-gaining privileges "
1166 "failed: %s\n", strerror (errno));
1167 exit (EXIT_FAILURE);
1168 }
1169 #endif
1171 for (i = optind; i < argc; i++)
1172 {
1173 if (ping_host_add (ping, argv[i]) < 0)
1174 {
1175 const char *errmsg = ping_get_error (ping);
1177 fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
1178 continue;
1179 }
1180 else
1181 {
1182 host_num++;
1183 }
1184 }
1186 /* Permanently drop root privileges if we're setuid-root. */
1187 status = setuid (getuid ());
1188 if (status != 0)
1189 {
1190 fprintf (stderr, "Dropping privileges failed: %s\n",
1191 strerror (errno));
1192 exit (EXIT_FAILURE);
1193 }
1195 #if _POSIX_SAVED_IDS
1196 saved_set_uid = (uid_t) -1;
1197 #endif
1199 ping_initialize_contexts (ping);
1201 if (i == 0)
1202 return (1);
1204 memset (&sigint_action, '\0', sizeof (sigint_action));
1205 sigint_action.sa_handler = sigint_handler;
1206 if (sigaction (SIGINT, &sigint_action, NULL) < 0)
1207 {
1208 perror ("sigaction");
1209 return (1);
1210 }
1212 pre_loop_hook (ping);
1214 while (opt_count != 0)
1215 {
1216 int index;
1217 int status;
1219 if (gettimeofday (&tv_begin, NULL) < 0)
1220 {
1221 perror ("gettimeofday");
1222 return (1);
1223 }
1225 if (ping_send (ping) < 0)
1226 {
1227 fprintf (stderr, "ping_send failed: %s\n",
1228 ping_get_error (ping));
1229 return (1);
1230 }
1232 index = 0;
1233 for (iter = ping_iterator_get (ping);
1234 iter != NULL;
1235 iter = ping_iterator_next (iter))
1236 {
1237 update_host_hook (iter, index);
1238 index++;
1239 }
1241 pre_sleep_hook (ping);
1243 /* Don't sleep in the last iteration */
1244 if (opt_count == 1)
1245 break;
1247 if (gettimeofday (&tv_end, NULL) < 0)
1248 {
1249 perror ("gettimeofday");
1250 return (1);
1251 }
1253 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1255 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1256 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1257 {
1258 if (errno != EINTR)
1259 {
1260 perror ("nanosleep");
1261 break;
1262 }
1263 else if (opt_count == 0)
1264 {
1265 /* sigint */
1266 break;
1267 }
1268 }
1270 post_sleep_hook (ping);
1272 if (opt_count > 0)
1273 opt_count--;
1274 } /* while (opt_count != 0) */
1276 post_loop_hook (ping);
1278 ping_destroy (ping);
1280 return (0);
1281 } /* }}} int main */
1283 /* vim: set fdm=marker : */