Handle duplicate hosts without visual corruption
[liboping.git] / src / oping.c
index cce4379..47249b5 100644 (file)
@@ -1,6 +1,6 @@
 /**
  * Object oriented C module to send ICMP and ICMPv6 `echo's.
- * Copyright (C) 2006-2014  Florian octo Forster <ff at octo.it>
+ * Copyright (C) 2006-2016  Florian octo Forster <ff at octo.it>
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
 /* http://newsgroups.derkeiler.com/Archive/Rec/rec.games.roguelike.development/2010-09/msg00050.html */
 # define _X_OPEN_SOURCE_EXTENDED
 
-# if HAVE_NCURSESW_NCURSES_H
-#  include <ncursesw/ncurses.h>
-# elif HAVE_NCURSES_H
+#if defined HAVE_NCURSESW_CURSES_H
+#  include <ncursesw/curses.h>
+#elif defined HAVE_NCURSESW_H
+#  include <ncursesw.h>
+#elif defined HAVE_NCURSES_CURSES_H
+#  include <ncurses/curses.h>
+#elif defined HAVE_NCURSES_H
 #  include <ncurses.h>
-# endif
+#else
+#  error "SysV or X/Open-compatible Curses header file required"
+#endif
 
 # define OPING_GREEN 1
 # define OPING_YELLOW 2
@@ -167,17 +173,22 @@ typedef struct ping_context
 #endif
        /* The last n RTTs in the order they were sent. */
        double history_by_time[HISTORY_SIZE_MAX];
-       /* Current size of the history. This is a value between 0 and
-        * HISTORY_SIZE_MAX. */
+
+       /* Current number of entries in the history. This is a value between 0
+        * and HISTORY_SIZE_MAX. */
        size_t history_size;
+
+       /* Total number of reponses received. */
+       size_t history_received;
+
        /* Index of the next RTT to be written to history_by_time. This wraps
         * around to 0 once the histroty has grown to HISTORY_SIZE_MAX. */
        size_t history_index;
-       /* Number received replies, i.e. non-NAN entries. */
-       size_t history_received;
-       /* The last n RTTs sorted by value. timed out packets are sorted to the
-        * back. */
+
+       /* The last history_size RTTs sorted by value. timed out packets (NAN
+        * entries) are sorted to the back. */
        double history_by_value[HISTORY_SIZE_MAX];
+
        /* If set to true, history_by_value has to be re-calculated. */
        _Bool history_dirty;
 
@@ -187,9 +198,11 @@ typedef struct ping_context
 } ping_context_t;
 
 static double  opt_interval   = 1.0;
+static double  opt_timeout    = PING_DEF_TIMEOUT;
 static int     opt_addrfamily = PING_DEF_AF;
 static char   *opt_srcaddr    = NULL;
 static char   *opt_device     = NULL;
+static char   *opt_mark       = NULL;
 static char   *opt_filename   = NULL;
 static int     opt_count      = -1;
 static int     opt_send_ttl   = 64;
@@ -201,8 +214,11 @@ static double  opt_exit_status_threshold = 1.0;
 static int     opt_show_graph = 1;
 static int     opt_utf8       = 0;
 #endif
+static char   *opt_outfile    = NULL;
+static int     opt_bell       = 0;
 
-static int host_num = 0;
+static int host_num  = 0;
+static FILE *outfile = NULL;
 
 #if USE_NCURSES
 static WINDOW *main_win = NULL;
@@ -216,22 +232,17 @@ static void sigint_handler (int signal) /* {{{ */
        opt_count = 0;
 } /* }}} void sigint_handler */
 
