make a few struct bb_applet members conditional
[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 #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         cur = list_arg;
117         while (1) {
118                 prev = cur;
119                 if (!cur) break;
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
146                         if (ISSPACE(c)) {
147                                 if (s) {
148 unexpected_eof:
149                                         state = SPACE;
150                                         c = 0;
151                                         goto set;
152                                 }
153                         } else {
154                                 if (s == NULL)
155                                         s = p = buf;
156                                 if (c == '\\') {
157                                         state = BACKSLASH;
158                                 } else if (c == '\'' || c == '"') {
159                                         q = c;
160                                         state = QUOTE;
161                                 } else {
162 set:
163                                         if ((size_t)(p - buf) >= mc)
164                                                 bb_error_msg_and_die("argument line too long");
165                                         *p++ = c;
166                                 }
167                         }
168                 }
169                 if (state == SPACE) {   /* word's delimiter or EOF detected */
170                         if (q) {
171                                 bb_error_msg_and_die("unmatched %s quote",
172                                         q == '\'' ? "single" : "double");
173                         }
174                         /* word loaded */
175                         if (eof_str) {
176                                 eof_str_detected = (strcmp(s, eof_str) == 0);
177                         }
178                         if (!eof_str_detected) {
179                                 size_t length = (p - buf);
180
181                                 cur = xzalloc(sizeof(xlist_t) + length);
182                                 cur->data = memcpy(cur + 1, s, length);
183                                 cur->length = length;
184                                 /*cur->link = NULL;*/
185                                 if (prev == NULL) {
186                                         list_arg = cur;
187                                 } else {
188                                         prev->link = cur;
189                                 }
190                                 prev = cur;
191                                 line_l += length;
192                                 if (line_l > mc) {
193                                         /* stop memory usage :-) */
194                                         break;
195                                 }
196                         }
197                         s = NULL;
198                         state = NORM;
199                 }
200         }
201         return list_arg;
202 }
203 #else
204 /* The variant does not support single quotes, double quotes or backslash */
205 static xlist_t *process_stdin(xlist_t *list_arg,
206                 const char *eof_str, size_t mc, char *buf)
207 {
208
209         int c;                  /* current char */
210         char eof_str_detected = 0;
211         char *s = NULL;         /* start word */
212         char *p = NULL;         /* pointer to end word */
213         size_t line_l = 0;      /* size loaded args line */
214         xlist_t *cur;
215         xlist_t *prev;
216
217         cur = list_arg;
218         while (1) {
219                 prev = cur;
220                 if (!cur) break;
221                 line_l += cur->length;
222                 cur = cur->link;
223         }
224
225         while (!eof_stdin_detected) {
226                 c = getchar();
227                 if (c == EOF) {
228                         eof_stdin_detected = 1;
229                 }
230                 if (eof_str_detected)
231                         continue;
232                 if (c == EOF || ISSPACE(c)) {
233                         if (s == NULL)
234                                 continue;
235                         c = EOF;
236                 }
237                 if (s == NULL)
238                         s = p = buf;
239                 if ((p - buf) >= mc)
240                         bb_error_msg_and_die("argument line too long");
241                 *p++ = c == EOF ? 0 : c;
242                 if (c == EOF) { /* word's delimiter or EOF detected */
243                         /* word loaded */
244                         if (eof_str) {
245                                 eof_str_detected = (strcmp(s, eof_str) == 0);
246                         }
247                         if (!eof_str_detected) {
248                                 size_t length = (p - buf);
249
250                                 cur = xzalloc(sizeof(xlist_t) + length);
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         cur = list_arg;
308         while (1) {
309                 prev = cur;
310                 if (!cur) break;
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                         cur->data = memcpy(cur + 1, s, length);
334                         cur->length = length;
335                         /*cur->link = NULL;*/
336                         if (prev == NULL) {
337                                 list_arg = cur;
338                         } else {
339                                 prev->link = cur;
340                         }
341                         prev = cur;
342                         line_l += length;
343                         if (line_l > mc) {
344                                 /* stop memory usage :-) */
345                                 break;
346                         }
347                         s = NULL;
348                 }
349         }
350         return list_arg;
351 }
352 #endif /* FEATURE_XARGS_SUPPORT_ZERO_TERM */
353
354 /* Correct regardless of combination of CONFIG_xxx */
355 enum {
356         OPTBIT_VERBOSE = 0,
357         OPTBIT_NO_EMPTY,
358         OPTBIT_UPTO_NUMBER,
359         OPTBIT_UPTO_SIZE,
360         OPTBIT_EOF_STRING,
361         USE_FEATURE_XARGS_SUPPORT_CONFIRMATION(OPTBIT_INTERACTIVE,)
362         USE_FEATURE_XARGS_SUPPORT_TERMOPT(     OPTBIT_TERMINATE  ,)
363         USE_FEATURE_XARGS_SUPPORT_ZERO_TERM(   OPTBIT_ZEROTERM   ,)
364
365         OPT_VERBOSE     = 1<<OPTBIT_VERBOSE    ,
366         OPT_NO_EMPTY    = 1<<OPTBIT_NO_EMPTY   ,
367         OPT_UPTO_NUMBER = 1<<OPTBIT_UPTO_NUMBER,
368         OPT_UPTO_SIZE   = 1<<OPTBIT_UPTO_SIZE  ,
369         OPT_EOF_STRING  = 1<<OPTBIT_EOF_STRING ,
370         OPT_INTERACTIVE = USE_FEATURE_XARGS_SUPPORT_CONFIRMATION((1<<OPTBIT_INTERACTIVE)) + 0,
371         OPT_TERMINATE   = USE_FEATURE_XARGS_SUPPORT_TERMOPT(     (1<<OPTBIT_TERMINATE  )) + 0,
372         OPT_ZEROTERM    = USE_FEATURE_XARGS_SUPPORT_ZERO_TERM(   (1<<OPTBIT_ZEROTERM   )) + 0,
373 };
374 #define OPTION_STR "+trn:s:e::" \
375         USE_FEATURE_XARGS_SUPPORT_CONFIRMATION("p") \
376         USE_FEATURE_XARGS_SUPPORT_TERMOPT(     "x") \
377         USE_FEATURE_XARGS_SUPPORT_ZERO_TERM(   "0")
378
379 int xargs_main(int argc, char **argv);
380 int xargs_main(int argc, char **argv)
381 {
382         char **args;
383         int i, n;
384         xlist_t *list = NULL;
385         xlist_t *cur;
386         int child_error = 0;
387         char *max_args, *max_chars;
388         int n_max_arg;
389         size_t n_chars = 0;
390         long orig_arg_max;
391         const char *eof_str = "_";
392         unsigned opt;
393         size_t n_max_chars;
394 #if ENABLE_FEATURE_XARGS_SUPPORT_ZERO_TERM
395         xlist_t* (*read_args)(xlist_t*, const char*, size_t, char*) = process_stdin;
396 #else
397 #define read_args process_stdin
398 #endif
399
400         opt = getopt32(argc, argv, OPTION_STR, &max_args, &max_chars, &eof_str);
401
402         if (opt & OPT_ZEROTERM)
403                 USE_FEATURE_XARGS_SUPPORT_ZERO_TERM(read_args = process0_stdin);
404
405         argv += optind;
406         argc -= optind;
407         if (!argc) {
408                 /* default behavior is to echo all the filenames */
409                 *argv = (char*)"echo";
410                 argc++;
411         }
412
413         orig_arg_max = ARG_MAX;
414         if (orig_arg_max == -1)
415                 orig_arg_max = LONG_MAX;
416         orig_arg_max -= 2048;   /* POSIX.2 requires subtracting 2048 */
417
418         if (opt & OPT_UPTO_SIZE) {
419                 n_max_chars = xatoul_range(max_chars, 1, orig_arg_max);
420                 for (i = 0; i < argc; i++) {
421                         n_chars += strlen(*argv) + 1;
422                 }
423                 if (n_max_chars < n_chars) {
424                         bb_error_msg_and_die("cannot fit single argument within argument list size limit");
425                 }
426                 n_max_chars -= n_chars;
427         } else {
428                 /* Sanity check for systems with huge ARG_MAX defines (e.g., Suns which
429                    have it at 1 meg).  Things will work fine with a large ARG_MAX but it
430                    will probably hurt the system more than it needs to; an array of this
431                    size is allocated.  */
432                 if (orig_arg_max > 20 * 1024)
433                         orig_arg_max = 20 * 1024;
434                 n_max_chars = orig_arg_max;
435         }
436         max_chars = xmalloc(n_max_chars);
437
438         if (opt & OPT_UPTO_NUMBER) {
439                 n_max_arg = xatoul_range(max_args, 1, INT_MAX);
440         } else {
441                 n_max_arg = n_max_chars;
442         }
443
444         while ((list = read_args(list, eof_str, n_max_chars, max_chars)) != NULL ||
445                 !(opt & OPT_NO_EMPTY))
446         {
447                 opt |= OPT_NO_EMPTY;
448                 n = 0;
449                 n_chars = 0;
450 #if ENABLE_FEATURE_XARGS_SUPPORT_TERMOPT
451                 for (cur = list; cur;) {
452                         n_chars += cur->length;
453                         n++;
454                         cur = cur->link;
455                         if (n_chars > n_max_chars || (n == n_max_arg && cur)) {
456                                 if (opt & OPT_TERMINATE)
457                                         bb_error_msg_and_die("argument list too long");
458                                 break;
459                         }
460                 }
461 #else
462                 for (cur = list; cur; cur = cur->link) {
463                         n_chars += cur->length;
464                         n++;
465                         if (n_chars > n_max_chars || n == n_max_arg) {
466                                 break;
467                         }
468                 }
469 #endif /* FEATURE_XARGS_SUPPORT_TERMOPT */
470
471                 /* allocate pointers for execvp:
472                    argc*arg, n*arg from stdin, NULL */
473                 args = xzalloc((n + argc + 1) * sizeof(char *));
474
475                 /* store the command to be executed
476                    (taken from the command line) */
477                 for (i = 0; i < argc; i++)
478                         args[i] = argv[i];
479                 /* (taken from stdin) */
480                 for (cur = list; n; cur = cur->link) {
481                         args[i++] = cur->data;
482                         n--;
483                 }
484
485                 if (opt & (OPT_INTERACTIVE | OPT_VERBOSE)) {
486                         for (i = 0; args[i]; i++) {
487                                 if (i)
488                                         fputc(' ', stderr);
489                                 fputs(args[i], stderr);
490                         }
491                         if (!(opt & OPT_INTERACTIVE))
492                                 fputc('\n', stderr);
493                 }
494                 if (!(opt & OPT_INTERACTIVE) || xargs_ask_confirmation()) {
495                         child_error = xargs_exec(args);
496                 }
497
498                 /* clean up */
499                 for (i = argc; args[i]; i++) {
500                         cur = list;
501                         list = list->link;
502                         free(cur);
503                 }
504                 free(args);
505                 if (child_error > 0 && child_error != 123) {
506                         break;
507                 }
508         }
509         if (ENABLE_FEATURE_CLEAN_UP)
510                 free(max_chars);
511         return child_error;
512 }
513
514
515 #ifdef TEST
516
517 const char *applet_name = "debug stuff usage";
518
519 void bb_show_usage(void)
520 {
521         fprintf(stderr, "Usage: %s [-p] [-r] [-t] -[x] [-n max_arg] [-s max_chars]\n",
522                 applet_name);
523         exit(1);
524 }
525
526 int main(int argc, char **argv)
527 {
528         return xargs_main(argc, argv);
529 }
530 #endif /* TEST */