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