-static ping_context_t *context_create (void) /* {{{ */
+static ping_context_t *context_create () /* {{{ */
 {
-       ping_context_t *ret;
-
-       if ((ret = malloc (sizeof (ping_context_t))) == NULL)
+       ping_context_t *ctx = calloc (1, sizeof (*ctx));
+       if (ctx == NULL)
                return (NULL);
 
-       memset (ret, '\0', sizeof (ping_context_t));
-
-       ret->latency_total = 0.0;
-
 #if USE_NCURSES
-       ret->window = NULL;
+       ctx->window = NULL;
 #endif
 
-       return (ret);
+       return (ctx);
 } /* }}} ping_context_t *context_create */
 
 static void context_destroy (ping_context_t *context) /* {{{ */
@@ -282,10 +293,17 @@ static void clean_history (ping_context_t *ctx) /* {{{ */
        /* Copy all values from by_time to by_value. */
        memcpy (ctx->history_by_value, ctx->history_by_time,
                        sizeof (ctx->history_by_time));
+
+       /* Remove impossible values caused by adding a new host */
+       for (i = 0; i < ctx->history_size; i++)
+               if (ctx->history_by_value[i] < 0)
+                       ctx->history_by_value[i] = NAN;
+
        /* Sort all RTTs. */
        qsort (ctx->history_by_value, ctx->history_size, sizeof
                        (ctx->history_by_value[0]), compare_double);
 
+       /* Update the number of received RTTs. */
        ctx->history_received = 0;
        for (i = 0; i < ctx->history_size; i++)
                if (!isnan (ctx->history_by_value[i]))
