Initial import from FreeBSD RELENG_4:
[games.git] / usr.bin / xargs / xargs.c
1 /*-
2  * Copyright (c) 1990, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * John B. Roll Jr.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by the University of
19  *      California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  * $xMach: xargs.c,v 1.6 2002/02/23 05:27:47 tim Exp $
37  */
38
39 #ifndef lint
40 static const char copyright[] =
41 "@(#) Copyright (c) 1990, 1993\n\
42         The Regents of the University of California.  All rights reserved.\n";
43 #endif /* not lint */
44
45 #if 0
46 #ifndef lint
47 static char sccsid[] = "@(#)xargs.c     8.1 (Berkeley) 6/6/93";
48 #endif /* not lint */
49 #endif
50
51 #include <sys/cdefs.h>
52 __FBSDID("$FreeBSD: src/usr.bin/xargs/xargs.c,v 1.9.2.6 2003/06/01 21:40:35 mux Exp $");
53
54 #include <sys/types.h>
55 #include <sys/wait.h>
56
57 #include <err.h>
58 #include <errno.h>
59 #include <fcntl.h>
60 #ifndef BOOTSTRAPPING
61 #include <langinfo.h>
62 #endif
63 #include <locale.h>
64 #include <paths.h>
65 #include <regex.h>
66 #include <stdio.h>
67 #include <stdlib.h>
68 #include <string.h>
69 #include <unistd.h>
70
71 #include "pathnames.h"
72
73 static void     parse_input(int, char *[]);
74 static void     prerun(int, char *[]);
75 static int      prompt(void);
76 static void     run(char **);
77 static void     usage(void);
78 void            strnsubst(char **, const char *, const char *, size_t);
79
80 static char echo[] = _PATH_ECHO;
81 static char **av, **bxp, **ep, **exp, **xp;
82 static char *argp, *bbp, *ebp, *inpline, *p, *replstr;
83 static const char *eofstr;
84 static int count, insingle, indouble, oflag, pflag, tflag, Rflag, rval, zflag;
85 static int cnt, Iflag, jfound, Lflag, wasquoted, xflag;
86
87 extern char **environ;
88
89 int
90 main(int argc, char *argv[])
91 {
92         long arg_max;
93         int ch, Jflag, nargs, nflag, nline;
94         size_t linelen;
95
96         inpline = replstr = NULL;
97         ep = environ;
98         eofstr = "";
99         Jflag = nflag = 0;
100
101         (void)setlocale(LC_MESSAGES, "");
102
103         /*
104          * POSIX.2 limits the exec line length to ARG_MAX - 2K.  Running that
105          * caused some E2BIG errors, so it was changed to ARG_MAX - 4K.  Given
106          * that the smallest argument is 2 bytes in length, this means that
107          * the number of arguments is limited to:
108          *
109          *       (ARG_MAX - 4K - LENGTH(utility + arguments)) / 2.
110          *
111          * We arbitrarily limit the number of arguments to 5000.  This is
112          * allowed by POSIX.2 as long as the resulting minimum exec line is
113          * at least LINE_MAX.  Realloc'ing as necessary is possible, but
114          * probably not worthwhile.
115          */
116         nargs = 5000;
117         if ((arg_max = sysconf(_SC_ARG_MAX)) == -1)
118                 errx(1, "sysconf(_SC_ARG_MAX) failed");
119         nline = arg_max - 4 * 1024;
120         while (*ep != NULL) {
121                 /* 1 byte for each '\0' */
122                 nline -= strlen(*ep++) + 1 + sizeof(*ep);
123         }
124         while ((ch = getopt(argc, argv, "0E:I:J:L:n:opR:s:tx")) != -1)
125                 switch(ch) {
126                 case 'E':
127                         eofstr = optarg;
128                         break;
129                 case 'I':
130                         Jflag = 0;
131                         Iflag = 1;
132                         Lflag = 1;
133                         replstr = optarg;
134                         break;
135                 case 'J':
136                         Iflag = 0;
137                         Jflag = 1;
138                         replstr = optarg;
139                         break;
140                 case 'L':
141                         Lflag = atoi(optarg);
142                         break;
143                 case 'n':
144                         nflag = 1;
145                         if ((nargs = atoi(optarg)) <= 0)
146                                 errx(1, "illegal argument count");
147                         break;
148                 case 'o':
149                         oflag = 1;
150                         break;
151                 case 'p':
152                         pflag = 1;
153                         break;
154                 case 'R':
155                         if ((Rflag = atoi(optarg)) <= 0)
156                                 errx(1, "illegal number of replacements");
157                         break;
158                 case 's':
159                         nline = atoi(optarg);
160                         break;
161                 case 't':
162                         tflag = 1;
163                         break;
164                 case 'x':
165                         xflag = 1;
166                         break;
167                 case '0':
168                         zflag = 1;
169                         break;
170                 case '?':
171                 default:
172                         usage();
173         }
174         argc -= optind;
175         argv += optind;
176
177         if (!Iflag && Rflag)
178                 usage();
179         if (Iflag && !Rflag)
180                 Rflag = 5;
181         if (xflag && !nflag)
182                 usage();
183         if (Iflag || Lflag)
184                 xflag = 1;
185         if (replstr != NULL && *replstr == '\0')
186                 errx(1, "replstr may not be empty");
187
188         /*
189          * Allocate pointers for the utility name, the utility arguments,
190          * the maximum arguments to be read from stdin and the trailing
191          * NULL.
192          */
193         linelen = 1 + argc + nargs + 1;
194         if ((av = bxp = malloc(linelen * sizeof(char **))) == NULL)
195                 errx(1, "malloc failed");
196
197         /*
198          * Use the user's name for the utility as argv[0], just like the
199          * shell.  Echo is the default.  Set up pointers for the user's
200          * arguments.
201          */
202         if (*argv == NULL)
203                 cnt = strlen(*bxp++ = echo);
204         else {
205                 do {
206                         if (Jflag && strcmp(*argv, replstr) == 0) {
207                                 char **avj;
208                                 jfound = 1;
209                                 argv++;
210                                 for (avj = argv; *avj; avj++)
211                                         cnt += strlen(*avj) + 1;
212                                 break;
213                         }
214                         cnt += strlen(*bxp++ = *argv) + 1;
215                 } while (*++argv != NULL);
216         }
217
218         /*
219          * Set up begin/end/traversing pointers into the array.  The -n
220          * count doesn't include the trailing NULL pointer, so the malloc
221          * added in an extra slot.
222          */
223         exp = (xp = bxp) + nargs;
224
225         /*
226          * Allocate buffer space for the arguments read from stdin and the
227          * trailing NULL.  Buffer space is defined as the default or specified
228          * space, minus the length of the utility name and arguments.  Set up
229          * begin/end/traversing pointers into the array.  The -s count does
230          * include the trailing NULL, so the malloc didn't add in an extra
231          * slot.
232          */
233         nline -= cnt;
234         if (nline <= 0)
235                 errx(1, "insufficient space for command");
236
237         if ((bbp = malloc((size_t)(nline + 1))) == NULL)
238                 errx(1, "malloc failed");
239         ebp = (argp = p = bbp) + nline - 1;
240         for (;;)
241                 parse_input(argc, argv);
242 }
243
244 static void
245 parse_input(int argc, char *argv[])
246 {
247         int ch, foundeof;
248         char **avj;
249
250         foundeof = 0;
251
252         switch(ch = getchar()) {
253         case EOF:
254                 /* No arguments since last exec. */
255                 if (p == bbp)
256                         exit(rval);
257                 goto arg1;
258         case ' ':
259         case '\t':
260                 /* Quotes escape tabs and spaces. */
261                 if (insingle || indouble || zflag)
262                         goto addch;
263                 goto arg2;
264         case '\0':
265                 if (zflag)
266                         goto arg2;
267                 goto addch;
268         case '\n':
269                 count++;
270                 if (zflag)
271                         goto addch;
272
273                 /* Quotes do not escape newlines. */
274 arg1:           if (insingle || indouble)
275                         errx(1, "unterminated quote");
276 arg2:
277                 foundeof = *eofstr != '\0' &&
278                     strcmp(argp, eofstr) == 0;
279
280                 /* Do not make empty args unless they are quoted */
281                 if ((argp != p || wasquoted) && !foundeof) {
282                         *p++ = '\0';
283                         *xp++ = argp;
284                         if (Iflag) {
285                                 size_t curlen;
286
287                                 if (inpline == NULL)
288                                         curlen = 0;
289                                 else {
290                                         /*
291                                          * If this string is not zero
292                                          * length, append a space for
293                                          * separation before the next
294                                          * argument.
295                                          */
296                                         if ((curlen = strlen(inpline)))
297                                                 strcat(inpline, " ");
298                                 }
299                                 curlen++;
300                                 /*
301                                  * Allocate enough to hold what we will
302                                  * be holding in a second, and to append
303                                  * a space next time through, if we have
304                                  * to.
305                                  */
306                                 inpline = realloc(inpline, curlen + 2 +
307                                     strlen(argp));
308                                 if (inpline == NULL)
309                                         errx(1, "realloc failed");
310                                 if (curlen == 1)
311                                         strcpy(inpline, argp);
312                                 else
313                                         strcat(inpline, argp);
314                         }
315                 }
316
317                 /*
318                  * If max'd out on args or buffer, or reached EOF,
319                  * run the command.  If xflag and max'd out on buffer
320                  * but not on args, object.  Having reached the limit
321                  * of input lines, as specified by -L is the same as
322                  * maxing out on arguments.
323                  */
324                 if (xp == exp || p > ebp || ch == EOF ||
325                     (Lflag <= count && xflag) || foundeof) {
326                         if (xflag && xp != exp && p > ebp)
327                                 errx(1, "insufficient space for arguments");
328                         if (jfound) {
329                                 for (avj = argv; *avj; avj++)
330                                         *xp++ = *avj;
331                         }
332                         prerun(argc, av);
333                         if (ch == EOF || foundeof)
334                                 exit(rval);
335                         p = bbp;
336                         xp = bxp;
337                         count = 0;
338                 }
339                 argp = p;
340                 wasquoted = 0;
341                 break;
342         case '\'':
343                 if (indouble || zflag)
344                         goto addch;
345                 insingle = !insingle;
346                 wasquoted = 1;
347                 break;
348         case '"':
349                 if (insingle || zflag)
350                         goto addch;
351                 indouble = !indouble;
352                 wasquoted = 1;
353                 break;
354         case '\\':
355                 if (zflag)
356                         goto addch;
357                 /* Backslash escapes anything, is escaped by quotes. */
358                 if (!insingle && !indouble && (ch = getchar()) == EOF)
359                         errx(1, "backslash at EOF");
360                 /* FALLTHROUGH */
361         default:
362 addch:          if (p < ebp) {
363                         *p++ = ch;
364                         break;
365                 }
366
367                 /* If only one argument, not enough buffer space. */
368                 if (bxp == xp)
369                         errx(1, "insufficient space for argument");
370                 /* Didn't hit argument limit, so if xflag object. */
371                 if (xflag)
372                         errx(1, "insufficient space for arguments");
373
374                 if (jfound) {
375                         for (avj = argv; *avj; avj++)
376                                 *xp++ = *avj;
377                 }
378                 prerun(argc, av);
379                 xp = bxp;
380                 cnt = ebp - argp;
381                 memcpy(bbp, argp, (size_t)cnt);
382                 p = (argp = bbp) + cnt;
383                 *p++ = ch;
384                 break;
385         }
386         return;
387 }
388
389 /*
390  * Do things necessary before run()'ing, such as -I substitution,
391  * and then call run().
392  */
393 static void
394 prerun(int argc, char *argv[])
395 {
396         char **tmp, **tmp2, **avj;
397         int repls;
398
399         repls = Rflag;
400
401         if (argc == 0 || repls == 0) {
402                 *xp = NULL;
403                 run(argv);
404                 return;
405         }
406
407         avj = argv;
408
409         /*
410          * Allocate memory to hold the argument list, and
411          * a NULL at the tail.
412          */
413         tmp = malloc((argc + 1) * sizeof(char**));
414         if (tmp == NULL)
415                 errx(1, "malloc failed");
416         tmp2 = tmp;
417
418         /*
419          * Save the first argument and iterate over it, we
420          * cannot do strnsubst() to it.
421          */
422         if ((*tmp++ = strdup(*avj++)) == NULL)
423                 errx(1, "strdup failed");
424
425         /*
426          * For each argument to utility, if we have not used up
427          * the number of replacements we are allowed to do, and
428          * if the argument contains at least one occurrence of
429          * replstr, call strnsubst(), else just save the string.
430          * Iterations over elements of avj and tmp are done
431          * where appropriate.
432          */
433         while (--argc) {
434                 *tmp = *avj++;
435                 if (repls && strstr(*tmp, replstr) != NULL) {
436                         strnsubst(tmp++, replstr, inpline, (size_t)255);
437                         repls--;
438                 } else {
439                         if ((*tmp = strdup(*tmp)) == NULL)
440                                 errx(1, "strdup failed");
441                         tmp++;
442                 }
443         }
444
445         /*
446          * Run it.
447          */
448         *tmp = NULL;
449         run(tmp2);
450
451         /*
452          * Walk from the tail to the head, free along the way.
453          */
454         for (; tmp2 != tmp; tmp--)
455                 free(*tmp);
456         /*
457          * Now free the list itself.
458          */
459         free(tmp2);
460
461         /*
462          * Free the input line buffer, if we have one.
463          */
464         if (inpline != NULL) {
465                 free(inpline);
466                 inpline = NULL;
467         }
468 }
469
470 static void
471 run(char **argv)
472 {
473         volatile int childerr;
474         char **avec;
475         pid_t pid;
476         int status;
477
478         /*
479          * If the user wants to be notified of each command before it is
480          * executed, notify them.  If they want the notification to be
481          * followed by a prompt, then prompt them.
482          */
483         if (tflag || pflag) {
484                 (void)fprintf(stderr, "%s", *argv);
485                 for (avec = argv + 1; *avec != NULL; ++avec)
486                         (void)fprintf(stderr, " %s", *avec);
487                 /*
488                  * If the user has asked to be prompted, do so.
489                  */
490                 if (pflag)
491                         /*
492                          * If they asked not to exec, return without execution
493                          * but if they asked to, go to the execution.  If we
494                          * could not open their tty, break the switch and drop
495                          * back to -t behaviour.
496                          */
497                         switch (prompt()) {
498                         case 0:
499                                 return;
500                         case 1:
501                                 goto exec;
502                         case 2:
503                                 break;
504                         }
505                 (void)fprintf(stderr, "\n");
506                 (void)fflush(stderr);
507         }
508 exec:
509         childerr = 0;
510         switch(pid = vfork()) {
511         case -1:
512                 err(1, "vfork");
513         case 0:
514                 close(0);
515                 if (oflag) {
516                         if (open("/dev/tty", O_RDONLY) == -1)
517                                 err(1, "open /dev/tty");
518                 } else {
519                         if (open("/dev/null", O_RDONLY) == -1)
520                                 err(1, "open /dev/null");
521                 }
522                 execvp(argv[0], argv);
523                 childerr = errno;
524                 _exit(1);
525         }
526         pid = waitpid(pid, &status, 0);
527         if (pid == -1)
528                 err(1, "waitpid");
529         /* If we couldn't invoke the utility, exit. */
530         if (childerr != 0)
531                 err(childerr == ENOENT ? 127 : 126, "%s", *argv);
532         /* If utility signaled or exited with a value of 255, exit 1-125. */
533         if (WIFSIGNALED(status) || WEXITSTATUS(status) == 255)
534                 exit(1);
535         if (WEXITSTATUS(status))
536                 rval = 1;
537 }
538
539 /*
540  * Prompt the user about running a command.
541  */
542 static int
543 prompt(void)
544 {
545         regex_t cre;
546         size_t rsize;
547         int match;
548         char *response;
549         FILE *ttyfp;
550
551         if ((ttyfp = fopen(_PATH_TTY, "r")) == NULL)
552                 return (2);     /* Indicate that the TTY failed to open. */
553         (void)fprintf(stderr, "?...");
554         (void)fflush(stderr);
555         if ((response = fgetln(ttyfp, &rsize)) == NULL ||
556             regcomp(&cre,
557 #ifdef BOOTSTRAPPING
558                 "^[yY]",
559 #else
560                 nl_langinfo(YESEXPR),
561 #endif
562                 REG_BASIC) != 0) {
563                 (void)fclose(ttyfp);
564                 return (0);
565         }
566         match = regexec(&cre, response, 0, NULL, 0);
567         (void)fclose(ttyfp);
568         regfree(&cre);
569         return (match == 0);
570 }
571
572 static void
573 usage(void)
574 {
575         fprintf(stderr,
576 "usage: xargs [-0opt] [-E eofstr] [-I replstr [-R replacements]] [-J replstr]\n"
577 "             [-L number] [-n number [-x] [-s size] [utility [argument ...]]\n");
578         exit(1);
579 }