]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - bin/dd/dd.c
Merge branch 'releng/11.3' into releng-CDN/11.3
[FreeBSD/FreeBSD.git] / bin / dd / dd.c
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  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 #if 0
35 #ifndef lint
36 static char const copyright[] =
37 "@(#) Copyright (c) 1991, 1993, 1994\n\
38         The Regents of the University of California.  All rights reserved.\n";
39 #endif /* not lint */
40
41 #ifndef lint
42 static char sccsid[] = "@(#)dd.c        8.5 (Berkeley) 4/2/94";
43 #endif /* not lint */
44 #endif
45 #include <sys/cdefs.h>
46 __FBSDID("$FreeBSD$");
47
48 #include <sys/param.h>
49 #include <sys/stat.h>
50 #include <sys/conf.h>
51 #include <sys/disklabel.h>
52 #include <sys/filio.h>
53 #include <sys/time.h>
54
55 #include <assert.h>
56 #include <ctype.h>
57 #include <err.h>
58 #include <errno.h>
59 #include <fcntl.h>
60 #include <inttypes.h>
61 #include <locale.h>
62 #include <stdio.h>
63 #include <stdlib.h>
64 #include <string.h>
65 #include <time.h>
66 #include <unistd.h>
67
68 #include "dd.h"
69 #include "extern.h"
70
71 static void dd_close(void);
72 static void dd_in(void);
73 static void getfdtype(IO *);
74 static void setup(void);
75
76 IO      in, out;                /* input/output state */
77 STAT    st;                     /* statistics */
78 void    (*cfunc)(void);         /* conversion function */
79 uintmax_t cpy_cnt;              /* # of blocks to copy */
80 static off_t    pending = 0;    /* pending seek if sparse */
81 u_int   ddflags = 0;            /* conversion options */
82 size_t  cbsz;                   /* conversion block size */
83 uintmax_t files_cnt = 1;        /* # of files to copy */
84 const   u_char *ctab;           /* conversion table */
85 char    fill_char;              /* Character to fill with if defined */
86 size_t  speed = 0;              /* maximum speed, in bytes per second */
87 volatile sig_atomic_t need_summary;
88 volatile sig_atomic_t need_progress;
89
90 int
91 main(int argc __unused, char *argv[])
92 {
93         struct itimerval itv = { { 1, 0 }, { 1, 0 } }; /* SIGALARM every second, if needed */
94
95         (void)setlocale(LC_CTYPE, "");
96         jcl(argv);
97         setup();
98
99         (void)signal(SIGINFO, siginfo_handler);
100         if (ddflags & C_PROGRESS) {
101                 (void)signal(SIGALRM, sigalarm_handler);
102                 setitimer(ITIMER_REAL, &itv, NULL);
103         }
104         (void)signal(SIGINT, terminate);
105
106         atexit(summary);
107
108         while (files_cnt--)
109                 dd_in();
110
111         dd_close();
112         /*
113          * Some devices such as cfi(4) may perform significant amounts
114          * of work when a write descriptor is closed.  Close the out
115          * descriptor explicitly so that the summary handler (called
116          * from an atexit() hook) includes this work.
117          */
118         close(out.fd);
119         exit(0);
120 }
121
122 static int
123 parity(u_char c)
124 {
125         int i;
126
127         i = c ^ (c >> 1) ^ (c >> 2) ^ (c >> 3) ^ 
128             (c >> 4) ^ (c >> 5) ^ (c >> 6) ^ (c >> 7);
129         return (i & 1);
130 }
131
132 static void
133 setup(void)
134 {
135         u_int cnt;
136
137         if (in.name == NULL) {
138                 in.name = "stdin";
139                 in.fd = STDIN_FILENO;
140         } else {
141                 in.fd = open(in.name, O_RDONLY, 0);
142                 if (in.fd == -1)
143                         err(1, "%s", in.name);
144         }
145
146         getfdtype(&in);
147
148         if (files_cnt > 1 && !(in.flags & ISTAPE))
149                 errx(1, "files is not supported for non-tape devices");
150
151         if (out.name == NULL) {
152                 /* No way to check for read access here. */
153                 out.fd = STDOUT_FILENO;
154                 out.name = "stdout";
155         } else {
156 #define OFLAGS \
157     (O_CREAT | (ddflags & (C_SEEK | C_NOTRUNC) ? 0 : O_TRUNC))
158                 out.fd = open(out.name, O_RDWR | OFLAGS, DEFFILEMODE);
159                 /*
160                  * May not have read access, so try again with write only.
161                  * Without read we may have a problem if output also does
162                  * not support seeks.
163                  */
164                 if (out.fd == -1) {
165                         out.fd = open(out.name, O_WRONLY | OFLAGS, DEFFILEMODE);
166                         out.flags |= NOREAD;
167                 }
168                 if (out.fd == -1)
169                         err(1, "%s", out.name);
170         }
171
172         getfdtype(&out);
173
174         /*
175          * Allocate space for the input and output buffers.  If not doing
176          * record oriented I/O, only need a single buffer.
177          */
178         if (!(ddflags & (C_BLOCK | C_UNBLOCK))) {
179                 if ((in.db = malloc(out.dbsz + in.dbsz - 1)) == NULL)
180                         err(1, "input buffer");
181                 out.db = in.db;
182         } else if ((in.db = malloc(MAX(in.dbsz, cbsz) + cbsz)) == NULL ||
183             (out.db = malloc(out.dbsz + cbsz)) == NULL)
184                 err(1, "output buffer");
185
186         /* dbp is the first free position in each buffer. */
187         in.dbp = in.db;
188         out.dbp = out.db;
189
190         /* Position the input/output streams. */
191         if (in.offset)
192                 pos_in();
193         if (out.offset)
194                 pos_out();
195
196         /*
197          * Truncate the output file.  If it fails on a type of output file
198          * that it should _not_ fail on, error out.
199          */
200         if ((ddflags & (C_OF | C_SEEK | C_NOTRUNC)) == (C_OF | C_SEEK) &&
201             out.flags & ISTRUNC)
202                 if (ftruncate(out.fd, out.offset * out.dbsz) == -1)
203                         err(1, "truncating %s", out.name);
204
205         if (ddflags & (C_LCASE  | C_UCASE | C_ASCII | C_EBCDIC | C_PARITY)) {
206                 if (ctab != NULL) {
207                         for (cnt = 0; cnt <= 0377; ++cnt)
208                                 casetab[cnt] = ctab[cnt];
209                 } else {
210                         for (cnt = 0; cnt <= 0377; ++cnt)
211                                 casetab[cnt] = cnt;
212                 }
213                 if ((ddflags & C_PARITY) && !(ddflags & C_ASCII)) {
214                         /*
215                          * If the input is not EBCDIC, and we do parity
216                          * processing, strip input parity.
217                          */
218                         for (cnt = 200; cnt <= 0377; ++cnt)
219                                 casetab[cnt] = casetab[cnt & 0x7f];
220                 }
221                 if (ddflags & C_LCASE) {
222                         for (cnt = 0; cnt <= 0377; ++cnt)
223                                 casetab[cnt] = tolower(casetab[cnt]);
224                 } else if (ddflags & C_UCASE) {
225                         for (cnt = 0; cnt <= 0377; ++cnt)
226                                 casetab[cnt] = toupper(casetab[cnt]);
227                 }
228                 if ((ddflags & C_PARITY)) {
229                         /*
230                          * This should strictly speaking be a no-op, but I
231                          * wonder what funny LANG settings could get us.
232                          */
233                         for (cnt = 0; cnt <= 0377; ++cnt)
234                                 casetab[cnt] = casetab[cnt] & 0x7f;
235                 }
236                 if ((ddflags & C_PARSET)) {
237                         for (cnt = 0; cnt <= 0377; ++cnt)
238                                 casetab[cnt] = casetab[cnt] | 0x80;
239                 }
240                 if ((ddflags & C_PAREVEN)) {
241                         for (cnt = 0; cnt <= 0377; ++cnt)
242                                 if (parity(casetab[cnt]))
243                                         casetab[cnt] = casetab[cnt] | 0x80;
244                 }
245                 if ((ddflags & C_PARODD)) {
246                         for (cnt = 0; cnt <= 0377; ++cnt)
247                                 if (!parity(casetab[cnt]))
248                                         casetab[cnt] = casetab[cnt] | 0x80;
249                 }
250
251                 ctab = casetab;
252         }
253
254         if (clock_gettime(CLOCK_MONOTONIC, &st.start))
255                 err(1, "clock_gettime");
256 }
257
258 static void
259 getfdtype(IO *io)
260 {
261         struct stat sb;
262         int type;
263
264         if (fstat(io->fd, &sb) == -1)
265                 err(1, "%s", io->name);
266         if (S_ISREG(sb.st_mode))
267                 io->flags |= ISTRUNC;
268         if (S_ISCHR(sb.st_mode) || S_ISBLK(sb.st_mode)) { 
269                 if (ioctl(io->fd, FIODTYPE, &type) == -1) {
270                         err(1, "%s", io->name);
271                 } else {
272                         if (type & D_TAPE)
273                                 io->flags |= ISTAPE;
274                         else if (type & (D_DISK | D_MEM))
275                                 io->flags |= ISSEEK;
276                         if (S_ISCHR(sb.st_mode) && (type & D_TAPE) == 0)
277                                 io->flags |= ISCHR;
278                 }
279                 return;
280         }
281         errno = 0;
282         if (lseek(io->fd, (off_t)0, SEEK_CUR) == -1 && errno == ESPIPE)
283                 io->flags |= ISPIPE;
284         else
285                 io->flags |= ISSEEK;
286 }
287
288 /*
289  * Limit the speed by adding a delay before every block read.
290  * The delay (t_usleep) is equal to the time computed from block
291  * size and the specified speed limit (t_target) minus the time
292  * spent on actual read and write operations (t_io).
293  */
294 static void
295 speed_limit(void)
296 {
297         static double t_prev, t_usleep;
298         double t_now, t_io, t_target;
299
300         t_now = secs_elapsed();
301         t_io = t_now - t_prev - t_usleep;
302         t_target = (double)in.dbsz / (double)speed;
303         t_usleep = t_target - t_io;
304         if (t_usleep > 0)
305                 usleep(t_usleep * 1000000);
306         else
307                 t_usleep = 0;
308         t_prev = t_now;
309 }
310
311 static void
312 swapbytes(void *v, size_t len)
313 {
314         unsigned char *p = v;
315         unsigned char t;
316
317         while (len > 1) {
318                 t = p[0];
319                 p[0] = p[1];
320                 p[1] = t;
321                 p += 2;
322                 len -= 2;
323         }
324 }
325
326 static void
327 dd_in(void)
328 {
329         ssize_t n;
330
331         for (;;) {
332                 switch (cpy_cnt) {
333                 case -1:                        /* count=0 was specified */
334                         return;
335                 case 0:
336                         break;
337                 default:
338                         if (st.in_full + st.in_part >= (uintmax_t)cpy_cnt)
339                                 return;
340                         break;
341                 }
342
343                 if (speed > 0)
344                         speed_limit();
345
346                 /*
347                  * Zero the buffer first if sync; if doing block operations,
348                  * use spaces.
349                  */
350                 if (ddflags & C_SYNC) {
351                         if (ddflags & C_FILL)
352                                 memset(in.dbp, fill_char, in.dbsz);
353                         else if (ddflags & (C_BLOCK | C_UNBLOCK))
354                                 memset(in.dbp, ' ', in.dbsz);
355                         else
356                                 memset(in.dbp, 0, in.dbsz);
357                 }
358
359                 n = read(in.fd, in.dbp, in.dbsz);
360                 if (n == 0) {
361                         in.dbrcnt = 0;
362                         return;
363                 }
364
365                 /* Read error. */
366                 if (n == -1) {
367                         /*
368                          * If noerror not specified, die.  POSIX requires that
369                          * the warning message be followed by an I/O display.
370                          */
371                         if (!(ddflags & C_NOERROR))
372                                 err(1, "%s", in.name);
373                         warn("%s", in.name);
374                         summary();
375
376                         /*
377                          * If it's a seekable file descriptor, seek past the
378                          * error.  If your OS doesn't do the right thing for
379                          * raw disks this section should be modified to re-read
380                          * in sector size chunks.
381                          */
382                         if (in.flags & ISSEEK &&
383                             lseek(in.fd, (off_t)in.dbsz, SEEK_CUR))
384                                 warn("%s", in.name);
385
386                         /* If sync not specified, omit block and continue. */
387                         if (!(ddflags & C_SYNC))
388                                 continue;
389
390                         /* Read errors count as full blocks. */
391                         in.dbcnt += in.dbrcnt = in.dbsz;
392                         ++st.in_full;
393
394                 /* Handle full input blocks. */
395                 } else if ((size_t)n == in.dbsz) {
396                         in.dbcnt += in.dbrcnt = n;
397                         ++st.in_full;
398
399                 /* Handle partial input blocks. */
400                 } else {
401                         /* If sync, use the entire block. */
402                         if (ddflags & C_SYNC)
403                                 in.dbcnt += in.dbrcnt = in.dbsz;
404                         else
405                                 in.dbcnt += in.dbrcnt = n;
406                         ++st.in_part;
407                 }
408
409                 /*
410                  * POSIX states that if bs is set and no other conversions
411                  * than noerror, notrunc or sync are specified, the block
412                  * is output without buffering as it is read.
413                  */
414                 if ((ddflags & ~(C_NOERROR | C_NOTRUNC | C_SYNC)) == C_BS) {
415                         out.dbcnt = in.dbcnt;
416                         dd_out(1);
417                         in.dbcnt = 0;
418                         continue;
419                 }
420
421                 if (ddflags & C_SWAB) {
422                         if ((n = in.dbrcnt) & 1) {
423                                 ++st.swab;
424                                 --n;
425                         }
426                         swapbytes(in.dbp, (size_t)n);
427                 }
428
429                 in.dbp += in.dbrcnt;
430                 (*cfunc)();
431                 if (need_summary)
432                         summary();
433                 if (need_progress)
434                         progress();
435         }
436 }
437
438 /*
439  * Clean up any remaining I/O and flush output.  If necessary, the output file
440  * is truncated.
441  */
442 static void
443 dd_close(void)
444 {
445         if (cfunc == def)
446                 def_close();
447         else if (cfunc == block)
448                 block_close();
449         else if (cfunc == unblock)
450                 unblock_close();
451         if (ddflags & C_OSYNC && out.dbcnt && out.dbcnt < out.dbsz) {
452                 if (ddflags & C_FILL)
453                         memset(out.dbp, fill_char, out.dbsz - out.dbcnt);
454                 else if (ddflags & (C_BLOCK | C_UNBLOCK))
455                         memset(out.dbp, ' ', out.dbsz - out.dbcnt);
456                 else
457                         memset(out.dbp, 0, out.dbsz - out.dbcnt);
458                 out.dbcnt = out.dbsz;
459         }
460         if (out.dbcnt || pending)
461                 dd_out(1);
462
463         /*
464          * If the file ends with a hole, ftruncate it to extend its size
465          * up to the end of the hole (without having to write any data).
466          */
467         if (out.seek_offset > 0 && (out.flags & ISTRUNC)) {
468                 if (ftruncate(out.fd, out.seek_offset) == -1)
469                         err(1, "truncating %s", out.name);
470         }
471 }
472
473 void
474 dd_out(int force)
475 {
476         u_char *outp;
477         size_t cnt, n;
478         ssize_t nw;
479         static int warned;
480         int sparse;
481
482         /*
483          * Write one or more blocks out.  The common case is writing a full
484          * output block in a single write; increment the full block stats.
485          * Otherwise, we're into partial block writes.  If a partial write,
486          * and it's a character device, just warn.  If a tape device, quit.
487          *
488          * The partial writes represent two cases.  1: Where the input block
489          * was less than expected so the output block was less than expected.
490          * 2: Where the input block was the right size but we were forced to
491          * write the block in multiple chunks.  The original versions of dd(1)
492          * never wrote a block in more than a single write, so the latter case
493          * never happened.
494          *
495          * One special case is if we're forced to do the write -- in that case
496          * we play games with the buffer size, and it's usually a partial write.
497          */
498         outp = out.db;
499
500         /*
501          * If force, first try to write all pending data, else try to write
502          * just one block. Subsequently always write data one full block at
503          * a time at most.
504          */
505         for (n = force ? out.dbcnt : out.dbsz;; n = out.dbsz) {
506                 cnt = n;
507                 do {
508                         sparse = 0;
509                         if (ddflags & C_SPARSE) {
510                                 /* Is buffer sparse? */
511                                 sparse = BISZERO(outp, cnt);
512                         }
513                         if (sparse && !force) {
514                                 pending += cnt;
515                                 nw = cnt;
516                         } else {
517                                 if (pending != 0) {
518                                         /*
519                                          * Seek past hole.  Note that we need to record the
520                                          * reached offset, because we might have no more data
521                                          * to write, in which case we'll need to call
522                                          * ftruncate to extend the file size.
523                                          */
524                                         out.seek_offset = lseek(out.fd, pending, SEEK_CUR);
525                                         if (out.seek_offset == -1)
526                                                 err(2, "%s: seek error creating sparse file",
527                                                     out.name);
528                                         pending = 0;
529                                 }
530                                 if (cnt) {
531                                         nw = write(out.fd, outp, cnt);
532                                         out.seek_offset = 0;
533                                 } else {
534                                         return;
535                                 }
536                         }
537
538                         if (nw <= 0) {
539                                 if (nw == 0)
540                                         errx(1, "%s: end of device", out.name);
541                                 if (errno != EINTR)
542                                         err(1, "%s", out.name);
543                                 nw = 0;
544                         }
545
546                         outp += nw;
547                         st.bytes += nw;
548
549                         if ((size_t)nw == n && n == out.dbsz)
550                                 ++st.out_full;
551                         else
552                                 ++st.out_part;
553
554                         if ((size_t) nw != cnt) {
555                                 if (out.flags & ISTAPE)
556                                         errx(1, "%s: short write on tape device",
557                                         out.name);
558                                 if (out.flags & ISCHR && !warned) {
559                                         warned = 1;
560                                         warnx("%s: short write on character device",
561                                         out.name);
562                                 }
563                         }
564
565                         cnt -= nw;
566                 } while (cnt != 0);
567
568                 if ((out.dbcnt -= n) < out.dbsz)
569                         break;
570         }
571
572         /* Reassemble the output block. */
573         if (out.dbcnt)
574                 (void)memmove(out.db, out.dbp - out.dbcnt, out.dbcnt);
575         out.dbp = out.db + out.dbcnt;
576 }