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 #include <locale.h>
79 #if USE_NCURSES
80 # define NCURSES_OPAQUE 1
81 /* http://newsgroups.derkeiler.com/Archive/Rec/rec.games.roguelike.development/2010-09/msg00050.html */
82 # define _X_OPEN_SOURCE_EXTENDED
83 # include <ncursesw/ncurses.h>
85 # define OPING_GREEN 1
86 # define OPING_YELLOW 2
87 # define OPING_RED 3
88 #endif
90 #include "oping.h"
92 const char *bars[BARS_LEN] = { "▁", "▂", "▃", "▄", "▅", "▆", "▇", "█" };
94 #ifndef _POSIX_SAVED_IDS
95 # define _POSIX_SAVED_IDS 0
96 #endif
98 /* Remove GNU specific __attribute__ settings when using another compiler */
99 #if !__GNUC__
100 # define __attribute__(x) /**/
101 #endif
103 typedef struct ping_context
104 {
105 char host[NI_MAXHOST];
106 char addr[NI_MAXHOST];
108 int index;
109 int req_sent;
110 int req_rcvd;
112 double latency_min;
113 double latency_max;
114 double latency_total;
115 double latency_total_square;
117 #if USE_NCURSES
118 WINDOW *window;
119 #endif
120 } ping_context_t;
122 static double opt_interval = 1.0;
123 static int opt_addrfamily = PING_DEF_AF;
124 static char *opt_srcaddr = NULL;
125 static char *opt_device = NULL;
126 static char *opt_filename = NULL;
127 static int opt_count = -1;
128 static int opt_send_ttl = 64;
129 static uint8_t opt_send_qos = 0;
131 static int host_num = 0;
133 #if USE_NCURSES
134 static WINDOW *main_win = NULL;
135 #endif
137 static void sigint_handler (int signal) /* {{{ */
138 {
139 /* Make compiler happy */
140 signal = 0;
141 /* Exit the loop */
142 opt_count = 0;
143 } /* }}} void sigint_handler */
145 static ping_context_t *context_create (void) /* {{{ */
146 {
147 ping_context_t *ret;
149 if ((ret = malloc (sizeof (ping_context_t))) == NULL)
150 return (NULL);
152 memset (ret, '\0', sizeof (ping_context_t));
154 ret->latency_min = -1.0;
155 ret->latency_max = -1.0;
156 ret->latency_total = 0.0;
157 ret->latency_total_square = 0.0;
159 #if USE_NCURSES
160 ret->window = NULL;
161 #endif
163 return (ret);
164 } /* }}} ping_context_t *context_create */
166 static void context_destroy (ping_context_t *context) /* {{{ */
167 {
168 if (context == NULL)
169 return;
171 #if USE_NCURSES
172 if (context->window != NULL)
173 {
174 delwin (context->window);
175 context->window = NULL;
176 }
177 #endif
179 free (context);
180 } /* }}} void context_destroy */
182 static double context_get_average (ping_context_t *ctx) /* {{{ */
183 {
184 double num_total;
186 if (ctx == NULL)
187 return (-1.0);
189 if (ctx->req_rcvd < 1)
190 return (-0.0);
192 num_total = (double) ctx->req_rcvd;
193 return (ctx->latency_total / num_total);
194 } /* }}} double context_get_average */
196 static double context_get_stddev (ping_context_t *ctx) /* {{{ */
197 {
198 double num_total;
200 if (ctx == NULL)
201 return (-1.0);
203 if (ctx->req_rcvd < 1)
204 return (-0.0);
205 else if (ctx->req_rcvd < 2)
206 return (0.0);
208 num_total = (double) ctx->req_rcvd;
209 return (sqrt (((num_total * ctx->latency_total_square)
210 - (ctx->latency_total * ctx->latency_total))
211 / (num_total * (num_total - 1.0))));
212 } /* }}} double context_get_stddev */
214 static double context_get_packet_loss (const ping_context_t *ctx) /* {{{ */
215 {
216 if (ctx == NULL)
217 return (-1.0);
219 if (ctx->req_sent < 1)
220 return (0.0);
222 return (100.0 * (ctx->req_sent - ctx->req_rcvd)
223 / ((double) ctx->req_sent));
224 } /* }}} double context_get_packet_loss */
226 static int ping_initialize_contexts (pingobj_t *ping) /* {{{ */
227 {
228 pingobj_iter_t *iter;
229 int index;
231 if (ping == NULL)
232 return (EINVAL);
234 index = 0;
235 for (iter = ping_iterator_get (ping);
236 iter != NULL;
237 iter = ping_iterator_next (iter))
238 {
239 ping_context_t *context;
240 size_t buffer_size;
242 context = context_create ();
243 context->index = index;
245 buffer_size = sizeof (context->host);
246 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
248 buffer_size = sizeof (context->addr);
249 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
251 ping_iterator_set_context (iter, (void *) context);
253 index++;
254 }
256 return (0);
257 } /* }}} int ping_initialize_contexts */
259 static void usage_exit (const char *name, int status) /* {{{ */
260 {
261 fprintf (stderr, "Usage: %s [OPTIONS] "
262 "-f filename | host [host [host ...]]\n"
264 "\nAvailable options:\n"
265 " -4|-6 force the use of IPv4 or IPv6\n"
266 " -c count number of ICMP packets to send\n"
267 " -i interval interval with which to send ICMP packets\n"
268 " -t ttl time to live for each ICMP packet\n"
269 " -Q qos Quality of Service (QoS) of outgoing packets\n"
270 " Use \"-Q help\" for a list of valid options.\n"
271 " -I srcaddr source address\n"
272 " -D device outgoing interface name\n"
273 " -f filename filename to read hosts from\n"
275 "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
276 "by Florian octo Forster <octo@verplant.org>\n"
277 "for contributions see `AUTHORS'\n",
278 name);
279 exit (status);
280 } /* }}} void usage_exit */
282 __attribute__((noreturn))
283 static void usage_qos_exit (const char *arg, int status) /* {{{ */
284 {
285 if (arg != 0)
286 fprintf (stderr, "Invalid QoS argument: \"%s\"\n\n", arg);
288 fprintf (stderr, "Valid QoS arguments (option \"-Q\") are:\n"
289 "\n"
290 " Differentiated Services (IPv4 and IPv6, RFC 2474)\n"
291 "\n"
292 " be Best Effort (BE, default PHB).\n"
293 " ef Expedited Forwarding (EF) PHB group (RFC 3246).\n"
294 " (low delay, low loss, low jitter)\n"
295 " va Voice Admit (VA) DSCP (RFC 5865).\n"
296 " (capacity-admitted traffic)\n"
297 " af[1-4][1-3] Assured Forwarding (AF) PHB group (RFC 2597).\n"
298 " For example: \"af12\" (class 1, precedence 2)\n"
299 " cs[0-7] Class Selector (CS) PHB group (RFC 2474).\n"
300 " For example: \"cs1\" (priority traffic)\n"
301 "\n"
302 " Type of Service (IPv4, RFC 1349, obsolete)\n"
303 "\n"
304 " lowdelay (%#04x) minimize delay\n"
305 " throughput (%#04x) maximize throughput\n"
306 " reliability (%#04x) maximize reliability\n"
307 " mincost (%#04x) minimize monetary cost\n"
308 "\n"
309 " Specify manually\n"
310 "\n"
311 " 0x00 - 0xff Hexadecimal numeric specification.\n"
312 " 0 - 255 Decimal numeric specification.\n"
313 "\n",
314 (unsigned int) IPTOS_LOWDELAY,
315 (unsigned int) IPTOS_THROUGHPUT,
316 (unsigned int) IPTOS_RELIABILITY,
317 (unsigned int) IPTOS_MINCOST);
319 exit (status);
320 } /* }}} void usage_qos_exit */
322 static int set_opt_send_qos (const char *opt) /* {{{ */
323 {
324 if (opt == NULL)
325 return (EINVAL);
327 if (strcasecmp ("help", opt) == 0)
328 usage_qos_exit (/* arg = */ NULL, /* status = */ EXIT_SUCCESS);
329 /* DiffServ (RFC 2474): */
330 /* - Best effort (BE) */
331 else if (strcasecmp ("be", opt) == 0)
332 opt_send_qos = 0;
333 /* - Expedited Forwarding (EF, RFC 3246) */
334 else if (strcasecmp ("ef", opt) == 0)
335 opt_send_qos = 0xB8; /* == 0x2E << 2 */
336 /* - Voice Admit (VA, RFC 5865) */
337 else if (strcasecmp ("va", opt) == 0)
338 opt_send_qos = 0xB0; /* == 0x2D << 2 */
339 /* - Assured Forwarding (AF, RFC 2597) */
340 else if ((strncasecmp ("af", opt, strlen ("af")) == 0)
341 && (strlen (opt) == 4))
342 {
343 uint8_t dscp;
344 uint8_t class = 0;
345 uint8_t prec = 0;
347 /* There are four classes, AF1x, AF2x, AF3x, and AF4x. */
348 if (opt[2] == '1')
349 class = 1;
350 else if (opt[2] == '2')
351 class = 2;
352 else if (opt[2] == '3')
353 class = 3;
354 else if (opt[2] == '4')
355 class = 4;
356 else
357 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
359 /* In each class, there are three precedences, AFx1, AFx2, and AFx3 */
360 if (opt[3] == '1')
361 prec = 1;
362 else if (opt[3] == '2')
363 prec = 2;
364 else if (opt[3] == '3')
365 prec = 3;
366 else
367 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
369 dscp = (8 * class) + (2 * prec);
370 /* The lower two bits are used for Explicit Congestion Notification (ECN) */
371 opt_send_qos = dscp << 2;
372 }
373 /* - Class Selector (CS) */
374 else if ((strncasecmp ("cs", opt, strlen ("cs")) == 0)
375 && (strlen (opt) == 3))
376 {
377 uint8_t class;
379 if ((opt[2] < '0') || (opt[2] > '7'))
380 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
382 /* Not exactly legal by the C standard, but I don't know of any
383 * system not supporting this hack. */
384 class = ((uint8_t) opt[2]) - ((uint8_t) '0');
385 opt_send_qos = class << 5;
386 }
387 /* Type of Service (RFC 1349) */
388 else if (strcasecmp ("lowdelay", opt) == 0)
389 opt_send_qos = IPTOS_LOWDELAY;
390 else if (strcasecmp ("throughput", opt) == 0)
391 opt_send_qos = IPTOS_THROUGHPUT;
392 else if (strcasecmp ("reliability", opt) == 0)
393 opt_send_qos = IPTOS_RELIABILITY;
394 else if (strcasecmp ("mincost", opt) == 0)
395 opt_send_qos = IPTOS_MINCOST;
396 /* Numeric value */
397 else
398 {
399 unsigned long value;
400 char *endptr;
402 errno = 0;
403 endptr = NULL;
404 value = strtoul (opt, &endptr, /* base = */ 0);
405 if ((errno != 0) || (endptr == opt)
406 || (endptr == NULL) || (*endptr != 0)
407 || (value > 0xff))
408 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
410 opt_send_qos = (uint8_t) value;
411 }
413 return (0);
414 } /* }}} int set_opt_send_qos */
416 static char *format_qos (uint8_t qos, char *buffer, size_t buffer_size) /* {{{ */
417 {
418 uint8_t dscp;
419 uint8_t ecn;
420 char *dscp_str;
421 char *ecn_str;
423 dscp = qos >> 2;
424 ecn = qos & 0x03;
426 switch (dscp)
427 {
428 case 0x00: dscp_str = "be"; break;
429 case 0x2e: dscp_str = "ef"; break;
430 case 0x2d: dscp_str = "va"; break;
431 case 0x0a: dscp_str = "af11"; break;
432 case 0x0c: dscp_str = "af12"; break;
433 case 0x0e: dscp_str = "af13"; break;
434 case 0x12: dscp_str = "af21"; break;
435 case 0x14: dscp_str = "af22"; break;
436 case 0x16: dscp_str = "af23"; break;
437 case 0x1a: dscp_str = "af31"; break;
438 case 0x1c: dscp_str = "af32"; break;
439 case 0x1e: dscp_str = "af33"; break;
440 case 0x22: dscp_str = "af41"; break;
441 case 0x24: dscp_str = "af42"; break;
442 case 0x26: dscp_str = "af43"; break;
443 case 0x08: dscp_str = "cs1"; break;
444 case 0x10: dscp_str = "cs2"; break;
445 case 0x18: dscp_str = "cs3"; break;
446 case 0x20: dscp_str = "cs4"; break;
447 case 0x28: dscp_str = "cs5"; break;
448 case 0x30: dscp_str = "cs6"; break;
449 case 0x38: dscp_str = "cs7"; break;
450 default: dscp_str = NULL;
451 }
453 switch (ecn)
454 {
455 case 0x01: ecn_str = ",ecn(1)"; break;
456 case 0x02: ecn_str = ",ecn(0)"; break;
457 case 0x03: ecn_str = ",ce"; break;
458 default: ecn_str = "";
459 }
461 if (dscp_str == NULL)
462 snprintf (buffer, buffer_size, "0x%02x%s", dscp, ecn_str);
463 else
464 snprintf (buffer, buffer_size, "%s%s", dscp_str, ecn_str);
465 buffer[buffer_size - 1] = 0;
467 return (buffer);
468 } /* }}} char *format_qos */
470 static int read_options (int argc, char **argv) /* {{{ */
471 {
472 int optchar;
474 while (1)
475 {
476 optchar = getopt (argc, argv, "46c:hi:I:t:Q:f:D:");
478 if (optchar == -1)
479 break;
481 switch (optchar)
482 {
483 case '4':
484 case '6':
485 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
486 break;
488 case 'c':
489 {
490 int new_count;
491 new_count = atoi (optarg);
492 if (new_count > 0)
493 opt_count = new_count;
494 else
495 fprintf(stderr, "Ignoring invalid count: %s\n",
496 optarg);
497 }
498 break;
500 case 'f':
501 {
502 if (opt_filename != NULL)
503 free (opt_filename);
504 opt_filename = strdup (optarg);
505 }
506 break;
508 case 'i':
509 {
510 double new_interval;
511 new_interval = atof (optarg);
512 if (new_interval < 0.001)
513 fprintf (stderr, "Ignoring invalid interval: %s\n",
514 optarg);
515 else
516 opt_interval = new_interval;
517 }
518 break;
519 case 'I':
520 {
521 if (opt_srcaddr != NULL)
522 free (opt_srcaddr);
523 opt_srcaddr = strdup (optarg);
524 }
525 break;
527 case 'D':
528 opt_device = optarg;
529 break;
531 case 't':
532 {
533 int new_send_ttl;
534 new_send_ttl = atoi (optarg);
535 if ((new_send_ttl > 0) && (new_send_ttl < 256))
536 opt_send_ttl = new_send_ttl;
537 else
538 fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
539 optarg);
540 break;
541 }
543 case 'Q':
544 set_opt_send_qos (optarg);
545 break;
547 case 'h':
548 usage_exit (argv[0], 0);
549 break;
550 default:
551 usage_exit (argv[0], 1);
552 }
553 }
555 return (optind);
556 } /* }}} read_options */
558 static void time_normalize (struct timespec *ts) /* {{{ */
559 {
560 while (ts->tv_nsec < 0)
561 {
562 if (ts->tv_sec == 0)
563 {
564 ts->tv_nsec = 0;
565 return;
566 }
568 ts->tv_sec -= 1;
569 ts->tv_nsec += 1000000000;
570 }
572 while (ts->tv_nsec >= 1000000000)
573 {
574 ts->tv_sec += 1;
575 ts->tv_nsec -= 1000000000;
576 }
577 } /* }}} void time_normalize */
579 static void time_calc (struct timespec *ts_dest, /* {{{ */
580 const struct timespec *ts_int,
581 const struct timeval *tv_begin,
582 const struct timeval *tv_end)
583 {
584 ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
585 ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
586 time_normalize (ts_dest);
588 /* Assure that `(begin + interval) > end'.
589 * This may seem overly complicated, but `tv_sec' is of type `time_t'
590 * which may be `unsigned. *sigh* */
591 if ((tv_end->tv_sec > ts_dest->tv_sec)
592 || ((tv_end->tv_sec == ts_dest->tv_sec)
593 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
594 {
595 ts_dest->tv_sec = 0;
596 ts_dest->tv_nsec = 0;
597 return;
598 }
600 ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
601 ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
602 time_normalize (ts_dest);
603 } /* }}} void time_calc */
605 #if USE_NCURSES
606 static int update_stats_from_context (ping_context_t *ctx) /* {{{ */
607 {
608 if ((ctx == NULL) || (ctx->window == NULL))
609 return (EINVAL);
611 werase (ctx->window);
613 box (ctx->window, 0, 0);
614 wattron (ctx->window, A_BOLD);
615 mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
616 " %s ", ctx->host);
617 wattroff (ctx->window, A_BOLD);
618 wprintw (ctx->window, "ping statistics ");
619 mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
620 "%i packets transmitted, %i received, %.2f%% packet "
621 "loss, time %.1fms",
622 ctx->req_sent, ctx->req_rcvd,
623 context_get_packet_loss (ctx),
624 ctx->latency_total);
625 if (ctx->req_rcvd != 0)
626 {
627 double average;
628 double deviation;
630 average = context_get_average (ctx);
631 deviation = context_get_stddev (ctx);
633 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
634 "rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms",
635 ctx->latency_min,
636 average,
637 ctx->latency_max,
638 deviation);
639 }
641 wrefresh (ctx->window);
643 return (0);
644 } /* }}} int update_stats_from_context */
646 static int on_resize (pingobj_t *ping) /* {{{ */
647 {
648 pingobj_iter_t *iter;
649 int width = 0;
650 int height = 0;
651 int main_win_height;
653 getmaxyx (stdscr, height, width);
654 if ((height < 1) || (width < 1))
655 return (EINVAL);
657 main_win_height = height - (4 * host_num);
658 wresize (main_win, main_win_height, /* width = */ width);
659 /* Allow scrolling */
660 scrollok (main_win, TRUE);
661 /* wsetscrreg (main_win, 0, main_win_height - 1); */
662 /* Allow hardware accelerated scrolling. */
663 idlok (main_win, TRUE);
664 wrefresh (main_win);
666 for (iter = ping_iterator_get (ping);
667 iter != NULL;
668 iter = ping_iterator_next (iter))
669 {
670 ping_context_t *context;
672 context = ping_iterator_get_context (iter);
673 if (context == NULL)
674 continue;
676 if (context->window != NULL)
677 {
678 delwin (context->window);
679 context->window = NULL;
680 }
681 context->window = newwin (/* height = */ 4,
682 /* width = */ width,
683 /* y = */ main_win_height + (4 * context->index),
684 /* x = */ 0);
685 }
687 return (0);
688 } /* }}} */
690 static int check_resize (pingobj_t *ping) /* {{{ */
691 {
692 int need_resize = 0;
694 while (42)
695 {
696 int key = wgetch (stdscr);
697 if (key == ERR)
698 break;
699 else if (key == KEY_RESIZE)
700 need_resize = 1;
701 }
703 if (need_resize)
704 return (on_resize (ping));
705 else
706 return (0);
707 } /* }}} int check_resize */
709 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
710 {
711 pingobj_iter_t *iter;
712 int width = 0;
713 int height = 0;
714 int main_win_height;
716 initscr ();
717 cbreak ();
718 noecho ();
719 nodelay (stdscr, TRUE);
721 getmaxyx (stdscr, height, width);
722 if ((height < 1) || (width < 1))
723 return (EINVAL);
725 if (has_colors () == TRUE)
726 {
727 start_color ();
728 init_pair (OPING_GREEN, COLOR_GREEN, /* default = */ 0);
729 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
730 init_pair (OPING_RED, COLOR_RED, /* default = */ 0);
731 }
733 main_win_height = height - (4 * host_num);
734 main_win = newwin (/* height = */ main_win_height,
735 /* width = */ width,
736 /* y = */ 0, /* x = */ 0);
737 /* Allow scrolling */
738 scrollok (main_win, TRUE);
739 /* wsetscrreg (main_win, 0, main_win_height - 1); */
740 /* Allow hardware accelerated scrolling. */
741 idlok (main_win, TRUE);
742 wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
743 wrefresh (main_win);
745 for (iter = ping_iterator_get (ping);
746 iter != NULL;
747 iter = ping_iterator_next (iter))
748 {
749 ping_context_t *context;
751 context = ping_iterator_get_context (iter);
752 if (context == NULL)
753 continue;
755 if (context->window != NULL)
756 {
757 delwin (context->window);
758 context->window = NULL;
759 }
760 context->window = newwin (/* height = */ 4,
761 /* width = */ width,
762 /* y = */ main_win_height + (4 * context->index),
763 /* x = */ 0);
764 }
767 /* Don't know what good this does exactly, but without this code
768 * "check_resize" will be called right after startup and *somehow*
769 * this leads to display errors. If we purge all initial characters
770 * here, the problem goes away. "wgetch" is non-blocking due to
771 * "nodelay" (see above). */
772 while (wgetch (stdscr) != ERR)
773 {
774 /* eat up characters */;
775 }
777 return (0);
778 } /* }}} int pre_loop_hook */
780 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
781 {
782 return (check_resize (ping));
783 } /* }}} int pre_sleep_hook */
785 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
786 {
787 return (check_resize (ping));
788 } /* }}} int pre_sleep_hook */
789 #else /* if !USE_NCURSES */
790 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
791 {
792 pingobj_iter_t *iter;
794 for (iter = ping_iterator_get (ping);
795 iter != NULL;
796 iter = ping_iterator_next (iter))
797 {
798 ping_context_t *ctx;
799 size_t buffer_size;
801 ctx = ping_iterator_get_context (iter);
802 if (ctx == NULL)
803 continue;
805 buffer_size = 0;
806 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
808 printf ("PING %s (%s) %zu bytes of data.\n",
809 ctx->host, ctx->addr, buffer_size);
810 }
812 return (0);
813 } /* }}} int pre_loop_hook */
815 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
816 {
817 fflush (stdout);
819 return (0);
820 } /* }}} int pre_sleep_hook */
822 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
823 {
824 return (0);
825 } /* }}} int post_sleep_hook */
826 #endif
828 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
829 __attribute__((unused)) int index)
830 {
831 double latency;
832 unsigned int sequence;
833 int recv_ttl;
834 uint8_t recv_qos;
835 char recv_qos_str[16];
836 size_t buffer_len;
837 size_t data_len;
838 ping_context_t *context;
840 latency = -1.0;
841 buffer_len = sizeof (latency);
842 ping_iterator_get_info (iter, PING_INFO_LATENCY,
843 &latency, &buffer_len);
845 sequence = 0;
846 buffer_len = sizeof (sequence);
847 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
848 &sequence, &buffer_len);
850 recv_ttl = -1;
851 buffer_len = sizeof (recv_ttl);
852 ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
853 &recv_ttl, &buffer_len);
855 recv_qos = 0;
856 buffer_len = sizeof (recv_qos);
857 ping_iterator_get_info (iter, PING_INFO_RECV_QOS,
858 &recv_qos, &buffer_len);
860 data_len = 0;
861 ping_iterator_get_info (iter, PING_INFO_DATA,
862 NULL, &data_len);
864 context = (ping_context_t *) ping_iterator_get_context (iter);
866 #if USE_NCURSES
867 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
868 #else
869 # define HOST_PRINTF(...) printf(__VA_ARGS__)
870 #endif
872 context->req_sent++;
873 if (latency > 0.0)
874 {
875 context->req_rcvd++;
876 context->latency_total += latency;
877 context->latency_total_square += (latency * latency);
879 if ((context->latency_max < 0.0) || (context->latency_max < latency))
880 context->latency_max = latency;
881 if ((context->latency_min < 0.0) || (context->latency_min > latency))
882 context->latency_min = latency;
884 #if USE_NCURSES
885 if (has_colors () == TRUE)
886 {
887 int color = OPING_GREEN;
888 float ratio = 0;
889 int index = 0;
891 ratio = ( latency - context->latency_min ) / ( context->latency_max - context->latency_min );
892 if (ratio > 2/3.0) {
893 color = OPING_RED;
894 }
895 else if (ratio > 1/3.0) {
896 color = OPING_YELLOW;
897 }
898 index = (int) (ratio * BARS_LEN * 3); /* 3 colors */
899 /* HOST_PRINTF ("%%r%f-ia%d-", ratio, index); */
900 index = index % (BARS_LEN-1);
901 /* HOST_PRINTF ("im%d-", index); */
902 if (index < 0 || index >= BARS_LEN) {
903 index = 0; /* safety check */
904 }
905 wattron (main_win, COLOR_PAIR(color));
906 HOST_PRINTF (bars[index]);
907 wattroff (main_win, COLOR_PAIR(color));
908 }
909 else
910 {
911 #endif
912 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
913 data_len,
914 context->host, context->addr,
915 sequence, recv_ttl);
916 if ((recv_qos != 0) || (opt_send_qos != 0))
917 {
918 HOST_PRINTF ("qos=%s ",
919 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
920 }
921 HOST_PRINTF ("time=%.2f ms\n", latency);
922 #if USE_NCURSES
923 }
924 #endif
925 }
926 else
927 {
928 #if USE_NCURSES
929 if (has_colors () == TRUE)
930 {
931 wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
932 HOST_PRINTF ("!");
933 wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
934 }
935 else
936 {
937 #endif
938 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
939 context->host, context->addr,
940 sequence);
941 #if USE_NCURSES
942 }
943 #endif
944 }
946 #if USE_NCURSES
947 update_stats_from_context (context);
948 wrefresh (main_win);
949 #endif
950 } /* }}} void update_host_hook */
952 static int post_loop_hook (pingobj_t *ping) /* {{{ */
953 {
954 pingobj_iter_t *iter;
956 #if USE_NCURSES
957 endwin ();
958 #endif
960 for (iter = ping_iterator_get (ping);
961 iter != NULL;
962 iter = ping_iterator_next (iter))
963 {
964 ping_context_t *context;
966 context = ping_iterator_get_context (iter);
968 printf ("\n--- %s ping statistics ---\n"
969 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
970 context->host, context->req_sent, context->req_rcvd,
971 context_get_packet_loss (context),
972 context->latency_total);
974 if (context->req_rcvd != 0)
975 {
976 double average;
977 double deviation;
979 average = context_get_average (context);
980 deviation = context_get_stddev (context);
982 printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
983 context->latency_min,
984 average,
985 context->latency_max,
986 deviation);
987 }
989 ping_iterator_set_context (iter, NULL);
990 context_destroy (context);
991 }
993 return (0);
994 } /* }}} int post_loop_hook */
996 int main (int argc, char **argv) /* {{{ */
997 {
998 pingobj_t *ping;
999 pingobj_iter_t *iter;
1001 struct sigaction sigint_action;
1003 struct timeval tv_begin;
1004 struct timeval tv_end;
1005 struct timespec ts_wait;
1006 struct timespec ts_int;
1008 int optind;
1009 int i;
1010 int status;
1011 #if _POSIX_SAVED_IDS
1012 uid_t saved_set_uid;
1014 /* Save the old effective user id */
1015 saved_set_uid = geteuid ();
1016 /* Set the effective user ID to the real user ID without changing the
1017 * saved set-user ID */
1018 status = seteuid (getuid ());
1019 if (status != 0)
1020 {
1021 fprintf (stderr, "Temporarily dropping privileges "
1022 "failed: %s\n", strerror (errno));
1023 exit (EXIT_FAILURE);
1024 }
1025 #endif
1027 setlocale(LC_ALL, "");
1028 optind = read_options (argc, argv);
1030 #if !_POSIX_SAVED_IDS
1031 /* Cannot temporarily drop privileges -> reject every file but "-". */
1032 if ((opt_filename != NULL)
1033 && (strcmp ("-", opt_filename) != 0)
1034 && (getuid () != geteuid ()))
1035 {
1036 fprintf (stderr, "Your real and effective user IDs don't "
1037 "match. Reading from a file (option '-f')\n"
1038 "is therefore too risky. You can still read "
1039 "from STDIN using '-f -' if you like.\n"
1040 "Sorry.\n");
1041 exit (EXIT_FAILURE);
1042 }
1043 #endif
1045 if ((optind >= argc) && (opt_filename == NULL)) {
1046 usage_exit (argv[0], 1);
1047 }
1049 if ((ping = ping_construct ()) == NULL)
1050 {
1051 fprintf (stderr, "ping_construct failed\n");
1052 return (1);
1053 }
1055 if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
1056 {
1057 fprintf (stderr, "Setting TTL to %i failed: %s\n",
1058 opt_send_ttl, ping_get_error (ping));
1059 }
1061 if (ping_setopt (ping, PING_OPT_QOS, &opt_send_qos) != 0)
1062 {
1063 fprintf (stderr, "Setting TOS to %i failed: %s\n",
1064 opt_send_qos, ping_get_error (ping));
1065 }
1067 {
1068 double temp_sec;
1069 double temp_nsec;
1071 temp_nsec = modf (opt_interval, &temp_sec);
1072 ts_int.tv_sec = (time_t) temp_sec;
1073 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
1075 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
1076 }
1078 if (opt_addrfamily != PING_DEF_AF)
1079 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
1081 if (opt_srcaddr != NULL)
1082 {
1083 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
1084 {
1085 fprintf (stderr, "Setting source address failed: %s\n",
1086 ping_get_error (ping));
1087 }
1088 }
1090 if (opt_device != NULL)
1091 {
1092 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
1093 {
1094 fprintf (stderr, "Setting device failed: %s\n",
1095 ping_get_error (ping));
1096 }
1097 }
1099 if (opt_filename != NULL)
1100 {
1101 FILE *infile;
1102 char line[256];
1103 char host[256];
1105 if (strcmp (opt_filename, "-") == 0)
1106 /* Open STDIN */
1107 infile = fdopen(0, "r");
1108 else
1109 infile = fopen(opt_filename, "r");
1111 if (infile == NULL)
1112 {
1113 fprintf (stderr, "Opening %s failed: %s\n",
1114 (strcmp (opt_filename, "-") == 0)
1115 ? "STDIN" : opt_filename,
1116 strerror(errno));
1117 return (1);
1118 }
1120 #if _POSIX_SAVED_IDS
1121 /* Regain privileges */
1122 status = seteuid (saved_set_uid);
1123 if (status != 0)
1124 {
1125 fprintf (stderr, "Temporarily re-gaining privileges "
1126 "failed: %s\n", strerror (errno));
1127 exit (EXIT_FAILURE);
1128 }
1129 #endif
1131 while (fgets(line, sizeof(line), infile))
1132 {
1133 /* Strip whitespace */
1134 if (sscanf(line, "%s", host) != 1)
1135 continue;
1137 if ((host[0] == 0) || (host[0] == '#'))
1138 continue;
1140 if (ping_host_add(ping, host) < 0)
1141 {
1142 const char *errmsg = ping_get_error (ping);
1144 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
1145 continue;
1146 }
1147 else
1148 {
1149 host_num++;
1150 }
1151 }
1153 #if _POSIX_SAVED_IDS
1154 /* Drop privileges */
1155 status = seteuid (getuid ());
1156 if (status != 0)
1157 {
1158 fprintf (stderr, "Temporarily dropping privileges "
1159 "failed: %s\n", strerror (errno));
1160 exit (EXIT_FAILURE);
1161 }
1162 #endif
1164 fclose(infile);
1165 }
1167 #if _POSIX_SAVED_IDS
1168 /* Regain privileges */
1169 status = seteuid (saved_set_uid);
1170 if (status != 0)
1171 {
1172 fprintf (stderr, "Temporarily re-gaining privileges "
1173 "failed: %s\n", strerror (errno));
1174 exit (EXIT_FAILURE);
1175 }
1176 #endif
1178 for (i = optind; i < argc; i++)
1179 {
1180 if (ping_host_add (ping, argv[i]) < 0)
1181 {
1182 const char *errmsg = ping_get_error (ping);
1184 fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
1185 continue;
1186 }
1187 else
1188 {
1189 host_num++;
1190 }
1191 }
1193 /* Permanently drop root privileges if we're setuid-root. */
1194 status = setuid (getuid ());
1195 if (status != 0)
1196 {
1197 fprintf (stderr, "Dropping privileges failed: %s\n",
1198 strerror (errno));
1199 exit (EXIT_FAILURE);
1200 }
1202 #if _POSIX_SAVED_IDS
1203 saved_set_uid = (uid_t) -1;
1204 #endif
1206 ping_initialize_contexts (ping);
1208 if (i == 0)
1209 return (1);
1211 memset (&sigint_action, '\0', sizeof (sigint_action));
1212 sigint_action.sa_handler = sigint_handler;
1213 if (sigaction (SIGINT, &sigint_action, NULL) < 0)
1214 {
1215 perror ("sigaction");
1216 return (1);
1217 }
1219 pre_loop_hook (ping);
1221 while (opt_count != 0)
1222 {
1223 int index;
1224 int status;
1226 if (gettimeofday (&tv_begin, NULL) < 0)
1227 {
1228 perror ("gettimeofday");
1229 return (1);
1230 }
1232 if (ping_send (ping) < 0)
1233 {
1234 fprintf (stderr, "ping_send failed: %s\n",
1235 ping_get_error (ping));
1236 return (1);
1237 }
1239 index = 0;
1240 for (iter = ping_iterator_get (ping);
1241 iter != NULL;
1242 iter = ping_iterator_next (iter))
1243 {
1244 update_host_hook (iter, index);
1245 index++;
1246 }
1248 pre_sleep_hook (ping);
1250 /* Don't sleep in the last iteration */
1251 if (opt_count == 1)
1252 break;
1254 if (gettimeofday (&tv_end, NULL) < 0)
1255 {
1256 perror ("gettimeofday");
1257 return (1);
1258 }
1260 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1262 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1263 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1264 {
1265 if (errno != EINTR)
1266 {
1267 perror ("nanosleep");
1268 break;
1269 }
1270 else if (opt_count == 0)
1271 {
1272 /* sigint */
1273 break;
1274 }
1275 }
1277 post_sleep_hook (ping);
1279 if (opt_count > 0)
1280 opt_count--;
1281 } /* while (opt_count != 0) */
1283 post_loop_hook (ping);
1285 ping_destroy (ping);
1287 return (0);
1288 } /* }}} int main */
1290 /* vim: set fdm=marker : */