xref: /netbsd-src/usr.bin/progress/progress.c (revision 8b0f9554ff8762542c4defc4f70e1eb76fb508fa)
1 /*	$NetBSD: progress.c,v 1.15 2007/06/06 17:49:14 briggs Exp $ */
2 
3 /*-
4  * Copyright (c) 2003 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by John Hawkinson.
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. Neither the name of The NetBSD Foundation nor the names of its
19  *    contributors may be used to endorse or promote products derived
20  *    from this software without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
23  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
24  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
25  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
26  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGE.
33  */
34 
35 #include <sys/cdefs.h>
36 #ifndef lint
37 __RCSID("$NetBSD: progress.c,v 1.15 2007/06/06 17:49:14 briggs Exp $");
38 #endif				/* not lint */
39 
40 #include <sys/types.h>
41 #include <sys/param.h>
42 #include <sys/socket.h>
43 #include <sys/ioctl.h>
44 #include <sys/time.h>
45 #include <sys/wait.h>
46 #include <netinet/in.h>
47 #include <arpa/ftp.h>
48 
49 #include <err.h>
50 #include <errno.h>
51 #include <fcntl.h>
52 #include <glob.h>
53 #include <signal.h>
54 #include <inttypes.h>
55 #include <limits.h>
56 #include <netdb.h>
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #include <termios.h>
61 #include <time.h>
62 #include <tzfile.h>
63 #include <unistd.h>
64 
65 #define GLOBAL			/* force GLOBAL decls in progressbar.h to be
66 				 * declared */
67 #include "progressbar.h"
68 
69 static void usage(void);
70 int main(int, char *[]);
71 
72 static void
73 usage(void)
74 {
75 	fprintf(stderr,
76 	    "usage: %s [-ez] [-b buffersize] [-f file] [-l length]\n"
77 	    "       %*.s [-p prefix] cmd [args...]\n",
78 	    getprogname(), (int) strlen(getprogname()), "");
79 	exit(EXIT_FAILURE);
80 }
81 
82 
83 int
84 main(int argc, char *argv[])
85 {
86 	char *fb_buf;
87 	char *infile = NULL;
88 	pid_t pid = 0, gzippid = 0, deadpid;
89 	int ch, fd, outpipe[2];
90 	int ws, gzipstat, cmdstat;
91 	int eflag = 0, lflag = 0, zflag = 0;
92 	ssize_t nr, nw, off;
93 	size_t buffersize;
94 	struct stat statb;
95 	struct ttysize ts;
96 
97 	setprogname(argv[0]);
98 
99 	/* defaults: Read from stdin, 0 filesize (no completion estimate) */
100 	fd = STDIN_FILENO;
101 	filesize = 0;
102 	buffersize = 64 * 1024;
103 	prefix = NULL;
104 
105 	while ((ch = getopt(argc, argv, "b:ef:l:p:z")) != -1)
106 		switch (ch) {
107 		case 'b':
108 			buffersize = (size_t) strsuftoll("buffer size", optarg,
109 			    0, SIZE_T_MAX);
110 			break;
111 		case 'e':
112 			eflag++;
113 			break;
114 		case 'f':
115 			infile = optarg;
116 			break;
117 		case 'l':
118 			lflag++;
119 			filesize = strsuftoll("input size", optarg, 0,
120 			    LLONG_MAX);
121 			break;
122 		case 'p':
123 			prefix = optarg;
124 			break;
125 		case 'z':
126 			zflag++;
127 			break;
128 		case '?':
129 		default:
130 			usage();
131 			/* NOTREACHED */
132 		}
133 	argc -= optind;
134 	argv += optind;
135 
136 	if (argc < 1)
137 		usage();
138 
139 	if (infile && (fd = open(infile, O_RDONLY, 0)) < 0)
140 		err(1, "%s", infile);
141 
142 	/* stat() to get the filesize unless overridden, or -z */
143 	if (!zflag && !lflag && (fstat(fd, &statb) == 0)) {
144 		if (S_ISFIFO(statb.st_mode)) {
145 			/* stat(2) on pipe may return only the
146 			 * first few bytes with more coming.
147 			 * Don't trust!
148 			 */
149 		} else {
150 			filesize = statb.st_size;
151 		}
152 	}
153 
154 	/* gzip -l the file if we have the name and -z is given */
155 	if (zflag && !lflag && infile != NULL) {
156 		FILE *gzipsizepipe;
157 		char buf[256], *cp, *cmd;
158 
159 		/*
160 		 * Read second word of last line of gzip -l output. Looks like:
161 		 * % gzip -l ../etc.tgz
162 		 *   compressed uncompressed  ratio uncompressed_name
163 		 * 	 119737       696320  82.8% ../etc.tar
164 		 */
165 
166 		asprintf(&cmd, "gzip -l %s", infile);
167 		if ((gzipsizepipe = popen(cmd, "r")) == NULL)
168 			err(1, "reading compressed file length");
169 		for (; fgets(buf, 256, gzipsizepipe) != NULL;)
170 		    continue;
171 		strtoimax(buf, &cp, 10);
172 		filesize = strtoimax(cp, NULL, 10);
173 		if (pclose(gzipsizepipe) < 0)
174 			err(1, "closing compressed file length pipe");
175 		free(cmd);
176 	}
177 	/* Pipe input through gzip -dc if -z is given */
178 	if (zflag) {
179 		int gzippipe[2];
180 
181 		if (pipe(gzippipe) < 0)
182 			err(1, "gzip pipe");
183 		gzippid = fork();
184 		if (gzippid < 0)
185 			err(1, "fork for gzip");
186 
187 		if (gzippid) {
188 			/* parent */
189 			dup2(gzippipe[0], fd);
190 			close(gzippipe[0]);
191 			close(gzippipe[1]);
192 		} else {
193 			dup2(gzippipe[1], STDOUT_FILENO);
194 			dup2(fd, STDIN_FILENO);
195 			close(gzippipe[0]);
196 			close(gzippipe[1]);
197 			if (execlp("gzip", "gzip", "-dc", NULL))
198 				err(1, "exec()ing gzip");
199 		}
200 	}
201 
202 	/* Initialize progressbar.c's global state */
203 	bytes = 0;
204 	progress = 1;
205 	ttyout = eflag ? stderr : stdout;
206 
207 	if (ioctl(fileno(ttyout), TIOCGSIZE, &ts) == -1)
208 		ttywidth = 80;
209 	else
210 		ttywidth = ts.ts_cols;
211 
212 	fb_buf = malloc(buffersize);
213 	if (fb_buf == NULL)
214 		err(1, "malloc for buffersize");
215 
216 	if (pipe(outpipe) < 0)
217 		err(1, "output pipe");
218 	pid = fork();
219 	if (pid < 0)
220 		err(1, "fork for output pipe");
221 
222 	if (pid == 0) {
223 		/* child */
224 		dup2(outpipe[0], STDIN_FILENO);
225 		close(outpipe[0]);
226 		close(outpipe[1]);
227 		execvp(argv[0], argv);
228 		err(1, "could not exec %s", argv[0]);
229 	}
230 	close(outpipe[0]);
231 
232 	progressmeter(-1);
233 	while ((nr = read(fd, fb_buf, buffersize)) > 0)
234 		for (off = 0; nr; nr -= nw, off += nw, bytes += nw)
235 			if ((nw = write(outpipe[1], fb_buf + off,
236 			    (size_t) nr)) < 0)
237 				err(1, "writing %u bytes to output pipe",
238 							(unsigned) nr);
239 	close(outpipe[1]);
240 
241 	gzipstat = 0;
242 	cmdstat = 0;
243 	while (pid || gzippid) {
244 		deadpid = wait(&ws);
245 		/*
246 		 * We need to exit with an error if the command (or gzip)
247 		 * exited abnormally.
248 		 * Unfortunately we can't generate a true 'exited by signal'
249 		 * error without sending the signal to ourselves :-(
250 		 */
251 		ws = WIFSIGNALED(ws) ? WTERMSIG(ws) : WEXITSTATUS(ws);
252 
253 		if (deadpid != -1 && errno == EINTR)
254 			continue;
255 		if (deadpid == pid) {
256 			pid = 0;
257 			cmdstat = ws;
258 			continue;
259 		}
260 		if (deadpid == gzippid) {
261 			gzippid = 0;
262 			gzipstat = ws;
263 			continue;
264 		}
265 		break;
266 	}
267 
268 	progressmeter(1);
269 
270 	free(fb_buf);
271 
272 	exit(cmdstat ? cmdstat : gzipstat);
273 }
274