46a62cbf1d0b3f93305d4765122b178512fe16fc
[oweals/busybox.git] / findutils / xargs.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini xargs implementation for busybox
4  *
5  * (C) 2002,2003 by Vladimir Oleynik <dzo@simtreas.ru>
6  *
7  * Special thanks
8  * - Mark Whitley and Glenn McGrath for stimulus to rewrite :)
9  * - Mike Rendell <michael@cs.mun.ca>
10  * and David MacKenzie <djm@gnu.ai.mit.edu>.
11  *
12  * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
13  *
14  * xargs is described in the Single Unix Specification v3 at
15  * http://www.opengroup.org/onlinepubs/007904975/utilities/xargs.html
16  */
17
18 //applet:IF_XARGS(APPLET_NOEXEC(xargs, xargs, _BB_DIR_USR_BIN, _BB_SUID_DROP, xargs))
19
20 //kbuild:lib-$(CONFIG_XARGS) += xargs.o
21
22 //config:config XARGS
23 //config:       bool "xargs"
24 //config:       default y
25 //config:       help
26 //config:         xargs is used to execute a specified command for
27 //config:         every item from standard input.
28 //config:
29 //config:config FEATURE_XARGS_SUPPORT_CONFIRMATION
30 //config:       bool "Enable -p: prompt and confirmation"
31 //config:       default y
32 //config:       depends on XARGS
33 //config:       help
34 //config:         Support -p: prompt the user whether to run each command
35 //config:         line and read a line from the terminal.
36 //config:
37 //config:config FEATURE_XARGS_SUPPORT_QUOTES
38 //config:       bool "Enable single and double quotes and backslash"
39 //config:       default y
40 //config:       depends on XARGS
41 //config:       help
42 //config:         Support quoting in the input.
43 //config:
44 //config:config FEATURE_XARGS_SUPPORT_TERMOPT
45 //config:       bool "Enable -x: exit if -s or -n is exceeded"
46 //config:       default y
47 //config:       depends on XARGS
48 //config:       help
49 //config:         Support -x: exit if the command size (see the -s or -n option)
50 //config:         is exceeded.
51 //config:
52 //config:config FEATURE_XARGS_SUPPORT_ZERO_TERM
53 //config:       bool "Enable -0: NUL-terminated input"
54 //config:       default y
55 //config:       depends on XARGS
56 //config:       help
57 //config:         Support -0: input items are terminated by a NUL character
58 //config:         instead of whitespace, and the quotes and backslash
59 //config:         are not special.
60
61 #include "libbb.h"
62 /* COMPAT:  SYSV version defaults size (and has a max value of) to 470.
63    We try to make it as large as possible. */
64 #if !defined(ARG_MAX) && defined(_SC_ARG_MAX)
65 # define ARG_MAX sysconf(_SC_ARG_MAX)
66 #endif
67 #if !defined(ARG_MAX)
68 # define ARG_MAX 470
69 #endif
70
71 /* This is a NOEXEC applet. Be very careful! */
72
73
74 //#define dbg_msg(...) bb_error_msg(__VA_ARGS__)
75 #define dbg_msg(...) ((void)0)
76
77
78 #ifdef TEST
79 # ifndef ENABLE_FEATURE_XARGS_SUPPORT_CONFIRMATION
80 #  define ENABLE_FEATURE_XARGS_SUPPORT_CONFIRMATION 1
81 # endif
82 # ifndef ENABLE_FEATURE_XARGS_SUPPORT_QUOTES
83 #  define ENABLE_FEATURE_XARGS_SUPPORT_QUOTES 1
84 # endif
85 # ifndef ENABLE_FEATURE_XARGS_SUPPORT_TERMOPT
86 #  define ENABLE_FEATURE_XARGS_SUPPORT_TERMOPT 1
87 # endif
88 # ifndef ENABLE_FEATURE_XARGS_SUPPORT_ZERO_TERM
89 #  define ENABLE_FEATURE_XARGS_SUPPORT_ZERO_TERM 1
90 # endif
91 #endif
92
93
94 struct globals {
95         char **args;
96         const char *eof_str;
97         int idx;
98 } FIX_ALIASING;
99 #define G (*(struct globals*)&bb_common_bufsiz1)
100 #define INIT_G() do { } while (0)
101
102
103 /*
104  * This function has special algorithm.
105  * Don't use fork and include to main!
106  */
107 static int xargs_exec(void)
108 {
109         int status;
110
111         status = spawn_and_wait(G.args);
112         if (status < 0) {
113                 bb_simple_perror_msg(G.args[0]);
114                 return errno == ENOENT ? 127 : 126;
115         }
116         if (status == 255) {
117                 bb_error_msg("%s: exited with status 255; aborting", G.args[0]);
118                 return 124;
119         }
120         if (status >= 0x180) {
121                 bb_error_msg("%s: terminated by signal %d",
122                         G.args[0], status - 0x180);
123                 return 125;
124         }
125         if (status)
126                 return 123;
127         return 0;
128 }
129
130 /* In POSIX/C locale isspace is only these chars: "\t\n\v\f\r" and space.
131  * "\t\n\v\f\r" happen to have ASCII codes 9,10,11,12,13.
132  */
133 #define ISSPACE(a) ({ unsigned char xargs__isspace = (a) - 9; xargs__isspace == (' ' - 9) || xargs__isspace <= (13 - 9); })
134
135 static void store_param(char *s)
136 {
137         /* Grow by 256 elements at once */
138         if (!(G.idx & 0xff)) { /* G.idx == N*256 */
139                 /* Enlarge, make G.args[(N+1)*256 - 1] last valid idx */
140                 G.args = xrealloc(G.args, sizeof(G.args[0]) * (G.idx + 0x100));
141         }
142         G.args[G.idx++] = s;
143 }
144
145 /* process[0]_stdin:
146  * Read characters into buf[n_max_chars+1], and when parameter delimiter
147  * is seen, store the address of a new parameter to args[].
148  * If reading discovers that last chars do not form the complete
149  * parameter, the pointer to the first such "tail character" is returned.
150  * (buf has extra byte at the end to accomodate terminating NUL
151  * of "tail characters" string).
152  * Otherwise, the returned pointer points to NUL byte.
153  * On entry, buf[] may contain some "seed chars" which are to become
154  * the beginning of the first parameter.
155  */
156
157 #if ENABLE_FEATURE_XARGS_SUPPORT_QUOTES
158 static char* FAST_FUNC process_stdin(int n_max_chars, int n_max_arg, char *buf)
159 {
160 #define NORM      0
161 #define QUOTE     1
162 #define BACKSLASH 2
163 #define SPACE     4
164         char q = '\0';             /* quote char */
165         char state = NORM;
166         char *s = buf;             /* start of the word */
167         char *p = s + strlen(buf); /* end of the word */
168
169         buf += n_max_chars;        /* past buffer's end */
170
171         /* "goto ret" is used instead of "break" to make control flow
172          * more obvious: */
173
174         while (1) {
175                 int c = getchar();
176                 if (c == EOF) {
177                         if (p != s)
178                                 goto close_word;
179                         goto ret;
180                 }
181                 if (state == BACKSLASH) {
182                         state = NORM;
183                         goto set;
184                 }
185                 if (state == QUOTE) {
186                         if (c != q)
187                                 goto set;
188                         q = '\0';
189                         state = NORM;
190                 } else { /* if (state == NORM) */
191                         if (ISSPACE(c)) {
192                                 if (p != s) {
193  close_word:
194                                         state = SPACE;
195                                         c = '\0';
196                                         goto set;
197                                 }
198                         } else {
199                                 if (c == '\\') {
200                                         state = BACKSLASH;
201                                 } else if (c == '\'' || c == '"') {
202                                         q = c;
203                                         state = QUOTE;
204                                 } else {
205  set:
206                                         *p++ = c;
207                                 }
208                         }
209                 }
210                 if (state == SPACE) {   /* word's delimiter or EOF detected */
211                         if (q) {
212                                 bb_error_msg_and_die("unmatched %s quote",
213                                         q == '\'' ? "single" : "double");
214                         }
215                         /* A full word is loaded */
216                         if (G.eof_str) {
217                                 if (strcmp(s, G.eof_str) == 0) {
218                                         while (getchar() != EOF)
219                                                 continue;
220                                         p = s;
221                                         goto ret;
222                                 }
223                         }
224                         store_param(s);
225                         dbg_msg("args[]:'%s'", s);
226                         s = p;
227                         n_max_arg--;
228                         if (n_max_arg == 0) {
229                                 goto ret;
230                         }
231                         state = NORM;
232                 }
233                 if (p == buf) {
234                         goto ret;
235                 }
236         }
237  ret:
238         *p = '\0';
239         /* store_param(NULL) - caller will do it */
240         dbg_msg("return:'%s'", s);
241         return s;
242 }
243 #else
244 /* The variant does not support single quotes, double quotes or backslash */
245 static char* FAST_FUNC process_stdin(int n_max_chars, int n_max_arg, char *buf)
246 {
247         char *s = buf;             /* start of the word */
248         char *p = s + strlen(buf); /* end of the word */
249
250         buf += n_max_chars;        /* past buffer's end */
251
252         while (1) {
253                 int c = getchar();
254                 if (c == EOF) {
255                         if (p == s)
256                                 goto ret;
257                 }
258                 if (c == EOF || ISSPACE(c)) {
259                         if (p == s)
260                                 continue;
261                         c = EOF;
262                 }
263                 *p++ = (c == EOF ? '\0' : c);
264                 if (c == EOF) { /* word's delimiter or EOF detected */
265                         /* A full word is loaded */
266                         if (G.eof_str) {
267                                 if (strcmp(s, G.eof_str) == 0) {
268                                         while (getchar() != EOF)
269                                                 continue;
270                                         p = s;
271                                         goto ret;
272                                 }
273                         }
274                         store_param(s);
275                         dbg_msg("args[]:'%s'", s);
276                         s = p;
277                         n_max_arg--;
278                         if (n_max_arg == 0) {
279                                 goto ret;
280                         }
281                 }
282                 if (p == buf) {
283                         goto ret;
284                 }
285         }
286  ret:
287         *p = '\0';
288         /* store_param(NULL) - caller will do it */
289         dbg_msg("return:'%s'", s);
290         return s;
291 }
292 #endif /* FEATURE_XARGS_SUPPORT_QUOTES */
293
294 #if ENABLE_FEATURE_XARGS_SUPPORT_ZERO_TERM
295 static char* FAST_FUNC process0_stdin(int n_max_chars, int n_max_arg, char *buf)
296 {
297         char *s = buf;             /* start of the word */
298         char *p = s + strlen(buf); /* end of the word */
299
300         buf += n_max_chars;        /* past buffer's end */
301
302         while (1) {
303                 int c = getchar();
304                 if (c == EOF) {
305                         if (p == s)
306                                 goto ret;
307                         c = '\0';
308                 }
309                 *p++ = c;
310                 if (c == '\0') {   /* word's delimiter or EOF detected */
311                         /* A full word is loaded */
312                         store_param(s);
313                         dbg_msg("args[]:'%s'", s);
314                         s = p;
315                         n_max_arg--;
316                         if (n_max_arg == 0) {
317                                 goto ret;
318                         }
319                 }
320                 if (p == buf) {
321                         goto ret;
322                 }
323         }
324  ret:
325         *p = '\0';
326         /* store_param(NULL) - caller will do it */
327         dbg_msg("return:'%s'", s);
328         return s;
329 }
330 #endif /* FEATURE_XARGS_SUPPORT_ZERO_TERM */
331
332 #if ENABLE_FEATURE_XARGS_SUPPORT_CONFIRMATION
333 /* Prompt the user for a response, and
334    if the user responds affirmatively, return true;
335    otherwise, return false. Uses "/dev/tty", not stdin. */
336 static int xargs_ask_confirmation(void)
337 {
338         FILE *tty_stream;
339         int c, savec;
340
341         tty_stream = xfopen_for_read(CURRENT_TTY);
342         fputs(" ?...", stderr);
343         fflush_all();
344         c = savec = getc(tty_stream);
345         while (c != EOF && c != '\n')
346                 c = getc(tty_stream);
347         fclose(tty_stream);
348         return (savec == 'y' || savec == 'Y');
349 }
350 #else
351 # define xargs_ask_confirmation() 1
352 #endif
353
354 //usage:#define xargs_trivial_usage
355 //usage:       "[OPTIONS] [PROG ARGS]"
356 //usage:#define xargs_full_usage "\n\n"
357 //usage:       "Run PROG on every item given by stdin\n"
358 //usage:     "\nOptions:"
359 //usage:        IF_FEATURE_XARGS_SUPPORT_CONFIRMATION(
360 //usage:     "\n        -p      Ask user whether to run each command"
361 //usage:        )
362 //usage:     "\n        -r      Don't run command if input is empty"
363 //usage:        IF_FEATURE_XARGS_SUPPORT_ZERO_TERM(
364 //usage:     "\n        -0      Input is separated by NUL characters"
365 //usage:        )
366 //usage:     "\n        -t      Print the command on stderr before execution"
367 //usage:     "\n        -e[STR] STR stops input processing"
368 //usage:     "\n        -n N    Pass no more than N args to PROG"
369 //usage:     "\n        -s N    Pass command line of no more than N bytes"
370 //usage:        IF_FEATURE_XARGS_SUPPORT_TERMOPT(
371 //usage:     "\n        -x      Exit if size is exceeded"
372 //usage:        )
373 //usage:#define xargs_example_usage
374 //usage:       "$ ls | xargs gzip\n"
375 //usage:       "$ find . -name '*.c' -print | xargs rm\n"
376
377 /* Correct regardless of combination of CONFIG_xxx */
378 enum {
379         OPTBIT_VERBOSE = 0,
380         OPTBIT_NO_EMPTY,
381         OPTBIT_UPTO_NUMBER,
382         OPTBIT_UPTO_SIZE,
383         OPTBIT_EOF_STRING,
384         OPTBIT_EOF_STRING1,
385         IF_FEATURE_XARGS_SUPPORT_CONFIRMATION(OPTBIT_INTERACTIVE,)
386         IF_FEATURE_XARGS_SUPPORT_TERMOPT(     OPTBIT_TERMINATE  ,)
387         IF_FEATURE_XARGS_SUPPORT_ZERO_TERM(   OPTBIT_ZEROTERM   ,)
388
389         OPT_VERBOSE     = 1 << OPTBIT_VERBOSE    ,
390         OPT_NO_EMPTY    = 1 << OPTBIT_NO_EMPTY   ,
391         OPT_UPTO_NUMBER = 1 << OPTBIT_UPTO_NUMBER,
392         OPT_UPTO_SIZE   = 1 << OPTBIT_UPTO_SIZE  ,
393         OPT_EOF_STRING  = 1 << OPTBIT_EOF_STRING , /* GNU: -e[<param>] */
394         OPT_EOF_STRING1 = 1 << OPTBIT_EOF_STRING1, /* SUS: -E<param> */
395         OPT_INTERACTIVE = IF_FEATURE_XARGS_SUPPORT_CONFIRMATION((1 << OPTBIT_INTERACTIVE)) + 0,
396         OPT_TERMINATE   = IF_FEATURE_XARGS_SUPPORT_TERMOPT(     (1 << OPTBIT_TERMINATE  )) + 0,
397         OPT_ZEROTERM    = IF_FEATURE_XARGS_SUPPORT_ZERO_TERM(   (1 << OPTBIT_ZEROTERM   )) + 0,
398 };
399 #define OPTION_STR "+trn:s:e::E:" \
400         IF_FEATURE_XARGS_SUPPORT_CONFIRMATION("p") \
401         IF_FEATURE_XARGS_SUPPORT_TERMOPT(     "x") \
402         IF_FEATURE_XARGS_SUPPORT_ZERO_TERM(   "0")
403
404 int xargs_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
405 int xargs_main(int argc, char **argv)
406 {
407         int i;
408         int child_error = 0;
409         char *max_args;
410         char *max_chars;
411         char *buf;
412         unsigned opt;
413         int n_max_chars;
414         int n_max_arg;
415 #if ENABLE_FEATURE_XARGS_SUPPORT_ZERO_TERM
416         char* FAST_FUNC (*read_args)(int, int, char*) = process_stdin;
417 #else
418 #define read_args process_stdin
419 #endif
420
421         INIT_G();
422
423         G.eof_str = NULL;
424         opt = getopt32(argv, OPTION_STR, &max_args, &max_chars, &G.eof_str, &G.eof_str);
425
426         /* -E ""? You may wonder why not just omit -E?
427          * This is used for portability:
428          * old xargs was using "_" as default for -E / -e */
429         if ((opt & OPT_EOF_STRING1) && G.eof_str[0] == '\0')
430                 G.eof_str = NULL;
431
432         if (opt & OPT_ZEROTERM)
433                 IF_FEATURE_XARGS_SUPPORT_ZERO_TERM(read_args = process0_stdin);
434
435         argv += optind;
436         argc -= optind;
437         if (!argv[0]) {
438                 /* default behavior is to echo all the filenames */
439                 *--argv = (char*)"echo";
440                 argc++;
441         }
442
443         /* The Open Group Base Specifications Issue 6:
444          * "The xargs utility shall limit the command line length such that
445          * when the command line is invoked, the combined argument
446          * and environment lists (see the exec family of functions
447          * in the System Interfaces volume of IEEE Std 1003.1-2001)
448          * shall not exceed {ARG_MAX}-2048 bytes".
449          */
450         n_max_chars = ARG_MAX; /* might be calling sysconf(_SC_ARG_MAX) */
451         if (n_max_chars < 4*1024); /* paranoia */
452                 n_max_chars = 4*1024;
453         n_max_chars -= 2048;
454         /* Sanity check for systems with huge ARG_MAX defines (e.g., Suns which
455          * have it at 1 meg).  Things will work fine with a large ARG_MAX
456          * but it will probably hurt the system more than it needs to;
457          * an array of this size is allocated.
458          */
459         if (n_max_chars > 20 * 1024)
460                 n_max_chars = 20 * 1024;
461
462         if (opt & OPT_UPTO_SIZE) {
463                 size_t n_chars = 0;
464                 n_max_chars = xatou_range(max_chars, 1, INT_MAX);
465                 for (i = 0; argv[i]; i++) {
466                         n_chars += strlen(argv[i]) + 1;
467                 }
468                 n_max_chars -= n_chars;
469                 if (n_max_chars <= 0) {
470                         bb_error_msg_and_die("can't fit single argument within argument list size limit");
471                 }
472         }
473
474         buf = xzalloc(n_max_chars + 1);
475
476         n_max_arg = n_max_chars;
477         if (opt & OPT_UPTO_NUMBER) {
478                 n_max_arg = xatou_range(max_args, 1, INT_MAX);
479         }
480
481         /* Allocate pointers for execvp */
482         /* We can statically allocate (argc + n_max_arg + 1) elements
483          * and do not bother with resizing args[], but on 64-bit machines
484          * this results in args[] vector which is ~8 times bigger
485          * than n_max_chars! That is, with n_max_chars == 20k,
486          * args[] will take 160k (!), which will most likely be
487          * almost entirely unused.
488          */
489         /* See store_param() for matching 256-step growth logic */
490         G.args = xmalloc(sizeof(G.args[0]) * ((argc + 0xff) & ~0xff));
491
492         /* Store the command to be executed, part 1 */
493         for (i = 0; argv[i]; i++)
494                 G.args[i] = argv[i];
495
496         while (1) {
497                 char *rem;
498
499                 G.idx = argc;
500                 rem = read_args(n_max_chars, n_max_arg, buf);
501                 store_param(NULL);
502
503                 if (!G.args[argc]) {
504                         if (*rem != '\0')
505                                 bb_error_msg_and_die("argument line too long");
506                         if (opt & OPT_NO_EMPTY)
507                                 break;
508                 }
509                 opt |= OPT_NO_EMPTY;
510
511                 if (opt & (OPT_INTERACTIVE | OPT_VERBOSE)) {
512                         const char *fmt = " %s" + 1;
513                         char **args = G.args;
514                         for (i = 0; args[i]; i++) {
515                                 fprintf(stderr, fmt, args[i]);
516                                 fmt = " %s";
517                         }
518                         if (!(opt & OPT_INTERACTIVE))
519                                 bb_putchar_stderr('\n');
520                 }
521
522                 if (!(opt & OPT_INTERACTIVE) || xargs_ask_confirmation()) {
523                         child_error = xargs_exec();
524                 }
525
526                 if (child_error > 0 && child_error != 123) {
527                         break;
528                 }
529
530                 overlapping_strcpy(buf, rem);
531         } /* while */
532
533         if (ENABLE_FEATURE_CLEAN_UP) {
534                 free(G.args);
535                 free(buf);
536         }
537
538         return child_error;
539 }
540
541
542 #ifdef TEST
543
544 const char *applet_name = "debug stuff usage";
545
546 void bb_show_usage(void)
547 {
548         fprintf(stderr, "Usage: %s [-p] [-r] [-t] -[x] [-n max_arg] [-s max_chars]\n",
549                 applet_name);
550         exit(EXIT_FAILURE);
551 }
552
553 int main(int argc, char **argv)
554 {
555         return xargs_main(argc, argv);
556 }
557 #endif /* TEST */