1 /**
2 * Object oriented C module to send ICMP and ICMPv6 `echo's.
3 * Copyright (C) 2006-2010 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;
125 static int host_num = 0;
127 #if USE_NCURSES
128 static WINDOW *main_win = NULL;
129 #endif
131 static void sigint_handler (int signal) /* {{{ */
132 {
133 /* Make compiler happy */
134 signal = 0;
135 /* Exit the loop */
136 opt_count = 0;
137 } /* }}} void sigint_handler */
139 static ping_context_t *context_create (void) /* {{{ */
140 {
141 ping_context_t *ret;
143 if ((ret = malloc (sizeof (ping_context_t))) == NULL)
144 return (NULL);
146 memset (ret, '\0', sizeof (ping_context_t));
148 ret->latency_min = -1.0;
149 ret->latency_max = -1.0;
150 ret->latency_total = 0.0;
151 ret->latency_total_square = 0.0;
153 #if USE_NCURSES
154 ret->window = NULL;
155 #endif
157 return (ret);
158 } /* }}} ping_context_t *context_create */
160 static void context_destroy (ping_context_t *context) /* {{{ */
161 {
162 if (context == NULL)
163 return;
165 #if USE_NCURSES
166 if (context->window != NULL)
167 {
168 delwin (context->window);
169 context->window = NULL;
170 }
171 #endif
173 free (context);
174 } /* }}} void context_destroy */
176 static double context_get_average (ping_context_t *ctx) /* {{{ */
177 {
178 double num_total;
180 if (ctx == NULL)
181 return (-1.0);
183 if (ctx->req_rcvd < 1)
184 return (-0.0);
186 num_total = (double) ctx->req_rcvd;
187 return (ctx->latency_total / num_total);
188 } /* }}} double context_get_average */
190 static double context_get_stddev (ping_context_t *ctx) /* {{{ */
191 {
192 double num_total;
194 if (ctx == NULL)
195 return (-1.0);
197 if (ctx->req_rcvd < 1)
198 return (-0.0);
199 else if (ctx->req_rcvd < 2)
200 return (0.0);
202 num_total = (double) ctx->req_rcvd;
203 return (sqrt (((num_total * ctx->latency_total_square)
204 - (ctx->latency_total * ctx->latency_total))
205 / (num_total * (num_total - 1.0))));
206 } /* }}} double context_get_stddev */
208 static double context_get_packet_loss (const ping_context_t *ctx) /* {{{ */
209 {
210 if (ctx == NULL)
211 return (-1.0);
213 if (ctx->req_sent < 1)
214 return (0.0);
216 return (100.0 * (ctx->req_sent - ctx->req_rcvd)
217 / ((double) ctx->req_sent));
218 } /* }}} double context_get_packet_loss */
220 static int ping_initialize_contexts (pingobj_t *ping) /* {{{ */
221 {
222 pingobj_iter_t *iter;
223 int index;
225 if (ping == NULL)
226 return (EINVAL);
228 index = 0;
229 for (iter = ping_iterator_get (ping);
230 iter != NULL;
231 iter = ping_iterator_next (iter))
232 {
233 ping_context_t *context;
234 size_t buffer_size;
236 context = context_create ();
237 context->index = index;
239 buffer_size = sizeof (context->host);
240 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
242 buffer_size = sizeof (context->addr);
243 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
245 ping_iterator_set_context (iter, (void *) context);
247 index++;
248 }
250 return (0);
251 } /* }}} int ping_initialize_contexts */
253 static void usage_exit (const char *name, int status) /* {{{ */
254 {
255 fprintf (stderr, "Usage: %s [OPTIONS] "
256 "-f filename | host [host [host ...]]\n"
258 "\nAvailable options:\n"
259 " -4|-6 force the use of IPv4 or IPv6\n"
260 " -c count number of ICMP packets to send\n"
261 " -i interval interval with which to send ICMP packets\n"
262 " -t ttl time to live for each ICMP packet\n"
263 " -Q qos Quality of Service (QoS) of outgoing packets\n"
264 " Use \"-Q help\" for a list of valid options.\n"
265 " -I srcaddr source address\n"
266 " -D device outgoing interface name\n"
267 " -f filename filename to read hosts from\n"
269 "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
270 "by Florian octo Forster <octo@verplant.org>\n"
271 "for contributions see `AUTHORS'\n",
272 name);
273 exit (status);
274 } /* }}} void usage_exit */
276 static void usage_qos_exit (const char *arg, int status) /* {{{ */
277 {
278 if (arg != 0)
279 fprintf (stderr, "Invalid QoS argument: \"%s\"\n\n", arg);
281 fprintf (stderr, "Valid QoS arguments (option \"-Q\") are:\n"
282 "\n"
283 " Differentiated Services (IPv4 and IPv6, RFC 2474)\n"
284 "\n"
285 " be Best Effort (BE, default PHB).\n"
286 " ef Expedited Forwarding (EF) PHB group (RFC 3246).\n"
287 " (low delay, low loss, low jitter)\n"
288 " va Voice Admit (VA) DSCP (RFC 5865).\n"
289 " (capacity-admitted traffic)\n"
290 " af[1-4][1-3] Assured Forwarding (AF) PHB group (RFC 2597).\n"
291 " For example: \"af12\" (class 1, precedence 2)\n"
292 " cs[0-7] Class Selector (CS) PHB group (RFC 2474).\n"
293 " For example: \"cs1\" (priority traffic)\n"
294 "\n"
295 " Type of Service (IPv4, RFC 1349, obsolete)\n"
296 "\n"
297 " lowdelay (%#04x) minimize delay\n"
298 " throughput (%#04x) maximize throughput\n"
299 " reliability (%#04x) maximize reliability\n"
300 " mincost (%#04x) minimize monetary cost\n"
301 "\n"
302 " Specify manually\n"
303 "\n"
304 " 0x00 - 0xff Hexadecimal numeric specification.\n"
305 " 0 - 255 Decimal numeric specification.\n"
306 "\n",
307 (unsigned int) IPTOS_LOWDELAY,
308 (unsigned int) IPTOS_THROUGHPUT,
309 (unsigned int) IPTOS_RELIABILITY,
310 (unsigned int) IPTOS_MINCOST);
312 exit (status);
313 } /* }}} void usage_qos_exit */
315 static int set_opt_send_qos (const char *opt) /* {{{ */
316 {
317 if (opt == NULL)
318 return (EINVAL);
320 if (strcasecmp ("help", opt) == 0)
321 usage_qos_exit (/* arg = */ NULL, /* status = */ EXIT_SUCCESS);
322 /* DiffServ (RFC 2474): */
323 /* - Best effort (BE) */
324 else if (strcasecmp ("be", opt) == 0)
325 opt_send_qos = 0;
326 /* - Expedited Forwarding (EF, RFC 3246) */
327 else if (strcasecmp ("ef", opt) == 0)
328 opt_send_qos = 0xB8; /* == 0x2E << 2 */
329 /* - Voice Admit (VA, RFC 5865) */
330 else if (strcasecmp ("va", opt) == 0)
331 opt_send_qos = 0xB0; /* == 0x2D << 2 */
332 /* - Assured Forwarding (AF, RFC 2597) */
333 else if ((strncasecmp ("af", opt, strlen ("af")) == 0)
334 && (strlen (opt) == 4))
335 {
336 uint8_t dscp;
337 uint8_t class;
338 uint8_t prec;
340 /* There are four classes, AF1x, AF2x, AF3x, and AF4x. */
341 if (opt[2] == '1')
342 class = 1;
343 else if (opt[2] == '2')
344 class = 2;
345 else if (opt[2] == '3')
346 class = 3;
347 else if (opt[2] == '4')
348 class = 4;
349 else
350 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
352 /* In each class, there are three precedences, AFx1, AFx2, and AFx3 */
353 if (opt[3] == '1')
354 prec = 1;
355 else if (opt[3] == '2')
356 prec = 2;
357 else if (opt[3] == '3')
358 prec = 3;
359 else
360 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
362 dscp = (8 * class) + (2 * prec);
363 /* The lower two bits are used for Explicit Congestion Notification (ECN) */
364 opt_send_qos = dscp << 2;
365 }
366 /* - Class Selector (CS) */
367 else if ((strncasecmp ("cs", opt, strlen ("cs")) == 0)
368 && (strlen (opt) == 3))
369 {
370 uint8_t class;
372 if ((opt[2] < '0') || (opt[2] > '7'))
373 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
375 /* Not exactly legal by the C standard, but I don't know of any
376 * system not supporting this hack. */
377 class = ((uint8_t) opt[2]) - ((uint8_t) '0');
378 opt_send_qos = class << 5;
379 }
380 /* Type of Service (RFC 1349) */
381 else if (strcasecmp ("lowdelay", opt) == 0)
382 opt_send_qos = IPTOS_LOWDELAY;
383 else if (strcasecmp ("throughput", opt) == 0)
384 opt_send_qos = IPTOS_THROUGHPUT;
385 else if (strcasecmp ("reliability", opt) == 0)
386 opt_send_qos = IPTOS_RELIABILITY;
387 else if (strcasecmp ("mincost", opt) == 0)
388 opt_send_qos = IPTOS_MINCOST;
389 /* Numeric value */
390 else
391 {
392 unsigned long value;
393 char *endptr;
395 errno = 0;
396 endptr = NULL;
397 value = strtoul (opt, &endptr, /* base = */ 0);
398 if ((errno != 0) || (endptr == opt)
399 || (endptr == NULL) || (*endptr != 0)
400 || (value > 0xff))
401 usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
403 opt_send_qos = (uint8_t) value;
404 }
406 return (0);
407 } /* }}} int set_opt_send_qos */
409 static char *format_qos (uint8_t qos, char *buffer, size_t buffer_size) /* {{{ */
410 {
411 uint8_t dscp;
412 uint8_t ecn;
413 char *dscp_str;
414 char *ecn_str;
416 dscp = qos >> 2;
417 ecn = qos & 0x03;
419 switch (dscp)
420 {
421 case 0x00: dscp_str = "be"; break;
422 case 0x2e: dscp_str = "ef"; break;
423 case 0x2d: dscp_str = "va"; break;
424 case 0x0a: dscp_str = "af11"; break;
425 case 0x0c: dscp_str = "af12"; break;
426 case 0x0e: dscp_str = "af13"; break;
427 case 0x12: dscp_str = "af21"; break;
428 case 0x14: dscp_str = "af22"; break;
429 case 0x16: dscp_str = "af23"; break;
430 case 0x1a: dscp_str = "af31"; break;
431 case 0x1c: dscp_str = "af32"; break;
432 case 0x1e: dscp_str = "af33"; break;
433 case 0x22: dscp_str = "af41"; break;
434 case 0x24: dscp_str = "af42"; break;
435 case 0x26: dscp_str = "af43"; break;
436 case 0x08: dscp_str = "cs1"; break;
437 case 0x10: dscp_str = "cs2"; break;
438 case 0x18: dscp_str = "cs3"; break;
439 case 0x20: dscp_str = "cs4"; break;
440 case 0x28: dscp_str = "cs5"; break;
441 case 0x30: dscp_str = "cs6"; break;
442 case 0x38: dscp_str = "cs7"; break;
443 default: dscp_str = NULL;
444 }
446 switch (ecn)
447 {
448 case 0x01: ecn_str = ",ecn(1)"; break;
449 case 0x02: ecn_str = ",ecn(0)"; break;
450 case 0x03: ecn_str = ",ce"; break;
451 default: ecn_str = "";
452 }
454 if (dscp_str == NULL)
455 snprintf (buffer, buffer_size, "0x%02x%s", dscp, ecn_str);
456 else
457 snprintf (buffer, buffer_size, "%s%s", dscp_str, ecn_str);
458 buffer[buffer_size - 1] = 0;
460 return (buffer);
461 } /* }}} char *format_qos */
463 static int read_options (int argc, char **argv) /* {{{ */
464 {
465 int optchar;
467 while (1)
468 {
469 optchar = getopt (argc, argv, "46c:hi:I:t:Q:f:D:");
471 if (optchar == -1)
472 break;
474 switch (optchar)
475 {
476 case '4':
477 case '6':
478 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
479 break;
481 case 'c':
482 {
483 int new_count;
484 new_count = atoi (optarg);
485 if (new_count > 0)
486 opt_count = new_count;
487 else
488 fprintf(stderr, "Ignoring invalid count: %s\n",
489 optarg);
490 }
491 break;
493 case 'f':
494 {
495 if (opt_filename != NULL)
496 free (opt_filename);
497 opt_filename = strdup (optarg);
498 }
499 break;
501 case 'i':
502 {
503 double new_interval;
504 new_interval = atof (optarg);
505 if (new_interval < 0.001)
506 fprintf (stderr, "Ignoring invalid interval: %s\n",
507 optarg);
508 else
509 opt_interval = new_interval;
510 }
511 break;
512 case 'I':
513 {
514 if (opt_srcaddr != NULL)
515 free (opt_srcaddr);
516 opt_srcaddr = strdup (optarg);
517 }
518 break;
520 case 'D':
521 opt_device = optarg;
522 break;
524 case 't':
525 {
526 int new_send_ttl;
527 new_send_ttl = atoi (optarg);
528 if ((new_send_ttl > 0) && (new_send_ttl < 256))
529 opt_send_ttl = new_send_ttl;
530 else
531 fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
532 optarg);
533 break;
534 }
536 case 'Q':
537 set_opt_send_qos (optarg);
538 break;
540 case 'h':
541 usage_exit (argv[0], 0);
542 break;
543 default:
544 usage_exit (argv[0], 1);
545 }
546 }
548 return (optind);
549 } /* }}} read_options */
551 static void time_normalize (struct timespec *ts) /* {{{ */
552 {
553 while (ts->tv_nsec < 0)
554 {
555 if (ts->tv_sec == 0)
556 {
557 ts->tv_nsec = 0;
558 return;
559 }
561 ts->tv_sec -= 1;
562 ts->tv_nsec += 1000000000;
563 }
565 while (ts->tv_nsec >= 1000000000)
566 {
567 ts->tv_sec += 1;
568 ts->tv_nsec -= 1000000000;
569 }
570 } /* }}} void time_normalize */
572 static void time_calc (struct timespec *ts_dest, /* {{{ */
573 const struct timespec *ts_int,
574 const struct timeval *tv_begin,
575 const struct timeval *tv_end)
576 {
577 ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
578 ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
579 time_normalize (ts_dest);
581 /* Assure that `(begin + interval) > end'.
582 * This may seem overly complicated, but `tv_sec' is of type `time_t'
583 * which may be `unsigned. *sigh* */
584 if ((tv_end->tv_sec > ts_dest->tv_sec)
585 || ((tv_end->tv_sec == ts_dest->tv_sec)
586 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
587 {
588 ts_dest->tv_sec = 0;
589 ts_dest->tv_nsec = 0;
590 return;
591 }
593 ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
594 ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
595 time_normalize (ts_dest);
596 } /* }}} void time_calc */
598 #if USE_NCURSES
599 static int update_stats_from_context (ping_context_t *ctx) /* {{{ */
600 {
601 if ((ctx == NULL) || (ctx->window == NULL))
602 return (EINVAL);
604 werase (ctx->window);
606 box (ctx->window, 0, 0);
607 wattron (ctx->window, A_BOLD);
608 mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
609 " %s ", ctx->host);
610 wattroff (ctx->window, A_BOLD);
611 wprintw (ctx->window, "ping statistics ");
612 mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
613 "%i packets transmitted, %i received, %.2f%% packet "
614 "loss, time %.1fms",
615 ctx->req_sent, ctx->req_rcvd,
616 context_get_packet_loss (ctx),
617 ctx->latency_total);
618 if (ctx->req_rcvd != 0)
619 {
620 double average;
621 double deviation;
623 average = context_get_average (ctx);
624 deviation = context_get_stddev (ctx);
626 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
627 "rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms",
628 ctx->latency_min,
629 average,
630 ctx->latency_max,
631 deviation);
632 }
634 wrefresh (ctx->window);
636 return (0);
637 } /* }}} int update_stats_from_context */
639 static int on_resize (pingobj_t *ping) /* {{{ */
640 {
641 pingobj_iter_t *iter;
642 int width = 0;
643 int height = 0;
644 int main_win_height;
646 getmaxyx (stdscr, height, width);
647 if ((height < 1) || (width < 1))
648 return (EINVAL);
650 main_win_height = height - (4 * host_num);
651 wresize (main_win, main_win_height, /* width = */ width);
652 /* Allow scrolling */
653 scrollok (main_win, TRUE);
654 /* wsetscrreg (main_win, 0, main_win_height - 1); */
655 /* Allow hardware accelerated scrolling. */
656 idlok (main_win, TRUE);
657 wrefresh (main_win);
659 for (iter = ping_iterator_get (ping);
660 iter != NULL;
661 iter = ping_iterator_next (iter))
662 {
663 ping_context_t *context;
665 context = ping_iterator_get_context (iter);
666 if (context == NULL)
667 continue;
669 if (context->window != NULL)
670 {
671 delwin (context->window);
672 context->window = NULL;
673 }
674 context->window = newwin (/* height = */ 4,
675 /* width = */ 0,
676 /* y = */ main_win_height + (4 * context->index),
677 /* x = */ 0);
678 }
680 return (0);
681 } /* }}} */
683 static int check_resize (pingobj_t *ping) /* {{{ */
684 {
685 int need_resize = 0;
687 while (42)
688 {
689 int key = wgetch (stdscr);
690 if (key == ERR)
691 break;
692 else if (key == KEY_RESIZE)
693 need_resize = 1;
694 }
696 if (need_resize)
697 return (on_resize (ping));
698 else
699 return (0);
700 } /* }}} int check_resize */
702 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
703 {
704 pingobj_iter_t *iter;
705 int width = 0;
706 int height = 0;
707 int main_win_height;
709 initscr ();
710 cbreak ();
711 noecho ();
712 nodelay (stdscr, TRUE);
714 getmaxyx (stdscr, height, width);
715 if ((height < 1) || (width < 1))
716 return (EINVAL);
718 if (has_colors () == TRUE)
719 {
720 start_color ();
721 init_pair (OPING_GREEN, COLOR_GREEN, /* default = */ 0);
722 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
723 init_pair (OPING_RED, COLOR_RED, /* default = */ 0);
724 }
726 main_win_height = height - (4 * host_num);
727 main_win = newwin (/* height = */ main_win_height,
728 /* width = */ 0,
729 /* y = */ 0, /* x = */ 0);
730 /* Allow scrolling */
731 scrollok (main_win, TRUE);
732 /* wsetscrreg (main_win, 0, main_win_height - 1); */
733 /* Allow hardware accelerated scrolling. */
734 idlok (main_win, TRUE);
735 wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
736 wrefresh (main_win);
738 for (iter = ping_iterator_get (ping);
739 iter != NULL;
740 iter = ping_iterator_next (iter))
741 {
742 ping_context_t *context;
744 context = ping_iterator_get_context (iter);
745 if (context == NULL)
746 continue;
748 if (context->window != NULL)
749 {
750 delwin (context->window);
751 context->window = NULL;
752 }
753 context->window = newwin (/* height = */ 4,
754 /* width = */ 0,
755 /* y = */ main_win_height + (4 * context->index),
756 /* x = */ 0);
757 }
760 /* Don't know what good this does exactly, but without this code
761 * "check_resize" will be called right after startup and *somehow*
762 * this leads to display errors. If we purge all initial characters
763 * here, the problem goes away. "wgetch" is non-blocking due to
764 * "nodelay" (see above). */
765 while (wgetch (stdscr) != ERR)
766 {
767 /* eat up characters */;
768 }
770 return (0);
771 } /* }}} int pre_loop_hook */
773 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
774 {
775 return (check_resize (ping));
776 } /* }}} int pre_sleep_hook */
778 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
779 {
780 return (check_resize (ping));
781 } /* }}} int pre_sleep_hook */
782 #else /* if !USE_NCURSES */
783 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
784 {
785 pingobj_iter_t *iter;
787 for (iter = ping_iterator_get (ping);
788 iter != NULL;
789 iter = ping_iterator_next (iter))
790 {
791 ping_context_t *ctx;
792 size_t buffer_size;
794 ctx = ping_iterator_get_context (iter);
795 if (ctx == NULL)
796 continue;
798 buffer_size = 0;
799 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
801 printf ("PING %s (%s) %zu bytes of data.\n",
802 ctx->host, ctx->addr, buffer_size);
803 }
805 return (0);
806 } /* }}} int pre_loop_hook */
808 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
809 {
810 fflush (stdout);
812 return (0);
813 } /* }}} int pre_sleep_hook */
815 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
816 {
817 return (0);
818 } /* }}} int post_sleep_hook */
819 #endif
821 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
822 __attribute__((unused)) int index)
823 {
824 double latency;
825 unsigned int sequence;
826 int recv_ttl;
827 uint8_t recv_qos;
828 char recv_qos_str[16];
829 size_t buffer_len;
830 size_t data_len;
831 ping_context_t *context;
833 latency = -1.0;
834 buffer_len = sizeof (latency);
835 ping_iterator_get_info (iter, PING_INFO_LATENCY,
836 &latency, &buffer_len);
838 sequence = 0;
839 buffer_len = sizeof (sequence);
840 ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
841 &sequence, &buffer_len);
843 recv_ttl = -1;
844 buffer_len = sizeof (recv_ttl);
845 ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
846 &recv_ttl, &buffer_len);
848 recv_qos = 0;
849 buffer_len = sizeof (recv_qos);
850 ping_iterator_get_info (iter, PING_INFO_RECV_QOS,
851 &recv_qos, &buffer_len);
853 data_len = 0;
854 ping_iterator_get_info (iter, PING_INFO_DATA,
855 NULL, &data_len);
857 context = (ping_context_t *) ping_iterator_get_context (iter);
859 #if USE_NCURSES
860 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
861 #else
862 # define HOST_PRINTF(...) printf(__VA_ARGS__)
863 #endif
865 context->req_sent++;
866 if (latency > 0.0)
867 {
868 context->req_rcvd++;
869 context->latency_total += latency;
870 context->latency_total_square += (latency * latency);
872 if ((context->latency_max < 0.0) || (context->latency_max < latency))
873 context->latency_max = latency;
874 if ((context->latency_min < 0.0) || (context->latency_min > latency))
875 context->latency_min = latency;
877 #if USE_NCURSES
878 if (has_colors () == TRUE)
879 {
880 int color = OPING_GREEN;
881 double average = context_get_average (context);
882 double stddev = context_get_stddev (context);
884 if ((latency < (average - (2 * stddev)))
885 || (latency > (average + (2 * stddev))))
886 color = OPING_RED;
887 else if ((latency < (average - stddev))
888 || (latency > (average + stddev)))
889 color = OPING_YELLOW;
891 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
892 data_len, context->host, context->addr,
893 sequence, recv_ttl,
894 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
895 if ((recv_qos != 0) || (opt_send_qos != 0))
896 {
897 HOST_PRINTF ("qos=%s ",
898 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
899 }
900 HOST_PRINTF ("time=");
901 wattron (main_win, COLOR_PAIR(color));
902 HOST_PRINTF ("%.2f", latency);
903 wattroff (main_win, COLOR_PAIR(color));
904 HOST_PRINTF (" ms\n");
905 }
906 else
907 {
908 #endif
909 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
910 data_len,
911 context->host, context->addr,
912 sequence, recv_ttl);
913 if ((recv_qos != 0) || (opt_send_qos != 0))
914 {
915 HOST_PRINTF ("qos=%s ",
916 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
917 }
918 HOST_PRINTF ("time=%.2f ms\n", latency);
919 #if USE_NCURSES
920 }
921 #endif
922 }
923 else
924 {
925 #if USE_NCURSES
926 if (has_colors () == TRUE)
927 {
928 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
929 context->host, context->addr,
930 sequence);
931 wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
932 HOST_PRINTF ("timeout");
933 wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
934 HOST_PRINTF ("\n");
935 }
936 else
937 {
938 #endif
939 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
940 context->host, context->addr,
941 sequence);
942 #if USE_NCURSES
943 }
944 #endif
945 }
947 #if USE_NCURSES
948 update_stats_from_context (context);
949 wrefresh (main_win);
950 #endif
951 } /* }}} void update_host_hook */
953 static int post_loop_hook (pingobj_t *ping) /* {{{ */
954 {
955 pingobj_iter_t *iter;
957 #if USE_NCURSES
958 endwin ();
959 #endif
961 for (iter = ping_iterator_get (ping);
962 iter != NULL;
963 iter = ping_iterator_next (iter))
964 {
965 ping_context_t *context;
967 context = ping_iterator_get_context (iter);
969 printf ("\n--- %s ping statistics ---\n"
970 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
971 context->host, context->req_sent, context->req_rcvd,
972 context_get_packet_loss (context),
973 context->latency_total);
975 if (context->req_rcvd != 0)
976 {
977 double average;
978 double deviation;
980 average = context_get_average (context);
981 deviation = context_get_stddev (context);
983 printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
984 context->latency_min,
985 average,
986 context->latency_max,
987 deviation);
988 }
990 ping_iterator_set_context (iter, NULL);
991 context_destroy (context);
992 }
994 return (0);
995 } /* }}} int post_loop_hook */
997 int main (int argc, char **argv) /* {{{ */
998 {
999 pingobj_t *ping;
1000 pingobj_iter_t *iter;
1002 struct sigaction sigint_action;
1004 struct timeval tv_begin;
1005 struct timeval tv_end;
1006 struct timespec ts_wait;
1007 struct timespec ts_int;
1009 int optind;
1010 int i;
1011 int status;
1012 #if _POSIX_SAVED_IDS
1013 uid_t saved_set_uid;
1015 /* Save the old effective user id */
1016 saved_set_uid = geteuid ();
1017 /* Set the effective user ID to the real user ID without changing the
1018 * saved set-user ID */
1019 status = seteuid (getuid ());
1020 if (status != 0)
1021 {
1022 fprintf (stderr, "Temporarily dropping privileges "
1023 "failed: %s\n", strerror (errno));
1024 exit (EXIT_FAILURE);
1025 }
1026 #endif
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 : */