Code

oping: Make the exit status the number of hosts failed.
[liboping.git] / src / oping.c
1 /**
2  * Object oriented C module to send ICMP and ICMPv6 `echo's.
3  * Copyright (C) 2006-2011  Florian octo Forster <ff at octo.it>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; only version 2 of the License is
8  * applicable.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
18  */
20 #if HAVE_CONFIG_H
21 # include <config.h>
22 #endif
24 #if STDC_HEADERS
25 # include <stdlib.h>
26 # include <stdio.h>
27 # include <string.h>
28 # include <stdint.h>
29 # include <inttypes.h>
30 # include <errno.h>
31 # include <assert.h>
32 #else
33 # error "You don't have the standard C99 header files installed"
34 #endif /* STDC_HEADERS */
36 #if HAVE_UNISTD_H
37 # include <unistd.h>
38 #endif
40 #if HAVE_MATH_H
41 # include <math.h>
42 #endif
44 #if TIME_WITH_SYS_TIME
45 # include <sys/time.h>
46 # include <time.h>
47 #else
48 # if HAVE_SYS_TIME_H
49 #  include <sys/time.h>
50 # else
51 #  include <time.h>
52 # endif
53 #endif
55 #if HAVE_SYS_SOCKET_H
56 # include <sys/socket.h>
57 #endif
58 #if HAVE_NETINET_IN_H
59 # include <netinet/in.h>
60 #endif
61 #if HAVE_NETINET_IP_H
62 # include <netinet/ip.h>
63 #endif
65 #if HAVE_NETDB_H
66 # include <netdb.h> /* NI_MAXHOST */
67 #endif
69 #if HAVE_SIGNAL_H
70 # include <signal.h>
71 #endif
73 #if HAVE_SYS_TYPES_H
74 #include <sys/types.h>
75 #endif
77 #if USE_NCURSES
78 # define NCURSES_OPAQUE 1
79 # include <ncurses.h>
81 # define OPING_GREEN 1
82 # define OPING_YELLOW 2
83 # define OPING_RED 3
84 #endif
86 #include "oping.h"
88 #ifndef _POSIX_SAVED_IDS
89 # define _POSIX_SAVED_IDS 0
90 #endif
92 /* Remove GNU specific __attribute__ settings when using another compiler */
93 #if !__GNUC__
94 # define __attribute__(x) /**/
95 #endif
97 typedef struct ping_context
98 {
99         char host[NI_MAXHOST];
100         char addr[NI_MAXHOST];
102         int index;
103         int req_sent;
104         int req_rcvd;
106         double latency_min;
107         double latency_max;
108         double latency_total;
109         double latency_total_square;
111 #if USE_NCURSES
112         WINDOW *window;
113 #endif
114 } ping_context_t;
116 static double  opt_interval   = 1.0;
117 static int     opt_addrfamily = PING_DEF_AF;
118 static char   *opt_srcaddr    = NULL;
119 static char   *opt_device     = NULL;
120 static char   *opt_filename   = NULL;
121 static int     opt_count      = -1;
122 static int     opt_send_ttl   = 64;
123 static uint8_t opt_send_qos   = 0;
124 static double  opt_exit_status_threshold = 1.0;
126 static int host_num = 0;
128 #if USE_NCURSES
129 static WINDOW *main_win = NULL;
130 #endif
132 static void sigint_handler (int signal) /* {{{ */
134         /* Make compiler happy */
135         signal = 0;
136         /* Exit the loop */
137         opt_count = 0;
138 } /* }}} void sigint_handler */
140 static ping_context_t *context_create (void) /* {{{ */
142         ping_context_t *ret;
144         if ((ret = malloc (sizeof (ping_context_t))) == NULL)
145                 return (NULL);
147         memset (ret, '\0', sizeof (ping_context_t));
149         ret->latency_min   = -1.0;
150         ret->latency_max   = -1.0;
151         ret->latency_total = 0.0;
152         ret->latency_total_square = 0.0;
154 #if USE_NCURSES
155         ret->window = NULL;
156 #endif
158         return (ret);
159 } /* }}} ping_context_t *context_create */
161 static void context_destroy (ping_context_t *context) /* {{{ */
163         if (context == NULL)
164                 return;
166 #if USE_NCURSES
167         if (context->window != NULL)
168         {
169                 delwin (context->window);
170                 context->window = NULL;
171         }
172 #endif
174         free (context);
175 } /* }}} void context_destroy */
177 static double context_get_average (ping_context_t *ctx) /* {{{ */
179         double num_total;
181         if (ctx == NULL)
182                 return (-1.0);
184         if (ctx->req_rcvd < 1)
185                 return (-0.0);
187         num_total = (double) ctx->req_rcvd;
188         return (ctx->latency_total / num_total);
189 } /* }}} double context_get_average */
191 static double context_get_stddev (ping_context_t *ctx) /* {{{ */
193         double num_total;
195         if (ctx == NULL)
196                 return (-1.0);
198         if (ctx->req_rcvd < 1)
199                 return (-0.0);
200         else if (ctx->req_rcvd < 2)
201                 return (0.0);
203         num_total = (double) ctx->req_rcvd;
204         return (sqrt (((num_total * ctx->latency_total_square)
205                                         - (ctx->latency_total * ctx->latency_total))
206                                 / (num_total * (num_total - 1.0))));
207 } /* }}} double context_get_stddev */
209 static double context_get_packet_loss (const ping_context_t *ctx) /* {{{ */
211         if (ctx == NULL)
212                 return (-1.0);
214         if (ctx->req_sent < 1)
215                 return (0.0);
217         return (100.0 * (ctx->req_sent - ctx->req_rcvd)
218                         / ((double) ctx->req_sent));
219 } /* }}} double context_get_packet_loss */
221 static int ping_initialize_contexts (pingobj_t *ping) /* {{{ */
223         pingobj_iter_t *iter;
224         int index;
226         if (ping == NULL)
227                 return (EINVAL);
229         index = 0;
230         for (iter = ping_iterator_get (ping);
231                         iter != NULL;
232                         iter = ping_iterator_next (iter))
233         {
234                 ping_context_t *context;
235                 size_t buffer_size;
237                 context = context_create ();
238                 context->index = index;
240                 buffer_size = sizeof (context->host);
241                 ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
243                 buffer_size = sizeof (context->addr);
244                 ping_iterator_get_info (iter, PING_INFO_ADDRESS, context->addr, &buffer_size);
246                 ping_iterator_set_context (iter, (void *) context);
248                 index++;
249         }
251         return (0);
252 } /* }}} int ping_initialize_contexts */
254 static void usage_exit (const char *name, int status) /* {{{ */
256         fprintf (stderr, "Usage: %s [OPTIONS] "
257                                 "-f filename | host [host [host ...]]\n"
259                         "\nAvailable options:\n"
260                         "  -4|-6        force the use of IPv4 or IPv6\n"
261                         "  -c count     number of ICMP packets to send\n"
262                         "  -i interval  interval with which to send ICMP packets\n"
263                         "  -t ttl       time to live for each ICMP packet\n"
264                         "  -Q qos       Quality of Service (QoS) of outgoing packets\n"
265                         "               Use \"-Q help\" for a list of valid options.\n"
266                         "  -I srcaddr   source address\n"
267                         "  -D device    outgoing interface name\n"
268                         "  -f filename  filename to read hosts from\n"
269                         "  -Z percent   Exit with non-zero exit status if more than this percentage of\n"
270                         "               probes timed out. (default: never)\n"
272                         "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
273                         "by Florian octo Forster <octo@verplant.org>\n"
274                         "for contributions see `AUTHORS'\n",
275                         name);
276         exit (status);
277 } /* }}} void usage_exit */
279 __attribute__((noreturn))
280 static void usage_qos_exit (const char *arg, int status) /* {{{ */
282         if (arg != 0)
283                 fprintf (stderr, "Invalid QoS argument: \"%s\"\n\n", arg);
285         fprintf (stderr, "Valid QoS arguments (option \"-Q\") are:\n"
286                         "\n"
287                         "  Differentiated Services (IPv4 and IPv6, RFC 2474)\n"
288                         "\n"
289                         "    be                     Best Effort (BE, default PHB).\n"
290                         "    ef                     Expedited Forwarding (EF) PHB group (RFC 3246).\n"
291                         "                           (low delay, low loss, low jitter)\n"
292                         "    va                     Voice Admit (VA) DSCP (RFC 5865).\n"
293                         "                           (capacity-admitted traffic)\n"
294                         "    af[1-4][1-3]           Assured Forwarding (AF) PHB group (RFC 2597).\n"
295                         "                           For example: \"af12\" (class 1, precedence 2)\n"
296                         "    cs[0-7]                Class Selector (CS) PHB group (RFC 2474).\n"
297                         "                           For example: \"cs1\" (priority traffic)\n"
298                         "\n"
299                         "  Type of Service (IPv4, RFC 1349, obsolete)\n"
300                         "\n"
301                         "    lowdelay     (%#04x)    minimize delay\n"
302                         "    throughput   (%#04x)    maximize throughput\n"
303                         "    reliability  (%#04x)    maximize reliability\n"
304                         "    mincost      (%#04x)    minimize monetary cost\n"
305                         "\n"
306                         "  Specify manually\n"
307                         "\n"
308                         "    0x00 - 0xff            Hexadecimal numeric specification.\n"
309                         "       0 -  255            Decimal numeric specification.\n"
310                         "\n",
311                         (unsigned int) IPTOS_LOWDELAY,
312                         (unsigned int) IPTOS_THROUGHPUT,
313                         (unsigned int) IPTOS_RELIABILITY,
314                         (unsigned int) IPTOS_MINCOST);
316         exit (status);
317 } /* }}} void usage_qos_exit */
319 static int set_opt_send_qos (const char *opt) /* {{{ */
321         if (opt == NULL)
322                 return (EINVAL);
324         if (strcasecmp ("help", opt) == 0)
325                 usage_qos_exit (/* arg = */ NULL, /* status = */ EXIT_SUCCESS);
326         /* DiffServ (RFC 2474): */
327         /* - Best effort (BE) */
328         else if (strcasecmp ("be", opt) == 0)
329                 opt_send_qos = 0;
330         /* - Expedited Forwarding (EF, RFC 3246) */
331         else if (strcasecmp ("ef", opt) == 0)
332                 opt_send_qos = 0xB8; /* == 0x2E << 2 */
333         /* - Voice Admit (VA, RFC 5865) */
334         else if (strcasecmp ("va", opt) == 0)
335                 opt_send_qos = 0xB0; /* == 0x2D << 2 */
336         /* - Assured Forwarding (AF, RFC 2597) */
337         else if ((strncasecmp ("af", opt, strlen ("af")) == 0)
338                         && (strlen (opt) == 4))
339         {
340                 uint8_t dscp;
341                 uint8_t class = 0;
342                 uint8_t prec = 0;
344                 /* There are four classes, AF1x, AF2x, AF3x, and AF4x. */
345                 if (opt[2] == '1')
346                         class = 1;
347                 else if (opt[2] == '2')
348                         class = 2;
349                 else if (opt[2] == '3')
350                         class = 3;
351                 else if (opt[2] == '4')
352                         class = 4;
353                 else
354                         usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
356                 /* In each class, there are three precedences, AFx1, AFx2, and AFx3 */
357                 if (opt[3] == '1')
358                         prec = 1;
359                 else if (opt[3] == '2')
360                         prec = 2;
361                 else if (opt[3] == '3')
362                         prec = 3;
363                 else
364                         usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_SUCCESS);
366                 dscp = (8 * class) + (2 * prec);
367                 /* The lower two bits are used for Explicit Congestion Notification (ECN) */
368                 opt_send_qos = dscp << 2;
369         }
370         /* - Class Selector (CS) */
371         else if ((strncasecmp ("cs", opt, strlen ("cs")) == 0)
372                         && (strlen (opt) == 3))
373         {
374                 uint8_t class;
376                 if ((opt[2] < '0') || (opt[2] > '7'))
377                         usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
379                 /* Not exactly legal by the C standard, but I don't know of any
380                  * system not supporting this hack. */
381                 class = ((uint8_t) opt[2]) - ((uint8_t) '0');
382                 opt_send_qos = class << 5;
383         }
384         /* Type of Service (RFC 1349) */
385         else if (strcasecmp ("lowdelay", opt) == 0)
386                 opt_send_qos = IPTOS_LOWDELAY;
387         else if (strcasecmp ("throughput", opt) == 0)
388                 opt_send_qos = IPTOS_THROUGHPUT;
389         else if (strcasecmp ("reliability", opt) == 0)
390                 opt_send_qos = IPTOS_RELIABILITY;
391         else if (strcasecmp ("mincost", opt) == 0)
392                 opt_send_qos = IPTOS_MINCOST;
393         /* Numeric value */
394         else
395         {
396                 unsigned long value;
397                 char *endptr;
399                 errno = 0;
400                 endptr = NULL;
401                 value = strtoul (opt, &endptr, /* base = */ 0);
402                 if ((errno != 0) || (endptr == opt)
403                                 || (endptr == NULL) || (*endptr != 0)
404                                 || (value > 0xff))
405                         usage_qos_exit (/* arg = */ opt, /* status = */ EXIT_FAILURE);
406                 
407                 opt_send_qos = (uint8_t) value;
408         }
410         return (0);
411 } /* }}} int set_opt_send_qos */
413 static char *format_qos (uint8_t qos, char *buffer, size_t buffer_size) /* {{{ */
415         uint8_t dscp;
416         uint8_t ecn;
417         char *dscp_str;
418         char *ecn_str;
420         dscp = qos >> 2;
421         ecn = qos & 0x03;
423         switch (dscp)
424         {
425                 case 0x00: dscp_str = "be";  break;
426                 case 0x2e: dscp_str = "ef";  break;
427                 case 0x2d: dscp_str = "va";  break;
428                 case 0x0a: dscp_str = "af11"; break;
429                 case 0x0c: dscp_str = "af12"; break;
430                 case 0x0e: dscp_str = "af13"; break;
431                 case 0x12: dscp_str = "af21"; break;
432                 case 0x14: dscp_str = "af22"; break;
433                 case 0x16: dscp_str = "af23"; break;
434                 case 0x1a: dscp_str = "af31"; break;
435                 case 0x1c: dscp_str = "af32"; break;
436                 case 0x1e: dscp_str = "af33"; break;
437                 case 0x22: dscp_str = "af41"; break;
438                 case 0x24: dscp_str = "af42"; break;
439                 case 0x26: dscp_str = "af43"; break;
440                 case 0x08: dscp_str = "cs1";  break;
441                 case 0x10: dscp_str = "cs2";  break;
442                 case 0x18: dscp_str = "cs3";  break;
443                 case 0x20: dscp_str = "cs4";  break;
444                 case 0x28: dscp_str = "cs5";  break;
445                 case 0x30: dscp_str = "cs6";  break;
446                 case 0x38: dscp_str = "cs7";  break;
447                 default:   dscp_str = NULL;
448         }
450         switch (ecn)
451         {
452                 case 0x01: ecn_str = ",ecn(1)"; break;
453                 case 0x02: ecn_str = ",ecn(0)"; break;
454                 case 0x03: ecn_str = ",ce"; break;
455                 default:   ecn_str = "";
456         }
458         if (dscp_str == NULL)
459                 snprintf (buffer, buffer_size, "0x%02x%s", dscp, ecn_str);
460         else
461                 snprintf (buffer, buffer_size, "%s%s", dscp_str, ecn_str);
462         buffer[buffer_size - 1] = 0;
464         return (buffer);
465 } /* }}} char *format_qos */
467 static int read_options (int argc, char **argv) /* {{{ */
469         int optchar;
471         while (1)
472         {
473                 optchar = getopt (argc, argv, "46c:hi:I:t:Q:f:D:Z:");
475                 if (optchar == -1)
476                         break;
478                 switch (optchar)
479                 {
480                         case '4':
481                         case '6':
482                                 opt_addrfamily = (optchar == '4') ? AF_INET : AF_INET6;
483                                 break;
485                         case 'c':
486                                 {
487                                         int new_count;
488                                         new_count = atoi (optarg);
489                                         if (new_count > 0)
490                                                 opt_count = new_count;
491                                         else
492                                                 fprintf(stderr, "Ignoring invalid count: %s\n",
493                                                                 optarg);
494                                 }
495                                 break;
497                         case 'f':
498                                 {
499                                         if (opt_filename != NULL)
500                                                 free (opt_filename);
501                                         opt_filename = strdup (optarg);
502                                 }
503                                 break;
505                         case 'i':
506                                 {
507                                         double new_interval;
508                                         new_interval = atof (optarg);
509                                         if (new_interval < 0.001)
510                                                 fprintf (stderr, "Ignoring invalid interval: %s\n",
511                                                                 optarg);
512                                         else
513                                                 opt_interval = new_interval;
514                                 }
515                                 break;
516                         case 'I':
517                                 {
518                                         if (opt_srcaddr != NULL)
519                                                 free (opt_srcaddr);
520                                         opt_srcaddr = strdup (optarg);
521                                 }
522                                 break;
524                         case 'D':
525                                 opt_device = optarg;
526                                 break;
528                         case 't':
529                         {
530                                 int new_send_ttl;
531                                 new_send_ttl = atoi (optarg);
532                                 if ((new_send_ttl > 0) && (new_send_ttl < 256))
533                                         opt_send_ttl = new_send_ttl;
534                                 else
535                                         fprintf (stderr, "Ignoring invalid TTL argument: %s\n",
536                                                         optarg);
537                                 break;
538                         }
540                         case 'Q':
541                                 set_opt_send_qos (optarg);
542                                 break;
544                         case 'Z':
545                         {
546                                 char *endptr = NULL;
547                                 double tmp;
549                                 errno = 0;
550                                 tmp = strtod (optarg, &endptr);
551                                 if ((errno != 0) || (endptr == NULL) || (*endptr != 0) || (tmp < 0.0) || (tmp > 100.0))
552                                 {
553                                         fprintf (stderr, "Ignoring invalid -Z argument: %s\n", optarg);
554                                         fprintf (stderr, "The \"-Z\" option requires a numeric argument between 0 and 100.\n");
555                                 }
556                                 else
557                                         opt_exit_status_threshold = tmp / 100.0;
559                                 break;
560                         }
562                         case 'h':
563                                 usage_exit (argv[0], 0);
564                                 break;
565                         default:
566                                 usage_exit (argv[0], 1);
567                 }
568         }
570         return (optind);
571 } /* }}} read_options */
573 static void time_normalize (struct timespec *ts) /* {{{ */
575         while (ts->tv_nsec < 0)
576         {
577                 if (ts->tv_sec == 0)
578                 {
579                         ts->tv_nsec = 0;
580                         return;
581                 }
583                 ts->tv_sec  -= 1;
584                 ts->tv_nsec += 1000000000;
585         }
587         while (ts->tv_nsec >= 1000000000)
588         {
589                 ts->tv_sec  += 1;
590                 ts->tv_nsec -= 1000000000;
591         }
592 } /* }}} void time_normalize */
594 static void time_calc (struct timespec *ts_dest, /* {{{ */
595                 const struct timespec *ts_int,
596                 const struct timeval  *tv_begin,
597                 const struct timeval  *tv_end)
599         ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
600         ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
601         time_normalize (ts_dest);
603         /* Assure that `(begin + interval) > end'.
604          * This may seem overly complicated, but `tv_sec' is of type `time_t'
605          * which may be `unsigned. *sigh* */
606         if ((tv_end->tv_sec > ts_dest->tv_sec)
607                         || ((tv_end->tv_sec == ts_dest->tv_sec)
608                                 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
609         {
610                 ts_dest->tv_sec  = 0;
611                 ts_dest->tv_nsec = 0;
612                 return;
613         }
615         ts_dest->tv_sec = ts_dest->tv_sec - tv_end->tv_sec;
616         ts_dest->tv_nsec = ts_dest->tv_nsec - (tv_end->tv_usec * 1000);
617         time_normalize (ts_dest);
618 } /* }}} void time_calc */
620 #if USE_NCURSES
621 static int update_stats_from_context (ping_context_t *ctx) /* {{{ */
623         if ((ctx == NULL) || (ctx->window == NULL))
624                 return (EINVAL);
626         werase (ctx->window);
628         box (ctx->window, 0, 0);
629         wattron (ctx->window, A_BOLD);
630         mvwprintw (ctx->window, /* y = */ 0, /* x = */ 5,
631                         " %s ", ctx->host);
632         wattroff (ctx->window, A_BOLD);
633         wprintw (ctx->window, "ping statistics ");
634         mvwprintw (ctx->window, /* y = */ 1, /* x = */ 2,
635                         "%i packets transmitted, %i received, %.2f%% packet "
636                         "loss, time %.1fms",
637                         ctx->req_sent, ctx->req_rcvd,
638                         context_get_packet_loss (ctx),
639                         ctx->latency_total);
640         if (ctx->req_rcvd != 0)
641         {
642                 double average;
643                 double deviation;
645                 average = context_get_average (ctx);
646                 deviation = context_get_stddev (ctx);
648                 mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
649                                 "rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms",
650                                 ctx->latency_min,
651                                 average,
652                                 ctx->latency_max,
653                                 deviation);
654         }
656         wrefresh (ctx->window);
658         return (0);
659 } /* }}} int update_stats_from_context */
661 static int on_resize (pingobj_t *ping) /* {{{ */
663         pingobj_iter_t *iter;
664         int width = 0;
665         int height = 0;
666         int main_win_height;
668         getmaxyx (stdscr, height, width);
669         if ((height < 1) || (width < 1))
670                 return (EINVAL);
672         main_win_height = height - (4 * host_num);
673         wresize (main_win, main_win_height, /* width = */ width);
674         /* Allow scrolling */
675         scrollok (main_win, TRUE);
676         /* wsetscrreg (main_win, 0, main_win_height - 1); */
677         /* Allow hardware accelerated scrolling. */
678         idlok (main_win, TRUE);
679         wrefresh (main_win);
681         for (iter = ping_iterator_get (ping);
682                         iter != NULL;
683                         iter = ping_iterator_next (iter))
684         {
685                 ping_context_t *context;
687                 context = ping_iterator_get_context (iter);
688                 if (context == NULL)
689                         continue;
691                 if (context->window != NULL)
692                 {
693                         delwin (context->window);
694                         context->window = NULL;
695                 }
696                 context->window = newwin (/* height = */ 4,
697                                 /* width = */ width,
698                                 /* y = */ main_win_height + (4 * context->index),
699                                 /* x = */ 0);
700         }
702         return (0);
703 } /* }}} */
705 static int check_resize (pingobj_t *ping) /* {{{ */
707         int need_resize = 0;
709         while (42)
710         {
711                 int key = wgetch (stdscr);
712                 if (key == ERR)
713                         break;
714                 else if (key == KEY_RESIZE)
715                         need_resize = 1;
716         }
718         if (need_resize)
719                 return (on_resize (ping));
720         else
721                 return (0);
722 } /* }}} int check_resize */
724 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
726         pingobj_iter_t *iter;
727         int width = 0;
728         int height = 0;
729         int main_win_height;
731         initscr ();
732         cbreak ();
733         noecho ();
734         nodelay (stdscr, TRUE);
736         getmaxyx (stdscr, height, width);
737         if ((height < 1) || (width < 1))
738                 return (EINVAL);
740         if (has_colors () == TRUE)
741         {
742                 start_color ();
743                 init_pair (OPING_GREEN,  COLOR_GREEN,  /* default = */ 0);
744                 init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
745                 init_pair (OPING_RED,    COLOR_RED,    /* default = */ 0);
746         }
748         main_win_height = height - (4 * host_num);
749         main_win = newwin (/* height = */ main_win_height,
750                         /* width = */ width,
751                         /* y = */ 0, /* x = */ 0);
752         /* Allow scrolling */
753         scrollok (main_win, TRUE);
754         /* wsetscrreg (main_win, 0, main_win_height - 1); */
755         /* Allow hardware accelerated scrolling. */
756         idlok (main_win, TRUE);
757         wmove (main_win, /* y = */ main_win_height - 1, /* x = */ 0);
758         wrefresh (main_win);
760         for (iter = ping_iterator_get (ping);
761                         iter != NULL;
762                         iter = ping_iterator_next (iter))
763         {
764                 ping_context_t *context;
766                 context = ping_iterator_get_context (iter);
767                 if (context == NULL)
768                         continue;
770                 if (context->window != NULL)
771                 {
772                         delwin (context->window);
773                         context->window = NULL;
774                 }
775                 context->window = newwin (/* height = */ 4,
776                                 /* width = */ width,
777                                 /* y = */ main_win_height + (4 * context->index),
778                                 /* x = */ 0);
779         }
782         /* Don't know what good this does exactly, but without this code
783          * "check_resize" will be called right after startup and *somehow*
784          * this leads to display errors. If we purge all initial characters
785          * here, the problem goes away. "wgetch" is non-blocking due to
786          * "nodelay" (see above). */
787         while (wgetch (stdscr) != ERR)
788         {
789                 /* eat up characters */;
790         }
792         return (0);
793 } /* }}} int pre_loop_hook */
795 static int pre_sleep_hook (pingobj_t *ping) /* {{{ */
797         return (check_resize (ping));
798 } /* }}} int pre_sleep_hook */
800 static int post_sleep_hook (pingobj_t *ping) /* {{{ */
802         return (check_resize (ping));
803 } /* }}} int pre_sleep_hook */
804 #else /* if !USE_NCURSES */
805 static int pre_loop_hook (pingobj_t *ping) /* {{{ */
807         pingobj_iter_t *iter;
809         for (iter = ping_iterator_get (ping);
810                         iter != NULL;
811                         iter = ping_iterator_next (iter))
812         {
813                 ping_context_t *ctx;
814                 size_t buffer_size;
816                 ctx = ping_iterator_get_context (iter);
817                 if (ctx == NULL)
818                         continue;
820                 buffer_size = 0;
821                 ping_iterator_get_info (iter, PING_INFO_DATA, NULL, &buffer_size);
823                 printf ("PING %s (%s) %zu bytes of data.\n",
824                                 ctx->host, ctx->addr, buffer_size);
825         }
827         return (0);
828 } /* }}} int pre_loop_hook */
830 static int pre_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
832         fflush (stdout);
834         return (0);
835 } /* }}} int pre_sleep_hook */
837 static int post_sleep_hook (__attribute__((unused)) pingobj_t *ping) /* {{{ */
839         return (0);
840 } /* }}} int post_sleep_hook */
841 #endif
843 static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
844                 __attribute__((unused)) int index)
846         double          latency;
847         unsigned int    sequence;
848         int             recv_ttl;
849         uint8_t         recv_qos;
850         char            recv_qos_str[16];
851         size_t          buffer_len;
852         size_t          data_len;
853         ping_context_t *context;
855         latency = -1.0;
856         buffer_len = sizeof (latency);
857         ping_iterator_get_info (iter, PING_INFO_LATENCY,
858                         &latency, &buffer_len);
860         sequence = 0;
861         buffer_len = sizeof (sequence);
862         ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
863                         &sequence, &buffer_len);
865         recv_ttl = -1;
866         buffer_len = sizeof (recv_ttl);
867         ping_iterator_get_info (iter, PING_INFO_RECV_TTL,
868                         &recv_ttl, &buffer_len);
870         recv_qos = 0;
871         buffer_len = sizeof (recv_qos);
872         ping_iterator_get_info (iter, PING_INFO_RECV_QOS,
873                         &recv_qos, &buffer_len);
875         data_len = 0;
876         ping_iterator_get_info (iter, PING_INFO_DATA,
877                         NULL, &data_len);
879         context = (ping_context_t *) ping_iterator_get_context (iter);
881 #if USE_NCURSES
882 # define HOST_PRINTF(...) wprintw(main_win, __VA_ARGS__)
883 #else
884 # define HOST_PRINTF(...) printf(__VA_ARGS__)
885 #endif
887         context->req_sent++;
888         if (latency > 0.0)
889         {
890                 context->req_rcvd++;
891                 context->latency_total += latency;
892                 context->latency_total_square += (latency * latency);
894                 if ((context->latency_max < 0.0) || (context->latency_max < latency))
895                         context->latency_max = latency;
896                 if ((context->latency_min < 0.0) || (context->latency_min > latency))
897                         context->latency_min = latency;
899 #if USE_NCURSES
900                 if (has_colors () == TRUE)
901                 {
902                         int color = OPING_GREEN;
903                         double average = context_get_average (context);
904                         double stddev = context_get_stddev (context);
906                         if ((latency < (average - (2 * stddev)))
907                                         || (latency > (average + (2 * stddev))))
908                                 color = OPING_RED;
909                         else if ((latency < (average - stddev))
910                                         || (latency > (average + stddev)))
911                                 color = OPING_YELLOW;
913                         HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
914                                         data_len, context->host, context->addr,
915                                         sequence, recv_ttl,
916                                         format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
917                         if ((recv_qos != 0) || (opt_send_qos != 0))
918                         {
919                                 HOST_PRINTF ("qos=%s ",
920                                                 format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
921                         }
922                         HOST_PRINTF ("time=");
923                         wattron (main_win, COLOR_PAIR(color));
924                         HOST_PRINTF ("%.2f", latency);
925                         wattroff (main_win, COLOR_PAIR(color));
926                         HOST_PRINTF (" ms\n");
927                 }
928                 else
929                 {
930 #endif
931                 HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
932                                 data_len,
933                                 context->host, context->addr,
934                                 sequence, recv_ttl);
935                 if ((recv_qos != 0) || (opt_send_qos != 0))
936                 {
937                         HOST_PRINTF ("qos=%s ",
938                                         format_qos (recv_qos, recv_qos_str, sizeof (recv_qos_str)));
939                 }
940                 HOST_PRINTF ("time=%.2f ms\n", latency);
941 #if USE_NCURSES
942                 }
943 #endif
944         }
945         else
946         {
947 #if USE_NCURSES
948                 if (has_colors () == TRUE)
949                 {
950                         HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u ",
951                                         context->host, context->addr,
952                                         sequence);
953                         wattron (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
954                         HOST_PRINTF ("timeout");
955                         wattroff (main_win, COLOR_PAIR(OPING_RED) | A_BOLD);
956                         HOST_PRINTF ("\n");
957                 }
958                 else
959                 {
960 #endif
961                 HOST_PRINTF ("echo reply from %s (%s): icmp_seq=%u timeout\n",
962                                 context->host, context->addr,
963                                 sequence);
964 #if USE_NCURSES
965                 }
966 #endif
967         }
969 #if USE_NCURSES
970         update_stats_from_context (context);
971         wrefresh (main_win);
972 #endif
973 } /* }}} void update_host_hook */
975 /* Prints statistics for each host, cleans up the contexts and returns the
976  * number of hosts which failed to return more than the fraction
977  * opt_exit_status_threshold of pings. */
978 static int post_loop_hook (pingobj_t *ping) /* {{{ */
980         pingobj_iter_t *iter;
981         int failure_count = 0;
983 #if USE_NCURSES
984         endwin ();
985 #endif
987         for (iter = ping_iterator_get (ping);
988                         iter != NULL;
989                         iter = ping_iterator_next (iter))
990         {
991                 ping_context_t *context;
993                 context = ping_iterator_get_context (iter);
995                 printf ("\n--- %s ping statistics ---\n"
996                                 "%i packets transmitted, %i received, %.2f%% packet loss, time %.1fms\n",
997                                 context->host, context->req_sent, context->req_rcvd,
998                                 context_get_packet_loss (context),
999                                 context->latency_total);
1001                 {
1002                         double pct_failed = 1.0 - (((double) context->req_rcvd)
1003                                         / ((double) context->req_sent));
1004                         if (pct_failed > opt_exit_status_threshold)
1005                                 failure_count++;
1006                 }
1008                 if (context->req_rcvd != 0)
1009                 {
1010                         double average;
1011                         double deviation;
1013                         average = context_get_average (context);
1014                         deviation = context_get_stddev (context);
1016                         printf ("rtt min/avg/max/sdev = %.3f/%.3f/%.3f/%.3f ms\n",
1017                                         context->latency_min,
1018                                         average,
1019                                         context->latency_max,
1020                                         deviation);
1021                 }
1023                 ping_iterator_set_context (iter, NULL);
1024                 context_destroy (context);
1025         }
1027         return (failure_count);
1028 } /* }}} int post_loop_hook */
1030 int main (int argc, char **argv) /* {{{ */
1032         pingobj_t      *ping;
1033         pingobj_iter_t *iter;
1035         struct sigaction sigint_action;
1037         struct timeval  tv_begin;
1038         struct timeval  tv_end;
1039         struct timespec ts_wait;
1040         struct timespec ts_int;
1042         int optind;
1043         int i;
1044         int status;
1045 #if _POSIX_SAVED_IDS
1046         uid_t saved_set_uid;
1048         /* Save the old effective user id */
1049         saved_set_uid = geteuid ();
1050         /* Set the effective user ID to the real user ID without changing the
1051          * saved set-user ID */
1052         status = seteuid (getuid ());
1053         if (status != 0)
1054         {
1055                 fprintf (stderr, "Temporarily dropping privileges "
1056                                 "failed: %s\n", strerror (errno));
1057                 exit (EXIT_FAILURE);
1058         }
1059 #endif
1061         optind = read_options (argc, argv);
1063 #if !_POSIX_SAVED_IDS
1064         /* Cannot temporarily drop privileges -> reject every file but "-". */
1065         if ((opt_filename != NULL)
1066                         && (strcmp ("-", opt_filename) != 0)
1067                         && (getuid () != geteuid ()))
1068         {
1069                 fprintf (stderr, "Your real and effective user IDs don't "
1070                                 "match. Reading from a file (option '-f')\n"
1071                                 "is therefore too risky. You can still read "
1072                                 "from STDIN using '-f -' if you like.\n"
1073                                 "Sorry.\n");
1074                 exit (EXIT_FAILURE);
1075         }
1076 #endif
1078         if ((optind >= argc) && (opt_filename == NULL)) {
1079                 usage_exit (argv[0], 1);
1080         }
1082         if ((ping = ping_construct ()) == NULL)
1083         {
1084                 fprintf (stderr, "ping_construct failed\n");
1085                 return (1);
1086         }
1088         if (ping_setopt (ping, PING_OPT_TTL, &opt_send_ttl) != 0)
1089         {
1090                 fprintf (stderr, "Setting TTL to %i failed: %s\n",
1091                                 opt_send_ttl, ping_get_error (ping));
1092         }
1094         if (ping_setopt (ping, PING_OPT_QOS, &opt_send_qos) != 0)
1095         {
1096                 fprintf (stderr, "Setting TOS to %i failed: %s\n",
1097                                 opt_send_qos, ping_get_error (ping));
1098         }
1100         {
1101                 double temp_sec;
1102                 double temp_nsec;
1104                 temp_nsec = modf (opt_interval, &temp_sec);
1105                 ts_int.tv_sec  = (time_t) temp_sec;
1106                 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
1108                 /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
1109         }
1111         if (opt_addrfamily != PING_DEF_AF)
1112                 ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
1114         if (opt_srcaddr != NULL)
1115         {
1116                 if (ping_setopt (ping, PING_OPT_SOURCE, (void *) opt_srcaddr) != 0)
1117                 {
1118                         fprintf (stderr, "Setting source address failed: %s\n",
1119                                         ping_get_error (ping));
1120                 }
1121         }
1123         if (opt_device != NULL)
1124         {
1125                 if (ping_setopt (ping, PING_OPT_DEVICE, (void *) opt_device) != 0)
1126                 {
1127                         fprintf (stderr, "Setting device failed: %s\n",
1128                                         ping_get_error (ping));
1129                 }
1130         }
1132         if (opt_filename != NULL)
1133         {
1134                 FILE *infile;
1135                 char line[256];
1136                 char host[256];
1138                 if (strcmp (opt_filename, "-") == 0)
1139                         /* Open STDIN */
1140                         infile = fdopen(0, "r");
1141                 else
1142                         infile = fopen(opt_filename, "r");
1144                 if (infile == NULL)
1145                 {
1146                         fprintf (stderr, "Opening %s failed: %s\n",
1147                                         (strcmp (opt_filename, "-") == 0)
1148                                         ? "STDIN" : opt_filename,
1149                                         strerror(errno));
1150                         return (1);
1151                 }
1153 #if _POSIX_SAVED_IDS
1154                 /* Regain privileges */
1155                 status = seteuid (saved_set_uid);
1156                 if (status != 0)
1157                 {
1158                         fprintf (stderr, "Temporarily re-gaining privileges "
1159                                         "failed: %s\n", strerror (errno));
1160                         exit (EXIT_FAILURE);
1161                 }
1162 #endif
1164                 while (fgets(line, sizeof(line), infile))
1165                 {
1166                         /* Strip whitespace */
1167                         if (sscanf(line, "%s", host) != 1)
1168                                 continue;
1170                         if ((host[0] == 0) || (host[0] == '#'))
1171                                 continue;
1173                         if (ping_host_add(ping, host) < 0)
1174                         {
1175                                 const char *errmsg = ping_get_error (ping);
1177                                 fprintf (stderr, "Adding host `%s' failed: %s\n", host, errmsg);
1178                                 continue;
1179                         }
1180                         else
1181                         {
1182                                 host_num++;
1183                         }
1184                 }
1186 #if _POSIX_SAVED_IDS
1187                 /* Drop privileges */
1188                 status = seteuid (getuid ());
1189                 if (status != 0)
1190                 {
1191                         fprintf (stderr, "Temporarily dropping privileges "
1192                                         "failed: %s\n", strerror (errno));
1193                         exit (EXIT_FAILURE);
1194                 }
1195 #endif
1197                 fclose(infile);
1198         }
1200 #if _POSIX_SAVED_IDS
1201         /* Regain privileges */
1202         status = seteuid (saved_set_uid);
1203         if (status != 0)
1204         {
1205                 fprintf (stderr, "Temporarily re-gaining privileges "
1206                                 "failed: %s\n", strerror (errno));
1207                 exit (EXIT_FAILURE);
1208         }
1209 #endif
1211         for (i = optind; i < argc; i++)
1212         {
1213                 if (ping_host_add (ping, argv[i]) < 0)
1214                 {
1215                         const char *errmsg = ping_get_error (ping);
1217                         fprintf (stderr, "Adding host `%s' failed: %s\n", argv[i], errmsg);
1218                         continue;
1219                 }
1220                 else
1221                 {
1222                         host_num++;
1223                 }
1224         }
1226         /* Permanently drop root privileges if we're setuid-root. */
1227         status = setuid (getuid ());
1228         if (status != 0)
1229         {
1230                 fprintf (stderr, "Dropping privileges failed: %s\n",
1231                                 strerror (errno));
1232                 exit (EXIT_FAILURE);
1233         }
1235 #if _POSIX_SAVED_IDS
1236         saved_set_uid = (uid_t) -1;
1237 #endif
1239         ping_initialize_contexts (ping);
1241         if (i == 0)
1242                 return (1);
1244         memset (&sigint_action, '\0', sizeof (sigint_action));
1245         sigint_action.sa_handler = sigint_handler;
1246         if (sigaction (SIGINT, &sigint_action, NULL) < 0)
1247         {
1248                 perror ("sigaction");
1249                 return (1);
1250         }
1252         pre_loop_hook (ping);
1254         while (opt_count != 0)
1255         {
1256                 int index;
1257                 int status;
1259                 if (gettimeofday (&tv_begin, NULL) < 0)
1260                 {
1261                         perror ("gettimeofday");
1262                         return (1);
1263                 }
1265                 if (ping_send (ping) < 0)
1266                 {
1267                         fprintf (stderr, "ping_send failed: %s\n",
1268                                         ping_get_error (ping));
1269                         return (1);
1270                 }
1272                 index = 0;
1273                 for (iter = ping_iterator_get (ping);
1274                                 iter != NULL;
1275                                 iter = ping_iterator_next (iter))
1276                 {
1277                         update_host_hook (iter, index);
1278                         index++;
1279                 }
1281                 pre_sleep_hook (ping);
1283                 /* Don't sleep in the last iteration */
1284                 if (opt_count == 1)
1285                         break;
1287                 if (gettimeofday (&tv_end, NULL) < 0)
1288                 {
1289                         perror ("gettimeofday");
1290                         return (1);
1291                 }
1293                 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
1295                 /* printf ("Sleeping for %i.%09li seconds\n", (int) ts_wait.tv_sec, ts_wait.tv_nsec); */
1296                 while ((status = nanosleep (&ts_wait, &ts_wait)) != 0)
1297                 {
1298                         if (errno != EINTR)
1299                         {
1300                                 perror ("nanosleep");
1301                                 break;
1302                         }
1303                         else if (opt_count == 0)
1304                         {
1305                                 /* sigint */
1306                                 break;
1307                         }
1308                 }
1310                 post_sleep_hook (ping);
1312                 if (opt_count > 0)
1313                         opt_count--;
1314         } /* while (opt_count != 0) */
1316         /* Returns the number of failed hosts according to -Z. */
1317         status = post_loop_hook (ping);
1319         ping_destroy (ping);
1321         if (status == 0)
1322                 exit (EXIT_SUCCESS);
1323         else
1324         {
1325                 if (status > 255)
1326                         status = 255;
1327                 exit (status);
1328         }
1329 } /* }}} int main */
1331 /* vim: set fdm=marker : */