1 /*- 2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD 3 * 4 * Copyright (c) 2005 - Garance Alistair Drosehn <gad@FreeBSD.org>. 5 * All rights reserved. 6 * 7 * Redistribution and use in source and binary forms, with or without 8 * modification, are permitted provided that the following conditions 9 * are met: 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. 15 * 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 26 * SUCH DAMAGE. 27 * 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. 31 */ 32 33 #include <sys/cdefs.h> 34 __FBSDID("$FreeBSD$"); 35 36 #include <sys/stat.h> 37 #include <sys/param.h> 38 #include <err.h> 39 #include <errno.h> 40 #include <ctype.h> 41 #include <stdio.h> 42 #include <stdlib.h> 43 #include <string.h> 44 #include <unistd.h> 45 46 #include "envopts.h" 47 48 static const char * 49 expand_vars(int in_thisarg, char **thisarg_p, char **dest_p, 50 const char **src_p); 51 static int is_there(char *candidate); 52 53 /* 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. 57 */ 58 #define isalnumch(Anychar) isalnum((u_char)(Anychar)) 59 #define isalphach(Anychar) isalpha((u_char)(Anychar)) 60 #define isspacech(Anychar) isspace((u_char)(Anychar)) 61 62 /* 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. 65 */ 66 static int 67 is_there(char *candidate) 68 { 69 struct stat fin; 70 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) && 75 (getuid() != 0 || 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); 79 return (1); 80 } 81 return (0); 82 } 83 84 /** 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. 90 * E.G.: 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. 95 * 96 * This is similar to the print_matches() routine in usr.bin/which/which.c. 97 */ 98 void 99 search_paths(char *path, char **argv) 100 { 101 char candidate[PATH_MAX]; 102 const char *d; 103 char *filename, *fqname; 104 105 /* If the file has a `/' in it, then no search is done */ 106 filename = *argv; 107 if (strchr(filename, '/') != NULL) 108 return; 109 110 if (env_verbosity > 1) { 111 fprintf(stderr, "#env Searching:\t'%s'\n", path); 112 fprintf(stderr, "#env for file:\t'%s'\n", filename); 113 } 114 115 fqname = NULL; 116 while ((d = strsep(&path, ":")) != NULL) { 117 if (*d == '\0') 118 d = "."; 119 if (snprintf(candidate, sizeof(candidate), "%s/%s", d, 120 filename) >= (int)sizeof(candidate)) 121 continue; 122 if (is_there(candidate)) { 123 fqname = candidate; 124 break; 125 } 126 } 127 128 if (fqname == NULL) { 129 errno = ENOENT; 130 err(127, "%s", filename); 131 } 132 *argv = strdup(candidate); 133 } 134 135 /** 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 143 * parses it. 144 * 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 "'". 149 * 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 155 * specify blanks. 156 * 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". 163 */ 164 void 165 split_spaces(const char *str, int *origind, int *origc, char ***origv) 166 { 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; 171 172 /* 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. 176 */ 177 while (isspacech(*str)) 178 str++; 179 if (*str == '\0') 180 return; 181 newstr = malloc(strlen(str) + 1); 182 183 /* 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 186 * array. 187 */ 188 newargv = malloc((*origc + (strlen(str) / 2) + 2) * sizeof(char *)); 189 nextarg = newargv; 190 *nextarg++ = **origv; 191 192 /* Come up with the new args by splitting up the given string. */ 193 addcount = 0; 194 bq_destlen = in_arg = in_dq = in_sq = 0; 195 bq_src = NULL; 196 for (src = str, dest = newstr; *src != '\0'; src++) { 197 /* 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. 202 */ 203 copychar = found_sep = 0; 204 copystr = NULL; 205 switch (*src) { 206 case '"': 207 if (in_sq) 208 copychar = *src; 209 else if (in_dq) 210 in_dq = 0; 211 else { 212 /* 213 * Referencing nullarg ensures that a new 214 * argument is created, even if this quoted 215 * string ends up with zero characters. 216 */ 217 copystr = nullarg; 218 in_dq = 1; 219 bq_destlen = dest - *(nextarg - 1); 220 bq_src = src; 221 } 222 break; 223 case '$': 224 if (in_sq) 225 copychar = *src; 226 else { 227 copystr = expand_vars(in_arg, (nextarg - 1), 228 &dest, &src); 229 } 230 break; 231 case '\'': 232 if (in_dq) 233 copychar = *src; 234 else if (in_sq) 235 in_sq = 0; 236 else { 237 /* 238 * Referencing nullarg ensures that a new 239 * argument is created, even if this quoted 240 * string ends up with zero characters. 241 */ 242 copystr = nullarg; 243 in_sq = 1; 244 bq_destlen = dest - *(nextarg - 1); 245 bq_src = src; 246 } 247 break; 248 case '\\': 249 if (in_sq) { 250 /* 251 * Inside single-quoted strings, only the 252 * "\'" and "\\" are recognized as special 253 * strings. 254 */ 255 copychar = *(src + 1); 256 if (copychar == '\'' || copychar == '\\') 257 src++; 258 else 259 copychar = *src; 260 break; 261 } 262 src++; 263 switch (*src) { 264 case '"': 265 case '#': 266 case '$': 267 case '\'': 268 case '\\': 269 copychar = *src; 270 break; 271 case '_': 272 /* 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. 276 */ 277 if (in_dq) 278 copychar = ' '; 279 else { 280 found_sep = 1; 281 src++; 282 } 283 break; 284 case 'c': 285 /* 286 * Ignore remaining characters in the -S string. 287 * This would not make sense if found in the 288 * middle of a quoted string. 289 */ 290 if (in_dq) 291 errx(1, "Sequence '\\%c' is not allowed" 292 " in quoted strings", *src); 293 goto str_done; 294 case 'f': 295 copychar = '\f'; 296 break; 297 case 'n': 298 copychar = '\n'; 299 break; 300 case 'r': 301 copychar = '\r'; 302 break; 303 case 't': 304 copychar = '\t'; 305 break; 306 case 'v': 307 copychar = '\v'; 308 break; 309 default: 310 if (isspacech(*src)) 311 copychar = *src; 312 else 313 errx(1, "Invalid sequence '\\%c' in -S", 314 *src); 315 } 316 break; 317 default: 318 if ((in_dq || in_sq) && in_arg) 319 copychar = *src; 320 else if (isspacech(*src)) 321 found_sep = 1; 322 else { 323 /* 324 * If the first character of a new argument 325 * is `#', then ignore the remaining chars. 326 */ 327 if (!in_arg && *src == '#') 328 goto str_done; 329 copychar = *src; 330 } 331 } 332 /* 333 * Now that the switch has determined what (if anything) 334 * needs to be copied, copy whatever that is to *dest. 335 */ 336 if (copychar || copystr != NULL) { 337 if (!in_arg) { 338 /* This is the first byte of a new argument */ 339 *nextarg++ = dest; 340 addcount++; 341 in_arg = 1; 342 } 343 if (copychar) 344 *dest++ = (char)copychar; 345 else if (copystr != NULL) 346 while (*copystr != '\0') 347 *dest++ = *copystr++; 348 } else if (found_sep) { 349 *dest++ = '\0'; 350 while (isspacech(*src)) 351 src++; 352 --src; 353 in_arg = 0; 354 } 355 } 356 str_done: 357 *dest = '\0'; 358 *nextarg = NULL; 359 if (in_dq || in_sq) { 360 errx(1, "No terminating quote for string: %.*s%s", 361 bq_destlen, *(nextarg - 1), bq_src); 362 } 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); 369 } 370 371 /* Copy the unprocessed arg-pointers from the original array */ 372 for (oldarg = *origv + *origind; *oldarg; oldarg++) 373 *nextarg++ = *oldarg; 374 *nextarg = NULL; 375 376 /* Update optind/argc/argv in the calling routine */ 377 *origc += addcount - *origind + 1; 378 *origv = newargv; 379 *origind = 1; 380 } 381 382 /** 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. 389 */ 390 static const char * 391 expand_vars(int in_thisarg, char **thisarg_p, char **dest_p, const char **src_p) 392 { 393 const char *vbegin, *vend, *vvalue; 394 char *newstr, *vname; 395 int bad_reference; 396 size_t namelen, newlen; 397 398 bad_reference = 1; 399 vbegin = vend = (*src_p) + 1; 400 if (*vbegin++ == '{') 401 if (*vbegin == '_' || isalphach(*vbegin)) { 402 vend = vbegin + 1; 403 while (*vend == '_' || isalnumch(*vend)) 404 vend++; 405 if (*vend == '}') 406 bad_reference = 0; 407 } 408 if (bad_reference) 409 errx(1, "Only ${VARNAME} expansion is supported, error at: %s", 410 *src_p); 411 412 /* 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. 417 */ 418 *src_p = vend; 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) 425 fprintf(stderr, 426 "#env replacing ${%s} with null string\n", 427 vname); 428 free(vname); 429 return (NULL); 430 } 431 432 if (env_verbosity > 2) 433 fprintf(stderr, "#env expanding ${%s} into '%s'\n", vname, 434 vvalue); 435 436 /* 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. 440 */ 441 if (strlen(vname) + 3 >= strlen(vvalue)) { 442 free(vname); 443 return (vvalue); 444 } 445 446 /* 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. 455 */ 456 newlen = strlen(vvalue) + strlen(*src_p) + 1; 457 if (in_thisarg) { 458 **dest_p = '\0'; /* Provide terminator for 'thisarg' */ 459 newlen += strlen(*thisarg_p); 460 newstr = malloc(newlen); 461 strcpy(newstr, *thisarg_p); 462 *thisarg_p = newstr; 463 } else { 464 newstr = malloc(newlen); 465 *newstr = '\0'; 466 } 467 *dest_p = strchr(newstr, '\0'); 468 free(vname); 469 return (vvalue); 470 } 471