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 /* some evilness: ncurses knows how to detect unicode, but won't
86 expose it, yet there's this function that does what we want, so we
87 steal it away from it */
88 extern int _nc_unicode_locale(void);
90 # define OPING_GREEN 1
91 # define OPING_YELLOW 2
92 # define OPING_RED 3
93 # define OPING_GREEN_HIST 4
94 # define OPING_YELLOW_HIST 5
95 # define OPING_RED_HIST 6
97 static char const * const hist_symbols_utf8[] = {
98 "▁", "▂", "▃", "▄", "▅", "▆", "▇", "█" };
99 static size_t const hist_symbols_utf8_num = sizeof (hist_symbols_utf8)
100 / sizeof (hist_symbols_utf8[0]);
102 /* scancodes for 6 levels of horizontal bars, ncurses-specific */
103 /* those are not the usual constants because those are not constant */
104 static int const hist_symbols_acs[] = {
105 115, /* ACS_S9 "⎽" */
106 114, /* ACS_S7 "⎼" */
107 113, /* ACS_S5 "─" */
108 112, /* ACS_S3 "⎻" */
109 111 /* ACS_S1 "⎺" */
110 };
111 static size_t const hist_symbols_acs_num = sizeof (hist_symbols_acs)
112 / sizeof (hist_symbols_acs[0]);
114 /* use different colors without a background for scancodes */
115 static int const hist_colors_utf8[] = {
116 OPING_GREEN_HIST, OPING_YELLOW_HIST, OPING_RED_HIST };
117 static int const hist_colors_acs[] = {
118 OPING_GREEN, OPING_YELLOW, OPING_RED };
119 /* assuming that both arrays are the same size */
120 static size_t const hist_colors_num = sizeof (hist_colors_utf8)
121 / sizeof (hist_colors_utf8[0]);
122 #endif
124 #include "oping.h"
126 #ifndef _POSIX_SAVED_IDS
127 # define _POSIX_SAVED_IDS 0
128 #endif
130 /* Remove GNU specific __attribute__ settings when using another compiler */
131 #if !__GNUC__
132 # define __attribute__(x) /**/
133 #endif
135 typedef struct ping_context
136 {
137 char host[NI_MAXHOST];
138 char addr[NI_MAXHOST];
140 int index;
141 int req_sent;
142 int req_rcvd;
144 double latency_min;
145 double latency_max;
146 double latency_total;
147 double latency_total_square;
149 #if USE_NCURSES
150 WINDOW *window;
151 #endif
152 } ping_context_t;
154 static double opt_interval = 1.0;
155 static int opt_addrfamily = PING_DEF_AF;
156 static char *opt_srcaddr = NULL;
157 static char *opt_device = NULL;
158 static char *opt_filename = NULL;
159 static int opt_count = -1;
160 static int opt_send_ttl = 64;
161 static uint8_t opt_send_qos = 0;
163 static int host_num = 0;
165 #if USE_NCURSES
166 static WINDOW *main_win = NULL;
167 #endif
169 static void sigint_handler (int signal) /* {{{ */
170 {
171 /* Make compiler happy */
172 signal = 0;
173 /* Exit the loop */
174 opt_count = 0;
175 } /* }}} void sigint_handler */
177 static ping_context_t *context_create (void) /* {{{ */
178 {
179 ping_context_t *ret;
181 if ((ret = malloc (sizeof (ping_context_t))) == NULL)
182 return (NULL);
184 memset (ret, '\0', sizeof (ping_context_t));
186 ret->latency_min = -1.0;
187 ret->latency_max = -1.0;
188 ret->latency_total = 0.0;
189 ret->latency_total_square = 0.0;
191 #if USE_NCURSES
192 ret->window = NULL;
193 #endif
195 return (ret);
196 } /* }}} ping_context_t *context_create */
198 static void context_destroy (ping_context_t *context) /* {{{ */
199 {
200 if (context == NULL)
201 return;
203 #if USE_NCURSES
204 if (context->window != NULL)
205 {
206 delwin (context->window);
207 context->window = NULL;
208 }
209 #endif
211 free (context);
212 } /* }}} void context_destroy */
214 static double context_get_average (ping_context_t *ctx) /* {{{ */
215 {
216 double num_total;
218 if (ctx == NULL)
219 return (-1.0);
221 if (ctx->req_rcvd < 1)
222 return (-0.0);
224 num_total = (double) ctx->req_rcvd;
225 return (ctx->latency_total / num_total);
226 } /* }}} double context_get_average */
228 static double context_get_stddev (ping_context_t *ctx) /* {{{ */
229 {
230 double num_total;
232 if (ctx == NULL)
233 return (-1.0);
235 if (ctx->req_rcvd < 1)
236 return (-0.0);
237 else if (ctx->req_rcvd < 2)
238 return (0.0);
240 num_total = (double) ctx->req_rcvd;
241 return (sqrt (((num_total * ctx->latency_total_square)
242 - (ctx->latency_total * ctx->latency_total))
243 / (num_total * (num_total - 1.0))));
244 } /* }}} double context_get_stddev */
246 static double context_get_packet_loss (const ping_context_t *ctx) /* {{{ */
247 {
248 if (ctx == NULL)
249 return (-1.0);
251 if (ctx->req_sent < 1)
252 return (0.0);
254 return (100.0 * (ctx->req_sent - ctx->req_rcvd)
255 / ((double) ctx->req_sent));
256 } /* }}} double context_get_packet_loss */
258 static int ping_initialize_contexts (pingobj_t *ping) /* {{{ */
259 {
260 pingobj_iter_t *iter;
261 int index;
263 if (ping == NULL)
264 return (EINVAL);
266 index = 0;
267 for (iter = ping_iterator_get (ping);
268 iter != NULL;
269 iter = ping_iterator_next (iter))
270 {
271 ping_context_t *context;
272 size_t buffer_size;
274 context = context_create ();
275 context->index = index;
277 buffer_size = sizeof (context->host);
278 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
280 buffer_size = sizeof (context->addr);
281 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
283 ping_iterator_set_context (iter, (void *) context);
285 index++;
286 }
288 return (0);
289 } /* }}} int ping_initialize_contexts */
291 static void usage_exit (const char *name, int status) /* {{{ */
292 {
293 fprintf (stderr, "Usage: %s [OPTIONS] "
294 "-f filename | host [host [host ...]]\n"
296 "\nAvailable options:\n"
297 " -4|-6 force the use of IPv4 or IPv6\n"
298 " -c count number of ICMP packets to send\n"
299 " -i interval interval with which to send ICMP packets\n"
300 " -t ttl time to live for each ICMP packet\n"
301 " -Q qos Quality of Service (QoS) of outgoing packets\n"
302 " Use \"-Q help\" for a list of valid options.\n"
303 " -I srcaddr source address\n"
304 " -D device outgoing interface name\n"
305 " -f filename filename to read hosts from\n"
307 "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
308 "by Florian octo Forster <octo@verplant.org>\n"
309 "for contributions see `AUTHORS'\n",
310 name);
311 exit (status);
312 } /* }}} void usage_exit */
314 __attribute__((noreturn))
315 static void usage_qos_exit (const char *arg, int status) /* {{{ */
316 {
317 if (arg != 0)
318 fprintf (stderr, "Invalid QoS argument: \"%s\"\n\n", arg);
320 fprintf (stderr, "Valid QoS arguments (option \"-Q\") are:\n"
321 "\n"
322 " Differentiated Services (IPv4 and IPv6, RFC 2474)\n"
323 "\n"
324 " be Best Effort (BE, default PHB).\n"
325 " ef Expedited Forwarding (EF) PHB group (RFC 3246).\n"
326 " (low delay, low loss, low jitter)\n"
327 " va Voice Admit (VA) DSCP (RFC 5865).\n"
328 " (capacity-admitted traffic)\n"
329 " af[1-4][1-3] Assured Forwarding (AF) PHB group (RFC 2597).\n"
330 " For example: \"af12\" (class 1, precedence 2)\n"
331 " cs[0-7] Class Selector (CS) PHB group (RFC 2474).\n"
332 " For example: \"cs1\" (priority traffic)\n"
333 "\n"
334 " Type of Service (IPv4, RFC 1349, obsolete)\n"
335 "\n"
336 " lowdelay (%#04x) minimize delay\n"
337 " throughput (%#04x) maximize throughput\n"
338 " reliability (%#04x) maximize reliability\n"
339 " mincost (%#04x) minimize monetary cost\n"
340 "\n"
341 " Specify manually\n"
342 "\n"
343 " 0x00 - 0xff Hexadecimal numeric specification.\n"
344 " 0 - 255 Decimal numeric specification.\n"
345 "\n",
346 (unsigned int) IPTOS_LOWDELAY,
347 (unsigned int) IPTOS_THROUGHPUT,
348 (unsigned int) IPTOS_RELIABILITY,
349 (unsigned int) IPTOS_MINCOST);
351 exit (status);
352 } /* }}} void usage_qos_exit */
354 static int set_opt_send_qos (const char *opt) /* {{{ */
355 {
356 if (opt == NULL)
357 return (EINVAL);
359 if (strcasecmp ("help", opt) == 0)
360 usage_qos_exit (/* arg = */ NULL, /* status = */ EXIT_SUCCESS);
361 /* DiffServ (RFC 2474): */
362 /* - Best effort (BE) */
363 else if (strcasecmp ("be", opt) == 0)
364 opt_send_qos = 0;
365 /* - Expedited Forwarding (EF, RFC 3246) */
366 else if (strcasecmp ("ef", opt) == 0)
367 opt_send_qos = 0xB8; /* == 0x2E << 2 */
368 /* - Voice Admit (VA, RFC 5865) */
369 else if (strcasecmp ("va", opt) == 0)
370 opt_send_qos = 0xB0; /* == 0x2D << 2 */
371 /* - Assured Forwarding (AF, RFC 2597) */
372 else if ((strncasecmp ("af", opt, strlen ("af")) == 0)
373 && (strlen (opt) == 4))
374 {
375 uint8_t dscp;
376 uint8_t class = 0;
377 uint8_t prec = 0;
379 /* There are four classes, AF1x, AF2x, AF3x, and AF4x. */
380 if (opt[2] == '1')
381 class = 1;
382 else if (opt[2] == '2')
383 class = 2;
384 else if (opt[2] == '3')
385 class = 3;
386 else if (opt[2] == '4')
387 class = 4;
388 else
389 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
391 /* In each class, there are three precedences, AFx1, AFx2, and AFx3 */
392 if (opt[3] == '1')
393 prec = 1;
394 else if (opt[3] == '2')
395 prec = 2;
396 else if (opt[3] == '3')
397 prec = 3;
398 else
399 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
401 dscp = (8 * class) + (2 * prec);
402 /* The lower two bits are used for Explicit Congestion Notification (ECN) */
403 opt_send_qos = dscp << 2;
404 }
405 /* - Class Selector (CS) */
406 else if ((strncasecmp ("cs", opt, strlen ("cs")) == 0)
407 && (strlen (opt) == 3))
408 {
409 uint8_t class;
411 if ((opt[2] < '0') || (opt[2] > '7'))
412 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
414 /* Not exactly legal by the C standard, but I don't know of any
415 * system not supporting this hack. */
416 class = ((uint8_t) opt[2]) - ((uint8_t) '0');
417 opt_send_qos = class << 5;
418 }
419 /* Type of Service (RFC 1349) */
420 else if (strcasecmp ("lowdelay", opt) == 0)
421 opt_send_qos = IPTOS_LOWDELAY;
422 else if (strcasecmp ("throughput", opt) == 0)
423 opt_send_qos = IPTOS_THROUGHPUT;
424 else if (strcasecmp ("reliability", opt) == 0)
425 opt_send_qos = IPTOS_RELIABILITY;
426 else if (strcasecmp ("mincost", opt) == 0)
427 opt_send_qos = IPTOS_MINCOST;
428 /* Numeric value */
429 else
430 {
431 unsigned long value;
432 char *endptr;
434 errno = 0;
435 endptr = NULL;
436 value = strtoul (opt, &endptr, /* base = */ 0);
437 if ((errno != 0) || (endptr == opt)
438 || (endptr == NULL) || (*endptr != 0)
439 || (value > 0xff))
440 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
442 opt_send_qos = (uint8_t) value;
443 }
445 return (0);
446 } /* }}} int set_opt_send_qos */
448 static char *format_qos (uint8_t qos, char *buffer, size_t buffer_size) /* {{{ */
449 {
450 uint8_t dscp;
451 uint8_t ecn;
452 char *dscp_str;
453 char *ecn_str;
455 dscp = qos >> 2;
456 ecn = qos & 0x03;
458 switch (dscp)
459 {
460 case 0x00: dscp_str = "be"; break;
461 case 0x2e: dscp_str = "ef"; break;
462 case 0x2d: dscp_str = "va"; break;
463 case 0x0a: dscp_str = "af11"; break;
464 case 0x0c: dscp_str = "af12"; break;
465 case 0x0e: dscp_str = "af13"; break;
466 case 0x12: dscp_str = "af21"; break;
467 case 0x14: dscp_str = "af22"; break;
468 case 0x16: dscp_str = "af23"; break;
469 case 0x1a: dscp_str = "af31"; break;
470 case 0x1c: dscp_str = "af32"; break;
471 case 0x1e: dscp_str = "af33"; break;
472 case 0x22: dscp_str = "af41"; break;
473 case 0x24: dscp_str = "af42"; break;
474 case 0x26: dscp_str = "af43"; break;
475 case 0x08: dscp_str = "cs1"; break;
476 case 0x10: dscp_str = "cs2"; break;
477 case 0x18: dscp_str = "cs3"; break;
478 case 0x20: dscp_str = "cs4"; break;
479 case 0x28: dscp_str = "cs5"; break;
480 case 0x30: dscp_str = "cs6"; break;
481 case 0x38: dscp_str = "cs7"; break;
482 default: dscp_str = NULL;
483 }
485 switch (ecn)
486 {
487 case 0x01: ecn_str = ",ecn(1)"; break;
488 case 0x02: ecn_str = ",ecn(0)"; break;
489 case 0x03: ecn_str = ",ce"; break;
490 default: ecn_str = "";
491 }
493 if (dscp_str == NULL)
494 snprintf (buffer, buffer_size, "0x%02x%s", dscp, ecn_str);
495 else
496 snprintf (buffer, buffer_size, "%s%s", dscp_str, ecn_str);
497 buffer[buffer_size - 1] = 0;
499 return (buffer);
500 } /* }}} char *format_qos */
502 static int read_options (int argc, char **argv) /* {{{ */
503 {
504 int optchar;
506 while (1)
507 {
508 optchar = getopt (argc, argv, "46c:hi:I:t:Q:f:D:");
510 if (optchar == -1)
511 break;
513 switch (optchar)
514 {
515 case '4':
516 case '6':
517 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
518 break;
520 case 'c':
521 {
522 int new_count;
523 new_count = atoi (optarg);
524 if (new_count > 0)
525 opt_count = new_count;
526 else
527 fprintf(stderr, "Ignoring invalid count: %s\n",
528 optarg);
529 }
530 break;
532 case 'f':
533 {
534 if (opt_filename != NULL)
535 free (opt_filename);
536 opt_filename = strdup (optarg);
537 }
538 break;
540 case 'i':
541 {
542 double new_interval;
543 new_interval = atof (optarg);
544 if (new_interval < 0.001)
545 fprintf (stderr, "Ignoring invalid interval: %s\n",
546 optarg);
547 else
548 opt_interval = new_interval;
549 }
550 break;
551 case 'I':
552 {
553 if (opt_srcaddr != NULL)
554 free (opt_srcaddr);
555 opt_srcaddr = strdup (optarg);
556 }
557 break;
559 case 'D':
560 opt_device = optarg;
561 break;
563 case 't':
564 {
565 int new_send_ttl;
566 new_send_ttl = atoi (optarg);
567 if ((new_send_ttl > 0) && (new_send_ttl < 256))
568 opt_send_ttl = new_send_ttl;
569 else
570 fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
571 optarg);
572 break;
573 }
575 case 'Q':
576 set_opt_send_qos (optarg);
577 break;
579 case 'h':
580 usage_exit (argv[0], 0);
581 break;
582 default:
583 usage_exit (argv[0], 1);
584 }
585 }
587 return (optind);
588 } /* }}} read_options */
590 static void time_normalize (struct timespec *ts) /* {{{ */
591 {
592 while (ts->tv_nsec < 0)
593 {
594 if (ts->tv_sec == 0)
595 {
596 ts->tv_nsec = 0;
597 return;
598 }
600 ts->tv_sec -= 1;
601 ts->tv_nsec += 1000000000;
602 }
604 while (ts->tv_nsec >= 1000000000)
605 {
606 ts->tv_sec += 1;
607 ts->tv_nsec -= 1000000000;
608 }
609 } /* }}} void time_normalize */
611 static void time_calc (struct timespec *ts_dest, /* {{{ */
612 const struct timespec *ts_int,
613 const struct timeval *tv_begin,
614 const struct timeval *tv_end)
615 {
616 ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
617 ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
618 time_normalize (ts_dest);
620 /* Assure that `(begin + interval) > end'.
621 * This may seem overly complicated, but `tv_sec' is of type `time_t'
622 * which may be `unsigned. *sigh* */
623 if ((tv_end->tv_sec > ts_dest->tv_sec)
624 || ((tv_end->tv_sec == ts_dest->tv_sec)
625 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
626 {
627 ts_dest->tv_sec = 0;
628 ts_dest->tv_nsec = 0;
629 return;
630 }
632 ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
633 ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
634 time_normalize (ts_dest);
635 } /* }}} void time_calc */
637 #if USE_NCURSES
638 static int unicode_locale() /* {{{ */
639 {
640 return _nc_unicode_locale();
641 } /* }}} int unicode_locale */
643 static int update_prettyping_graph (ping_context_t *ctx, /* {{{ */
644 double latency, unsigned int sequence)
645 {
646 int color = OPING_RED;
647 char const *symbol = "!";
648 int symbolc = '!';
649 size_t hist_symbols_num;
650 size_t index_symbols;
652 int x_max;
653 int x_pos;
655 x_max = getmaxx (ctx->window);
656 x_pos = ((sequence - 1) % (x_max - 4)) + 2;
658 if (unicode_locale())
659 {
660 hist_symbols_num = hist_symbols_utf8_num;
661 }
662 else {
663 hist_symbols_num = hist_symbols_acs_num;
664 }
666 if (latency >= 0.0)
667 {
668 double ratio;
669 size_t intensity;
670 size_t index_colors;
672 ratio = latency / PING_DEF_TTL;
673 if (ratio > 1) {
674 ratio = 1.0;
675 }
677 intensity = (size_t) ((ratio * hist_symbols_num
678 * hist_colors_num) - 1);
680 index_colors = intensity / hist_symbols_num;
681 assert (index_colors < hist_colors_num);
683 index_symbols = intensity % hist_symbols_num;
684 if (unicode_locale())
685 {
686 color = hist_colors_utf8[index_colors];
687 symbol = hist_symbols_utf8[index_symbols];
688 }
689 else
690 {
691 color = hist_colors_acs[index_colors];
692 symbolc = hist_symbols_acs[index_symbols] | A_ALTCHARSET;
693 }
694 }
695 else /* if (!(latency >= 0.0)) */
696 wattron (ctx->window, A_BOLD);
698 wattron (ctx->window, COLOR_PAIR(color));
699 if (unicode_locale())
700 {
701 mvwprintw (ctx->window,
702 /* y = */ 3,
703 /* x = */ x_pos,
704 symbol);
705 }
706 else {
707 mvwaddch (ctx->window,
708 /* y = */ 3,
709 /* x = */ x_pos,
710 symbolc);
711 }
712 wattroff (ctx->window, COLOR_PAIR(color));
714 /* Use negation here to handle NaN correctly. */
715 if (!(latency >= 0.0))
716 wattroff (ctx->window, A_BOLD);
718 wprintw (ctx->window, " ");
719 return (0);
720 } /* }}} int update_prettyping_graph */
722 static int update_stats_from_context (ping_context_t *ctx, pingobj_iter_t *iter) /* {{{ */
723 {
724 double latency = -1.0;
725 size_t buffer_len = sizeof (latency);
727 ping_iterator_get_info (iter, PING_INFO_LATENCY,
728 &latency, &buffer_len);
730 unsigned int sequence = 0;
731 buffer_len = sizeof (sequence);
732 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
733 &sequence, &buffer_len);
736 if ((ctx == NULL) || (ctx->window == NULL))
737 return (EINVAL);
739 /* werase (ctx->window); */
741 box (ctx->window, 0, 0);
742 wattron (ctx->window, A_BOLD);
743 mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
744 " %s ", ctx->host);
745 wattroff (ctx->window, A_BOLD);
746 wprintw (ctx->window, "ping statistics ");
747 mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
748 "%i packets transmitted, %i received, %.2f%% packet "
749 "loss, time %.1fms",
750 ctx->req_sent, ctx->req_rcvd,
751 context_get_packet_loss (ctx),
752 ctx->latency_total);
753 if (ctx->req_rcvd != 0)
754 {
755 double average;
756 double deviation;
758 average = context_get_average (ctx);
759 deviation = context_get_stddev (ctx);
761 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
762 "rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms",
763 ctx->latency_min,
764 average,
765 ctx->latency_max,
766 deviation);
767 }
769 if (has_colors () == TRUE)
770 update_prettyping_graph (ctx, latency, sequence);
772 wrefresh (ctx->window);
774 return (0);
775 } /* }}} int update_stats_from_context */
777 static int on_resize (pingobj_t *ping) /* {{{ */
778 {
779 pingobj_iter_t *iter;
780 int width = 0;
781 int height = 0;
782 int main_win_height;
784 getmaxyx (stdscr, height, width);
785 if ((height < 1) || (width < 1))
786 return (EINVAL);
788 main_win_height = height - (5 * host_num);
789 wresize (main_win, main_win_height, /* width = */ width);
790 /* Allow scrolling */
791 scrollok (main_win, TRUE);
792 /* wsetscrreg (main_win, 0, main_win_height - 1); */
793 /* Allow hardware accelerated scrolling. */
794 idlok (main_win, TRUE);
795 wrefresh (main_win);
797 for (iter = ping_iterator_get (ping);
798 iter != NULL;
799 iter = ping_iterator_next (iter))
800 {
801 ping_context_t *context;
803 context = ping_iterator_get_context (iter);
804 if (context == NULL)
805 continue;
807 if (context->window != NULL)
808 {
809 delwin (context->window);
810 context->window = NULL;
811 }
812 context->window = newwin (/* height = */ 5,
813 /* width = */ width,
814 /* y = */ main_win_height + (5 * context->index),
815 /* x = */ 0);
816 }
818 return (0);
819 } /* }}} */
821 static int check_resize (pingobj_t *ping) /* {{{ */
822 {
823 int need_resize = 0;
825 while (42)
826 {
827 int key = wgetch (stdscr);
828 if (key == ERR)
829 break;
830 else if (key == KEY_RESIZE)
831 need_resize = 1;
832 }
834 if (need_resize)
835 return (on_resize (ping));
836 else
837 return (0);
838 } /* }}} int check_resize */
840 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
841 {
842 pingobj_iter_t *iter;
843 int width = 0;
844 int height = 0;
845 int main_win_height;
847 initscr ();
848 cbreak ();
849 noecho ();
850 nodelay (stdscr, TRUE);
852 getmaxyx (stdscr, height, width);
853 if ((height < 1) || (width < 1))
854 return (EINVAL);
856 if (has_colors () == TRUE)
857 {
858 start_color ();
859 init_pair (OPING_GREEN, COLOR_GREEN, /* default = */ 0);
860 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
861 init_pair (OPING_RED, COLOR_RED, /* default = */ 0);
862 init_pair (OPING_GREEN_HIST, COLOR_GREEN, COLOR_BLACK);
863 init_pair (OPING_YELLOW_HIST, COLOR_YELLOW, COLOR_GREEN);
864 init_pair (OPING_RED_HIST, COLOR_RED, COLOR_YELLOW);
865 }
867 main_win_height = height - (5 * host_num);
868 main_win = newwin (/* height = */ main_win_height,
869 /* width = */ width,
870 /* y = */ 0, /* x = */ 0);
871 /* Allow scrolling */
872 scrollok (main_win, TRUE);
873 /* wsetscrreg (main_win, 0, main_win_height - 1); */
874 /* Allow hardware accelerated scrolling. */
875 idlok (main_win, TRUE);
876 wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
877 wrefresh (main_win);
879 for (iter = ping_iterator_get (ping);
880 iter != NULL;
881 iter = ping_iterator_next (iter))
882 {
883 ping_context_t *context;
885 context = ping_iterator_get_context (iter);
886 if (context == NULL)
887 continue;
889 if (context->window != NULL)
890 {
891 delwin (context->window);
892 context->window = NULL;
893 }
894 context->window = newwin (/* height = */ 5,
895 /* width = */ width,
896 /* y = */ main_win_height + (5 * context->index),
897 /* x = */ 0);
898 }
901 /* Don't know what good this does exactly, but without this code
902 * "check_resize" will be called right after startup and *somehow*
903 * this leads to display errors. If we purge all initial characters
904 * here, the problem goes away. "wgetch" is non-blocking due to
905 * "nodelay" (see above). */
906 while (wgetch (stdscr) != ERR)
907 {
908 /* eat up characters */;
909 }
911 return (0);
912 } /* }}} int pre_loop_hook */
914 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
915 {
916 return (check_resize (ping));
917 } /* }}} int pre_sleep_hook */
919 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
920 {
921 return (check_resize (ping));
922 } /* }}} int pre_sleep_hook */
923 #else /* if !USE_NCURSES */
924 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
925 {
926 pingobj_iter_t *iter;
928 for (iter = ping_iterator_get (ping);
929 iter != NULL;
930 iter = ping_iterator_next (iter))
931 {
932 ping_context_t *ctx;
933 size_t buffer_size;
935 ctx = ping_iterator_get_context (iter);
936 if (ctx == NULL)
937 continue;
939 buffer_size = 0;
940 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
942 printf ("PING %s (%s) %zu bytes of data.\n",
943 ctx->host, ctx->addr, buffer_size);
944 }
946 return (0);
947 } /* }}} int pre_loop_hook */
949 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
950 {
951 fflush (stdout);
953 return (0);
954 } /* }}} int pre_sleep_hook */
956 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
957 {
958 return (0);
959 } /* }}} int post_sleep_hook */
960 #endif
962 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
963 __attribute__((unused)) int index)
964 {
965 double latency;
966 unsigned int sequence;
967 int recv_ttl;
968 uint8_t recv_qos;
969 char recv_qos_str[16];
970 size_t buffer_len;
971 size_t data_len;
972 ping_context_t *context;
974 latency = -1.0;
975 buffer_len = sizeof (latency);
976 ping_iterator_get_info (iter, PING_INFO_LATENCY,
977 &latency, &buffer_len);
979 sequence = 0;
980 buffer_len = sizeof (sequence);
981 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
982 &sequence, &buffer_len);
984 recv_ttl = -1;
985 buffer_len = sizeof (recv_ttl);
986 ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
987 &recv_ttl, &buffer_len);
989 recv_qos = 0;
990 buffer_len = sizeof (recv_qos);
991 ping_iterator_get_info (iter, PING_INFO_RECV_QOS,
992 &recv_qos, &buffer_len);
994 data_len = 0;
995 ping_iterator_get_info (iter, PING_INFO_DATA,
996 NULL, &data_len);
998 context = (ping_context_t *) ping_iterator_get_context (iter);
1000 #if USE_NCURSES
1001 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
1002 #else
1003 # define HOST_PRINTF(...) printf(__VA_ARGS__)
1004 #endif
1006 context->req_sent++;
1007 if (latency > 0.0)
1008 {
1009 context->req_rcvd++;
1010 context->latency_total += latency;
1011 context->latency_total_square += (latency * latency);
1013 if ((context->latency_max < 0.0) || (context->latency_max < latency))
1014 context->latency_max = latency;
1015 if ((context->latency_min < 0.0) || (context->latency_min > latency))
1016 context->latency_min = latency;
1018 #if USE_NCURSES
1019 if (has_colors () == TRUE)
1020 {
1021 int color = OPING_GREEN;
1022 double average = context_get_average (context);
1023 double stddev = context_get_stddev (context);
1025 if ((latency < (average - (2 * stddev)))
1026 || (latency > (average + (2 * stddev))))
1027 color = OPING_RED;
1028 else if ((latency < (average - stddev))
1029 || (latency > (average + stddev)))
1030 color = OPING_YELLOW;
1032 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
1033 data_len, context->host, context->addr,
1034 sequence, recv_ttl,
1035 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1036 if ((recv_qos != 0) || (opt_send_qos != 0))
1037 {
1038 HOST_PRINTF ("qos=%s ",
1039 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1040 }
1041 HOST_PRINTF ("time=");
1042 wattron (main_win, COLOR_PAIR(color));
1043 HOST_PRINTF ("%.2f", latency);
1044 wattroff (main_win, COLOR_PAIR(color));
1045 HOST_PRINTF (" ms\n");
1046 }
1047 else
1048 {
1049 #endif
1050 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
1051 data_len,
1052 context->host, context->addr,
1053 sequence, recv_ttl);
1054 if ((recv_qos != 0) || (opt_send_qos != 0))
1055 {
1056 HOST_PRINTF ("qos=%s ",
1057 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
1058 }
1059 HOST_PRINTF ("time=%.2f ms\n", latency);
1060 #if USE_NCURSES
1061 }
1062 #endif
1063 }
1064 else
1065 {
1066 #if USE_NCURSES
1067 if (has_colors () == TRUE)
1068 {
1069 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
1070 context->host, context->addr,
1071 sequence);
1072 wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
1073 HOST_PRINTF ("timeout");
1074 wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
1075 HOST_PRINTF ("\n");
1076 }
1077 else
1078 {
1079 #endif
1080 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
1081 context->host, context->addr,
1082 sequence);
1083 #if USE_NCURSES
1084 }
1085 #endif
1086 }
1088 #if USE_NCURSES
1089 update_stats_from_context (context, iter);
1090 wrefresh (main_win);
1091 #endif
1092 } /* }}} void update_host_hook */
1094 static int post_loop_hook (pingobj_t *ping) /* {{{ */
1095 {
1096 pingobj_iter_t *iter;
1098 #if USE_NCURSES
1099 endwin ();
1100 #endif
1102 for (iter = ping_iterator_get (ping);
1103 iter != NULL;
1104 iter = ping_iterator_next (iter))
1105 {
1106 ping_context_t *context;
1108 context = ping_iterator_get_context (iter);
1110 printf ("\n--- %s ping statistics ---\n"
1111 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
1112 context->host, context->req_sent, context->req_rcvd,
1113 context_get_packet_loss (context),
1114 context->latency_total);
1116 if (context->req_rcvd != 0)
1117 {
1118 double average;
1119 double deviation;
1121 average = context_get_average (context);
1122 deviation = context_get_stddev (context);
1124 printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
1125 context->latency_min,
1126 average,
1127 context->latency_max,
1128 deviation);
1129 }
1131 ping_iterator_set_context (iter, NULL);
1132 context_destroy (context);
1133 }
1135 return (0);
1136 } /* }}} int post_loop_hook */
1138 int main (int argc, char **argv) /* {{{ */
1139 {
1140 pingobj_t *ping;
1141 pingobj_iter_t *iter;
1143 struct sigaction sigint_action;
1145 struct timeval tv_begin;
1146 struct timeval tv_end;
1147 struct timespec ts_wait;
1148 struct timespec ts_int;
1150 int optind;
1151 int i;
1152 int status;
1153 #if _POSIX_SAVED_IDS
1154 uid_t saved_set_uid;
1156 /* Save the old effective user id */
1157 saved_set_uid = geteuid ();
1158 /* Set the effective user ID to the real user ID without changing the
1159 * saved set-user ID */
1160 status = seteuid (getuid ());
1161 if (status != 0)
1162 {
1163 fprintf (stderr, "Temporarily dropping privileges "
1164 "failed: %s\n", strerror (errno));
1165 exit (EXIT_FAILURE);
1166 }
1167 #endif
1169 setlocale(LC_ALL, "");
1170 optind = read_options (argc, argv);
1172 #if !_POSIX_SAVED_IDS
1173 /* Cannot temporarily drop privileges -> reject every file but "-". */
1174 if ((opt_filename != NULL)
1175 && (strcmp ("-", opt_filename) != 0)
1176 && (getuid () != geteuid ()))
1177 {
1178 fprintf (stderr, "Your real and effective user IDs don't "
1179 "match. Reading from a file (option '-f')\n"
1180 "is therefore too risky. You can still read "
1181 "from STDIN using '-f -' if you like.\n"
1182 "Sorry.\n");
1183 exit (EXIT_FAILURE);
1184 }
1185 #endif
1187 if ((optind >= argc) && (opt_filename == NULL)) {
1188 usage_exit (argv[0], 1);
1189 }
1191 if ((ping = ping_construct ()) == NULL)
1192 {
1193 fprintf (stderr, "ping_construct failed\n");
1194 return (1);
1195 }
1197 if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
1198 {
1199 fprintf (stderr, "Setting TTL to %i failed: %s\n",
1200 opt_send_ttl, ping_get_error (ping));
1201 }
1203 if (ping_setopt (ping, PING_OPT_QOS, &opt_send_qos) != 0)
1204 {
1205 fprintf (stderr, "Setting TOS to %i failed: %s\n",
1206 opt_send_qos, ping_get_error (ping));
1207 }
1209 {
1210 double temp_sec;
1211 double temp_nsec;
1213 temp_nsec = modf (opt_interval, &temp_sec);
1214 ts_int.tv_sec = (time_t) temp_sec;
1215 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
1217 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
1218 }
1220 if (opt_addrfamily != PING_DEF_AF)
1221 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
1223 if (opt_srcaddr != NULL)
1224 {
1225 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
1226 {
1227 fprintf (stderr, "Setting source address failed: %s\n",
1228 ping_get_error (ping));
1229 }
1230 }
1232 if (opt_device != NULL)
1233 {
1234 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
1235 {
1236 fprintf (stderr, "Setting device failed: %s\n",
1237 ping_get_error (ping));
1238 }
1239 }
1241 if (opt_filename != NULL)
1242 {
1243 FILE *infile;
1244 char line[256];
1245 char host[256];
1247 if (strcmp (opt_filename, "-") == 0)
1248 /* Open STDIN */
1249 infile = fdopen(0, "r");
1250 else
1251 infile = fopen(opt_filename, "r");
1253 if (infile == NULL)
1254 {
1255 fprintf (stderr, "Opening %s failed: %s\n",
1256 (strcmp (opt_filename, "-") == 0)
1257 ? "STDIN" : opt_filename,
1258 strerror(errno));
1259 return (1);
1260 }
1262 #if _POSIX_SAVED_IDS
1263 /* Regain privileges */
1264 status = seteuid (saved_set_uid);
1265 if (status != 0)
1266 {
1267 fprintf (stderr, "Temporarily re-gaining privileges "
1268 "failed: %s\n", strerror (errno));
1269 exit (EXIT_FAILURE);
1270 }
1271 #endif
1273 while (fgets(line, sizeof(line), infile))
1274 {
1275 /* Strip whitespace */
1276 if (sscanf(line, "%s", host) != 1)
1277 continue;
1279 if ((host[0] == 0) || (host[0] == '#'))
1280 continue;
1282 if (ping_host_add(ping, host) < 0)
1283 {
1284 const char *errmsg = ping_get_error (ping);
1286 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
1287 continue;
1288 }
1289 else
1290 {
1291 host_num++;
1292 }
1293 }
1295 #if _POSIX_SAVED_IDS
1296 /* Drop privileges */
1297 status = seteuid (getuid ());
1298 if (status != 0)
1299 {
1300 fprintf (stderr, "Temporarily dropping privileges "
1301 "failed: %s\n", strerror (errno));
1302 exit (EXIT_FAILURE);
1303 }
1304 #endif
1306 fclose(infile);
1307 }
1309 #if _POSIX_SAVED_IDS
1310 /* Regain privileges */
1311 status = seteuid (saved_set_uid);
1312 if (status != 0)
1313 {
1314 fprintf (stderr, "Temporarily re-gaining privileges "
1315 "failed: %s\n", strerror (errno));
1316 exit (EXIT_FAILURE);
1317 }
1318 #endif
1320 for (i = optind; i < argc; i++)
1321 {
1322 if (ping_host_add (ping, argv[i]) < 0)
1323 {
1324 const char *errmsg = ping_get_error (ping);
1326 fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
1327 continue;
1328 }
1329 else
1330 {
1331 host_num++;
1332 }
1333 }
1335 /* Permanently drop root privileges if we're setuid-root. */
1336 status = setuid (getuid ());
1337 if (status != 0)
1338 {
1339 fprintf (stderr, "Dropping privileges failed: %s\n",
1340 strerror (errno));
1341 exit (EXIT_FAILURE);
1342 }
1344 #if _POSIX_SAVED_IDS
1345 saved_set_uid = (uid_t) -1;
1346 #endif
1348 ping_initialize_contexts (ping);
1350 if (i == 0)
1351 return (1);
1353 memset (&sigint_action, '\0', sizeof (sigint_action));
1354 sigint_action.sa_handler = sigint_handler;
1355 if (sigaction (SIGINT, &sigint_action, NULL) < 0)
1356 {
1357 perror ("sigaction");
1358 return (1);
1359 }
1361 pre_loop_hook (ping);
1363 while (opt_count != 0)
1364 {
1365 int index;
1366 int status;
1368 if (gettimeofday (&tv_begin, NULL) < 0)
1369 {
1370 perror ("gettimeofday");
1371 return (1);
1372 }
1374 if (ping_send (ping) < 0)
1375 {
1376 fprintf (stderr, "ping_send failed: %s\n",
1377 ping_get_error (ping));
1378 return (1);
1379 }
1381 index = 0;
1382 for (iter = ping_iterator_get (ping);
1383 iter != NULL;
1384 iter = ping_iterator_next (iter))
1385 {
1386 update_host_hook (iter, index);
1387 index++;
1388 }
1390 pre_sleep_hook (ping);
1392 /* Don't sleep in the last iteration */
1393 if (opt_count == 1)
1394 break;
1396 if (gettimeofday (&tv_end, NULL) < 0)
1397 {
1398 perror ("gettimeofday");
1399 return (1);
1400 }
1402 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1404 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1405 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1406 {
1407 if (errno != EINTR)
1408 {
1409 perror ("nanosleep");
1410 break;
1411 }
1412 else if (opt_count == 0)
1413 {
1414 /* sigint */
1415 break;
1416 }
1417 }
1419 post_sleep_hook (ping);
1421 if (opt_count > 0)
1422 opt_count--;
1423 } /* while (opt_count != 0) */
1425 post_loop_hook (ping);
1427 ping_destroy (ping);
1429 return (0);
1430 } /* }}} int main */
1432 /* vim: set fdm=marker : */