@@ -302,6 +320,7 @@ static double percentile_to_latency (ping_context_t *ctx, /* {{{ */
 
        clean_history (ctx);
 
+       /* Not a single packet was received successfully. */
        if (ctx->history_received == 0)
                return NAN;
 
@@ -320,7 +339,7 @@ static double percentile_to_latency (ping_context_t *ctx, /* {{{ */
 } /* }}} double percentile_to_latency */
 
 #if USE_NCURSES
-static double latency_to_percentile (ping_context_t *ctx, /* {{{ */
+static double latency_to_ratio (ping_context_t *ctx, /* {{{ */
                double latency)
 {
        size_t low;
@@ -329,6 +348,7 @@ static double latency_to_percentile (ping_context_t *ctx, /* {{{ */
 
        clean_history (ctx);
 
+       /* Not a single packet was received successfully. */
        if (ctx->history_received == 0)
                return NAN;
 
@@ -340,6 +360,11 @@ static double latency_to_percentile (ping_context_t *ctx, /* {{{ */
        else if (latency >= ctx->history_by_value[high])
                return 100.0;
 
+       /* Do a binary search for the latency. This will work even when the
+        * exact latency is not in the array. If the latency is in the array
+        * multiple times, "low" will be set to the index of the last
+        * occurrence. The value at index "high" will be larger than the
+        * searched for latency (assured by the above "if" block. */
        while ((high - low) > 1)
        {
                index = (high + low) / 2;
@@ -358,8 +383,8 @@ static double latency_to_percentile (ping_context_t *ctx, /* {{{ */
        else
                index = high;
 
-       return (100.0 * ((double) (index + 1)) / ((double) ctx->history_received));
-} /* }}} double latency_to_percentile */
+       return (((double) (index + 1)) / ((double) ctx->history_received));
+} /* }}} double latency_to_ratio */
 #endif
 
 static double context_get_packet_loss (const ping_context_t *ctx) /* {{{ */
@@ -378,6 +403,7 @@ static int ping_initialize_contexts (pingobj_t *ping) /* {{{ */
 {
        pingobj_iter_t *iter;
        int index;
+       size_t history_size = 0;
 
        if (ping == NULL)
                return (EINVAL);
@@ -389,10 +415,27 @@ static int ping_initialize_contexts (pingobj_t *ping) /* {{{ */
        {
                ping_context_t *context;
                size_t buffer_size;
+               int i;
+
+               context = ping_iterator_get_context(iter);
+
+               /* if this is a previously existing host, do not recreate it */
+               if (context != NULL)
+               {
+                       history_size = context->history_size;
+                       context->index = index++;
+                       continue;
+               }
 
                context = context_create ();
                context->index = index;
 
+               /* start new hosts at the same graph point as old hosts */
+               context->history_size = history_size;
+               context->history_index = history_size;
+               for (i = 0; i < history_size; i++)
+                       context->history_by_time[i] = -1;
+
                buffer_size = sizeof (context->host);
                ping_iterator_get_info (iter, PING_INFO_HOSTNAME, context->host, &buffer_size);
 
@@ -416,12 +459,15 @@ static void usage_exit (const char *name, int status) /* {{{ */
                        "  -4|-6        force the use of IPv4 or IPv6\n"
                        "  -c count     number of ICMP packets to send\n"
                        "  -i interval  interval with which to send ICMP packets\n"
+                       "  -w timeout   time to wait for replies, in seconds\n"
                        "  -t ttl       time to live for each ICMP packet\n"
                        "  -Q qos       Quality of Service (QoS) of outgoing packets\n"
                        "               Use \"-Q help\" for a list of valid options.\n"
                        "  -I srcaddr   source address\n"
                        "  -D device    outgoing interface name\n"
-                       "  -f filename  filename to read hosts from\n"
+                       "  -m mark      mark to set on outgoing packets\n"
+                       "  -f filename  read hosts from <filename>\n"
+                       "  -O filename  write RTT measurements to <filename>\n"
 #if USE_NCURSES
                        "  -u / -U      force / disable UTF-8 output\n"
                        "  -g graph     graph type to draw\n"
@@ -430,8 +476,8 @@ static void usage_exit (const char *name, int status) /* {{{ */
                        "  -Z percent   Exit with non-zero exit status if more than this percentage of\n"
                        "               probes timed out. (default: never)\n"
 
-                       "\noping "PACKAGE_VERSION", http://verplant.org/liboping/\n"
-                       "by Florian octo Forster <octo@verplant.org>\n"
+                       "\noping "PACKAGE_VERSION", http://noping.cc/\n"
+                       "by Florian octo Forster <ff@octo.it>\n"
                        "for contributions see `AUTHORS'\n",
                        name);
        exit (status);
@@ -631,7 +677,7 @@ static int read_options (int argc, char **argv) /* {{{ */
 
        while (1)
        {
-               optchar = getopt (argc, argv, "46c:hi:I:t:Q:f:D:Z:P:"
+               optchar = getopt (argc, argv, "46c:hi:I:t:Q:f:D:Z:O:P:m:w:b"
 #if USE_NCURSES
                                "uUg:"
 #endif
@@ -684,6 +730,18 @@ static int read_options (int argc, char **argv) /* {{{ */
                                }
                                break;
 
+                       case 'w':
+                               {
+                                       char *endp = NULL;
+                                       double t = strtod (optarg, &endp);
+                                       if ((optarg[0] != 0) && (endp != NULL) && (*endp == 0))
+                                               opt_timeout = t;
+                                       else
+                                               fprintf (stderr, "Ignoring invalid timeout: %s\n",
+                                                               optarg);
+                               }
+                               break;
+
                        case 'I':
                                {
                                        if (opt_srcaddr != NULL)
@@ -696,6 +754,10 @@ static int read_options (int argc, char **argv) /* {{{ */
                                opt_device = optarg;
                                break;
 
+                       case 'm':
+                               opt_mark = optarg;
+                               break;
+
                        case 't':
                        {
                                int new_send_ttl;
@@ -712,6 +774,13 @@ static int read_options (int argc, char **argv) /* {{{ */
                                set_opt_send_qos (optarg);
                                break;
 
+                       case 'O':
+                               {
+                                       free (opt_outfile);
+                                       opt_outfile = strdup (optarg);
+                               }
+                               break;
+
                        case 'P':
                                {
                                        double new_percentile;
@@ -732,9 +801,9 @@ static int read_options (int argc, char **argv) /* {{{ */
                                        opt_show_graph = 0;
                                else if (strcasecmp ("prettyping", optarg) == 0)
                                        opt_show_graph = 1;
-                               else if (strcasecmp ("boxplot", optarg) == 0)
-                                       opt_show_graph = 2;
                                else if (strcasecmp ("histogram", optarg) == 0)
+                                       opt_show_graph = 2;
+                               else if (strcasecmp ("boxplot", optarg) == 0)
                                        opt_show_graph = 3;
                                else
                                        fprintf (stderr, "Unknown graph option: %s\n", optarg);
@@ -747,6 +816,9 @@ static int read_options (int argc, char **argv) /* {{{ */
                                opt_utf8 = 1;
                                break;
 #endif
+                       case 'b':
+                               opt_bell = 1;
+                               break;
 
                        case 'Z':
                        {
@@ -951,7 +1023,7 @@ static int update_graph_boxplot (ping_context_t *ctx) /* {{{ */
 } /* }}} int update_graph_boxplot */
 
 static int update_graph_prettyping (ping_context_t *ctx, /* {{{ */
-               double latency, unsigned int sequence)
+               double latency)
 {
        size_t x;
        size_t x_max;
@@ -962,13 +1034,22 @@ static int update_graph_prettyping (ping_context_t *ctx, /* {{{ */
                return (EINVAL);
        x_max -= 4;
 
+       /* Determine the first index in the history we need to draw
+        * the graph. */
        history_offset = 0;
-       if (((size_t) x_max) < ctx->history_size)
+       if (((size_t) x_max) < ctx->history_size) /* window is smaller than history */
        {
                if (ctx->history_index > x_max)
                        history_offset = ctx->history_index - x_max;
                else /* wrap around */
-                       history_offset = ctx->history_index + x_max - ctx->history_size;
+                       history_offset = ctx->history_index + ctx->history_size - x_max;
+       }
+       else /* window is larger than history */
+       {
+               if (ctx->history_index != ctx->history_size) /* no longer growing. */
+                       history_offset = ctx->history_index;
+               else /* start-up */
+                       history_offset = 0;
        }
 
        for (x = 0; x < x_max; x++)
@@ -989,6 +1070,10 @@ static int update_graph_prettyping (ping_context_t *ctx, /* {{{ */
                index = (history_offset + x) % ctx->history_size;
                latency = ctx->history_by_time[index];
 
+               if (latency < 0) {
+                       continue;
+               }
+
                if (latency >= 0.0)
                {
                        double ratio;
@@ -1160,12 +1245,6 @@ static int update_stats_from_context (ping_context_t *ctx, pingobj_iter_t *iter)
        ping_iterator_get_info (iter, PING_INFO_LATENCY,
                        &latency, &buffer_len);
 
-       unsigned int sequence = 0;
-       buffer_len = sizeof (sequence);
-       ping_iterator_get_info (iter, PING_INFO_SEQUENCE,
-                       &sequence, &buffer_len);
-
-
        if ((ctx == NULL) || (ctx->window == NULL))
                return (EINVAL);
 
@@ -1196,16 +1275,16 @@ static int update_stats_from_context (ping_context_t *ctx, pingobj_iter_t *iter)
                percentile = percentile_to_latency (ctx, opt_percentile);
 
                mvwprintw (ctx->window, /* y = */ 2, /* x = */ 2,
-                               "RTT[ms]: min = %.0f, median = %.0f, p(%.0f) = %.0f, max = %.0f",
+                               "RTT[ms]: min = %.0f, median = %.0f, p(%.0f) = %.0f, max = %.0f  ",
                                min, median, opt_percentile, percentile, max);
        }
 
        if (opt_show_graph == 1)
-               update_graph_prettyping (ctx, latency, sequence);
+               update_graph_prettyping (ctx, latency);
        else if (opt_show_graph == 2)
-               update_graph_boxplot (ctx);
-       else if (opt_show_graph == 3)
                update_graph_histogram (ctx);
+       else if (opt_show_graph == 3)
+               update_graph_boxplot (ctx);
 
        wrefresh (ctx->window);
 
@@ -1245,6 +1324,8 @@ static int on_resize (pingobj_t *ping) /* {{{ */
 
                if (context->window != NULL)
                {
+                        werase (context->window);
+                        wrefresh (context->window);
                        delwin (context->window);
                        context->window = NULL;
                }
@@ -1268,6 +1349,37 @@ static int check_resize (pingobj_t *ping) /* {{{ */
                        break;
                else if (key == KEY_RESIZE)
                        need_resize = 1;
+               else if (key == 'g')
+               {
+                       if (opt_show_graph == 3)
+                               opt_show_graph = 1;
+                       else if (opt_show_graph > 0)
+                               opt_show_graph++;
+               }
+               else if (key == 'a')
+               {
+                       char host[NI_MAXHOST];
+
+                       wprintw (main_win, "New Host: ");
+                       echo ();
+                       wgetnstr (main_win, host, sizeof (host));
+                       noecho ();
+
+                       if (ping_host_add(ping, host) < 0)
+                       {
+                               const char *errmsg = ping_get_error (ping);
+
+                               wprintw (main_win, "Adding host `%s' failed: %s\n", host, errmsg);
+                       }
+                       else
+                       {
+                               /* FIXME - scroll main_win correctly so that old
+                                * data is still visible */
+                               need_resize = 1;
+                               host_num = ping_iterator_count(ping);
+                               ping_initialize_contexts(ping);
+                       }
+               }
        }
 
        if (need_resize)
@@ -1296,10 +1408,11 @@ static int pre_loop_hook (pingobj_t *ping) /* {{{ */
        if (has_colors () == TRUE)
        {
                start_color ();
-               init_pair (OPING_GREEN,  COLOR_GREEN,  /* default = */ 0);
-               init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ 0);
-               init_pair (OPING_RED,    COLOR_RED,    /* default = */ 0);
-               init_pair (OPING_GREEN_HIST,  COLOR_GREEN,  COLOR_BLACK);
+               use_default_colors ();
+               init_pair (OPING_GREEN,  COLOR_GREEN,  /* default = */ -1);
+               init_pair (OPING_YELLOW, COLOR_YELLOW, /* default = */ -1);
+               init_pair (OPING_RED,    COLOR_RED,    /* default = */ -1);
+               init_pair (OPING_GREEN_HIST,  COLOR_GREEN,  -1);
                init_pair (OPING_YELLOW_HIST, COLOR_YELLOW, COLOR_GREEN);
                init_pair (OPING_RED_HIST,    COLOR_RED,    COLOR_YELLOW);
        }
@@ -1474,30 +1587,17 @@ static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
 #if USE_NCURSES
                if (has_colors () == TRUE)
                {
-                       double percentile;
+                       double ratio;
                        int color = OPING_GREEN;
 
-                       percentile = latency_to_percentile (context, latency);
-                       if (percentile < (100.0 * threshold_green))
+                       ratio = latency_to_ratio (context, latency);
+                       if (ratio < threshold_green)
                                color = OPING_GREEN;
-                       else if (percentile < (100.0 * threshold_yellow))
+                       else if (ratio < threshold_yellow)
                                color = OPING_YELLOW;
                        else
                                color = OPING_RED;
 
-#if 0
-                       if ((ratio_this <= threshold_green)
-                                       || ((ratio_prev < threshold_green)
-                                               && (ratio_this > threshold_green)))
-                               color = OPING_GREEN;
-                       else if ((ratio_this <= threshold_yellow)
-                                       || ((ratio_prev < threshold_yellow)
-                                               && (ratio_this > threshold_yellow)))
-                               color = OPING_YELLOW;
-                       else
-                               color = OPING_RED;
-#endif
-
                        HOST_PRINTF ("%zu bytes from %s (%s): icmp_seq=%u ttl=%i ",
                                        data_len, context->host, context->addr,
                                        sequence, recv_ttl,
@@ -1529,6 +1629,13 @@ static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
 #if USE_NCURSES
                }
 #endif
+                if (opt_bell) {
+#if USE_NCURSES
+                       beep();
+#else
+                       HOST_PRINTF ("\a");
+#endif
+                }
        }
        else /* if (!(latency > 0.0)) */
        {
@@ -1554,6 +1661,20 @@ static void update_host_hook (pingobj_iter_t *iter, /* {{{ */
 #endif
        }
 
+       if (outfile != NULL)
+       {
+               struct timeval tv = {0};
+               if (gettimeofday (&tv, NULL) == 0)
+               {
+                       double t = ((double) tv.tv_sec) + (((double) tv.tv_usec) / 1000000.0);
+
+                       if ((sequence % 32) == 0)
+                               fprintf (outfile, "#time,host,latency[ms]\n");
+
+                       fprintf (outfile, "%.3f,\"%s\",%.2f\n", t, context->host, latency);
+               }
+       }
+
 #if USE_NCURSES
        update_stats_from_context (context, iter);
        wrefresh (main_win);
@@ -1647,7 +1768,7 @@ int main (int argc, char **argv) /* {{{ */
        }
 #endif
 
-        setlocale(LC_ALL, "");
+       setlocale(LC_ALL, "");
        optind = read_options (argc, argv);
 
 #if !_POSIX_SAVED_IDS
@@ -1698,6 +1819,12 @@ int main (int argc, char **argv) /* {{{ */
                /* printf ("ts_int = %i.%09li\n", (int) ts_int.tv_sec, ts_int.tv_nsec); */
        }
 
+       if (ping_setopt (ping, PING_OPT_TIMEOUT, (void*)(&opt_timeout)) != 0)
+       {
+               fprintf (stderr, "Setting timeout failed: %s\n",
+                               ping_get_error (ping));
+       }
+
        if (opt_addrfamily != PING_DEF_AF)
                ping_setopt (ping, PING_OPT_AF, (void *) &opt_addrfamily);
 
@@ -1719,6 +1846,24 @@ int main (int argc, char **argv) /* {{{ */
                }
        }
 
+       if (opt_mark != NULL)
+       {
+               char *endp = NULL;
+               int mark = (int) strtol (opt_mark, &endp, /* base = */ 0);
+               if ((opt_mark[0] != 0) && (endp != NULL) && (*endp == 0))
+               {
+                       if (ping_setopt(ping, PING_OPT_MARK, (void*)(&mark)) != 0)
+                       {
+                               fprintf (stderr, "Setting mark failed: %s\n",
+                                       ping_get_error (ping));
+                       }
+               }
+               else
+               {
+                       fprintf(stderr, "Ignoring invalid mark: %s\n", optarg);
+               }
+       }
+
        if (opt_filename != NULL)
        {
                FILE *infile;
@@ -1829,6 +1974,17 @@ int main (int argc, char **argv) /* {{{ */
        saved_set_uid = (uid_t) -1;
 #endif
 
+       if (opt_outfile != NULL)
+       {
+               outfile = fopen (opt_outfile, "a");
+               if (outfile == NULL)
+               {
+                       fprintf (stderr, "opening \"%s\" failed: %s\n",
+                                opt_outfile, strerror (errno));
+                       exit (EXIT_FAILURE);
+               }
+       }
+
        ping_initialize_contexts (ping);
 
        if (i == 0)
@@ -1915,6 +2071,12 @@ int main (int argc, char **argv) /* {{{ */
 
        ping_destroy (ping);
 
+       if (outfile != NULL)
+       {
+               fclose (outfile);
+               outfile = NULL;
+       }
+
        if (status == 0)
                exit (EXIT_SUCCESS);
        else