xref: /openbsd-src/usr.bin/apply/apply.c (revision b2ea75c1b17e1a9a339660e7ed45cd24946b230e)
1 /*	$OpenBSD: apply.c,v 1.9 2001/07/09 07:04:47 deraadt Exp $	*/
2 /*	$NetBSD: apply.c,v 1.3 1995/03/25 03:38:23 glass Exp $	*/
3 
4 /*-
5  * Copyright (c) 1994
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * Jan-Simon Pendry.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. All advertising materials mentioning features or use of this software
20  *    must display the following acknowledgement:
21  *	This product includes software developed by the University of
22  *	California, Berkeley and its contributors.
23  * 4. Neither the name of the University nor the names of its contributors
24  *    may be used to endorse or promote products derived from this software
25  *    without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37  * SUCH DAMAGE.
38  */
39 
40 #ifndef lint
41 #if 0
42 static char sccsid[] = "@(#)apply.c	8.4 (Berkeley) 4/4/94";
43 #else
44 static char rcsid[] = "$OpenBSD: apply.c,v 1.9 2001/07/09 07:04:47 deraadt Exp $";
45 #endif
46 #endif /* not lint */
47 
48 #include <sys/wait.h>
49 
50 #include <ctype.h>
51 #include <err.h>
52 #include <paths.h>
53 #include <signal.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <unistd.h>
58 
59 void	usage __P((void));
60 int	system __P((const char *));
61 
62 int
63 main(argc, argv)
64 	int argc;
65 	char *argv[];
66 {
67 	int ch, clen, debug, i, l, magic, n, nargs, rval;
68 	char *c, *cmd, *p, *q;
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 	 * If there were any %digit references, then use those, otherwise
114 	 * build a new command string with sufficient %digit references at
115 	 * the end to consume (nargs) arguments each time round the loop.
116 	 * Allocate enough space to hold the maximum command.
117 	 */
118 	if ((cmd = malloc(sizeof("exec ") - 1 +
119 	    strlen(argv[0]) + 9 * (sizeof(" %1") - 1) + 1)) == NULL)
120 		err(1, NULL);
121 
122 	if (n == 0) {
123 		/* If nargs not set, default to a single argument. */
124 		if (nargs == -1)
125 			nargs = 1;
126 
127 		p = cmd;
128 		p += sprintf(cmd, "exec %s", argv[0]);
129 		for (i = 1; i <= nargs; i++)
130 			p += sprintf(p, " %c%d", magic, i);
131 
132 		/*
133 		 * If nargs set to the special value 0, eat a single
134 		 * argument for each command execution.
135 		 */
136 		if (nargs == 0)
137 			nargs = 1;
138 	} else {
139 		(void)sprintf(cmd, "exec %s", argv[0]);
140 		nargs = n;
141 	}
142 
143 	/*
144 	 * Grab some space in which to build the command.  Allocate
145 	 * as necessary later, but no reason to build it up slowly
146 	 * for the normal case.
147 	 */
148 	if ((c = malloc(clen = 1024)) == NULL)
149 		err(1, NULL);
150 
151 	/*
152 	 * (argc) and (argv) are still offset by one to make it simpler to
153 	 * expand %digit references.  At the end of the loop check for (argc)
154 	 * equals 1 means that all the (argv) has been consumed.
155 	 */
156 	for (rval = 0; argc > nargs; argc -= nargs, argv += nargs) {
157 		/*
158 		 * Find a max value for the command length, and ensure
159 		 * there's enough space to build it.
160 		 */
161 		for (l = strlen(cmd), i = 0; i < nargs; i++)
162 			l += strlen(argv[i+1]);
163 		if (l > clen && (c = realloc(c, clen = l)) == NULL)
164 			err(1, NULL);
165 
166 		/* Expand command argv references. */
167 		for (p = cmd, q = c; *p != '\0'; ++p)
168 			if (p[0] == magic && isdigit(p[1]) && p[1] != '0')
169 				q += sprintf(q, "%s", argv[(++p)[0] - '0']);
170 			else
171 				*q++ = *p;
172 
173 		/* Terminate the command string. */
174 		*q = '\0';
175 
176 		/* Run the command. */
177 		if (debug)
178 			(void)printf("%s\n", c);
179 		else
180 			if (system(c))
181 				rval = 1;
182 	}
183 
184 	if (argc != 1)
185 		errx(1, "expecting additional argument%s after \"%s\"",
186 		    (nargs - argc) ? "s" : "", argv[argc - 1]);
187 	exit(rval);
188 }
189 
190 /*
191  * system --
192  * 	Private version of system(3).  Use the user's SHELL environment
193  *	variable as the shell to execute.
194  */
195 int
196 system(command)
197 	const char *command;
198 {
199 	static char *name, *shell;
200 	pid_t pid;
201 	int omask, pstat;
202 	sig_t intsave, quitsave;
203 
204 	if (shell == NULL) {
205 		if ((shell = getenv("SHELL")) == NULL)
206 			shell = _PATH_BSHELL;
207 		if ((name = strrchr(shell, '/')) == NULL)
208 			name = shell;
209 		else
210 			++name;
211 	}
212 	if (!command)		/* just checking... */
213 		return(1);
214 
215 	omask = sigblock(sigmask(SIGCHLD));
216 	switch(pid = fork()) {
217 	case -1:			/* error */
218 		err(1, "fork");
219 	case 0:				/* child */
220 		(void)sigsetmask(omask);
221 		execl(shell, name, "-c", command, (char *)NULL);
222 		err(1, "%s", shell);
223 	}
224 	intsave = signal(SIGINT, SIG_IGN);
225 	quitsave = signal(SIGQUIT, SIG_IGN);
226 	pid = waitpid(pid, &pstat, 0);
227 	(void)sigsetmask(omask);
228 	(void)signal(SIGINT, intsave);
229 	(void)signal(SIGQUIT, quitsave);
230 	return(pid == -1 ? -1 : pstat);
231 }
232 
233 void
234 usage()
235 {
236 	(void)fprintf(stderr,
237 	    "usage: apply [-#] [-a magic] [-d] command argument [...]\n");
238 	exit(1);
239 }
240