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