xref: /freebsd/bin/dd/dd.c (revision 417ed37975261df51f61d13e179ad04d8f4839c7)
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$
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 	(void)time(&st.start);			/* Statistics timestamp. */
201 }
202 
203 static void
204 getfdtype(io)
205 	IO *io;
206 {
207 	struct mtget mt;
208 	struct stat sb;
209 
210 	if (fstat(io->fd, &sb))
211 		err(1, "%s", io->name);
212 	if (S_ISCHR(sb.st_mode))
213 		io->flags |= ioctl(io->fd, MTIOCGET, &mt) ? ISCHR : ISTAPE;
214 	else if (lseek(io->fd, (off_t)0, SEEK_CUR) == -1 && errno == ESPIPE)
215 		io->flags |= ISPIPE;		/* XXX fixed in 4.4BSD */
216 }
217 
218 static void
219 dd_in()
220 {
221 	int flags, n;
222 
223 	for (flags = ddflags;;) {
224 		if (cpy_cnt && (st.in_full + st.in_part) >= cpy_cnt)
225 			return;
226 
227 		/*
228 		 * Zero the buffer first if trying to recover from errors so
229 		 * lose the minimum amount of data.  If doing block operations
230 		 * use spaces.
231 		 */
232 		if ((flags & (C_NOERROR|C_SYNC)) == (C_NOERROR|C_SYNC))
233 			if (flags & (C_BLOCK|C_UNBLOCK))
234 				memset(in.dbp, ' ', in.dbsz);
235 			else
236 				memset(in.dbp, 0, in.dbsz);
237 
238 		n = read(in.fd, in.dbp, in.dbsz);
239 		if (n == 0) {
240 			in.dbrcnt = 0;
241 			return;
242 		}
243 
244 		/* Read error. */
245 		if (n < 0) {
246 			/*
247 			 * If noerror not specified, die.  POSIX requires that
248 			 * the warning message be followed by an I/O display.
249 			 */
250 			if (!(flags & C_NOERROR))
251 				err(1, "%s", in.name);
252 			warn("%s", in.name);
253 			summary();
254 
255 			/*
256 			 * If it's not a tape drive or a pipe, seek past the
257 			 * error.  If your OS doesn't do the right thing for
258 			 * raw disks this section should be modified to re-read
259 			 * in sector size chunks.
260 			 */
261 			if (!(in.flags & (ISPIPE|ISTAPE)) &&
262 			    lseek(in.fd, (off_t)in.dbsz, SEEK_CUR))
263 				warn("%s", in.name);
264 
265 			/* If sync not specified, omit block and continue. */
266 			if (!(ddflags & C_SYNC))
267 				continue;
268 
269 			/* Read errors count as full blocks. */
270 			in.dbcnt += in.dbrcnt = in.dbsz;
271 			++st.in_full;
272 
273 		/* Handle full input blocks. */
274 		} else if (n == in.dbsz) {
275 			in.dbcnt += in.dbrcnt = n;
276 			++st.in_full;
277 
278 		/* Handle partial input blocks. */
279 		} else {
280 			/* If sync, use the entire block. */
281 			if (ddflags & C_SYNC)
282 				in.dbcnt += in.dbrcnt = in.dbsz;
283 			else
284 				in.dbcnt += in.dbrcnt = n;
285 			++st.in_part;
286 		}
287 
288 		/*
289 		 * POSIX states that if bs is set and no other conversions
290 		 * than noerror, notrunc or sync are specified, the block
291 		 * is output without buffering as it is read.
292 		 */
293 		if (ddflags & C_BS) {
294 			out.dbcnt = in.dbcnt;
295 			dd_out(1);
296 			in.dbcnt = 0;
297 			continue;
298 		}
299 
300 		if (ddflags & C_SWAB) {
301 			if ((n = in.dbcnt) & 1) {
302 				++st.swab;
303 				--n;
304 			}
305 			swab(in.dbp, in.dbp, n);
306 		}
307 
308 		in.dbp += in.dbrcnt;
309 		(*cfunc)();
310 	}
311 }
312 
313 /*
314  * Cleanup any remaining I/O and flush output.  If necesssary, output file
315  * is truncated.
316  */
317 static void
318 dd_close()
319 {
320 	if (cfunc == def)
321 		def_close();
322 	else if (cfunc == block)
323 		block_close();
324 	else if (cfunc == unblock)
325 		unblock_close();
326 	if (ddflags & C_OSYNC && out.dbcnt < out.dbsz) {
327 		memset(out.dbp, 0, out.dbsz - out.dbcnt);
328 		out.dbcnt = out.dbsz;
329 	}
330 	if (out.dbcnt)
331 		dd_out(1);
332 }
333 
334 void
335 dd_out(force)
336 	int force;
337 {
338 	static int warned;
339 	int cnt, n, nw;
340 	u_char *outp;
341 
342 	/*
343 	 * Write one or more blocks out.  The common case is writing a full
344 	 * output block in a single write; increment the full block stats.
345 	 * Otherwise, we're into partial block writes.  If a partial write,
346 	 * and it's a character device, just warn.  If a tape device, quit.
347 	 *
348 	 * The partial writes represent two cases.  1: Where the input block
349 	 * was less than expected so the output block was less than expected.
350 	 * 2: Where the input block was the right size but we were forced to
351 	 * write the block in multiple chunks.  The original versions of dd(1)
352 	 * never wrote a block in more than a single write, so the latter case
353 	 * never happened.
354 	 *
355 	 * One special case is if we're forced to do the write -- in that case
356 	 * we play games with the buffer size, and it's usually a partial write.
357 	 */
358 	outp = out.db;
359 	for (n = force ? out.dbcnt : out.dbsz;; n = out.dbsz) {
360 		for (cnt = n;; cnt -= nw) {
361 			nw = write(out.fd, outp, cnt);
362 			if (nw <= 0) {
363 				if (nw == 0)
364 					errx(1, "%s: end of device", out.name);
365 				if (errno != EINTR)
366 					err(1, "%s", out.name);
367 				nw = 0;
368 			}
369 			outp += nw;
370 			st.bytes += nw;
371 			if (nw == n) {
372 				if (n != out.dbsz)
373 					++st.out_part;
374 				else
375 					++st.out_full;
376 				break;
377 			}
378 			++st.out_part;
379 			if (nw == cnt)
380 				break;
381 			if (out.flags & ISCHR && !warned) {
382 				warned = 1;
383 				warnx("%s: short write on character device",
384 				    out.name);
385 			}
386 			if (out.flags & ISTAPE)
387 				errx(1, "%s: short write on tape device", out.name);
388 		}
389 		if ((out.dbcnt -= n) < out.dbsz)
390 			break;
391 	}
392 
393 	/* Reassemble the output block. */
394 	if (out.dbcnt)
395 		memmove(out.db, out.dbp - out.dbcnt, out.dbcnt);
396 	out.dbp = out.db + out.dbcnt;
397 }
398