xref: /freebsd/bin/dd/dd.c (revision df7f5d4de4592a8948a25ce01e5bddfbb7ce39dc)
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 const 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 const 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 <locale.h>
60 #include <signal.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_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 	struct timeval tv;
109 
110 	if (in.name == NULL) {
111 		in.name = "stdin";
112 		in.fd = STDIN_FILENO;
113 	} else {
114 		in.fd = open(in.name, O_RDONLY, 0);
115 		if (in.fd < 0)
116 			err(1, "%s", in.name);
117 	}
118 
119 	getfdtype(&in);
120 
121 	if (files_cnt > 1 && !(in.flags & ISTAPE))
122 		errx(1, "files is not supported for non-tape devices");
123 
124 	if (out.name == NULL) {
125 		/* No way to check for read access here. */
126 		out.fd = STDOUT_FILENO;
127 		out.name = "stdout";
128 	} else {
129 #define	OFLAGS \
130     (O_CREAT | (ddflags & (C_SEEK | C_NOTRUNC) ? 0 : O_TRUNC))
131 		out.fd = open(out.name, O_RDWR | OFLAGS, DEFFILEMODE);
132 		/*
133 		 * May not have read access, so try again with write only.
134 		 * Without read we may have a problem if output also does
135 		 * not support seeks.
136 		 */
137 		if (out.fd < 0) {
138 			out.fd = open(out.name, O_WRONLY | OFLAGS, DEFFILEMODE);
139 			out.flags |= NOREAD;
140 		}
141 		if (out.fd < 0)
142 			err(1, "%s", out.name);
143 	}
144 
145 	getfdtype(&out);
146 
147 	/*
148 	 * Allocate space for the input and output buffers.  If not doing
149 	 * record oriented I/O, only need a single buffer.
150 	 */
151 	if (!(ddflags & (C_BLOCK|C_UNBLOCK))) {
152 		if ((in.db = malloc(out.dbsz + in.dbsz - 1)) == NULL)
153 			err(1, NULL);
154 		out.db = in.db;
155 	} else if ((in.db =
156 	    malloc((u_int)(MAX(in.dbsz, cbsz) + cbsz))) == NULL ||
157 	    (out.db = malloc((u_int)(out.dbsz + cbsz))) == NULL)
158 		err(1, NULL);
159 	in.dbp = in.db;
160 	out.dbp = out.db;
161 
162 	/* Position the input/output streams. */
163 	if (in.offset)
164 		pos_in();
165 	if (out.offset)
166 		pos_out();
167 
168 	/*
169 	 * Truncate the output file; ignore errors because it fails on some
170 	 * kinds of output files, tapes, for example.
171 	 */
172 	if ((ddflags & (C_OF | C_SEEK | C_NOTRUNC)) == (C_OF | C_SEEK))
173 		(void)ftruncate(out.fd, (off_t)out.offset * out.dbsz);
174 
175 	/*
176 	 * If converting case at the same time as another conversion, build a
177 	 * table that does both at once.  If just converting case, use the
178 	 * built-in tables.
179 	 */
180 	if (ddflags & (C_LCASE|C_UCASE))
181 		if (ddflags & C_ASCII)
182 			if (ddflags & C_LCASE) {
183 				for (cnt = 0; cnt <= 0377; ++cnt)
184 					if (isupper(ctab[cnt]))
185 						ctab[cnt] = tolower(ctab[cnt]);
186 			} else {
187 				for (cnt = 0; cnt <= 0377; ++cnt)
188 					if (islower(ctab[cnt]))
189 						ctab[cnt] = toupper(ctab[cnt]);
190 			}
191 		else if (ddflags & C_EBCDIC)
192 			if (ddflags & C_LCASE) {
193 				for (cnt = 0; cnt <= 0377; ++cnt)
194 					if (isupper(cnt))
195 						ctab[cnt] = ctab[tolower(cnt)];
196 			} else {
197 				for (cnt = 0; cnt <= 0377; ++cnt)
198 					if (islower(cnt))
199 						ctab[cnt] = ctab[toupper(cnt)];
200 			}
201 		else {
202 			ctab = ddflags & C_LCASE ? u2l : l2u;
203 			if (ddflags & C_LCASE) {
204 				for (cnt = 0; cnt <= 0377; ++cnt)
205 					if (isupper(cnt))
206 						ctab[cnt] = tolower(cnt);
207 					else
208 						ctab[cnt] = cnt;
209 			} else {
210 				for (cnt = 0; cnt <= 0377; ++cnt)
211 					if (islower(cnt))
212 						ctab[cnt] = toupper(cnt);
213 					else
214 						ctab[cnt] = cnt;
215 			}
216 		}
217 	(void)gettimeofday(&tv, (struct timezone *)NULL);
218 	st.start = tv.tv_sec + tv.tv_usec * 1e-6;
219 }
220 
221 static void
222 getfdtype(io)
223 	IO *io;
224 {
225 	struct mtget mt;
226 	struct stat sb;
227 
228 	if (fstat(io->fd, &sb))
229 		err(1, "%s", io->name);
230 	if (S_ISCHR(sb.st_mode))
231 		io->flags |= ioctl(io->fd, MTIOCGET, &mt) ? ISCHR : ISTAPE;
232 	else if (lseek(io->fd, (off_t)0, SEEK_CUR) == -1 && errno == ESPIPE)
233 		io->flags |= ISPIPE;		/* XXX fixed in 4.4BSD */
234 }
235 
236 static void
237 dd_in()
238 {
239 	int flags, n;
240 
241 	for (flags = ddflags;;) {
242 		if (cpy_cnt && (st.in_full + st.in_part) >= cpy_cnt)
243 			return;
244 
245 		/*
246 		 * Zero the buffer first if trying to recover from errors so
247 		 * lose the minimum amount of data.  If doing block operations
248 		 * use spaces.
249 		 */
250 		if ((flags & (C_NOERROR|C_SYNC)) == (C_NOERROR|C_SYNC))
251 			if (flags & (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 (!(flags & 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.dbcnt) & 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.dbsz) {
345 		memset(out.dbp, 0, out.dbsz - out.dbcnt);
346 		out.dbcnt = out.dbsz;
347 	}
348 	if (out.dbcnt)
349 		dd_out(1);
350 }
351 
352 void
353 dd_out(force)
354 	int force;
355 {
356 	static int warned;
357 	int cnt, n, nw;
358 	u_char *outp;
359 
360 	/*
361 	 * Write one or more blocks out.  The common case is writing a full
362 	 * output block in a single write; increment the full block stats.
363 	 * Otherwise, we're into partial block writes.  If a partial write,
364 	 * and it's a character device, just warn.  If a tape device, quit.
365 	 *
366 	 * The partial writes represent two cases.  1: Where the input block
367 	 * was less than expected so the output block was less than expected.
368 	 * 2: Where the input block was the right size but we were forced to
369 	 * write the block in multiple chunks.  The original versions of dd(1)
370 	 * never wrote a block in more than a single write, so the latter case
371 	 * never happened.
372 	 *
373 	 * One special case is if we're forced to do the write -- in that case
374 	 * we play games with the buffer size, and it's usually a partial write.
375 	 */
376 	outp = out.db;
377 	for (n = force ? out.dbcnt : out.dbsz;; n = out.dbsz) {
378 		for (cnt = n;; cnt -= nw) {
379 			nw = write(out.fd, outp, cnt);
380 			if (nw <= 0) {
381 				if (nw == 0)
382 					errx(1, "%s: end of device", out.name);
383 				if (errno != EINTR)
384 					err(1, "%s", out.name);
385 				nw = 0;
386 			}
387 			outp += nw;
388 			st.bytes += nw;
389 			if (nw == n) {
390 				if (n != out.dbsz)
391 					++st.out_part;
392 				else
393 					++st.out_full;
394 				break;
395 			}
396 			++st.out_part;
397 			if (nw == cnt)
398 				break;
399 			if (out.flags & ISCHR && !warned) {
400 				warned = 1;
401 				warnx("%s: short write on character device",
402 				    out.name);
403 			}
404 			if (out.flags & ISTAPE)
405 				errx(1, "%s: short write on tape device", out.name);
406 		}
407 		if ((out.dbcnt -= n) < out.dbsz)
408 			break;
409 	}
410 
411 	/* Reassemble the output block. */
412 	if (out.dbcnt)
413 		memmove(out.db, out.dbp - out.dbcnt, out.dbcnt);
414 	out.dbp = out.db + out.dbcnt;
415 }
416