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