xref: /netbsd-src/usr.bin/ftp/progressbar.c (revision 23c8222edbfb0f0932d88a8351d3a0cf817dfb9e)
1 /*	$NetBSD: progressbar.c,v 1.5 2004/03/09 17:04:24 hubertf Exp $	*/
2 
3 /*-
4  * Copyright (c) 1997-2003 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Luke Mewburn.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the NetBSD
21  *	Foundation, Inc. and its contributors.
22  * 4. Neither the name of The NetBSD Foundation nor the names of its
23  *    contributors may be used to endorse or promote products derived
24  *    from this software without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36  * POSSIBILITY OF SUCH DAMAGE.
37  */
38 
39 #include <sys/cdefs.h>
40 #ifndef lint
41 __RCSID("$NetBSD: progressbar.c,v 1.5 2004/03/09 17:04:24 hubertf Exp $");
42 #endif /* not lint */
43 
44 /*
45  * FTP User Program -- Misc support routines
46  */
47 #include <sys/types.h>
48 #include <sys/param.h>
49 
50 #include <err.h>
51 #include <errno.h>
52 #include <signal.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <time.h>
57 #include <tzfile.h>
58 #include <unistd.h>
59 
60 #include "progressbar.h"
61 
62 #if !defined(NO_PROGRESS)
63 /*
64  * return non-zero if we're the current foreground process
65  */
66 int
67 foregroundproc(void)
68 {
69 	static pid_t pgrp = -1;
70 
71 	if (pgrp == -1)
72 		pgrp = getpgrp();
73 
74 	return (tcgetpgrp(fileno(ttyout)) == pgrp);
75 }
76 #endif	/* !defined(NO_PROGRESS) */
77 
78 
79 #ifndef	NO_PROGRESS
80 static void updateprogressmeter(int);
81 
82 /*
83  * SIGALRM handler to update the progress meter
84  */
85 static void
86 updateprogressmeter(int dummy)
87 {
88 	int oerrno = errno;
89 
90 	progressmeter(0);
91 	errno = oerrno;
92 }
93 #endif	/* NO_PROGRESS */
94 
95 
96 /*
97  * List of order of magnitude prefixes.
98  * The last is `P', as 2^64 = 16384 Petabytes
99  */
100 static const char prefixes[] = " KMGTP";
101 
102 /*
103  * Display a transfer progress bar if progress is non-zero.
104  * SIGALRM is hijacked for use by this function.
105  * - Before the transfer, set filesize to size of file (or -1 if unknown),
106  *   and call with flag = -1. This starts the once per second timer,
107  *   and a call to updateprogressmeter() upon SIGALRM.
108  * - During the transfer, updateprogressmeter will call progressmeter
109  *   with flag = 0
110  * - After the transfer, call with flag = 1
111  */
112 static struct timeval start;
113 static struct timeval lastupdate;
114 
115 #define	BUFLEFT	(sizeof(buf) - len)
116 
117 void
118 progressmeter(int flag)
119 {
120 	static off_t lastsize;
121 	off_t cursize;
122 	struct timeval now, wait;
123 #ifndef NO_PROGRESS
124 	struct timeval td;
125 	off_t abbrevsize, bytespersec;
126 	double elapsed;
127 	int ratio, barlength, i, len, remaining;
128 
129 			/*
130 			 * Work variables for progress bar.
131 			 *
132 			 * XXX:	if the format of the progress bar changes
133 			 *	(especially the number of characters in the
134 			 *	`static' portion of it), be sure to update
135 			 *	these appropriately.
136 			 */
137 	char		buf[256];	/* workspace for progress bar */
138 #define	BAROVERHEAD	43		/* non `*' portion of progress bar */
139 					/*
140 					 * stars should contain at least
141 					 * sizeof(buf) - BAROVERHEAD entries
142 					 */
143 	static const char	stars[] =
144 "*****************************************************************************"
145 "*****************************************************************************"
146 "*****************************************************************************";
147 
148 #endif
149 
150 	if (flag == -1) {
151 		(void)gettimeofday(&start, NULL);
152 		lastupdate = start;
153 		lastsize = restart_point;
154 	}
155 
156 	(void)gettimeofday(&now, NULL);
157 	cursize = bytes + restart_point;
158 	timersub(&now, &lastupdate, &wait);
159 	if (cursize > lastsize) {
160 		lastupdate = now;
161 		lastsize = cursize;
162 		wait.tv_sec = 0;
163 	} else {
164 #ifndef STANDALONE_PROGRESS
165 		if (quit_time > 0 && wait.tv_sec > quit_time) {
166 			len = snprintf(buf, sizeof(buf), "\r\n%s: "
167 			    "transfer aborted because stalled for %lu sec.\r\n",
168 			    getprogname(), (unsigned long)wait.tv_sec);
169 			(void)write(fileno(ttyout), buf, len);
170 			(void)xsignal(SIGALRM, SIG_DFL);
171 			alarmtimer(0);
172 			siglongjmp(toplevel, 1);
173 		}
174 #endif	/* !STANDALONE_PROGRESS */
175 	}
176 	/*
177 	 * Always set the handler even if we are not the foreground process.
178 	 */
179 #ifdef STANDALONE_PROGRESS
180 	if (progress) {
181 #else
182 	if (quit_time > 0 || progress) {
183 #endif /* !STANDALONE_PROGRESS */
184 		if (flag == -1) {
185 			(void)xsignal_restart(SIGALRM, updateprogressmeter, 1);
186 			alarmtimer(1);		/* set alarm timer for 1 Hz */
187 		} else if (flag == 1) {
188 			(void)xsignal(SIGALRM, SIG_DFL);
189 			alarmtimer(0);
190 		}
191 	}
192 #ifndef NO_PROGRESS
193 	if (!progress)
194 		return;
195 	len = 0;
196 
197 	/*
198 	 * print progress bar only if we are foreground process.
199 	 */
200 	if (! foregroundproc())
201 		return;
202 
203 	len += snprintf(buf + len, BUFLEFT, "\r");
204 	if (prefix)
205 	  len += snprintf(buf + len, BUFLEFT, "%s", prefix);
206 	if (filesize > 0) {
207 		ratio = (int)((double)cursize * 100.0 / (double)filesize);
208 		ratio = MAX(ratio, 0);
209 		ratio = MIN(ratio, 100);
210 		len += snprintf(buf + len, BUFLEFT, "%3d%% ", ratio);
211 
212 			/*
213 			 * calculate the length of the `*' bar, ensuring that
214 			 * the number of stars won't exceed the buffer size
215 			 */
216 		barlength = MIN(sizeof(buf) - 1, ttywidth) - BAROVERHEAD;
217 		if (prefix)
218 		  	barlength -= strlen(prefix);
219 		if (barlength > 0) {
220 			i = barlength * ratio / 100;
221 			len += snprintf(buf + len, BUFLEFT,
222 			    "|%.*s%*s|", i, stars, barlength - i, "");
223 		}
224 	}
225 
226 	abbrevsize = cursize;
227 	for (i = 0; abbrevsize >= 100000 && i < sizeof(prefixes); i++)
228 		abbrevsize >>= 10;
229 	len += snprintf(buf + len, BUFLEFT, " " LLFP("5") " %c%c ",
230 	    (LLT)abbrevsize,
231 	    prefixes[i],
232 	    i == 0 ? ' ' : 'B');
233 
234 	timersub(&now, &start, &td);
235 	elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
236 
237 	bytespersec = 0;
238 	if (bytes > 0) {
239 		bytespersec = bytes;
240 		if (elapsed > 0.0)
241 			bytespersec /= elapsed;
242 	}
243 	for (i = 1; bytespersec >= 1024000 && i < sizeof(prefixes); i++)
244 		bytespersec >>= 10;
245 	len += snprintf(buf + len, BUFLEFT,
246 	    " " LLFP("3") ".%02d %cB/s ",
247 	    (LLT)(bytespersec / 1024),
248 	    (int)((bytespersec % 1024) * 100 / 1024),
249 	    prefixes[i]);
250 
251 	if (filesize > 0) {
252 		if (bytes <= 0 || elapsed <= 0.0 || cursize > filesize) {
253 			len += snprintf(buf + len, BUFLEFT, "   --:-- ETA");
254 		} else if (wait.tv_sec >= STALLTIME) {
255 			len += snprintf(buf + len, BUFLEFT, " - stalled -");
256 		} else {
257 			remaining = (int)
258 			    ((filesize - restart_point) / (bytes / elapsed) -
259 			    elapsed);
260 			if (remaining >= 100 * SECSPERHOUR)
261 				len += snprintf(buf + len, BUFLEFT,
262 				    "   --:-- ETA");
263 			else {
264 				i = remaining / SECSPERHOUR;
265 				if (i)
266 					len += snprintf(buf + len, BUFLEFT,
267 					    "%2d:", i);
268 				else
269 					len += snprintf(buf + len, BUFLEFT,
270 					    "   ");
271 				i = remaining % SECSPERHOUR;
272 				len += snprintf(buf + len, BUFLEFT,
273 				    "%02d:%02d ETA", i / 60, i % 60);
274 			}
275 		}
276 	}
277 	if (flag == 1)
278 		len += snprintf(buf + len, BUFLEFT, "\n");
279 	(void)write(fileno(ttyout), buf, len);
280 
281 #endif	/* !NO_PROGRESS */
282 }
283 
284 #ifndef STANDALONE_PROGRESS
285 /*
286  * Display transfer statistics.
287  * Requires start to be initialised by progressmeter(-1),
288  * direction to be defined by xfer routines, and filesize and bytes
289  * to be updated by xfer routines
290  * If siginfo is nonzero, an ETA is displayed, and the output goes to stderr
291  * instead of ttyout.
292  */
293 void
294 ptransfer(int siginfo)
295 {
296 	struct timeval now, td, wait;
297 	double elapsed;
298 	off_t bytespersec;
299 	int remaining, hh, i, len;
300 
301 	char buf[256];		/* Work variable for transfer status. */
302 
303 	if (!verbose && !progress && !siginfo)
304 		return;
305 
306 	(void)gettimeofday(&now, NULL);
307 	timersub(&now, &start, &td);
308 	elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
309 	bytespersec = 0;
310 	if (bytes > 0) {
311 		bytespersec = bytes;
312 		if (elapsed > 0.0)
313 			bytespersec /= elapsed;
314 	}
315 	len = 0;
316 	len += snprintf(buf + len, BUFLEFT, LLF " byte%s %s in ",
317 	    (LLT)bytes, bytes == 1 ? "" : "s", direction);
318 	remaining = (int)elapsed;
319 	if (remaining > SECSPERDAY) {
320 		int days;
321 
322 		days = remaining / SECSPERDAY;
323 		remaining %= SECSPERDAY;
324 		len += snprintf(buf + len, BUFLEFT,
325 		    "%d day%s ", days, days == 1 ? "" : "s");
326 	}
327 	hh = remaining / SECSPERHOUR;
328 	remaining %= SECSPERHOUR;
329 	if (hh)
330 		len += snprintf(buf + len, BUFLEFT, "%2d:", hh);
331 	len += snprintf(buf + len, BUFLEFT,
332 	    "%02d:%02d ", remaining / 60, remaining % 60);
333 
334 	for (i = 1; bytespersec >= 1024000 && i < sizeof(prefixes); i++)
335 		bytespersec >>= 10;
336 	len += snprintf(buf + len, BUFLEFT, "(" LLF ".%02d %cB/s)",
337 	    (LLT)(bytespersec / 1024),
338 	    (int)((bytespersec % 1024) * 100 / 1024),
339 	    prefixes[i]);
340 
341 	if (siginfo && bytes > 0 && elapsed > 0.0 && filesize >= 0
342 	    && bytes + restart_point <= filesize) {
343 		remaining = (int)((filesize - restart_point) /
344 				  (bytes / elapsed) - elapsed);
345 		hh = remaining / SECSPERHOUR;
346 		remaining %= SECSPERHOUR;
347 		len += snprintf(buf + len, BUFLEFT, "  ETA: ");
348 		if (hh)
349 			len += snprintf(buf + len, BUFLEFT, "%2d:", hh);
350 		len += snprintf(buf + len, BUFLEFT, "%02d:%02d",
351 		    remaining / 60, remaining % 60);
352 		timersub(&now, &lastupdate, &wait);
353 		if (wait.tv_sec >= STALLTIME)
354 			len += snprintf(buf + len, BUFLEFT, "  (stalled)");
355 	}
356 	len += snprintf(buf + len, BUFLEFT, "\n");
357 	(void)write(siginfo ? STDERR_FILENO : fileno(ttyout), buf, len);
358 }
359 
360 /*
361  * SIG{INFO,QUIT} handler to print transfer stats if a transfer is in progress
362  */
363 void
364 psummary(int notused)
365 {
366 	int oerrno = errno;
367 
368 	if (bytes > 0) {
369 		if (fromatty)
370 			write(fileno(ttyout), "\n", 1);
371 		ptransfer(1);
372 	}
373 	errno = oerrno;
374 }
375 #endif	/* !STANDALONE_PROGRESS */
376 
377 
378 /*
379  * Set the SIGALRM interval timer for wait seconds, 0 to disable.
380  */
381 void
382 alarmtimer(int wait)
383 {
384 	struct itimerval itv;
385 
386 	itv.it_value.tv_sec = wait;
387 	itv.it_value.tv_usec = 0;
388 	itv.it_interval = itv.it_value;
389 	setitimer(ITIMER_REAL, &itv, NULL);
390 }
391 
392 
393 /*
394  * Install a POSIX signal handler, allowing the invoker to set whether
395  * the signal should be restartable or not
396  */
397 sigfunc
398 xsignal_restart(int sig, sigfunc func, int restartable)
399 {
400 	struct sigaction act, oact;
401 	act.sa_handler = func;
402 
403 	sigemptyset(&act.sa_mask);
404 #if defined(SA_RESTART)			/* 4.4BSD, Posix(?), SVR4 */
405 	act.sa_flags = restartable ? SA_RESTART : 0;
406 #elif defined(SA_INTERRUPT)		/* SunOS 4.x */
407 	act.sa_flags = restartable ? 0 : SA_INTERRUPT;
408 #else
409 #error "system must have SA_RESTART or SA_INTERRUPT"
410 #endif
411 	if (sigaction(sig, &act, &oact) < 0)
412 		return (SIG_ERR);
413 	return (oact.sa_handler);
414 }
415 
416 /*
417  * Install a signal handler with the `restartable' flag set dependent upon
418  * which signal is being set. (This is a wrapper to xsignal_restart())
419  */
420 sigfunc
421 xsignal(int sig, sigfunc func)
422 {
423 	int restartable;
424 
425 	/*
426 	 * Some signals print output or change the state of the process.
427 	 * There should be restartable, so that reads and writes are
428 	 * not affected.  Some signals should cause program flow to change;
429 	 * these signals should not be restartable, so that the system call
430 	 * will return with EINTR, and the program will go do something
431 	 * different.  If the signal handler calls longjmp() or siglongjmp(),
432 	 * it doesn't matter if it's restartable.
433 	 */
434 
435 	switch(sig) {
436 #ifdef SIGINFO
437 	case SIGINFO:
438 #endif
439 	case SIGQUIT:
440 	case SIGUSR1:
441 	case SIGUSR2:
442 	case SIGWINCH:
443 		restartable = 1;
444 		break;
445 
446 	case SIGALRM:
447 	case SIGINT:
448 	case SIGPIPE:
449 		restartable = 0;
450 		break;
451 
452 	default:
453 		/*
454 		 * This is unpleasant, but I don't know what would be better.
455 		 * Right now, this "can't happen"
456 		 */
457 		errx(1, "xsignal_restart called with signal %d", sig);
458 	}
459 
460 	return(xsignal_restart(sig, func, restartable));
461 }
462