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