/*-1* SPDX-License-Identifier: BSD-3-Clause2*3* Copyright (c) 19944* The Regents of the University of California. All rights reserved.5*6* This code is derived from software contributed to Berkeley by7* Jan-Simon Pendry.8*9* Redistribution and use in source and binary forms, with or without10* modification, are permitted provided that the following conditions11* are met:12* 1. Redistributions of source code must retain the above copyright13* notice, this list of conditions and the following disclaimer.14* 2. Redistributions in binary form must reproduce the above copyright15* notice, this list of conditions and the following disclaimer in the16* documentation and/or other materials provided with the distribution.17* 3. Neither the name of the University nor the names of its contributors18* may be used to endorse or promote products derived from this software19* without specific prior written permission.20*21* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND22* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE23* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE24* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE25* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL26* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS27* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)28* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT29* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY30* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF31* SUCH DAMAGE.32*/3334#include <sys/types.h>35#include <sys/sbuf.h>36#include <sys/wait.h>3738#include <ctype.h>39#include <err.h>40#include <errno.h>41#include <paths.h>42#include <signal.h>43#include <stdio.h>44#include <stdlib.h>45#include <string.h>46#include <unistd.h>4748#define ISMAGICNO(p) \49(p)[0] == magic && isdigit((unsigned char)(p)[1]) && (p)[1] != '0'5051static int exec_shell(const char *, const char *, const char *);52static void usage(void);5354int55main(int argc, char *argv[])56{57struct sbuf *cmdbuf;58long arg_max;59int ch, debug, i, magic, n, nargs, rval;60size_t cmdsize;61char buf[4];62char *cmd, *name, *p, *shell, *slashp, *tmpshell;6364debug = 0;65magic = '%'; /* Default magic char is `%'. */66nargs = -1;67while ((ch = getopt(argc, argv, "a:d0123456789")) != -1)68switch (ch) {69case 'a':70if (optarg[0] == '\0' || optarg[1] != '\0')71errx(1,72"illegal magic character specification");73magic = optarg[0];74break;75case 'd':76debug = 1;77break;78case '0': case '1': case '2': case '3': case '4':79case '5': case '6': case '7': case '8': case '9':80if (nargs != -1)81errx(1,82"only one -# argument may be specified");83nargs = optopt - '0';84break;85default:86usage();87}88argc -= optind;89argv += optind;9091if (argc < 2)92usage();9394/*95* The command to run is argv[0], and the args are argv[1..].96* Look for %digit references in the command, remembering the97* largest one.98*/99for (n = 0, p = argv[0]; *p != '\0'; ++p)100if (ISMAGICNO(p)) {101++p;102if (p[0] - '0' > n)103n = p[0] - '0';104}105106/*107* Figure out the shell and name arguments to pass to execl()108* in exec_shell(). Always malloc() shell and just set name109* to point at the last part of shell if there are any backslashes,110* otherwise just set it to point at the space malloc()'d. If111* SHELL environment variable exists, replace contents of112* shell with it.113*/114shell = name = NULL;115tmpshell = getenv("SHELL");116shell = (tmpshell != NULL) ? strdup(tmpshell) : strdup(_PATH_BSHELL);117if (shell == NULL)118err(1, "strdup() failed");119slashp = strrchr(shell, '/');120name = (slashp != NULL) ? slashp + 1 : shell;121122/*123* If there were any %digit references, then use those, otherwise124* build a new command string with sufficient %digit references at125* the end to consume (nargs) arguments each time round the loop.126* Allocate enough space to hold the maximum command. Save the127* size to pass to snprintf().128*/129if (n == 0) {130cmdsize = strlen(argv[0]) + 9 * (sizeof(" %1") - 1) + 1;131if ((cmd = malloc(cmdsize)) == NULL)132err(1, NULL);133strlcpy(cmd, argv[0], cmdsize);134135/* If nargs not set, default to a single argument. */136if (nargs == -1)137nargs = 1;138139for (i = 1; i <= nargs; i++) {140snprintf(buf, sizeof(buf), " %c%d", magic, i);141strlcat(cmd, buf, cmdsize);142}143144/*145* If nargs set to the special value 0, eat a single146* argument for each command execution.147*/148if (nargs == 0)149nargs = 1;150} else {151if ((cmd = strdup(argv[0])) == NULL)152err(1, NULL);153nargs = n;154}155156cmdbuf = sbuf_new(NULL, NULL, 1024, SBUF_AUTOEXTEND);157if (cmdbuf == NULL)158err(1, NULL);159160arg_max = sysconf(_SC_ARG_MAX);161162/*163* (argc) and (argv) are still offset by one to make it simpler to164* expand %digit references. At the end of the loop check for (argc)165* equals 1 means that all the (argv) has been consumed.166*/167for (rval = 0; argc > nargs; argc -= nargs, argv += nargs) {168sbuf_clear(cmdbuf);169if (sbuf_cat(cmdbuf, "exec ") != 0)170err(1, "sbuf");171/* Expand command argv references. */172for (p = cmd; *p != '\0'; ++p) {173if (ISMAGICNO(p)) {174if (sbuf_cat(cmdbuf, argv[*++p - '0']) != 0)175err(1, "sbuf");176} else {177if (sbuf_putc(cmdbuf, *p) != 0)178err(1, "sbuf");179}180if (sbuf_len(cmdbuf) > arg_max)181errc(1, E2BIG, NULL);182}183184/* Terminate the command string. */185if (sbuf_finish(cmdbuf) != 0)186err(1, "sbuf");187188/* Run the command. */189if (debug)190(void)printf("%s\n", sbuf_data(cmdbuf));191else192if (exec_shell(sbuf_data(cmdbuf), shell, name))193rval = 1;194}195196if (argc != 1)197errx(1, "expecting additional argument%s after \"%s\"",198(nargs - argc) ? "s" : "", argv[argc - 1]);199free(cmd);200sbuf_delete(cmdbuf);201free(shell);202exit(rval);203}204205/*206* exec_shell --207* Execute a shell command using passed use_shell and use_name208* arguments.209*/210static int211exec_shell(const char *command, const char *use_shell, const char *use_name)212{213pid_t pid;214int omask, pstat;215sig_t intsave, quitsave;216217if (!command) /* just checking... */218return(1);219220omask = sigblock(sigmask(SIGCHLD));221switch(pid = vfork()) {222case -1: /* error */223err(1, "vfork");224case 0: /* child */225(void)sigsetmask(omask);226execl(use_shell, use_name, "-c", command, (char *)NULL);227warn("%s", use_shell);228_exit(1);229}230intsave = signal(SIGINT, SIG_IGN);231quitsave = signal(SIGQUIT, SIG_IGN);232pid = waitpid(pid, &pstat, 0);233(void)sigsetmask(omask);234(void)signal(SIGINT, intsave);235(void)signal(SIGQUIT, quitsave);236return(pid == -1 ? -1 : pstat);237}238239static void240usage(void)241{242243(void)fprintf(stderr,244"usage: apply [-a magic] [-d] [-0123456789] command arguments ...\n");245exit(1);246}247248249