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