1 /**
2 * Object oriented C module to send ICMP and ICMPv6 `echo's.
3 * Copyright (C) 2006-2011 Florian octo Forster <ff at octo.it>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; only version 2 of the License is
8 * applicable.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18 */
20 #if HAVE_CONFIG_H
21 # include <config.h>
22 #endif
24 #if STDC_HEADERS
25 # include <stdlib.h>
26 # include <stdio.h>
27 # include <string.h>
28 # include <stdint.h>
29 # include <inttypes.h>
30 # include <errno.h>
31 # include <assert.h>
32 #else
33 # error "You don't have the standard C99 header files installed"
34 #endif /* STDC_HEADERS */
36 #if HAVE_UNISTD_H
37 # include <unistd.h>
38 #endif
40 #if HAVE_MATH_H
41 # include <math.h>
42 #endif
44 #if TIME_WITH_SYS_TIME
45 # include <sys/time.h>
46 # include <time.h>
47 #else
48 # if HAVE_SYS_TIME_H
49 # include <sys/time.h>
50 # else
51 # include <time.h>
52 # endif
53 #endif
55 #if HAVE_SYS_SOCKET_H
56 # include <sys/socket.h>
57 #endif
58 #if HAVE_NETINET_IN_H
59 # include <netinet/in.h>
60 #endif
61 #if HAVE_NETINET_IP_H
62 # include <netinet/ip.h>
63 #endif
65 #if HAVE_NETDB_H
66 # include <netdb.h> /* NI_MAXHOST */
67 #endif
69 #if HAVE_SIGNAL_H
70 # include <signal.h>
71 #endif
73 #if HAVE_SYS_TYPES_H
74 #include <sys/types.h>
75 #endif
77 #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 /* Remove GNU specific __attribute__ settings when using another compiler */
93 #if !__GNUC__
94 # define __attribute__(x) /**/
95 #endif
97 typedef struct ping_context
98 {
99 char host[NI_MAXHOST];
100 char addr[NI_MAXHOST];
102 int index;
103 int req_sent;
104 int req_rcvd;
106 double latency_min;
107 double latency_max;
108 double latency_total;
109 double latency_total_square;
111 #if USE_NCURSES
112 WINDOW *window;
113 #endif
114 } ping_context_t;
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;
128 #if USE_NCURSES
129 static WINDOW *main_win = NULL;
130 #endif
132 static void sigint_handler (int signal) /* {{{ */
133 {
134 /* Make compiler happy */
135 signal = 0;
136 /* Exit the loop */
137 opt_count = 0;
138 } /* }}} void sigint_handler */
140 static ping_context_t *context_create (void) /* {{{ */
141 {
142 ping_context_t *ret;
144 if ((ret = malloc (sizeof (ping_context_t))) == NULL)
145 return (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;
154 #if USE_NCURSES
155 ret->window = NULL;
156 #endif
158 return (ret);
159 } /* }}} ping_context_t *context_create */
161 static void context_destroy (ping_context_t *context) /* {{{ */
162 {
163 if (context == NULL)
164 return;
166 #if USE_NCURSES
167 if (context->window != NULL)
168 {
169 delwin (context->window);
170 context->window = NULL;
171 }
172 #endif
174 free (context);
175 } /* }}} void context_destroy */
177 static double context_get_average (ping_context_t *ctx) /* {{{ */
178 {
179 double num_total;
181 if (ctx == NULL)
182 return (-1.0);
184 if (ctx->req_rcvd < 1)
185 return (-0.0);
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) /* {{{ */
192 {
193 double num_total;
195 if (ctx == NULL)
196 return (-1.0);
198 if (ctx->req_rcvd < 1)
199 return (-0.0);
200 else if (ctx->req_rcvd < 2)
201 return (0.0);
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) /* {{{ */
210 {
211 if (ctx == NULL)
212 return (-1.0);
214 if (ctx->req_sent < 1)
215 return (0.0);
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) /* {{{ */
222 {
223 pingobj_iter_t *iter;
224 int index;
226 if (ping == NULL)
227 return (EINVAL);
229 index = 0;
230 for (iter = ping_iterator_get (ping);
231 iter != NULL;
232 iter = ping_iterator_next (iter))
233 {
234 ping_context_t *context;
235 size_t buffer_size;
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);
248 index++;
249 }
251 return (0);
252 } /* }}} int ping_initialize_contexts */
254 static void usage_exit (const char *name, int status) /* {{{ */
255 {
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",
275 name);
276 exit (status);
277 } /* }}} void usage_exit */
279 __attribute__((noreturn))
280 static void usage_qos_exit (const char *arg, int status) /* {{{ */
281 {
282 if (arg != 0)
283 fprintf (stderr, "Invalid QoS argument: \"%s\"\n\n", arg);
285 fprintf (stderr, "Valid QoS arguments (option \"-Q\") are:\n"
286 "\n"
287 " Differentiated Services (IPv4 and IPv6, RFC 2474)\n"
288 "\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"
298 "\n"
299 " Type of Service (IPv4, RFC 1349, obsolete)\n"
300 "\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"
305 "\n"
306 " Specify manually\n"
307 "\n"
308 " 0x00 - 0xff Hexadecimal numeric specification.\n"
309 " 0 - 255 Decimal numeric specification.\n"
310 "\n",
311 (unsigned int) IPTOS_LOWDELAY,
312 (unsigned int) IPTOS_THROUGHPUT,
313 (unsigned int) IPTOS_RELIABILITY,
314 (unsigned int) IPTOS_MINCOST);
316 exit (status);
317 } /* }}} void usage_qos_exit */
319 static int set_opt_send_qos (const char *opt) /* {{{ */
320 {
321 if (opt == NULL)
322 return (EINVAL);
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)
329 opt_send_qos = 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))
339 {
340 uint8_t dscp;
341 uint8_t class = 0;
342 uint8_t prec = 0;
344 /* There are four classes, AF1x, AF2x, AF3x, and AF4x. */
345 if (opt[2] == '1')
346 class = 1;
347 else if (opt[2] == '2')
348 class = 2;
349 else if (opt[2] == '3')
350 class = 3;
351 else if (opt[2] == '4')
352 class = 4;
353 else
354 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
356 /* In each class, there are three precedences, AFx1, AFx2, and AFx3 */
357 if (opt[3] == '1')
358 prec = 1;
359 else if (opt[3] == '2')
360 prec = 2;
361 else if (opt[3] == '3')
362 prec = 3;
363 else
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;
369 }
370 /* - Class Selector (CS) */
371 else if ((strncasecmp ("cs", opt, strlen ("cs")) == 0)
372 && (strlen (opt) == 3))
373 {
374 uint8_t class;
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;
383 }
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;
393 /* Numeric value */
394 else
395 {
396 unsigned long value;
397 char *endptr;
399 errno = 0;
400 endptr = NULL;
401 value = strtoul (opt, &endptr, /* base = */ 0);
402 if ((errno != 0) || (endptr == opt)
403 || (endptr == NULL) || (*endptr != 0)
404 || (value > 0xff))
405 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
407 opt_send_qos = (uint8_t) value;
408 }
410 return (0);
411 } /* }}} int set_opt_send_qos */
413 static char *format_qos (uint8_t qos, char *buffer, size_t buffer_size) /* {{{ */
414 {
415 uint8_t dscp;
416 uint8_t ecn;
417 char *dscp_str;
418 char *ecn_str;
420 dscp = qos >> 2;
421 ecn = qos & 0x03;
423 switch (dscp)
424 {
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;
448 }
450 switch (ecn)
451 {
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 = "";
456 }
458 if (dscp_str == NULL)
459 snprintf (buffer, buffer_size, "0x%02x%s", dscp, ecn_str);
460 else
461 snprintf (buffer, buffer_size, "%s%s", dscp_str, ecn_str);
462 buffer[buffer_size - 1] = 0;
464 return (buffer);
465 } /* }}} char *format_qos */
467 static int read_options (int argc, char **argv) /* {{{ */
468 {
469 int optchar;
471 while (1)
472 {
473 optchar = getopt (argc, argv, "46c:hi:I:t:Q:f:D:Z:");
475 if (optchar == -1)
476 break;
478 switch (optchar)
479 {
480 case '4':
481 case '6':
482 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
483 break;
485 case 'c':
486 {
487 int new_count;
488 new_count = atoi (optarg);
489 if (new_count > 0)
490 opt_count = new_count;
491 else
492 fprintf(stderr, "Ignoring invalid count: %s\n",
493 optarg);
494 }
495 break;
497 case 'f':
498 {
499 if (opt_filename != NULL)
500 free (opt_filename);
501 opt_filename = strdup (optarg);
502 }
503 break;
505 case 'i':
506 {
507 double new_interval;
508 new_interval = atof (optarg);
509 if (new_interval < 0.001)
510 fprintf (stderr, "Ignoring invalid interval: %s\n",
511 optarg);
512 else
513 opt_interval = new_interval;
514 }
515 break;
516 case 'I':
517 {
518 if (opt_srcaddr != NULL)
519 free (opt_srcaddr);
520 opt_srcaddr = strdup (optarg);
521 }
522 break;
524 case 'D':
525 opt_device = optarg;
526 break;
528 case 't':
529 {
530 int new_send_ttl;
531 new_send_ttl = atoi (optarg);
532 if ((new_send_ttl > 0) && (new_send_ttl < 256))
533 opt_send_ttl = new_send_ttl;
534 else
535 fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
536 optarg);
537 break;
538 }
540 case 'Q':
541 set_opt_send_qos (optarg);
542 break;
544 case 'Z':
545 {
546 char *endptr = NULL;
547 double tmp;
549 errno = 0;
550 tmp = strtod (optarg, &endptr);
551 if ((errno != 0) || (endptr == NULL) || (*endptr != 0) || (tmp < 0.0) || (tmp > 100.0))
552 {
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");
555 }
556 else
557 opt_exit_status_threshold = tmp / 100.0;
559 break;
560 }
562 case 'h':
563 usage_exit (argv[0], 0);
564 break;
565 default:
566 usage_exit (argv[0], 1);
567 }
568 }
570 return (optind);
571 } /* }}} read_options */
573 static void time_normalize (struct timespec *ts) /* {{{ */
574 {
575 while (ts->tv_nsec < 0)
576 {
577 if (ts->tv_sec == 0)
578 {
579 ts->tv_nsec = 0;
580 return;
581 }
583 ts->tv_sec -= 1;
584 ts->tv_nsec += 1000000000;
585 }
587 while (ts->tv_nsec >= 1000000000)
588 {
589 ts->tv_sec += 1;
590 ts->tv_nsec -= 1000000000;
591 }
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)
598 {
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)))
609 {
610 ts_dest->tv_sec = 0;
611 ts_dest->tv_nsec = 0;
612 return;
613 }
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 */
620 #if USE_NCURSES
621 static int update_stats_from_context (ping_context_t *ctx) /* {{{ */
622 {
623 if ((ctx == NULL) || (ctx->window == NULL))
624 return (EINVAL);
626 werase (ctx->window);
628 box (ctx->window, 0, 0);
629 wattron (ctx->window, A_BOLD);
630 mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
631 " %s ", ctx->host);
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 "
636 "loss, time %.1fms",
637 ctx->req_sent, ctx->req_rcvd,
638 context_get_packet_loss (ctx),
639 ctx->latency_total);
640 if (ctx->req_rcvd != 0)
641 {
642 double average;
643 double deviation;
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",
650 ctx->latency_min,
651 average,
652 ctx->latency_max,
653 deviation);
654 }
656 wrefresh (ctx->window);
658 return (0);
659 } /* }}} int update_stats_from_context */
661 static int on_resize (pingobj_t *ping) /* {{{ */
662 {
663 pingobj_iter_t *iter;
664 int width = 0;
665 int height = 0;
666 int main_win_height;
668 getmaxyx (stdscr, height, width);
669 if ((height < 1) || (width < 1))
670 return (EINVAL);
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);
679 wrefresh (main_win);
681 for (iter = ping_iterator_get (ping);
682 iter != NULL;
683 iter = ping_iterator_next (iter))
684 {
685 ping_context_t *context;
687 context = ping_iterator_get_context (iter);
688 if (context == NULL)
689 continue;
691 if (context->window != NULL)
692 {
693 delwin (context->window);
694 context->window = NULL;
695 }
696 context->window = newwin (/* height = */ 4,
697 /* width = */ width,
698 /* y = */ main_win_height + (4 * context->index),
699 /* x = */ 0);
700 }
702 return (0);
703 } /* }}} */
705 static int check_resize (pingobj_t *ping) /* {{{ */
706 {
707 int need_resize = 0;
709 while (42)
710 {
711 int key = wgetch (stdscr);
712 if (key == ERR)
713 break;
714 else if (key == KEY_RESIZE)
715 need_resize = 1;
716 }
718 if (need_resize)
719 return (on_resize (ping));
720 else
721 return (0);
722 } /* }}} int check_resize */
724 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
725 {
726 pingobj_iter_t *iter;
727 int width = 0;
728 int height = 0;
729 int main_win_height;
731 initscr ();
732 cbreak ();
733 noecho ();
734 nodelay (stdscr, TRUE);
736 getmaxyx (stdscr, height, width);
737 if ((height < 1) || (width < 1))
738 return (EINVAL);
740 if (has_colors () == TRUE)
741 {
742 start_color ();
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);
746 }
748 main_win_height = height - (4 * host_num);
749 main_win = newwin (/* height = */ main_win_height,
750 /* width = */ width,
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);
758 wrefresh (main_win);
760 for (iter = ping_iterator_get (ping);
761 iter != NULL;
762 iter = ping_iterator_next (iter))
763 {
764 ping_context_t *context;
766 context = ping_iterator_get_context (iter);
767 if (context == NULL)
768 continue;
770 if (context->window != NULL)
771 {
772 delwin (context->window);
773 context->window = NULL;
774 }
775 context->window = newwin (/* height = */ 4,
776 /* width = */ width,
777 /* y = */ main_win_height + (4 * context->index),
778 /* x = */ 0);
779 }
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)
788 {
789 /* eat up characters */;
790 }
792 return (0);
793 } /* }}} int pre_loop_hook */
795 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
796 {
797 return (check_resize (ping));
798 } /* }}} int pre_sleep_hook */
800 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
801 {
802 return (check_resize (ping));
803 } /* }}} int pre_sleep_hook */
804 #else /* if !USE_NCURSES */
805 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
806 {
807 pingobj_iter_t *iter;
809 for (iter = ping_iterator_get (ping);
810 iter != NULL;
811 iter = ping_iterator_next (iter))
812 {
813 ping_context_t *ctx;
814 size_t buffer_size;
816 ctx = ping_iterator_get_context (iter);
817 if (ctx == NULL)
818 continue;
820 buffer_size = 0;
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);
825 }
827 return (0);
828 } /* }}} int pre_loop_hook */
830 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
831 {
832 fflush (stdout);
834 return (0);
835 } /* }}} int pre_sleep_hook */
837 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
838 {
839 return (0);
840 } /* }}} int post_sleep_hook */
841 #endif
843 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
844 __attribute__((unused)) int index)
845 {
846 double latency;
847 unsigned int sequence;
848 int recv_ttl;
849 uint8_t recv_qos;
850 char recv_qos_str[16];
851 size_t buffer_len;
852 size_t data_len;
853 ping_context_t *context;
855 latency = -1.0;
856 buffer_len = sizeof (latency);
857 ping_iterator_get_info (iter, PING_INFO_LATENCY,
858 &latency, &buffer_len);
860 sequence = 0;
861 buffer_len = sizeof (sequence);
862 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
863 &sequence, &buffer_len);
865 recv_ttl = -1;
866 buffer_len = sizeof (recv_ttl);
867 ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
868 &recv_ttl, &buffer_len);
870 recv_qos = 0;
871 buffer_len = sizeof (recv_qos);
872 ping_iterator_get_info (iter, PING_INFO_RECV_QOS,
873 &recv_qos, &buffer_len);
875 data_len = 0;
876 ping_iterator_get_info (iter, PING_INFO_DATA,
877 NULL, &data_len);
879 context = (ping_context_t *) ping_iterator_get_context (iter);
881 #if USE_NCURSES
882 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
883 #else
884 # define HOST_PRINTF(...) printf(__VA_ARGS__)
885 #endif
887 context->req_sent++;
888 if (latency > 0.0)
889 {
890 context->req_rcvd++;
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;
899 #if USE_NCURSES
900 if (has_colors () == TRUE)
901 {
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))))
908 color = OPING_RED;
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,
915 sequence, recv_ttl,
916 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
917 if ((recv_qos != 0) || (opt_send_qos != 0))
918 {
919 HOST_PRINTF ("qos=%s ",
920 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
921 }
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");
927 }
928 else
929 {
930 #endif
931 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
932 data_len,
933 context->host, context->addr,
934 sequence, recv_ttl);
935 if ((recv_qos != 0) || (opt_send_qos != 0))
936 {
937 HOST_PRINTF ("qos=%s ",
938 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
939 }
940 HOST_PRINTF ("time=%.2f ms\n", latency);
941 #if USE_NCURSES
942 }
943 #endif
944 }
945 else
946 {
947 #if USE_NCURSES
948 if (has_colors () == TRUE)
949 {
950 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
951 context->host, context->addr,
952 sequence);
953 wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
954 HOST_PRINTF ("timeout");
955 wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
956 HOST_PRINTF ("\n");
957 }
958 else
959 {
960 #endif
961 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
962 context->host, context->addr,
963 sequence);
964 #if USE_NCURSES
965 }
966 #endif
967 }
969 #if USE_NCURSES
970 update_stats_from_context (context);
971 wrefresh (main_win);
972 #endif
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) /* {{{ */
978 {
979 pingobj_iter_t *iter;
980 int failure_count = 0;
982 #if USE_NCURSES
983 endwin ();
984 #endif
986 for (iter = ping_iterator_get (ping);
987 iter != NULL;
988 iter = ping_iterator_next (iter))
989 {
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);
1000 {
1001 double pct_failed = 1.0 - (((double) context->req_rcvd)
1002 / ((double) context->req_sent));
1003 if (pct_failed > opt_exit_status_threshold)
1004 failure_count++;
1005 }
1007 if (context->req_rcvd != 0)
1008 {
1009 double average;
1010 double deviation;
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,
1017 average,
1018 context->latency_max,
1019 deviation);
1020 }
1022 ping_iterator_set_context (iter, NULL);
1023 context_destroy (context);
1024 }
1026 return (failure_count);
1027 } /* }}} int post_loop_hook */
1029 int main (int argc, char **argv) /* {{{ */
1030 {
1031 pingobj_t *ping;
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;
1041 int optind;
1042 int i;
1043 int status;
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 ());
1052 if (status != 0)
1053 {
1054 fprintf (stderr, "Temporarily dropping privileges "
1055 "failed: %s\n", strerror (errno));
1056 exit (EXIT_FAILURE);
1057 }
1058 #endif
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 ()))
1067 {
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"
1072 "Sorry.\n");
1073 exit (EXIT_FAILURE);
1074 }
1075 #endif
1077 if ((optind >= argc) && (opt_filename == NULL)) {
1078 usage_exit (argv[0], 1);
1079 }
1081 if ((ping = ping_construct ()) == NULL)
1082 {
1083 fprintf (stderr, "ping_construct failed\n");
1084 return (1);
1085 }
1087 if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
1088 {
1089 fprintf (stderr, "Setting TTL to %i failed: %s\n",
1090 opt_send_ttl, ping_get_error (ping));
1091 }
1093 if (ping_setopt (ping, PING_OPT_QOS, &opt_send_qos) != 0)
1094 {
1095 fprintf (stderr, "Setting TOS to %i failed: %s\n",
1096 opt_send_qos, ping_get_error (ping));
1097 }
1099 {
1100 double temp_sec;
1101 double temp_nsec;
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); */
1108 }
1110 if (opt_addrfamily != PING_DEF_AF)
1111 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
1113 if (opt_srcaddr != NULL)
1114 {
1115 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
1116 {
1117 fprintf (stderr, "Setting source address failed: %s\n",
1118 ping_get_error (ping));
1119 }
1120 }
1122 if (opt_device != NULL)
1123 {
1124 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
1125 {
1126 fprintf (stderr, "Setting device failed: %s\n",
1127 ping_get_error (ping));
1128 }
1129 }
1131 if (opt_filename != NULL)
1132 {
1133 FILE *infile;
1134 char line[256];
1135 char host[256];
1137 if (strcmp (opt_filename, "-") == 0)
1138 /* Open STDIN */
1139 infile = fdopen(0, "r");
1140 else
1141 infile = fopen(opt_filename, "r");
1143 if (infile == NULL)
1144 {
1145 fprintf (stderr, "Opening %s failed: %s\n",
1146 (strcmp (opt_filename, "-") == 0)
1147 ? "STDIN" : opt_filename,
1148 strerror(errno));
1149 return (1);
1150 }
1152 #if _POSIX_SAVED_IDS
1153 /* Regain privileges */
1154 status = seteuid (saved_set_uid);
1155 if (status != 0)
1156 {
1157 fprintf (stderr, "Temporarily re-gaining privileges "
1158 "failed: %s\n", strerror (errno));
1159 exit (EXIT_FAILURE);
1160 }
1161 #endif
1163 while (fgets(line, sizeof(line), infile))
1164 {
1165 /* Strip whitespace */
1166 if (sscanf(line, "%s", host) != 1)
1167 continue;
1169 if ((host[0] == 0) || (host[0] == '#'))
1170 continue;
1172 if (ping_host_add(ping, host) < 0)
1173 {
1174 const char *errmsg = ping_get_error (ping);
1176 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
1177 continue;
1178 }
1179 else
1180 {
1181 host_num++;
1182 }
1183 }
1185 #if _POSIX_SAVED_IDS
1186 /* Drop privileges */
1187 status = seteuid (getuid ());
1188 if (status != 0)
1189 {
1190 fprintf (stderr, "Temporarily dropping privileges "
1191 "failed: %s\n", strerror (errno));
1192 exit (EXIT_FAILURE);
1193 }
1194 #endif
1196 fclose(infile);
1197 }
1199 #if _POSIX_SAVED_IDS
1200 /* Regain privileges */
1201 status = seteuid (saved_set_uid);
1202 if (status != 0)
1203 {
1204 fprintf (stderr, "Temporarily re-gaining privileges "
1205 "failed: %s\n", strerror (errno));
1206 exit (EXIT_FAILURE);
1207 }
1208 #endif
1210 for (i = optind; i < argc; i++)
1211 {
1212 if (ping_host_add (ping, argv[i]) < 0)
1213 {
1214 const char *errmsg = ping_get_error (ping);
1216 fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
1217 continue;
1218 }
1219 else
1220 {
1221 host_num++;
1222 }
1223 }
1225 /* Permanently drop root privileges if we're setuid-root. */
1226 status = setuid (getuid ());
1227 if (status != 0)
1228 {
1229 fprintf (stderr, "Dropping privileges failed: %s\n",
1230 strerror (errno));
1231 exit (EXIT_FAILURE);
1232 }
1234 #if _POSIX_SAVED_IDS
1235 saved_set_uid = (uid_t) -1;
1236 #endif
1238 ping_initialize_contexts (ping);
1240 if (i == 0)
1241 return (1);
1243 memset (&sigint_action, '\0', sizeof (sigint_action));
1244 sigint_action.sa_handler = sigint_handler;
1245 if (sigaction (SIGINT, &sigint_action, NULL) < 0)
1246 {
1247 perror ("sigaction");
1248 return (1);
1249 }
1251 pre_loop_hook (ping);
1253 while (opt_count != 0)
1254 {
1255 int index;
1256 int status;
1258 if (gettimeofday (&tv_begin, NULL) < 0)
1259 {
1260 perror ("gettimeofday");
1261 return (1);
1262 }
1264 if (ping_send (ping) < 0)
1265 {
1266 fprintf (stderr, "ping_send failed: %s\n",
1267 ping_get_error (ping));
1268 return (1);
1269 }
1271 index = 0;
1272 for (iter = ping_iterator_get (ping);
1273 iter != NULL;
1274 iter = ping_iterator_next (iter))
1275 {
1276 update_host_hook (iter, index);
1277 index++;
1278 }
1280 pre_sleep_hook (ping);
1282 /* Don't sleep in the last iteration */
1283 if (opt_count == 1)
1284 break;
1286 if (gettimeofday (&tv_end, NULL) < 0)
1287 {
1288 perror ("gettimeofday");
1289 return (1);
1290 }
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)
1296 {
1297 if (errno != EINTR)
1298 {
1299 perror ("nanosleep");
1300 break;
1301 }
1302 else if (opt_count == 0)
1303 {
1304 /* sigint */
1305 break;
1306 }
1307 }
1309 post_sleep_hook (ping);
1311 if (opt_count > 0)
1312 opt_count--;
1313 } /* while (opt_count != 0) */
1315 status = post_loop_hook (ping);
1317 ping_destroy (ping);
1319 if (status)
1320 return (EXIT_FAILURE + status);
1321 else
1322 return (EXIT_SUCCESS);
1323 } /* }}} int main */
1325 /* vim: set fdm=marker : */