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