xref: /freebsd/bin/dd/dd.c (revision 05c7a37afb48ddd5ee1bd921a5d46fe59cc70b15)
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  *	$Id: dd.c,v 1.4 1995/01/17 23:04:29 ache Exp $
38  */
39 
40 #ifndef lint
41 static char copyright[] =
42 "@(#) Copyright (c) 1991, 1993, 1994\n\
43 	The Regents of the University of California.  All rights reserved.\n";
44 #endif /* not lint */
45 
46 #ifndef lint
47 static char sccsid[] = "@(#)dd.c	8.5 (Berkeley) 4/2/94";
48 #endif /* not lint */
49 
50 #include <sys/param.h>
51 #include <sys/stat.h>
52 #include <sys/ioctl.h>
53 #include <sys/mtio.h>
54 
55 #include <ctype.h>
56 #include <err.h>
57 #include <errno.h>
58 #include <fcntl.h>
59 #include <signal.h>
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #include <unistd.h>
64 #include <locale.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_int	ddflags;		/* conversion options */
79 u_int	cbsz;			/* conversion block size */
80 u_int	files_cnt = 1;		/* # of files to copy */
81 u_char	*ctab;			/* conversion table */
82 
83 int
84 main(argc, argv)
85 	int argc;
86 	char *argv[];
87 {
88 	(void) setlocale(LC_CTYPE, "");
89 	jcl(argv);
90 	setup();
91 
92 	(void)signal(SIGINFO, summaryx);
93 	(void)signal(SIGINT, terminate);
94 
95 	atexit(summary);
96 
97 	while (files_cnt--)
98 		dd_in();
99 
100 	dd_close();
101 	exit(0);
102 }
103 
104 static void
105 setup()
106 {
107 	u_int cnt;
108 
109 	if (in.name == NULL) {
110 		in.name = "stdin";
111 		in.fd = STDIN_FILENO;
112 	} else {
113 		in.fd = open(in.name, O_RDONLY, 0);
114 		if (in.fd < 0)
115 			err(1, "%s", in.name);
116 	}
117 
118 	getfdtype(&in);
119 
120 	if (files_cnt > 1 && !(in.flags & ISTAPE))
121 		errx(1, "files is not supported for non-tape devices");
122 
123 	if (out.name == NULL) {
124 		/* No way to check for read access here. */
125 		out.fd = STDOUT_FILENO;
126 		out.name = "stdout";
127 	} else {
128 #define	OFLAGS \
129     (O_CREAT | (ddflags & (C_SEEK | C_NOTRUNC) ? 0 : O_TRUNC))
130 		out.fd = open(out.name, O_RDWR | OFLAGS, DEFFILEMODE);
131 		/*
132 		 * May not have read access, so try again with write only.
133 		 * Without read we may have a problem if output also does
134 		 * not support seeks.
135 		 */
136 		if (out.fd < 0) {
137 			out.fd = open(out.name, O_WRONLY | OFLAGS, DEFFILEMODE);
138 			out.flags |= NOREAD;
139 		}
140 		if (out.fd < 0)
141 			err(1, "%s", out.name);
142 	}
143 
144 	getfdtype(&out);
145 
146 	/*
147 	 * Allocate space for the input and output buffers.  If not doing
148 	 * record oriented I/O, only need a single buffer.
149 	 */
150 	if (!(ddflags & (C_BLOCK|C_UNBLOCK))) {
151 		if ((in.db = malloc(out.dbsz + in.dbsz - 1)) == NULL)
152 			err(1, NULL);
153 		out.db = in.db;
154 	} else if ((in.db =
155 	    malloc((u_int)(MAX(in.dbsz, cbsz) + cbsz))) == NULL ||
156 	    (out.db = malloc((u_int)(out.dbsz + cbsz))) == NULL)
157 		err(1, NULL);
158 	in.dbp = in.db;
159 	out.dbp = out.db;
160 
161 	/* Position the input/output streams. */
162 	if (in.offset)
163 		pos_in();
164 	if (out.offset)
165 		pos_out();
166 
167 	/*
168 	 * Truncate the output file; ignore errors because it fails on some
169 	 * kinds of output files, tapes, for example.
170 	 */
171 	if (ddflags & (C_OF | C_SEEK | C_NOTRUNC) == (C_OF | C_SEEK))
172 		(void)ftruncate(out.fd, (off_t)out.offset * out.dbsz);
173 
174 	/*
175 	 * If converting case at the same time as another conversion, build a
176 	 * table that does both at once.  If just converting case, use the
177 	 * built-in tables.
178 	 */
179 	if (ddflags & (C_LCASE|C_UCASE))
180 		if (ddflags & C_ASCII)
181 			if (ddflags & C_LCASE) {
182 				for (cnt = 0; cnt <= 0377; ++cnt)
183 					if (isupper(ctab[cnt]))
184 						ctab[cnt] = tolower(ctab[cnt]);
185 			} else {
186 				for (cnt = 0; cnt <= 0377; ++cnt)
187 					if (islower(ctab[cnt]))
188 						ctab[cnt] = toupper(ctab[cnt]);
189 			}
190 		else if (ddflags & C_EBCDIC)
191 			if (ddflags & C_LCASE) {
192 				for (cnt = 0; cnt <= 0377; ++cnt)
193 					if (isupper(cnt))
194 						ctab[cnt] = ctab[tolower(cnt)];
195 			} else {
196 				for (cnt = 0; cnt <= 0377; ++cnt)
197 					if (islower(cnt))
198 						ctab[cnt] = ctab[toupper(cnt)];
199 			}
200 		else {
201 			ctab = ddflags & C_LCASE ? u2l : l2u;
202 			if (ddflags & C_LCASE) {
203 				for (cnt = 0; cnt <= 0377; ++cnt)
204 					if (isupper(cnt))
205 						ctab[cnt] = tolower(cnt);
206 					else
207 						ctab[cnt] = cnt;
208 			} else {
209 				for (cnt = 0; cnt <= 0377; ++cnt)
210 					if (islower(cnt))
211 						ctab[cnt] = toupper(cnt);
212 					else
213 						ctab[cnt] = cnt;
214 			}
215 		}
216 	(void)time(&st.start);			/* Statistics timestamp. */
217 }
218 
219 static void
220 getfdtype(io)
221 	IO *io;
222 {
223 	struct mtget mt;
224 	struct stat sb;
225 
226 	if (fstat(io->fd, &sb))
227 		err(1, "%s", io->name);
228 	if (S_ISCHR(sb.st_mode))
229 		io->flags |= ioctl(io->fd, MTIOCGET, &mt) ? ISCHR : ISTAPE;
230 	else if (lseek(io->fd, (off_t)0, SEEK_CUR) == -1 && errno == ESPIPE)
231 		io->flags |= ISPIPE;		/* XXX fixed in 4.4BSD */
232 }
233 
234 static void
235 dd_in()
236 {
237 	int flags, n;
238 
239 	for (flags = ddflags;;) {
240 		if (cpy_cnt && (st.in_full + st.in_part) >= cpy_cnt)
241 			return;
242 
243 		/*
244 		 * Zero the buffer first if trying to recover from errors so
245 		 * lose the minimum amount of data.  If doing block operations
246 		 * use spaces.
247 		 */
248 		if ((flags & (C_NOERROR|C_SYNC)) == (C_NOERROR|C_SYNC))
249 			if (flags & (C_BLOCK|C_UNBLOCK))
250 				memset(in.dbp, ' ', in.dbsz);
251 			else
252 				memset(in.dbp, 0, in.dbsz);
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 < 0) {
262 			/*
263 			 * If noerror not specified, die.  POSIX requires that
264 			 * the warning message be followed by an I/O display.
265 			 */
266 			if (!(flags & C_NOERROR))
267 				err(1, "%s", in.name);
268 			warn("%s", in.name);
269 			summary();
270 
271 			/*
272 			 * If it's not a tape drive or a pipe, 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 & (ISPIPE|ISTAPE)) &&
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 (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.dbcnt) & 1) {
318 				++st.swab;
319 				--n;
320 			}
321 			swab(in.dbp, in.dbp, n);
322 		}
323 
324 		in.dbp += in.dbrcnt;
325 		(*cfunc)();
326 	}
327 }
328 
329 /*
330  * Cleanup any remaining I/O and flush output.  If necesssary, output file
331  * is truncated.
332  */
333 static void
334 dd_close()
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.dbsz) {
343 		memset(out.dbp, 0, out.dbsz - out.dbcnt);
344 		out.dbcnt = out.dbsz;
345 	}
346 	if (out.dbcnt)
347 		dd_out(1);
348 }
349 
350 void
351 dd_out(force)
352 	int force;
353 {
354 	static int warned;
355 	int cnt, n, nw;
356 	u_char *outp;
357 
358 	/*
359 	 * Write one or more blocks out.  The common case is writing a full
360 	 * output block in a single write; increment the full block stats.
361 	 * Otherwise, we're into partial block writes.  If a partial write,
362 	 * and it's a character device, just warn.  If a tape device, quit.
363 	 *
364 	 * The partial writes represent two cases.  1: Where the input block
365 	 * was less than expected so the output block was less than expected.
366 	 * 2: Where the input block was the right size but we were forced to
367 	 * write the block in multiple chunks.  The original versions of dd(1)
368 	 * never wrote a block in more than a single write, so the latter case
369 	 * never happened.
370 	 *
371 	 * One special case is if we're forced to do the write -- in that case
372 	 * we play games with the buffer size, and it's usually a partial write.
373 	 */
374 	outp = out.db;
375 	for (n = force ? out.dbcnt : out.dbsz;; n = out.dbsz) {
376 		for (cnt = n;; cnt -= nw) {
377 			nw = write(out.fd, outp, cnt);
378 			if (nw <= 0) {
379 				if (nw == 0)
380 					errx(1, "%s: end of device", out.name);
381 				if (errno != EINTR)
382 					err(1, "%s", out.name);
383 				nw = 0;
384 			}
385 			outp += nw;
386 			st.bytes += nw;
387 			if (nw == n) {
388 				if (n != out.dbsz)
389 					++st.out_part;
390 				else
391 					++st.out_full;
392 				break;
393 			}
394 			++st.out_part;
395 			if (nw == cnt)
396 				break;
397 			if (out.flags & ISCHR && !warned) {
398 				warned = 1;
399 				warnx("%s: short write on character device",
400 				    out.name);
401 			}
402 			if (out.flags & ISTAPE)
403 				errx(1, "%s: short write on tape device", out.name);
404 		}
405 		if ((out.dbcnt -= n) < out.dbsz)
406 			break;
407 	}
408 
409 	/* Reassemble the output block. */
410 	if (out.dbcnt)
411 		memmove(out.db, out.dbp - out.dbcnt, out.dbcnt);
412 	out.dbp = out.db + out.dbcnt;
413 }
414