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