xref: /netbsd-src/usr.bin/xargs/xargs.c (revision 804a0485e5973966bd7e2cc216dda7da1b1122af)
1*804a0485Splunky /*	$NetBSD: xargs.c,v 1.20 2010/12/17 11:32:57 plunky Exp $	*/
25bbd8ba4Sjtc 
361f28255Scgd /*-
45bbd8ba4Sjtc  * Copyright (c) 1990, 1993
55bbd8ba4Sjtc  *	The Regents of the University of California.  All rights reserved.
661f28255Scgd  *
761f28255Scgd  * This code is derived from software contributed to Berkeley by
861f28255Scgd  * John B. Roll Jr.
961f28255Scgd  *
1061f28255Scgd  * Redistribution and use in source and binary forms, with or without
1161f28255Scgd  * modification, are permitted provided that the following conditions
1261f28255Scgd  * are met:
1361f28255Scgd  * 1. Redistributions of source code must retain the above copyright
1461f28255Scgd  *    notice, this list of conditions and the following disclaimer.
1561f28255Scgd  * 2. Redistributions in binary form must reproduce the above copyright
1661f28255Scgd  *    notice, this list of conditions and the following disclaimer in the
1761f28255Scgd  *    documentation and/or other materials provided with the distribution.
1889aaa1bbSagc  * 3. Neither the name of the University nor the names of its contributors
1961f28255Scgd  *    may be used to endorse or promote products derived from this software
2061f28255Scgd  *    without specific prior written permission.
2161f28255Scgd  *
2261f28255Scgd  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2361f28255Scgd  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2461f28255Scgd  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2561f28255Scgd  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2661f28255Scgd  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2761f28255Scgd  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2861f28255Scgd  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2961f28255Scgd  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3061f28255Scgd  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3161f28255Scgd  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3261f28255Scgd  * SUCH DAMAGE.
33a173e99aSchristos  *
34a173e99aSchristos  * $xMach: xargs.c,v 1.6 2002/02/23 05:27:47 tim Exp $
3561f28255Scgd  */
3661f28255Scgd 
378a4eca0eSlukem #include <sys/cdefs.h>
3861f28255Scgd #ifndef lint
3998e5374cSlukem __COPYRIGHT("@(#) Copyright (c) 1990, 1993\
4098e5374cSlukem  The Regents of the University of California.  All rights reserved.");
415bbd8ba4Sjtc #if 0
425bbd8ba4Sjtc static char sccsid[] = "@(#)xargs.c	8.1 (Berkeley) 6/6/93";
43a173e99aSchristos __FBSDID("$FreeBSD: src/usr.bin/xargs/xargs.c,v 1.62 2006/01/01 22:59:54 jmallett Exp $");
445bbd8ba4Sjtc #endif
45*804a0485Splunky __RCSID("$NetBSD: xargs.c,v 1.20 2010/12/17 11:32:57 plunky Exp $");
4661f28255Scgd #endif /* not lint */
4761f28255Scgd 
48a173e99aSchristos #include <sys/param.h>
4961f28255Scgd #include <sys/wait.h>
50a173e99aSchristos 
511a2a0445Skleink #include <err.h>
5261f28255Scgd #include <errno.h>
53a173e99aSchristos #include <fcntl.h>
541a2a0445Skleink #include <langinfo.h>
551a2a0445Skleink #include <locale.h>
561a2a0445Skleink #include <paths.h>
571a2a0445Skleink #include <regex.h>
5861f28255Scgd #include <stdio.h>
5961f28255Scgd #include <stdlib.h>
6061f28255Scgd #include <string.h>
61a173e99aSchristos #include <signal.h>
6261f28255Scgd #include <unistd.h>
63a173e99aSchristos 
6461f28255Scgd #include "pathnames.h"
6561f28255Scgd 
66a173e99aSchristos static void	parse_input(int, char *[]);
67a173e99aSchristos static void	prerun(int, char *[]);
68a173e99aSchristos static int	prompt(void);
69a173e99aSchristos static void	run(char **);
708b0f9554Sperry static void	usage(void) __dead;
71a173e99aSchristos void		strnsubst(char **, const char *, const char *, size_t);
72a173e99aSchristos static void	waitchildren(const char *, int);
735bbd8ba4Sjtc 
74a173e99aSchristos static char echo[] = _PATH_ECHO;
75a173e99aSchristos static char **av, **bxp, **ep, **endxp, **xp;
76a173e99aSchristos static char *argp, *bbp, *ebp, *inpline, *p, *replstr;
77a173e99aSchristos static const char *eofstr;
78a173e99aSchristos static int count, insingle, indouble, oflag, pflag, tflag, Rflag, rval, zflag;
79a173e99aSchristos static int cnt, Iflag, jfound, Lflag, Sflag, wasquoted, xflag;
80a173e99aSchristos static int curprocs, maxprocs;
81a173e99aSchristos 
82a173e99aSchristos static volatile int childerr;
83a173e99aSchristos 
84a173e99aSchristos extern char **environ;
8561f28255Scgd 
86f7c6bf57Sjtc int
main(int argc,char * argv[])87a173e99aSchristos main(int argc, char *argv[])
8861f28255Scgd {
893e3d6f89Sjoerg 	long arg_max;
90a173e99aSchristos 	int ch, Jflag, nargs, nflag, nline;
91a173e99aSchristos 	size_t linelen;
92a173e99aSchristos 	char *endptr;
9361f28255Scgd 
94a173e99aSchristos 	setprogname(argv[0]);
95a173e99aSchristos 
96a173e99aSchristos 	inpline = replstr = NULL;
97a173e99aSchristos 	ep = environ;
98a173e99aSchristos 	eofstr = "";
99a173e99aSchristos 	Jflag = nflag = 0;
100a173e99aSchristos 
101a173e99aSchristos 	(void)setlocale(LC_ALL, "");
102e9398347Sjtc 
10361f28255Scgd 	/*
10474bc6bcbSapb 	 * SUSv3 says of the exec family of functions:
10574bc6bcbSapb 	 *     The number of bytes available for the new process'
10674bc6bcbSapb 	 *     combined argument and environment lists is {ARG_MAX}. It
10774bc6bcbSapb 	 *     is implementation-defined whether null terminators,
10874bc6bcbSapb 	 *     pointers, and/or any alignment bytes are included in this
10974bc6bcbSapb 	 *     total.
11061f28255Scgd 	 *
11174bc6bcbSapb 	 * SUSv3 says of xargs:
11274bc6bcbSapb 	 *     ... the combined argument and environment lists ...
11374bc6bcbSapb 	 *     shall not exceed {ARG_MAX}-2048.
11474bc6bcbSapb 	 *
11574bc6bcbSapb 	 * To be conservative, we use ARG_MAX - 4K, and we do include
11674bc6bcbSapb 	 * nul terminators and pointers in the calculation.
11774bc6bcbSapb 	 *
11874bc6bcbSapb 	 * Given that the smallest argument is 2 bytes in length, this
11974bc6bcbSapb 	 * means that the number of arguments is limited to:
12074bc6bcbSapb 	 *
12174bc6bcbSapb 	 *	 (ARG_MAX - 4K - LENGTH(env + utility + arguments)) / 2.
12261f28255Scgd 	 *
12361f28255Scgd 	 * We arbitrarily limit the number of arguments to 5000.  This is
12461f28255Scgd 	 * allowed by POSIX.2 as long as the resulting minimum exec line is
12561f28255Scgd 	 * at least LINE_MAX.  Realloc'ing as necessary is possible, but
12661f28255Scgd 	 * probably not worthwhile.
12761f28255Scgd 	 */
12861f28255Scgd 	nargs = 5000;
1293e3d6f89Sjoerg 	if ((arg_max = sysconf(_SC_ARG_MAX)) == -1)
1303e3d6f89Sjoerg 		errx(1, "sysconf(_SC_ARG_MAX) failed");
1313e3d6f89Sjoerg 	nline = arg_max - 4 * 1024;
132a173e99aSchristos 	while (*ep != NULL) {
133a173e99aSchristos 		/* 1 byte for each '\0' */
134a173e99aSchristos 		nline -= strlen(*ep++) + 1 + sizeof(*ep);
135a173e99aSchristos 	}
136a173e99aSchristos 	maxprocs = 1;
137a173e99aSchristos 	while ((ch = getopt(argc, argv, "0E:I:J:L:n:oP:pR:S:s:rtx")) != -1)
13861f28255Scgd 		switch (ch) {
139a173e99aSchristos 		case 'E':
140a173e99aSchristos 			eofstr = optarg;
141a173e99aSchristos 			break;
142a173e99aSchristos 		case 'I':
143a173e99aSchristos 			Jflag = 0;
144a173e99aSchristos 			Iflag = 1;
145a173e99aSchristos 			Lflag = 1;
146a173e99aSchristos 			replstr = optarg;
147a173e99aSchristos 			break;
148a173e99aSchristos 		case 'J':
149a173e99aSchristos 			Iflag = 0;
150a173e99aSchristos 			Jflag = 1;
151a173e99aSchristos 			replstr = optarg;
152a173e99aSchristos 			break;
153a173e99aSchristos 		case 'L':
154a173e99aSchristos 			Lflag = atoi(optarg);
1554182cf29Slukem 			break;
15661f28255Scgd 		case 'n':
15761f28255Scgd 			nflag = 1;
15861f28255Scgd 			if ((nargs = atoi(optarg)) <= 0)
1595bbd8ba4Sjtc 				errx(1, "illegal argument count");
16061f28255Scgd 			break;
161a173e99aSchristos 		case 'o':
162a173e99aSchristos 			oflag = 1;
163a173e99aSchristos 			break;
164a173e99aSchristos 		case 'P':
165a173e99aSchristos 			if ((maxprocs = atoi(optarg)) <= 0)
166a173e99aSchristos 				errx(1, "max. processes must be >0");
167a173e99aSchristos 			break;
1681a2a0445Skleink 		case 'p':
169a173e99aSchristos 			pflag = 1;
170a173e99aSchristos 			break;
171a173e99aSchristos 		case 'R':
172a173e99aSchristos 			Rflag = strtol(optarg, &endptr, 10);
173a173e99aSchristos 			if (*endptr != '\0')
174a173e99aSchristos 				errx(1, "replacements must be a number");
175a173e99aSchristos 			break;
176a173e99aSchristos 		case 'r':
177a173e99aSchristos 			/* GNU compatibility */
178a173e99aSchristos 			break;
179a173e99aSchristos 		case 'S':
180a173e99aSchristos 			Sflag = strtoul(optarg, &endptr, 10);
181a173e99aSchristos 			if (*endptr != '\0')
182a173e99aSchristos 				errx(1, "replsize must be a number");
1831a2a0445Skleink 			break;
18461f28255Scgd 		case 's':
18561f28255Scgd 			nline = atoi(optarg);
18661f28255Scgd 			break;
18761f28255Scgd 		case 't':
18861f28255Scgd 			tflag = 1;
18961f28255Scgd 			break;
19061f28255Scgd 		case 'x':
19161f28255Scgd 			xflag = 1;
19261f28255Scgd 			break;
193a173e99aSchristos 		case '0':
194a173e99aSchristos 			zflag = 1;
195a173e99aSchristos 			break;
19661f28255Scgd 		case '?':
19761f28255Scgd 		default:
19861f28255Scgd 			usage();
19961f28255Scgd 	}
20061f28255Scgd 	argc -= optind;
20161f28255Scgd 	argv += optind;
20261f28255Scgd 
203a173e99aSchristos 	if (!Iflag && Rflag)
204a173e99aSchristos 		usage();
205a173e99aSchristos 	if (!Iflag && Sflag)
206a173e99aSchristos 		usage();
207a173e99aSchristos 	if (Iflag && !Rflag)
208a173e99aSchristos 		Rflag = 5;
209a173e99aSchristos 	if (Iflag && !Sflag)
210a173e99aSchristos 		Sflag = 255;
21161f28255Scgd 	if (xflag && !nflag)
21261f28255Scgd 		usage();
213a173e99aSchristos 	if (Iflag || Lflag)
214a173e99aSchristos 		xflag = 1;
215a173e99aSchristos 	if (replstr != NULL && *replstr == '\0')
216a173e99aSchristos 		errx(1, "replstr may not be empty");
21761f28255Scgd 
21861f28255Scgd 	/*
21961f28255Scgd 	 * Allocate pointers for the utility name, the utility arguments,
22061f28255Scgd 	 * the maximum arguments to be read from stdin and the trailing
22161f28255Scgd 	 * NULL.
22261f28255Scgd 	 */
223a173e99aSchristos 	linelen = 1 + argc + nargs + 1;
224a173e99aSchristos 	if ((av = bxp = malloc(linelen * sizeof(char **))) == NULL)
225a173e99aSchristos 		errx(1, "malloc failed");
22661f28255Scgd 
22761f28255Scgd 	/*
22861f28255Scgd 	 * Use the user's name for the utility as argv[0], just like the
22961f28255Scgd 	 * shell.  Echo is the default.  Set up pointers for the user's
23061f28255Scgd 	 * arguments.
23161f28255Scgd 	 */
232a173e99aSchristos 	if (*argv == NULL)
233a173e99aSchristos 		cnt = strlen(*bxp++ = echo);
23461f28255Scgd 	else {
23561f28255Scgd 		do {
236a173e99aSchristos 			if (Jflag && strcmp(*argv, replstr) == 0) {
237a173e99aSchristos 				char **avj;
238a173e99aSchristos 				jfound = 1;
239a173e99aSchristos 				argv++;
240a173e99aSchristos 				for (avj = argv; *avj; avj++)
241a173e99aSchristos 					cnt += strlen(*avj) + 1;
242a173e99aSchristos 				break;
243a173e99aSchristos 			}
24461f28255Scgd 			cnt += strlen(*bxp++ = *argv) + 1;
245a173e99aSchristos 		} while (*++argv != NULL);
24661f28255Scgd 	}
24761f28255Scgd 
24861f28255Scgd 	/*
24961f28255Scgd 	 * Set up begin/end/traversing pointers into the array.  The -n
25061f28255Scgd 	 * count doesn't include the trailing NULL pointer, so the malloc
25161f28255Scgd 	 * added in an extra slot.
25261f28255Scgd 	 */
253a173e99aSchristos 	endxp = (xp = bxp) + nargs;
25461f28255Scgd 
25561f28255Scgd 	/*
25661f28255Scgd 	 * Allocate buffer space for the arguments read from stdin and the
25761f28255Scgd 	 * trailing NULL.  Buffer space is defined as the default or specified
25861f28255Scgd 	 * space, minus the length of the utility name and arguments.  Set up
25961f28255Scgd 	 * begin/end/traversing pointers into the array.  The -s count does
26061f28255Scgd 	 * include the trailing NULL, so the malloc didn't add in an extra
26161f28255Scgd 	 * slot.
26261f28255Scgd 	 */
26361f28255Scgd 	nline -= cnt;
26461f28255Scgd 	if (nline <= 0)
2655bbd8ba4Sjtc 		errx(1, "insufficient space for command");
26661f28255Scgd 
267a173e99aSchristos 	if ((bbp = malloc((size_t)(nline + 1))) == NULL)
268a173e99aSchristos 		errx(1, "malloc failed");
26961f28255Scgd 	ebp = (argp = p = bbp) + nline - 1;
270a173e99aSchristos 	for (;;)
271a173e99aSchristos 		parse_input(argc, argv);
2721a2a0445Skleink }
2731a2a0445Skleink 
274a173e99aSchristos static void
parse_input(int argc,char * argv[])275a173e99aSchristos parse_input(int argc, char *argv[])
276a173e99aSchristos {
277a173e99aSchristos 	int ch, foundeof;
278a173e99aSchristos 	char **avj;
279a173e99aSchristos 
280a173e99aSchristos 	foundeof = 0;
281a173e99aSchristos 
28261f28255Scgd 	switch (ch = getchar()) {
28361f28255Scgd 	case EOF:
28461f28255Scgd 		/* No arguments since last exec. */
285a173e99aSchristos 		if (p == bbp) {
286a173e99aSchristos 			waitchildren(*argv, 1);
2875bbd8ba4Sjtc 			exit(rval);
28861f28255Scgd 		}
28961f28255Scgd 		goto arg1;
29061f28255Scgd 	case ' ':
29161f28255Scgd 	case '\t':
29261f28255Scgd 		/* Quotes escape tabs and spaces. */
2934182cf29Slukem 		if (insingle || indouble || zflag)
29461f28255Scgd 			goto addch;
29561f28255Scgd 		goto arg2;
2964182cf29Slukem 	case '\0':
297a173e99aSchristos 		if (zflag) {
298a173e99aSchristos 			/*
299a173e99aSchristos 			 * Increment 'count', so that nulls will be treated
300a173e99aSchristos 			 * as end-of-line, as well as end-of-argument.  This
301a173e99aSchristos 			 * is needed so -0 works properly with -I and -L.
302a173e99aSchristos 			 */
303a173e99aSchristos 			count++;
3044182cf29Slukem 			goto arg2;
305a173e99aSchristos 		}
3064182cf29Slukem 		goto addch;
30761f28255Scgd 	case '\n':
3084182cf29Slukem 		if (zflag)
3094182cf29Slukem 			goto addch;
310a173e99aSchristos 		count++;	    /* Indicate end-of-line (used by -L) */
31161f28255Scgd 
31261f28255Scgd 		/* Quotes do not escape newlines. */
31361f28255Scgd arg1:		if (insingle || indouble)
3145bbd8ba4Sjtc 			errx(1, "unterminated quote");
315a173e99aSchristos arg2:
316a173e99aSchristos 		foundeof = *eofstr != '\0' &&
317a173e99aSchristos 		    strncmp(argp, eofstr, (size_t)(p - argp)) == 0;
31861f28255Scgd 
319a173e99aSchristos 		/* Do not make empty args unless they are quoted */
320a173e99aSchristos 		if ((argp != p || wasquoted) && !foundeof) {
321a173e99aSchristos 			*p++ = '\0';
32261f28255Scgd 			*xp++ = argp;
323a173e99aSchristos 			if (Iflag) {
324a173e99aSchristos 				size_t curlen;
325a173e99aSchristos 
326a173e99aSchristos 				if (inpline == NULL)
327a173e99aSchristos 					curlen = 0;
328a173e99aSchristos 				else {
329a173e99aSchristos 					/*
330a173e99aSchristos 					 * If this string is not zero
331a173e99aSchristos 					 * length, append a space for
332a173e99aSchristos 					 * separation before the next
333a173e99aSchristos 					 * argument.
334a173e99aSchristos 					 */
335a173e99aSchristos 					if ((curlen = strlen(inpline)) != 0)
336a173e99aSchristos 						(void)strcat(inpline, " ");
337a173e99aSchristos 				}
338a173e99aSchristos 				curlen++;
339a173e99aSchristos 				/*
340a173e99aSchristos 				 * Allocate enough to hold what we will
341a173e99aSchristos 				 * be holding in a second, and to append
342a173e99aSchristos 				 * a space next time through, if we have
343a173e99aSchristos 				 * to.
344a173e99aSchristos 				 */
345a173e99aSchristos 				inpline = realloc(inpline, curlen + 2 +
346a173e99aSchristos 				    strlen(argp));
347a173e99aSchristos 				if (inpline == NULL)
348a173e99aSchristos 					errx(1, "realloc failed");
349a173e99aSchristos 				if (curlen == 1)
350a173e99aSchristos 					(void)strcpy(inpline, argp);
351a173e99aSchristos 				else
352a173e99aSchristos 					(void)strcat(inpline, argp);
353a173e99aSchristos 			}
354a173e99aSchristos 		}
35561f28255Scgd 
35661f28255Scgd 		/*
35761f28255Scgd 		 * If max'd out on args or buffer, or reached EOF,
35861f28255Scgd 		 * run the command.  If xflag and max'd out on buffer
359a173e99aSchristos 		 * but not on args, object.  Having reached the limit
360a173e99aSchristos 		 * of input lines, as specified by -L is the same as
361a173e99aSchristos 		 * maxing out on arguments.
36261f28255Scgd 		 */
363a173e99aSchristos 		if (xp == endxp || p > ebp || ch == EOF ||
364a173e99aSchristos 		    (Lflag <= count && xflag) || foundeof) {
365a173e99aSchristos 			if (xflag && xp != endxp && p > ebp)
3665bbd8ba4Sjtc 				errx(1, "insufficient space for arguments");
367a173e99aSchristos 			if (jfound) {
368a173e99aSchristos 				for (avj = argv; *avj; avj++)
369a173e99aSchristos 					*xp++ = *avj;
370a173e99aSchristos 			}
371a173e99aSchristos 			prerun(argc, av);
372a173e99aSchristos 			if (ch == EOF || foundeof) {
373a173e99aSchristos 				waitchildren(*argv, 1);
3745bbd8ba4Sjtc 				exit(rval);
375a173e99aSchristos 			}
37661f28255Scgd 			p = bbp;
37761f28255Scgd 			xp = bxp;
378a173e99aSchristos 			count = 0;
379a173e99aSchristos 		}
38061f28255Scgd 		argp = p;
381a173e99aSchristos 		wasquoted = 0;
38261f28255Scgd 		break;
38361f28255Scgd 	case '\'':
3844182cf29Slukem 		if (indouble || zflag)
38561f28255Scgd 			goto addch;
38661f28255Scgd 		insingle = !insingle;
387a173e99aSchristos 		wasquoted = 1;
38861f28255Scgd 		break;
38961f28255Scgd 	case '"':
3904182cf29Slukem 		if (insingle || zflag)
39161f28255Scgd 			goto addch;
39261f28255Scgd 		indouble = !indouble;
393a173e99aSchristos 		wasquoted = 1;
39461f28255Scgd 		break;
39561f28255Scgd 	case '\\':
3964182cf29Slukem 		if (zflag)
3974182cf29Slukem 			goto addch;
39861f28255Scgd 		/* Backslash escapes anything, is escaped by quotes. */
39961f28255Scgd 		if (!insingle && !indouble && (ch = getchar()) == EOF)
4005bbd8ba4Sjtc 			errx(1, "backslash at EOF");
40161f28255Scgd 		/* FALLTHROUGH */
40261f28255Scgd 	default:
40361f28255Scgd addch:		if (p < ebp) {
40461f28255Scgd 			*p++ = ch;
40561f28255Scgd 			break;
40661f28255Scgd 		}
40761f28255Scgd 
40861f28255Scgd 		/* If only one argument, not enough buffer space. */
40961f28255Scgd 		if (bxp == xp)
4105bbd8ba4Sjtc 			errx(1, "insufficient space for argument");
41161f28255Scgd 		/* Didn't hit argument limit, so if xflag object. */
41261f28255Scgd 		if (xflag)
4135bbd8ba4Sjtc 			errx(1, "insufficient space for arguments");
41461f28255Scgd 
415a173e99aSchristos 		if (jfound) {
416a173e99aSchristos 			for (avj = argv; *avj; avj++)
417a173e99aSchristos 				*xp++ = *avj;
418a173e99aSchristos 		}
419a173e99aSchristos 		prerun(argc, av);
42061f28255Scgd 		xp = bxp;
42161f28255Scgd 		cnt = ebp - argp;
422a173e99aSchristos 		(void)memcpy(bbp, argp, (size_t)cnt);
42361f28255Scgd 		p = (argp = bbp) + cnt;
42461f28255Scgd 		*p++ = ch;
42561f28255Scgd 		break;
42661f28255Scgd 	}
427a173e99aSchristos }
428a173e99aSchristos 
429a173e99aSchristos /*
430a173e99aSchristos  * Do things necessary before run()'ing, such as -I substitution,
431a173e99aSchristos  * and then call run().
432a173e99aSchristos  */
433a173e99aSchristos static void
prerun(int argc,char * argv[])434a173e99aSchristos prerun(int argc, char *argv[])
435a173e99aSchristos {
436a173e99aSchristos 	char **tmp, **tmp2, **avj;
437a173e99aSchristos 	int repls;
438a173e99aSchristos 
439a173e99aSchristos 	repls = Rflag;
440a173e99aSchristos 
441a173e99aSchristos 	if (argc == 0 || repls == 0) {
442a173e99aSchristos 		*xp = NULL;
443a173e99aSchristos 		run(argv);
444a173e99aSchristos 		return;
445a173e99aSchristos 	}
446a173e99aSchristos 
447a173e99aSchristos 	avj = argv;
448a173e99aSchristos 
449a173e99aSchristos 	/*
450a173e99aSchristos 	 * Allocate memory to hold the argument list, and
451a173e99aSchristos 	 * a NULL at the tail.
452a173e99aSchristos 	 */
453a173e99aSchristos 	tmp = malloc((argc + 1) * sizeof(char**));
454a173e99aSchristos 	if (tmp == NULL)
455a173e99aSchristos 		errx(1, "malloc failed");
456a173e99aSchristos 	tmp2 = tmp;
457a173e99aSchristos 
458a173e99aSchristos 	/*
459a173e99aSchristos 	 * Save the first argument and iterate over it, we
460a173e99aSchristos 	 * cannot do strnsubst() to it.
461a173e99aSchristos 	 */
462a173e99aSchristos 	if ((*tmp++ = strdup(*avj++)) == NULL)
463a173e99aSchristos 		errx(1, "strdup failed");
464a173e99aSchristos 
465a173e99aSchristos 	/*
466a173e99aSchristos 	 * For each argument to utility, if we have not used up
467a173e99aSchristos 	 * the number of replacements we are allowed to do, and
468a173e99aSchristos 	 * if the argument contains at least one occurrence of
469a173e99aSchristos 	 * replstr, call strnsubst(), else just save the string.
470a173e99aSchristos 	 * Iterations over elements of avj and tmp are done
471a173e99aSchristos 	 * where appropriate.
472a173e99aSchristos 	 */
473a173e99aSchristos 	while (--argc) {
474a173e99aSchristos 		*tmp = *avj++;
475a173e99aSchristos 		if (repls && strstr(*tmp, replstr) != NULL) {
476a173e99aSchristos 			strnsubst(tmp++, replstr, inpline, (size_t)Sflag);
477a173e99aSchristos 			if (repls > 0)
478a173e99aSchristos 				repls--;
479a173e99aSchristos 		} else {
480a173e99aSchristos 			if ((*tmp = strdup(*tmp)) == NULL)
481a173e99aSchristos 				errx(1, "strdup failed");
482a173e99aSchristos 			tmp++;
483a173e99aSchristos 		}
484a173e99aSchristos 	}
485a173e99aSchristos 
486a173e99aSchristos 	/*
487a173e99aSchristos 	 * Run it.
488a173e99aSchristos 	 */
489a173e99aSchristos 	*tmp = NULL;
490a173e99aSchristos 	run(tmp2);
491a173e99aSchristos 
492a173e99aSchristos 	/*
493a173e99aSchristos 	 * Walk from the tail to the head, free along the way.
494a173e99aSchristos 	 */
495a173e99aSchristos 	for (; tmp2 != tmp; tmp--)
496a173e99aSchristos 		free(*tmp);
497a173e99aSchristos 	/*
498a173e99aSchristos 	 * Now free the list itself.
499a173e99aSchristos 	 */
500a173e99aSchristos 	free(tmp2);
501a173e99aSchristos 
502a173e99aSchristos 	/*
503a173e99aSchristos 	 * Free the input line buffer, if we have one.
504a173e99aSchristos 	 */
505a173e99aSchristos 	if (inpline != NULL) {
506a173e99aSchristos 		free(inpline);
507a173e99aSchristos 		inpline = NULL;
508a173e99aSchristos 	}
50961f28255Scgd }
51061f28255Scgd 
5111a2a0445Skleink static void
run(char ** argv)512a173e99aSchristos run(char **argv)
51361f28255Scgd {
514a173e99aSchristos 	int fd;
515a173e99aSchristos 	char **avec;
516a173e99aSchristos 
517a173e99aSchristos 	/*
518a173e99aSchristos 	 * If the user wants to be notified of each command before it is
519a173e99aSchristos 	 * executed, notify them.  If they want the notification to be
520a173e99aSchristos 	 * followed by a prompt, then prompt them.
521a173e99aSchristos 	 */
522a173e99aSchristos 	if (tflag || pflag) {
523a173e99aSchristos 		(void)fprintf(stderr, "%s", *argv);
524a173e99aSchristos 		for (avec = argv + 1; *avec != NULL; ++avec)
525a173e99aSchristos 			(void)fprintf(stderr, " %s", *avec);
526a173e99aSchristos 		/*
527a173e99aSchristos 		 * If the user has asked to be prompted, do so.
528a173e99aSchristos 		 */
529a173e99aSchristos 		if (pflag)
530a173e99aSchristos 			/*
531a173e99aSchristos 			 * If they asked not to exec, return without execution
532a173e99aSchristos 			 * but if they asked to, go to the execution.  If we
533a173e99aSchristos 			 * could not open their tty, break the switch and drop
534a173e99aSchristos 			 * back to -t behaviour.
535a173e99aSchristos 			 */
536a173e99aSchristos 			switch (prompt()) {
537a173e99aSchristos 			case 0:
538a173e99aSchristos 				return;
539a173e99aSchristos 			case 1:
540a173e99aSchristos 				goto exec;
541a173e99aSchristos 			case 2:
542a173e99aSchristos 				break;
543a173e99aSchristos 			}
544a173e99aSchristos 		(void)fprintf(stderr, "\n");
545a173e99aSchristos 		(void)fflush(stderr);
546a173e99aSchristos 	}
547a173e99aSchristos exec:
548a173e99aSchristos 	childerr = 0;
549a173e99aSchristos 	switch (vfork()) {
550a173e99aSchristos 	case -1:
551a173e99aSchristos 		err(1, "vfork");
552a173e99aSchristos 		/*NOTREACHED*/
553a173e99aSchristos 	case 0:
554a173e99aSchristos 		if (oflag) {
555a173e99aSchristos 			if ((fd = open(_PATH_TTY, O_RDONLY)) == -1)
556a173e99aSchristos 				err(1, "can't open /dev/tty");
557a173e99aSchristos 		} else {
558a173e99aSchristos 			fd = open(_PATH_DEVNULL, O_RDONLY);
559a173e99aSchristos 		}
560a173e99aSchristos 		if (fd > STDIN_FILENO) {
561a173e99aSchristos 			if (dup2(fd, STDIN_FILENO) != 0)
562a173e99aSchristos 				err(1, "can't dup2 to stdin");
563a173e99aSchristos 			(void)close(fd);
564a173e99aSchristos 		}
565a173e99aSchristos 		(void)execvp(argv[0], argv);
566a173e99aSchristos 		childerr = errno;
567a173e99aSchristos 		_exit(1);
568a173e99aSchristos 	}
569a173e99aSchristos 	curprocs++;
570a173e99aSchristos 	waitchildren(*argv, 0);
571a173e99aSchristos }
572a173e99aSchristos 
573a173e99aSchristos static void
waitchildren(const char * name,int waitall)574a173e99aSchristos waitchildren(const char *name, int waitall)
575a173e99aSchristos {
57661f28255Scgd 	pid_t pid;
57761f28255Scgd 	int status;
57861f28255Scgd 
579a173e99aSchristos 	while ((pid = waitpid(-1, &status, !waitall && curprocs < maxprocs ?
580a173e99aSchristos 	    WNOHANG : 0)) > 0) {
581a173e99aSchristos 		curprocs--;
582a173e99aSchristos 		/* If we couldn't invoke the utility, exit. */
583a173e99aSchristos 		if (childerr != 0) {
584a173e99aSchristos 			errno = childerr;
585a173e99aSchristos 			err(errno == ENOENT ? 127 : 126, "%s", name);
5861a2a0445Skleink 		}
58761f28255Scgd 		/*
588a173e99aSchristos 		 * According to POSIX, we have to exit if the utility exits
589a173e99aSchristos 		 * with a 255 status, or is interrupted by a signal. xargs
590a173e99aSchristos 		 * is allowed to return any exit status between 1 and 125
591a173e99aSchristos 		 * in these cases, but we'll use 124 and 125, the same
592a173e99aSchristos 		 * values used by GNU xargs.
5932ab235c8Sjtc 		 */
5942ab235c8Sjtc 		if (WIFEXITED(status)) {
5952ab235c8Sjtc 			if (WEXITSTATUS (status) == 255) {
596a173e99aSchristos 				warnx ("%s exited with status 255", name);
5972ab235c8Sjtc 				exit(124);
5982ab235c8Sjtc 			} else if (WEXITSTATUS (status) != 0) {
5995bbd8ba4Sjtc 				rval = 123;
6002ab235c8Sjtc 			}
6012ab235c8Sjtc 		} else if (WIFSIGNALED (status)) {
6020e43b474Schristos 			if (WTERMSIG(status) < NSIG) {
603a173e99aSchristos 				warnx("%s terminated by SIG%s", name,
60454e08fd7Sfair 				    sys_signame[WTERMSIG(status)]);
60554e08fd7Sfair 			} else {
606a173e99aSchristos 				warnx("%s terminated by signal %d", name,
60754e08fd7Sfair 				    WTERMSIG(status));
60854e08fd7Sfair 			}
6092ab235c8Sjtc 			exit(125);
6102ab235c8Sjtc 		}
61161f28255Scgd 	}
612a173e99aSchristos 	if (pid == -1 && errno != ECHILD)
613*804a0485Splunky 		err(1, "waitpid");
614a173e99aSchristos }
615a173e99aSchristos 
616a173e99aSchristos /*
617a173e99aSchristos  * Prompt the user about running a command.
618a173e99aSchristos  */
619a173e99aSchristos static int
prompt(void)620a173e99aSchristos prompt(void)
621a173e99aSchristos {
622a173e99aSchristos 	regex_t cre;
623a173e99aSchristos 	size_t rsize;
624a173e99aSchristos 	int match;
625a173e99aSchristos 	char *response;
626a173e99aSchristos 	FILE *ttyfp;
627a173e99aSchristos 
628a173e99aSchristos 	if ((ttyfp = fopen(_PATH_TTY, "r")) == NULL)
629a173e99aSchristos 		return (2);	/* Indicate that the TTY failed to open. */
630a173e99aSchristos 	(void)fprintf(stderr, "?...");
631a173e99aSchristos 	(void)fflush(stderr);
632a173e99aSchristos 	if ((response = fgetln(ttyfp, &rsize)) == NULL ||
633a173e99aSchristos 	    regcomp(&cre, nl_langinfo(YESEXPR), REG_BASIC) != 0) {
634a173e99aSchristos 		(void)fclose(ttyfp);
635a173e99aSchristos 		return (0);
636a173e99aSchristos 	}
637a173e99aSchristos 	response[rsize - 1] = '\0';
638a173e99aSchristos 	match = regexec(&cre, response, 0, NULL, 0);
639a173e99aSchristos 	(void)fclose(ttyfp);
640a173e99aSchristos 	regfree(&cre);
641a173e99aSchristos 	return (match == 0);
642a173e99aSchristos }
64361f28255Scgd 
6441a2a0445Skleink static void
usage(void)645a173e99aSchristos usage(void)
64661f28255Scgd {
64761f28255Scgd 	(void)fprintf(stderr,
648a173e99aSchristos "Usage: %s [-0opt] [-E eofstr] [-I replstr [-R replacements] [-S replsize]]\n"
649a173e99aSchristos "             [-J replstr] [-L number] [-n number [-x]] [-P maxprocs]\n"
650a173e99aSchristos "             [-s size] [utility [argument ...]]\n", getprogname());
65161f28255Scgd 	exit(1);
65261f28255Scgd }
653