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