Add a comment with link to the SUSv3 standard for xargs
[oweals/busybox.git] / findutils / xargs.c
1 /*
2  * Mini xargs implementation for busybox
3  * Options are supported: "-prtx -n max_arg -s max_chars -e[ouf_str]"
4  *
5  * (C) 2002,2003 by Vladimir Oleynik <dzo@simtreas.ru>
6  *
7  * Special thanks
8  * - Mark Whitley and Glenn McGrath for stimul to rewrote :)
9  * - Mike Rendell <michael@cs.mun.ca>
10  * and David MacKenzie <djm@gnu.ai.mit.edu>.
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20  * General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25  *
26  * xargs is described in the Single Unix Specification v3 at
27  * http://www.opengroup.org/onlinepubs/007904975/utilities/xargs.html
28  *
29  */
30
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <unistd.h>
35 #include <getopt.h>
36 #include <errno.h>
37 #include <fcntl.h>
38 #include <sys/types.h>
39 #include <sys/wait.h>
40 #include "busybox.h"
41
42 /* COMPAT:  SYSV version defaults size (and has a max value of) to 470.
43    We try to make it as large as possible. */
44 #if !defined(ARG_MAX) && defined(_SC_ARG_MAX)
45 #define ARG_MAX sysconf (_SC_ARG_MAX)
46 #endif
47 #ifndef ARG_MAX
48 #define ARG_MAX 470
49 #endif
50
51
52 #ifdef TEST
53 # ifndef CONFIG_FEATURE_XARGS_SUPPORT_CONFIRMATION
54 #  define CONFIG_FEATURE_XARGS_SUPPORT_CONFIRMATION
55 # endif
56 # ifndef CONFIG_FEATURE_XARGS_SUPPORT_QUOTES
57 #  define CONFIG_FEATURE_XARGS_SUPPORT_QUOTES
58 # endif
59 # ifndef CONFIG_FEATURE_XARGS_SUPPORT_TERMOPT
60 #  define CONFIG_FEATURE_XARGS_SUPPORT_TERMOPT
61 # endif
62 # ifndef CONFIG_FEATURE_XARGS_SUPPORT_ZERO_TERM
63 #  define CONFIG_FEATURE_XARGS_SUPPORT_ZERO_TERM
64 # endif
65 #endif
66
67 /*
68    This function have special algorithm.
69    Don`t use fork and include to main!
70 */
71 static int xargs_exec(char *const *args)
72 {
73         pid_t p;
74         volatile int exec_errno = 0;    /* shared vfork stack */
75
76         if ((p = vfork()) >= 0) {
77                 if (p == 0) {
78                         /* vfork -- child */
79                         execvp(args[0], args);
80                         exec_errno = errno;     /* set error to shared stack */
81                         _exit(1);
82                 } else {
83                         /* vfork -- parent */
84                         int status;
85
86                         while (wait(&status) == (pid_t) - 1)
87                                 if (errno != EINTR)
88                                         break;
89                         if (exec_errno) {
90                                 errno = exec_errno;
91                                 bb_perror_msg("%s", args[0]);
92                                 return exec_errno == ENOENT ? 127 : 126;
93                         } else {
94                                 if (WEXITSTATUS(status) == 255) {
95                                         bb_error_msg("%s: exited with status 255; aborting",
96                                                                  args[0]);
97                                         return 124;
98                                 }
99                                 if (WIFSTOPPED(status)) {
100                                         bb_error_msg("%s: stopped by signal %d", args[0],
101                                                                  WSTOPSIG(status));
102                                         return 125;
103                                 }
104                                 if (WIFSIGNALED(status)) {
105                                         bb_error_msg("%s: terminated by signal %d", args[0],
106                                                                  WTERMSIG(status));
107                                         return 125;
108                                 }
109                                 if (WEXITSTATUS(status) != 0)
110                                         return 123;
111                                 return 0;
112                         }
113                 }
114         } else {
115                 bb_perror_msg_and_die("vfork");
116         }
117 }
118
119
120 typedef struct xlist_s {
121         char *data;
122         size_t lenght;
123         struct xlist_s *link;
124 } xlist_t;
125
126 static int eof_stdin_detected;
127
128 #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
129 #define ISSPACE(c) (ISBLANK (c) || (c) == '\n' || (c) == '\r' \
130                     || (c) == '\f' || (c) == '\v')
131
132 #ifdef CONFIG_FEATURE_XARGS_SUPPORT_QUOTES
133 static xlist_t *process_stdin(xlist_t * list_arg, const char *eof_str,
134                                                           size_t mc, char *buf)
135 {
136 #define NORM      0
137 #define QUOTE     1
138 #define BACKSLASH 2
139 #define SPACE     4
140
141         char *s = NULL;         /* start word */
142         char *p = NULL;         /* pointer to end word */
143         char q = 0;                     /* quote char */
144         char state = NORM;
145         char eof_str_detected = 0;
146         size_t line_l = 0;      /* size loaded args line */
147         int c;                          /* current char */
148         xlist_t *cur;
149         xlist_t *prev;
150
151         for (prev = cur = list_arg; cur; cur = cur->link) {
152                 line_l += cur->lenght;  /* previous allocated */
153                 if (prev != cur)
154                         prev = prev->link;
155         }
156
157         while (!eof_stdin_detected) {
158                 c = getchar();
159                 if (c == EOF) {
160                         eof_stdin_detected++;
161                         if (s)
162                                 goto unexpected_eof;
163                         break;
164                 }
165                 if (eof_str_detected)
166                         continue;
167                 if (state == BACKSLASH) {
168                         state = NORM;
169                         goto set;
170                 } else if (state == QUOTE) {
171                         if (c == q) {
172                                 q = 0;
173                                 state = NORM;
174                         } else {
175                                 goto set;
176                         }
177                 } else {                /* if(state == NORM) */
178
179                         if (ISSPACE(c)) {
180                                 if (s) {
181                                   unexpected_eof:
182                                         state = SPACE;
183                                         c = 0;
184                                         goto set;
185                                 }
186                         } else {
187                                 if (s == NULL)
188                                         s = p = buf;
189                                 if (c == '\\') {
190                                         state = BACKSLASH;
191                                 } else if (c == '\'' || c == '"') {
192                                         q = c;
193                                         state = QUOTE;
194                                 } else {
195                                   set:
196                                         if ((p - buf) >= mc)
197                                                 bb_error_msg_and_die("argument line too long");
198                                         *p++ = c;
199                                 }
200                         }
201                 }
202                 if (state == SPACE) {   /* word's delimiter or EOF detected */
203                         if (q)
204                                 bb_error_msg_and_die("unmatched %s quote",
205                                                                          q == '\'' ? "single" : "double");
206                         /* word loaded */
207                         if (eof_str) {
208                                 eof_str_detected = strcmp(s, eof_str) == 0;
209                         }
210                         if (!eof_str_detected) {
211                                 size_t lenght = (p - buf);
212
213                                 cur = xmalloc(sizeof(xlist_t) + lenght);
214                                 cur->data = memcpy(cur + 1, s, lenght);
215                                 cur->lenght = lenght;
216                                 cur->link = NULL;
217                                 if (prev == NULL) {
218                                         list_arg = cur;
219                                 } else {
220                                         prev->link = cur;
221                                 }
222                                 prev = cur;
223                                 line_l += lenght;
224                                 if (line_l > mc) {
225                                         /* stop memory usage :-) */
226                                         break;
227                                 }
228                         }
229                         s = NULL;
230                         state = NORM;
231                 }
232         }
233         return list_arg;
234 }
235 #else
236 /* The variant is unsupport single, double quotes and backslash */
237 static xlist_t *process_stdin(xlist_t * list_arg, const char *eof_str,
238                                                           size_t mc, char *buf)
239 {
240
241         int c;                          /* current char */
242         int eof_str_detected = 0;
243         char *s = NULL;         /* start word */
244         char *p = NULL;         /* pointer to end word */
245         size_t line_l = 0;      /* size loaded args line */
246         xlist_t *cur;
247         xlist_t *prev;
248
249         for (prev = cur = list_arg; cur; cur = cur->link) {
250                 line_l += cur->lenght;  /* previous allocated */
251                 if (prev != cur)
252                         prev = prev->link;
253         }
254
255         while (!eof_stdin_detected) {
256                 c = getchar();
257                 if (c == EOF) {
258                         eof_stdin_detected++;
259                 }
260                 if (eof_str_detected)
261                         continue;
262                 if (c == EOF || ISSPACE(c)) {
263                         if (s == NULL)
264                                 continue;
265                         c = EOF;
266                 }
267                 if (s == NULL)
268                         s = p = buf;
269                 if ((p - buf) >= mc)
270                         bb_error_msg_and_die("argument line too long");
271                 *p++ = c == EOF ? 0 : c;
272                 if (c == EOF) { /* word's delimiter or EOF detected */
273                         /* word loaded */
274                         if (eof_str) {
275                                 eof_str_detected = strcmp(s, eof_str) == 0;
276                         }
277                         if (!eof_str_detected) {
278                                 size_t lenght = (p - buf);
279
280                                 cur = xmalloc(sizeof(xlist_t) + lenght);
281                                 cur->data = memcpy(cur + 1, s, lenght);
282                                 cur->lenght = lenght;
283                                 cur->link = NULL;
284                                 if (prev == NULL) {
285                                         list_arg = cur;
286                                 } else {
287                                         prev->link = cur;
288                                 }
289                                 prev = cur;
290                                 line_l += lenght;
291                                 if (line_l > mc) {
292                                         /* stop memory usage :-) */
293                                         break;
294                                 }
295                                 s = NULL;
296                         }
297                 }
298         }
299         return list_arg;
300 }
301 #endif                                                  /* CONFIG_FEATURE_XARGS_SUPPORT_QUOTES */
302
303
304 #ifdef CONFIG_FEATURE_XARGS_SUPPORT_CONFIRMATION
305 /* Prompt the user for a response, and
306    if the user responds affirmatively, return true;
307    otherwise, return false. Used "/dev/tty", not stdin. */
308 static int xargs_ask_confirmation(void)
309 {
310         static FILE *tty_stream;
311         int c, savec;
312
313         if (!tty_stream) {
314                 tty_stream = fopen("/dev/tty", "r");
315                 if (!tty_stream)
316                         bb_perror_msg_and_die("/dev/tty");
317                 /* pranoidal security by vodz */
318                 fcntl(fileno(tty_stream), F_SETFD, FD_CLOEXEC);
319         }
320         fputs(" ?...", stderr);
321         fflush(stderr);
322         c = savec = getc(tty_stream);
323         while (c != EOF && c != '\n')
324                 c = getc(tty_stream);
325         if (savec == 'y' || savec == 'Y')
326                 return 1;
327         return 0;
328 }
329
330 # define OPT_INC_P 1
331 #else
332 # define OPT_INC_P 0
333 # define xargs_ask_confirmation() 1
334 #endif                                                  /* CONFIG_FEATURE_XARGS_SUPPORT_CONFIRMATION */
335
336 #ifdef CONFIG_FEATURE_XARGS_SUPPORT_TERMOPT
337 # define OPT_INC_X 1
338 #else
339 # define OPT_INC_X 0
340 #endif
341
342 #ifdef CONFIG_FEATURE_XARGS_SUPPORT_ZERO_TERM
343 static xlist_t *process0_stdin(xlist_t * list_arg, const char *eof_str,
344                                                            size_t mc, char *buf)
345 {
346         int c;                          /* current char */
347         char *s = NULL;         /* start word */
348         char *p = NULL;         /* pointer to end word */
349         size_t line_l = 0;      /* size loaded args line */
350         xlist_t *cur;
351         xlist_t *prev;
352
353         for (prev = cur = list_arg; cur; cur = cur->link) {
354                 line_l += cur->lenght;  /* previous allocated */
355                 if (prev != cur)
356                         prev = prev->link;
357         }
358
359         while (!eof_stdin_detected) {
360                 c = getchar();
361                 if (c == EOF) {
362                         eof_stdin_detected++;
363                         if (s == NULL)
364                                 break;
365                         c = 0;
366                 }
367                 if (s == NULL)
368                         s = p = buf;
369                 if ((p - buf) >= mc)
370                         bb_error_msg_and_die("argument line too long");
371                 *p++ = c;
372                 if (c == 0) {   /* word's delimiter or EOF detected */
373                         /* word loaded */
374                         size_t lenght = (p - buf);
375
376                         cur = xmalloc(sizeof(xlist_t) + lenght);
377                         cur->data = memcpy(cur + 1, s, lenght);
378                         cur->lenght = lenght;
379                         cur->link = NULL;
380                         if (prev == NULL) {
381                                 list_arg = cur;
382                         } else {
383                                 prev->link = cur;
384                         }
385                         prev = cur;
386                         line_l += lenght;
387                         if (line_l > mc) {
388                                 /* stop memory usage :-) */
389                                 break;
390                         }
391                         s = NULL;
392                 }
393         }
394         return list_arg;
395 }
396
397 # define READ_ARGS(l, e, nmc, mc) (*read_args)(l, e, nmc, mc)
398 # define OPT_INC_0 1    /* future use */
399 #else
400 # define OPT_INC_0 0    /* future use */
401 # define READ_ARGS(l, e, nmc, mc) process_stdin(l, e, nmc, mc)
402 #endif                                                  /* CONFIG_FEATURE_XARGS_SUPPORT_ZERO_TERM */
403
404
405 #define OPT_VERBOSE     (1<<0)
406 #define OPT_NO_EMPTY    (1<<1)
407 #define OPT_UPTO_NUMBER (1<<2)
408 #define OPT_UPTO_SIZE   (1<<3)
409 #define OPT_EOF_STRING  (1<<4)
410 #ifdef CONFIG_FEATURE_XARGS_SUPPORT_CONFIRMATION
411 #define OPT_INTERACTIVE (1<<5)
412 #else
413 #define OPT_INTERACTIVE (0)     /* require for algorithm &| */
414 #endif
415 #define OPT_TERMINATE   (1<<(5+OPT_INC_P))
416 #define OPT_ZEROTERM    (1<<(5+OPT_INC_P+OPT_INC_X))
417 /* next future
418 #define OPT_NEXT_OTHER  (1<<(5+OPT_INC_P+OPT_INC_X+OPT_INC_0))
419 */
420
421 int xargs_main(int argc, char **argv)
422 {
423         char **args;
424         int i, a, n;
425         xlist_t *list = NULL;
426         xlist_t *cur;
427         int child_error = 0;
428         char *max_args, *max_chars;
429         int n_max_arg;
430         size_t n_chars = 0;
431         long orig_arg_max;
432         const char *eof_str = "_";
433         unsigned long opt;
434         size_t n_max_chars;
435
436 #ifdef CONFIG_FEATURE_XARGS_SUPPORT_ZERO_TERM
437         xlist_t *(*read_args) (xlist_t *, const char *, size_t, char *) =
438                 process_stdin;
439 #endif
440
441 #ifdef CONFIG_FEATURE_XARGS_SUPPORT_CONFIRMATION
442         bb_opt_complementaly = "pt";
443 #endif
444
445         opt = bb_getopt_ulflags(argc, argv, "+trn:s:e::"
446 #ifdef CONFIG_FEATURE_XARGS_SUPPORT_CONFIRMATION
447                                                         "p"
448 #endif
449 #ifdef CONFIG_FEATURE_XARGS_SUPPORT_TERMOPT
450                                                         "x"
451 #endif
452 #ifdef CONFIG_FEATURE_XARGS_SUPPORT_ZERO_TERM
453                                                         "0"
454 #endif
455                                                         , &max_args, &max_chars, &eof_str);
456
457         a = argc - optind;
458         argv += optind;
459         if (a == 0) {
460                 /* default behavior is to echo all the filenames */
461                 *argv = "echo";
462                 a++;
463         }
464
465         orig_arg_max = ARG_MAX;
466         if (orig_arg_max == -1)
467                 orig_arg_max = LONG_MAX;
468         orig_arg_max -= 2048;   /* POSIX.2 requires subtracting 2048.  */
469         if ((opt & OPT_UPTO_SIZE)) {
470                 n_max_chars = bb_xgetularg10_bnd(max_chars, 1, orig_arg_max);
471                 for (i = 0; i < a; i++) {
472                         n_chars += strlen(*argv) + 1;
473                 }
474                 if (n_max_chars < n_chars) {
475                         bb_error_msg_and_die
476                                 ("can not fit single argument within argument list size limit");
477                 }
478                 n_max_chars -= n_chars;
479         } else {
480                 /* Sanity check for systems with huge ARG_MAX defines (e.g., Suns which
481                    have it at 1 meg).  Things will work fine with a large ARG_MAX but it
482                    will probably hurt the system more than it needs to; an array of this
483                    size is allocated.  */
484                 if (orig_arg_max > 20 * 1024)
485                         orig_arg_max = 20 * 1024;
486                 n_max_chars = orig_arg_max;
487         }
488         max_chars = xmalloc(n_max_chars);
489
490         if ((opt & OPT_UPTO_NUMBER)) {
491                 n_max_arg = bb_xgetularg10_bnd(max_args, 1, INT_MAX);
492         } else {
493                 n_max_arg = n_max_chars;
494         }
495
496 #ifdef CONFIG_FEATURE_XARGS_SUPPORT_ZERO_TERM
497         if (opt & OPT_ZEROTERM)
498                 read_args = process0_stdin;
499 #endif
500
501         while ((list = READ_ARGS(list, eof_str, n_max_chars, max_chars)) != NULL
502                    || (opt & OPT_NO_EMPTY) == 0) {
503                 opt |= OPT_NO_EMPTY;
504                 n = 0;
505                 n_chars = 0;
506 #ifdef CONFIG_FEATURE_XARGS_SUPPORT_TERMOPT
507                 for (cur = list; cur;) {
508                         n_chars += cur->lenght;
509                         n++;
510                         cur = cur->link;
511                         if (n_chars > n_max_chars || (n == n_max_arg && cur)) {
512                                 if (opt & OPT_TERMINATE)
513                                         bb_error_msg_and_die("argument list too long");
514                                 break;
515                         }
516                 }
517 #else
518                 for (cur = list; cur; cur = cur->link) {
519                         n_chars += cur->lenght;
520                         n++;
521                         if (n_chars > n_max_chars || n == n_max_arg) {
522                                 break;
523                         }
524                 }
525 #endif                                                  /* CONFIG_FEATURE_XARGS_SUPPORT_TERMOPT */
526
527                 /* allocating pointers for execvp:
528                    a*arg, n*arg from stdin, NULL */
529                 args = xcalloc(n + a + 1, sizeof(char *));
530
531                 /* Store the command to be executed
532                    (taken from the command line) */
533                 for (i = 0; i < a; i++)
534                         args[i] = argv[i];
535                 /* (taken from stdin) */
536                 for (cur = list; n; cur = cur->link) {
537                         args[i++] = cur->data;
538                         n--;
539                 }
540
541                 if ((opt & (OPT_INTERACTIVE | OPT_VERBOSE))) {
542                         for (i = 0; args[i]; i++) {
543                                 if (i)
544                                         fputc(' ', stderr);
545                                 fputs(args[i], stderr);
546                         }
547                         if ((opt & OPT_INTERACTIVE) == 0)
548                                 fputc('\n', stderr);
549                 }
550                 if ((opt & OPT_INTERACTIVE) == 0 || xargs_ask_confirmation() != 0) {
551                         child_error = xargs_exec(args);
552                 }
553
554                 /* clean up */
555                 for (i = a; args[i]; i++) {
556                         cur = list;
557                         list = list->link;
558                         free(cur);
559                 }
560                 free(args);
561                 if (child_error > 0 && child_error != 123) {
562                         break;
563                 }
564         }
565 #ifdef CONFIG_FEATURE_CLEAN_UP
566         free(max_chars);
567 #endif
568         return child_error;
569 }
570
571
572 #ifdef TEST
573
574 const char *bb_applet_name = "debug stuff usage";
575
576 void bb_show_usage(void)
577 {
578         fprintf(stderr,
579                         "Usage: %s [-p] [-r] [-t] -[x] [-n max_arg] [-s max_chars]\n",
580                         bb_applet_name);
581         exit(1);
582 }
583
584 int main(int argc, char **argv)
585 {
586         return xargs_main(argc, argv);
587 }
588 #endif                                                  /* TEST */