dd.c revision 50487
1/*-
2 * Copyright (c) 1991, 1993, 1994
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * Keith Muller of the University of California, San Diego and Lance
7 * Visser of Convex Computer Corporation.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 *    notice, this list of conditions and the following disclaimer in the
16 *    documentation and/or other materials provided with the distribution.
17 * 3. All advertising materials mentioning features or use of this software
18 *    must display the following acknowledgement:
19 *	This product includes software developed by the University of
20 *	California, Berkeley and its contributors.
21 * 4. Neither the name of the University nor the names of its contributors
22 *    may be used to endorse or promote products derived from this software
23 *    without specific prior written permission.
24 *
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * SUCH DAMAGE.
36 */
37
38#ifndef lint
39static char const copyright[] =
40"@(#) Copyright (c) 1991, 1993, 1994\n\
41	The Regents of the University of California.  All rights reserved.\n";
42#endif /* not lint */
43
44#ifndef lint
45#if 0
46static char sccsid[] = "@(#)dd.c	8.5 (Berkeley) 4/2/94";
47#endif
48static const char rcsid[] =
49  "$FreeBSD: head/bin/dd/dd.c 50487 1999-08-28 03:37:38Z green $";
50#endif /* not lint */
51
52#include <sys/param.h>
53#include <sys/stat.h>
54#include <sys/conf.h>
55#include <sys/diskslice.h>
56#include <sys/filio.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 <locale.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
72static void dd_close __P((void));
73static void dd_in __P((void));
74static void getfdtype __P((IO *));
75static void setup __P((void));
76
77IO	in, out;		/* input/output state */
78STAT	st;			/* statistics */
79void	(*cfunc) __P((void));	/* conversion function */
80quad_t	cpy_cnt;		/* # of blocks to copy */
81off_t	pending = 0;		/* pending seek if sparse */
82u_int	ddflags;		/* conversion options */
83int	cbsz;			/* conversion block size */
84quad_t	files_cnt = 1;		/* # of files to copy */
85u_char	*ctab;			/* conversion table */
86
87int
88main(argc, argv)
89	int argc;
90	char *argv[];
91{
92	(void)setlocale(LC_CTYPE, "");
93	jcl(argv);
94	setup();
95
96	(void)signal(SIGINFO, summaryx);
97	(void)signal(SIGINT, terminate);
98
99	atexit(summary);
100
101	while (files_cnt--)
102		dd_in();
103
104	dd_close();
105	exit(0);
106}
107
108static void
109setup()
110{
111	u_int cnt;
112	struct timeval tv;
113
114	if (in.name == NULL) {
115		in.name = "stdin";
116		in.fd = STDIN_FILENO;
117	} else {
118		in.fd = open(in.name, O_RDONLY, 0);
119		if (in.fd == -1)
120			err(1, "%s", in.name);
121	}
122
123	getfdtype(&in);
124
125	if (files_cnt > 1 && !(in.flags & ISTAPE))
126		errx(1, "files is not supported for non-tape devices");
127
128	if (out.name == NULL) {
129		/* No way to check for read access here. */
130		out.fd = STDOUT_FILENO;
131		out.name = "stdout";
132	} else {
133#define	OFLAGS \
134    (O_CREAT | (ddflags & (C_SEEK | C_NOTRUNC) ? 0 : O_TRUNC))
135		out.fd = open(out.name, O_RDWR | OFLAGS, DEFFILEMODE);
136		/*
137		 * May not have read access, so try again with write only.
138		 * Without read we may have a problem if output also does
139		 * not support seeks.
140		 */
141		if (out.fd == -1) {
142			out.fd = open(out.name, O_WRONLY | OFLAGS, DEFFILEMODE);
143			out.flags |= NOREAD;
144		}
145		if (out.fd == -1)
146			err(1, "%s", out.name);
147	}
148
149	getfdtype(&out);
150
151	/*
152	 * Allocate space for the input and output buffers.  If not doing
153	 * record oriented I/O, only need a single buffer.
154	 */
155	if (!(ddflags & (C_BLOCK|C_UNBLOCK))) {
156		if ((in.db = malloc(out.dbsz + in.dbsz - 1)) == NULL)
157			err(1, NULL);
158		out.db = in.db;
159	} else if ((in.db = malloc((u_int)(MAX(in.dbsz, cbsz) + cbsz))) == NULL
160		   || (out.db = malloc((u_int)(out.dbsz + cbsz))) == NULL)
161		err(1, NULL);
162	in.dbp = in.db;
163	out.dbp = out.db;
164
165	/* Position the input/output streams. */
166	if (in.offset)
167		pos_in();
168	if (out.offset)
169		pos_out();
170
171	/*
172	 * Truncate the output file; ignore errors because it fails on some
173	 * kinds of output files, tapes, for example.
174	 */
175	if ((ddflags & (C_OF | C_SEEK | C_NOTRUNC)) == (C_OF | C_SEEK))
176		(void)ftruncate(out.fd, out.offset * out.dbsz);
177
178	/*
179	 * If converting case at the same time as another conversion, build a
180	 * table that does both at once.  If just converting case, use the
181	 * built-in tables.
182	 */
183	if (ddflags & (C_LCASE|C_UCASE)) {
184		if (ddflags & C_ASCII) {
185			if (ddflags & C_LCASE) {
186				for (cnt = 0; cnt <= 0377; ++cnt)
187					if (isupper(ctab[cnt]))
188						ctab[cnt] = tolower(ctab[cnt]);
189			} else {
190				for (cnt = 0; cnt <= 0377; ++cnt)
191					if (islower(ctab[cnt]))
192						ctab[cnt] = toupper(ctab[cnt]);
193			}
194		} else if (ddflags & C_EBCDIC) {
195			if (ddflags & C_LCASE) {
196				for (cnt = 0; cnt <= 0377; ++cnt)
197					if (isupper(cnt))
198						ctab[cnt] = ctab[tolower(cnt)];
199			} else {
200				for (cnt = 0; cnt <= 0377; ++cnt)
201					if (islower(cnt))
202						ctab[cnt] = ctab[toupper(cnt)];
203			}
204		} else {
205			ctab = ddflags & C_LCASE ? u2l : l2u;
206			if (ddflags & C_LCASE) {
207				for (cnt = 0; cnt <= 0377; ++cnt)
208					if (isupper(cnt))
209						ctab[cnt] = tolower(cnt);
210					else
211						ctab[cnt] = cnt;
212			} else {
213				for (cnt = 0; cnt <= 0377; ++cnt)
214					if (islower(cnt))
215						ctab[cnt] = toupper(cnt);
216					else
217						ctab[cnt] = cnt;
218			}
219		}
220	}
221	(void)gettimeofday(&tv, (struct timezone *)NULL);
222	st.start = tv.tv_sec + tv.tv_usec * 1e-6;
223}
224
225static void
226getfdtype(io)
227	IO *io;
228{
229	struct stat sb;
230	int type;
231
232	if (fstat(io->fd, &sb))
233		err(1, "%s", io->name);
234	if (S_ISCHR(sb.st_mode) || S_ISBLK(sb.st_mode)) {
235		if (ioctl(io->fd, FIODTYPE, &type) == -1) {
236			warn("%s", io->name);
237			if (S_ISCHR(sb.st_mode))
238				io->flags |= ISCHR;
239		} else {
240			if (type & D_TAPE)
241				io->flags |= ISTAPE;
242			else if (type & D_DISK)
243				io->flags |= ISDISK;
244			if (S_ISCHR(sb.st_mode) && (type & D_TAPE) == 0)
245				io->flags |= ISCHR;
246		}
247	} else if (!S_ISREG(sb.st_mode))
248		io->flags |= ISPIPE;
249}
250
251static void
252dd_in()
253{
254	ssize_t n;
255
256	for (;;) {
257		if (cpy_cnt && (st.in_full + st.in_part) >= cpy_cnt)
258			return;
259
260		/*
261		 * Zero the buffer first if sync; If doing block operations
262		 * use spaces.
263		 */
264		if (ddflags & C_SYNC) {
265			if (ddflags & (C_BLOCK|C_UNBLOCK))
266				memset(in.dbp, ' ', in.dbsz);
267			else
268				memset(in.dbp, 0, in.dbsz);
269		}
270
271		n = read(in.fd, in.dbp, in.dbsz);
272		if (n == 0) {
273			in.dbrcnt = 0;
274			return;
275		}
276
277		/* Read error. */
278		if (n == -1) {
279			/*
280			 * If noerror not specified, die.  POSIX requires that
281			 * the warning message be followed by an I/O display.
282			 */
283			if (!(ddflags & C_NOERROR))
284				err(1, "%s", in.name);
285			warn("%s", in.name);
286			summary();
287
288			/*
289			 * If it's not a tape drive or a pipe, seek past the
290			 * error.  If your OS doesn't do the right thing for
291			 * raw disks this section should be modified to re-read
292			 * in sector size chunks.
293			 */
294			if (!(in.flags & (ISPIPE|ISTAPE)) &&
295			    lseek(in.fd, (off_t)in.dbsz, SEEK_CUR))
296				warn("%s", in.name);
297
298			/* If sync not specified, omit block and continue. */
299			if (!(ddflags & C_SYNC))
300				continue;
301
302			/* Read errors count as full blocks. */
303			in.dbcnt += in.dbrcnt = in.dbsz;
304			++st.in_full;
305
306		/* Handle full input blocks. */
307		} else if (n == in.dbsz) {
308			in.dbcnt += in.dbrcnt = n;
309			++st.in_full;
310
311		/* Handle partial input blocks. */
312		} else {
313			/* If sync, use the entire block. */
314			if (ddflags & C_SYNC)
315				in.dbcnt += in.dbrcnt = in.dbsz;
316			else
317				in.dbcnt += in.dbrcnt = n;
318			++st.in_part;
319		}
320
321		/*
322		 * POSIX states that if bs is set and no other conversions
323		 * than noerror, notrunc or sync are specified, the block
324		 * is output without buffering as it is read.
325		 */
326		if (ddflags & C_BS) {
327			out.dbcnt = in.dbcnt;
328			dd_out(1);
329			in.dbcnt = 0;
330			continue;
331		}
332
333		if (ddflags & C_SWAB) {
334			if ((n = in.dbrcnt) & 1) {
335				++st.swab;
336				--n;
337			}
338			swab(in.dbp, in.dbp, n);
339		}
340
341		in.dbp += in.dbrcnt;
342		(*cfunc)();
343	}
344}
345
346/*
347 * Cleanup any remaining I/O and flush output.  If necesssary, output file
348 * is truncated.
349 */
350static void
351dd_close()
352{
353	if (cfunc == def)
354		def_close();
355	else if (cfunc == block)
356		block_close();
357	else if (cfunc == unblock)
358		unblock_close();
359	if (ddflags & C_OSYNC && out.dbcnt && out.dbcnt < out.dbsz) {
360		if (ddflags & (C_BLOCK|C_UNBLOCK))
361			memset(out.dbp, ' ', out.dbsz - out.dbcnt);
362		else
363			memset(out.dbp, 0, out.dbsz - out.dbcnt);
364		out.dbcnt = out.dbsz;
365	}
366	if (out.dbcnt || pending)
367		dd_out(1);
368}
369
370void
371dd_out(force)
372	int force;
373{
374	static int warned;
375	int cnt, n, i, sparse;
376	ssize_t nw;
377	u_char *outp;
378
379	/*
380	 * Write one or more blocks out.  The common case is writing a full
381	 * output block in a single write; increment the full block stats.
382	 * Otherwise, we're into partial block writes.  If a partial write,
383	 * and it's a character device, just warn.  If a tape device, quit.
384	 *
385	 * The partial writes represent two cases.  1: Where the input block
386	 * was less than expected so the output block was less than expected.
387	 * 2: Where the input block was the right size but we were forced to
388	 * write the block in multiple chunks.  The original versions of dd(1)
389	 * never wrote a block in more than a single write, so the latter case
390	 * never happened.
391	 *
392	 * One special case is if we're forced to do the write -- in that case
393	 * we play games with the buffer size, and it's usually a partial write.
394	 */
395	outp = out.db;
396	for (n = force ? out.dbcnt : out.dbsz;; n = out.dbsz) {
397		for (cnt = n;; cnt -= nw) {
398			sparse = 0;
399			if (ddflags & C_SPARSE) {
400				sparse = 1;	/* Is buffer sparse? */
401				for (i = 0; i < cnt; i++)
402					if (outp[i] != 0) {
403						sparse = 0;
404						break;
405					}
406			}
407			if (sparse && !force) {
408				pending += cnt;
409				nw = cnt;
410			} else {
411				if (pending != 0) {
412					if (force)
413						pending--;
414					if (lseek(out.fd, pending, SEEK_CUR) ==
415					    -1)
416						err(2, "%s: seek error creating sparse file",
417						    out.name);
418					if (force)
419						write(out.fd, outp, 1);
420					pending = 0;
421				}
422				if (cnt)
423					nw = write(out.fd, outp, cnt);
424				else
425					return;
426			}
427
428			if (nw <= 0) {
429				if (nw == 0)
430					errx(1, "%s: end of device", out.name);
431				if (errno != EINTR)
432					err(1, "%s", out.name);
433				nw = 0;
434			}
435			outp += nw;
436			st.bytes += nw;
437			if (nw == n) {
438				if (n != out.dbsz)
439					++st.out_part;
440				else
441					++st.out_full;
442				break;
443			}
444			++st.out_part;
445			if (nw == cnt)
446				break;
447			if (out.flags & ISCHR && !warned) {
448				warned = 1;
449				warnx("%s: short write on character device",
450				    out.name);
451			}
452			if (out.flags & ISTAPE)
453				errx(1, "%s: short write on tape device", out.name);
454		}
455		if ((out.dbcnt -= n) < out.dbsz)
456			break;
457	}
458
459	/* Reassemble the output block. */
460	if (out.dbcnt)
461		memmove(out.db, out.dbp - out.dbcnt, out.dbcnt);
462	out.dbp = out.db + out.dbcnt;
463}
464