xref: /freebsd/bin/dd/dd.c (revision 64db83a8ab2d1f72a9b2174b39d2ef42b5b0580c)
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 
58 #include <ctype.h>
59 #include <err.h>
60 #include <errno.h>
61 #include <fcntl.h>
62 #include <locale.h>
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <string.h>
66 #include <unistd.h>
67 
68 #include "dd.h"
69 #include "extern.h"
70 
71 static void dd_close __P((void));
72 static void dd_in __P((void));
73 static void getfdtype __P((IO *));
74 static void setup __P((void));
75 
76 IO	in, out;		/* input/output state */
77 STAT	st;			/* statistics */
78 void	(*cfunc) __P((void));	/* conversion function */
79 quad_t	cpy_cnt;		/* # of blocks to copy */
80 off_t	pending = 0;		/* pending seek if sparse */
81 u_int	ddflags;		/* conversion options */
82 size_t	cbsz;			/* conversion block size */
83 quad_t	files_cnt = 1;		/* # of files to copy */
84 const	u_char *ctab;		/* conversion table */
85 
86 int
87 main(argc, argv)
88 	int argc;
89 	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 
107 static void
108 setup()
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; ignore errors because it fails on some
172 	 * kinds of output files, tapes, for example.
173 	 */
174 	if ((ddflags & (C_OF | C_SEEK | C_NOTRUNC)) == (C_OF | C_SEEK))
175 		(void)ftruncate(out.fd, out.offset * out.dbsz);
176 
177 	/*
178 	 * If converting case at the same time as another conversion, build a
179 	 * table that does both at once.  If just converting case, use the
180 	 * built-in tables.
181 	 */
182 	if (ddflags & (C_LCASE | C_UCASE)) {
183 		if (ddflags & (C_ASCII | C_EBCDIC)) {
184 			if (ddflags & C_LCASE) {
185 				for (cnt = 0; cnt <= 0377; ++cnt)
186 					casetab[cnt] = tolower(ctab[cnt]);
187 			} else {
188 				for (cnt = 0; cnt <= 0377; ++cnt)
189 					casetab[cnt] = toupper(ctab[cnt]);
190 			}
191 		} else {
192 			if (ddflags & C_LCASE) {
193 				for (cnt = 0; cnt <= 0377; ++cnt)
194 					casetab[cnt] = tolower(cnt);
195 			} else {
196 				for (cnt = 0; cnt <= 0377; ++cnt)
197 					casetab[cnt] = toupper(cnt);
198 			}
199 		}
200 		ctab = casetab;
201 	}
202 
203 	(void)gettimeofday(&tv, (struct timezone *)NULL);
204 	st.start = tv.tv_sec + tv.tv_usec * 1e-6;
205 }
206 
207 static void
208 getfdtype(io)
209 	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_ISCHR(sb.st_mode) || S_ISBLK(sb.st_mode)) {
217 		if (ioctl(io->fd, FIODTYPE, &type) == -1) {
218 			err(1, "%s", io->name);
219 		} else {
220 			if (type & D_TAPE)
221 				io->flags |= ISTAPE;
222 			else if (type & (D_DISK | D_MEM)) {
223 				if (type & D_DISK) {
224 					const int one = 1;
225 
226 					(void)ioctl(io->fd, DIOCWLABEL, &one);
227 				}
228 				io->flags |= ISSEEK;
229 			}
230 			if (S_ISCHR(sb.st_mode) && (type & D_TAPE) == 0)
231 				io->flags |= ISCHR;
232 		}
233 		return;
234 	}
235 	errno = 0;
236 	if (lseek(io->fd, (off_t)0, SEEK_CUR) == -1 && errno == ESPIPE)
237 		io->flags |= ISPIPE;
238 	else
239 		io->flags |= ISSEEK;
240 }
241 
242 static void
243 dd_in()
244 {
245 	ssize_t n;
246 
247 	for (;;) {
248 		switch (cpy_cnt) {
249 		case -1:			/* count=0 was specified */
250 			return;
251 		case 0:
252 			break;
253 		default:
254 			if (st.in_full + st.in_part >= cpy_cnt)
255 				return;
256 			break;
257 		}
258 
259 		/*
260 		 * Zero the buffer first if sync; if doing block operations,
261 		 * use spaces.
262 		 */
263 		if (ddflags & C_SYNC) {
264 			if (ddflags & (C_BLOCK | C_UNBLOCK))
265 				memset(in.dbp, ' ', in.dbsz);
266 			else
267 				memset(in.dbp, 0, in.dbsz);
268 		}
269 
270 		n = read(in.fd, in.dbp, in.dbsz);
271 		if (n == 0) {
272 			in.dbrcnt = 0;
273 			return;
274 		}
275 
276 		/* Read error. */
277 		if (n == -1) {
278 			/*
279 			 * If noerror not specified, die.  POSIX requires that
280 			 * the warning message be followed by an I/O display.
281 			 */
282 			if (!(ddflags & C_NOERROR))
283 				err(1, "%s", in.name);
284 			warn("%s", in.name);
285 			summary();
286 
287 			/*
288 			 * If it's a seekable file descriptor, seek past the
289 			 * error.  If your OS doesn't do the right thing for
290 			 * raw disks this section should be modified to re-read
291 			 * in sector size chunks.
292 			 */
293 			if (in.flags & ISSEEK &&
294 			    lseek(in.fd, (off_t)in.dbsz, SEEK_CUR))
295 				warn("%s", in.name);
296 
297 			/* If sync not specified, omit block and continue. */
298 			if (!(ddflags & C_SYNC))
299 				continue;
300 
301 			/* Read errors count as full blocks. */
302 			in.dbcnt += in.dbrcnt = in.dbsz;
303 			++st.in_full;
304 
305 		/* Handle full input blocks. */
306 		} else if (n == in.dbsz) {
307 			in.dbcnt += in.dbrcnt = n;
308 			++st.in_full;
309 
310 		/* Handle partial input blocks. */
311 		} else {
312 			/* If sync, use the entire block. */
313 			if (ddflags & C_SYNC)
314 				in.dbcnt += in.dbrcnt = in.dbsz;
315 			else
316 				in.dbcnt += in.dbrcnt = n;
317 			++st.in_part;
318 		}
319 
320 		/*
321 		 * POSIX states that if bs is set and no other conversions
322 		 * than noerror, notrunc or sync are specified, the block
323 		 * is output without buffering as it is read.
324 		 */
325 		if (ddflags & C_BS) {
326 			out.dbcnt = in.dbcnt;
327 			dd_out(1);
328 			in.dbcnt = 0;
329 			continue;
330 		}
331 
332 		if (ddflags & C_SWAB) {
333 			if ((n = in.dbrcnt) & 1) {
334 				++st.swab;
335 				--n;
336 			}
337 			swab(in.dbp, in.dbp, n);
338 		}
339 
340 		in.dbp += in.dbrcnt;
341 		(*cfunc)();
342 	}
343 }
344 
345 /*
346  * Clean up any remaining I/O and flush output.  If necessary, the output file
347  * is truncated.
348  */
349 static void
350 dd_close()
351 {
352 	if (cfunc == def)
353 		def_close();
354 	else if (cfunc == block)
355 		block_close();
356 	else if (cfunc == unblock)
357 		unblock_close();
358 	if (ddflags & C_OSYNC && out.dbcnt && out.dbcnt < out.dbsz) {
359 		if (ddflags & (C_BLOCK | C_UNBLOCK))
360 			memset(out.dbp, ' ', out.dbsz - out.dbcnt);
361 		else
362 			memset(out.dbp, 0, out.dbsz - out.dbcnt);
363 		out.dbcnt = out.dbsz;
364 	}
365 	if (out.dbcnt || pending)
366 		dd_out(1);
367 }
368 
369 void
370 dd_out(force)
371 	int force;
372 {
373 	u_char *outp;
374 	size_t cnt, i, n;
375 	ssize_t nw;
376 	static int warned;
377 	int sparse;
378 
379 	/*
380 	 * Write one or more blocks out.  The common case is writing a full
381 	 * output block in a single write; increment the full block stats.
382 	 * Otherwise, we're into partial block writes.  If a partial write,
383 	 * and it's a character device, just warn.  If a tape device, quit.
384 	 *
385 	 * The partial writes represent two cases.  1: Where the input block
386 	 * was less than expected so the output block was less than expected.
387 	 * 2: Where the input block was the right size but we were forced to
388 	 * write the block in multiple chunks.  The original versions of dd(1)
389 	 * never wrote a block in more than a single write, so the latter case
390 	 * never happened.
391 	 *
392 	 * One special case is if we're forced to do the write -- in that case
393 	 * we play games with the buffer size, and it's usually a partial write.
394 	 */
395 	outp = out.db;
396 	for (n = force ? out.dbcnt : out.dbsz;; n = out.dbsz) {
397 		for (cnt = n;; cnt -= nw) {
398 			sparse = 0;
399 			if (ddflags & C_SPARSE) {
400 				sparse = 1;	/* Is buffer sparse? */
401 				for (i = 0; i < cnt; i++)
402 					if (outp[i] != 0) {
403 						sparse = 0;
404 						break;
405 					}
406 			}
407 			if (sparse && !force) {
408 				pending += cnt;
409 				nw = cnt;
410 			} else {
411 				if (pending != 0) {
412 					if (force)
413 						pending--;
414 					if (lseek(out.fd, pending, SEEK_CUR) ==
415 					    -1)
416 						err(2, "%s: seek error creating sparse file",
417 						    out.name);
418 					if (force)
419 						write(out.fd, outp, 1);
420 					pending = 0;
421 				}
422 				if (cnt)
423 					nw = write(out.fd, outp, cnt);
424 				else
425 					return;
426 			}
427 
428 			if (nw <= 0) {
429 				if (nw == 0)
430 					errx(1, "%s: end of device", out.name);
431 				if (errno != EINTR)
432 					err(1, "%s", out.name);
433 				nw = 0;
434 			}
435 			outp += nw;
436 			st.bytes += nw;
437 			if (nw == n) {
438 				if (n != out.dbsz)
439 					++st.out_part;
440 				else
441 					++st.out_full;
442 				break;
443 			}
444 			++st.out_part;
445 			if (nw == cnt)
446 				break;
447 			if (out.flags & ISTAPE)
448 				errx(1, "%s: short write on tape device",
449 				    out.name);
450 			if (out.flags & ISCHR && !warned) {
451 				warned = 1;
452 				warnx("%s: short write on character device",
453 				    out.name);
454 			}
455 		}
456 		if ((out.dbcnt -= n) < out.dbsz)
457 			break;
458 	}
459 
460 	/* Reassemble the output block. */
461 	if (out.dbcnt)
462 		(void)memmove(out.db, out.dbp - out.dbcnt, out.dbcnt);
463 	out.dbp = out.db + out.dbcnt;
464 }
465