xref: /netbsd-src/usr.bin/apply/apply.c (revision 23c8222edbfb0f0932d88a8351d3a0cf817dfb9e)
1 /*	$NetBSD: apply.c,v 1.13 2004/01/05 23:23:34 jmmv Exp $	*/
2 
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/cdefs.h>
36 #ifndef lint
37 #if 0
38 static char sccsid[] = "@(#)apply.c	8.4 (Berkeley) 4/4/94";
39 #else
40 __RCSID("$NetBSD: apply.c,v 1.13 2004/01/05 23:23:34 jmmv Exp $");
41 #endif
42 #endif /* not lint */
43 
44 #include <sys/wait.h>
45 
46 #include <ctype.h>
47 #include <err.h>
48 #include <paths.h>
49 #include <signal.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <unistd.h>
54 
55 int	main __P((int, char **));
56 void	usage __P((void));
57 int	shell_system __P((const char *));
58 
59 int
60 main(argc, argv)
61 	int argc;
62 	char *argv[];
63 {
64 	int ch, clen, debug, i, l, magic, n, nargs, rval;
65 	char *c, *cmd, *p, *q, *nc;
66 
67 	debug = 0;
68 	magic = '%';		/* Default magic char is `%'. */
69 	nargs = -1;
70 	while ((ch = getopt(argc, argv, "a:d0123456789")) != -1)
71 		switch (ch) {
72 		case 'a':
73 			if (optarg[1] != '\0')
74 				errx(1,
75 				    "illegal magic character specification.");
76 			magic = optarg[0];
77 			break;
78 		case 'd':
79 			debug = 1;
80 			break;
81 		case '0': case '1': case '2': case '3': case '4':
82 		case '5': case '6': case '7': case '8': case '9':
83 			if (nargs != -1)
84 				errx(1,
85 				    "only one -# argument may be specified.");
86 			nargs = optopt - '0';
87 			break;
88 		default:
89 			usage();
90 		}
91 	argc -= optind;
92 	argv += optind;
93 
94 	if (argc < 2)
95 		usage();
96 
97 	/*
98 	 * The command to run is argv[0], and the args are argv[1..].
99 	 * Look for %digit references in the command, remembering the
100 	 * largest one.
101 	 */
102 	for (n = 0, p = argv[0]; *p != '\0'; ++p)
103 		if (p[0] == magic && isdigit((unsigned char)p[1]) &&
104 		    p[1] != '0') {
105 			++p;
106 			if (p[0] - '0' > n)
107 				n = p[0] - '0';
108 		}
109 
110 	/*
111 	 * If there were any %digit references, then use those, otherwise
112 	 * build a new command string with sufficient %digit references at
113 	 * the end to consume (nargs) arguments each time round the loop.
114 	 * Allocate enough space to hold the maximum command.
115 	 */
116 	if ((cmd = malloc(sizeof("exec ") - 1 +
117 	    strlen(argv[0]) + 9 * (sizeof(" %1") - 1) + 1)) == NULL)
118 		err(1, "malloc");
119 
120 	if (n == 0) {
121 		/* If nargs not set, default to a single argument. */
122 		if (nargs == -1)
123 			nargs = 1;
124 
125 		p = cmd;
126 		p += sprintf(cmd, "exec %s", argv[0]);
127 		for (i = 1; i <= nargs; i++)
128 			p += sprintf(p, " %c%d", magic, i);
129 
130 		/*
131 		 * If nargs set to the special value 0, eat a single
132 		 * argument for each command execution.
133 		 */
134 		if (nargs == 0)
135 			nargs = 1;
136 	} else {
137 		(void)sprintf(cmd, "exec %s", argv[0]);
138 		nargs = n;
139 	}
140 
141 	/*
142 	 * Grab some space in which to build the command.  Allocate
143 	 * as necessary later, but no reason to build it up slowly
144 	 * for the normal case.
145 	 */
146 	if ((c = malloc(clen = 1024)) == NULL)
147 		err(1, "malloc");
148 
149 	/*
150 	 * (argc) and (argv) are still offset by one to make it simpler to
151 	 * expand %digit references.  At the end of the loop check for (argc)
152 	 * equals 1 means that all the (argv) has been consumed.
153 	 */
154 	for (rval = 0; argc > nargs; argc -= nargs, argv += nargs) {
155 		/*
156 		 * Find a max value for the command length, and ensure
157 		 * there's enough space to build it.
158 		 */
159 		for (l = strlen(cmd), i = 0; i < nargs; i++)
160 			l += strlen(argv[i+1]);
161 		if (l > clen) {
162 			nc = realloc(c, l);
163 			if (nc == NULL)
164 				err(1, "malloc");
165 			c = nc;
166 			clen = l;
167 		}
168 
169 		/* Expand command argv references. */
170 		for (p = cmd, q = c; *p != '\0'; ++p)
171 			if (p[0] == magic && isdigit((unsigned char)p[1]) &&
172 			    p[1] != '0')
173 				q += sprintf(q, "%s", argv[(++p)[0] - '0']);
174 			else
175 				*q++ = *p;
176 
177 		/* Terminate the command string. */
178 		*q = '\0';
179 
180 		/* Run the command. */
181 		if (debug)
182 			(void)printf("%s\n", c);
183 		else
184 			if (shell_system(c))
185 				rval = 1;
186 	}
187 
188 	if (argc != 1)
189 		errx(1, "expecting additional argument%s after \"%s\"",
190 		    (nargs - argc) ? "s" : "", argv[argc - 1]);
191 	exit(rval);
192 }
193 
194 /*
195  * shell_system --
196  * 	Private version of system(3).  Use the user's SHELL environment
197  *	variable as the shell to execute.
198  */
199 int
200 shell_system(command)
201 	const char *command;
202 {
203 	static char *name, *shell;
204 	int status;
205 	pid_t pid;
206 	int omask;
207 	sig_t intsave, quitsave;
208 
209 	if (shell == NULL) {
210 		if ((shell = getenv("SHELL")) == NULL)
211 			shell = _PATH_BSHELL;
212 		if ((name = strrchr(shell, '/')) == NULL)
213 			name = shell;
214 		else
215 			++name;
216 	}
217 	if (!command)		/* just checking... */
218 		return(1);
219 
220 	omask = sigblock(sigmask(SIGCHLD));
221 	switch(pid = vfork()) {
222 	case -1:			/* error */
223 		err(1, "vfork");
224 	case 0:				/* child */
225 		(void)sigsetmask(omask);
226 		execl(shell, name, "-c", command, NULL);
227 		warn("%s", shell);
228 		_exit(1);
229 	}
230 	intsave = signal(SIGINT, SIG_IGN);
231 	quitsave = signal(SIGQUIT, SIG_IGN);
232 	pid = waitpid(pid, &status, 0);
233 	(void)sigsetmask(omask);
234 	(void)signal(SIGINT, intsave);
235 	(void)signal(SIGQUIT, quitsave);
236 	return(pid == -1 ? -1 : status);
237 }
238 
239 void
240 usage()
241 {
242 
243 	(void)fprintf(stderr,
244 	    "usage: %s [-a magic] [-0123456789] command arguments ...\n",
245 	    getprogname());
246 	exit(1);
247 }
248