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