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