Home | History | Annotate | Line # | Download | only in dd
dd.c revision 1.21
      1 /*	$NetBSD: dd.c,v 1.21 2001/11/25 06:53:48 lukem 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.21 2001/11/25 06:53:48 lukem 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 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(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 	u_int cnt;
    128 
    129 	if (in.name == NULL) {
    130 		in.name = "stdin";
    131 		in.fd = STDIN_FILENO;
    132 	} else {
    133 		in.fd = open(in.name, O_RDONLY, 0);
    134 		if (in.fd < 0)
    135 			err(1, "%s", in.name);
    136 	}
    137 
    138 	getfdtype(&in);
    139 
    140 	if (files_cnt > 1 && !(in.flags & ISTAPE))
    141 		errx(1, "files is not supported for non-tape devices");
    142 
    143 	if (out.name == NULL) {
    144 		/* No way to check for read access here. */
    145 		out.fd = STDOUT_FILENO;
    146 		out.name = "stdout";
    147 	} else {
    148 #define	OFLAGS \
    149     (O_CREAT | (ddflags & (C_SEEK | C_NOTRUNC) ? 0 : O_TRUNC))
    150 		out.fd = open(out.name, O_RDWR | OFLAGS, DEFFILEMODE);
    151 		/*
    152 		 * May not have read access, so try again with write only.
    153 		 * Without read we may have a problem if output also does
    154 		 * not support seeks.
    155 		 */
    156 		if (out.fd < 0) {
    157 			out.fd = open(out.name, O_WRONLY | OFLAGS, DEFFILEMODE);
    158 			out.flags |= NOREAD;
    159 		}
    160 		if (out.fd < 0)
    161 			err(1, "%s", out.name);
    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(1, NULL);
    173 		out.db = in.db;
    174 	} else if ((in.db =
    175 	    malloc((u_int)(MAX(in.dbsz, cbsz) + cbsz))) == NULL ||
    176 	    (out.db = malloc((u_int)(out.dbsz + cbsz))) == NULL)
    177 		err(1, NULL);
    178 	in.dbp = in.db;
    179 	out.dbp = out.db;
    180 
    181 	/* Position the input/output streams. */
    182 	if (in.offset)
    183 		pos_in();
    184 	if (out.offset)
    185 		pos_out();
    186 
    187 	/*
    188 	 * Truncate the output file; ignore errors because it fails on some
    189 	 * kinds of output files, tapes, for example.
    190 	 */
    191 	if ((ddflags & (C_OF | C_SEEK | C_NOTRUNC)) == (C_OF | C_SEEK))
    192 		(void)ftruncate(out.fd, (off_t)out.offset * out.dbsz);
    193 
    194 	/*
    195 	 * If converting case at the same time as another conversion, build a
    196 	 * table that does both at once.  If just converting case, use the
    197 	 * built-in tables.
    198 	 */
    199 	if (ddflags & (C_LCASE|C_UCASE)) {
    200 #ifdef	NO_CONV
    201 		/* Should not get here, but just in case... */
    202 		errx(1, "case conv and -DNO_CONV");
    203 #else	/* NO_CONV */
    204 		if (ddflags & C_ASCII || ddflags & C_EBCDIC) {
    205 			if (ddflags & C_LCASE) {
    206 				for (cnt = 0; cnt < 0377; ++cnt)
    207 					casetab[cnt] = tolower(ctab[cnt]);
    208 			} else {
    209 				for (cnt = 0; cnt < 0377; ++cnt)
    210 					casetab[cnt] = toupper(ctab[cnt]);
    211 			}
    212 		} else {
    213 			if (ddflags & C_LCASE) {
    214 				for (cnt = 0; cnt < 0377; ++cnt)
    215 					casetab[cnt] = tolower(cnt);
    216 			} else {
    217 				for (cnt = 0; cnt < 0377; ++cnt)
    218 					casetab[cnt] = toupper(cnt);
    219 			}
    220 		}
    221 
    222 		ctab = casetab;
    223 #endif	/* NO_CONV */
    224 	}
    225 
    226 	(void)gettimeofday(&st.start, NULL);	/* Statistics timestamp. */
    227 }
    228 
    229 static void
    230 getfdtype(IO *io)
    231 {
    232 	struct mtget mt;
    233 	struct stat sb;
    234 
    235 	if (fstat(io->fd, &sb))
    236 		err(1, "%s", io->name);
    237 	if (S_ISCHR(sb.st_mode))
    238 		io->flags |= ioctl(io->fd, MTIOCGET, &mt) ? ISCHR : ISTAPE;
    239 	else if (lseek(io->fd, (off_t)0, SEEK_CUR) == -1 && errno == ESPIPE)
    240 		io->flags |= ISPIPE;		/* XXX fixed in 4.4BSD */
    241 }
    242 
    243 static void
    244 dd_in(void)
    245 {
    246 	int flags, n;
    247 
    248 	for (flags = ddflags;;) {
    249 		if (cpy_cnt && (st.in_full + st.in_part) >= cpy_cnt)
    250 			return;
    251 
    252 		/*
    253 		 * Clear the buffer first if doing "sync" on input.
    254 		 * If doing block operations use spaces.  This will
    255 		 * affect not only the C_NOERROR case, but also the
    256 		 * last partial input block which should be padded
    257 		 * with zero and not garbage.
    258 		 */
    259 		if (flags & C_SYNC) {
    260 			if (flags & (C_BLOCK|C_UNBLOCK))
    261 				(void)memset(in.dbp, ' ', in.dbsz);
    262 			else
    263 				(void)memset(in.dbp, 0, in.dbsz);
    264 		}
    265 
    266 		n = read(in.fd, in.dbp, in.dbsz);
    267 		if (n == 0) {
    268 			in.dbrcnt = 0;
    269 			return;
    270 		}
    271 
    272 		/* Read error. */
    273 		if (n < 0) {
    274 			/*
    275 			 * If noerror not specified, die.  POSIX requires that
    276 			 * the warning message be followed by an I/O display.
    277 			 */
    278 			if (!(flags & C_NOERROR))
    279 				err(1, "%s", in.name);
    280 			warn("%s", in.name);
    281 			summary();
    282 
    283 			/*
    284 			 * If it's not a tape drive or a pipe, seek past the
    285 			 * error.  If your OS doesn't do the right thing for
    286 			 * raw disks this section should be modified to re-read
    287 			 * in sector size chunks.
    288 			 */
    289 			if (!(in.flags & (ISPIPE|ISTAPE)) &&
    290 			    lseek(in.fd, (off_t)in.dbsz, SEEK_CUR))
    291 				warn("%s", in.name);
    292 
    293 			/* If sync not specified, omit block and continue. */
    294 			if (!(ddflags & C_SYNC))
    295 				continue;
    296 
    297 			/* Read errors count as full blocks. */
    298 			in.dbcnt += in.dbrcnt = in.dbsz;
    299 			++st.in_full;
    300 
    301 		/* Handle full input blocks. */
    302 		} else if (n == in.dbsz) {
    303 			in.dbcnt += in.dbrcnt = n;
    304 			++st.in_full;
    305 
    306 		/* Handle partial input blocks. */
    307 		} else {
    308 			/* If sync, use the entire block. */
    309 			if (ddflags & C_SYNC)
    310 				in.dbcnt += in.dbrcnt = in.dbsz;
    311 			else
    312 				in.dbcnt += in.dbrcnt = n;
    313 			++st.in_part;
    314 		}
    315 
    316 		/*
    317 		 * POSIX states that if bs is set and no other conversions
    318 		 * than noerror, notrunc or sync are specified, the block
    319 		 * is output without buffering as it is read.
    320 		 */
    321 		if (ddflags & C_BS) {
    322 			out.dbcnt = in.dbcnt;
    323 			dd_out(1);
    324 			in.dbcnt = 0;
    325 			continue;
    326 		}
    327 
    328 		if (ddflags & C_SWAB) {
    329 			if ((n = in.dbrcnt) & 1) {
    330 				++st.swab;
    331 				--n;
    332 			}
    333 			swab(in.dbp, in.dbp, n);
    334 		}
    335 
    336 		in.dbp += in.dbrcnt;
    337 		(*cfunc)();
    338 	}
    339 }
    340 
    341 /*
    342  * Cleanup any remaining I/O and flush output.  If necesssary, output file
    343  * is truncated.
    344  */
    345 static void
    346 dd_close(void)
    347 {
    348 
    349 	if (cfunc == def)
    350 		def_close();
    351 	else if (cfunc == block)
    352 		block_close();
    353 	else if (cfunc == unblock)
    354 		unblock_close();
    355 	if (ddflags & C_OSYNC && out.dbcnt < out.dbsz) {
    356 		(void)memset(out.dbp, 0, out.dbsz - out.dbcnt);
    357 		out.dbcnt = out.dbsz;
    358 	}
    359 	if (out.dbcnt)
    360 		dd_out(1);
    361 }
    362 
    363 void
    364 dd_out(int force)
    365 {
    366 	static int warned;
    367 	int cnt, n, nw;
    368 	u_char *outp;
    369 
    370 	/*
    371 	 * Write one or more blocks out.  The common case is writing a full
    372 	 * output block in a single write; increment the full block stats.
    373 	 * Otherwise, we're into partial block writes.  If a partial write,
    374 	 * and it's a character device, just warn.  If a tape device, quit.
    375 	 *
    376 	 * The partial writes represent two cases.  1: Where the input block
    377 	 * was less than expected so the output block was less than expected.
    378 	 * 2: Where the input block was the right size but we were forced to
    379 	 * write the block in multiple chunks.  The original versions of dd(1)
    380 	 * never wrote a block in more than a single write, so the latter case
    381 	 * never happened.
    382 	 *
    383 	 * One special case is if we're forced to do the write -- in that case
    384 	 * we play games with the buffer size, and it's usually a partial write.
    385 	 */
    386 	outp = out.db;
    387 	for (n = force ? out.dbcnt : out.dbsz;; n = out.dbsz) {
    388 		for (cnt = n;; cnt -= nw) {
    389 			nw = bwrite(out.fd, outp, cnt);
    390 			if (nw <= 0) {
    391 				if (nw == 0)
    392 					errx(1, "%s: end of device", out.name);
    393 				if (errno != EINTR)
    394 					err(1, "%s", out.name);
    395 				nw = 0;
    396 			}
    397 			outp += nw;
    398 			st.bytes += nw;
    399 			if (nw == n) {
    400 				if (n != out.dbsz)
    401 					++st.out_part;
    402 				else
    403 					++st.out_full;
    404 				break;
    405 			}
    406 			++st.out_part;
    407 			if (nw == cnt)
    408 				break;
    409 			if (out.flags & ISCHR && !warned) {
    410 				warned = 1;
    411 				warnx("%s: short write on character device",
    412 				    out.name);
    413 			}
    414 			if (out.flags & ISTAPE)
    415 				errx(1, "%s: short write on tape device", out.name);
    416 		}
    417 		if ((out.dbcnt -= n) < out.dbsz)
    418 			break;
    419 	}
    420 
    421 	/* Reassemble the output block. */
    422 	if (out.dbcnt)
    423 		(void)memmove(out.db, out.dbp - out.dbcnt, out.dbcnt);
    424 	out.dbp = out.db + out.dbcnt;
    425 
    426 	if (progress)
    427 		(void)write(STDERR_FILENO, ".", 1);
    428 }
    429 
    430 /*
    431  * A protected against SIGINFO write
    432  */
    433 ssize_t
    434 bwrite(int fd, const void *buf, size_t len)
    435 {
    436 	sigset_t oset;
    437 	ssize_t rv;
    438 	int oerrno;
    439 
    440 	(void)sigprocmask(SIG_BLOCK, &infoset, &oset);
    441 	rv = write(fd, buf, len);
    442 	oerrno = errno;
    443 	(void)sigprocmask(SIG_SETMASK, &oset, NULL);
    444 	errno = oerrno;
    445 	return rv;
    446 }
    447