xref: /netbsd-src/usr.bin/apply/apply.c (revision ae9172d6cd9432a6a1a56760d86b32c57a66c39c)
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  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 
37 #ifndef lint
38 /*static char sccsid[] = "@(#)apply.c	8.4 (Berkeley) 4/4/94";*/
39 static char rcsid[] = "$Id: apply.c,v 1.2 1994/09/21 03:17:36 glass Exp $";
40 #endif /* not lint */
41 
42 #include <sys/wait.h>
43 
44 #include <ctype.h>
45 #include <err.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 void	usage __P((void));
54 int	system __P((const char *));
55 
56 int
57 main(argc, argv)
58 	int argc;
59 	char *argv[];
60 {
61 	int ch, clen, debug, i, l, magic, n, nargs, rval;
62 	char *c, *cmd, *p, *q;
63 
64 	debug = 0;
65 	magic = '%';		/* Default magic char is `%'. */
66 	nargs = -1;
67 	while ((ch = getopt(argc, argv, "a:d0123456789")) != EOF)
68 		switch (ch) {
69 		case 'a':
70 			if (optarg[1] != '\0')
71 				errx(1,
72 				    "illegal magic character specification.");
73 			magic = optarg[0];
74 			break;
75 		case 'd':
76 			debug = 1;
77 			break;
78 		case '0': case '1': case '2': case '3': case '4':
79 		case '5': case '6': case '7': case '8': case '9':
80 			if (nargs != -1)
81 				errx(1,
82 				    "only one -# argument may be specified.");
83 			nargs = optopt - '0';
84 			break;
85 		default:
86 			usage();
87 		}
88 	argc -= optind;
89 	argv += optind;
90 
91 	if (argc < 2)
92 		usage();
93 
94 	/*
95 	 * The command to run is argv[0], and the args are argv[1..].
96 	 * Look for %digit references in the command, remembering the
97 	 * largest one.
98 	 */
99 	for (n = 0, p = argv[0]; *p != '\0'; ++p)
100 		if (p[0] == magic && isdigit(p[1]) && p[1] != '0') {
101 			++p;
102 			if (p[0] - '0' > n)
103 				n = p[0] - '0';
104 		}
105 
106 	/*
107 	 * If there were any %digit references, then use those, otherwise
108 	 * build a new command string with sufficient %digit references at
109 	 * the end to consume (nargs) arguments each time round the loop.
110 	 * Allocate enough space to hold the maximum command.
111 	 */
112 	if ((cmd = malloc(sizeof("exec ") - 1 +
113 	    strlen(argv[0]) + 9 * (sizeof(" %1") - 1) + 1)) == NULL)
114 		err(1, NULL);
115 
116 	if (n == 0) {
117 		/* If nargs not set, default to a single argument. */
118 		if (nargs == -1)
119 			nargs = 1;
120 
121 		p = cmd;
122 		p += sprintf(cmd, "exec %s", argv[0]);
123 		for (i = 1; i <= nargs; i++)
124 			p += sprintf(p, " %c%d", magic, i);
125 
126 		/*
127 		 * If nargs set to the special value 0, eat a single
128 		 * argument for each command execution.
129 		 */
130 		if (nargs == 0)
131 			nargs = 1;
132 	} else {
133 		(void)sprintf(cmd, "exec %s", argv[0]);
134 		nargs = n;
135 	}
136 
137 	/*
138 	 * Grab some space in which to build the command.  Allocate
139 	 * as necessary later, but no reason to build it up slowly
140 	 * for the normal case.
141 	 */
142 	if ((c = malloc(clen = 1024)) == NULL)
143 		err(1, NULL);
144 
145 	/*
146 	 * (argc) and (argv) are still offset by one to make it simpler to
147 	 * expand %digit references.  At the end of the loop check for (argc)
148 	 * equals 1 means that all the (argv) has been consumed.
149 	 */
150 	for (rval = 0; argc > nargs; argc -= nargs, argv += nargs) {
151 		/*
152 		 * Find a max value for the command length, and ensure
153 		 * there's enough space to build it.
154 		 */
155 		for (l = strlen(cmd), i = 0; i < nargs; i++)
156 			l += strlen(argv[i]);
157 		if (l > clen && (c = realloc(c, clen = l)) == NULL)
158 			err(1, NULL);
159 
160 		/* Expand command argv references. */
161 		for (p = cmd, q = c; *p != '\0'; ++p)
162 			if (p[0] == magic && isdigit(p[1]) && p[1] != '0')
163 				q += sprintf(q, "%s", argv[(++p)[0] - '0']);
164 			else
165 				*q++ = *p;
166 
167 		/* Terminate the command string. */
168 		*q = '\0';
169 
170 		/* Run the command. */
171 		if (debug)
172 			(void)printf("%s\n", c);
173 		else
174 			if (system(c))
175 				rval = 1;
176 	}
177 
178 	if (argc != 1)
179 		errx(1, "expecting additional argument%s after \"%s\"",
180 		    (nargs - argc) ? "s" : "", argv[argc - 1]);
181 	exit(rval);
182 }
183 
184 /*
185  * system --
186  * 	Private version of system(3).  Use the user's SHELL environment
187  *	variable as the shell to execute.
188  */
189 int
190 system(command)
191 	const char *command;
192 {
193 	static char *name, *shell;
194 	union wait pstat;
195 	pid_t pid;
196 	int omask;
197 	sig_t intsave, quitsave;
198 
199 	if (shell == NULL) {
200 		if ((shell = getenv("SHELL")) == NULL)
201 			shell = _PATH_BSHELL;
202 		if ((name = strrchr(shell, '/')) == NULL)
203 			name = shell;
204 		else
205 			++name;
206 	}
207 	if (!command)		/* just checking... */
208 		return(1);
209 
210 	omask = sigblock(sigmask(SIGCHLD));
211 	switch(pid = vfork()) {
212 	case -1:			/* error */
213 		err(1, "fork");
214 	case 0:				/* child */
215 		(void)sigsetmask(omask);
216 		execl(shell, name, "-c", command, NULL);
217 		err(1, "%s", shell);
218 	}
219 	intsave = signal(SIGINT, SIG_IGN);
220 	quitsave = signal(SIGQUIT, SIG_IGN);
221 	pid = waitpid(pid, (int *)&pstat, 0);
222 	(void)sigsetmask(omask);
223 	(void)signal(SIGINT, intsave);
224 	(void)signal(SIGQUIT, quitsave);
225 	return(pid == -1 ? -1 : pstat.w_status);
226 }
227 
228 void
229 usage()
230 {
231 
232 	(void)fprintf(stderr,
233 	    "usage: apply [-a magic] [-0123456789] command arguments ...\n");
234 	exit(1);
235 }
236