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