xref: /freebsd/bin/dd/dd.c (revision 39ee7a7a6bdd1557b1c3532abf60d139798ac88b)
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 
54 #include <assert.h>
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 <time.h>
65 #include <unistd.h>
66 
67 #include "dd.h"
68 #include "extern.h"
69 
70 static void dd_close(void);
71 static void dd_in(void);
72 static void getfdtype(IO *);
73 static void setup(void);
74 
75 IO	in, out;		/* input/output state */
76 STAT	st;			/* statistics */
77 void	(*cfunc)(void);		/* conversion function */
78 uintmax_t cpy_cnt;		/* # of blocks to copy */
79 static off_t	pending = 0;	/* pending seek if sparse */
80 static off_t	last_sp = 0;	/* size of last added sparse block */
81 u_int	ddflags = 0;		/* conversion options */
82 size_t	cbsz;			/* conversion block size */
83 uintmax_t files_cnt = 1;	/* # of files to copy */
84 const	u_char *ctab;		/* conversion table */
85 char	fill_char;		/* Character to fill with if defined */
86 volatile sig_atomic_t need_summary;
87 
88 int
89 main(int argc __unused, char *argv[])
90 {
91 	(void)setlocale(LC_CTYPE, "");
92 	jcl(argv);
93 	setup();
94 
95 	(void)signal(SIGINFO, siginfo_handler);
96 	(void)signal(SIGINT, terminate);
97 
98 	atexit(summary);
99 
100 	while (files_cnt--)
101 		dd_in();
102 
103 	dd_close();
104 	/*
105 	 * Some devices such as cfi(4) may perform significant amounts
106 	 * of work when a write descriptor is closed.  Close the out
107 	 * descriptor explicitly so that the summary handler (called
108 	 * from an atexit() hook) includes this work.
109 	 */
110 	close(out.fd);
111 	exit(0);
112 }
113 
114 static int
115 parity(u_char c)
116 {
117 	int i;
118 
119 	i = c ^ (c >> 1) ^ (c >> 2) ^ (c >> 3) ^
120 	    (c >> 4) ^ (c >> 5) ^ (c >> 6) ^ (c >> 7);
121 	return (i & 1);
122 }
123 
124 static void
125 setup(void)
126 {
127 	u_int cnt;
128 
129 	if (in.name == NULL) {
130 		in.name = "stdin";
131 		in.fd = STDIN_FILENO;
132 	} else {
133 		in.fd = open(in.name, O_RDONLY, 0);
134 		if (in.fd == -1)
135 			err(1, "%s", in.name);
136 	}
137 
138 	getfdtype(&in);
139 
140 	if (files_cnt > 1 && !(in.flags & ISTAPE))
141 		errx(1, "files is not supported for non-tape devices");
142 
143 	if (out.name == NULL) {
144 		/* No way to check for read access here. */
145 		out.fd = STDOUT_FILENO;
146 		out.name = "stdout";
147 	} else {
148 #define	OFLAGS \
149     (O_CREAT | (ddflags & (C_SEEK | C_NOTRUNC) ? 0 : O_TRUNC))
150 		out.fd = open(out.name, O_RDWR | OFLAGS, DEFFILEMODE);
151 		/*
152 		 * May not have read access, so try again with write only.
153 		 * Without read we may have a problem if output also does
154 		 * not support seeks.
155 		 */
156 		if (out.fd == -1) {
157 			out.fd = open(out.name, O_WRONLY | OFLAGS, DEFFILEMODE);
158 			out.flags |= NOREAD;
159 		}
160 		if (out.fd == -1)
161 			err(1, "%s", out.name);
162 	}
163 
164 	getfdtype(&out);
165 
166 	/*
167 	 * Allocate space for the input and output buffers.  If not doing
168 	 * record oriented I/O, only need a single buffer.
169 	 */
170 	if (!(ddflags & (C_BLOCK | C_UNBLOCK))) {
171 		if ((in.db = malloc(out.dbsz + in.dbsz - 1)) == NULL)
172 			err(1, "input buffer");
173 		out.db = in.db;
174 	} else if ((in.db = malloc(MAX(in.dbsz, cbsz) + cbsz)) == NULL ||
175 	    (out.db = malloc(out.dbsz + cbsz)) == NULL)
176 		err(1, "output buffer");
177 
178 	/* dbp is the first free position in each buffer. */
179 	in.dbp = in.db;
180 	out.dbp = out.db;
181 
182 	/* Position the input/output streams. */
183 	if (in.offset)
184 		pos_in();
185 	if (out.offset)
186 		pos_out();
187 
188 	/*
189 	 * Truncate the output file.  If it fails on a type of output file
190 	 * that it should _not_ fail on, error out.
191 	 */
192 	if ((ddflags & (C_OF | C_SEEK | C_NOTRUNC)) == (C_OF | C_SEEK) &&
193 	    out.flags & ISTRUNC)
194 		if (ftruncate(out.fd, out.offset * out.dbsz) == -1)
195 			err(1, "truncating %s", out.name);
196 
197 	if (ddflags & (C_LCASE  | C_UCASE | C_ASCII | C_EBCDIC | C_PARITY)) {
198 		if (ctab != NULL) {
199 			for (cnt = 0; cnt <= 0377; ++cnt)
200 				casetab[cnt] = ctab[cnt];
201 		} else {
202 			for (cnt = 0; cnt <= 0377; ++cnt)
203 				casetab[cnt] = cnt;
204 		}
205 		if ((ddflags & C_PARITY) && !(ddflags & C_ASCII)) {
206 			/*
207 			 * If the input is not EBCDIC, and we do parity
208 			 * processing, strip input parity.
209 			 */
210 			for (cnt = 200; cnt <= 0377; ++cnt)
211 				casetab[cnt] = casetab[cnt & 0x7f];
212 		}
213 		if (ddflags & C_LCASE) {
214 			for (cnt = 0; cnt <= 0377; ++cnt)
215 				casetab[cnt] = tolower(casetab[cnt]);
216 		} else if (ddflags & C_UCASE) {
217 			for (cnt = 0; cnt <= 0377; ++cnt)
218 				casetab[cnt] = toupper(casetab[cnt]);
219 		}
220 		if ((ddflags & C_PARITY)) {
221 			/*
222 			 * This should strictly speaking be a no-op, but I
223 			 * wonder what funny LANG settings could get us.
224 			 */
225 			for (cnt = 0; cnt <= 0377; ++cnt)
226 				casetab[cnt] = casetab[cnt] & 0x7f;
227 		}
228 		if ((ddflags & C_PARSET)) {
229 			for (cnt = 0; cnt <= 0377; ++cnt)
230 				casetab[cnt] = casetab[cnt] | 0x80;
231 		}
232 		if ((ddflags & C_PAREVEN)) {
233 			for (cnt = 0; cnt <= 0377; ++cnt)
234 				if (parity(casetab[cnt]))
235 					casetab[cnt] = casetab[cnt] | 0x80;
236 		}
237 		if ((ddflags & C_PARODD)) {
238 			for (cnt = 0; cnt <= 0377; ++cnt)
239 				if (!parity(casetab[cnt]))
240 					casetab[cnt] = casetab[cnt] | 0x80;
241 		}
242 
243 		ctab = casetab;
244 	}
245 
246 	if (clock_gettime(CLOCK_MONOTONIC, &st.start))
247 		err(1, "clock_gettime");
248 }
249 
250 static void
251 getfdtype(IO *io)
252 {
253 	struct stat sb;
254 	int type;
255 
256 	if (fstat(io->fd, &sb) == -1)
257 		err(1, "%s", io->name);
258 	if (S_ISREG(sb.st_mode))
259 		io->flags |= ISTRUNC;
260 	if (S_ISCHR(sb.st_mode) || S_ISBLK(sb.st_mode)) {
261 		if (ioctl(io->fd, FIODTYPE, &type) == -1) {
262 			err(1, "%s", io->name);
263 		} else {
264 			if (type & D_TAPE)
265 				io->flags |= ISTAPE;
266 			else if (type & (D_DISK | D_MEM))
267 				io->flags |= ISSEEK;
268 			if (S_ISCHR(sb.st_mode) && (type & D_TAPE) == 0)
269 				io->flags |= ISCHR;
270 		}
271 		return;
272 	}
273 	errno = 0;
274 	if (lseek(io->fd, (off_t)0, SEEK_CUR) == -1 && errno == ESPIPE)
275 		io->flags |= ISPIPE;
276 	else
277 		io->flags |= ISSEEK;
278 }
279 
280 static void
281 dd_in(void)
282 {
283 	ssize_t n;
284 
285 	for (;;) {
286 		switch (cpy_cnt) {
287 		case -1:			/* count=0 was specified */
288 			return;
289 		case 0:
290 			break;
291 		default:
292 			if (st.in_full + st.in_part >= (uintmax_t)cpy_cnt)
293 				return;
294 			break;
295 		}
296 
297 		/*
298 		 * Zero the buffer first if sync; if doing block operations,
299 		 * use spaces.
300 		 */
301 		if (ddflags & C_SYNC) {
302 			if (ddflags & C_FILL)
303 				memset(in.dbp, fill_char, in.dbsz);
304 			else if (ddflags & (C_BLOCK | C_UNBLOCK))
305 				memset(in.dbp, ' ', in.dbsz);
306 			else
307 				memset(in.dbp, 0, in.dbsz);
308 		}
309 
310 		n = read(in.fd, in.dbp, in.dbsz);
311 		if (n == 0) {
312 			in.dbrcnt = 0;
313 			return;
314 		}
315 
316 		/* Read error. */
317 		if (n == -1) {
318 			/*
319 			 * If noerror not specified, die.  POSIX requires that
320 			 * the warning message be followed by an I/O display.
321 			 */
322 			if (!(ddflags & C_NOERROR))
323 				err(1, "%s", in.name);
324 			warn("%s", in.name);
325 			summary();
326 
327 			/*
328 			 * If it's a seekable file descriptor, seek past the
329 			 * error.  If your OS doesn't do the right thing for
330 			 * raw disks this section should be modified to re-read
331 			 * in sector size chunks.
332 			 */
333 			if (in.flags & ISSEEK &&
334 			    lseek(in.fd, (off_t)in.dbsz, SEEK_CUR))
335 				warn("%s", in.name);
336 
337 			/* If sync not specified, omit block and continue. */
338 			if (!(ddflags & C_SYNC))
339 				continue;
340 
341 			/* Read errors count as full blocks. */
342 			in.dbcnt += in.dbrcnt = in.dbsz;
343 			++st.in_full;
344 
345 		/* Handle full input blocks. */
346 		} else if ((size_t)n == in.dbsz) {
347 			in.dbcnt += in.dbrcnt = n;
348 			++st.in_full;
349 
350 		/* Handle partial input blocks. */
351 		} else {
352 			/* If sync, use the entire block. */
353 			if (ddflags & C_SYNC)
354 				in.dbcnt += in.dbrcnt = in.dbsz;
355 			else
356 				in.dbcnt += in.dbrcnt = n;
357 			++st.in_part;
358 		}
359 
360 		/*
361 		 * POSIX states that if bs is set and no other conversions
362 		 * than noerror, notrunc or sync are specified, the block
363 		 * is output without buffering as it is read.
364 		 */
365 		if ((ddflags & ~(C_NOERROR | C_NOTRUNC | C_SYNC)) == C_BS) {
366 			out.dbcnt = in.dbcnt;
367 			dd_out(1);
368 			in.dbcnt = 0;
369 			continue;
370 		}
371 
372 		if (ddflags & C_SWAB) {
373 			if ((n = in.dbrcnt) & 1) {
374 				++st.swab;
375 				--n;
376 			}
377 			swab(in.dbp, in.dbp, (size_t)n);
378 		}
379 
380 		in.dbp += in.dbrcnt;
381 		(*cfunc)();
382 		if (need_summary) {
383 			summary();
384 		}
385 	}
386 }
387 
388 /*
389  * Clean up any remaining I/O and flush output.  If necessary, the output file
390  * is truncated.
391  */
392 static void
393 dd_close(void)
394 {
395 	if (cfunc == def)
396 		def_close();
397 	else if (cfunc == block)
398 		block_close();
399 	else if (cfunc == unblock)
400 		unblock_close();
401 	if (ddflags & C_OSYNC && out.dbcnt && out.dbcnt < out.dbsz) {
402 		if (ddflags & C_FILL)
403 			memset(out.dbp, fill_char, out.dbsz - out.dbcnt);
404 		else if (ddflags & (C_BLOCK | C_UNBLOCK))
405 			memset(out.dbp, ' ', out.dbsz - out.dbcnt);
406 		else
407 			memset(out.dbp, 0, out.dbsz - out.dbcnt);
408 		out.dbcnt = out.dbsz;
409 	}
410 	if (out.dbcnt || pending)
411 		dd_out(1);
412 }
413 
414 void
415 dd_out(int force)
416 {
417 	u_char *outp;
418 	size_t cnt, i, n;
419 	ssize_t nw;
420 	static int warned;
421 	int sparse;
422 
423 	/*
424 	 * Write one or more blocks out.  The common case is writing a full
425 	 * output block in a single write; increment the full block stats.
426 	 * Otherwise, we're into partial block writes.  If a partial write,
427 	 * and it's a character device, just warn.  If a tape device, quit.
428 	 *
429 	 * The partial writes represent two cases.  1: Where the input block
430 	 * was less than expected so the output block was less than expected.
431 	 * 2: Where the input block was the right size but we were forced to
432 	 * write the block in multiple chunks.  The original versions of dd(1)
433 	 * never wrote a block in more than a single write, so the latter case
434 	 * never happened.
435 	 *
436 	 * One special case is if we're forced to do the write -- in that case
437 	 * we play games with the buffer size, and it's usually a partial write.
438 	 */
439 	outp = out.db;
440 
441 	/*
442 	 * If force, first try to write all pending data, else try to write
443 	 * just one block. Subsequently always write data one full block at
444 	 * a time at most.
445 	 */
446 	for (n = force ? out.dbcnt : out.dbsz;; n = out.dbsz) {
447 		cnt = n;
448 		do {
449 			sparse = 0;
450 			if (ddflags & C_SPARSE) {
451 				sparse = 1;	/* Is buffer sparse? */
452 				for (i = 0; i < cnt; i++)
453 					if (outp[i] != 0) {
454 						sparse = 0;
455 						break;
456 					}
457 			}
458 			if (sparse && !force) {
459 				pending += cnt;
460 				last_sp = cnt;
461 				nw = cnt;
462 			} else {
463 				if (pending != 0) {
464 					/* If forced to write, and we have no
465 					 * data left, we need to write the last
466 					 * sparse block explicitly.
467 					 */
468 					if (force && cnt == 0) {
469 						pending -= last_sp;
470 						assert(outp == out.db);
471 						memset(outp, 0, cnt);
472 					}
473 					if (lseek(out.fd, pending, SEEK_CUR) ==
474 					    -1)
475 						err(2, "%s: seek error creating sparse file",
476 						    out.name);
477 					pending = last_sp = 0;
478 				}
479 				if (cnt)
480 					nw = write(out.fd, outp, cnt);
481 				else
482 					return;
483 			}
484 
485 			if (nw <= 0) {
486 				if (nw == 0)
487 					errx(1, "%s: end of device", out.name);
488 				if (errno != EINTR)
489 					err(1, "%s", out.name);
490 				nw = 0;
491 			}
492 
493 			outp += nw;
494 			st.bytes += nw;
495 
496 			if ((size_t)nw == n && n == out.dbsz)
497 				++st.out_full;
498 			else
499 				++st.out_part;
500 
501 			if ((size_t) nw != cnt) {
502 				if (out.flags & ISTAPE)
503 					errx(1, "%s: short write on tape device",
504 				    	out.name);
505 				if (out.flags & ISCHR && !warned) {
506 					warned = 1;
507 					warnx("%s: short write on character device",
508 				    	out.name);
509 				}
510 			}
511 
512 			cnt -= nw;
513 		} while (cnt != 0);
514 
515 		if ((out.dbcnt -= n) < out.dbsz)
516 			break;
517 	}
518 
519 	/* Reassemble the output block. */
520 	if (out.dbcnt)
521 		(void)memmove(out.db, out.dbp - out.dbcnt, out.dbcnt);
522 	out.dbp = out.db + out.dbcnt;
523 }
524