1 /*
   2  * Copyright (c) 2003 Nils Nordman.  All rights reserved.
   3  *
   4  * Redistribution and use in source and binary forms, with or without
   5  * modification, are permitted provided that the following conditions
   6  * are met:
   7  * 1. Redistributions of source code must retain the above copyright
   8  *    notice, this list of conditions and the following disclaimer.
   9  * 2. Redistributions in binary form must reproduce the above copyright
  10  *    notice, this list of conditions and the following disclaimer in the
  11  *    documentation and/or other materials provided with the distribution.
  12  *
  13  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  14  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  15  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  16  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  17  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  18  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  19  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  20  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  21  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  22  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  23  */
  24 
  25 /* $OpenBSD: progressmeter.c,v 1.37 2006/08/03 03:34:42 deraadt Exp $ */
  26 
  27 #pragma ident   "%Z%%M% %I%     %E% SMI"
  28 
  29 #include "includes.h"
  30 
  31 #include <sys/types.h>
  32 #include <sys/ioctl.h>
  33 #include <sys/uio.h>
  34 
  35 #include <errno.h>
  36 #include <signal.h>
  37 #include <stdio.h>
  38 #include <string.h>
  39 #include <time.h>
  40 #include <unistd.h>
  41 
  42 #include "progressmeter.h"
  43 #include "atomicio.h"
  44 #include "misc.h"
  45 
  46 #define DEFAULT_WINSIZE 80
  47 #define MAX_WINSIZE 512
  48 #define PADDING 1               /* padding between the progress indicators */
  49 #define UPDATE_INTERVAL 1       /* update the progress meter every second */
  50 #define STALL_TIME 5            /* we're stalled after this many seconds */
  51 
  52 /* determines whether we can output to the terminal */
  53 static int can_output(void);
  54 
  55 /* formats and inserts the specified size into the given buffer */
  56 static void format_size(char *, int, off_t);
  57 static void format_rate(char *, int, off_t);
  58 
  59 /* window resizing */
  60 static void sig_winch(int);
  61 static void setscreensize(void);
  62 
  63 /* updates the progressmeter to reflect the current state of the transfer */
  64 void refresh_progress_meter(void);
  65 
  66 /* signal handler for updating the progress meter */
  67 static void update_progress_meter(int);
  68 
  69 static time_t start;            /* start progress */
  70 static time_t last_update;      /* last progress update */
  71 static char *file;              /* name of the file being transferred */
  72 static off_t end_pos;           /* ending position of transfer */
  73 static off_t cur_pos;           /* transfer position as of last refresh */
  74 static volatile off_t *counter; /* progress counter */
  75 static long stalled;            /* how long we have been stalled */
  76 static int bytes_per_second;    /* current speed in bytes per second */
  77 static int win_size;            /* terminal window size */
  78 static volatile sig_atomic_t win_resized; /* for window resizing */
  79 
  80 /* units for format_size */
  81 static const char unit[] = " KMGT";
  82 
  83 static int
  84 can_output(void)
  85 {
  86         return (getpgrp() == tcgetpgrp(STDOUT_FILENO));
  87 }
  88 
  89 static void
  90 format_rate(char *buf, int size, off_t bytes)
  91 {
  92         int i;
  93 
  94         bytes *= 100;
  95         for (i = 0; bytes >= 100*1000 && unit[i] != 'T'; i++)
  96                 bytes = (bytes + 512) / 1024;
  97         if (i == 0) {
  98                 i++;
  99                 bytes = (bytes + 512) / 1024;
 100         }
 101         snprintf(buf, size, "%3lld.%1lld%c%s",
 102             (long long) (bytes + 5) / 100,
 103             (long long) (bytes + 5) / 10 % 10,
 104             unit[i],
 105             i ? "B" : " ");
 106 }
 107 
 108 static void
 109 format_size(char *buf, int size, off_t bytes)
 110 {
 111         int i;
 112 
 113         for (i = 0; bytes >= 10000 && unit[i] != 'T'; i++)
 114                 bytes = (bytes + 512) / 1024;
 115         snprintf(buf, size, "%4lld%c%s",
 116             (long long) bytes,
 117             unit[i],
 118             i ? "B" : " ");
 119 }
 120 
 121 void
 122 refresh_progress_meter(void)
 123 {
 124         char buf[MAX_WINSIZE + 1];
 125         time_t now;
 126         off_t transferred;
 127         double elapsed;
 128         int percent;
 129         off_t bytes_left;
 130         int cur_speed;
 131         int hours, minutes, seconds;
 132         int i, len;
 133         int file_len;
 134 
 135         transferred = *counter - cur_pos;
 136         cur_pos = *counter;
 137         now = time(NULL);
 138         bytes_left = end_pos - cur_pos;
 139 
 140         if (bytes_left > 0)
 141                 elapsed = now - last_update;
 142         else {
 143                 elapsed = now - start;
 144                 /* Calculate true total speed when done */
 145                 transferred = end_pos;
 146                 bytes_per_second = 0;
 147         }
 148 
 149         /* calculate speed */
 150         if (elapsed != 0)
 151                 cur_speed = (int)(transferred / elapsed);
 152         else
 153                 cur_speed = transferred;
 154 
 155 #define AGE_FACTOR 0.9
 156         if (bytes_per_second != 0) {
 157                 bytes_per_second = (int)((bytes_per_second * AGE_FACTOR) +
 158                     (cur_speed * (1.0 - AGE_FACTOR)));
 159         } else
 160                 bytes_per_second = cur_speed;
 161 
 162         /* filename */
 163         buf[0] = '\0';
 164         file_len = win_size - 35;
 165         if (file_len > 0) {
 166                 len = snprintf(buf, file_len + 1, "\r%s", file);
 167                 if (len < 0)
 168                         len = 0;
 169                 if (len >= file_len + 1)
 170                         len = file_len;
 171                 for (i = len; i < file_len; i++)
 172                         buf[i] = ' ';
 173                 buf[file_len] = '\0';
 174         }
 175 
 176         /* percent of transfer done */
 177         if (end_pos != 0)
 178                 percent = (int)(((float)cur_pos / end_pos) * 100);
 179         else
 180                 percent = 100;
 181         snprintf(buf + strlen(buf), win_size - strlen(buf),
 182             " %3d%% ", percent);
 183 
 184         /* amount transferred */
 185         format_size(buf + strlen(buf), win_size - strlen(buf),
 186             cur_pos);
 187         strlcat(buf, " ", win_size);
 188 
 189         /* bandwidth usage */
 190         format_rate(buf + strlen(buf), win_size - strlen(buf),
 191             (off_t)bytes_per_second);
 192         strlcat(buf, "/s ", win_size);
 193 
 194         /* ETA */
 195         if (!transferred)
 196                 stalled += elapsed;
 197         else
 198                 stalled = 0;
 199 
 200         if (stalled >= STALL_TIME)
 201                 strlcat(buf, "- stalled -", win_size);
 202         else if (bytes_per_second == 0 && bytes_left)
 203                 strlcat(buf, "  --:-- ETA", win_size);
 204         else {
 205                 if (bytes_left > 0)
 206                         seconds = bytes_left / bytes_per_second;
 207                 else
 208                         seconds = (int)elapsed;
 209 
 210                 hours = seconds / 3600;
 211                 seconds -= hours * 3600;
 212                 minutes = seconds / 60;
 213                 seconds -= minutes * 60;
 214 
 215                 if (hours != 0)
 216                         snprintf(buf + strlen(buf), win_size - strlen(buf),
 217                             "%d:%02d:%02d", hours, minutes, seconds);
 218                 else
 219                         snprintf(buf + strlen(buf), win_size - strlen(buf),
 220                             "  %02d:%02d", minutes, seconds);
 221 
 222                 if (bytes_left > 0)
 223                         strlcat(buf, " ETA", win_size);
 224                 else
 225                         strlcat(buf, "    ", win_size);
 226         }
 227 
 228         atomicio(vwrite, STDOUT_FILENO, buf, win_size - 1);
 229         last_update = now;
 230 }
 231 
 232 /*ARGSUSED*/
 233 static void
 234 update_progress_meter(int ignore)
 235 {
 236         int save_errno;
 237 
 238         save_errno = errno;
 239 
 240         if (win_resized) {
 241                 setscreensize();
 242                 win_resized = 0;
 243         }
 244         if (can_output())
 245                 refresh_progress_meter();
 246 
 247         signal(SIGALRM, update_progress_meter);
 248         alarm(UPDATE_INTERVAL);
 249         errno = save_errno;
 250 }
 251 
 252 void
 253 start_progress_meter(char *f, off_t filesize, off_t *ctr)
 254 {
 255         start = last_update = time(NULL);
 256         file = f;
 257         end_pos = filesize;
 258         cur_pos = 0;
 259         counter = ctr;
 260         stalled = 0;
 261         bytes_per_second = 0;
 262 
 263         setscreensize();
 264         if (can_output())
 265                 refresh_progress_meter();
 266 
 267         signal(SIGALRM, update_progress_meter);
 268         signal(SIGWINCH, sig_winch);
 269         alarm(UPDATE_INTERVAL);
 270 }
 271 
 272 void
 273 stop_progress_meter(void)
 274 {
 275         alarm(0);
 276 
 277         if (!can_output())
 278                 return;
 279 
 280         /* Ensure we complete the progress */
 281         if (cur_pos != end_pos)
 282                 refresh_progress_meter();
 283 
 284         atomicio(vwrite, STDOUT_FILENO, "\n", 1);
 285 }
 286 
 287 /*ARGSUSED*/
 288 static void
 289 sig_winch(int sig)
 290 {
 291         win_resized = 1;
 292 }
 293 
 294 static void
 295 setscreensize(void)
 296 {
 297         struct winsize winsize;
 298 
 299         if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &winsize) != -1 &&
 300             winsize.ws_col != 0) {
 301                 if (winsize.ws_col > MAX_WINSIZE)
 302                         win_size = MAX_WINSIZE;
 303                 else
 304                         win_size = winsize.ws_col;
 305         } else
 306                 win_size = DEFAULT_WINSIZE;
 307         win_size += 1;                                  /* trailing \0 */
 308 }