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