Home | History | Annotate | Line # | Download | only in dd
dd.c revision 1.32
      1 /*	$NetBSD: dd.c,v 1.32 2003/08/20 14:25:54 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. 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\n\
     39 	The Regents of the University of California.  All rights reserved.\n");
     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.32 2003/08/20 14:25:54 jschauma 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 <signal.h>
     61 #include <stdio.h>
     62 #include <stdlib.h>
     63 #include <string.h>
     64 #include <unistd.h>
     65 
     66 #include "dd.h"
     67 #include "extern.h"
     68 
     69 static void dd_close(void);
     70 static void dd_in(void);
     71 static void getfdtype(IO *);
     72 static void setup(void);
     73 
     74 int main(int, char *[]);
     75 
     76 IO		in, out;		/* input/output state */
     77 STAT		st;			/* statistics */
     78 void		(*cfunc)(void);		/* conversion function */
     79 uint64_t	cpy_cnt;		/* # of blocks to copy */
     80 u_int		ddflags;		/* conversion options */
     81 uint64_t	cbsz;			/* conversion block size */
     82 u_int		files_cnt = 1;		/* # of files to copy */
     83 int		progress = 0;		/* display sign of life */
     84 const u_char	*ctab;			/* conversion table */
     85 sigset_t	infoset;		/* a set blocking SIGINFO */
     86 
     87 int
     88 main(int argc, char *argv[])
     89 {
     90 	int ch;
     91 
     92 	while ((ch = getopt(argc, argv, "")) != -1) {
     93 		switch (ch) {
     94 		default:
     95 			errx(EXIT_FAILURE, "usage: dd [operand ...]");
     96 			/* NOTREACHED */
     97 		}
     98 	}
     99 	argc -= (optind - 1);
    100 	argv += (optind - 1);
    101 
    102 	jcl(argv);
    103 	setup();
    104 
    105 	(void)signal(SIGINFO, summaryx);
    106 	(void)signal(SIGINT, terminate);
    107 	(void)sigemptyset(&infoset);
    108 	(void)sigaddset(&infoset, SIGINFO);
    109 
    110 	(void)atexit(summary);
    111 
    112 	while (files_cnt--)
    113 		dd_in();
    114 
    115 	dd_close();
    116 	exit(0);
    117 	/* NOTREACHED */
    118 }
    119 
    120 static void
    121 setup(void)
    122 {
    123 
    124 	if (in.name == NULL) {
    125 		in.name = "stdin";
    126 		in.fd = STDIN_FILENO;
    127 	} else {
    128 		in.fd = open(in.name, O_RDONLY, 0);
    129 		if (in.fd < 0)
    130 			err(EXIT_FAILURE, "%s", printescaped(in.name));
    131 			/* NOTREACHED */
    132 	}
    133 
    134 	getfdtype(&in);
    135 
    136 	if (files_cnt > 1 && !(in.flags & ISTAPE)) {
    137 		errx(EXIT_FAILURE, "files is not supported for non-tape devices");
    138 		/* NOTREACHED */
    139 	}
    140 
    141 	if (out.name == NULL) {
    142 		/* No way to check for read access here. */
    143 		out.fd = STDOUT_FILENO;
    144 		out.name = "stdout";
    145 	} else {
    146 #define	OFLAGS \
    147     (O_CREAT | (ddflags & (C_SEEK | C_NOTRUNC) ? 0 : O_TRUNC))
    148 		out.fd = open(out.name, O_RDWR | OFLAGS, DEFFILEMODE);
    149 		/*
    150 		 * May not have read access, so try again with write only.
    151 		 * Without read we may have a problem if output also does
    152 		 * not support seeks.
    153 		 */
    154 		if (out.fd < 0) {
    155 			out.fd = open(out.name, O_WRONLY | OFLAGS, DEFFILEMODE);
    156 			out.flags |= NOREAD;
    157 		}
    158 		if (out.fd < 0) {
    159 			err(EXIT_FAILURE, "%s", printescaped(out.name));
    160 			/* NOTREACHED */
    161 		}
    162 	}
    163 
    164 	getfdtype(&out);
    165 
    166 	/*
    167 	 * Allocate space for the input and output buffers.  If not doing
    168 	 * record oriented I/O, only need a single buffer.
    169 	 */
    170 	if (!(ddflags & (C_BLOCK|C_UNBLOCK))) {
    171 		if ((in.db = malloc(out.dbsz + in.dbsz - 1)) == NULL) {
    172 			err(EXIT_FAILURE, NULL);
    173 			/* NOTREACHED */
    174 		}
    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(EXIT_FAILURE, NULL);
    180 		/* NOTREACHED */
    181 	}
    182 	in.dbp = in.db;
    183 	out.dbp = out.db;
    184 
    185 	/* Position the input/output streams. */
    186 	if (in.offset)
    187 		pos_in();
    188 	if (out.offset)
    189 		pos_out();
    190 
    191 	/*
    192 	 * Truncate the output file; ignore errors because it fails on some
    193 	 * kinds of output files, tapes, for example.
    194 	 */
    195 	if ((ddflags & (C_OF | C_SEEK | C_NOTRUNC)) == (C_OF | C_SEEK))
    196 		(void)ftruncate(out.fd, (off_t)out.offset * out.dbsz);
    197 
    198 	/*
    199 	 * If converting case at the same time as another conversion, build a
    200 	 * table that does both at once.  If just converting case, use the
    201 	 * built-in tables.
    202 	 */
    203 	if (ddflags & (C_LCASE|C_UCASE)) {
    204 #ifdef	NO_CONV
    205 		/* Should not get here, but just in case... */
    206 		errx(EXIT_FAILURE, "case conv and -DNO_CONV");
    207 		/* NOTREACHED */
    208 #else	/* NO_CONV */
    209 		u_int cnt;
    210 
    211 		if (ddflags & C_ASCII || ddflags & C_EBCDIC) {
    212 			if (ddflags & C_LCASE) {
    213 				for (cnt = 0; cnt < 0377; ++cnt)
    214 					casetab[cnt] = tolower(ctab[cnt]);
    215 			} else {
    216 				for (cnt = 0; cnt < 0377; ++cnt)
    217 					casetab[cnt] = toupper(ctab[cnt]);
    218 			}
    219 		} else {
    220 			if (ddflags & C_LCASE) {
    221 				for (cnt = 0; cnt < 0377; ++cnt)
    222 					casetab[cnt] = tolower(cnt);
    223 			} else {
    224 				for (cnt = 0; cnt < 0377; ++cnt)
    225 					casetab[cnt] = toupper(cnt);
    226 			}
    227 		}
    228 
    229 		ctab = casetab;
    230 #endif	/* NO_CONV */
    231 	}
    232 
    233 	(void)gettimeofday(&st.start, NULL);	/* Statistics timestamp. */
    234 }
    235 
    236 static void
    237 getfdtype(IO *io)
    238 {
    239 	struct mtget mt;
    240 	struct stat sb;
    241 
    242 	if (fstat(io->fd, &sb)) {
    243 		err(EXIT_FAILURE, "%s", printescaped(io->name));
    244 		/* NOTREACHED */
    245 	}
    246 	if (S_ISCHR(sb.st_mode))
    247 		io->flags |= ioctl(io->fd, MTIOCGET, &mt) ? ISCHR : ISTAPE;
    248 	else if (lseek(io->fd, (off_t)0, SEEK_CUR) == -1 && errno == ESPIPE)
    249 		io->flags |= ISPIPE;		/* XXX fixed in 4.4BSD */
    250 }
    251 
    252 static void
    253 dd_in(void)
    254 {
    255 	int flags;
    256 	int64_t n;
    257 
    258 	for (flags = ddflags;;) {
    259 		if (cpy_cnt && (st.in_full + st.in_part) >= cpy_cnt)
    260 			return;
    261 
    262 		/*
    263 		 * Clear the buffer first if doing "sync" on input.
    264 		 * If doing block operations use spaces.  This will
    265 		 * affect not only the C_NOERROR case, but also the
    266 		 * last partial input block which should be padded
    267 		 * with zero and not garbage.
    268 		 */
    269 		if (flags & C_SYNC) {
    270 			if (flags & (C_BLOCK|C_UNBLOCK))
    271 				(void)memset(in.dbp, ' ', in.dbsz);
    272 			else
    273 				(void)memset(in.dbp, 0, in.dbsz);
    274 		}
    275 
    276 		n = read(in.fd, in.dbp, in.dbsz);
    277 		if (n == 0) {
    278 			in.dbrcnt = 0;
    279 			return;
    280 		}
    281 
    282 		/* Read error. */
    283 		if (n < 0) {
    284 			char *fn;
    285 
    286 			fn = printescaped(in.name);
    287 			/*
    288 			 * If noerror not specified, die.  POSIX requires that
    289 			 * the warning message be followed by an I/O display.
    290 			 */
    291 			if (!(flags & C_NOERROR)) {
    292 				err(EXIT_FAILURE, "%s", fn);
    293 				/* NOTREACHED */
    294 			}
    295 			warn("%s", fn);
    296 			summary();
    297 
    298 			/*
    299 			 * If it's not a tape drive or a pipe, seek past the
    300 			 * error.  If your OS doesn't do the right thing for
    301 			 * raw disks this section should be modified to re-read
    302 			 * in sector size chunks.
    303 			 */
    304 			if (!(in.flags & (ISPIPE|ISTAPE)) &&
    305 			    lseek(in.fd, (off_t)in.dbsz, SEEK_CUR))
    306 				warn("%s", fn);
    307 
    308 			/*
    309 			 * Free memory from printescaped() before possible
    310 			 * continue
    311 			 */
    312 			free(fn);
    313 
    314 			/* If sync not specified, omit block and continue. */
    315 			if (!(ddflags & C_SYNC))
    316 				continue;
    317 
    318 			/* Read errors count as full blocks. */
    319 			in.dbcnt += in.dbrcnt = in.dbsz;
    320 			++st.in_full;
    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 				free(fn);
    448 				break;
    449 			}
    450 			++st.out_part;
    451 			if (nw == cnt) {
    452 				free(fn);
    453 				break;
    454 			}
    455 			if (out.flags & ISCHR && !warned) {
    456 				warned = 1;
    457 				warnx("%s: short write on character device", fn);
    458 			}
    459 			if (out.flags & ISTAPE)
    460 				errx(EXIT_FAILURE,
    461 					"%s: short write on tape device", fn);
    462 				/* NOTREACHED */
    463 
    464 			free(fn);
    465 		}
    466 		if ((out.dbcnt -= n) < out.dbsz)
    467 			break;
    468 	}
    469 
    470 	/* Reassemble the output block. */
    471 	if (out.dbcnt)
    472 		(void)memmove(out.db, out.dbp - out.dbcnt, out.dbcnt);
    473 	out.dbp = out.db + out.dbcnt;
    474 
    475 	if (progress)
    476 		(void)write(STDERR_FILENO, ".", 1);
    477 }
    478 
    479 /*
    480  * A protected against SIGINFO write
    481  */
    482 ssize_t
    483 bwrite(int fd, const void *buf, size_t len)
    484 {
    485 	sigset_t oset;
    486 	ssize_t rv;
    487 	int oerrno;
    488 
    489 	(void)sigprocmask(SIG_BLOCK, &infoset, &oset);
    490 	rv = write(fd, buf, len);
    491 	oerrno = errno;
    492 	(void)sigprocmask(SIG_SETMASK, &oset, NULL);
    493 	errno = oerrno;
    494 	return (rv);
    495 }
    496