xargs: code shrink -15 bytes
[oweals/busybox.git] / findutils / xargs.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini xargs implementation for busybox
4  * Options are supported: "-prtx -n max_arg -s max_chars -e[ouf_str]"
5  *
6  * (C) 2002,2003 by Vladimir Oleynik <dzo@simtreas.ru>
7  *
8  * Special thanks
9  * - Mark Whitley and Glenn McGrath for stimulus to rewrite :)
10  * - Mike Rendell <michael@cs.mun.ca>
11  * and David MacKenzie <djm@gnu.ai.mit.edu>.
12  *
13  * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
14  *
15  * xargs is described in the Single Unix Specification v3 at
16  * http://www.opengroup.org/onlinepubs/007904975/utilities/xargs.html
17  *
18  */
19
20 //kbuild:lib-$(CONFIG_XARGS) += xargs.o
21 //config:
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
63 /* This is a NOEXEC applet. Be very careful! */
64
65
66 /* COMPAT:  SYSV version defaults size (and has a max value of) to 470.
67    We try to make it as large as possible. */
68 #if !defined(ARG_MAX) && defined(_SC_ARG_MAX)
69 # define ARG_MAX sysconf(_SC_ARG_MAX)
70 #endif
71 #if !defined(ARG_MAX)
72 # define ARG_MAX 470
73 #endif
74
75
76 #ifdef TEST
77 # ifndef ENABLE_FEATURE_XARGS_SUPPORT_CONFIRMATION
78 #  define ENABLE_FEATURE_XARGS_SUPPORT_CONFIRMATION 1
79 # endif
80 # ifndef ENABLE_FEATURE_XARGS_SUPPORT_QUOTES
81 #  define ENABLE_FEATURE_XARGS_SUPPORT_QUOTES 1
82 # endif
83 # ifndef ENABLE_FEATURE_XARGS_SUPPORT_TERMOPT
84 #  define ENABLE_FEATURE_XARGS_SUPPORT_TERMOPT 1
85 # endif
86 # ifndef ENABLE_FEATURE_XARGS_SUPPORT_ZERO_TERM
87 #  define ENABLE_FEATURE_XARGS_SUPPORT_ZERO_TERM 1
88 # endif
89 #endif
90
91 /*
92    This function has special algorithm.
93    Don't use fork and include to main!
94 */
95 static int xargs_exec(char **args)
96 {
97         int status;
98
99         status = spawn_and_wait(args);
100         if (status < 0) {
101                 bb_simple_perror_msg(args[0]);
102                 return errno == ENOENT ? 127 : 126;
103         }
104         if (status == 255) {
105                 bb_error_msg("%s: exited with status 255; aborting", args[0]);
106                 return 124;
107         }
108         if (status >= 0x180) {
109                 bb_error_msg("%s: terminated by signal %d",
110                         args[0], status - 0x180);
111                 return 125;
112         }
113         if (status)
114                 return 123;
115         return 0;
116 }
117
118
119 typedef struct xlist_t {
120         struct xlist_t *link;
121         size_t length;
122         char xstr[1];
123 } xlist_t;
124
125 /* In POSIX/C locale isspace is only these chars: "\t\n\v\f\r" and space.
126  * "\t\n\v\f\r" happen to have ASCII codes 9,10,11,12,13.
127  */
128 #define ISSPACE(a) ({ unsigned char xargs__isspace = (a) - 9; xargs__isspace == (' ' - 9) || xargs__isspace <= (13 - 9); })
129
130 #if ENABLE_FEATURE_XARGS_SUPPORT_QUOTES
131 static xlist_t* process_stdin(xlist_t *list_arg,
132         const char *eof_str, size_t mc, char *buf)
133 {
134 #define NORM      0
135 #define QUOTE     1
136 #define BACKSLASH 2
137 #define SPACE     4
138         char *s = NULL;         /* start of the word */
139         char *p = NULL;         /* pointer to end of the word */
140         char q = '\0';          /* quote char */
141         char state = NORM;
142         char eof_str_detected = 0;
143         size_t line_l = 0;      /* size of loaded args */
144         xlist_t *cur;
145         xlist_t *prev;
146
147         prev = cur = list_arg;
148         while (cur) {
149                 prev = cur;
150                 line_l += cur->length;
151                 cur = cur->link;
152         }
153
154         while (1) {
155                 int c = getchar();
156                 if (c == EOF) {
157                         if (s)
158                                 goto unexpected_eof;
159                         break;
160                 }
161                 if (eof_str_detected) /* skip till EOF */
162                         continue;
163                 if (state == BACKSLASH) {
164                         state = NORM;
165                         goto set;
166                 }
167                 if (state == QUOTE) {
168                         if (c != q)
169                                 goto set;
170                         q = '\0';
171                         state = NORM;
172                 } else { /* if (state == NORM) */
173                         if (ISSPACE(c)) {
174                                 if (s) {
175  unexpected_eof:
176                                         state = SPACE;
177                                         c = '\0';
178                                         goto set;
179                                 }
180                         } else {
181                                 if (s == NULL)
182                                         s = p = buf;
183                                 if (c == '\\') {
184                                         state = BACKSLASH;
185                                 } else if (c == '\'' || c == '"') {
186                                         q = c;
187                                         state = QUOTE;
188                                 } else {
189  set:
190                                         if ((size_t)(p - buf) >= mc)
191                                                 bb_error_msg_and_die("argument line too long");
192                                         *p++ = c;
193                                 }
194                         }
195                 }
196                 if (state == SPACE) {   /* word's delimiter or EOF detected */
197                         if (q) {
198                                 bb_error_msg_and_die("unmatched %s quote",
199                                         q == '\'' ? "single" : "double");
200                         }
201                         /* A full word is loaded */
202                         if (eof_str) {
203                                 eof_str_detected = (strcmp(s, eof_str) == 0);
204                         }
205                         if (!eof_str_detected) {
206                                 size_t length = (p - buf);
207                                 /* Dont xzalloc - it can be quite big */
208                                 cur = xmalloc(offsetof(xlist_t, xstr) + length);
209                                 cur->link = NULL;
210                                 cur->length = length;
211                                 memcpy(cur->xstr, s, length);
212                                 if (prev == NULL) {
213                                         list_arg = cur;
214                                 } else {
215                                         prev->link = cur;
216                                 }
217                                 prev = cur;
218                                 line_l += length;
219                                 if (line_l > mc) /* limit stop memory usage */
220                                         break;
221                         }
222                         s = NULL;
223                         state = NORM;
224                 }
225         }
226         return list_arg;
227 }
228 #else
229 /* The variant does not support single quotes, double quotes or backslash */
230 static xlist_t* process_stdin(xlist_t *list_arg,
231                 const char *eof_str, size_t mc, char *buf)
232 {
233         char eof_str_detected = 0;
234         char *s = NULL;         /* start of the word */
235         char *p = NULL;         /* pointer to end of the word */
236         size_t line_l = 0;      /* size of loaded args */
237         xlist_t *cur;
238         xlist_t *prev;
239
240         prev = cur = list_arg;
241         while (cur) {
242                 prev = cur;
243                 line_l += cur->length;
244                 cur = cur->link;
245         }
246
247         while (1) {
248                 int c = getchar();
249                 if (c == EOF) {
250                         if (s == NULL)
251                                 break;
252                 }
253                 if (eof_str_detected) { /* skip till EOF */
254                         continue;
255                 }
256                 if (c == EOF || ISSPACE(c)) {
257                         if (s == NULL)
258                                 continue;
259                         c = EOF;
260                 }
261                 if (s == NULL)
262                         s = p = buf;
263                 if ((size_t)(p - buf) >= mc)
264                         bb_error_msg_and_die("argument line too long");
265                 *p++ = (c == EOF ? '\0' : c);
266                 if (c == EOF) { /* word's delimiter or EOF detected */
267                         /* A full word is loaded */
268                         if (eof_str) {
269                                 eof_str_detected = (strcmp(s, eof_str) == 0);
270                         }
271                         if (!eof_str_detected) {
272                                 size_t length = (p - buf);
273                                 /* Dont xzalloc - it can be quite big */
274                                 cur = xmalloc(offsetof(xlist_t, xstr) + length);
275                                 cur->link = NULL;
276                                 cur->length = length;
277                                 memcpy(cur->xstr, s, length);
278                                 if (prev == NULL) {
279                                         list_arg = cur;
280                                 } else {
281                                         prev->link = cur;
282                                 }
283                                 prev = cur;
284                                 line_l += length;
285                                 if (line_l > mc) /* limit stop memory usage */
286                                         break;
287                         }
288                         s = NULL;
289                 }
290         }
291         return list_arg;
292 }
293 #endif /* FEATURE_XARGS_SUPPORT_QUOTES */
294
295
296 #if ENABLE_FEATURE_XARGS_SUPPORT_CONFIRMATION
297 /* Prompt the user for a response, and
298    if the user responds affirmatively, return true;
299    otherwise, return false. Uses "/dev/tty", not stdin. */
300 static int xargs_ask_confirmation(void)
301 {
302         FILE *tty_stream;
303         int c, savec;
304
305         tty_stream = xfopen_for_read(CURRENT_TTY);
306         fputs(" ?...", stderr);
307         fflush_all();
308         c = savec = getc(tty_stream);
309         while (c != EOF && c != '\n')
310                 c = getc(tty_stream);
311         fclose(tty_stream);
312         return (savec == 'y' || savec == 'Y');
313 }
314 #else
315 # define xargs_ask_confirmation() 1
316 #endif /* FEATURE_XARGS_SUPPORT_CONFIRMATION */
317
318 #if ENABLE_FEATURE_XARGS_SUPPORT_ZERO_TERM
319 static xlist_t* process0_stdin(xlist_t *list_arg,
320                 const char *eof_str UNUSED_PARAM, size_t mc, char *buf)
321 {
322         char *s = NULL;         /* start of the word */
323         char *p = NULL;         /* pointer to end of the word */
324         size_t line_l = 0;      /* size of loaded args */
325         xlist_t *cur;
326         xlist_t *prev;
327
328         prev = cur = list_arg;
329         while (cur) {
330                 prev = cur;
331                 line_l += cur->length;
332                 cur = cur->link;
333         }
334
335         while (1) {
336                 int c = getchar();
337                 if (c == EOF) {
338                         if (s == NULL)
339                                 break;
340                         c = '\0';
341                 }
342                 if (s == NULL)
343                         s = p = buf;
344                 if ((size_t)(p - buf) >= mc)
345                         bb_error_msg_and_die("argument line too long");
346                 *p++ = c;
347                 if (c == '\0') {   /* word's delimiter or EOF detected */
348                         /* A full word is loaded */
349                         size_t length = (p - buf);
350                         /* Dont xzalloc - it can be quite big */
351                         cur = xmalloc(offsetof(xlist_t, xstr) + length);
352                         cur->link = NULL;
353                         cur->length = length;
354                         memcpy(cur->xstr, s, length);
355                         if (prev == NULL) {
356                                 list_arg = cur;
357                         } else {
358                                 prev->link = cur;
359                         }
360                         prev = cur;
361                         line_l += length;
362                         if (line_l > mc) /* limit stop memory usage */
363                                 break;
364                         s = NULL;
365                 }
366         }
367         return list_arg;
368 }
369 #endif /* FEATURE_XARGS_SUPPORT_ZERO_TERM */
370
371 /* Correct regardless of combination of CONFIG_xxx */
372 enum {
373         OPTBIT_VERBOSE = 0,
374         OPTBIT_NO_EMPTY,
375         OPTBIT_UPTO_NUMBER,
376         OPTBIT_UPTO_SIZE,
377         OPTBIT_EOF_STRING,
378         OPTBIT_EOF_STRING1,
379         IF_FEATURE_XARGS_SUPPORT_CONFIRMATION(OPTBIT_INTERACTIVE,)
380         IF_FEATURE_XARGS_SUPPORT_TERMOPT(     OPTBIT_TERMINATE  ,)
381         IF_FEATURE_XARGS_SUPPORT_ZERO_TERM(   OPTBIT_ZEROTERM   ,)
382
383         OPT_VERBOSE     = 1 << OPTBIT_VERBOSE    ,
384         OPT_NO_EMPTY    = 1 << OPTBIT_NO_EMPTY   ,
385         OPT_UPTO_NUMBER = 1 << OPTBIT_UPTO_NUMBER,
386         OPT_UPTO_SIZE   = 1 << OPTBIT_UPTO_SIZE  ,
387         OPT_EOF_STRING  = 1 << OPTBIT_EOF_STRING , /* GNU: -e[<param>] */
388         OPT_EOF_STRING1 = 1 << OPTBIT_EOF_STRING1, /* SUS: -E<param> */
389         OPT_INTERACTIVE = IF_FEATURE_XARGS_SUPPORT_CONFIRMATION((1 << OPTBIT_INTERACTIVE)) + 0,
390         OPT_TERMINATE   = IF_FEATURE_XARGS_SUPPORT_TERMOPT(     (1 << OPTBIT_TERMINATE  )) + 0,
391         OPT_ZEROTERM    = IF_FEATURE_XARGS_SUPPORT_ZERO_TERM(   (1 << OPTBIT_ZEROTERM   )) + 0,
392 };
393 #define OPTION_STR "+trn:s:e::E:" \
394         IF_FEATURE_XARGS_SUPPORT_CONFIRMATION("p") \
395         IF_FEATURE_XARGS_SUPPORT_TERMOPT(     "x") \
396         IF_FEATURE_XARGS_SUPPORT_ZERO_TERM(   "0")
397
398 int xargs_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
399 int xargs_main(int argc, char **argv)
400 {
401         xlist_t *list = NULL;
402         int child_error = 0;
403         char *max_args;
404         char *max_chars;
405         char *buf;
406         int n_max_arg;
407         const char *eof_str = NULL;
408         unsigned opt;
409         size_t n_max_chars;
410 #if ENABLE_FEATURE_XARGS_SUPPORT_ZERO_TERM
411         xlist_t* (*read_args)(xlist_t*, const char*, size_t, char*) = process_stdin;
412 #else
413 #define read_args process_stdin
414 #endif
415
416         opt = getopt32(argv, OPTION_STR, &max_args, &max_chars, &eof_str, &eof_str);
417
418         /* -E ""? You may wonder why not just omit -E?
419          * This is used for portability:
420          * old xargs was using "_" as default for -E / -e */
421         if ((opt & OPT_EOF_STRING1) && eof_str[0] == '\0')
422                 eof_str = NULL;
423
424         if (opt & OPT_ZEROTERM)
425                 IF_FEATURE_XARGS_SUPPORT_ZERO_TERM(read_args = process0_stdin);
426
427         argv += optind;
428         argc -= optind;
429         if (!argv[0]) {
430                 /* default behavior is to echo all the filenames */
431                 *--argv = (char*)"echo";
432                 argc++;
433         }
434
435         /* The Open Group Base Specifications Issue 6:
436          * "The xargs utility shall limit the command line length such that
437          * when the command line is invoked, the combined argument
438          * and environment lists (see the exec family of functions
439          * in the System Interfaces volume of IEEE Std 1003.1-2001)
440          * shall not exceed {ARG_MAX}-2048 bytes".
441          */
442         n_max_chars = ARG_MAX; /* might be calling sysconf(_SC_ARG_MAX) */
443         if (n_max_chars < 4*1024); /* paranoia */
444                 n_max_chars = 4*1024;
445         n_max_chars -= 2048;
446         /* Sanity check for systems with huge ARG_MAX defines (e.g., Suns which
447          * have it at 1 meg).  Things will work fine with a large ARG_MAX
448          * but it will probably hurt the system more than it needs to;
449          * an array of this size is allocated.
450          */
451         if (n_max_chars > 20 * 1024)
452                 n_max_chars = 20 * 1024;
453
454         if (opt & OPT_UPTO_SIZE) {
455                 int i;
456                 size_t n_chars = 0;
457                 n_max_chars = xatoul_range(max_chars, 1, n_max_chars);
458                 for (i = 0; argv[i]; i++) {
459                         n_chars += strlen(argv[i]) + 1;
460                 }
461                 n_max_chars -= n_chars;
462                 if ((ssize_t)n_max_chars <= 0) {
463                         bb_error_msg_and_die("can't fit single argument within argument list size limit");
464                 }
465         }
466
467         buf = xmalloc(n_max_chars);
468
469         if (opt & OPT_UPTO_NUMBER) {
470                 n_max_arg = xatoul_range(max_args, 1, INT_MAX);
471         } else {
472                 n_max_arg = n_max_chars;
473         }
474
475         while ((list = read_args(list, eof_str, n_max_chars, buf)) != NULL
476          ||    !(opt & OPT_NO_EMPTY)
477         ) {
478                 char **args;
479                 xlist_t *cur;
480                 int i, n;
481                 size_t n_chars = 0;
482
483                 opt |= OPT_NO_EMPTY;
484                 n = 0;
485 #if ENABLE_FEATURE_XARGS_SUPPORT_TERMOPT
486                 for (cur = list; cur;) {
487                         n_chars += cur->length;
488                         n++;
489                         cur = cur->link;
490                         if (n_chars > n_max_chars || (n == n_max_arg && cur)) {
491                                 if (opt & OPT_TERMINATE)
492                                         bb_error_msg_and_die("argument list too long");
493                                 break;
494                         }
495                 }
496 #else
497                 for (cur = list; cur; cur = cur->link) {
498                         n_chars += cur->length;
499                         n++;
500                         if (n_chars > n_max_chars || n == n_max_arg) {
501                                 break;
502                         }
503                 }
504 #endif
505
506                 /* allocate pointers for execvp */
507                 args = xzalloc(sizeof(args[0]) * (argc + n + 1));
508
509                 /* store the command to be executed
510                  * (taken from the command line) */
511                 for (i = 0; argv[i]; i++)
512                         args[i] = argv[i];
513                 /* (taken from stdin) */
514                 for (cur = list; n; cur = cur->link) {
515                         args[i++] = cur->xstr;
516                         n--;
517                 }
518
519                 if (opt & (OPT_INTERACTIVE | OPT_VERBOSE)) {
520                         for (i = 0; args[i]; i++) {
521                                 if (i)
522                                         bb_putchar_stderr(' ');
523                                 fputs(args[i], stderr);
524                         }
525                         if (!(opt & OPT_INTERACTIVE))
526                                 bb_putchar_stderr('\n');
527                 }
528
529                 if (!(opt & OPT_INTERACTIVE) || xargs_ask_confirmation()) {
530                         child_error = xargs_exec(args);
531                 }
532
533                 /* clean up */
534                 for (i = argc; args[i]; i++) {
535                         cur = list;
536                         list = list->link;
537                         free(cur);
538                 }
539                 free(args);
540
541                 if (child_error > 0 && child_error != 123) {
542                         break;
543                 }
544         } /* while */
545
546         if (ENABLE_FEATURE_CLEAN_UP)
547                 free(buf);
548
549         return child_error;
550 }
551
552
553 #ifdef TEST
554
555 const char *applet_name = "debug stuff usage";
556
557 void bb_show_usage(void)
558 {
559         fprintf(stderr, "Usage: %s [-p] [-r] [-t] -[x] [-n max_arg] [-s max_chars]\n",
560                 applet_name);
561         exit(EXIT_FAILURE);
562 }
563
564 int main(int argc, char **argv)
565 {
566         return xargs_main(argc, argv);
567 }
568 #endif /* TEST */