xref: /netbsd-src/bin/dd/dd.c (revision ae9172d6cd9432a6a1a56760d86b32c57a66c39c)
1 /*-
2  * Copyright (c) 1991, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Keith Muller of the University of California, San Diego and Lance
7  * Visser of Convex Computer Corporation.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. All advertising materials mentioning features or use of this software
18  *    must display the following acknowledgement:
19  *	This product includes software developed by the University of
20  *	California, Berkeley and its contributors.
21  * 4. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  */
37 
38 #ifndef lint
39 static char copyright[] =
40 "@(#) Copyright (c) 1991, 1993, 1994\n\
41 	The Regents of the University of California.  All rights reserved.\n";
42 #endif /* not lint */
43 
44 #ifndef lint
45 /*static char sccsid[] = "from: @(#)dd.c	8.5 (Berkeley) 4/2/94";*/
46 static char *rcsid = "$Id: dd.c,v 1.3 1994/09/22 09:25:04 mycroft Exp $";
47 #endif /* not lint */
48 
49 #include <sys/param.h>
50 #include <sys/stat.h>
51 #include <sys/ioctl.h>
52 #include <sys/mtio.h>
53 
54 #include <ctype.h>
55 #include <err.h>
56 #include <errno.h>
57 #include <fcntl.h>
58 #include <signal.h>
59 #include <stdio.h>
60 #include <stdlib.h>
61 #include <string.h>
62 #include <unistd.h>
63 
64 #include "dd.h"
65 #include "extern.h"
66 
67 static void dd_close __P((void));
68 static void dd_in __P((void));
69 static void getfdtype __P((IO *));
70 static void setup __P((void));
71 
72 IO	in, out;		/* input/output state */
73 STAT	st;			/* statistics */
74 void	(*cfunc) __P((void));	/* conversion function */
75 u_long	cpy_cnt;		/* # of blocks to copy */
76 u_int	ddflags;		/* conversion options */
77 u_int	cbsz;			/* conversion block size */
78 u_int	files_cnt = 1;		/* # of files to copy */
79 u_char	*ctab;			/* conversion table */
80 
81 int
82 main(argc, argv)
83 	int argc;
84 	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 	while (files_cnt--)
95 		dd_in();
96 
97 	dd_close();
98 	exit(0);
99 }
100 
101 static void
102 setup()
103 {
104 	u_int cnt;
105 
106 	if (in.name == NULL) {
107 		in.name = "stdin";
108 		in.fd = STDIN_FILENO;
109 	} else {
110 		in.fd = open(in.name, O_RDONLY, 0);
111 		if (in.fd < 0)
112 			err(1, "%s", in.name);
113 	}
114 
115 	getfdtype(&in);
116 
117 	if (files_cnt > 1 && !(in.flags & ISTAPE))
118 		errx(1, "files is not supported for non-tape devices");
119 
120 	if (out.name == NULL) {
121 		/* No way to check for read access here. */
122 		out.fd = STDOUT_FILENO;
123 		out.name = "stdout";
124 	} else {
125 #define	OFLAGS \
126     (O_CREAT | (ddflags & (C_SEEK | C_NOTRUNC) ? 0 : O_TRUNC))
127 		out.fd = open(out.name, O_RDWR | OFLAGS, DEFFILEMODE);
128 		/*
129 		 * May not have read access, so try again with write only.
130 		 * Without read we may have a problem if output also does
131 		 * not support seeks.
132 		 */
133 		if (out.fd < 0) {
134 			out.fd = open(out.name, O_WRONLY | OFLAGS, DEFFILEMODE);
135 			out.flags |= NOREAD;
136 		}
137 		if (out.fd < 0)
138 			err(1, "%s", out.name);
139 	}
140 
141 	getfdtype(&out);
142 
143 	/*
144 	 * Allocate space for the input and output buffers.  If not doing
145 	 * record oriented I/O, only need a single buffer.
146 	 */
147 	if (!(ddflags & (C_BLOCK|C_UNBLOCK))) {
148 		if ((in.db = malloc(out.dbsz + in.dbsz - 1)) == NULL)
149 			err(1, NULL);
150 		out.db = in.db;
151 	} else if ((in.db =
152 	    malloc((u_int)(MAX(in.dbsz, cbsz) + cbsz))) == NULL ||
153 	    (out.db = malloc((u_int)(out.dbsz + cbsz))) == NULL)
154 		err(1, NULL);
155 	in.dbp = in.db;
156 	out.dbp = out.db;
157 
158 	/* Position the input/output streams. */
159 	if (in.offset)
160 		pos_in();
161 	if (out.offset)
162 		pos_out();
163 
164 	/*
165 	 * Truncate the output file; ignore errors because it fails on some
166 	 * kinds of output files, tapes, for example.
167 	 */
168 	if (ddflags & (C_OF | C_SEEK | C_NOTRUNC) == (C_OF | C_SEEK))
169 		(void)ftruncate(out.fd, (off_t)out.offset * out.dbsz);
170 
171 	/*
172 	 * If converting case at the same time as another conversion, build a
173 	 * table that does both at once.  If just converting case, use the
174 	 * built-in tables.
175 	 */
176 	if (ddflags & (C_LCASE|C_UCASE))
177 		if (ddflags & C_ASCII)
178 			if (ddflags & C_LCASE) {
179 				for (cnt = 0; cnt < 0377; ++cnt)
180 					if (isupper(ctab[cnt]))
181 						ctab[cnt] = tolower(ctab[cnt]);
182 			} else {
183 				for (cnt = 0; cnt < 0377; ++cnt)
184 					if (islower(ctab[cnt]))
185 						ctab[cnt] = toupper(ctab[cnt]);
186 			}
187 		else if (ddflags & C_EBCDIC)
188 			if (ddflags & C_LCASE) {
189 				for (cnt = 0; cnt < 0377; ++cnt)
190 					if (isupper(cnt))
191 						ctab[cnt] = ctab[tolower(cnt)];
192 			} else {
193 				for (cnt = 0; cnt < 0377; ++cnt)
194 					if (islower(cnt))
195 						ctab[cnt] = ctab[toupper(cnt)];
196 			}
197 		else
198 			ctab = ddflags & C_LCASE ? u2l : l2u;
199 	(void)time(&st.start);			/* Statistics timestamp. */
200 }
201 
202 static void
203 getfdtype(io)
204 	IO *io;
205 {
206 	struct mtget mt;
207 	struct stat sb;
208 
209 	if (fstat(io->fd, &sb))
210 		err(1, "%s", io->name);
211 	if (S_ISCHR(sb.st_mode))
212 		io->flags |= ioctl(io->fd, MTIOCGET, &mt) ? ISCHR : ISTAPE;
213 	else if (lseek(io->fd, (off_t)0, SEEK_CUR) == -1 && errno == ESPIPE)
214 		io->flags |= ISPIPE;		/* XXX fixed in 4.4BSD */
215 }
216 
217 static void
218 dd_in()
219 {
220 	int flags, n;
221 
222 	for (flags = ddflags;;) {
223 		if (cpy_cnt && (st.in_full + st.in_part) >= cpy_cnt)
224 			return;
225 
226 		/*
227 		 * Zero the buffer first if trying to recover from errors so
228 		 * lose the minimum amount of data.  If doing block operations
229 		 * use spaces.
230 		 */
231 		if ((flags & (C_NOERROR|C_SYNC)) == (C_NOERROR|C_SYNC))
232 			if (flags & (C_BLOCK|C_UNBLOCK))
233 				memset(in.dbp, ' ', in.dbsz);
234 			else
235 				memset(in.dbp, 0, in.dbsz);
236 
237 		n = read(in.fd, in.dbp, in.dbsz);
238 		if (n == 0) {
239 			in.dbrcnt = 0;
240 			return;
241 		}
242 
243 		/* Read error. */
244 		if (n < 0) {
245 			/*
246 			 * If noerror not specified, die.  POSIX requires that
247 			 * the warning message be followed by an I/O display.
248 			 */
249 			if (!(flags & C_NOERROR))
250 				err(1, "%s", in.name);
251 			warn("%s", in.name);
252 			summary();
253 
254 			/*
255 			 * If it's not a tape drive or a pipe, seek past the
256 			 * error.  If your OS doesn't do the right thing for
257 			 * raw disks this section should be modified to re-read
258 			 * in sector size chunks.
259 			 */
260 			if (!(in.flags & (ISPIPE|ISTAPE)) &&
261 			    lseek(in.fd, (off_t)in.dbsz, SEEK_CUR))
262 				warn("%s", in.name);
263 
264 			/* If sync not specified, omit block and continue. */
265 			if (!(ddflags & C_SYNC))
266 				continue;
267 
268 			/* Read errors count as full blocks. */
269 			in.dbcnt += in.dbrcnt = in.dbsz;
270 			++st.in_full;
271 
272 		/* Handle full input blocks. */
273 		} else if (n == in.dbsz) {
274 			in.dbcnt += in.dbrcnt = n;
275 			++st.in_full;
276 
277 		/* Handle partial input blocks. */
278 		} else {
279 			/* If sync, use the entire block. */
280 			if (ddflags & C_SYNC)
281 				in.dbcnt += in.dbrcnt = in.dbsz;
282 			else
283 				in.dbcnt += in.dbrcnt = n;
284 			++st.in_part;
285 		}
286 
287 		/*
288 		 * POSIX states that if bs is set and no other conversions
289 		 * than noerror, notrunc or sync are specified, the block
290 		 * is output without buffering as it is read.
291 		 */
292 		if (ddflags & C_BS) {
293 			out.dbcnt = in.dbcnt;
294 			dd_out(1);
295 			in.dbcnt = 0;
296 			continue;
297 		}
298 
299 		if (ddflags & C_SWAB) {
300 			if ((n = in.dbcnt) & 1) {
301 				++st.swab;
302 				--n;
303 			}
304 			swab(in.dbp, in.dbp, n);
305 		}
306 
307 		in.dbp += in.dbrcnt;
308 		(*cfunc)();
309 	}
310 }
311 
312 /*
313  * Cleanup any remaining I/O and flush output.  If necesssary, output file
314  * is truncated.
315  */
316 static void
317 dd_close()
318 {
319 	if (cfunc == def)
320 		def_close();
321 	else if (cfunc == block)
322 		block_close();
323 	else if (cfunc == unblock)
324 		unblock_close();
325 	if (ddflags & C_OSYNC && out.dbcnt < out.dbsz) {
326 		memset(out.dbp, 0, out.dbsz - out.dbcnt);
327 		out.dbcnt = out.dbsz;
328 	}
329 	if (out.dbcnt)
330 		dd_out(1);
331 }
332 
333 void
334 dd_out(force)
335 	int force;
336 {
337 	static int warned;
338 	int cnt, n, nw;
339 	u_char *outp;
340 
341 	/*
342 	 * Write one or more blocks out.  The common case is writing a full
343 	 * output block in a single write; increment the full block stats.
344 	 * Otherwise, we're into partial block writes.  If a partial write,
345 	 * and it's a character device, just warn.  If a tape device, quit.
346 	 *
347 	 * The partial writes represent two cases.  1: Where the input block
348 	 * was less than expected so the output block was less than expected.
349 	 * 2: Where the input block was the right size but we were forced to
350 	 * write the block in multiple chunks.  The original versions of dd(1)
351 	 * never wrote a block in more than a single write, so the latter case
352 	 * never happened.
353 	 *
354 	 * One special case is if we're forced to do the write -- in that case
355 	 * we play games with the buffer size, and it's usually a partial write.
356 	 */
357 	outp = out.db;
358 	for (n = force ? out.dbcnt : out.dbsz;; n = out.dbsz) {
359 		for (cnt = n;; cnt -= nw) {
360 			nw = write(out.fd, outp, cnt);
361 			if (nw <= 0) {
362 				if (nw == 0)
363 					errx(1, "%s: end of device", out.name);
364 				if (errno != EINTR)
365 					err(1, "%s", out.name);
366 				nw = 0;
367 			}
368 			outp += nw;
369 			st.bytes += nw;
370 			if (nw == n) {
371 				if (n != out.dbsz)
372 					++st.out_part;
373 				else
374 					++st.out_full;
375 				break;
376 			}
377 			++st.out_part;
378 			if (nw == cnt)
379 				break;
380 			if (out.flags & ISCHR && !warned) {
381 				warned = 1;
382 				warnx("%s: short write on character device",
383 				    out.name);
384 			}
385 			if (out.flags & ISTAPE)
386 				errx(1, "%s: short write on tape device", out.name);
387 		}
388 		if ((out.dbcnt -= n) < out.dbsz)
389 			break;
390 	}
391 
392 	/* Reassemble the output block. */
393 	if (out.dbcnt)
394 		memmove(out.db, out.dbp - out.dbcnt, out.dbcnt);
395 	out.dbp = out.db + out.dbcnt;
396 }
397