move help text from include/usage.src.h to coreutils/*.c
[oweals/busybox.git] / coreutils / dd.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini dd implementation for busybox
4  *
5  *
6  * Copyright (C) 2000,2001  Matt Kraai
7  *
8  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
9  */
10
11 //usage:#define dd_trivial_usage
12 //usage:       "[if=FILE] [of=FILE] " IF_FEATURE_DD_IBS_OBS("[ibs=N] [obs=N] ") "[bs=N] [count=N] [skip=N]\n"
13 //usage:       "        [seek=N]" IF_FEATURE_DD_IBS_OBS(" [conv=notrunc|noerror|sync|fsync]")
14 //usage:#define dd_full_usage "\n\n"
15 //usage:       "Copy a file with converting and formatting\n"
16 //usage:     "\nOptions:"
17 //usage:     "\n        if=FILE         Read from FILE instead of stdin"
18 //usage:     "\n        of=FILE         Write to FILE instead of stdout"
19 //usage:     "\n        bs=N            Read and write N bytes at a time"
20 //usage:        IF_FEATURE_DD_IBS_OBS(
21 //usage:     "\n        ibs=N           Read N bytes at a time"
22 //usage:        )
23 //usage:        IF_FEATURE_DD_IBS_OBS(
24 //usage:     "\n        obs=N           Write N bytes at a time"
25 //usage:        )
26 //usage:     "\n        count=N         Copy only N input blocks"
27 //usage:     "\n        skip=N          Skip N input blocks"
28 //usage:     "\n        seek=N          Skip N output blocks"
29 //usage:        IF_FEATURE_DD_IBS_OBS(
30 //usage:     "\n        conv=notrunc    Don't truncate output file"
31 //usage:     "\n        conv=noerror    Continue after read errors"
32 //usage:     "\n        conv=sync       Pad blocks with zeros"
33 //usage:     "\n        conv=fsync      Physically write data out before finishing"
34 //usage:        )
35 //usage:     "\n"
36 //usage:     "\nNumbers may be suffixed by c (x1), w (x2), b (x512), kD (x1000), k (x1024),"
37 //usage:     "\nMD (x1000000), M (x1048576), GD (x1000000000) or G (x1073741824)"
38 //usage:
39 //usage:#define dd_example_usage
40 //usage:       "$ dd if=/dev/zero of=/dev/ram1 bs=1M count=4\n"
41 //usage:       "4+0 records in\n"
42 //usage:       "4+0 records out\n"
43
44 #include "libbb.h"
45
46 /* This is a NOEXEC applet. Be very careful! */
47
48
49 enum {
50         ifd = STDIN_FILENO,
51         ofd = STDOUT_FILENO,
52 };
53
54 static const struct suffix_mult dd_suffixes[] = {
55         { "c", 1 },
56         { "w", 2 },
57         { "b", 512 },
58         { "kD", 1000 },
59         { "k", 1024 },
60         { "K", 1024 },  /* compat with coreutils dd */
61         { "MD", 1000000 },
62         { "M", 1048576 },
63         { "GD", 1000000000 },
64         { "G", 1073741824 },
65         { "", 0 }
66 };
67
68 struct globals {
69         off_t out_full, out_part, in_full, in_part;
70 #if ENABLE_FEATURE_DD_THIRD_STATUS_LINE
71         unsigned long long total_bytes;
72         unsigned long long begin_time_us;
73 #endif
74 } FIX_ALIASING;
75 #define G (*(struct globals*)&bb_common_bufsiz1)
76 #define INIT_G() do { \
77         /* we have to zero it out because of NOEXEC */ \
78         memset(&G, 0, sizeof(G)); \
79 } while (0)
80
81
82 static void dd_output_status(int UNUSED_PARAM cur_signal)
83 {
84 #if ENABLE_FEATURE_DD_THIRD_STATUS_LINE
85         double seconds;
86         unsigned long long bytes_sec;
87         unsigned long long now_us = monotonic_us(); /* before fprintf */
88 #endif
89
90         /* Deliberately using %u, not %d */
91         fprintf(stderr, "%"OFF_FMT"u+%"OFF_FMT"u records in\n"
92                         "%"OFF_FMT"u+%"OFF_FMT"u records out\n",
93                         G.in_full, G.in_part,
94                         G.out_full, G.out_part);
95
96 #if ENABLE_FEATURE_DD_THIRD_STATUS_LINE
97         fprintf(stderr, "%llu bytes (%sB) copied, ",
98                         G.total_bytes,
99                         /* show fractional digit, use suffixes */
100                         make_human_readable_str(G.total_bytes, 1, 0)
101         );
102         /* Corner cases:
103          * ./busybox dd </dev/null >/dev/null
104          * ./busybox dd bs=1M count=2000 </dev/zero >/dev/null
105          * (echo DONE) | ./busybox dd >/dev/null
106          * (sleep 1; echo DONE) | ./busybox dd >/dev/null
107          */
108         seconds = (now_us - G.begin_time_us) / 1000000.0;
109         bytes_sec = G.total_bytes / seconds;
110         fprintf(stderr, "%f seconds, %sB/s\n",
111                         seconds,
112                         /* show fractional digit, use suffixes */
113                         make_human_readable_str(bytes_sec, 1, 0)
114         );
115 #endif
116 }
117
118 static ssize_t full_write_or_warn(const void *buf, size_t len,
119         const char *const filename)
120 {
121         ssize_t n = full_write(ofd, buf, len);
122         if (n < 0)
123                 bb_perror_msg("writing '%s'", filename);
124         return n;
125 }
126
127 static bool write_and_stats(const void *buf, size_t len, size_t obs,
128         const char *filename)
129 {
130         ssize_t n = full_write_or_warn(buf, len, filename);
131         if (n < 0)
132                 return 1;
133         if ((size_t)n == obs)
134                 G.out_full++;
135         else if (n) /* > 0 */
136                 G.out_part++;
137 #if ENABLE_FEATURE_DD_THIRD_STATUS_LINE
138         G.total_bytes += n;
139 #endif
140         return 0;
141 }
142
143 #if ENABLE_LFS
144 # define XATOU_SFX xatoull_sfx
145 #else
146 # define XATOU_SFX xatoul_sfx
147 #endif
148
149 int dd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
150 int dd_main(int argc UNUSED_PARAM, char **argv)
151 {
152         enum {
153                 /* Must be in the same order as OP_conv_XXX! */
154                 /* (see "flags |= (1 << what)" below) */
155                 FLAG_NOTRUNC = 1 << 0,
156                 FLAG_SYNC    = 1 << 1,
157                 FLAG_NOERROR = 1 << 2,
158                 FLAG_FSYNC   = 1 << 3,
159                 /* end of conv flags */
160                 FLAG_TWOBUFS = 1 << 4,
161                 FLAG_COUNT   = 1 << 5,
162         };
163         static const char keywords[] ALIGN1 =
164                 "bs\0""count\0""seek\0""skip\0""if\0""of\0"
165 #if ENABLE_FEATURE_DD_IBS_OBS
166                 "ibs\0""obs\0""conv\0"
167 #endif
168                 ;
169 #if ENABLE_FEATURE_DD_IBS_OBS
170         static const char conv_words[] ALIGN1 =
171                 "notrunc\0""sync\0""noerror\0""fsync\0";
172 #endif
173         enum {
174                 OP_bs = 0,
175                 OP_count,
176                 OP_seek,
177                 OP_skip,
178                 OP_if,
179                 OP_of,
180 #if ENABLE_FEATURE_DD_IBS_OBS
181                 OP_ibs,
182                 OP_obs,
183                 OP_conv,
184                 /* Must be in the same order as FLAG_XXX! */
185                 OP_conv_notrunc = 0,
186                 OP_conv_sync,
187                 OP_conv_noerror,
188                 OP_conv_fsync,
189         /* Unimplemented conv=XXX: */
190         //nocreat       do not create the output file
191         //excl          fail if the output file already exists
192         //fdatasync     physically write output file data before finishing
193         //swab          swap every pair of input bytes
194         //lcase         change upper case to lower case
195         //ucase         change lower case to upper case
196         //block         pad newline-terminated records with spaces to cbs-size
197         //unblock       replace trailing spaces in cbs-size records with newline
198         //ascii         from EBCDIC to ASCII
199         //ebcdic        from ASCII to EBCDIC
200         //ibm           from ASCII to alternate EBCDIC
201 #endif
202         };
203         int exitcode = EXIT_FAILURE;
204         size_t ibs = 512, obs = 512;
205         ssize_t n, w;
206         char *ibuf, *obuf;
207         /* And these are all zeroed at once! */
208         struct {
209                 int flags;
210                 size_t oc;
211                 off_t count;
212                 off_t seek, skip;
213                 const char *infile, *outfile;
214         } Z;
215 #define flags   (Z.flags  )
216 #define oc      (Z.oc     )
217 #define count   (Z.count  )
218 #define seek    (Z.seek   )
219 #define skip    (Z.skip   )
220 #define infile  (Z.infile )
221 #define outfile (Z.outfile)
222
223         memset(&Z, 0, sizeof(Z));
224         INIT_G();
225         //fflush_all(); - is this needed because of NOEXEC?
226
227         for (n = 1; argv[n]; n++) {
228                 int what;
229                 char *val;
230                 char *arg = argv[n];
231
232 #if ENABLE_DESKTOP
233                 /* "dd --". NB: coreutils 6.9 will complain if they see
234                  * more than one of them. We wouldn't. */
235                 if (arg[0] == '-' && arg[1] == '-' && arg[2] == '\0')
236                         continue;
237 #endif
238                 val = strchr(arg, '=');
239                 if (val == NULL)
240                         bb_show_usage();
241                 *val = '\0';
242                 what = index_in_strings(keywords, arg);
243                 if (what < 0)
244                         bb_show_usage();
245                 /* *val = '='; - to preserve ps listing? */
246                 val++;
247 #if ENABLE_FEATURE_DD_IBS_OBS
248                 if (what == OP_ibs) {
249                         /* Must fit into positive ssize_t */
250                         ibs = xatoul_range_sfx(val, 1, ((size_t)-1L)/2, dd_suffixes);
251                         /*continue;*/
252                 }
253                 if (what == OP_obs) {
254                         obs = xatoul_range_sfx(val, 1, ((size_t)-1L)/2, dd_suffixes);
255                         /*continue;*/
256                 }
257                 if (what == OP_conv) {
258                         while (1) {
259                                 /* find ',', replace them with NUL so we can use val for
260                                  * index_in_strings() without copying.
261                                  * We rely on val being non-null, else strchr would fault.
262                                  */
263                                 arg = strchr(val, ',');
264                                 if (arg)
265                                         *arg = '\0';
266                                 what = index_in_strings(conv_words, val);
267                                 if (what < 0)
268                                         bb_error_msg_and_die(bb_msg_invalid_arg, val, "conv");
269                                 flags |= (1 << what);
270                                 if (!arg) /* no ',' left, so this was the last specifier */
271                                         break;
272                                 /* *arg = ','; - to preserve ps listing? */
273                                 val = arg + 1; /* skip this keyword and ',' */
274                         }
275                         continue; /* we trashed 'what', can't fall through */
276                 }
277 #endif
278                 if (what == OP_bs) {
279                         ibs = obs = xatoul_range_sfx(val, 1, ((size_t)-1L)/2, dd_suffixes);
280                         /*continue;*/
281                 }
282                 /* These can be large: */
283                 if (what == OP_count) {
284                         flags |= FLAG_COUNT;
285                         count = XATOU_SFX(val, dd_suffixes);
286                         /*continue;*/
287                 }
288                 if (what == OP_seek) {
289                         seek = XATOU_SFX(val, dd_suffixes);
290                         /*continue;*/
291                 }
292                 if (what == OP_skip) {
293                         skip = XATOU_SFX(val, dd_suffixes);
294                         /*continue;*/
295                 }
296                 if (what == OP_if) {
297                         infile = val;
298                         /*continue;*/
299                 }
300                 if (what == OP_of) {
301                         outfile = val;
302                         /*continue;*/
303                 }
304         } /* end of "for (argv[n])" */
305
306 //XXX:FIXME for huge ibs or obs, malloc'ing them isn't the brightest idea ever
307         ibuf = obuf = xmalloc(ibs);
308         if (ibs != obs) {
309                 flags |= FLAG_TWOBUFS;
310                 obuf = xmalloc(obs);
311         }
312
313 #if ENABLE_FEATURE_DD_SIGNAL_HANDLING
314         signal_SA_RESTART_empty_mask(SIGUSR1, dd_output_status);
315 #endif
316 #if ENABLE_FEATURE_DD_THIRD_STATUS_LINE
317         G.begin_time_us = monotonic_us();
318 #endif
319
320         if (infile != NULL)
321                 xmove_fd(xopen(infile, O_RDONLY), ifd);
322         else {
323                 infile = bb_msg_standard_input;
324         }
325         if (outfile != NULL) {
326                 int oflag = O_WRONLY | O_CREAT;
327
328                 if (!seek && !(flags & FLAG_NOTRUNC))
329                         oflag |= O_TRUNC;
330
331                 xmove_fd(xopen(outfile, oflag), ofd);
332
333                 if (seek && !(flags & FLAG_NOTRUNC)) {
334                         if (ftruncate(ofd, seek * obs) < 0) {
335                                 struct stat st;
336
337                                 if (fstat(ofd, &st) < 0
338                                  || S_ISREG(st.st_mode)
339                                  || S_ISDIR(st.st_mode)
340                                 ) {
341                                         goto die_outfile;
342                                 }
343                         }
344                 }
345         } else {
346                 outfile = bb_msg_standard_output;
347         }
348         if (skip) {
349                 if (lseek(ifd, skip * ibs, SEEK_CUR) < 0) {
350                         while (skip-- > 0) {
351                                 n = safe_read(ifd, ibuf, ibs);
352                                 if (n < 0)
353                                         goto die_infile;
354                                 if (n == 0)
355                                         break;
356                         }
357                 }
358         }
359         if (seek) {
360                 if (lseek(ofd, seek * obs, SEEK_CUR) < 0)
361                         goto die_outfile;
362         }
363
364         while (!(flags & FLAG_COUNT) || (G.in_full + G.in_part != count)) {
365                 n = safe_read(ifd, ibuf, ibs);
366                 if (n == 0)
367                         break;
368                 if (n < 0) {
369                         /* "Bad block" */
370                         if (!(flags & FLAG_NOERROR))
371                                 goto die_infile;
372                         bb_simple_perror_msg(infile);
373                         /* GNU dd with conv=noerror skips over bad blocks */
374                         xlseek(ifd, ibs, SEEK_CUR);
375                         /* conv=noerror,sync writes NULs,
376                          * conv=noerror just ignores input bad blocks */
377                         n = 0;
378                 }
379                 if ((size_t)n == ibs)
380                         G.in_full++;
381                 else {
382                         G.in_part++;
383                         if (flags & FLAG_SYNC) {
384                                 memset(ibuf + n, 0, ibs - n);
385                                 n = ibs;
386                         }
387                 }
388                 if (flags & FLAG_TWOBUFS) {
389                         char *tmp = ibuf;
390                         while (n) {
391                                 size_t d = obs - oc;
392
393                                 if (d > (size_t)n)
394                                         d = n;
395                                 memcpy(obuf + oc, tmp, d);
396                                 n -= d;
397                                 tmp += d;
398                                 oc += d;
399                                 if (oc == obs) {
400                                         if (write_and_stats(obuf, obs, obs, outfile))
401                                                 goto out_status;
402                                         oc = 0;
403                                 }
404                         }
405                 } else if (write_and_stats(ibuf, n, obs, outfile))
406                         goto out_status;
407
408                 if (flags & FLAG_FSYNC) {
409                         if (fsync(ofd) < 0)
410                                 goto die_outfile;
411                 }
412         }
413
414         if (ENABLE_FEATURE_DD_IBS_OBS && oc) {
415                 w = full_write_or_warn(obuf, oc, outfile);
416                 if (w < 0) goto out_status;
417                 if (w > 0) G.out_part++;
418         }
419         if (close(ifd) < 0) {
420  die_infile:
421                 bb_simple_perror_msg_and_die(infile);
422         }
423
424         if (close(ofd) < 0) {
425  die_outfile:
426                 bb_simple_perror_msg_and_die(outfile);
427         }
428
429         exitcode = EXIT_SUCCESS;
430  out_status:
431         dd_output_status(0);
432
433         if (ENABLE_FEATURE_CLEAN_UP) {
434                 free(obuf);
435                 if (flags & FLAG_TWOBUFS)
436                         free(ibuf);
437         }
438
439         return exitcode;
440 }