more C standard compat fixes from Dan Fandrich
[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 tarball for details.
9  */
10
11 #include "libbb.h"
12
13 /* This is a NOEXEC applet. Be very careful! */
14
15
16 enum {
17         ifd = STDIN_FILENO,
18         ofd = STDOUT_FILENO,
19 };
20
21 static const struct suffix_mult dd_suffixes[] = {
22         { "c", 1 },
23         { "w", 2 },
24         { "b", 512 },
25         { "kD", 1000 },
26         { "k", 1024 },
27         { "K", 1024 },  /* compat with coreutils dd */
28         { "MD", 1000000 },
29         { "M", 1048576 },
30         { "GD", 1000000000 },
31         { "G", 1073741824 },
32         { "", 0 }
33 };
34
35 struct globals {
36         off_t out_full, out_part, in_full, in_part;
37 };
38 #define G (*(struct globals*)&bb_common_bufsiz1)
39 /* We have to zero it out because of NOEXEC */
40 #define INIT_G() memset(&G, 0, sizeof(G))
41
42
43 static void dd_output_status(int UNUSED_PARAM cur_signal)
44 {
45         /* Deliberately using %u, not %d */
46         fprintf(stderr, "%"OFF_FMT"u+%"OFF_FMT"u records in\n"
47                         "%"OFF_FMT"u+%"OFF_FMT"u records out\n",
48                         G.in_full, G.in_part,
49                         G.out_full, G.out_part);
50 }
51
52 static ssize_t full_write_or_warn(const void *buf, size_t len,
53         const char *const filename)
54 {
55         ssize_t n = full_write(ofd, buf, len);
56         if (n < 0)
57                 bb_perror_msg("writing '%s'", filename);
58         return n;
59 }
60
61 static bool write_and_stats(const void *buf, size_t len, size_t obs,
62         const char *filename)
63 {
64         ssize_t n = full_write_or_warn(buf, len, filename);
65         if (n < 0)
66                 return 1;
67         if ((size_t)n == obs)
68                 G.out_full++;
69         else if (n) /* > 0 */
70                 G.out_part++;
71         return 0;
72 }
73
74 #if ENABLE_LFS
75 #define XATOU_SFX xatoull_sfx
76 #else
77 #define XATOU_SFX xatoul_sfx
78 #endif
79
80 int dd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
81 int dd_main(int argc UNUSED_PARAM, char **argv)
82 {
83         enum {
84                 /* Must be in the same order as OP_conv_XXX! */
85                 /* (see "flags |= (1 << what)" below) */
86                 FLAG_NOTRUNC = 1 << 0,
87                 FLAG_SYNC    = 1 << 1,
88                 FLAG_NOERROR = 1 << 2,
89                 FLAG_FSYNC   = 1 << 3,
90                 /* end of conv flags */
91                 FLAG_TWOBUFS = 1 << 4,
92                 FLAG_COUNT   = 1 << 5,
93         };
94         static const char keywords[] ALIGN1 =
95                 "bs\0""count\0""seek\0""skip\0""if\0""of\0"
96 #if ENABLE_FEATURE_DD_IBS_OBS
97                 "ibs\0""obs\0""conv\0"
98 #endif
99                 ;
100 #if ENABLE_FEATURE_DD_IBS_OBS
101         static const char conv_words[] ALIGN1 =
102                 "notrunc\0""sync\0""noerror\0""fsync\0";
103 #endif
104         enum {
105                 OP_bs = 0,
106                 OP_count,
107                 OP_seek,
108                 OP_skip,
109                 OP_if,
110                 OP_of,
111 #if ENABLE_FEATURE_DD_IBS_OBS
112                 OP_ibs,
113                 OP_obs,
114                 OP_conv,
115                 /* Must be in the same order as FLAG_XXX! */
116                 OP_conv_notrunc = 0,
117                 OP_conv_sync,
118                 OP_conv_noerror,
119                 OP_conv_fsync,
120         /* Unimplemented conv=XXX: */
121         //nocreat       do not create the output file
122         //excl          fail if the output file already exists
123         //fdatasync     physically write output file data before finishing
124         //swab          swap every pair of input bytes
125         //lcase         change upper case to lower case
126         //ucase         change lower case to upper case
127         //block         pad newline-terminated records with spaces to cbs-size
128         //unblock       replace trailing spaces in cbs-size records with newline
129         //ascii         from EBCDIC to ASCII
130         //ebcdic        from ASCII to EBCDIC
131         //ibm           from ASCII to alternate EBCDIC
132 #endif
133         };
134         int exitcode = EXIT_FAILURE;
135         size_t ibs = 512, obs = 512;
136         ssize_t n, w;
137         char *ibuf, *obuf;
138         /* And these are all zeroed at once! */
139         struct {
140                 int flags;
141                 size_t oc;
142                 off_t count;
143                 off_t seek, skip;
144                 const char *infile, *outfile;
145         } Z;
146 #define flags   (Z.flags  )
147 #define oc      (Z.oc     )
148 #define count   (Z.count  )
149 #define seek    (Z.seek   )
150 #define skip    (Z.skip   )
151 #define infile  (Z.infile )
152 #define outfile (Z.outfile)
153
154         memset(&Z, 0, sizeof(Z));
155         INIT_G();
156         //fflush(NULL); - is this needed because of NOEXEC?
157
158 #if ENABLE_FEATURE_DD_SIGNAL_HANDLING
159         signal_SA_RESTART_empty_mask(SIGUSR1, dd_output_status);
160 #endif
161
162         for (n = 1; argv[n]; n++) {
163                 int what;
164                 char *val;
165                 char *arg = argv[n];
166
167 #if ENABLE_DESKTOP
168                 /* "dd --". NB: coreutils 6.9 will complain if they see
169                  * more than one of them. We wouldn't. */
170                 if (arg[0] == '-' && arg[1] == '-' && arg[2] == '\0')
171                         continue;
172 #endif
173                 val = strchr(arg, '=');
174                 if (val == NULL)
175                         bb_show_usage();
176                 *val = '\0';
177                 what = index_in_strings(keywords, arg);
178                 if (what < 0)
179                         bb_show_usage();
180                 /* *val = '='; - to preserve ps listing? */
181                 val++;
182 #if ENABLE_FEATURE_DD_IBS_OBS
183                 if (what == OP_ibs) {
184                         /* Must fit into positive ssize_t */
185                         ibs = xatoul_range_sfx(val, 1, ((size_t)-1L)/2, dd_suffixes);
186                         /*continue;*/
187                 }
188                 if (what == OP_obs) {
189                         obs = xatoul_range_sfx(val, 1, ((size_t)-1L)/2, dd_suffixes);
190                         /*continue;*/
191                 }
192                 if (what == OP_conv) {
193                         while (1) {
194                                 /* find ',', replace them with NUL so we can use val for
195                                  * index_in_strings() without copying.
196                                  * We rely on val being non-null, else strchr would fault.
197                                  */
198                                 arg = strchr(val, ',');
199                                 if (arg)
200                                         *arg = '\0';
201                                 what = index_in_strings(conv_words, val);
202                                 if (what < 0)
203                                         bb_error_msg_and_die(bb_msg_invalid_arg, val, "conv");
204                                 flags |= (1 << what);
205                                 if (!arg) /* no ',' left, so this was the last specifier */
206                                         break;
207                                 /* *arg = ','; - to preserve ps listing? */
208                                 val = arg + 1; /* skip this keyword and ',' */
209                         }
210                         continue; /* we trashed 'what', can't fall through */
211                 }
212 #endif
213                 if (what == OP_bs) {
214                         ibs = obs = xatoul_range_sfx(val, 1, ((size_t)-1L)/2, dd_suffixes);
215                         /*continue;*/
216                 }
217                 /* These can be large: */
218                 if (what == OP_count) {
219                         flags |= FLAG_COUNT;
220                         count = XATOU_SFX(val, dd_suffixes);
221                         /*continue;*/
222                 }
223                 if (what == OP_seek) {
224                         seek = XATOU_SFX(val, dd_suffixes);
225                         /*continue;*/
226                 }
227                 if (what == OP_skip) {
228                         skip = XATOU_SFX(val, dd_suffixes);
229                         /*continue;*/
230                 }
231                 if (what == OP_if) {
232                         infile = val;
233                         /*continue;*/
234                 }
235                 if (what == OP_of) {
236                         outfile = val;
237                         /*continue;*/
238                 }
239         } /* end of "for (argv[n])" */
240
241 //XXX:FIXME for huge ibs or obs, malloc'ing them isn't the brightest idea ever
242         ibuf = obuf = xmalloc(ibs);
243         if (ibs != obs) {
244                 flags |= FLAG_TWOBUFS;
245                 obuf = xmalloc(obs);
246         }
247         if (infile != NULL)
248                 xmove_fd(xopen(infile, O_RDONLY), ifd);
249         else {
250                 infile = bb_msg_standard_input;
251         }
252         if (outfile != NULL) {
253                 int oflag = O_WRONLY | O_CREAT;
254
255                 if (!seek && !(flags & FLAG_NOTRUNC))
256                         oflag |= O_TRUNC;
257
258                 xmove_fd(xopen(outfile, oflag), ofd);
259
260                 if (seek && !(flags & FLAG_NOTRUNC)) {
261                         if (ftruncate(ofd, seek * obs) < 0) {
262                                 struct stat st;
263
264                                 if (fstat(ofd, &st) < 0 || S_ISREG(st.st_mode) ||
265                                                 S_ISDIR(st.st_mode))
266                                         goto die_outfile;
267                         }
268                 }
269         } else {
270                 outfile = bb_msg_standard_output;
271         }
272         if (skip) {
273                 if (lseek(ifd, skip * ibs, SEEK_CUR) < 0) {
274                         while (skip-- > 0) {
275                                 n = safe_read(ifd, ibuf, ibs);
276                                 if (n < 0)
277                                         goto die_infile;
278                                 if (n == 0)
279                                         break;
280                         }
281                 }
282         }
283         if (seek) {
284                 if (lseek(ofd, seek * obs, SEEK_CUR) < 0)
285                         goto die_outfile;
286         }
287
288         while (!(flags & FLAG_COUNT) || (G.in_full + G.in_part != count)) {
289                 if (flags & FLAG_NOERROR) /* Pre-zero the buffer if conv=noerror */
290                         memset(ibuf, 0, ibs);
291                 n = safe_read(ifd, ibuf, ibs);
292                 if (n == 0)
293                         break;
294                 if (n < 0) {
295                         if (!(flags & FLAG_NOERROR))
296                                 goto die_infile;
297                         n = ibs;
298                         bb_simple_perror_msg(infile);
299                         /* GNU dd with conv=noerror skips over "bad blocks" */
300                         xlseek(ifd, ibs, SEEK_CUR);
301                 }
302                 if ((size_t)n == ibs)
303                         G.in_full++;
304                 else {
305                         G.in_part++;
306                         if (flags & FLAG_SYNC) {
307                                 memset(ibuf + n, '\0', ibs - n);
308                                 n = ibs;
309                         }
310                 }
311                 if (flags & FLAG_TWOBUFS) {
312                         char *tmp = ibuf;
313                         while (n) {
314                                 size_t d = obs - oc;
315
316                                 if (d > (size_t)n)
317                                         d = n;
318                                 memcpy(obuf + oc, tmp, d);
319                                 n -= d;
320                                 tmp += d;
321                                 oc += d;
322                                 if (oc == obs) {
323                                         if (write_and_stats(obuf, obs, obs, outfile))
324                                                 goto out_status;
325                                         oc = 0;
326                                 }
327                         }
328                 } else if (write_and_stats(ibuf, n, obs, outfile))
329                         goto out_status;
330
331                 if (flags & FLAG_FSYNC) {
332                         if (fsync(ofd) < 0)
333                                 goto die_outfile;
334                 }
335         }
336
337         if (ENABLE_FEATURE_DD_IBS_OBS && oc) {
338                 w = full_write_or_warn(obuf, oc, outfile);
339                 if (w < 0) goto out_status;
340                 if (w > 0) G.out_part++;
341         }
342         if (close(ifd) < 0) {
343  die_infile:
344                 bb_simple_perror_msg_and_die(infile);
345         }
346
347         if (close(ofd) < 0) {
348  die_outfile:
349                 bb_simple_perror_msg_and_die(outfile);
350         }
351
352         exitcode = EXIT_SUCCESS;
353  out_status:
354         dd_output_status(0);
355
356         return exitcode;
357 }