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