xref: /openbsd/bin/dd/dd.c (revision db3296cf)
1 /*	$OpenBSD: dd.c,v 1.14 2003/06/11 23:42:12 deraadt Exp $	*/
2 /*	$NetBSD: dd.c,v 1.6 1996/02/20 19:29:06 jtc Exp $	*/
3 
4 /*-
5  * Copyright (c) 1991, 1993, 1994
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * Keith Muller of the University of California, San Diego and Lance
10  * Visser of Convex Computer Corporation.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 
37 #ifndef lint
38 static char copyright[] =
39 "@(#) Copyright (c) 1991, 1993, 1994\n\
40 	The Regents of the University of California.  All rights reserved.\n";
41 #endif /* not lint */
42 
43 #ifndef lint
44 #if 0
45 static char sccsid[] = "@(#)dd.c	8.5 (Berkeley) 4/2/94";
46 #else
47 static char rcsid[] = "$OpenBSD: dd.c,v 1.14 2003/06/11 23:42:12 deraadt Exp $";
48 #endif
49 #endif /* not lint */
50 
51 #include <sys/param.h>
52 #include <sys/stat.h>
53 #include <sys/ioctl.h>
54 #include <sys/mtio.h>
55 
56 #include <ctype.h>
57 #include <err.h>
58 #include <errno.h>
59 #include <fcntl.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(void);
70 static void dd_in(void);
71 static void getfdtype(IO *);
72 static void setup(void);
73 
74 IO	in, out;		/* input/output state */
75 STAT	st;			/* statistics */
76 void	(*cfunc)(void);		/* conversion function */
77 size_t	cpy_cnt;		/* # of blocks to copy */
78 u_int	ddflags;		/* conversion options */
79 size_t	cbsz;			/* conversion block size */
80 size_t	files_cnt = 1;		/* # of files to copy */
81 const	u_char	*ctab;		/* conversion table */
82 
83 int
84 main(int argc, char *argv[])
85 {
86 	jcl(argv);
87 	setup();
88 
89 	(void)signal(SIGINFO, summaryx);
90 	(void)signal(SIGINT, terminate);
91 
92 	atexit(summary);
93 
94 	if (cpy_cnt != (size_t)-1) {
95 		while (files_cnt--)
96 			dd_in();
97 	}
98 
99 	dd_close();
100 	exit(0);
101 }
102 
103 static void
104 setup(void)
105 {
106 	u_int cnt;
107 
108 	if (in.name == NULL) {
109 		in.name = "stdin";
110 		in.fd = STDIN_FILENO;
111 	} else {
112 		in.fd = open(in.name, O_RDONLY, 0);
113 		if (in.fd < 0)
114 			err(1, "%s", in.name);
115 	}
116 
117 	getfdtype(&in);
118 
119 	if (files_cnt > 1 && !(in.flags & ISTAPE))
120 		errx(1, "files is not supported for non-tape devices");
121 
122 	if (out.name == NULL) {
123 		/* No way to check for read access here. */
124 		out.fd = STDOUT_FILENO;
125 		out.name = "stdout";
126 	} else {
127 #define	OFLAGS \
128     (O_CREAT | (ddflags & (C_SEEK | C_NOTRUNC) ? 0 : O_TRUNC))
129 		out.fd = open(out.name, O_RDWR | OFLAGS, DEFFILEMODE);
130 		/*
131 		 * May not have read access, so try again with write only.
132 		 * Without read we may have a problem if output also does
133 		 * not support seeks.
134 		 */
135 		if (out.fd < 0) {
136 			out.fd = open(out.name, O_WRONLY | OFLAGS, DEFFILEMODE);
137 			out.flags |= NOREAD;
138 		}
139 		if (out.fd < 0)
140 			err(1, "%s", out.name);
141 	}
142 
143 	getfdtype(&out);
144 
145 	/*
146 	 * Allocate space for the input and output buffers.  If not doing
147 	 * record oriented I/O, only need a single buffer.
148 	 */
149 	if (!(ddflags & (C_BLOCK|C_UNBLOCK))) {
150 		if ((in.db = malloc(out.dbsz + in.dbsz - 1)) == NULL)
151 			err(1, "input buffer");
152 		out.db = in.db;
153 	} else if ((in.db =
154 	    malloc((u_int)(MAX(in.dbsz, cbsz) + cbsz))) == NULL ||
155 	    (out.db = malloc((u_int)(out.dbsz + cbsz))) == NULL)
156 		err(1, "output buffer");
157 	in.dbp = in.db;
158 	out.dbp = out.db;
159 
160 	/* Position the input/output streams. */
161 	if (in.offset)
162 		pos_in();
163 	if (out.offset)
164 		pos_out();
165 
166 	/*
167 	 * Truncate the output file; ignore errors because it fails on some
168 	 * kinds of output files, tapes, for example.
169 	 */
170 	if ((ddflags & (C_OF | C_SEEK | C_NOTRUNC)) == (C_OF | C_SEEK))
171 		(void)ftruncate(out.fd, out.offset * out.dbsz);
172 
173 	/*
174 	 * If converting case at the same time as another conversion, build a
175 	 * table that does both at once.  If just converting case, use the
176 	 * built-in tables.
177 	 */
178 	if (ddflags & (C_LCASE|C_UCASE)) {
179 #ifdef	NO_CONV
180 		/* Should not get here, but just in case... */
181 		errx(1, "case conv and -DNO_CONV");
182 #else	/* NO_CONV */
183 		if (ddflags & C_ASCII || ddflags & C_EBCDIC) {
184 			if (ddflags & C_LCASE) {
185 				for (cnt = 0; cnt < 0377; ++cnt)
186 					casetab[cnt] = tolower(ctab[cnt]);
187 			} else {
188 				for (cnt = 0; cnt < 0377; ++cnt)
189 					casetab[cnt] = toupper(ctab[cnt]);
190 			}
191 		} else {
192 			if (ddflags & C_LCASE) {
193 				for (cnt = 0; cnt < 0377; ++cnt)
194 					casetab[cnt] = tolower(cnt);
195 			} else {
196 				for (cnt = 0; cnt < 0377; ++cnt)
197 					casetab[cnt] = toupper(cnt);
198 			}
199 		}
200 
201 		ctab = casetab;
202 #endif	/* NO_CONV */
203 	}
204 
205 	/* Statistics timestamp. */
206 	(void)gettimeofday(&st.startv, (struct timezone *)NULL);
207 }
208 
209 static void
210 getfdtype(IO *io)
211 {
212 	struct mtget mt;
213 	struct stat sb;
214 
215 	if (fstat(io->fd, &sb))
216 		err(1, "%s", io->name);
217 	if (S_ISCHR(sb.st_mode))
218 		io->flags |= ioctl(io->fd, MTIOCGET, &mt) ? ISCHR : ISTAPE;
219 	else if (lseek(io->fd, (off_t)0, SEEK_CUR) == -1 && errno == ESPIPE)
220 		io->flags |= ISPIPE;		/* XXX fixed in 4.4BSD */
221 }
222 
223 static void
224 dd_in(void)
225 {
226 	ssize_t n;
227 
228 	for (;;) {
229 		if (cpy_cnt && (st.in_full + st.in_part) >= cpy_cnt)
230 			return;
231 
232 		/*
233 		 * Zero the buffer first if sync; if doing block operations
234 		 * use spaces.
235 		 */
236 		if (ddflags & C_SYNC) {
237 			if (ddflags & (C_BLOCK|C_UNBLOCK))
238 				(void)memset(in.dbp, ' ', in.dbsz);
239 			else
240 				(void)memset(in.dbp, 0, in.dbsz);
241 		}
242 
243 		n = read(in.fd, in.dbp, in.dbsz);
244 		if (n == 0) {
245 			in.dbrcnt = 0;
246 			return;
247 		}
248 
249 		/* Read error. */
250 		if (n < 0) {
251 			/*
252 			 * If noerror not specified, die.  POSIX requires that
253 			 * the warning message be followed by an I/O display.
254 			 */
255 			if (!(ddflags & C_NOERROR))
256 				err(1, "%s", in.name);
257 			warn("%s", in.name);
258 			summary();
259 
260 			/*
261 			 * If it's not a tape drive or a pipe, seek past the
262 			 * error.  If your OS doesn't do the right thing for
263 			 * raw disks this section should be modified to re-read
264 			 * in sector size chunks.
265 			 */
266 			if (!(in.flags & (ISPIPE|ISTAPE)) &&
267 			    lseek(in.fd, (off_t)in.dbsz, SEEK_CUR))
268 				warn("%s", in.name);
269 
270 			/* If sync not specified, omit block and continue. */
271 			if (!(ddflags & C_SYNC))
272 				continue;
273 
274 			/* Read errors count as full blocks. */
275 			in.dbcnt += in.dbrcnt = in.dbsz;
276 			++st.in_full;
277 
278 		/* Handle full input blocks. */
279 		} else if (n == in.dbsz) {
280 			in.dbcnt += in.dbrcnt = n;
281 			++st.in_full;
282 
283 		/* Handle partial input blocks. */
284 		} else {
285 			/* If sync, use the entire block. */
286 			if (ddflags & C_SYNC)
287 				in.dbcnt += in.dbrcnt = in.dbsz;
288 			else
289 				in.dbcnt += in.dbrcnt = n;
290 			++st.in_part;
291 		}
292 
293 		/*
294 		 * POSIX states that if bs is set and no other conversions
295 		 * than noerror, notrunc or sync are specified, the block
296 		 * is output without buffering as it is read.
297 		 */
298 		if (ddflags & C_BS) {
299 			out.dbcnt = in.dbcnt;
300 			dd_out(1);
301 			in.dbcnt = 0;
302 			continue;
303 		}
304 
305 		if (ddflags & C_SWAB) {
306 			if ((n = in.dbcnt) & 1) {
307 				++st.swab;
308 				--n;
309 			}
310 			swab(in.dbp, in.dbp, n);
311 		}
312 
313 		in.dbp += in.dbrcnt;
314 		(*cfunc)();
315 	}
316 }
317 
318 /*
319  * Cleanup any remaining I/O and flush output.  If necessary, output file
320  * is truncated.
321  */
322 static void
323 dd_close(void)
324 {
325 	if (cfunc == def)
326 		def_close();
327 	else if (cfunc == block)
328 		block_close();
329 	else if (cfunc == unblock)
330 		unblock_close();
331 	if (ddflags & C_OSYNC && out.dbcnt && out.dbcnt < out.dbsz) {
332 		if (ddflags & (C_BLOCK|C_UNBLOCK))
333 			memset(out.dbp, ' ', out.dbsz - out.dbcnt);
334 		else
335 			memset(out.dbp, 0, out.dbsz - out.dbcnt);
336 		out.dbcnt = out.dbsz;
337 	}
338 	if (out.dbcnt)
339 		dd_out(1);
340 }
341 
342 void
343 dd_out(int force)
344 {
345 	static int warned;
346 	size_t cnt, n;
347 	ssize_t nw;
348 	u_char *outp;
349 
350 	/*
351 	 * Write one or more blocks out.  The common case is writing a full
352 	 * output block in a single write; increment the full block stats.
353 	 * Otherwise, we're into partial block writes.  If a partial write,
354 	 * and it's a character device, just warn.  If a tape device, quit.
355 	 *
356 	 * The partial writes represent two cases.  1: Where the input block
357 	 * was less than expected so the output block was less than expected.
358 	 * 2: Where the input block was the right size but we were forced to
359 	 * write the block in multiple chunks.  The original versions of dd(1)
360 	 * never wrote a block in more than a single write, so the latter case
361 	 * never happened.
362 	 *
363 	 * One special case is if we're forced to do the write -- in that case
364 	 * we play games with the buffer size, and it's usually a partial write.
365 	 */
366 	outp = out.db;
367 	for (n = force ? out.dbcnt : out.dbsz;; n = out.dbsz) {
368 		for (cnt = n;; cnt -= nw) {
369 			nw = write(out.fd, outp, cnt);
370 			if (nw <= 0) {
371 				if (nw == 0)
372 					errx(1, "%s: end of device", out.name);
373 				if (errno != EINTR)
374 					err(1, "%s", out.name);
375 				nw = 0;
376 			}
377 			outp += nw;
378 			st.bytes += nw;
379 			if (nw == n) {
380 				if (n != out.dbsz)
381 					++st.out_part;
382 				else
383 					++st.out_full;
384 				break;
385 			}
386 			++st.out_part;
387 			if (nw == cnt)
388 				break;
389 			if (out.flags & ISCHR && !warned) {
390 				warned = 1;
391 				warnx("%s: short write on character device",
392 				    out.name);
393 			}
394 			if (out.flags & ISTAPE)
395 				errx(1, "%s: short write on tape device", out.name);
396 		}
397 		if ((out.dbcnt -= n) < out.dbsz)
398 			break;
399 	}
400 
401 	/* Reassemble the output block. */
402 	if (out.dbcnt)
403 		(void)memmove(out.db, out.dbp - out.dbcnt, out.dbcnt);
404 	out.dbp = out.db + out.dbcnt;
405 }
406