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