xref: /netbsd-src/bin/dd/dd.c (revision 3b01aba77a7a698587faaae455bbfe740923c1f5)
1 /*	$NetBSD: dd.c,v 1.20 2001/04/28 22:47:23 ross Exp $	*/
2 
3 /*-
4  * Copyright (c) 1991, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Keith Muller of the University of California, San Diego and Lance
9  * Visser of Convex Computer Corporation.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. All advertising materials mentioning features or use of this software
20  *    must display the following acknowledgement:
21  *	This product includes software developed by the University of
22  *	California, Berkeley and its contributors.
23  * 4. Neither the name of the University nor the names of its contributors
24  *    may be used to endorse or promote products derived from this software
25  *    without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37  * SUCH DAMAGE.
38  */
39 
40 #include <sys/cdefs.h>
41 #ifndef lint
42 __COPYRIGHT("@(#) Copyright (c) 1991, 1993, 1994\n\
43 	The Regents of the University of California.  All rights reserved.\n");
44 #endif /* not lint */
45 
46 #ifndef lint
47 #if 0
48 static char sccsid[] = "@(#)dd.c	8.5 (Berkeley) 4/2/94";
49 #else
50 __RCSID("$NetBSD: dd.c,v 1.20 2001/04/28 22:47:23 ross Exp $");
51 #endif
52 #endif /* not lint */
53 
54 #include <sys/param.h>
55 #include <sys/stat.h>
56 #include <sys/ioctl.h>
57 #include <sys/mtio.h>
58 #include <sys/time.h>
59 
60 #include <ctype.h>
61 #include <err.h>
62 #include <errno.h>
63 #include <fcntl.h>
64 #include <signal.h>
65 #include <stdio.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <unistd.h>
69 
70 #include "dd.h"
71 #include "extern.h"
72 
73 static void dd_close __P((void));
74 static void dd_in __P((void));
75 static void getfdtype __P((IO *));
76 static void setup __P((void));
77 
78 int main __P((int, char *[]));
79 
80 IO	in, out;		/* input/output state */
81 STAT	st;			/* statistics */
82 void	(*cfunc) __P((void));	/* conversion function */
83 u_long	cpy_cnt;		/* # of blocks to copy */
84 u_int	ddflags;		/* conversion options */
85 u_int	cbsz;			/* conversion block size */
86 u_int	files_cnt = 1;		/* # of files to copy */
87 int	progress = 0;		/* display sign of life */
88 const u_char	*ctab;		/* conversion table */
89 sigset_t infoset;			/* a set blocking SIGINFO */
90 
91 int
92 main(argc, argv)
93 	int argc;
94 	char *argv[];
95 {
96 	int ch;
97 
98 	while ((ch = getopt(argc, argv, "")) != -1) {
99 		switch (ch) {
100 		default:
101 			errx(EXIT_FAILURE, "usage: dd [operand ...]");
102 			/* NOTREACHED */
103 		}
104 	}
105 	argc -= (optind - 1);
106 	argv += (optind - 1);
107 
108 	jcl(argv);
109 	setup();
110 
111 	(void)signal(SIGINFO, summaryx);
112 	(void)signal(SIGINT, terminate);
113 	(void)sigemptyset(&infoset);
114 	(void)sigaddset(&infoset, SIGINFO);
115 
116 	(void)atexit(summary);
117 
118 	while (files_cnt--)
119 		dd_in();
120 
121 	dd_close();
122 	exit(0);
123 	/* NOTREACHED */
124 }
125 
126 static void
127 setup()
128 {
129 	u_int cnt;
130 
131 	if (in.name == NULL) {
132 		in.name = "stdin";
133 		in.fd = STDIN_FILENO;
134 	} else {
135 		in.fd = open(in.name, O_RDONLY, 0);
136 		if (in.fd < 0)
137 			err(1, "%s", in.name);
138 	}
139 
140 	getfdtype(&in);
141 
142 	if (files_cnt > 1 && !(in.flags & ISTAPE))
143 		errx(1, "files is not supported for non-tape devices");
144 
145 	if (out.name == NULL) {
146 		/* No way to check for read access here. */
147 		out.fd = STDOUT_FILENO;
148 		out.name = "stdout";
149 	} else {
150 #define	OFLAGS \
151     (O_CREAT | (ddflags & (C_SEEK | C_NOTRUNC) ? 0 : O_TRUNC))
152 		out.fd = open(out.name, O_RDWR | OFLAGS, DEFFILEMODE);
153 		/*
154 		 * May not have read access, so try again with write only.
155 		 * Without read we may have a problem if output also does
156 		 * not support seeks.
157 		 */
158 		if (out.fd < 0) {
159 			out.fd = open(out.name, O_WRONLY | OFLAGS, DEFFILEMODE);
160 			out.flags |= NOREAD;
161 		}
162 		if (out.fd < 0)
163 			err(1, "%s", out.name);
164 	}
165 
166 	getfdtype(&out);
167 
168 	/*
169 	 * Allocate space for the input and output buffers.  If not doing
170 	 * record oriented I/O, only need a single buffer.
171 	 */
172 	if (!(ddflags & (C_BLOCK|C_UNBLOCK))) {
173 		if ((in.db = malloc(out.dbsz + in.dbsz - 1)) == NULL)
174 			err(1, NULL);
175 		out.db = in.db;
176 	} else if ((in.db =
177 	    malloc((u_int)(MAX(in.dbsz, cbsz) + cbsz))) == NULL ||
178 	    (out.db = malloc((u_int)(out.dbsz + cbsz))) == NULL)
179 		err(1, NULL);
180 	in.dbp = in.db;
181 	out.dbp = out.db;
182 
183 	/* Position the input/output streams. */
184 	if (in.offset)
185 		pos_in();
186 	if (out.offset)
187 		pos_out();
188 
189 	/*
190 	 * Truncate the output file; ignore errors because it fails on some
191 	 * kinds of output files, tapes, for example.
192 	 */
193 	if ((ddflags & (C_OF | C_SEEK | C_NOTRUNC)) == (C_OF | C_SEEK))
194 		(void)ftruncate(out.fd, (off_t)out.offset * out.dbsz);
195 
196 	/*
197 	 * If converting case at the same time as another conversion, build a
198 	 * table that does both at once.  If just converting case, use the
199 	 * built-in tables.
200 	 */
201 	if (ddflags & (C_LCASE|C_UCASE)) {
202 #ifdef	NO_CONV
203 		/* Should not get here, but just in case... */
204 		errx(1, "case conv and -DNO_CONV");
205 #else	/* NO_CONV */
206 		if (ddflags & C_ASCII || ddflags & C_EBCDIC) {
207 			if (ddflags & C_LCASE) {
208 				for (cnt = 0; cnt < 0377; ++cnt)
209 					casetab[cnt] = tolower(ctab[cnt]);
210 			} else {
211 				for (cnt = 0; cnt < 0377; ++cnt)
212 					casetab[cnt] = toupper(ctab[cnt]);
213 			}
214 		} else {
215 			if (ddflags & C_LCASE) {
216 				for (cnt = 0; cnt < 0377; ++cnt)
217 					casetab[cnt] = tolower(cnt);
218 			} else {
219 				for (cnt = 0; cnt < 0377; ++cnt)
220 					casetab[cnt] = toupper(cnt);
221 			}
222 		}
223 
224 		ctab = casetab;
225 #endif	/* NO_CONV */
226 	}
227 
228 	(void)gettimeofday(&st.start, NULL);	/* Statistics timestamp. */
229 }
230 
231 static void
232 getfdtype(io)
233 	IO *io;
234 {
235 	struct mtget mt;
236 	struct stat sb;
237 
238 	if (fstat(io->fd, &sb))
239 		err(1, "%s", io->name);
240 	if (S_ISCHR(sb.st_mode))
241 		io->flags |= ioctl(io->fd, MTIOCGET, &mt) ? ISCHR : ISTAPE;
242 	else if (lseek(io->fd, (off_t)0, SEEK_CUR) == -1 && errno == ESPIPE)
243 		io->flags |= ISPIPE;		/* XXX fixed in 4.4BSD */
244 }
245 
246 static void
247 dd_in()
248 {
249 	int flags, n;
250 
251 	for (flags = ddflags;;) {
252 		if (cpy_cnt && (st.in_full + st.in_part) >= cpy_cnt)
253 			return;
254 
255 		/*
256 		 * Clear the buffer first if doing "sync" on input.
257 		 * If doing block operations use spaces.  This will
258 		 * affect not only the C_NOERROR case, but also the
259 		 * last partial input block which should be padded
260 		 * with zero and not garbage.
261 		 */
262 		if (flags & C_SYNC) {
263 			if (flags & (C_BLOCK|C_UNBLOCK))
264 				(void)memset(in.dbp, ' ', in.dbsz);
265 			else
266 				(void)memset(in.dbp, 0, in.dbsz);
267 		}
268 
269 		n = read(in.fd, in.dbp, in.dbsz);
270 		if (n == 0) {
271 			in.dbrcnt = 0;
272 			return;
273 		}
274 
275 		/* Read error. */
276 		if (n < 0) {
277 			/*
278 			 * If noerror not specified, die.  POSIX requires that
279 			 * the warning message be followed by an I/O display.
280 			 */
281 			if (!(flags & C_NOERROR))
282 				err(1, "%s", in.name);
283 			warn("%s", in.name);
284 			summary();
285 
286 			/*
287 			 * If it's not a tape drive or a pipe, seek past the
288 			 * error.  If your OS doesn't do the right thing for
289 			 * raw disks this section should be modified to re-read
290 			 * in sector size chunks.
291 			 */
292 			if (!(in.flags & (ISPIPE|ISTAPE)) &&
293 			    lseek(in.fd, (off_t)in.dbsz, SEEK_CUR))
294 				warn("%s", in.name);
295 
296 			/* If sync not specified, omit block and continue. */
297 			if (!(ddflags & C_SYNC))
298 				continue;
299 
300 			/* Read errors count as full blocks. */
301 			in.dbcnt += in.dbrcnt = in.dbsz;
302 			++st.in_full;
303 
304 		/* Handle full input blocks. */
305 		} else if (n == in.dbsz) {
306 			in.dbcnt += in.dbrcnt = n;
307 			++st.in_full;
308 
309 		/* Handle partial input blocks. */
310 		} else {
311 			/* If sync, use the entire block. */
312 			if (ddflags & C_SYNC)
313 				in.dbcnt += in.dbrcnt = in.dbsz;
314 			else
315 				in.dbcnt += in.dbrcnt = n;
316 			++st.in_part;
317 		}
318 
319 		/*
320 		 * POSIX states that if bs is set and no other conversions
321 		 * than noerror, notrunc or sync are specified, the block
322 		 * is output without buffering as it is read.
323 		 */
324 		if (ddflags & C_BS) {
325 			out.dbcnt = in.dbcnt;
326 			dd_out(1);
327 			in.dbcnt = 0;
328 			continue;
329 		}
330 
331 		if (ddflags & C_SWAB) {
332 			if ((n = in.dbrcnt) & 1) {
333 				++st.swab;
334 				--n;
335 			}
336 			swab(in.dbp, in.dbp, n);
337 		}
338 
339 		in.dbp += in.dbrcnt;
340 		(*cfunc)();
341 	}
342 }
343 
344 /*
345  * Cleanup any remaining I/O and flush output.  If necesssary, output file
346  * is truncated.
347  */
348 static void
349 dd_close()
350 {
351 	if (cfunc == def)
352 		def_close();
353 	else if (cfunc == block)
354 		block_close();
355 	else if (cfunc == unblock)
356 		unblock_close();
357 	if (ddflags & C_OSYNC && out.dbcnt < out.dbsz) {
358 		(void)memset(out.dbp, 0, out.dbsz - out.dbcnt);
359 		out.dbcnt = out.dbsz;
360 	}
361 	if (out.dbcnt)
362 		dd_out(1);
363 }
364 
365 void
366 dd_out(force)
367 	int force;
368 {
369 	static int warned;
370 	int cnt, n, nw;
371 	u_char *outp;
372 
373 	/*
374 	 * Write one or more blocks out.  The common case is writing a full
375 	 * output block in a single write; increment the full block stats.
376 	 * Otherwise, we're into partial block writes.  If a partial write,
377 	 * and it's a character device, just warn.  If a tape device, quit.
378 	 *
379 	 * The partial writes represent two cases.  1: Where the input block
380 	 * was less than expected so the output block was less than expected.
381 	 * 2: Where the input block was the right size but we were forced to
382 	 * write the block in multiple chunks.  The original versions of dd(1)
383 	 * never wrote a block in more than a single write, so the latter case
384 	 * never happened.
385 	 *
386 	 * One special case is if we're forced to do the write -- in that case
387 	 * we play games with the buffer size, and it's usually a partial write.
388 	 */
389 	outp = out.db;
390 	for (n = force ? out.dbcnt : out.dbsz;; n = out.dbsz) {
391 		for (cnt = n;; cnt -= nw) {
392 			nw = bwrite(out.fd, outp, cnt);
393 			if (nw <= 0) {
394 				if (nw == 0)
395 					errx(1, "%s: end of device", out.name);
396 				if (errno != EINTR)
397 					err(1, "%s", out.name);
398 				nw = 0;
399 			}
400 			outp += nw;
401 			st.bytes += nw;
402 			if (nw == n) {
403 				if (n != out.dbsz)
404 					++st.out_part;
405 				else
406 					++st.out_full;
407 				break;
408 			}
409 			++st.out_part;
410 			if (nw == cnt)
411 				break;
412 			if (out.flags & ISCHR && !warned) {
413 				warned = 1;
414 				warnx("%s: short write on character device",
415 				    out.name);
416 			}
417 			if (out.flags & ISTAPE)
418 				errx(1, "%s: short write on tape device", out.name);
419 		}
420 		if ((out.dbcnt -= n) < out.dbsz)
421 			break;
422 	}
423 
424 	/* Reassemble the output block. */
425 	if (out.dbcnt)
426 		(void)memmove(out.db, out.dbp - out.dbcnt, out.dbcnt);
427 	out.dbp = out.db + out.dbcnt;
428 
429 	if (progress)
430 		(void)write(STDERR_FILENO, ".", 1);
431 }
432 
433 /*
434  * A protected against SIGINFO write
435  */
436 ssize_t
437 bwrite(fd, buf, len)
438 	int fd;
439 	const void *buf;
440 	size_t len;
441 {
442 	sigset_t oset;
443 	ssize_t rv;
444 	int oerrno;
445 
446 	(void)sigprocmask(SIG_BLOCK, &infoset, &oset);
447 	rv = write(fd, buf, len);
448 	oerrno = errno;
449 	(void)sigprocmask(SIG_SETMASK, &oset, NULL);
450 	errno = oerrno;
451 	return rv;
452 }
453