]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - usr.bin/xargs/xargs.c
MFC r215615, r215642:
[FreeBSD/stable/8.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 #if 0
40 #ifndef lint
41 static const char copyright[] =
42 "@(#) Copyright (c) 1990, 1993\n\
43         The Regents of the University of California.  All rights reserved.\n";
44 #endif /* not lint */
45
46 #ifndef lint
47 static char sccsid[] = "@(#)xargs.c     8.1 (Berkeley) 6/6/93";
48 #endif /* not lint */
49 #endif
50 #include <sys/cdefs.h>
51 __FBSDID("$FreeBSD$");
52
53 #include <sys/param.h>
54 #include <sys/wait.h>
55
56 #include <err.h>
57 #include <errno.h>
58 #include <fcntl.h>
59 #include <langinfo.h>
60 #include <locale.h>
61 #include <paths.h>
62 #include <regex.h>
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <string.h>
66 #include <unistd.h>
67
68 #include "pathnames.h"
69
70 static void     parse_input(int, char *[]);
71 static void     prerun(int, char *[]);
72 static int      prompt(void);
73 static void     run(char **);
74 static void     usage(void);
75 void            strnsubst(char **, const char *, const char *, size_t);
76 static pid_t    xwait(int block, int *status);
77 static void     waitchildren(const char *, int);
78 static void     pids_init(void);
79 static int      pids_empty(void);
80 static int      pids_full(void);
81 static void     pids_add(pid_t pid);
82 static int      pids_remove(pid_t pid);
83 static int      findslot(pid_t pid);
84 static int      findfreeslot(void);
85 static void     clearslot(int slot);
86
87 static char echo[] = _PATH_ECHO;
88 static char **av, **bxp, **ep, **endxp, **xp;
89 static char *argp, *bbp, *ebp, *inpline, *p, *replstr;
90 static const char *eofstr;
91 static int count, insingle, indouble, oflag, pflag, tflag, Rflag, rval, zflag;
92 static int cnt, Iflag, jfound, Lflag, Sflag, wasquoted, xflag;
93 static int curprocs, maxprocs;
94 static pid_t *childpids;
95
96 static volatile int childerr;
97
98 extern char **environ;
99
100 int
101 main(int argc, char *argv[])
102 {
103         long arg_max;
104         int ch, Jflag, nargs, nflag, nline;
105         size_t linelen;
106         char *endptr;
107
108         inpline = replstr = NULL;
109         ep = environ;
110         eofstr = "";
111         Jflag = nflag = 0;
112
113         (void)setlocale(LC_ALL, "");
114
115         /*
116          * POSIX.2 limits the exec line length to ARG_MAX - 2K.  Running that
117          * caused some E2BIG errors, so it was changed to ARG_MAX - 4K.  Given
118          * that the smallest argument is 2 bytes in length, this means that
119          * the number of arguments is limited to:
120          *
121          *       (ARG_MAX - 4K - LENGTH(utility + arguments)) / 2.
122          *
123          * We arbitrarily limit the number of arguments to 5000.  This is
124          * allowed by POSIX.2 as long as the resulting minimum exec line is
125          * at least LINE_MAX.  Realloc'ing as necessary is possible, but
126          * probably not worthwhile.
127          */
128         nargs = 5000;
129         if ((arg_max = sysconf(_SC_ARG_MAX)) == -1)
130                 errx(1, "sysconf(_SC_ARG_MAX) failed");
131         nline = arg_max - 4 * 1024;
132         while (*ep != NULL) {
133                 /* 1 byte for each '\0' */
134                 nline -= strlen(*ep++) + 1 + sizeof(*ep);
135         }
136         maxprocs = 1;
137         while ((ch = getopt(argc, argv, "0E:I:J:L:n:oP:pR:S:s:rtx")) != -1)
138                 switch (ch) {
139                 case 'E':
140                         eofstr = optarg;
141                         break;
142                 case 'I':
143                         Jflag = 0;
144                         Iflag = 1;
145                         Lflag = 1;
146                         replstr = optarg;
147                         break;
148                 case 'J':
149                         Iflag = 0;
150                         Jflag = 1;
151                         replstr = optarg;
152                         break;
153                 case 'L':
154                         Lflag = atoi(optarg);
155                         break;
156                 case 'n':
157                         nflag = 1;
158                         if ((nargs = atoi(optarg)) <= 0)
159                                 errx(1, "illegal argument count");
160                         break;
161                 case 'o':
162                         oflag = 1;
163                         break;
164                 case 'P':
165                         if ((maxprocs = atoi(optarg)) <= 0)
166                                 errx(1, "max. processes must be >0");
167                         break;
168                 case 'p':
169                         pflag = 1;
170                         break;
171                 case 'R':
172                         Rflag = strtol(optarg, &endptr, 10);
173                         if (*endptr != '\0')
174                                 errx(1, "replacements must be a number");
175                         break;
176                 case 'r':
177                         /* GNU compatibility */
178                         break;
179                 case 'S':
180                         Sflag = strtoul(optarg, &endptr, 10);
181                         if (*endptr != '\0')
182                                 errx(1, "replsize must be a number");
183                         break;
184                 case 's':
185                         nline = atoi(optarg);
186                         break;
187                 case 't':
188                         tflag = 1;
189                         break;
190                 case 'x':
191                         xflag = 1;
192                         break;
193                 case '0':
194                         zflag = 1;
195                         break;
196                 case '?':
197                 default:
198                         usage();
199         }
200         argc -= optind;
201         argv += optind;
202
203         if (!Iflag && Rflag)
204                 usage();
205         if (!Iflag && Sflag)
206                 usage();
207         if (Iflag && !Rflag)
208                 Rflag = 5;
209         if (Iflag && !Sflag)
210                 Sflag = 255;
211         if (xflag && !nflag)
212                 usage();
213         if (Iflag || Lflag)
214                 xflag = 1;
215         if (replstr != NULL && *replstr == '\0')
216                 errx(1, "replstr may not be empty");
217
218         pids_init();
219
220         /*
221          * Allocate pointers for the utility name, the utility arguments,
222          * the maximum arguments to be read from stdin and the trailing
223          * NULL.
224          */
225         linelen = 1 + argc + nargs + 1;
226         if ((av = bxp = malloc(linelen * sizeof(char **))) == NULL)
227                 errx(1, "malloc failed");
228
229         /*
230          * Use the user's name for the utility as argv[0], just like the
231          * shell.  Echo is the default.  Set up pointers for the user's
232          * arguments.
233          */
234         if (*argv == NULL)
235                 cnt = strlen(*bxp++ = echo);
236         else {
237                 do {
238                         if (Jflag && strcmp(*argv, replstr) == 0) {
239                                 char **avj;
240                                 jfound = 1;
241                                 argv++;
242                                 for (avj = argv; *avj; avj++)
243                                         cnt += strlen(*avj) + 1;
244                                 break;
245                         }
246                         cnt += strlen(*bxp++ = *argv) + 1;
247                 } while (*++argv != NULL);
248         }
249
250         /*
251          * Set up begin/end/traversing pointers into the array.  The -n
252          * count doesn't include the trailing NULL pointer, so the malloc
253          * added in an extra slot.
254          */
255         endxp = (xp = bxp) + nargs;
256
257         /*
258          * Allocate buffer space for the arguments read from stdin and the
259          * trailing NULL.  Buffer space is defined as the default or specified
260          * space, minus the length of the utility name and arguments.  Set up
261          * begin/end/traversing pointers into the array.  The -s count does
262          * include the trailing NULL, so the malloc didn't add in an extra
263          * slot.
264          */
265         nline -= cnt;
266         if (nline <= 0)
267                 errx(1, "insufficient space for command");
268
269         if ((bbp = malloc((size_t)(nline + 1))) == NULL)
270                 errx(1, "malloc failed");
271         ebp = (argp = p = bbp) + nline - 1;
272         for (;;)
273                 parse_input(argc, argv);
274 }
275
276 static void
277 parse_input(int argc, char *argv[])
278 {
279         int ch, foundeof;
280         char **avj;
281
282         foundeof = 0;
283
284         switch (ch = getchar()) {
285         case EOF:
286                 /* No arguments since last exec. */
287                 if (p == bbp) {
288                         waitchildren(*argv, 1);
289                         exit(rval);
290                 }
291                 goto arg1;
292         case ' ':
293         case '\t':
294                 /* Quotes escape tabs and spaces. */
295                 if (insingle || indouble || zflag)
296                         goto addch;
297                 goto arg2;
298         case '\0':
299                 if (zflag) {
300                         /*
301                          * Increment 'count', so that nulls will be treated
302                          * as end-of-line, as well as end-of-argument.  This
303                          * is needed so -0 works properly with -I and -L.
304                          */
305                         count++;
306                         goto arg2;
307                 }
308                 goto addch;
309         case '\n':
310                 if (zflag)
311                         goto addch;
312                 count++;            /* Indicate end-of-line (used by -L) */
313
314                 /* Quotes do not escape newlines. */
315 arg1:           if (insingle || indouble)
316                         errx(1, "unterminated quote");
317 arg2:
318                 foundeof = *eofstr != '\0' &&
319                     strncmp(argp, eofstr, p - argp) == 0;
320
321                 /* Do not make empty args unless they are quoted */
322                 if ((argp != p || wasquoted) && !foundeof) {
323                         *p++ = '\0';
324                         *xp++ = argp;
325                         if (Iflag) {
326                                 size_t curlen;
327
328                                 if (inpline == NULL)
329                                         curlen = 0;
330                                 else {
331                                         /*
332                                          * If this string is not zero
333                                          * length, append a space for
334                                          * separation before the next
335                                          * argument.
336                                          */
337                                         if ((curlen = strlen(inpline)))
338                                                 strcat(inpline, " ");
339                                 }
340                                 curlen++;
341                                 /*
342                                  * Allocate enough to hold what we will
343                                  * be holding in a second, and to append
344                                  * a space next time through, if we have
345                                  * to.
346                                  */
347                                 inpline = realloc(inpline, curlen + 2 +
348                                     strlen(argp));
349                                 if (inpline == NULL)
350                                         errx(1, "realloc failed");
351                                 if (curlen == 1)
352                                         strcpy(inpline, argp);
353                                 else
354                                         strcat(inpline, argp);
355                         }
356                 }
357
358                 /*
359                  * If max'd out on args or buffer, or reached EOF,
360                  * run the command.  If xflag and max'd out on buffer
361                  * but not on args, object.  Having reached the limit
362                  * of input lines, as specified by -L is the same as
363                  * maxing out on arguments.
364                  */
365                 if (xp == endxp || p > ebp || ch == EOF ||
366                     (Lflag <= count && xflag) || foundeof) {
367                         if (xflag && xp != endxp && p > ebp)
368                                 errx(1, "insufficient space for arguments");
369                         if (jfound) {
370                                 for (avj = argv; *avj; avj++)
371                                         *xp++ = *avj;
372                         }
373                         prerun(argc, av);
374                         if (ch == EOF || foundeof) {
375                                 waitchildren(*argv, 1);
376                                 exit(rval);
377                         }
378                         p = bbp;
379                         xp = bxp;
380                         count = 0;
381                 }
382                 argp = p;
383                 wasquoted = 0;
384                 break;
385         case '\'':
386                 if (indouble || zflag)
387                         goto addch;
388                 insingle = !insingle;
389                 wasquoted = 1;
390                 break;
391         case '"':
392                 if (insingle || zflag)
393                         goto addch;
394                 indouble = !indouble;
395                 wasquoted = 1;
396                 break;
397         case '\\':
398                 if (zflag)
399                         goto addch;
400                 /* Backslash escapes anything, is escaped by quotes. */
401                 if (!insingle && !indouble && (ch = getchar()) == EOF)
402                         errx(1, "backslash at EOF");
403                 /* FALLTHROUGH */
404         default:
405 addch:          if (p < ebp) {
406                         *p++ = ch;
407                         break;
408                 }
409
410                 /* If only one argument, not enough buffer space. */
411                 if (bxp == xp)
412                         errx(1, "insufficient space for argument");
413                 /* Didn't hit argument limit, so if xflag object. */
414                 if (xflag)
415                         errx(1, "insufficient space for arguments");
416
417                 if (jfound) {
418                         for (avj = argv; *avj; avj++)
419                                 *xp++ = *avj;
420                 }
421                 prerun(argc, av);
422                 xp = bxp;
423                 cnt = ebp - argp;
424                 memcpy(bbp, argp, (size_t)cnt);
425                 p = (argp = bbp) + cnt;
426                 *p++ = ch;
427                 break;
428         }
429 }
430
431 /*
432  * Do things necessary before run()'ing, such as -I substitution,
433  * and then call run().
434  */
435 static void
436 prerun(int argc, char *argv[])
437 {
438         char **tmp, **tmp2, **avj;
439         int repls;
440
441         repls = Rflag;
442
443         if (argc == 0 || repls == 0) {
444                 *xp = NULL;
445                 run(argv);
446                 return;
447         }
448
449         avj = argv;
450
451         /*
452          * Allocate memory to hold the argument list, and
453          * a NULL at the tail.
454          */
455         tmp = malloc((argc + 1) * sizeof(char**));
456         if (tmp == NULL)
457                 errx(1, "malloc failed");
458         tmp2 = tmp;
459
460         /*
461          * Save the first argument and iterate over it, we
462          * cannot do strnsubst() to it.
463          */
464         if ((*tmp++ = strdup(*avj++)) == NULL)
465                 errx(1, "strdup failed");
466
467         /*
468          * For each argument to utility, if we have not used up
469          * the number of replacements we are allowed to do, and
470          * if the argument contains at least one occurrence of
471          * replstr, call strnsubst(), else just save the string.
472          * Iterations over elements of avj and tmp are done
473          * where appropriate.
474          */
475         while (--argc) {
476                 *tmp = *avj++;
477                 if (repls && strstr(*tmp, replstr) != NULL) {
478                         strnsubst(tmp++, replstr, inpline, (size_t)Sflag);
479                         if (repls > 0)
480                                 repls--;
481                 } else {
482                         if ((*tmp = strdup(*tmp)) == NULL)
483                                 errx(1, "strdup failed");
484                         tmp++;
485                 }
486         }
487
488         /*
489          * Run it.
490          */
491         *tmp = NULL;
492         run(tmp2);
493
494         /*
495          * Walk from the tail to the head, free along the way.
496          */
497         for (; tmp2 != tmp; tmp--)
498                 free(*tmp);
499         /*
500          * Now free the list itself.
501          */
502         free(tmp2);
503
504         /*
505          * Free the input line buffer, if we have one.
506          */
507         if (inpline != NULL) {
508                 free(inpline);
509                 inpline = NULL;
510         }
511 }
512
513 static void
514 run(char **argv)
515 {
516         pid_t pid;
517         int fd;
518         char **avec;
519
520         /*
521          * If the user wants to be notified of each command before it is
522          * executed, notify them.  If they want the notification to be
523          * followed by a prompt, then prompt them.
524          */
525         if (tflag || pflag) {
526                 (void)fprintf(stderr, "%s", *argv);
527                 for (avec = argv + 1; *avec != NULL; ++avec)
528                         (void)fprintf(stderr, " %s", *avec);
529                 /*
530                  * If the user has asked to be prompted, do so.
531                  */
532                 if (pflag)
533                         /*
534                          * If they asked not to exec, return without execution
535                          * but if they asked to, go to the execution.  If we
536                          * could not open their tty, break the switch and drop
537                          * back to -t behaviour.
538                          */
539                         switch (prompt()) {
540                         case 0:
541                                 return;
542                         case 1:
543                                 goto exec;
544                         case 2:
545                                 break;
546                         }
547                 (void)fprintf(stderr, "\n");
548                 (void)fflush(stderr);
549         }
550 exec:
551         childerr = 0;
552         switch (pid = vfork()) {
553         case -1:
554                 err(1, "vfork");
555         case 0:
556                 if (oflag) {
557                         if ((fd = open(_PATH_TTY, O_RDONLY)) == -1)
558                                 err(1, "can't open /dev/tty");
559                 } else {
560                         fd = open(_PATH_DEVNULL, O_RDONLY);
561                 }
562                 if (fd > STDIN_FILENO) {
563                         if (dup2(fd, STDIN_FILENO) != 0)
564                                 err(1, "can't dup2 to stdin");
565                         close(fd);
566                 }
567                 execvp(argv[0], argv);
568                 childerr = errno;
569                 _exit(1);
570         }
571         pids_add(pid);
572         waitchildren(*argv, 0);
573 }
574
575 /*
576  * Wait for a tracked child to exit and return its pid and exit status.
577  *
578  * Ignores (discards) all untracked child processes.
579  * Returns -1 and sets errno to ECHILD if no tracked children exist.
580  * If block is set, waits indefinitely for a child process to exit.
581  * If block is not set and no children have exited, returns 0 immediately.
582  */
583 static pid_t
584 xwait(int block, int *status) {
585         pid_t pid;
586
587         if (pids_empty()) {
588                 errno = ECHILD;
589                 return (-1);
590         }
591
592         while ((pid = waitpid(-1, status, block ? 0 : WNOHANG)) > 0)
593                 if (pids_remove(pid))
594                         break;
595
596         return (pid);
597 }
598
599 static void
600 waitchildren(const char *name, int waitall)
601 {
602         pid_t pid;
603         int status;
604
605         while ((pid = xwait(waitall || pids_full(), &status)) > 0) {
606                 /* If we couldn't invoke the utility, exit. */
607                 if (childerr != 0) {
608                         errno = childerr;
609                         err(errno == ENOENT ? 127 : 126, "%s", name);
610                 }
611                 /*
612                  * If utility signaled or exited with a value of 255,
613                  * exit 1-125.
614                  */
615                 if (WIFSIGNALED(status) || WEXITSTATUS(status) == 255)
616                         exit(1);
617                 if (WEXITSTATUS(status))
618                         rval = 1;
619         }
620
621         if (pid == -1 && errno != ECHILD)
622                 err(1, "waitpid");
623 }
624
625 #define NOPID   (0)
626
627 static void
628 pids_init(void)
629 {
630         int i;
631
632         if ((childpids = malloc(maxprocs * sizeof(*childpids))) == NULL)
633                 errx(1, "malloc failed");
634
635         for (i = 0; i < maxprocs; i++)
636                 clearslot(i);
637 }
638
639 static int
640 pids_empty(void)
641 {
642         return (curprocs == 0);
643 }
644
645 static int
646 pids_full(void)
647 {
648         return (curprocs >= maxprocs);
649 }
650
651 static void
652 pids_add(pid_t pid)
653 {
654         int slot;
655
656         slot = findfreeslot();
657         childpids[slot] = pid;
658         curprocs++;
659 }
660
661 static int
662 pids_remove(pid_t pid)
663 {
664         int slot;
665
666         if ((slot = findslot(pid)) < 0)
667                 return (0);
668
669         clearslot(slot);
670         curprocs--;
671         return (1);
672 }
673
674 static int
675 findfreeslot(void)
676 {
677         int slot;
678
679         if ((slot = findslot(NOPID)) < 0)
680                 errx(1, "internal error: no free pid slot");
681
682         return (slot);
683 }
684
685 static int
686 findslot(pid_t pid)
687 {
688         int slot;
689
690         for (slot = 0; slot < maxprocs; slot++)
691                 if (childpids[slot] == pid)
692                         return (slot);
693
694         return (-1);
695 }
696
697 static void
698 clearslot(int slot)
699 {
700         childpids[slot] = NOPID;
701 }
702
703 /*
704  * Prompt the user about running a command.
705  */
706 static int
707 prompt(void)
708 {
709         regex_t cre;
710         size_t rsize;
711         int match;
712         char *response;
713         FILE *ttyfp;
714
715         if ((ttyfp = fopen(_PATH_TTY, "r")) == NULL)
716                 return (2);     /* Indicate that the TTY failed to open. */
717         (void)fprintf(stderr, "?...");
718         (void)fflush(stderr);
719         if ((response = fgetln(ttyfp, &rsize)) == NULL ||
720             regcomp(&cre, nl_langinfo(YESEXPR), REG_BASIC) != 0) {
721                 (void)fclose(ttyfp);
722                 return (0);
723         }
724         response[rsize - 1] = '\0';
725         match = regexec(&cre, response, 0, NULL, 0);
726         (void)fclose(ttyfp);
727         regfree(&cre);
728         return (match == 0);
729 }
730
731 static void
732 usage(void)
733 {
734         fprintf(stderr,
735 "usage: xargs [-0opt] [-E eofstr] [-I replstr [-R replacements] [-S replsize]]\n"
736 "             [-J replstr] [-L number] [-n number [-x]] [-P maxprocs]\n"
737 "             [-s size] [utility [argument ...]]\n");
738         exit(1);
739 }