xref: /dragonfly/usr.bin/env/envopts.c (revision 6cd3723e33d07f75108e7f2694de1f7fdbf151e6)
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  * $FreeBSD: head/usr.bin/env/envopts.c 326276 2017-11-27 15:37:16Z pfg $
33  */
34 
35 #include <sys/stat.h>
36 #include <sys/param.h>
37 #include <err.h>
38 #include <errno.h>
39 #include <ctype.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <unistd.h>
44 
45 #include "envopts.h"
46 
47 static const char *
48                      expand_vars(int in_thisarg, char **thisarg_p, char **dest_p,
49                          const char **src_p);
50 static int           is_there(char *candidate);
51 
52 /*
53  * The is*() routines take a parameter of 'int', but expect values in the range
54  * of unsigned char.  Define some wrappers which take a value of type 'char',
55  * whether signed or unsigned, and ensure the value ends up in the right range.
56  */
57 #define   isalnumch(Anychar) isalnum((u_char)(Anychar))
58 #define   isalphach(Anychar) isalpha((u_char)(Anychar))
59 #define   isspacech(Anychar) isspace((u_char)(Anychar))
60 
61 /*
62  * Routine to determine if a given fully-qualified filename is executable.
63  * This is copied almost verbatim from FreeBSD's usr.bin/which/which.c.
64  */
65 static int
is_there(char * candidate)66 is_there(char *candidate)
67 {
68         struct stat fin;
69 
70         /* XXX work around access(2) false positives for superuser */
71         if (access(candidate, X_OK) == 0 &&
72             stat(candidate, &fin) == 0 &&
73             S_ISREG(fin.st_mode) &&
74             (getuid() != 0 ||
75             (fin.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0)) {
76                 if (env_verbosity > 1)
77                               fprintf(stderr, "#env   matched:\t'%s'\n", candidate);
78                 return (1);
79         }
80         return (0);
81 }
82 
83 /**
84  * Routine to search through an alternate path-list, looking for a given
85  * filename to execute.  If the file is found, replace the original
86  * unqualified name with a fully-qualified path.  This allows `env' to
87  * execute programs from a specific strict list of possible paths, without
88  * changing the value of PATH seen by the program which will be executed.
89  * E.G.:
90  *        #!/usr/bin/env -S-P/usr/local/bin:/usr/bin perl
91  * will execute /usr/local/bin/perl or /usr/bin/perl (whichever is found
92  * first), no matter what the current value of PATH is, and without
93  * changing the value of PATH that the script will see when it runs.
94  *
95  * This is similar to the print_matches() routine in usr.bin/which/which.c.
96  */
97 void
search_paths(char * path,char ** argv)98 search_paths(char *path, char **argv)
99 {
100         char candidate[PATH_MAX];
101         const char *d;
102           char *filename, *fqname;
103 
104           /* If the file has a `/' in it, then no search is done */
105           filename = *argv;
106           if (strchr(filename, '/') != NULL)
107                     return;
108 
109           if (env_verbosity > 1) {
110                     fprintf(stderr, "#env Searching:\t'%s'\n", path);
111                     fprintf(stderr, "#env  for file:\t'%s'\n", filename);
112           }
113 
114           fqname = NULL;
115         while ((d = strsep(&path, ":")) != NULL) {
116                 if (*d == '\0')
117                         d = ".";
118                 if (snprintf(candidate, sizeof(candidate), "%s/%s", d,
119                     filename) >= (int)sizeof(candidate))
120                         continue;
121                 if (is_there(candidate)) {
122                         fqname = candidate;
123                               break;
124                 }
125         }
126 
127           if (fqname == NULL) {
128                     errno = ENOENT;
129                     err(127, "%s", filename);
130           }
131           *argv = strdup(candidate);
132 }
133 
134 /**
135  * Routine to split a string into multiple parameters, while recognizing a
136  * few special characters.  It recognizes both single and double-quoted
137  * strings.  This processing is designed entirely for the benefit of the
138  * parsing of "#!"-lines (aka "shebang" lines == the first line of an
139  * executable script).  Different operating systems parse that line in very
140  * different ways, and this split-on-spaces processing is meant to provide
141  * ways to specify arbitrary arguments on that line, no matter how the OS
142  * parses it.
143  *
144  * Within a single-quoted string, the two characters "\'" are treated as
145  * a literal "'" character to add to the string, and "\\" are treated as
146  * a literal "\" character to add.  Other than that, all characters are
147  * copied until the processing gets to a terminating "'".
148  *
149  * Within a double-quoted string, many more "\"-style escape sequences
150  * are recognized, mostly copied from what is recognized in the `printf'
151  * command.  Some OS's will not allow a literal blank character to be
152  * included in the one argument that they recognize on a shebang-line,
153  * so a few additional escape-sequences are defined to provide ways to
154  * specify blanks.
155  *
156  * Within a double-quoted string "\_" is turned into a literal blank.
157  * (Inside of a single-quoted string, the two characters are just copied)
158  * Outside of a quoted string, "\_" is treated as both a blank, and the
159  * end of the current argument.  So with a shelbang-line of:
160  *                  #!/usr/bin/env -SA=avalue\_perl
161  * the -S value would be broken up into arguments "A=avalue" and "perl".
162  */
163 void
split_spaces(const char * str,int * origind,int * origc,char *** origv)164 split_spaces(const char *str, int *origind, int *origc, char ***origv)
165 {
166           static const char *nullarg = "";
167           const char *bq_src, *copystr, *src;
168           char *dest, **newargv, *newstr, **nextarg, **oldarg;
169           int addcount, bq_destlen, copychar, found_sep, in_arg, in_dq, in_sq;
170 
171           /*
172            * Ignore leading space on the string, and then malloc enough room
173            * to build a copy of it.  The copy might end up shorter than the
174            * original, due to quoted strings and '\'-processing.
175            */
176           while (isspacech(*str))
177                     str++;
178           if (*str == '\0')
179                     return;
180           newstr = malloc(strlen(str) + 1);
181 
182           /*
183            * Allocate plenty of space for the new array of arg-pointers,
184            * and start that array off with the first element of the old
185            * array.
186            */
187           newargv = malloc((*origc + (strlen(str) / 2) + 2) * sizeof(char *));
188           nextarg = newargv;
189           *nextarg++ = **origv;
190 
191           /* Come up with the new args by splitting up the given string. */
192           addcount = 0;
193           bq_destlen = in_arg = in_dq = in_sq = 0;
194           bq_src = NULL;
195           for (src = str, dest = newstr; *src != '\0'; src++) {
196                     /*
197                      * This switch will look at a character in *src, and decide
198                      * what should be copied to *dest.  It only decides what
199                      * character(s) to copy, it should not modify *dest.  In some
200                      * cases, it will look at multiple characters from *src.
201                      */
202                     copychar = found_sep = 0;
203                     copystr = NULL;
204                     switch (*src) {
205                     case '"':
206                               if (in_sq)
207                                         copychar = *src;
208                               else if (in_dq)
209                                         in_dq = 0;
210                               else {
211                                         /*
212                                          * Referencing nullarg ensures that a new
213                                          * argument is created, even if this quoted
214                                          * string ends up with zero characters.
215                                          */
216                                         copystr = nullarg;
217                                         in_dq = 1;
218                                         bq_destlen = dest - *(nextarg - 1);
219                                         bq_src = src;
220                               }
221                               break;
222                     case '$':
223                               if (in_sq)
224                                         copychar = *src;
225                               else {
226                                         copystr = expand_vars(in_arg, (nextarg - 1),
227                                             &dest, &src);
228                               }
229                               break;
230                     case '\'':
231                               if (in_dq)
232                                         copychar = *src;
233                               else if (in_sq)
234                                         in_sq = 0;
235                               else {
236                                         /*
237                                          * Referencing nullarg ensures that a new
238                                          * argument is created, even if this quoted
239                                          * string ends up with zero characters.
240                                          */
241                                         copystr = nullarg;
242                                         in_sq = 1;
243                                         bq_destlen = dest - *(nextarg - 1);
244                                         bq_src = src;
245                               }
246                               break;
247                     case '\\':
248                               if (in_sq) {
249                                         /*
250                                          * Inside single-quoted strings, only the
251                                          * "\'" and "\\" are recognized as special
252                                          * strings.
253                                          */
254                                         copychar = *(src + 1);
255                                         if (copychar == '\'' || copychar == '\\')
256                                                   src++;
257                                         else
258                                                   copychar = *src;
259                                         break;
260                               }
261                               src++;
262                               switch (*src) {
263                               case '"':
264                               case '#':
265                               case '$':
266                               case '\'':
267                               case '\\':
268                                         copychar = *src;
269                                         break;
270                               case '_':
271                                         /*
272                                          * Alternate way to get a blank, which allows
273                                          * that blank be used to separate arguments
274                                          * when it is not inside a quoted string.
275                                          */
276                                         if (in_dq)
277                                                   copychar = ' ';
278                                         else {
279                                                   found_sep = 1;
280                                                   src++;
281                                         }
282                                         break;
283                               case 'c':
284                                         /*
285                                          * Ignore remaining characters in the -S string.
286                                          * This would not make sense if found in the
287                                          * middle of a quoted string.
288                                          */
289                                         if (in_dq)
290                                                   errx(1, "Sequence '\\%c' is not allowed"
291                                                       " in quoted strings", *src);
292                                         goto str_done;
293                               case 'f':
294                                         copychar = '\f';
295                                         break;
296                               case 'n':
297                                         copychar = '\n';
298                                         break;
299                               case 'r':
300                                         copychar = '\r';
301                                         break;
302                               case 't':
303                                         copychar = '\t';
304                                         break;
305                               case 'v':
306                                         copychar = '\v';
307                                         break;
308                               default:
309                                         if (isspacech(*src))
310                                                   copychar = *src;
311                                         else
312                                                   errx(1, "Invalid sequence '\\%c' in -S",
313                                                       *src);
314                               }
315                               break;
316                     default:
317                               if ((in_dq || in_sq) && in_arg)
318                                         copychar = *src;
319                               else if (isspacech(*src))
320                                         found_sep = 1;
321                               else {
322                                         /*
323                                          * If the first character of a new argument
324                                          * is `#', then ignore the remaining chars.
325                                          */
326                                         if (!in_arg && *src == '#')
327                                                   goto str_done;
328                                         copychar = *src;
329                               }
330                     }
331                     /*
332                      * Now that the switch has determined what (if anything)
333                      * needs to be copied, copy whatever that is to *dest.
334                      */
335                     if (copychar || copystr != NULL) {
336                               if (!in_arg) {
337                                         /* This is the first byte of a new argument */
338                                         *nextarg++ = dest;
339                                         addcount++;
340                                         in_arg = 1;
341                               }
342                               if (copychar)
343                                         *dest++ = (char)copychar;
344                               else if (copystr != NULL)
345                                         while (*copystr != '\0')
346                                                   *dest++ = *copystr++;
347                     } else if (found_sep) {
348                               *dest++ = '\0';
349                               while (isspacech(*src))
350                                         src++;
351                               --src;
352                               in_arg = 0;
353                     }
354           }
355 str_done:
356           *dest = '\0';
357           *nextarg = NULL;
358           if (in_dq || in_sq) {
359                     errx(1, "No terminating quote for string: %.*s%s",
360                         bq_destlen, *(nextarg - 1), bq_src);
361           }
362           if (env_verbosity > 1) {
363                     fprintf(stderr, "#env  split -S:\t'%s'\n", str);
364                     oldarg = newargv + 1;
365                     fprintf(stderr, "#env      into:\t'%s'\n", *oldarg);
366                     for (oldarg++; *oldarg; oldarg++)
367                               fprintf(stderr, "#env          &\t'%s'\n", *oldarg);
368           }
369 
370           /* Copy the unprocessed arg-pointers from the original array */
371           for (oldarg = *origv + *origind; *oldarg; oldarg++)
372                     *nextarg++ = *oldarg;
373           *nextarg = NULL;
374 
375           /* Update optind/argc/argv in the calling routine */
376           *origc += addcount - *origind + 1;
377           *origv = newargv;
378           *origind = 1;
379 }
380 
381 /**
382  * Routine to split expand any environment variables referenced in the string
383  * that -S is processing.  For now it only supports the form ${VARNAME}.  It
384  * explicitly does not support $VARNAME, and obviously can not handle special
385  * shell-variables such as $?, $*, $1, etc.  It is called with *src_p pointing
386  * at the initial '$', and if successful it will update *src_p, *dest_p, and
387  * possibly *thisarg_p in the calling routine.
388  */
389 static const char *
expand_vars(int in_thisarg,char ** thisarg_p,char ** dest_p,const char ** src_p)390 expand_vars(int in_thisarg, char **thisarg_p, char **dest_p, const char **src_p)
391 {
392           const char *vbegin, *vend, *vvalue;
393           char *newstr, *vname;
394           int bad_reference;
395           size_t namelen, newlen;
396 
397           bad_reference = 1;
398           vbegin = vend = (*src_p) + 1;
399           if (*vbegin++ == '{')
400                     if (*vbegin == '_' || isalphach(*vbegin)) {
401                               vend = vbegin + 1;
402                               while (*vend == '_' || isalnumch(*vend))
403                                         vend++;
404                               if (*vend == '}')
405                                         bad_reference = 0;
406                     }
407           if (bad_reference)
408                     errx(1, "Only ${VARNAME} expansion is supported, error at: %s",
409                         *src_p);
410 
411           /*
412            * We now know we have a valid environment variable name, so update
413            * the caller's source-pointer to the last character in that reference,
414            * and then pick up the matching value.  If the variable is not found,
415            * or if it has a null value, then our work here is done.
416            */
417           *src_p = vend;
418           namelen = vend - vbegin + 1;
419           vname = malloc(namelen);
420           strlcpy(vname, vbegin, namelen);
421           vvalue = getenv(vname);
422           if (vvalue == NULL || *vvalue == '\0') {
423                     if (env_verbosity > 2)
424                               fprintf(stderr,
425                                   "#env  replacing ${%s} with null string\n",
426                                   vname);
427                     free(vname);
428                     return (NULL);
429           }
430 
431           if (env_verbosity > 2)
432                     fprintf(stderr, "#env  expanding ${%s} into '%s'\n", vname,
433                         vvalue);
434 
435           /*
436            * There is some value to copy to the destination.  If the value is
437            * shorter than the ${VARNAME} reference that it replaces, then our
438            * caller can just copy the value to the existing destination.
439            */
440           if (strlen(vname) + 3 >= strlen(vvalue)) {
441                     free(vname);
442                     return (vvalue);
443           }
444 
445           /*
446            * The value is longer than the string it replaces, which means the
447            * present destination area is too small to hold it.  Create a new
448            * destination area, and update the caller's 'dest' variable to match.
449            * If the caller has already started copying some info for 'thisarg'
450            * into the present destination, then the new destination area must
451            * include a copy of that data, and the pointer to 'thisarg' must also
452            * be updated.  Note that it is still the caller which copies this
453            * vvalue to the new *dest.
454            */
455           newlen = strlen(vvalue) + strlen(*src_p) + 1;
456           if (in_thisarg) {
457                     **dest_p = '\0';    /* Provide terminator for 'thisarg' */
458                     newlen += strlen(*thisarg_p);
459                     newstr = malloc(newlen);
460                     strcpy(newstr, *thisarg_p);
461                     *thisarg_p = newstr;
462           } else {
463                     newstr = malloc(newlen);
464                     *newstr = '\0';
465           }
466           *dest_p = strchr(newstr, '\0');
467           free(vname);
468           return (vvalue);
469 }
470