xref: /freebsd/bin/dd/dd.c (revision 0957b409a90fd597c1e9124cbaf3edd2b488f4ac)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
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. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #if 0
37 #ifndef lint
38 static char const copyright[] =
39 "@(#) Copyright (c) 1991, 1993, 1994\n\
40 	The Regents of the University of California.  All rights reserved.\n";
41 #endif /* not lint */
42 
43 #ifndef lint
44 static char sccsid[] = "@(#)dd.c	8.5 (Berkeley) 4/2/94";
45 #endif /* not lint */
46 #endif
47 #include <sys/cdefs.h>
48 __FBSDID("$FreeBSD$");
49 
50 #include <sys/param.h>
51 #include <sys/stat.h>
52 #include <sys/capsicum.h>
53 #include <sys/conf.h>
54 #include <sys/disklabel.h>
55 #include <sys/filio.h>
56 #include <sys/mtio.h>
57 #include <sys/time.h>
58 
59 #include <assert.h>
60 #include <capsicum_helpers.h>
61 #include <ctype.h>
62 #include <err.h>
63 #include <errno.h>
64 #include <fcntl.h>
65 #include <inttypes.h>
66 #include <locale.h>
67 #include <stdio.h>
68 #include <stdlib.h>
69 #include <string.h>
70 #include <time.h>
71 #include <unistd.h>
72 
73 #include "dd.h"
74 #include "extern.h"
75 
76 static void dd_close(void);
77 static void dd_in(void);
78 static void getfdtype(IO *);
79 static void setup(void);
80 
81 IO	in, out;		/* input/output state */
82 STAT	st;			/* statistics */
83 void	(*cfunc)(void);		/* conversion function */
84 uintmax_t cpy_cnt;		/* # of blocks to copy */
85 static off_t	pending = 0;	/* pending seek if sparse */
86 u_int	ddflags = 0;		/* conversion options */
87 size_t	cbsz;			/* conversion block size */
88 uintmax_t files_cnt = 1;	/* # of files to copy */
89 const	u_char *ctab;		/* conversion table */
90 char	fill_char;		/* Character to fill with if defined */
91 size_t	speed = 0;		/* maximum speed, in bytes per second */
92 volatile sig_atomic_t need_summary;
93 volatile sig_atomic_t need_progress;
94 
95 int
96 main(int argc __unused, char *argv[])
97 {
98 	struct itimerval itv = { { 1, 0 }, { 1, 0 } }; /* SIGALARM every second, if needed */
99 
100 	(void)setlocale(LC_CTYPE, "");
101 	jcl(argv);
102 	setup();
103 
104 	caph_cache_catpages();
105 	if (caph_enter() < 0)
106 		err(1, "unable to enter capability mode");
107 
108 	(void)signal(SIGINFO, siginfo_handler);
109 	if (ddflags & C_PROGRESS) {
110 		(void)signal(SIGALRM, sigalarm_handler);
111 		setitimer(ITIMER_REAL, &itv, NULL);
112 	}
113 	(void)signal(SIGINT, terminate);
114 
115 	atexit(summary);
116 
117 	while (files_cnt--)
118 		dd_in();
119 
120 	dd_close();
121 	/*
122 	 * Some devices such as cfi(4) may perform significant amounts
123 	 * of work when a write descriptor is closed.  Close the out
124 	 * descriptor explicitly so that the summary handler (called
125 	 * from an atexit() hook) includes this work.
126 	 */
127 	close(out.fd);
128 	exit(0);
129 }
130 
131 static int
132 parity(u_char c)
133 {
134 	int i;
135 
136 	i = c ^ (c >> 1) ^ (c >> 2) ^ (c >> 3) ^
137 	    (c >> 4) ^ (c >> 5) ^ (c >> 6) ^ (c >> 7);
138 	return (i & 1);
139 }
140 
141 static void
142 setup(void)
143 {
144 	u_int cnt;
145 	cap_rights_t rights;
146 	unsigned long cmds[] = { FIODTYPE, MTIOCTOP };
147 
148 	if (in.name == NULL) {
149 		in.name = "stdin";
150 		in.fd = STDIN_FILENO;
151 	} else {
152 		in.fd = open(in.name, O_RDONLY, 0);
153 		if (in.fd == -1)
154 			err(1, "%s", in.name);
155 	}
156 
157 	getfdtype(&in);
158 
159 	cap_rights_init(&rights, CAP_READ, CAP_SEEK);
160 	if (caph_rights_limit(in.fd, &rights) == -1)
161 		err(1, "unable to limit capability rights");
162 
163 	if (files_cnt > 1 && !(in.flags & ISTAPE))
164 		errx(1, "files is not supported for non-tape devices");
165 
166 	cap_rights_set(&rights, CAP_FTRUNCATE, CAP_IOCTL, CAP_WRITE);
167 	if (out.name == NULL) {
168 		/* No way to check for read access here. */
169 		out.fd = STDOUT_FILENO;
170 		out.name = "stdout";
171 	} else {
172 #define	OFLAGS \
173     (O_CREAT | (ddflags & (C_SEEK | C_NOTRUNC) ? 0 : O_TRUNC))
174 		out.fd = open(out.name, O_RDWR | OFLAGS, DEFFILEMODE);
175 		/*
176 		 * May not have read access, so try again with write only.
177 		 * Without read we may have a problem if output also does
178 		 * not support seeks.
179 		 */
180 		if (out.fd == -1) {
181 			out.fd = open(out.name, O_WRONLY | OFLAGS, DEFFILEMODE);
182 			out.flags |= NOREAD;
183 			cap_rights_clear(&rights, CAP_READ);
184 		}
185 		if (out.fd == -1)
186 			err(1, "%s", out.name);
187 	}
188 
189 	getfdtype(&out);
190 
191 	if (caph_rights_limit(out.fd, &rights) == -1)
192 		err(1, "unable to limit capability rights");
193 	if (caph_ioctls_limit(out.fd, cmds, nitems(cmds)) == -1)
194 		err(1, "unable to limit capability rights");
195 
196 	if (in.fd != STDIN_FILENO && out.fd != STDIN_FILENO) {
197 		if (caph_limit_stdin() == -1)
198 			err(1, "unable to limit capability rights");
199 	}
200 
201 	if (in.fd != STDOUT_FILENO && out.fd != STDOUT_FILENO) {
202 		if (caph_limit_stdout() == -1)
203 			err(1, "unable to limit capability rights");
204 	}
205 
206 	if (in.fd != STDERR_FILENO && out.fd != STDERR_FILENO) {
207 		if (caph_limit_stderr() == -1)
208 			err(1, "unable to limit capability rights");
209 	}
210 
211 	/*
212 	 * Allocate space for the input and output buffers.  If not doing
213 	 * record oriented I/O, only need a single buffer.
214 	 */
215 	if (!(ddflags & (C_BLOCK | C_UNBLOCK))) {
216 		if ((in.db = malloc((size_t)out.dbsz + in.dbsz - 1)) == NULL)
217 			err(1, "input buffer");
218 		out.db = in.db;
219 	} else if ((in.db = malloc(MAX((size_t)in.dbsz, cbsz) + cbsz)) == NULL ||
220 	    (out.db = malloc(out.dbsz + cbsz)) == NULL)
221 		err(1, "output buffer");
222 
223 	/* dbp is the first free position in each buffer. */
224 	in.dbp = in.db;
225 	out.dbp = out.db;
226 
227 	/* Position the input/output streams. */
228 	if (in.offset)
229 		pos_in();
230 	if (out.offset)
231 		pos_out();
232 
233 	/*
234 	 * Truncate the output file.  If it fails on a type of output file
235 	 * that it should _not_ fail on, error out.
236 	 */
237 	if ((ddflags & (C_OF | C_SEEK | C_NOTRUNC)) == (C_OF | C_SEEK) &&
238 	    out.flags & ISTRUNC)
239 		if (ftruncate(out.fd, out.offset * out.dbsz) == -1)
240 			err(1, "truncating %s", out.name);
241 
242 	if (ddflags & (C_LCASE  | C_UCASE | C_ASCII | C_EBCDIC | C_PARITY)) {
243 		if (ctab != NULL) {
244 			for (cnt = 0; cnt <= 0377; ++cnt)
245 				casetab[cnt] = ctab[cnt];
246 		} else {
247 			for (cnt = 0; cnt <= 0377; ++cnt)
248 				casetab[cnt] = cnt;
249 		}
250 		if ((ddflags & C_PARITY) && !(ddflags & C_ASCII)) {
251 			/*
252 			 * If the input is not EBCDIC, and we do parity
253 			 * processing, strip input parity.
254 			 */
255 			for (cnt = 200; cnt <= 0377; ++cnt)
256 				casetab[cnt] = casetab[cnt & 0x7f];
257 		}
258 		if (ddflags & C_LCASE) {
259 			for (cnt = 0; cnt <= 0377; ++cnt)
260 				casetab[cnt] = tolower(casetab[cnt]);
261 		} else if (ddflags & C_UCASE) {
262 			for (cnt = 0; cnt <= 0377; ++cnt)
263 				casetab[cnt] = toupper(casetab[cnt]);
264 		}
265 		if ((ddflags & C_PARITY)) {
266 			/*
267 			 * This should strictly speaking be a no-op, but I
268 			 * wonder what funny LANG settings could get us.
269 			 */
270 			for (cnt = 0; cnt <= 0377; ++cnt)
271 				casetab[cnt] = casetab[cnt] & 0x7f;
272 		}
273 		if ((ddflags & C_PARSET)) {
274 			for (cnt = 0; cnt <= 0377; ++cnt)
275 				casetab[cnt] = casetab[cnt] | 0x80;
276 		}
277 		if ((ddflags & C_PAREVEN)) {
278 			for (cnt = 0; cnt <= 0377; ++cnt)
279 				if (parity(casetab[cnt]))
280 					casetab[cnt] = casetab[cnt] | 0x80;
281 		}
282 		if ((ddflags & C_PARODD)) {
283 			for (cnt = 0; cnt <= 0377; ++cnt)
284 				if (!parity(casetab[cnt]))
285 					casetab[cnt] = casetab[cnt] | 0x80;
286 		}
287 
288 		ctab = casetab;
289 	}
290 
291 	if (clock_gettime(CLOCK_MONOTONIC, &st.start))
292 		err(1, "clock_gettime");
293 }
294 
295 static void
296 getfdtype(IO *io)
297 {
298 	struct stat sb;
299 	int type;
300 
301 	if (fstat(io->fd, &sb) == -1)
302 		err(1, "%s", io->name);
303 	if (S_ISREG(sb.st_mode))
304 		io->flags |= ISTRUNC;
305 	if (S_ISCHR(sb.st_mode) || S_ISBLK(sb.st_mode)) {
306 		if (ioctl(io->fd, FIODTYPE, &type) == -1) {
307 			err(1, "%s", io->name);
308 		} else {
309 			if (type & D_TAPE)
310 				io->flags |= ISTAPE;
311 			else if (type & (D_DISK | D_MEM))
312 				io->flags |= ISSEEK;
313 			if (S_ISCHR(sb.st_mode) && (type & D_TAPE) == 0)
314 				io->flags |= ISCHR;
315 		}
316 		return;
317 	}
318 	errno = 0;
319 	if (lseek(io->fd, (off_t)0, SEEK_CUR) == -1 && errno == ESPIPE)
320 		io->flags |= ISPIPE;
321 	else
322 		io->flags |= ISSEEK;
323 }
324 
325 /*
326  * Limit the speed by adding a delay before every block read.
327  * The delay (t_usleep) is equal to the time computed from block
328  * size and the specified speed limit (t_target) minus the time
329  * spent on actual read and write operations (t_io).
330  */
331 static void
332 speed_limit(void)
333 {
334 	static double t_prev, t_usleep;
335 	double t_now, t_io, t_target;
336 
337 	t_now = secs_elapsed();
338 	t_io = t_now - t_prev - t_usleep;
339 	t_target = (double)in.dbsz / (double)speed;
340 	t_usleep = t_target - t_io;
341 	if (t_usleep > 0)
342 		usleep(t_usleep * 1000000);
343 	else
344 		t_usleep = 0;
345 	t_prev = t_now;
346 }
347 
348 static void
349 swapbytes(void *v, size_t len)
350 {
351 	unsigned char *p = v;
352 	unsigned char t;
353 
354 	while (len > 1) {
355 		t = p[0];
356 		p[0] = p[1];
357 		p[1] = t;
358 		p += 2;
359 		len -= 2;
360 	}
361 }
362 
363 static void
364 dd_in(void)
365 {
366 	ssize_t n;
367 
368 	for (;;) {
369 		switch (cpy_cnt) {
370 		case -1:			/* count=0 was specified */
371 			return;
372 		case 0:
373 			break;
374 		default:
375 			if (st.in_full + st.in_part >= (uintmax_t)cpy_cnt)
376 				return;
377 			break;
378 		}
379 
380 		if (speed > 0)
381 			speed_limit();
382 
383 		/*
384 		 * Zero the buffer first if sync; if doing block operations,
385 		 * use spaces.
386 		 */
387 		if (ddflags & C_SYNC) {
388 			if (ddflags & C_FILL)
389 				memset(in.dbp, fill_char, in.dbsz);
390 			else if (ddflags & (C_BLOCK | C_UNBLOCK))
391 				memset(in.dbp, ' ', in.dbsz);
392 			else
393 				memset(in.dbp, 0, in.dbsz);
394 		}
395 
396 		n = read(in.fd, in.dbp, in.dbsz);
397 		if (n == 0) {
398 			in.dbrcnt = 0;
399 			return;
400 		}
401 
402 		/* Read error. */
403 		if (n == -1) {
404 			/*
405 			 * If noerror not specified, die.  POSIX requires that
406 			 * the warning message be followed by an I/O display.
407 			 */
408 			if (!(ddflags & C_NOERROR))
409 				err(1, "%s", in.name);
410 			warn("%s", in.name);
411 			summary();
412 
413 			/*
414 			 * If it's a seekable file descriptor, seek past the
415 			 * error.  If your OS doesn't do the right thing for
416 			 * raw disks this section should be modified to re-read
417 			 * in sector size chunks.
418 			 */
419 			if (in.flags & ISSEEK &&
420 			    lseek(in.fd, (off_t)in.dbsz, SEEK_CUR))
421 				warn("%s", in.name);
422 
423 			/* If sync not specified, omit block and continue. */
424 			if (!(ddflags & C_SYNC))
425 				continue;
426 
427 			/* Read errors count as full blocks. */
428 			in.dbcnt += in.dbrcnt = in.dbsz;
429 			++st.in_full;
430 
431 		/* Handle full input blocks. */
432 		} else if ((size_t)n == (size_t)in.dbsz) {
433 			in.dbcnt += in.dbrcnt = n;
434 			++st.in_full;
435 
436 		/* Handle partial input blocks. */
437 		} else {
438 			/* If sync, use the entire block. */
439 			if (ddflags & C_SYNC)
440 				in.dbcnt += in.dbrcnt = in.dbsz;
441 			else
442 				in.dbcnt += in.dbrcnt = n;
443 			++st.in_part;
444 		}
445 
446 		/*
447 		 * POSIX states that if bs is set and no other conversions
448 		 * than noerror, notrunc or sync are specified, the block
449 		 * is output without buffering as it is read.
450 		 */
451 		if ((ddflags & ~(C_NOERROR | C_NOTRUNC | C_SYNC)) == C_BS) {
452 			out.dbcnt = in.dbcnt;
453 			dd_out(1);
454 			in.dbcnt = 0;
455 			continue;
456 		}
457 
458 		if (ddflags & C_SWAB) {
459 			if ((n = in.dbrcnt) & 1) {
460 				++st.swab;
461 				--n;
462 			}
463 			swapbytes(in.dbp, (size_t)n);
464 		}
465 
466 		in.dbp += in.dbrcnt;
467 		(*cfunc)();
468 		if (need_summary)
469 			summary();
470 		if (need_progress)
471 			progress();
472 	}
473 }
474 
475 /*
476  * Clean up any remaining I/O and flush output.  If necessary, the output file
477  * is truncated.
478  */
479 static void
480 dd_close(void)
481 {
482 	if (cfunc == def)
483 		def_close();
484 	else if (cfunc == block)
485 		block_close();
486 	else if (cfunc == unblock)
487 		unblock_close();
488 	if (ddflags & C_OSYNC && out.dbcnt && out.dbcnt < out.dbsz) {
489 		if (ddflags & C_FILL)
490 			memset(out.dbp, fill_char, out.dbsz - out.dbcnt);
491 		else if (ddflags & (C_BLOCK | C_UNBLOCK))
492 			memset(out.dbp, ' ', out.dbsz - out.dbcnt);
493 		else
494 			memset(out.dbp, 0, out.dbsz - out.dbcnt);
495 		out.dbcnt = out.dbsz;
496 	}
497 	if (out.dbcnt || pending)
498 		dd_out(1);
499 
500 	/*
501 	 * If the file ends with a hole, ftruncate it to extend its size
502 	 * up to the end of the hole (without having to write any data).
503 	 */
504 	if (out.seek_offset > 0 && (out.flags & ISTRUNC)) {
505 		if (ftruncate(out.fd, out.seek_offset) == -1)
506 			err(1, "truncating %s", out.name);
507 	}
508 }
509 
510 void
511 dd_out(int force)
512 {
513 	u_char *outp;
514 	size_t cnt, n;
515 	ssize_t nw;
516 	static int warned;
517 	int sparse;
518 
519 	/*
520 	 * Write one or more blocks out.  The common case is writing a full
521 	 * output block in a single write; increment the full block stats.
522 	 * Otherwise, we're into partial block writes.  If a partial write,
523 	 * and it's a character device, just warn.  If a tape device, quit.
524 	 *
525 	 * The partial writes represent two cases.  1: Where the input block
526 	 * was less than expected so the output block was less than expected.
527 	 * 2: Where the input block was the right size but we were forced to
528 	 * write the block in multiple chunks.  The original versions of dd(1)
529 	 * never wrote a block in more than a single write, so the latter case
530 	 * never happened.
531 	 *
532 	 * One special case is if we're forced to do the write -- in that case
533 	 * we play games with the buffer size, and it's usually a partial write.
534 	 */
535 	outp = out.db;
536 
537 	/*
538 	 * If force, first try to write all pending data, else try to write
539 	 * just one block. Subsequently always write data one full block at
540 	 * a time at most.
541 	 */
542 	for (n = force ? out.dbcnt : out.dbsz;; n = out.dbsz) {
543 		cnt = n;
544 		do {
545 			sparse = 0;
546 			if (ddflags & C_SPARSE) {
547 				/* Is buffer sparse? */
548 				sparse = BISZERO(outp, cnt);
549 			}
550 			if (sparse && !force) {
551 				pending += cnt;
552 				nw = cnt;
553 			} else {
554 				if (pending != 0) {
555 					/*
556 					 * Seek past hole.  Note that we need to record the
557 					 * reached offset, because we might have no more data
558 					 * to write, in which case we'll need to call
559 					 * ftruncate to extend the file size.
560 					 */
561 					out.seek_offset = lseek(out.fd, pending, SEEK_CUR);
562 					if (out.seek_offset == -1)
563 						err(2, "%s: seek error creating sparse file",
564 						    out.name);
565 					pending = 0;
566 				}
567 				if (cnt) {
568 					nw = write(out.fd, outp, cnt);
569 					out.seek_offset = 0;
570 				} else {
571 					return;
572 				}
573 			}
574 
575 			if (nw <= 0) {
576 				if (nw == 0)
577 					errx(1, "%s: end of device", out.name);
578 				if (errno != EINTR)
579 					err(1, "%s", out.name);
580 				nw = 0;
581 			}
582 
583 			outp += nw;
584 			st.bytes += nw;
585 
586 			if ((size_t)nw == n && n == (size_t)out.dbsz)
587 				++st.out_full;
588 			else
589 				++st.out_part;
590 
591 			if ((size_t) nw != cnt) {
592 				if (out.flags & ISTAPE)
593 					errx(1, "%s: short write on tape device",
594 				    	out.name);
595 				if (out.flags & ISCHR && !warned) {
596 					warned = 1;
597 					warnx("%s: short write on character device",
598 				    	out.name);
599 				}
600 			}
601 
602 			cnt -= nw;
603 		} while (cnt != 0);
604 
605 		if ((out.dbcnt -= n) < out.dbsz)
606 			break;
607 	}
608 
609 	/* Reassemble the output block. */
610 	if (out.dbcnt)
611 		(void)memmove(out.db, out.dbp - out.dbcnt, out.dbcnt);
612 	out.dbp = out.db + out.dbcnt;
613 }
614