apply.c revision 70669
1/*-
2 * Copyright (c) 1994
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * Jan-Simon Pendry.
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
37#ifndef lint
38#if 0
39static const char sccsid[] = "@(#)apply.c	8.4 (Berkeley) 4/4/94";
40#endif
41static const char rcsid[] =
42  "$FreeBSD: head/usr.bin/apply/apply.c 70669 2001-01-04 19:05:49Z will $";
43#endif /* not lint */
44
45#include <sys/types.h>
46
47#include <sys/wait.h>
48
49#include <ctype.h>
50#include <err.h>
51#include <paths.h>
52#include <signal.h>
53#include <stdio.h>
54#include <stdlib.h>
55#include <string.h>
56#include <unistd.h>
57
58void			usage (void);
59static int		exec_shell (const char *);
60
61static unsigned int	prespecified;
62static char		*shell;
63
64int
65main(int argc, char **argv)
66{
67	int ch, debug, i, magic, n, nargs, rval;
68	size_t clen, l;
69	char *c, *cmd, *p, *q;
70
71	debug = 0;
72	magic = '%';		/* Default magic char is `%'. */
73	nargs = -1;
74	while ((ch = getopt(argc, argv, "a:ds:0123456789")) != -1)
75		switch (ch) {
76		case 'a':
77			if (optarg[1] != '\0')
78				errx(1,
79				    "illegal magic character specification");
80			magic = optarg[0];
81			break;
82		case 'd':
83			debug = 1;
84			break;
85		case 's':
86			prespecified = 1;
87			shell = optarg;
88			break;
89		case '0': case '1': case '2': case '3': case '4':
90		case '5': case '6': case '7': case '8': case '9':
91			if (nargs != -1)
92				errx(1,
93				    "only one -# argument may be specified");
94			nargs = optopt - '0';
95			break;
96		default:
97			usage();
98		}
99	argc -= optind;
100	argv += optind;
101
102	if (argc < 2)
103		usage();
104
105	/*
106	 * The command to run is argv[0], and the args are argv[1..].
107	 * Look for %digit references in the command, remembering the
108	 * largest one.
109	 */
110	for (n = 0, p = argv[0]; *p != '\0'; ++p)
111		if (p[0] == magic && isdigit(p[1]) && p[1] != '0') {
112			++p;
113			if (p[0] - '0' > n)
114				n = p[0] - '0';
115		}
116
117	/*
118	 * If there were any %digit references, then use those, otherwise
119	 * build a new command string with sufficient %digit references at
120	 * the end to consume (nargs) arguments each time round the loop.
121	 * Allocate enough space to hold the maximum command.
122	 */
123	if ((cmd = malloc(sizeof("exec ") - 1 +
124	    strlen(argv[0]) + 9 * (sizeof(" %1") - 1) + 1)) == NULL)
125		err(1, NULL);
126
127	if (n == 0) {
128		/* If nargs not set, default to a single argument. */
129		if (nargs == -1)
130			nargs = 1;
131
132		p = cmd;
133		p += snprintf(cmd, sizeof(cmd), "exec %s", argv[0]);
134		for (i = 1; i <= nargs; i++)
135			p += snprintf(p, sizeof(p), " %c%d", magic, i);
136
137		/*
138		 * If nargs set to the special value 0, eat a single
139		 * argument for each command execution.
140		 */
141		if (nargs == 0)
142			nargs = 1;
143	} else {
144		(void)snprintf(cmd, sizeof(cmd), "exec %s", argv[0]);
145		nargs = n;
146	}
147
148	/*
149	 * Grab some space in which to build the command.  Allocate
150	 * as necessary later, but no reason to build it up slowly
151	 * for the normal case.
152	 */
153	if ((c = malloc(clen = 1024)) == NULL)
154		err(1, NULL);
155
156	/*
157	 * (argc) and (argv) are still offset by one to make it simpler to
158	 * expand %digit references.  At the end of the loop check for (argc)
159	 * equals 1 means that all the (argv) has been consumed.
160	 */
161	for (rval = 0; argc > nargs; argc -= nargs, argv += nargs) {
162		/*
163		 * Find a max value for the command length, and ensure
164		 * there's enough space to build it.
165		 */
166		for (l = strlen(cmd), i = 0; i < nargs; i++)
167			l += strlen(argv[i+1]);
168		if (l > clen && (c = realloc(c, clen = l)) == NULL)
169			err(1, NULL);
170
171		/* Expand command argv references. */
172		for (p = cmd, q = c; *p != '\0'; ++p)
173			if (p[0] == magic && isdigit(p[1]) && p[1] != '0')
174				q += snprintf(q, sizeof(q), "%s", argv[(++p)[0] - '0']);
175			else
176				*q++ = *p;
177
178		/* Terminate the command string. */
179		*q = '\0';
180
181		/* Run the command. */
182		if (debug)
183			(void)printf("%s\n", c);
184		else
185			if (exec_shell(c))
186				rval = 1;
187	}
188
189	if (argc != 1)
190		errx(1, "expecting additional argument%s after \"%s\"",
191		    (nargs - argc) ? "s" : "", argv[argc - 1]);
192	exit(rval);
193}
194
195/*
196 * exec_shell --
197 * 	Private version of system(3).  Use the user's SHELL environment
198 *	variable as the shell to execute.
199 */
200static int
201exec_shell(const char *command)
202{
203	static char *name;
204	char *tmpshell;
205	pid_t pid;
206	int omask, pstat;
207	sig_t intsave, quitsave;
208	unsigned int okshell = 0;
209
210	if (shell == NULL) {
211		if ((shell = getenv("SHELL")) == NULL)
212			if (strlcpy(shell, _PATH_BSHELL, sizeof(shell)) != strlen(shell))
213				err(1, "strlcpy() failed");
214		if ((name = strrchr(shell, '/')) == NULL) {
215			if (strlcpy(name, shell, sizeof(name)) != strlen(shell))
216				err(1, "strlcpy() failed");
217		} else {
218			++name;
219		}
220	}
221
222	/* Now double-check to make sure the shell is friendly */
223	if (!prespecified)
224		while((tmpshell = getusershell()) != NULL)
225			if (strcmp((const char *)tmpshell, (const char *)shell) == 0)
226				okshell = 1;
227
228	if (!command || !okshell)		/* just checking... */
229		return(1);
230
231	omask = sigblock(sigmask(SIGCHLD));
232	switch(pid = vfork()) {
233	case -1:			/* error */
234		err(1, "vfork");
235	case 0:				/* child */
236		(void)sigsetmask(omask);
237		execl(shell, name, "-c", command, NULL);
238		warn("%s", shell);
239		_exit(1);
240	}
241	intsave = signal(SIGINT, SIG_IGN);
242	quitsave = signal(SIGQUIT, SIG_IGN);
243	pid = waitpid(pid, &pstat, 0);
244	(void)sigsetmask(omask);
245	(void)signal(SIGINT, intsave);
246	(void)signal(SIGQUIT, quitsave);
247	return(pid == -1 ? -1 : pstat);
248}
249
250void
251usage()
252{
253
254	(void)fprintf(stderr,
255	"usage: apply [-a magic] [-d] [-s shell] [-0123456789] command arguments ...\n");
256	exit(1);
257}
258