xref: /dragonfly/usr.bin/apply/apply.c (revision 733c7039)
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. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  * @(#)apply.c	8.4 (Berkeley) 4/4/94
33  * $FreeBSD: src/usr.bin/apply/apply.c,v 1.8.2.3 2001/08/01 23:28:04 obrien Exp $
34  */
35 
36 #include <sys/types.h>
37 
38 #include <sys/wait.h>
39 
40 #include <ctype.h>
41 #include <err.h>
42 #include <paths.h>
43 #include <signal.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <unistd.h>
48 
49 #define EXEC	"exec "
50 
51 static int	exec_shell(const char *, const char *, const char *);
52 static void	usage(void);
53 
54 int
55 main(int argc, char *argv[])
56 {
57 	int ch, debug, i, magic, n, nargs, offset, rval;
58 	size_t clen, cmdsize, l;
59 	char *c, *cmd, *name, *p, *q, *shell, *slashp, *tmpshell;
60 
61 	debug = 0;
62 	magic = '%';		/* Default magic char is `%'. */
63 	nargs = -1;
64 	while ((ch = getopt(argc, argv, "a:d0123456789")) != -1)
65 		switch (ch) {
66 		case 'a':
67 			if (optarg[1] != '\0')
68 				errx(1,
69 				    "illegal magic character specification");
70 			magic = optarg[0];
71 			break;
72 		case 'd':
73 			debug = 1;
74 			break;
75 		case '0': case '1': case '2': case '3': case '4':
76 		case '5': case '6': case '7': case '8': case '9':
77 			if (nargs != -1)
78 				errx(1,
79 				    "only one -# argument may be specified");
80 			nargs = optopt - '0';
81 			break;
82 		default:
83 			usage();
84 		}
85 	argc -= optind;
86 	argv += optind;
87 
88 	if (argc < 2)
89 		usage();
90 
91 	/*
92 	 * The command to run is argv[0], and the args are argv[1..].
93 	 * Look for %digit references in the command, remembering the
94 	 * largest one.
95 	 */
96 	for (n = 0, p = argv[0]; *p != '\0'; ++p)
97 		if (p[0] == magic && isdigit(p[1]) && p[1] != '0') {
98 			++p;
99 			if (p[0] - '0' > n)
100 				n = p[0] - '0';
101 		}
102 
103 	/*
104 	 * Figure out the shell and name arguments to pass to execl()
105 	 * in exec_shell().  Always malloc() shell and just set name
106 	 * to point at the last part of shell if there are any backslashes,
107 	 * otherwise just set it to point at the space malloc()'d.  If
108 	 * SHELL environment variable exists, replace contents of
109 	 * shell with it.
110 	 */
111 	shell = name = NULL;
112 	tmpshell = getenv("SHELL");
113 	shell = (tmpshell != NULL) ? strdup(tmpshell) : strdup(_PATH_BSHELL);
114 	if (shell == NULL)
115 		err(1, "strdup() failed");
116 	slashp = strrchr(shell, '/');
117 	name = (slashp != NULL) ? slashp + 1 : shell;
118 
119 	/*
120 	 * If there were any %digit references, then use those, otherwise
121 	 * build a new command string with sufficient %digit references at
122 	 * the end to consume (nargs) arguments each time round the loop.
123 	 * Allocate enough space to hold the maximum command.  Save the
124 	 * size to pass to snprintf().
125 	 */
126 	cmdsize = sizeof(EXEC) - 1 + strlen(argv[0])
127 	    + 9 * (sizeof(" %1") - 1) + 1;
128 	if ((cmd = malloc(cmdsize)) == NULL)
129 		err(1, NULL);
130 
131 	if (n == 0) {
132 		/* If nargs not set, default to a single argument. */
133 		if (nargs == -1)
134 			nargs = 1;
135 
136 		p = cmd;
137 		offset = snprintf(cmd, cmdsize, EXEC "%s", argv[0]);
138 		if ((size_t)offset >= cmdsize)
139 			err(1, "snprintf() failed");
140 		p += offset;
141 		cmdsize -= offset;
142 		for (i = 1; i <= nargs; i++) {
143 			offset = snprintf(p, cmdsize, " %c%d", magic, i);
144 			if ((size_t)offset >= cmdsize)
145 				err(1, "snprintf() failed");
146 			p += offset;
147 			cmdsize -= offset;
148 		}
149 
150 		/*
151 		 * If nargs set to the special value 0, eat a single
152 		 * argument for each command execution.
153 		 */
154 		if (nargs == 0)
155 			nargs = 1;
156 	} else {
157 		offset = snprintf(cmd, cmdsize, EXEC "%s", argv[0]);
158 		if ((size_t)offset >= cmdsize)
159 			err(1, "snprintf() failed");
160 		nargs = n;
161 	}
162 
163 	/*
164 	 * Grab some space in which to build the command.  Allocate
165 	 * as necessary later, but no reason to build it up slowly
166 	 * for the normal case.
167 	 */
168 	if ((c = malloc(clen = 1024)) == NULL)
169 		err(1, NULL);
170 
171 	/*
172 	 * (argc) and (argv) are still offset by one to make it simpler to
173 	 * expand %digit references.  At the end of the loop check for (argc)
174 	 * equals 1 means that all the (argv) has been consumed.
175 	 */
176 	for (rval = 0; argc > nargs; argc -= nargs, argv += nargs) {
177 		/*
178 		 * Find a max value for the command length, and ensure
179 		 * there's enough space to build it.
180 		 */
181 		for (l = strlen(cmd), i = 0; i < nargs; i++)
182 			l += strlen(argv[i+1]);
183 		if (l > clen && (c = realloc(c, clen = l)) == NULL)
184 			err(1, NULL);
185 
186 		/* Expand command argv references. */
187 		for (p = cmd, q = c; *p != '\0'; ++p) {
188 			if (p[0] == magic && isdigit(p[1]) && p[1] != '0') {
189 				offset = snprintf(q, l, "%s",
190 				    argv[(++p)[0] - '0']);
191 				if ((size_t)offset >= l)
192 					err(1, "snprintf() failed");
193 				q += offset;
194 				l -= offset;
195 			} else {
196 				*q++ = *p;
197 			}
198 		}
199 
200 		/* Terminate the command string. */
201 		*q = '\0';
202 
203 		/* Run the command. */
204 		if (debug) {
205 			printf("%s\n", c);
206 		} else {
207 			if (exec_shell(c, shell, name))
208 				rval = 1;
209 		}
210 	}
211 
212 	if (argc != 1)
213 		errx(1, "expecting additional argument%s after \"%s\"",
214 	    (nargs - argc) ? "s" : "", argv[argc - 1]);
215 	free(cmd);
216 	free(c);
217 	free(shell);
218 	exit(rval);
219 }
220 
221 /*
222  * exec_shell --
223  * 	Execute a shell command using passed use_shell and use_name
224  * 	arguments.
225  */
226 static int
227 exec_shell(const char *command, const char *use_shell, const char *use_name)
228 {
229 	pid_t pid;
230 	int omask, pstat;
231 	sig_t intsave, quitsave;
232 
233 	if (command == NULL)		/* just checking... */
234 		return(1);
235 
236 	omask = sigblock(sigmask(SIGCHLD));
237 	switch(pid = vfork()) {
238 	case -1:			/* error */
239 		err(1, "vfork");
240 	case 0:				/* child */
241 		(void)sigsetmask(omask);
242 		execl(use_shell, use_name, "-c", command, NULL);
243 		warn("%s", use_shell);
244 		_exit(1);
245 	}
246 	intsave = signal(SIGINT, SIG_IGN);
247 	quitsave = signal(SIGQUIT, SIG_IGN);
248 	pid = waitpid(pid, &pstat, 0);
249 	sigsetmask(omask);
250 	signal(SIGINT, intsave);
251 	signal(SIGQUIT, quitsave);
252 	return(pid == -1 ? -1 : pstat);
253 }
254 
255 static void
256 usage(void)
257 {
258 	fprintf(stderr,
259 	    "usage: apply [-a magic] [-d] [-0123456789] "
260 	    "command arguments ...\n");
261 	exit(1);
262 }
263