Home | History | Annotate | Line # | Download | only in dd
dd.c revision 1.30
      1 /*	$NetBSD: dd.c,v 1.30 2003/08/04 22:31:23 jschauma 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.30 2003/08/04 22:31:23 jschauma 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(void);
     74 static void dd_in(void);
     75 static void getfdtype(IO *);
     76 static void setup(void);
     77 
     78 int main(int, char *[]);
     79 
     80 IO		in, out;		/* input/output state */
     81 STAT		st;			/* statistics */
     82 void		(*cfunc)(void);		/* conversion function */
     83 uint64_t	cpy_cnt;		/* # of blocks to copy */
     84 u_int		ddflags;		/* conversion options */
     85 uint64_t	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(int argc, char *argv[])
     93 {
     94 	int ch;
     95 
     96 	while ((ch = getopt(argc, argv, "")) != -1) {
     97 		switch (ch) {
     98 		default:
     99 			errx(EXIT_FAILURE, "usage: dd [operand ...]");
    100 			/* NOTREACHED */
    101 		}
    102 	}
    103 	argc -= (optind - 1);
    104 	argv += (optind - 1);
    105 
    106 	jcl(argv);
    107 	setup();
    108 
    109 	(void)signal(SIGINFO, summaryx);
    110 	(void)signal(SIGINT, terminate);
    111 	(void)sigemptyset(&infoset);
    112 	(void)sigaddset(&infoset, SIGINFO);
    113 
    114 	(void)atexit(summary);
    115 
    116 	while (files_cnt--)
    117 		dd_in();
    118 
    119 	dd_close();
    120 	exit(0);
    121 	/* NOTREACHED */
    122 }
    123 
    124 static void
    125 setup(void)
    126 {
    127 
    128 	if (in.name == NULL) {
    129 		in.name = "stdin";
    130 		in.fd = STDIN_FILENO;
    131 	} else {
    132 		in.fd = open(in.name, O_RDONLY, 0);
    133 		if (in.fd < 0)
    134 			err(EXIT_FAILURE, "%s", printescaped(in.name));
    135 			/* NOTREACHED */
    136 	}
    137 
    138 	getfdtype(&in);
    139 
    140 	if (files_cnt > 1 && !(in.flags & ISTAPE)) {
    141 		errx(EXIT_FAILURE, "files is not supported for non-tape devices");
    142 		/* NOTREACHED */
    143 	}
    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(EXIT_FAILURE, "%s", printescaped(out.name));
    164 			/* NOTREACHED */
    165 		}
    166 	}
    167 
    168 	getfdtype(&out);
    169 
    170 	/*
    171 	 * Allocate space for the input and output buffers.  If not doing
    172 	 * record oriented I/O, only need a single buffer.
    173 	 */
    174 	if (!(ddflags & (C_BLOCK|C_UNBLOCK))) {
    175 		if ((in.db = malloc(out.dbsz + in.dbsz - 1)) == NULL) {
    176 			err(EXIT_FAILURE, NULL);
    177 			/* NOTREACHED */
    178 		}
    179 		out.db = in.db;
    180 	} else if ((in.db =
    181 	    malloc((u_int)(MAX(in.dbsz, cbsz) + cbsz))) == NULL ||
    182 	    (out.db = malloc((u_int)(out.dbsz + cbsz))) == NULL) {
    183 		err(EXIT_FAILURE, NULL);
    184 		/* NOTREACHED */
    185 	}
    186 	in.dbp = in.db;
    187 	out.dbp = out.db;
    188 
    189 	/* Position the input/output streams. */
    190 	if (in.offset)
    191 		pos_in();
    192 	if (out.offset)
    193 		pos_out();
    194 
    195 	/*
    196 	 * Truncate the output file; ignore errors because it fails on some
    197 	 * kinds of output files, tapes, for example.
    198 	 */
    199 	if ((ddflags & (C_OF | C_SEEK | C_NOTRUNC)) == (C_OF | C_SEEK))
    200 		(void)ftruncate(out.fd, (off_t)out.offset * out.dbsz);
    201 
    202 	/*
    203 	 * If converting case at the same time as another conversion, build a
    204 	 * table that does both at once.  If just converting case, use the
    205 	 * built-in tables.
    206 	 */
    207 	if (ddflags & (C_LCASE|C_UCASE)) {
    208 #ifdef	NO_CONV
    209 		/* Should not get here, but just in case... */
    210 		errx(EXIT_FAILURE, "case conv and -DNO_CONV");
    211 		/* NOTREACHED */
    212 #else	/* NO_CONV */
    213 		u_int cnt;
    214 
    215 		if (ddflags & C_ASCII || ddflags & C_EBCDIC) {
    216 			if (ddflags & C_LCASE) {
    217 				for (cnt = 0; cnt < 0377; ++cnt)
    218 					casetab[cnt] = tolower(ctab[cnt]);
    219 			} else {
    220 				for (cnt = 0; cnt < 0377; ++cnt)
    221 					casetab[cnt] = toupper(ctab[cnt]);
    222 			}
    223 		} else {
    224 			if (ddflags & C_LCASE) {
    225 				for (cnt = 0; cnt < 0377; ++cnt)
    226 					casetab[cnt] = tolower(cnt);
    227 			} else {
    228 				for (cnt = 0; cnt < 0377; ++cnt)
    229 					casetab[cnt] = toupper(cnt);
    230 			}
    231 		}
    232 
    233 		ctab = casetab;
    234 #endif	/* NO_CONV */
    235 	}
    236 
    237 	(void)gettimeofday(&st.start, NULL);	/* Statistics timestamp. */
    238 }
    239 
    240 static void
    241 getfdtype(IO *io)
    242 {
    243 	struct mtget mt;
    244 	struct stat sb;
    245 
    246 	if (fstat(io->fd, &sb)) {
    247 		err(EXIT_FAILURE, "%s", printescaped(io->name));
    248 		/* NOTREACHED */
    249 	}
    250 	if (S_ISCHR(sb.st_mode))
    251 		io->flags |= ioctl(io->fd, MTIOCGET, &mt) ? ISCHR : ISTAPE;
    252 	else if (lseek(io->fd, (off_t)0, SEEK_CUR) == -1 && errno == ESPIPE)
    253 		io->flags |= ISPIPE;		/* XXX fixed in 4.4BSD */
    254 }
    255 
    256 static void
    257 dd_in(void)
    258 {
    259 	int flags;
    260 	int64_t n;
    261 
    262 	for (flags = ddflags;;) {
    263 		if (cpy_cnt && (st.in_full + st.in_part) >= cpy_cnt)
    264 			return;
    265 
    266 		/*
    267 		 * Clear the buffer first if doing "sync" on input.
    268 		 * If doing block operations use spaces.  This will
    269 		 * affect not only the C_NOERROR case, but also the
    270 		 * last partial input block which should be padded
    271 		 * with zero and not garbage.
    272 		 */
    273 		if (flags & C_SYNC) {
    274 			if (flags & (C_BLOCK|C_UNBLOCK))
    275 				(void)memset(in.dbp, ' ', in.dbsz);
    276 			else
    277 				(void)memset(in.dbp, 0, in.dbsz);
    278 		}
    279 
    280 		n = read(in.fd, in.dbp, in.dbsz);
    281 		if (n == 0) {
    282 			in.dbrcnt = 0;
    283 			return;
    284 		}
    285 
    286 		/* Read error. */
    287 		if (n < 0) {
    288 			char *fn;
    289 
    290 			fn = printescaped(in.name);
    291 			/*
    292 			 * If noerror not specified, die.  POSIX requires that
    293 			 * the warning message be followed by an I/O display.
    294 			 */
    295 			if (!(flags & C_NOERROR)) {
    296 				err(EXIT_FAILURE, "%s", fn);
    297 				/* NOTREACHED */
    298 			}
    299 			warn("%s", fn);
    300 			summary();
    301 
    302 			/*
    303 			 * If it's not a tape drive or a pipe, seek past the
    304 			 * error.  If your OS doesn't do the right thing for
    305 			 * raw disks this section should be modified to re-read
    306 			 * in sector size chunks.
    307 			 */
    308 			if (!(in.flags & (ISPIPE|ISTAPE)) &&
    309 			    lseek(in.fd, (off_t)in.dbsz, SEEK_CUR))
    310 				warn("%s", fn);
    311 
    312 			/* If sync not specified, omit block and continue. */
    313 			if (!(ddflags & C_SYNC))
    314 				continue;
    315 
    316 			/* Read errors count as full blocks. */
    317 			in.dbcnt += in.dbrcnt = in.dbsz;
    318 			++st.in_full;
    319 
    320 			free(fn);
    321 
    322 		/* Handle full input blocks. */
    323 		} else if (n == in.dbsz) {
    324 			in.dbcnt += in.dbrcnt = n;
    325 			++st.in_full;
    326 
    327 		/* Handle partial input blocks. */
    328 		} else {
    329 			/* If sync, use the entire block. */
    330 			if (ddflags & C_SYNC)
    331 				in.dbcnt += in.dbrcnt = in.dbsz;
    332 			else
    333 				in.dbcnt += in.dbrcnt = n;
    334 			++st.in_part;
    335 		}
    336 
    337 		/*
    338 		 * POSIX states that if bs is set and no other conversions
    339 		 * than noerror, notrunc or sync are specified, the block
    340 		 * is output without buffering as it is read.
    341 		 */
    342 		if (ddflags & C_BS) {
    343 			out.dbcnt = in.dbcnt;
    344 			dd_out(1);
    345 			in.dbcnt = 0;
    346 			continue;
    347 		}
    348 
    349 		if (ddflags & C_SWAB) {
    350 			if ((n = in.dbrcnt) & 1) {
    351 				++st.swab;
    352 				--n;
    353 			}
    354 			swab(in.dbp, in.dbp, n);
    355 		}
    356 
    357 		in.dbp += in.dbrcnt;
    358 		(*cfunc)();
    359 	}
    360 }
    361 
    362 /*
    363  * Cleanup any remaining I/O and flush output.  If necesssary, output file
    364  * is truncated.
    365  */
    366 static void
    367 dd_close(void)
    368 {
    369 
    370 	if (cfunc == def)
    371 		def_close();
    372 	else if (cfunc == block)
    373 		block_close();
    374 	else if (cfunc == unblock)
    375 		unblock_close();
    376 	if (ddflags & C_OSYNC && out.dbcnt < out.dbsz) {
    377 		(void)memset(out.dbp, 0, out.dbsz - out.dbcnt);
    378 		out.dbcnt = out.dbsz;
    379 	}
    380 	if (out.dbcnt)
    381 		dd_out(1);
    382 
    383 	/*
    384 	 * Reporting nfs write error may be defered until next
    385 	 * write(2) or close(2) system call.  So, we need to do an
    386 	 * extra check.  If an output is stdout, the file structure
    387 	 * may be shared among with other processes and close(2) just
    388 	 * decreases the reference count.
    389 	 */
    390 	if (out.fd == STDOUT_FILENO && fsync(out.fd) == -1 && errno != EINVAL) {
    391 		err(EXIT_FAILURE, "fsync stdout");
    392 		/* NOTREACHED */
    393 	}
    394 	if (close(out.fd) == -1) {
    395 		err(EXIT_FAILURE, "close");
    396 		/* NOTREACHED */
    397 	}
    398 }
    399 
    400 void
    401 dd_out(int force)
    402 {
    403 	static int warned;
    404 	int64_t cnt, n, nw;
    405 	u_char *outp;
    406 
    407 	/*
    408 	 * Write one or more blocks out.  The common case is writing a full
    409 	 * output block in a single write; increment the full block stats.
    410 	 * Otherwise, we're into partial block writes.  If a partial write,
    411 	 * and it's a character device, just warn.  If a tape device, quit.
    412 	 *
    413 	 * The partial writes represent two cases.  1: Where the input block
    414 	 * was less than expected so the output block was less than expected.
    415 	 * 2: Where the input block was the right size but we were forced to
    416 	 * write the block in multiple chunks.  The original versions of dd(1)
    417 	 * never wrote a block in more than a single write, so the latter case
    418 	 * never happened.
    419 	 *
    420 	 * One special case is if we're forced to do the write -- in that case
    421 	 * we play games with the buffer size, and it's usually a partial write.
    422 	 */
    423 	outp = out.db;
    424 	for (n = force ? out.dbcnt : out.dbsz;; n = out.dbsz) {
    425 		for (cnt = n;; cnt -= nw) {
    426 			char *fn;
    427 
    428 			fn = printescaped(out.name);
    429 			nw = bwrite(out.fd, outp, cnt);
    430 			if (nw <= 0) {
    431 				if (nw == 0)
    432 					errx(EXIT_FAILURE,
    433 						"%s: end of device", fn);
    434 					/* NOTREACHED */
    435 				if (errno != EINTR)
    436 					err(EXIT_FAILURE, "%s", fn);
    437 					/* NOTREACHED */
    438 				nw = 0;
    439 			}
    440 			outp += nw;
    441 			st.bytes += nw;
    442 			if (nw == n) {
    443 				if (n != out.dbsz)
    444 					++st.out_part;
    445 				else
    446 					++st.out_full;
    447 				break;
    448 			}
    449 			++st.out_part;
    450 			if (nw == cnt)
    451 				break;
    452 			if (out.flags & ISCHR && !warned) {
    453 				warned = 1;
    454 				warnx("%s: short write on character device", fn);
    455 			}
    456 			if (out.flags & ISTAPE)
    457 				errx(EXIT_FAILURE,
    458 					"%s: short write on tape device", fn);
    459 				/* NOTREACHED */
    460 
    461 			free(fn);
    462 		}
    463 		if ((out.dbcnt -= n) < out.dbsz)
    464 			break;
    465 	}
    466 
    467 	/* Reassemble the output block. */
    468 	if (out.dbcnt)
    469 		(void)memmove(out.db, out.dbp - out.dbcnt, out.dbcnt);
    470 	out.dbp = out.db + out.dbcnt;
    471 
    472 	if (progress)
    473 		(void)write(STDERR_FILENO, ".", 1);
    474 }
    475 
    476 /*
    477  * A protected against SIGINFO write
    478  */
    479 ssize_t
    480 bwrite(int fd, const void *buf, size_t len)
    481 {
    482 	sigset_t oset;
    483 	ssize_t rv;
    484 	int oerrno;
    485 
    486 	(void)sigprocmask(SIG_BLOCK, &infoset, &oset);
    487 	rv = write(fd, buf, len);
    488 	oerrno = errno;
    489 	(void)sigprocmask(SIG_SETMASK, &oset, NULL);
    490 	errno = oerrno;
    491 	return (rv);
    492 }
    493