Home | History | Annotate | Line # | Download | only in apply
apply.c revision 1.17
      1 /*	$NetBSD: apply.c,v 1.17 2008/03/08 03:35:53 christos 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.17 2008/03/08 03:35:53 christos 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 static void	usage(void) __dead;
     56 static int	shell_system(const char *);
     57 
     58 int
     59 main(int argc, char *argv[])
     60 {
     61 	size_t clen, l;
     62 	int ch, debug, i, magic, n, nargs, rval;
     63 	char *c, *cmd, *p, *q, *nc;
     64 
     65 	(void)setprogname(argv[0]);	/* for portability */
     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(EXIT_FAILURE,
     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(EXIT_FAILURE,
     85 				    "only one -# argument may be specified.");
     86 			nargs = optopt - '0';
     87 			break;
     88 		default:
     89 			usage();
     90 		}
     91 	}
     92 	argc -= optind;
     93 	argv += optind;
     94 
     95 	if (argc < 2)
     96 		usage();
     97 
     98 	/*
     99 	 * The command to run is argv[0], and the args are argv[1..].
    100 	 * Look for %digit references in the command, remembering the
    101 	 * largest one.
    102 	 */
    103 	for (n = 0, p = argv[0]; *p != '\0'; ++p) {
    104 		if (p[0] == magic && isdigit((unsigned char)p[1]) &&
    105 		    p[1] != '0') {
    106 			++p;
    107 			if (p[0] - '0' > n)
    108 				n = p[0] - '0';
    109 		}
    110 	}
    111 	/*
    112 	 * If there were any %digit references, then use those, otherwise
    113 	 * build a new command string with sufficient %digit references at
    114 	 * the end to consume (nargs) arguments each time round the loop.
    115 	 * Allocate enough space to hold the maximum command.
    116 	 */
    117 	if ((cmd = malloc(sizeof("exec ") - 1 +
    118 	    strlen(argv[0]) + 9 * (sizeof(" %1") - 1) + 1)) == NULL)
    119 		err(EXIT_FAILURE, "malloc");
    120 
    121 	if (n == 0) {
    122 		/* If nargs not set, default to a single argument. */
    123 		if (nargs == -1)
    124 			nargs = 1;
    125 
    126 		p = cmd;
    127 		p += sprintf(cmd, "exec %s", argv[0]);
    128 		for (i = 1; i <= nargs; i++)
    129 			p += sprintf(p, " %c%d", magic, i);
    130 
    131 		/*
    132 		 * If nargs set to the special value 0, eat a single
    133 		 * argument for each command execution.
    134 		 */
    135 		if (nargs == 0)
    136 			nargs = 1;
    137 	} else {
    138 		(void)sprintf(cmd, "exec %s", argv[0]);
    139 		nargs = n;
    140 	}
    141 
    142 	/*
    143 	 * Grab some space in which to build the command.  Allocate
    144 	 * as necessary later, but no reason to build it up slowly
    145 	 * for the normal case.
    146 	 */
    147 	if ((c = malloc(clen = 1024)) == NULL)
    148 		err(EXIT_FAILURE, "malloc");
    149 
    150 	/*
    151 	 * (argc) and (argv) are still offset by one to make it simpler to
    152 	 * expand %digit references.  At the end of the loop check for (argc)
    153 	 * equals 1 means that all the (argv) has been consumed.
    154 	 */
    155 	for (rval = 0; argc > nargs; argc -= nargs, argv += nargs) {
    156 		/*
    157 		 * Find a max value for the command length, and ensure
    158 		 * there's enough space to build it.
    159 		 */
    160 		for (l = strlen(cmd), i = 0; i < nargs; i++)
    161 			l += strlen(argv[i+1]);
    162 		if (l > clen) {
    163 			nc = realloc(c, l);
    164 			if (nc == NULL)
    165 				err(EXIT_FAILURE, "malloc");
    166 			c = nc;
    167 			clen = l;
    168 		}
    169 
    170 		/* Expand command argv references. */
    171 		for (p = cmd, q = c; *p != '\0'; ++p) {
    172 			if (p[0] == magic && isdigit((unsigned char)p[1]) &&
    173 			    p[1] != '0')
    174 				q += sprintf(q, "%s", argv[(++p)[0] - '0']);
    175 			else
    176 				*q++ = *p;
    177 		}
    178 
    179 		/* Terminate the command string. */
    180 		*q = '\0';
    181 
    182 		/* Run the command. */
    183 		if (debug)
    184 			(void)printf("%s\n", c);
    185 		else if (shell_system(c))
    186 			rval = 1;
    187 	}
    188 
    189 	if (argc != 1)
    190 		errx(EXIT_FAILURE,
    191 		    "expecting additional argument%s after \"%s\"",
    192 		    (nargs - argc) ? "s" : "", argv[argc - 1]);
    193 	return rval;
    194 }
    195 
    196 /*
    197  * shell_system --
    198  * 	Private version of system(3).  Use the user's SHELL environment
    199  *	variable as the shell to execute.
    200  */
    201 static int
    202 shell_system(const char *command)
    203 {
    204 	static const char *name, *shell;
    205 	int status;
    206 	int omask;
    207 	pid_t pid;
    208 	sig_t intsave, quitsave;
    209 
    210 	if (shell == NULL) {
    211 		if ((shell = getenv("SHELL")) == NULL)
    212 			shell = _PATH_BSHELL;
    213 		if ((name = strrchr(shell, '/')) == NULL)
    214 			name = shell;
    215 		else
    216 			++name;
    217 	}
    218 	if (!command)		/* just checking... */
    219 		return(1);
    220 
    221 	omask = sigblock(sigmask(SIGCHLD));
    222 	switch (pid = vfork()) {
    223 	case -1:			/* error */
    224 		err(EXIT_FAILURE, "vfork");
    225 		/*NOTREACHED*/
    226 	case 0:				/* child */
    227 		(void)sigsetmask(omask);
    228 		(void)execl(shell, name, "-c", command, NULL);
    229 		warn("%s", shell);
    230 		_exit(1);
    231 		/*NOTREACHED*/
    232 	default:			/* parent */
    233 		intsave = signal(SIGINT, SIG_IGN);
    234 		quitsave = signal(SIGQUIT, SIG_IGN);
    235 		pid = waitpid(pid, &status, 0);
    236 		(void)sigsetmask(omask);
    237 		(void)signal(SIGINT, intsave);
    238 		(void)signal(SIGQUIT, quitsave);
    239 		return pid == -1 ? -1 : status;
    240 	}
    241 	/*NOTREACHED*/
    242 }
    243 
    244 __dead
    245 static void
    246 usage(void)
    247 {
    248 
    249 	(void)fprintf(stderr,
    250 	    "usage: %s [-a magic] [-0123456789] command arguments ...\n",
    251 	    getprogname());
    252 	exit(1);
    253 }
    254