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