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