dd.c revision 111629
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
48#endif /* not lint */
49#include <sys/cdefs.h>
50__FBSDID("$FreeBSD: head/bin/dd/dd.c 111629 2003-02-27 18:04:54Z markm $");
51
52#include <sys/param.h>
53#include <sys/stat.h>
54#include <sys/conf.h>
55#include <sys/disklabel.h>
56#include <sys/filio.h>
57#include <sys/time.h>
58
59#include <ctype.h>
60#include <err.h>
61#include <errno.h>
62#include <fcntl.h>
63#include <inttypes.h>
64#include <locale.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
73static void dd_close(void);
74static void dd_in(void);
75static void getfdtype(IO *);
76static void setup(void);
77
78IO	in, out;		/* input/output state */
79STAT	st;			/* statistics */
80void	(*cfunc)(void);		/* conversion function */
81uintmax_t cpy_cnt;		/* # of blocks to copy */
82static off_t	pending = 0;	/* pending seek if sparse */
83u_int	ddflags = 0;		/* conversion options */
84size_t	cbsz;			/* conversion block size */
85uintmax_t files_cnt = 1;	/* # of files to copy */
86const	u_char *ctab;		/* conversion table */
87
88int
89main(int argc __unused, char *argv[])
90{
91	(void)setlocale(LC_CTYPE, "");
92	jcl(argv);
93	setup();
94
95	(void)signal(SIGINFO, summaryx);
96	(void)signal(SIGINT, terminate);
97
98	atexit(summary);
99
100	while (files_cnt--)
101		dd_in();
102
103	dd_close();
104	exit(0);
105}
106
107static void
108setup(void)
109{
110	u_int cnt;
111	struct timeval tv;
112
113	if (in.name == NULL) {
114		in.name = "stdin";
115		in.fd = STDIN_FILENO;
116	} else {
117		in.fd = open(in.name, O_RDONLY, 0);
118		if (in.fd == -1)
119			err(1, "%s", in.name);
120	}
121
122	getfdtype(&in);
123
124	if (files_cnt > 1 && !(in.flags & ISTAPE))
125		errx(1, "files is not supported for non-tape devices");
126
127	if (out.name == NULL) {
128		/* No way to check for read access here. */
129		out.fd = STDOUT_FILENO;
130		out.name = "stdout";
131	} else {
132#define	OFLAGS \
133    (O_CREAT | (ddflags & (C_SEEK | C_NOTRUNC) ? 0 : O_TRUNC))
134		out.fd = open(out.name, O_RDWR | OFLAGS, DEFFILEMODE);
135		/*
136		 * May not have read access, so try again with write only.
137		 * Without read we may have a problem if output also does
138		 * not support seeks.
139		 */
140		if (out.fd == -1) {
141			out.fd = open(out.name, O_WRONLY | OFLAGS, DEFFILEMODE);
142			out.flags |= NOREAD;
143		}
144		if (out.fd == -1)
145			err(1, "%s", out.name);
146	}
147
148	getfdtype(&out);
149
150	/*
151	 * Allocate space for the input and output buffers.  If not doing
152	 * record oriented I/O, only need a single buffer.
153	 */
154	if (!(ddflags & (C_BLOCK | C_UNBLOCK))) {
155		if ((in.db = malloc(out.dbsz + in.dbsz - 1)) == NULL)
156			err(1, "input buffer");
157		out.db = in.db;
158	} else if ((in.db = malloc(MAX(in.dbsz, cbsz) + cbsz)) == NULL ||
159	    (out.db = malloc(out.dbsz + cbsz)) == NULL)
160		err(1, "output buffer");
161	in.dbp = in.db;
162	out.dbp = out.db;
163
164	/* Position the input/output streams. */
165	if (in.offset)
166		pos_in();
167	if (out.offset)
168		pos_out();
169
170	/*
171	 * Truncate the output file.  If it fails on a type of output file
172	 * that it should _not_ fail on, error out.
173	 */
174	if ((ddflags & (C_OF | C_SEEK | C_NOTRUNC)) == (C_OF | C_SEEK) &&
175	    out.flags & ISTRUNC)
176		if (ftruncate(out.fd, out.offset * out.dbsz) == -1)
177			err(1, "truncating %s", out.name);
178
179	/*
180	 * If converting case at the same time as another conversion, build a
181	 * table that does both at once.  If just converting case, use the
182	 * built-in tables.
183	 */
184	if (ddflags & (C_LCASE | C_UCASE)) {
185		if (ddflags & (C_ASCII | C_EBCDIC)) {
186			if (ddflags & C_LCASE) {
187				for (cnt = 0; cnt <= 0377; ++cnt)
188					casetab[cnt] = tolower(ctab[cnt]);
189			} else {
190				for (cnt = 0; cnt <= 0377; ++cnt)
191					casetab[cnt] = toupper(ctab[cnt]);
192			}
193		} else {
194			if (ddflags & C_LCASE) {
195				for (cnt = 0; cnt <= 0377; ++cnt)
196					casetab[cnt] = tolower((int)cnt);
197			} else {
198				for (cnt = 0; cnt <= 0377; ++cnt)
199					casetab[cnt] = toupper((int)cnt);
200			}
201		}
202		ctab = casetab;
203	}
204
205	(void)gettimeofday(&tv, (struct timezone *)NULL);
206	st.start = tv.tv_sec + tv.tv_usec * 1e-6;
207}
208
209static void
210getfdtype(IO *io)
211{
212	struct stat sb;
213	int type;
214
215	if (fstat(io->fd, &sb) == -1)
216		err(1, "%s", io->name);
217	if (S_ISREG(sb.st_mode))
218		io->flags |= ISTRUNC;
219	if (S_ISCHR(sb.st_mode) || S_ISBLK(sb.st_mode)) {
220		if (ioctl(io->fd, FIODTYPE, &type) == -1) {
221			err(1, "%s", io->name);
222		} else {
223			if (type & D_TAPE)
224				io->flags |= ISTAPE;
225			else if (type & (D_DISK | D_MEM))
226				io->flags |= ISSEEK;
227			if (S_ISCHR(sb.st_mode) && (type & D_TAPE) == 0)
228				io->flags |= ISCHR;
229		}
230		return;
231	}
232	errno = 0;
233	if (lseek(io->fd, (off_t)0, SEEK_CUR) == -1 && errno == ESPIPE)
234		io->flags |= ISPIPE;
235	else
236		io->flags |= ISSEEK;
237}
238
239static void
240dd_in(void)
241{
242	ssize_t n;
243
244	for (;;) {
245		switch (cpy_cnt) {
246		case -1:			/* count=0 was specified */
247			return;
248		case 0:
249			break;
250		default:
251			if (st.in_full + st.in_part >= (uintmax_t)cpy_cnt)
252				return;
253			break;
254		}
255
256		/*
257		 * Zero the buffer first if sync; if doing block operations,
258		 * use spaces.
259		 */
260		if (ddflags & C_SYNC) {
261			if (ddflags & (C_BLOCK | C_UNBLOCK))
262				memset(in.dbp, ' ', in.dbsz);
263			else
264				memset(in.dbp, 0, in.dbsz);
265		}
266
267		n = read(in.fd, in.dbp, in.dbsz);
268		if (n == 0) {
269			in.dbrcnt = 0;
270			return;
271		}
272
273		/* Read error. */
274		if (n == -1) {
275			/*
276			 * If noerror not specified, die.  POSIX requires that
277			 * the warning message be followed by an I/O display.
278			 */
279			if (!(ddflags & C_NOERROR))
280				err(1, "%s", in.name);
281			warn("%s", in.name);
282			summary();
283
284			/*
285			 * If it's a seekable file descriptor, seek past the
286			 * error.  If your OS doesn't do the right thing for
287			 * raw disks this section should be modified to re-read
288			 * in sector size chunks.
289			 */
290			if (in.flags & ISSEEK &&
291			    lseek(in.fd, (off_t)in.dbsz, SEEK_CUR))
292				warn("%s", in.name);
293
294			/* If sync not specified, omit block and continue. */
295			if (!(ddflags & C_SYNC))
296				continue;
297
298			/* Read errors count as full blocks. */
299			in.dbcnt += in.dbrcnt = in.dbsz;
300			++st.in_full;
301
302		/* Handle full input blocks. */
303		} else if ((size_t)n == in.dbsz) {
304			in.dbcnt += in.dbrcnt = n;
305			++st.in_full;
306
307		/* Handle partial input blocks. */
308		} else {
309			/* If sync, use the entire block. */
310			if (ddflags & C_SYNC)
311				in.dbcnt += in.dbrcnt = in.dbsz;
312			else
313				in.dbcnt += in.dbrcnt = n;
314			++st.in_part;
315		}
316
317		/*
318		 * POSIX states that if bs is set and no other conversions
319		 * than noerror, notrunc or sync are specified, the block
320		 * is output without buffering as it is read.
321		 */
322		if (ddflags & C_BS) {
323			out.dbcnt = in.dbcnt;
324			dd_out(1);
325			in.dbcnt = 0;
326			continue;
327		}
328
329		if (ddflags & C_SWAB) {
330			if ((n = in.dbrcnt) & 1) {
331				++st.swab;
332				--n;
333			}
334			swab(in.dbp, in.dbp, (size_t)n);
335		}
336
337		in.dbp += in.dbrcnt;
338		(*cfunc)();
339	}
340}
341
342/*
343 * Clean up any remaining I/O and flush output.  If necessary, the output file
344 * is truncated.
345 */
346static void
347dd_close(void)
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.dbcnt < out.dbsz) {
356		if (ddflags & (C_BLOCK | C_UNBLOCK))
357			memset(out.dbp, ' ', out.dbsz - out.dbcnt);
358		else
359			memset(out.dbp, 0, out.dbsz - out.dbcnt);
360		out.dbcnt = out.dbsz;
361	}
362	if (out.dbcnt || pending)
363		dd_out(1);
364}
365
366void
367dd_out(int force)
368{
369	u_char *outp;
370	size_t cnt, i, n;
371	ssize_t nw;
372	static int warned;
373	int sparse;
374
375	/*
376	 * Write one or more blocks out.  The common case is writing a full
377	 * output block in a single write; increment the full block stats.
378	 * Otherwise, we're into partial block writes.  If a partial write,
379	 * and it's a character device, just warn.  If a tape device, quit.
380	 *
381	 * The partial writes represent two cases.  1: Where the input block
382	 * was less than expected so the output block was less than expected.
383	 * 2: Where the input block was the right size but we were forced to
384	 * write the block in multiple chunks.  The original versions of dd(1)
385	 * never wrote a block in more than a single write, so the latter case
386	 * never happened.
387	 *
388	 * One special case is if we're forced to do the write -- in that case
389	 * we play games with the buffer size, and it's usually a partial write.
390	 */
391	outp = out.db;
392	for (n = force ? out.dbcnt : out.dbsz;; n = out.dbsz) {
393		for (cnt = n;; cnt -= nw) {
394			sparse = 0;
395			if (ddflags & C_SPARSE) {
396				sparse = 1;	/* Is buffer sparse? */
397				for (i = 0; i < cnt; i++)
398					if (outp[i] != 0) {
399						sparse = 0;
400						break;
401					}
402			}
403			if (sparse && !force) {
404				pending += cnt;
405				nw = cnt;
406			} else {
407				if (pending != 0) {
408					if (force)
409						pending--;
410					if (lseek(out.fd, pending, SEEK_CUR) ==
411					    -1)
412						err(2, "%s: seek error creating sparse file",
413						    out.name);
414					if (force)
415						write(out.fd, outp, 1);
416					pending = 0;
417				}
418				if (cnt)
419					nw = write(out.fd, outp, cnt);
420				else
421					return;
422			}
423
424			if (nw <= 0) {
425				if (nw == 0)
426					errx(1, "%s: end of device", out.name);
427				if (errno != EINTR)
428					err(1, "%s", out.name);
429				nw = 0;
430			}
431			outp += nw;
432			st.bytes += nw;
433			if ((size_t)nw == n) {
434				if (n != out.dbsz)
435					++st.out_part;
436				else
437					++st.out_full;
438				break;
439			}
440			++st.out_part;
441			if ((size_t)nw == cnt)
442				break;
443			if (out.flags & ISTAPE)
444				errx(1, "%s: short write on tape device",
445				    out.name);
446			if (out.flags & ISCHR && !warned) {
447				warned = 1;
448				warnx("%s: short write on character device",
449				    out.name);
450			}
451		}
452		if ((out.dbcnt -= n) < out.dbsz)
453			break;
454	}
455
456	/* Reassemble the output block. */
457	if (out.dbcnt)
458		(void)memmove(out.db, out.dbp - out.dbcnt, out.dbcnt);
459	out.dbp = out.db + out.dbcnt;
460}
461