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