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