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