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