apply.c revision 79452
11590Srgrimes/*-
21590Srgrimes * Copyright (c) 1994
31590Srgrimes *	The Regents of the University of California.  All rights reserved.
41590Srgrimes *
51590Srgrimes * This code is derived from software contributed to Berkeley by
61590Srgrimes * Jan-Simon Pendry.
71590Srgrimes *
81590Srgrimes * Redistribution and use in source and binary forms, with or without
91590Srgrimes * modification, are permitted provided that the following conditions
101590Srgrimes * are met:
111590Srgrimes * 1. Redistributions of source code must retain the above copyright
121590Srgrimes *    notice, this list of conditions and the following disclaimer.
131590Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
141590Srgrimes *    notice, this list of conditions and the following disclaimer in the
151590Srgrimes *    documentation and/or other materials provided with the distribution.
161590Srgrimes * 3. All advertising materials mentioning features or use of this software
171590Srgrimes *    must display the following acknowledgement:
181590Srgrimes *	This product includes software developed by the University of
191590Srgrimes *	California, Berkeley and its contributors.
201590Srgrimes * 4. Neither the name of the University nor the names of its contributors
211590Srgrimes *    may be used to endorse or promote products derived from this software
221590Srgrimes *    without specific prior written permission.
231590Srgrimes *
241590Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
251590Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
261590Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
271590Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
281590Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
291590Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
301590Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
311590Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
321590Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
331590Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
341590Srgrimes * SUCH DAMAGE.
351590Srgrimes */
361590Srgrimes
371590Srgrimes#ifndef lint
3854113Skris#if 0
3941568Sarchiestatic const char sccsid[] = "@(#)apply.c	8.4 (Berkeley) 4/4/94";
4054113Skris#endif
4154113Skrisstatic const char rcsid[] =
4254113Skris  "$FreeBSD: head/usr.bin/apply/apply.c 79452 2001-07-09 09:24:06Z brian $";
431590Srgrimes#endif /* not lint */
441590Srgrimes
4567189Sbrian#include <sys/types.h>
4667189Sbrian
471590Srgrimes#include <sys/wait.h>
481590Srgrimes
491590Srgrimes#include <ctype.h>
501590Srgrimes#include <err.h>
511590Srgrimes#include <paths.h>
521590Srgrimes#include <signal.h>
531590Srgrimes#include <stdio.h>
541590Srgrimes#include <stdlib.h>
551590Srgrimes#include <string.h>
561590Srgrimes#include <unistd.h>
571590Srgrimes
5871326Swill#define EXEC	"exec "
591590Srgrimes
6071326Swillstatic int	exec_shell(const char *, char *, char *);
6171326Swillstatic void	usage(void);
6270692Swill
631590Srgrimesint
6471326Swillmain(int argc, char *argv[]) {
6571326Swill	int ch, debug, i, magic, n, nargs, offset, rval;
6671326Swill	size_t clen, cmdsize, l;
6771326Swill	char *c, *cmd, *name, *p, *q, *shell, *slashp, *tmpshell;
681590Srgrimes
691590Srgrimes	debug = 0;
701590Srgrimes	magic = '%';		/* Default magic char is `%'. */
711590Srgrimes	nargs = -1;
7270672Swill	while ((ch = getopt(argc, argv, "a:d0123456789")) != -1)
731590Srgrimes		switch (ch) {
741590Srgrimes		case 'a':
751590Srgrimes			if (optarg[1] != '\0')
761590Srgrimes				errx(1,
7754157Scharnier				    "illegal magic character specification");
781590Srgrimes			magic = optarg[0];
791590Srgrimes			break;
801590Srgrimes		case 'd':
811590Srgrimes			debug = 1;
821590Srgrimes			break;
831590Srgrimes		case '0': case '1': case '2': case '3': case '4':
841590Srgrimes		case '5': case '6': case '7': case '8': case '9':
851590Srgrimes			if (nargs != -1)
861590Srgrimes				errx(1,
8754157Scharnier				    "only one -# argument may be specified");
881590Srgrimes			nargs = optopt - '0';
891590Srgrimes			break;
901590Srgrimes		default:
911590Srgrimes			usage();
921590Srgrimes		}
931590Srgrimes	argc -= optind;
941590Srgrimes	argv += optind;
951590Srgrimes
961590Srgrimes	if (argc < 2)
971590Srgrimes		usage();
981590Srgrimes
991590Srgrimes	/*
1001590Srgrimes	 * The command to run is argv[0], and the args are argv[1..].
1011590Srgrimes	 * Look for %digit references in the command, remembering the
1021590Srgrimes	 * largest one.
1031590Srgrimes	 */
1041590Srgrimes	for (n = 0, p = argv[0]; *p != '\0'; ++p)
1051590Srgrimes		if (p[0] == magic && isdigit(p[1]) && p[1] != '0') {
1061590Srgrimes			++p;
1071590Srgrimes			if (p[0] - '0' > n)
1081590Srgrimes				n = p[0] - '0';
1091590Srgrimes		}
1101590Srgrimes
1111590Srgrimes	/*
11270692Swill	 * Figure out the shell and name arguments to pass to execl()
11370692Swill	 * in exec_shell().  Always malloc() shell and just set name
11470692Swill	 * to point at the last part of shell if there are any backslashes,
11570692Swill	 * otherwise just set it to point at the space malloc()'d.  If
11670692Swill	 * SHELL environment variable exists, replace contents of
11770692Swill	 * shell with it.
11870692Swill	 */
11970692Swill	shell = name = NULL;
12070692Swill	tmpshell = getenv("SHELL");
12170692Swill	shell = (tmpshell != NULL) ? strdup(tmpshell) : strdup(_PATH_BSHELL);
12270692Swill	if (shell == NULL)
12370692Swill		err(1, "strdup() failed");
12470692Swill	slashp = strrchr(shell, '/');
12570692Swill	name = (slashp != NULL) ? slashp + 1 : shell;
12670692Swill
12770692Swill	/*
1281590Srgrimes	 * If there were any %digit references, then use those, otherwise
1291590Srgrimes	 * build a new command string with sufficient %digit references at
1301590Srgrimes	 * the end to consume (nargs) arguments each time round the loop.
13170692Swill	 * Allocate enough space to hold the maximum command.  Save the
13270692Swill	 * size to pass to snprintf().
1331590Srgrimes	 */
13471326Swill	cmdsize = sizeof(EXEC) - 1 + strlen(argv[0])
13571326Swill	    + 9 * (sizeof(" %1") - 1) + 1;
13670692Swill	if ((cmd = malloc(cmdsize)) == NULL)
1371590Srgrimes		err(1, NULL);
1388874Srgrimes
1391590Srgrimes	if (n == 0) {
1401590Srgrimes		/* If nargs not set, default to a single argument. */
1411590Srgrimes		if (nargs == -1)
1421590Srgrimes			nargs = 1;
1431590Srgrimes
1441590Srgrimes		p = cmd;
14570692Swill		offset = snprintf(cmd, cmdsize, EXEC "%s", argv[0]);
14670692Swill		if ((size_t)offset >= cmdsize)
14770692Swill			err(1, "snprintf() failed");
14870692Swill		p += offset;
14971615Swill		cmdsize -= offset;
15070692Swill		for (i = 1; i <= nargs; i++) {
15170692Swill			offset = snprintf(p, cmdsize, " %c%d", magic, i);
15270692Swill			if ((size_t)offset >= cmdsize)
15370692Swill				err(1, "snprintf() failed");
15470692Swill			p += offset;
15571615Swill			cmdsize -= offset;
15670692Swill		}
1571590Srgrimes
1581590Srgrimes		/*
1591590Srgrimes		 * If nargs set to the special value 0, eat a single
1601590Srgrimes		 * argument for each command execution.
1611590Srgrimes		 */
1621590Srgrimes		if (nargs == 0)
1631590Srgrimes			nargs = 1;
1641590Srgrimes	} else {
16570692Swill		offset = snprintf(cmd, cmdsize, EXEC "%s", argv[0]);
16670692Swill		if ((size_t)offset >= cmdsize)
16770692Swill			err(1, "snprintf() failed");
1681590Srgrimes		nargs = n;
1691590Srgrimes	}
1701590Srgrimes
1711590Srgrimes	/*
1721590Srgrimes	 * Grab some space in which to build the command.  Allocate
1731590Srgrimes	 * as necessary later, but no reason to build it up slowly
1741590Srgrimes	 * for the normal case.
1751590Srgrimes	 */
1761590Srgrimes	if ((c = malloc(clen = 1024)) == NULL)
1771590Srgrimes		err(1, NULL);
1781590Srgrimes
1791590Srgrimes	/*
1801590Srgrimes	 * (argc) and (argv) are still offset by one to make it simpler to
1811590Srgrimes	 * expand %digit references.  At the end of the loop check for (argc)
1821590Srgrimes	 * equals 1 means that all the (argv) has been consumed.
1831590Srgrimes	 */
1841590Srgrimes	for (rval = 0; argc > nargs; argc -= nargs, argv += nargs) {
1851590Srgrimes		/*
1861590Srgrimes		 * Find a max value for the command length, and ensure
1871590Srgrimes		 * there's enough space to build it.
1881590Srgrimes		 */
1891590Srgrimes		for (l = strlen(cmd), i = 0; i < nargs; i++)
19054113Skris			l += strlen(argv[i+1]);
1911590Srgrimes		if (l > clen && (c = realloc(c, clen = l)) == NULL)
1921590Srgrimes			err(1, NULL);
1931590Srgrimes
1941590Srgrimes		/* Expand command argv references. */
1951590Srgrimes		for (p = cmd, q = c; *p != '\0'; ++p)
19670692Swill			if (p[0] == magic && isdigit(p[1]) && p[1] != '0') {
19770692Swill				offset = snprintf(q, l, "%s",
19870692Swill				    argv[(++p)[0] - '0']);
19970692Swill				if ((size_t)offset >= l)
20070692Swill					err(1, "snprintf() failed");
20170692Swill				q += offset;
20271615Swill				l -= offset;
20370692Swill			} else
2041590Srgrimes				*q++ = *p;
2051590Srgrimes
2061590Srgrimes		/* Terminate the command string. */
2071590Srgrimes		*q = '\0';
2081590Srgrimes
2091590Srgrimes		/* Run the command. */
2101590Srgrimes		if (debug)
2111590Srgrimes			(void)printf("%s\n", c);
2121590Srgrimes		else
21371326Swill			if (exec_shell(c, shell, name))
2141590Srgrimes				rval = 1;
2151590Srgrimes	}
2161590Srgrimes
2171590Srgrimes	if (argc != 1)
2181590Srgrimes		errx(1, "expecting additional argument%s after \"%s\"",
21970692Swill	    (nargs - argc) ? "s" : "", argv[argc - 1]);
22070692Swill	free(cmd);
22170692Swill	free(c);
22270692Swill	free(shell);
2231590Srgrimes	exit(rval);
2241590Srgrimes}
2251590Srgrimes
2261590Srgrimes/*
22770692Swill * exec_shell --
22870692Swill * 	Execute a shell command using passed use_shell and use_name
22970692Swill * 	arguments.
2301590Srgrimes */
23170692Swillstatic int
23271326Swillexec_shell(const char *command, char *use_shell, char *use_name)
2331590Srgrimes{
2341590Srgrimes	pid_t pid;
23543928Seivind	int omask, pstat;
2361590Srgrimes	sig_t intsave, quitsave;
2371590Srgrimes
23870672Swill	if (!command)		/* just checking... */
2391590Srgrimes		return(1);
2401590Srgrimes
2411590Srgrimes	omask = sigblock(sigmask(SIGCHLD));
24260706Skris	switch(pid = vfork()) {
2431590Srgrimes	case -1:			/* error */
24460706Skris		err(1, "vfork");
2451590Srgrimes	case 0:				/* child */
2461590Srgrimes		(void)sigsetmask(omask);
24779452Sbrian		execl(use_shell, use_name, "-c", command, (char *)NULL);
24870692Swill		warn("%s", use_shell);
24960706Skris		_exit(1);
2501590Srgrimes	}
2511590Srgrimes	intsave = signal(SIGINT, SIG_IGN);
2521590Srgrimes	quitsave = signal(SIGQUIT, SIG_IGN);
25343928Seivind	pid = waitpid(pid, &pstat, 0);
2541590Srgrimes	(void)sigsetmask(omask);
2551590Srgrimes	(void)signal(SIGINT, intsave);
2561590Srgrimes	(void)signal(SIGQUIT, quitsave);
25743928Seivind	return(pid == -1 ? -1 : pstat);
2581590Srgrimes}
2591590Srgrimes
2601590Srgrimesvoid
2611590Srgrimesusage()
2621590Srgrimes{
2631590Srgrimes
2641590Srgrimes	(void)fprintf(stderr,
26570672Swill	"usage: apply [-a magic] [-d] [-0123456789] command arguments ...\n");
2661590Srgrimes	exit(1);
2671590Srgrimes}
268