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