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