Home | History | Annotate | Line # | Download | only in dd
dd.c revision 1.42.10.1
      1 /*	$NetBSD: dd.c,v 1.42.10.1 2012/02/24 06:59:43 matt 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. Neither the name of the University nor the names of its contributors
     20  *    may be used to endorse or promote products derived from this software
     21  *    without specific prior written permission.
     22  *
     23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     33  * SUCH DAMAGE.
     34  */
     35 
     36 #include <sys/cdefs.h>
     37 #ifndef lint
     38 __COPYRIGHT("@(#) Copyright (c) 1991, 1993, 1994\
     39  The Regents of the University of California.  All rights reserved.");
     40 #endif /* not lint */
     41 
     42 #ifndef lint
     43 #if 0
     44 static char sccsid[] = "@(#)dd.c	8.5 (Berkeley) 4/2/94";
     45 #else
     46 __RCSID("$NetBSD: dd.c,v 1.42.10.1 2012/02/24 06:59:43 matt Exp $");
     47 #endif
     48 #endif /* not lint */
     49 
     50 #include <sys/param.h>
     51 #include <sys/stat.h>
     52 #include <sys/ioctl.h>
     53 #include <sys/mtio.h>
     54 #include <sys/time.h>
     55 
     56 #include <ctype.h>
     57 #include <err.h>
     58 #include <errno.h>
     59 #include <fcntl.h>
     60 #include <locale.h>
     61 #include <signal.h>
     62 #include <stdio.h>
     63 #include <stdlib.h>
     64 #include <string.h>
     65 #include <unistd.h>
     66 
     67 #include "dd.h"
     68 #include "extern.h"
     69 
     70 static void dd_close(void);
     71 static void dd_in(void);
     72 static void getfdtype(IO *);
     73 static int redup_clean_fd(int);
     74 static void setup(void);
     75 
     76 int main(int, char *[]);
     77 
     78 IO		in, out;		/* input/output state */
     79 STAT		st;			/* statistics */
     80 void		(*cfunc)(void);		/* conversion function */
     81 uint64_t	cpy_cnt;		/* # of blocks to copy */
     82 static off_t	pending = 0;		/* pending seek if sparse */
     83 u_int		ddflags;		/* conversion options */
     84 uint64_t	cbsz;			/* conversion block size */
     85 u_int		files_cnt = 1;		/* # of files to copy */
     86 uint64_t	progress = 0;		/* display sign of life */
     87 const u_char	*ctab;			/* conversion table */
     88 sigset_t	infoset;		/* a set blocking SIGINFO */
     89 const char	*msgfmt = "posix";	/* default summary() message format */
     90 
     91 int
     92 main(int argc, char *argv[])
     93 {
     94 	int ch;
     95 
     96 	setprogname(argv[0]);
     97 	(void)setlocale(LC_ALL, "");
     98 
     99 	while ((ch = getopt(argc, argv, "")) != -1) {
    100 		switch (ch) {
    101 		default:
    102 			errx(EXIT_FAILURE, "usage: dd [operand ...]");
    103 			/* NOTREACHED */
    104 		}
    105 	}
    106 	argc -= (optind - 1);
    107 	argv += (optind - 1);
    108 
    109 	jcl(argv);
    110 	setup();
    111 
    112 	(void)signal(SIGINFO, summaryx);
    113 	(void)signal(SIGINT, terminate);
    114 	(void)sigemptyset(&infoset);
    115 	(void)sigaddset(&infoset, SIGINFO);
    116 
    117 	(void)atexit(summary);
    118 
    119 	while (files_cnt--)
    120 		dd_in();
    121 
    122 	dd_close();
    123 	exit(0);
    124 	/* NOTREACHED */
    125 }
    126 
    127 static void
    128 setup(void)
    129 {
    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(EXIT_FAILURE, "%s", in.name);
    138 			/* NOTREACHED */
    139 
    140 		/* Ensure in.fd is outside the stdio descriptor range */
    141 		in.fd = redup_clean_fd(in.fd);
    142 	}
    143 
    144 	getfdtype(&in);
    145 
    146 	if (files_cnt > 1 && !(in.flags & ISTAPE)) {
    147 		errx(EXIT_FAILURE, "files is not supported for non-tape devices");
    148 		/* NOTREACHED */
    149 	}
    150 
    151 	if (out.name == NULL) {
    152 		/* No way to check for read access here. */
    153 		out.fd = STDOUT_FILENO;
    154 		out.name = "stdout";
    155 	} else {
    156 #define	OFLAGS \
    157     (O_CREAT | (ddflags & (C_SEEK | C_NOTRUNC) ? 0 : O_TRUNC))
    158 		out.fd = open(out.name, O_RDWR | OFLAGS, DEFFILEMODE);
    159 		/*
    160 		 * May not have read access, so try again with write only.
    161 		 * Without read we may have a problem if output also does
    162 		 * not support seeks.
    163 		 */
    164 		if (out.fd < 0) {
    165 			out.fd = open(out.name, O_WRONLY | OFLAGS, DEFFILEMODE);
    166 			out.flags |= NOREAD;
    167 		}
    168 		if (out.fd < 0) {
    169 			err(EXIT_FAILURE, "%s", out.name);
    170 			/* NOTREACHED */
    171 		}
    172 
    173 		/* Ensure out.fd is outside the stdio descriptor range */
    174 		out.fd = redup_clean_fd(out.fd);
    175 	}
    176 
    177 	getfdtype(&out);
    178 
    179 	/*
    180 	 * Allocate space for the input and output buffers.  If not doing
    181 	 * record oriented I/O, only need a single buffer.
    182 	 */
    183 	if (!(ddflags & (C_BLOCK|C_UNBLOCK))) {
    184 		size_t dbsz = out.dbsz;
    185 		if (!(ddflags & C_BS))
    186 			dbsz += in.dbsz - 1;
    187 		if ((in.db = malloc(dbsz)) == NULL) {
    188 			err(EXIT_FAILURE, NULL);
    189 			/* NOTREACHED */
    190 		}
    191 		out.db = in.db;
    192 	} else if ((in.db =
    193 	    malloc((u_int)(MAX(in.dbsz, cbsz) + cbsz))) == NULL ||
    194 	    (out.db = malloc((u_int)(out.dbsz + cbsz))) == NULL) {
    195 		err(EXIT_FAILURE, NULL);
    196 		/* NOTREACHED */
    197 	}
    198 	in.dbp = in.db;
    199 	out.dbp = out.db;
    200 
    201 	/* Position the input/output streams. */
    202 	if (in.offset)
    203 		pos_in();
    204 	if (out.offset)
    205 		pos_out();
    206 
    207 	/*
    208 	 * Truncate the output file; ignore errors because it fails on some
    209 	 * kinds of output files, tapes, for example.
    210 	 */
    211 	if ((ddflags & (C_OF | C_SEEK | C_NOTRUNC)) == (C_OF | C_SEEK))
    212 		(void)ftruncate(out.fd, (off_t)out.offset * out.dbsz);
    213 
    214 	/*
    215 	 * If converting case at the same time as another conversion, build a
    216 	 * table that does both at once.  If just converting case, use the
    217 	 * built-in tables.
    218 	 */
    219 	if (ddflags & (C_LCASE|C_UCASE)) {
    220 #ifdef	NO_CONV
    221 		/* Should not get here, but just in case... */
    222 		errx(EXIT_FAILURE, "case conv and -DNO_CONV");
    223 		/* NOTREACHED */
    224 #else	/* NO_CONV */
    225 		u_int cnt;
    226 
    227 		if (ddflags & C_ASCII || ddflags & C_EBCDIC) {
    228 			if (ddflags & C_LCASE) {
    229 				for (cnt = 0; cnt < 256; ++cnt)
    230 					casetab[cnt] = tolower(ctab[cnt]);
    231 			} else {
    232 				for (cnt = 0; cnt < 256; ++cnt)
    233 					casetab[cnt] = toupper(ctab[cnt]);
    234 			}
    235 		} else {
    236 			if (ddflags & C_LCASE) {
    237 				for (cnt = 0; cnt < 256; ++cnt)
    238 					casetab[cnt] = tolower(cnt);
    239 			} else {
    240 				for (cnt = 0; cnt < 256; ++cnt)
    241 					casetab[cnt] = toupper(cnt);
    242 			}
    243 		}
    244 
    245 		ctab = casetab;
    246 #endif	/* NO_CONV */
    247 	}
    248 
    249 	(void)gettimeofday(&st.start, NULL);	/* Statistics timestamp. */
    250 }
    251 
    252 static void
    253 getfdtype(IO *io)
    254 {
    255 	struct mtget mt;
    256 	struct stat sb;
    257 
    258 	if (fstat(io->fd, &sb)) {
    259 		err(EXIT_FAILURE, "%s", io->name);
    260 		/* NOTREACHED */
    261 	}
    262 	if (S_ISCHR(sb.st_mode))
    263 		io->flags |= ioctl(io->fd, MTIOCGET, &mt) ? ISCHR : ISTAPE;
    264 	else if (lseek(io->fd, (off_t)0, SEEK_CUR) == -1 && errno == ESPIPE)
    265 		io->flags |= ISPIPE;		/* XXX fixed in 4.4BSD */
    266 }
    267 
    268 /*
    269  * Move the parameter file descriptor to a descriptor that is outside the
    270  * stdio descriptor range, if necessary.  This is required to avoid
    271  * accidentally outputting completion or error messages into the
    272  * output file that were intended for the tty.
    273  */
    274 static int
    275 redup_clean_fd(int fd)
    276 {
    277 	int newfd;
    278 
    279 	if (fd != STDIN_FILENO && fd != STDOUT_FILENO &&
    280 	    fd != STDERR_FILENO)
    281 		/* File descriptor is ok, return immediately. */
    282 		return fd;
    283 
    284 	/*
    285 	 * 3 is the first descriptor greater than STD*_FILENO.  Any
    286 	 * free descriptor valued 3 or above is acceptable...
    287 	 */
    288 	newfd = fcntl(fd, F_DUPFD, 3);
    289 	if (newfd < 0) {
    290 		err(EXIT_FAILURE, "dupfd IO");
    291 		/* NOTREACHED */
    292 	}
    293 
    294 	close(fd);
    295 
    296 	return newfd;
    297 }
    298 
    299 static void
    300 dd_in(void)
    301 {
    302 	int flags;
    303 	int64_t n;
    304 
    305 	for (flags = ddflags;;) {
    306 		if (cpy_cnt && (st.in_full + st.in_part) >= cpy_cnt)
    307 			return;
    308 
    309 		/*
    310 		 * Clear the buffer first if doing "sync" on input.
    311 		 * If doing block operations use spaces.  This will
    312 		 * affect not only the C_NOERROR case, but also the
    313 		 * last partial input block which should be padded
    314 		 * with zero and not garbage.
    315 		 */
    316 		if (flags & C_SYNC) {
    317 			if (flags & (C_BLOCK|C_UNBLOCK))
    318 				(void)memset(in.dbp, ' ', in.dbsz);
    319 			else
    320 				(void)memset(in.dbp, 0, in.dbsz);
    321 		}
    322 
    323 		n = read(in.fd, in.dbp, in.dbsz);
    324 		if (n == 0) {
    325 			in.dbrcnt = 0;
    326 			return;
    327 		}
    328 
    329 		/* Read error. */
    330 		if (n < 0) {
    331 
    332 			/*
    333 			 * If noerror not specified, die.  POSIX requires that
    334 			 * the warning message be followed by an I/O display.
    335 			 */
    336 			if (!(flags & C_NOERROR)) {
    337 				err(EXIT_FAILURE, "%s", in.name);
    338 				/* NOTREACHED */
    339 			}
    340 			warn("%s", in.name);
    341 			summary();
    342 
    343 			/*
    344 			 * If it's not a tape drive or a pipe, seek past the
    345 			 * error.  If your OS doesn't do the right thing for
    346 			 * raw disks this section should be modified to re-read
    347 			 * in sector size chunks.
    348 			 */
    349 			if (!(in.flags & (ISPIPE|ISTAPE)) &&
    350 			    lseek(in.fd, (off_t)in.dbsz, SEEK_CUR))
    351 				warn("%s", in.name);
    352 
    353 			/* If sync not specified, omit block and continue. */
    354 			if (!(ddflags & C_SYNC))
    355 				continue;
    356 
    357 			/* Read errors count as full blocks. */
    358 			in.dbcnt += in.dbrcnt = in.dbsz;
    359 			++st.in_full;
    360 
    361 		/* Handle full input blocks. */
    362 		} else if (n == in.dbsz) {
    363 			in.dbcnt += in.dbrcnt = n;
    364 			++st.in_full;
    365 
    366 		/* Handle partial input blocks. */
    367 		} else {
    368 			/* If sync, use the entire block. */
    369 			if (ddflags & C_SYNC)
    370 				in.dbcnt += in.dbrcnt = in.dbsz;
    371 			else
    372 				in.dbcnt += in.dbrcnt = n;
    373 			++st.in_part;
    374 		}
    375 
    376 		/*
    377 		 * POSIX states that if bs is set and no other conversions
    378 		 * than noerror, notrunc or sync are specified, the block
    379 		 * is output without buffering as it is read.
    380 		 */
    381 		if (ddflags & C_BS) {
    382 			out.dbcnt = in.dbcnt;
    383 			dd_out(1);
    384 			in.dbcnt = 0;
    385 			continue;
    386 		}
    387 
    388 		if (ddflags & C_SWAB) {
    389 			if ((n = in.dbrcnt) & 1) {
    390 				++st.swab;
    391 				--n;
    392 			}
    393 			swab(in.dbp, in.dbp, n);
    394 		}
    395 
    396 		in.dbp += in.dbrcnt;
    397 		(*cfunc)();
    398 	}
    399 }
    400 
    401 /*
    402  * Cleanup any remaining I/O and flush output.  If necessary, output file
    403  * is truncated.
    404  */
    405 static void
    406 dd_close(void)
    407 {
    408 
    409 	if (cfunc == def)
    410 		def_close();
    411 	else if (cfunc == block)
    412 		block_close();
    413 	else if (cfunc == unblock)
    414 		unblock_close();
    415 	if (ddflags & C_OSYNC && out.dbcnt < out.dbsz) {
    416 		(void)memset(out.dbp, 0, out.dbsz - out.dbcnt);
    417 		out.dbcnt = out.dbsz;
    418 	}
    419 	/* If there are pending sparse blocks, make sure
    420 	 * to write out the final block un-sparse
    421 	 */
    422 	if ((out.dbcnt == 0) && pending) {
    423 		memset(out.db, 0, out.dbsz);
    424 		out.dbcnt = out.dbsz;
    425 		out.dbp = out.db + out.dbcnt;
    426 		pending -= out.dbsz;
    427 	}
    428 	if (out.dbcnt)
    429 		dd_out(1);
    430 
    431 	/*
    432 	 * Reporting nfs write error may be defered until next
    433 	 * write(2) or close(2) system call.  So, we need to do an
    434 	 * extra check.  If an output is stdout, the file structure
    435 	 * may be shared among with other processes and close(2) just
    436 	 * decreases the reference count.
    437 	 */
    438 	if (out.fd == STDOUT_FILENO && fsync(out.fd) == -1 && errno != EINVAL) {
    439 		err(EXIT_FAILURE, "fsync stdout");
    440 		/* NOTREACHED */
    441 	}
    442 	if (close(out.fd) == -1) {
    443 		err(EXIT_FAILURE, "close");
    444 		/* NOTREACHED */
    445 	}
    446 }
    447 
    448 void
    449 dd_out(int force)
    450 {
    451 	static int warned;
    452 	int64_t cnt, n, nw;
    453 	u_char *outp;
    454 
    455 	/*
    456 	 * Write one or more blocks out.  The common case is writing a full
    457 	 * output block in a single write; increment the full block stats.
    458 	 * Otherwise, we're into partial block writes.  If a partial write,
    459 	 * and it's a character device, just warn.  If a tape device, quit.
    460 	 *
    461 	 * The partial writes represent two cases.  1: Where the input block
    462 	 * was less than expected so the output block was less than expected.
    463 	 * 2: Where the input block was the right size but we were forced to
    464 	 * write the block in multiple chunks.  The original versions of dd(1)
    465 	 * never wrote a block in more than a single write, so the latter case
    466 	 * never happened.
    467 	 *
    468 	 * One special case is if we're forced to do the write -- in that case
    469 	 * we play games with the buffer size, and it's usually a partial write.
    470 	 */
    471 	outp = out.db;
    472 	for (n = force ? out.dbcnt : out.dbsz;; n = out.dbsz) {
    473 		for (cnt = n;; cnt -= nw) {
    474 
    475 			if (!force && ddflags & C_SPARSE) {
    476 				int sparse, i;
    477 				sparse = 1;	/* Is buffer sparse? */
    478 				for (i = 0; i < cnt; i++)
    479 					if (outp[i] != 0) {
    480 						sparse = 0;
    481 						break;
    482 					}
    483 				if (sparse) {
    484 					pending += cnt;
    485 					outp += cnt;
    486 					nw = 0;
    487 					break;
    488 				}
    489 			}
    490 			if (pending != 0) {
    491 				if (lseek(out.fd, pending, SEEK_CUR) ==
    492 				    -1)
    493 					err(EXIT_FAILURE, "%s: seek error creating sparse file",
    494 					    out.name);
    495 			}
    496 			nw = bwrite(out.fd, outp, cnt);
    497 			if (nw <= 0) {
    498 				if (nw == 0)
    499 					errx(EXIT_FAILURE,
    500 						"%s: end of device", out.name);
    501 					/* NOTREACHED */
    502 				if (errno != EINTR)
    503 					err(EXIT_FAILURE, "%s", out.name);
    504 					/* NOTREACHED */
    505 				nw = 0;
    506 			}
    507 			if (pending) {
    508 				st.bytes += pending;
    509 				st.sparse += pending/out.dbsz;
    510 				st.out_full += pending/out.dbsz;
    511 				pending = 0;
    512 			}
    513 			outp += nw;
    514 			st.bytes += nw;
    515 			if (nw == n) {
    516 				if (n != out.dbsz)
    517 					++st.out_part;
    518 				else
    519 					++st.out_full;
    520 				break;
    521 			}
    522 			++st.out_part;
    523 			if (nw == cnt)
    524 				break;
    525 			if (out.flags & ISCHR && !warned) {
    526 				warned = 1;
    527 				warnx("%s: short write on character device", out.name);
    528 			}
    529 			if (out.flags & ISTAPE)
    530 				errx(EXIT_FAILURE,
    531 					"%s: short write on tape device", out.name);
    532 				/* NOTREACHED */
    533 
    534 		}
    535 		if ((out.dbcnt -= n) < out.dbsz)
    536 			break;
    537 	}
    538 
    539 	/* Reassemble the output block. */
    540 	if (out.dbcnt)
    541 		(void)memmove(out.db, out.dbp - out.dbcnt, out.dbcnt);
    542 	out.dbp = out.db + out.dbcnt;
    543 
    544 	if (progress && (st.out_full + st.out_part) % progress == 0)
    545 		(void)write(STDERR_FILENO, ".", 1);
    546 }
    547 
    548 /*
    549  * A protected against SIGINFO write
    550  */
    551 ssize_t
    552 bwrite(int fd, const void *buf, size_t len)
    553 {
    554 	sigset_t oset;
    555 	ssize_t rv;
    556 	int oerrno;
    557 
    558 	(void)sigprocmask(SIG_BLOCK, &infoset, &oset);
    559 	rv = write(fd, buf, len);
    560 	oerrno = errno;
    561 	(void)sigprocmask(SIG_SETMASK, &oset, NULL);
    562 	errno = oerrno;
    563 	return (rv);
    564 }
    565