Merge branch 'vendor/OPENSSL'
[dragonfly.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  * 3. 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  * @(#) Copyright (c) 1991, 1993, 1994 The Regents of the University of California.  All rights reserved.
34  * @(#)dd.c     8.5 (Berkeley) 4/2/94
35  * $FreeBSD: src/bin/dd/dd.c,v 1.27.2.3 2001/08/01 01:37:35 obrien Exp $
36  */
37
38 #include <sys/param.h>
39 #include <sys/stat.h>
40 #include <sys/conf.h>
41 #include <sys/device.h>
42 #include <sys/filio.h>
43 #include <sys/time.h>
44
45 #include <ctype.h>
46 #include <err.h>
47 #include <errno.h>
48 #include <fcntl.h>
49 #include <locale.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <unistd.h>
54
55 #include "dd.h"
56 #include "extern.h"
57
58 static void dd_close (void);
59 static void dd_in (void);
60 static void getfdtype (IO *);
61 static void setup (void);
62
63 IO      in, out;                /* input/output state */
64 STAT    st;                     /* statistics */
65 void    (*cfunc) (void);        /* conversion function */
66 quad_t  cpy_cnt;                /* # of blocks to copy */
67 off_t   pending = 0;            /* pending seek if sparse */
68 u_int   ddflags;                /* conversion options */
69 size_t  cbsz;                   /* conversion block size */
70 quad_t  files_cnt = 1;          /* # of files to copy */
71 const   u_char *ctab;           /* conversion table */
72
73 int
74 main(int argc __unused, char **argv)
75 {
76         setlocale(LC_CTYPE, "");
77         jcl(argv);
78         setup();
79
80         signal(SIGINFO, summaryx);
81         signal(SIGINT, terminate);
82
83         atexit(summary);
84
85         while (files_cnt--)
86                 dd_in();
87
88         dd_close();
89         exit(0);
90 }
91
92 static void
93 setup(void)
94 {
95         u_int cnt;
96         struct timeval tv;
97
98         if (in.name == NULL) {
99                 in.name = "stdin";
100                 in.fd = STDIN_FILENO;
101         } else {
102                 in.fd = open(in.name, O_RDONLY, 0);
103                 if (in.fd == -1)
104                         err(1, "%s", in.name);
105         }
106
107         getfdtype(&in);
108
109         if (files_cnt > 1 && !(in.flags & ISTAPE))
110                 errx(1, "files is not supported for non-tape devices");
111
112         if (out.name == NULL) {
113                 /* No way to check for read access here. */
114                 out.fd = STDOUT_FILENO;
115                 out.name = "stdout";
116         } else {
117 #define OFLAGS \
118     (O_CREAT | (ddflags & (C_SEEK | C_NOTRUNC) ? 0 : O_TRUNC))
119                 out.fd = open(out.name, O_RDWR | OFLAGS, DEFFILEMODE);
120                 /*
121                  * May not have read access, so try again with write only.
122                  * Without read we may have a problem if output also does
123                  * not support seeks.
124                  */
125                 if (out.fd == -1) {
126                         out.fd = open(out.name, O_WRONLY | OFLAGS, DEFFILEMODE);
127                         out.flags |= NOREAD;
128                 }
129                 if (out.fd == -1)
130                         err(1, "%s", out.name);
131         }
132
133         getfdtype(&out);
134
135         /*
136          * Allocate space for the input and output buffers.  If not doing
137          * record oriented I/O, only need a single buffer.
138          */
139         if (!(ddflags & (C_BLOCK | C_UNBLOCK))) {
140                 if ((in.db = malloc(out.dbsz + in.dbsz - 1)) == NULL)
141                         err(1, "input buffer");
142                 out.db = in.db;
143         } else if ((in.db = malloc(MAX(in.dbsz, cbsz) + cbsz)) == NULL ||
144             (out.db = malloc(out.dbsz + cbsz)) == NULL)
145                 err(1, "output buffer");
146         in.dbp = in.db;
147         out.dbp = out.db;
148
149         /* Position the input/output streams. */
150         if (in.offset)
151                 pos_in();
152         if (out.offset)
153                 pos_out();
154
155         /*
156          * Truncate the output file.  If it fails on a type of output file
157          * that it should _not_ fail on, error out.
158          */
159         if ((ddflags & (C_OF | C_SEEK | C_NOTRUNC)) == (C_OF | C_SEEK) &&
160             out.flags & ISTRUNC)
161                 if (ftruncate(out.fd, out.offset * out.dbsz) == -1)
162                         err(1, "truncating %s", out.name);
163
164         /*
165          * If converting case at the same time as another conversion, build a
166          * table that does both at once.  If just converting case, use the
167          * built-in tables.
168          */
169         if (ddflags & (C_LCASE | C_UCASE)) {
170                 if (ddflags & (C_ASCII | C_EBCDIC)) {
171                         if (ddflags & C_LCASE) {
172                                 for (cnt = 0; cnt <= 0377; ++cnt)
173                                         casetab[cnt] = tolower(ctab[cnt]);
174                         } else {
175                                 for (cnt = 0; cnt <= 0377; ++cnt)
176                                         casetab[cnt] = toupper(ctab[cnt]);
177                         }
178                 } else {
179                         if (ddflags & C_LCASE) {
180                                 for (cnt = 0; cnt <= 0377; ++cnt)
181                                         casetab[cnt] = tolower((int)cnt);
182                         } else {
183                                 for (cnt = 0; cnt <= 0377; ++cnt)
184                                         casetab[cnt] = toupper((int)cnt);
185                         }
186                 }
187                 ctab = casetab;
188         }
189
190         gettimeofday(&tv, NULL);
191         st.start = tv.tv_sec + tv.tv_usec * 1e-6; 
192 }
193
194 static void
195 getfdtype(IO *io)
196 {
197         struct stat sb;
198         int type;
199
200         if (fstat(io->fd, &sb) == -1)
201                 err(1, "%s", io->name);
202         if (S_ISREG(sb.st_mode))
203                 io->flags |= ISTRUNC;
204         if (S_ISCHR(sb.st_mode) || S_ISBLK(sb.st_mode)) { 
205                 if (ioctl(io->fd, FIODTYPE, &type) == -1) {
206                         err(1, "%s", io->name);
207                 } else {
208                         if (type & D_TAPE)
209                                 io->flags |= ISTAPE;
210                         else if (type & (D_DISK | D_MEM))
211                                 io->flags |= ISSEEK;
212                         if (S_ISCHR(sb.st_mode) && (type & D_TAPE) == 0)
213                                 io->flags |= ISCHR;
214                 }
215                 return;
216         }
217         errno = 0;
218         if (lseek(io->fd, (off_t)0, SEEK_CUR) == -1 && errno == ESPIPE)
219                 io->flags |= ISPIPE;
220         else
221                 io->flags |= ISSEEK;
222 }
223
224 static void
225 dd_in(void)
226 {
227         ssize_t n;
228
229         for (;;) {
230                 switch (cpy_cnt) {
231                 case -1:                        /* count=0 was specified */
232                         return;
233                 case 0:
234                         break;
235                 default:
236                         if (st.in_full + st.in_part >= (u_quad_t)cpy_cnt)
237                                 return;
238                         break;
239                 }
240
241                 /*
242                  * Zero the buffer first if sync; if doing block operations,
243                  * use spaces.
244                  */
245                 if (ddflags & C_SYNC) {
246                         if (ddflags & (C_BLOCK | C_UNBLOCK))
247                                 memset(in.dbp, ' ', in.dbsz);
248                         else
249                                 memset(in.dbp, 0, in.dbsz);
250                 }
251
252                 n = read(in.fd, in.dbp, in.dbsz);
253                 if (n == 0) {
254                         in.dbrcnt = 0;
255                         return;
256                 }
257
258                 /* Read error. */
259                 if (n == -1) {
260                         /*
261                          * If noerror not specified, die.  POSIX requires that
262                          * the warning message be followed by an I/O display.
263                          */
264                         if (!(ddflags & C_NOERROR))
265                                 err(1, "%s", in.name);
266                         warn("%s", in.name);
267                         summary();
268
269                         /*
270                          * If it's a seekable file descriptor, seek past the
271                          * error.  If your OS doesn't do the right thing for
272                          * raw disks this section should be modified to re-read
273                          * in sector size chunks.
274                          */
275                         if (in.flags & ISSEEK &&
276                             lseek(in.fd, (off_t)in.dbsz, SEEK_CUR))
277                                 warn("%s", in.name);
278
279                         /* If sync not specified, omit block and continue. */
280                         if (!(ddflags & C_SYNC))
281                                 continue;
282
283                         /* Read errors count as full blocks. */
284                         in.dbcnt += in.dbrcnt = in.dbsz;
285                         ++st.in_full;
286
287                 /* Handle full input blocks. */
288                 } else if ((size_t)n == in.dbsz) {
289                         in.dbcnt += in.dbrcnt = n;
290                         ++st.in_full;
291
292                 /* Handle partial input blocks. */
293                 } else {
294                         /* If sync, use the entire block. */
295                         if (ddflags & C_SYNC)
296                                 in.dbcnt += in.dbrcnt = in.dbsz;
297                         else
298                                 in.dbcnt += in.dbrcnt = n;
299                         ++st.in_part;
300                 }
301
302                 /*
303                  * POSIX states that if bs is set and no other conversions
304                  * than noerror, notrunc or sync are specified, the block
305                  * is output without buffering as it is read.
306                  */
307                 if (ddflags & C_BS) {
308                         out.dbcnt = in.dbcnt;
309                         dd_out(1);
310                         in.dbcnt = 0;
311                         continue;
312                 }
313
314                 if (ddflags & C_SWAB) {
315                         if ((n = in.dbrcnt) & 1) {
316                                 ++st.swab;
317                                 --n;
318                         }
319                         swab(in.dbp, in.dbp, (size_t)n);
320                 }
321
322                 in.dbp += in.dbrcnt;
323                 (*cfunc)();
324         }
325 }
326
327 /*
328  * Clean up any remaining I/O and flush output.  If necessary, the output file
329  * is truncated.
330  */
331 static void
332 dd_close(void)
333 {
334         if (cfunc == def)
335                 def_close();
336         else if (cfunc == block)
337                 block_close();
338         else if (cfunc == unblock)
339                 unblock_close();
340         if (ddflags & C_OSYNC && out.dbcnt && out.dbcnt < out.dbsz) {
341                 if (ddflags & (C_BLOCK | C_UNBLOCK))
342                         memset(out.dbp, ' ', out.dbsz - out.dbcnt);
343                 else
344                         memset(out.dbp, 0, out.dbsz - out.dbcnt);
345                 out.dbcnt = out.dbsz;
346         }
347         if (out.dbcnt || pending)
348                 dd_out(1);
349 }
350
351 void
352 dd_out(int force)
353 {
354         u_char *outp;
355         size_t cnt, i, n;
356         ssize_t nw;
357         static int warned;
358         int sparse;
359
360         /*
361          * Write one or more blocks out.  The common case is writing a full
362          * output block in a single write; increment the full block stats.
363          * Otherwise, we're into partial block writes.  If a partial write,
364          * and it's a character device, just warn.  If a tape device, quit.
365          *
366          * The partial writes represent two cases.  1: Where the input block
367          * was less than expected so the output block was less than expected.
368          * 2: Where the input block was the right size but we were forced to
369          * write the block in multiple chunks.  The original versions of dd(1)
370          * never wrote a block in more than a single write, so the latter case
371          * never happened.
372          *
373          * One special case is if we're forced to do the write -- in that case
374          * we play games with the buffer size, and it's usually a partial write.
375          */
376         outp = out.db;
377         for (n = force ? out.dbcnt : out.dbsz;; n = out.dbsz) {
378                 for (cnt = n;; cnt -= nw) {
379                         sparse = 0;
380                         if (ddflags & C_SPARSE) {
381                                 sparse = 1;     /* Is buffer sparse? */
382                                 for (i = 0; i < cnt; i++)
383                                         if (outp[i] != 0) {
384                                                 sparse = 0;
385                                                 break;
386                                         }
387                         }
388                         if (sparse && !force) {
389                                 pending += cnt;
390                                 nw = cnt;
391                         } else {
392                                 if (pending != 0) {
393                                         if (force)
394                                                 pending--;
395                                         if (lseek(out.fd, pending, SEEK_CUR) ==
396                                             -1)
397                                                 err(2, "%s: seek error creating sparse file",
398                                                     out.name);
399                                         if (force)
400                                                 write(out.fd, outp, 1);
401                                         pending = 0;
402                                 }
403                                 if (cnt)
404                                         nw = write(out.fd, outp, cnt);
405                                 else
406                                         return;
407                         }
408
409                         if (nw <= 0) {
410                                 if (nw == 0)
411                                         errx(1, "%s: end of device", out.name);
412                                 if (errno != EINTR)
413                                         err(1, "%s", out.name);
414                                 nw = 0;
415                         }
416                         outp += nw;
417                         st.bytes += nw;
418                         if ((size_t)nw == n) {
419                                 if (n != out.dbsz)
420                                         ++st.out_part;
421                                 else
422                                         ++st.out_full;
423                                 break;
424                         }
425                         ++st.out_part;
426                         if ((size_t)nw == cnt)
427                                 break;
428                         if (out.flags & ISTAPE)
429                                 errx(1, "%s: short write on tape device",
430                                     out.name);
431                         if (out.flags & ISCHR && !warned) {
432                                 warned = 1;
433                                 warnx("%s: short write on character device",
434                                     out.name);
435                         }
436                 }
437                 if ((out.dbcnt -= n) < out.dbsz)
438                         break;
439         }
440
441         /* Reassemble the output block. */
442         if (out.dbcnt)
443                 memmove(out.db, out.dbp - out.dbcnt, out.dbcnt);
444         out.dbp = out.db + out.dbcnt;
445 }