dd.c revision 1.34 1 /* $NetBSD: dd.c,v 1.34 2003/11/15 12:44:54 dsainty 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. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
34 */
35
36 #include <sys/cdefs.h>
37 #ifndef lint
38 __COPYRIGHT("@(#) Copyright (c) 1991, 1993, 1994\n\
39 The Regents of the University of California. All rights reserved.\n");
40 #endif /* not lint */
41
42 #ifndef lint
43 #if 0
44 static char sccsid[] = "@(#)dd.c 8.5 (Berkeley) 4/2/94";
45 #else
46 __RCSID("$NetBSD: dd.c,v 1.34 2003/11/15 12:44:54 dsainty Exp $");
47 #endif
48 #endif /* not lint */
49
50 #include <sys/param.h>
51 #include <sys/stat.h>
52 #include <sys/ioctl.h>
53 #include <sys/mtio.h>
54 #include <sys/time.h>
55
56 #include <ctype.h>
57 #include <err.h>
58 #include <errno.h>
59 #include <fcntl.h>
60 #include <signal.h>
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <string.h>
64 #include <unistd.h>
65
66 #include "dd.h"
67 #include "extern.h"
68
69 static void dd_close(void);
70 static void dd_in(void);
71 static void getfdtype(IO *);
72 static int redup_clean_fd(int);
73 static void setup(void);
74
75 int main(int, char *[]);
76
77 IO in, out; /* input/output state */
78 STAT st; /* statistics */
79 void (*cfunc)(void); /* conversion function */
80 uint64_t cpy_cnt; /* # of blocks to copy */
81 u_int ddflags; /* conversion options */
82 uint64_t cbsz; /* conversion block size */
83 u_int files_cnt = 1; /* # of files to copy */
84 int progress = 0; /* display sign of life */
85 const u_char *ctab; /* conversion table */
86 sigset_t infoset; /* a set blocking SIGINFO */
87
88 int
89 main(int argc, char *argv[])
90 {
91 int ch;
92
93 while ((ch = getopt(argc, argv, "")) != -1) {
94 switch (ch) {
95 default:
96 errx(EXIT_FAILURE, "usage: dd [operand ...]");
97 /* NOTREACHED */
98 }
99 }
100 argc -= (optind - 1);
101 argv += (optind - 1);
102
103 jcl(argv);
104 setup();
105
106 (void)signal(SIGINFO, summaryx);
107 (void)signal(SIGINT, terminate);
108 (void)sigemptyset(&infoset);
109 (void)sigaddset(&infoset, SIGINFO);
110
111 (void)atexit(summary);
112
113 while (files_cnt--)
114 dd_in();
115
116 dd_close();
117 exit(0);
118 /* NOTREACHED */
119 }
120
121 static void
122 setup(void)
123 {
124
125 if (in.name == NULL) {
126 in.name = "stdin";
127 in.fd = STDIN_FILENO;
128 } else {
129 in.fd = open(in.name, O_RDONLY, 0);
130 if (in.fd < 0)
131 err(EXIT_FAILURE, "%s", in.name);
132 /* NOTREACHED */
133
134 /* Ensure in.fd is outside the stdio descriptor range */
135 in.fd = redup_clean_fd(in.fd);
136 }
137
138 getfdtype(&in);
139
140 if (files_cnt > 1 && !(in.flags & ISTAPE)) {
141 errx(EXIT_FAILURE, "files is not supported for non-tape devices");
142 /* NOTREACHED */
143 }
144
145 if (out.name == NULL) {
146 /* No way to check for read access here. */
147 out.fd = STDOUT_FILENO;
148 out.name = "stdout";
149 } else {
150 #define OFLAGS \
151 (O_CREAT | (ddflags & (C_SEEK | C_NOTRUNC) ? 0 : O_TRUNC))
152 out.fd = open(out.name, O_RDWR | OFLAGS, DEFFILEMODE);
153 /*
154 * May not have read access, so try again with write only.
155 * Without read we may have a problem if output also does
156 * not support seeks.
157 */
158 if (out.fd < 0) {
159 out.fd = open(out.name, O_WRONLY | OFLAGS, DEFFILEMODE);
160 out.flags |= NOREAD;
161 }
162 if (out.fd < 0) {
163 err(EXIT_FAILURE, "%s", out.name);
164 /* NOTREACHED */
165 }
166
167 /* Ensure out.fd is outside the stdio descriptor range */
168 out.fd = redup_clean_fd(out.fd);
169 }
170
171 getfdtype(&out);
172
173 /*
174 * Allocate space for the input and output buffers. If not doing
175 * record oriented I/O, only need a single buffer.
176 */
177 if (!(ddflags & (C_BLOCK|C_UNBLOCK))) {
178 if ((in.db = malloc(out.dbsz + in.dbsz - 1)) == NULL) {
179 err(EXIT_FAILURE, NULL);
180 /* NOTREACHED */
181 }
182 out.db = in.db;
183 } else if ((in.db =
184 malloc((u_int)(MAX(in.dbsz, cbsz) + cbsz))) == NULL ||
185 (out.db = malloc((u_int)(out.dbsz + cbsz))) == NULL) {
186 err(EXIT_FAILURE, NULL);
187 /* NOTREACHED */
188 }
189 in.dbp = in.db;
190 out.dbp = out.db;
191
192 /* Position the input/output streams. */
193 if (in.offset)
194 pos_in();
195 if (out.offset)
196 pos_out();
197
198 /*
199 * Truncate the output file; ignore errors because it fails on some
200 * kinds of output files, tapes, for example.
201 */
202 if ((ddflags & (C_OF | C_SEEK | C_NOTRUNC)) == (C_OF | C_SEEK))
203 (void)ftruncate(out.fd, (off_t)out.offset * out.dbsz);
204
205 /*
206 * If converting case at the same time as another conversion, build a
207 * table that does both at once. If just converting case, use the
208 * built-in tables.
209 */
210 if (ddflags & (C_LCASE|C_UCASE)) {
211 #ifdef NO_CONV
212 /* Should not get here, but just in case... */
213 errx(EXIT_FAILURE, "case conv and -DNO_CONV");
214 /* NOTREACHED */
215 #else /* NO_CONV */
216 u_int cnt;
217
218 if (ddflags & C_ASCII || ddflags & C_EBCDIC) {
219 if (ddflags & C_LCASE) {
220 for (cnt = 0; cnt < 0377; ++cnt)
221 casetab[cnt] = tolower(ctab[cnt]);
222 } else {
223 for (cnt = 0; cnt < 0377; ++cnt)
224 casetab[cnt] = toupper(ctab[cnt]);
225 }
226 } else {
227 if (ddflags & C_LCASE) {
228 for (cnt = 0; cnt < 0377; ++cnt)
229 casetab[cnt] = tolower(cnt);
230 } else {
231 for (cnt = 0; cnt < 0377; ++cnt)
232 casetab[cnt] = toupper(cnt);
233 }
234 }
235
236 ctab = casetab;
237 #endif /* NO_CONV */
238 }
239
240 (void)gettimeofday(&st.start, NULL); /* Statistics timestamp. */
241 }
242
243 static void
244 getfdtype(IO *io)
245 {
246 struct mtget mt;
247 struct stat sb;
248
249 if (fstat(io->fd, &sb)) {
250 err(EXIT_FAILURE, "%s", io->name);
251 /* NOTREACHED */
252 }
253 if (S_ISCHR(sb.st_mode))
254 io->flags |= ioctl(io->fd, MTIOCGET, &mt) ? ISCHR : ISTAPE;
255 else if (lseek(io->fd, (off_t)0, SEEK_CUR) == -1 && errno == ESPIPE)
256 io->flags |= ISPIPE; /* XXX fixed in 4.4BSD */
257 }
258
259 /*
260 * Move the parameter file descriptor to a descriptor that is outside the
261 * stdio descriptor range, if necessary. This is required to avoid
262 * accidentally outputting completion or error messages into the
263 * output file that were intended for the tty.
264 */
265 static int
266 redup_clean_fd(int fd)
267 {
268 int newfd;
269
270 if (fd != STDIN_FILENO && fd != STDOUT_FILENO &&
271 fd != STDERR_FILENO)
272 /* File descriptor is ok, return immediately. */
273 return fd;
274
275 newfd = dup(fd);
276 if (newfd < 0) {
277 err(EXIT_FAILURE, "dup IO");
278 /* NOTREACHED */
279 }
280
281 /*
282 * Recurse, to ensure that the new descriptor is clean. Don't
283 * free the old descriptor(s) until we've allocated a clean
284 * one.
285 */
286 newfd = redup_clean_fd(newfd);
287 close(fd);
288
289 return newfd;
290 }
291
292 static void
293 dd_in(void)
294 {
295 int flags;
296 int64_t n;
297
298 for (flags = ddflags;;) {
299 if (cpy_cnt && (st.in_full + st.in_part) >= cpy_cnt)
300 return;
301
302 /*
303 * Clear the buffer first if doing "sync" on input.
304 * If doing block operations use spaces. This will
305 * affect not only the C_NOERROR case, but also the
306 * last partial input block which should be padded
307 * with zero and not garbage.
308 */
309 if (flags & C_SYNC) {
310 if (flags & (C_BLOCK|C_UNBLOCK))
311 (void)memset(in.dbp, ' ', in.dbsz);
312 else
313 (void)memset(in.dbp, 0, in.dbsz);
314 }
315
316 n = read(in.fd, in.dbp, in.dbsz);
317 if (n == 0) {
318 in.dbrcnt = 0;
319 return;
320 }
321
322 /* Read error. */
323 if (n < 0) {
324
325 /*
326 * If noerror not specified, die. POSIX requires that
327 * the warning message be followed by an I/O display.
328 */
329 if (!(flags & C_NOERROR)) {
330 err(EXIT_FAILURE, "%s", in.name);
331 /* NOTREACHED */
332 }
333 warn("%s", in.name);
334 summary();
335
336 /*
337 * If it's not a tape drive or a pipe, seek past the
338 * error. If your OS doesn't do the right thing for
339 * raw disks this section should be modified to re-read
340 * in sector size chunks.
341 */
342 if (!(in.flags & (ISPIPE|ISTAPE)) &&
343 lseek(in.fd, (off_t)in.dbsz, SEEK_CUR))
344 warn("%s", in.name);
345
346 /* If sync not specified, omit block and continue. */
347 if (!(ddflags & C_SYNC))
348 continue;
349
350 /* Read errors count as full blocks. */
351 in.dbcnt += in.dbrcnt = in.dbsz;
352 ++st.in_full;
353
354 /* Handle full input blocks. */
355 } else if (n == in.dbsz) {
356 in.dbcnt += in.dbrcnt = n;
357 ++st.in_full;
358
359 /* Handle partial input blocks. */
360 } else {
361 /* If sync, use the entire block. */
362 if (ddflags & C_SYNC)
363 in.dbcnt += in.dbrcnt = in.dbsz;
364 else
365 in.dbcnt += in.dbrcnt = n;
366 ++st.in_part;
367 }
368
369 /*
370 * POSIX states that if bs is set and no other conversions
371 * than noerror, notrunc or sync are specified, the block
372 * is output without buffering as it is read.
373 */
374 if (ddflags & C_BS) {
375 out.dbcnt = in.dbcnt;
376 dd_out(1);
377 in.dbcnt = 0;
378 continue;
379 }
380
381 if (ddflags & C_SWAB) {
382 if ((n = in.dbrcnt) & 1) {
383 ++st.swab;
384 --n;
385 }
386 swab(in.dbp, in.dbp, n);
387 }
388
389 in.dbp += in.dbrcnt;
390 (*cfunc)();
391 }
392 }
393
394 /*
395 * Cleanup any remaining I/O and flush output. If necesssary, output file
396 * is truncated.
397 */
398 static void
399 dd_close(void)
400 {
401
402 if (cfunc == def)
403 def_close();
404 else if (cfunc == block)
405 block_close();
406 else if (cfunc == unblock)
407 unblock_close();
408 if (ddflags & C_OSYNC && out.dbcnt < out.dbsz) {
409 (void)memset(out.dbp, 0, out.dbsz - out.dbcnt);
410 out.dbcnt = out.dbsz;
411 }
412 if (out.dbcnt)
413 dd_out(1);
414
415 /*
416 * Reporting nfs write error may be defered until next
417 * write(2) or close(2) system call. So, we need to do an
418 * extra check. If an output is stdout, the file structure
419 * may be shared among with other processes and close(2) just
420 * decreases the reference count.
421 */
422 if (out.fd == STDOUT_FILENO && fsync(out.fd) == -1 && errno != EINVAL) {
423 err(EXIT_FAILURE, "fsync stdout");
424 /* NOTREACHED */
425 }
426 if (close(out.fd) == -1) {
427 err(EXIT_FAILURE, "close");
428 /* NOTREACHED */
429 }
430 }
431
432 void
433 dd_out(int force)
434 {
435 static int warned;
436 int64_t cnt, n, nw;
437 u_char *outp;
438
439 /*
440 * Write one or more blocks out. The common case is writing a full
441 * output block in a single write; increment the full block stats.
442 * Otherwise, we're into partial block writes. If a partial write,
443 * and it's a character device, just warn. If a tape device, quit.
444 *
445 * The partial writes represent two cases. 1: Where the input block
446 * was less than expected so the output block was less than expected.
447 * 2: Where the input block was the right size but we were forced to
448 * write the block in multiple chunks. The original versions of dd(1)
449 * never wrote a block in more than a single write, so the latter case
450 * never happened.
451 *
452 * One special case is if we're forced to do the write -- in that case
453 * we play games with the buffer size, and it's usually a partial write.
454 */
455 outp = out.db;
456 for (n = force ? out.dbcnt : out.dbsz;; n = out.dbsz) {
457 for (cnt = n;; cnt -= nw) {
458
459 nw = bwrite(out.fd, outp, cnt);
460 if (nw <= 0) {
461 if (nw == 0)
462 errx(EXIT_FAILURE,
463 "%s: end of device", out.name);
464 /* NOTREACHED */
465 if (errno != EINTR)
466 err(EXIT_FAILURE, "%s", out.name);
467 /* NOTREACHED */
468 nw = 0;
469 }
470 outp += nw;
471 st.bytes += nw;
472 if (nw == n) {
473 if (n != out.dbsz)
474 ++st.out_part;
475 else
476 ++st.out_full;
477 break;
478 }
479 ++st.out_part;
480 if (nw == cnt)
481 break;
482 if (out.flags & ISCHR && !warned) {
483 warned = 1;
484 warnx("%s: short write on character device", out.name);
485 }
486 if (out.flags & ISTAPE)
487 errx(EXIT_FAILURE,
488 "%s: short write on tape device", out.name);
489 /* NOTREACHED */
490
491 }
492 if ((out.dbcnt -= n) < out.dbsz)
493 break;
494 }
495
496 /* Reassemble the output block. */
497 if (out.dbcnt)
498 (void)memmove(out.db, out.dbp - out.dbcnt, out.dbcnt);
499 out.dbp = out.db + out.dbcnt;
500
501 if (progress)
502 (void)write(STDERR_FILENO, ".", 1);
503 }
504
505 /*
506 * A protected against SIGINFO write
507 */
508 ssize_t
509 bwrite(int fd, const void *buf, size_t len)
510 {
511 sigset_t oset;
512 ssize_t rv;
513 int oerrno;
514
515 (void)sigprocmask(SIG_BLOCK, &infoset, &oset);
516 rv = write(fd, buf, len);
517 oerrno = errno;
518 (void)sigprocmask(SIG_SETMASK, &oset, NULL);
519 errno = oerrno;
520 return (rv);
521 }
522