1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
9 #include "alloc-util.h"
12 #include "extract-word.h"
14 #include "parse-util.h"
15 #include "path-util.h"
16 #include "process-util.h"
17 #include "stdio-util.h"
18 #include "string-util.h"
22 /* We follow bash for the character set. Different shells have different rules. */
23 #define VALID_BASH_ENV_NAME_CHARS \
27 static bool env_name_is_valid_n(const char *e
, size_t n
) {
34 if (e
[0] >= '0' && e
[0] <= '9')
37 /* POSIX says the overall size of the environment block cannot
38 * be > ARG_MAX, an individual assignment hence cannot be
39 * either. Discounting the equal sign and trailing NUL this
40 * hence leaves ARG_MAX-2 as longest possible variable
42 if (n
> (size_t) sysconf(_SC_ARG_MAX
) - 2)
45 for (const char *p
= e
; p
< e
+ n
; p
++)
46 if (!strchr(VALID_BASH_ENV_NAME_CHARS
, *p
))
52 bool env_name_is_valid(const char *e
) {
53 return env_name_is_valid_n(e
, strlen_ptr(e
));
56 bool env_value_is_valid(const char *e
) {
60 if (!utf8_is_valid(e
))
63 /* Note that variable *values* may contain control characters, in particular NL, TAB, BS, DEL, ESC…
64 * When printing those variables with show-environment, we'll escape them. Make sure to print
65 * environment variables carefully! */
67 /* POSIX says the overall size of the environment block cannot be > ARG_MAX, an individual assignment
68 * hence cannot be either. Discounting the shortest possible variable name of length 1, the equal
69 * sign and trailing NUL this hence leaves ARG_MAX-3 as longest possible variable value. */
70 if (strlen(e
) > sc_arg_max() - 3)
76 bool env_assignment_is_valid(const char *e
) {
83 if (!env_name_is_valid_n(e
, eq
- e
))
86 if (!env_value_is_valid(eq
+ 1))
89 /* POSIX says the overall size of the environment block cannot be > ARG_MAX, hence the individual
90 * variable assignments cannot be either, but let's leave room for one trailing NUL byte. */
91 if (strlen(e
) > sc_arg_max() - 1)
97 bool strv_env_is_valid(char **e
) {
103 if (!env_assignment_is_valid(*p
))
106 /* Check if there are duplicate assignments */
107 k
= strcspn(*p
, "=");
108 STRV_FOREACH(q
, p
+ 1)
109 if (strneq(*p
, *q
, k
) && (*q
)[k
] == '=')
116 bool strv_env_name_is_valid(char **l
) {
120 if (!env_name_is_valid(*p
))
123 if (strv_contains(p
+ 1, *p
))
130 bool strv_env_name_or_assignment_is_valid(char **l
) {
134 if (!env_assignment_is_valid(*p
) && !env_name_is_valid(*p
))
137 if (strv_contains(p
+ 1, *p
))
144 static int env_append(char **r
, char ***k
, char **a
) {
152 /* Expects the following arguments: 'r' shall point to the beginning of an strv we are going to append to, 'k'
153 * to a pointer pointing to the NULL entry at the end of the same array. 'a' shall point to another strv.
155 * This call adds every entry of 'a' to 'r', either overriding an existing matching entry, or appending to it.
157 * This call assumes 'r' has enough pre-allocated space to grow by all of 'a''s items. */
163 n
= strcspn(*a
, "=");
167 for (j
= r
; j
< *k
; j
++)
168 if (strneq(*j
, *a
, n
))
175 if (j
>= *k
) { /* Append to the end? */
180 free_and_replace(*j
, c
); /* Override existing item */
186 char** _strv_env_merge(char **first
, ...) {
187 _cleanup_strv_free_
char **merged
= NULL
;
191 /* Merges an arbitrary number of environment sets */
193 size_t n
= strv_length(first
);
199 l
= va_arg(ap
, char**);
200 if (l
== POINTER_MAX
)
207 k
= merged
= new(char*, n
+ 1);
212 if (env_append(merged
, &k
, first
) < 0)
219 l
= va_arg(ap
, char**);
220 if (l
== POINTER_MAX
)
223 if (env_append(merged
, &k
, l
) < 0) {
230 return TAKE_PTR(merged
);
233 static bool env_match(const char *t
, const char *pattern
) {
237 /* pattern a matches string a
242 * a= does not match a
243 * a=b does not match a=
244 * a=b does not match a
245 * a=b does not match a=c */
247 if (streq(t
, pattern
))
250 if (!strchr(pattern
, '=')) {
251 size_t l
= strlen(pattern
);
253 return strneq(t
, pattern
, l
) && t
[l
] == '=';
259 static bool env_entry_has_name(const char *entry
, const char *name
) {
265 t
= startswith(entry
, name
);
272 char **strv_env_delete(char **x
, size_t n_lists
, ...) {
277 /* Deletes every entry from x that is mentioned in the other
287 va_start(ap
, n_lists
);
288 for (size_t v
= 0; v
< n_lists
; v
++) {
291 l
= va_arg(ap
, char**);
293 if (env_match(*k
, *j
))
318 char **strv_env_unset(char **l
, const char *p
) {
326 /* Drops every occurrence of the env var setting p in the
327 * string list. Edits in-place. */
329 for (f
= t
= l
; *f
; f
++) {
331 if (env_match(*f
, p
)) {
343 char **strv_env_unset_many(char **l
, ...) {
349 /* Like strv_env_unset() but applies many at once. Edits in-place. */
351 for (f
= t
= l
; *f
; f
++) {
358 while ((p
= va_arg(ap
, const char*))) {
359 if (env_match(*f
, p
)) {
379 int strv_env_replace_consume(char ***l
, char *p
) {
380 const char *t
, *name
;
386 /* Replace first occurrence of the env var or add a new one in the string list. Drop other
387 * occurrences. Edits in-place. Does not copy p and CONSUMES p EVEN ON FAILURE.
389 * p must be a valid key=value assignment. */
397 name
= strndupa(p
, t
- p
);
400 if (env_entry_has_name(*f
, name
)) {
401 free_and_replace(*f
, p
);
402 strv_env_unset(f
+ 1, *f
);
406 /* We didn't find a match, we need to append p or create a new strv */
407 r
= strv_consume(l
, p
);
414 int strv_env_replace_strdup(char ***l
, const char *assignment
) {
415 /* Like strv_env_replace_consume(), but copies the argument. */
417 char *p
= strdup(assignment
);
421 return strv_env_replace_consume(l
, p
);
424 int strv_env_replace_strdup_passthrough(char ***l
, const char *assignment
) {
425 /* Like strv_env_replace_strdup(), but pulls the variable from the environment of
426 * the calling program, if a variable name without value is specified.
430 if (strchr(assignment
, '=')) {
431 if (!env_assignment_is_valid(assignment
))
434 p
= strdup(assignment
);
436 if (!env_name_is_valid(assignment
))
439 /* If we can't find the variable in our environment, we will use
440 * the empty string. This way "passthrough" is equivalent to passing
441 * --setenv=FOO=$FOO in the shell. */
442 p
= strjoin(assignment
, "=", secure_getenv(assignment
));
447 return strv_env_replace_consume(l
, p
);
450 int strv_env_assign(char ***l
, const char *key
, const char *value
) {
451 if (!env_name_is_valid(key
))
454 /* NULL removes assignment, "" creates an empty assignment. */
457 strv_env_unset(*l
, key
);
461 char *p
= strjoin(key
, "=", value
);
465 return strv_env_replace_consume(l
, p
);
468 char *strv_env_get_n(char **l
, const char *name
, size_t k
, unsigned flags
) {
476 STRV_FOREACH_BACKWARDS(i
, l
)
477 if (strneq(*i
, name
, k
) &&
481 if (flags
& REPLACE_ENV_USE_ENVIRONMENT
) {
484 t
= strndupa(name
, k
);
491 char *strv_env_get(char **l
, const char *name
) {
494 return strv_env_get_n(l
, name
, strlen(name
), 0);
497 char *strv_env_pairs_get(char **l
, const char *name
) {
498 char **key
, **value
, *result
= NULL
;
502 STRV_FOREACH_PAIR(key
, value
, l
)
503 if (streq(*key
, name
))
509 char **strv_env_clean_with_callback(char **e
, void (*invalid_callback
)(const char *p
, void *userdata
), void *userdata
) {
515 bool duplicate
= false;
517 if (!env_assignment_is_valid(*p
)) {
518 if (invalid_callback
)
519 invalid_callback(*p
, userdata
);
524 n
= strcspn(*p
, "=");
525 STRV_FOREACH(q
, p
+ 1)
526 if (strneq(*p
, *q
, n
) && (*q
)[n
] == '=') {
545 char *replace_env_n(const char *format
, size_t n
, char **env
, unsigned flags
) {
556 const char *e
, *word
= format
, *test_value
= NULL
; /* test_value is initialized to appease gcc */
558 _cleanup_free_
char *r
= NULL
;
559 size_t i
, len
= 0; /* len is initialized to appease gcc */
564 for (e
= format
, i
= 0; *e
&& i
< n
; e
++, i
++)
574 k
= strnappend(r
, word
, e
-word
-1);
578 free_and_replace(r
, k
);
583 } else if (*e
== '$') {
584 k
= strnappend(r
, word
, e
-word
);
588 free_and_replace(r
, k
);
593 } else if (flags
& REPLACE_ENV_ALLOW_BRACELESS
&& strchr(VALID_BASH_ENV_NAME_CHARS
, *e
)) {
594 k
= strnappend(r
, word
, e
-word
-1);
598 free_and_replace(r
, k
);
601 state
= VARIABLE_RAW
;
611 t
= strv_env_get_n(env
, word
+2, e
-word
-2, flags
);
613 if (!strextend(&r
, t
))
619 } else if (*e
== ':') {
620 if (flags
& REPLACE_ENV_ALLOW_EXTENDED
) {
624 /* Treat this as unsupported syntax, i.e. do no replacement */
631 state
= DEFAULT_VALUE
;
633 state
= ALTERNATE_VALUE
;
642 case DEFAULT_VALUE
: /* fall through */
643 case ALTERNATE_VALUE
:
644 assert(flags
& REPLACE_ENV_ALLOW_EXTENDED
);
657 _cleanup_free_
char *v
= NULL
;
659 t
= strv_env_get_n(env
, word
+2, len
, flags
);
661 if (t
&& state
== ALTERNATE_VALUE
)
662 t
= v
= replace_env_n(test_value
, e
-test_value
, env
, flags
);
663 else if (!t
&& state
== DEFAULT_VALUE
)
664 t
= v
= replace_env_n(test_value
, e
-test_value
, env
, flags
);
666 if (!strextend(&r
, t
))
675 assert(flags
& REPLACE_ENV_ALLOW_BRACELESS
);
677 if (!strchr(VALID_BASH_ENV_NAME_CHARS
, *e
)) {
680 t
= strv_env_get_n(env
, word
+1, e
-word
-1, flags
);
682 if (!strextend(&r
, t
))
692 if (state
== VARIABLE_RAW
) {
695 assert(flags
& REPLACE_ENV_ALLOW_BRACELESS
);
697 t
= strv_env_get_n(env
, word
+1, e
-word
-1, flags
);
698 return strjoin(r
, t
);
700 return strnappend(r
, word
, e
-word
);
703 char **replace_env_argv(char **argv
, char **env
) {
707 l
= strv_length(argv
);
709 ret
= new(char*, l
+1);
713 STRV_FOREACH(i
, argv
) {
715 /* If $FOO appears as single word, replace it by the split up variable */
716 if ((*i
)[0] == '$' && !IN_SET((*i
)[1], '{', '$')) {
718 char **w
, **m
= NULL
;
721 e
= strv_env_get(env
, *i
+1);
725 r
= strv_split_full(&m
, e
, WHITESPACE
, EXTRACT_RELAX
|EXTRACT_UNQUOTE
);
737 w
= reallocarray(ret
, l
+ 1, sizeof(char *));
747 memcpy(ret
+ k
, m
, q
* sizeof(char*));
755 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
756 ret
[k
] = replace_env(*i
, env
, 0);
768 int getenv_bool(const char *p
) {
775 return parse_boolean(e
);
778 int getenv_bool_secure(const char *p
) {
781 e
= secure_getenv(p
);
785 return parse_boolean(e
);
788 int set_unset_env(const char *name
, const char *value
, bool overwrite
) {
792 r
= setenv(name
, value
, overwrite
);
800 int putenv_dup(const char *assignment
, bool override
) {
803 e
= strchr(assignment
, '=');
807 n
= strndupa(assignment
, e
- assignment
);
809 /* This is like putenv(), but uses setenv() so that our memory doesn't become part of environ[]. */
810 if (setenv(n
, e
+ 1, override
) < 0)
815 int setenv_systemd_exec_pid(bool update_only
) {
816 char str
[DECIMAL_STR_MAX(pid_t
)];
819 /* Update $SYSTEMD_EXEC_PID=pid except when '*' is set for the variable. */
821 e
= secure_getenv("SYSTEMD_EXEC_PID");
822 if (!e
&& update_only
)
825 if (streq_ptr(e
, "*"))
828 xsprintf(str
, PID_FMT
, getpid_cached());
830 if (setenv("SYSTEMD_EXEC_PID", str
, 1) < 0)
836 int getenv_path_list(const char *name
, char ***ret_paths
) {
837 _cleanup_strv_free_
char **l
= NULL
;
845 e
= secure_getenv(name
);
849 r
= strv_split_full(&l
, e
, ":", EXTRACT_DONT_COALESCE_SEPARATORS
);
851 return log_debug_errno(r
, "Failed to parse $%s: %m", name
);
854 if (!path_is_absolute(*p
))
855 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
856 "Path '%s' is not absolute, refusing.", *p
);
858 if (!path_is_normalized(*p
))
859 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
860 "Path '%s' is not normalized, refusing.", *p
);
862 if (path_equal(*p
, "/"))
863 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
864 "Path '%s' is the root fs, refusing.", *p
);
868 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
869 "No paths specified, refusing.");
871 *ret_paths
= TAKE_PTR(l
);
875 int unsetenv_erase(const char *name
) {
886 if (unsetenv(name
) < 0)