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