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