apply.c revision 87231
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
3787231Smarkm#include <sys/cdefs.h>
3887231Smarkm
3987231Smarkm__FBSDID("$FreeBSD: head/usr.bin/apply/apply.c 87231 2001-12-02 20:40:22Z markm $");
4087231Smarkm
411590Srgrimes#ifndef lint
4241568Sarchiestatic const char sccsid[] = "@(#)apply.c	8.4 (Berkeley) 4/4/94";
4354113Skris#endif
441590Srgrimes
4567189Sbrian#include <sys/types.h>
461590Srgrimes#include <sys/wait.h>
471590Srgrimes
481590Srgrimes#include <ctype.h>
491590Srgrimes#include <err.h>
501590Srgrimes#include <paths.h>
511590Srgrimes#include <signal.h>
521590Srgrimes#include <stdio.h>
531590Srgrimes#include <stdlib.h>
541590Srgrimes#include <string.h>
551590Srgrimes#include <unistd.h>
561590Srgrimes
5771326Swill#define EXEC	"exec "
581590Srgrimes
5971326Swillstatic int	exec_shell(const char *, char *, char *);
6071326Swillstatic void	usage(void);
6170692Swill
621590Srgrimesint
6371326Swillmain(int argc, char *argv[]) {
6471326Swill	int ch, debug, i, magic, n, nargs, offset, rval;
6571326Swill	size_t clen, cmdsize, l;
6671326Swill	char *c, *cmd, *name, *p, *q, *shell, *slashp, *tmpshell;
671590Srgrimes
681590Srgrimes	debug = 0;
691590Srgrimes	magic = '%';		/* Default magic char is `%'. */
701590Srgrimes	nargs = -1;
7170672Swill	while ((ch = getopt(argc, argv, "a:d0123456789")) != -1)
721590Srgrimes		switch (ch) {
731590Srgrimes		case 'a':
741590Srgrimes			if (optarg[1] != '\0')
751590Srgrimes				errx(1,
7654157Scharnier				    "illegal magic character specification");
771590Srgrimes			magic = optarg[0];
781590Srgrimes			break;
791590Srgrimes		case 'd':
801590Srgrimes			debug = 1;
811590Srgrimes			break;
821590Srgrimes		case '0': case '1': case '2': case '3': case '4':
831590Srgrimes		case '5': case '6': case '7': case '8': case '9':
841590Srgrimes			if (nargs != -1)
851590Srgrimes				errx(1,
8654157Scharnier				    "only one -# argument may be specified");
871590Srgrimes			nargs = optopt - '0';
881590Srgrimes			break;
891590Srgrimes		default:
901590Srgrimes			usage();
911590Srgrimes		}
921590Srgrimes	argc -= optind;
931590Srgrimes	argv += optind;
941590Srgrimes
951590Srgrimes	if (argc < 2)
961590Srgrimes		usage();
971590Srgrimes
981590Srgrimes	/*
991590Srgrimes	 * The command to run is argv[0], and the args are argv[1..].
1001590Srgrimes	 * Look for %digit references in the command, remembering the
1011590Srgrimes	 * largest one.
1021590Srgrimes	 */
1031590Srgrimes	for (n = 0, p = argv[0]; *p != '\0'; ++p)
1041590Srgrimes		if (p[0] == magic && isdigit(p[1]) && p[1] != '0') {
1051590Srgrimes			++p;
1061590Srgrimes			if (p[0] - '0' > n)
1071590Srgrimes				n = p[0] - '0';
1081590Srgrimes		}
1091590Srgrimes
1101590Srgrimes	/*
11170692Swill	 * Figure out the shell and name arguments to pass to execl()
11270692Swill	 * in exec_shell().  Always malloc() shell and just set name
11370692Swill	 * to point at the last part of shell if there are any backslashes,
11470692Swill	 * otherwise just set it to point at the space malloc()'d.  If
11570692Swill	 * SHELL environment variable exists, replace contents of
11670692Swill	 * shell with it.
11770692Swill	 */
11870692Swill	shell = name = NULL;
11970692Swill	tmpshell = getenv("SHELL");
12070692Swill	shell = (tmpshell != NULL) ? strdup(tmpshell) : strdup(_PATH_BSHELL);
12170692Swill	if (shell == NULL)
12270692Swill		err(1, "strdup() failed");
12370692Swill	slashp = strrchr(shell, '/');
12470692Swill	name = (slashp != NULL) ? slashp + 1 : shell;
12570692Swill
12670692Swill	/*
1271590Srgrimes	 * If there were any %digit references, then use those, otherwise
1281590Srgrimes	 * build a new command string with sufficient %digit references at
1291590Srgrimes	 * the end to consume (nargs) arguments each time round the loop.
13070692Swill	 * Allocate enough space to hold the maximum command.  Save the
13170692Swill	 * size to pass to snprintf().
1321590Srgrimes	 */
13371326Swill	cmdsize = sizeof(EXEC) - 1 + strlen(argv[0])
13471326Swill	    + 9 * (sizeof(" %1") - 1) + 1;
13570692Swill	if ((cmd = malloc(cmdsize)) == NULL)
1361590Srgrimes		err(1, NULL);
1378874Srgrimes
1381590Srgrimes	if (n == 0) {
1391590Srgrimes		/* If nargs not set, default to a single argument. */
1401590Srgrimes		if (nargs == -1)
1411590Srgrimes			nargs = 1;
1421590Srgrimes
1431590Srgrimes		p = cmd;
14470692Swill		offset = snprintf(cmd, cmdsize, EXEC "%s", argv[0]);
14582057Sbrian		if ((size_t)offset >= cmdsize)
14670692Swill			err(1, "snprintf() failed");
14770692Swill		p += offset;
14871615Swill		cmdsize -= offset;
14970692Swill		for (i = 1; i <= nargs; i++) {
15070692Swill			offset = snprintf(p, cmdsize, " %c%d", magic, i);
15182057Sbrian			if ((size_t)offset >= cmdsize)
15270692Swill				err(1, "snprintf() failed");
15370692Swill			p += offset;
15471615Swill			cmdsize -= offset;
15570692Swill		}
1561590Srgrimes
1571590Srgrimes		/*
1581590Srgrimes		 * If nargs set to the special value 0, eat a single
1591590Srgrimes		 * argument for each command execution.
1601590Srgrimes		 */
1611590Srgrimes		if (nargs == 0)
1621590Srgrimes			nargs = 1;
1631590Srgrimes	} else {
16470692Swill		offset = snprintf(cmd, cmdsize, EXEC "%s", argv[0]);
16582057Sbrian		if ((size_t)offset >= cmdsize)
16670692Swill			err(1, "snprintf() failed");
1671590Srgrimes		nargs = n;
1681590Srgrimes	}
1691590Srgrimes
1701590Srgrimes	/*
1711590Srgrimes	 * Grab some space in which to build the command.  Allocate
1721590Srgrimes	 * as necessary later, but no reason to build it up slowly
1731590Srgrimes	 * for the normal case.
1741590Srgrimes	 */
1751590Srgrimes	if ((c = malloc(clen = 1024)) == NULL)
1761590Srgrimes		err(1, NULL);
1771590Srgrimes
1781590Srgrimes	/*
1791590Srgrimes	 * (argc) and (argv) are still offset by one to make it simpler to
1801590Srgrimes	 * expand %digit references.  At the end of the loop check for (argc)
1811590Srgrimes	 * equals 1 means that all the (argv) has been consumed.
1821590Srgrimes	 */
1831590Srgrimes	for (rval = 0; argc > nargs; argc -= nargs, argv += nargs) {
1841590Srgrimes		/*
1851590Srgrimes		 * Find a max value for the command length, and ensure
1861590Srgrimes		 * there's enough space to build it.
1871590Srgrimes		 */
1881590Srgrimes		for (l = strlen(cmd), i = 0; i < nargs; i++)
18954113Skris			l += strlen(argv[i+1]);
1901590Srgrimes		if (l > clen && (c = realloc(c, clen = l)) == NULL)
1911590Srgrimes			err(1, NULL);
1921590Srgrimes
1931590Srgrimes		/* Expand command argv references. */
1941590Srgrimes		for (p = cmd, q = c; *p != '\0'; ++p)
19570692Swill			if (p[0] == magic && isdigit(p[1]) && p[1] != '0') {
19670692Swill				offset = snprintf(q, l, "%s",
19770692Swill				    argv[(++p)[0] - '0']);
19882057Sbrian				if ((size_t)offset >= l)
19970692Swill					err(1, "snprintf() failed");
20070692Swill				q += offset;
20171615Swill				l -= offset;
20270692Swill			} else
2031590Srgrimes				*q++ = *p;
2041590Srgrimes
2051590Srgrimes		/* Terminate the command string. */
2061590Srgrimes		*q = '\0';
2071590Srgrimes
2081590Srgrimes		/* Run the command. */
2091590Srgrimes		if (debug)
2101590Srgrimes			(void)printf("%s\n", c);
2111590Srgrimes		else
21271326Swill			if (exec_shell(c, shell, name))
2131590Srgrimes				rval = 1;
2141590Srgrimes	}
2151590Srgrimes
2161590Srgrimes	if (argc != 1)
2171590Srgrimes		errx(1, "expecting additional argument%s after \"%s\"",
21870692Swill	    (nargs - argc) ? "s" : "", argv[argc - 1]);
21970692Swill	free(cmd);
22070692Swill	free(c);
22170692Swill	free(shell);
2221590Srgrimes	exit(rval);
2231590Srgrimes}
2241590Srgrimes
2251590Srgrimes/*
22670692Swill * exec_shell --
22770692Swill * 	Execute a shell command using passed use_shell and use_name
22870692Swill * 	arguments.
2291590Srgrimes */
23070692Swillstatic int
23171326Swillexec_shell(const char *command, char *use_shell, char *use_name)
2321590Srgrimes{
2331590Srgrimes	pid_t pid;
23443928Seivind	int omask, pstat;
2351590Srgrimes	sig_t intsave, quitsave;
2361590Srgrimes
23770672Swill	if (!command)		/* just checking... */
2381590Srgrimes		return(1);
2391590Srgrimes
2401590Srgrimes	omask = sigblock(sigmask(SIGCHLD));
24160706Skris	switch(pid = vfork()) {
2421590Srgrimes	case -1:			/* error */
24360706Skris		err(1, "vfork");
2441590Srgrimes	case 0:				/* child */
2451590Srgrimes		(void)sigsetmask(omask);
24679452Sbrian		execl(use_shell, use_name, "-c", command, (char *)NULL);
24770692Swill		warn("%s", use_shell);
24860706Skris		_exit(1);
2491590Srgrimes	}
2501590Srgrimes	intsave = signal(SIGINT, SIG_IGN);
2511590Srgrimes	quitsave = signal(SIGQUIT, SIG_IGN);
25243928Seivind	pid = waitpid(pid, &pstat, 0);
2531590Srgrimes	(void)sigsetmask(omask);
2541590Srgrimes	(void)signal(SIGINT, intsave);
2551590Srgrimes	(void)signal(SIGQUIT, quitsave);
25643928Seivind	return(pid == -1 ? -1 : pstat);
2571590Srgrimes}
2581590Srgrimes
2591590Srgrimesvoid
2601590Srgrimesusage()
2611590Srgrimes{
2621590Srgrimes
2631590Srgrimes	(void)fprintf(stderr,
26470672Swill	"usage: apply [-a magic] [-d] [-0123456789] command arguments ...\n");
2651590Srgrimes	exit(1);
2661590Srgrimes}
267