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