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