2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2005 - Garance Alistair Drosehn <gad@FreeBSD.org>.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 * The views and conclusions contained in the software and documentation
29 * are those of the authors and should not be interpreted as representing
30 * official policies, either expressed or implied, of the FreeBSD Project.
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
37 #include <sys/param.h>
49 expand_vars(int in_thisarg, char **thisarg_p, char **dest_p,
51 static int is_there(char *candidate);
54 * The is*() routines take a parameter of 'int', but expect values in the range
55 * of unsigned char. Define some wrappers which take a value of type 'char',
56 * whether signed or unsigned, and ensure the value ends up in the right range.
58 #define isalnumch(Anychar) isalnum((u_char)(Anychar))
59 #define isalphach(Anychar) isalpha((u_char)(Anychar))
60 #define isspacech(Anychar) isspace((u_char)(Anychar))
63 * Routine to determine if a given fully-qualified filename is executable.
64 * This is copied almost verbatim from FreeBSD's usr.bin/which/which.c.
67 is_there(char *candidate)
71 /* XXX work around access(2) false positives for superuser */
72 if (access(candidate, X_OK) == 0 &&
73 stat(candidate, &fin) == 0 &&
74 S_ISREG(fin.st_mode) &&
76 (fin.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0)) {
77 if (env_verbosity > 1)
78 fprintf(stderr, "#env matched:\t'%s'\n", candidate);
85 * Routine to search through an alternate path-list, looking for a given
86 * filename to execute. If the file is found, replace the original
87 * unqualified name with a fully-qualified path. This allows `env' to
88 * execute programs from a specific strict list of possible paths, without
89 * changing the value of PATH seen by the program which will be executed.
91 * #!/usr/bin/env -S-P/usr/local/bin:/usr/bin perl
92 * will execute /usr/local/bin/perl or /usr/bin/perl (whichever is found
93 * first), no matter what the current value of PATH is, and without
94 * changing the value of PATH that the script will see when it runs.
96 * This is similar to the print_matches() routine in usr.bin/which/which.c.
99 search_paths(char *path, char **argv)
101 char candidate[PATH_MAX];
103 char *filename, *fqname;
105 /* If the file has a `/' in it, then no search is done */
107 if (strchr(filename, '/') != NULL)
110 if (env_verbosity > 1) {
111 fprintf(stderr, "#env Searching:\t'%s'\n", path);
112 fprintf(stderr, "#env for file:\t'%s'\n", filename);
116 while ((d = strsep(&path, ":")) != NULL) {
119 if (snprintf(candidate, sizeof(candidate), "%s/%s", d,
120 filename) >= (int)sizeof(candidate))
122 if (is_there(candidate)) {
128 if (fqname == NULL) {
130 err(127, "%s", filename);
132 *argv = strdup(candidate);
136 * Routine to split a string into multiple parameters, while recognizing a
137 * few special characters. It recognizes both single and double-quoted
138 * strings. This processing is designed entirely for the benefit of the
139 * parsing of "#!"-lines (aka "shebang" lines == the first line of an
140 * executable script). Different operating systems parse that line in very
141 * different ways, and this split-on-spaces processing is meant to provide
142 * ways to specify arbitrary arguments on that line, no matter how the OS
145 * Within a single-quoted string, the two characters "\'" are treated as
146 * a literal "'" character to add to the string, and "\\" are treated as
147 * a literal "\" character to add. Other than that, all characters are
148 * copied until the processing gets to a terminating "'".
150 * Within a double-quoted string, many more "\"-style escape sequences
151 * are recognized, mostly copied from what is recognized in the `printf'
152 * command. Some OS's will not allow a literal blank character to be
153 * included in the one argument that they recognize on a shebang-line,
154 * so a few additional escape-sequences are defined to provide ways to
157 * Within a double-quoted string "\_" is turned into a literal blank.
158 * (Inside of a single-quoted string, the two characters are just copied)
159 * Outside of a quoted string, "\_" is treated as both a blank, and the
160 * end of the current argument. So with a shelbang-line of:
161 * #!/usr/bin/env -SA=avalue\_perl
162 * the -S value would be broken up into arguments "A=avalue" and "perl".
165 split_spaces(const char *str, int *origind, int *origc, char ***origv)
167 static const char *nullarg = "";
168 const char *bq_src, *copystr, *src;
169 char *dest, **newargv, *newstr, **nextarg, **oldarg;
170 int addcount, bq_destlen, copychar, found_sep, in_arg, in_dq, in_sq;
173 * Ignore leading space on the string, and then malloc enough room
174 * to build a copy of it. The copy might end up shorter than the
175 * original, due to quoted strings and '\'-processing.
177 while (isspacech(*str))
181 newstr = malloc(strlen(str) + 1);
184 * Allocate plenty of space for the new array of arg-pointers,
185 * and start that array off with the first element of the old
188 newargv = malloc((*origc + (strlen(str) / 2) + 2) * sizeof(char *));
190 *nextarg++ = **origv;
192 /* Come up with the new args by splitting up the given string. */
194 bq_destlen = in_arg = in_dq = in_sq = 0;
196 for (src = str, dest = newstr; *src != '\0'; src++) {
198 * This switch will look at a character in *src, and decide
199 * what should be copied to *dest. It only decides what
200 * character(s) to copy, it should not modify *dest. In some
201 * cases, it will look at multiple characters from *src.
203 copychar = found_sep = 0;
213 * Referencing nullarg ensures that a new
214 * argument is created, even if this quoted
215 * string ends up with zero characters.
219 bq_destlen = dest - *(nextarg - 1);
227 copystr = expand_vars(in_arg, (nextarg - 1),
238 * Referencing nullarg ensures that a new
239 * argument is created, even if this quoted
240 * string ends up with zero characters.
244 bq_destlen = dest - *(nextarg - 1);
251 * Inside single-quoted strings, only the
252 * "\'" and "\\" are recognized as special
255 copychar = *(src + 1);
256 if (copychar == '\'' || copychar == '\\')
273 * Alternate way to get a blank, which allows
274 * that blank be used to separate arguments
275 * when it is not inside a quoted string.
286 * Ignore remaining characters in the -S string.
287 * This would not make sense if found in the
288 * middle of a quoted string.
291 errx(1, "Sequence '\\%c' is not allowed"
292 " in quoted strings", *src);
313 errx(1, "Invalid sequence '\\%c' in -S",
318 if ((in_dq || in_sq) && in_arg)
320 else if (isspacech(*src))
324 * If the first character of a new argument
325 * is `#', then ignore the remaining chars.
327 if (!in_arg && *src == '#')
333 * Now that the switch has determined what (if anything)
334 * needs to be copied, copy whatever that is to *dest.
336 if (copychar || copystr != NULL) {
338 /* This is the first byte of a new argument */
344 *dest++ = (char)copychar;
345 else if (copystr != NULL)
346 while (*copystr != '\0')
347 *dest++ = *copystr++;
348 } else if (found_sep) {
350 while (isspacech(*src))
359 if (in_dq || in_sq) {
360 errx(1, "No terminating quote for string: %.*s%s",
361 bq_destlen, *(nextarg - 1), bq_src);
363 if (env_verbosity > 1) {
364 fprintf(stderr, "#env split -S:\t'%s'\n", str);
365 oldarg = newargv + 1;
366 fprintf(stderr, "#env into:\t'%s'\n", *oldarg);
367 for (oldarg++; *oldarg; oldarg++)
368 fprintf(stderr, "#env &\t'%s'\n", *oldarg);
371 /* Copy the unprocessed arg-pointers from the original array */
372 for (oldarg = *origv + *origind; *oldarg; oldarg++)
373 *nextarg++ = *oldarg;
376 /* Update optind/argc/argv in the calling routine */
377 *origc += addcount - *origind + 1;
383 * Routine to split expand any environment variables referenced in the string
384 * that -S is processing. For now it only supports the form ${VARNAME}. It
385 * explicitly does not support $VARNAME, and obviously can not handle special
386 * shell-variables such as $?, $*, $1, etc. It is called with *src_p pointing
387 * at the initial '$', and if successful it will update *src_p, *dest_p, and
388 * possibly *thisarg_p in the calling routine.
391 expand_vars(int in_thisarg, char **thisarg_p, char **dest_p, const char **src_p)
393 const char *vbegin, *vend, *vvalue;
394 char *newstr, *vname;
396 size_t namelen, newlen;
399 vbegin = vend = (*src_p) + 1;
400 if (*vbegin++ == '{')
401 if (*vbegin == '_' || isalphach(*vbegin)) {
403 while (*vend == '_' || isalnumch(*vend))
409 errx(1, "Only ${VARNAME} expansion is supported, error at: %s",
413 * We now know we have a valid environment variable name, so update
414 * the caller's source-pointer to the last character in that reference,
415 * and then pick up the matching value. If the variable is not found,
416 * or if it has a null value, then our work here is done.
419 namelen = vend - vbegin + 1;
420 vname = malloc(namelen);
421 strlcpy(vname, vbegin, namelen);
422 vvalue = getenv(vname);
423 if (vvalue == NULL || *vvalue == '\0') {
424 if (env_verbosity > 2)
426 "#env replacing ${%s} with null string\n",
432 if (env_verbosity > 2)
433 fprintf(stderr, "#env expanding ${%s} into '%s'\n", vname,
437 * There is some value to copy to the destination. If the value is
438 * shorter than the ${VARNAME} reference that it replaces, then our
439 * caller can just copy the value to the existing destination.
441 if (strlen(vname) + 3 >= strlen(vvalue)) {
447 * The value is longer than the string it replaces, which means the
448 * present destination area is too small to hold it. Create a new
449 * destination area, and update the caller's 'dest' variable to match.
450 * If the caller has already started copying some info for 'thisarg'
451 * into the present destination, then the new destination area must
452 * include a copy of that data, and the pointer to 'thisarg' must also
453 * be updated. Note that it is still the caller which copies this
454 * vvalue to the new *dest.
456 newlen = strlen(vvalue) + strlen(*src_p) + 1;
458 **dest_p = '\0'; /* Provide terminator for 'thisarg' */
459 newlen += strlen(*thisarg_p);
460 newstr = malloc(newlen);
461 strcpy(newstr, *thisarg_p);
464 newstr = malloc(newlen);
467 *dest_p = strchr(newstr, '\0');