xref: /freebsd/crypto/openssh/progressmeter.c (revision f126890ac5386406dadf7c4cfa9566cbb56537c5)
1 /* $OpenBSD: progressmeter.c,v 1.53 2023/04/12 14:22:04 jsg 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 <stdarg.h>
36 #include <stdlib.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 #include "utf8.h"
46 
47 #define DEFAULT_WINSIZE 80
48 #define MAX_WINSIZE 512
49 #define PADDING 1		/* padding between the progress indicators */
50 #define UPDATE_INTERVAL 1	/* update the progress meter every second */
51 #define STALL_TIME 5		/* we're stalled after this many seconds */
52 
53 /* determines whether we can output to the terminal */
54 static int can_output(void);
55 
56 /* window resizing */
57 static void sig_winch(int);
58 static void setscreensize(void);
59 
60 /* signal handler for updating the progress meter */
61 static void sig_alarm(int);
62 
63 static double start;		/* start progress */
64 static double last_update;	/* last progress update */
65 static const char *file;	/* name of the file being transferred */
66 static off_t start_pos;		/* initial position of transfer */
67 static off_t end_pos;		/* ending position of transfer */
68 static off_t cur_pos;		/* transfer position as of last refresh */
69 static volatile off_t *counter;	/* progress counter */
70 static long stalled;		/* how long we have been stalled */
71 static int bytes_per_second;	/* current speed in bytes per second */
72 static int win_size;		/* terminal window size */
73 static volatile sig_atomic_t win_resized; /* for window resizing */
74 static volatile sig_atomic_t alarm_fired;
75 
76 /* units for format_size */
77 static const char unit[] = " KMGT";
78 
79 static int
80 can_output(void)
81 {
82 	return (getpgrp() == tcgetpgrp(STDOUT_FILENO));
83 }
84 
85 /* size needed to format integer type v, using (nbits(v) * log2(10) / 10) */
86 #define STRING_SIZE(v) (((sizeof(v) * 8 * 4) / 10) + 1)
87 
88 static const char *
89 format_rate(off_t bytes)
90 {
91 	int i;
92 	static char buf[STRING_SIZE(bytes) * 2 + 16];
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, sizeof(buf), "%3lld.%1lld%c%s",
102 	    (long long) (bytes + 5) / 100,
103 	    (long long) (bytes + 5) / 10 % 10,
104 	    unit[i],
105 	    i ? "B" : " ");
106 	return buf;
107 }
108 
109 static const char *
110 format_size(off_t bytes)
111 {
112 	int i;
113 	static char buf[STRING_SIZE(bytes) + 16];
114 
115 	for (i = 0; bytes >= 10000 && unit[i] != 'T'; i++)
116 		bytes = (bytes + 512) / 1024;
117 	snprintf(buf, sizeof(buf), "%4lld%c%s",
118 	    (long long) bytes,
119 	    unit[i],
120 	    i ? "B" : " ");
121 	return buf;
122 }
123 
124 void
125 refresh_progress_meter(int force_update)
126 {
127 	char *buf = NULL, *obuf = NULL;
128 	off_t transferred;
129 	double elapsed, now;
130 	int percent;
131 	off_t bytes_left;
132 	int cur_speed;
133 	int hours, minutes, seconds;
134 	int file_len, cols;
135 
136 	if ((!force_update && !alarm_fired && !win_resized) || !can_output())
137 		return;
138 	alarm_fired = 0;
139 
140 	if (win_resized) {
141 		setscreensize();
142 		win_resized = 0;
143 	}
144 
145 	transferred = *counter - (cur_pos ? cur_pos : start_pos);
146 	cur_pos = *counter;
147 	now = monotime_double();
148 	bytes_left = end_pos - cur_pos;
149 
150 	if (bytes_left > 0)
151 		elapsed = now - last_update;
152 	else {
153 		elapsed = now - start;
154 		/* Calculate true total speed when done */
155 		transferred = end_pos - start_pos;
156 		bytes_per_second = 0;
157 	}
158 
159 	/* calculate speed */
160 	if (elapsed != 0)
161 		cur_speed = (transferred / elapsed);
162 	else
163 		cur_speed = transferred;
164 
165 #define AGE_FACTOR 0.9
166 	if (bytes_per_second != 0) {
167 		bytes_per_second = (bytes_per_second * AGE_FACTOR) +
168 		    (cur_speed * (1.0 - AGE_FACTOR));
169 	} else
170 		bytes_per_second = cur_speed;
171 
172 	last_update = now;
173 
174 	/* Don't bother if we can't even display the completion percentage */
175 	if (win_size < 4)
176 		return;
177 
178 	/* filename */
179 	file_len = cols = win_size - 36;
180 	if (file_len > 0) {
181 		asmprintf(&buf, INT_MAX, &cols, "%-*s", file_len, file);
182 		/* If we used fewer columns than expected then pad */
183 		if (cols < file_len)
184 			xextendf(&buf, NULL, "%*s", file_len - cols, "");
185 	}
186 	/* percent of transfer done */
187 	if (end_pos == 0 || cur_pos == end_pos)
188 		percent = 100;
189 	else
190 		percent = ((float)cur_pos / end_pos) * 100;
191 
192 	/* percent / amount transferred / bandwidth usage */
193 	xextendf(&buf, NULL, " %3d%% %s %s/s ", percent, format_size(cur_pos),
194 	    format_rate((off_t)bytes_per_second));
195 
196 	/* ETA */
197 	if (!transferred)
198 		stalled += elapsed;
199 	else
200 		stalled = 0;
201 
202 	if (stalled >= STALL_TIME)
203 		xextendf(&buf, NULL, "- stalled -");
204 	else if (bytes_per_second == 0 && bytes_left)
205 		xextendf(&buf, NULL, "  --:-- ETA");
206 	else {
207 		if (bytes_left > 0)
208 			seconds = bytes_left / bytes_per_second;
209 		else
210 			seconds = elapsed;
211 
212 		hours = seconds / 3600;
213 		seconds -= hours * 3600;
214 		minutes = seconds / 60;
215 		seconds -= minutes * 60;
216 
217 		if (hours != 0) {
218 			xextendf(&buf, NULL, "%d:%02d:%02d",
219 			    hours, minutes, seconds);
220 		} else
221 			xextendf(&buf, NULL, "  %02d:%02d", minutes, seconds);
222 
223 		if (bytes_left > 0)
224 			xextendf(&buf, NULL, " ETA");
225 		else
226 			xextendf(&buf, NULL, "    ");
227 	}
228 
229 	/* Finally, truncate string at window width */
230 	cols = win_size - 1;
231 	asmprintf(&obuf, INT_MAX, &cols, " %s", buf);
232 	if (obuf != NULL) {
233 		*obuf = '\r'; /* must insert as asmprintf() would escape it */
234 		atomicio(vwrite, STDOUT_FILENO, obuf, strlen(obuf));
235 	}
236 	free(buf);
237 	free(obuf);
238 }
239 
240 static void
241 sig_alarm(int ignore)
242 {
243 	alarm_fired = 1;
244 	alarm(UPDATE_INTERVAL);
245 }
246 
247 void
248 start_progress_meter(const char *f, off_t filesize, off_t *ctr)
249 {
250 	start = last_update = monotime_double();
251 	file = f;
252 	start_pos = *ctr;
253 	end_pos = filesize;
254 	cur_pos = 0;
255 	counter = ctr;
256 	stalled = 0;
257 	bytes_per_second = 0;
258 
259 	setscreensize();
260 	refresh_progress_meter(1);
261 
262 	ssh_signal(SIGALRM, sig_alarm);
263 	ssh_signal(SIGWINCH, sig_winch);
264 	alarm(UPDATE_INTERVAL);
265 }
266 
267 void
268 stop_progress_meter(void)
269 {
270 	alarm(0);
271 
272 	if (!can_output())
273 		return;
274 
275 	/* Ensure we complete the progress */
276 	if (cur_pos != end_pos)
277 		refresh_progress_meter(1);
278 
279 	atomicio(vwrite, STDOUT_FILENO, "\n", 1);
280 }
281 
282 static void
283 sig_winch(int sig)
284 {
285 	win_resized = 1;
286 }
287 
288 static void
289 setscreensize(void)
290 {
291 	struct winsize winsize;
292 
293 	if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &winsize) != -1 &&
294 	    winsize.ws_col != 0) {
295 		if (winsize.ws_col > MAX_WINSIZE)
296 			win_size = MAX_WINSIZE;
297 		else
298 			win_size = winsize.ws_col;
299 	} else
300 		win_size = DEFAULT_WINSIZE;
301 	win_size += 1;					/* trailing \0 */
302 }
303