055bb65ff5fe534a749b16ff1f2056587bc5abfc
[dragonfly.git] / usr.bin / apply / apply.c
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  * @(#)apply.c  8.4 (Berkeley) 4/4/94
37  * $FreeBSD: src/usr.bin/apply/apply.c,v 1.8.2.3 2001/08/01 23:28:04 obrien Exp $
38  * $DragonFly: src/usr.bin/apply/apply.c,v 1.2 2003/06/17 04:29:25 dillon Exp $
39  */
40
41 #include <sys/types.h>
42
43 #include <sys/wait.h>
44
45 #include <ctype.h>
46 #include <err.h>
47 #include <paths.h>
48 #include <signal.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <unistd.h>
53
54 #define EXEC    "exec "
55
56 static int      exec_shell(const char *, char *, char *);
57 static void     usage(void);
58
59 int
60 main(int argc, char *argv[]) {
61         int ch, debug, i, magic, n, nargs, offset, rval;
62         size_t clen, cmdsize, l;
63         char *c, *cmd, *name, *p, *q, *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[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 (p[0] == magic && isdigit(p[1]) && p[1] != '0') {
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         cmdsize = sizeof(EXEC) - 1 + strlen(argv[0])
131             + 9 * (sizeof(" %1") - 1) + 1;
132         if ((cmd = malloc(cmdsize)) == NULL)
133                 err(1, NULL);
134
135         if (n == 0) {
136                 /* If nargs not set, default to a single argument. */
137                 if (nargs == -1)
138                         nargs = 1;
139
140                 p = cmd;
141                 offset = snprintf(cmd, cmdsize, EXEC "%s", argv[0]);
142                 if ((size_t)offset >= cmdsize)
143                         err(1, "snprintf() failed");
144                 p += offset;
145                 cmdsize -= offset;
146                 for (i = 1; i <= nargs; i++) {
147                         offset = snprintf(p, cmdsize, " %c%d", magic, i);
148                         if ((size_t)offset >= cmdsize)
149                                 err(1, "snprintf() failed");
150                         p += offset;
151                         cmdsize -= offset;
152                 }
153
154                 /*
155                  * If nargs set to the special value 0, eat a single
156                  * argument for each command execution.
157                  */
158                 if (nargs == 0)
159                         nargs = 1;
160         } else {
161                 offset = snprintf(cmd, cmdsize, EXEC "%s", argv[0]);
162                 if ((size_t)offset >= cmdsize)
163                         err(1, "snprintf() failed");
164                 nargs = n;
165         }
166
167         /*
168          * Grab some space in which to build the command.  Allocate
169          * as necessary later, but no reason to build it up slowly
170          * for the normal case.
171          */
172         if ((c = malloc(clen = 1024)) == NULL)
173                 err(1, NULL);
174
175         /*
176          * (argc) and (argv) are still offset by one to make it simpler to
177          * expand %digit references.  At the end of the loop check for (argc)
178          * equals 1 means that all the (argv) has been consumed.
179          */
180         for (rval = 0; argc > nargs; argc -= nargs, argv += nargs) {
181                 /*
182                  * Find a max value for the command length, and ensure
183                  * there's enough space to build it.
184                  */
185                 for (l = strlen(cmd), i = 0; i < nargs; i++)
186                         l += strlen(argv[i+1]);
187                 if (l > clen && (c = realloc(c, clen = l)) == NULL)
188                         err(1, NULL);
189
190                 /* Expand command argv references. */
191                 for (p = cmd, q = c; *p != '\0'; ++p)
192                         if (p[0] == magic && isdigit(p[1]) && p[1] != '0') {
193                                 offset = snprintf(q, l, "%s",
194                                     argv[(++p)[0] - '0']);
195                                 if ((size_t)offset >= l)
196                                         err(1, "snprintf() failed");
197                                 q += offset;
198                                 l -= offset;
199                         } else
200                                 *q++ = *p;
201
202                 /* Terminate the command string. */
203                 *q = '\0';
204
205                 /* Run the command. */
206                 if (debug)
207                         (void)printf("%s\n", c);
208                 else
209                         if (exec_shell(c, shell, name))
210                                 rval = 1;
211         }
212
213         if (argc != 1)
214                 errx(1, "expecting additional argument%s after \"%s\"",
215             (nargs - argc) ? "s" : "", argv[argc - 1]);
216         free(cmd);
217         free(c);
218         free(shell);
219         exit(rval);
220 }
221
222 /*
223  * exec_shell --
224  *      Execute a shell command using passed use_shell and use_name
225  *      arguments.
226  */
227 static int
228 exec_shell(const char *command, char *use_shell, char *use_name)
229 {
230         pid_t pid;
231         int omask, pstat;
232         sig_t intsave, quitsave;
233
234         if (!command)           /* just checking... */
235                 return(1);
236
237         omask = sigblock(sigmask(SIGCHLD));
238         switch(pid = vfork()) {
239         case -1:                        /* error */
240                 err(1, "vfork");
241         case 0:                         /* child */
242                 (void)sigsetmask(omask);
243                 execl(use_shell, use_name, "-c", command, (char *)NULL);
244                 warn("%s", use_shell);
245                 _exit(1);
246         }
247         intsave = signal(SIGINT, SIG_IGN);
248         quitsave = signal(SIGQUIT, SIG_IGN);
249         pid = waitpid(pid, &pstat, 0);
250         (void)sigsetmask(omask);
251         (void)signal(SIGINT, intsave);
252         (void)signal(SIGQUIT, quitsave);
253         return(pid == -1 ? -1 : pstat);
254 }
255
256 void
257 usage()
258 {
259
260         (void)fprintf(stderr,
261         "usage: apply [-a magic] [-d] [-0123456789] command arguments ...\n");
262         exit(1);
263 }