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