xref: /freebsd/bin/dd/dd.c (revision 380a989b3223d455375b4fae70fd0b9bdd43bafb)
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.14 1998/05/06 06:51:39 charnier 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 u_long	cpy_cnt;		/* # of blocks to copy */
78 u_long	pending = 0;		/* pending seek if sparse */
79 u_int	ddflags;		/* conversion options */
80 u_int	cbsz;			/* conversion block size */
81 u_int	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 < 0)
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 < 0) {
139 			out.fd = open(out.name, O_WRONLY | OFLAGS, DEFFILEMODE);
140 			out.flags |= NOREAD;
141 		}
142 		if (out.fd < 0)
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 =
157 	    malloc((u_int)(MAX(in.dbsz, cbsz) + cbsz))) == NULL ||
158 	    (out.db = malloc((u_int)(out.dbsz + cbsz))) == NULL)
159 		err(1, NULL);
160 	in.dbp = in.db;
161 	out.dbp = out.db;
162 
163 	/* Position the input/output streams. */
164 	if (in.offset)
165 		pos_in();
166 	if (out.offset)
167 		pos_out();
168 
169 	/*
170 	 * Truncate the output file; ignore errors because it fails on some
171 	 * kinds of output files, tapes, for example.
172 	 */
173 	if ((ddflags & (C_OF | C_SEEK | C_NOTRUNC)) == (C_OF | C_SEEK))
174 		(void)ftruncate(out.fd, (off_t)out.offset * out.dbsz);
175 
176 	/*
177 	 * If converting case at the same time as another conversion, build a
178 	 * table that does both at once.  If just converting case, use the
179 	 * built-in tables.
180 	 */
181 	if (ddflags & (C_LCASE|C_UCASE))
182 		if (ddflags & C_ASCII)
183 			if (ddflags & C_LCASE) {
184 				for (cnt = 0; cnt <= 0377; ++cnt)
185 					if (isupper(ctab[cnt]))
186 						ctab[cnt] = tolower(ctab[cnt]);
187 			} else {
188 				for (cnt = 0; cnt <= 0377; ++cnt)
189 					if (islower(ctab[cnt]))
190 						ctab[cnt] = toupper(ctab[cnt]);
191 			}
192 		else if (ddflags & C_EBCDIC)
193 			if (ddflags & C_LCASE) {
194 				for (cnt = 0; cnt <= 0377; ++cnt)
195 					if (isupper(cnt))
196 						ctab[cnt] = ctab[tolower(cnt)];
197 			} else {
198 				for (cnt = 0; cnt <= 0377; ++cnt)
199 					if (islower(cnt))
200 						ctab[cnt] = ctab[toupper(cnt)];
201 			}
202 		else {
203 			ctab = ddflags & C_LCASE ? u2l : l2u;
204 			if (ddflags & C_LCASE) {
205 				for (cnt = 0; cnt <= 0377; ++cnt)
206 					if (isupper(cnt))
207 						ctab[cnt] = tolower(cnt);
208 					else
209 						ctab[cnt] = cnt;
210 			} else {
211 				for (cnt = 0; cnt <= 0377; ++cnt)
212 					if (islower(cnt))
213 						ctab[cnt] = toupper(cnt);
214 					else
215 						ctab[cnt] = cnt;
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 	int 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 		n = read(in.fd, in.dbp, in.dbsz);
257 		if (n == 0) {
258 			in.dbrcnt = 0;
259 			return;
260 		}
261 
262 		/* Read error. */
263 		if (n < 0) {
264 			/*
265 			 * If noerror not specified, die.  POSIX requires that
266 			 * the warning message be followed by an I/O display.
267 			 */
268 			if (!(ddflags & C_NOERROR))
269 				err(1, "%s", in.name);
270 			warn("%s", in.name);
271 			summary();
272 
273 			/*
274 			 * If it's not a tape drive or a pipe, seek past the
275 			 * error.  If your OS doesn't do the right thing for
276 			 * raw disks this section should be modified to re-read
277 			 * in sector size chunks.
278 			 */
279 			if (!(in.flags & (ISPIPE|ISTAPE)) &&
280 			    lseek(in.fd, (off_t)in.dbsz, SEEK_CUR))
281 				warn("%s", in.name);
282 
283 			/* If sync not specified, omit block and continue. */
284 			if (!(ddflags & C_SYNC))
285 				continue;
286 
287 			/* Read errors count as full blocks. */
288 			in.dbcnt += in.dbrcnt = in.dbsz;
289 			++st.in_full;
290 
291 		/* Handle full input blocks. */
292 		} else if (n == in.dbsz) {
293 			in.dbcnt += in.dbrcnt = n;
294 			++st.in_full;
295 
296 		/* Handle partial input blocks. */
297 		} else {
298 			/* If sync, use the entire block. */
299 			if (ddflags & C_SYNC)
300 				in.dbcnt += in.dbrcnt = in.dbsz;
301 			else
302 				in.dbcnt += in.dbrcnt = n;
303 			++st.in_part;
304 		}
305 
306 		/*
307 		 * POSIX states that if bs is set and no other conversions
308 		 * than noerror, notrunc or sync are specified, the block
309 		 * is output without buffering as it is read.
310 		 */
311 		if (ddflags & C_BS) {
312 			out.dbcnt = in.dbcnt;
313 			dd_out(1);
314 			in.dbcnt = 0;
315 			continue;
316 		}
317 
318 		if (ddflags & C_SWAB) {
319 			if ((n = in.dbrcnt) & 1) {
320 				++st.swab;
321 				--n;
322 			}
323 			swab(in.dbp, in.dbp, n);
324 		}
325 
326 		in.dbp += in.dbrcnt;
327 		(*cfunc)();
328 	}
329 }
330 
331 /*
332  * Cleanup any remaining I/O and flush output.  If necesssary, output file
333  * is truncated.
334  */
335 static void
336 dd_close()
337 {
338 	if (cfunc == def)
339 		def_close();
340 	else if (cfunc == block)
341 		block_close();
342 	else if (cfunc == unblock)
343 		unblock_close();
344 	if (ddflags & C_OSYNC && out.dbcnt && out.dbcnt < out.dbsz) {
345 		if (ddflags & (C_BLOCK|C_UNBLOCK))
346 			memset(out.dbp, ' ', out.dbsz - out.dbcnt);
347 		else
348 			memset(out.dbp, 0, out.dbsz - out.dbcnt);
349 		out.dbcnt = out.dbsz;
350 	}
351 	if (out.dbcnt || pending)
352 		dd_out(1);
353 }
354 
355 void
356 dd_out(force)
357 	int force;
358 {
359 	static int warned;
360 	int cnt, n, nw, i, sparse;
361 	u_char *outp;
362 
363 	/*
364 	 * Write one or more blocks out.  The common case is writing a full
365 	 * output block in a single write; increment the full block stats.
366 	 * Otherwise, we're into partial block writes.  If a partial write,
367 	 * and it's a character device, just warn.  If a tape device, quit.
368 	 *
369 	 * The partial writes represent two cases.  1: Where the input block
370 	 * was less than expected so the output block was less than expected.
371 	 * 2: Where the input block was the right size but we were forced to
372 	 * write the block in multiple chunks.  The original versions of dd(1)
373 	 * never wrote a block in more than a single write, so the latter case
374 	 * never happened.
375 	 *
376 	 * One special case is if we're forced to do the write -- in that case
377 	 * we play games with the buffer size, and it's usually a partial write.
378 	 */
379 	outp = out.db;
380 	for (n = force ? out.dbcnt : out.dbsz;; n = out.dbsz) {
381 		for (cnt = n;; cnt -= nw) {
382 			sparse = 0;
383 			if (ddflags & C_SPARSE) {
384 				sparse = 1;	/* Is buffer sparse? */
385 				for (i = 0; i < cnt; i++)
386 					if (outp[i] != 0) {
387 						sparse = 0;
388 						break;
389 					}
390 			}
391 			if (sparse && !force) {
392 				pending += cnt;
393 				nw = cnt;
394 			} else {
395 				if (pending != 0) {
396 					if (force)
397 						pending--;
398 					if (lseek (out.fd, pending, SEEK_CUR) == -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 (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 (nw == cnt)
429 				break;
430 			if (out.flags & ISCHR && !warned) {
431 				warned = 1;
432 				warnx("%s: short write on character device",
433 				    out.name);
434 			}
435 			if (out.flags & ISTAPE)
436 				errx(1, "%s: short write on tape device", out.name);
437 		}
438 		if ((out.dbcnt -= n) < out.dbsz)
439 			break;
440 	}
441 
442 	/* Reassemble the output block. */
443 	if (out.dbcnt)
444 		memmove(out.db, out.dbp - out.dbcnt, out.dbcnt);
445 	out.dbp = out.db + out.dbcnt;
446 }
447