1 /* env - run a program in a modified environment
2 Copyright (C) 1986-2024 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
17 /* Richard Mlynarik and David MacKenzie */
21 #include <sys/types.h>
27 #include "operand2sig.h"
31 /* The official name of this program (e.g., no 'g' prefix). */
32 #define PROGRAM_NAME "env"
35 proper_name ("Richard Mlynarik"), \
36 proper_name ("David MacKenzie"), \
37 proper_name ("Assaf Gordon")
39 /* Array of envvars to unset. */
40 static char const **usvars
;
41 static size_t usvars_alloc
;
42 static idx_t usvars_used
;
44 /* Annotate the output with extra info to aid the user. */
45 static bool dev_debug
;
47 /* Buffer and length of extracted envvars in -S strings. */
51 /* Possible actions on each signal. */
54 DEFAULT
, /* Set to default handler (SIG_DFL). */
55 DEFAULT_NOERR
, /* Ditto, but ignore sigaction(2) errors. */
56 IGNORE
, /* Set to ignore (SIG_IGN). */
57 IGNORE_NOERR
/* Ditto, but ignore sigaction(2) errors. */
59 static enum SIGNAL_MODE
*signals
;
61 /* Set of signals to block. */
62 static sigset_t block_signals
;
64 /* Set of signals to unblock. */
65 static sigset_t unblock_signals
;
67 /* Whether signal mask adjustment requested. */
68 static bool sig_mask_changed
;
70 /* Whether to list non default handling. */
71 static bool report_signal_handling
;
73 /* The isspace characters in the C locale. */
74 #define C_ISSPACE_CHARS " \t\n\v\f\r"
76 static char const shortopts
[] = "+C:iS:u:v0" C_ISSPACE_CHARS
;
78 /* For long options that have no equivalent short option, use a
79 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
82 DEFAULT_SIGNAL_OPTION
= CHAR_MAX
+ 1,
85 LIST_SIGNAL_HANDLING_OPTION
,
88 static struct option
const longopts
[] =
90 {"ignore-environment", no_argument
, nullptr, 'i'},
91 {"null", no_argument
, nullptr, '0'},
92 {"unset", required_argument
, nullptr, 'u'},
93 {"chdir", required_argument
, nullptr, 'C'},
94 {"default-signal", optional_argument
, nullptr, DEFAULT_SIGNAL_OPTION
},
95 {"ignore-signal", optional_argument
, nullptr, IGNORE_SIGNAL_OPTION
},
96 {"block-signal", optional_argument
, nullptr, BLOCK_SIGNAL_OPTION
},
97 {"list-signal-handling", no_argument
, nullptr, LIST_SIGNAL_HANDLING_OPTION
},
98 {"debug", no_argument
, nullptr, 'v'},
99 {"split-string", required_argument
, nullptr, 'S'},
100 {GETOPT_HELP_OPTION_DECL
},
101 {GETOPT_VERSION_OPTION_DECL
},
102 {nullptr, 0, nullptr, 0}
108 if (status
!= EXIT_SUCCESS
)
113 Usage: %s [OPTION]... [-] [NAME=VALUE]... [COMMAND [ARG]...]\n"),
116 Set each NAME to VALUE in the environment and run COMMAND.\n\
119 emit_mandatory_arg_note ();
122 -i, --ignore-environment start with an empty environment\n\
123 -0, --null end each output line with NUL, not newline\n\
124 -u, --unset=NAME remove variable from the environment\n\
127 -C, --chdir=DIR change working directory to DIR\n\
130 -S, --split-string=S process and split S into separate arguments;\n\
131 used to pass multiple arguments on shebang lines\n\
134 --block-signal[=SIG] block delivery of SIG signal(s) to COMMAND\n\
137 --default-signal[=SIG] reset handling of SIG signal(s) to the default\n\
140 --ignore-signal[=SIG] set handling of SIG signal(s) to do nothing\n\
143 --list-signal-handling list non default signal handling to stderr\n\
146 -v, --debug print verbose information for each processing step\n\
148 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
149 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
152 A mere - implies -i. If no COMMAND, print the resulting environment.\n\
156 SIG may be a signal name like 'PIPE', or a signal number like '13'.\n\
157 Without SIG, all known signals are included. Multiple signals can be\n\
158 comma-separated. An empty SIG argument is a no-op.\n\
160 emit_exec_status (PROGRAM_NAME
);
161 emit_ancillary_info (PROGRAM_NAME
);
167 append_unset_var (char const *var
)
169 if (usvars_used
== usvars_alloc
)
170 usvars
= x2nrealloc (usvars
, &usvars_alloc
, sizeof *usvars
);
171 usvars
[usvars_used
++] = var
;
177 for (idx_t i
= 0; i
< usvars_used
; ++i
)
179 devmsg ("unset: %s\n", usvars
[i
]);
181 if (unsetenv (usvars
[i
]))
182 error (EXIT_CANCELED
, errno
, _("cannot unset %s"),
187 /* Return a pointer to the end of a valid ${VARNAME} string, or nullptr.
188 'str' should point to the '$' character.
189 First letter in VARNAME must be alpha or underscore,
190 rest of letters are alnum or underscore.
191 Any other character is an error. */
194 scan_varname (char const *str
)
196 if (str
[1] == '{' && (c_isalpha (str
[2]) || str
[2] == '_'))
198 char const *end
= str
+ 3;
199 while (c_isalnum (*end
) || *end
== '_')
208 /* Return a pointer to a static buffer containing the VARNAME as
209 extracted from a '${VARNAME}' string.
210 The returned string will be NUL terminated.
211 The returned pointer should not be freed.
212 Return nullptr if not a valid ${VARNAME} syntax. */
214 extract_varname (char const *str
)
219 p
= scan_varname (str
);
223 /* -2 and +2 (below) account for the '${' prefix. */
229 varname
= xrealloc (varname
, vnlen
);
232 memcpy (varname
, str
+ 2, i
);
238 /* Temporary buffer used by --split-string processing. */
241 /* Buffer address, arg count, and half the number of elements in the buffer.
242 ARGC and ARGV are as in 'main', and ARGC + 1 <= HALF_ALLOC so
243 that the upper half of ARGV can be used for string contents.
244 This may waste up to half the space but keeps the code simple,
245 which is better for this rarely-used but security-sensitive code.
247 ARGV[0] is not initialized; that is the caller's responsibility
250 During assembly, ARGV[I] (where 0 < I < ARGC) contains the offset
251 of the Ith string (relative to ARGV + HALF_ALLOC), so that
252 reallocating ARGV does not change the validity of its contents.
253 The integer offset is cast to char * during assembly, and is
254 converted to a true char * pointer on finalization.
256 During assembly, ARGV[ARGC] contains the offset of the first
257 unused string byte (relative to ARGV + HALF_ALLOC). */
262 /* The number of extra argv slots to keep room for. */
265 /* Whether processing should act as if the most recent character
266 seen was a separator. */
270 /* Expand SS so that it has at least one more argv slot and at least
271 one more string byte. */
273 splitbuf_grow (struct splitbuf
*ss
)
275 idx_t old_half_alloc
= ss
->half_alloc
;
276 idx_t string_bytes
= (intptr_t) ss
->argv
[ss
->argc
];
277 ss
->argv
= xpalloc (ss
->argv
, &ss
->half_alloc
, 1,
278 MIN (INT_MAX
, IDX_MAX
), 2 * sizeof *ss
->argv
);
279 memmove (ss
->argv
+ ss
->half_alloc
, ss
->argv
+ old_half_alloc
, string_bytes
);
282 /* In SS, append C to the last string. */
284 splitbuf_append_byte (struct splitbuf
*ss
, char c
)
286 idx_t string_bytes
= (intptr_t) ss
->argv
[ss
->argc
];
287 if (ss
->half_alloc
* sizeof *ss
->argv
<= string_bytes
)
289 ((char *) (ss
->argv
+ ss
->half_alloc
))[string_bytes
] = c
;
290 ss
->argv
[ss
->argc
] = (char *) (intptr_t) (string_bytes
+ 1);
293 /* If SS's most recent character was a separator, finish off its
294 previous argument and start a new one. */
296 check_start_new_arg (struct splitbuf
*ss
)
300 splitbuf_append_byte (ss
, '\0');
302 if (ss
->half_alloc
<= argc
+ ss
->extra_argc
+ 1)
304 ss
->argv
[argc
+ 1] = ss
->argv
[argc
];
310 /* All additions to SS have been made. Convert its offsets to pointers,
311 and return the resulting argument vector. */
313 splitbuf_finishup (struct splitbuf
*ss
)
316 char **argv
= ss
->argv
;
317 char *stringbase
= (char *) (ss
->argv
+ ss
->half_alloc
);
318 for (int i
= 1; i
< argc
; i
++)
319 argv
[i
] = stringbase
+ (intptr_t) argv
[i
];
323 /* Return a newly-allocated argv-like array,
324 by parsing and splitting the input 'str'.
326 'extra_argc' is the number of additional elements to allocate
327 in the array (on top of the number of args required to split 'str').
329 Store into *argc the number of arguments found (plus 1 for
334 char **argv = build_argv ("A=B uname -k', 3, &argc);
337 argv[0] = [not initialized]
341 argv[4,5,6,7] = [allocated due to extra_argc + 1, but not initialized]
343 To free allocated memory:
345 However, 'env' does not free since it's about to exec or exit anyway
346 and the complexity of keeping track of the storage that may have been
347 allocated via multiple calls to build_argv is not worth the hassle. */
349 build_argv (char const *str
, int extra_argc
, int *argc
)
351 bool dq
= false, sq
= false;
353 ss
.argv
= xnmalloc (extra_argc
+ 2, 2 * sizeof *ss
.argv
);
355 ss
.half_alloc
= extra_argc
+ 2;
356 ss
.extra_argc
= extra_argc
;
358 ss
.argv
[ss
.argc
] = 0;
360 /* In the following loop,
361 'break' causes the character 'newc' to be added to *dest,
362 'continue' skips the character. */
365 char newc
= *str
; /* Default: add the next character. */
373 check_start_new_arg (&ss
);
381 check_start_new_arg (&ss
);
385 case ' ': case '\t': case '\n': case '\v': case '\f': case '\r':
386 /* Start a new argument if outside quotes. */
390 str
+= strspn (str
, C_ISSPACE_CHARS
);
396 goto eos
; /* '#' as first char terminates the string. */
399 /* Backslash inside single-quotes is not special, except \\
401 if (sq
&& str
[1] != '\\' && str
[1] != '\'')
404 /* Skip the backslash and examine the next character. */
408 case '"': case '#': case '$': case '\'': case '\\':
409 /* Pass escaped character as-is. */
415 ++str
; /* '\_' outside double-quotes is arg separator. */
419 newc
= ' '; /* '\_' inside double-quotes is space. */
424 error (EXIT_CANCELED
, 0,
425 _("'\\c' must not appear in double-quoted -S string"));
426 goto eos
; /* '\c' terminates the string. */
428 case 'f': newc
= '\f'; break;
429 case 'n': newc
= '\n'; break;
430 case 'r': newc
= '\r'; break;
431 case 't': newc
= '\t'; break;
432 case 'v': newc
= '\v'; break;
435 error (EXIT_CANCELED
, 0,
436 _("invalid backslash at end of string in -S"));
439 error (EXIT_CANCELED
, 0,
440 _("invalid sequence '\\%c' in -S"), newc
);
445 /* ${VARNAME} are not expanded inside single-quotes. */
449 /* Store the ${VARNAME} value. */
451 char *n
= extract_varname (str
);
453 error (EXIT_CANCELED
, 0,
454 _("only ${VARNAME} expansion is supported, error at: %s"),
457 char *v
= getenv (n
);
460 check_start_new_arg (&ss
);
461 devmsg ("expanding ${%s} into %s\n", n
, quote (v
));
463 splitbuf_append_byte (&ss
, *v
);
466 devmsg ("replacing ${%s} with null string\n", n
);
468 str
= strchr (str
, '}') + 1;
473 check_start_new_arg (&ss
);
474 splitbuf_append_byte (&ss
, newc
);
479 error (EXIT_CANCELED
, 0, _("no terminating quote in -S string"));
482 splitbuf_append_byte (&ss
, '\0');
484 return splitbuf_finishup (&ss
);
487 /* Process an "-S" string and create the corresponding argv array.
488 Update the given argc/argv parameters with the new argv.
490 Example: if executed as:
491 $ env -S"-i -C/tmp A=B" foo bar
494 argv[1] = "-S-i -C/tmp A=B"
498 This function will modify argv to be:
506 argc will be updated from 4 to 6.
507 optind will be reset to 0 to force getopt_long to rescan all arguments. */
509 parse_split_string (char const *str
, int *orig_optind
,
510 int *orig_argc
, char ***orig_argv
)
512 int extra_argc
= *orig_argc
- *orig_optind
, newargc
;
513 char **newargv
= build_argv (str
, extra_argc
, &newargc
);
515 /* Restore argv[0] - the 'env' executable name. */
516 *newargv
= (*orig_argv
)[0];
518 /* Print parsed arguments. */
519 if (dev_debug
&& 1 < newargc
)
521 devmsg ("split -S: %s\n", quote (str
));
522 devmsg (" into: %s\n", quote (newargv
[1]));
523 for (int i
= 2; i
< newargc
; i
++)
524 devmsg (" & %s\n", quote (newargv
[i
]));
527 /* Add remaining arguments and terminating null from the original
529 memcpy (newargv
+ newargc
, *orig_argv
+ *orig_optind
,
530 (extra_argc
+ 1) * sizeof *newargv
);
532 /* Set new values for original getopt variables. */
533 *orig_argc
= newargc
+ extra_argc
;
534 *orig_argv
= newargv
;
535 *orig_optind
= 0; /* Tell getopt to restart from first argument. */
539 parse_signal_action_params (char const *arg
, bool set_default
)
541 char signame
[SIG2STR_MAX
];
543 char *optarg_writable
;
547 /* Without an argument, reset all signals.
548 Some signals cannot be set to ignore or default (e.g., SIGKILL,
549 SIGSTOP on most OSes, and SIGCONT on AIX.) - so ignore errors. */
550 for (int i
= 1 ; i
<= SIGNUM_BOUND
; i
++)
551 if (sig2str (i
, signame
) == 0)
552 signals
[i
] = set_default
? DEFAULT_NOERR
: IGNORE_NOERR
;
556 optarg_writable
= xstrdup (arg
);
558 opt_sig
= strtok (optarg_writable
, ",");
561 int signum
= operand2sig (opt_sig
, signame
);
562 /* operand2sig accepts signal 0 (EXIT) - but we reject it. */
564 error (0, 0, _("%s: invalid signal"), quote (opt_sig
));
566 usage (exit_failure
);
568 signals
[signum
] = set_default
? DEFAULT
: IGNORE
;
570 opt_sig
= strtok (nullptr, ",");
573 free (optarg_writable
);
577 reset_signal_handlers (void)
579 for (int i
= 1; i
<= SIGNUM_BOUND
; i
++)
581 struct sigaction act
;
583 if (signals
[i
] == UNCHANGED
)
586 bool ignore_errors
= (signals
[i
] == DEFAULT_NOERR
587 || signals
[i
] == IGNORE_NOERR
);
589 bool set_to_default
= (signals
[i
] == DEFAULT
590 || signals
[i
] == DEFAULT_NOERR
);
592 int sig_err
= sigaction (i
, nullptr, &act
);
594 if (sig_err
&& !ignore_errors
)
595 error (EXIT_CANCELED
, errno
,
596 _("failed to get signal action for signal %d"), i
);
600 act
.sa_handler
= set_to_default
? SIG_DFL
: SIG_IGN
;
601 sig_err
= sigaction (i
, &act
, nullptr);
602 if (sig_err
&& !ignore_errors
)
603 error (EXIT_CANCELED
, errno
,
604 _("failed to set signal action for signal %d"), i
);
609 char signame
[SIG2STR_MAX
];
610 sig2str (i
, signame
);
611 devmsg ("Reset signal %s (%d) to %s%s\n",
613 set_to_default
? "DEFAULT" : "IGNORE",
614 sig_err
? " (failure ignored)" : "");
621 parse_block_signal_params (char const *arg
, bool block
)
623 char signame
[SIG2STR_MAX
];
625 char *optarg_writable
;
629 /* Without an argument, reset all signals. */
630 sigfillset (block
? &block_signals
: &unblock_signals
);
631 sigemptyset (block
? &unblock_signals
: &block_signals
);
633 else if (! sig_mask_changed
)
635 /* Initialize the sets. */
636 sigemptyset (&block_signals
);
637 sigemptyset (&unblock_signals
);
640 sig_mask_changed
= true;
645 optarg_writable
= xstrdup (arg
);
647 opt_sig
= strtok (optarg_writable
, ",");
650 int signum
= operand2sig (opt_sig
, signame
);
651 /* operand2sig accepts signal 0 (EXIT) - but we reject it. */
653 error (0, 0, _("%s: invalid signal"), quote (opt_sig
));
655 usage (exit_failure
);
657 sigaddset (block
? &block_signals
: &unblock_signals
, signum
);
658 sigdelset (block
? &unblock_signals
: &block_signals
, signum
);
660 opt_sig
= strtok (nullptr, ",");
663 free (optarg_writable
);
667 set_signal_proc_mask (void)
669 /* Get the existing signal mask */
671 char const *debug_act
;
675 if (sigprocmask (0, nullptr, &set
))
676 error (EXIT_CANCELED
, errno
, _("failed to get signal process mask"));
678 for (int i
= 1; i
<= SIGNUM_BOUND
; i
++)
680 if (sigismember (&block_signals
, i
))
685 else if (sigismember (&unblock_signals
, i
))
688 debug_act
= "UNBLOCK";
695 if (dev_debug
&& debug_act
)
697 char signame
[SIG2STR_MAX
];
698 sig2str (i
, signame
);
699 devmsg ("signal %s (%d) mask set to %s\n",
700 signame
, i
, debug_act
);
704 if (sigprocmask (SIG_SETMASK
, &set
, nullptr))
705 error (EXIT_CANCELED
, errno
, _("failed to set signal process mask"));
709 list_signal_handling (void)
712 char signame
[SIG2STR_MAX
];
715 if (sigprocmask (0, nullptr, &set
))
716 error (EXIT_CANCELED
, errno
, _("failed to get signal process mask"));
718 for (int i
= 1; i
<= SIGNUM_BOUND
; i
++)
720 struct sigaction act
;
721 if (sigaction (i
, nullptr, &act
))
724 char const *ignored
= act
.sa_handler
== SIG_IGN
? "IGNORE" : "";
725 char const *blocked
= sigismember (&set
, i
) ? "BLOCK" : "";
726 char const *connect
= *ignored
&& *blocked
? "," : "";
728 if (! *ignored
&& ! *blocked
)
731 sig2str (i
, signame
);
732 fprintf (stderr
, "%-10s (%2d): %s%s%s\n", signame
, i
,
733 blocked
, connect
, ignored
);
738 initialize_signals (void)
740 signals
= xmalloc ((sizeof *signals
) * (SIGNUM_BOUND
+ 1));
742 for (int i
= 0 ; i
<= SIGNUM_BOUND
; i
++)
743 signals
[i
] = UNCHANGED
;
749 main (int argc
, char **argv
)
752 bool ignore_environment
= false;
753 bool opt_nul_terminate_output
= false;
754 char const *newdir
= nullptr;
756 initialize_main (&argc
, &argv
);
757 set_program_name (argv
[0]);
758 setlocale (LC_ALL
, "");
759 bindtextdomain (PACKAGE
, LOCALEDIR
);
760 textdomain (PACKAGE
);
762 initialize_exit_failure (EXIT_CANCELED
);
763 atexit (close_stdout
);
765 initialize_signals ();
767 while ((optc
= getopt_long (argc
, argv
, shortopts
, longopts
, nullptr)) != -1)
772 ignore_environment
= true;
775 append_unset_var (optarg
);
781 opt_nul_terminate_output
= true;
783 case DEFAULT_SIGNAL_OPTION
:
784 parse_signal_action_params (optarg
, true);
785 parse_block_signal_params (optarg
, false);
787 case IGNORE_SIGNAL_OPTION
:
788 parse_signal_action_params (optarg
, false);
790 case BLOCK_SIGNAL_OPTION
:
791 parse_block_signal_params (optarg
, true);
793 case LIST_SIGNAL_HANDLING_OPTION
:
794 report_signal_handling
= true;
800 parse_split_string (optarg
, &optind
, &argc
, &argv
);
802 case ' ': case '\t': case '\n': case '\v': case '\f': case '\r':
803 /* These are undocumented options. Attempt to detect
804 incorrect shebang usage with extraneous space, e.g.:
805 #!/usr/bin/env -i command
806 In which case argv[1] == "-i command". */
807 error (0, 0, _("invalid option -- '%c'"), optc
);
808 error (0, 0, _("use -[v]S to pass options in shebang lines"));
809 usage (EXIT_CANCELED
);
811 case_GETOPT_HELP_CHAR
;
812 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
814 usage (EXIT_CANCELED
);
818 if (optind
< argc
&& STREQ (argv
[optind
], "-"))
820 ignore_environment
= true;
824 if (ignore_environment
)
826 devmsg ("cleaning environ\n");
827 static char *dummy_environ
[] = { nullptr };
828 environ
= dummy_environ
;
834 while (optind
< argc
&& (eq
= strchr (argv
[optind
], '=')))
836 devmsg ("setenv: %s\n", argv
[optind
]);
838 if (putenv (argv
[optind
]))
841 error (EXIT_CANCELED
, errno
, _("cannot set %s"),
842 quote (argv
[optind
]));
847 bool program_specified
= optind
< argc
;
849 if (opt_nul_terminate_output
&& program_specified
)
851 error (0, 0, _("cannot specify --null (-0) with command"));
852 usage (EXIT_CANCELED
);
855 if (newdir
&& ! program_specified
)
857 error (0, 0, _("must specify command with --chdir (-C)"));
858 usage (EXIT_CANCELED
);
861 if (! program_specified
)
863 /* Print the environment and exit. */
864 char *const *e
= environ
;
866 printf ("%s%c", *e
++, opt_nul_terminate_output
? '\0' : '\n');
870 reset_signal_handlers ();
871 if (sig_mask_changed
)
872 set_signal_proc_mask ();
874 if (report_signal_handling
)
875 list_signal_handling ();
879 devmsg ("chdir: %s\n", quoteaf (newdir
));
881 if (chdir (newdir
) != 0)
882 error (EXIT_CANCELED
, errno
, _("cannot change directory to %s"),
888 devmsg ("executing: %s\n", argv
[optind
]);
889 for (int i
=optind
; i
<argc
; ++i
)
890 devmsg (" arg[%d]= %s\n", i
-optind
, quote (argv
[i
]));
893 execvp (argv
[optind
], &argv
[optind
]);
895 int exit_status
= errno
== ENOENT
? EXIT_ENOENT
: EXIT_CANNOT_INVOKE
;
896 error (0, errno
, "%s", quote (argv
[optind
]));
898 if (exit_status
== EXIT_ENOENT
&& strpbrk (argv
[optind
], C_ISSPACE_CHARS
))
899 error (0, 0, _("use -[v]S to pass options in shebang lines"));
901 main_exit (exit_status
);