1/*	$NetBSD: progressmeter.c,v 1.4 2011/07/25 03:03:10 christos Exp $	*/
2/* $OpenBSD: progressmeter.c,v 1.37 2006/08/03 03:34:42 deraadt 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.4 2011/07/25 03:03:10 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
43#define DEFAULT_WINSIZE 80
44#define MAX_WINSIZE 512
45#define PADDING 1		/* padding between the progress indicators */
46#define UPDATE_INTERVAL 1	/* update the progress meter every second */
47#define STALL_TIME 5		/* we're stalled after this many seconds */
48
49/* determines whether we can output to the terminal */
50static int can_output(void);
51
52/* formats and inserts the specified size into the given buffer */
53static void format_size(char *, int, off_t);
54static void format_rate(char *, int, off_t);
55
56/* window resizing */
57static void sig_winch(int);
58static void setscreensize(void);
59
60/* updates the progressmeter to reflect the current state of the transfer */
61void refresh_progress_meter(void);
62
63/* signal handler for updating the progress meter */
64static void update_progress_meter(int);
65
66static time_t start;		/* start progress */
67static time_t last_update;	/* last progress update */
68static char *file;		/* name of the file being transferred */
69static off_t end_pos;		/* ending position of transfer */
70static off_t cur_pos;		/* transfer position as of last refresh */
71static off_t last_pos;
72static off_t max_delta_pos = 0;
73static volatile off_t *counter;	/* progress counter */
74static long stalled;		/* how long we have been stalled */
75static int bytes_per_second;	/* current speed in bytes per second */
76static int win_size;		/* terminal window size */
77static volatile sig_atomic_t win_resized; /* for window resizing */
78
79/* units for format_size */
80static const char unit[] = " KMGT";
81
82static int
83can_output(void)
84{
85	return (getpgrp() == tcgetpgrp(STDOUT_FILENO));
86}
87
88static void
89format_rate(char *buf, int size, off_t bytes)
90{
91	int i;
92
93	bytes *= 100;
94	for (i = 0; bytes >= 100*1000 && unit[i] != 'T'; i++)
95		bytes = (bytes + 512) / 1024;
96	if (i == 0) {
97		i++;
98		bytes = (bytes + 512) / 1024;
99	}
100	snprintf(buf, size, "%3lld.%1lld%c%s",
101	    (long long) (bytes + 5) / 100,
102	    (long long) (bytes + 5) / 10 % 10,
103	    unit[i],
104	    i ? "B" : " ");
105}
106
107static void
108format_size(char *buf, int size, off_t bytes)
109{
110	int i;
111
112	for (i = 0; bytes >= 10000 && unit[i] != 'T'; i++)
113		bytes = (bytes + 512) / 1024;
114	snprintf(buf, size, "%4lld%c%s",
115	    (long long) bytes,
116	    unit[i],
117	    i ? "B" : " ");
118}
119
120void
121refresh_progress_meter(void)
122{
123	char buf[MAX_WINSIZE + 1];
124	time_t now;
125	off_t transferred;
126	double elapsed;
127	int percent;
128	off_t bytes_left;
129	int cur_speed;
130	int hours, minutes, seconds;
131	int i, len;
132	int file_len;
133	off_t delta_pos;
134
135	transferred = *counter - cur_pos;
136	cur_pos = *counter;
137	now = time(NULL);
138	bytes_left = end_pos - cur_pos;
139
140	delta_pos = cur_pos - last_pos;
141	if (delta_pos > max_delta_pos)
142		max_delta_pos = delta_pos;
143
144	if (bytes_left > 0)
145		elapsed = now - last_update;
146	else {
147		elapsed = now - start;
148		/* Calculate true total speed when done */
149		transferred = end_pos;
150		bytes_per_second = 0;
151	}
152
153	/* calculate speed */
154	if (elapsed != 0)
155		cur_speed = (transferred / elapsed);
156	else
157		cur_speed = transferred;
158
159#define AGE_FACTOR 0.9
160	if (bytes_per_second != 0) {
161		bytes_per_second = (bytes_per_second * AGE_FACTOR) +
162		    (cur_speed * (1.0 - AGE_FACTOR));
163	} else
164		bytes_per_second = cur_speed;
165
166	/* filename */
167	buf[0] = '\0';
168	file_len = win_size - 45;
169	if (file_len > 0) {
170		len = snprintf(buf, file_len + 1, "\r%s", file);
171		if (len < 0)
172			len = 0;
173		if (len >= file_len + 1)
174			len = file_len;
175		for (i = len; i < file_len; i++)
176			buf[i] = ' ';
177		buf[file_len] = '\0';
178	}
179
180	/* percent of transfer done */
181	if (end_pos != 0)
182		percent = ((float)cur_pos / end_pos) * 100;
183	else
184		percent = 100;
185	snprintf(buf + strlen(buf), win_size - strlen(buf) - 8,
186	    " %3d%% ", percent);
187
188	/* amount transferred */
189	format_size(buf + strlen(buf), win_size - strlen(buf),
190	    cur_pos);
191	strlcat(buf, " ", win_size);
192
193	/* bandwidth usage */
194	format_rate(buf + strlen(buf), win_size - strlen(buf),
195	    (off_t)bytes_per_second);
196	strlcat(buf, "/s ", win_size);
197
198	/* instantaneous rate */
199	if (bytes_left > 0)
200		format_rate(buf + strlen(buf), win_size - strlen(buf),
201			    delta_pos);
202	else
203		format_rate(buf + strlen(buf), win_size - strlen(buf),
204			    max_delta_pos);
205	strlcat(buf, "/s ", win_size);
206
207	/* ETA */
208	if (!transferred)
209		stalled += elapsed;
210	else
211		stalled = 0;
212
213	if (stalled >= STALL_TIME)
214		strlcat(buf, "- stalled -", win_size);
215	else if (bytes_per_second == 0 && bytes_left)
216		strlcat(buf, "  --:-- ETA", win_size);
217	else {
218		if (bytes_left > 0)
219			seconds = bytes_left / bytes_per_second;
220		else
221			seconds = elapsed;
222
223		hours = seconds / 3600;
224		seconds -= hours * 3600;
225		minutes = seconds / 60;
226		seconds -= minutes * 60;
227
228		if (hours != 0)
229			snprintf(buf + strlen(buf), win_size - strlen(buf),
230			    "%d:%02d:%02d", hours, minutes, seconds);
231		else
232			snprintf(buf + strlen(buf), win_size - strlen(buf),
233			    "  %02d:%02d", minutes, seconds);
234
235		if (bytes_left > 0)
236			strlcat(buf, " ETA", win_size);
237		else
238			strlcat(buf, "    ", win_size);
239	}
240
241	atomicio(vwrite, STDOUT_FILENO, buf, win_size - 1);
242	last_update = now;
243	last_pos = cur_pos;
244}
245
246/*ARGSUSED*/
247static void
248update_progress_meter(int ignore)
249{
250	int save_errno;
251
252	save_errno = errno;
253
254	if (win_resized) {
255		setscreensize();
256		win_resized = 0;
257	}
258	if (can_output())
259		refresh_progress_meter();
260
261	signal(SIGALRM, update_progress_meter);
262	alarm(UPDATE_INTERVAL);
263	errno = save_errno;
264}
265
266void
267start_progress_meter(char *f, off_t filesize, off_t *ctr)
268{
269	start = last_update = time(NULL);
270	file = f;
271	end_pos = filesize;
272	cur_pos = 0;
273	counter = ctr;
274	stalled = 0;
275	bytes_per_second = 0;
276
277	setscreensize();
278	if (can_output())
279		refresh_progress_meter();
280
281	signal(SIGALRM, update_progress_meter);
282	signal(SIGWINCH, sig_winch);
283	alarm(UPDATE_INTERVAL);
284}
285
286void
287stop_progress_meter(void)
288{
289	alarm(0);
290
291	if (!can_output())
292		return;
293
294	/* Ensure we complete the progress */
295	if (cur_pos != end_pos)
296		refresh_progress_meter();
297
298	atomicio(vwrite, STDOUT_FILENO, __UNCONST("\n"), 1);
299}
300
301/*ARGSUSED*/
302static void
303sig_winch(int sig)
304{
305	win_resized = 1;
306}
307
308static void
309setscreensize(void)
310{
311	struct winsize winsize;
312
313	if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &winsize) != -1 &&
314	    winsize.ws_col != 0) {
315		if (winsize.ws_col > MAX_WINSIZE)
316			win_size = MAX_WINSIZE;
317		else
318			win_size = winsize.ws_col;
319	} else
320		win_size = DEFAULT_WINSIZE;
321	win_size += 1;					/* trailing \0 */
322}
323