1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
9 #include "alloc-util.h"
11 #include "errno-util.h"
13 #include "extract-word.h"
15 #include "parse-util.h"
16 #include "path-util.h"
17 #include "process-util.h"
18 #include "stdio-util.h"
19 #include "string-util.h"
23 /* We follow bash for the character set. Different shells have different rules. */
24 #define VALID_BASH_ENV_NAME_CHARS \
28 static bool env_name_is_valid_n(const char *e
, size_t n
) {
35 if (ascii_isdigit(e
[0]))
38 /* POSIX says the overall size of the environment block cannot
39 * be > ARG_MAX, an individual assignment hence cannot be
40 * either. Discounting the equal sign and trailing NUL this
41 * hence leaves ARG_MAX-2 as longest possible variable
43 if (n
> (size_t) sysconf(_SC_ARG_MAX
) - 2)
46 for (const char *p
= e
; p
< e
+ n
; p
++)
47 if (!strchr(VALID_BASH_ENV_NAME_CHARS
, *p
))
53 bool env_name_is_valid(const char *e
) {
54 return env_name_is_valid_n(e
, strlen_ptr(e
));
57 bool env_value_is_valid(const char *e
) {
61 if (!utf8_is_valid(e
))
64 /* Note that variable *values* may contain control characters, in particular NL, TAB, BS, DEL, ESC…
65 * When printing those variables with show-environment, we'll escape them. Make sure to print
66 * environment variables carefully! */
68 /* POSIX says the overall size of the environment block cannot be > ARG_MAX, an individual assignment
69 * hence cannot be either. Discounting the shortest possible variable name of length 1, the equal
70 * sign and trailing NUL this hence leaves ARG_MAX-3 as longest possible variable value. */
71 if (strlen(e
) > sc_arg_max() - 3)
77 bool env_assignment_is_valid(const char *e
) {
84 if (!env_name_is_valid_n(e
, eq
- e
))
87 if (!env_value_is_valid(eq
+ 1))
90 /* POSIX says the overall size of the environment block cannot be > ARG_MAX, hence the individual
91 * variable assignments cannot be either, but let's leave room for one trailing NUL byte. */
92 if (strlen(e
) > sc_arg_max() - 1)
98 bool strv_env_is_valid(char **e
) {
102 if (!env_assignment_is_valid(*p
))
105 /* Check if there are duplicate assignments */
106 k
= strcspn(*p
, "=");
107 STRV_FOREACH(q
, p
+ 1)
108 if (strneq(*p
, *q
, k
) && (*q
)[k
] == '=')
115 bool strv_env_name_is_valid(char **l
) {
117 if (!env_name_is_valid(*p
))
120 if (strv_contains(p
+ 1, *p
))
127 bool strv_env_name_or_assignment_is_valid(char **l
) {
129 if (!env_assignment_is_valid(*p
) && !env_name_is_valid(*p
))
132 if (strv_contains(p
+ 1, *p
))
139 static int env_append(char **r
, char ***k
, char **a
) {
147 /* Expects the following arguments: 'r' shall point to the beginning of an strv we are going to append to, 'k'
148 * to a pointer pointing to the NULL entry at the end of the same array. 'a' shall point to another strv.
150 * This call adds every entry of 'a' to 'r', either overriding an existing matching entry, or appending to it.
152 * This call assumes 'r' has enough pre-allocated space to grow by all of 'a''s items. */
158 n
= strcspn(*a
, "=");
162 for (j
= r
; j
< *k
; j
++)
163 if (strneq(*j
, *a
, n
))
170 if (j
>= *k
) { /* Append to the end? */
175 free_and_replace(*j
, c
); /* Override existing item */
181 char** _strv_env_merge(char **first
, ...) {
182 _cleanup_strv_free_
char **merged
= NULL
;
186 /* Merges an arbitrary number of environment sets */
188 size_t n
= strv_length(first
);
194 l
= va_arg(ap
, char**);
195 if (l
== POINTER_MAX
)
202 k
= merged
= new(char*, n
+ 1);
207 if (env_append(merged
, &k
, first
) < 0)
214 l
= va_arg(ap
, char**);
215 if (l
== POINTER_MAX
)
218 if (env_append(merged
, &k
, l
) < 0) {
225 return TAKE_PTR(merged
);
228 static bool env_match(const char *t
, const char *pattern
) {
232 /* pattern a matches string a
237 * a= does not match a
238 * a=b does not match a=
239 * a=b does not match a
240 * a=b does not match a=c */
242 if (streq(t
, pattern
))
245 if (!strchr(pattern
, '=')) {
246 size_t l
= strlen(pattern
);
248 return strneq(t
, pattern
, l
) && t
[l
] == '=';
254 static bool env_entry_has_name(const char *entry
, const char *name
) {
260 t
= startswith(entry
, name
);
267 char **strv_env_delete(char **x
, size_t n_lists
, ...) {
272 /* Deletes every entry from x that is mentioned in the other
282 va_start(ap
, n_lists
);
283 for (size_t v
= 0; v
< n_lists
; v
++) {
286 l
= va_arg(ap
, char**);
288 if (env_match(*k
, *j
))
313 char **strv_env_unset(char **l
, const char *p
) {
321 /* Drops every occurrence of the env var setting p in the
322 * string list. Edits in-place. */
324 for (f
= t
= l
; *f
; f
++) {
326 if (env_match(*f
, p
)) {
338 char **strv_env_unset_many(char **l
, ...) {
344 /* Like strv_env_unset() but applies many at once. Edits in-place. */
346 for (f
= t
= l
; *f
; f
++) {
353 while ((p
= va_arg(ap
, const char*))) {
354 if (env_match(*f
, p
)) {
374 int strv_env_replace_consume(char ***l
, char *p
) {
375 const char *t
, *name
;
380 /* Replace first occurrence of the env var or add a new one in the string list. Drop other
381 * occurrences. Edits in-place. Does not copy p and CONSUMES p EVEN ON FAILURE.
383 * p must be a valid key=value assignment. */
391 name
= strndupa_safe(p
, t
- p
);
394 if (env_entry_has_name(*f
, name
)) {
395 free_and_replace(*f
, p
);
396 strv_env_unset(f
+ 1, *f
);
400 /* We didn't find a match, we need to append p or create a new strv */
401 r
= strv_consume(l
, p
);
408 int strv_env_replace_strdup(char ***l
, const char *assignment
) {
409 /* Like strv_env_replace_consume(), but copies the argument. */
411 char *p
= strdup(assignment
);
415 return strv_env_replace_consume(l
, p
);
418 int strv_env_replace_strdup_passthrough(char ***l
, const char *assignment
) {
419 /* Like strv_env_replace_strdup(), but pulls the variable from the environment of
420 * the calling program, if a variable name without value is specified.
424 if (strchr(assignment
, '=')) {
425 if (!env_assignment_is_valid(assignment
))
428 p
= strdup(assignment
);
430 if (!env_name_is_valid(assignment
))
433 /* If we can't find the variable in our environment, we will use
434 * the empty string. This way "passthrough" is equivalent to passing
435 * --setenv=FOO=$FOO in the shell. */
436 p
= strjoin(assignment
, "=", secure_getenv(assignment
));
441 return strv_env_replace_consume(l
, p
);
444 int strv_env_assign(char ***l
, const char *key
, const char *value
) {
445 if (!env_name_is_valid(key
))
448 /* NULL removes assignment, "" creates an empty assignment. */
451 strv_env_unset(*l
, key
);
455 char *p
= strjoin(key
, "=", value
);
459 return strv_env_replace_consume(l
, p
);
462 char *strv_env_get_n(char **l
, const char *name
, size_t k
, unsigned flags
) {
468 STRV_FOREACH_BACKWARDS(i
, l
)
469 if (strneq(*i
, name
, k
) &&
473 if (flags
& REPLACE_ENV_USE_ENVIRONMENT
) {
476 t
= strndupa_safe(name
, k
);
483 char *strv_env_get(char **l
, const char *name
) {
486 return strv_env_get_n(l
, name
, strlen(name
), 0);
489 char *strv_env_pairs_get(char **l
, const char *name
) {
494 STRV_FOREACH_PAIR(key
, value
, l
)
495 if (streq(*key
, name
))
501 char **strv_env_clean_with_callback(char **e
, void (*invalid_callback
)(const char *p
, void *userdata
), void *userdata
) {
506 bool duplicate
= false;
508 if (!env_assignment_is_valid(*p
)) {
509 if (invalid_callback
)
510 invalid_callback(*p
, userdata
);
515 n
= strcspn(*p
, "=");
516 STRV_FOREACH(q
, p
+ 1)
517 if (strneq(*p
, *q
, n
) && (*q
)[n
] == '=') {
536 char *replace_env_n(const char *format
, size_t n
, char **env
, unsigned flags
) {
547 const char *e
, *word
= format
, *test_value
= NULL
; /* test_value is initialized to appease gcc */
549 _cleanup_free_
char *r
= NULL
;
550 size_t i
, len
= 0; /* len is initialized to appease gcc */
555 for (e
= format
, i
= 0; *e
&& i
< n
; e
++, i
++)
565 k
= strnappend(r
, word
, e
-word
-1);
569 free_and_replace(r
, k
);
574 } else if (*e
== '$') {
575 k
= strnappend(r
, word
, e
-word
);
579 free_and_replace(r
, k
);
584 } else if (flags
& REPLACE_ENV_ALLOW_BRACELESS
&& strchr(VALID_BASH_ENV_NAME_CHARS
, *e
)) {
585 k
= strnappend(r
, word
, e
-word
-1);
589 free_and_replace(r
, k
);
592 state
= VARIABLE_RAW
;
602 t
= strv_env_get_n(env
, word
+2, e
-word
-2, flags
);
604 if (!strextend(&r
, t
))
610 } else if (*e
== ':') {
611 if (flags
& REPLACE_ENV_ALLOW_EXTENDED
) {
615 /* Treat this as unsupported syntax, i.e. do no replacement */
622 state
= DEFAULT_VALUE
;
624 state
= ALTERNATE_VALUE
;
633 case DEFAULT_VALUE
: /* fall through */
634 case ALTERNATE_VALUE
:
635 assert(flags
& REPLACE_ENV_ALLOW_EXTENDED
);
648 _cleanup_free_
char *v
= NULL
;
650 t
= strv_env_get_n(env
, word
+2, len
, flags
);
652 if (t
&& state
== ALTERNATE_VALUE
)
653 t
= v
= replace_env_n(test_value
, e
-test_value
, env
, flags
);
654 else if (!t
&& state
== DEFAULT_VALUE
)
655 t
= v
= replace_env_n(test_value
, e
-test_value
, env
, flags
);
657 if (!strextend(&r
, t
))
666 assert(flags
& REPLACE_ENV_ALLOW_BRACELESS
);
668 if (!strchr(VALID_BASH_ENV_NAME_CHARS
, *e
)) {
671 t
= strv_env_get_n(env
, word
+1, e
-word
-1, flags
);
673 if (!strextend(&r
, t
))
683 if (state
== VARIABLE_RAW
) {
686 assert(flags
& REPLACE_ENV_ALLOW_BRACELESS
);
688 t
= strv_env_get_n(env
, word
+1, e
-word
-1, flags
);
689 return strjoin(r
, t
);
691 return strnappend(r
, word
, e
-word
);
694 char **replace_env_argv(char **argv
, char **env
) {
698 l
= strv_length(argv
);
700 ret
= new(char*, l
+1);
704 STRV_FOREACH(i
, argv
) {
706 /* If $FOO appears as single word, replace it by the split up variable */
707 if ((*i
)[0] == '$' && !IN_SET((*i
)[1], '{', '$')) {
709 char **w
, **m
= NULL
;
712 e
= strv_env_get(env
, *i
+1);
716 r
= strv_split_full(&m
, e
, WHITESPACE
, EXTRACT_RELAX
|EXTRACT_UNQUOTE
);
728 w
= reallocarray(ret
, l
+ 1, sizeof(char *));
738 memcpy(ret
+ k
, m
, q
* sizeof(char*));
746 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
747 ret
[k
] = replace_env(*i
, env
, 0);
759 int getenv_bool(const char *p
) {
766 return parse_boolean(e
);
769 int getenv_bool_secure(const char *p
) {
772 e
= secure_getenv(p
);
776 return parse_boolean(e
);
779 int set_unset_env(const char *name
, const char *value
, bool overwrite
) {
783 return RET_NERRNO(setenv(name
, value
, overwrite
));
785 return RET_NERRNO(unsetenv(name
));
788 int putenv_dup(const char *assignment
, bool override
) {
791 e
= strchr(assignment
, '=');
795 n
= strndupa_safe(assignment
, e
- assignment
);
797 /* This is like putenv(), but uses setenv() so that our memory doesn't become part of environ[]. */
798 return RET_NERRNO(setenv(n
, e
+ 1, override
));
801 int setenv_systemd_exec_pid(bool update_only
) {
802 char str
[DECIMAL_STR_MAX(pid_t
)];
805 /* Update $SYSTEMD_EXEC_PID=pid except when '*' is set for the variable. */
807 e
= secure_getenv("SYSTEMD_EXEC_PID");
808 if (!e
&& update_only
)
811 if (streq_ptr(e
, "*"))
814 xsprintf(str
, PID_FMT
, getpid_cached());
816 if (setenv("SYSTEMD_EXEC_PID", str
, 1) < 0)
822 int getenv_path_list(const char *name
, char ***ret_paths
) {
823 _cleanup_strv_free_
char **l
= NULL
;
830 e
= secure_getenv(name
);
834 r
= strv_split_full(&l
, e
, ":", EXTRACT_DONT_COALESCE_SEPARATORS
);
836 return log_debug_errno(r
, "Failed to parse $%s: %m", name
);
839 if (!path_is_absolute(*p
))
840 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
841 "Path '%s' is not absolute, refusing.", *p
);
843 if (!path_is_normalized(*p
))
844 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
845 "Path '%s' is not normalized, refusing.", *p
);
847 if (path_equal(*p
, "/"))
848 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
849 "Path '%s' is the root fs, refusing.", *p
);
853 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
854 "No paths specified, refusing.");
856 *ret_paths
= TAKE_PTR(l
);
860 int getenv_steal_erase(const char *name
, char **ret
) {
861 _cleanup_(erase_and_freep
) char *a
= NULL
;
866 /* Reads an environment variable, makes a copy of it, erases its memory in the environment block and removes
867 * it from there. Usecase: reading passwords from the env block (which is a bad idea, but useful for
868 * testing, and given that people are likely going to misuse this, be thorough) */
885 if (unsetenv(name
) < 0)