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