Home | History | Annotate | Line # | Download | only in dd
dd.c revision 1.5
      1 /*	$NetBSD: dd.c,v 1.5 1995/10/08 23:01:24 gwr 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.5 1995/10/08 23:01:24 gwr 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 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)
    187 			if (ddflags & C_LCASE) {
    188 				for (cnt = 0; cnt < 0377; ++cnt)
    189 					if (isupper(ctab[cnt]))
    190 						ctab[cnt] = tolower(ctab[cnt]);
    191 			} else {
    192 				for (cnt = 0; cnt < 0377; ++cnt)
    193 					if (islower(ctab[cnt]))
    194 						ctab[cnt] = toupper(ctab[cnt]);
    195 			}
    196 		else if (ddflags & C_EBCDIC)
    197 			if (ddflags & C_LCASE) {
    198 				for (cnt = 0; cnt < 0377; ++cnt)
    199 					if (isupper(cnt))
    200 						ctab[cnt] = ctab[tolower(cnt)];
    201 			} else {
    202 				for (cnt = 0; cnt < 0377; ++cnt)
    203 					if (islower(cnt))
    204 						ctab[cnt] = ctab[toupper(cnt)];
    205 			}
    206 		else
    207 			ctab = ddflags & C_LCASE ? u2l : l2u;
    208 #endif	/* NO_CONV */
    209 	}
    210 
    211 	(void)time(&st.start);			/* Statistics timestamp. */
    212 }
    213 
    214 static void
    215 getfdtype(io)
    216 	IO *io;
    217 {
    218 	struct mtget mt;
    219 	struct stat sb;
    220 
    221 	if (fstat(io->fd, &sb))
    222 		err(1, "%s", io->name);
    223 	if (S_ISCHR(sb.st_mode))
    224 		io->flags |= ioctl(io->fd, MTIOCGET, &mt) ? ISCHR : ISTAPE;
    225 	else if (lseek(io->fd, (off_t)0, SEEK_CUR) == -1 && errno == ESPIPE)
    226 		io->flags |= ISPIPE;		/* XXX fixed in 4.4BSD */
    227 }
    228 
    229 static void
    230 dd_in()
    231 {
    232 	int flags, n;
    233 
    234 	for (flags = ddflags;;) {
    235 		if (cpy_cnt && (st.in_full + st.in_part) >= cpy_cnt)
    236 			return;
    237 
    238 		/*
    239 		 * Zero the buffer first if trying to recover from errors so
    240 		 * lose the minimum amount of data.  If doing block operations
    241 		 * use spaces.
    242 		 */
    243 		if ((flags & (C_NOERROR|C_SYNC)) == (C_NOERROR|C_SYNC))
    244 			if (flags & (C_BLOCK|C_UNBLOCK))
    245 				memset(in.dbp, ' ', in.dbsz);
    246 			else
    247 				memset(in.dbp, 0, in.dbsz);
    248 
    249 		n = read(in.fd, in.dbp, in.dbsz);
    250 		if (n == 0) {
    251 			in.dbrcnt = 0;
    252 			return;
    253 		}
    254 
    255 		/* Read error. */
    256 		if (n < 0) {
    257 			/*
    258 			 * If noerror not specified, die.  POSIX requires that
    259 			 * the warning message be followed by an I/O display.
    260 			 */
    261 			if (!(flags & C_NOERROR))
    262 				err(1, "%s", in.name);
    263 			warn("%s", in.name);
    264 			summary();
    265 
    266 			/*
    267 			 * If it's not a tape drive or a pipe, seek past the
    268 			 * error.  If your OS doesn't do the right thing for
    269 			 * raw disks this section should be modified to re-read
    270 			 * in sector size chunks.
    271 			 */
    272 			if (!(in.flags & (ISPIPE|ISTAPE)) &&
    273 			    lseek(in.fd, (off_t)in.dbsz, SEEK_CUR))
    274 				warn("%s", in.name);
    275 
    276 			/* If sync not specified, omit block and continue. */
    277 			if (!(ddflags & C_SYNC))
    278 				continue;
    279 
    280 			/* Read errors count as full blocks. */
    281 			in.dbcnt += in.dbrcnt = in.dbsz;
    282 			++st.in_full;
    283 
    284 		/* Handle full input blocks. */
    285 		} else if (n == in.dbsz) {
    286 			in.dbcnt += in.dbrcnt = n;
    287 			++st.in_full;
    288 
    289 		/* Handle partial input blocks. */
    290 		} else {
    291 			/* If sync, use the entire block. */
    292 			if (ddflags & C_SYNC)
    293 				in.dbcnt += in.dbrcnt = in.dbsz;
    294 			else
    295 				in.dbcnt += in.dbrcnt = n;
    296 			++st.in_part;
    297 		}
    298 
    299 		/*
    300 		 * POSIX states that if bs is set and no other conversions
    301 		 * than noerror, notrunc or sync are specified, the block
    302 		 * is output without buffering as it is read.
    303 		 */
    304 		if (ddflags & C_BS) {
    305 			out.dbcnt = in.dbcnt;
    306 			dd_out(1);
    307 			in.dbcnt = 0;
    308 			continue;
    309 		}
    310 
    311 		if (ddflags & C_SWAB) {
    312 			if ((n = in.dbcnt) & 1) {
    313 				++st.swab;
    314 				--n;
    315 			}
    316 			swab(in.dbp, in.dbp, n);
    317 		}
    318 
    319 		in.dbp += in.dbrcnt;
    320 		(*cfunc)();
    321 	}
    322 }
    323 
    324 /*
    325  * Cleanup any remaining I/O and flush output.  If necesssary, output file
    326  * is truncated.
    327  */
    328 static void
    329 dd_close()
    330 {
    331 	if (cfunc == def)
    332 		def_close();
    333 	else if (cfunc == block)
    334 		block_close();
    335 	else if (cfunc == unblock)
    336 		unblock_close();
    337 	if (ddflags & C_OSYNC && out.dbcnt < out.dbsz) {
    338 		memset(out.dbp, 0, out.dbsz - out.dbcnt);
    339 		out.dbcnt = out.dbsz;
    340 	}
    341 	if (out.dbcnt)
    342 		dd_out(1);
    343 }
    344 
    345 void
    346 dd_out(force)
    347 	int force;
    348 {
    349 	static int warned;
    350 	int cnt, n, nw;
    351 	u_char *outp;
    352 
    353 	/*
    354 	 * Write one or more blocks out.  The common case is writing a full
    355 	 * output block in a single write; increment the full block stats.
    356 	 * Otherwise, we're into partial block writes.  If a partial write,
    357 	 * and it's a character device, just warn.  If a tape device, quit.
    358 	 *
    359 	 * The partial writes represent two cases.  1: Where the input block
    360 	 * was less than expected so the output block was less than expected.
    361 	 * 2: Where the input block was the right size but we were forced to
    362 	 * write the block in multiple chunks.  The original versions of dd(1)
    363 	 * never wrote a block in more than a single write, so the latter case
    364 	 * never happened.
    365 	 *
    366 	 * One special case is if we're forced to do the write -- in that case
    367 	 * we play games with the buffer size, and it's usually a partial write.
    368 	 */
    369 	outp = out.db;
    370 	for (n = force ? out.dbcnt : out.dbsz;; n = out.dbsz) {
    371 		for (cnt = n;; cnt -= nw) {
    372 			nw = write(out.fd, outp, cnt);
    373 			if (nw <= 0) {
    374 				if (nw == 0)
    375 					errx(1, "%s: end of device", out.name);
    376 				if (errno != EINTR)
    377 					err(1, "%s", out.name);
    378 				nw = 0;
    379 			}
    380 			outp += nw;
    381 			st.bytes += nw;
    382 			if (nw == n) {
    383 				if (n != out.dbsz)
    384 					++st.out_part;
    385 				else
    386 					++st.out_full;
    387 				break;
    388 			}
    389 			++st.out_part;
    390 			if (nw == cnt)
    391 				break;
    392 			if (out.flags & ISCHR && !warned) {
    393 				warned = 1;
    394 				warnx("%s: short write on character device",
    395 				    out.name);
    396 			}
    397 			if (out.flags & ISTAPE)
    398 				errx(1, "%s: short write on tape device", out.name);
    399 		}
    400 		if ((out.dbcnt -= n) < out.dbsz)
    401 			break;
    402 	}
    403 
    404 	/* Reassemble the output block. */
    405 	if (out.dbcnt)
    406 		memmove(out.db, out.dbp - out.dbcnt, out.dbcnt);
    407 	out.dbp = out.db + out.dbcnt;
    408 }
    409