hush: use NOFORK applets as appropriate. Net reduction of code size.
[platform/upstream/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 #include "busybox.h"
21
22 /* This is a NOEXEC applet. Be very careful! */
23
24
25 /* COMPAT:  SYSV version defaults size (and has a max value of) to 470.
26    We try to make it as large as possible. */
27 #if !defined(ARG_MAX) && defined(_SC_ARG_MAX)
28 #define ARG_MAX sysconf (_SC_ARG_MAX)
29 #endif
30 #ifndef ARG_MAX
31 #define ARG_MAX 470
32 #endif
33
34
35 #ifdef TEST
36 # ifndef ENABLE_FEATURE_XARGS_SUPPORT_CONFIRMATION
37 #  define ENABLE_FEATURE_XARGS_SUPPORT_CONFIRMATION 1
38 # endif
39 # ifndef ENABLE_FEATURE_XARGS_SUPPORT_QUOTES
40 #  define ENABLE_FEATURE_XARGS_SUPPORT_QUOTES 1
41 # endif
42 # ifndef ENABLE_FEATURE_XARGS_SUPPORT_TERMOPT
43 #  define ENABLE_FEATURE_XARGS_SUPPORT_TERMOPT 1
44 # endif
45 # ifndef ENABLE_FEATURE_XARGS_SUPPORT_ZERO_TERM
46 #  define ENABLE_FEATURE_XARGS_SUPPORT_ZERO_TERM 1
47 # endif
48 #endif
49
50 /*
51    This function has special algorithm.
52    Don't use fork and include to main!
53 */
54 static int xargs_exec(char **args)
55 {
56         int status;
57
58         status = spawn_and_wait(args);
59         if (status < 0) {
60                 bb_perror_msg("%s", args[0]);
61                 return errno == ENOENT ? 127 : 126;
62         }
63         if (status == 255) {
64                 bb_error_msg("%s: exited with status 255; aborting", args[0]);
65                 return 124;
66         }
67 /* Huh? I think we won't see this, ever. We don't wait with WUNTRACED!
68         if (WIFSTOPPED(status)) {
69                 bb_error_msg("%s: stopped by signal %d",
70                         args[0], WSTOPSIG(status));
71                 return 125;
72         }
73 */
74         if (status >= 1000) {
75                 bb_error_msg("%s: terminated by signal %d",
76                         args[0], status - 1000);
77                 return 125;
78         }
79         if (status)
80                 return 123;
81         return 0;
82 }
83
84
85 typedef struct xlist_t {
86         char *data;
87         size_t length;
88         struct xlist_t *link;
89 } xlist_t;
90
91 static smallint eof_stdin_detected;
92
93 #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
94 #define ISSPACE(c) (ISBLANK(c) || (c) == '\n' || (c) == '\r' \
95                     || (c) == '\f' || (c) == '\v')
96
97 #if ENABLE_FEATURE_XARGS_SUPPORT_QUOTES
98 static xlist_t *process_stdin(xlist_t *list_arg,
99         const char *eof_str, size_t mc, char *buf)
100 {
101 #define NORM      0
102 #define QUOTE     1
103 #define BACKSLASH 2
104 #define SPACE     4
105
106         char *s = NULL;         /* start word */
107         char *p = NULL;         /* pointer to end word */
108         char q = 0;             /* quote char */
109         char state = NORM;
110         char eof_str_detected = 0;
111         size_t line_l = 0;      /* size loaded args line */
112         int c;                  /* current char */
113         xlist_t *cur;
114         xlist_t *prev;
115
116         prev = cur = list_arg;
117         while (1) {
118                 if (!cur) break;
119                 prev = cur;
120                 line_l += cur->length;
121                 cur = cur->link;
122         }
123
124         while (!eof_stdin_detected) {
125                 c = getchar();
126                 if (c == EOF) {
127                         eof_stdin_detected = 1;
128                         if (s)
129                                 goto unexpected_eof;
130                         break;
131                 }
132                 if (eof_str_detected)
133                         continue;
134                 if (state == BACKSLASH) {
135                         state = NORM;
136                         goto set;
137                 } else if (state == QUOTE) {
138                         if (c == q) {
139                                 q = 0;
140                                 state = NORM;
141                         } else {
142                                 goto set;
143                         }
144                 } else { /* if (state == NORM) */
145                         if (ISSPACE(c)) {
146                                 if (s) {
147 unexpected_eof:
148                                         state = SPACE;
149                                         c = 0;
150                                         goto set;
151                                 }
152                         } else {
153                                 if (s == NULL)
154                                         s = p = buf;
155                                 if (c == '\\') {
156                                         state = BACKSLASH;
157                                 } else if (c == '\'' || c == '"') {
158                                         q = c;
159                                         state = QUOTE;
160                                 } else {
161 set:
162                                         if ((size_t)(p - buf) >= mc)
163                                                 bb_error_msg_and_die("argument line too long");
164                                         *p++ = c;
165                                 }
166                         }
167                 }
168                 if (state == SPACE) {   /* word's delimiter or EOF detected */
169                         if (q) {
170                                 bb_error_msg_and_die("unmatched %s quote",
171                                         q == '\'' ? "single" : "double");
172                         }
173                         /* word loaded */
174                         if (eof_str) {
175                                 eof_str_detected = (strcmp(s, eof_str) == 0);
176                         }
177                         if (!eof_str_detected) {
178                                 size_t length = (p - buf);
179 // TODO: smarter llist_t
180                                 cur = xzalloc(sizeof(xlist_t) + length);
181                                 cur->data = memcpy(cur + 1, s, length);
182                                 cur->length = length;
183                                 /*cur->link = NULL;*/
184                                 if (prev == NULL) {
185                                         list_arg = cur;
186                                 } else {
187                                         prev->link = cur;
188                                 }
189                                 prev = cur;
190                                 line_l += length;
191                                 if (line_l > mc) {
192                                         /* stop memory usage :-) */
193                                         break;
194                                 }
195                         }
196                         s = NULL;
197                         state = NORM;
198                 }
199         }
200         return list_arg;
201 }
202 #else
203 /* The variant does not support single quotes, double quotes or backslash */
204 static xlist_t *process_stdin(xlist_t *list_arg,
205                 const char *eof_str, size_t mc, char *buf)
206 {
207
208         int c;                  /* current char */
209         char eof_str_detected = 0;
210         char *s = NULL;         /* start word */
211         char *p = NULL;         /* pointer to end word */
212         size_t line_l = 0;      /* size loaded args line */
213         xlist_t *cur;
214         xlist_t *prev;
215
216         prev = cur = list_arg;
217         while (1) {
218                 if (!cur) break;
219                 prev = cur;
220                 line_l += cur->length;
221                 cur = cur->link;
222         }
223
224         while (!eof_stdin_detected) {
225                 c = getchar();
226                 if (c == EOF) {
227                         eof_stdin_detected = 1;
228                 }
229                 if (eof_str_detected)
230                         continue;
231                 if (c == EOF || ISSPACE(c)) {
232                         if (s == NULL)
233                                 continue;
234                         c = EOF;
235                 }
236                 if (s == NULL)
237                         s = p = buf;
238                 if ((p - buf) >= mc)
239                         bb_error_msg_and_die("argument line too long");
240                 *p++ = c == EOF ? 0 : c;
241                 if (c == EOF) { /* word's delimiter or EOF detected */
242                         /* word loaded */
243                         if (eof_str) {
244                                 eof_str_detected = (strcmp(s, eof_str) == 0);
245                         }
246                         if (!eof_str_detected) {
247                                 size_t length = (p - buf);
248
249                                 cur = xzalloc(sizeof(xlist_t) + length);
250 // TODO: smarter llist_t
251                                 cur->data = memcpy(cur + 1, s, length);
252                                 cur->length = length;
253                                 /*cur->link = NULL;*/
254                                 if (prev == NULL) {
255                                         list_arg = cur;
256                                 } else {
257                                         prev->link = cur;
258                                 }
259                                 prev = cur;
260                                 line_l += length;
261                                 if (line_l > mc) {
262                                         /* stop memory usage :-) */
263                                         break;
264                                 }
265                                 s = NULL;
266                         }
267                 }
268         }
269         return list_arg;
270 }
271 #endif /* FEATURE_XARGS_SUPPORT_QUOTES */
272
273
274 #if ENABLE_FEATURE_XARGS_SUPPORT_CONFIRMATION
275 /* Prompt the user for a response, and
276    if the user responds affirmatively, return true;
277    otherwise, return false. Uses "/dev/tty", not stdin. */
278 static int xargs_ask_confirmation(void)
279 {
280         FILE *tty_stream;
281         int c, savec;
282
283         tty_stream = xfopen(CURRENT_TTY, "r");
284         fputs(" ?...", stderr);
285         fflush(stderr);
286         c = savec = getc(tty_stream);
287         while (c != EOF && c != '\n')
288                 c = getc(tty_stream);
289         fclose(tty_stream);
290         return (savec == 'y' || savec == 'Y');
291 }
292 #else
293 # define xargs_ask_confirmation() 1
294 #endif /* FEATURE_XARGS_SUPPORT_CONFIRMATION */
295
296 #if ENABLE_FEATURE_XARGS_SUPPORT_ZERO_TERM
297 static xlist_t *process0_stdin(xlist_t *list_arg,
298                 const char *eof_str ATTRIBUTE_UNUSED, size_t mc, char *buf)
299 {
300         int c;                  /* current char */
301         char *s = NULL;         /* start word */
302         char *p = NULL;         /* pointer to end word */
303         size_t line_l = 0;      /* size loaded args line */
304         xlist_t *cur;
305         xlist_t *prev;
306
307         prev = cur = list_arg;
308         while (1) {
309                 if (!cur) break;
310                 prev = cur;
311                 line_l += cur->length;
312                 cur = cur->link;
313         }
314
315         while (!eof_stdin_detected) {
316                 c = getchar();
317                 if (c == EOF) {
318                         eof_stdin_detected = 1;
319                         if (s == NULL)
320                                 break;
321                         c = 0;
322                 }
323                 if (s == NULL)
324                         s = p = buf;
325                 if ((size_t)(p - buf) >= mc)
326                         bb_error_msg_and_die("argument line too long");
327                 *p++ = c;
328                 if (c == 0) {   /* word's delimiter or EOF detected */
329                         /* word loaded */
330                         size_t length = (p - buf);
331
332                         cur = xzalloc(sizeof(xlist_t) + length);
333 // TODO: smarter llist_t
334                         cur->data = memcpy(cur + 1, s, length);
335                         cur->length = length;
336                         /*cur->link = NULL;*/
337                         if (prev == NULL) {
338                                 list_arg = cur;
339                         } else {
340                                 prev->link = cur;
341                         }
342                         prev = cur;
343                         line_l += length;
344                         if (line_l > mc) {
345                                 /* stop memory usage :-) */
346                                 break;
347                         }
348                         s = NULL;
349                 }
350         }
351         return list_arg;
352 }
353 #endif /* FEATURE_XARGS_SUPPORT_ZERO_TERM */
354
355 /* Correct regardless of combination of CONFIG_xxx */
356 enum {
357         OPTBIT_VERBOSE = 0,
358         OPTBIT_NO_EMPTY,
359         OPTBIT_UPTO_NUMBER,
360         OPTBIT_UPTO_SIZE,
361         OPTBIT_EOF_STRING,
362         USE_FEATURE_XARGS_SUPPORT_CONFIRMATION(OPTBIT_INTERACTIVE,)
363         USE_FEATURE_XARGS_SUPPORT_TERMOPT(     OPTBIT_TERMINATE  ,)
364         USE_FEATURE_XARGS_SUPPORT_ZERO_TERM(   OPTBIT_ZEROTERM   ,)
365
366         OPT_VERBOSE     = 1<<OPTBIT_VERBOSE    ,
367         OPT_NO_EMPTY    = 1<<OPTBIT_NO_EMPTY   ,
368         OPT_UPTO_NUMBER = 1<<OPTBIT_UPTO_NUMBER,
369         OPT_UPTO_SIZE   = 1<<OPTBIT_UPTO_SIZE  ,
370         OPT_EOF_STRING  = 1<<OPTBIT_EOF_STRING ,
371         OPT_INTERACTIVE = USE_FEATURE_XARGS_SUPPORT_CONFIRMATION((1<<OPTBIT_INTERACTIVE)) + 0,
372         OPT_TERMINATE   = USE_FEATURE_XARGS_SUPPORT_TERMOPT(     (1<<OPTBIT_TERMINATE  )) + 0,
373         OPT_ZEROTERM    = USE_FEATURE_XARGS_SUPPORT_ZERO_TERM(   (1<<OPTBIT_ZEROTERM   )) + 0,
374 };
375 #define OPTION_STR "+trn:s:e::" \
376         USE_FEATURE_XARGS_SUPPORT_CONFIRMATION("p") \
377         USE_FEATURE_XARGS_SUPPORT_TERMOPT(     "x") \
378         USE_FEATURE_XARGS_SUPPORT_ZERO_TERM(   "0")
379
380 int xargs_main(int argc, char **argv);
381 int xargs_main(int argc, char **argv)
382 {
383         char **args;
384         int i, n;
385         xlist_t *list = NULL;
386         xlist_t *cur;
387         int child_error = 0;
388         char *max_args, *max_chars;
389         int n_max_arg;
390         size_t n_chars = 0;
391         long orig_arg_max;
392         const char *eof_str = "_";
393         unsigned opt;
394         size_t n_max_chars;
395 #if ENABLE_FEATURE_XARGS_SUPPORT_ZERO_TERM
396         xlist_t* (*read_args)(xlist_t*, const char*, size_t, char*) = process_stdin;
397 #else
398 #define read_args process_stdin
399 #endif
400
401         opt = getopt32(argc, argv, OPTION_STR, &max_args, &max_chars, &eof_str);
402
403         if (opt & OPT_ZEROTERM)
404                 USE_FEATURE_XARGS_SUPPORT_ZERO_TERM(read_args = process0_stdin);
405
406         argv += optind;
407         argc -= optind;
408         if (!argc) {
409                 /* default behavior is to echo all the filenames */
410                 *argv = (char*)"echo";
411                 argc++;
412         }
413
414         orig_arg_max = ARG_MAX;
415         if (orig_arg_max == -1)
416                 orig_arg_max = LONG_MAX;
417         orig_arg_max -= 2048;   /* POSIX.2 requires subtracting 2048 */
418
419         if (opt & OPT_UPTO_SIZE) {
420                 n_max_chars = xatoul_range(max_chars, 1, orig_arg_max);
421                 for (i = 0; i < argc; i++) {
422                         n_chars += strlen(*argv) + 1;
423                 }
424                 if (n_max_chars < n_chars) {
425                         bb_error_msg_and_die("cannot fit single argument within argument list size limit");
426                 }
427                 n_max_chars -= n_chars;
428         } else {
429                 /* Sanity check for systems with huge ARG_MAX defines (e.g., Suns which
430                    have it at 1 meg).  Things will work fine with a large ARG_MAX but it
431                    will probably hurt the system more than it needs to; an array of this
432                    size is allocated.  */
433                 if (orig_arg_max > 20 * 1024)
434                         orig_arg_max = 20 * 1024;
435                 n_max_chars = orig_arg_max;
436         }
437         max_chars = xmalloc(n_max_chars);
438
439         if (opt & OPT_UPTO_NUMBER) {
440                 n_max_arg = xatoul_range(max_args, 1, INT_MAX);
441         } else {
442                 n_max_arg = n_max_chars;
443         }
444
445         while ((list = read_args(list, eof_str, n_max_chars, max_chars)) != NULL ||
446                 !(opt & OPT_NO_EMPTY))
447         {
448                 opt |= OPT_NO_EMPTY;
449                 n = 0;
450                 n_chars = 0;
451 #if ENABLE_FEATURE_XARGS_SUPPORT_TERMOPT
452                 for (cur = list; cur;) {
453                         n_chars += cur->length;
454                         n++;
455                         cur = cur->link;
456                         if (n_chars > n_max_chars || (n == n_max_arg && cur)) {
457                                 if (opt & OPT_TERMINATE)
458                                         bb_error_msg_and_die("argument list too long");
459                                 break;
460                         }
461                 }
462 #else
463                 for (cur = list; cur; cur = cur->link) {
464                         n_chars += cur->length;
465                         n++;
466                         if (n_chars > n_max_chars || n == n_max_arg) {
467                                 break;
468                         }
469                 }
470 #endif /* FEATURE_XARGS_SUPPORT_TERMOPT */
471
472                 /* allocate pointers for execvp:
473                    argc*arg, n*arg from stdin, NULL */
474                 args = xzalloc((n + argc + 1) * sizeof(char *));
475
476                 /* store the command to be executed
477                    (taken from the command line) */
478                 for (i = 0; i < argc; i++)
479                         args[i] = argv[i];
480                 /* (taken from stdin) */
481                 for (cur = list; n; cur = cur->link) {
482                         args[i++] = cur->data;
483                         n--;
484                 }
485
486                 if (opt & (OPT_INTERACTIVE | OPT_VERBOSE)) {
487                         for (i = 0; args[i]; i++) {
488                                 if (i)
489                                         fputc(' ', stderr);
490                                 fputs(args[i], stderr);
491                         }
492                         if (!(opt & OPT_INTERACTIVE))
493                                 fputc('\n', stderr);
494                 }
495                 if (!(opt & OPT_INTERACTIVE) || xargs_ask_confirmation()) {
496                         child_error = xargs_exec(args);
497                 }
498
499                 /* clean up */
500                 for (i = argc; args[i]; i++) {
501                         cur = list;
502                         list = list->link;
503                         free(cur);
504                 }
505                 free(args);
506                 if (child_error > 0 && child_error != 123) {
507                         break;
508                 }
509         }
510         if (ENABLE_FEATURE_CLEAN_UP)
511                 free(max_chars);
512         return child_error;
513 }
514
515
516 #ifdef TEST
517
518 const char *applet_name = "debug stuff usage";
519
520 void bb_show_usage(void)
521 {
522         fprintf(stderr, "Usage: %s [-p] [-r] [-t] -[x] [-n max_arg] [-s max_chars]\n",
523                 applet_name);
524         exit(1);
525 }
526
527 int main(int argc, char **argv)
528 {
529         return xargs_main(argc, argv);
530 }
531 #endif /* TEST */