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